简单的多层神经网络实现



前段时间,我开始了我的机器学习之旅(在我学习的最后两年)。除了神经网络之外,我读了很多关于机器学习算法的书,写了很多代码,这些都超出了我的范围。我对这个话题很感兴趣,但我有一个大问题:我读过的所有书都有两个主要问题:

  1. 包含数学方程的音调。课后我对它们很熟悉,我可以在纸上手写计算。
  2. 包含嵌入在一些复杂上下文中的大示例(例如调查互联网商店销售率),并且为了进入神经网络实现,我必须编写大量代码来重现上下文。缺少什么-简单直接的实现,没有大量的上下文和方程。

你能告诉我,我在哪里可以找到多层感知(神经网络)的简单实现?我不需要理论知识,也不需要上下文嵌入的例子。为了节省时间和精力,我更喜欢一些脚本语言——我以前99%的工作都是用Python完成的。

这是我以前读过的书的清单(没有找到我想要的):

  1. 机器学习在行动
  2. 编程集体智能
  3. 机器学习:算法视角
  4. Java神经网络简介
  5. c#神经网络介绍

一个简单的实现

这是一个使用Python中的类的可读实现。这个实现以效率换取可理解性:

    import math
    import random
    BIAS = -1
    """
    To view the structure of the Neural Network, type
    print network_name
    """
    class Neuron:
        def __init__(self, n_inputs ):
            self.n_inputs = n_inputs
            self.set_weights( [random.uniform(0,1) for x in range(0,n_inputs+1)] ) # +1 for bias weight
        def sum(self, inputs ):
            # Does not include the bias
            return sum(val*self.weights[i] for i,val in enumerate(inputs))
        def set_weights(self, weights ):
            self.weights = weights
        def __str__(self):
            return 'Weights: %s, Bias: %s' % ( str(self.weights[:-1]),str(self.weights[-1]) )
    class NeuronLayer:
        def __init__(self, n_neurons, n_inputs):
            self.n_neurons = n_neurons
            self.neurons = [Neuron( n_inputs ) for _ in range(0,self.n_neurons)]
        def __str__(self):
            return 'Layer:nt'+'nt'.join([str(neuron) for neuron in self.neurons])+''
    class NeuralNetwork:
        def __init__(self, n_inputs, n_outputs, n_neurons_to_hl, n_hidden_layers):
            self.n_inputs = n_inputs
            self.n_outputs = n_outputs
            self.n_hidden_layers = n_hidden_layers
            self.n_neurons_to_hl = n_neurons_to_hl
    
            # Do not touch
            self._create_network()
            self._n_weights = None
            # end
        def _create_network(self):
            if self.n_hidden_layers>0:
                # create the first layer
                self.layers = [NeuronLayer( self.n_neurons_to_hl,self.n_inputs )]
        
                # create hidden layers
                self.layers += [NeuronLayer( self.n_neurons_to_hl,self.n_neurons_to_hl ) for _ in range(0,self.n_hidden_layers)]
        
                # hidden-to-output layer
                self.layers += [NeuronLayer( self.n_outputs,self.n_neurons_to_hl )]
            else:
                # If we don't require hidden layers
                self.layers = [NeuronLayer( self.n_outputs,self.n_inputs )]
        def get_weights(self):
            weights = []
    
            for layer in self.layers:
                for neuron in layer.neurons:
                    weights += neuron.weights
    
            return weights
        @property
        def n_weights(self):
            if not self._n_weights:
                self._n_weights = 0
                for layer in self.layers:
                    for neuron in layer.neurons:
                        self._n_weights += neuron.n_inputs+1 # +1 for bias weight
            return self._n_weights
        def set_weights(self, weights ):
            assert len(weights)==self.n_weights, "Incorrect amount of weights."
    
            stop = 0
            for layer in self.layers:
                for neuron in layer.neurons:
                    start, stop = stop, stop+(neuron.n_inputs+1)
                    neuron.set_weights( weights[start:stop] )
            return self
        def update(self, inputs ):
            assert len(inputs)==self.n_inputs, "Incorrect amount of inputs."
    
            for layer in self.layers:
                outputs = []
                for neuron in layer.neurons:
                    tot = neuron.sum(inputs) + neuron.weights[-1]*BIAS
                    outputs.append( self.sigmoid(tot) )
                inputs = outputs   
            return outputs
        def sigmoid(self, activation,response=1 ):
            # the activation function
            try:
                return 1/(1+math.e**(-activation/response))
            except OverflowError:
                return float("inf")
        def __str__(self):
            return 'n'.join([str(i+1)+' '+str(layer) for i,layer in enumerate(self.layers)])

更有效的实现(通过学习)

如果你正在寻找一个更有效的神经网络学习(反向传播)的例子,看看我的神经网络Github库在这里。

嗯,这很棘手。我以前也遇到过同样的问题,但我找不到任何好的,但大量数学负载的解释和准备使用的实现。

准备使用实现(如PyBrain)的问题是它们隐藏了细节,因此对学习如何实现ann感兴趣的人需要其他东西。阅读这些解决方案的代码也可能具有挑战性,因为它们经常使用启发式方法来提高性能,这使得代码对初学者来说更难理解。

然而,有一些资源你可以使用:

http://msdn.microsoft.com/en-us/magazine/jj658979.aspx

http://itee.uq.edu.au/~ cogs2010/cmc/章节/BackProp/

http://www.codeproject.com/Articles/19323/Image-Recognition-with-Neural-Networks

http://freedelta.free.fr/r/php-code-samples/artificial-intelligence-neural-network-backpropagation/

下面是如何使用numpy实现前馈神经网络的示例。首先导入numpy并指定输入和目标的尺寸。

import numpy as np
input_dim = 1000
target_dim = 10

我们现在将构建网络结构。正如Bishop在《模式识别和机器学习》中所建议的那样,你可以简单地将numpy矩阵的最后一行视为偏置权重,将激活的最后一列视为偏置神经元。第一个/最后一个权重矩阵的输入/输出维数需要再大1,则

dimensions = [input_dim+1, 500, 500, target_dim+1]
weight_matrices = []
for i in range(len(dimensions)-1):
  weight_matrix = np.ones((dimensions[i], dimensions[i]))
  weight_matrices.append(weight_matrix)

如果你的输入存储在二维numpy矩阵中,其中每行对应一个样本,列对应样本的属性,你可以像这样通过网络传播:(假设logistic sigmoid函数作为激活函数)

def activate_network(inputs):
  activations = [] # we store the activations for each layer here
  a = np.ones((inputs.shape[0], inputs.shape[1]+1)) #add the bias to the inputs
  a[:,:-1] = inputs
  for w in weight_matrices:
    x = a.dot(w) # sum of weighted inputs
    a = 1. / (1. - np.exp(-x)) # apply logistic sigmoid activation
    a[:,-1] = 1. # bias for the next layer.
    activations.append(a)
  return activations

activations中的最后一个元素将是您的网络的输出,但是要小心,您需要省略偏倚的附加列,因此您的输出将是activations[-1][:,:-1]

要训练一个网络,你需要实现反向传播,这需要几行额外的代码。基本上,您需要从activations的最后一个元素循环到第一个元素。在每个反向传播步骤之前,请确保将误差信号中的偏差列设置为零。

这是原生python中的反向prop算法。

你试过PyBrain吗?

最新更新