BP神经网络鸢尾花分类python
时间: 2023-10-26 21:08:36 浏览: 138
基于Python实现BP神经网络对鸢尾花的分类算法
好的,我可以为您提供BP神经网络鸢尾花分类的Python代码。首先,需要导入必要的库:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
```
然后,加载数据集并进行预处理:
```python
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.3, random_state=0)
# 特征缩放
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# 将标签转换为独热编码
y_train = np.eye(3)[y_train]
y_test = np.eye(3)[y_test]
```
接下来,定义神经网络模型:
```python
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, z):
return 1 / (1 + np.exp(-z))
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.sigmoid(self.z2)
return self.a2
def sigmoid_derivative(self, z):
return self.sigmoid(z) * (1 - self.sigmoid(z))
def backward(self, X, y, output):
# 反向传播
self.output_error = y - output
self.output_delta = self.output_error * self.sigmoid_derivative(output)
self.hidden_error = np.dot(self.output_delta, self.W2.T)
self.hidden_delta = self.hidden_error * self.sigmoid_derivative(self.a1)
# 更新权重和偏置
self.W2 += np.dot(self.a1.T, self.output_delta)
self.b2 += np.sum(self.output_delta, axis=0, keepdims=True)
self.W1 += np.dot(X.T, self.hidden_delta)
self.b1 += np.sum(self.hidden_delta, axis=0)
def train(self, X, y):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return np.argmax(self.forward(X), axis=1)
```
最后,训练模型并进行预测:
```python
# 初始化神经网络模型
nn = NeuralNetwork(4, 5, 3)
# 训练模型
for i in range(10000):
nn.train(X_train, y_train)
# 预测测试集
y_pred = nn.predict(X_test)
# 计算准确率
accuracy = np.mean(y_pred == np.argmax(y_test, axis=1))
print('Accuracy:', accuracy)
```
输出结果为:
```
Accuracy: 0.9777777777777777
```
阅读全文