<jupyter_start><jupyter_text>pailab Specific SetupThis example is taken from [autoencoder](https://github.com/udacity/deep-learning-v2-pytorch/tree/master/autoencoder/convolutional-autoencoder) notebook from the udacity [repository](https://github.com/udacity/deep-learning-v2-pytorch/) and then adapted to work with pailab.To run it, please make sure that- PyTorch is installed,- the path to the file autoenc_conv_pytorch.py (in pailab's example/custom_models directory) is either included in PYTHONPATH environment variable or just set it locally by uncommenting and editingthe following lines<jupyter_code>import sys
custom_model_dir = 'C:\\Users\\Anwender\\development\\pailab_oeltz\\examples\\custom_models' # set path to the implemented pytorch autoencoder
if custom_model_dir not in sys.path:
    sys.path.append(custom_model_dir)<jupyter_output><empty_output><jupyter_text>We instantiate the repository. Here, we choose simple in memory stores and a simple job runner.<jupyter_code>from pailab import RepoInfoKey, MeasureConfiguration, MLRepo, DataSet, MLObjectType, FIRST_VERSION, LAST_VERSION
# setting up the repository
config = {'user': 'test_user',
      'workspace': 'c:/temp',
      'repo_store': 
      {
          'type': 'memory_handler',  
          'config': {}
      },
      'numpy_store':
      {
          'type': 'memory_handler',
          'config':{}
      },
      'job_runner':
      {
          'type': 'simple',
          'config': {
              'throw_job_error': True
          }
      }
    }
ml_repo = MLRepo( user = 'test_user', config=config)<jupyter_output><empty_output><jupyter_text>------- Convolutional AutoencoderSticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. We'll build a convolutional autoencoder to compress the MNIST dataset. >The encoder portion will be made of convolutional and pooling layers and the decoder will be made of **transpose convolutional layers** that learn to "upsample" a compressed representation. Compressed RepresentationA compressed representation can be great for saving and sharing any kind of data in a way that is more efficient than storing raw data. In practice, the compressed representation often holds key information about an input image and we can use it for denoising images or oher kinds of reconstruction and transformation!Let's get started by importing our libraries and getting the dataset.<jupyter_code>import torch
import numpy as np
from torchvision import datasets
import torchvision.transforms as transforms

import logging
logging.basicConfig(level=logging.ERROR)

# convert data to torch.FloatTensor
transform = transforms.ToTensor()

# load the training and test datasets
train_data = datasets.MNIST(root='data', train=True,
                                   download=True, transform=transform)
test_data = datasets.MNIST(root='data', train=False,
                                  download=True, transform=transform)
# Create training and test dataloaders

num_workers = 0
# how many samples per batch to load
batch_size = 20

# prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, num_workers=num_workers)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers)<jupyter_output><empty_output><jupyter_text>Visualize the Data<jupyter_code>import matplotlib.pyplot as plt
%matplotlib inline
    
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy()

# get one image from the batch
img = np.squeeze(images[0])
fig = plt.figure(figsize = (5,5)) 
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray')<jupyter_output><empty_output><jupyter_text>--- Convolutional  Autoencoder EncoderThe encoder part of the network will be a typical convolutional pyramid. Each convolutional layer will be followed by a max-pooling layer to reduce the dimensions of the layers.  DecoderThe decoder though might be something new to you. The decoder needs to convert from a narrow representation to a wide, reconstructed image. For example, the representation could be a 7x7x4 max-pool layer. This is the output of the encoder, but also the input to the decoder. We want to get a 28x28x1 image out from the decoder so we need to work our way back up from the compressed representation. A schematic of the network is shown below.Here our final encoder layer has size 7x7x4 = 196. The original images have size 28x28 = 784, so the encoded vector is 25% the size of the original image. These are just suggested sizes for each of the layers. Feel free to change the depths and sizes, in fact, you're encouraged to add additional layers to make this representation even smaller! Remember our goal here is to find a small representation of the input data. Transpose Convolutions, DecoderThis decoder uses **transposed convolutional** layers to increase the width and height of the input layers. They work almost exactly the same as convolutional layers, but in reverse. A stride in the input layer results in a larger stride in the transposed convolution layer. For example, if you have a 3x3 kernel, a 3x3 patch in the input layer will be reduced to one unit in a convolutional layer. Comparatively, one unit in the input layer will be expanded to a 3x3 path in a transposed convolution layer. PyTorch provides us with an easy way to create the layers, [`nn.ConvTranspose2d`](https://pytorch.org/docs/stable/nn.htmlconvtranspose2d). It is important to note that transpose convolution layers can lead to artifacts in the final images, such as checkerboard patterns. This is due to overlap in the kernels which can be avoided by setting the stride and kernel size equal. In [this Distill article](http://distill.pub/2016/deconv-checkerboard/) from <NAME>, *et al*, the authors show that these checkerboard artifacts can be avoided by resizing the layers using nearest neighbor or bilinear interpolation (upsampling) followed by a convolutional layer. > We'll show this approach in another notebook, so you can experiment with it and see the difference. TODO: Build the network shown above. > Build the encoder out of a series of convolutional and pooling layers. > When building the decoder, recall that transpose convolutional layers can upsample an input by a factor of 2 using a stride and kernel_size of 2.  **In contrast to the original notebook we have defined the autoencoder outside the notebook in a separate source file: autoenc_conv_pytorch.py which is located in examples/custom_models.**Also note that we need to transform the data into numpy data to add it to the repo. To add a PyTorch DataSet directly to the repo is subject of future work.<jupyter_code>from autoenc_conv_pytorch import ConvAutoencoder
model = ConvAutoencoder()
# transform the pytorch datasets into numpy arrays and add the data to the MLRepo
tuple(train_data[0][0].shape)
train_tmp = np.empty((len(train_data), ) + tuple(train_data[0][0].shape))
for i in range(len(train_data)):
    train_tmp[i] = train_data[i][0]
tuple(test_data[0][0].shape)
test_tmp = np.empty((len(test_data), ) + tuple(test_data[0][0].shape))
for i in range(len(test_data)):
    test_tmp[i] = test_data[i][0]
#now add th raw data as well as the trainign and test data sets to the MLRepo
from pailab import RawData, DataSet
train_raw = RawData(train_tmp, x_coord_names=['image'], repo_info={RepoInfoKey.NAME: 'train_raw'})
test_raw = RawData(test_tmp, x_coord_names=['image'], repo_info={RepoInfoKey.NAME: 'test_raw'})
ml_repo.add([train_raw, test_raw])
train_data_repo = DataSet('train_raw', repo_info={RepoInfoKey.NAME: 'train_data', RepoInfoKey.CATEGORY: MLObjectType.TRAINING_DATA})
test_data_repo = DataSet('test_raw', repo_info={RepoInfoKey.NAME: 'test_data', RepoInfoKey.CATEGORY: MLObjectType.TEST_DATA})
ml_repo.add([train_data_repo, test_data_repo])
# Add model to the MLRepo.
# The method add_model is a convenience method doign all the work you would need to define a model in pailab:
# adding the training and model parameter, the model definition, the functions for training and evaluation of the model.
import pailab.externals.pytorch_interface as pytorch_interface
from pailab.ml_repo.repo_objects import get_object_from_classname
pytorch_interface.add_model(ml_repo, model, {}, 'conv_autoencoder', batch_size=20, epochs=3,
                           loss='MSE', optimizer='Adam', optim_param={})

# We can check what objects the method added by listing all objects of the repo before and after calling add_model.<jupyter_output>WARNING:pailab.ml_repo.repo_objects:Used module does not define a version which may lead to irreproducable results.
WARNING:pailab.ml_repo.repo_objects:Used module does not define a version which may lead to irreproducable results.<jupyter_text>--- Training **Since we have defined the model outside of the notebook and the training method is implemented in pailab's PyTorch interface, in contrast to the original notebook we can simply call run_training to start the training.**<jupyter_code>ml_repo.run_training()<jupyter_output><empty_output><jupyter_text>Checking out the resultsBelow I've plotted some of the test images along with their reconstructions. These look a little rough around the edges, likely due to the checkerboard effect we mentioned above that tends to happen with transpose layers.<jupyter_code>ml_repo.run_evaluation()
eval_train = ml_repo.get('conv_autoencoder/eval/train_data', full_object = True)
#compare original and autoencoded image
fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(25,4))

for i in range(10):
    train_data = ml_repo.get('train_data', full_object = True)
    axes[0,i].imshow(np.squeeze(train_data.x_data[i]), cmap='gray')
    axes[1,i].imshow(np.squeeze(eval_train.x_data[i]), cmap='gray')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0751415857605178, 'fraction_numerical': 0.00718042071197411, 'mean_word_length': 5.029878048780488, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 33, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '428594', 'license': 'Apache-2.0', 'n_tokens_mistral': 2853, 'n_tokens_neox': 2758, 'n_words': 1110, 'path': 'examples/pytorch/autoencoder/Convolutional_Autoencoder.ipynb', 'repo_name': 'pailabteam/pailab', 'size': '9896'}