[关闭]
@NumberFairy 2017-08-17T10:11:30.000000Z 字数 1426 阅读 758

感知器实验


import numpy as np
class Perceptron(object):
    """
    eta:学习率
    n_iter: 权重向量的训练次数
    errors_: 用于记录神经元判断出错次数
    """
    def __init__(self,eta  = 0.01, n_iter = 10):
        self.eta =  eta;
        self.n_iter = n_iter;
        pass

def fit(self, X , y):
    """
    该方法作用:输入训练数据,培训神经元,x 输入样本向量, y 对应样本分类

    X:shape[n_samples,n_features]
    X:[[1,2,3],[4,5,6]]
    n_samples:2(样本数量)
    n_features:3(每一个向量对应三个电信号)

    Y:[1,-1] ([1,2,3]这个向量对应的分类是1,[4,5,6]这个向量对应的分类是-1)
    """

    """
    初始化权重向量为0
    加  1 是因为算法提到的w0 ,也就是步调函数的阈值
    """        
    self.w_ = np.zeros(1 + X.shape[1]);
    self.errors_ = [];

    for _ in range(self.n_iter):
        errors = 0;
        """
        X:[[1,2,3],[4,5,6]]
        y:[1,-1]
        zip(X,y) =  [[1,2,3,1],[4,5,6,-1]]
        """
        for xi, target in zip(X,y):
            """
            update = η * (y - y')
            """
            update = self.eta * (target - self.predict(xi))
            """
            下面就是全重更新
            xi是一个向量
            update * xi 等价:
            [ΔW(1)  = X[1] * update , Δw(2) = X[2] * update , Δw(3) = X[3] *update;
            """
            self.w_[1:] += update * xi
            self.w_[0]  +=  update;
            errors += int(update !=0.0)
            self.errors_.append(errors)
            pass

        pass       
    pass
def net_input(self,X):
        """
        z = w0 * X1 +... wn * Xn
        """
        return np.dot(X,self.w_[1:] + self.w_[0])
        pass

def predict(self,X):
        return np.where(self.net_input(X) >= 0.0 ,1, -1)
        pass

#读取csv
file = "C:/Users/X240/Desktop/testCSV.csv"
import pandas as pd
df = pd.read_csv(file,header = None)
df.head(20)


#绘制数据图像
import matplotlib.pyplot as plt
import numpy as np

y = df.loc[0:100,4].values
y = np.where(y == 'LIKE',-1,1)

X = df.iloc[0:100,[0,2]].values

plt.scatter(X[:50, 0], X[:50, 1], color = 'red', marker = 'o', label = 'setosa')
plt.scatter(X[50:100, 0],X[50:100, 1], color = 'blue', marker = 'x' , label = 'versicolor')
plt.xlabel('XBe')
plt.ylabel('YBe')
plt.legend(loc = 'upper left')
plt.show()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注