《机器学习基石》作业一第17题的程序

import os
import sys 
import random
# An example in that book, the training set and parameters' sizes are fixed
#training_set = [[(3, 3), 1], [(4, 3), 1], [(1, 1), -1]]
training_set=[]
for line in sys.stdin:
    arr= line.split('\t')
    tag=int(arr[1].strip(' \n'))
    data_items=arr[0].split(' ')
    iterms=()
    item=[]
    for term in data_items:
        str1=term.strip(' ')
        iterms+=(float(str1),)
    item.append(iterms)
    item.append(tag)
    training_set.append(item)
circle=range(len(training_set))
random.shuffle(circle)
w = [0, 0,0,0]
b = 0
global steps
steps=0
# update parameters using stochastic gradient descent
def update(item):
    global w, b
    global steps
    ratio=0.5
    steps+=1
    w[0] = w[0] + ratio * item[1] * item[0][0]
    w[2] = w[2] + ratio * item[1] * item[0][2]
    w[3] = w[3] + ratio * item[1] * item[0][3]
    w[1] = w[1] + ratio * item[1] * item[0][1]
    b = b + ratio * item[1]
    # print w, b # you can uncomment this line to check the process of stochastic gradient descent
 
# calculate the functional distance between 'item' an the dicision surface
def cal(item):
    global w, b
    res = 0
    for i in range(len(item[0])):
        res += item[0][i] * w[i]
    res += b
    res *= item[1]
    if item[1]==-1 and res==0 :
        return 1
    return res
 
# check if the hyperplane can classify the examples correctly
def check():
    flag = False
    global circle
    for k in circle:
        item=training_set[k]
        if cal(item) <= 0:
            flag = True
            update(item)
    if not flag:
    #    print "RESULT: w: " + str(w) + " b: "+ str(b)
        print steps
        os._exit(0)
    flag = False
 
if __name__=="__main__":


    for i in range(1000):
        check()
    print steps
    print "The training_set is not linear separable. "
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值