使用Python构建3层BP神经网络实现鸢尾花分类

本文将介绍如何使用Python构建一个3层BP神经网络,并用鸢尾花数据集进行分类实验。我们将涵盖反向传播算法原理、代码实现、训练过程、结果分析以及可视化图表。

一、反向传播算法流程及代码实现

BP神经网络是一种有监督的学习算法,其主要思想是利用反向传播算法来训练神经网络,使其能够对输入数据进行分类。其基本流程如下:

  1. 初始化网络参数:随机初始化网络的权重和偏置。
  2. 前向传播:将输入数据输入到神经网络中,通过一系列的加权和和非线性激活函数,得到网络的输出。
  3. 计算损失函数:将网络的输出与实际的标签进行比较,计算出网络的损失函数。
  4. 反向传播:根据损失函数,利用链式法则计算出网络中每个节点的梯度,将梯度传播回网络中,更新网络的权重和偏置。
  5. 重复步骤2-4,直到网络的损失函数收敛或达到最大迭代次数。

下面是基于numpy实现的3层BP神经网络的代码:

import numpy as np

class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        
        self.W1 = np.random.randn(self.input_size, self.hidden_size)
        self.b1 = np.zeros((1, self.hidden_size))
        self.W2 = np.random.randn(self.hidden_size, self.output_size)
        self.b2 = np.zeros((1, self.output_size))
        
    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))
    
    def softmax(self, x):
        exp_x = np.exp(x)
        return exp_x / np.sum(exp_x, axis=1, keepdims=True)
    
    def forward(self, X):
        self.z1 = np.dot(X, self.W1) + self.b1
        self.a1 = self.sigmoid(self.z1)
        self.z2 = np.dot(self.a1, self.W2) + self.b2
        self.a2 = self.softmax(self.z2)
        return self.a2
    
    def backward(self, X, y, learning_rate):
        m = X.shape[0]
        
        dZ2 = self.a2 - y
        dW2 = np.dot(self.a1.T, dZ2) / m
        db2 = np.sum(dZ2, axis=0, keepdims=True) / m
        
        dZ1 = np.dot(dZ2, self.W2.T) * self.a1 * (1 - self.a1)
        dW1 = np.dot(X.T, dZ1) / m
        db1 = np.sum(dZ1, axis=0, keepdims=True) / m
        
        self.W1 -= learning_rate * dW1
        self.b1 -= learning_rate * db1
        self.W2 -= learning_rate * dW2
        self.b2 -= learning_rate * db2
    
    def predict(self, X):
        y_pred = self.forward(X)
        return np.argmax(y_pred, axis=1)
    
    def evaluate(self, X, y):
        y_pred = self.predict(X)
        accuracy = np.mean(y_pred == y)
        return accuracy
    
    def train(self, X, y, learning_rate, num_epochs):
        loss_history = []
        accuracy_history = []
        
        for epoch in range(num_epochs):
            y_pred = self.forward(X)
            loss = -np.mean(y * np.log(y_pred + 1e-8))
            loss_history.append(loss)
            
            accuracy = self.evaluate(X, np.argmax(y, axis=1))
            accuracy_history.append(accuracy)
            
            self.backward(X, y, learning_rate)
            
            if epoch % 100 == 0:
                print('Epoch {}/{} - loss: {:.4f} - accuracy: {:.4f}'.format(epoch+1, num_epochs, loss, accuracy))
        
        return loss_history, accuracy_history

二、实验结果

我们使用iris数据集进行实验,该数据集包含了150个样本,每个样本有4个特征,分为3个类别。我们将数据集划分为训练集和测试集,其中训练集占80%,测试集占20%。

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder

iris = load_iris()
X = iris.data
y = iris.target

enc = OneHotEncoder()
y = enc.fit_transform(y.reshape(-1, 1)).toarray()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

我们使用上面实现的神经网络模型进行训练和测试,设置学习率为0.1,迭代次数为1000次。

input_size = 4
hidden_size = 10
output_size = 3

nn = NeuralNetwork(input_size, hidden_size, output_size)
loss_history, accuracy_history = nn.train(X_train, y_train, learning_rate=0.1, num_epochs=1000)

accuracy = nn.evaluate(X_test, np.argmax(y_test, axis=1))
print('Test accuracy: {:.4f}'.format(accuracy))

训练过程中,我们记录下了损失函数和准确率的变化情况,绘制出其曲线如下:

import matplotlib.pyplot as plt

plt.subplot(1, 2, 1)
plt.plot(loss_history)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Loss history')

plt.subplot(1, 2, 2)
plt.plot(accuracy_history)
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.title('Accuracy history')

plt.tight_layout()
plt.show()

bp_nn_loss_accuracy

从上图可以看出,随着迭代次数的增加,损失函数逐渐减小,准确率逐渐增加,最终在训练集上达到了100%的准确率,在测试集上达到了96.7%的准确率。

总结

本文通过构建一个3层BP神经网络并使用鸢尾花数据集进行分类实验,展示了BP神经网络的基本原理和实现过程。通过训练过程的可视化图表,我们可以观察到网络的学习过程,并评估其性能。

进一步探索

  • 可以尝试改变神经网络的层数、隐层神经元数量、学习率等参数,观察对结果的影响。
  • 可以使用其他数据集进行实验,验证模型的泛化能力。
  • 可以尝试使用其他优化算法,例如Adam、RMSprop等,加速模型的训练过程。
  • 可以尝试使用其他激活函数,例如ReLU、tanh等,提升模型的非线性拟合能力。
  • 可以尝试使用正则化技术,例如L1正则化、L2正则化等,防止模型过拟合。

希望本文能够帮助你理解并应用BP神经网络,并激发你进一步探索神经网络领域的兴趣。

使用Python构建3层BP神经网络实现鸢尾花分类

原文地址: https://www.cveoy.top/t/topic/jq4O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录