pytorch之 regression
1 import torch 2 import torch.nn.functional as F 3 import matplotlib.pyplot as plt 4 5 # torch.manual_seed(1) # reproducible 6 7 x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # x data (tensor), shape=(100, 1) 8 y = x.pow(2) + 0.2*torch.rand(x.size()) # noisy y data (tensor), shape=(100, 1) 9 10 # torch can only train on Variable, so convert them to Variable 11 # The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors 12 # x, y = Variable(x), Variable(y) 13 14 # plt.scatter(x.data.numpy(), y.data.numpy()) 15 # plt.show() 16 17 18 class Net(torch.nn.Module): 19 def __init__(self, n_feature, n_hidden, n_output): 20 super(Net, self).__init__() 21 self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer 22 self.predict = torch.nn.Linear(n_hidden, n_output) # output layer 23 24 def forward(self, x): 25 x = F.relu(self.hidden(x)) # activation function for hidden layer 26 x = self.predict(x) # linear output 27 return x 28 29 net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network 30 print(net) # net architecture 31 32 optimizer = torch.optim.SGD(net.parameters(), lr=0.2) 33 loss_func = torch.nn.MSELoss() # this is for regression mean squared loss 34 35 plt.ion() # something about plotting 36 37 for t in range(200): 38 prediction = net(x) # input x and predict based on x 39 40 loss = loss_func(prediction, y) # must be (1. nn output, 2. target) 41 42 optimizer.zero_grad() # clear gradients for next train 43 loss.backward() # backpropagation, compute gradients 44 optimizer.step() # apply gradients 45 46 if t % 5 == 0: 47 # plot and show learning process 48 plt.cla() 49 plt.scatter(x.data.numpy(), y.data.numpy()) 50 plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5) 51 plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'}) 52 plt.pause(0.1) 53 54 plt.ioff() 55 plt.show()