台大机器学习基石(Machine Learning Foundations)(Quiz1--作业一)的Python实现(带详细注释)

Quiz 1 (q15-20)

源码文件链接:https://github.com/Alex-YP-Jiang/Machine-Learning-Foundations-Taiwan-University-Quiz-1-4-Python-Codes

 

>>> import math,random
>>> from pylab import*

>>> def getList(fname):  # Read the .txt file that contains the training examples(x_n, y_n), processing it to a list of lists in float.
    F = open(fname)
    L_strings = F.readlines() # returns a list of strings, each line in file is a string needs to be processed
    L_float_lists = []
    for l in L_strings:
        t1 = l.strip()
        t2 = t1.split()
        for i in range(len(t2)):
            t2[i] = float(t2[i])
        L_float_lists.append(t2)
    return L_float_lists

>>> a = getList('C:\\Users\logic\Desktop\Q15.txt')

>>> def input_array(List):  # Converts the raw list of training examples to a list of input arrays with -1 as an extra attribute value for w's threshold.
    array_list = []
    for l in List:
        L = array(l)
        L[-1] = -1
        array_list.append(L)
    return array_list

>>> def labels(List):  # saves the y_n of sample into a list
        label = []
        for l in List:
                label.append(l[-1])
        return label


>>> def PLA(inputs, labels):
    if len(inputs)!=len(labels):
        raise ValueError('# of inputs and outputs do not match!')
    N = len(labels)
    T = 0
    w = array([0,0,0,0,0])
    for i in range(N):
        match = False
        product = inputs[i]*w
        scalar = product.sum()
        if scalar*labels[i]>0:
            match = True
        elif scalar==0 and labels[i]<0:
            match = True
        while not match:    # Boolean flag + while loop
            w = w + labels[i]*inputs[i]   # PLA update
            T+=1
            p = inputs[i]*w
            s = p.sum()
            if s*labels[i]>0:
                match = True
            elif s=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值