簡體   English   中英

在Perceptron Learning Model的Python實現中將數組傳遞給numpy.dot()

[英]Passing an array to numpy.dot() in Python implementation of Perceptron Learning Model

我正在嘗試將單層Perceptron分類器的Python實現放在一起。 我發現Sebastian Raschka的書“Python機器學習”中的例子非常有用,但我對他實現的一小部分有疑問。 這是代碼:

import numpy as np    
class Perceptron(object):
    """Perceptron classifier.

    Parameters
    ------------
    eta : float
        Learning rate (between 0.0 and 1.0)
    n_iter : int
        Passes over the training dataset.

    Attributes
    -----------
    w_ : 1d-array
        Weights after fitting.
    errors_ : list
        Number of misclassifications in every epoch.

    """
    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        """Fit training data.

        Parameters
        ----------
        X : {array-like}, shape = [n_samples, n_features]
            Training vectors, where n_samples 
            is the number of samples and
            n_features is the number of features.
        y : array-like, shape = [n_samples]
            Target values.

        Returns
        -------
        self : object

        """
        self.w_ = np.zeros(1 + X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X, y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)

我無法net_input()的部分是為什么我們定義net_input()predict()來獲取數組X而不僅僅是一個向量。 一切都工作正常,因為我們只是在fit()函數中傳遞向量xipredict() (因此也只是將向量傳遞給net_input() ),但是定義函數的邏輯是什么呢?陣列? 如果我正確理解模型,我們一次只取一個樣本,計算權重向量和與樣本相​​關的特征向量的點積,我們永遠不需要將整個數組傳遞給net_input()predict()

您的擔憂似乎是為什么net_input中的X和預測被定義為數組而不是向量(我假設您的定義是我在上面的注釋中提到的 - 實際上我會說在這種情況下沒有區別) ......是什么讓你覺得X是'數組'而不是'向量'?

這里的輸入是由你傳遞函數決定的,所以如果你傳遞一個向量,X就是一個向量(python使用所謂的duck typing)。 所以回答這個問題,'為什么net_input和predict被定義為采用數組而不是向量?'......它們不是,它們只是被定義為采用參數X,這是你傳遞它的任何類型。 。

也許你很困惑他將變量名稱X重新用作擬合上下文中的2d訓練數據數組,但作為其他函數中的單個樣本......他們可能共享一個名稱,但它們彼此不同,在於不同的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM