首页 > 解决方案 > 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}}]]

标签: tensorflowtensorflow-hubelmo

解决方案


要使用 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(),但这变得很奇怪。)


推荐阅读