python感知器_用Python编程感知器

python感知器

At HSR, I’m currently enrolled in a course about neural networks and machine learning. One of the simplest forms of a neural network model is the perceptron.

HSR ,我目前正在学习有关神经网络和机器学习的课程。 一个神经网络模型的简单形式是感知

背景资料 (Background Information)

A perceptron classifier is a simple model of a neuron. It has different inputs ($x_1$…$x_n$) with different weights ($w_1$…$w_n$).

感知器分类器是神经元的简单模型。 它具有不同权重($ w_1 $…$ w_n $)的不同输入($ x_1 $…$ x_n $)。

$$s = sum_{i=0}^n w_i cdot x_i$$
$$ s = sum_ {i = 0} ^ n w_i cdot x_i $$

The weighted sum $s$ of these inputs is then passed through a step function $f$ (usually a Heaviside step function).

然后,将这些输入的加权总和$ s $传递给阶跃函数$ f $(通常是Heaviside阶跃函数 )。

$$f(s) = begin{cases} 1 & textrm{if } s ge 0 0 & textrm{otherwise} end{cases}$$
$$ f(s)=开始{cases} 1和textrm {if} s ge ge 0 0&textrm {否则} end {cases} $$

To make things cleaner, here’s a little diagram:

为了使事情更干净,这是一个小图:

The mathematical model of a perceptron.

Python! (Python!)

Here’s a simple version of such a perceptron using Python and NumPy. It will take two inputs and learn to act like the logical OR function. First, let’s import some libraries we need:

这是使用Python和NumPy的这种感知器的简单版本。 这将需要两个输入,并学会像逻辑或功能一样工作。 首先,让我们导入一些我们需要的库:

 from from random random import import choice
choice
from from numpy numpy import import arrayarray , , dotdot , , random
random

Then let’s create the step function. In reference to Mathematica, I’ll call this function unit_step.

然后让我们创建step函数。 关于Mathematica ,我将其称为unit_step

Next we need to map the possible input to the expected output. The first two entries of the NumPy array in each tuple are the two input values. The second element of the tuple is the expected result. And the third entry of the array is a “dummy” input (also called the bias) which is needed to move the threshold (also known as the decision boundary) up or down as needed by the step function. Its value is always 1, so that its influence on the result can be controlled by its weight.

接下来,我们需要将可能的输入映射到预期的输出。 每个元组中NumPy数组的前两个条目是两个输入值。 元组的第二个元素是预期结果。 数组的第三个条目是“虚拟”输入(也称为“偏差”),根据阶跃函数的需要,该阈值可用于上下移动阈值(也称为决策边界)。 它的值始终为1,因此可以通过权重控制其对结果的影响。

 training_data training_data = = [
    [
    (( arrayarray ([([ 00 ,, 00 ,, 11 ]), ]), 00 ),
    ),
    (( arrayarray ([([ 00 ,, 11 ,, 11 ]), ]), 11 ),
    ),
    (( arrayarray ([([ 11 ,, 00 ,, 11 ]), ]), 11 ),
    ),
    (( arrayarray ([([ 11 ,, 11 ,, 11 ]), ]), 11 ),
),
]
]

As you can see, this training sequence maps exactly to the definition of the OR function:

如您所见,此训练序列完全映射到OR函数的定义:

A 一个 BA OR B A或B
0 0 0 0 0 0
0 0 1 1个 1 1个
1 1个 0 0 1 1个
1 1个 1 1个 1 1个

Next we’ll choose three random numbers between 0 and 1 as the initial weights:

接下来,我们将选择介于0和1之间的三个随机数作为初始权重:

Now on to some variable initializations. The errors list is only used to store the error values so that they can be plotted later on. If you don’t want to do any plotting, you can just leave it away. The eta variable controls the learning rate. And n specifies the number of learning iterations.

现在进行一些变量初始化。 错误列表仅用于存储错误值,以便以后可以绘制它们。 如果您不想进行任何绘图,则可以将其保留。 eta变量控制学习率。 n指定学习迭代的次数。

 errors errors = = []
[]
eta eta = = 0.2
0.2
n n = = 100
100

