我对自编码器是新手。我已经构建了一个简单的卷积自编码器,如下所示:
# ENCODERinput_img = Input(shape=(64, 64, 1))encode1 = Conv2D(32, (3, 3), activation=tf.nn.leaky_relu, padding='same')(input_img) encode2 = MaxPooling2D((2, 2), padding='same')(encode1)l = Flatten()(encode2)l = Dense(100, activation='linear')(l)# DECODERd = Dense(1024, activation='linear')(l) d = Reshape((32,32,1))(d)decode3 = Conv2D(64, (3, 3), activation=tf.nn.leaky_relu, padding='same')(d) decode4 = UpSampling2D((2, 2))(decode3)model = models.Model(input_img, decode4)model.compile(optimizer='adam', loss='mse')# Train it by providing training imagesmodel.fit(x, y, epochs=20, batch_size=16)
现在,在训练了这个模型之后,我想获取瓶颈层(即全连接层)的输出。这意味着,如果我输入形状为(1000, 64, 64)的数组到模型中,我希望得到形状为(1000, 100)的压缩数组。
我尝试了一种方法,如下所示,但它出现了一些错误。
model = Model(inputs=[x], outputs=[l])
错误信息如下:
ValueError: Input tensors to a Functional must come from `tf.keras.Input`.
我还尝试了一些其他方法,但也未能成功。有人能告诉我如何在训练模型后获取压缩数组吗?
回答:
您需要为encoder
创建一个独立的模型。在训练了整个encoder-decoder
系统后,您可以仅使用encoder
进行预测。代码示例如下:
# ENCODERinput_img = layers.Input(shape=(64, 64, 1))encode1 = layers.Conv2D(32, (3, 3), activation=tf.nn.leaky_relu, padding='same')(input_img) encode2 = layers.MaxPooling2D((2, 2), padding='same')(encode1)l = layers.Flatten()(encode2)encoder_output = layers.Dense(100, activation='linear')(l)# DECODERd = layers.Dense(1024, activation='linear')(encoder_output) d = layers.Reshape((32,32,1))(d)decode3 = layers.Conv2D(64, (3, 3), activation=tf.nn.leaky_relu, padding='same')(d) decode4 = layers.UpSampling2D((2, 2))(decode3)model_encoder = Model(input_img, encoder_output)model = Model(input_img, decode4)model.fit(X, y, epochs=20, batch_size=16)
model_encoder.predict(X)
应该为每张图像返回一个向量。