<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Image Space Projection using Autoencoders
In this example we are going to autoencode the faces of the olivetti dataset and try to reconstruct them back.
Step1:  http
Step3:  We now need some code to read pgm files.
Thanks to StackOverflow we have some code to leverage
Step4:  Let's import it to H2O
Step5:  Reconstructing the hidden space
Now that we have our model trained, we would like to understand better what is the internal representation of this model? What makes a face a .. face? 
We will provide to the model some gaussian noise and see what is the results.
We star by creating some gaussian noise
Step6:  Then we import this data inside H2O. We have to first map the columns to the gaussian data.
<ASSISTANT_TASK:>
Python Code:
%matplotlib inline
import matplotlib
import numpy as np
import pandas as pd
import scipy.io
import matplotlib.pyplot as plt
from IPython.display import Image, display
import h2o
from h2o.estimators.deeplearning import H2OAutoEncoderEstimator
h2o.init()
Explanation: Image Space Projection using Autoencoders
In this example we are going to autoencode the faces of the olivetti dataset and try to reconstruct them back.
End of explanation
!wget -c http://www.cl.cam.ac.uk/Research/DTG/attarchive/pub/data/att_faces.tar.Z
!tar xzvf att_faces.tar.Z;rm att_faces.tar.Z;
Explanation: http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
End of explanation
import re
def read_pgm(filename, byteorder='>'):
    Return image data from a raw PGM file as numpy array.
    Format specification: http://netpbm.sourceforge.net/doc/pgm.html
    
    with open(filename, 'rb') as f:
        buffer = f.read()
    try:
        header, width, height, maxval = re.search(
            b"(^P5\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", buffer).groups()
    except AttributeError:
        raise ValueError("Not a raw PGM file: '%s'" % filename)
    return np.frombuffer(buffer,
                            dtype='u1' if int(maxval) < 256 else byteorder+'u2',
                            count=int(width)*int(height),
                            offset=len(header)
                            ).reshape((int(height), int(width)))
image = read_pgm("orl_faces/s12/6.pgm", byteorder='<')
image.shape
plt.imshow(image, plt.cm.gray)
plt.show()
import glob
import os
from collections import defaultdict
images = glob.glob("orl_faces/**/*.pgm")
data = defaultdict(list)
image_data = []
for img in images:
    _,label,_ = img.split(os.path.sep)
    imgdata = read_pgm(img, byteorder='<').flatten().tolist()
    data[label].append(imgdata)
    image_data.append(imgdata)
Explanation: We now need some code to read pgm files.
Thanks to StackOverflow we have some code to leverage:
End of explanation
faces = h2o.H2OFrame(image_data)
faces.shape
from h2o.estimators.deeplearning import H2OAutoEncoderEstimator
model = H2OAutoEncoderEstimator( 
        activation="Tanh", 
        hidden=[50], 
        l1=1e-4, 
        epochs=10
)
model.train(x=faces.names, training_frame=faces)
model
Explanation: Let's import it to H2O
End of explanation
import pandas as pd
gaussian_noise = np.random.randn(10304)
plt.imshow(gaussian_noise.reshape(112, 92), plt.cm.gray);
Explanation: Reconstructing the hidden space
Now that we have our model trained, we would like to understand better what is the internal representation of this model? What makes a face a .. face? 
We will provide to the model some gaussian noise and see what is the results.
We star by creating some gaussian noise:
End of explanation
gaussian_noise_pre = dict(zip(faces.names,gaussian_noise))
gaussian_noise_hf = h2o.H2OFrame.from_python(gaussian_noise_pre)
result = model.predict(gaussian_noise_hf)
result.shape
img = result.as_data_frame()
img_data = img.T.values.reshape(112, 92)
plt.imshow(img_data, plt.cm.gray);
Explanation: Then we import this data inside H2O. We have to first map the columns to the gaussian data.
End of explanation
<END_TASK>