首先,我们需要导入必要的库和数据集:

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

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

接着,我们需要对数据进行预处理,将标签进行独热编码,并将数据集划分为训练集和测试集:

# 独热编码
def one_hot(y):
    n_values = np.max(y) + 1
    return np.eye(n_values)[y]

y = one_hot(y)

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

接下来,我们需要定义神经网络的结构和参数:

# 定义神经网络结构和参数
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))

然后,我们需要定义激活函数和损失函数:

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

def softmax(x):
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=0)

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

接下来,我们可以开始训练模型了,这里我们定义一个函数来进行模型的训练:

# 定义训练函数
def train(X, y, w1, b1, w2, b2, learning_rate, n_iters):
    losses = []
    for i in range(n_iters):
        # 前向传播
        hidden = sigmoid(np.dot(X, w1) + b1)
        output = softmax(np.dot(hidden, w2) + b2)

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

        # 反向传播
        grad_output = output - y
        grad_w2 = np.dot(hidden.T, grad_output)
        grad_b2 = np.sum(grad_output, axis=0, keepdims=True)
        grad_hidden = np.dot(grad_output, w2.T) * sigmoid(hidden) * (1 - sigmoid(hidden))
        grad_w1 = np.dot(X.T, grad_hidden)
        grad_b1 = np.sum(grad_hidden, axis=0, keepdims=True)

        # 更新参数
        w1 -= learning_rate * grad_w1
        b1 -= learning_rate * grad_b1
        w2 -= learning_rate * grad_w2
        b2 -= learning_rate * grad_b2

        if i % 100 == 0:
            print(f'Iteration {i}, loss: {loss}')

    return w1, b1, w2, b2, losses

最后,我们可以调用训练函数来训练模型,并输出损失值和准确率的曲线变化:

# 训练模型
learning_rate = 0.1
n_iters = 1000

w1, b1, w2, b2, losses = train(X_train, y_train, w1, b1, w2, b2, learning_rate, n_iters)

# 测试模型
def predict(X, w1, b1, w2, b2):
    hidden = sigmoid(np.dot(X, w1) + b1)
    output = softmax(np.dot(hidden, w2) + b2)
    return np.argmax(output, axis=1)

y_pred = predict(X_test, w1, b1, w2, b2)
y_true = np.argmax(y_test, axis=1)

# 输出准确率和损失值的曲线变化
plt.plot(losses)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()

acc = np.mean(y_pred == y_true)
print(f'Accuracy: {acc}')

完整代码如下:

基于Python实现3层BP神经网络鸢尾花分类

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

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