1.前言
这次我们也是用最简单的途径来看看神经网络是怎么进行事物的分类.
2.数据准备
import torch
import matplotlib.pyplot as plt
n_data = torch.ones(200,2)
x0 = torch.normal(2*n_data, 1)
y0 = torch.zeros(200)
x1 = torch.normal(-2*n_data, 1)
y1 = torch.ones(200)
x = torch.cat((x0,x1),0).type(torch.FloatTensor)
print(x)
y = torch.cat((y0,y1),).type(torch.LongTensor)
print(y)
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy())
plt.show()
3.搭建神经网络
建立一个神经网络我们可以直接运用 torch 中的体系. 先定义所有的层属性(init()), 然后再一层层搭建(forward(x))层于层的关系链接. 这个和我们在前面回归问题的神经网络相似. 建立关系的时候, 我们会用到激励函数
from torch import nn
import torch.nn.functional as F
class NetWork(nn.Module):
def __init__(self,n_input,n_hidden,n_output):
super(NetWork,self).__init__()
self.hidden = nn.Linear(n_input, n_hidden)
self.output_for_predict = nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.output_for_predict(x)
return x
network = NetWork(n_input = 1,n_hidden = 8, n_output = 2) #对于二分类问题n_output为2
print(network) #打印网络结构
4.训练搭建的神经网络
训练的步骤很简单, 如下:
optimizer = torch.optim.SGD(network.parameters(), lr = 0.01)
criterion = nn.CrossEntropyLoss()
for i in range(200):
out = network(x) #把数据放入模型得到预测值
loss = criterion(out, y) #计算预测值与真是值之间的误差
loss.backward() #误差的反向传递
optimizer.step() #更新参数到network.parameters()
5.可视化操作
import torch
import matplotlib.pyplot as plt
n_data = torch.ones(100,2)
x0 = torch.normal(2*n_data, 1)
y0 = torch.zeros(100)
x1 = torch.normal(-2*n_data, 1)
y1 = torch.ones(100)
x = torch.cat((x0,x1),0).type(torch.FloatTensor)
#print(x)
y = torch.cat((y0,y1),).type(torch.LongTensor)
#print(y)
from torch import nn
import torch.nn.functional as F
class NetWork(nn.Module):
def __init__(self,n_input,n_hidden,n_output):
super(NetWork,self).__init__()
self.hidden = nn.Linear(n_input, n_hidden)
self.output_for_predict = nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.output_for_predict(x)
return x
network = NetWork(n_input = 2,n_hidden = 8, n_output = 2) #对于二分类问题n_output为2
print(network) #打印网络结构
import matplotlib.pyplot as plt
plt.ion()
plt.show()
optimizer = torch.optim.SGD(network.parameters(), lr = 0.01)
criterion = nn.CrossEntropyLoss()
for i in range(200):
out = network(x) #把数据放入模型得到预测值
loss = criterion(out, y) #计算预测值与真是值之间的误差
optimizer.zero_grad()
loss.backward() #误差的反向传递
optimizer.step() #更新参数到network.parameters()
if i % 5 == 0:
plt.cla()
predication = torch.max(F.softmax(out),1)[1]
print(torch.max(F.softmax(out),1))
print(predication)
pred_y = predication.data.numpy().squeeze()
target_y = y.data.numpy()
plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y)
accuracy = sum(pred_y == target_y)/200
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size':20,'color':'red'})
plt.pause(0.5)
plt.ioff()
plt.show()