統(tǒng)計學習方法之感知機Perceptron

1. 感知機模型詳解

感知機由1957年提出蘸拔,感知機模型較為簡單北戏,是NN和SVM的基礎(chǔ)模型负芋。
結(jié)構(gòu)如下圖


perceptron.jpg

定義:
給定訓練集合

2.原始學習方法

一個常見的想法是給定誤分類點集合M,

3.學習方法的對偶形式

對偶形式的思想在于,

4.代碼實現(xiàn)

抽象類 classifier.py
感知機模型 perceptron.py
測試 test_perceptron.py

#classifier.py
class Classifier(metaclass=ABCMeta):
    """Base class for all classifiers

        Warning: This class should not be used directly.
        Use derived classes instead.
    """

    @abstractmethod
    def fit(self, X, y):
        """Given train data X and labels y,and feature labels,  fit the classifier

        Parameters
        ----------
        X : array_like or sparse matrix, shape = [n_samples, n_features]
            The input samples. Internally, it will be converted to
            ``dtype=np.float32`` and if a sparse matrix is provided
            to a sparse ``csr_matrix``.

        y : array_like, length = n_samples

        Returns
        -------
        None
        """
        raise NotImplementedError()

    @abstractmethod
    def predict(self, X):
        """Given train data X and labels y, fit the classifier

        Parameters
        ----------
        X : array_like or sparse matrix, shape = [n_samples, n_features]
            The input samples. Internally, it will be converted to
            ``dtype=np.float32`` and if a sparse matrix is provided
            to a sparse ``csr_matrix``.

        Returns
        -------
        predit labels,array_like, length=n_samples
        """
        raise NotImplementedError()
#perceptron.py

import numpy as np
from numpy import shape
from base import Classifier
from utils import accuracy_score
from utils import sign

class Perceptron(Classifier):
    '''
    Implementation of Perceptron
    '''

    def __init__(self, max_iterations=100, esplion=1e-3, learning_rate=0.1, threshold=0.9):
        assert max_iterations > 0
        assert 1 > esplion > 0
        assert 0 < learning_rate <= 1

        self.max_iterations = max_iterations
        self.esplion = esplion
        self.learning_rate = learning_rate
        self.threshold = threshold

    def fit(self, X, y):
        '''
        fit process of perceptron
        '''
        self.X = X
        self.y = y
        self._check_params()

        n_samples, n_features = shape(self.X)
        # Gram matrix
        gram_matrix = np.dot(self.X, self.X.T)
        self.alpha = np.zeros(n_samples)
        self.b = 0
        for iter in range(self.max_iterations):
            for ind in range(n_samples):
                # misclassification point
                if self.y[ind] * sum(self.alpha * (gram_matrix[:, ind].T * self.y)) <= 0:
                    self.alpha[ind] = self.alpha[ind] + self.learning_rate
                    self.b = self.b + self.y[ind] * self.learning_rate

            # compare accuracy
            if self.score(X, y) > self.threshold:
                break

    def score(self, X, y):
        return accuracy_score(y, self.predict(X))

    def _check_params(self):
        '''
        check params
        '''
        # assert type(self.X).__name__=='ndarray'
        # assert type(self.y).__name__=='ndarray'
        assert shape(self.X)[0] == len(self.y)

    def _predict_sample(self, sample):
        return sign(sum((sum((self.alpha * self.X.T * self.y).T)) * sample) + self.b)

    def predict(self, X):
        return np.array([self._predict_sample(sample) for sample in X])
#test_perceptron.py

import numpy as np
from linear import Perceptron

class TestPerceptron(object):
    def test_perceptron(self):
        clf = Perceptron(learning_rate=1)
        X, y = np.array([[3, 3], [4, 3], [1, 1]]), np.array([1, 1, -1])
        clf.fit(X, y)
        assert clf.score(X, y) > 0.9

5.FAQ

  • Q1 感知機和NN以及SVM的區(qū)別與聯(lián)系嗜愈?
    A:
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末示罗,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子芝硬,更是在濱河造成了極大的恐慌,老刑警劉巖轧房,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拌阴,死亡現(xiàn)場離奇詭異,居然都是意外死亡奶镶,警方通過查閱死者的電腦和手機迟赃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門陪拘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人纤壁,你說我怎么就攤上這事左刽。” “怎么了酌媒?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵欠痴,是天一觀的道長。 經(jīng)常有香客問我秒咨,道長喇辽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任雨席,我火速辦了婚禮菩咨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘陡厘。我一直安慰自己抽米,他們只是感情好,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布糙置。 她就那樣靜靜地躺著云茸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪罢低。 梳的紋絲不亂的頭發(fā)上查辩,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機與錄音网持,去河邊找鬼宜岛。 笑死,一個胖子當著我的面吹牛功舀,可吹牛的內(nèi)容都是我干的萍倡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼辟汰,長吁一口氣:“原來是場噩夢啊……” “哼列敲!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起帖汞,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤戴而,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后翩蘸,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體所意,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年泄鹏,在試婚紗的時候發(fā)現(xiàn)自己被綠了秧耗。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片备籽。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖车猬,靈堂內(nèi)的尸體忽然破棺而出诈唬,到底是詐尸還是另有隱情,我是刑警寧澤杭朱,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站刃唐,受9級特大地震影響衔瓮,放射性物質(zhì)發(fā)生泄漏热鞍。R本人自食惡果不足惜薇宠,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望慢睡。 院中可真熱鬧漂辐,春花似錦髓涯、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽护姆。三九已至卵皂,卻和暖如春灯变,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背膝捞。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留林艘,地道東北人钢坦。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓镶殷,卻偏偏與公主長得像颤陶,于是被迫代替她去往敵國和親滓走。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容