我试图使用keras model.fit_generator()来拟合模型,下面是我对生成器的定义:
from sklearn.utils import shuffle
IMG_PATH_PREFIX = "./data/IMG/"
def generator(samples, batch_size=64):
num_samples = len(samples)
while 1: # Loop forever so the generator never terminates
shuffle(samples)
for offset in range(0, num_samples, batch_size):
batch_samples = samples[offset:offset+batch_size]
images = []
angles = []
for batch_sample in batch_samples:
name = IMG_PATH_PREFIX + batch_sample[0].split('/')[-1]
center_image = cv2.imread(name)
center_angle = float(batch_sample[3])
images.append(center_image)
angles.append(center_angle)
X_train = np.array(images)
y_train = np.array(angles)
#X_train = np.expand_dims(X_train, axis=0)
#y_train = np.expand_dims(y_train, axis=1)
print("X_train shape: ", X_train.shape, " y_train shape:", y_train.shape)
#print("X train: ", X_train)
yield X_train, y_train
train_generator = generator(train_samples, batch_size = 32)
validation_generator = generator(validation_samples, batch_size = 32)
这里的输出形状是: X_train形状:(32,160,320,3)y_train形状:(32,)
模型拟合代码是:
model = Sequential()
#cropping layer
model.add(Cropping2D(cropping=((50,20), (1,1)), input_shape=(160,320,3), dim_ordering='tf'))
model.compile(loss = "mse", optimizer="adam")
model.fit_generator(train_generator, samples_per_epoch= len(train_samples), validation_data=validation_generator, nb_val_samples=len(validation_samples), nb_epoch=3)
然后我收到错误消息:
ValueError:检查模型目标时出错:预期cropping2d_6有4个维度,但得到的数组有形状(32,1)
有人可以帮我告诉我这是什么问题吗?
答案 0 :(得分:1)
这里最大的问题是:你知道你想做什么吗?
1)如果你读here,输入是4D张量,输出也是4D张量。您的目标是2D张量形状(batch_size,1)。所以当然,当keras尝试计算具有3D(没有批量维度)的输出和具有1D(没有批量维度)的目标之间的误差时,它无法理解。输出和目标必须具有相同的尺寸。
2)你知道cropping2D究竟在做什么吗?它正在裁剪您的图像...因此删除裁剪尺寸开始和结束时的值。在您的情况下,您正在输出形状的图像(90,218,3)。这不是一个预测,没有重量训练在这一层,所以没有理由适应"模型"。你的模型只是剪裁图像。不需要培训。