import torch from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt # make fake data n_data = torch.ones(100, 2) X0 = torch.normal ( 2 * n_data, 1 ) of each element # (x, y) from the mean value = 2 * corresponding to the position n_data values, a standard deviation of a normal distribution of randomly generated yO = torch.zeros ( 100 ) 0 # a label to each element X1 = torch.normal (- 2 * n_data, 1 ) of each element # (x, y) from the mean = - 2 * corresponding to the position n_data values, a standard deviation of a normal distribution of randomly generated Y1 = torch.ones ( 100 ) # 1 to each element of a tag x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # shape (200, 2) FloatTensor = 32-bit floating y = torch.cat((y0, y1), ).type(torch.LongTensor) # shape (200,) LongTensor = 64-bit integer # torch can only train on Variable, so convert them to Variable x, y = Variable (x), variable (y) # draw the data plt.scatter (x.data.numpy () [:, 0 ], x.data.numpy () [:, . 1 ], C = y.data.numpy ()) is a sequence of colors C # #plt.show() # Neural network module class Net (torch.nn.Module): # inherited neural network module def __init __ (self, n_features, n_hidden, n_output): super neural network initialization parameter # super (Net, self) .__ init __ () # initialization method is called the parent neural network modules, three of the above fixing step, do not go into self.hidden = torch.nn.Linear (n_features, n_hidden) # Specifies how many input hidden layers, the number of output self.predict = torch.nn.Linear (n_hidden, n_output) # forecast specify how the input layer, the number of output def forward (self, x): # building neural networks x = F.relu (self.hidden (x)) # actively function through activation of the hidden layer processing x X = Data self.predict (x) # of the hidden layer through the layer obtain the prediction result predicted return X NET = Net ( 2 , 10 , 2 ) declare a class object # print(net) plt.ion () # and code between Plt.ion plt.ioff, interactive graphics plt.show() # Neural network optimizer, mainly in order to optimize our neural network, make him get up in our training process, saving time for training social networks. Optimizer = torch.optim.SGD (net.parameters (), LR = 0.01 ) # actually back propagation neural network, updating the first parameter is the weight and other parameters, corresponding to the second learning rate is loss_func = torch.nn.CrossEntropyLoss () # tag error cost function for t in range(50): out = net(x) Loss = loss_func ( OUT , Y) calculated loss # optimizer.zero_grad () # zero gradient loss.backward () # back-propagation optimizer.step () # of the compute nodes and gradient optimization, if t % 2 == 0: plt.cla () # Clear axis that is clear track before the current drawing Prediction = torch.max (F.softmax ( OUT ), . 1 ) [ . 1 ] # is converted into a probability, the maximum value of the index the latter one, if the maximum value returned is 0 pred_y = prediction.data.numpy().squeeze() target_y = y.data.numpy() plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn') Accuracy = SUM (pred_y == target_y) / 200 is . # accuracy requirements plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'}) plt.pause ( 0.1 ) plt.ioff () plt.show()
The following is a faster build neural network code, modified in the above code, the following code
import torch from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt # make fake data n_data = torch.ones(100, 2) X0 = torch.normal ( 2 * n_data, 1 ) of each element # (x, y) from the mean value = 2 * corresponding to the position n_data values, a standard deviation of a normal distribution of randomly generated yO = torch.zeros ( 100 ) 0 # a label to each element X1 = torch.normal (- 2 * n_data, 1 ) of each element # (x, y) from the mean = - 2 * corresponding to the position n_data values, a standard deviation of a normal distribution of randomly generated Y1 = torch.ones ( 100 ) # 1 to each element of a tag x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # shape (200, 2) FloatTensor = 32-bit floating y = torch.cat((y0, y1), ).type(torch.LongTensor) # shape (200,) LongTensor = 64-bit integer # torch can only train on Variable, so convert them to Variable x, y = Variable (x), variable (y) # draw the data plt.scatter (x.data.numpy () [:, 0 ], x.data.numpy () [:, . 1 ], C = y.data.numpy ()) is a sequence of colors C # #plt.show() # Neural network module net2 = torch.nn.Sequential( torch.nn.Linear(2,10), torch.nn.ReLU(), torch.nn.Linear(10,2) ) plt.ion () # and code between Plt.ion plt.ioff, interactive graphics plt.show() # Neural network optimizer, mainly in order to optimize our neural network, make him get up in our training process, saving time for training social networks. Optimizer = torch.optim.SGD (net.parameters (), LR = 0.01 ) # actually back propagation neural network, updating the first parameter is the weight and other parameters, corresponding to the second learning rate is loss_func = torch.nn.CrossEntropyLoss () # tag error cost function for t in range(50): out = net(x) Loss = loss_func ( OUT , Y) calculated loss # optimizer.zero_grad () # zero gradient loss.backward () # back-propagation optimizer.step () # of the compute nodes and gradient optimization, if t % 2 == 0: plt.cla () # Clear axis that is clear track before the current drawing Prediction = torch.max (F.softmax ( OUT ), . 1 ) [ . 1 ] # is converted into a probability, the maximum value of the index the latter one, if the maximum value returned is 0 pred_y = prediction.data.numpy().squeeze() target_y = y.data.numpy() plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn') Accuracy = SUM (pred_y == target_y) / 200 is . # accuracy requirements plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'}) plt.pause ( 0.1 ) plt.ioff () plt.show()