1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| import torch as t import torch.nn as nn from torch.autograd import Variable as V import torch.optim as opt
import matplotlib.pyplot as plt
x = t.unsqueeze(t.linspace(-1, 1, 100), dim=1) y = x.pow(2) + 0.2 * t.rand(x.size()) x, y = V(x), V(y)
class myNet(nn.Module): def __init__(self, n_features, n_hidden, n_output): super(myNet, self).__init__() self.hidden = nn.Linear(n_features, n_hidden) self.predict = nn.Linear(n_hidden, n_output) def forward(self, x): x = self.hidden(x) x = self.predict(nn.ReLU()(x)) return x net = myNet(1, 10, 1) print(net)
criterion = nn.MSELoss() optimaizer = opt.SGD(net.parameters(), lr=0.5)
for t in range(100): optimaizer.zero_grad() prediction = net(x) loss = criterion(prediction, y) loss.backward() optimaizer.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.data, fontdict={'size': 20, 'color': 'red'}) plt.pause(0.1)
plt.ioff() plt.show()
|