用Python实现人工神经网络训练过程

人工神经网络(ANN)是一种受大脑启发的信息处理范式。像人类一样,人工智能也会以身作则。ANN是通过学习过程为特定应用(如模式识别或数据分类)配置的。学习主要涉及调整神经元之间的突触连接。

null

Artificial neural network1

大脑由数千亿个叫做神经元的细胞组成。这些神经元通过突触连接在一起,而突触不过是神经元向另一个神经元发送脉冲的连接。当一个神经元向另一个神经元发送兴奋性信号时,该信号将被添加到该神经元的所有其他输入中。如果它超过一个给定的阈值,那么它将导致目标神经元向前发射一个动作信号——这就是思维过程内部的工作方式。 在计算机科学中,我们通过使用矩阵在计算机上创建“网络”来模拟这个过程。这些网络可以理解为神经元的抽象,而不考虑所有的生物复杂性。为了简单起见,我们将只对一个简单的神经网络建模,它有两层,能够解决线性分类问题。

Artificial neural network1

假设我们有一个问题,我们想要预测输出,给定一组输入和输出作为训练示例,如下所示:

Artificial neural network2

注意,输出与第三列直接相关,即输入3的值是图2中每个训练示例中的输出。因此,对于测试示例,输出值应为1。

培训过程包括以下步骤:

  1. 正向传播: 获取输入,乘以权重(仅使用随机数作为权重) 设Y=W =W 1. 1. +W 2. 2. +W 3. 3. 将结果通过一个s形公式来计算神经元的输出。Sigmoid函数用于标准化0和1之间的结果: 1/1+e -y
  2. 反向传播 计算误差,即实际输出和预期输出之间的差值。根据误差,将误差与输入相乘,再与S形曲线的梯度相乘,以调整权重: 权重+=误差输入输出(1-输出),这里的输出(1-输出)是S形曲线的导数。

注: 重复整个过程几千次。 让我们用Python编写整个过程。我们将使用Numpy库帮助我们轻松完成所有矩阵计算。您需要在系统上安装一个numpy库来运行代码 安装numpy的命令:

 sudo apt -get install python-numpy

实施:

Python3

from joblib.numpy_pickle_utils import xrange
from numpy import *
class NeuralNet( object ):
def __init__( self ):
# Generate random numbers
random.seed( 1 )
# Assign random weights to a 3 x 1 matrix,
self .synaptic_weights = 2 * random.random(( 3 , 1 )) - 1
# The Sigmoid function
def __sigmoid( self , x):
return 1 / ( 1 + exp( - x))
# The derivative of the Sigmoid function.
# This is the gradient of the Sigmoid curve.
def __sigmoid_derivative( self , x):
return x * ( 1 - x)
# Train the neural network and adjust the weights each time.
def train( self , inputs, outputs, training_iterations):
for iteration in xrange (training_iterations):
# Pass the training set through the network.
output = self .learn(inputs)
# Calculate the error
error = outputs - output
# Adjust the weights by a factor
factor = dot(inputs.T, error * self .__sigmoid_derivative(output))
self .synaptic_weights + = factor
# The neural network thinks.
def learn( self , inputs):
return self .__sigmoid(dot(inputs, self .synaptic_weights))
if __name__ = = "__main__" :
# Initialize
neural_network = NeuralNet()
# The training set.
inputs = array([[ 0 , 1 , 1 ], [ 1 , 0 , 0 ], [ 1 , 0 , 1 ]])
outputs = array([[ 1 , 0 , 1 ]]).T
# Train the neural network
neural_network.train(inputs, outputs, 10000 )
# Test the neural network with a test example.
print (neural_network.learn(array([ 1 , 0 , 1 ])))


预期产出: 经过10次迭代后,我们的神经网络预测值为0.65980921。看起来不太好,因为答案应该是1。如果我们将迭代次数增加到100,则得到0.87680541。我们的网络越来越智能了!随后,对于10000次迭代,我们得到了0.9897704,这非常接近,并且确实是一个令人满意的输出。 参考资料:

本文由 维韦克·帕尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享