- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 Tensorflow BERT 语言模型创建了一个二元分类器。这是link 。模型训练完成后,保存模型并生成以下文件。
预测代码。
from tensorflow.contrib import predictor
#MODEL_FILE = 'graph.pbtxt'
with tf.Session() as sess:
predict_fn = predictor.from_saved_model(f'/content/drive/My Drive/binary_class/bert/graph.pbtxt')
predictions = predict_fn(pred_sentences)
print(predictions)
错误
OSError: SavedModel file does not exist at: /content/drive/My Drive/binary_class/bert/graph.pbtxt/{saved_model.pbtxt|saved_model.pb}
深入研究这个问题后。我遇到了 tf.train.Saver() 类来保存模型。我将估计器训练代码更改为以下以保存模型。我提到了这个link 。我想 tensorflow 估计器可以用它来保存。
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
saver = tf.train.Saver()
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
# Save the variables to disk.
save_path = saver.save(sess, f'/content/drive/My Drive/binary_class/bert/tmp/model.ckpt')
这是错误。
Beginning Training!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-38-0c9f9b70d76b> in <module>()
9 sess.run(init_op)
10 # Do some work with the model.
---> 11 saver = tf.train.Saver()
12 estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
13 # Save the variables to disk.
2 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/training/saver.py in _build(self, checkpoint_path, build_save, build_restore)
860 return
861 else:
--> 862 raise ValueError("No variables to save")
863 self._is_empty = False
864
ValueError: No variables to save
变量、权重在create_model函数中创建。我应该更改什么来保存经过训练的模型?
更新:保存模型的代码。我不确定 feature_spec 和特征张量。
feature_spec = {'x': tf.VarLenFeature(tf.string)}
def serving_input_receiver_fn():
serialized_tf_example = tf.placeholder(dtype=tf.string,
shape=[1], # batch size
name='input_example_tensor')
receiver_tensors = {'examples': serialized_tf_example}
features = tf.parse_example(serialized_tf_example, feature_spec)
return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)
# Export the estimator
export_path = f'/content/drive/My Drive/binary_class/bert/'
estimator.export_saved_model(
export_path,
serving_input_receiver_fn=serving_input_receiver_fn)
我收到此错误:-
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-55-209298910d1e> in <module>()
16 estimator.export_saved_model(
17 export_path,
---> 18 serving_input_receiver_fn=serving_input_receiver_fn)
4 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py in export_saved_model(self, export_dir_base, serving_input_receiver_fn, assets_extra, as_text, checkpoint_path, experimental_mode)
730 as_text=as_text,
731 checkpoint_path=checkpoint_path,
--> 732 strip_default_attrs=True)
733
734 def experimental_export_all_saved_models(
/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py in _export_all_saved_models(self, export_dir_base, input_receiver_fn_map, assets_extra, as_text, checkpoint_path, strip_default_attrs)
854 builder, input_receiver_fn_map, checkpoint_path,
855 save_variables, mode=ModeKeys.PREDICT,
--> 856 strip_default_attrs=strip_default_attrs)
857 save_variables = False
858
/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py in _add_meta_graph_for_mode(self, builder, input_receiver_fn_map, checkpoint_path, save_variables, mode, export_tags, check_variables, strip_default_attrs)
927 labels=getattr(input_receiver, 'labels', None),
928 mode=mode,
--> 929 config=self.config)
930
931 export_outputs = export_lib.export_outputs_for_mode(
/usr/local/lib/python3.6/dist-packages/tensorflow_estimator/python/estimator/estimator.py in _call_model_fn(self, features, labels, mode, config)
1144
1145 logging.info('Calling model_fn.')
-> 1146 model_fn_results = self._model_fn(features=features, **kwargs)
1147 logging.info('Done calling model_fn.')
1148
<ipython-input-17-119a3167bf33> in model_fn(features, labels, mode, params)
5 """The `model_fn` for TPUEstimator."""
6
----> 7 input_ids = features["input_ids"]
8 input_mask = features["input_mask"]
9 segment_ids = features["segment_ids"]
KeyError: 'input_ids'
最佳答案
笔记本中的create_model函数需要一些参数。这些特征将传递给模型。
通过将serving_input_fn函数更新为以下内容,服务函数将按预期工作。
更新代码
def serving_input_receiver_fn():
feature_spec = {
"input_ids" : tf.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),
"input_mask" : tf.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),
"segment_ids" : tf.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),
"label_ids" : tf.FixedLenFeature([], tf.int64)
}
serialized_tf_example = tf.placeholder(dtype=tf.string,
shape=[None],
name='input_example_tensor')
print(serialized_tf_example.shape)
receiver_tensors = {'example': serialized_tf_example}
features = tf.parse_example(serialized_tf_example, feature_spec)
return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)
export_path = '/content/drive/My Drive/binary_class/bert/'
estimator._export_to_tpu = False # this is important
estimator.export_saved_model(export_dir_base=export_path,serving_input_receiver_fn=serving_input_receiver_fn)
关于python - 使用 Tensorflow BERT 模型保存并进行推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831583/
我正在尝试从 BERT 模型中的隐藏状态中获取句子向量。看着拥抱脸 BertModel 说明 here ,其中说: from transformers import BertTokenizer, Be
我正在将 Huggingface BERT 用于 NLP 任务。我的文本包含被分成子词的公司名称。 tokenizer = BertTokenizerFast.from_pretrained('ber
对于 Transformer 模型,尤其是 BERT,以编程方式禁止模型以特殊标记作为预测结果是否有意义(并且在统计上是否正确)?在最初的实现中情况如何?在收敛过程中,模型必须学会不预测这些,但这种干
我有一个包含段落的数据集,我需要将其分为两类。这些段落通常有 3-5 句话长。其中绝大多数的长度不到 500 字。我想利用BERT来解决这个问题。 我想知道我应该如何使用 BERT 来生成这些段落的向
我想在特定域上微调 BERT。我在文本文件中有该域的文本。我如何使用这些来微调 BERT? 我在找 here目前。 我的主要目标是使用 BERT 获得句子嵌入。 最佳答案 这里要做出的重要区别是您是否
我想针对未标记数据的特定域微调 BERT,并让输出层检查它们之间的相似性。我该怎么做?我是否需要先微调分类器任务(或问题答案等)并获得嵌入?或者我可以只使用预先训练好的 Bert 模型而无需执行任务并
我遇到了这个page 1)我想在微调完成后获得句子级嵌入(由[CLS] token 给出的嵌入)。我怎么能做到? 2)我还注意到该页面上的代码需要花费大量时间才能返回测试数据的结果。这是为什么?当我训
我读过解释滑动窗口如何工作的帖子,但我找不到任何关于它是如何实际实现的信息。 据我了解,如果输入太长,可以使用滑动窗口来处理文本。 如果我错了,请纠正我。 假设我有一个文本 “2017 年 6 月 K
我正在尝试使用 BERT 微调模型(使用 transformers 库),但我对优化器和调度器有点不确定。 首先,我明白我应该使用 transformers.AdamW而不是 Pytorch 的版本。
我在 Tensorflow 中使用 BERT,有一个细节我不太明白。根据文档( https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1 ),合并
我正在阅读 BERT paper并且不清楚 transformer 的输入编码器和解码器。 对于学习掩码语言模型(Cloze 任务),论文称 15% 的标记是被掩码的,并且训练网络来预测被掩码的标记。
我想使用 Bert 训练一个21 类 文本分类模型。但是我的训练数据很少,所以下载了一个类似的数据集,其中包含 5 类 和 200 万个样本。t并使用 bert 提供的 uncased 预训练模型对下
我正在训练一个在 BERT 之上使用自定义层的分类模型。在此期间,该模型的训练性能随着纪元的增加而下降(在第一个纪元之后)..我不确定这里要修复什么 - 是模型还是数据? (对于数据来说,它是二进制标
我是初学者..我正在和伯特一起工作。但出于公司网络的安全考虑,以下代码并没有直接接收bert模型。 tokenizer = BertTokenizer.from_pretrained('bert-ba
如何卡住上述预训练模型中的最后两层(dropout 和分类器层)?这样当模型运行时,我将得到一个致密层作为输出。 最佳答案 我想指出 BertForSequenceClassification 的定义
我正在使用 Huggingface 进一步训练 BERT 模型。我使用两种方法保存模型:步骤 (1) 使用此代码保存整个模型:model.save_pretrained(save_location),
我收到以下错误: AssertionError:文本输入必须为 str(单个示例)、List[str](批处理或单个预标记示例)或 List[List[str]](预标记示例批处理)类型。,当我运行
我想构建一个多类分类模型,我将对话数据作为 BERT 模型的输入(使用 bert-base-uncased)。 QUERY: I want to ask a question. ANSWER: Sur
我很感兴趣如何从 BERT 模型中获得不同句子中词嵌入的相似性(实际上,这意味着词在不同场景中具有不同的含义)。 例如: sent1 = 'I like living in New York.' se
众所周知,BERT 模型的词嵌入能力可能优于 word2vec 和任何其他模型。 我想在 BERT 词嵌入上创建一个模型来生成同义词或相似词。就像我们在 Gensim Word2Vec 中所做的一样。
我是一名优秀的程序员,十分优秀!