需要一个类似字节的对象,而在热切模式下在字符串张量上调用map时不是'Tensor'

问题描述 投票:4回答:1

我正在尝试使用TF.dataset.map来移植此旧代码,因为我收到了弃用警告。

从TFRecord文件读取一组自定义原型的旧代码:

record_iterator = tf.python_io.tf_record_iterator(path=filename)
for record in record_iterator:
    example = MyProto()
    example.ParseFromString(record)

我正在尝试使用急切模式和地图,但出现此错误。

def parse_proto(string):
      proto_object = MyProto()
      proto_object.ParseFromString(string)
dataset = tf.data.TFRecordDataset(dataset_paths)
parsed_protos = raw_tf_dataset.map(parse_proto)

此代码有效:

for raw_record in raw_tf_dataset:                                                                                                                                         
    proto_object = MyProto()                                                                                                                                              
    proto_object.ParseFromString(raw_record.numpy())                                                                                                                                 

但是地图给我一个错误:

TypeError: a bytes-like object is required, not 'Tensor'

使用参数作为地图函数结果并将其视为字符串的正确方法是什么?

tensorflow tensorflow-datasets
1个回答
0
投票

您需要从张量提取字符串并在map函数中使用。以下是要在代码中实现此目标的步骤。

  1. 您必须用tf.py_function(get_path, [x], [tf.float32])装饰地图功能。您可以找到有关tf.py_function here的更多信息。在tf.py_function中,第一个参数是map函数的名称,第二个参数是要传递给map函数的元素,而最后一个参数是返回类型。
  2. 您可以通过使用地图功能中的bytes.decode(file_path.numpy())来获得琴弦部分。

因此,如下修改程序,

parsed_protos = raw_tf_dataset.map(parse_proto)

parsed_protos = raw_tf_dataset.map(lambda x: tf.py_function(parse_proto, [x], [function return type]))

也如下修改parse_proto

def parse_proto(string):
      proto_object = MyProto()
      proto_object.ParseFromString(string)

to

def parse_proto(string):
      proto_object = MyProto()
      proto_object.ParseFromString(bytes.decode(string.numpy()))

在下面的简单程序中,我们使用tf.data.Dataset.list_files读取图像的路径。接下来,在map功能中,我们使用load_img读取图像,然后再执行tf.image.central_crop功能以裁剪图像的中央部分。

代码-

%tensorflow_version 2.x
import tensorflow as tf
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = img_to_array(image)
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)

输出-

enter image description here

希望这能回答您的问题。祝您学习愉快。

© www.soinside.com 2019 - 2024. All rights reserved.