Bimo Wicaksana
Bimo Wicaksana

Reputation: 21

How to fix “ValueError: Expected 2D array, got 1D array instead” in sklearn/python?

i got this eror messsages on jupytet notebook python


ValueError                                Traceback (most recent call last)
<ipython-input-47-24ba7430f88f> in <module>
----> 1 y_pred = nbtrain.predict(x_test)
      2 y_pred

~\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=[3 3 3 2]. 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 my code :

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, x_test = train_test_split(x,y, test_size = 0.34, random_state=123)

modelnb=GaussianNB()

nbtrain=modelnb.fit(x_train,y_train)

y_pred = nbtrain.predict(x_test)
y_pred

Upvotes: 0

Views: 5627

Answers (1)

Aditya Bhattacharya
Aditya Bhattacharya

Reputation: 41

Check your x_test. If it has only 1 sample, then use

x_test.reshape(1, -1)

just before you call predict().

If however, your code has only 1 feature, then use

x_test.reshape(-1, 1)

again, just before you call predict().

Upvotes: 2

Related Questions