感知器算法解决问题

问题描述

编写感知器算法程序,求下列模式分类的解向量。编程实现,编程语言不限。

ω1: {(0 0 0) t,(1 0 0) t,(1 0 1 ) t,(1 1 0) t}
ω2: {(0 0 1) t, (0 1 1) t,(0 1 0) t, (1 1 1) t}
设w(1)=(-1 -2 -2 0) t.

算法介绍

概念模型

感知器是一种神经网络模型,是20世纪50年代中期到60年代初人们对模拟人脑学习能力的一种分类学习机模型的称呼。当时有些研究者认为它是一种学习机的强有力模型,后来发现估计过高,由于无法实现非线性分类,到60年代中期,从事感知器研究的实验室纷纷下马,但在发展感知器时所获得的一些数学概念,如“赏罚分明”今天仍在模式识别中起着很大的作用。

算法描述

  1. 选择N个分属于ω1和ω2类的模式样本构成训练样本集
    { X1, …, XN }
    构成增广向量形式,并进行规范化处理。任取权向量初始
    值W(1),开始迭代。迭代次数k=1。
  2. 用全部训练样本进行一轮迭代,计算WT(k)Xi 的值,并修正权向量。分两种情况,更新权向量的值:
    • 若W(k)Xi<=0,说明分类器发生错误,权向量需要矫正,矫正为W(k+1) = W(k) + cXi。
    • W(k+1) = W(k)
  3. 分析分类结果:只要有一个错误分类,回到2,直至对所有样本正确分类。

思路

算法实现(c=1)

import numpy as np

vector = np.array(
    [
        [0, 1, 1, 1, 0, 0, 0, -1],
        [0, 0, 0, 1, 0, -1, -1, -1],
        [0, 0, 1, 0, -1, -1, 0, -1],
        [1, 1, 1, 1, -1, -1, -1, -1]
    ]
)

w = np.array([[-1, -2, -2, 0]])

c = 1       #矫正增量系数

top = 0     #迭代次数
num = 0     #判断循环结束标记
ans = 0     #当前增广向量的下标

while True:
    temp = vector[:,ans].reshape(4,1)
    res = np.matmul(w, temp)[0][0]
    if res <= 0:
        temp = temp.reshape(1,4)
        w = w + c * temp
        num += 1
    ans += 1
    if num == 0 and ans >= 8:
        top += 1
        break
    if ans >= 8:
        ans = 0
        num = 0
        top += 1

print("it has %d loop" % top)
print("the w vector is " + str(w[0]))

结果分析(c=1)

it has 4 loop
the w vector is [ 3 -2 -3  1]

经过四次循环迭代,最终w的向量值为[3,-2,-3,1]

取不同的c值,重复运行感知器算法,观测结果变化(c=2,3,4,5)

import numpy as np

vector = np.array(
    [
        [0, 1, 1, 1, 0, 0, 0, -1],
        [0, 0, 0, 1, 0, -1, -1, -1],
        [0, 0, 1, 0, -1, -1, 0, -1],
        [1, 1, 1, 1, -1, -1, -1, -1]
    ]
)


for c in range(2,6):
    w = np.array([[-1, -2, -2, 0]])

    # c = 1       #矫正增量系数

    top = 0     #迭代次数
    num = 0     #判断循环结束标记
    ans = 0     #当前增广向量的下标

    while True:
        temp = vector[:,ans].reshape(4,1)
        res = np.matmul(w, temp)[0][0]
        if res <= 0:
            temp = temp.reshape(1,4)
            w = w + c * temp
            num += 1
        ans += 1
        if num == 0 and ans >= 8:
            top += 1
            break
        if ans >= 8:
            ans = 0
            num = 0
            top += 1

    print("it has %d loop" % top)
    print("the w vector is " + str(w[0]))

结果分析(c=2,3,4,5)

it has 4 loop
the w vector is [ 3 -4 -4  2]
it has 4 loop
the w vector is [ 5 -5 -5  3]
it has 4 loop
the w vector is [ 3 -6 -6  4]
it has 4 loop
the w vector is [ 4 -7 -7  5]

进程已结束,退出代码 0

可见当校正增量系数c取值不同时,结果可能不一样,所以感知器算法的解并不是单值的。

发布了267 篇原创文章 · 获赞 51 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/AcSuccess/article/details/102696577