¿Cómo utilizar la API del conjunto de datos para leer el archivo TFRecords de listas de longitud variable?

Quiero usar la API de conjunto de datos de Tensorflow para leer el archivo TFRecords de listas de longitud variable. Aquí está mi código.

def _int64_feature(value):
    # value must be a numpy array.
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def main1():
    # Write an array to TFrecord.
    # a is an array which contains lists of variant length.
    a = np.array([[0, 54, 91, 153, 177],
                 [0, 50, 89, 147, 196],
                 [0, 38, 79, 157],
                 [0, 49, 89, 147, 177],
                 [0, 32, 73, 145]])

    writer = tf.python_io.TFRecordWriter('file')

    for i in range(a.shape[0]): # i = 0 ~ 4
        x_train = a[i]
        feature = {'i': _int64_feature(np.array([i])), 'data': _int64_feature(x_train)}

        # Create an example protocol buffer
        example = tf.train.Example(features=tf.train.Features(feature=feature))

        # Serialize to string and write on the file
        writer.write(example.SerializeToString())

    writer.close()

    # Check TFRocord file.
    record_iterator = tf.python_io.tf_record_iterator(path='file')
    for string_record in record_iterator:
        example = tf.train.Example()
        example.ParseFromString(string_record)

        i = (example.features.feature['i'].int64_list.value)
        data = (example.features.feature['data'].int64_list.value)
        #data = np.fromstring(data_string, dtype=np.int64)
        print(i, data)

    # Use Dataset API to read the TFRecord file.
    def _parse_function(example_proto):
        keys_to_features = {'i'   :tf.FixedLenFeature([], tf.int64),
                            'data':tf.FixedLenFeature([], tf.int64)}
        parsed_features = tf.parse_single_example(example_proto, keys_to_features)
        return parsed_features['i'], parsed_features['data']

    ds = tf.data.TFRecordDataset('file')
    iterator = ds.map(_parse_function).make_one_shot_iterator()
    i, data = iterator.get_next()
    with tf.Session() as sess:
        print(i.eval())
        print(data.eval())

Verifique el archivo TFRecord

[0] [0, 54, 91, 153, 177]
[1] [0, 50, 89, 147, 196]
[2] [0, 38, 79, 157]
[3] [0, 49, 89, 147, 177]
[4] [0, 32, 73, 145]

Pero mostró el siguiente error cuando intenté usar la API del conjunto de datos para leer el archivo TFRecord.

tensorflow.python.framework.errors_impl.InvalidArgumentError: Nombre:, Clave: datos, Índice: 0. Número de valores int64! = esperado. Tamaño de valores: 5 pero forma de salida: []

Gracias.
ACTUALIZAR: Intenté usar el siguiente código para leer TFRecord con Dataset API, pero ambos fallaron.

def _parse_function(example_proto):
    keys_to_features = {'i'   :tf.FixedLenFeature([], tf.int64),
                        'data':tf.VarLenFeature(tf.int64)}
    parsed_features = tf.parse_single_example(example_proto, keys_to_features)
    return parsed_features['i'], parsed_features['data']

ds = tf.data.TFRecordDataset('file')
iterator = ds.map(_parse_function).make_one_shot_iterator()
i, data = iterator.get_next()
with tf.Session() as sess:
    print(sess.run([i, data]))

o

def _parse_function(example_proto):
    keys_to_features = {'i'   :tf.VarLenFeature(tf.int64),
                        'data':tf.VarLenFeature(tf.int64)}
    parsed_features = tf.parse_single_example(example_proto, keys_to_features)
    return parsed_features['i'], parsed_features['data']

ds = tf.data.TFRecordDataset('file')
iterator = ds.map(_parse_function).make_one_shot_iterator()
i, data = iterator.get_next()
with tf.Session() as sess:
    print(sess.run([i, data]))

Y el error:

Rastreo (última llamada más reciente): archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/tensor_util.py", línea 468, en make_tensor_proto str_values = [compat.as_bytes (x) para x en proto_values] Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/tensor_util.py", línea 468, en str_values = [compat.as_bytes (x) para x en proto_values ] Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/util/compat.py", línea 65, en as_bytes (bytes_or_text,)) TypeError: Cadena binaria o unicode esperada, obtenida

Durante el manejo de la excepción anterior, se produjo otra excepción:

Rastreo (última llamada más reciente): Archivo "2tfrecord.py", línea 126, en main1 () Archivo "2tfrecord.py", línea 72, en main1 iterator = ds.map (_parse_function) .make_one_shot_iterator () Archivo "/ usr /local/lib/python3.5/dist-packages/tensorflow/python/data/ops/dataset_ops.py ", línea 712, en el mapa devuelve MapDataset (self, map_func) File" /usr/local/lib/python3.5 /dist-packages/tensorflow/python/data/ops/dataset_ops.py ", línea 1385, enen eso self._map_func.add_to_graph (ops.get_default_graph ()) Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/function.py", línea 486, en add_to_graph self._create_definition_if_needed () Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/function.py", línea 321, en _create_definition_if_needed self._create_definition_if_needed_impl () Archivo "/usr/local/lib/python3.5 /dist-packages/tensorflow/python/framework/function.py ", línea 338, en _create_definition_if_needed_impl salidas = self._func (* entradas) Archivo" /usr/local/lib/python3.5/dist-packages/tensorflow/python /data/ops/dataset_ops.py ", línea 1376, en tf_map_func flattened_ret = [ops.convert_to_tensor (t) para t en nest.flatten (ret)] Archivo" /usr/local/lib/python3.5/dist-packages /tensorflow/python/data/ops/dataset_ops.py ", línea 1376, en flattened_ret = [ops.convert_to_tensor (t) para t en nest.flatten (ret)] Archivo" /usr/local/lib/python3.5/ dist-packages / tensorflow / python / framework / ops.py ", línea 836, en convert_to_ tensor as_ref = False) Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", línea 926, en internal_convert_to_tensor ret = conversion_func (value, dtype = dtype, name = nombre, as_ref = as_ref) Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/constant_op.py", línea 229, en _constant_tensor_conversion_function return constant (v, dtype = dtype, name = nombre) Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/constant_op.py", línea 208, en valor constante, dtype = dtype, shape = shape, verificar_formar = verificar_forma))) Archivo "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/tensor_util.py", línea 472, en make_tensor_proto "tipo admitido". % (tipo (valores), valores)) TypeError: no se pudo convertir el objeto de tipo a Tensor. Contenido: SparseTensor (índices = Tensor ("ParseSingleExample / Slice_Indices_i: 0", shape = (?, 1), dtype = int64), values = Tensor ("ParseSingleExample / ParseExample / ParseExample: 3", shape = (?), dtype = int64), dense_shape = Tensor ("ParseSingleExample / Squeeze_Shape_i: 0", shape = (1,), dtype = int64)). Considere enviar elementos a un tipo compatible.

Versión de Python: 3.5.2
Versión de Tensorflow: 1.4.1

Respuestas a la pregunta(2)

Su respuesta a la pregunta