每日总结(2)
作者:互联网
今天学习了用pytorch框架进行线性模型的搭建。
import torch
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])
class LinerModel(torch.nn.Module):
def __init__(self):
super(LinerModel, self).__init__()#父类的初始化函数
self.linear = torch.nn.Linear(1, 1)
# def __init__(self, in_features, out_features, bias=True):
#形参的含义:in:输入样本是几维的即x的是几次方的 out:输出样本是几维的 ,bias是要不要加上偏执量
def forward(self, x):
y_pred = self.linear(x) #linera函数做的就是 (w*x+b)的操作
return y_pred
model = LinerModel()
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
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_data)
print('y_pred = ', y_test.detach())
标签:总结,__,每日,torch,print,model,data,self 来源: https://www.cnblogs.com/wlqyyds/p/16460365.html