反向传播算法案例代码python
时间: 2023-11-16 07:58:51 浏览: 85
以下是一个简单的Python实现的反向传播算法案例代码:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义sigmoid函数的导数
def sigmoid_derivative(x):
return x * (1 - x)
# 定义神经网络类
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape[1], 4)
self.weights2 = np.random.rand(4, 1)
self.y = y
self.output = np.zeros(self.y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
# 应用链式法则计算误差
d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid_derivative(self.output), self.weights2.T) * sigmoid_derivative(self.layer1)))
# 更新权重
self.weights1 += d_weights1
self.weights2 += d_weights2
def train(self, epochs):
for i in range(epochs):
self.feedforward()
self.backprop()
def predict(self, x):
layer1 = sigmoid(np.dot(x, self.weights1))
output = sigmoid(np.dot(layer1, self.weights2))
return output
# 测试代码
if __name__ == "__main__":
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
y = np.array([[0],[1],[1],[0]])
nn = NeuralNetwork(X, y)
nn.train(10000)
print(nn.predict(np.array([0, 1, 0])))
```
该代码实现了一个简单的神经网络,使用反向传播算法进行训练,并预测了一个输入的输出值。
阅读全文