在本节的课程中,利用PyTorh实现了线性模型,总结如下:
给出代码:
import torch
x_data = torch.tensor([[1.0],[2.0],[3.0]])
y_data = torch.tensor([[2.0],[4.0],[6.0]])
print(x_data.shape)
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)
epoch_list=[]
loss_list=[]
for epoch in range(100):
for x,y in zip(x_data,y_data):
y_pred = model(x)
print(y_pred.shape)
loss = criterion(y_pred,y)
#
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)
未完待续。。。。
|