FailedPreconditionError: Error while reading resource variable module/bilm/CNN_proj/W_proj from Container: localhost

FailedPreconditionError: Error while reading resource variable module/bilm/CNN_proj/W_proj from Container: 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: Error while reading resource variable module/bilm/CNN_proj/W_proj from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/module/bilm/CNN_proj/W_proj/N10tensorflow3VarE does not exist. [[{{node lambda/module_apply_default/bilm/MatMul_9/ReadVariableOp}}]]

要在构建 Keras 模型时使用来自 TF Hub 的模型片段,请使用 hub.KerasLayer class。它实现了Keras收集初始化变量的方式。使用 tensorflow_hub 0.7.0(最好是 tensorflow 1.15),您还可以将它用于较旧的 TF Hub 模块(如 https://tfhub.dev/google/elmo/3 in your example), subject to some caveats, see tensorflow.org/hub/migration_tf2

对于上下文:较旧的 hub.Module class 用于以 classic TF1 方式构建模型(如 tf.layers)。它通过 tf.Graph 的 GLOBAL_VARIABLES 集合实现了收集初始化变量的老式方法。你的情况遗漏了这些。 (您可以尝试在 tf.compat.v1.keras.backend.get_session() 返回的 Session 中手动初始化它们,但这会变得很奇怪。)