在尝试拟合我的模型时,我得到了不兼容的形状。 我正在使用具有 CNN 架构 (Vgg16) 的一类分类。 通过函数 wrap_generator() 生成假标签以创建 2 个输出。 Keras 版本 = 2.2.5 Tensorflow 版本 = 2.1.0
这是我的脚本
:show
当我尝试拟合模型时,出现以下错误:
tf.compat.v1.disable_eager_execution()
SHAPE = (224,224,3)
batch_size = 2
def get_model(train=True):
pre_process = Lambda(preprocess_input)
vgg = VGG16(weights = 'imagenet', include_top = True, input_shape = SHAPE)
vgg = Model(vgg.input, vgg.layers[-3].output)
vgg.trainable = False
inp = Input(SHAPE)
vgg_16_process = pre_process(GaussianNoise(0.1)(inp))
vgg_out = vgg(vgg_16_process)
noise = Lambda(tf.zeros_like)(vgg_out)
noise = GaussianNoise(0.1)(noise)
if train:
x = Lambda(lambda z: tf.concat(z, axis=0))([vgg_out,noise])
x = Activation('relu')(x)
else:
x = vgg_out
x = Dense(512, activation='relu')(x)
x = Dense(128, activation='relu')(x)
out = Dense(2, activation='softmax')(x)
model = Model(inp, out)
model.compile(Adam(lr=1e-4), loss='binary_crossentropy')
return model
train_datagen = ImageDataGenerator()
test_datagen = ImageDataGenerator()
def wrap_generator(generator):
while True:
x,y = next(generator)
zeros = tf.zeros_like(y) + tf.constant([1.,0.])
y=tf.constant([1.,0.])
x= np.array(x)
an_array = y.eval(session=tf.compat.v1.Session())
from keras.utils import to_categorical
an_array = to_categorical(an_array)
yield (x, an_array)
train_generator = train_datagen.flow_from_directory(
'..\\dataset\\train\\',
target_size = (SHAPE[0], SHAPE[1]),
batch_size = batch_size,
class_mode = 'categorical',
shuffle = True,
seed = 3,
classes = ['0_ok']
)
test_generator = test_datagen.flow_from_directory(
'..\\dataset\\test\\',
target_size = (SHAPE[0], SHAPE[1]),
batch_size = batch_size,
class_mode = 'categorical',
shuffle = True,
seed = 3,
classes = ['0_ok', '1_nok']
)
tf.random.set_seed(3)
os.environ['PYTHONHASHSEED'] = str(2)
np.random.seed(3)
random.seed(3)
session_conf = tf.compat.v1.ConfigProto(
intra_op_parallelism_threads=1,
inter_op_parallelism_threads=1
)
sess = tf.compat.v1.Session(
graph=tf.compat.v1.get_default_graph(),
config=session_conf
)
tf.compat.v1.keras.backend.set_session(sess)
model = get_model()
model.fit(wrap_generator(train_generator), steps_per_epoch=train_generator.samples/train_generator.batch_size, epochs=2)
我确认我的训练样本数量是批量大小的倍数。 我验证了在 train 目录中创建的类与脚本中的相同。 当我显示我的输入形状时,我的输出形状得到了 (2,224,224,3) 和 (2,2)。 len(输入)= len(输出)= 2 我试图将 Flatten 添加到我的输入中,但我仍然有同样的错误。 如何修复此错误?