Perceptron#
- class sklearn.linear_model.Perceptron(*, penalty=None, alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=0.001, shuffle=True, verbose=0, eta0=1.0, n_jobs=None, random_state=0, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False)[source]#
线性感知器分类器。
此实现是
SGDClassifier的一个封装,通过固定loss和learning_rate参数来实现SGDClassifier(loss="perceptron", learning_rate="constant")
其他可用的参数在下面描述,并转发给
SGDClassifier。在 User Guide 中阅读更多内容。
- 参数:
- penalty{‘l2’,’l1’,’elasticnet’}, default=None
要使用的惩罚项(也称为正则化项)。
- alphafloat, default=0.0001
如果使用正则化,则此常量乘以正则化项。
- l1_ratiofloat, default=0.15
弹性网络混合参数,其中
0 <= l1_ratio <= 1。l1_ratio=0对应于 L2 惩罚项,l1_ratio=1对应于 L1 惩罚项。仅当penalty='elasticnet'时使用。0.24 版本新增。
- fit_interceptbool, default=True
Whether the intercept should be estimated or not. If False, the data is assumed to be already centered.
- max_iterint, default=1000
在训练数据上的最大迭代次数(又称 epoch)。它只影响
fit方法的行为,而不影响partial_fit方法。Added in version 0.19.
- tolfloat or None, default=1e-3
The stopping criterion. If it is not None, the iterations will stop when (loss > previous_loss - tol).
Added in version 0.19.
- shufflebool, default=True
Whether or not the training data should be shuffled after each epoch.
- verboseint, default=0
详细程度。
- eta0float, default=1
更新所乘的常数。
- n_jobsint, default=None
用于执行 OVA(一对多,针对多类别问题)计算的 CPU 数量。除非在
joblib.parallel_backend上下文中,None表示 1。-1表示使用所有处理器。有关更多详细信息,请参阅词汇表。- random_stateint, RandomState instance or None, default=0
Used to shuffle the training data, when
shuffleis set toTrue. Pass an int for reproducible output across multiple function calls. See Glossary.- early_stoppingbool, default=False
是否使用早停来终止训练,当验证分数没有提高时。如果设置为 True,它将自动留出分层比例的训练数据作为验证集,当验证分数在连续
n_iter_no_change个 epoch 中没有提高至少tol时,终止训练。0.20 版本新增。
- validation_fractionfloat, default=0.1
The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True.
0.20 版本新增。
- n_iter_no_changeint, default=5
Number of iterations with no improvement to wait before early stopping.
0.20 版本新增。
- class_weightdict, {class_label: weight} or “balanced”, default=None
class_weight fit 参数的预设。
与类别相关的权重。如果未给出,则假定所有类别的权重均为 1。
“balanced” 模式使用 y 的值根据输入数据中与类频率成反比的权重自动调整权重,计算公式为
n_samples / (n_classes * np.bincount(y))。- warm_startbool, default=False
When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See the Glossary.
- 属性:
- classes_ndarray of shape (n_classes,)
唯一的类别标签。
- coef_ndarray of shape (1, n_features) if n_classes == 2 else (n_classes, n_features)
Weights assigned to the features.
- intercept_ndarray of shape (1,) if n_classes == 2 else (n_classes,)
决策函数中的常数。
- n_features_in_int
在 拟合 期间看到的特征数。
0.24 版本新增。
- feature_names_in_shape 为 (
n_features_in_,) 的 ndarray 在 fit 期间看到的特征名称。仅当
X具有全部为字符串的特征名称时才定义。1.0 版本新增。
- n_iter_int
达到停止标准的实际迭代次数。对于多类别拟合,它是每个二元拟合的最大值。
- t_int
Number of weight updates performed during training. Same as
(n_iter_ * n_samples + 1).
另请参阅
sklearn.linear_model.SGDClassifier具有 SGD 训练的线性分类器(SVM、logistic 回归等)。
注意事项
Perceptron是一种分类算法,与SGDClassifier共享相同的底层实现。实际上,Perceptron()等同于SGDClassifier(loss="perceptron", eta0=1, learning_rate="constant", penalty=None)。References
https://en.wikipedia.org/wiki/Perceptron 及其中的参考文献。
示例
>>> from sklearn.datasets import load_digits >>> from sklearn.linear_model import Perceptron >>> X, y = load_digits(return_X_y=True) >>> clf = Perceptron(tol=1e-3, random_state=0) >>> clf.fit(X, y) Perceptron() >>> clf.score(X, y) 0.939...
- decision_function(X)[source]#
预测样本的置信度得分。
样本的置信度得分与该样本到超平面的有符号距离成比例。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
我们想要获取置信度得分的数据矩阵。
- 返回:
- scoresndarray of shape (n_samples,) or (n_samples, n_classes)
每个
(n_samples, n_classes)组合的置信度得分。在二元情况下,self.classes_[1]的置信度得分大于 0 意味着将预测此类。
- densify()[source]#
Convert coefficient matrix to dense array format.
Converts the
coef_member (back) to a numpy.ndarray. This is the default format ofcoef_and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op.- 返回:
- self
拟合的估计器。
- fit(X, y, coef_init=None, intercept_init=None, sample_weight=None)[source]#
Fit linear model with Stochastic Gradient Descent.
- 参数:
- X{array-like, sparse matrix}, shape (n_samples, n_features)
训练数据。
- yndarray of shape (n_samples,)
目标值。
- coef_initndarray of shape (n_classes, n_features), default=None
The initial coefficients to warm-start the optimization.
- intercept_initndarray of shape (n_classes,), default=None
The initial intercept to warm-start the optimization.
- sample_weightarray-like, shape (n_samples,), default=None
应用于单个样本的权重。如果未提供,则假定均匀权重。如果指定了 class_weight(通过构造函数传入),这些权重将与 class_weight 相乘。
- 返回:
- selfobject
Returns an instance of self.
- get_metadata_routing()[source]#
获取此对象的元数据路由。
请查阅 用户指南,了解路由机制如何工作。
- 返回:
- routingMetadataRequest
封装路由信息的
MetadataRequest。
- get_params(deep=True)[source]#
获取此估计器的参数。
- 参数:
- deepbool, default=True
如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。
- 返回:
- paramsdict
参数名称映射到其值。
- partial_fit(X, y, classes=None, sample_weight=None)[source]#
Perform one epoch of stochastic gradient descent on given samples.
在内部,此方法使用
max_iter = 1。因此,不能保证在调用一次后达到成本函数的最小值。诸如目标收敛、早停和学习率调整之类的事情应由用户处理。- 参数:
- X{array-like, sparse matrix}, shape (n_samples, n_features)
训练数据的子集。
- yndarray of shape (n_samples,)
目标值的子集。
- classesndarray of shape (n_classes,), default=None
对 partial_fit 的所有调用中的类别。可以通过
np.unique(y_all)获得,其中 y_all 是整个数据集的目标向量。此参数在第一次调用 partial_fit 时是必需的,在后续调用中可以省略。请注意,y 不需要包含classes中的所有标签。- sample_weightarray-like, shape (n_samples,), default=None
Weights applied to individual samples. If not provided, uniform weights are assumed.
- 返回:
- selfobject
Returns an instance of self.
- predict(X)[source]#
预测 X 中样本的类标签。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
我们要获取预测值的数据矩阵。
- 返回:
- y_pred形状为 (n_samples,) 的 ndarray
包含每个样本的类标签的向量。
- score(X, y, sample_weight=None)[source]#
返回在提供的数据和标签上的 准确率 (accuracy)。
在多标签分类中,这是子集准确率 (subset accuracy),这是一个严格的指标,因为它要求每个样本的每个标签集都被正确预测。
- 参数:
- Xshape 为 (n_samples, n_features) 的 array-like
测试样本。
- yshape 为 (n_samples,) 或 (n_samples, n_outputs) 的 array-like
X的真实标签。- sample_weightshape 为 (n_samples,) 的 array-like, default=None
样本权重。
- 返回:
- scorefloat
self.predict(X)相对于y的平均准确率。
- set_fit_request(*, coef_init: bool | None | str = '$UNCHANGED$', intercept_init: bool | None | str = '$UNCHANGED$', sample_weight: bool | None | str = '$UNCHANGED$') Perceptron[source]#
配置是否应请求元数据以传递给
fit方法。请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过
enable_metadata_routing=True启用了元数据路由(请参阅sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。每个参数的选项如下:
True:请求元数据,如果提供则传递给fit。如果未提供元数据,则忽略该请求。False:不请求元数据,元估计器不会将其传递给fit。None:不请求元数据,如果用户提供元数据,元估计器将引发错误。str:应将元数据以给定别名而不是原始名称传递给元估计器。
默认值 (
sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。在版本 1.3 中新增。
- 参数:
- coef_initstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
coef_initparameter infit.- intercept_initstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
intercept_initparameter infit.- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
fit方法中sample_weight参数的元数据路由。
- 返回:
- selfobject
更新后的对象。
- set_params(**params)[source]#
设置此估计器的参数。
此方法适用于简单的估计器以及嵌套对象(如
Pipeline)。后者具有<component>__<parameter>形式的参数,以便可以更新嵌套对象的每个组件。- 参数:
- **paramsdict
估计器参数。
- 返回:
- selfestimator instance
估计器实例。
- set_partial_fit_request(*, classes: bool | None | str = '$UNCHANGED$', sample_weight: bool | None | str = '$UNCHANGED$') Perceptron[source]#
Configure whether metadata should be requested to be passed to the
partial_fitmethod.请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过
enable_metadata_routing=True启用了元数据路由(请参阅sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。每个参数的选项如下:
True: metadata is requested, and passed topartial_fitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topartial_fit.None:不请求元数据,如果用户提供元数据,元估计器将引发错误。str:应将元数据以给定别名而不是原始名称传递给元估计器。
默认值 (
sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。在版本 1.3 中新增。
- 参数:
- classesstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
用于
partial_fit中classes参数的元数据路由。- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
sample_weightparameter inpartial_fit.
- 返回:
- selfobject
更新后的对象。
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') Perceptron[source]#
配置是否应请求元数据以传递给
score方法。请注意,此方法仅在以下情况下相关:此估计器用作 元估计器 中的子估计器,并且通过
enable_metadata_routing=True启用了元数据路由(请参阅sklearn.set_config)。请查看 用户指南 以了解路由机制的工作原理。每个参数的选项如下:
True:请求元数据,如果提供则传递给score。如果未提供元数据,则忽略该请求。False:不请求元数据,元估计器不会将其传递给score。None:不请求元数据,如果用户提供元数据,元估计器将引发错误。str:应将元数据以给定别名而不是原始名称传递给元估计器。
默认值 (
sklearn.utils.metadata_routing.UNCHANGED) 保留现有请求。这允许您更改某些参数的请求而不更改其他参数。在版本 1.3 中新增。
- 参数:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
score方法中sample_weight参数的元数据路由。
- 返回:
- selfobject
更新后的对象。
- sparsify()[source]#
Convert coefficient matrix to sparse format.
Converts the
coef_member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation.The
intercept_member is not converted.- 返回:
- self
拟合的估计器。
注意事项
For non-sparse models, i.e. when there are not many zeros in
coef_, this may actually increase memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with(coef_ == 0).sum(), must be more than 50% for this to provide significant benefits.After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify.