如何将列表重塑为数组?

时间:2019-07-03 18:48:34

标签: python scikit-learn

How to declare an array in Python?

您好,我一直在尝试为我的预测算法设置列表格式。但是,当我尝试预测时会出现错误:

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.

因此,当我尝试使用.reshape(1,-1)调整数组的形状时[错误告诉我],我得到'list'对象没有属性'reshape'。但是,根据这篇文章,我的列表是一个数组,应该可以做到这一点。

此外,我尝试使用numpy将其强制为数组(或转置它),但出现错误:ValueError: setting an array element with a sequence.

我的代码是这样的:

for i in range(len(best.indi)):
    data.append(best.features[best.indi[i]])
for i in data:
  try:
    value = i[-1:]
    prediction_data.append(value[0])
  except:
    prediction_data.append(i)

from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split as tts
import numpy as np

knn = KNeighborsClassifier(n_neighbors=best.neighbors)

knn.fit(np.transpose(data), best.y)

prediction = knn.predict(np.transpose(prediction_data))


print(prediction)

尝试捕获将遍历数据(由1个列出的列表和数字组成的组合),并创建一个仅包含数字的列表。

https://repl.it/@JacksonEnnis/KNN-Final

那么,重申一下,如何将数据重塑为scikit可以识别的预测格式?

1 个答案:

答案 0 :(得分:1)

在显示的示例中,您将数据追加到列表中。要使用reshape,您必须将它们转换为numpy数组。调用reshape之前,请确保已检查变量的类型。

import numpy as np

data = []
for i in range(10):
    data.append(i)

print(type(data))

输出:<class 'list'>

data = np.array(data) # Convert the list to numpy array
print(type(data))

输出:<class 'numpy.ndarray'>

现在您可以根据需要重塑了。

print(data.reshape(1,-1))

输出:[[0 1 2 3 4 5 6 7 8 9]]