利用神经网络对一组数据进行二分类
老生常谈,导入函数库
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
生成伪数据
n_data=torch.ones(100,2)#生成100行2列的全1矩阵
x0=torch.normal(2*n_data,1)#生成以2为中心的随机数矩阵
x1=torch.normal(-2*n_data,1)#生成以-2为中心的随机数矩阵
y0=torch.zeros(100)#作为标签--0
y1=torch.ones(100)#作为标签--1
x=torch.cat((x0,x1),0).type(torch.FloatTensor)#将矩阵竖着拼,合并一起作为数据
y=torch.cat((y0,y1),).type(torch.LongTensor)
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()
#[:,0]行范围全取,列范围取到0
生成图像如下
搭建神经网络
Class Net(torch.nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(Net,self).__init__() # 继承 __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(2,10,2)
print(net)
搭建好的网络
Net(
(hidden): Linear(in_features=2, out_features=10, bias=True)
(out): Linear(in_features=10, out_features=2, bias=True)
)
优化网络参数
optimizer=torch.optim.SGD(net.parameters(),lr=0.02)
loss_func=torch.nn.CrossEntropyLoss()#解决二分类问题
画图代码起点
plt.ion()
plt.show()
训练网络
for t in range(100):
out=net(x)
loss=loss_func(out,y)
optimizer.zero_autograd()
loss.backward()
optimizer.step()
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()