由于近期想做一些关于回归分析的问题,所以就尝试使用了一下多层感知机来构建模型,效果还挺不错,因而记录一下。
一、简介
二、实现步骤
三、代码实现
四、小批量代码实现
一、简介
从已有的文献来看,感知机应该是已知最早的神经网络模型,它在1960年应该就被提出。之后由于单层感知机无法解决XOR问题,所以被搁浅,直至1969年多层感知机的提出,神经网络又焕发了活力。作为最早的多层神经网络,它已初具后世一直沿用的网络结构,如输入层、隐藏层、输出层、激活函数以及优化器等。具体内容可以观看李沐老师的视频,讲的很清楚。
二、实现步骤
主要分为以下几个步骤: (1)获取输入数据。这些数据可以是csv文件或者是其他等等,不管怎样它们尽可能都要行数据的标椎化处理。 (2)设计网络结构。如设置隐藏层的数量、epoch次数以及学习率等等。 (3)训练模型并获得预测值。 (4)计算损失值。使用事先选好的损失函数来计算预测值与真值之间的差距。 (5)清零、计算并更新梯度。这些工作后面会用于W的更新。 (6)重复(3)~(5)的过程epoch次即可。
三、代码实现
'''
多层感知机
'''
#导入所需要的包
import d2lzh_pytorch
from pandas._config.config import reset_option
import torch
from torch import nn
from torch.autograd import Variable
import pandas as pd
#初始化权重
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight,std=0.01)
'''
#z-score标准化
'''
def standard(df):
for key in df.keys():
if df[key].dtype != object and key !="季度":
mean = df[key].mean()
std = df[key].std()
df[key] = (df[key] - mean)/std
#R平方
def Rsquare(y_pred,y):
y_mean = y.mean()
SSr = (y_pred - y_mean).pow(2).sum()
SSt = (y - y_mean).pow(2).sum()
return SSr/SSt
#调整后R平方
def RsquareAdjust(y_pred,y,n,p):
# y_mean = y.mean()
# SSt = (y - y_mean).pow(2).sum()
# SSe = (y-y_pred).pow(2).sum()
r2 = Rsquare(y_pred,y)
return 1-((1-r2)*(n-1)/(n-p-1))
# return 1-((SSe/(n-p-1))/(SSt/(n-1)))
# 继承 nn.Module
class MLPNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(MLPNet, self).__init__()
self.flatten = torch.nn.Flatten()
self.linear1 = torch.nn.Linear(input_size, hidden_size)
self.relu1 = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(hidden_size, output_size)
def forward(self, x):
x = torch.flatten(x)
Z1 = self.linear1(x)
A1 = self.relu1(Z1)
y_pred = self.linear2(A1)
return y_pred
if __name__ == "__main__":
#获取数据
df = pd.read_csv(r"C:\Users\23547\Desktop\others\yingying\data\pm2.5nian经度0.721.csv")
#数据归一化处理
standard(df)
x = Variable(torch.as_tensor(df.values[:,0:5]))
y = Variable(torch.as_tensor(df.values[:,5]))
#构建网路模型
# net = nn.Sequential(
# nn.Flatten(), #首先将多维维数据转换为一维数据
# nn.Linear(74*5,256),
# nn.ReLU(),
# nn.Linear(256,74)
# )
net = MLPNet(74*5,256,74)
net = net.double()
# net.apply(init_weights)
#设置超参数
batch_size, lr, num_epochs = 256, 0.001,15
#定义损失函数
# loss_fn = nn.CrossEntropyLoss(reduction='none')
loss_fn = nn.MSELoss(reduction="sum")
#优化器
optimizer = torch.optim.SGD(net.parameters(),lr=lr)
#训练
for i in range(num_epochs):
#向前传播
y_pred = net(x.to(torch.double))
#计算损失
loss = loss_fn(y_pred,y)
print("第{}迭代,损失为:{}".format(i+1,loss.item()))
#将之前累积的梯度清零
optimizer.zero_grad()
#计算梯度
loss.backward()
#更新梯度
optimizer.step()
# print(y)
net.eval()
y_pred = net(x.to(torch.double))
# print(y_pred)
r2 = Rsquare(y_pred,y)
print("R平方值为:{}".format(r2))
r2_adjust = RsquareAdjust(y_pred,y,74,5)
print("调整后R平方值为:{}".format(r2_adjust))
实验结果:
四、小批量代码实现
上述方式虽然拟合精度很高,但是像这样训练出的模型几乎没啥用,因为模型发生了过拟合(参数过多),而且进行预测的时候输入的数据也必须是mxn的矩阵,这不利于后续的使用,因此我后面改用小批量的方式来实现建模过程,如下所示。
'''
多层感知机
'''
#导入所需要的包
import torch
from torch import nn
from torch.autograd import Variable
import pandas as pd
from sklearn.model_selection import KFold
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
#创建自定义数据集
class MyDataset(Dataset):
def __init__(self, data, samples,transform=None, target_transform=None):
self.samples = samples
self.data = data
self.transform = transform
self.target_transform = target_transform
def __len__(self):
return (len(self.data) // self.samples)
def __getitem__(self, idx):
trainData = torch.as_tensor(
self.data.values[idx*self.samples:(idx+1)*self.samples,0:5])
label = torch.as_tensor(
self.data.values[idx*self.samples:(idx+1)*self.samples,5])
sample = {'trainData':trainData,'label':label}#根据图片和标签创建字典
return sample
#初始化权重
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight,std=0.01)
'''
#z-score标准化
'''
def standard(df):
for key in df.keys():
if df[key].dtype != object and key !="季度":
mean = df[key].mean()
std = df[key].std()
df[key] = (df[key] - mean)/std
#R平方
def Rsquare(y_pred,y):
y_mean = y.mean()
SSr = (y_pred - y_mean).pow(2).sum()
SSt = (y - y_mean).pow(2).sum()
return SSr/SSt
#调整后R平方
def RsquareAdjust(y_pred,y,n,p):
# y_mean = y.mean()
# SSt = (y - y_mean).pow(2).sum()
# SSe = (y-y_pred).pow(2).sum()
r2 = Rsquare(y_pred,y)
return 1-((1-r2)*(n-1)/(n-p-1))
# return 1-((SSe/(n-p-1))/(SSt/(n-1)))
# 继承 nn.Module
class MLPNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(MLPNet, self).__init__()
self.flatten = torch.nn.Flatten()
self.linear1 = torch.nn.Linear(input_size, hidden_size)
self.relu1 = torch.nn.ReLU()
self.linear2 = torch.nn.Linear(hidden_size, output_size)
def forward(self, x):
x = self.flatten(x)
Z1 = self.linear1(x)
A1 = self.relu1(Z1)
y_pred = self.linear2(A1)
return y_pred
if __name__ == "__main__":
#获取数据
df = pd.read_csv(r"C:\Users\23547\Desktop\others\yingying\data\pm2.5nian经度0.721.csv")
#数据归一化处理
standard(df)
x = Variable(torch.as_tensor(df.values[:,0:5]))
y = Variable(torch.as_tensor(df.values[:,5]))
#设置超参数
samples,lr, num_epochs = 1,0.001,200
#定义损失函数
# loss_fn = nn.CrossEntropyLoss(reduction='none')
loss_fn = nn.MSELoss(reduction="sum")
#优化器
net = MLPNet(samples*5,32,samples)
net = net.double()
optimizer = torch.optim.SGD(net.parameters(),lr=lr)
#小批量
myDataset = MyDataset(df,samples)
loader = DataLoader(myDataset,batch_size=20,shuffle=False)
for id,batch_data in enumerate(loader):
print("第{}批次".format(id))
trainData = batch_data['trainData']
print("训练集大小:{}".format(trainData.size()))
trainLabels = batch_data['label']
#训练
for j in range(num_epochs):
#向前传播
y_pred = net(trainData.to(torch.double))
#计算损失
loss = loss_fn(y_pred,trainLabels)
print("第{}迭代,损失为:{}".format(j+1,loss.item()))
#将之前累积的梯度清零
optimizer.zero_grad()
#计算梯度
loss.backward()
#更新梯度
optimizer.step()
net.eval()
y_pred = torch.tensor([])
for it in range(len(y)):
y_tmp = net(x[it].reshape(1,1,5))
y_pred = torch.cat([y_pred,y_tmp],1)
y_pred = torch.flatten(y_pred)
r2 = Rsquare(y_pred,y)
print("R平方值为:{}".format(r2))
r2_adjust = RsquareAdjust(y_pred,y,74,5)
print("调整后R平方值为:{}".format(r2_adjust))
实验结果:
参考资料:李沐老师视频、百度Paddle相关资料