用python画出BP神经网络epoch与error图
时间: 2023-07-12 21:04:51 浏览: 104
好的,以下是一个简单的代码示例,实现了用Python画出BP神经网络的epoch与error图。
首先,我们需要导入需要的库:
```python
import numpy as np
import matplotlib.pyplot as plt
```
然后,我们定义一个函数 `train_BP()`,用于训练BP神经网络,并返回每个epoch的误差值:
```python
def train_BP(X, y, hidden_layers, learning_rate, max_iter):
"""
X: 输入数据
y: 目标输出
hidden_layers: 隐藏层神经元数量的列表
learning_rate: 学习率
max_iter: 最大迭代次数
"""
# 初始化权重和偏置
input_layers = X.shape[1]
output_layers = y.shape[1]
layers = [input_layers] + hidden_layers + [output_layers]
weights = [np.random.normal(size=(layers[i], layers[i+1])) for i in range(len(layers)-1)]
biases = [np.random.normal(size=(1, layers[i+1])) for i in range(len(layers)-1)]
# 记录每个epoch的误差值
errors = []
# 循环训练
for i in range(max_iter):
# 前向传播
activations = [X]
for j in range(len(layers)-1):
z = np.dot(activations[-1], weights[j]) + biases[j]
a = 1/(1+np.exp(-z))
activations.append(a)
# 计算误差
error = y - activations[-1]
errors.append(np.mean(np.abs(error)))
# 反向传播
deltas = [error * activations[-1] * (1-activations[-1])]
for j in range(len(layers)-2, 0, -1):
delta = np.dot(deltas[-1], weights[j].T) * activations[j] * (1-activations[j])
deltas.append(delta)
deltas.reverse()
# 更新权重和偏置
for j in range(len(layers)-1):
weights[j] += learning_rate * np.dot(activations[j].T, deltas[j])
biases[j] += learning_rate * np.sum(deltas[j], axis=0, keepdims=True)
return errors
```
接下来,我们使用这个函数来训练一个BP神经网络,并记录每个epoch的误差值:
```python
# 生成随机数据
X = np.random.rand(100, 5)
y = np.random.rand(100, 3)
# 训练BP神经网络
hidden_layers = [10, 5]
learning_rate = 0.1
max_iter = 1000
errors = train_BP(X, y, hidden_layers, learning_rate, max_iter)
```
最后,我们使用Matplotlib库来画出每个epoch的误差值:
```python
# 画出epoch与error图
plt.plot(range(max_iter), errors)
plt.xlabel('Epoch')
plt.ylabel('Error')
plt.show()
```
完整代码示例如下:
阅读全文