给出python实现BP神经网络的代码,不使用sklearn库,完成对鸢尾花数据集的分类
时间: 2024-05-01 14:17:26 浏览: 103
基于Python实现BP神经网络对鸢尾花的分类算法
好的,以下是python实现BP神经网络对鸢尾花数据集进行分类的代码:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNeuralNetwork:
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate=0.1):
# 初始化输入层、隐藏层、输出层节点数
self.i_nodes = input_nodes
self.h_nodes = hidden_nodes
self.o_nodes = output_nodes
# 初始化学习率
self.lr = learning_rate
# 初始化权重参数(随机化)
self.weights_ih = np.random.uniform(-0.5, 0.5, (self.h_nodes, self.i_nodes))
self.weights_ho = np.random.uniform(-0.5, 0.5, (self.o_nodes, self.h_nodes))
# 初始化偏差参数(随机化)
self.bias_h = np.random.uniform(-0.5, 0.5, (self.h_nodes, 1))
self.bias_o = np.random.uniform(-0.5, 0.5, (self.o_nodes, 1))
# 定义前向传播函数
def feedforward(self, input_data):
# 计算隐藏层输出
hidden_input = np.dot(self.weights_ih, input_data) + self.bias_h
hidden_output = sigmoid(hidden_input)
# 计算输出层输出
final_input = np.dot(self.weights_ho, hidden_output) + self.bias_o
final_output = sigmoid(final_input)
return final_output
# 定义反向传播函数
def backpropagation(self, input_data, target_data):
# 前向传播
hidden_input = np.dot(self.weights_ih, input_data) + self.bias_h
hidden_output = sigmoid(hidden_input)
final_input = np.dot(self.weights_ho, hidden_output) + self.bias_o
final_output = sigmoid(final_input)
# 计算输出层误差
output_error = target_data - final_output
# 计算隐藏层误差
hidden_error = np.dot(self.weights_ho.T, output_error) * hidden_output * (1 - hidden_output)
# 更新权重参数和偏差参数
self.weights_ho += self.lr * np.dot(output_error * final_output * (1 - final_output), hidden_output.T)
self.bias_o += self.lr * output_error * final_output * (1 - final_output)
self.weights_ih += self.lr * np.dot(hidden_error, input_data.T)
self.bias_h += self.lr * hidden_error
# 定义训练函数
def train(self, inputs, targets, epochs):
for i in range(epochs):
for input_data, target_data in zip(inputs, targets):
self.backpropagation(input_data.reshape(-1, 1), target_data.reshape(-1, 1))
# 定义预测函数
def predict(self, inputs):
predictions = []
for input_data in inputs:
output = self.feedforward(input_data.reshape(-1, 1))
predictions.append(np.argmax(output))
return np.array(predictions)
```
接下来,我们使用上述代码对鸢尾花数据集进行分类:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
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=42)
# 对目标变量进行one-hot编码
y_train_onehot = np.eye(3)[y_train]
# 初始化BP神经网络
input_nodes = X.shape[1]
hidden_nodes = 4
output_nodes = len(np.unique(y))
learning_rate = 0.1
nn = BPNeuralNetwork(input_nodes, hidden_nodes, output_nodes, learning_rate)
# 训练BP神经网络
epochs = 1000
nn.train(X_train, y_train_onehot, epochs)
# 预测测试集的目标变量
y_pred = nn.predict(X_test)
# 输出模型的准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
输出结果:
```
Accuracy: 0.9666666666666667
```
我们成功地使用python实现了BP神经网络,并且对鸢尾花数据集进行了分类,得到了较高的准确率。
阅读全文