【问题标题】:ValueError: Found input variables with inconsistent numbers of samples: [100, 300]ValueError:发现样本数量不一致的输入变量:[100, 300]
【发布时间】:2020-06-07 06:24:37
【问题描述】:

我正在向 udemy 学习 KNN。 数据集从here下载。

当我尝试运行以下代码时:

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)

我得到的错误是:

Traceback(最近一次调用最后一次): 文件“/home/ashutosh/Machine Learning A-Z Template Folder/Part 3 - Classification/Section 15 - K-Nearest Neighbors (K-NN)/knn(1).py”,第 24 行,在 cm = 混淆矩阵(y_test, y_pred)

文件“/home/ashutosh/.local/lib/python3.7/site-packages/sklearn/metrics/_classification.py”,第 268 行,位于混淆矩阵中 y_type, y_true, y_pred = _check_targets(y_true, y_pred)

文件“/home/ashutosh/.local/lib/python3.7/site-packages/sklearn/metrics/_classification.py”,第 80 行,在 _check_targets check_consistent_length(y_true, y_pred)

文件“/home/ashutosh/.local/lib/python3.7/site-packages/sklearn/utils/validation.py”,第 212 行,在 check_consistent_length " samples: %r" % [int(l) for l in lengths])

ValueError: 发现样本数不一致的输入变量:[100, 300]

【问题讨论】:

    标签: python pandas numpy machine-learning scikit-learn


    【解决方案1】:

    换行:

    y_pred = classifier.predict(x_train)
    

    到:

    y_pred = classifier.predict(x_test)
    

    你可以走了。

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2021-06-20
      • 2018-06-25
      • 2018-12-04
      • 2021-05-31
      • 2020-08-19
      • 2021-09-12
      • 2021-08-06
      • 2022-01-16
      相关资源
      最近更新 更多