guopengfa
发布于 2022-04-21 / 2417 阅读 / 0 评论 / 0 点赞

pytorch 1

let's use torch to create first neural network: according we input data to trainning model by itself.

import torch
from torch.nn import functional
from matplotlib import pyplot as plt


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 = functional.relu(self.hidden(x))
        x = self.predict(x)
        return x


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


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

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

plt.figure(1, figsize=(8, 5))
plt.subplot(111)
plt.scatter(x.numpy(), y.numpy())
# plt.show()

plt.ion()
plt.show()

for t in range(500):
    prediction = net(x)
    loss = loss_func(prediction, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    # plot
    if t % 5 == 0:
        plt.cla()
        plt.scatter(x, y)
        plt.plot(x, prediction.data.numpy())
        plt.text(0.5, 0, f'loss={loss.data.numpy()}', fontdict={'size': 20, 'color':  'red'})
        plt.pause(0.1)

fit_progress.gif


评论