我正在尝试使用 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
我使用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)
如何禁用此警告?
ner_model = pipeline('ner', model=model, tokenizer=tokenizer, device=0, grouped_entities=True)
Run Code Online (Sandbox Code Playgroud)
设备指示管道使用 no_gpu=0(仅使用 GPU),请告诉我如何使用多 GPU 。
我尝试使用 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) 使用 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) 我正在尝试使用 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) 我使用变压器(BertForSequenceClassification)训练了一个序列分类模型,但出现错误:
\n预计所有张量都在同一设备上,但发现至少有两个设备,cpu 和 cuda:0!(在方法wrapper__index_select中检查参数索引时)
\n我真的不明白问题出在哪里,如果问题出在我的模型上,问题出在我如何标记数据上,或者是什么。
\n这是我的代码:
\n加载预训练模型
\nmodel_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')\nRun Code Online (Sandbox Code Playgroud)\n创建数据加载
\ndef 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) 根据here pipeline提供了一个接口,用一种方法在本地保存预训练的管道save_pretrained。当我使用它时,我看到一个使用一堆 json 和 bin 文件创建的文件夹,大概是用于标记器和模型的。
但文档没有指定加载方法。如何pipeline使用本地保存的管道来初始化?
Hugging Face 的 Transformers 库中的 Trainer 使用的损失函数是什么?
我正在尝试使用Hugging Face 的 Transformers 库中的Trainer 类来微调 BERT 模型。
在他们的文档中,他们提到可以通过重写compute_loss类中的方法来指定自定义损失函数。但是,如果我不进行方法覆盖并使用 Trainer 直接微调 BERT 模型以进行情感分类,那么使用的默认损失函数是什么?它是分类交叉熵吗?谢谢!
python nlp artificial-intelligence machine-learning huggingface-transformers
“令牌”和“特殊令牌”到底有什么区别?
\n我了解以下内容:
\n我不明白的是,您想要在什么样的容量下创建新的特殊令牌,我们需要它的任何示例以及何时想要创建除默认特殊令牌之外的特殊令牌?如果一个示例使用特殊令牌,为什么普通令牌不能实现相同的目标?
\ntokenizer.add_tokens(['[EOT]'], special_tokens=True)\nRun Code Online (Sandbox Code Playgroud)\n而且我也不太明白源文档中的以下描述。\n如果我们将 add_special_tokens 设置为 False,这对我们的模型有什么区别?
\nadd_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.\nRun Code Online (Sandbox Code Playgroud)\n nlp tokenize bert-language-model huggingface-transformers huggingface-tokenizers