Keras-组合模型如何仅提取自动编码器上的部分

Keras- Combined model how to extract only portion on autoencoder

我使用 KERAS 编译了 2 个模型(分类和自动编码器),我能够评估模型并且没有问题 运行ning 如下所示。

   model.compile(loss={'classification': 'categorical_crossentropy', 
                        'autoencoder': 'mean_squared_error'},
                  optimizer='adam',
                  metrics={'classification': 'accuracy'})

history = model.fit(x_train, 
          {'classification': y_train, 'autoencoder': x_train},
          batch_size=300,
          epochs=1,
          validation_data= (x_test, {'classification': y_test}),
          verbose=1)

第二部分要求我仅利用自动编码器上的模型部分,并可视化 8 个图像样本。请参考下面的代码,它不能 运行 因为代码是针对整个模型的,我如何只提取自动编码器上的模型部分来绘制图像?

# Generate reconstructions
num_reconstructions = 8
samples = x_test[:num_reconstructions]
targets = y_test[:num_reconstructions]
reconstructions = model.autoencoder.predict(samples)

import numpy as np

# Plot reconstructions
for i in np.arange(0, num_reconstructions):
  # Get the sample and the recoax = pp.subplot(111)nstruction
  sample = samples[i][:, :, 0]
  reconstruction = reconstructions[i][:, :, 0]
  input_class = targets[i]
  # Matplotlib preparations
  fig, axes = plt.subplots(1, 2)
  # Plot sample and reconstruciton
  axes[0].imshow(sample)
  axes[0].set_title('Original image')
  axes[1].imshow(reconstruction)
  axes[1].set_title('Reconstruction with Conv2DTranspose')
  fig.suptitle(f'MNIST target = {input_class}')
  plt.show()

我的网络架构师见下:

这可以毫无问题地完成

我重新推荐你模型的一个版本:

inp = Input((28,28,1))
enc = Conv2D(63, 3, padding='same')(inp)
enc = MaxPool2D()(enc)

clas = Flatten()(enc)
clas = Dense(1000)(clas)
clas = Dropout(0.3)(clas)
clas = Dense(10, activation='softmax', name='classification')(clas)

dec = Dense(1000)(enc)
dec = Conv2DTranspose(63, 3, padding='same')(dec)
dec = Conv2D(1, 3, padding='same')(dec)
dec = UpSampling2D(name='autoencoder')(dec)

model = Model(inp, [clas,dec])
model.compile(loss={'classification': 'sparse_categorical_crossentropy', 'autoencoder': 'mean_squared_error'},
                  optimizer='adam',
                  metrics={'classification': 'accuracy'})

我创建虚拟数据并拟合整个结构(分类 + 自动编码器)

X = np.random.uniform(0,1, (8,28,28,1))
y = np.random.randint(0,10, 8)

model.fit(X, [y,X], epochs=3)
prob, rec1 = model.predict(X)

拟合后我只提取自动编码器部分

autoenc = Model(inp, dec)
rec2 = autoenc.predict(X)

检查结果(rec1 必须等于 rec2)

(rec1 == rec2).all() # True ===> correct

此处是完整的 运行 示例:https://colab.research.google.com/drive/12CJzXHz8fdjAv2Jvmp5IV_D-UDiHWtTY?usp=sharing