
Pytorch 预测产量(易化学习笔记一)
实验目的(二维)
通过温度进行产量预测。
实验代码
导入数据集
import torch
import matplotlib.pyplot as plt
## 1.导入数据集
# 输入样本数据集
inputs = torch.tensor([[10.1, 12., 12.4, 15.,17.1]])
# 目标样本集
targets = torch.tensor([[200., 230., 249., 370., 391.]])
# 创建1*1的随机矩阵,元素是随机选取自一个均值为0 且标准差为1的正态分布
w = torch.randn(1, 1, requires_grad=True)
# 创建1*1的随机数
b = torch.randn(1, 1, requires_grad=True)
构建模型
## 2.构建模型
# 定义模型
def model(x):
# 线性回归算法
return x * w + b
# 定义均方差损失函数 -> 比较预测值与目标值差距
def loss_mse(p,t):
diff = p - t
return torch.mean(diff * diff) / diff.numel()
训练模型
# 学习率
learning_rate = 1e-5
# 训练13000轮
for i in range(13000):
# 模型对输入进行预测
preds = model(inputs)
# 计算损失函数
loss = loss_mse(preds, targets)
# 反向传播
loss.backward()
# 更新权重和偏置
with torch.no_grad():
w -= learning_rate * w.grad
b -= learning_rate * b.grad
# 梯度清零
w.grad.zero_()
b.grad.zero_()
# 每训练500次打印一次
if i % 500 == 0:
print('Epoch %d, Loss: %.3f' % (i, loss.item()))
plt.plot(inputs.numpy(),targets.numpy(),'go',label='样本点集')
# 显示预测结果
plt.plot(inputs.numpy()[0],preds.detach().numpy()[0],'r-',lw=3)
#plt.show()
可以发现它的损失越来越低,预测的正确率越来越高。
预测
## 4.模型评估
# 输入全新的值(温度),预测输出的值(产量)
new_inputs = torch.tensor([[11.1]])
print("输入新值的单点:\n",new_inputs)
preds = model(new_inputs)
print("预测out:\n",preds)
# 输入多点的值(温度),预测输出的值(产量)
new_inputs = torch.tensor([[11.1,23.5,32.1]])
print("输入新值的多点:\n",new_inputs)
preds = model(new_inputs)
print("预测out:\n",preds)
实验目的(三维)
通过温度、降雨量和光照进行预测苹果和桔子的产量。
import torch
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置默认字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
## 1.导入数据集
# 输入样本数据集
inputs = torch.tensor([
[10.1, 12., 12.4, 15.,17.1],
[100., 120., 130., 150., 160.],
[36., 39., 42., 54., 69.]
])
# 目标样本集
targets = torch.tensor([
[200., 230., 249., 370., 391.],
[410., 470., 520., 711., 823.]
])
# 创建3*2的随机矩阵,元素是随机选取自一个均值为0 且标准差为1的正态分布
w = torch.randn(2, 3, requires_grad=True)
# 创建1*1的随机数
b = torch.randn(2, 1, requires_grad=True)
## 2.构建模型
# 定义模型
def model(x):
# 线性回归算法
return torch.matmul(w, x) + b
# 定义均方差损失函数 -> 比较预测值与目标值差距
def loss_mse(p,t):
diff = p - t
return torch.mean(diff * diff) / diff.numel()
## 3.训练模型
# 学习率
learning_rate = 1e-5
# 训练3000轮
for i in range(13000):
# 模型对输入进行预测
preds = model(inputs)
# 计算损失函数
loss = loss_mse(preds, targets)
# 反向传播
loss.backward()
# 更新权重和偏置
with torch.no_grad():
w -= learning_rate * w.grad
b -= learning_rate * b.grad
# 梯度清零
w.grad.zero_()
b.grad.zero_()
# 每训练500次打印一次
if i % 500 == 0:
print('Epoch %d, Loss: %.3f' % (i, loss.item()))
# 绘图
fig = plt.figure(figsize=(12, 6))
for j in range(targets.shape[0]):
ax = fig.add_subplot(1, 2, j+1, projection='3d')
ax.scatter(inputs[0].numpy(), inputs[1].numpy(), targets[j].numpy(), c='g', marker='o', label='样本点集')
ax.plot(inputs[0].numpy(), inputs[1].numpy(), preds[j].detach().numpy(), 'r-', lw=3)
ax.set_xlabel('温度')
ax.set_ylabel('降雨量')
ax.set_zlabel('产量' if j == 0 else '目标')
ax.set_title(f'{"苹果" if j == 0 else "桔子"} 产量预测')
# 添加标注
for k in range(inputs.shape[1]):
ax.text(inputs[0, k].item(), inputs[1, k].item(), targets[j, k].item(),
f'({inputs[0, k].item()}, {inputs[1, k].item()}, {targets[j, k].item()})',
fontsize=9)
ax.legend()
plt.show()
简化
import torch
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置默认字体为黑体
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
## 1.导入数据集
# 输入样本数据集
inputs = torch.tensor([
[10.1, 12., 12.4, 15.,17.1],
[100., 120., 130., 150., 160.],
[36., 39., 42., 54., 69.]
]).T
# 目标样本集
targets = torch.tensor([
[200., 230., 249., 370., 391.],
[410., 470., 520., 711., 823.]
]).T
from torch import nn
# 设置内置的线性回归
model = nn.Linear(3,2)
# 内置均值损失函数
loss_mse = nn.MSELoss()
# 设置优化器 随机梯度下降,学习速率为10^-5
optimizer = torch.optim.SGD(model.parameters(),lr = 1e-5)
## 训练评估
# 训练3000论
num_epochs = 3000
for i in range(num_epochs):
# 向前传播
preds = model(inputs)
# 计算损失函数
loss = loss_mse(preds, targets)
# 梯度清零
optimizer.zero_grad()
# 反向传播
loss.backward()
# 按照学习率减去少量梯度来调整权重
optimizer.step()
# 每训练500次打印一次
if i % 500 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(i + 1,num_epochs, loss.item()))
print('targets is :\n',targets.T)
print('preds after train: \n',preds.T)
# 单点预测
new_inputs = torch.tensor([[11.1],[98.],[35.]]).T
print("输入新值(单点):\n",new_inputs.T)
preds = model(new_inputs)
print("预测out:\n",preds.T)
# 多点预测
new_inputs = torch.tensor([[11.1,16.2],[98.,102.3],[35.,40.2]]).T
print("输入新值(多点):\n",new_inputs.T)
preds = model(new_inputs)
print("预测out:\n",preds.T)
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
评价
排名
2
文章
657
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 :
好是好,这个对效率影响大不大哇,效率高不高
一个bug让程序员走上法庭 索赔金额达400亿日元
剑轩 : 有点可怕
ASP.NET Core 服务注册生命周期
剑轩 :
http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术