我正在尝试运行TF中的以下教程:加载图像。
我正在运行第二种方法(使用tf.data进行更精细的控制)。
提供的教程在使用Dataset.map
来“创建图像和标签对的数据集”之前运行正常。在这里,TF提供了以下函数来使用Dataset.map
:
def get_label(file_path): # 将路径转换为路径组件列表 parts = tf.strings.split(file_path, os.path.sep) # 倒数第二个是类别目录 one_hot = parts[-2] == class_names # 整数编码标签 return tf.argmax(one_hot)def decode_img(img): # 将压缩字符串转换为3D uint8张量 img = tf.image.decode_jpeg(img, channels=3) # 将图像调整到所需大小 return tf.image.resize(img, [img_height, img_width])def process_path(file_path): label = get_label(file_path) # 从文件中加载原始数据为字符串 img = tf.io.read_file(file_path) img = decode_img(img) return img, label
当我运行示例时,我得到了以下错误:
train_ds = train_ds.map(process_path, num_parallel_calls = AUTOTUNE)TypeError: 传递给参数'input'的值的数据类型为'bool',不在允许的值列表中:float32, float64...
由于这是直接来自TF网站的教程,我不确定我哪里做错了。有没有想法?数据目录的结构与教程中完全相同:
flowers_photos/daisy/dandelion/roses/sunflowers/tulips/
更新1
尝试@***的回答后的输出:
for image, label in train_ds.take(5): print("图像形状: ", image.numpy().shape) print("标签: ", label.numpy () )图像形状: (180, 180, 3)标签: [[1.0 0 0 0 0]]图像形状: (180, 180, 3)标签: [[0. 0. 0. 1. 0.]]图像形状: (180, 180, 3)标签: [[1. 0. 0. 0. 0.]]图像形状: (180, 180, 3)标签: [[0. 0. 1. 0. 0.]]图像形状: (180, 180, 3)标签: [[0. 0. 1. 0. 0.]]
应该类似于:图像形状: (180, 180, 3)
标签: 4
更新2
看起来以上并不符合要求,导致模型失败:
class_names = np.array(sorted([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"]))print(class_names)['daisy' 'dandelion' 'roses' 'sunflowers' 'tulips']print(len(class_names))5...model.fit(train_ds,validation_data=val_ds,epochs=15)InvalidArgumentError: Logits和labels必须具有相同的第一维度,得到的logits形状为[5,5],labels形状为[25]
回答:
更新3(最终)
发现TensorFlow在这里有一个选项可以传递,特别是给tf.io.decode_png。
tf.io.decode_png( contents, channels=0, dtype=tf.dtypes.uint8, name=None)
在将dtype更改为tf.dtypes.uint16后,没有问题了。希望这对未来有帮助的人有用。