Search code examples
pythonpython-3.xmachine-learningscikit-learnlinear-regression

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


While I am predicting the one sample from my data, it gives reshape error but my model has equal number of rows. Here is my code:

import pandas as pd
from sklearn.linear_model import LinearRegression
import numpy as np
x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])

lr = LinearRegression()
lr.fit(x,y)

print(lr.predict(2.4))

The error is

if it contains a single sample.".format(array))
ValueError: Expected 2D array, got scalar array instead:
array=2.4.
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.

Solution

  • You should reshape your X to be a 2D array not 1D array. Fitting a model requires requires a 2D array. i.e (n_samples, n_features)

    x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
    y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])
    
    lr = LinearRegression()
    lr.fit(x.reshape(-1, 1), y)
    
    print(lr.predict([[2.4]]))