pytorch之 classification

 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 # make fake data
 8 n_data = torch.ones(100, 2)
 9 x0 = torch.normal(2*n_data, 1)      # class0 x data (tensor), shape=(100, 2)
10 y0 = torch.zeros(100)               # class0 y data (tensor), shape=(100, 1)
11 x1 = torch.normal(-2*n_data, 1)     # class1 x data (tensor), shape=(100, 2)
12 y1 = torch.ones(100)                # class1 y data (tensor), shape=(100, 1)
13 x = torch.cat((x0, x1), 0).type(torch.FloatTensor)  # shape (200, 2) FloatTensor = 32-bit floating
14 y = torch.cat((y0, y1), ).type(torch.LongTensor)    # shape (200,1) LongTensor = 64-bit integer
15 
16 # The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
17 # x, y = Variable(x), Variable(y)
18 
19 # plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')
20 # plt.show()
21 
22 
23 class Net(torch.nn.Module):
24     def __init__(self, n_feature, n_hidden, n_output):
25         super(Net, self).__init__()
26         self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
27         self.out = torch.nn.Linear(n_hidden, n_output)   # output layer
28 
29     def forward(self, x):
30         x = F.relu(self.hidden(x))      # activation function for hidden layer
31         x = self.out(x)
32         return x
33 
34 net = Net(n_feature=2, n_hidden=10, n_output=2)     # define the network
35 print(net)  # net architecture
36 
37 optimizer = torch.optim.SGD(net.parameters(), lr=0.02)
38 loss_func = torch.nn.CrossEntropyLoss()  # the target label is NOT an one-hotted
39 
40 plt.ion()   # something about plotting
41 
42 for t in range(100):
43     out = net(x)                 # input x and predict based on x
44     loss = loss_func(out, y)     # must be (1. nn output, 2. target), the target label is NOT one-hotted
45 
46     optimizer.zero_grad()   # clear gradients for next train
47     loss.backward()         # backpropagation, compute gradients
48     optimizer.step()        # apply gradients
49 
50     if t % 2 == 0:
51         # plot and show learning process
52         plt.cla()
53         prediction = torch.max(out, 1)[1]
54         pred_y = prediction.data.numpy()
55         target_y = y.data.numpy()
56         plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')
57         accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
58         plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color':  'red'})
59         plt.pause(0.1)
60 
61 plt.ioff()
62 plt.show()
原文地址:https://www.cnblogs.com/dhName/p/11742939.html