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

基于python的BP神经网络红酒品质分类预测模型

1 导入必要的库

import pandas as pd  
import numpy as np  
import matplotlib.pyplot as plt  
from sklearn.model_selection import train_test_split  
from sklearn.preprocessing import LabelEncoder  
from tensorflow.keras.models import Sequential  
from tensorflow.keras.layers import Dense  
from tensorflow.keras.callbacks import EarlyStopping  
from sklearn.metrics import classification_report, confusion_matrix
# 忽略Matplotlib的警告(可选)  
import warnings  
warnings.filterwarnings("ignore") 
# 设置中文显示和负号正常显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

2 数据加载与预处理

# 读取数据  
df = pd.read_csv('train.csv')  # 处理缺失值(这里假设我们删除含有缺失值的行)  
df.dropna(inplace=True)  # 处理重复值(这里选择删除重复的行)  
df.drop_duplicates(inplace=True)  # 将'wine types'列的文本转换为数值  
df['wine types'] = df['wine types'].map({'red': 1, 'white': 2})    
# 假设'quality'是我们要预测的标签  
X = df.drop('quality', axis=1)  
y = df['quality']

3 数据探索

# 选择绘制特征数据的折线图
X_columns_to_plot = X.columnsdf_plot = df[X_columns_to_plot]  df_plot.plot(subplots=True, figsize=(15, 15))  
plt.tight_layout()  
plt.show()

图 3-1

4 BP神经网络模型构建

import tensorflow as tf  
from tensorflow.keras.models import Sequential  
from tensorflow.keras.layers import Dense  
from sklearn.model_selection import train_test_split  
from sklearn.preprocessing import StandardScaler  # 分离特征和标签  
X = df.drop('quality', axis=1)  
y = df['quality']  # 划分训练集和测试集  
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)  # 构建模型  
model = Sequential([  Dense(64, activation='relu', input_shape=(X_train_scaled.shape[1],)),  Dense(32, activation='relu'),  Dense(10, activation='softmax')  # 假设有10个类别,根据实际情况调整  
])  # 编译模型  
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])  # 训练模型  
history = model.fit(X_train_scaled, y_train, epochs=100, validation_split=0.2, verbose=1)

图 4-1

5 训练评估可视化

# 绘制训练和验证的准确率与损失  
plt.figure(figsize=(12, 6))  
plt.subplot(1, 2, 1)  
plt.plot(history.history['accuracy'], color='#B0D5DF',label='Training Accuracy')  
plt.plot(history.history['val_accuracy'],  color='#1BA784',label='Validation Accuracy')  
plt.title('Training and Validation Accuracy')  
plt.legend()  plt.subplot(1, 2, 2)  
plt.plot(history.history['loss'],  color='#D11A2D',label='Training Loss')  
plt.plot(history.history['val_loss'], color='#87723E', label='Validation Loss')  
plt.title('Training and Validation Loss')  
plt.legend()  
plt.show()

图 5-1 过拟合

        成功过拟合了,其实早有预料,我手里的数据集都挺顽固的,训练效果都不好。

6 正则化

        这里采用L2正则化

import tensorflow as tf  
from tensorflow.keras.models import Sequential  
from tensorflow.keras.layers import Dense 
from tensorflow.keras.regularizers import l2  
from sklearn.model_selection import train_test_split  
from sklearn.preprocessing import StandardScaler  # 分离特征和标签  
X = df.drop('quality', axis=1)  
y = df['quality']  # 划分训练集和测试集  
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(64, activation='relu', kernel_regularizer=l2(0.01)),  # 对第二个Dense层的权重也添加L2正则化  Dense(10, activation='softmax')  # 输出层,假设是多分类问题  
])  # 编译模型  
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])  # 训练模型  
history = model.fit(X_train_scaled, y_train, epochs=100, validation_split=0.2, verbose=1)
# 绘制训练和验证的准确率与损失  
plt.figure(figsize=(12, 6))  
plt.subplot(1, 2, 1)  
plt.plot(history.history['accuracy'], color='#B0D5DF',label='Training Accuracy')  
plt.plot(history.history['val_accuracy'],  color='#1BA784',label='Validation Accuracy')  
plt.title('Training and Validation Accuracy')  
plt.legend()  plt.subplot(1, 2, 2)  
plt.plot(history.history['loss'],  color='#D11A2D',label='Training Loss')  
plt.plot(history.history['val_loss'], color='#87723E', label='Validation Loss')  
plt.title('Training and Validation Loss')  
plt.legend()  
plt.show()

