首页 > 解决方案 > 从数据帧创建 DataLoaders 时出现 FASTAI 错误

问题描述

我试图建立一个预测器来告诉我一条推文是否在谈论自然灾害。

使用 Kaggle 数据集。

我有:

    text               target
15  What's up man?      0
16  I love fruits       0
17  Summer is lovely    0
18  My car is so fast   0

名单还在继续。。

我得到了目标,这个数量的出现

0 4342

1 3271

名称:目标,数据类型:int64

这是我的数据块

dls_lm = DataBlock(
blocks=(TextBlock.from_df('text', seq_len=15, is_lm=True), CategoryBlock),
get_x=ColReader('text'), get_y=ColReader('target'), splitter=ColSplitter())

这是我的数据加载器

dls = dls_lm.dataloaders(df2, bs=24)

这是我遇到的错误

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2897             try:
-> 2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'is_valid'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
5 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:
-> 2900                 raise KeyError(key) from err
   2901 
   2902         if tolerance is not None:

KeyError: 'is_valid'

如果有人知道我可以如何解决它真的会帮助我。谢谢!

标签: pythondataframemachine-learningdeep-learningfast-ai

解决方案


这个错误的原因是参数splitter=ColSplitter()

TL;TR

用类似的东西替换它splitter=RandomSplitter(valid_pct=0.1, seed=42)

详细解答

ColSplitter 的签名是

def ColSplitter(col='is_valid'):
    "Split `items` (supposed to be a dataframe) by value in `col`"

这意味着什么?好吧,FastAI 将您的输入数据拆分为一个训练集和一个验证集,以评估您的训练模型在每次迭代中的性能。

ColSplitter 期望您的输入 DataFrame 有一个列,该列is_valid指定哪些项目(行)应该在验证集中。

由于您没有is_valid在输入数据中调用列,因此您应该将 ColSplitter 替换为不同的数据拆分策略,例如随机拆分:

splitter=RandomSplitter(valid_pct=0.1, seed=42)

推荐阅读