import torch
import torch.nn as nn
# 1.准备数据集
x_data = torch.Tensor([[1.0], [2.0], [3.0]]) # 1维的,1个特征,3*1, 必须是tensor
y_data = torch.Tensor([[2.0], [4.0], [6.0]]) # 输出1维. 1个特征,3*1
# 2.定义模型
class LinearModel(nn.Module):
def __init__(self): #####
super(LinearModel, self).__init__() #####
self.linear = nn.Linear(1, 1) # (1,1)表示x,y都只有一个特征(行表示样本数,列表示特征)
def forward(self, x):
y_pred = self.linear(x) # linear为callable,将x传入具体运用
return y_pred
model = LinearModel() # creat a instance of class LinearModel,model is callable, using model(x)
# 3.构造损失函数和优化器
loss_fn = nn.MSELoss(size_average=False) # True相当于除以N/1 criterion需要y_hat和y则可求出loss
optimizer = torch.optim.SGD(model.parameters(),
lr=0.01) # 优化器不会构建计算图,不继承Module model.parameters()表优化器对哪些权重做优化和学习率,将来直接用其对模型优化
# 4. training cycle
for epoch in range(1000):
# forward
y_pred = model(x_data)
loss = loss_fn(y_pred, y_data)
print(epoch, loss.item())
# backward
optimizer.zero_grad() # member
loss.backward()
optimizer.step()
# output weight and bias
print('w =', model.linear.weight.item())
print('b = ', model.linear.bias.item())
# Test Model
x_test = torch.Tensor([[4.0]]) # 输入是1*1的矩阵
y_test = model(x_test) # 输出是1*1的矩阵
print('y_pred = ', y_test.data)
调用关系:model.linear.weight.item()用来拿到w和b
epoch=100
epoch=1000