机器学习中的神经网络建模——Sklearn.neural_network概要

sklearn.neural_network 是 scikit-learn 库中的一个模块,提供了创建和训练神经网络模型的工具。scikit-learn 是一个广泛使用的 Python 机器学习库,以其简洁性和高效性著称。该库的设计理念是通过简洁的接口和高效的实现,使用户能够快速构建和应用机器学习模型。neural_network 模块特别实现了多层感知器(MLP),这是一种前馈人工神经网络,适用于各种分类和回归任务。该模块的参数化设计允许用户根据具体需求调整模型结构和训练过程,从而在处理复杂的非线性问题时获得更好的性能。通过与 scikit-learn 生态系统中的其他工具(如数据预处理、模型评估和交叉验证)的无缝集成,用户可以实现从数据准备到模型训练再到模型评估的完整工作流。这种高可用性和易用性,使得 sklearn.neural_network 成为机器学习应用中构建神经网络模型的理想选择,无论是用于学术研究、工业应用还是个人项目。

一、sklearn.neural_network简介

sklearn官方神经网络文档

sklearn.neural_network 是 scikit-learn 库中的一个模块,提供了创建和训练神经网络模型的工具。neural_network 模块包括多层感知器 (MLP) 的实现,这是一种前馈人工神经网络。多层感知器(MLP)是神经网络中的一种基本类型,由一个输入层、一个或多个隐藏层和一个输出层组成。每一层的神经元通过权重连接,与上一层的输出和下一层的输入相关联。MLP 通过调整这些权重来学习和预测。
在实际应用中,neural_network 模块广泛应用于图像识别、语音识别、自然语言处理等领域。其简洁的接口和强大的功能,使得用户可以快速构建和训练神经网络模型。无论是初学者还是有经验的研究人员,sklearn.neural_network 都提供了便捷的工具来实现复杂的机器学习任务。

二、 Sklearn.neural_network模块

在 neural_network 模块中,主要包含两个类:MLPClassifier 和 MLPRegressor。MLPClassifier 用于分类任务,而 MLPRegressor 用于回归任务。这两个类都具有高度的可配置性,可以通过参数设置来调整网络的结构和训练过程。例如,可以通过 hidden_layer_sizes 参数来设置隐藏层的数量和每层的神经元数量;通过 activation 参数来选择激活函数,如 ReLU、tanh、logistic 等;通过 solver 参数来选择优化算法,如 SGD、Adam、LBFGS 等。
除了基本参数配置外,MLPClassifier 和 MLPRegressor 还支持多种训练和优化技巧,例如早停法(early stopping)、正则化(regularization)以及批量归一化(batch normalization)。这些技巧可以帮助提高模型的泛化能力,防止过拟合,并加速训练过程。

2.1 MLPClassifier 和 MLPRegressor 的关键特性

  • 隐藏层:可以使用 hidden_layer_sizes 参数指定隐藏层的数量和每个隐藏层中的神经元数量。
  • 激活函数:可用的激活函数包括 'identity''logistic''tanh''relu'
  • 求解器:可以使用不同的优化算法如 'lbfgs''sgd''adam' 来训练模型。
  • 学习率:支持各种学习率调度和策略。
  • 正则化:可以使用 alpha 参数应用正则化技术以防止过拟合。
  • 早停:如果验证分数停止提高,可以提前停止训练,这有助于避免过拟合。

2.2 用法示例

以下是如何使用 MLPClassifier 来训练一个分类任务的神经网络的示例:

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 classification_report

# 生成一个合成数据集
X, y = make_classification(n_samples=1000, n_features=20, n_classes=3, random_state=42)

# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 标准化特征(均值=0,方差=1)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 创建并训练 MLPClassifier
mlp = MLPClassifier(hidden_layer_sizes=(100,), max_iter=300, activation='relu', solver='adam', random_state=42)
mlp.fit(X_train, y_train)

# 进行预测
y_pred = mlp.predict(X_test)

# 评估模型
print(classification_report(y_test, y_pred))

2.3 参数说明

  • hidden_layer_sizes:一个元组,表示隐藏层中神经元的数量。例如,(100,) 表示一个隐藏层,包含 100 个神经元。
  • activation:隐藏层的激活函数。选项有 'identity''logistic''tanh''relu'
  • solver:用于权重优化的优化器。'lbfgs' 是一种准牛顿法,'sgd' 是随机梯度下降,'adam' 是一种基于随机梯度的优化器。
  • alpha:L2 惩罚(正则化项)参数。
  • batch_size:随机优化器的小批量大小。
  • learning_rate:权重更新的学习率调度。选项有 'constant''invscaling''adaptive'
  • max_iter:最大迭代次数。求解器迭代直到收敛或达到此迭代次数。
  • random_state:随机数生成的种子。

属性导图 方法导图

三、Python算法

3.1 神经网络示例1

# 首先我们要导入科学计算库,用于一些科学计算
import numpy as np # 为numpy起一个别名,调用使用起来会很方便
# 现在导入神经网络中的一个多分类模型,用于训练多分类数据
from sklearn.neural_network import MLPClassifier
# 现在导入sklearn中的用于评测预测结果指标的库,如混淆矩阵和分类报告
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 加载iris数据集
iris = load_iris()
X_data = iris.data
y_data = iris.target

# 定义数据预处理函数
def preprocess(X,y):
	# 对数据的处理我通常会都放入这个函数中,下面将列出部分处理步骤,根据实际情况进行处理
	# 数据提取
	# 特征缩放
	X_min = np.min(X)
	X_max = np.max(X)
	X = (X - X_min) / (X_max - X_min)
	# 数据初始化
	X = np.c_[np.ones(len(X)),X]
	y = np.c_[y]
	# 数据洗牌
	np.random.seed(1)
	m = len(X)
	o = np.random.permutation(m)
	X = X[o]
	y = y[o]
	# 数据切割
	d = int(0.7 * m)
	X_train,X_test = np.split(X,[d])
	y_train,y_test = np.split(y,[d])
	# 数据处理基本完毕,返回处理好的数据
	return X_train,X_test,y_train,y_test
# 调用数据处理函数,获得处理好的数据
X_train,X_test,y_train,y_test = preprocess(X_data,y_data)

"""
	主要参数:
	hidden_layer_sizes: 隐藏层单元数(tuple),如(100,100,100,50)
	activation : 激活函数,{‘identity’, ‘logistic’, ‘tanh’, ‘relu’}, 缺省 ‘relu‘; [f(x) = x, 1/(1+exp(-x)), tanh(x), max(0, x)]
	solver : 解决器, {‘lbfgs’, ‘sgd’, ‘adam’}, 缺省 ‘adam’; [牛顿法,随机梯度下降, 自适应momemtum] 
	alpha : L2正则化参数,float, 可选,缺省0.0001
	batch_size : 批次,可选, 不适用于’lbfgs’, 缺省 ‘auto‘, 此时,batch_size=min(200, n_samples)`
	learning_rate : 学习率, {‘constant’, ‘invscaling’, ‘adaptive’}, 缺省 ‘constant’, 只适用于梯度下降sgd
	learning_rate_init : 学习率初始值, 可选, 缺省 0.001, 仅适用于sgd或adam
	power_t : 下降指数, 可选, 缺省 0.5,  适用于’invscaling’,learning_rate_init/pow(t,power_t), 仅适用于sgd
	max_iter : 最大迭代数, 可选, 缺省200, 迭代器收敛迭代次数,对于sgd/adam, 代表的是epochs数目,不是下降步数
	shuffle : 每次迭代, 是否洗牌, 可选, 缺省True,仅适用于sgd或adam
	random_state: 缺省None; 若int, 随机数产生器seed, 若RandomStates实例, 随机数产生器, 若None, np.random
	tol : 容忍度, 可选, 缺省le-4, 连续两次迭代loss达不到此值,除非设置成’adaptive’,否则,就停止迭代,
	beta_1 : adam指数衰减参数1,可选, 缺省0.9
	beta_2 : adam指数衰减参数2,可选, 缺省0.999
	epsilon : adam数值稳定值,可选,缺省1e-8
"""
# 首先,创建一个多分类模型对象 类似于Java的类调用
# 括号中填写多个参数,如果不写,则使用默认值,我们一般要构建隐层结构,调试正则化参数,设置最大迭代次数
mlp = MLPClassifier(hidden_layer_sizes=(400,100),alpha=0.01,max_iter=300) 
# 调用fit函数就可以进行模型训练,一般的调用模型函数的训练方法都是fit()
mlp.fit(X_train,y_train.ravel()) # 这里y值需要注意,还原成一维数组
# 模型就这样训练好了,而后我们可以调用多种函数来获取训练好的参数
# 比如获取准确率
print('训练集的准确率是:',mlp.score(X_train,y_train))
# 比如输出当前的代价值
print('训练集的代价值是:',mlp.loss_)
# 比如输出每个theta的权重
print('训练集的权重值是:',mlp.coefs_)

