使用 Python 进行 AI – 神经网络
使用 Python 实现 AI – 神经网络
Section titled “使用 Python 实现 AI – 神经网络”神经网络(Neural Networks),灵感来源于人脑的结构,是 AI 中强大的计算模型。它们擅长模式识别、分类、回归和生成建模等任务。它们从数据中学习复杂非线性关系的能力使其用途广泛。
什么是人工神经网络 (ANNs)?
Section titled “什么是人工神经网络 (ANNs)?”人工神经网络(Artificial Neural Network,简称 ANN)是由相互连接的处理单元(称为神经元 neuron 或节点 node)组成的系统,这些单元分层组织。神经元之间的每个连接都有一个相关的权重(Weight),在学习过程中会对其进行调整。神经元接收输入信号,使用激活函数(Activation Function)处理它们,并产生一个输出信号,该信号被传递给其他神经元。
ANN 的关键组成部分包括:
- 神经元(节点):基本计算单元。
- 层(Layers):神经元通常被组织成一个输入层(Input layer)、一个或多个隐藏层(Hidden layers)和一个输出层(Output layer)。
- 权重和偏置(Weights and Biases):网络学习的参数。权重调节神经元之间信号的强度,偏置改变激活函数的输出。
- 激活函数:引入非线性(Non-linearity),使网络能够学习复杂模式(例如,Sigmoid、ReLU、Tanh)。
有关更深入的概念细节,您可以参考有关 ANN 和深度学习(Deep Learning)的入门资料。现代深度学习通常涉及具有许多隐藏层的网络。
现代工具:Scikit-learn、TensorFlow 和 PyTorch
Section titled “现代工具:Scikit-learn、TensorFlow 和 PyTorch”虽然存在 NeuroLab 等较旧的库,但目前 Python 中的神经网络开发主要使用 Scikit-learn(用于更简单的模型)以及 TensorFlow(带 Keras API)或 PyTorch(用于更复杂和定制的架构)。
在本入门章节的示例中,我们将使用 Scikit-learn 的 MLPClassifier(多层感知机分类器)和 MLPRegressor(多层感知机回归器),它们适用于基本的神经网络任务。您可以通过 pip 安装 Scikit-learn:
pip install scikit-learn matplotlib numpy使用 Scikit-learn 构建神经网络
Section titled “使用 Scikit-learn 构建神经网络”感知机:最简单的神经网络
Section titled “感知机:最简单的神经网络”感知机(Perceptron)是最简单类型的 ANN,由一个带有激活函数(通常是阶跃函数 - step function)的单个神经元组成。它是一个线性分类器。Scikit-learn 提供了 sklearn.linear_model.Perceptron。
示例:一个用于简单二元分类任务(例如,与门 AND gate)的感知机。
import numpy as npfrom sklearn.linear_model import Perceptronimport matplotlib.pyplot as plt
# Input data for AND gateX = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])# Target output for AND gatey = np.array([0, 0, 0, 1])
# Create and train the Perceptron model# max_iter: maximum number of passes over the training data (epochs)# tol: stopping criterion (training stops if loss > previous_loss - tol)# eta0: learning rateperceptron_model = Perceptron(max_iter=100, tol=1e-3, eta0=0.1, random_state=42)perceptron_model.fit(X, y)
# Test the modelprint("Perceptron predictions for AND gate inputs:")for i, sample in enumerate(X): prediction = perceptron_model.predict([sample]) print(f"Input: {sample}, Actual: {y[i]}, Predicted: {prediction[0]}")
# Plotting decision boundary (for 2D data)# (This is more complex and often skipped for basic perceptron examples)# print(f"Learned weights: {perceptron_model.coef_}, Intercept: {perceptron_model.intercept_}")感知机只能解决线性可分问题。对于更复杂的任务,需要多层网络。
用于分类的多层感知机 (MLP)
Section titled “用于分类的多层感知机 (MLP)”MLP 由一个输入层、一个或多个隐藏层和一个输出层组成。这使得学习非线性决策边界成为可能。
我们创建一个简单的数据集,并使用 MLPClassifier 对其进行分类。
from sklearn.neural_network import MLPClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.datasets import make_classification
# Generate a synthetic dataset for classificationX_clf, y_clf = make_classification(n_samples=200, n_features=2, n_informative=2, n_redundant=0, random_state=42, n_clusters_per_class=1)
# Scale features for better performancescaler = StandardScaler()X_clf_scaled = scaler.fit_transform(X_clf)
# Split dataX_train, X_test, y_train, y_test = train_test_split(X_clf_scaled, y_clf, test_size=0.3, random_state=42)
# Create MLPClassifier model# hidden_layer_sizes: tuple, e.g., (50,) means one hidden layer with 50 neurons# activation: 'relu' is common# solver: 'adam' is a popular optimizer# max_iter: number of epochsmlp_clf = MLPClassifier(hidden_layer_sizes=(50,), activation='relu', solver='adam', max_iter=500, random_state=42, early_stopping=True, tol=1e-4)
# Train the modelmlp_clf.fit(X_train, y_train)
# Evaluate the modelaccuracy = mlp_clf.score(X_test, y_test)print(f"MLP Classifier Accuracy: {accuracy:.4f}")
# Plot loss curveplt.figure()plt.plot(mlp_clf.loss_curve_)plt.title('MLP Classifier Training Loss Curve')plt.xlabel('Epochs')plt.ylabel('Loss')plt.grid(True)plt.show()[图片描述:一条线图,显示 MLP 分类器的训练损失(training loss)随迭代次数(Epochs)的减少而下降。x 轴表示“迭代次数”,y 轴表示“损失”。下降趋势表明模型正在学习。]
这个示例演示了一个基本的分类任务。loss_curve_ 属性显示了训练期间误差是如何下降的。
用于回归的多层感知机 (MLP)
Section titled “用于回归的多层感知机 (MLP)”MLP 也可用于回归任务,预测连续值。Scikit-learn 提供了 MLPRegressor。
我们生成基于非线性函数 y = 2x^2 - x + 3 + noise 的数据,并尝试拟合一个 MLPRegressor。
from sklearn.neural_network import MLPRegressorimport numpy as npimport matplotlib.pyplot as plt
# Generate synthetic data for regressionnp.random.seed(42)num_points = 100X_reg = np.linspace(-5, 5, num_points).reshape(-1, 1)y_reg = (2 * X_reg**2 - X_reg + 3 + np.random.randn(num_points, 1) * 5).ravel()
# Scale features (important for NNs)scaler_X_reg = StandardScaler()X_reg_scaled = scaler_X_reg.fit_transform(X_reg)
# Split dataX_reg_train, X_reg_test, y_reg_train, y_reg_test = train_test_split(X_reg_scaled, y_reg, test_size=0.2, random_state=42)
# Create MLPRegressor model# Two hidden layers: 64 neurons, then 32 neuronsmlp_reg = MLPRegressor(hidden_layer_sizes=(64, 32), activation='relu', solver='adam', max_iter=1000, random_state=42, early_stopping=True, tol=1e-4)
# Train the modelmlp_reg.fit(X_reg_train, y_reg_train)
# Make predictionsy_reg_pred = mlp_reg.predict(X_reg_test)
# Evaluate (e.g., R-squared score)r2 = mlp_reg.score(X_reg_test, y_reg_test)print(f"MLP Regressor R-squared: {r2:.4f}")
# Plot actual vs. predicted values# To plot the regression line smoothly, predict on a dense range of X valuesX_dense = np.linspace(X_reg_scaled.min(), X_reg_scaled.max(), 200).reshape(-1, 1)y_dense_pred = mlp_reg.predict(X_dense)
plt.figure(figsize=(10, 6))plt.scatter(X_reg_test, y_reg_test, color='blue', label='Actual Data', alpha=0.6)# Need to sort X_dense for correct line plotting if using original (unscaled) X values for x-axis# For simplicity, plotting against scaled X_denseplt.plot(X_dense, y_dense_pred, color='red', linewidth=2, label='MLP Regression Fit')plt.title('MLP Regressor: Actual vs. Predicted')plt.xlabel('Scaled Feature X')plt.ylabel('Target y')plt.legend()plt.grid(True)plt.show()[图片描述:一个散点图,蓝色点代表实际数据。一条红色直线代表 MLP 回归器的拟合曲线,它试图遵循这些数据点的非线性趋势。x 轴表示“缩放后的特征 X”,y 轴表示“目标 y”。]
这些示例提供了使用 Scikit-learn 进行神经网络建模的基本介绍。对于更高级的应用,建议探索 TensorFlow/Keras 或 PyTorch,因为它们在定义自定义架构、层和训练循环方面提供了更大的灵活性。