鱼C论坛

 找回密码
 立即注册
查看: 354|回复: 3

预处理dataset产生的问题

[复制链接]
发表于 2024-11-3 12:17:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. def prepare_input(cfg, text):
  2.     inputs = cfg.tokenizer.encode_plus(
  3.         text,
  4.         return_tensors=None,
  5.         add_special_tokens=True,#自动在每个文本前后添加特殊标记(如CLS和SEP)
  6.         return_attention_mask=True # 计算注意力(attention)时忽略那些paddle值
  7.     )
  8.    
  9.     if len(inputs['input_ids']) > CFG.max_len:#句子长度大于max_length时截断
  10.         inputs['input_ids'] = inputs['input_ids'][:CFG.max_len]
  11.         inputs['attention_mask'] = inputs['attention_mask'][:CFG.max_len]
  12.         inputs['token_type_ids'] = inputs['token_type_ids'][:CFG.max_len]

  13.     for k, v in inputs.items():
  14.         inputs[k] = torch.tensor(v, dtype=torch.long)
  15.     return inputs


  16. class LLMDataset(Dataset):
  17.     def __init__(self, cfg, df,is_grad):
  18.         self.cfg = cfg
  19.         self.df = df
  20.         self.texts = df["cleaned"].values
  21.         self.is_grad = is_grad

  22.     def __len__(self):
  23.         return len(self.texts)

  24.     def __getitem__(self,idx,item):
  25.         inputs = prepare_input(self.cfg, self.texts[item])
  26.         
  27.         
  28.         if self.is_grad:#训练集
  29.             labels = self.df.loc[idx]['label']
  30.             # [batch,1,max_len(84)] -> [batch,max_len]#使用squeeze降维
  31.             return {'input_ids':inputs['input_ids'].squeeze(),
  32.                     'attention_mask':inputs['attention_mask'].squeeze(),
  33.                     'token_type_ids':inputs['token_type_ids'].squeeze(),
  34.                    # Our loss_fn wants it to be a "float" type
  35.                     'labels':torch.tensor(labels,dtype=torch.float).unsqueeze(dim=0)}
  36.         else:#测试集
  37.             # [batch,1,max_len(84)] -> [batch,max_len]
  38.             return {'input_ids':inputs['input_ids'].squeeze(),
  39.                     'attention_mask':inputs['attention_mask'].squeeze(),
  40.                    'token_type_ids':inputs['token_type_ids'].squeeze()}


  41. class CollateCls:
  42.     def __init__(self, cfg):
  43.         self.tokenizer = cfg.tokenizer
  44.         self.cfg = cfg
  45.         
  46.     def __call__(self, batch):
  47.         output = dict()
  48.         output["input_ids"] = [sample["input_ids"] for sample in batch]
  49.         output["attention_mask"] = [sample["attention_mask"] for sample in batch]
  50.         output["token_type_ids"] = [sample["token_type_ids"] for sample in batch]
  51.         # calculate max token length of this batch
  52.         batch_max = max([len(ids) for ids in output["input_ids"]])

  53.         # add padding
  54.         if self.tokenizer.padding_side == "right":
  55.             output["input_ids"] = [
  56.                 list(s) + (batch_max - len(s)) * [self.tokenizer.pad_token_id]
  57.                 for s in output["input_ids"]
  58.             ]
  59.             output["attention_mask"] = [
  60.                 list(s) + (batch_max - len(s)) * [0] for s in output["attention_mask"]
  61.             ]
  62.             output["token_type_ids"] = [list(s) + (batch_max - len(s)) * [0] for s in output["token_type_ids"]]

  63.         else:
  64.             output["input_ids"] = [
  65.                 (batch_max - len(s)) * [self.tokenizer.pad_token_id] + list(s)
  66.                 for s in output["input_ids"]
  67.             ]
  68.             output["attention_mask"] = [
  69.                 (batch_max - len(s)) * [0] + list(s) for s in output["attention_mask"]
  70.             ]
  71.             output["token_type_ids"] = [(batch_max - len(s)) * [0] + list(s) for s in output["token_type_ids"]]
  72.         
  73.         
  74.         # convert to tensors
  75.         output["input_ids"] = torch.tensor(output["input_ids"], dtype=torch.long)
  76.         output["attention_mask"] = torch.tensor(output["attention_mask"], dtype=torch.long)
  77.         output["token_type_ids"] = torch.tensor(output["token_type_ids"], dtype=torch.long)
  78.         
  79.         return output
复制代码


上述代码哪里有错误
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-11-3 12:17:30 | 显示全部楼层
在你提供的代码中,有几个地方可能存在问题:

