简体   繁体   中英

ValueError: Found input variables with inconsistent numbers of samples: [100, 300]

I was learning KNN from udemy. The dataset is downloaded from here .

When I try to run the following code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

dataset = pd.read_csv('Social_Network_Ads.csv')
x = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4:].values

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.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2)
classifier.fit(x_train, y_train.ravel())

y_pred = classifier.predict(x_train)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

I got error as:

Traceback (most recent call last): File "/home/ashutosh/Machine Learning AZ Template Folder/Part 3 - Classification/Section 15 - K-Nearest Neighbors (K-NN)/knn(1).py", line 24, in cm = confusion_matrix(y_test, y_pred)

File "/home/ashutosh/.local/lib/python3.7/site-packages/sklearn/metrics/_classification.py", line 268, in confusion_matrix y_type, y_true, y_pred = _check_targets(y_true, y_pred)

File "/home/ashutosh/.local/lib/python3.7/site-packages/sklearn/metrics/_classification.py", line 80, in _check_targets check_consistent_length(y_true, y_pred)

File "/home/ashutosh/.local/lib/python3.7/site-packages/sklearn/utils/validation.py", line 212, in check_consistent_length " samples: %r" % [int(l) for l in lengths])

ValueError: Found input variables with inconsistent numbers of samples: [100, 300]

Change line:

y_pred = classifier.predict(x_train)

to:

y_pred = classifier.predict(x_test)

and you're fine to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM