使用pytorch快速搭建神经网络解决回归问题
详细代码与注释:
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = pow(x, 2) + 0.2 * torch.rand(x.size())
class Net(torch.nn.Module):
def __init__(self, n_features, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_features, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
x = torch.relu(self.hidden(x))
x = self.predict(x)
return x
net = Net(1, 10, 1)
print(net)
plt.ion()
optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
loss_func = torch.nn.MSELoss()
for t in range(100):
prediction = net(x)
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % 5 == 0:
plt.cla()
plt.scatter(x, y)
plt.plot(x.numpy(), prediction.detach().numpy(), "r-", lw=5)
plt.text(0.5, 0, "Loss=%.4f" % loss.data.numpy(), fontdict={"size": 20, "color": "red"})
plt.pause(0.2)
print(f"最终的loss为{loss.data.numpy()}")
plt.ioff()
plt.show()
效果展示:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e2f3f2a80f5b2fb6eaecba7180070195.gif)