台大林轩田《机器学习基石》:作业一python实现
台大林轩田《机器学习基石》:作业二python实现
台大林轩田《机器学习基石》:作业三python实现
台大林轩田《机器学习基石》:作业四python实现
完整代码:
https://github.com/xjwhhh/LearningML/tree/master/MLFoundation
欢迎follow和star
在学习和总结的过程中参考了不少别的博文,且自己的水平有限,如果有错,希望能指出,共同学习,共同进步
##15
下载训练数据,每一行都是一个训练实例,每一行的数据中,前四项是特征值,最后一项是标签,编写PLA算法进行分类,设w初始为0,sign(0)=-1,问迭代多少次后算法结束?
1.需要自己手动添加一维特征,X0=1
2.一个点分类正确的条件是xwy>0(PLA)
3.算法结束的条件是所有实例都被分配正确
代码如下:
import numpy
class NaiveCyclePLA(object):
def __init__(self, dimension, count):
self.__dimension = dimension
self.__count = count
# get data
def train_matrix(self, path):
training_set = open(path)
x_train = numpy.zeros((self.__count, self.__dimension))
y_train = numpy.zeros((self.__count, 1))
x = []
x_count = 0
for line in training_set:
# add 1 dimension manually
x.append(1)
for str in line.split(' '):
if len(str.split('\t')) == 1:
x.append(float(str))
else:
x.append(float(str.split('\t')[0]))
y_train[x_count, 0] = int(str.split('\t')[1].strip())
x_train[x_count, :] = x
x = []
x_count += 1
return x_train, y_train
def iteration_count(self, path):
count = 0
x_train, y_train = self.train_matrix(path)
w = numpy.zeros((self.__dimension, 1))
# loop until all x are classified right
while True:
flag = 0
for i in range(self.__count):
if numpy.dot(x_train[i, :], w)[0] * y_train[i, 0] &