在感知器学习模型的 Python 实现中将数组传递给 numpy.dot()

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

我正在尝试组合 Python 单层感知器分类器的实现。我发现 Sebastian Raschka 的书 'Python Machine Learning' 中的示例非常有用,但我对他的实现的一小部分有疑问。这是代码:

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()predict() 来获取数组 X 而不仅仅是向量。一切正常,因为我们只在 fit() 函数中将向量 xi 传递给 predict()(因此也只将向量传递给 net_input()),但是定义函数获取数组的逻辑是什么?如果我正确理解模型,我们一次只取一个样本,计算权重向量和与样本相​​关的特征向量的点积,我们永远不需要将整个数组传递给 net_input()predict().

你关心的似乎是为什么 net_input 中的 X 和预测被定义为数组而不是向量(我假设你的定义是我在上面的评论中提到的 - 虽然我会说在这种情况下没有区别)...是什么让您觉得 X 是 'array' 而不是 'vector'?

此处的类型取决于您传递给函数的内容,因此如果您将其传递给一个向量,则 X 就是一个向量(python 使用所谓的鸭子类型)。所以要回答这个问题,'why are net_input and predict defined to take an array as opposed to a vector?'...它们不是,它们只是被定义为采用参数 X,即您传递给它的任何类型...

也许您对他在拟合上下文中将变量名称 X 重用为训练数据的二维数组但在其他函数中重用为单个样本感到困惑...它们可能共享一个名称,但它们是不同的来自彼此,处于不同的范围。