1. **`prepare_input`函数中的重复代码**:
   - 在检查输入长度时,`inputs = inputs`重复了三次,应该是想要截断或处理输入,但没有实现。

2. **`__getitem__`方法中的索引问题**:
   - `self.texts`是一个数组,但在`prepare_input`中传入的是整个数组而不是单个文本。应该是`self.texts[idx]`。

3. **`__getitem__`方法中的`labels`获取**:
   - `labels = self.df.loc`不完整,应该指定行和列。可能是`labels = self.df.loc[idx, 'label_column_name']`。

4. **`CollateCls`类中的`output`处理**:
   - `output`的处理重复了三次,且缺少填充值。应该在`*`后面加上填充值,比如`self.tokenizer.pad_token_id`。

5. **`torch.tensor`转换重复**:
   - `torch.tensor(output, dtype=torch.long)`重复了三次,只需一次即可。

以下是一些修正建议:

- 在`prepare_input`中,处理输入长度的逻辑需要实现。
- 在`__getitem__`中,确保从`self.texts`中获取单个文本,并正确获取`labels`。
- 在`CollateCls`中,确保填充值正确,并只进行一次`torch.tensor`转换。

如果需要进一步的代码示例或详细解释,请告诉我。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-11-3 12:38:44 | 显示全部楼层
FishC 发表于 2024-11-3 12:17
在你提供的代码中,有几个地方可能存在问题:

1. **`prepare_input`函数中的重复代码**:
  1. ---------------------------------------------------------------------------
  2. KeyError                                  Traceback (most recent call last)
  3. Cell In[118], line 4
  4.       1 print('Training Start!')
  5.       2 print('=' * 100)
  6. ----> 4 train(model,
  7.       5     device,
  8.       6     train_dataloader,
  9.       7     valid_dataloader,
  10.       8     CFG.epochs,
  11.       9     loss_fn,
  12.      10     optimizer,
  13.      11     metric)
  14.      13 del model,train_dataloader, valid_dataloader
  15.      14 gc.collect()

  16. Cell In[82], line 17, in train(model, device, train_dataloader, valid_dataloader, epochs, loss_fn, optimizer, metric)
  17.      14 train_step = 0
  18.      15 pbar = tqdm(train_dataloader)#tqdm参数是一个iterable
  19. ---> 17 for batch in pbar: # you can also write like "for batch in tqdm(train_dataloader"
  20.      18     optimizer.zero_grad() # initialize
  21.      19     train_step += 1

  22. File /opt/conda/lib/python3.10/site-packages/tqdm/notebook.py:250, in tqdm_notebook.__iter__(self)
  23.     248 try:
  24.     249     it = super().__iter__()
  25. --> 250     for obj in it:
  26.     251         # return super(tqdm...) will not catch exception
  27.     252         yield obj
  28.     253 # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt

  29. File /opt/conda/lib/python3.10/site-packages/tqdm/std.py:1181, in tqdm.__iter__(self)
  30.    1178 time = self._time
  31.    1180 try:
  32. -> 1181     for obj in iterable:
  33.    1182         yield obj
  34.    1183         # Update and possibly print the progressbar.
  35.    1184         # Note: does not call self.update(1) for speed optimisation.

  36. File /opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py:630, in _BaseDataLoaderIter.__next__(self)
  37.     627 if self._sampler_iter is None:
  38.     628     # TODO(https://github.com/pytorch/pytorch/issues/76750)
  39.     629     self._reset()  # type: ignore[call-arg]
  40. --> 630 data = self._next_data()
  41.     631 self._num_yielded += 1
  42.     632 if self._dataset_kind == _DatasetKind.Iterable and \
  43.     633         self._IterableDataset_len_called is not None and \
  44.     634         self._num_yielded > self._IterableDataset_len_called:

  45. File /opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py:1344, in _MultiProcessingDataLoaderIter._next_data(self)
  46.    1342 else:
  47.    1343     del self._task_info[idx]
  48. -> 1344     return self._process_data(data)

  49. File /opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py:1370, in _MultiProcessingDataLoaderIter._process_data(self, data)
  50.    1368 self._try_put_index()
  51.    1369 if isinstance(data, ExceptionWrapper):
  52. -> 1370     data.reraise()
  53.    1371 return data

  54. File /opt/conda/lib/python3.10/site-packages/torch/_utils.py:706, in ExceptionWrapper.reraise(self)
  55.     702 except TypeError:
  56.     703     # If the exception takes multiple arguments, don't try to
  57.     704     # instantiate since we don't know how to
  58.     705     raise RuntimeError(msg) from None
  59. --> 706 raise exception

  60. KeyError: Caught KeyError in DataLoader worker process 0.
  61. Original Traceback (most recent call last):
  62.   File "/opt/conda/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3805, in get_loc
  63.     return self._engine.get_loc(casted_key)
  64.   File "index.pyx", line 167, in pandas._libs.index.IndexEngine.get_loc
  65.   File "index.pyx", line 196, in pandas._libs.index.IndexEngine.get_loc
  66.   File "pandas/_libs/hashtable_class_helper.pxi", line 2606, in pandas._libs.hashtable.Int64HashTable.get_item
  67.   File "pandas/_libs/hashtable_class_helper.pxi", line 2630, in pandas._libs.hashtable.Int64HashTable.get_item
  68. KeyError: 2183

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

  70. Traceback (most recent call last):
  71.   File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/worker.py", line 309, in _worker_loop
  72.     data = fetcher.fetch(index)  # type: ignore[possibly-undefined]
  73.   File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 52, in fetch
  74.     data = [self.dataset[idx] for idx in possibly_batched_index]
  75.   File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 52, in <listcomp>
  76.     data = [self.dataset[idx] for idx in possibly_batched_index]
  77.   File "/tmp/ipykernel_31/2920046666.py", line 34, in __getitem__
  78.     labels = self.df.loc[idx]['label']
  79.   File "/opt/conda/lib/python3.10/site-packages/pandas/core/indexing.py", line 1191, in __getitem__
  80.     return self._getitem_axis(maybe_callable, axis=axis)
  81.   File "/opt/conda/lib/python3.10/site-packages/pandas/core/indexing.py", line 1431, in _getitem_axis
  82.     return self._get_label(key, axis=axis)
  83.   File "/opt/conda/lib/python3.10/site-packages/pandas/core/indexing.py", line 1381, in _get_label
  84.     return self.obj.xs(label, axis=axis)
  85.   File "/opt/conda/lib/python3.10/site-packages/pandas/core/generic.py", line 4301, in xs
  86.     loc = index.get_loc(key)
  87.   File "/opt/conda/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3812, in get_loc
  88.     raise KeyError(key) from err
  89. KeyError: 2183