# 混淆矩阵和分类报告是评价预测值和真实值的一种指标
# 混淆矩阵可以直观的看出分类中正确的个数和分错的个数,以及将正确的样本错误地分到了哪个类别
matrix_train = confusion_matrix(y_train,mlp.predict(X_train))
print('训练集的混淆矩阵是:',matrix_train)
# 分类报告中有多个指标用于评价预测的好坏。
'''
	TP: 预测为1(Positive),实际也为1(Truth-预测对了)
	TN: 预测为0(Negative),实际也为0(Truth-预测对了)
	FP: 预测为1(Positive),实际为0(False-预测错了)
	FN: 预测为0(Negative),实际为1(False-预测错了)
'''
report_train = classification_report(y_train,mlp.predict(X_train))
print('训练集的分类报告是:\n', report_train)

3.2 神经网络示例2

import numpy as np
import pandas as pd
from sklearn.neural_network import MLPRegressor
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

# 加载加州房价数据集
housing = fetch_california_housing()
feature = housing.data
target = housing.target

xtrain, xtest, ytrain, ytest = train_test_split(feature, target, train_size=0.7, random_state=421)

nn = MLPRegressor(hidden_layer_sizes=(100, 100), activation="identity", shuffle=False, solver="lbfgs", alpha=0.001)
model = nn.fit(xtrain, ytrain)
pre = model.predict(xtest)

print(pre)
print(ytest)
print(model.coefs_)
print(model.n_layers_)
print(model.n_outputs_)
print(model.score(xtest, ytest))

index = 0
for w in model.coefs_:
    index += 1
    print('第{}层网络层:'.format(index))
    print('权重矩阵:', w.shape)
    print('系数矩阵:', w)

plt.plot(range(len(pre)), pre, color='red', label='Predicted')
plt.plot(range(len(ytest)), ytest, color='blue', label='Actual')

plt.legend()
plt.show()

3.3 神经网络示例3

序号 x1 x2 y 序号 x1 x2 y
1 -3 -2 0.6589 10 -0.3 -0.2 -0.2875
2 -2.7 -1.8 0.2206 11 0 -2.22 0
3 -2.4 -1.6 -0.1635 12 0.3 0.2 0.3035
4 -2.1 -1.4 -0.4712 13 0.6 0.4 0.5966
5 -1.8 -1.2 -0.6858 14 0.9 0.6 0.8553
6 -1.5 -1 -0.7975 15 1.2 0.8 1.06
7 -1.2 -0.8 -0.804 16 1.5 1 1.1975
8 -0.9 -0.6 -0.7113 17 1.8 1.2 1.2618
9 -0.6 -0.4 -0.5326
import numpy as np
from sklearn.neural_network import MLPRegressor
import matplotlib.pyplot as plt
import networkx as nx

