标签: huggingface-transformers

如何使用 Tensorflow 中的 Hugging Face Transformers 库对自定义数据进行文本分类?

我正在尝试使用 Hugging Face 'Transformers' 库提供的不同转换器架构对自定义数据(采用 csv 格式)进行二进制文本分类。我正在使用这篇Tensorflow 博客文章作为参考。

我正在使用以下代码将自定义数据集加载为“tf.data.Dataset”格式:

def get_dataset(file_path, **kwargs):
   dataset = tf.data.experimental.make_csv_dataset(
     file_path,
     batch_size=5, # Artificially small to make examples easier to show.
     na_value="",
     num_epochs=1,
     ignore_errors=True, 
     **kwargs)
   return dataset 
Run Code Online (Sandbox Code Playgroud)

在此之后,当我尝试使用“glue_convert_examples_to_features”方法进行标记化时,如下所示:

train_dataset = glue_convert_examples_to_features(
                           examples = train_data,
                           tokenizer = tokenizer, 
                           task = None,
                           label_list = ['0', '1'],
                           max_length = 128
                           )
Run Code Online (Sandbox Code Playgroud)

在以下位置引发错误“UnboundLocalError:分配前引用的局部变量‘处理器’”:

 if is_tf_dataset:
    example = processor.get_example_from_tensor_dict(example)
    example = processor.tfds_map(example)
Run Code Online (Sandbox Code Playgroud)

在所有示例中,我看到他们正在使用诸如“mrpc”之类的任务,这些任务是预定义的并且有一个glue_processor 来处理。在源代码中的“第 85 行”处引发错误。

任何人都可以使用“自定义数据”帮助解决此问题吗?

python text-classification tensorflow huggingface-transformers

12
推荐指数
1
解决办法
2426
查看次数

如何禁用 TOKENIZERS_PARALLELISM=(true | false) 警告?

我使用pytorch来训练huggingface-transformers模型,但是每个epoch,总是输出警告:

The current process just got forked. Disabling parallelism to avoid deadlocks... To disable this warning, please explicitly set TOKENIZERS_PARALLELISM=(true | false)
Run Code Online (Sandbox Code Playgroud)

如何禁用此警告?

pytorch huggingface-transformers huggingface-tokenizers

12
推荐指数
3
解决办法
6766
查看次数

如何在多 GPU 上使用 Transformer 管道?

ner_model = pipeline('ner', model=model, tokenizer=tokenizer, device=0, grouped_entities=True)
Run Code Online (Sandbox Code Playgroud)

设备指示管道使用 no_gpu=0(仅使用 GPU),请告诉我如何使用多 GPU

python huggingface-transformers

12
推荐指数
1
解决办法
6640
查看次数

导入错误:使用 `low_cpu_mem_usage=True` 或 `device_map` 需要加速:`pip install Accelerate`

我尝试使用 HuggingFace Transformer 通过运行以下代码来创建管道(代码在 SageMaker Jupyter 实验室上运行):

pipeline = transformers.pipeline(
    "text-generation",
    model="meta-llama/Llama-2-7b-chat-hf",
    torch_dtype=torch.float16,
    device_map="auto",
)
Run Code Online (Sandbox Code Playgroud)

但是,它会生成以下错误:

ImportError: Using `low_cpu_mem_usage=True` or a `device_map` requires Accelerate: `pip install accelerate`
Run Code Online (Sandbox Code Playgroud)

参考:

Packages version:print(accelerate.__version__), print(transformers.__version__)
0.21.0
4.31.0
Run Code Online (Sandbox Code Playgroud)

accelerate huggingface-transformers amazon-sagemaker-studio

12
推荐指数
1
解决办法
2万
查看次数

PyTorch BERT 类型错误:forward() 得到了意外的关键字参数“标签”

使用 PyTorch 转换器训练 BERT 模型(遵循此处的教程)。

教程中的以下语句

loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
Run Code Online (Sandbox Code Playgroud)

造成

TypeError: forward() got an unexpected keyword argument 'labels'
Run Code Online (Sandbox Code Playgroud)

这是完整的错误,

TypeError                                 Traceback (most recent call last)
<ipython-input-53-56aa2f57dcaf> in <module>
     26         optimizer.zero_grad()
     27         # Forward pass
---> 28         loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)
     29         train_loss_set.append(loss.item())
     30         # Backward pass

~/anaconda3/envs/systreviewclassifi/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    539             result = self._slow_forward(*input, **kwargs)
    540         else:
