本文的程序中的神经网络模型来着于上一篇文章,只是上一个文章是对mnist中的图片进行处理,而本文用AE对一串数据进行处理,得到这串数据的特征信息。
一、python程序(基于pytorch)
import torch
import torch.nn as nn
import torch.nn.functional as F
# 创建模型
class AE_Net(nn.Module):
def __init__(self):
super(AE_Net,self).__init__()
self.encoder1=nn.Linear(16,8)
self.encoder2=nn.Linear(8,4)
self.encoder3=nn.Linear(4,2)
self.decoder1=nn.Linear(2,4)
self.decoder2=nn.Linear(4,8)
self.decoder3=nn.Linear(8,16)
def forward(self,x):
x = F.relu(self.encoder1(x))
# print(x)
x = F.relu(self.encoder2(x))
# print(x)
x = F.relu(self.encoder3(x))
print(x)
x = F.relu(self.decoder1(x))
# print(x)
x = F.relu(self.decoder2(x))
# print(x)
# x = self.decoder3(x)
x = torch.sigmoid(self.decoder3(x))
# print(x)
x = x.squeeze(-1)
# print(x)
return x
# 定义传入数据
x=torch.tensor(torch.linspace(0.4,0.8,16))
# x=torch.unsqueeze(x,dim=1)
net=AE_Net() # 建模三大法宝
optimizer=torch.optim.Adam(net.parameters(),lr=1e-3) # 优化
los=nn.MSELoss() # 损失
# 多次训练
for i in range(600):
y=net(x)
loss = los(y, x) # decoder的输出y就应该跟一开始encoder的输入一样,以他们的差作为损失
# loss = los(y, x.view(-1, 16))
optimizer.zero_grad() # 三大固定步骤 优化阶梯归零
loss.backward() # 后向传递
optimizer.step() # 更新参数
print(y)
二、输出结果
能够得出瓶颈层的那两个神经元对应的数,但是不懂它包含的物理意义。
三、Notice
当输入的数据的个数是n时,输入层和输出层的神经元应该是n个,如果写为其他数值则会报错。
x=torch.tensor(torch.linspace(0.4,0.8,16))
self.encoder1=nn.Linear(16,8)
self.decoder3=nn.Linear(8,16)