Moinak Dey
Moinak Dey

Reputation: 83

ValueError: Number of labels=25 does not match number of samples=56

I am getting this in

C:/Users/HP/.PyCharmCE2019.1/config/scratches/scratch.py Traceback (most recent call last):
File "C:/Users/HP/.PyCharmCE2019.1/config/scratches/scratch.py", line 25, in dtree.fit(x_train,y_train)
File "C:\Users\HP\PycharmProjects\untitled\venv\lib\site-packages\sklearn\tree\tree.py", line 801, in fit X_idx_sorted=X_idx_sorted)
File "C:\Users\HP\PycharmProjects\untitled\venv\lib\site-packages\sklearn\tree\tree.py", line 236, in fit "number of samples=%d" % (len(y), n_samples))
ValueError: Number of labels=45 does not match number of samples=36

I am using DecisionTree model but I am getting error. Help will be appreciated.

#importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

#reading the dataset
df=pd.read_csv(r'C:\csv\kyphosis.csv')
print(df)
print(df.head())

#visualising the dataset
print(sns.pairplot(df,hue='Kyphosis',palette='Set1'))
plt.show()

#training and testing
from sklearn.modelselection import traintestsplit 
c=df.drop('Kyphosis',axis=1) d=df['Kyphosis'] 
xtrain,ytrain,xtest,ytest=traintestsplit(c,d,testsize=0.30)

#Decision_Tree
from sklearn.tree import DecisionTreeClassifier
dtree=DecisionTreeClassifier()
dtree.fit(xtrain,ytrain)

#Predictions
predictions=dtree.predict(xtest) from sklearn.metrics import 
classificationreport,confusionmatrix 
print(classificationreport(ytest,predictions)) 
print(confusionmatrix(y_test,predictions))

Expected result should be my classification_report and confusion_matrix

Upvotes: 2

Views: 1939

Answers (1)

warped
warped

Reputation: 9481

So, the error is thrown by the function dtree.fit(xtrain, ytrain), because xtrain and ytrain have unequal length.

Checking the part of code that generates it:

xtrain,ytrain,xtest,ytest=traintestsplit(c,d,testsize=0.30)

and comparing to the example in the documentation

import numpy as np
from sklearn.model_selection import train_test_split
[...]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

you can see two things:

1 traintestsplit should be train_test_split

2 by changing the order of variables left of the =, you assign different data to these variables.

so, your code should be:

 xtrain, xtest, ytrain, ytest = train_test_split(c,d,testsize=0.30)

Upvotes: 3

Related Questions