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

BP神经网络-学习日志Day3

BP神经网络是一种多层前馈神经网络,采用误差反向传播算法进行训练。该算法由Rumelhart等人于1986年提出,是应用最广泛的神经网络模型之一。BP网络通过梯度下降法不断调整网络权值,使网络输出逐渐逼近期望输出。

核心思想:网络学习过程由两部分组成——信号的正向传播误差的反向传播。正向传播时,输入信号经隐藏层处理后传向输出层;若输出与期望不符,则转入反向传播,将误差信号沿原路返回,逐层调整各神经元的权值。

方法特点:

  • 非线性映射能力强:理论上可以逼近任意连续函数
  • 自学习自组织:通过样本自动学习输入输出间的映射关系
  • 泛化能力好:训练好的网络可对未见过的样本进行合理预测
  • 应用广泛:分类、回归、预测、模式识别等领域

代码见最后

5.1 分类问题示例

"""BP神经网络分类示例 - 使用sklearn""" import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, classification_report # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 1. 生成模拟数据 X, y = make_classification( n_samples=500, n_features=2, n_redundant=0, n_informative=2, n_clusters_per_class=1 ) # 2. 数据预处理(归一化) scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 3. 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X_scaled, y, test_size=0.2 ) # 4. 创建BP神经网络模型 model = MLPClassifier( hidden_layer_sizes=(10, 5), # 两个隐藏层,分别10和5个神经元 activation='relu', # 激活函数:relu、logistic、tanh solver='adam', # 优化器:adam、sgd、lbfgs learning_rate_init=0.01, # 初始学习率 max_iter=500, # 最大迭代次数 verbose=True # 打印训练过程 ) # 5. 训练模型 model.fit(X_train, y_train) # 6. 预测与评估 y_pred = model.predict(X_test) print(f"\n测试集准确率: {accuracy_score(y_test, y_pred):.4f}") print("\n分类报告:") print(classification_report(y_test, y_pred)) # 7. 可视化决策边界 def plot_decision_boundary(model, X, y, title): h = 0.02 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.figure(figsize=(10, 8)) plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.coolwarm) scatter = plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm, edgecolors='k') plt.xlabel('特征1', fontsize=12) plt.ylabel('特征2', fontsize=12) plt.title(title, fontsize=14) plt.colorbar(scatter) plt.savefig('bp_decision_boundary.png', dpi=150, bbox_inches='tight') plt.show() plot_decision_boundary(model, X_scaled, y, 'BP神经网络分类决策边界')

5.2 训练过程可视化

"""训练过程可视化""" import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPClassifier from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 加载数据 iris = load_iris() X, y = iris.data, iris.target X = StandardScaler().fit_transform(X) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 训练模型(记录损失曲线) model = MLPClassifier( hidden_layer_sizes=(16, 8), activation='relu', solver='adam', learning_rate_init=0.01, max_iter=200 ) model.fit(X_train, y_train) # 绘制损失曲线 plt.figure(figsize=(12, 5)) # 子图1:损失曲线 plt.subplot(1, 2, 1) plt.plot(model.loss_curve_, 'b-', linewidth=2) plt.xlabel('迭代次数', fontsize=12) plt.ylabel('损失值', fontsize=12) plt.title('训练损失曲线', fontsize=14) plt.grid(True, alpha=0.3) # 子图2:验证准确率 plt.subplot(1, 2, 2) train_scores = [] test_scores = [] for i in range(10, 201, 10): temp_model = MLPClassifier( hidden_layer_sizes=(16, 8), activation='relu', solver='adam', learning_rate_init=0.01, max_iter=i ) temp_model.fit(X_train, y_train) train_scores.append(temp_model.score(X_train, y_train)) test_scores.append(temp_model.score(X_test, y_test)) plt.plot(range(10, 201, 10), train_scores, 'g-', label='训练集', linewidth=2) plt.plot(range(10, 201, 10), test_scores, 'r-', label='测试集', linewidth=2) plt.xlabel('迭代次数', fontsize=12) plt.ylabel('准确率', fontsize=12) plt.title('训练/测试准确率变化', fontsize=14) plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.savefig('bp_training_process.png', dpi=150, bbox_inches='tight') plt.show() print(f"最终测试集准确率: {model.score(X_test, y_test):.4f}")

5.3 回归问题示例

