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


0

0

这是一个如何使用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)
如果您的输入存储在2d numpy矩阵中,其中每一行对应一个样本,列对应于样本的属性,则您可以像这样通过网络传播(假设逻辑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
的最后一个元素到第一个元素进行循环。在每个反向传播步骤之前,请确保将每一层的误差信号中的偏置列设置为零。
0

一个简单的实现
这是使用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:\n\t'+'\n\t'.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存储库 。
0

嗯,这很棘手。我之前也遇到过同样的问题,但在很好的解释却很难使用的实现之间,我找不到任何东西。
像PyBrain这样的即用型实现的问题在于它们隐藏了细节,因此对学习如何实现ANN感兴趣的人还需要其他东西。阅读此类解决方案的代码也可能具有挑战性,因为它们经常使用启发式方法来提高性能,这使入门的代码更难遵循。
但是,您可以使用一些资源:
http://msdn.microsoft.com/zh-CN/magazine/jj658979.aspx
http://itee.uq.edu.au/~cogs2010/cmc/chapters/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/
- 社区规范
- 提出问题
- 进行投票
- 个人资料
- 优化问题
- 回答问题
0
前一段时间,我开始学习机器学习(在我学习的最后两年中)。我已经读了很多书,并用机器学习算法(神经网络除外)编写了很多代码,这超出了我的范围。我对该主题非常感兴趣,但是我有一个很大的问题:我读过的所有书都有两个主要问题:
您能否建议我,在哪里可以找到多层感知(神经网络)的简单实现?我不需要理论知识,也不需要上下文嵌入的示例。我更喜欢一些脚本语言以节省时间和精力-我之前的工作中有99%是用Python完成的。
这是我之前读过的书的清单(但没有找到我想要的):