import torch
x_data = torch.Tensor([[1], [2], [3]])
y_data = torch.Tensor([[4], [5], [6]])
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel,self).__init__() # 继承父类的初始化函数
self.linear = torch.nn.Linear(1,1) # 对输入的数据做线性变换
def forward(self,x):
y_pred = self.linear(x) # 前向传播
return y_pred
model = LinearModel() # 实例化对象
criterion = torch.nn.MSELoss(size_average=False) # 定义损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 定义优化器
for epoch in range(100): # 训练过程
y_pred = model(x_data) # 计算预测值
loss = criterion(y_pred,y_data) # 计算损失函数
print(epoch, loss) # 打印当前轮次和损失值
optimizer.zero_grad() # 梯度归零
loss.backward() # 反向传播
optimizer.step() # 更新
print('w=', model.linear.weight.item()) # 打印权重 加了item()不显示矩阵,只显示数值,返回标量值
print('b=', model.linear.bias.item()) # 打印偏置
# Test Model
x_test = torch.Tensor([[4]])
y_test = model(x_test)
print('y_pred = ', y_test.data)
运行结果
......................
96 tensor(0.4340, grad_fn=<MseLossBackward0>)
97 tensor(0.4278, grad_fn=<MseLossBackward0>)
98 tensor(0.4217, grad_fn=<MseLossBackward0>)
99 tensor(0.4156, grad_fn=<MseLossBackward0>)
w= 1.4291688203811646
b= 2.0243985652923584
y_pred = tensor([[7.7411]])
只循环了100次,在测试集上表现不算特别好
作业代码示例,通过绘图来观察
import torch
import matplotlib.pyplot as plt
x_data = torch.Tensor([[1], [2], [3]])
y_data = torch.Tensor([[4], [5], [6]])
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel,self).__init__() # 继承父类的初始化函数
self.linear = torch.nn.Linear(1,1) # 对输入的数据做线性变换
def forward(self,x):
y_pred = self.linear(x) # 前向传播
return y_pred
model = LinearModel() # 实例化对象
criterion = torch.nn.MSELoss(size_average=False) # 定义损失函数
optimizer = torch.optim.ASGD(model.parameters(), lr=0.01) # 定义优化器,pytorch有很多种优化器可以换
losses = []
epoches = []
for epoch in range(100): # 训练过程
y_pred = model(x_data) # 计算预测值
loss = criterion(y_pred,y_data) # 计算损失函数
losses.append(loss.item())
epoches.append(epoch)
print(epoch, loss) # 打印当前轮次和损失值
optimizer.zero_grad() # 梯度归零
loss.backward() # 反向传播
optimizer.step() # 更新
print('w=', model.linear.weight.item()) # 打印权重 加了item()不显示矩阵,只显示数值,返回标量值
print('b=', model.linear.bias.item()) # 打印偏置
# Test Model
x_test = torch.Tensor([[4]])
y_test = model(x_test)
print('y_pred = ', y_test.data)
plt.plot(epoches, losses)
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Training Loss vs. Epochs')
plt.show()