我正在使用可变自动编码器,并希望适应a Keras example found on GitHub。
[基本上,该示例基于mnist数据集非常简单,我希望在更困难的集合上实现,因为它更现实。
我正在尝试修改的代码:
vae_dfc.fit(
x_train,
epochs=epochs,
steps_per_epoch=train_size//batch_size,
validation_data=(x_val),
validation_steps=val_size//batch_size,
verbose=1
)
对于更复杂的数据集,几乎不可能将所有内容加载到内存中,因此我们需要使用fit_generator()
来训练模型。但这似乎无法处理:
image_generator = image.ImageDataGenerator(
rescale=1./255,
validation_split=0.2
)
train_generator = image_generator.flow_from_directory(
dir,
class_mode=None,
color_mode='rgb',
target_size=(ORIGINAL_SHAPE[0], ORIGINAL_SHAPE[1]),
batch_size=BATCH_SIZE,
subset='training'
)
vae.fit_generator(
train_generator,
epochs=EPOCHS,
steps_per_epoch=train_generator.samples // BATCH_SIZE,
validation_data=validation_generator,
validation_steps=validation_generator.samples // BATCH_SIZE
)
我的理解是,class_mode=None
正在产生类似于原始简单示例的输出,但是fit_generator()
无法处理此问题。是否有任何解决方法来处理拟合生成器错误?
配置:
tensorflow-gpu==1.12.0
Python 3.6
Windows 10
Cuda 9.0
完整错误:
文件“ xxx \ venv \ lib \ site-packages \ tensorflow \ python \ keras \ engine \ training.py”,在fit_generator中的第2177行initial_epoch = initial_epoch)文件“ xxx \ venv \ lib \ site-packages \ tensorflow \ python \ keras \ engine \ training_generator.py”,在fit_generator中的第162行'或[C0]。找到:'+ str(generator_output))ValueError:发电机的输出应为元组
(x, y)
或(x, y, sample_weight)
。找到:[[[[[0.48627454 0.34901962 0.2901961] ....]]]
自动编码器需要(x, y)
。它不同于没有输出。
我相信您可以尝试outputs = inputs
。
如果这不起作用,您可以创建一个包装生成器以同时输出两者:
class_mode='input'
当然,这两个选项都需要模型具有输出。如果创建的模型没有输出(异常),请使其输出结果,并使用class AutoencGenerator(keras.utils.Sequence):
def __init__(self, originalGenerator):
self.generator = originalGenerator
def __len__(self):
return len(self.generator)
def __getitem__(self, i):
x = self.generator[i]
return x, x
def on_epoch_end(self):
self.generator.on_epoch_end() #this only if there is an on_epoch_end in the original
train_autoenc_generator = AutoencGenerator(train_generator)
中的损失函数。
model.compile(loss=the_loss)
与发电机一起训练:
inputs = Input(shape)
means, sigmas = encoder(inputs)
def encode(x):
means, sigmas = x
randomSamples = tf.random_normal(K.shape(means)) #samples
encoded = (sigmas * randomSamples) + means
return encoded
encodings = Lambda(encode)([means, sigmas])
outputs = decoder(encodings)
kl_loss = some_tensor_function(means, sigmas)
VAE = Model(inputs, outputs)
VAE.add_loss(kl_loss)
VAE.compile(loss = 'mse', optimizer='adam')