Error in Python script “Expected 2D array, got 1D array instead:”?

后端 未结 9 708
执念已碎
执念已碎 2020-11-30 01:29

I\'m following this tutorial to make this ML prediction:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style

style.use(\"ggplot\         


        
相关标签:
9条回答
  • 2020-11-30 01:57

    The X and Y matrix of Independent Variable and Dependent Variable respectively to DataFrame from int64 Type so that it gets converted from 1D array to 2D array.. i.e X=pd.DataFrame(X) and Y=pd.dataFrame(Y) where pd is of pandas class in python. and thus feature scaling in-turn doesn't lead to any error!

    0 讨论(0)
  • 2020-11-30 02:01

    With one feature my Dataframe list converts to a Series. I had to convert it back to a Dataframe list and it worked.

    if type(X) is Series:
        X = X.to_frame()
    
    0 讨论(0)
  • 2020-11-30 02:02

    You are just supposed to provide the predict method with the same 2D array, but with one value that you want to process (or more). In short, you can just replace

    [0.58,0.76]
    

    With

    [[0.58,0.76]]
    

    And it should work.

    EDIT: This answer became popular so I thought I'd add a little more explanation about ML. The short version: we can only use predict on data that is of the same dimensionality as the training data (X) was.

    In the example in question, we give the computer a bunch of rows in X (with 2 values each) and we show it the correct responses in y. When we want to predict using new values, our program expects the same - a bunch of rows. Even if we want to do it to just one row (with two values), that row has to be part of another array.

    0 讨论(0)
  • 2020-11-30 02:05

    I faced the same problem. You just have to make it an array and moreover you have to put double squared brackets to make it a single element of the 2D array as first bracket initializes the array and the second makes it an element of that array.

    So simply replace the last statement by:

    print(clf.predict(np.array[[0.58,0.76]]))
    
    0 讨论(0)
  • 2020-11-30 02:06

    I faced the same issue except that the data type of the instance I wanted to predict was a panda.Series object.

    Well I just needed to predict one input instance. I took it from a slice of my data.

    df = pd.DataFrame(list(BiogasPlant.objects.all()))
    test = df.iloc[-1:]       # sliced it here
    

    In this case, you'll need to convert it into a 1-D array and then reshape it.

     test2d = test.values.reshape(1,-1)
    

    From the docs, values will convert Series into a numpy array.

    0 讨论(0)
  • 2020-11-30 02:11

    I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

    The API used to allow scalar value but now you need to give a 2D array.

    0 讨论(0)
提交回复
热议问题