课程:b站刘二大人《PyTorch深度学习实践》完结合集
1. 课堂代码
准备数据集->设计模型->构造loss,优化器->写训练周期:前馈、反馈、更新
import torch
import matplotlib.pyplot as plt
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[2.0], [4.0], [6.0]])
loss_list = []
Epoch_list = []
class LinearModel(torch.nn.Module):#继承torch.nn.Module的模块
def __init__(self):
super(LinearModel, self).__init__()#子类(LinearModel)把父类(nn.Module)的__init__()放到自己的__init__(),写就行了
self.linear = torch.nn.Linear(1, 1)#输入的神经元个数为1,只有一个w,所以为1,输出的神经元个数为1,b
def forward(self, x):
y_pred = self.linear(x)#子类已经继承了__call__
return y_pred
model = LinearModel()
criterion = torch.nn.MSELoss(size_average = False)#构造loss
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)#构造优化器,lr:学习率 随机梯度下降
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
#print(epoch, loss.item())
loss_list.append(loss.item())
Epoch_list.append(epoch)
optimizer.zero_grad()#权重梯度清零
loss.backward()#反馈
optimizer.step()#权重更新
print('w = ',model.linear.weight.item())
print('b = ',model.linear.bias.item())
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)
plt.plot(Epoch_list, loss_list)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
结果:
w = 1.9996702671051025 b = 0.0007495086756534874 y_pred = tensor([[7.9994]])
2.课后
参考PyTorch进阶之路(二):如何实现线性回归 - 知乎 (zhihu.com)中的数据集进行
yield_apple = w11 * temp + w12 * rainfall + w13 * humidity + b1
yield_orange = w21 * temp + w22 * rainfall + w23 * humidity + b2
import torch
import matplotlib.pyplot as plt
x_data = torch.Tensor([[73.0, 67.0, 43.0],
[91.0, 88.0, 64.0],
[87.0, 134.0, 58.0],
[102.0, 43.0, 37.0]])
y_data = torch.Tensor([[56.0, 70.0],
[81.0, 101.0],
[119.0, 133.0],
[22.0, 37.0]])
#model: y1 = w11* x1 + w12* x2 +w13* x3 + b1
# y2 = w21* x1 + w22* x2 +w23* x3 + b2
#test x[69.0, 96.0, 70.0] y[103.0, 119.0]
#x: 4x3 y:4x2 w:3x2 y = x * w
loss_list = []
Epoch_list = []
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(3, 2)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
model = LinearModel()
criterion = torch.nn.MSELoss(size_average = False)#构造loss
optimizer = torch.optim.SGD(model.parameters(), lr = 1e-5)#构造优化器,lr:学习率 随机梯度下降
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
loss_list.append(loss.item())
Epoch_list.append(epoch)
optimizer.zero_grad()#权重梯度清零
loss.backward()#反馈
optimizer.step()#权重更新
print('w = ',model.linear.weight)
print('b = ',model.linear.bias)
x_test = torch.Tensor([[69.0, 96.0, 70.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)
plt.plot(Epoch_list, loss_list)
plt.xlabel('epoch')
plt.ylabel('loss')
plt.show()
结果:
998 0.8368473052978516 999 0.8367823958396912 w = Parameter containing: tensor([[-0.3629, 0.8734, 0.5770], [-0.3008, 0.7932, 0.9200]], requires_grad=True) b = Parameter containing: tensor([-0.0607, -0.4898], requires_grad=True) y_pred = tensor([[ 99.1335, 119.3076]])