tensorflow - FailedPreconditionError:从容器读取资源变量模块/bilm/CNN_proj/W_proj 时出错:localhost
问题描述
我正在尝试在带有 python 3.7 的 jupyter notebook 中使用预训练的 elmo 嵌入。TensorFlow 版本 - 1.14.0
这是我的代码
def ElmoEmbeddingLayer(x):
print(x.shape)
module = hub.Module("https://tfhub.dev/google/elmo/3", trainable=False)
embeddings = module(tf.squeeze(tf.cast(x, tf.string)), signature="default", as_dict=True)["elmo"]
return embeddings
elmo_dim=1024
elmo_input = Input(shape=(None,), dtype=tf.string)
elmo_embedding = Lambda(ElmoEmbeddingLayer, output_shape=(None,elmo_dim))(elmo_input)
x = Dense(1)(elmo_embedding)
x = Activation('relu')(x)
model = Model(inputs=[elmo_input], outputs=x)
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
model.fit(x_train, y_train, epochs=1,validation_data=(x_test, y_test))
但是我收到了一个运行时错误
FailedPreconditionError:从容器读取资源变量模块/bilm/CNN_proj/W_proj 时出错:localhost。这可能意味着该变量未初始化。未找到:资源 localhost/module/bilm/CNN_proj/W_proj/N10tensorflow3VarE 不存在。[[{{node lambda/module_apply_default/bilm/MatMul_9/ReadVariableOp}}]]
解决方案
要使用 TF Hub 中的模型片段来构建 Keras 模型,请使用hub.KerasLayer
该类。它实现了 Keras 为初始化收集变量的方式。使用 tensorflow_hub 0.7.0(最好是 tensorflow 1.15),您还可以将它用于较旧的 TF Hub 模块(例如您的示例中的https://tfhub.dev/google/elmo/3),但有一些注意事项,请参阅tensorflow .org/hub/migration_tf2
对于上下文:较旧的hub.Module
类用于以经典的 TF1 方式(如 tf.layers)构建模型。它通过 tf.Graph 的 GLOBAL_VARIABLES 集合实现了收集初始化变量的老式方法。这些在你的情况下被遗漏了。(您可以尝试在 Session 返回的 Session 中手动初始化它们tf.compat.v1.keras.backend.get_session()
,但这变得很奇怪。)
推荐阅读
- sql - 在 PostgresQL 表中,如何使用 column1 中的所有值创建列,其中 column1 中的当前行的值出现在 column2 中?
- dialogflow-cx - 注册免费试用 google DialogFlow cx 服务
- python - 如果“-”位于字符串中间,则在数据框单元格中将“-”替换为“E-”
- python - 使用 Jmespath 过滤 JSON,如果表达式存在则返回值,如果它不返回 None/Null (python)
- typescript - 基于 Vue CLI / Typescript 的项目不再构建或运行 Mocha 测试
- wordpress - 根目录中的 Wordpress 和子目录中的 vue。使用 wordpress URL 屏蔽 vue。URL 指向 root 和页面加载是 vue
- sharepoint - 在 BizTalk 中,无法在没有旧身份验证的情况下将文件从本地发送到 SharePoint Online
- android - 无法将 Android Native Module 添加到 React Native 项目
- javascript - Panzoom 库,测量 div 之间的距离,getBoundingClientRect()
- java - JAVA OCA Oracle Certified Associate Java SE 8 Programmer I Exam_1Z0-808