用python代码写一个bp神经网络1-10的数字识别
时间: 2024-05-08 20:17:19 浏览: 10
以下是使用Python代码实现的bp神经网络1-10数字识别的示例:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义sigmoid函数的导数
def sigmoid_derivative(x):
return x * (1 - x)
# 定义bp神经网络类
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, X, y):
self.output = self.predict(X)
self.backprop()
def predict(self, X):
self.input = X
self.feedforward()
return self.output
# 训练数据
X = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0], # 0
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], # 1
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0], # 2
[0, 0, 0, 0, 1, 0, 1, 0, 0, 0], # 3
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0], # 4
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # 5
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0], # 6
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], # 1
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0], # 5
[0, 0, 0, 0, 0, 0, 0, 1, 1, 0]]) # 6
y = np.array([[1], [2], [3], [4], [5], [6], [7], [2], [5], [6]])
# 创建bp神经网络
nn = NeuralNetwork(X, y)
# 训练bp神经网络
for i in range(10000):
nn.train(X, y)
# 预测数字
print(nn.predict(np.array([[0, 0, 0, 0, 1, 0, 1, 0, 0, 0]]))) # 预测为3
```
在上述代码中,我们首先定义了一个sigmoid函数和它的导数,然后定义了一个bp神经网络类,其中包含了前向传播、反向传播和训练等方法。接着,我们使用一个10维的数组来表示0-9这10个数字,使用一个1维的数组来表示对应的数字,然后使用这些数据来创建bp神经网络。最后,我们使用训练好的bp神经网络来预测数字。