建建设网站,保定网站建设找谁,音乐网站排名,番禺外贸网站建设快速搭建一个简单的神经网络预测模型 采用的数据是kaggle的房价预测数据 涉及的数据文件#xff0c;提取码为#xff1a;zxcv
#导入相关包
import pandas as pd
import numpy as np
import torch
import torch.nn as nn首先读取数据
trainpd.read_csv(path,enc…快速搭建一个简单的神经网络预测模型 采用的数据是kaggle的房价预测数据 涉及的数据文件提取码为zxcv
#导入相关包
import pandas as pd
import numpy as np
import torch
import torch.nn as nn首先读取数据
trainpd.read_csv(path,encodinggbk)
testpd.read_csv(path,encodinggbk)数据预处理 数据预处理包括对数据进行标准化处理将非数字类型数据转化为数字类型数据
#查看训练集和测试集的数据大小
train.shape
#(1460, 81)
test.shape
#(1460, 81)
#将需要训练和测试的特征合成为一个DataFrame保证对于训练数据和测试数据的处理是一致的。
all_featurepd.concat([train.iloc[:,1:80],test.iloc[]])
#找出数字类型的数据进行标准化处理
num_da[i for i in all_feature.columns if all_feature[i].dtypes!object]
all_feature[num_da]all_feature[num_da].apply(lambda x: (x-x.mean())/x.std())
#将非数字类型数据转化为数字类型的数据
all_featurepd.get_dummies(all_feature,dummy_naTrue)
#对缺失值用所在列的均值进行填充
all_feature all_feature.fillna(all_feature.mean())
#将训练数据的y取log值
train_ytrain[SalePrice].apply(lambda x:np.log(x))将数据划分为训练数据集和测试数据集做好数据的预处理转化工作之后
X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.2, random_state42)
X_train torch.tensor(X_train.values, dtypetorch.float32)
y_train torch.tensor(y_train.values, dtypetorch.long)
X_test torch.tensor(X_test.values, dtypetorch.float32)
y_test torch.tensor(y_test.values, dtypetorch.long)数据转换python
#我们需要将dataframe数据转化为神经网络能处理的tensor数据
input_xtorch.tensor(all_feature.iloc[:train.shape[0],:].values.astype(np.float32))
input_ytorch.tensor(train_y.values.astype(np.float32))
test_xtorch.tensor(all_feature.iloc[train.shape[0]:,:].values.astype(np.float32))
#查看各类数据的维度是否符合要求
input_x
input_y
test_x
模型搭建
input_size input_x.shape[1] #样本个数
hidden1_size 128 # 隐含层神经元个数
hidden2_size256
output_size 1
batch_size 16
my_nn torch.nn.Sequential(torch.nn.Linear(input_size, hidden1_size), #全连接层torch.nn.ReLU(), #激活函数torch.nn.Linear(hidden1_size, hidden2_size), #全连接层torch.nn.ReLU(), #激活函数torch.nn.Linear(hidden2_size, output_size),
)
# MSE损失函数
cost torch.nn.MSELoss(reductionmean)
# Adam优化器
optimizer torch.optim.Adam(my_nn.parameters(), lr0.001)
模型训练
losses []
for i in range(500):batch_loss []# MINI-Batch方法来进行训练for start in range(0, len(input_x), batch_size):end start batch_size if start batch_size len(input_x) else len(input_x)xx torch.tensor(input_x[start:end],dtypetorch.float,requires_gradTrue)yy torch.tensor(input_y[start:end],dtypetorch.float,requires_gradTrue)prediction my_nn(xx)# 前向传播loss cost(prediction, yy) # 计算损失optimizer.zero_grad() # 梯度清零loss.backward(retain_graphTrue) #反向传播optimizer.step() # 更新参数batch_loss.append(loss.data.numpy()) #记录损失便于打印# 打印损失if i % 100 0:losses.append(np.mean(batch_loss))print(i, np.mean(batch_loss))模型保存
torch.save(my_nn,model.pth)
print(Saved PyTorch Model to model.pth)模型预测
#加载模型
model torch.load(model.pth)
#不改变模型参数的基础上进行预测
predmodel(torch.tensor(test_x)).detach()
#对预测后的结果进行还原之前取了对数
prednp.exp(pred)
保存结果
#对测试的结果进行保存
test[SalePrice]pred.reshape(1,-1)[0]
subpd.concat([test[Id],test[SalePrice]],axis1)
subsub.set_index(Id)
sub.to_csv(sub.csv)