【问题标题】:Scikit Value Error: Expected 2D array, got 1D array insteadScikit 值错误:预期 2D 数组,得到 1D 数组
【发布时间】:2021-05-14 18:03:03
【问题描述】:

我正在尝试 scikit-learn。我有一个非常简单的时间戳和气体浓度数据集,格式为 ppm。

错误:

ValueError: Expected 2D array, got 1D array instead:
array=[396.4 394.  395.8 395.3 404.2 400.6 397.7 401.5 394.7 398.9 402.5 394.6
 401.2 401.  399.  398.5 401.3 401.7 406.5 395.9 401.2 399.8 398.2 401.9
 405.4 396.1 402.8 404.4 402.5 400.9 402.8 397.8 399.7 398.4 403.4 401.4
 393.1].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

代码:

import numpy as np
import pandas as pd
from sklearn.cluster import KMeans

data = pd.read_csv(r"myfilepath.csv")
print(data.shape)

kmeans = KMeans(n_clusters = 2, random_state = 0)
X = data['reading']
kmeans.fit(X)
#clusters = kmeans.fit_predict(data)
print(kmeans.cluster_centers_.shape)

【问题讨论】:

  • 您要使用的函数需要一个二维数组,例如[[1, 2], [2, 3]],而您提供了一个一维数组。
  • 该消息带有一些非常明确的建议;你试过了吗?它到底发生在哪里?请使用完整的错误跟踪编辑和更新您的问题。
  • 只有版主可以删除cmets,但用户可以在不合适的时候举报。此处未标记任何内容,但如果您留下 this 之类的内容,可能会被其他人标记为不友好/不友善(或者可能更糟 - 我没有看到它,所以我不知道您写了什么)

标签: python scikit-learn k-means


【解决方案1】:

我进行了更多挖掘,发现将我的数据帧转换为 numpy 数组,然后使用 python 负索引解决了我的问题

更新代码:

import numpy as np
import pandas as pd
from sklearn.cluster import KMeans

# CHANGES
data = pd.read_csv(r"myfilepath.csv").to_numpy()

print(data.shape)

kmeans = KMeans(n_clusters = 2, random_state = 0)

#CHANGES
X = data[:-1]

kmeans.fit(X)
#clusters = kmeans.fit_predict(data)
print(kmeans.cluster_centers_.shape)

plt.scatter(X[:, 0], X[:, 1], s=50, cmap='viridis')
centers = kmeans.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], s=200, alpha=0.5)

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 2021-12-28
    • 2018-09-16
    • 1970-01-01
    • 2020-12-18
    • 2021-12-29
    • 2020-11-02
    • 2018-12-11
    相关资源
    最近更新 更多