OperatorNotAllowedInGraphError: использование `tf.Tensor` в качестве Python` bool` не допускается при выполнении Graph - PullRequest
1 голос
/ 26 января 2020

Я пытаюсь выполнить эти функции

def evaluate(sentence):
  sentence = preprocess_sentence(sentence)

  sentence = tf.expand_dims(
      START_TOKEN + tokenizer.encode(sentence) + END_TOKEN, axis=0)

  output = tf.expand_dims(START_TOKEN, 0)

  for i in range(MAX_LENGTH):

    predictions = model(inputs=[sentence, output], training=False)

    # select the last word from the seq_len dimension
    predictions = predictions[:, -1:, :]
    predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)

    # return the result if the predicted_id is equal to the end token

    if tf.equal(predicted_id, END_TOKEN[0]):
      break
    #check()
    #tf.cond(tf.equal(predicted_id, END_TOKEN[0]),true_fn=break,false_fn=lambda: tf.no_op())


    # concatenated the predicted_id to the output which is given to the decoder
    # as its input.
    output = tf.concat([output, predicted_id], axis=-1)

  return tf.squeeze(output, axis=0)


def predict(sentence):
  prediction = evaluate(sentence)

  predicted_sentence = tokenizer.decode(
      [i for i in prediction if i < tokenizer.vocab_size])

  print('Input: {}'.format(sentence))
  print('Output: {}'.format(predicted_sentence))

  return predicted_sentence

, однако у меня возникает следующая ошибка: OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function. Я понимаю, что мне нужно переписать условие if в виде tf. Cond (). Тем не менее, я не знаю, как написать break в тензорном потоке, а также я не уверен, что, если условие вызывает проблему, так как та же функция точно в этом ноутбуке работает правильно? https://colab.research.google.com/github/tensorflow/examples/blob/master/community/en/transformer_chatbot.ipynb#scrollTo = _ NURhwYz5AXa Любая помощь?

1 Ответ

0 голосов
/ 26 января 2020

Код в записной книжке работает, потому что он использует TF 2.0, для которого по умолчанию включено активное выполнение. Вы можете включить его в более старых версиях с помощью tf.enable_eager_execution.

В качестве альтернативы, вы можете использовать разрыв в графическом режиме без записи tf.cond, если вы используете tf.function или tf.autograph , но у них есть некоторые ограничения на код, который вы можете запустить.

...