复制代码


以上为报错信息,相关代码如下
  1. def prepare_input(cfg, text):
  2.     inputs = cfg.tokenizer.encode_plus(
  3.         text,
  4.         return_tensors=None,
  5.         add_special_tokens=True,#自动在每个文本前后添加特殊标记(如CLS和SEP)
  6.         return_attention_mask=True # 计算注意力(attention)时忽略那些paddle值
  7.     )
  8.    
  9.     if len(inputs['input_ids']) > CFG.max_len:#句子长度大于max_length时截断
  10.         inputs['input_ids'] = inputs['input_ids'][:CFG.max_len]
  11.         inputs['attention_mask'] = inputs['attention_mask'][:CFG.max_len]
  12.         inputs['token_type_ids'] = inputs['token_type_ids'][:CFG.max_len]

  13.     for k, v in inputs.items():
  14.         inputs[k] = torch.tensor(v, dtype=torch.long)
  15.     return inputs


  16. class LLMDataset(Dataset):
  17.     def __init__(self, cfg, df,is_grad):
  18.         self.cfg = cfg
  19.         self.df = df
  20.         self.texts = df["cleaned"].values
  21.         self.is_grad = is_grad

  22.     def __len__(self):
  23.         return len(self.texts)

  24.     def __getitem__(self,idx):
  25.         inputs = prepare_input(self.cfg, self.texts[idx])#inputs是一个字典
  26.         
  27.         
  28.         if self.is_grad:#训练集
  29.             labels = self.df.loc[idx]['label']
  30.             # [batch,1,max_len(84)] -> [batch,max_len]#使用squeeze降维
  31.             return {'input_ids':inputs['input_ids'].squeeze(),
  32.                     'attention_mask':inputs['attention_mask'].squeeze(),
  33.                     'token_type_ids':inputs['token_type_ids'].squeeze(),
  34.                    # Our loss_fn wants it to be a "float" type
  35.                     'labels':torch.tensor(labels,dtype=torch.float).unsqueeze(dim=0)}
  36.         else:#测试集
  37.             # [batch,1,max_len(84)] -> [batch,max_len]
  38.             return {'input_ids':inputs['input_ids'].squeeze(),
  39.                     'attention_mask':inputs['attention_mask'].squeeze(),
  40.                    'token_type_ids':inputs['token_type_ids'].squeeze()}


  41. class CollateCls:
  42.     def __init__(self, cfg):
  43.         self.tokenizer = cfg.tokenizer
  44.         self.cfg = cfg
  45.         
  46.     def __call__(self, batch):
  47.         output = dict()
  48.         output["input_ids"] = [sample["input_ids"] for sample in batch]
  49.         output["attention_mask"] = [sample["attention_mask"] for sample in batch]
  50.         output["token_type_ids"] = [sample["token_type_ids"] for sample in batch]
  51.         # calculate max token length of this batch
  52.         batch_max = max([len(ids) for ids in output["input_ids"]])

  53.         # add padding
  54.         if self.tokenizer.padding_side == "right":
  55.             output["input_ids"] = [
  56.                 list(s) + (batch_max - len(s)) * [self.tokenizer.pad_token_id]
  57.                 for s in output["input_ids"]
  58.             ]
  59.             output["attention_mask"] = [
  60.                 list(s) + (batch_max - len(s)) * [0] for s in output["attention_mask"]
  61.             ]
  62.             output["token_type_ids"] = [list(s) + (batch_max - len(s)) * [0] for s in output["token_type_ids"]]

  63.         else:
  64.             output["input_ids"] = [
  65.                 (batch_max - len(s)) * [self.tokenizer.pad_token_id] + list(s)
  66.                 for s in output["input_ids"]
  67.             ]
  68.             output["attention_mask"] = [
  69.                 (batch_max - len(s)) * [0] + list(s) for s in output["attention_mask"]
  70.             ]
  71.             output["token_type_ids"] = [(batch_max - len(s)) * [0] + list(s) for s in output["token_type_ids"]]
  72.         
  73.         
  74.         # convert to tensors
  75.         output["input_ids"] = torch.tensor(output["input_ids"], dtype=torch.long)
  76.         output["attention_mask"] = torch.tensor(output["attention_mask"], dtype=torch.long)
  77.         output["token_type_ids"] = torch.tensor(output["token_type_ids"], dtype=torch.long)
  78.         
  79.         return output
