python - scikit-learn 使用什么距离函数来处理分类特征?

标签 python machine-learning scikit-learn

我正在学习一点机器学习知识。我了解 k 最近邻 (kNN) 的基础知识,但我总是在示例中看到它用于连续数据。

我正在学习的教程现在使用 kNN 对一些混合类型的数据(连续特征和几个分类特征)进行分类。我知道对于连续的,通常只使用欧几里得距离或其他距离,但是当它混合时他们如何处理它?<​​/p>

我知道如何轻松计算二元变量的距离,但是没有“顺序”的分类变量又如何呢?

编辑:我正在关注this Kaggle 问题的教程。清理数据后,他的形式如下:

Survived    Pclass  Sex Age Fare    Embarked    Title   IsAlone Age*Class
0   0   3   0   1   0   0   1   0   3
1   1   1   1   2   3   1   3   0   2
2   1   3   1   1   1   0   2   1   3
3   1   1   1   2   3   0   3   0   2
4   0   3   0   2   1   0   1   1   6
5   0   3   0   1   1   2   1   1   3
6   0   1   0   3   3   0   1   1   3
7   0   3   0   0   2   0   4   0   0
8   1   3   1   1   1   0   3   0   3
9   1   2   1   0   2   1   3   0   0

(第一列实际上是 ID)

所以这有点奇怪,因为它是二元(例如,性别)、分类和有序(例如,年龄分为 4 或 5 个年龄段)和分类但无序(例如,Embarked 是 0, 1,或 2 基于他们所在的端口,所以我认为它没有顺序)。

数据被这样分割:

X_train = train_df.drop("Survived", axis=1)
Y_train = train_df["Survived"]
X_test  = test_df.drop("PassengerId", axis=1).copy()
X_train.shape, Y_train.shape, X_test.shape

然后一切都像这样传递给 kNN:

knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
acc_knn

那么它是如何做 kNN 的事情的呢?我们尚未提供任何信息或指示。

最佳答案

sklearn 的 kNN 将对所有特征使用相同的(选择的)指标(在 API 中指出;没有混合指标的选项!)。

你是对的,这在混合情况下是有问题的,但为此准备数据是你的工作!标准方法是使用 one-hot 编码,如所述 here :

Often features are not given as continuous values but categorical.

...

Such integer representation can not be used directly with scikit-learn estimators, as these expect continuous input, and would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily).

One possibility to convert categorical features to features that can be used with scikit-learn estimators is to use a one-of-K or one-hot encoding, which is implemented in OneHotEncoder. This estimator transforms each categorical feature with m possible values into m binary features, with only one active.

根据您的数据,这可能会大大增加功能数量!在这种情况下,您需要做出决定:

  • 使用密集数据结构(并且仍然能够在内部使用 kd 树/球树)
  • 使用稀疏数据结构(将使用强力查找;注意:使用强力查找拟合稀疏输入将覆盖此参数的设置。)

关于python - scikit-learn 使用什么距离函数来处理分类特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677080/

相关文章:

python - 如何在 scikit-learn 中使用 SGDRegressor

c# - Python3.6内调用C#代码

c++ - swig 没有名为 _example 的模块

machine-learning - 概率在机器学习软件中的作用是什么?

python-3.x - 使用 MNIST 加载数据集但出现文件未找到错误,Windows 10,Python 3

python - load_iris() 得到了一个意外的关键字参数 'as_frame'

python - 如何继承Django变量?

python - sympy:使用二项式公式和二次补数简化较大的表达式

python - 通过预定义规则将字符串列编码为数值

machine-learning - LeaveOneOut 的可疑输出