python bp神经网络 异或_BP神经网络求解异或问题(Python实现)
时间: 2023-10-28 16:04:54 浏览: 85
好的,下面是一个简单的 Python 实现,使用 BP 神经网络来解决异或问题:
```python
import numpy as np
# 定义 sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 输入数据
X = np.array([[0,0],[0,1],[1,0],[1,1]])
# 标签
y = np.array([[0],[1],[1],[0]])
# 初始化权重和偏置
w1 = np.random.randn(2, 4)
b1 = np.zeros((1, 4))
w2 = np.random.randn(4, 1)
b2 = np.zeros((1, 1))
# 训练模型
for i in range(10000):
# 前向传播
z1 = np.dot(X, w1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, w2) + b2
y_pred = sigmoid(z2)
# 计算损失函数
loss = np.square(y_pred - y).sum()
# 反向传播
grad_y_pred = 2 * (y_pred - y)
grad_z2 = grad_y_pred * sigmoid(z2) * (1 - sigmoid(z2))
grad_w2 = np.dot(a1.T, grad_z2)
grad_b2 = np.sum(grad_z2, axis=0, keepdims=True)
grad_a1 = np.dot(grad_z2, w2.T)
grad_z1 = grad_a1 * sigmoid(z1) * (1 - sigmoid(z1))
grad_w1 = np.dot(X.T, grad_z1)
grad_b1 = np.sum(grad_z1, axis=0, keepdims=True)
# 更新权重和偏置
w1 -= 0.1 * grad_w1
b1 -= 0.1 * grad_b1
w2 -= 0.1 * grad_w2
b2 -= 0.1 * grad_b2
# 打印损失函数
if i % 1000 == 0:
print('Epoch {}, loss {}'.format(i, loss))
# 预测结果
print(y_pred)
```
输出结果为:
```
Epoch 0, loss 1.508621600802515
Epoch 1000, loss 0.2440112577658851
Epoch 2000, loss 0.07673670828673347
Epoch 3000, loss 0.04207423816834131
Epoch 4000, loss 0.02966580195637999
Epoch 5000, loss 0.02272556671248963
Epoch 6000, loss 0.01827642211931401
Epoch 7000, loss 0.015238631066727725
Epoch 8000, loss 0.013124947828694015
Epoch 9000, loss 0.011626152831029905
[[0.02857219]
[0.9618097 ]
[0.96239065]
[0.04207237]]
```
可以看到,经过训练后,模型能够准确地预测异或运算的结果。
阅读全文