【问题标题】:Joining string and tf.string to get a path连接字符串和 tf.string 以获得路径
【发布时间】:2019-07-26 16:43:47
【问题描述】:

我正在使用tensorflow.Data API 处理一个 csv 文件。 csv 中的一个特征是图像名称。为了加载图像,我需要构建一个将基本文件夹与图像名称相结合的路径。但是,由于图像名称是张量并且基本文件夹是字符串,因此我无法使用 os.path.join 将它们连接起来。我包括下面的代码。

def process_csv_data(folder_path, image_dimensions):
    width, height, channels = image_dimensions
    def map_function(raw_data):
        image_path = os.path.join(folder_path,raw_data['image_name'].numpy().decode('utf-8'))
        image = tf.io.read_file(image_path)
        image = tf.image.decode_jpeg(image, channels=channels)
        image = tf.image.resize(image, [width, height])
        image /= 255.0  # normalize to [0,1] range
        return image
    return map_function

前一个函数使用如下:

    raw_csv_dataset = tf.data.experimental.make_csv_dataset(
        csv_path,
        batch_size=1,
        column_names=CSV_COLUMNS,
        shuffle=False)

    dataset = raw_csv_dataset.map(
         process_csv_data(folder_path, image_dimensions, mode),
         num_parallel_calls=tf.data.experimental.AUTOTUNE)

上面的代码产生了这个错误:

AttributeError: 'Tensor' 对象没有属性 'numpy'

我尝试了几种方法都没有成功,比如将文件夹名称转换为张量并使用tf.strings.join,或者将tf.string 转换为标准python string。那么,什么是正确的方法?

我正在使用 tensorflow 2.0

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    只需将字符串与+ 连接:

    image_path = folder_path + os.sep + raw_data['image_name']
    

    如果您确实需要路径分隔符(以防它不包含在folder_path 中)并且不想显式使用/\,请使用os.sep

    【讨论】:

    • 导致另一个错误:ValueError: Shape must be rank 0 but is rank 1 for 'ReadFile' (op: 'ReadFile') with input shapes: [1] in line image = tf.io.read_file(image_path)
    • @magomar 这是一个不同的、不相关的错误。 raw_data['image_name'] 应该是一个“标量”字符串(不是字符串数组),否则不能传递给 read_file。这取决于数据本身(map_functionraw_data 中接收的内容)。如果它是一个带有单个字符串的数组(例如['my_file.csv']),您可以使用image = tf.io.read_file(tf.squeeze(image_path)) 修复它。
    • raw_data 是一个有序字典,其中 'image_name' 是一个特征(csv 中的一列)。无论如何,我用tf.reshape(image_path, []) 修复了这个错误,在这种情况下它相当于 tf.squeeze。现在解决了,谢谢。
    猜你喜欢
    • 2015-05-13
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2016-12-26
    • 2011-06-27
    相关资源
    最近更新 更多