如何在TensorFlow Datasets中修改decoder的特征输出类型?
问题根因
你的报错和decoder返回类型无关,是你自定义的map_data转换没有正确应用到TFDS加载的数据集上,导致遍历的时候拿到的还是TFDS原始输出的image、label键,和模型预期的image_input输入键不匹配。
解决方案
1. 正确构造数据集pipeline
TFDS加载数据集后,必须显式调用.map()方法应用你写的map_data函数,同时要补全numpy_function返回后的shape定义,避免后续操作丢失shape信息,参考代码如下:
import tensorflow as tf import tensorflow_datasets as tfds # 按你的数据集替换实际类别数,比如cifar10为10 num_classes = 10 # 你的自定义增强逻辑,这里仅做示例 def aug_fn(image): return image def map_data(inputs): image = inputs['image'] image = tf.numpy_function(func=aug_fn, inp=[image], Tout=tf.float32) # 补全shape定义,按你使用的数据集实际图像尺寸修改,比如cifar10为32*32*3 image.set_shape([32, 32, 3]) image = image / 255.0 labels = inputs['label'] labels = tf.one_hot(labels, num_classes) return {'image_input': image, 'label': labels}, labels # 加载数据集后必须调用map应用转换 ds = tfds.load('cifar10', split='train', shuffle_files=True) ds = ds.map(map_data, num_parallel_calls=tf.data.AUTOTUNE) # 后续正常加batch、prefetch等操作 ds = ds.batch(32).prefetch(tf.data.AUTOTUNE)
2. 如需修改decoder输出类型的操作
如果你确实需要调整decoder的输出类型,不需要直接修改decoder对象属性,直接在tfds.load时通过decoders参数配置即可,参考代码如下:
ds = tfds.load( 'cifar10', split='train', decoders={ # 跳过默认的uint8解码,后续自行处理解码逻辑 'image': tfds.decode.SkipDecoding(), } ) # 在map函数中手动解码并指定输出类型 def map_data(inputs): image = tf.image.decode_png(inputs['image'], channels=3) image = tf.cast(image, tf.float32) # 后续增强、归一化逻辑和之前一致 ...
3. 确认模型输入层配置
检查你使用的Keras模型输入层的name参数是否为image_input,和你返回的字典键保持一致,示例如下:
# 输入层name必须和返回的键匹配 input_layer = tf.keras.Input(shape=(32,32,3), name='image_input') # 后续模型结构定义 ...
内容的提问来源于stack exchange,提问作者Olli
相关产品推荐
相关产品推荐

