In the following code I have defined a Sequential model, that contains two parts conv_encoder and conv_decoder. After training the model I want to use conv_encoder to predict.
How Can I access the trained conv_encoder? (See the last line of the code bellow)
And also I want to it from inside of a fucntion.
from tensorflow.keras.layers import Conv2D, Flatten ,BatchNormalization ,MaxPooling2D
from tensorflow.keras.layers import Reshape, Conv2DTranspose
# network parameters
input_shape = (200,300,3)
batch_size = 20
import tensorflow as tf
import keras
from keras.applications.vgg16 import VGG16
from skimage.feature import hog
import pandas as pd
# Defining a custom metric
def rounded_accuracy(y_true, y_pred):
return keras.metrics.binary_accuracy(tf.round(y_true), tf.round(y_pred))
# Create the CAE model
def create_cae():
# Define encoder
conv_encoder = keras.models.Sequential([
keras.layers.Conv2D(256, kernel_size=3, padding="SAME", activation="relu", input_shape=[200, 300, 3]),
keras.layers.BatchNormalization(),
keras.layers.Conv2D(128, kernel_size=3, padding="SAME", activation="relu"),
keras.layers.MaxPool2D(pool_size=2),
keras.layers.Conv2D(64, kernel_size=3, padding="SAME", activation="relu"),
keras.layers.BatchNormalization(),
keras.layers.MaxPool2D(pool_size=2),
])
# Define decoder
conv_decoder = keras.models.Sequential([
keras.layers.Conv2DTranspose(128, kernel_size=3, strides=2, padding="SAME", activation="relu",input_shape=[50, 75, 64]),
keras.layers.BatchNormalization(),
keras.layers.Conv2DTranspose(256, kernel_size=3, strides=2, padding="SAME", activation="relu"),
keras.layers.BatchNormalization(),
keras.layers.Conv2DTranspose(3, kernel_size=3, strides=1, padding="SAME", activation="sigmoid"),
])
# Define AE
conv_ae = keras.models.Sequential([conv_encoder, conv_decoder])
# Display the model's architecture
conv_encoder.summary()
conv_decoder.summary()
# Compile the model
conv_ae.compile(loss="mse", optimizer=keras.optimizers.Adam(),
metrics=[rounded_accuracy])
return conv_ae
# Create CAE
conv_ae = create_cae()
print("New CAE model created")
history=conv_ae.fit(gaussian_noise_imgs,sample_train_imgs,epochs=5)
sample_train = conv_ae.predict(gaussian_noise_imgs)
N_bin=50
F= encoder.predict( sample_train )
CodePudding user response:
After training your model, you can retrieve the encoder from the trained model like so:
encoder = keras.Model(inputs=conv_ae.layers[0].input, outputs=conv_ae.layers[0].layers[-1].output)
CodePudding user response: