text_plain_output_1.png
from keras.layers import Conv2D, MaxPooling2D, GlobalMaxPooling2D

from keras.layers import Input, UpSampling2D

from keras.models import Sequential, load_model, Model

from matplotlib import cm

import h5py

import matplotlib.pylab as plt

import numpy as np

import pandas as pd

data = pd.read_csv('../input/letters.csv')
files = data['file']
letters = data['letter']
backgrounds = data['background']

f = h5py.File('../input/LetterColorImages.h5', 'r')
keys = list(f.keys())
keys

backgrounds = np.array(f[keys[0]])
tensors = np.array(f[keys[1]])
targets = np.array(f[keys[2]])

# Plot letter images
fig, ax = plt.subplots(figsize=(18, 3), nrows=1, ncols=5, sharex=True, sharey=True,)
ax = ax.flatten()
for i in range(5):
    image = tensors[i*200]/255
    ax[i].imshow(image)

ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.gcf()
ax[2].set_title('Examples of letters', fontsize=25);

def autoencoder():
    inputs = Input(shape=(32, 32, 1))
    x = Conv2D(32, 3, activation='relu', padding='same')(inputs)
    x = MaxPooling2D(padding='same')(x)
    x = Conv2D(16, 3, activation='relu', padding='same')(x)
    x = MaxPooling2D(padding='same')(x)
    x = Conv2D(8, 3, activation='relu', padding='same')(x)
    encoded = MaxPooling2D(padding='same')(x)
    x = Conv2D(8, 3, activation='relu', padding='same')(encoded)
    x = UpSampling2D()(x)
    x = Conv2D(16, 3, activation='relu', padding='same')(x)
    x = UpSampling2D()(x)
    x = Conv2D(32, 3, activation='relu', padding='same')(x)
    x = UpSampling2D()(x)
    decoded = Conv2D(1, 3, activation='sigmoid', padding='same')(x)
    autoencoder = Model(inputs, decoded)
    autoencoder.compile(optimizer='nadam', loss='binary_crossentropy')
    return autoencoder

autoencoder = autoencoder()
autoencoder.summary()

autoencoder_history = autoencoder.fit(x_train, x_train, epochs=200, batch_size=64, verbose=0, validation_data=(x_valid, x_valid))

x_test_decoded = autoencoder.predict(x_test)

# Plot original grayscaled images
fig, ax = plt.subplots(figsize=(18, 3), nrows=1, ncols=5, sharex=True, sharey=True,)
ax = ax.flatten()
for i in range(5):
    image = x_test[i*10].reshape(32,32)
    ax[i].imshow(image, cmap=cm.bone)

ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.gcf()
ax[2].set_title('Examples of original grayscaled letters', fontsize=25);

fig, ax = plt.subplots(figsize=(18, 3), nrows=1, ncols=5, sharex=True, sharey=True)
ax = ax.flatten()
for i in range(5):
    image = x_test_decoded[i * 10].reshape(32, 32)
    ax[i].imshow(image, cmap=cm.bone)
ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.gcf()
ax[2].set_title('Examples of decoded grayscaled letters', fontsize=25)