参考自:
https://blog.csdn.net/weixin_44912159/article/details/105051602
https://blog.csdn.net/Ever_glow/article/details/89086960
以下代码摘抄自https://blog.csdn.net/weixin_44912159/article/details/105051602
,请先阅读上述参考文章。(改了几个参数试试)
import torch
import matplotlib.pyplot as plt
# 搭建神经网络
class Neuro_net(torch.nn.Module): #主要构成为__init__和forward函数
"""神经网络"""
def __init__(self, n_feature, n_hidden_layer, n_output):
super(Neuro_net, self).__init__() #固定继承模块
self.hidden_layer1 = torch.nn.Linear(n_feature, 25) #第一个隐层,2,25
self.hidden_layer2 = torch.nn.Linear(25, 20) #第二个隐层,25,20
self.output_layer = torch.nn.Linear(20, n_output) #输出层, 20,2
def forward(self, input):
hidden_out1 = torch.relu(self.hidden_layer1(input)) #将第一个隐层的输入relu
out1 = self.hidden_layer2(hidden_out1) #将第一个隐层的输出作为第二个隐层的输入
hidden_out2 = torch.relu(out1) #第二个隐层的输入relu
out2 = self.output_layer(hidden_out2) #将第二个隐层的输出作为输出层的输入
return out2
## 准备数据
data = torch.ones(100, 2)
x1 = torch.normal(mean=2*data, std=1)
y1 = torch.zeros(100) # x1 对应的标签
x2 = torch.normal(mean=-2*data, std=1)
y2 = torch.ones(100) # x2 对应的标签
train_x = torch.cat((x1, x2), dim=0).type(torch.float32) # 合并两类数据(x1, x2),生成训练数据
label_y = torch.cat((y1, y2), dim=0).type(torch.int64) # 合并两类便签(y1,y2),生成真实标签
print(train_x, label_y)
# # 查看数据分布
# plt.scatter(train_x.numpy()[:, 0], train_x.numpy()[:, 1])
# plt.show()
## 进行训练
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.02)
# 定义损失函数
loss_function = torch.nn.CrossEntropyLoss()
for epoch in range(epoches):
#以下的五句话为固定使用
out = net(train_x) #网络输出
loss = loss_function(out, label_y) #计算网络预测值和真实值之间的loss
optimizer.zero_grad() #因为训练的过程通常使用mini-batch方法,所以如果不将梯度清零的话,梯度会与上一个batch的数据相关,因此该函数要写在反向传播和梯度下降之前。
loss.backward() #反向传播
optimizer.step() #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() # 预测的label
true_label = label_y.data.numpy() # 真实的label
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()
最重要且固定的: