简单的线性回归(一维输入,一维输出)

import torch
import torch.nn.functional as F
import matplotlib.pylab as plt
import torch.nn as nn

#1.构建数据集 y=x+1
x=torch.tensor([[1.0],
                [2.0],
                [3.0]])
y=torch.tensor([[2.0],
                [3.0],
                [4.0]])

plt.plot(x,y)
plt.show()

#2.搭建神经网络
class LinearNet(nn.Module):
    def __init__(self,num_input,num_output):
        super(LinearNet,self).__init__() #官方定义模板
        self.predict=nn.Linear(num_input,num_output,bias=True)

    def forward(self,x):
        y=self.predict(x)
        return y

net=LinearNet(1,1)

#3.定义优化器和损失函数
optimizer=torch.optim.SGD(net.parameters(),lr=0.05)
loss_func=nn.MSELoss()

#4.训练模型
for epoch in range(100):
    y_prediction=net(x)
    loss=loss_func(y_prediction,y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    print(epoch,loss)

x_test=torch.tensor([[4.0]])
y_test=net(x_test)
print(y_test)
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页