pytorch实现回归模型
一、代码
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size())
net = torch.nn.Sequential(
torch.nn.Linear(1,10),
torch.nn.ReLU(),
torch.nn.Linear(10,1)
)
plt.ion()
plt.show()
optimizer = torch.optim.SGD(net.parameters(),lr=0.2)
loss_func = torch.nn.MSELoss()
for t in range(100):
pre_y = net(x)
loss = loss_func(pre_y,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t%5 == 0 :
plt.cla()
plt.scatter(x.data.numpy(),y.data.numpy())
plt.plot(x.data.numpy(),pre_y.data.numpy(),'r_',lw=5)
plt.text(0.5,0,'Loss=%.4f'%loss.data.numpy(),fontdict={'size':20,'color':'red'})
plt.pause(0.1)
二、实现效果
|