我们知道BERT有tokens的最大长度限制=512,那么如果一篇文章的长度远远大于512,比如文本中有10000个tokens,BERT怎么用呢?
我正在处理文本分类问题,我想使用 BERT 模型作为基础,然后使用密集层。我想知道这 3 个参数是如何工作的?例如,如果我有 3 个句子:
'My name is slim shade and I am an aspiring AI Engineer',
'I am an aspiring AI Engineer',
'My name is Slim'
Run Code Online (Sandbox Code Playgroud)
那么这 3 个参数会做什么呢?我的想法如下:
max_length=5将严格保留长度为 5 之前的所有句子padding=max_length将为第三句添加 1 的填充truncate=True将截断第一句和第二句,使其长度严格为 5。如果我错了,请纠正我。
下面是我使用过的代码。
! pip install transformers==3.5.1
from transformers import BertTokenizerFast
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
tokens = tokenizer.batch_encode_plus(text,max_length=5,padding='max_length', truncation=True)
text_seq = torch.tensor(tokens['input_ids'])
text_mask = torch.tensor(tokens['attention_mask'])
Run Code Online (Sandbox Code Playgroud) python deep-learning pytorch bert-language-model huggingface-tokenizers
对于 ElMo、FastText 和 Word2Vec,我正在对句子中的词嵌入进行平均,并使用 HDBSCAN/KMeans 聚类对相似的句子进行分组。
在这篇短文中可以看到一个很好的实现示例:http : //ai.intelligentonlinetools.com/ml/text-clustering-word-embedding-machine-learning/
我想使用 BERT(使用 Hugging face 中的 BERT python 包)做同样的事情,但是我不太熟悉如何提取原始词/句子向量以将它们输入到聚类算法中。我知道 BERT 可以输出句子表示 - 那么我实际上如何从句子中提取原始向量呢?
任何信息都有帮助。
python nlp artificial-intelligence word-embedding bert-language-model
此训练代码基于此处找到的run_glue.py脚本:
# Set the seed value all over the place to make this reproducible.
seed_val = 42
random.seed(seed_val)
np.random.seed(seed_val)
torch.manual_seed(seed_val)
torch.cuda.manual_seed_all(seed_val)
# Store the average loss after each epoch so we can plot them.
loss_values = []
# For each epoch...
for epoch_i in range(0, epochs):
# ========================================
# Training
# ========================================
# Perform one full pass over the training set.
print("")
print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs))
print('Training...')
# Measure how long the …Run Code Online (Sandbox Code Playgroud) 在 colab 中运行 pytorch 深度学习模型时出现以下错误
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)
1370 ret = torch.addmm(bias, input, weight.t())
1371 else:
-> 1372 output = input.matmul(weight.t())
1373 if bias is not None:
1374 output += bias
RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`
Run Code Online (Sandbox Code Playgroud)
我什至将批量大小从 128 减少到 64,即减少到一半,但仍然出现此错误。早些时候,我以 128 的批量大小运行了相同的代码,但没有收到任何类似的错误。
我的代码运行良好,当我今天尝试在不更改任何内容的情况下运行它时,出现以下错误:
dropout(): 参数“输入”(位置 1)必须是张量,而不是 str
如果可以提供帮助,将不胜感激。可能是数据加载器的问题?
\n\n\n返回last_hidden_state(torch.FloatTensor,形状为(batch_size,\n sequence_length,hidden_size)):模型最后一层输出的隐藏状态序列。
\n\npooler_output (torch.FloatTensor: of shape (batch_size, hide_size)):\n 序列第一个标记的最后一层隐藏状态\n(分类标记)由线性层和 Tanh\n 激活函数进一步处理。线性层权重是在预训练期间根据下一个句子预测(分类)目标进行训练的。
\n\n此输出通常不是输入语义内容的良好摘要,对整个输入序列的隐藏状态序列进行平均或池化通常会更好。
\n\nhidden_states(tuple(torch.FloatTensor),可选,当 config.output_hidden_states=True 时返回):形状的 torch.FloatTensor 元组(一个用于\n 嵌入的输出 + 一个用于\n 每层的输出) (批量大小、序列长度、隐藏大小)。
\n\n每层输出处模型的隐藏状态加上初始嵌入输出。
\n\n注意(tuple(torch.FloatTensor),可选,当 config.output_attentions=True 时返回):torch.FloatTensor 的元组(每层一个),形状(batch_size、num_heads、sequence_length、sequence_length)。
\n\n注意力权重位于注意力softmax之后,用于计算自注意力头中的加权平均值。
\n
这是来自https://huggingface.co/transformers/model_doc/bert.html#bertmodel。虽然文档中描述的很清楚,但是我还是不明白returns的hidden_states。有一个元组,一个用于嵌入的输出,另一个用于每一层的输出。\n请告诉我如何区分它们,或者它们的含义是什么?非常感谢!![眨眼~
\nnlp pytorch bert-language-model electrate huggingface-transformers
我正在对 bert 架构进行实验,发现大部分微调任务都将最终隐藏层作为文本表示,然后将其传递给其他模型以进行进一步的下游任务。
伯特的最后一层看起来像这样:
我们取每个句子的 [CLS] 标记:
我经历了许多的讨论继续这一huggingface问题, 数据科学论坛的问题, GitHub的问题大部分数据科学家给出了这样的解释:
BERT 是双向的,[CLS] 是通过多层编码过程编码的,包括所有令牌的所有代表信息。[CLS] 的表示在不同的句子中是单独的。
我的问题是,为什么作者忽略了其他信息(每个令牌的向量)并采用平均值、max_pool 或其他方法来利用所有信息而不是使用 [CLS] 令牌进行分类?
这个 [CLS] 令牌与所有令牌向量的平均值相比有何帮助?
machine-learning deep-learning keras tensorflow bert-language-model
我正在使用 SentenceTransformers 库(此处: https: //pypi.org/project/sentence-transformers/#pretrained-models)使用预训练模型 bert-base-nli-mean-tokens 创建句子嵌入。我有一个应用程序将部署到无法访问互联网的设备。到这里,已经回答了,如何保存模型下载预训练的BERT模型到本地。然而我一直坚持从本地保存的路径加载保存的模型。
当我尝试使用上述技术保存模型时,这些是输出文件:
('/bert-base-nli-mean-tokens/tokenizer_config.json',
'/bert-base-nli-mean-tokens/special_tokens_map.json',
'/bert-base-nli-mean-tokens/vocab.txt',
'/bert-base-nli-mean-tokens/added_tokens.json')
Run Code Online (Sandbox Code Playgroud)
当我尝试将其加载到内存中时,使用
tokenizer = AutoTokenizer.from_pretrained(to_save_path)
Run Code Online (Sandbox Code Playgroud)
我越来越
Can't load config for '/bert-base-nli-mean-tokens'. Make sure that:
- '/bert-base-nli-mean-tokens' is a correct model identifier listed on 'https://huggingface.co/models'
- or '/bert-base-nli-mean-tokens' is the correct path to a directory containing a config.json
Run Code Online (Sandbox Code Playgroud) word-embedding bert-language-model huggingface-tokenizers sentence-transformers
尝试使用 BERT 模型制作文本情感分类器,但得到ValueError : too many dimensions 'str'
这是列车数据值的 DataFrame;所以它们是train_labels
0 notr
1 notr
2 notr
3 negative
4 notr
... ...
854 positive
855 notr
856 notr
857 notr
858 positive
Run Code Online (Sandbox Code Playgroud)
并且有代码产生错误
train_seq = torch.tensor(tokens_train['input_ids'])
train_mask = torch.tensor(tokens_train['attention_mask'])
train_y = torch.tensor(train_labels.tolist())
Run Code Online (Sandbox Code Playgroud)
At train_y = torch.tensor(train_labels.tolist());出现错误:
ValueError: too many dimensions 'str'
你能帮我吗