图 6-1 

        这就不错了。

相关文章:

  • Github个人网站搭建详细教程【Github+Jekyll模板】
  • HTTP详解
  • MySQL之视图和索引实战
  • 使用git工具管理泰山派内核源码目录及抽打补丁简易流程
  • 【SpringCloud】 微服务分布式环境下的事务问题,seata大合集
  • STM32智能工业监控系统教程
  • 乾坤: 微前端项目切换时样式闪动(从无样式变为正常样式需要等 css chunk 文件加载完成, 加载延时受网速影响)
  • Apache Nifi挂接MQTT与Kafka实践
  • 认知觉醒:铸就非凡人生的进阶之路
  • 单例模式懒汉模式和饿汉模式
  • 2024年【甘肃省安全员B证】考试资料及甘肃省安全员B证模拟试题
  • 探索 SPL-404 协议标准:NFT 与 DeFi 的融合
  • spring框架实现滑动验证码功能
  • Java修炼 Java SE 面试题目 (简答) 2024.7.26 22:16
  • .net core docker部署教程和细节问题
  • [PHP内核探索]PHP中的哈希表
  • [deviceone开发]-do_Webview的基本示例
  • 【跃迁之路】【641天】程序员高效学习方法论探索系列(实验阶段398-2018.11.14)...
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • Brief introduction of how to 'Call, Apply and Bind'
  • CentOS 7 修改主机名
  • download使用浅析
  • LeetCode18.四数之和 JavaScript
  • rc-form之最单纯情况
  • 大快搜索数据爬虫技术实例安装教学篇
  • 机器学习中为什么要做归一化normalization
  • 老板让我十分钟上手nx-admin
  • 面试遇到的一些题
  • 配置 PM2 实现代码自动发布
  • 温故知新之javascript面向对象
  • 《码出高效》学习笔记与书中错误记录
  • 哈罗单车融资几十亿元,蚂蚁金服与春华资本加持 ...
  • ​​​​​​​Installing ROS on the Raspberry Pi
  • ​软考-高级-系统架构设计师教程(清华第2版)【第12章 信息系统架构设计理论与实践(P420~465)-思维导图】​
  • # windows 安装 mysql 显示 no packages found 解决方法
  • #AngularJS#$sce.trustAsResourceUrl
  • #我与虚拟机的故事#连载20:周志明虚拟机第 3 版:到底值不值得买?
  • %check_box% in rails :coditions={:has_many , :through}
  • (2020)Java后端开发----(面试题和笔试题)
  • (Matalb回归预测)PSO-BP粒子群算法优化BP神经网络的多维回归预测
  • (Ruby)Ubuntu12.04安装Rails环境
  • (阿里巴巴 dubbo,有数据库,可执行 )dubbo zookeeper spring demo
  • (附源码)python房屋租赁管理系统 毕业设计 745613
  • (十八)Flink CEP 详解
  • (原创) cocos2dx使用Curl连接网络(客户端)
  • .[hudsonL@cock.li].mkp勒索加密数据库完美恢复---惜分飞
  • .net core控制台应用程序初识
  • .NET 中什么样的类是可使用 await 异步等待的?
  • .NET/MSBuild 中的发布路径在哪里呢?如何在扩展编译的时候修改发布路径中的文件呢?
  • .NET编程——利用C#调用海康机器人工业相机SDK实现回调取图与软触发取图【含免费源码】
  • .Net程序猿乐Android发展---(10)框架布局FrameLayout
  • .NET命名规范和开发约定
  • .NET企业级应用架构设计系列之技术选型
  • .NET应用架构设计:原则、模式与实践 目录预览
  • @EventListener注解使用说明