python实现BP神经网络模型对鸢尾花分类

        这里没有用pytorch,直接通过逻辑实践,使用的是梯度下降算法,由于本身计算量不大,所以没有采用其他的优化器,当然可以使用Adam之类的更优化的算法。参数设置哪里可以修改使得准确率提高。


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

# 预处理数据
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

X_train = X_train.T  # 调整数据维度
X_test = X_test.T
y_train = y_train.reshape(1, -1)  # 调整标签维度
y_test = y_test.reshape(1, -1)
n, m = X_train.shape

# 参数设置
input_size = n
hidden_size = 10
output_size = 3
learning_rate = 0.01
epochs = 1000
L1 = []
# 初始化参数
np.random.seed(0)
W1 = np.random.randn(hidden_size, input_size) * 0.01 # random.randn函数生成一个大小为(hidden_size, input_size)的随机数组,并将其乘以0.01
b1 = np.zeros((hidden_size, 1)) # 创建一个hidden_size行1列的0矩阵
W2 = np.random.randn(output_size, hidden_size) * 0.01
b2 = np.zeros((output_size, 1))
L1 = []
# 定义激活函数
def relu(x):# 这里意思就是取最大值
    return np.maximum(0, x)

# 训练模型
for epoch in range(epochs):
# 前向传播
    Z1 = np.dot(W1, X_train) + b1 # x矩阵*w矩阵
    A1 = relu(Z1) # 通过relu函数
    Z2 = np.dot(W2, A1) + b2
    A2 = np.exp(Z2) / np.sum(np.exp(Z2), axis=0)  # softmax激活函数

 # 计算损失
    logprobs = -np.log(A2[y_train, range(m)]) #这些预测概率值取对数
    cost = np.sum(logprobs) / m
    L1.append(cost)
    # 反向传播
    dZ2 = A2
    dZ2[y_train, range(m)] -= 1
    dW2 = np.dot(dZ2, A1.T) / m
    db2 = np.sum(dZ2, axis=1, keepdims=True) / m  # keepdims=True表示保持原有数组的维度
    dA1 = np.dot(W2.T, dZ2)
    dZ1 = dA1 * (Z1 > 0)
    dW1 = np.dot(dZ1, X_train.T) / m
    db1 = np.sum(dZ1, axis=1, keepdims=True) / m

# 更新参数,进行梯度下降算法
    W2 -= learning_rate * dW2  
    b2 -= learning_rate * db2
    W1 -= learning_rate * dW1
    b1 -= learning_rate * db1

    if epoch % 100 == 0:
        print(f'Epoch {epoch}, cost: {cost}')
        L1.append(cost)
# 模型评估
Z1 = np.dot(W1, X_test) + b1
A1 = relu(Z1)
Z2 = np.dot(W2, A1) + b2
A2 = np.exp(Z2) / np.sum(np.exp(Z2), axis=0)
predictions = np.argmax(A2, axis=0)
accuracy = np.mean(predictions == y_test)

# 绘制图像
plt.plot(np.arange(len(L1)), L1, label='Training Loss')
plt.xlabel('epochs')  # 横坐标轴标题
plt.ylabel('the change of losses')  # 纵坐标轴标题
plt.show()
print('Test accuracy:', accuracy)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,关于Python基于BP神经网络鸢尾花分类问题,我可以给你一些参考。 首先,BP神经网络是一种常见的人工神经网络,它可以用于分类、回归等任务。而鸢尾花是一种常见的分类问题,因此可以用BP神经网络来进行分类。 在Python中,有多个库可以用来实现BP神经网络,例如TensorFlow、Keras、PyTorch等。这里以Keras为例,给出一个基于BP神经网络鸢尾花分类的代码: ```python from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.optimizers import SGD # 加载数据 iris = load_iris() X = iris.data y = iris.target # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) # 构建BP神经网络 model = Sequential() model.add(Dense(10, input_dim=4)) model.add(Activation('sigmoid')) model.add(Dense(3)) model.add(Activation('softmax')) # 设置优化器和损失函数 sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) # 训练模型 model.fit(X_train, y_train, epochs=200, batch_size=10) # 在测试集上评估模型 loss, accuracy = model.evaluate(X_test, y_test) print("Test loss:", loss) print("Test accuracy:", accuracy) ``` 这段代码中,先用`load_iris()`方法加载鸢尾花数据集,然后将数据集划分为训练集和测试集。接着,用Keras的`Sequential()`方法构建BP神经网络,并设置优化器和损失函数。最后,用`fit()`方法对模型进行训练,用`evaluate()`方法在测试集上评估模型的性能。 需要注意的是,鸢尾花数据集的输出有3个类别,因此需要使用softmax作为最后一层的激活函数,并使用交叉熵损失函数。此外,还需要将输出进行one-hot编码,以便进行训练和评估。 希望这个例子能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值