【问题标题】:Cross validation inconsistent numbers of samples error (Python)交叉验证不一致的样本数错误(Python)
【发布时间】:2020-12-05 16:41:03
【问题描述】:

我正在尝试使用交叉验证方法和 SVM 分类器进行分类。在我的数据文件中,最后一列包含我的类(分别是 0、1、2、3、4、5),其余的(第一列除外)是我想用来预测这些类的数字数据。

from sklearn import svm
from sklearn import metrics
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score


filename = "Features.csv"
dataset = np.loadtxt(filename, delimiter=',', skiprows=1, usecols=range(1, 39))

x = dataset[:, 0:36]
y = dataset[:, 36]
print("len(x): " + str(len(x)))
print("len(y): " + str(len(x)))

skf = StratifiedKFold(n_splits=10, shuffle=False, random_state=42)

modelsvm = svm.SVC()

expected = y
print("len(expected): " + str(len(expected)))

predictedsvm = cross_val_score(modelsvm, x, y, cv=skf)
print("len(predictedsvm): " + str(len(predictedsvm)))

svm_results = metrics.classification_report(expected, predictedsvm)

print(svm_results)

我收到这样的错误:

len(x): 2069
len(y): 2069
len(expected): 2069
C:\Python\Python37\lib\site-packages\sklearn\model_selection\_split.py:297: FutureWarning: Setting a random_state has no effect since shuffle is False. This will raise an error in 0.24. You should leave random_state to its default (None), or set shuffle=True.
  FutureWarning
len(predictedsvm): 10
Traceback (most recent call last):
  File "C:/Users/MyComp/PycharmProjects/GG/AR.py", line 54, in <module>
    svm_results = metrics.classification_report(expected, predictedsvm)
  File "C:\Python\Python37\lib\site-packages\sklearn\utils\validation.py", line 73, in inner_f
    return f(**kwargs)
  File "C:\Python\Python37\lib\site-packages\sklearn\metrics\_classification.py", line 1929, in classification_report
    y_type, y_true, y_pred = _check_targets(y_true, y_pred)
  File "C:\Python\Python37\lib\site-packages\sklearn\metrics\_classification.py", line 81, in _check_targets
    check_consistent_length(y_true, y_pred)
  File "C:\Python\Python37\lib\site-packages\sklearn\utils\validation.py", line 257, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of samples: [2069, 10]

Process finished with exit code 1

当我尝试使用 CV 进行预测时,我不明白 y 中的数据计数如何下降到 10。

谁能帮我解决这个问题?

【问题讨论】:

    标签: python numpy scikit-learn


    【解决方案1】:

    您误解了cross_val_score 的输出。根据documentation,它返回“交叉验证每次运行的估计器分数数组”,而不是实际预测。因为你有 10 个折叠,所以你得到 10 个值。

    classification_report 期望真实值和预测值。要使用它,您需要使用模型进行预测。为此,您需要根据数据拟合模型。如果您对 cross_val_score 的结果感到满意,您可以根据数据训练该模型。或者,您可以使用GridSearchCV 一次性完成所有操作。

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2013-02-21
      • 1970-01-01
      • 2015-07-06
      • 2021-07-10
      • 2018-12-01
      • 2016-03-11
      • 2020-11-29
      • 2017-05-07
      相关资源
      最近更新 更多