0

I started learning Sklearn today and wanted to set up a simple regression model using one X value, then use that model to predict the next 5 Y values.

I keep getting the following error:

ValueError: Expected 2D array, got 1D array instead:
array=[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20].
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.

This is all of the code I currently have:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn import datasets
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score

histYlist = [65.98685126, 56.78302597, 94.79205606, 20.70468985, 90.25959717, 60.6194846, 27.08425346, 15.8715957, 69.41508813, 7.362478092, 82.45058027, 53.44812953, 32.52252966, 43.1278569, 91.2854072, 99.80998002, 89.02868447, 45.31115274, 98.65222136, 70.56292757]
histY = np.array(histYlist)
histY.reshape(-1,1)
histXlist = list()
i = 1
for items in histY :
    histXlist.append(i)
    i = i + 1

histX = np.array(histXlist)
histX.reshape(-1,1)
print(histX.shape, histY.shape)
#print(histX)
#rint(len(histX))

model = linear_model.LinearRegression()

model.fit(histX,histY)

X_pred = list()
newPredicts = 5
j = 1
while j <= newPredicts :
    X_pred.append(len(histX) + j)
    j = j + 1
#print(predictX)

Y_pred = model.predict(X_pred)
print(Y_pred)

Hopefully you can help or lead me in the right direction thanks!

2
  • 1
    I believe you have to reshape X_pred too, just like you did for histX and histY. Commented Aug 8, 2020 at 19:30
  • @MarioIshac from what I can gather the: "model.fit(histX,histY)" line is causing a traceback Commented Aug 8, 2020 at 19:35

1 Answer 1

1

The np.array.reshape() method only returns the reshaped array without updating its object. If you want to use the reshaped object you should store in a new variable or update the original variable. I tried the former with your code and it now works.

So instead of:

histX.reshape(-1,1)

You should do:

histX = histX.reshape(-1,1)

And the same for the variables histY and X_pred.

For the documentation, see: numpy.reshape, where it states

numpy.reshape(a, newshape, order='C')[source]

Gives a new shape to an array without changing its data.

Sign up to request clarification or add additional context in comments.

2 Comments

Jesus, I'm an idiot. Sometimes it's nice to have another pair of eyes look over your code.
(Almost) nothing that the documentation can't solve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.