"""BP神经网络回归示例""" import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPRegressor from sklearn.preprocessing import StandardScaler # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 生成非线性数据 X = np.linspace(-3, 3, 200).reshape(-1, 1) y_true = np.sin(X).ravel() + 0.1 * X.ravel() y = y_true + 0.1 * np.random.randn(200) # 数据标准化 scaler_X = StandardScaler() scaler_y = StandardScaler() X_scaled = scaler_X.fit_transform(X) y_scaled = scaler_y.fit_transform(y.reshape(-1, 1)).ravel() # 创建回归模型 model = MLPRegressor( hidden_layer_sizes=(20, 10), activation='tanh', solver='adam', learning_rate_init=0.01, max_iter=500 ) model.fit(X_scaled, y_scaled) # 预测 y_pred_scaled = model.predict(X_scaled) y_pred = scaler_y.inverse_transform(y_pred_scaled.reshape(-1, 1)).ravel() # 可视化 plt.figure(figsize=(10, 6)) plt.scatter(X, y, c='blue', alpha=0.5, label='训练数据', s=30) plt.plot(X, y_true, 'g--', label='真实函数', linewidth=2) plt.plot(X, y_pred, 'r-', label='BP网络拟合', linewidth=2) plt.xlabel('x', fontsize=12) plt.ylabel('y', fontsize=12) plt.title('BP神经网络函数拟合', fontsize=14) plt.legend(fontsize=10) plt.grid(True, alpha=0.3) plt.savefig('bp_regression.png', dpi=150, bbox_inches='tight') plt.show() # 计算拟合效果 from sklearn.metrics import r2_score, mean_squared_error print(f"R² 分数: {r2_score(y, y_pred):.4f}") print(f"均方误差: {mean_squared_error(y, y_pred):.4f}")
http://www.jsqmd.com/news/428032/

相关文章:

  • 闲置微信立减金怎么处理?正规回收渠道推荐 - 团团收购物卡回收
  • 潮玩盲盒小程序开发:核心玩法拆解与商业化落地全解析
  • 中型卧式水煤气固定管板式换热器S170m²的机械设计
  • DevExpress WPF中文教程:Data Grid - 示例服务教程
  • 探讨北大青鸟华巨校区,京津冀晋地区哪家更值得推荐? - mypinpai
  • 携程卡套装在哪里回收兑换安全靠谱 - 抖抖收
  • 一湾碧海,半壁悬崖,这里是北洛秘境的温柔时光
  • 2026年热门的双组脚踏开关/无线脚踏开关值得信赖厂家推荐(精选) - 行业平台推荐
  • 264_尚硅谷_go协程和go主线程
  • 收藏! 2026最强开源AI编程工具清单:从代码补全到自主智能体 - AI
  • 2026工业机器人管线包权威厂家推荐榜 - 优质品牌商家
  • 聊聊女装量身定制服务,泉州厦门有哪些值得推荐的品牌? - 工业品牌热点
  • 基于单片机智能输液器监控系统的设计
  • 剖析医疗器械翻译哪家合适,性价比高的服务怎么选择 - 工业设备
  • 2026年评价高的襄阳装修定制/襄阳装修案例定制服务公司 - 行业平台推荐
  • 2026年比较好的船用不锈钢灯/灯管不锈钢灯优质厂商精选推荐(口碑) - 行业平台推荐
  • 2026年选购指南:柔性风琴防护罩/风琴罩哪家口碑好值得信赖 - 品牌推荐大师
  • 2026年口碑好的跨境电商物流方案企业盘点,易斯拉国际物流上榜 - 工业品牌热点
  • perf分析问题
  • 简易改装飞行器的飞行和反侦察技术特点
  • 基于单片机的家用温湿度控制器的设计与实现
  • winform 下拉框ComboBox绘制颜色选项,下拉颜色使用系统已知的
  • 应对简易改装飞行器威胁的光电对抗技术和防卫策略
  • C#全套源代码:手机组态APP监控西门子S7-1200 PLC的无线WiFi通信
  • 2026年评价高的襄阳本地装修全包/襄阳现代简约装修可靠供应商推荐 - 行业平台推荐
  • 新年规划更清晰,OCR 办公更高效
  • Telerik UI for .NET MAUI 2026 Q1轻松输入和编辑多行文本
  • Lychee Rerank MM:基于Qwen2.5-VL的排序系统优化技巧
  • Nacos安装下载教程
  • 2026 年四川搬家服务企业权威推荐| 厂房搬家、单位搬家、钢琴搬运、设备搬运优质机构盘点 - 深度智识库