0
$\begingroup$
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('iris.csv')
X = dataset.iloc[:,:4]
y = dataset.iloc[:,4]


from sklearn.preprocessing import OneHotEncoder

encoder = OneHotEncoder(sparse=False)
y=encoder.fit_transform(y.values.reshape(-1,1))

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)


from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

I am getting these small errors which hinder my projects. Can you please provide a solution to this error? Also how can I avoid these mistakes?

$\endgroup$

1 Answer 1

0
$\begingroup$

You are getting error because of below-

y=encoder.fit_transform(y.values.reshape(-1,1))

This is changing the shape of the y. try print(y.shape)

You might want to handle you data once its labels and transformed. I am not sure if you are trying to "learn" to apply OneHotEncoding. If yes, you might wanna look at the documentation in detail. here-https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

Let me know if you have tried it and still have problem.

$\endgroup$
5
  • $\begingroup$ y=encoder.fit_transform(y.values.reshape(-1,1)) was to encode the names (this is iris dataset). Before that on using y.shape I was getting too many indexers error $\endgroup$ May 9, 2020 at 17:25
  • $\begingroup$ did you try and print the shape of y after transforming? After that compare it to the shape FIT method expects . $\endgroup$ May 9, 2020 at 17:45
  • $\begingroup$ Firstly, thankyou for looking into the problem. Also I tried the print(y.shape) just after fit_transform method. But still the same error is coming. output of print(y.shape) is coming (149,3) $\endgroup$ May 9, 2020 at 18:01
  • $\begingroup$ okay... so initially i thought it was because of the mismatch shape. but turned out GaussianNB FIT method expects numerical type not the OneEncoded. either you use different transformation or doesn't encode it.this has the detailed answer already here-stackoverflow.com/questions/61302916/…. scikit-learn.org/stable/modules/generated/… $\endgroup$ May 9, 2020 at 18:21
  • $\begingroup$ And there is also the explanation why so -stackoverflow.com/questions/40578619/… $\endgroup$ May 9, 2020 at 18:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.