In order to find the ideal values for the weights w, we try to reduce the error magnitude to zero. In this simple case n = 100 iterations are enough; for a bigger and possibly “noisier” set of input data much larger numbers should be used.

为了找到权重w的理想值,我们尝试将误差幅度减小为零。 在这种简单情况下, n = 100次迭代就足够了; 对于更大且可能更“嘈杂”的输入数据集,应使用更大的数字。

First we get a random input set from the training data. Then we calculate the dot product (sometimes also called scalar product or inner product) of the input and weight vectors. This is our (scalar) result, which we can compare to the expected value. If the expected value is bigger, we need to increase the weights, if it’s smaller, we need to decrease them. This correction factor is calculated in the last line, where the error is multiplied with the learning rate (eta) and the input vector (x). It is then added to the weights vector, in order to improve the results in the next iteration.

首先,我们从训练数据中获得一个随机输入集。 然后我们计算输入和权重向量的点积(有时也称为标量积或内积)。 这是我们的(标量)结果,可以将其与期望值进行比较。 如果期望值较大,则需要增加权重;如果期望值较小,则需要减小权重。 该校正因子在最后一行中计算,其中误差乘以学习率( eta )和输入向量( x )。 然后将其添加到权重向量,以便在下一次迭代中改善结果。

And that’s already everything we need in order to train the perceptron! It has now “learned” to act like a logical OR function:

这已经是我们训练感知器所需的一切! 现在,它已“学习”以充当逻辑或函数:

 for for xx , , _ _ in in training_datatraining_data :
    :
    result result = = dotdot (( xx , , ww )
    )
    printprint (( "{}: {} -> {}""{}: {} -> {}" .. formatformat (( xx [:[: 22 ], ], resultresult , , unit_stepunit_step (( resultresult )))

)))

[[ 0 0 00 ]: ]: -- 0.0714566687173 0.0714566687173 -> -> 0
0
[[ 0 0 11 ]: ]: 0.829739696273 0.829739696273 -> -> 1
1
[[ 1 1 00 ]: ]: 0.345454042997 0.345454042997 -> -> 1
1
[[ 1 1 11 ]: ]: 1.24665040799 1.24665040799 -> -> 1
1

If you’re interested, you can also plot the errors, which is a great way to visualize the learning process:

如果您有兴趣,也可以绘制错误,这是可视化学习过程的好方法:

It’s easy to see that the errors stabilize around the 60th iteration. If you doubt that the errors are definitely eliminated, you can re-run the training with an iteration count of 500 or more and plot the errors:

不难发现,误差在第60次迭代左右稳定下来。 如果您不确定错误是否已消除,则可以使用500或更多的迭代次数重新运行训练并绘制错误:

You could also try to change the training sequence in order to model an AND, NOR or NOT function. Note that it’s not possible to model an XOR function using a single perceptron like this, because the two classes (0 and 1) of an XOR function are not linearly separable. In that case you would have to use multiple layers of perceptrons (which is basically a small neural network).

您也可以尝试更改训练序列,以对AND,NOR或NOT函数建模。 注意,不可能像这样使用单个感知器对XOR函数建模,因为XOR函数的两个类(0和1)不是线性可分离的。 在这种情况下,您将必须使用多层感知器(基本上是一个小的神经网络)。

结语 (Wrap Up)

Here’s the entire code:

这是完整的代码:

 from from random random import import choice
choice
from from numpy numpy import import arrayarray , , dotdot , , random

random

unit_step unit_step = = lambda lambda xx : : 0 0 if if x x < < 0 0 else else 1

1

training_data training_data = = [
    [
    (( arrayarray ([([ 00 ,, 00 ,, 11 ]), ]), 00 ),
    ),
    (( arrayarray ([([ 00 ,, 11 ,, 11 ]), ]), 11 ),
    ),
    (( arrayarray ([([ 11 ,, 00 ,, 11 ]), ]), 11 ),
    ),
    (( arrayarray ([([ 11 ,, 11 ,, 11 ]), ]), 11 ),
),
]

]

w w = = randomrandom .. randrand (( 33 )
)
errors errors = = []
[]
eta eta = = 0.2
0.2
n n = = 100

