Python 神经网络:手写识别-使用自己的图像
最近,我一直在学习一个很好的教程,以创建一个能够识别Python中手写数字的神经网络,但对于如何使用经过训练的网络来识别我自己的图像,我有点困惑 我在一个类似的SO线程上发现了以下代码,用于将图像转换为我需要的数组:Python 神经网络:手写识别-使用自己的图像,python,machine-learning,neural-network,Python,Machine Learning,Neural Network,最近,我一直在学习一个很好的教程,以创建一个能够识别Python中手写数字的神经网络,但对于如何使用经过训练的网络来识别我自己的图像,我有点困惑 我在一个类似的SO线程上发现了以下代码,用于将图像转换为我需要的数组: data = np.vectorize(lambda x: 255 - x)(np.ndarray.flatten(scipy.ndimage.imread("test.png", flatten=True))) 我想如果我在网络经过10个时代的训练后,通过前馈函数来实现这一点
data = np.vectorize(lambda x: 255 - x)(np.ndarray.flatten(scipy.ndimage.imread("test.png", flatten=True)))
我想如果我在网络经过10个时代的训练后,通过前馈函数来实现这一点
def feedforward(self,a):
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a)+b)
return a
然后它会返回结果——我很快发现它返回了乙状结肠神经元阵列以及哪些神经元被激发,我用以下代码将其与输出关联:
print("Prediction: " + str(unravel_index(np.argmax(data),data.shape)[1]))
这适用于某些图像,如以下图像:
但对于其他图像,返回的值接近或完全错误,例如:
我做了一些搜索,似乎没有其他人对这个问题有一个精确的答案,或者有一个关于如何做的例子或解释的答案
我不应该通过前馈方法发送图像吗?这是通过代码回顾得出的合乎逻辑的结论。在这种情况下,我应该怎么发送
整个代码
import numpy as np
import scipy
import random
# Example - net = Network([2,3,1]) creates a network with 2 neurons in
# the first layer, 3 in the second (hidden) and 1 in the final layer.
class Network(object):
def __init__(self,sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]] # Initializes
# Biases and weights randomly.
self.weights = [np.random.randn(y, x) # Stored as Numpy matrices.
for x, y in zip(sizes[:-1], sizes[1:])]
def feedforward(self,a):
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a)+b)
return a
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):
# Train the network using mini batch stoachastic gradient
# descent. The "training_data" is a list of tuples "(x,y)" representing
# training inputs and desired outputs. The "eta" is the learning rate.
if test_data: n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs): # Shuffles training data and aplies SGD for
# each mini_batch.
random.shuffle(training_data)
mini_batches = [
training_data[k:k+mini_batch_size]
for k in xrange(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print "Epoch {0}: {1} / {2}".format(
j, self.evaluate(test_data), n_test)
else:
print "Epoch {0} complete".format(j)
def update_mini_batch(self, mini_batch, eta):
#Update the network's weights and biases by applying
#gradient descent using backpropagation to a single mini batch.
#The "mini_batch" is a list of tuples "(x, y)", and "eta"
#is the learning rate.
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y) # Invokes
# backpropagation to compute gradient of the cost function.
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [w-(eta/len(mini_batch))*nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b-(eta/len(mini_batch))*nb
for b, nb in zip(self.biases, nabla_b)]
def backprop(self, x, y):
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
# Note that the variable l in the loop below is used a little
# differently to the notation in Chapter 2 of the book. Here,
# l = 1 means the last layer of neurons, l = 2 is the
# second-last layer, and so on. It's a renumbering of the
# scheme in the book, used here to take advantage of the fact
# that Python can use negative indices in lists.
for l in xrange(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)
def evaluate(self, test_data):
test_results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def cost_derivative(self, output_activations, y):
return (output_activations-y)
# Miscellaneous Functions
def sigmoid(z):
return 1.0/(1.0+np.exp(-z)) # Sigmoid Function in Vector Form
def sigmoid_prime(z):
#Derivative of the sigmoid function.
return sigmoid(z)*(1-sigmoid(z))
是的,你应该把它传给你的NN。只是因为你的模型精度低,所以它不能正确识别所有数字,比如6。为了进一步诊断您的特定问题,您必须报告模型的准确性。为此,您必须计算错误分类的样本数/除以样本总数,然后报告here@TNM在这6幅图像中,经过10个时期的30个隐藏神经元:
Epoch 9:9437/10000
so 94.37%的准确率,它打印出Prediction:1