PassiveAggressiveClassifier#
- class sklearn.linear_model.PassiveAggressiveClassifier(*, C=1.0, fit_intercept=True, max_iter=1000, tol=0.001, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, shuffle=True, verbose=0, loss='hinge', n_jobs=None, random_state=None, warm_start=False, class_weight=None, average=False)[source]#
Passive Aggressive 分类器。
自版本 1.8 弃用:整个
PassiveAggressiveClassifier类在版本 1.8 中已弃用,并将在 1.10 中移除。请改用clf = SGDClassifier( loss="hinge", penalty=None, learning_rate="pa1", # or "pa2" eta0=1.0, # for parameter C )
在用户指南中阅读更多内容。
- 参数:
- Cfloat, default=1.0
被动攻击算法的攻击性参数,参见[1]。对于PA-I,它是最大步长。对于PA-II,它对步长进行正则化(
C越小,正则化程度越高)。通常,当数据有噪声时,C应取较小值。- 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.
- 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 版本新增。
- shufflebool, default=True
Whether or not the training data should be shuffled after each epoch.
- verboseint, default=0
详细程度。
- lossstr, default=”hinge”
要使用的损失函数:hinge:等同于参考文献中的 PA-I。squared_hinge:等同于参考文献中的 PA-II。
- n_jobsint or None, default=None
用于执行 OVA(一对多,针对多类别问题)计算的 CPU 数量。除非在
joblib.parallel_backend上下文中,None表示 1。-1表示使用所有处理器。有关更多详细信息,请参阅词汇表。- random_stateint, RandomState instance, default=None
Used to shuffle the training data, when
shuffleis set toTrue. Pass an int for reproducible output across multiple function calls. See Glossary.- 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.
当 warm_start 为 True 时,重复调用 fit 或 partial_fit 可能导致与单次调用 fit 不同的解决方案,因为数据洗牌的方式。
- class_weightdict, {class_label: weight} 或 “balanced” 或 None, default=None
class_weight fit 参数的预设。
与类别相关的权重。如果未给出,则假定所有类别的权重均为 1。
“balanced” 模式使用 y 的值根据输入数据中与类频率成反比的权重自动调整权重,计算公式为
n_samples / (n_classes * np.bincount(y))。版本 0.17 新增:参数 class_weight 用于自动对样本进行加权。
- averagebool or int, default=False
当设置为 True 时,计算平均 SGD 权重并将结果存储在
coef_属性中。如果设置为大于 1 的整数,则在看到的样本总数达到平均值时开始平均。因此 average=10 将在看到 10 个样本后开始平均。版本 0.19 新增:参数 average 用于在 SGD 中使用权重平均。
- 属性:
- 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
达到停止标准的实际迭代次数。对于多类拟合,它是所有二元拟合中的最大值。
- classes_ndarray of shape (n_classes,)
唯一的类别标签。
- t_int
Number of weight updates performed during training. Same as
(n_iter_ * n_samples + 1).
另请参阅
SGDClassifier增量训练的逻辑回归。
Perceptron线性感知器分类器。
References
[1]Online Passive-Aggressive Algorithms <http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf> K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006)
示例
>>> from sklearn.linear_model import PassiveAggressiveClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_features=4, random_state=0) >>> clf = PassiveAggressiveClassifier(max_iter=1000, random_state=0, ... tol=1e-3) >>> clf.fit(X, y) PassiveAggressiveClassifier(random_state=0) >>> print(clf.coef_) [[0.26642044 0.45070924 0.67251877 0.64185414]] >>> print(clf.intercept_) [1.84127814] >>> print(clf.predict([[0, 0, 0, 0]])) [1]
- 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)[source]#
使用被动攻击算法拟合线性模型。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练数据。
- yarray-like of shape (n_samples,)
目标值。
- coef_initshape 为 (n_classes, n_features) 的 ndarray
The initial coefficients to warm-start the optimization.
- intercept_initshape 为 (n_classes,) 的 ndarray
The initial intercept to warm-start the optimization.
- 返回:
- selfobject
拟合的估计器。
- get_metadata_routing()[source]#
获取此对象的元数据路由。
请查阅 用户指南,了解路由机制如何工作。
- 返回:
- routingMetadataRequest
封装路由信息的
MetadataRequest。
- get_params(deep=True)[source]#
获取此估计器的参数。
- 参数:
- deepbool, default=True
如果为 True,将返回此估计器以及包含的子对象(如果它们是估计器)的参数。
- 返回:
- paramsdict
参数名称映射到其值。
- partial_fit(X, y, classes=None)[source]#
使用被动攻击算法拟合线性模型。
- 参数:
- Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}
训练数据的子集。
- yarray-like of shape (n_samples,)
目标值的子集。
- classesshape 为 (n_classes,) 的 ndarray
对 partial_fit 的所有调用中的类别。可以通过
np.unique(y_all)获得,其中 y_all 是整个数据集的目标向量。此参数在第一次调用 partial_fit 时是必需的,在后续调用中可以省略。请注意,y 不需要包含classes中的所有标签。
- 返回:
- selfobject
拟合的估计器。
- 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$') PassiveAggressiveClassifier[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.
- 返回:
- selfobject
更新后的对象。
- set_params(**params)[source]#
设置此估计器的参数。
此方法适用于简单的估计器以及嵌套对象(如
Pipeline)。后者具有<component>__<parameter>形式的参数,以便可以更新嵌套对象的每个组件。- 参数:
- **paramsdict
估计器参数。
- 返回:
- selfestimator instance
估计器实例。
- set_partial_fit_request(*, classes: bool | None | str = '$UNCHANGED$') PassiveAggressiveClassifier[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参数的元数据路由。
- 返回:
- selfobject
更新后的对象。
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') PassiveAggressiveClassifier[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.