感知机学习

基本概念:感知机是二类分类的线性分类模型,对应于特征空间中将实例划分为正负两类的分离超平面,属判别模型。感知机学习旨在求出将训练数据进行线性划分的分离超平面。

 

感知机的定义:

从输入空间Rn到输出空间{+1,-1}的函数映射:f(x)= sign(w*x+b)

模型参数:w----权值向量   b----偏置

wx+b = 0 -----分离超平面方程

 

数据集{(xi,yi)}with 1<=i<=N称为线性可分的,如果存在分离超平面S:wx+b=0 可以将数据集的正例、负例点正确划分到其两侧

 

定义经验风险函数(损失函数):所有误分类点到分离超平面距离之和(这里为了计算方便略去一个比例系数),因此有Loss(w,b)= -sigma{yi*(w*xi+b)}, (xi,yi)属于误分类集合。在训练集上最小化损失函数,求得感知机模型。

 

感知机学习算法原始形式(使用随机梯度下降方法)

1.    选初值w0,b0

2.    从训练集随机挑选数据(xi,yi),如果训练集所有数据均以正确分类,那么结束算法,输出结果

3.    如果yi*(w*xi+b)<= 0:

更新 w,b 

w = w + r*xi*yi

b = b + r*yi

4.    转2。

 

程序实现:
import os
import sys
import random
 
#This algorithm learns a perceptron model from trainingdataset
#note: the trainset is linearly seperable, and different choicesof initial parameters or false-classified points
#may lead to different perceptron model, which is reasonableunder this framework.
#DATE:2013-7-4, by zhl
if __name__ == "__main__":
       trainset =[(3,3,1),(4,3,1),(1,1,-1)]
       #initialize
       w1 = w2 = b = 0
       id = 0
       # we set learning rate = 1
      
       while True:
            id += 1
           flag = False
           for choice in range(3):
              iftrainset[choice][2] * (w1 * trainset[choice][0] + w2 * trainset[choice][1] + b)<= 0:
                        flag = True
                        break
           if flag == False:
                  break
            #randomlyselect a point from trainset
           choice = random.randint(0,2)
      
           #judge whether it's false-classified
           if trainset[choice][2] * (w1 *trainset[choice][0] + w2 * trainset[choice][1] + b) <= 0:
                 w1 = w1 + trainset[choice][2] *trainset[choice][0]
                 w2 = w2 + trainset[choice][2] *trainset[choice][1]
                 b = b + trainset[choice][2]
        
           #print out current values
           print 'Round ',id,':','Flase ClassifiedPoint:',choice + 1,',w1:',w1,',w2:',w2,',b:',b,'\n'
      
       print 'Theperceptron model learned is sign(%d x1 + %d x2 + %d)\n' % (w1,w2,b)


<实验>给定训练集,正例x1=(3,3)x2=(4,3) 负例x3=(1,1),学习感知机模型

感知机学习_第1张图片

程序运行过程:

Round  1 : FlaseClassified Point: 1 ,w1: 3 ,w2: 3 ,b: 1

Round  2 : FlaseClassified Point: 1 ,w1: 3 ,w2: 3 ,b: 1

Round  3 : FlaseClassified Point: 2 ,w1: 3 ,w2: 3 ,b: 1

Round  4 : FlaseClassified Point: 2 ,w1: 3 ,w2: 3 ,b: 1

Round  5 : FlaseClassified Point: 1 ,w1: 3 ,w2: 3 ,b: 1

Round  6 : FlaseClassified Point: 3 ,w1: 2 ,w2: 2 ,b: 0

Round  7 : FlaseClassified Point: 1 ,w1: 2 ,w2: 2 ,b: 0

你可能感兴趣的:(机器学习,Python)