机器学习-MLP预测

本文使用机器学习MLP对数据进行预测。

1、数据

1.1 训练数据集:

medol.xlsx文件示例

otv
3015-1.915362209
3018-1.963409776
3021-1.762028408
3024-1.789477583

1.2 预测数据集

test.xlsx文件示例

ot
3516
3519

2、模型训练

train.py

import pandas as pd
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler
import joblib
import numpy as np
import matplotlib.pyplot as plt

# 加载数据
df = pd.read_excel("model.xlsx")

# 定义 o 和 t 列的名称
feature_columns = ['o', 't']

# 初始化 StandardScaler
scaler = StandardScaler()

# 在规范化数据集
X_scaled = scaler.fit_transform(df[feature_columns])

target_column = 'v'

# 将数据拆分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, df[target_column], test_size=0.1)

# 初始化 MLP 回归模型
mlp = MLPRegressor(solver='adam', max_iter=10000)  # 你可以根据需要修改 max_iter 的值和添加 random_state

# 定义参数网格
param_grid = {
    'hidden_layer_sizes': [(200, 200, 200), (250, 250, 250),  (300, 300, 300)],
    'activation': ['relu', 'logistic', 'tanh', 'identity'],
    'alpha': [0.01, 0.02, 0.05],
}

# 使用 GridSearchCV 进行网格搜索
grid_search = GridSearchCV(mlp, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1)
grid_search.fit(X_train, y_train)

# 获取最佳模型
best_model = grid_search.best_estimator_

# 输出最佳超参数
print("Best Hyperparameters:", grid_search.best_params_)

# 计算训练集和测试集的指标
train_predictions = best_model.predict(X_train)
test_predictions = best_model.predict(X_test)

# 训练集指标
print("\n[训练集指标]")
print("平均绝对误差: {}".format(mean_absolute_error(y_train, train_predictions)))
print("均方误差: {}".format(mean_squared_error(y_train, train_predictions)))
print("均方根误差: {}".format(np.sqrt(mean_squared_error(y_train, train_predictions))))
print("R2: {}".format(r2_score(y_train, train_predictions)))

# 测试集指标
print("\n[测试集指标]")
print("平均绝对误差: {}".format(mean_absolute_error(y_test, test_predictions)))
print("均方误差: {}".format(mean_squared_error(y_test, test_predictions)))
print("均方根误差: {}".format(np.sqrt(mean_squared_error(y_test, test_predictions))))
print("R2: {}".format(r2_score(y_test, test_predictions)))

# 绘制训练集误差随循环次数的变化图
plt.plot(range(1, best_model.n_iter_ + 1), best_model.loss_curve_, label='Train MSE')
plt.xlabel('Epoch')
plt.ylabel('Mean Squared Error')
plt.title('Training Set Error Over Epochs')
plt.legend()
plt.show()


# 绘制测试集的实际值和预测值的对比图
plt.scatter(y_test, test_predictions, alpha=0.5)
plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], '--', color='red', label='Identity Line')
plt.xlabel('Actual Values')
plt.ylabel('Predicted Values')
plt.title('Actual vs Predicted Values on Test Set')
plt.legend()
plt.show()

# 保存训练好的模型
model_filename = f'mlp_model'
joblib.dump(best_model, model_filename)

# 保存训练好的标准化器
joblib.dump(scaler, 'scaler_model')

3、预测模型

test.py

import pandas as pd
import joblib
from sklearn.preprocessing import StandardScaler

# 加载训练好的模型和标准化器
test_df = pd.read_excel("test.xlsx")  # 读取测试数据
scaler = joblib.load('scaler_model')  # 加载标准化器
loaded_model = joblib.load('mlp_model')  # 加载训练好的模型

# 对测试数据进行标准化并进行预测
predictions = loaded_model.predict(scaler.transform(test_df[['o', 't']]))

# 创建包含 'o'、't' 和 'v' 列的新 DataFrame
predicted_df = pd.DataFrame({'o': test_df['o'], 't': test_df['t'], 'v': predictions})

# 将预测结果保存到 Excel 文件
predicted_df.to_excel("predicted.xlsx", index=False)

4、结果

[训练集指标]
平均绝对误差: 0.019941036723566126
均方误差: 0.0008276974741736414
均方根误差: 0.028769731910006417
R2: 0.9996524173965567

[测试集指标]
平均绝对误差: 0.04383257685533077
均方误差: 0.0046869818043724755
均方根误差: 0.06846153521775915
R2: 0.9956609856525347

若有问题,欢迎讨论

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
PyTorch-MNIST-MLP是一个使用PyTorch库和多层感知器(MLP)来训练和测试MNIST手写数字数据集的项目。 MNIST是一个经典的手写数字识别数据集,包含了大量的手写数字图片和对应的标签。通过训练一个模型,我们可以实现自动识别手写数字的功能。 MLP是一种基本的人工神经网络模型,包含了多个全连接的神经网络层,并且每个神经元都与相邻层的所有神经元连接。通过多层的非线性变换和权重调整,MLP可以处理复杂的分类和回归任务。 PyTorch是一个开源的机器学习框架,提供了丰富的工具和函数来简化神经网络模型的构建和训练过程。通过PyTorch,我们可以轻松地搭建和训练MLP模型,并在MNIST数据集上进行实验。 在PyTorch-MNIST-MLP项目中,我们首先加载MNIST数据集,并将其转换成适合MLP模型的格式。然后,我们定义MLP模型的结构,包括输入层、隐藏层和输出层,并使用PyTorch提供的函数来定义损失函数和优化器。 接下来,我们使用训练数据集对MLP模型进行训练,通过反向传播算法和优化器来逐步调整模型的权重和偏置。在训练过程中,我们可以监控模型的精确度和损失值,以评估模型的性能。 最后,我们使用测试数据集对训练好的模型进行测试,并计算模型在测试集上的准确率。通过比较预测结果和真实标签,我们可以评估模型在手写数字识别任务上的表现。 总之,PyTorch-MNIST-MLP是一个基于PyTorch库和MLP模型的项目,用于训练和测试MNIST手写数字数据集。通过该项目,我们可以学习和掌握使用PyTorch构建神经网络模型的基本方法,并实现手写数字识别的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张er

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值