神经网络:手写识别 - 使用自己的图像

时间:2017-06-30 16:16:47

标签: python machine-learning neural-network

我最近在http://neuralnetworksanddeeplearning.com/chap1.html关注了一个很好的教程来创建一个能够识别Python中手写数字的神经网络,但我对如何使用训练有素的网络识别我自己有点困惑图片。

我在类似的SO线程上找到了这个代码,将图像转换为我需要的数组:

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

然后它将返回结果 - 因为我很快发现它返回了Sigmoid神经​​元阵列以及哪些触发了,我使用以下代码与输出相关:

print("Prediction: " + str(unravel_index(np.argmax(data),data.shape)[1]))

这适用于某些图像,例如: Handwritten Digit

但是对于其他图像,如下所示返回接近或完全错误的值:

Another Handwritten Digit

我已经做了一些搜索,没有其他人似乎对这个问题有一个确切的答案,或者有关如何做的例子或解释的答案。

我不应该通过前馈方法发送图像吗?这是通过代码向后看的逻辑结论。在这种情况下,我通过什么发送它?

整个代码

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))

0 个答案:

没有答案