Search code examples
pythonscikit-learnlinear-regressionsklearn-pandas

Sklearn Fit Linear Regression


I have this problem:

  regression.fit(X_train, y_train)

I got the following error:

ValueError: Expected 2D array, got 1D array instead:
array=[ 2.9  5.1  3.2  4.5  8.2  6.8  1.3 10.5  3.   2.2  5.9  6.   3.7  3.2
  9.   2.   1.1  7.1  4.9  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 haven't shared your source code but here's my 2 cents:

    If you have a hardcoded array, instead of 1D array:

    array=[ 2.9, 5.1, 3.2, 4.5, 8.2, 6.8, 1.3, 10.5, 3., 2.2, 5.9, 6., 3.7, 3.2, 9., 2., 1.1, 7.1, 4.9, 4.]
    

    use a 2D array:

    array=[[ 2.9, 5.1, 3.2, 4.5, 8.2, 6.8, 1.3, 10.5, 3., 2.2, 5.9, 6., 3.7, 3.2, 9., 2., 1.1, 7.1, 4.9, 4.]]
    

    If you want to convert a 1D array to 2D array then simply use numpy's reshape function. For example,

    >>> test_array = np.array([1, 2, 3, 4, 5])
    >>> test_array
    array([1, 2, 3, 4, 5])
    >>> test_array = test_array.reshape(1, -1)
    >>> test_array
    array([[1, 2, 3, 4, 5]])