代码如下:
注意:如果没有安装matplat模块,可以把画图部分注释掉,然后把要画的点打印出来即可
import torch import torch.nn.functional as F import matplotlib.pyplot as plt # 1.假数据 n_data = torch.ones(100, 2) # 数据的基本形态 x0 = torch.normal(2*n_data, 1) # 类型0 x data (tensor), shape=(100, 2) y0 = torch.zeros(100) # 类型0 y data (tensor), shape=(100, ) x1 = torch.normal(-2*n_data, 1) # 类型1 x data (tensor), shape=(100, 1) y1 = torch.ones(100) # 类型1 y data (tensor), shape=(100, ) # 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是在合并数据) x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # FloatTensor = 32-bit floating y = torch.cat((y0, y1), 0).type(torch.LongTensor) # LongTensor = 64-bit integer print(x,x.size()) print() print(y,y.size()) plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn') plt.show() #2.建立神经网络 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) # 隐藏层线性输出n_hidden self.out=torch.nn.Linear(n_hidden,n_output)# 输出层线性输出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) # 几个类别就几个 output print(net) # net 的结构 #3.训练网络 optimizer=torch.optim.SGD(net.parameters(),lr=0.02)# 传入 net 的所有参数, 学习率 loss_func=torch.nn.CrossEntropyLoss()#损失函数 for t in range(200): # 喂给 net 训练数据 x, 输出分析值 out=net(x) # 计算两者的误差 loss=loss_func(out,y) # 清空上一步的残余更新参数值 optimizer.zero_grad() # 误差反向传播, 计算参数更新值 loss.backward() # 将参数更新值施加到 net 的 parameters 上 optimizer.step() #4.可视化训练过程 if t % 2 == 0: plt.cla() # 过了一道 softmax 的激励函数后的最大概率才是预测值 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()