gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Give a python code of autoencoders
- User
Give a python code of autoencoders
- Assistant
Give a python code of autoencoders
Sure! Below is an example of a simple autoencoder implemented in Python using TensorFlow and Keras. This autoencoder will be trained on the MNIST dataset, a popular dataset of handwritten digits. The goal of the autoencoder is to learn a compressed representation of the input images.
First, make sure you have TensorFlow installed. You can install it using pip if you haven't already:
pip install tensorflow
Then, you can use the following code for the autoencoder:
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
# Load the MNIST dataset
(x_train, _), (x_test, _) = keras.datasets.mnist.load_data()
# Normalize and reshape the data
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = np.reshape(x_train, (len(x_train), 28 * 28))
x_test = np.reshape(x_test, (len(x_test), 28 * 28))
# Define the size of the encoded representation
encoding_dim = 32 # 32 floats is compression from 784 dimensions to 32 dimensions
# Define the autoencoder model
input_img = layers.Input(shape=(784,))
encoded = layers.Dense(encoding_dim, activation='relu')(input_img)
decoded = layers.Dense(784, activation='sigmoid')(encoded)
autoencoder = keras.Model(input_img, decoded)
# Define the encoder model
encoder = keras.Model(input_img, encoded)
# Compile the autoencoder
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
# Train the autoencoder
autoencoder.fit(x_train, x_train,
epochs=50,
batch_size=256,
shuffle=True,
validation_data=(x_test, x_test))
# Encode and decode some digits
encoded_imgs = encoder.predict(x_test)
decoded_imgs = autoencoder.predict(x_test)
# Display original and reconstructed images
n = 10 # number of digits to display
plt.figure(figsize=(20, 4))
for i in range(n):
# Display original
ax = plt.subplot(2, n, i + 1)
plt.imshow(x_test[i].reshape(28, 28), cmap='gray')
plt.title("Original")
plt.axis('off')
# Display reconstruction
ax = plt.subplot(2, n, i + 1 + n)
plt.imshow(decoded_imgs[i].reshape(28, 28), cmap='gray')
plt.title("Reconstructed")
plt.axis('off')
plt.show()
Feel free to modify the encoding_dim, increase or decrease the number of epochs, or adjust other parameters to see how it affects the performance!