100

for for i i in in xrangexrange (( nn ):
    ):
    xx , , expected expected = = choicechoice (( training_datatraining_data )
    )
    result result = = dotdot (( ww , , xx )
    )
    error error = = expected expected - - unit_stepunit_step (( resultresult )
    )
    errorserrors .. appendappend (( errorerror )
    )
    w w += += eta eta * * error error * * x

x

for for xx , , _ _ in in training_datatraining_data :
    :
    result result = = dotdot (( xx , , ww )
    )
    printprint (( "{}: {} -> {}""{}: {} -> {}" .. formatformat (( xx [:[: 22 ], ], resultresult , , unit_stepunit_step (( resultresult )))
)))

If you have any questions, or if you’ve discovered an error (which is easily possible as I’ve just learned about this stuff), feel free to leave a comment below.

如果您有任何疑问,或者您发现了一个错误(这很容易实现,因为我刚刚了解了这些东西),请在下面发表评论。

翻译自: https://www.pybloggers.com/2013/03/programming-a-perceptron-in-python/

python感知器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 感知器算法 感知器算法是通过训练模式的迭代和学习算法,产生线性可分的模式判别函数。感知器算法就是通过对训练模式样本集的“学习”得出判别函数的系数解。在本次实验中,我们主要是采用硬限幅函数进行分类。 感知器的训练算法如下: 设输入矢量 , 加权矢量 ,则神经元 的输出可通过下式来计算 (1) 这里对于训练结束我们判断的依据是实际输出值与理想预期值之间误差的均方值最小。定义 它的均方值记作 ,令 , 则可以推出 (2) 可证存在最佳的加权矢量 ,使 达到最小。解得 (3) 式(3)给出了求最佳加权矢量的方法,但是需要做大量的统计计算,并且需要解决高阶矩阵求逆的问题,这些都是非常困难的。于是我们给出一种递推求解的方法: 在给定初始权值后,以这种方法可以得到递推公式: (4) 用这种方法虽然可以保证求得严格的最佳解,且避开了矩阵求逆的困难,但学习过程中的每一步仍需完成大量的统计计算。 2.BP算法 由于硬限幅函数是非可微函数,不能实现多层神经网络的一种有效的LMS学习算法。而BP算法中所用到的是Sigmoid型函数,它既具有完成分类所需的非线性特性,又具有实现LMS算法所需的可微特性。采用S型函数的神经元的输入和输出之间的关系为: (5) 采用了S型函数就可将用于单神经元的LMS学习算法适当推广,得到一种适用于前向多层神经网络的有效学习算法。 我们现在研究一个采用S型函数的前向三层神经网络来说明其原理。 对于训练样本p,它的输入是N维矢量X,X= ,网络的第一,二,三层分别包括J,K,M个神经元,它的总输出是一个M维矢量,Y= ,第i层到第i+1层之间的权重系数用 来表示。可设前向三层神经网络输出各个分量的理想值是 ,i=0,1,……M-1,而这些分量的实际值是 , i=0,1,……M-1,理想值和实际值之间的误差是 。各输出误差的平方和可以表示为: (6) 现在我们希望改变网络中的各个加权系数 ,使得 尽可能的减小。为此我们可以采取最陡下降算法的公式来调整权重系数 。公式如下: 式中的 是学习的步幅,它应随学习过程而变化。 对于通用神经层,它的各个输出 与各个输入 之间的关系可以表示为: 如果设 ,则 式中的 表示s型函数。我们不难看出上式即为给输入加一个恒等于1的部分,在神经网络中也应相应的加一个节点,而且这个节点的权系数就是这一层网络的阈值。经推倒可得权系数调整的递推公式如下: (7) 对输出层: 对隐含层: 现对于三层神经网络有 l=3时(输出层) l=2时(隐含层) l=1时(第一层) 其中: 可见,这一算法的计算过程是先计算第三层(即输出层)的各项“误差分量” ,然 后用 计算第二层(隐含层)的“等效误差分量” ,最后再用 计算第一层(隐含层)的“等效误差分量”

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值