python - 为什么 cross_val_scores 运行良好但 cv.splits 显示错误?

标签 python machine-learning scikit-learn

我尝试了cross_val_score。它没有显示错误。

但是如果我尝试使用cv.split它会显示错误

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import TimeSeriesSplit

cv = TimeSeriesSplit(n_splits = 5)

clf = RandomForestClassifier(n_estimators=500, max_depth = 10, random_state=100, n_jobs = -1)
for train, val in cv.split(X, y):
    clf.fit(X.iloc[train], y[train])
FutureWarning: 
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.

See the documentation here:
https://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
  return self.loc[key]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-143-9c8fe6b057e9> in <module>
      1 for train, val in cv.split(X, y):
----> 2     clf.fit(X.iloc[train], y[train])

~\Anaconda3\lib\site-packages\sklearn\ensemble\forest.py in fit(self, X, y, sample_weight)
    248         # Validate or convert input data
    249         X = check_array(X, accept_sparse="csc", dtype=DTYPE)
--> 250         y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None)
    251         if sample_weight is not None:
    252             sample_weight = check_array(sample_weight, ensure_2d=False)

~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    540         if force_all_finite:
    541             _assert_all_finite(array,
--> 542                                allow_nan=force_all_finite == 'allow-nan')
    543 
    544     if ensure_min_samples > 0:

~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in _assert_all_finite(X, allow_nan)
     58     elif X.dtype == np.dtype('object') and not allow_nan:
     59         if _object_dtype_isnan(X).any():
---> 60             raise ValueError("Input contains NaN")
     61 
     62 

ValueError: Input contains NaN

我通过 np.sum(X.isnull()) 检查 NaN,但数据没有 NaN

但它在下面运行良好!

for train, val in cv.split(X.iloc[:200000, ], y[:200000]):
    clf.fit(X.iloc[train, ], y[train])

我更改了索引,但它之前显示了相同的错误。

for train, val in cv.split(X.iloc[:400000, ], y[:400000]):
    clf.fit(X.iloc[train, ], y[train])
FutureWarning: 
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
.
.
.
ValueError: Input contains NaN

我又更改了一次索引,效果很好!

for train, val in cv.split(X.iloc[200000:400000, ], y[200000:400000]):
    clf.fit(X.iloc[train, ], y[train])

我能做什么?

最佳答案

简短回答:在第 200 000 行和 400 000 行之间的 y 中可能存在 NaN,并且可能不太接近 400k。

长答案: 您应该检查 np.sum(y.isnull()) 而不是 np.sum(X.isnull()), 因为回溯表明 y 中存在 NaN。那里会有 NaN。

显示的交叉验证检查并不能保证y一切正常, 因为似乎对最后一个函数的作用有误解:cv.split() 返回您提供给它的数组的索引。在两者中

  • cv.split(X.iloc[:200000, ], y[:200000])
  • cv.split(X.iloc[200000:400000, ], y[200000:400000])

数组具有相同的行数,因此返回相同的索引。当你这样做时

for train, val in cv.split(X.iloc[200000:400000, ], y[200000:400000]):
    clf.fit(X.iloc[train, ], y[train])

您实际上访问了 X 中的第 0-200000 行。要访问第 200000-400000 行,您可以这样做

for train, val in cv.split(X.iloc[200000:400000, ], y[200000:400000]):
    clf.fit(X.iloc[200000:400000, ][train, ], y[200000:400000][train])

我怀疑,如果你这样做,错误将会再次出现。顺便说一句,TimeSeriesSplit 并不使用所有数据进行训练,请参阅 here 。由于您只显示拟合分类器,但没有预测,因此当 NaN 非常接近 y 向量的末尾时,不会出现错误。时间序列中的最后观察结果仅用于测试,绝不用于训练。

关于python - 为什么 cross_val_scores 运行良好但 cv.splits 显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57651302/

相关文章:

python - 在没有集合的情况下减去两个范围之间的重叠

python - 读取 csv 时删除 pandas 中的索引列

python - 以 f1 为评分函数的网格搜索,几页错误信息

python - Classifier.fit for oneclassSVM 提示 float 类型。 TypeError float 是必需的

python - 将预测结果合并到原始数据帧?

python - 如何使用 PyPDF2 旋转页面?

python - 解析具有未知列数的 Pandas 数据框以在 statsmodels.api 中使用

numpy - 为什么 Keras 中的 to_categorical() 使用 float64 而不是 float32?

python - 将自定义标签添加到 pytorch 数据加载器/数据集不适用于自定义数据集

python - 如何使用pickle保存聊天机器人模型