Search code examples
pythonmachine-learningscikit-learngaussiannaivebayes

Getting "ValueError: Expected 2D array, got 1D array instead" error in python-sklearn


Please help me. I am unable to resolve one error that I am getting. I am new to machine learning in python. Would be grateful for any advice on this.

Below is my code, that I wrote to predict the type of transportation an employee of a company may prefer based on their Gender, academic qualification and license:

Gender = preprocessing.LabelEncoder().fit_transform(df.loc[:,'Gender'])
Engineer = preprocessing.LabelEncoder().fit_transform(df.loc[:,'Engineer'])
MBA = preprocessing.LabelEncoder().fit_transform(df.loc[:,'MBA'])
License = preprocessing.LabelEncoder().fit_transform(df.loc[:,'license'])
Transport = preprocessing.LabelEncoder().fit_transform(df.loc[:,'Transport'])
x,y = Gender.reshape(-1,1), Transport
print("\n\nGender:", Gender, "\n\nEngineer:", Engineer, "\n\nMBA:", MBA, "\n\nLicense:", license, "\n\nTransport:", Transport)
model = GaussianNB().fit(x,y)
a1 = input("\n\n Choose Gender : Male:1 or Female:0 = ")
b1 = input("\n\n Are you an Engineer? : Yes:1 or No:0 = ")
c1 = input("\n\n Have you done MBA? : Yes:1 or No:0 = ")
d1 = input("\n\n Do you have license? : Yes:1 or No:0 = ")

#store the output in y_pred

y_pred = model = model.predict([int(a1),int(b1),int(c1),int(d1)])

#for loop to predict customizable output
if y_pred == [1]:
    print("\n\n You prefer Public Transport")
else:
    print("\n\n You prefer Private Transport")

And here is the error I am getting at the final stage:

ValueError                                Traceback (most recent call last)
<ipython-input-104-a14f86182731> in <module>
      6 #store the output in y_pred
      7 
----> 8 y_pred = model = model.predict([int(a1),int(b1),int(c1),int(d1)])
      9 
     10 #for loop to predict customizable output

~\Anaconda3\lib\site-packages\sklearn\naive_bayes.py in predict(self, X)
     63             Predicted target values for X
     64         """
---> 65         jll = self._joint_log_likelihood(X)
     66         return self.classes_[np.argmax(jll, axis=1)]
     67 

~\Anaconda3\lib\site-packages\sklearn\naive_bayes.py in _joint_log_likelihood(self, X)
    428         check_is_fitted(self, "classes_")
    429 
--> 430         X = check_array(X)
    431         joint_log_likelihood = []
    432         for i in range(np.size(self.classes_)):

~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    519                     "Reshape your data either using array.reshape(-1, 1) if "
    520                     "your data has a single feature or array.reshape(1, -1) "
--> 521                     "if it contains a single sample.".format(array))
    522 
    523         # in the future np.flexible dtypes will be handled like object dtypes

ValueError: Expected 2D array, got 1D array instead:
array=[1 1 0 1].
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.

Below is the structure of my datasets:

<class 'pandas.core.frame.DataFrame'>
    Int64Index: 444 entries, 28 to 39
    Data columns (total 8 columns):
    Gender       444 non-null object
    Engineer     444 non-null int64
    MBA          444 non-null int64
    Work Exp     444 non-null int64
    Salary       444 non-null float64
    Distance     444 non-null float64
    license      444 non-null int64
    Transport    444 non-null object
    dtypes: float64(2), int64(4), object(2)
    memory usage: 31.2+ KB

Solution

  • The error message is quite verbose and tells you that you provided a 1D array where a 2D array was expected:

    Expected 2D array, got 1D array instead

    The stack trace is pointing to this line:

    y_pred = model = model.predict([int(a1),int(b1),int(c1),int(d1)])
    

    It also tells you how to resolve this problem:

    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.

    Since you are trying to predict a single sample, you should use the latter:

    import numpy as np
    
    
    y_pred = model.predict(np.array([int(a1),int(b1),int(c1),int(d1)]).reshape(1, -1))
    

    Note that I removed the double assignment y_pred = model = ... which was not useful.


    Additional note

    Not related to this particular error but probably not what you want: you are fitting your model on the gender feature only. See these lines:

    x,y = Gender.reshape(-1,1), Transport
    ...
    model = GaussianNB().fit(x,y)
    

    This will break your code as you are fitting the model on a single feature and then want to predict a sample with four features. You should fix this as well. A solution could look like this:

    X = OrdinalEncoder().fit_transform(df.loc[:,['Gender', 'Engineer', 'MBA', 'license']])
    y = LabelEncoder().fit_transform(df.loc[:,'Transport'])
    
    model = GaussianNB()
    model.fit(X, y)
    

    See that I used OrdinalEncoder for the features since LabelEncoder is intended to only encode the target y (compare with the documentation).