我正在尝试在带有python 3.7的jupyter笔记本中使用预训练的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:从容器:本地主机读取资源变量module / bilm / CNN_proj / W_proj时出错。这可能意味着该变量未初始化。找不到:资源localhost / module / bilm / CNN_proj / W_proj / N10tensorflow3VarE不存在。 [[{{node lambda / module_apply_default / bilm / MatMul_9 / ReadVariableOp}}]]
答案 0 :(得分:1)
要使用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集合实现了收集变量以进行初始化的旧方法。在您的情况下,这些都是错过的。 (您可以尝试在tf.compat.v1.keras.backend.get_session()
返回的会话中手动初始化它们,但这很奇怪。)