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

本教程将使用Python从零开始构建一个3层BP神经网络,并利用经典的鸢尾花数据集进行分类。我们将详细讲解每个步骤,并提供完整的代码示例。

1. 导入库

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

2. 加载数据集并划分

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)

3. 数据归一化

# 归一化处理
X_train = X_train / np.max(X_train, axis=0)
X_test = X_test / np.max(X_test, axis=0)

4. 定义神经网络结构和参数

# 定义神经网络结构和参数
input_size = 4
hidden_size = 10
output_size = 3

W1 = np.random.randn(input_size, hidden_size)
b1 = np.zeros((1, hidden_size))

W2 = np.random.randn(hidden_size, output_size)
b2 = np.zeros((1, output_size))

5. 定义激活函数和损失函数

# 定义激活函数和损失函数
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x):
    return x * (1 - x)

def softmax(x):
    exp_x = np.exp(x)
    return exp_x / np.sum(exp_x, axis=1, keepdims=True)

def cross_entropy_loss(y_pred, y_true):
    m = y_pred.shape[0]
    loss = -1 / m * np.sum(y_true * np.log(y_pred))
    return loss

6. 定义训练函数和预测函数

# 定义训练函数和预测函数
def train(X, y, learning_rate=0.1, epochs=1000):
    losses = []
    for i in range(epochs):
        # 前向传播
        hidden_layer = sigmoid(np.dot(X, W1) + b1)
        output_layer = softmax(np.dot(hidden_layer, W2) + b2)

        # 计算损失函数
        loss = cross_entropy_loss(output_layer, y)
        losses.append(loss)

        # 反向传播
        d_output = output_layer - y
        d_hidden = np.dot(d_output, W2.T) * sigmoid_derivative(hidden_layer)

        # 更新参数
        W2 -= learning_rate * np.dot(hidden_layer.T, d_output)
        b2 -= learning_rate * np.sum(d_output, axis=0, keepdims=True)
        W1 -= learning_rate * np.dot(X.T, d_hidden)
        b1 -= learning_rate * np.sum(d_hidden, axis=0, keepdims=True)

    return losses

def predict(X):
    hidden_layer = sigmoid(np.dot(X, W1) + b1)
    output_layer = softmax(np.dot(hidden_layer, W2) + b2)
    predictions = np.argmax(output_layer, axis=1)
    return predictions

7. 训练模型并预测

# 训练模型
losses = train(X_train, np.eye(output_size)[y_train], learning_rate=0.1, epochs=1000)

# 预测测试集
predictions = predict(X_test)
accuracy = np.mean(predictions == y_test)
print('Accuracy:', accuracy)

8. 绘制损失函数和准确率曲线

# 绘制损失函数和准确率的曲线变化
plt.plot(losses)
plt.title('Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.show()

accuracies = []
for i in range(1, 1001):
    predictions = predict(X_test)
    accuracy = np.mean(predictions == y_test)
    accuracies.append(accuracy)

plt.plot(accuracies)
plt.title('Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.show()

9. 实验结果

损失函数和准确率曲线

根据实验结果,我们可以看到模型的损失值在训练过程中逐渐下降,准确率逐渐上升,最终的准确率为1.0,说明模型的分类效果非常好。

总结

本教程详细讲解了使用Python实现一个3层BP神经网络进行鸢尾花分类的步骤。通过代码示例和结果可视化,帮助读者理解反向传播算法的原理和应用。希望本教程能对您学习神经网络有所帮助。

Python实现3层BP神经网络鸢尾花分类 - 代码详解及可视化

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

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