淘先锋技术网

首页 1 2 3 4 5 6 7

这里用torch 做一个最简单的测试

 

目标就是我们用torch 建立一个一层的网络,然后拟合一组可以回归的数据

import torch
from torch.autograd import Variable
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())

x, y = Variable(x), Variable(y)

这里我们先早出来假数据,这里需要注意的是,最新版本的torch已经不需要variable了

接着我们来搭建我们的网络

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

 

我们做了个 1-10-1这样的单隐藏层的网络

net = Net(n_feature=1, n_hidden=10, n_output=1)
print(net)

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

接着我们选SGD来优化,选MSE做loss function

开始训练

plt.ion()

# begin training
for t in range(200):
    prediction = net(x)
    loss = loss_func(prediction, y)   # must be (1. nn output, 2. target)

    optimizer.zero_grad()  # clear gradients for next train
    loss.backward()   # backpropagation, compute gradients
    optimizer.step()    # apply gradients
    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.data.numpy(), fontdict={'size': 20, 'color': 'red'})
        plt.pause(0.1)

plt.ioff()
plt.show()

大概效果是这样

 

转载于:https://www.cnblogs.com/chenyusheng0803/p/10849053.html