bp神经网络图片识别 python
时间: 2023-11-29 22:46:53 浏览: 68
以下是使用BP神经网络实现图片识别的Python代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
class NeuralNetwork:
def __init__(self, layers):
self.layers = layers
self.activation = sigmoid
self.derivative = sigmoid_derivative
self.weights = []
for i in range(1, len(layers) - 1):
self.weights.append((2 * np.random.random((layers[i - 1] + 1, layers[i] + 1)) - 1) * 0.25)
self.weights.append((2 * np.random.random((layers[i] + 1, layers[i + 1])) - 1) * 0.25)
def fit(self, X, y, learning_rate=0.2, epochs=10000):
X = np.hstack([np.ones((X.shape[0], 1)), X])
for k in range(epochs):
i = np.random.randint(X.shape[0])
a = [X[i]]
for l in range(len(self.weights)):
a.append(self.activation(np.dot(a[l], self.weights[l])))
error = y[i] - a[-1]
deltas = [error * self.derivative(a[-1])]
for l in range(len(a) - 2, 0, -1):
deltas.append(deltas[-1].dot(self.weights[l].T) * self.derivative(a[l]))
deltas.reverse()
for i in range(len(self.weights)):
layer = np.atleast_2d(a[i])
delta = np.atleast_2d(deltas[i])
self.weights[i] += learning_rate * layer.T.dot(delta)
def predict(self, X):
X = np.hstack([np.ones((X.shape[0], 1)), X])
a = [X]
for l in range(0, len(self.weights)):
a.append(self.activation(np.dot(a[l], self.weights[l])))
return a[-1]
digits = load_digits()
X = digits.data
y = digits.target
X -= X.min()
X /= X.max()
nn = NeuralNetwork([64, 100, 10])
X_train, X_test, y_train, y_test = train_test_split(X, y)
labels_train = LabelBinarizer().fit_transform(y_train)
labels_test = LabelBinarizer().fit_transform(y_test)
print("start fitting")
nn.fit(X_train, labels_train, epochs=20000)
print("end fitting")
predictions = []
for i in range(X_test.shape[0]):
o = nn.predict(np.atleast_2d(X_test[i]))
predictions.append(np.argmax(o))
print("Accuracy: ", (np.array(predictions) == y_test).mean())
```
该代码使用了sklearn库中的手写数字数据集,通过BP神经网络实现了对手写数字的识别。具体实现过程如下:
1. 定义sigmoid函数及其导数sigmoid_derivative函数,用于神经网络的激活函数和误差反向传播时的计算。
2. 定义NeuralNetwork类,初始化时传入神经网络的层数layers,以及激活函数和导数函数。在初始化时,随机生成每层之间的权重weights。
3. 定义fit函数,传入训练数据X和标签y,以及学习率learning_rate和迭代次数epochs。在每次迭代中,随机选择一个样本进行前向传播和误差反向传播,更新权重weights。
4. 定义predict函数,传入测试数据X,进行前向传播,得到预测结果。
5. 加载手写数字数据集,将数据归一化处理,将标签进行二值化处理。
6. 初始化神经网络,将数据集分为训练集和测试集,进行训练。
7. 对测试集进行预测,计算准确率。
阅读全文