复制代码

  1. #生成训练集
  2. train_dataset = LLMDataset(CFG,pd.concat([X_train,y_train],axis=1),True)
  3. valid_dataset = LLMDataset(CFG,pd.concat([X_valid,y_valid],axis=1),False)
复制代码

  1. from torch.utils.data import DataLoader

  2. train_dataloader = DataLoader(train_dataset,batch_size=32,collate_fn=CollateCls(CFG),shuffle=True,num_workers = 4,pin_memory=True)#锁页内存(pin_memory)能够保持与GPU进行高速传输,在训练时加快数据的读取
  3. valid_dataloader = DataLoader(valid_dataset,batch_size=32,collate_fn=CollateCls(CFG),shuffle=False,num_workers = 4,pin_memory=True)

  4. #collate_fn用于自定义数据加载和批处理的方式
复制代码

  1. import gc,os
  2. from tqdm.auto import tqdm # visualizing tool for progress

  3. # They will be used to pick the best model.pt given to the valid loss
  4. best_model_epoch, valid_loss_values = [],[]
  5. valid_loss_min = [1] # arbitrary loss I set here
  6. def train(model,device,train_dataloader,valid_dataloader,epochs,loss_fn,optimizer,metric):

  7.     for epoch in range(epochs):
  8.         gc.collect() # memory cleaning垃圾回收机制,减少占用内存
  9.         model.train()

  10.         train_loss = 0
  11.         train_step = 0
  12.         pbar = tqdm(train_dataloader)#tqdm参数是一个iterable

  13.         for batch in pbar: # you can also write like "for batch in tqdm(train_dataloader"
  14.             optimizer.zero_grad() # initialize
  15.             train_step += 1
  16.             

  17.             train_input_ids = batch['input_ids'].to(device)
  18.             train_attention_mask = batch['attention_mask'].to(device)
  19.             train_token_type_ids = batch['token_type_ids'].to(device)
  20.             train_labels = batch['labels'].squeeze().to(device).long()#label真实值long()转化成一维张量
  21.             
  22.             # You can refer to the class "TweetsModel" for understand
  23.             # what would be logits
  24.             logits = model(train_input_ids, train_attention_mask,train_token_type_ids).to(device)
  25.             predictions = torch.argmax(logits, dim=1) # get an index from larger one
  26.             detached_predictions = predictions.detach().cpu().numpy()
  27.             
  28.             loss = loss_fn(logits, train_labels)
  29.             loss.backward()
  30.             optimizer.step()
  31.             model.zero_grad()

  32.             train_loss += loss.detach().cpu().numpy().item()

  33.             pbar.set_postfix({'train_loss':train_loss/train_step})#设置进度条显示信息
  34.         pbar.close()

  35.         with torch.no_grad():
  36.             model.eval()

  37.             valid_loss = 0
  38.             valid_step = 0
  39.             total_valid_score = 0

  40.             y_pred = [] # for getting f1_score that is a metric of the competition
  41.             y_true = []

  42.             pbar = tqdm(valid_dataloader)
  43.             for batch in pbar:
  44.                 valid_step += 1

  45.                 valid_input_ids = batch['input_ids'].to(device)
  46.                 valid_attention_mask = batch['attention_mask'].to(device)
  47.                 valid_token_type_ids = batch['token_type_ids'].to(device)
  48.                 valid_labels = batch['labels'].squeeze().to(device).long()

  49.                 logits = model(valid_input_ids, valid_attention_mask).to(device)
  50.                 predictions = torch.argmax(logits, dim=1)
  51.                 detached_predictions = predictions.detach().cpu().numpy()
  52.                
  53.                 loss = loss_fn(logits, valid_labels)
  54.                 valid_loss += loss.detach().cpu().numpy().item()

  55.                 y_pred.extend(predictions.cpu().numpy())
  56.                 y_true.extend(valid_labels.cpu().numpy())

  57.             valid_loss /= valid_step
  58.             f1 = f1_score(y_true,y_pred)

  59.             print(f'Epoch [{epoch+1}/{epochs}] Score: {f1}')
  60.             print(f'Epoch [{epoch+1}/{epochs}] Valid_loss: {valid_loss}')

  61.             if valid_loss < min(valid_loss_min):
  62.                 print('model improved!')
  63.             else:
  64.                 print('model not improved')
  65.    
  66.             torch.save(model.state_dict(), f'epoch:{epoch+1}_model.pt')#state_dict 是一个字典对象,包含了模型的所有可学习参数(如权重和偏置)及其当前值
  67.             print('save checkpoint!')
  68.             valid_loss_min.append(valid_loss)
  69.             print(f'valid_loss_min:{min(valid_loss_min)}')

  70.         best_model_epoch.append(f'/kaggle/working/epoch:{epoch+1}_model.pt')
  71.         valid_loss_values.append(valid_loss)
  72.         print('='*100)

  73.     select_best_model() # refer to below function
  74.     print('Train/Valid Completed!!')
  75.     del train_dataloader, valid_dataloader # memory cleaning
  76.     gc.collect()

  77. def select_best_model():
  78.     best_model = best_model_epoch[np.array(valid_loss_values).argmin()]
  79.     os.rename(best_model, best_model.split('.pt')[0] + '_best.pt')#重命名文件
