Reputation: 1246
I am studying machine learning and in the video course lecturer shows how to predict 1 value by predict function from sklearn. He just executes it with a float parameter and it works fine. But when I try to do the same I receive a ValueError:
>linear_regressor.predict(6.5)
ValueError: Expected 2D array, got scalar array instead:
array=6.5.
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.
I tried to reshape it but I get the same error:
lvl_of_interest = np.array([6.5])
np.reshape(lvl_of_interest,(1,-1))
linear_regressor.predict(6.5)
Please tell me maybe there are some changes in the library from version to version (the course is few years old). And how is it possible to get the one feature for one sample?
Upvotes: 0
Views: 556
Reputation: 220
There are two issues :
You reshape your array but call predict with the same float (instead of the reshaped array, ie linear_regressor.predict(6.5)
instead of linear_regressor.predict(lvl_of_interest)
)
Furthermore, np.reshape should be reassigned :
lvl_of_interest = np.array([6.5])
lvl_of_interest = np.reshape(lvl_of_interest,(1,-1))
linear_regressor.predict(lvl_of_interest)
or in 1 line : linear_regressor.predict(np.array([6.5]).reshape(1,-1))
(nb : if you inspect shapes, you transform a (1,) array into a (1,1))
Upvotes: 2
Reputation: 5741
LinearRegression().predict()
expects as 2-dimensional feature array for X
.
You can make your array 2-dimensional with .reshape(1, -1)
like the error message suggests or just make it 2-dimensional from the start:
linear_regressor.predict(np.array([[6.5]]))
Upvotes: 0