- 用pytorch搭建神经网络,将数据分成两类
- 环境 pytoch1.1.0
1. 生成训练数据
data = torch.ones(100, 2)
x1 = torch.normal(mean=2*data, std=1)
y1 = torch.zeros(100)
x2 = torch.normal(mean=-2*data, std=1)
y2 = torch.ones(100)
train_x = torch.cat((x1, x2), dim=0).type(torch.float32)
label_y = torch.cat((y1, y2), dim=0).type(torch.int64)
2. 搭建神经网络
class Neuro_net(torch.nn.Module):
"""神经网络"""
def __init__(self, n_feature, n_hidden_layer, n_output):
super(Neuro_net, self).__init__()
self.hidden_layer = torch.nn.Linear(n_feature, n_hidden_layer)
self.output_layer = torch.nn.Linear(n_hidden_layer, n_output)
def forward(self, input):
hidden_out = torch.relu(self.hidden_layer(input))
out = self.output_layer(hidden_out)
return out
3. 训练神经网络
num_feature = 2
num_hidden_layer = 10
num_output = 2
epoches = 200
net = Neuro_net(num_feature, num_hidden_layer, num_output)
print(net)
optimizer = torch.optim.SGD(net.parameters(), lr=0.002)
loss_function = torch.nn.CrossEntropyLoss()
for epoch in range(epoches):
out = net(train_x)
loss = loss_function(out, label_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
4. 为了更好理解训练过程,加入可视化
import matplotlib.pyplot as plt
plt.ion()
for epoch in range(epoches):
...
loss.backward()
optimizer.step()
if epoch % 5 == 0:
print("已训练{}步 | loss:{}。".format(epoch, loss))
plt.cla()
pridect_y = torch.max(out, dim=1)[1]
pridect_label = pridect_y.data.numpy()
true_label = label_y.data.numpy()
plt.scatter(train_x.data.numpy()[:, 0], train_x.data.numpy()[:, 1], c=pridect_label)
accuracy = float((pridect_label == true_label).astype(int).sum()) / float(true_label.size)
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 12, 'color': 'blue'})
plt.pause(0.1)
plt.ioff()
plt.show()
整体代码:
import torch
import matplotlib.pyplot as plt
class Neuro_net(torch.nn.Module):
"""神经网络"""
def __init__(self, n_feature, n_hidden_layer, n_output):
super(Neuro_net, self).__init__()
self.hidden_layer = torch.nn.Linear(n_feature, n_hidden_layer)
self.output_layer = torch.nn.Linear(n_hidden_layer, n_output)
def forward(self, input):
hidden_out = torch.relu(self.hidden_layer(input))
out = self.output_layer(hidden_out)
return out
data = torch.ones(100, 2)
x1 = torch.normal(mean=2*data, std=1)
y1 = torch.zeros(100)
x2 = torch.normal(mean=-2*data, std=1)
y2 = torch.ones(100)
train_x = torch.cat((x1, x2), dim=0).type(torch.float32)
label_y = torch.cat((y1, y2), dim=0).type(torch.int64)
num_feature = 2
num_hidden_layer = 10
num_output = 2
epoches = 200
net = Neuro_net(num_feature, num_hidden_layer, num_output)
print(net)
plt.ion()
optimizer = torch.optim.SGD(net.parameters(), lr=0.002)
loss_function = torch.nn.CrossEntropyLoss()
for epoch in range(epoches):
out = net(train_x)
loss = loss_function(out, label_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if epoch % 5 == 0:
print("已训练{}步 | loss:{}。".format(epoch, loss))
plt.cla()
pridect_y = torch.max(out, dim=1)[1]
pridect_label = pridect_y.data.numpy()
true_label = label_y.data.numpy()
plt.scatter(train_x.data.numpy()[:, 0], train_x.data.numpy()[:, 1], c=pridect_label)
accuracy = float((pridect_label == true_label).astype(int).sum()) / float(true_label.size)
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 12, 'color': 'blue'})
plt.pause(0.1)
plt.ioff()
plt.show()
可视化动态拟合图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a74c6fe0286f64d2be2e6753c11602c0.png)