复制代码

  1. print('Training Start!')
  2. print('=' * 100)

  3. train(model,
  4.     device,
  5.     train_dataloader,
  6.     valid_dataloader,
  7.     CFG.epochs,
  8.     loss_fn,
  9.     optimizer,
  10.     metric)

  11. del model,train_dataloader, valid_dataloader
  12. gc.collect()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-11-3 12:38:56 | 显示全部楼层
Terence888 发表于 2024-11-03 12:38
-------------------------------------------------- ...


根据错误信息和代码,以下是可能导致`KeyError`的原因和解决方案:

1. **`__getitem__`方法中的索引问题**:
   - 在`LLMDataset`类的`__getitem__`方法中,`labels = self.df.loc`不完整。你需要指定行和列。应该是`labels = self.df.loc[idx, 'label_column_name']`,其中`'label_column_name'`是你数据框中标签列的名称。

2. **`prepare_input`函数中的输入问题**:
   - `prepare_input`函数中,`self.texts`传入的是整个数组而不是单个文本。应该是`self.texts[idx]`。

3. **`CollateCls`类中的填充值**:
   - 在`CollateCls`类中,填充值缺失。你需要在`*`后面加上填充值,比如`self.tokenizer.pad_token_id`。

4. **数据集的创建**:
   - 在创建`train_dataset`和`valid_dataset`时,`pd.concat(,axis=1)`缺少参数。你需要传入要合并的DataFrame列表。

5. **`train`函数中的数据处理**:
   - 在`train`函数中,`batch`是一个字典,你需要从中提取`input_ids`、`attention_mask`、`token_type_ids`和`labels`。例如:`train_input_ids = batch['input_ids'].to(device)`。

以下是一些修正建议:

- 确保在`__getitem__`中正确获取单个文本和标签。
- 在`CollateCls`中,确保填充值正确。
- 在`train`函数中,从`batch`字典中提取正确的张量。

如果需要进一步的代码示例或详细解释,请告诉我。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-18 16:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表