如何解决AttributeError: 'BatchDataset'对象无shape属性错误?
问题解决:AttributeError: 'BatchDataset' object has no attribute 'shape'
错误原因
tf.keras.utils.image_dataset_from_directory返回的是**tf.data.BatchDataset对象**,而非单一张量或numpy数组,这类数据集对象没有直接的.shape属性,不能像处理单一张量那样调用tf.reshape。- 代码存在逻辑错误:将测试目录的数据赋值给
train_labels,混淆了训练集与测试集的加载逻辑。
修正方案
直接利用image_dataset_from_directory的参数完成图像尺寸统一,再通过map函数对数据集做归一化处理,无需手动提取张量或修改形状:
# 正确加载训练集和测试集,同时指定统一图像尺寸 train_dataset = tf.keras.utils.image_dataset_from_directory( '/content/drive/MyDrive/ArabicHandwritten2/train', image_size=(256, 256), # 加载时直接将图像resize到目标尺寸 batch_size=32 ) test_dataset = tf.keras.utils.image_dataset_from_directory( '/content/drive/MyDrive/ArabicHandwritten2/test', image_size=(256, 256), batch_size=32 ) # 定义归一化函数,处理每个批次的图像和标签 def normalize_images(image, label): image = tf.cast(image, tf.float32) image = (image - 127.5) / 127.5 # 归一化到[-1, 1]区间 return image, label # 对数据集应用归一化,并打乱训练集 train_dataset = train_dataset.map(normalize_images).shuffle(16765) test_dataset = test_dataset.map(normalize_images)
额外说明
如果需要查看数据集的张量形状,可以提取一个批次进行查看:
# 取第一个批次的图像和标签,打印形状 for images, labels in train_dataset.take(1): print(f"单批次图像形状: {images.shape}") print(f"单批次标签形状: {labels.shape}")
内容的提问来源于stack exchange,提问作者Modi
相关产品推荐
相关产品推荐

