0

How to declare an array in Python?

Hello, I have been trying to format a list for my predictive algorithm. However, when I try to predict I get the error:

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.

So, when I try to reshape the array using .reshape(1,-1) [As told to me by the error] I get that the 'list' object has no attribute 'reshape'. However, according to this post, my list IS an array, and should be able to do this.

Furthermore, I have tried using numpy to force it to be an array (or transpose it) I got the error: ValueError: setting an array element with a sequence.

My code is such:

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)

The try catch is going through the data (which is a combo of 1 itemed lists and numbers) and creating a list that is only a collection of numbers.

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

So, to reiterate, how do you reshape the data to a format that scikit will recognize for predictions?

Jackson Ennis
  • 315
  • 2
  • 10

1 Answers1

1

In the example you showed you are appending the data to a list. To use reshape you have to convert them to an numpy array. Make sure that you check the type of your variable before calling reshape.

import numpy as np

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

print(type(data))

Output: <class 'list'>

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

Output: <class 'numpy.ndarray'>

Now you can reshape as you like.

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

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

klaus
  • 1,187
  • 2
  • 9
  • 19