markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Global Params
num_trials = 100000 # Num trials at each sigma sigmas = np.linspace(0.125, 0.5, 4)
_____no_output_____
Apache-2.0
special_orthogonalization/svd_vs_gs_simulations.ipynb
wy-go/google-research
Gaussian NoiseHere we generate a noise matrix with iid Gaussian entries drawn from$\sigma N(0,1)$.The "Frobenius Error Diff" shows the distributions of the error differences$\|A - \textrm{GS}(\tilde A)\|_F^2 - \|A - \textrm{SVD}(\tilde A)\|_F^2$ fordifferent values of $\sigma$. The "Geodesic Error Diff" plot shows the...
(all_errs_svd, all_errs_gs, all_geo_errs_svd, all_geo_errs_gs, all_noise_norms, all_noise_sq_norms ) = run_expt(sigmas, num_trials, noise_type='gaussian') plt.plot(sigmas, 3*sigmas**2, '--b', label='3 $\\sigma^2$') plt.errorbar(sigmas, all_errs_svd.mean(axis=1), c...
_____no_output_____
Apache-2.0
special_orthogonalization/svd_vs_gs_simulations.ipynb
wy-go/google-research
Uniform NoiseHere, the noise matrix is constructed with iid entries drawn from $\sigma \textrm{Unif}(-1, 1)$.
(all_errs_svd, all_errs_gs, all_geo_errs_svd, all_geo_errs_gs, all_noise_norms, all_noise_sq_norms ) = run_expt(sigmas, num_trials, noise_type='uniform') make_diff_plot(all_errs_svd, all_errs_gs, sigmas, title='Uniform Noise', ytitle='Frobenius Error Diff', xtitle='$\\phi$') make_diff_plot(all_geo_errs_svd, all_geo_...
_____no_output_____
Apache-2.0
special_orthogonalization/svd_vs_gs_simulations.ipynb
wy-go/google-research
Rotation Noise
(all_errs_svd, all_errs_gs, all_geo_errs_svd, all_geo_errs_gs, all_noise_norms, all_noise_sq_norms ) = run_expt(sigmas, num_trials, noise_type='rotation') make_diff_plot(all_errs_svd, all_errs_gs, sigma_to_kappa(sigmas), title='Rotation Noise', ytitle='Frobenius Error Diff', xtitle='$\\kappa$') make_diff_plot(all_ge...
_____no_output_____
Apache-2.0
special_orthogonalization/svd_vs_gs_simulations.ipynb
wy-go/google-research
Character-Level LSTM in PyTorchIn this notebook, I'll construct a character-level LSTM with PyTorch. The network will train character by character on some text, then generate new text character by character. As an example, I will train on Anna Karenina. **This model will be able to generate new text based on the text ...
import numpy as np import torch from torch import nn import torch.nn.functional as F
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Load in DataThen, we'll load the Anna Karenina text file and convert it into integers for our network to use.
# open text file and read in data as `text` with open('data/anna.txt', 'r') as f: text = f.read()
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Let's check out the first 100 characters, make sure everything is peachy. According to the [American Book Review](http://americanbookreview.org/100bestlines.asp), this is the 6th best first line of a book ever.
text[:100]
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
TokenizationIn the cells, below, I'm creating a couple **dictionaries** to convert the characters to and from integers. Encoding the characters as integers makes it easier to use as input in the network.
# encode the text and map each character to an integer and vice versa # we create two dictionaries: # 1. int2char, which maps integers to characters # 2. char2int, which maps characters to unique integers chars = tuple(set(text)) int2char = dict(enumerate(chars)) char2int = {ch: ii for ii, ch in int2char.items()} # e...
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
And we can see those same characters from above, encoded as integers.
encoded[:100]
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Pre-processing the dataAs you can see in our char-RNN image above, our LSTM expects an input that is **one-hot encoded** meaning that each character is converted into an integer (via our created dictionary) and *then* converted into a column vector where only it's corresponding integer index will have the value of 1 a...
def one_hot_encode(arr, n_labels): # Initialize the the encoded array one_hot = np.zeros((arr.size, n_labels), dtype=np.float32) # Fill the appropriate elements with ones one_hot[np.arange(one_hot.shape[0]), arr.flatten()] = 1. # Finally reshape it to get back to the original array ...
[[[0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 1. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0.]]]
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Making training mini-batchesTo train on this data, we also want to create mini-batches for training. Remember that we want our batches to be multiple sequences of some desired number of sequence steps. Considering a simple example, our batches would look like this:In this example, we'll take the encoded characters (pa...
def get_batches(arr, batch_size, seq_length): '''Create a generator that returns batches of size batch_size x seq_length from arr. Arguments --------- arr: Array you want to make batches from batch_size: Batch size, the number of sequences per batch seq_length: Numb...
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Test Your ImplementationNow I'll make some data sets and we can check out what's going on as we batch data. Here, as an example, I'm going to use a batch size of 8 and 50 sequence steps.
batches = get_batches(encoded, 8, 50) x, y = next(batches) # printing out the first 10 items in a sequence print('x\n', x[:10, :10]) print('\ny\n', y[:10, :10])
x [[54 68 75 18 59 45 37 33 66 48] [25 46 26 33 59 68 75 59 33 75] [45 26 70 33 46 37 33 75 33 13] [25 33 59 68 45 33 39 68 53 45] [33 25 75 51 33 68 45 37 33 59] [39 43 25 25 53 46 26 33 75 26] [33 82 26 26 75 33 68 75 70 33] [20 27 7 46 26 25 77 81 76 33]] y [[68 75 18 59 45 37 33 66 48 48] [46 26 33 59 6...
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
If you implemented `get_batches` correctly, the above output should look something like ```x [[25 8 60 11 45 27 28 73 1 2] [17 7 20 73 45 8 60 45 73 60] [27 20 80 73 7 28 73 60 73 65] [17 73 45 8 27 73 66 8 46 27] [73 17 60 12 73 8 27 28 73 45] [66 64 17 17 46 7 20 73 60 20] [73 76 20 20 60 73 8 60 80 73] [4...
# check if GPU is available train_on_gpu = torch.cuda.is_available() if(train_on_gpu): print('Training on GPU!') else: print('No GPU available, training on CPU; consider making n_epochs very small.') class CharRNN(nn.Module): def __init__(self, tokens, n_hidden=256, n_layers=2, ...
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Time to trainThe train function gives us the ability to set the number of epochs, the learning rate, and other parameters.Below we're using an Adam optimizer and cross entropy loss since we are looking at character class scores as output. We calculate the loss and perform backpropagation, as usual!A couple of details ...
def train(net, data, epochs=10, batch_size=10, seq_length=50, lr=0.001, clip=5, val_frac=0.1, print_every=10): ''' Training a network Arguments --------- net: CharRNN network data: text data to train the network epochs: Number of epochs to train batch_s...
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Instantiating the modelNow we can actually train the network. First we'll create the network itself, with some given hyperparameters. Then, define the mini-batches sizes, and start training!
# define and print the net n_hidden=512 n_layers=2 net = CharRNN(chars, n_hidden, n_layers) print(net) batch_size = 128 seq_length = 100 n_epochs = 20 # start smaller if you are just testing initial behavior # train the model train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_length=seq_length, lr=0.001,...
Epoch: 1/20... Step: 10... Loss: 3.2482... Val Loss: 3.2114 Epoch: 1/20... Step: 20... Loss: 3.1410... Val Loss: 3.1354 Epoch: 1/20... Step: 30... Loss: 3.1360... Val Loss: 3.1238 Epoch: 1/20... Step: 40... Loss: 3.1139... Val Loss: 3.1195 Epoch: 1/20... Step: 50... Loss: 3.1408... Val Loss: 3.1170 Epoch: 1/20... Step:...
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Getting the best modelTo set your hyperparameters to get the best performance, you'll want to watch the training and validation losses. If your training loss is much lower than the validation loss, you're overfitting. Increase regularization (more dropout) or use a smaller network. If the training and validation losse...
# change the name, for saving multiple files model_name = 'rnn_20_epoch.net' checkpoint = {'n_hidden': net.n_hidden, 'n_layers': net.n_layers, 'state_dict': net.state_dict(), 'tokens': net.chars} with open(model_name, 'wb') as f: torch.save(checkpoint, f)
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
--- Making PredictionsNow that the model is trained, we'll want to sample from it and make predictions about next characters! To sample, we pass in a character and have the network predict the next character. Then we take that character, pass it back in, and get another predicted character. Just keep doing this and you...
def predict(net, char, h=None, top_k=None): ''' Given a character, predict the next character. Returns the predicted character and the hidden state. ''' # tensor inputs x = np.array([[net.char2int[char]]]) x = one_hot_encode(x, len(net.chars)) inputs ...
_____no_output_____
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Priming and generating text Typically you'll want to prime the network so you can build up a hidden state. Otherwise the network will start out generating characters at random. In general the first bunch of characters will be a little rough since it hasn't built up a long history of characters to predict from.
def sample(net, size, prime='The', top_k=None): if(train_on_gpu): net.cuda() else: net.cpu() net.eval() # eval mode # First off, run through the prime characters chars = [ch for ch in prime] h = net.init_hidden(1) for ch in prime: char, h = predict(...
Anna had so that an enter strength to be says off and he cared to be an unmarrely sister. The children are saying in a place. A smile of their secretary and the sense of a condition. He saw that the princess was the same, the peaciting of his briderous country second still. That she had seen him a little as it was the...
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
Loading a checkpoint
# Here we have loaded in a model that trained over 20 epochs `rnn_20_epoch.net` with open('rnn_20_epoch.net', 'rb') as f: checkpoint = torch.load(f) loaded = CharRNN(checkpoint['tokens'], n_hidden=checkpoint['n_hidden'], n_layers=checkpoint['n_layers']) loaded.load_state_dict(checkpoint['state_dict']) # Sample...
And Levin said those second portryit on the contrast. "What is it?" said Stepan Arkadyevitch, letting up his shirt and talking to her face. And he had not speak to Levin that his head on the round stop and trouble to be faint, as he was not a man who was said, she was the setter times that had been before so much talk...
MIT
recurrent-neural-networks/char-rnn/Character_Level_RNN_Solution.ipynb
danielbank/deep-learning-v2-pytorch
1 - Sequence to Sequence Learning with Neural NetworksIn this series we'll be building a machine learning model to go from once sequence to another, using PyTorch and torchtext. This will be done on German to English translations, but the models can be applied to any problem that involves going from one sequence to an...
import torch import torch.nn as nn import torch.optim as optim from torchtext.legacy.datasets import Multi30k from torchtext.legacy.data import Field, BucketIterator import spacy import numpy as np import random import math import time
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We'll set the random seeds for deterministic results.
SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.deterministic = True
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next, we'll create the tokenizers. A tokenizer is used to turn a string containing a sentence into a list of individual tokens that make up that string, e.g. "good morning!" becomes ["good", "morning", "!"]. We'll start talking about the sentences being a sequence of tokens from now, instead of saying they're a sequenc...
spacy_de = spacy.load('de_core_news_sm') spacy_en = spacy.load('en_core_web_sm')
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next, we create the tokenizer functions. These can be passed to torchtext and will take in the sentence as a string and return the sentence as a list of tokens.In the paper we are implementing, they find it beneficial to reverse the order of the input which they believe "introduces many short term dependencies in the d...
def tokenize_de(text): """ Tokenizes German text from a string into a list of strings (tokens) and reverses it """ return [tok.text for tok in spacy_de.tokenizer(text)][::-1] def tokenize_en(text): """ Tokenizes English text from a string into a list of strings (tokens) """ return [tok....
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
torchtext's `Field`s handle how data should be processed. All of the possible arguments are detailed [here](https://github.com/pytorch/text/blob/master/torchtext/data/field.pyL61). We set the `tokenize` argument to the correct tokenization function for each, with German being the `SRC` (source) field and English being ...
SRC = Field(tokenize = tokenize_de, init_token = '<sos>', eos_token = '<eos>', lower = True) TRG = Field(tokenize = tokenize_en, init_token = '<sos>', eos_token = '<eos>', lower = True)
/home/ben/miniconda3/envs/pytorch17/lib/python3.8/site-packages/torchtext-0.9.0a0+c38fd42-py3.8-linux-x86_64.egg/torchtext/data/field.py:150: UserWarning: Field class will be retired soon and moved to torchtext.legacy. Please see the most recent release notes for further information. warnings.warn('{} class will be r...
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next, we download and load the train, validation and test data. The dataset we'll be using is the [Multi30k dataset](https://github.com/multi30k/dataset). This is a dataset with ~30,000 parallel English, German and French sentences, each with ~12 words per sentence. `exts` specifies which languages to use as the source...
train_data, valid_data, test_data = Multi30k.splits(exts = ('.de', '.en'), fields = (SRC, TRG))
/home/ben/miniconda3/envs/pytorch17/lib/python3.8/site-packages/torchtext-0.9.0a0+c38fd42-py3.8-linux-x86_64.egg/torchtext/data/example.py:78: UserWarning: Example class will be retired soon and moved to torchtext.legacy. Please see the most recent release notes for further information. warnings.warn('Example class w...
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We can double check that we've loaded the right number of examples:
print(f"Number of training examples: {len(train_data.examples)}") print(f"Number of validation examples: {len(valid_data.examples)}") print(f"Number of testing examples: {len(test_data.examples)}")
Number of training examples: 29000 Number of validation examples: 1014 Number of testing examples: 1000
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We can also print out an example, making sure the source sentence is reversed:
print(vars(train_data.examples[0]))
{'src': ['.', 'büsche', 'vieler', 'nähe', 'der', 'in', 'freien', 'im', 'sind', 'männer', 'weiße', 'junge', 'zwei'], 'trg': ['two', 'young', ',', 'white', 'males', 'are', 'outside', 'near', 'many', 'bushes', '.']}
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
The period is at the beginning of the German (src) sentence, so it looks like the sentence has been correctly reversed.Next, we'll build the *vocabulary* for the source and target languages. The vocabulary is used to associate each unique token with an index (an integer). The vocabularies of the source and target langu...
SRC.build_vocab(train_data, min_freq = 2) TRG.build_vocab(train_data, min_freq = 2) print(f"Unique tokens in source (de) vocabulary: {len(SRC.vocab)}") print(f"Unique tokens in target (en) vocabulary: {len(TRG.vocab)}")
Unique tokens in source (de) vocabulary: 7853 Unique tokens in target (en) vocabulary: 5893
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
The final step of preparing the data is to create the iterators. These can be iterated on to return a batch of data which will have a `src` attribute (the PyTorch tensors containing a batch of numericalized source sentences) and a `trg` attribute (the PyTorch tensors containing a batch of numericalized target sentences...
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') BATCH_SIZE = 128 train_iterator, valid_iterator, test_iterator = BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, device = device)
/home/ben/miniconda3/envs/pytorch17/lib/python3.8/site-packages/torchtext-0.9.0a0+c38fd42-py3.8-linux-x86_64.egg/torchtext/data/iterator.py:48: UserWarning: BucketIterator class will be retired soon and moved to torchtext.legacy. Please see the most recent release notes for further information. warnings.warn('{} clas...
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Building the Seq2Seq ModelWe'll be building our model in three parts. The encoder, the decoder and a seq2seq model that encapsulates the encoder and decoder and will provide a way to interface with each. EncoderFirst, the encoder, a 2 layer LSTM. The paper we are implementing uses a 4-layer LSTM, but in the interest o...
class Encoder(nn.Module): def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout): super().__init__() self.hid_dim = hid_dim self.n_layers = n_layers self.embedding = nn.Embedding(input_dim, emb_dim) self.rnn = nn.LSTM(emb_dim, hid_dim, n...
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
DecoderNext, we'll build our decoder, which will also be a 2-layer (4 in the paper) LSTM.![](assets/seq2seq3.png)The `Decoder` class does a single step of decoding, i.e. it ouputs single token per time-step. The first layer will receive a hidden and cell state from the previous time-step, $(s_{t-1}^1, c_{t-1}^1)$, and...
class Decoder(nn.Module): def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout): super().__init__() self.output_dim = output_dim self.hid_dim = hid_dim self.n_layers = n_layers self.embedding = nn.Embedding(output_dim, emb_dim) ...
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Seq2SeqFor the final part of the implemenetation, we'll implement the seq2seq model. This will handle: - receiving the input/source sentence- using the encoder to produce the context vectors - using the decoder to produce the predicted output/target sentenceOur full model will look like this:![](assets/seq2seq4.png)Th...
class Seq2Seq(nn.Module): def __init__(self, encoder, decoder, device): super().__init__() self.encoder = encoder self.decoder = decoder self.device = device assert encoder.hid_dim == decoder.hid_dim, \ "Hidden dimensions of encoder and decoder m...
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Training the Seq2Seq ModelNow we have our model implemented, we can begin training it. First, we'll initialize our model. As mentioned before, the input and output dimensions are defined by the size of the vocabulary. The embedding dimesions and dropout for the encoder and decoder can be different, but the number of l...
INPUT_DIM = len(SRC.vocab) OUTPUT_DIM = len(TRG.vocab) ENC_EMB_DIM = 256 DEC_EMB_DIM = 256 HID_DIM = 512 N_LAYERS = 2 ENC_DROPOUT = 0.5 DEC_DROPOUT = 0.5 enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT) dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT) model = Seq2Seq(enc, de...
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next up is initializing the weights of our model. In the paper they state they initialize all weights from a uniform distribution between -0.08 and +0.08, i.e. $\mathcal{U}(-0.08, 0.08)$.We initialize weights in PyTorch by creating a function which we `apply` to our model. When using `apply`, the `init_weights` functio...
def init_weights(m): for name, param in m.named_parameters(): nn.init.uniform_(param.data, -0.08, 0.08) model.apply(init_weights)
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We also define a function that will calculate the number of trainable parameters in the model.
def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The model has {count_parameters(model):,} trainable parameters')
The model has 13,898,501 trainable parameters
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We define our optimizer, which we use to update our parameters in the training loop. Check out [this](http://ruder.io/optimizing-gradient-descent/) post for information about different optimizers. Here, we'll use Adam.
optimizer = optim.Adam(model.parameters())
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next, we define our loss function. The `CrossEntropyLoss` function calculates both the log softmax as well as the negative log-likelihood of our predictions. Our loss function calculates the average loss per token, however by passing the index of the `` token as the `ignore_index` argument we ignore the loss whenever t...
TRG_PAD_IDX = TRG.vocab.stoi[TRG.pad_token] criterion = nn.CrossEntropyLoss(ignore_index = TRG_PAD_IDX)
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next, we'll define our training loop. First, we'll set the model into "training mode" with `model.train()`. This will turn on dropout (and batch normalization, which we aren't using) and then iterate through our data iterator.As stated before, our decoder loop starts at 1, not 0. This means the 0th element of our `outp...
def train(model, iterator, optimizer, criterion, clip): model.train() epoch_loss = 0 for i, batch in enumerate(iterator): src = batch.src trg = batch.trg optimizer.zero_grad() output = model(src, trg) #trg = [trg len,...
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Our evaluation loop is similar to our training loop, however as we aren't updating any parameters we don't need to pass an optimizer or a clip value.We must remember to set the model to evaluation mode with `model.eval()`. This will turn off dropout (and batch normalization, if used).We use the `with torch.no_grad()` b...
def evaluate(model, iterator, criterion): model.eval() epoch_loss = 0 with torch.no_grad(): for i, batch in enumerate(iterator): src = batch.src trg = batch.trg output = model(src, trg, 0) #turn off teacher forcing #trg = [trg le...
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
Next, we'll create a function that we'll use to tell us how long an epoch takes.
def epoch_time(start_time, end_time): elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
_____no_output_____
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We can finally start training our model!At each epoch, we'll be checking if our model has achieved the best validation loss so far. If it has, we'll update our best validation loss and save the parameters of our model (called `state_dict` in PyTorch). Then, when we come to test our model, we'll use the saved parameters...
N_EPOCHS = 10 CLIP = 1 best_valid_loss = float('inf') for epoch in range(N_EPOCHS): start_time = time.time() train_loss = train(model, train_iterator, optimizer, criterion, CLIP) valid_loss = evaluate(model, valid_iterator, criterion) end_time = time.time() epoch_mins, epoch_se...
/home/ben/miniconda3/envs/pytorch17/lib/python3.8/site-packages/torchtext-0.9.0a0+c38fd42-py3.8-linux-x86_64.egg/torchtext/data/batch.py:23: UserWarning: Batch class will be retired soon and moved to torchtext.legacy. Please see the most recent release notes for further information. warnings.warn('{} class will be re...
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
We'll load the parameters (`state_dict`) that gave our model the best validation loss and run it the model on the test set.
model.load_state_dict(torch.load('tut1-model.pt')) test_loss = evaluate(model, test_iterator, criterion) print(f'| Test Loss: {test_loss:.3f} | Test PPL: {math.exp(test_loss):7.3f} |')
| Test Loss: 3.951 | Test PPL: 52.001 |
MIT
1 - Sequence to Sequence Learning with Neural Networks.ipynb
RCXD/pytorch-seq2seq
IBM Quantum Challenge Fall 2021 Challenge 3: Classify images with quantum machine learning We recommend that you switch to **light** workspace theme under the Account menu in the upper right corner for optimal experience. IntroductionMachine learning is a technology that has attracted a great deal of attention due...
# General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # scikit-learn imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, M...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Part 1: Tutorial - QSVM for binary classification of MNISTIn this part, you will apply QSVM to the binary classification of handwritten numbers 4 and 9. Through this tutorial, you will learn the workflow of applying QSVM to binary classification. Find better combinations and achieve higher accuracy.Related QGSS materi...
# Load MNIST dataset DATA_PATH = './resources/ch3_part1.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, tes...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
2. Data EncodingWe will take the classical data and encode it to the quantum state space using a quantum feature map. The choice of which feature map to use is important and may depend on the given dataset we want to classify. Here we'll look at the feature maps available in Qiskit, before selecting and customising on...
# 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.decompose().draw('mpl')
/Users/scapape/miniconda3/envs/qiskit_env/lib/python3.8/site-packages/sympy/core/expr.py:2451: SymPyDeprecationWarning: expr_free_symbols method has been deprecated since SymPy 1.9. See https://github.com/sympy/sympy/issues/21494 for more info. SymPyDeprecationWarning(feature="expr_free_symbols method",
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Note the lack of entanglement in this feature map, this means that this feature map is simple to simulate classically and will not provide quantum advantage.and when $k = 2, P_0 = Z, P_1 = ZZ$, this is the `ZZFeatureMap`: $$\mathcal{U}_{\Phi(\mathbf{x})} = \left( \exp\left(i\sum_{jk} \phi_{\{j,k\}}(\mathbf{x}) \, Z_j \...
# 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.decompose().draw('mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Note that there is entanglement in the feature map, we can define the entanglement map:
# 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.decompose().draw('mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
We can customise the Pauli gates in the feature map, for example, $P_0 = X, P_1 = Y, P_2 = ZZ$:$$\mathcal{U}_{\Phi(\mathbf{x})} = \left( \exp\left(i\sum_{jk} \phi_{\{j,k\}}(\mathbf{x}) \, Z_j \otimes Z_k\right) \, \exp\left(i\sum_{j} \phi_{\{j\}}(\mathbf{x}) \, Y_j\right) \, \exp\left(i\sum_j \phi_{\{j\}}(\mathbf{x}) \...
# 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.decompose().draw('mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
The [`NLocal`](https://qiskit.org/documentation/stubs/qiskit.circuit.library.NLocal.html) and [`TwoLocal`](https://qiskit.org/documentation/stubs/qiskit.circuit.library.TwoLocal.html) functions in Qiskit's circuit library can also be used to create parameterised quantum circuits as feature maps. ```pythonTwoLocal(num_q...
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.decompose().draw('mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
and the equivalent `NLocal` circuit:
twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.decompose().draw('mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Let's encode the first training sample using the `PauliFeatureMap`:
print(f'First training data: {sample_train[0]}') encode_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.decompose().draw(output='mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
**Challenge 3a**Construct a feature map to encode a 5-dimensionally embedded data, using 'ZZFeatureMap' with 3 repetitions, 'circular' entanglement and the rest as default. Submission format:```pythonex3a_fmap = ZZFeatureMap(...)```
############################## # Provide your code here ex3a_fmap = ZZFeatureMap(feature_dimension=N_DIM, reps=3, entanglement='circular', data_map_func=None, insert_barriers=False) ############################## # Check your answer and submit using the following code from qc_grader import grade_e...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
2.2 Quantum Kernel EstimationA quantum feature map, $\phi(\mathbf{x})$, naturally gives rise to a quantum kernel, $k(\mathbf{x}_i,\mathbf{x}_j)= \phi(\mathbf{x}_j)^\dagger\phi(\mathbf{x}_i)$, which can be seen as a measure of similarity: $k(\mathbf{x}_i,\mathbf{x}_j)$ is large when $\mathbf{x}_i$ and $\mathbf{x}_j$ ar...
pauli_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) pauli_kernel = QuantumKernel(feature_map=pauli_map, quantum_instance=Aer.get_backend('statevector_simulator'))
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Let's calculate the transition amplitude between the first and second training data samples, one of the entries in the training kernel matrix.
print(f'First training data : {sample_train[0]}') print(f'Second training data: {sample_train[1]}')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
First we create and draw the circuit:
pauli_circuit = pauli_kernel.construct_circuit(sample_train[0], sample_train[1]) pauli_circuit.decompose().decompose().draw(output='mpl')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
The parameters in the gates are a little difficult to read, but notice how the circuit is symmetrical, with one half encoding one of the data samples, the other half encoding the other. We then simulate the circuit. We will use the `qasm_simulator` since the circuit contains measurements, but increase the number of sho...
backend = Aer.get_backend('qasm_simulator') job = execute(pauli_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(pauli_circuit) counts['0'*N_DIM] counts
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
The transition amplitude is the proportion of counts in the zero state:
print(f"Transition amplitude: {counts['0'*N_DIM]/sum(counts.values())}")
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
This process is then repeated for each pair of training data samples to fill in the training kernel matrix, and between each training and testing data sample to fill in the testing kernel matrix. Note that each matrix is symmetric, so to reduce computation time, only half the entries are calculated explicitly. Here we ...
matrix_train = pauli_kernel.evaluate(x_vec=sample_train) matrix_val = pauli_kernel.evaluate(x_vec=sample_val, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kerne...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
**Challenge 3b**Calculate the transition amplitude between $x = (-0.5, -0.4, 0.3, 0, -0.9)$ and $y = (0, -0.7, -0.3, 0, -0.4)$ using the 'ZZFeatureMap' with 3 repetitions, 'circular' entanglement and the rest as default. Use the 'qasm_simulator' with 'shots=8192', 'seed_simulator=1024' and 'seed_transpiler=1024'. ...
sample_train[0] np.array([-0.5,-0.4,0.3,0,-0.9]) x = [-0.5, -0.4, 0.3, 0, -0.9] y = [0, -0.7, -0.3, 0, -0.4] ############################## # Provide your code here pauli_map = ZZFeatureMap(feature_dimension=N_DIM, reps=3, entanglement='circular', data_map_func=None, insert_barriers=False) pauli_ker...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Related QGSS materials:- [**Kernel Trick (Lecture 6.1)**](https://www.youtube.com/watch?v=m6EzmYsEOiI&list=PLOFEBzvs-VvqJwybFxkTiDzhf5E11p8BI&index=14)- [**Kernel Trick (Lecture 6.2)**](https://www.youtube.com/watch?v=zw3JYUrS-v8&list=PLOFEBzvs-VvqJwybFxkTiDzhf5E11p8BI&index=15) 2.3 Quantum Support Vector Machine (QSV...
pauli_svc = SVC(kernel='precomputed') pauli_svc.fit(matrix_train, labels_train) pauli_score = pauli_svc.score(matrix_val, labels_val) print(f'Precomputed kernel classification test score: {pauli_score*100}%')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Related QGSS materials:- [**Classical SVM (Lecture 4.2)**](https://www.youtube.com/watch?v=lpPij21jnZ4&list=PLOFEBzvs-VvqJwybFxkTiDzhf5E11p8BI&index=9)- [**Quantum Classifier (Lecture 5.1)**](https://www.youtube.com/watch?v=-sxlXNz7ZxU&list=PLOFEBzvs-VvqJwybFxkTiDzhf5E11p8BI&index=11) Part 2: Challenge - QSVM for 3-cl...
# Load MNIST dataset DATA_PATH = './resources/ch3_part2.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, tes...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Then, preprocess the dataset in the same way as before.- Standardization- PCA- NormalizationNote that you can change the number of features here by changing N_DIM.
# Standardize standard_scaler = StandardScaler() sample_train = standard_scaler.fit_transform(sample_train) sample_val = standard_scaler.transform(sample_val) sample_test = standard_scaler.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) ...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
2. ModelingBased on the One-vs-Rest approach, you need to create the following three QSVM binary classifiers- the label 0 and the rest- the label 2 and the rest- the label 3 and the restHere is the first one as a hint. 2.1: Label 0 vs RestCreate new labels with label 0 as positive(1) and the rest as negative(0) as fol...
labels_train_0 = np.where(labels_train==0, 1, 0) labels_val_0 = np.where(labels_val==0, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 0 vs Rest: {labels_val_0}')
Original validation labels: [3 3 2 0 3 0 3 2 3 2 2 3 2 2 2 3 0 2 3 3] Validation labels for 0 vs Rest: [0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0]
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
See only places where the original label was 0 are set to 1. Next, construct a binary classifier using QSVM as before. Note that PauliFeatureMap is used in this hint but you can use a different feature map.
pauli_map_0 = PauliFeatureMap(feature_dimension=N_DIM, reps=2, paulis = ['X', 'Y', 'ZZ']) pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = pauli_kernel_0.evaluate(x_vec=sample_t...
Accuracy of discriminating between label 0 and others: 75.0%
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
You can see that the QSVM binary classifier is able to distinguish between label 0 and the rest with a reasonable probability.Finally, for each of the test data, calculate the probability that it has label 0. It can be obtained by ```predict_proba``` method.
matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=sample_train) pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}')
Probability of label 0: [0.31 0.32 0.25 0.46 0.21 0.3 0.24 0.23 0.34 0.51 0.38 0.3 0.22 0.26 0.41 0.49 0.38 0.47 0.33 0.22]
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
These probabilities are important clues for multiclass classification. Obtain the probabilities for the remaining two labels in the same way. 2.2: Label 2 vs RestBuild a binary classifier using QSVM and get the probability of label 2 for test dataset.
labels_train_2 = np.where(labels_train==2, 1, 0) labels_val_2 = np.where(labels_val==2, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_2}') pauli_map_2 = PauliFeatureMap(feature_dimension=N_DIM, reps=2, paulis = ['X', 'Y', 'ZZ']) pauli_kernel_2 = Quan...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
2.3 Label 3 vs RestBuild a binary classifier using QSVM and get the probability of label 3 for test dataset.
labels_train_3 = np.where(labels_train==3, 1, 0) labels_val_3 = np.where(labels_val==3, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 3 vs Rest: {labels_val_3}') pauli_map_3 = PauliFeatureMap(feature_dimension=N_DIM, reps=2, paulis = ['X', 'Y', 'ZZ']) pauli_kernel_3 = Quan...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
3. PredictionLastly, make a final prediction based on the probability of each label. The prediction you submit should be in the following format.
sample_pred = np.load('./resources/ch3_part2_sub.npy') print(f'Sample prediction: {sample_pred}')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
In order to understand the method to make predictions for multiclass classification, let's begin with the case of making predictions for just two labels, label 2 and label 3.If probabilities are as follows for a certain data, label 2 should be considered the most plausible.- probability of label 2: 0.7- probability of ...
pred_2_ex = np.array([0.7]) pred_3_ex = np.array([0.2]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
You can apply this method as is to multiple data.If second data has probabilities for each label as follows, it should be classified as label 3.- probability of label 2: 0.1- probability of label 3: 0.6
pred_2_ex = np.array([0.7, 0.1]) pred_3_ex = np.array([0.2, 0.6]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}')
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
This method can be extended to make predictions for 3-class classification.Implement such an extended method and make the final 3-class predictions.
############################## # Provide your code here pred_test = np.array([0 if ((pred_0[i] > pred_2[i]) & (pred_0[i] > pred_3[i])) else 2 if ((pred_2[i] > pred_0[i]) & (pred_2[i] > pred_3[i])) else 3 if ((pred_3[i] > pred_0[i]) & (pred_3[i] > pred_2[i])) else -1 for i in range(len(pred_0))]) #########...
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
4. Submission **Challenge 3c****Submission**: Submit the following 11 items.- **pred_test**: prediction for the public test dataset- **sample_train**: train data used to obtain kernels- **standard_scaler**: the one used to standardize data- **pca**: the one used to reduce dimention- **min_max_scaler**: the one used...
print(f'Sample prediction: {sample_pred}') # Check your answer and submit using the following code from qc_grader import grade_ex3c grade_ex3c(pred_test, sample_train, standard_scaler, pca, min_max_scaler, kernel_0, kernel_2, kernel_3, svc_0, svc_2, svc_3)
_____no_output_____
Apache-2.0
content/challenge-3/.ipynb_checkpoints/challenge-3-checkpoint.ipynb
scapape/ibm-quantum-challenge-fall-2021
Session 2 - Training a Network w/ TensorflowAssignment: Teach a Deep Neural Network to PaintParag K. MitalCreative Applications of Deep Learning w/ TensorflowKadenze AcademyCADLThis work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Learning Goals* Learn how to cr...
# First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n' \ 'You should consider updating to Python 3.4.0 or ' \ 'higher as the libraries built for this course ' \ 'have only been tested in Python 3.4 and higher.\n'...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Assignment SynopsisIn this assignment, we're going to create our first neural network capable of taking any two continuous values as inputs. Those two values will go through a series of multiplications, additions, and nonlinearities, coming out of the network as 3 outputs. Remember from the last homework, we used co...
xs = np.linspace(-6, 6, 100) plt.plot(xs, np.maximum(xs, 0), label='relu') plt.plot(xs, 1 / (1 + np.exp(-xs)), label='sigmoid') plt.plot(xs, np.tanh(xs), label='tanh') plt.xlabel('Input') plt.xlim([-6, 6]) plt.ylabel('Output') plt.ylim([-1.5, 1.5]) plt.title('Common Activation Functions/Nonlinearities') plt.legend(loc=...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Remember, having series of linear followed by nonlinear operations is what makes neural networks expressive. By stacking a lot of "linear" + "nonlinear" operations in a series, we can create a deep neural network! Have a look at the output ranges of the above nonlinearity when considering which nonlinearity seems mos...
# Create a placeholder with None x 2 dimensions of dtype tf.float32, and name it "X": X = ...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Now multiply the tensor using a new variable, $\textbf{W}$, which has 2 rows and 20 columns, so that when it is left mutiplied by $\textbf{X}$, the output of the multiplication is None x 20, giving you 20 output neurons. Recall that the `tf.matmul` function takes two arguments, the left hand ($\textbf{X}$) and right h...
W = tf.get_variable(... h = tf.matmul(...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
And add to this result another new variable, $\textbf{b}$, which has [20] dimensions. These values will be added to every output neuron after the multiplication above. Instead of the `tf.random_normal_initializer` that you used for creating $\textbf{W}$, now use the `tf.constant_initializer`. Often for bias, you'll ...
b = tf.get_variable(... h = tf.nn.bias_add(...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
So far we have done:$$\textbf{X}\textbf{W} + \textbf{b}$$Finally, apply a nonlinear activation to this output, such as `tf.nn.relu`, to complete the equation:$$\textbf{H} = \phi(\textbf{X}\textbf{W} + \textbf{b})$$TODO! COMPLETE THIS SECTION!
h = ...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Now that we've done all of this work, let's stick it inside a function. I've already done this for you and placed it inside the `utils` module under the function name `linear`. We've already imported the `utils` module so we can call it like so, `utils.linear(...)`. The docstring is copied below, and the code itself...
h, W = utils.linear( x=X, n_output=20, name='linear', activation=tf.nn.relu)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Part Two - Image Painting Network InstructionsFollow along the steps below, first setting up input and output data of the network, $\textbf{X}$ and $\textbf{Y}$. Then work through building the neural network which will try to compress the information in $\textbf{X}$ through a series of linear and non-linear functions ...
# First load an image img = ... # Be careful with the size of your image. # Try a fairly small image to begin with, # then come back here and try larger sizes. img = imresize(img, (100, 100)) plt.figure(figsize=(5, 5)) plt.imshow(img) # Make sure you save this image as "reference.png" # and include it in your zipped ...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
In the lecture, I showed how to aggregate the pixel locations and their colors using a loop over every pixel position. I put that code into a function `split_image` below. Feel free to experiment with other features for `xs` or `ys`.
def split_image(img): # We'll first collect all the positions in the image in our list, xs xs = [] # And the corresponding colors for each of these positions ys = [] # Now loop over the image for row_i in range(img.shape[0]): for col_i in range(img.shape[1]): # And store th...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Let's use this function to create the inputs (xs) and outputs (ys) to our network as the pixel locations (xs) and their colors (ys):
xs, ys = split_image(img) # and print the shapes xs.shape, ys.shape
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Also remember, we should normalize our input values!TODO! COMPLETE THIS SECTION!
# Normalize the input (xs) using its mean and standard deviation xs = ... # Just to make sure you have normalized it correctly: print(np.min(xs), np.max(xs)) assert(np.min(xs) > -3.0 and np.max(xs) < 3.0)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Similarly for the output:
print(np.min(ys), np.max(ys))
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
We'll normalize the output using a simpler normalization method, since we know the values range from 0-255:
ys = ys / 255.0 print(np.min(ys), np.max(ys))
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Scaling the image values like this has the advantage that it is still interpretable as an image, unlike if we have negative values.What we're going to do is use regression to predict the value of a pixel given its (row, col) position. So the input to our network is `X = (row, col)` value. And the output of the networ...
plt.imshow(ys.reshape(img.shape))
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
But when we give inputs of (row, col) to our network, it won't know what order they are, because we will randomize them. So it will have to *learn* what color value should be output for any given (row, col).Create 2 placeholders of `dtype` `tf.float32`: one for the input of the network, a `None x 2` dimension placehol...
# Let's reset the graph: tf.reset_default_graph() # Create a placeholder of None x 2 dimensions and dtype tf.float32 # This will be the input to the network which takes the row/col X = tf.placeholder(... # Create the placeholder, Y, with 3 output dimensions instead of 2. # This will be the output of the network, the ...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Now create a deep neural network that takes your network input $\textbf{X}$ of 2 neurons, multiplies it by a linear and non-linear transformation which makes its shape [None, 20], meaning it will have 20 output neurons. Then repeat the same process again to give you 20 neurons again, and then again and again until you...
# We'll create 6 hidden layers. Let's create a variable # to say how many neurons we want for each of the layers # (try 20 to begin with, then explore other values) n_neurons = ... # Create the first linear + nonlinear layer which will # take the 2 input neurons and fully connects it to 20 neurons. # Use the `utils.l...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Cost FunctionNow we're going to work on creating a `cost` function. The cost should represent how much `error` there is in the network, and provide the optimizer this value to help it train the network's parameters using gradient descent and backpropagation.Let's say our error is `E`, then the cost will be:$$cost(\te...
error = np.linspace(0.0, 128.0**2, 100) loss = error**2.0 plt.plot(error, loss) plt.xlabel('error') plt.ylabel('loss')
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
This is known as the $l_2$ (pronounced el-two) loss. It doesn't penalize small errors as much as it does large errors. This is easier to see when we compare it with another common loss, the $l_1$ (el-one) loss. It is linear in error, by taking the absolute value of the error. We'll compare the $l_1$ loss with norma...
error = np.linspace(0.0, 1.0, 100) plt.plot(error, error**2, label='l_2 loss') plt.plot(error, np.abs(error), label='l_1 loss') plt.xlabel('error') plt.ylabel('loss') plt.legend(loc='lower right')
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
So unlike the $l_2$ loss, the $l_1$ loss is really quickly upset if there is *any* error at all: as soon as error moves away from $0.0$, to $0.1$, the $l_1$ loss is $0.1$. But the $l_2$ loss is $0.1^2 = 0.01$. Having a stronger penalty on smaller errors often leads to what the literature calls "sparse" solutions, sin...
# first compute the error, the inner part of the summation. # This should be the l1-norm or l2-norm of the distance # between each color channel. error = ... assert(error.get_shape().as_list() == [None, 3])
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
TODO! COMPLETE THIS SECTION!
# Now sum the error for each feature in Y. # If Y is [Batch, Features], the sum should be [Batch]: sum_error = ... assert(sum_error.get_shape().as_list() == [None])
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
TODO! COMPLETE THIS SECTION!
# Finally, compute the cost, as the mean error of the batch. # This should be a single value. cost = ... assert(cost.get_shape().as_list() == [])
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
We now need an `optimizer` which will take our `cost` and a `learning_rate`, which says how far along the gradient to move. This optimizer calculates all the gradients in our network with respect to the `cost` variable and updates all of the weights in our network using backpropagation. We'll then create mini-batches...
# Refer to the help for the function optimizer = tf.train....minimize(cost) # Create parameters for the number of iterations to run for (< 100) n_iterations = ... # And how much data is in each minibatch (< 500) batch_size = ... # Then create a session sess = tf.Session()
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
We'll now train our network! The code below should do this for you if you've setup everything else properly. Please read through this and make sure you understand each step! Note that this can take a VERY LONG time depending on the size of your image (make it < 100 x 100 pixels), the number of neurons per layer (e.g...
# Initialize all your variables and run the operation with your session sess.run(tf.initialize_all_variables()) # Optimize over a few iterations, each time following the gradient # a little at a time imgs = [] costs = [] gif_step = n_iterations // 10 step_i = 0 for it_i in range(n_iterations): # Get a random...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Let's now display the GIF we've just created:
ipyd.Image(url='single.gif?{}'.format(np.random.rand()), height=500, width=500)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
ExploreGo back over the previous cells and exploring changing different parameters of the network. I would suggest first trying to change the `learning_rate` parameter to different values and see how the cost curve changes. What do you notice? Try exponents of $10$, e.g. $10^1$, $10^2$, $10^3$... and so on. Also t...
def build_model(xs, ys, n_neurons, n_layers, activation_fn, final_activation_fn, cost_type): xs = np.asarray(xs) ys = np.asarray(ys) if xs.ndim != 2: raise ValueError( 'xs should be a n_observates x n_features, ' + 'or a 2-dimensional array.') if...
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
CodeBelow, I've shown code for loading the first 100 celeb files. Run through the next few cells to see how this works with the celeb dataset, and then come back here and replace the `imgs` variable with your own set of images. For instance, you can try your entire sorted dataset from Session 1 as an N x H x W x C a...
celeb_imgs = utils.get_celeb_imgs() plt.figure(figsize=(10, 10)) plt.imshow(utils.montage(celeb_imgs).astype(np.uint8)) # It doesn't have to be 100 images, explore! imgs = np.array(celeb_imgs).copy()
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Explore changing the parameters of the `train` function and your own dataset of images. Note, you do not have to use the dataset from the last assignment! Explore different numbers of images, whatever you prefer.TODO! COMPLETE THIS SECTION!
# Change the parameters of the train function and # explore changing the dataset gifs = train(imgs=imgs)
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl
Now we'll create a gif out of the training process. Be sure to call this 'multiple.gif' for your homework submission:
montage_gifs = [np.clip(utils.montage( (m * 127.5) + 127.5), 0, 255).astype(np.uint8) for m in gifs] _ = gif.build_gif(montage_gifs, saveto='multiple.gif')
_____no_output_____
Apache-2.0
session-2/session-2.ipynb
takitsuba/kadenze_cadl