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)
简单的线性回归(一维输入,一维输出)
最新推荐文章于 2022-05-06 09:19:04 发布