完整代码:

import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
import torch.optim as optim

#生成数据
#随机取100个-1到1之间的数,利用unsqueeze将一维变成二维
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size())

#神经网络只能接受Variable的数
x,y = Variable(x),Variable(y)

#绘制图像
plt.scatter(x.data.numpy(), y.data.numpy())
#plt.show()


#定义网络
class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.predict = torch.nn.Linear(n_hidden,n_output)

    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = self.predict(x)
        return x

net = Net(1, 10, 1)
#print(net)  


#优化
optimizer = optim.SGD(net.parameters(), lr=0.5)
loss_func = torch.nn.MSELoss()

#可视化
plt.ion()
#plt.show()

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.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
        plt.text(0.5, 0, 'Loss=%.4f' % loss.item(), fontdict={'size': 20, 'color':  'red'})
        plt.pause(0.1)

plt.ioff()
plt.show()

 

在我运行代码是,出现过以下报错:

这是因为我的pytorch版本比较高,将代码plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})改为plt.text(0.5, 0, 'Loss=%.4f' % loss.item(), fontdict={'size': 20, 'color': 'red'})就好了