当前位置: 首页 > news >正文

基于python的BP神经网络回归模型

1  导入必要的库

import pandas as pd  
from sklearn.model_selection import train_test_split, cross_val_score, KFold  
import xgboost as xgb  
from sklearn.model_selection import train_test_split  
from sklearn.metrics import mean_squared_error, r2_score  
import matplotlib.pyplot as plt  
import seaborn as sns  
import pandas as pd  
import numpy as np   
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score  
from sklearn.model_selection import RandomizedSearchCV 
from sklearn.tree import plot_tree  
import matplotlib.pyplot as plt  
import seaborn as sns
import missingno as msno
# 忽略Matplotlib的警告(可选)  
import warnings  
warnings.filterwarnings("ignore") 
# 设置中文显示和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import tensorflow as tf    
from tensorflow.keras.models import Sequential    
from tensorflow.keras.layers import Dense    
from tensorflow.keras.regularizers import l2  # 导入l2正则化  
from sklearn.model_selection import train_test_split    
from sklearn.preprocessing import StandardScaler  

2 加载数据与预处理

df = pd.read_excel('10.xls')  
for column in ['Fault type', 'lithology']:  df[column] = pd.factorize(df[column])[0]
df

3 模型构建

# 假设df已经定义并包含了数据  
# 分离特征和标签    
X = df.drop('magnitude', axis=1)    
y = df['magnitude']    # 划分训练集和测试集    
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)    # 特征缩放    
scaler = StandardScaler()    
X_train_scaled = scaler.fit_transform(X_train)    
X_test_scaled = scaler.transform(X_test)    # 构建模型,添加L2正则化  
model = Sequential([    Dense(64, activation='relu', input_shape=(X_train_scaled.shape[1],), kernel_regularizer=l2(0.01)),  # 对第一个Dense层的权重添加L2正则化  Dense(32, activation='relu', kernel_regularizer=l2(0.01)),  # 对第二个Dense层的权重也添加L2正则化  Dense(1, activation='linear')  # 回归问题,输出层使用线性激活函数  
])    # 编译模型,使用回归损失函数  
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_error'])    # 训练模型    
history = model.fit(X_train_scaled, y_train, epochs=100, validation_split=0.2, verbose=1)

图 3-1 

4 模型评估

import matplotlib.pyplot as plt  # 假设你已经通过model.fit()训练了模型,并得到了history对象  
# 这里我们直接使用你提供的history变量  # 绘制训练损失和验证损失  
plt.figure(figsize=(10, 3))  
plt.plot(history.history['loss'], color='lime',label='Training Loss')  
plt.plot(history.history['val_loss'],  color='black', label='Validation Loss')  
plt.title('Training and Validation Loss')  
plt.xlabel('Epoch')  
plt.ylabel('Loss')  
plt.legend()  
plt.grid(True)  # 如果你还想绘制平均绝对误差(MAE),确保在model.compile时添加了它作为metrics之一  
# 如果添加了,可以这样绘制:  
if 'mean_absolute_error' in history.history:  plt.figure(figsize=(10, 3))  plt.plot(history.history['mean_absolute_error'],color='red',label='Training MAE')  plt.plot(history.history['val_mean_absolute_error'], color='lime',  label='Validation MAE')  plt.title('Training and Validation Mean Absolute Error')  plt.xlabel('Epoch')  plt.ylabel('MAE')  plt.legend()  plt.grid(True)  # 显示图表  
plt.show()

图 4-1 

 

相关文章:

  • RT-Thread Studio搭建 Renesa Version Board开发环境
  • Python 中数据科学和机器学习的作用
  • 如何在 SpringBoot 中优雅的做参数校验?
  • Pytorch使用教学8-张量的科学运算
  • ubuntu 22.04 安装部署gitlab详细过程
  • ubuntu新机依赖
  • [Mysql-视图和存储过程]
  • 【React】条件渲染:深入探讨高效开发技巧与最佳实践
  • Python | Leetcode Python题解之第292题Nim游戏
  • 【前端手写代码】手写Object.create
  • 在CentOS 7上安装Apache Tomcat 10.0.27
  • Logback原理及应用详解(三)
  • C++ | Leetcode C++题解之第292题Nim游戏
  • python安装驱动
  • 自动驾驶-机器人-slam-定位面经和面试知识系列01之常考公式推导(01)
  • Android 控件背景颜色处理
  • CAP 一致性协议及应用解析
  • Java多态
  • Just for fun——迅速写完快速排序
  • Lucene解析 - 基本概念
  • PHP 程序员也能做的 Java 开发 30分钟使用 netty 轻松打造一个高性能 websocket 服务...
  • php面试题 汇集2
  • Python爬虫--- 1.3 BS4库的解析器
  • 从零开始在ubuntu上搭建node开发环境
  • 浮动相关
  • 看完九篇字体系列的文章,你还觉得我是在说字体?
  • 理解IaaS, PaaS, SaaS等云模型 (Cloud Models)
  • 十年未变!安全,谁之责?(下)
  • 我看到的前端
  • 怎样选择前端框架
  • 新海诚画集[秒速5センチメートル:樱花抄·春]
  • ​sqlite3 --- SQLite 数据库 DB-API 2.0 接口模块​
  • ​业务双活的数据切换思路设计(下)
  • #pragma pack(1)
  • #在线报价接单​再坚持一下 明天是真的周六.出现货 实单来谈
  • (02)Unity使用在线AI大模型(调用Python)
  • (1/2)敏捷实践指南 Agile Practice Guide ([美] Project Management institute 著)
  • (21)起落架/可伸缩相机支架
  • (MATLAB)第五章-矩阵运算
  • (创新)基于VMD-CNN-BiLSTM的电力负荷预测—代码+数据
  • (九)信息融合方式简介
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (五)IO流之ByteArrayInput/OutputStream
  • (转载)虚函数剖析
  • (轉貼) 蒼井そら挑戰筋肉擂台 (Misc)
  • (总结)Linux下的暴力密码在线破解工具Hydra详解
  • .NET 8.0 中有哪些新的变化?
  • .NET 分布式技术比较
  • .netcore 6.0/7.0项目迁移至.netcore 8.0 注意事项
  • .net连接oracle数据库
  • .sh
  • /tmp目录下出现system-private文件夹解决方法
  • :如何用SQL脚本保存存储过程返回的结果集
  • @SpringBootApplication 包含的三个注解及其含义
  • [autojs]逍遥模拟器和vscode对接