首页 > 解决方案 > 收到一个奇怪的错误,上面写着“使用 array.reshape(-1, 1) 重塑你的数据”

问题描述

我正在测试这段代码。

# Import the necessary packages
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Normalizer
from sklearn.cluster import KMeans
# Define a normalizer
normalizer = Normalizer()
# Create Kmeans model
kmeans = KMeans(n_clusters = 10,max_iter = 1000)
# Make a pipeline chaining normalizer and kmeans
pipeline = make_pipeline(normalizer,kmeans)
# Fit pipeline to daily stock movements
pipeline.fit(score)
labels = pipeline.predict(score)

此行会引发错误:

pipeline.fit(score)

这是我看到的错误:

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.

我不知道这个错误是什么意思。我用谷歌搜索并没有发现任何有用的东西。这是我的数据的一个小样本:

array=[1. 1. 1. ... 8. 1. 1.].

我正在按照下面链接中的示例进行操作。

https://medium.com/datadriveninvestor/stock-market-clustering-with-k-means-clustering-in-python-4bf6bd5bd685

当我从链接运行代码时,一切正常。我不确定为什么在我自己的数据上运行代码时它会掉下来,这只是:

1, 1.9, 2.62, 3.5, 4.1, 7.7, 9.75, etc, etc.  

它从1-10开始。就是这样。

标签: pythonpython-3.xscikit-learnk-means

解决方案


Anysklearn.Transformer期望一个[sample size, n_features]大小的数组。所以有两种情况你将不得不重塑你的数据,

  • 如果您只有一个样本,则需要将其重塑为 [1, n_features] 大小的数组
  • 如果您只有一个特征,则需要将其重塑为 [sample size, 1] 大小的数组

所以你需要做适合问题的事情。您正在传递一维向量。

[1. 1. 1. ... 8. 1. 1.]

如果这是单个样本,请将其重塑为 (1, -1) 大小的数组,你会没事的。但话虽如此,您可能需要考虑以下问题。

  • 如果这是单个样本,那么用单个样本拟合模型是没有意义的。你不会得到任何好处。
  • 如果这是一组具有单一特征的样本,我真的看不出在这样的数据集上执行 K-means 有什么好处。

推荐阅读