一段时间前,我从机器学习开始了我的冒险(在我过去两年的学习中)。我读过很多书,用机器学习算法写了很多代码,除了神经网络,这超出了我的范围。我对这个话题很感兴趣,但我有一个大问题:我读过的所有书都有两个主要问题:
你能告诉我,哪里可以找到多层感知(神经网络)的简单实现?我不需要理论知识,也不需要上下文嵌入的例子。为了节省时间和精力,我更喜欢一些脚本语言--我以前的工作有99%是用Python完成的。
以下是我以前读过的书清单(但没有找到我想要的):
发布于 2013-06-11 16:42:20
一个简单的实现
下面是一个在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)])更有效的实施(通过学习)
如果您正在寻找一个更有效的具有学习能力的神经网络示例(反向传播),请看我的神经网络在此存储库。
发布于 2013-03-15 14:36:51
嗯,这很棘手。我以前也遇到过同样的问题,我找不到好的,但数学负荷很大的解释和准备使用实现之间的任何东西。
准备使用像PyBrain这样的实现的问题在于它们隐藏了细节,因此对学习如何实现ANN感兴趣的人需要其他的东西。阅读此类解决方案的代码也可能具有挑战性,因为它们经常使用启发式来提高性能,这会使代码更难开始执行。
但是,您可以使用一些资源:
http://msdn.microsoft.com/en-us/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/
发布于 2013-03-23 20:36:50
下面是一个示例,说明如何使用numpy实现前馈神经网络。首先导入numpy并指定输入和目标的尺寸。
import numpy as np
input_dim = 1000
target_dim = 10我们现在要建立网络结构。正如毕晓普伟大的“模式识别和机器学习”中所建议的那样,你可以简单地把你的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 activationsactivations中的最后一个元素将是网络的输出,但是要小心,您需要省略附加的列,以便输出为activations[-1][:,:-1]。
要训练一个网络,您需要实现反向传播,这需要额外的几行代码。基本上,您需要从activations的最后一个元素循环到第一个元素。确保在每个反向传播步骤之前,将误差信号中的偏差列设置为零。
https://stackoverflow.com/questions/15395835
复制相似问题