@xuchongfeng
2017-12-31T05:40:39.000000Z
字数 2250
阅读 96
机器学习 感知机


learning rate 则公式<1>
又可得公式<2>
由<1><2>可得
#!/usr/bin/python# coding: utf-8import numpy as npDATA_PATH = r"C:\Users\Administrator\PycharmProjects\learn_machine_learning\perceptron\dataset\data.dat"def init():data = np.loadtxt(DATA_PATH)X = data[:,0:-1]y = data[:,-1]return X, yclass Perceptron(object):def __init__(self, w_shape, learning_rate=0.01):self.w = np.random.rand(w_shape[1], w_shape[0])self.b = np.random.rand(1)self.learning_rate = learning_ratedef fit(self, X, y):while True:w, b = np.copy(self.w), np.copy(self.b)count = 0for i in range(len(X)):if y[i] * ((np.dot(w, X[i])) + b) < 0:count += 1self.w += self.learning_rate * y[i] * X[i]self.b += self.learning_rate * y[i]if count == 0: breakdef predict(self, x):return 1 if self.w * x + self.b > 0 else -1def main():X, y = init()perceptron = Perceptron((X.shape[1], 1))perceptron.fit(X, y)print(perceptron.w, perceptron.b)if __name__ == "__main__":main()
参考资料:
1. 统计学习方法-李航
2. 机器学习基石课程-林轩田