在python中K最近的邻居

时间:2013-03-31 12:16:22

标签: python-2.7 machine-learning knn

我的数据包含单个维度和类标签。我想在上面运行KNN。

我的数据是这样的

feature       Label
0.70436073      1
0.91564351      1
0.9931506       1
2.26418779      0

我做了以下操作并最终出错了。我从错误中了解到列车的数据类型无法识别,但我不知道如何修复它。请帮忙

>>> train = [ 0.70436073,  0.91564351,  0.9931506,   2.26418779]
>>> train
[0.70436073, 0.91564351, 0.9931506, 2.26418779]
>>> label = ['1','1','1','0']
>>> from sklearn.neighbors import KNeighborsClassifier
>>> knn = KNeighborsClassifier()
>>> knn.fit(train, label)

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    knn.fit(train, label)
  File "C:\Python27\lib\site-packages\sklearn\neighbors\base.py", line 586, in fit
    return self._fit(X)
  File "C:\Python27\lib\site-packages\sklearn\neighbors\base.py", line 126, in _fit
    raise ValueError("data type not understood")
ValueError: data type not understood

2 个答案:

答案 0 :(得分:3)

错误信息很糟糕,你应该邮寄那些人并要求他们修复它,但无论如何...... http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier上的例子很清楚:fit()的第一个参数是一个列表列表,而不是数字列表。此外,第二个参数必须是“整数值数组”,但是您已经编写了一个字符串数组。

答案 1 :(得分:0)

您首先需要使用debugImplementation Deps.leakcanary releaseImplementation Deps.leakcanary_noop armImplementation Gecko.geckoview_nightly_arm x86Implementation Gecko.geckoview_nightly_x86 aarch64Implementation Gecko.geckoview_nightly_aarch64 androidTestImplementation Deps.uiautomator androidTestImplementation Deps.espresso_core, { exclude group: 'com.android.support', module: 'support-annotations' } androidTestImplementation(Deps.espresso_contrib) { exclude module: 'appcompat-v7' exclude module: 'support-v4' exclude module: 'support-annotations' exclude module: 'recyclerview-v7' exclude module: 'design' exclude module: 'espresso-core' } androidTestImplementation Deps.espresso_idling_resources androidTestImplementation Deps.tools_test_runner androidTestImplementation Deps.tools_test_rules androidTestUtil Deps.orchestrator androidTestImplementation Deps.espresso_core, { exclude group: 'com.android.support', module: 'support-annotations' } testImplementation Deps.junit_jupiter_api testImplementation Deps.junit_jupiter_params testImplementation Deps.junit_jupiter_engine testImplementation Deps.mockito_core androidTestImplementation Deps.mockito_android testImplementation Deps.mockk implementation Deps.glide debugImplementation Deps.flipper debugImplementation Deps.soLoader 将列表转换为数组。然后,由于您的数据具有一项功能,因此需要对数组进行整形。请遵循以下代码:

np.array