--> 541             result = self.forward(*input, **kwargs)
    542         for hook in self._forward_hooks.values():
    543             hook_result = hook(self, …
Run Code Online (Sandbox Code Playgroud)

python pytorch bert-language-model huggingface-transformers

11
推荐指数
1
解决办法
2万
查看次数

具有 dropout 设置的 Transformers 预训练模型

我正在尝试使用 Transformer 的 Huggingface 预训练模型bert-base-uncased,但我想增加 dropout。方法中没有提到这一点from_pretrained,但 colab 运行下面的对象实例化没有任何问题。我在classtransformers.BertConfig文档中看到了这些 dropout 参数。

我是否使用 bert-base-uncased 并以正确的方式改变 dropout ?

model = BertForSequenceClassification.from_pretrained(
        pretrained_model_name_or_path='bert-base-uncased',
        num_labels=2,
        output_attentions = False,
        output_hidden_states = False,
        attention_probs_dropout_prob=0.5,
        hidden_dropout_prob=0.5
    )
Run Code Online (Sandbox Code Playgroud)

python bert-language-model huggingface-transformers

11
推荐指数
2
解决办法
1万
查看次数

RuntimeError: 预期所有张量都在同一设备上,但发​​现至少有两个设备,cpu 和 cuda:0!使用我的模型进行预测时

我使用变压器(BertForSequenceClassification)训练了一个序列分类模型,但出现错误:

\n

预计所有张量都在同一设备上,但发​​现至少有两个设备,cpu 和 cuda:0!(在方法wrapper__index_select中检查参数索引时)

\n

我真的不明白问题出在哪里,如果问题出在我的模型上,问题出在我如何标记数据上,或者是什么。

\n

这是我的代码:

\n

加载预训练模型

\n
model_state_dict = torch.load("../MODELOS/TRANSFORMERS/TransformersNormal",  map_location='cpu') #Doesnt work with map_location='cuda:0' neither\nmodel = BertForSequenceClassification.from_pretrained(pretrained_model_name_or_path="bert-base-uncased", state_dict=model_state_dict, cache_dir='./data')\n
Run Code Online (Sandbox Code Playgroud)\n

创建数据加载

\n
def crearDataLoad(dfv,tokenizer): \n\n  dft=dfv  # usamos el del validacion para que nos salga los resultados y no tener que cambiar mucho codigo\n\n  #validation=dfv['text']  \n  validation=dfv['text'].str.lower()  # para modelos uncased  # el fichero que hemos llamado test es usado en la red neuronal\n  validation_labels=dfv['label']\n  \n  validation_inputs = crearinputs (validation,tokenizer)\n  validation_masks= crearmask (validation_inputs)\n …
Run Code Online (Sandbox Code Playgroud)

python pytorch huggingface-transformers

11
推荐指数
1
解决办法
2万
查看次数

如何从文件夹加载变压器管道?

根据here pipeline提供了一个接口,用一种方法在本地保存预训练的管道save_pretrained。当我使用它时,我看到一个使用一堆 json 和 bin 文件创建的文件夹,大概是用于标记器和模型的。

但文档没有指定加载方法。如何pipeline使用本地保存的管道来初始化?

python huggingface-transformers

11
推荐指数
2
解决办法
1万
查看次数

Hugging Face 的 Transformers 库中的 Trainer 使用的损失函数是什么?

Hugging Face 的 Transformers 库中的 Trainer 使用的损失函数是什么?

我正在尝试使用Hugging Face 的 Transformers 库中的Trainer 类来微调 BERT 模型。

在他们的文档中,他们提到可以通过重写compute_loss类中的方法来指定自定义损失函数。但是,如果我不进行方法覆盖并使用 Trainer 直接微调 BERT 模型以进行情感分类,那么使用的默认损失函数是什么?它是分类交叉熵吗?谢谢!

python nlp artificial-intelligence machine-learning huggingface-transformers

11
推荐指数
1
解决办法
2万
查看次数

特殊代币有什么特别之处?

“令牌”和“特殊令牌”到底有什么区别?

\n

我了解以下内容:

\n
    \n
  • 什么是典型的代币
  • \n
  • 什么是典型的特殊代币:MASK、UNK、SEP等
  • \n
  • 你什么时候添加一个标记(当你想扩展你的词汇量时)
  • \n
\n

我不明白的是,您想要在什么样的容量下创建新的特殊令牌,我们需要它的任何示例以及何时想要创建除默认特殊令牌之外的特殊令牌?如果一个示例使用特殊令牌,为什么普通令牌不能实现相同的目标?

\n
tokenizer.add_tokens(['[EOT]'], special_tokens=True)\n
Run Code Online (Sandbox Code Playgroud)\n

而且我也不太明白源文档中的以下描述。\n如果我们将 add_special_tokens 设置为 False,这对我们的模型有什么区别?

\n
add_special_tokens (bool, optional, defaults to True) \xe2\x80\x94 Whether or not to encode the sequences with the special tokens relative to their model.\n
Run Code Online (Sandbox Code Playgroud)\n

nlp tokenize bert-language-model huggingface-transformers huggingface-tokenizers

11
推荐指数
1
解决办法
5322
查看次数