使用python不调包基于BP算法实现对鸢尾花数据集的分类并可视化的代码
时间: 2023-06-03 13:01:48 浏览: 144
好的,这是一个关于机器学习的技术问题,我可以回答。以下是使用Python基于BP算法实现对鸢尾花数据集分类并可视化的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
# 加载鸢尾花数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 对数据进行预处理,将标签转为独热编码
def one_hot_encoder(y):
n_values = np.max(y) + 1
return np.eye(n_values)[y]
y = one_hot_encoder(y)
# 分离训练集和测试集
I = np.random.permutation(X.shape[0])
X_train = X[I[:100], :]
y_train = y[I[:100], :]
X_test = X[I[100:], :]
y_test = y[I[100:], :]
# 定义神经网络结构,包含一个输入层,一个隐层和一个输出层
n_input = 4
n_hidden = 5
n_output = 3
# 初始化权重和偏置
w1 = np.random.randn(n_input, n_hidden)
b1 = np.zeros(n_hidden)
w2 = np.random.randn(n_hidden, n_output)
b2 = np.zeros(n_output)
# 定义激活函数以及其导数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return sigmoid(x) * (1 - sigmoid(x))
# 训练神经网络
learning_rate = 0.1
n_iterations = 500
for i in range(n_iterations):
# 前向传播
z1 = np.dot(X_train, w1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, w2) + b2
a2 = sigmoid(z2)
# 计算误差并反向传播
error = y_train - a2
delta2 = error * sigmoid_derivative(z2)
delta1 = np.dot(delta2, w2.T) * sigmoid_derivative(z1)
# 更新权重和偏置
w2 += learning_rate * np.dot(a1.T, delta2)
b2 += learning_rate * np.sum(delta2, axis=0)
w1 += learning_rate * np.dot(X_train.T, delta1)
b1 += learning_rate * np.sum(delta1, axis=0)
# 在测试集上进行预测并计算准确率
z1 = np.dot(X_test, w1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, w2) + b2
a2 = sigmoid(z2)
predictions = np.argmax(a2, axis=1)
labels = np.argmax(y_test, axis=1)
accuracy = np.mean(predictions == labels)
print("准确率为:", accuracy)
# 可视化分类结果
plt.scatter(X_test[:, 0], X_test[:, 1], c=predictions)
plt.show()
```
希望这段代码对您有所帮助!
阅读全文