TensorFlow-tensorflow.python.framework.errors_impl.FailedPreconditionError

时间:2019-11-15 16:20:13

标签: python python-3.x tensorflow elmo

我尝试将以下code从TF 1.7更新为TF 1.14:

@Test
fun `Validates something`() {
    runBlocking {
        try {
            // Assert something
        } catch (t: Throwable) {
            fail<Nothing>("Should not throw $t")
        }
    }
}

当我拟合模型时,下一行

def build(self, input_shape):
    self.max_length = input_shape[1]
    self.word_mapping = [x[1] for x in sorted(self.idx2word.items(), key=lambda x: x[0])]
    self.lookup_table = tf.contrib.lookup.index_to_string_table_from_tensor(self.word_mapping, default_value="<UNK>")
    self.lookup_table.init.run(session=K.get_session())
    self.elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=self.trainable)
    super(ELMoEmbedding, self).build(input_shape)

def call(self, x):
    x = tf.cast(x, dtype=tf.int64)
    sequence_lengths = tf.cast(tf.count_nonzero(x, axis=1), dtype=tf.int32)
    strings = self.lookup_table.lookup(x)
    inputs = {
        "tokens": strings,
        "sequence_len": sequence_lengths
    }
    return self.elmo_model(inputs, signature="tokens", as_dict=True)[self.output_mode]

产生以下错误:

  

“ StaticHashTableV1”对象没有属性“ init”。因此,我按照TF r1.14 doc

修改了代码
self.lookup_table.init.run(session=K.get_session())

我得到这个错误:

def build(self, input_shape):
    self.max_length = input_shape[1]
    self.word_mapping = [x[1] for x in sorted(self.idx2word.items(), key=lambda x: x[0])]
    #self.lookup_table = tf.contrib.lookup.index_to_string_table_from_tensor(self.word_mapping, default_value="<UNK>")
    self.lookup_table = tf.contrib.lookup.index_to_string_table_from_tensor(self.word_mapping,
            default_value='<UNK>',
            name=None
            )
    with tf.Session() as session:
        session.run(tf.compat.v1.tables_initializer)
    # Initialize the variables (i.e. assign their default value)
    self.elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=self.trainable)
    super(ELMoEmbedding, self).build(input_shape)

def call(self, x):
    x = tf.cast(x, dtype=tf.int64)
    sequence_lengths = tf.cast(tf.count_nonzero(x, axis=1), dtype=tf.int32)
    strings = self.lookup_table.lookup(x)
    inputs = {
        "tokens": strings,
        "sequence_len": sequence_lengths
    }
    return self.elmo_model(inputs, signature="tokens", as_dict=True)[self.output_mode]

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

打开

with tf.Session() as session:
    session.run(tf.compat.v1.tables_initializer)

超出范围时,该会话停止存在。 您可以将其替换为

tf.compat.v1.tables_initializer().run(session=K.get_session())

我认为应该可以解决问题。