Получение ошибки при передаче токенизированного ввода в ElMo с подписью «токены» - PullRequest
0 голосов
/ 28 мая 2019

Я новичок в Data Science и изучаю концепцию техники встраивания ElMo.Я использую опцию signature = tokens при вызове метода elmo.Однако когда тензор входной строки, который я передаю в ElMo, содержит более 2 элементов, я получаю сообщение об ошибке формы тензора.

Я использую версию Tensorflow 1.13.1.Я попытался изменить ввод, но он работает только тогда, когда длина строки составляет 2 элемента.Я не могу узнать, где произошло несоответствие формы.Может кто-нибудь предоставить решение этой ошибки, а также объяснить, почему эта подпись "токены" работает таким образом?

import tensorflow_hub as hub
import tensorflow as tf
import numpy as np
elmo = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)

tokens_input = [["the", "cat", "is", "on", "the", "mat"],["hello"],
                ["dogs", "are", "in", "the", "fog", ""],["happiness", 
               "cannot", "be", "bought", "by", "us"]]

print(tokens_input,type(tokens_input))
tokens_length = len(tokens_input)
print(tokens_length)

#get the maximum length of elements in tokens_input
strlen = len(max(tokens_input, key=len))
print(strlen)

#append array elements which have lower length than strlen with space
for i in range(tokens_length):
  if len(tokens_input[i])<strlen:
    for j in range(strlen-len(tokens_input[i])):
      tokens_input[i].insert(j,"null")
np_arr = np.array(tokens_input)
print("np_arr details are ",np_arr,np_arr.shape,np_arr.dtype) 

tokens_shp = tf.strings.length(np_arr).shape
print("Tokens shape",tokens_shp)

embeddings = elmo(inputs={
        "tokens": tokens_input,
        "sequence_len": tokens_shp
        },signature="tokens",
        as_dict=True)["elmo"]

Строка ввода для метода elmo в моем коде - tokens_input.Я могу получить правильную форму tokens_input, добавив в массив пустую строку (в данном случае (4,6)). Но когда я запускаю приведенный выше код, я получаю следующую ошибку:

InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/importer.py in import_graph_def(graph_def, input_map, return_elements, name, op_dict, producer_op_list)
    425         results = c_api.TF_GraphImportGraphDefWithResults(
--> 426             graph._c_graph, serialized, options)  # pylint: disable=protected-access
    427         results = c_api_util.ScopedTFImportGraphDefResults(results)

InvalidArgumentError: Dimension 0 in both shapes must be equal, but are 2 and 4. Shapes are [2] and [4]. for 'module_apply_tokens/bilm/RNN_0/RNN/MultiRNNCell/Cell0/rnn/while/Select' (op: 'Select') with input shapes: [2], [4,512], [?,512].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
7 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/importer.py in import_graph_def(graph_def, input_map, return_elements, name, op_dict, producer_op_list)
    428       except errors.InvalidArgumentError as e:
    429         # Convert to ValueError for backwards compatibility.
--> 430         raise ValueError(str(e))
    431 
    432     # Create _DefinedFunctions for any imported functions.

ValueError: Dimension 0 in both shapes must be equal, but are 2 and 4. Shapes are [2] and [4]. for 'module_apply_tokens/bilm/RNN_0/RNN/MultiRNNCell/Cell0/rnn/while/Select' (op: 'Select') with input shapes: [2], [4,512], [?,512].
...