误差反向传播法实现Python代码
时间: 2023-11-12 14:12:49 浏览: 42
好的,以下是一个简单的误差反向传播算法的Python代码实现,供参考:
```python
# 定义激活函数sigmoid
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义误差函数
def error_function(y, y_hat):
return 0.5 * np.sum(np.square(y - y_hat))
# 定义误差反向传播算法函数
def back_propagation(x, y, weights, learning_rate):
# 前向传播
hidden_input = np.dot(weights['input_hidden'], x)
hidden_output = sigmoid(hidden_input)
output_input = np.dot(weights['hidden_output'], hidden_output)
y_hat = sigmoid(output_input)
# 计算输出层误差和梯度
output_error = y - y_hat
output_gradient = output_error * y_hat * (1 - y_hat)
# 计算隐藏层误差和梯度
hidden_error = np.dot(weights['hidden_output'].T, output_gradient)
hidden_gradient = hidden_error * hidden_output * (1 - hidden_output)
# 更新权重
weights['hidden_output'] += learning_rate * output_gradient * hidden_output.reshape(-1, 1)
weights['input_hidden'] += learning_rate * hidden_gradient * x.reshape(-1, 1)
# 返回误差
return error_function(y, y_hat)
```
使用时,可以先初始化权重,然后用数据逐步训练:
```python
# 初始化权重
weights = {
'input_hidden': np.random.randn(4, 3),
'hidden_output': np.random.randn(1, 4)
}
# 定义学习率和迭代次数
learning_rate = 0.5
epochs = 1000
# 逐步训练
for i in range(epochs):
error = back_propagation(x, y, weights, learning_rate)
if i % 100 == 0:
print(f'Epoch {i}, Error: {error}')
```
其中,`x` 和 `y` 分别表示输入和输出的数据,可以根据具体情况进行定义。