林轩田 机器学习基石 作业1 PLA算法 16-17题 python2.7

林轩田 机器学习 PLA算法 16-17题

代码还没简化,能跑通

16题题意就是在15题基础上打乱数据顺序,这里利用random模块里面的shuffle函数即可解决战斗
17题就是在15题的基础上,在修改W的时候添加一个步长系数0.5
下面的代码,我将16题和17题混合在了一起写。

数据集来自

https://d396qusza40orc.cloudfront.net/ntumlone%2Fhw1%2Fhw1_15_train.dat
我直接复制下来放到txt中保存的。
同时参考了https://blog.csdn.net/devil_bye/article/details/80752529
其中如果不在样本特征中添加一位标签位,则无法跑通。
例如,该样本提供的特征是4个特征,如样本[0.32,0.178,0.156,0.97,1],最后的需要添加一位标志变成
[0.32,0.178,0.156,0.97,1](至于原因为什么,还没想通,希望有朋友能够帮我解惑)

希望大家能够提建议,谢谢

草稿代码如下

from numpy import *
import random as rd
def loadData(filename,Shuffle=False):##添加随机打乱控制位
    fr=open(filename)
    Xmat=[]
    Ymat=[]
    shuffle_data=[]
    for line in fr.readlines():
        line=line.strip()##去除头尾的空格或者是Tab
        curLine=line.split(' ')##以‘ ’为标准将string转换成list
        shuffle_data.append(curLine)
    if Shuffle:
        rd.shuffle(shuffle_data)
    for curLine in shuffle_data:
        k=curLine
        temp=curLine[:-1]
        temp2=(curLine[-1].split('\t'))[0]
        Ymat.append((curLine[-1].split('\t'))[1])
        temp.append(temp2)
        temp.append(1)
        Xmat.append(map(float,temp))###txt中的样本特征是str格式的数字字符串,所以需要转换
    Ymat=map(float,Ymat)
    return mat(Xmat),Ymat

def PLA(Xmat,Ymat,n=1):
    m,n=shape(Xmat)
    wbegin=zeros(n)
    count=0
    while True :
        iter_count = 0
        breakflag=1
        for X in Xmat:
            X=array(X[0])[0]###获得样本特征
            Ypre=array(dot(X,wbegin))
            if Ypre>0:
                Ypre=1
            else:
                Ypre=-1
            k=Ymat[iter_count]
            if Ypre!=k:
                wbegin=wbegin+n*X*Ymat[iter_count]
                count = count + 1
                breakflag=0
            iter_count = iter_count+1
        if breakflag==1:
            break
    print 'finish'
    return wbegin,count
Xmat,Ymat=loadData('hw.txt')
print PLA(Xmat,Ymat,0.5)

猜你喜欢

转载自blog.csdn.net/m0_37534550/article/details/82314008