Skip to content

Instantly share code, notes, and snippets.

@thebabush
Last active April 16, 2016 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebabush/7a9848532856e5aa81ff02f15a50abc1 to your computer and use it in GitHub Desktop.
Save thebabush/7a9848532856e5aa81ff02f15a50abc1 to your computer and use it in GitHub Desktop.
Keras: get hidden layer's output (autoencoder)
#!/usr/bin/env python
import keras
import keras.callbacks
import keras.models
import keras.optimizers
import keras.layers
import numpy as np
import theano
data = np.load("data.npy")
np.random.shuffle(data)
xx = data[:, :-1]
yy = data[:, -1]
data = None
def build(features):
m = keras.models.Sequential()
m.add(keras.layers.Dense(50, input_shape=(features,), activation='sigmoid'))
m.add(keras.layers.Dropout(p=0.1))
m.add(keras.layers.Dense(features, activation='linear'))
m.compile(optimizer=keras.optimizers.Adagrad(), loss='mse')
return m
early = keras.callbacks.EarlyStopping(
monitor='val_loss', patience=10, verbose=1, mode='min'
)
model = build(xx.shape[1])
model.fit(xx, xx, batch_size=2000, nb_epoch=10000, validation_split=0.1, callbacks=[early])
get_activations = theano.function([model.layers[0].input], model.layers[0].get_output(train=False), allow_input_downcast=True)
xx_latent = get_activations(xx)
np.save("data/encoded_denoise.npy", model.predict(xx, batch_size=2000))
np.save("data/encoded_latent.npy", xx_latent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment