使用Python的 Numpy 编写一个神经网络,并开发 BP 算法。两个隐层,第 一个隐层 4 个神经元,第二个隐层 8 个神经元,输入是 4 个神经 元,输出是 2 个神经元。激活函数用 ReLu。并对 data.csv 数据集进 行训练和测试,计算精度。
时间: 2024-02-21 08:57:10 浏览: 80
好的,下面是使用Python的Numpy编写一个神经网络,并开发BP算法的代码实现:
首先,我们需要导入必要的库和数据集:
```python
import numpy as np
import pandas as pd
# 读取数据集
data = pd.read_csv('data.csv')
# 分离输入和输出数据
X = data.iloc[:, :-2].values
y = data.iloc[:, -2:].values
```
接下来,我们可以设置神经网络的参数和激活函数:
```python
# 设置神经网络参数
input_size = 4
hidden_size1 = 4
hidden_size2 = 8
output_size = 2
# 设置学习率和训练次数
learning_rate = 0.01
num_epochs = 1000
# 定义激活函数(ReLU和softmax)
def ReLU(x):
return np.maximum(0, x)
def softmax(x):
exp_x = np.exp(x)
return exp_x / np.sum(exp_x, axis=1, keepdims=True)
```
接下来,我们可以初始化神经网络的权重和偏置:
```python
# 随机初始化权重和偏置
W1 = np.random.randn(input_size, hidden_size1) * 0.01
b1 = np.zeros((1, hidden_size1))
W2 = np.random.randn(hidden_size1, hidden_size2) * 0.01
b2 = np.zeros((1, hidden_size2))
W3 = np.random.randn(hidden_size2, output_size) * 0.01
b3 = np.zeros((1, output_size))
```
然后,我们可以开始训练神经网络:
```python
# 训练神经网络
for epoch in range(num_epochs):
# 前向传播
z1 = np.dot(X, W1) + b1
a1 = ReLU(z1)
z2 = np.dot(a1, W2) + b2
a2 = ReLU(z2)
z3 = np.dot(a2, W3) + b3
y_pred = softmax(z3)
# 计算损失
loss = -np.mean(np.sum(y * np.log(y_pred), axis=1))
# 反向传播
delta4 = y_pred - y
dW3 = np.dot(a2.T, delta4)
db3 = np.sum(delta4, axis=0, keepdims=True)
delta3 = np.dot(delta4, W3.T) * (z2 > 0)
dW2 = np.dot(a1.T, delta3)
db2 = np.sum(delta3, axis=0)
delta2 = np.dot(delta3, W2.T) * (z1 > 0)
dW1 = np.dot(X.T, delta2)
db1 = np.sum(delta2, axis=0)
# 更新权重和偏置
W1 = W1 - learning_rate * dW1
b1 = b1 - learning_rate * db1
W2 = W2 - learning_rate * dW2
b2 = b2 - learning_rate * db2
W3 = W3 - learning_rate * dW3
b3 = b3 - learning_rate * db3
# 打印每次训练的损失
if epoch % 100 == 0:
print("Epoch {} - loss: {}".format(epoch, loss))
```
最后,我们可以使用训练好的神经网络对测试集进行预测,并计算精度:
```python
# 在测试集上进行预测
z1 = np.dot(X_test, W1) + b1
a1 = ReLU(z1)
z2 = np.dot(a1, W2) + b2
a2 = ReLU(z2)
z3 = np.dot(a2, W3) + b3
y_pred_test = softmax(z3)
# 计算精度
accuracy = np.mean(np.argmax(y_pred_test, axis=1) == np.argmax(y_test, axis=1))
print("Accuracy: {:.2f}%".format(accuracy * 100))
```
完整的代码实现如下:
阅读全文