├── Sparse_autoencoder.ipynb ├── images └── SAE.jpeg ├── readme.md ├── readme.tex.md ├── tex ├── 2ece8916c80529609c5cc5d5b4e259f4.svg ├── 6dec54c48a0438a5fcde6053bdb9d712.svg └── 77cfa7d35f1f6e57bffec24519aaf628.svg └── utils.py /images/SAE.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AntonP999/Sparse_autoencoder/2ebaabd114088fb0defd1ad5f2daa72c9864c10b/images/SAE.jpeg -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ### This repository contains PyTorch implementation of sparse autoencoder and it's application for image denosing and reconstruction. 2 | 3 | Autoencoder (AE) is an unsupervised deep learning algorithm, capable of extracting useful features from data. To do so, the model tries to learn an approximation to identity function, setting the labels equal to input. Although learning an identity function may seem like an easy task, placing some constrains on a model makes it discover essential features for reconstructing input data. Typically, these constraints are imposed on the middle layer of AE model, and consist in limiting the number of neurons. 4 | 5 | Autoencoder architecture. 6 | ![SAE](/images/SAE.jpeg) 7 | 8 | In the image above, AE is applied to image from MNIST dataset with size 28*28 pixels. Passing it through middle layer (also called latent space), which has 10 neurons, network is forced to learn a lower dimension representation of the image, thus learning to reconstruct a 784-dimensional data from 10-dimensional space. 9 | 10 | This way, AEs can be used as dimension reduction algorithm similar to PCA. Another major application of AEs is data denoising. Previously, AEs was also used for such tasks as pre-training of deep networks. 11 | 12 | Restrictions on latent representation can be imposed not only by limiting number of neurons, but also by adding some term in the loss function. By imposing sparsity constraint, the latent layer can have even more neurons than number of input dimensions. And that type of AE (sparse autoencoder, SAE) will still be able to discover interesting features in the input data. 13 | 14 | The sparsity constraint is penalizing activations of neurons in such way, that only few of them can be active at the same time. By "active" here means that activation of this particular neuron is close to 1, while inactive neurons activate close to 0. Most of the time neurons should be inactive. So with only few hidden units active for some input data and ability to reconstruct input one can say that model has learned some usefull features from data and not overfitting. 15 | 16 | One way to achive that is by adding to the loss function a Kullback-Leibler divergence between Bernoulli distribution whith mean and distribution of latent layer activations: 17 | 18 | 19 | 20 | where is the mean of distribution of latent neurons activations over training data. Setting to small value will force hidden neurons activations be mostly close to 0. Thus, this is a way of regularizing activations of neurons and make them data-dependend, where different neurons "fire" from different input samples. 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /readme.tex.md: -------------------------------------------------------------------------------- 1 | ### This repository contains PyTorch implementation of sparse autoencoder and it's application for image denosing and reconstruction. 2 | 3 | Autoencoder (AE) is an unsupervised deep learning algorithm, capable of extracting useful features from data. To do so, the model tries to learn an approximation to identity function, setting the labels equal to input. Although learning an identity function may seem like an easy task, placing some constrains on a model makes it discover essential features for reconstructing input data. Typically, these constraints are imposed on the middle layer of AE model, and consist in limiting the number of neurons. 4 | 5 | Autoencoder architecture. 6 | ![SAE](/images/SAE.jpeg) 7 | 8 | In the image above, AE is applied to image from MNIST dataset with size 28*28 pixels. Passing it through middle layer (also called latent space), which has 10 neurons, network is forced to learn a lower dimension representation of the image, thus learning to reconstruct a 784-dimensional data from 10-dimensional space. 9 | 10 | This way, AEs can be used as dimension reduction algorithm similar to PCA. Another major application of AEs is data denoising. Previously, AEs was also used for such tasks as pre-training of deep networks. 11 | 12 | Restrictions on latent representation can be imposed not only by limiting number of neurons, but also by adding some term in the loss function. By imposing sparsity constraint, the latent layer can have even more neurons than number of input dimensions. And that type of AE (sparse autoencoder, SAE) will still be able to discover interesting features in the input data. 13 | 14 | The sparsity constraint is penalizing activations of neurons in such way, that only few of them can be active at the same time. By "active" here means that activation of this particular neuron is close to 1, while inactive neurons activate close to 0. Most of the time neurons should be inactive. So with only few hidden units active for some input data and ability to reconstruct input one can say that model has learned some usefull features from data and not overfitting. 15 | 16 | One way to achive that is by adding to the loss function a Kullback-Leibler divergence between Bernoulli distribution whith mean $\rho$ and distribution of latent layer activations: 17 | 18 | $D_{KL}(\rho||\hat{\rho}) = \rho\log{\frac{\rho}{\hat{\rho}}} + (1-\rho)\log{\frac{(1-\rho)}{(1-\hat{\rho})}}$ 19 | 20 | where $\hat{\rho}$ is the mean of distribution of latent neurons activations over training data. Setting $\rho$ to small value will force hidden neurons activations be mostly close to 0. Thus, this is a way of regularizing activations of neurons and make them data-dependend, where different neurons "fire" from different input samples. 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /tex/2ece8916c80529609c5cc5d5b4e259f4.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /tex/6dec54c48a0438a5fcde6053bdb9d712.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /tex/77cfa7d35f1f6e57bffec24519aaf628.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.utils.data import DataLoader 3 | from torch.utils.data.sampler import SubsetRandomSampler 4 | from torchvision import datasets, transforms 5 | import matplotlib 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | 9 | mnist_transform = transforms.Compose([ 10 | transforms.ToTensor(), 11 | transforms.Normalize((0.1307,), (0.3081,)), 12 | ]) 13 | 14 | def mnist(batch_size=50, valid=0, shuffle=True, transform=mnist_transform, path='./MNIST_data'): 15 | test_data = datasets.MNIST(path, train=False, download=True, transform=transform) 16 | test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False) 17 | 18 | train_data = datasets.MNIST(path, train=True, download=True, transform=transform) 19 | if valid > 0: 20 | num_train = len(train_data) 21 | indices = list(range(num_train)) 22 | split = num_train-valid 23 | np.random.shuffle(indices) 24 | 25 | train_idx, valid_idx = indices[:split], indices[split:] 26 | train_sampler = SubsetRandomSampler(train_idx) 27 | valid_sampler = SubsetRandomSampler(valid_idx) 28 | 29 | train_loader = DataLoader(train_data, batch_size=batch_size, sampler=train_sampler) 30 | valid_loader = DataLoader(train_data, batch_size=batch_size, sampler=valid_sampler) 31 | 32 | return train_loader, valid_loader, test_loader 33 | else: 34 | train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=shuffle) 35 | return train_loader, test_loader 36 | 37 | 38 | def plot_mnist(images, shape): 39 | fig = plt.figure(figsize=shape[::-1], dpi=80) 40 | for j in range(1, len(images) + 1): 41 | ax = fig.add_subplot(shape[0], shape[1], j) 42 | ax.matshow(images[j - 1, 0, :, :], cmap = matplotlib.cm.binary) 43 | plt.xticks(np.array([])) 44 | plt.yticks(np.array([])) 45 | plt.show() 46 | 47 | def plot_graphs(log, tpe='loss'): 48 | keys = log.keys() 49 | logs = {k:[z for z in zip(*log[k])] for k in keys} 50 | epochs = {k:range(len(log[k])) for k in keys} 51 | 52 | if tpe == 'loss': 53 | handlers, = zip(*[plt.plot(epochs[k], logs[k][0], label=k) for k in keys]) 54 | plt.title('errors') 55 | plt.xlabel('epoch') 56 | plt.ylabel('error') 57 | plt.legend(handles=handlers) 58 | plt.show() 59 | elif tpe == 'accuracy': 60 | handlers, = zip(*[plt.plot(epochs[k], logs[k][1], label=k) for k in log.keys()]) 61 | plt.title('accuracy') 62 | plt.xlabel('epoch') 63 | plt.ylabel('accuracy') 64 | plt.legend(handles=handlers) 65 | plt.show() --------------------------------------------------------------------------------