1. 程式人生 > >pytorch神經網路搭建及動態展示

pytorch神經網路搭建及動態展示

import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np


x = torch.unsqueeze(torch.linspace(-1, 1, 100), 1)
y = x.pow(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 = F.relu(self.hidden(x))
        x = self.predict(x)
        return x


net = Net(1, 10, 1)
print(net)
optimizer = torch.optim.SGD(net.parameters(), 0.2)
loss_func = torch.nn.MSELoss()
fig, ax = plt.subplots()
plots, = ax.plot(x.numpy(), net(x).detach().numpy(), 'r-', lw=2)


##利用Python繪製動態圖形
def train_step(i):
    prediction = net(x)
    loss = loss_func(prediction, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    label = 'step{0}'.format(i)
    ax.set_xlabel(label)
    plots.set_ydata(prediction.detach().numpy())
    return plots, ax


ani = animation.FuncAnimation(fig, train_step, frames=np.arange(200), interval=20)
plt.scatter(x.numpy(), y.numpy())
plt.show()