各位大佬,我使用Tensorflow2.2加载自己的数据集图片,在训练的时候报错。
英文报错:
ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 154587 but received input with shape [227, 681]
中文报错:
ValueError:密集层的输入0与层不兼容:输入形状的轴-1的值应为154587,但接收到形状为[227,681]的输入
import tensorflow as tf
import pathlib
import random
from tensorflow import keras
from tensorflow.keras import layers
train_path_raw = 'D:/深度学习/混凝土裂缝数据集/train_file'
train_date_root = pathlib.Path(train_path_raw)
train_image_paths = list(train_date_root.glob('*/*')) # 提取所有图片路径
train_image_paths = [str(path) for path in train_image_paths] # 修改图片路径的格式
random.shuffle(train_image_paths)
train_label_names = sorted(item.name for item in train_date_root.glob('*/') if item.is_dir())
train_label_index = dict((name, index) for index, name in enumerate(train_label_names))
train_all_labels = [train_label_index[pathlib.Path(path).parent.name] for path in train_image_paths]
image_count = len(train_all_labels)
print(image_count)
for image, label in zip(train_image_paths[0:5], train_all_labels[0:5]):
print(image, '---------', label)
# 创建一个Dataset,不过这个里面的元素只是图片路径,所以需要进一步转化(读取图片、设置图片大小、归一化、转化类型)
train_ds = tf.data.Dataset.from_tensor_slices((train_image_paths, train_all_labels))
# 自定义一个函数,处理图片
def load_and_preprocess_form_path_label(path, label):
image = tf.io.read_file(path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, [227, 227])
image /= 255.0
return image, label
train_data = train_ds.map(load_and_preprocess_form_path_label)
model = keras.Sequential([
layers.Flatten(input_shape=(227, 227, 3)),
layers.Dense(128, activation='relu'),
layers.Dense(2, activation='softmax')
])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(train_data, epochs=10)