pythonbp神经网络iris分类
时间: 2023-05-30 19:05:29 浏览: 105
以下是一个使用Python和BP神经网络对鸢尾花数据集进行分类的示例代码:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 加载数据集并进行预处理
iris = load_iris()
X = iris.data
y = iris.target
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义BP神经网络模型
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 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, x):
return x * (1 - x)
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)
# 训练模型
input_size = X_train.shape[1]
hidden_size = 5
output_size = 3
nn = NeuralNetwork(input_size, hidden_size, output_size)
epochs = 1000
for i in range(epochs):
nn.train(X_train, np.eye(output_size)[y_train])
# 测试模型
y_pred = np.argmax(nn.forward(X_test), axis=1)
accuracy = np.mean(y_pred == y_test)
print('Accuracy:', accuracy)
```
上述代码中,首先加载鸢尾花数据集并对其进行预处理,然后将数据集分为训练集和测试集。接着定义BP神经网络模型,包括前向传播、反向传播和权重、偏置的更新。最后训练模型并使用测试集进行测试,计算准确度并输出结果。
阅读全文