python实现单层感知机组成多层感知机实现 异或门 函数定义
时间: 2023-12-28 19:49:41 浏览: 120
以下是Python实现单层感知机组成多层感知机实现异或门函数的定义:
```python
import numpy as np
# 定义激活函数sigmoid
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义单层感知机函数
def perceptron(x, w, b):
y = np.sum(w * x) + b
return 1 if y > 0 else 0
# 定义多层感知机函数
def MLP(x, w1, b1, w2, b2):
# 第一层神经元
h1 = sigmoid(np.sum(w1 * x) + b1)
# 第二层神经元
y = sigmoid(np.sum(w2 * h1) + b2)
return y
# 定义训练函数
def train(X, y):
# 初始化权重和偏置
w1 = np.random.rand(2, 2)
b1 = np.random.rand(2)
w2 = np.random.rand(2)
b2 = np.random.rand(1)
# 定义学习率和迭代次数
lr = 0.1
epochs = 10000
# 进行训练
for i in range(epochs):
# 前向传播
h1 = sigmoid(np.dot(X, w1) + b1)
y_pred = sigmoid(np.dot(h1, w2) + b2)
# 计算误差和梯度
error = y - y_pred
d_w2 = np.dot(h1.T, error * y_pred * (1 - y_pred))
d_b2 = np.sum(error * y_pred * (1 - y_pred))
d_h1 = np.dot(error * y_pred * (1 - y_pred), w2.T)
d_w1 = np.dot(X.T, d_h1 * h1 * (1 - h1))
d_b1 = np.sum(d_h1 * h1 * (1 - h1), axis=0)
# 更新权重和偏置
w2 += lr * d_w2
b2 += lr * d_b2
w1 += lr * d_w1
b1 += lr * d_b1
return w1, b1, w2, b2
# 测试异或门函数
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
w1, b1, w2, b2 = train(X, y)
print("w1: ", w1)
print("b1: ", b1)
print("w2: ", w2)
print("b2: ", b2)
print("Predictions: ", [MLP(x, w1, b1, w2, b2) for x in X])
```
其中,`sigmoid`函数为激活函数,`perceptron`函数为单层感知机函数,`MLP`函数为多层感知机函数,`train`函数为训练函数。最后,我们可以通过`train`训练出神经网络的权重和偏置,并通过`MLP`函数来预测输入数据的输出结果。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)