机器学习算法——感知机(Python源码)

#*-encoding:utf-8-*

########################################################################################################
# Summary: 感知机模型
# Author: Kurt
# Date: 2016/3/23
########################################################################################################

#-------------------------------------------------------------------------------------------------------
# 装作有数据的函数
def createData():
    data = [[3, 3, 1], [4, 3, 1], [1, 1, -1]]
    return data

#-------------------------------------------------------------------------------------------------------
# 更新权重
def update(weight, tuple, step):
    weight[0] += step * tuple[-1]
    for i in range(len(tuple) -1):
        weight[i+1] += step * tuple[i] * tuple[-1]
    return weight


#-------------------------------------------------------------------------------------------------------
# 返回权重与样本点的向量点积
def calculate(weight, tuple):
    sum = weight[0]
    for i in range(len(tuple) -1):
        sum += weight[i+1] * tuple[i]
    sum *= tuple[-1]
    print sum
    return sum

#-------------------------------------------------------------------------------------------------------
# 感知机模型
def percetron(dataSet, step = 1):
    w = []  # 权重向量,里面包括了偏倚b
    isNotDone = True
    # 初始化权重向量
    for i in range(len(dataSet[0])):
        w.append(0)
    while(isNotDone):
        print "\n\nScan the data again"
        # 遍历每一个样本点
        for tuple in dataSet:
            # 如果分类错误
            if(calculate(w, tuple) <= 0):
                print "Error point: "
                print tuple
                isNotDone = True
                update(w, tuple, step)
                print "----->>>New weight is ", w
                break
            else:
                isNotDone = False
    return w
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值