'Extracting the bottleneck layer oy my autoencoder model
I am trying to extract the flattened (bottleneck) layer of my auto-encoder for bio-image shape analysis. The goal is to be able to extract the bottleneck layer of thousand of images to study the variability of the values of the bottleneck layers knowing other informations about the patient.
I've heard that auto-encoder are interesting for this because of their dimensionality reduction. I've trained an auto-encoder on a single image just for testing it. I want to extract the bottleneck layer in she shape of a value array or a grayscale array.
Here's my code :
from matplotlib.pyplot import imshow
import numpy as np
import cv2
from keras.preprocessing.image import img_to_array
from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.models import Sequential
np.random.seed(42)
SIZE=256
img_data=[]
img=cv2.imread('/content/drive/MyDrive/CNN/Test/yes/image100704_71.png', 1) #Change 1 to 0 for grey images
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #Changing BGR to RGB to show images in true colors
img=cv2.resize(img,(SIZE, SIZE))
img_data.append(img_to_array(img))
img_array = np.reshape(img_data, (len(img_data), SIZE, SIZE, 3))
img_array = img_array.astype('float32') / 255.
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(SIZE, SIZE, 3)))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D((2, 2), padding='same'))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(8, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D((2, 2)))
model.add(Conv2D(3, (3, 3), activation='relu', padding='same'))
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
model.summary()
model.fit(img_array, img_array,
epochs=300,
shuffle=True)
print("Neural network output")
pred = model.predict(img_array)
imshow(pred[0].reshape(SIZE,SIZE,3), cmap="gray")
Do you know what should I precisely change to have the desired output ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|