分类中的目标变量是否需要数值编码?
Is numerical encoding necessary for the target variable in classification?
我正在使用 sklearn 进行文本分类,我所有的特征都是数字,但我的目标变量标签在文本中。我可以理解将特征编码为数字背后的基本原理,但我认为这不适用于目标变量吗?
如果您的目标变量是文本形式,您可以将其转换为数字形式(或者您可以不理会它,请参阅下面我的注释)以便任何 Scikit-learn 算法在 OVA 中选择它( One Versus All) 方案:你的学习算法将尝试猜测每个 class 与剩余的相比,只有当它们将被转换为从 0 到(classes 的数字 - 1)的数字代码时.
例如,在 Scikit-Learn 文档中的这个 example 中,您可以计算出虹膜的 class,因为有三个模型可以评估每个可能的 class:
- class 0 与 classes 1 和 2
- class 1 与 classes 0 和 2
- class 2 对比 classes 0 和 1
当然,class0、1、2是Setosa、Versicolor和Virginica,但算法需要将它们表示为数字代码,您可以通过探索示例代码的结果来验证:
list(iris.target_names)
['setosa', 'versicolor', 'virginica']
np.unique(Y)
array([0, 1, 2])
NOTE: it is true that Scikit-learn encodes by itself the target labels
if they are strings. On Scikit-learn's Github page for logistic
regression
(https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/logistic.py)
you can see at rows 1623 and 1624 where the code calls the label encoder
and it encodes labels automatically:
# Encode for string labels
label_encoder = LabelEncoder().fit(y)
y = label_encoder.transform(y)
我会说是的。 Scikit-learn 对其一些训练和预测方法以及一些评分方法进行自动编码 - 但不是全部。 Source code for skl's _encode method code here。我不知道其他库,但你可能不会进行这种自动编码。
如果您在商业环境中工作,我认为最好首先对标签进行编码,这样您就不必在生产阶段重做流水线。
我正在使用 sklearn 进行文本分类,我所有的特征都是数字,但我的目标变量标签在文本中。我可以理解将特征编码为数字背后的基本原理,但我认为这不适用于目标变量吗?
如果您的目标变量是文本形式,您可以将其转换为数字形式(或者您可以不理会它,请参阅下面我的注释)以便任何 Scikit-learn 算法在 OVA 中选择它( One Versus All) 方案:你的学习算法将尝试猜测每个 class 与剩余的相比,只有当它们将被转换为从 0 到(classes 的数字 - 1)的数字代码时.
例如,在 Scikit-Learn 文档中的这个 example 中,您可以计算出虹膜的 class,因为有三个模型可以评估每个可能的 class:
- class 0 与 classes 1 和 2
- class 1 与 classes 0 和 2
- class 2 对比 classes 0 和 1
当然,class0、1、2是Setosa、Versicolor和Virginica,但算法需要将它们表示为数字代码,您可以通过探索示例代码的结果来验证:
list(iris.target_names)
['setosa', 'versicolor', 'virginica']
np.unique(Y)
array([0, 1, 2])
NOTE: it is true that Scikit-learn encodes by itself the target labels if they are strings. On Scikit-learn's Github page for logistic regression (https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/linear_model/logistic.py) you can see at rows 1623 and 1624 where the code calls the label encoder and it encodes labels automatically:
# Encode for string labels label_encoder = LabelEncoder().fit(y) y = label_encoder.transform(y)
我会说是的。 Scikit-learn 对其一些训练和预测方法以及一些评分方法进行自动编码 - 但不是全部。 Source code for skl's _encode method code here。我不知道其他库,但你可能不会进行这种自动编码。
如果您在商业环境中工作,我认为最好首先对标签进行编码,这样您就不必在生产阶段重做流水线。