用Sequential快速搭建pytorch神经网络

用Sequential快速搭建pytorch神经网络

pytorch实现回归一文中,搭建神经网络分为两步,首先确定每层结构,然后规定数据流向。

以下代码用Sequential类一步快速搭建神经网络:

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

os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + torch.rand(x.size()) * 0.2
x = Variable(x)
y = Variable(y)


# plt.scatter(x.data.numpy(), y.data.numpy())
# plt.show()


class Net(torch.nn.Module):
    def __init__(self, n_input, n_hidden, n_output):
        super(Net, self).__init__()
        self.l1 = torch.nn.Linear(n_input, n_hidden)
        self.l2 = torch.nn.Linear(n_hidden, n_output)

    def forward(self, x):
        x = F.relu(self.l1(x))
        x = self.l2(x)
        return x


net1 = Net(1, 10, 1)

net2 = torch.nn.Sequential(
    torch.nn.Linear(1, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 1)
)

plt.ion()
plt.show()

optimizer = torch.optim.SGD(net2.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss()

for t in range(2000):
    prediction = net2(x)  # result from neural network
    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)  # color of line = r,width of line = 5
        plt.text(0.5, 0, ‘Loss=%.4f‘ % loss.data, fontdict={‘size‘: 20, ‘color‘: ‘red‘})
        plt.pause(0.1)
plt.ioff()
plt.show()

输出结果:

用Sequential快速搭建pytorch神经网络

第34行的net2即使用Sequential搭建神经网络的过程,其他代码与pytorch实现回归文中代码相同。

最后应用此网络的输出效果与pytorch实现回归的结果一致。

只需在Sequential类中依次输入每一层结构,即可完成搭建。

用Sequential快速搭建pytorch神经网络

上一篇:dremio 反射支持小于小时的处理


下一篇:解决: Uncaught ReferenceError: process is not defined