""" pytorch中数据标签默认的数据格式是LongTensor,即64位的整数 """ import torch from torch.autograd import Variable import torch.nn.functional as F import matplotlib.pyplot as plt # 制作数据 n_data = torch.ones(100, 2) x0 = torch.normal(2*n_data, 1) # x0的横纵坐标 y0 = torch.zeros(100) # x0对应的标签 x1 = torch.normal(-2*n_data, 1) # x1的横纵坐标 y1 = torch.ones(100) # x1对应的标签 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 x, y = Variable(x), Variable(y) # 以下显示出散点图 # plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn') # plt.show() 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.out = torch.nn.Linear(n_hidden, n_output) def forward(self, x): x = F.relu(self.hidden(x)) x = self.out(x) return x net = Net(n_feature=2, n_hidden=10, n_output=2) # 定义网络 print(net) # 打印出网络结构 optimizer = torch.optim.SGD(net.parameters(), lr=0.02) loss_func = torch.nn.CrossEntropyLoss() # 用于分类问题 plt.ion() # 设置为实时打印 for t in range(100): out = net(x) # 输入x经过网络的前向传播,得到预测值,此时还不是概率 loss = loss_func(out, y) # 预测值在前,真实值在后 optimizer.zero_grad() # 清除上一次的梯度 loss.backward() # 反向传播,计算梯度 optimizer.step() # 优化梯度 if t % 2 == 0: # 打印 plt.cla() prediction = torch.max(F.softmax(out), 1)[1] 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. plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'}) plt.pause(0.1) plt.ioff() plt.show()