# Data
x1 = np.array([-3, -2.7, -2.4, -2.1, -1.8, -1.5, -1.2, -0.9, -0.6, -0.3, 0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
x2 = np.array([-2, -1.8, -1.6, -1.4, -1.2, -1, -0.8, -0.6, -0.4, -0.2, -2.2204, 0.2, 0.4, 0.6, 0.8, 1, 1.2])
y = np.array([0.6589, 0.2206, -0.1635, -0.4712, -0.6858, -0.7975, -0.8040,
              -0.7113, -0.5326, -0.2875, 0, 0.3035, 0.5966, 0.8553, 1.0600, 1.1975, 1.2618])

# Prepare input data
inputData = np.vstack((x1, x2)).T  # shape (17, 2)

# Initialize the neural network
np.random.seed(88888)  # Set random seed for reproducibility
net = MLPRegressor(hidden_layer_sizes=(3,), activation='tanh', solver='lbfgs', max_iter=15000, tol=0.0001, random_state=88888)

# Train the network
net.fit(inputData, y)

# Extract weights and biases
weights = net.coefs_
biases = net.intercepts_

# Create a directed graph
G = nx.DiGraph()

# Add nodes for input, hidden, and output layers
input_nodes = ['x1', 'x2']
hidden_nodes = ['h1', 'h2', 'h3']
output_node = ['y']

# Adding nodes to graph
G.add_nodes_from(input_nodes, layer='input')
G.add_nodes_from(hidden_nodes, layer='hidden')
G.add_nodes_from(output_node, layer='output')

# Connect input layer to hidden layer
for i, input_node in enumerate(input_nodes):
    for h, hidden_node in enumerate(hidden_nodes):
        weight = weights[0][i][h]
        G.add_edge(input_node, hidden_node, weight=f'{weight:.2f}')

# Connect hidden layer to output layer
for h, hidden_node in enumerate(hidden_nodes):
    weight = weights[1][h][0]
    G.add_edge(hidden_node, output_node[0], weight=f'{weight:.2f}')

# Position the nodes in layers
pos = {'x1': (0, 1), 'x2': (0, -1),
       'h1': (1, 2), 'h2': (1, 0), 'h3': (1, -2),
       'y': (2, 0)}

# Draw the graph
plt.figure(figsize=(10, 8))
nx.draw(G, pos, with_labels=True, node_size=3000, node_color='lightblue', arrowsize=20, font_size=10, font_weight='bold')

# Draw edge labels (weights)
edge_labels = {(u, v): d['weight'] for u, v, d in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10)

# Add bias labels to hidden and output nodes
for i, hidden_node in enumerate(hidden_nodes):
    bias_label = f'bias: {biases[0][i]:.2f}'
    x, y = pos[hidden_node]
    plt.text(x, y-0.4, bias_label, fontsize=10, ha='center', bbox=dict(facecolor='white', alpha=0.5))

output_bias_label = f'bias: {biases[1][0]:.2f}'
x, y = pos[output_node[0]]
plt.text(x, y-0.4, output_bias_label, fontsize=10, ha='center', bbox=dict(facecolor='white', alpha=0.5))

plt.title('Neural Network Structure with Weights and Biases')
plt.show()
参照图 真实图

总结

sklearn.neural_network 模块提供了强大的工具来创建和训练神经网络,使其适用于分类和回归任务。凭借其灵活性和与 scikit-learn 生态系统的无缝集成,这个模块成为机器学习实践者的宝贵资源。通过 MLPClassifierMLPRegressor 类,用户可以方便地实现多层感知器模型,这些模型可以处理复杂的非线性问题。模块支持多种激活函数和优化算法,并提供正则化和早停等机制来防止过拟合。其参数化设计允许用户根据具体需求调整模型结构,如设置隐藏层数量、神经元数量和学习率等。此外,通过与其他 scikit-learn 工具(如数据预处理、模型评估和交叉验证)结合使用,可以实现从数据准备到模型训练再到模型评估的完整工作流。这种高可用性和易用性,使得 sklearn.neural_network 成为机器学习应用中构建神经网络模型的理想选择,无论是用于学术研究、工业应用还是个人项目。

参考文献

  1. 一个简单的神经网络例子
  2. 机器学习之sklearn(一)neural_network调库实现
  3. 神经网络——基于sklearn的参数介绍及应用
  4. Sklearn中的数据处理流程和神经网络导图学习
posted @   郝hai  阅读(2045)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示