import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
torch.manual_seed(100)
## 生成数据
x = torch.linspace(-1, 1, 100).view(-1,1) # shape=(100, 1),(batch,dim)
y = x.pow(2) + 0.2*torch.rand(x.shape) # shape=(100, 1),(batch,dim)
# plt.scatter(x.numpy(), y.numpy())
# plt.show()
## 构建网络
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(1, 10)
self.output = torch.nn.Linear(10, 1)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.output(x)
return x
## 初始化网络,优化器和损失函数
net = Net()
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
mse = torch.nn.MSELoss()
## 开始训练
for t in range(200):
prediction = net(x)
loss = mse(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 可视化
if t % 5 == 0:
plt.scatter(x.numpy(), y.numpy())
plt.plot(x.numpy(), prediction.detach().numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.detach().numpy(), fontdict={'size': 20, 'color': 'red'})
plt.pause(0.2)
plt.clf() # 清除当前图像
plt.show()
参考:
https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents/301_regression.py