2016-10-26 06:35:09 +03:00
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Hands-On Lab: Language Understanding with Recurrent Networks\n",
"\n",
"This hands-on lab shows how to implement a recurrent network to process text,\n",
2016-10-31 23:51:01 +03:00
"for the [Air Travel Information Services](https://catalog.ldc.upenn.edu/LDC95S26) \n",
"(ATIS) task of slot tagging (tag individual words to their respective classes, \n",
2016-11-18 13:48:30 +03:00
"where the classes are provided as labels in the training data set).\n",
2016-10-31 23:51:01 +03:00
"We will start with a straight-forward embedding of the words followed by a recurrent LSTM.\n",
2016-11-18 13:48:30 +03:00
"This will then be extended to include neighboring words and run bidirectionally.\n",
2016-10-26 06:35:09 +03:00
"Lastly, we will turn this system into an intent classifier. \n",
"\n",
2016-10-31 23:51:01 +03:00
"The techniques you will practice are:\n",
"* model description by composing layer blocks, a convenient way to compose \n",
" networks/models without requiring the need to write formulas,\n",
2016-10-26 06:35:09 +03:00
"* creating your own layer block\n",
"* variables with different sequence lengths in the same network\n",
2016-10-31 23:51:01 +03:00
"* training the network\n",
2016-10-26 06:35:09 +03:00
"\n",
"We assume that you are familiar with basics of deep learning, and these specific concepts:\n",
"* recurrent networks ([Wikipedia page](https://en.wikipedia.org/wiki/Recurrent_neural_network))\n",
"* text embedding ([Wikipedia page](https://en.wikipedia.org/wiki/Word_embedding))\n",
"\n",
"### Prerequisites\n",
"\n",
2016-11-18 13:48:30 +03:00
"We assume that you have already [installed CNTK](https://github.com/Microsoft/CNTK/wiki/Setup-CNTK-on-your-machine).\n",
"This tutorial requires CNTK V2. We strongly recommend to run this tutorial on a machine with\n",
2016-10-31 23:51:01 +03:00
"a capable CUDA-compatible GPU. Deep learning without GPUs is not fun."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Downloading the data\n",
2016-10-26 06:35:09 +03:00
"\n",
2016-11-18 13:48:30 +03:00
"In this tutorial we are going to use a (lightly preprocessed) version of the ATIS dataset. You can download the data automatically by running the cells below or by executing the manual instructions.\n",
2016-10-26 06:35:09 +03:00
"\n",
2016-10-31 23:51:01 +03:00
"#### Fallback manual instructions\n",
2017-03-15 12:46:15 +03:00
"Download the ATIS [training](https://github.com/Microsoft/CNTK/blob/v2.0.beta15.0/Tutorials/SLUHandsOn/atis.train.ctf) \n",
"and [test](https://github.com/Microsoft/CNTK/blob/v2.0.beta15.0/Tutorials/SLUHandsOn/atis.test.ctf) \n",
2016-10-31 23:51:01 +03:00
"files and put them at the same folder as this notebook. If you want to see how the model is \n",
2016-11-10 15:02:35 +03:00
"predicting on new sentences you will also need the vocabulary files for \n",
2017-03-15 12:46:15 +03:00
"[queries](https://github.com/Microsoft/CNTK/blob/v2.0.beta15.0/Examples/LanguageUnderstanding/ATIS/BrainScript/query.wl) and\n",
"[slots](https://github.com/Microsoft/CNTK/blob/v2.0.beta15.0/Examples/LanguageUnderstanding/ATIS/BrainScript/slots.wl)"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 1,
2016-10-26 06:35:09 +03:00
"metadata": {
2016-10-26 10:37:04 +03:00
"collapsed": false
2016-10-26 06:35:09 +03:00
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Reusing locally cached: query.wl\n",
"Reusing locally cached: atis.test.ctf\n",
2017-03-29 12:07:15 +03:00
"Reusing locally cached: atis.train.ctf\n",
"Reusing locally cached: slots.wl\n"
2017-02-03 04:40:20 +03:00
]
}
],
2016-10-26 06:35:09 +03:00
"source": [
2016-12-19 15:49:05 +03:00
"from __future__ import print_function\n",
2016-10-26 06:35:09 +03:00
"import requests\n",
2016-12-08 23:42:46 +03:00
"import os\n",
2016-10-26 06:35:09 +03:00
"\n",
2016-10-31 23:51:01 +03:00
"def download(url, filename):\n",
2016-12-08 23:42:46 +03:00
" \"\"\" utility function to download a file \"\"\"\n",
2016-10-31 23:51:01 +03:00
" response = requests.get(url, stream=True)\n",
" with open(filename, \"wb\") as handle:\n",
" for data in response.iter_content():\n",
2016-10-26 06:35:09 +03:00
" handle.write(data)\n",
"\n",
2016-12-08 23:42:46 +03:00
"locations = ['Tutorials/SLUHandsOn', 'Examples/LanguageUnderstanding/ATIS/BrainScript']\n",
2016-10-31 23:51:01 +03:00
"\n",
2016-12-08 23:42:46 +03:00
"data = {\n",
" 'train': { 'file': 'atis.train.ctf', 'location': 0 },\n",
" 'test': { 'file': 'atis.test.ctf', 'location': 0 },\n",
" 'query': { 'file': 'query.wl', 'location': 1 },\n",
" 'slots': { 'file': 'slots.wl', 'location': 1 }\n",
"}\n",
"\n",
"for item in data.values():\n",
" location = locations[item['location']]\n",
" path = os.path.join('..', location, item['file'])\n",
" if os.path.exists(path):\n",
" print(\"Reusing locally cached:\", item['file'])\n",
" # Update path\n",
" item['file'] = path\n",
" elif os.path.exists(item['file']):\n",
" print(\"Reusing locally cached:\", item['file'])\n",
" else:\n",
" print(\"Starting download:\", item['file'])\n",
2017-03-15 12:46:15 +03:00
" url = \"https://github.com/Microsoft/CNTK/blob/v2.0.beta15.0/%s/%s?raw=true\"%(location, item['file'])\n",
2016-12-08 23:42:46 +03:00
" download(url, item['file'])\n",
" print(\"Download completed\")\n"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2016-10-31 23:51:01 +03:00
"#### Importing CNTK and other useful libraries\n",
"\n",
2016-11-18 13:48:30 +03:00
"CNTK's Python module contains several submodules like `io`, `learner`, and `layers`. We also use NumPy in some cases since the results returned by CNTK work like NumPy arrays."
2016-10-26 06:35:09 +03:00
]
},
2016-10-26 10:37:04 +03:00
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 2,
2016-10-26 10:37:04 +03:00
"metadata": {
2017-03-29 12:07:15 +03:00
"collapsed": false
2016-10-26 10:37:04 +03:00
},
"outputs": [],
"source": [
2016-10-31 23:51:01 +03:00
"import math\n",
"import numpy as np\n",
2017-03-16 08:07:51 +03:00
"\n",
2017-03-29 12:07:15 +03:00
"import cntk as C\n",
2017-03-16 08:07:51 +03:00
"from cntk.logging import ProgressPrinter, log_number_of_parameters\n",
2016-10-31 23:51:01 +03:00
"from cntk.io import MinibatchSource, CTFDeserializer\n",
2017-03-27 17:20:19 +03:00
"from cntk.io import StreamDef, StreamDefs, INFINITELY_REPEAT\n",
2016-11-15 16:45:00 +03:00
"from cntk import *\n",
2017-03-16 08:07:51 +03:00
"from cntk.learners import fsadagrad, learning_rate_schedule\n",
"from cntk.layers import * # CNTK Layers library\n",
"\n",
2017-01-10 12:39:24 +03:00
"# Select the right target device when this notebook is being tested:\n",
"if 'TEST_DEVICE' in os.environ:\n",
" import cntk\n",
" if os.environ['TEST_DEVICE'] == 'cpu':\n",
2017-02-15 19:00:41 +03:00
" cntk.device.try_set_default_device(cntk.device.cpu())\n",
2017-01-10 12:39:24 +03:00
" else:\n",
2017-02-15 19:00:41 +03:00
" cntk.device.try_set_default_device(cntk.device.gpu(0))\n"
2016-10-26 10:37:04 +03:00
]
},
2016-10-26 06:35:09 +03:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Task and Model Structure\n",
"\n",
"The task we want to approach in this tutorial is slot tagging.\n",
"We use the [ATIS corpus](https://catalog.ldc.upenn.edu/LDC95S26).\n",
"ATIS contains human-computer queries from the domain of Air Travel Information Services,\n",
"and our task will be to annotate (tag) each word of a query whether it belongs to a\n",
"specific item of information (slot), and which one.\n",
"\n",
"The data in your working folder has already been converted into the \"CNTK Text Format.\"\n",
"Let's look at an example from the test-set file `atis.test.ctf`:\n",
"\n",
" 19 |S0 178:1 |# BOS |S1 14:1 |# flight |S2 128:1 |# O\n",
" 19 |S0 770:1 |# show |S2 128:1 |# O\n",
" 19 |S0 429:1 |# flights |S2 128:1 |# O\n",
" 19 |S0 444:1 |# from |S2 128:1 |# O\n",
" 19 |S0 272:1 |# burbank |S2 48:1 |# B-fromloc.city_name\n",
" 19 |S0 851:1 |# to |S2 128:1 |# O\n",
" 19 |S0 789:1 |# st. |S2 78:1 |# B-toloc.city_name\n",
" 19 |S0 564:1 |# louis |S2 125:1 |# I-toloc.city_name\n",
" 19 |S0 654:1 |# on |S2 128:1 |# O\n",
" 19 |S0 601:1 |# monday |S2 26:1 |# B-depart_date.day_name\n",
" 19 |S0 179:1 |# EOS |S2 128:1 |# O\n",
"\n",
"This file has 7 columns:\n",
"\n",
"* a sequence id (19). There are 11 entries with this sequence id. This means that sequence 19 consists\n",
"of 11 tokens;\n",
"* column `S0`, which contains numeric word indices;\n",
"* a comment column denoted by `#`, to allow a human reader to know what the numeric word index stands for;\n",
"Comment columns are ignored by the system. `BOS` and `EOS` are special words\n",
"to denote beginning and end of sentence, respectively;\n",
"* column `S1` is an intent label, which we will only use in the last part of the tutorial;\n",
"* another comment column that shows the human-readable label of the numeric intent index;\n",
"* column `S2` is the slot label, represented as a numeric index; and\n",
"* another comment column that shows the human-readable label of the numeric label index.\n",
"\n",
"The task of the neural network is to look at the query (column `S0`) and predict the\n",
"slot label (column `S2`).\n",
"As you can see, each word in the input gets assigned either an empty label `O`\n",
"or a slot label that begins with `B-` for the first word, and with `I-` for any\n",
"additional consecutive word that belongs to the same slot.\n",
"\n",
"The model we will use is a recurrent model consisting of an embedding layer,\n",
"a recurrent LSTM cell, and a dense layer to compute the posterior probabilities:\n",
"\n",
"\n",
" slot label \"O\" \"O\" \"O\" \"O\" \"B-fromloc.city_name\"\n",
" ^ ^ ^ ^ ^\n",
" | | | | |\n",
" +-------+ +-------+ +-------+ +-------+ +-------+\n",
" | Dense | | Dense | | Dense | | Dense | | Dense | ...\n",
" +-------+ +-------+ +-------+ +-------+ +-------+\n",
" ^ ^ ^ ^ ^\n",
" | | | | |\n",
" +------+ +------+ +------+ +------+ +------+ \n",
" 0 -->| LSTM |-->| LSTM |-->| LSTM |-->| LSTM |-->| LSTM |-->...\n",
" +------+ +------+ +------+ +------+ +------+ \n",
" ^ ^ ^ ^ ^\n",
" | | | | |\n",
" +-------+ +-------+ +-------+ +-------+ +-------+\n",
" | Embed | | Embed | | Embed | | Embed | | Embed | ...\n",
" +-------+ +-------+ +-------+ +-------+ +-------+\n",
" ^ ^ ^ ^ ^\n",
" | | | | |\n",
" w ------>+--------->+--------->+--------->+--------->+------... \n",
" BOS \"show\" \"flights\" \"from\" \"burbank\"\n",
"\n",
"Or, as a CNTK network description. Please have a quick look and match it with the description above:\n",
2016-11-18 13:48:30 +03:00
"(descriptions of these functions can be found at: [the layers reference](http://cntk.ai/pythondocs/layerref.html))\n"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 3,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
2016-10-31 23:51:01 +03:00
"# number of words in vocab, slot labels, and intent labels\n",
"vocab_size = 943 ; num_labels = 129 ; num_intents = 26 \n",
2016-10-26 06:35:09 +03:00
"\n",
"# model dimensions\n",
"input_dim = vocab_size\n",
"label_dim = num_labels\n",
"emb_dim = 150\n",
"hidden_dim = 300\n",
"\n",
"def create_model():\n",
2016-10-26 10:37:04 +03:00
" with default_options(initial_state=0.1):\n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
2017-03-04 01:02:18 +03:00
" Embedding(emb_dim, name='embed'),\n",
2016-10-26 06:35:09 +03:00
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
2017-03-04 01:02:18 +03:00
" Dense(num_labels, name='classify')\n",
2016-10-26 06:35:09 +03:00
" ])"
]
},
2016-10-31 23:51:01 +03:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are ready to create a model and inspect it.\n"
]
},
2016-10-26 10:37:04 +03:00
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 4,
2016-10-26 10:37:04 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(-1, 150)\n",
"[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n",
" 0. 0. 0.]\n"
]
}
],
2016-10-26 10:37:04 +03:00
"source": [
"# peek\n",
"model = create_model()\n",
2017-03-04 01:02:18 +03:00
"print(model.embed.E.shape)\n",
"print(model.classify.b.value)"
2016-10-26 10:37:04 +03:00
]
},
2016-10-31 23:51:01 +03:00
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
2016-11-18 13:48:30 +03:00
"As you can see the attributes of the model are fully accessible from Python. The model has 3 layers. The first layer is an embedding and you can access its parameter `E` (where the embeddings are stored) like any other attribute of a Python object. Its shape contains a `-1` which indicates that this parameter is not fully specified yet. When we decide what data we will run through this network (very shortly) the shape will be the size of the input vocabulary. We also print the bias term in the last layer. Bias terms are by default initialized to 0 (but there's also a way to change that).\n"
2016-10-31 23:51:01 +03:00
]
},
2016-10-26 06:35:09 +03:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CNTK Configuration\n",
"\n",
"To train and test a model in CNTK, we need to create a model and specify how to read data and perform training and testing. \n",
"\n",
"In order to train we need to specify:\n",
"\n",
"* how to read the data \n",
2016-10-31 23:51:01 +03:00
"* the model function, its inputs, and outputs\n",
"* hyper-parameters for the learner such as the learning rate\n",
2016-10-26 06:35:09 +03:00
"\n",
"[comment]: <> (For testing ...)\n",
"\n",
"### A Brief Look at Data and Data Reading\n",
"\n",
"We already looked at the data.\n",
"But how do you generate this format?\n",
"For reading text, this tutorial uses the `CNTKTextFormatReader`. It expects the input data to be\n",
2016-10-31 23:51:01 +03:00
"in a specific format, as described [here](https://github.com/Microsoft/CNTK/wiki/CNTKTextFormat-Reader).\n",
2016-10-26 06:35:09 +03:00
"\n",
"For this tutorial, we created the corpora by two steps:\n",
"* convert the raw data into a plain text file that contains of TAB-separated columns of space-separated text. For example:\n",
"\n",
" ```\n",
" BOS show flights from burbank to st. louis on monday EOS (TAB) flight (TAB) O O O O B-fromloc.city_name O B-toloc.city_name I-toloc.city_name O B-depart_date.day_name O\n",
" ```\n",
"\n",
" This is meant to be compatible with the output of the `paste` command.\n",
"* convert it to CNTK Text Format (CTF) with the following command:\n",
"\n",
" ```\n",
2016-10-31 23:51:01 +03:00
" python [CNTK root]/Scripts/txt2ctf.py --map query.wl intent.wl slots.wl --annotated True --input atis.test.txt --output atis.test.ctf\n",
2016-10-26 06:35:09 +03:00
" ```\n",
2016-10-31 23:51:01 +03:00
" where the three `.wl` files give the vocabulary as plain text files, one word per line.\n",
2016-10-26 06:35:09 +03:00
"\n",
"In these CTF files, our columns are labeled `S0`, `S1`, and `S2`.\n",
"These are connected to the actual network inputs by the corresponding lines in the reader definition:"
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 5,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def create_reader(path, is_training):\n",
" return MinibatchSource(CTFDeserializer(path, StreamDefs(\n",
" query = StreamDef(field='S0', shape=vocab_size, is_sparse=True),\n",
" intent_unused = StreamDef(field='S1', shape=num_intents, is_sparse=True), \n",
" slot_labels = StreamDef(field='S2', shape=num_labels, is_sparse=True)\n",
2017-03-27 17:20:19 +03:00
" )), randomize=is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)"
2016-10-26 06:35:09 +03:00
]
},
2016-10-26 10:37:04 +03:00
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 6,
2016-10-26 10:37:04 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"data": {
"text/plain": [
2017-03-29 12:07:15 +03:00
"dict_keys(['query', 'slot_labels', 'intent_unused'])"
2017-02-03 04:40:20 +03:00
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
2016-10-26 10:37:04 +03:00
"source": [
"# peek\n",
2016-12-08 23:42:46 +03:00
"reader = create_reader(data['train']['file'], is_training=True)\n",
2016-10-31 23:51:01 +03:00
"reader.streams.keys()"
2016-10-26 10:37:04 +03:00
]
},
2016-10-26 06:35:09 +03:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
2016-10-26 10:37:04 +03:00
"### Trainer\n",
2016-10-26 06:35:09 +03:00
"\n",
2017-03-29 12:07:15 +03:00
"We also must define the training criterion (loss function), and also an error metric to track. Below we make extensive use of `placeholders`. Remember that the code we have been writing is not actually executing any heavy computation it is just specifying the function we want to compute on data during training/testing. And in the same way that it is convenient to have names for arguments when you write a regular function in a programming language, it is convenient to have placeholders that refer to arguments (or local computations that need to be reused). Eventually, some other code will replace these placeholders with other known quantities in the same way that in a programming language the function will be called with concrete values bound to its arguments. "
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 7,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
2016-10-26 10:37:04 +03:00
"def create_criterion_function(model):\n",
2017-03-29 12:07:15 +03:00
" labels = C.placeholder(name='labels')\n",
2016-10-26 10:37:04 +03:00
" ce = cross_entropy_with_softmax(model, labels)\n",
" errs = classification_error (model, labels)\n",
" return combine ([ce, errs]) # (features, labels) -> (loss, metric)"
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 8,
2016-10-26 10:37:04 +03:00
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def train(reader, model, max_epochs=16):\n",
" # criterion: (model args, labels) -> (loss, metric)\n",
" # here (query, slot_labels) -> (ce, errs)\n",
" criterion = create_criterion_function(model)\n",
2016-10-26 06:35:09 +03:00
"\n",
2017-03-29 12:07:15 +03:00
" criterion.replace_placeholders({criterion.placeholders[0]: C.sequence.input(vocab_size),\n",
" criterion.placeholders[1]: C.sequence.input(num_labels)})\n",
2016-10-26 06:35:09 +03:00
"\n",
" # training config\n",
2016-10-31 23:51:01 +03:00
" epoch_size = 18000 # 18000 samples is half the dataset size \n",
2016-10-26 06:35:09 +03:00
" minibatch_size = 70\n",
2016-10-31 23:51:01 +03:00
" \n",
" # LR schedule over epochs \n",
" # In CNTK, an epoch is how often we get out of the minibatch loop to\n",
" # do other stuff (e.g. checkpointing, adjust learning rate, etc.)\n",
" # (we don't run this many epochs, but if we did, these are good values)\n",
" lr_per_sample = [0.003]*4+[0.0015]*24+[0.0003]\n",
2016-11-15 16:45:00 +03:00
" lr_per_minibatch = [x * minibatch_size for x in lr_per_sample]\n",
" lr_schedule = learning_rate_schedule(lr_per_minibatch, UnitType.minibatch, epoch_size)\n",
2016-10-31 23:51:01 +03:00
" \n",
2016-11-15 16:45:00 +03:00
" # Momentum\n",
" momentum_as_time_constant = momentum_as_time_constant_schedule(700)\n",
2016-10-31 23:51:01 +03:00
" \n",
2017-03-16 08:07:51 +03:00
" # We use a variant of the FSAdaGrad optimizer which is known to work well on this dataset\n",
2016-10-31 23:51:01 +03:00
" # Feel free to try other optimizers from \n",
" # https://www.cntk.ai/pythondocs/cntk.learner.html#module-cntk.learner\n",
2017-03-16 08:07:51 +03:00
" learner = fsadagrad(criterion.parameters,\n",
" lr=lr_schedule, momentum=momentum_as_time_constant,\n",
" gradient_clipping_threshold_per_sample=15, gradient_clipping_with_truncation=True)\n",
2016-10-26 06:35:09 +03:00
"\n",
2016-10-26 10:37:04 +03:00
" # trainer\n",
2017-02-23 03:37:37 +03:00
" progress_printer = ProgressPrinter(tag='Training', num_epochs=max_epochs)\n",
" #progress_printer = ProgressPrinter(freq=100, first=10, tag='Training', num_epochs=max_epochs) # more detailed logging\n",
" trainer = Trainer(model, criterion, learner, progress_printer)\n",
2016-10-26 06:35:09 +03:00
"\n",
" # process minibatches and perform model training\n",
2016-10-26 10:37:04 +03:00
" log_number_of_parameters(model)\n",
2016-10-26 06:35:09 +03:00
"\n",
" t = 0\n",
" for epoch in range(max_epochs): # loop over epochs\n",
" epoch_end = (epoch+1) * epoch_size\n",
2016-10-26 10:37:04 +03:00
" while t < epoch_end: # loop over minibatches on the epoch\n",
" data = reader.next_minibatch(minibatch_size, input_map={ # fetch minibatch\n",
2017-01-05 13:22:42 +03:00
" criterion.arguments[0]: reader.streams.query,\n",
" criterion.arguments[1]: reader.streams.slot_labels\n",
2016-10-26 10:37:04 +03:00
" })\n",
" trainer.train_minibatch(data) # update model with it\n",
2017-01-05 13:22:42 +03:00
" t += data[criterion.arguments[1]].num_samples # samples so far\n",
2017-02-23 03:37:37 +03:00
" trainer.summarize_training_progress()\n"
2016-10-26 06:35:09 +03:00
]
},
{
2016-10-26 10:37:04 +03:00
"cell_type": "markdown",
"metadata": {},
2016-10-26 06:35:09 +03:00
"source": [
2016-10-26 10:37:04 +03:00
"### Running it\n",
"\n",
"You can find the complete recipe below."
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 9,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": false,
"scrolled": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Training 721479 parameters in 6 parameter tensors.\n",
2017-03-29 12:07:15 +03:00
"Finished Epoch[1 of 16]: [Training] loss = 1.097468 * 18010, metric = 0.00% * 18010 3.835s (4696.2 samples/s);\n",
"Finished Epoch[2 of 16]: [Training] loss = 0.443539 * 18051, metric = 0.00% * 18051 3.464s (5211.0 samples/s);\n",
"Finished Epoch[3 of 16]: [Training] loss = 0.294534 * 17941, metric = 0.00% * 17941 3.383s (5303.3 samples/s);\n",
"Finished Epoch[4 of 16]: [Training] loss = 0.213083 * 18059, metric = 0.00% * 18059 3.455s (5226.9 samples/s);\n",
"Finished Epoch[5 of 16]: [Training] loss = 0.158128 * 17957, metric = 0.00% * 17957 3.430s (5235.3 samples/s);\n",
"Finished Epoch[6 of 16]: [Training] loss = 0.143503 * 18021, metric = 0.00% * 18021 3.435s (5246.3 samples/s);\n",
"Finished Epoch[7 of 16]: [Training] loss = 0.117660 * 17980, metric = 0.00% * 17980 3.362s (5348.0 samples/s);\n",
"Finished Epoch[8 of 16]: [Training] loss = 0.121787 * 18025, metric = 0.00% * 18025 3.423s (5265.8 samples/s);\n",
"Finished Epoch[9 of 16]: [Training] loss = 0.082948 * 17956, metric = 0.00% * 17956 3.401s (5279.6 samples/s);\n",
"Finished Epoch[10 of 16]: [Training] loss = 0.084909 * 18039, metric = 0.00% * 18039 3.401s (5304.0 samples/s);\n",
"Finished Epoch[11 of 16]: [Training] loss = 0.091183 * 17966, metric = 0.00% * 17966 3.314s (5421.2 samples/s);\n",
"Finished Epoch[12 of 16]: [Training] loss = 0.065457 * 18041, metric = 0.00% * 18041 3.370s (5353.4 samples/s);\n",
"Finished Epoch[13 of 16]: [Training] loss = 0.069261 * 17984, metric = 0.00% * 17984 3.529s (5096.1 samples/s);\n",
"Finished Epoch[14 of 16]: [Training] loss = 0.069089 * 17976, metric = 0.00% * 17976 3.338s (5385.3 samples/s);\n",
"Finished Epoch[15 of 16]: [Training] loss = 0.061216 * 18030, metric = 0.00% * 18030 3.407s (5292.0 samples/s);\n",
"Finished Epoch[16 of 16]: [Training] loss = 0.052744 * 18014, metric = 0.00% * 18014 3.482s (5173.5 samples/s);\n"
2017-02-03 04:40:20 +03:00
]
}
],
2016-10-26 06:35:09 +03:00
"source": [
2016-10-26 10:37:04 +03:00
"def do_train():\n",
" global model\n",
" model = create_model()\n",
2016-12-08 23:42:46 +03:00
" reader = create_reader(data['train']['file'], is_training=True)\n",
2016-10-26 10:37:04 +03:00
" train(reader, model)\n",
"do_train()"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This shows how learning proceeds over epochs (passes through the data).\n",
2016-10-26 10:37:04 +03:00
"For example, after four epochs, the loss, which is the cross-entropy criterion, has reached 0.22 as measured on the ~18000 samples of this epoch,\n",
"and that the error rate is 5.0% on those same 18000 training samples.\n",
2016-10-26 06:35:09 +03:00
"\n",
"The epoch size is the number of samples--counted as *word tokens*, not sentences--to\n",
"process between model checkpoints.\n",
"\n",
"Once the training has completed (a little less than 2 minutes on a Titan-X or a Surface Book),\n",
"you will see an output like this\n",
"```\n",
2016-10-31 23:51:01 +03:00
"Finished Epoch [16]: [Training] loss = 0.058111 * 18014, metric = 1.3% * 18014\n",
2016-10-26 06:35:09 +03:00
"```\n",
2016-10-31 23:51:01 +03:00
"which is the loss (cross entropy) and the metric (classification error) averaged over the final epoch.\n",
2016-10-26 06:35:09 +03:00
"\n",
2016-10-31 23:51:01 +03:00
"On a CPU-only machine, it can be 4 or more times slower. You can try setting\n",
"```python\n",
"emb_dim = 50 \n",
"hidden_dim = 100\n",
"```\n",
"to reduce the time it takes to run on a CPU, but the model will not fit as well as when the \n",
"hidden and embedding dimension are larger. "
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
2016-10-26 10:37:04 +03:00
"source": [
"### Evaluating the model\n",
"\n",
2016-12-01 22:20:17 +03:00
"Like the train() function, we also define a function to measure accuracy on a test set by computing the error over multiple minibatches of test data. For evaluating on a small sample read from a file, you can set a minibatch size reflecting the sample size and run the test_minibatch on that instance of data. To see how to evaluate a single sequence, we provide an instance later in the tutorial. "
2016-10-26 10:37:04 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 10,
2016-10-26 10:37:04 +03:00
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def evaluate(reader, model):\n",
" criterion = create_criterion_function(model)\n",
2017-03-29 12:07:15 +03:00
" criterion.replace_placeholders({criterion.placeholders[0]: C.sequence.input(num_labels)})\n",
2016-10-26 10:37:04 +03:00
"\n",
" # process minibatches and perform evaluation\n",
2016-11-15 16:45:00 +03:00
" lr_schedule = learning_rate_schedule(1, UnitType.minibatch)\n",
" momentum_as_time_constant = momentum_as_time_constant_schedule(0)\n",
2017-03-16 08:07:51 +03:00
" dummy_learner = fsadagrad(criterion.parameters, \n",
" lr=lr_schedule, momentum=momentum_as_time_constant)\n",
2017-02-03 20:50:13 +03:00
" progress_printer = ProgressPrinter(tag='Evaluation', num_epochs=0)\n",
2017-02-23 03:37:37 +03:00
" evaluator = Trainer(model, criterion, dummy_learner, progress_printer)\n",
2016-10-26 10:37:04 +03:00
"\n",
" while True:\n",
2017-01-11 12:00:09 +03:00
" minibatch_size = 500\n",
2016-10-26 10:37:04 +03:00
" data = reader.next_minibatch(minibatch_size, input_map={ # fetch minibatch\n",
2017-01-05 13:22:42 +03:00
" criterion.arguments[0]: reader.streams.query,\n",
" criterion.arguments[1]: reader.streams.slot_labels\n",
2016-10-26 10:37:04 +03:00
" })\n",
" if not data: # until we hit the end\n",
" break\n",
2017-02-23 03:37:37 +03:00
" evaluator.test_minibatch(data)\n",
" evaluator.summarize_test_progress()\n"
2016-10-26 10:37:04 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2016-10-31 23:51:01 +03:00
"Now we can measure the model accuracy by going through all the examples in the test set and using the ``test_minibatch`` method of the trainer created inside the evaluate function defined above. At the moment (when this tutorial was written) the Trainer constructor requires a learner (even if it is only used to perform ``test_minibatch``) so we have to specify a dummy learner. In the future it will be allowed to construct a Trainer without specifying a learner as long as the trainer only calls ``test_minibatch``"
2016-10-26 10:37:04 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 11,
2016-10-26 10:37:04 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2017-03-16 08:07:51 +03:00
"Finished Evaluation [1]: Minibatch[1-23]: metric = 2.75% * 10984;\n"
2017-02-03 04:40:20 +03:00
]
},
{
"data": {
"text/plain": [
2017-03-16 08:07:51 +03:00
"array([ -6.17747717e-02, 1.67661443e-01, 2.67170966e-01,\n",
" -1.74591824e-01, -8.95597786e-02, -1.41288519e-01,\n",
" -1.65670067e-01, -3.37033689e-01, -2.43425101e-01,\n",
" -4.46879327e-01, -1.68832064e-01, -3.02033067e-01,\n",
" -1.76276788e-01, -2.74571389e-01, 1.39392257e-01,\n",
" 8.47953185e-02, -5.46203911e-01, -1.13420285e-01,\n",
" 2.31410667e-01, -6.03151739e-01, 1.89564034e-01,\n",
" 1.24402806e-01, -2.14793026e-01, -4.18093294e-01,\n",
" -3.74919385e-01, 1.71167374e-01, -2.51746088e-01,\n",
" -1.43728435e-01, -9.00750905e-02, -3.50904576e-02,\n",
" -1.18319996e-01, -1.28747627e-01, 5.05147576e-02,\n",
" -1.58297736e-02, -2.74065882e-01, 8.33015382e-01,\n",
" 2.71681130e-01, 2.87652642e-01, 5.84618635e-02,\n",
" -8.77579302e-02, -5.99530458e-01, 5.89624830e-02,\n",
" 4.13840532e-01, 2.55903602e-01, 5.06808400e-01,\n",
" -1.23152020e-03, -9.60507244e-02, -1.53484166e-01,\n",
" 2.22164527e-01, -1.28024921e-01, -1.65894926e-01,\n",
" -1.12369537e-01, -1.55051336e-01, 2.41953477e-01,\n",
" 1.22186437e-01, -4.66029584e-01, 9.18036997e-02,\n",
" -2.58443505e-01, -2.13418171e-01, -1.93984643e-01,\n",
" -4.68383253e-01, -3.08870435e-01, -2.98281580e-01,\n",
" -4.93319303e-01, -4.19607669e-01, -4.19408053e-01,\n",
" 2.76399136e-01, -2.33146876e-01, -4.22037452e-01,\n",
" -5.73692262e-01, -5.13007641e-01, -4.26108152e-01,\n",
" -2.96079516e-01, -4.26696450e-01, -5.30181289e-01,\n",
" -4.90620822e-01, -1.50063947e-01, -8.53931606e-02,\n",
" -2.88960963e-01, -3.32533240e-01, -1.82914421e-01,\n",
" -6.08625636e-02, 1.39558926e-01, -3.55813682e-01,\n",
" 2.61406936e-02, -3.05180758e-01, -2.52452403e-01,\n",
" -3.59835297e-01, -3.46008271e-01, -7.74578974e-02,\n",
" -4.68599826e-01, -4.85255606e-02, 8.09183344e-03,\n",
" -1.18216865e-01, -2.91808456e-01, -3.23003262e-01,\n",
" -5.39603047e-02, -2.29025170e-01, -2.62914300e-01,\n",
" -2.39585713e-01, 3.86748970e-01, -4.06216830e-01,\n",
" -7.60369599e-02, -1.73274621e-01, -4.33509350e-01,\n",
" -1.12799823e-01, -5.64482391e-01, -8.78849402e-02,\n",
" -1.08817495e-01, 1.01803876e-01, -1.71952978e-01,\n",
" -1.97624609e-01, -3.14228594e-01, -5.24510920e-01,\n",
" -4.37267244e-01, -2.05273271e-01, -4.08936590e-01,\n",
" -4.90692288e-01, -4.09333557e-01, 5.79499081e-02,\n",
" -6.00475848e-01, -2.65847117e-01, -5.08210480e-01,\n",
" -3.80596757e-01, 7.19741860e-04, -3.00036907e-01,\n",
" -2.07646489e-01, -1.52841002e-01, 4.92504120e-01], dtype=float32)"
2017-02-03 04:40:20 +03:00
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
2016-10-26 10:37:04 +03:00
"source": [
"def do_test():\n",
2016-12-08 23:42:46 +03:00
" reader = create_reader(data['test']['file'], is_training=False)\n",
2016-10-26 10:37:04 +03:00
" evaluate(reader, model)\n",
"do_test()\n",
2017-03-04 01:02:18 +03:00
"model.classify.b.value"
2016-10-26 10:37:04 +03:00
]
},
2016-12-01 06:14:05 +03:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following block of code illustrates how to evaluate a single sequence. Additionally we show how one can pass in the information using NumPy arrays."
]
},
2016-10-26 10:37:04 +03:00
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 12,
2016-10-26 10:37:04 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[178, 429, 444, 619, 937, 851, 752, 179]\n",
"(1, 8, 129)\n",
"[128 128 128 48 110 128 78 128]\n"
]
},
{
"data": {
"text/plain": [
"[('BOS', 'O'),\n",
" ('flights', 'O'),\n",
" ('from', 'O'),\n",
" ('new', 'B-fromloc.city_name'),\n",
" ('york', 'I-fromloc.city_name'),\n",
" ('to', 'O'),\n",
" ('seattle', 'B-toloc.city_name'),\n",
" ('EOS', 'O')]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
2016-10-26 10:37:04 +03:00
"source": [
2016-10-31 23:51:01 +03:00
"# load dictionaries\n",
2016-12-08 23:42:46 +03:00
"query_wl = [line.rstrip('\\n') for line in open(data['query']['file'])]\n",
"slots_wl = [line.rstrip('\\n') for line in open(data['slots']['file'])]\n",
2016-10-31 23:51:01 +03:00
"query_dict = {query_wl[i]:i for i in range(len(query_wl))}\n",
"slots_dict = {slots_wl[i]:i for i in range(len(slots_wl))}\n",
"\n",
2016-10-26 10:37:04 +03:00
"# let's run a sequence through\n",
2016-10-31 23:51:01 +03:00
"seq = 'BOS flights from new york to seattle EOS'\n",
"w = [query_dict[w] for w in seq.split()] # convert to word indices\n",
2016-10-26 10:37:04 +03:00
"print(w)\n",
"onehot = np.zeros([len(w),len(query_dict)], np.float32)\n",
"for t in range(len(w)):\n",
" onehot[t,w[t]] = 1\n",
2017-03-29 11:41:04 +03:00
"pred = model.eval({model.arguments[0]:[onehot]})[0]\n",
2016-10-26 10:37:04 +03:00
"print(pred.shape)\n",
2017-03-29 11:41:04 +03:00
"best = np.argmax(pred,axis=1)\n",
"print(best)\n",
"list(zip(seq.split(),[slots_wl[s] for s in best]))"
2016-10-26 10:37:04 +03:00
]
},
{
2016-10-26 18:53:19 +03:00
"cell_type": "markdown",
2016-10-26 10:37:04 +03:00
"metadata": {},
2016-10-26 06:35:09 +03:00
"source": [
"## Modifying the Model\n",
"\n",
"In the following, you will be given tasks to practice modifying CNTK configurations.\n",
"The solutions are given at the end of this document... but please try without!\n",
"\n",
"### A Word About [`Sequential()`](https://www.cntk.ai/pythondocs/layerref.html#sequential)\n",
"\n",
"Before jumping to the tasks, let's have a look again at the model we just ran.\n",
"The model is described in what we call *function-composition style*.\n",
"```python\n",
" Sequential([\n",
" Embedding(emb_dim),\n",
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
" Dense(num_labels)\n",
" ])\n",
"```\n",
"You may be familiar with the \"sequential\" notation from other neural-network toolkits.\n",
"If not, [`Sequential()`](https://www.cntk.ai/pythondocs/layerref.html#sequential) is a powerful operation that,\n",
"in a nutshell, allows to compactly express a very common situation in neural networks\n",
"where an input is processed by propagating it through a progression of layers.\n",
"`Sequential()` takes an list of functions as its argument,\n",
"and returns a *new* function that invokes these functions in order,\n",
"each time passing the output of one to the next.\n",
"For example,\n",
"```python\n",
"\tFGH = Sequential ([F,G,H])\n",
" y = FGH (x)\n",
"```\n",
"means the same as\n",
"```\n",
" y = H(G(F(x))) \n",
"```\n",
"This is known as [\"function composition\"](https://en.wikipedia.org/wiki/Function_composition),\n",
"and is especially convenient for expressing neural networks, which often have this form:\n",
"\n",
" +-------+ +-------+ +-------+\n",
" x -->| F |-->| G |-->| H |--> y\n",
" +-------+ +-------+ +-------+\n",
"\n",
"Coming back to our model at hand, the `Sequential` expression simply\n",
"says that our model has this form:\n",
"\n",
" +-----------+ +----------------+ +------------+\n",
" x -->| Embedding |-->| Recurrent LSTM |-->| DenseLayer |--> y\n",
" +-----------+ +----------------+ +------------+"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 1: Add Batch Normalization\n",
"\n",
"We now want to add new layers to the model, specifically batch normalization.\n",
"\n",
"Batch normalization is a popular technique for speeding up convergence.\n",
"It is often used for image-processing setups, for example our other [hands-on lab on image\n",
"recognition](./Hands-On-Labs-Image-Recognition).\n",
"But could it work for recurrent models, too?\n",
2016-11-18 21:15:15 +03:00
"\n",
"> Note: training with Batch Normalization is currently only supported on GPU.\n",
"\n",
2016-10-26 06:35:09 +03:00
"So your task will be to insert batch-normalization layers before and after the recurrent LSTM layer.\n",
2017-03-15 12:46:15 +03:00
"If you have completed the [hands-on labs on image processing](https://github.com/Microsoft/CNTK/blob/v2.0.beta15.0/Tutorials/CNTK_201B_CIFAR-10_ImageHandsOn.ipynb),\n",
2016-10-26 06:35:09 +03:00
"you may remember that the [batch-normalization layer](https://www.cntk.ai/pythondocs/layerref.html#batchnormalization-layernormalization-stabilizer) has this form:\n",
"```\n",
" BatchNormalization()\n",
"```\n",
"So please go ahead and modify the configuration and see what happens.\n",
"\n",
"If everything went right, you will notice improved convergence speed (`loss` and `metric`)\n",
"compared to the previous configuration."
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 13,
2016-10-26 06:35:09 +03:00
"metadata": {
2016-10-26 10:37:04 +03:00
"collapsed": false
2016-10-26 06:35:09 +03:00
},
"outputs": [],
"source": [
2016-10-31 23:51:01 +03:00
"# Your task: Add batch normalization\n",
2016-10-26 06:35:09 +03:00
"def create_model():\n",
2016-10-26 10:37:04 +03:00
" with default_options(initial_state=0.1):\n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
" Embedding(emb_dim),\n",
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
" Dense(num_labels)\n",
" ])\n",
2016-10-31 23:51:01 +03:00
"\n",
2016-12-08 23:42:46 +03:00
"# Enable these when done:\n",
"#do_train()\n",
"#do_test()"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 2: Add a Lookahead \n",
"\n",
"Our recurrent model suffers from a structural deficit:\n",
"Since the recurrence runs from left to right, the decision for a slot label\n",
"has no information about upcoming words. The model is a bit lopsided.\n",
"Your task will be to modify the model such that\n",
"the input to the recurrence consists not only of the current word, but also of the next one\n",
"(lookahead).\n",
"\n",
"Your solution should be in function-composition style.\n",
"Hence, you will need to write a Python function that does the following:\n",
"\n",
"* takes no input arguments\n",
2016-10-31 23:51:01 +03:00
"* creates a placeholder (sequence) variable\n",
"* computes the \"next value\" in this sequence using the `future_value()` operation and\n",
"* concatenates the current and the next value into a vector of twice the embedding dimension using `splice()`\n",
2016-10-26 06:35:09 +03:00
"\n",
2016-10-31 23:51:01 +03:00
"and then insert this function into `Sequential()`'s list right after the embedding layer."
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 14,
2016-10-26 06:35:09 +03:00
"metadata": {
2016-10-26 10:37:04 +03:00
"collapsed": false
2016-10-26 06:35:09 +03:00
},
"outputs": [],
"source": [
2016-10-31 23:51:01 +03:00
"# Your task: Add lookahead\n",
2016-10-26 06:35:09 +03:00
"def create_model():\n",
2016-10-26 10:37:04 +03:00
" with default_options(initial_state=0.1):\n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
" Embedding(emb_dim),\n",
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
" Dense(num_labels)\n",
" ])\n",
2016-12-08 23:42:46 +03:00
" \n",
"# Enable these when done:\n",
"#do_train()\n",
"#do_test()"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 3: Bidirectional Recurrent Model\n",
"\n",
"Aha, knowledge of future words help. So instead of a one-word lookahead,\n",
"why not look ahead until all the way to the end of the sentence, through a backward recurrence?\n",
"Let us create a bidirectional model!\n",
"\n",
"Your task is to implement a new layer that\n",
"performs both a forward and a backward recursion over the data, and\n",
"concatenates the output vectors.\n",
"\n",
"Note, however, that this differs from the previous task in that\n",
"the bidirectional layer contains learnable model parameters.\n",
"In function-composition style,\n",
"the pattern to implement a layer with model parameters is to write a *factory function*\n",
"that creates a *function object*.\n",
"\n",
2016-10-31 23:51:01 +03:00
"A function object, also known as [*functor*](https://en.wikipedia.org/wiki/Function_object), is an object that is both a function and an object.\n",
2016-10-26 06:35:09 +03:00
"Which means nothing else that it contains data yet still can be invoked as if it was a function.\n",
"\n",
"For example, `Dense(outDim)` is a factory function that returns a function object that contains\n",
2016-10-31 23:51:01 +03:00
"a weight matrix `W`, a bias `b`, and another function to compute \n",
"`input @ W + b.` (This is using \n",
"[Python 3.5 notation for matrix multiplication](https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-465).\n",
"In Numpy syntax it is `input.dot(W) + b`).\n",
2016-10-26 06:35:09 +03:00
"E.g. saying `Dense(1024)` will create this function object, which can then be used\n",
"like any other function, also immediately: `Dense(1024)(x)`. \n",
"\n",
2016-10-31 23:51:01 +03:00
"Let's look at an example for further clarity: Let us implement a new layer that combines\n",
2016-10-26 06:35:09 +03:00
"a linear layer with a subsequent batch normalization. \n",
"To allow function composition, the layer needs to be realized as a factory function,\n",
"which could look like this:\n",
"\n",
"```python\n",
"def DenseLayerWithBN(dim):\n",
" F = Dense(dim)\n",
" G = BatchNormalization()\n",
2017-03-29 12:07:15 +03:00
" x = placeholder()\n",
2016-10-26 06:35:09 +03:00
" apply_x = G(F(x))\n",
" return apply_x\n",
"```\n",
"\n",
"Invoking this factory function will create `F`, `G`, `x`, and `apply_x`. In this example, `F` and `G` are function objects themselves, and `apply_x` is the function to be applied to the data.\n",
"Thus, e.g. calling `DenseLayerWithBN(1024)` will\n",
"create an object containing a linear-layer function object called `F`, a batch-normalization function object `G`,\n",
"and `apply_x` which is the function that implements the actual operation of this layer\n",
"using `F` and `G`. It will then return `apply_x`. To the outside, `apply_x` looks and behaves\n",
"like a function. Under the hood, however, `apply_x` retains access to its specific instances of `F` and `G`.\n",
"\n",
"Now back to our task at hand. You will now need to create a factory function,\n",
"very much like the example above.\n",
"You shall create a factory function\n",
"that creates two recurrent layer instances (one forward, one backward), and then defines an `apply_x` function\n",
"which applies both layer instances to the same `x` and concatenate the two results.\n",
"\n",
2016-11-17 00:33:23 +03:00
"Alright, give it a try! To know how to realize a backward recursion in CNTK,\n",
2016-10-26 06:35:09 +03:00
"please take a hint from how the forward recursion is done.\n",
"Please also do the following:\n",
"* remove the one-word lookahead you added in the previous task, which we aim to replace; and\n",
2016-10-31 23:51:01 +03:00
"* make sure each LSTM is using `hidden_dim//2` outputs to keep the total number of model parameters limited."
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 15,
2016-10-26 06:35:09 +03:00
"metadata": {
2016-10-26 10:37:04 +03:00
"collapsed": false
2016-10-26 06:35:09 +03:00
},
"outputs": [],
"source": [
2016-10-31 23:51:01 +03:00
"# Your task: Add bidirectional recurrence\n",
2016-10-26 06:35:09 +03:00
"def create_model():\n",
2016-10-31 23:51:01 +03:00
" with default_options(initial_state=0.1): \n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
" Embedding(emb_dim),\n",
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
" Dense(num_labels)\n",
" ])\n",
2016-12-08 23:42:46 +03:00
"\n",
"# Enable these when done:\n",
"#do_train()\n",
"#do_test()"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
2016-10-31 23:51:01 +03:00
"Works like a charm! This model achieves 2.1%, a tiny bit better than the lookahead model above.\n",
2016-10-26 06:35:09 +03:00
"The bidirectional model has 40% less parameters than the lookahead one. However, if you go back and look closely\n",
2016-10-31 23:51:01 +03:00
"you may find that the lookahead one trained about 30% faster.\n",
2016-10-26 06:35:09 +03:00
"This is because the lookahead model has both less horizontal dependencies (one instead of two\n",
"recurrences) and larger matrix products, and can thus achieve higher parallelism."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Solution 1: Adding Batch Normalization"
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 16,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Training 722379 parameters in 10 parameter tensors.\n",
2017-03-29 12:07:15 +03:00
"Finished Epoch[1 of 16]: [Training] loss = 0.442527 * 18010, metric = 0.00% * 18010 4.111s (4380.9 samples/s);\n",
"Finished Epoch[2 of 16]: [Training] loss = 0.162579 * 18051, metric = 0.00% * 18051 3.543s (5094.8 samples/s);\n",
"Finished Epoch[3 of 16]: [Training] loss = 0.118221 * 17941, metric = 0.00% * 17941 3.453s (5195.8 samples/s);\n",
"Finished Epoch[4 of 16]: [Training] loss = 0.091876 * 18059, metric = 0.00% * 18059 3.578s (5047.2 samples/s);\n",
"Finished Epoch[5 of 16]: [Training] loss = 0.050012 * 17957, metric = 0.00% * 17957 3.531s (5085.5 samples/s);\n",
"Finished Epoch[6 of 16]: [Training] loss = 0.048105 * 18021, metric = 0.00% * 18021 3.466s (5199.4 samples/s);\n",
"Finished Epoch[7 of 16]: [Training] loss = 0.043658 * 17980, metric = 0.00% * 17980 3.395s (5296.0 samples/s);\n",
"Finished Epoch[8 of 16]: [Training] loss = 0.036579 * 18025, metric = 0.00% * 18025 3.464s (5203.5 samples/s);\n",
"Finished Epoch[9 of 16]: [Training] loss = 0.025926 * 17956, metric = 0.00% * 17956 3.461s (5188.1 samples/s);\n",
"Finished Epoch[10 of 16]: [Training] loss = 0.026058 * 18039, metric = 0.00% * 18039 3.445s (5236.3 samples/s);\n",
"Finished Epoch[11 of 16]: [Training] loss = 0.027655 * 17966, metric = 0.00% * 17966 3.443s (5218.1 samples/s);\n",
"Finished Epoch[12 of 16]: [Training] loss = 0.017355 * 18041, metric = 0.00% * 18041 3.400s (5306.2 samples/s);\n",
"Finished Epoch[13 of 16]: [Training] loss = 0.019586 * 17984, metric = 0.00% * 17984 3.559s (5053.1 samples/s);\n",
"Finished Epoch[14 of 16]: [Training] loss = 0.019649 * 17976, metric = 0.00% * 17976 3.391s (5301.1 samples/s);\n",
"Finished Epoch[15 of 16]: [Training] loss = 0.019151 * 18030, metric = 0.00% * 18030 3.277s (5502.0 samples/s);\n",
"Finished Epoch[16 of 16]: [Training] loss = 0.013417 * 18014, metric = 0.00% * 18014 3.500s (5146.9 samples/s);\n",
2017-03-16 08:07:51 +03:00
"Finished Evaluation [1]: Minibatch[1-23]: metric = 2.08% * 10984;\n"
2017-02-03 04:40:20 +03:00
]
}
],
2016-10-26 06:35:09 +03:00
"source": [
"def create_model():\n",
2016-10-31 23:51:01 +03:00
" with default_options(initial_state=0.1):\n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
" Embedding(emb_dim),\n",
" BatchNormalization(),\n",
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
" BatchNormalization(),\n",
" Dense(num_labels)\n",
" ])\n",
"\n",
2016-10-31 23:51:01 +03:00
"do_train()\n",
"do_test()"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Solution 2: Add a Lookahead"
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 17,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Training 901479 parameters in 6 parameter tensors.\n",
2017-03-29 12:07:15 +03:00
"Finished Epoch[1 of 16]: [Training] loss = 1.042147 * 18010, metric = 0.00% * 18010 3.837s (4693.8 samples/s);\n",
"Finished Epoch[2 of 16]: [Training] loss = 0.367830 * 18051, metric = 0.00% * 18051 3.642s (4956.3 samples/s);\n",
"Finished Epoch[3 of 16]: [Training] loss = 0.240927 * 17941, metric = 0.00% * 17941 3.681s (4873.9 samples/s);\n",
"Finished Epoch[4 of 16]: [Training] loss = 0.162869 * 18059, metric = 0.00% * 18059 3.922s (4604.5 samples/s);\n",
"Finished Epoch[5 of 16]: [Training] loss = 0.117314 * 17957, metric = 0.00% * 17957 4.501s (3989.6 samples/s);\n",
"Finished Epoch[6 of 16]: [Training] loss = 0.104019 * 18021, metric = 0.00% * 18021 4.452s (4047.8 samples/s);\n",
"Finished Epoch[7 of 16]: [Training] loss = 0.091837 * 17980, metric = 0.00% * 17980 3.672s (4896.5 samples/s);\n",
"Finished Epoch[8 of 16]: [Training] loss = 0.085473 * 18025, metric = 0.00% * 18025 3.660s (4924.9 samples/s);\n",
"Finished Epoch[9 of 16]: [Training] loss = 0.055418 * 17956, metric = 0.00% * 17956 3.668s (4895.3 samples/s);\n",
"Finished Epoch[10 of 16]: [Training] loss = 0.056879 * 18039, metric = 0.00% * 18039 3.616s (4988.7 samples/s);\n",
"Finished Epoch[11 of 16]: [Training] loss = 0.059523 * 17966, metric = 0.00% * 17966 3.561s (5045.2 samples/s);\n",
"Finished Epoch[12 of 16]: [Training] loss = 0.038848 * 18041, metric = 0.00% * 18041 3.594s (5019.8 samples/s);\n",
"Finished Epoch[13 of 16]: [Training] loss = 0.042280 * 17984, metric = 0.00% * 17984 3.670s (4900.3 samples/s);\n",
"Finished Epoch[14 of 16]: [Training] loss = 0.046722 * 17976, metric = 0.00% * 17976 3.591s (5005.8 samples/s);\n",
"Finished Epoch[15 of 16]: [Training] loss = 0.037370 * 18030, metric = 0.00% * 18030 3.629s (4968.3 samples/s);\n",
"Finished Epoch[16 of 16]: [Training] loss = 0.034207 * 18014, metric = 0.00% * 18014 3.650s (4935.3 samples/s);\n",
2017-03-16 08:07:51 +03:00
"Finished Evaluation [1]: Minibatch[1-23]: metric = 2.18% * 10984;\n"
2017-02-03 04:40:20 +03:00
]
}
],
2016-10-26 06:35:09 +03:00
"source": [
"def OneWordLookahead():\n",
2017-03-29 12:07:15 +03:00
" x = C.placeholder()\n",
2017-02-10 04:06:09 +03:00
" apply_x = splice (x, future_value(x))\n",
2016-10-26 06:35:09 +03:00
" return apply_x\n",
"\n",
"def create_model():\n",
2016-10-31 23:51:01 +03:00
" with default_options(initial_state=0.1):\n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
" Embedding(emb_dim),\n",
" OneWordLookahead(),\n",
" Recurrence(LSTM(hidden_dim), go_backwards=False),\n",
" Dense(num_labels) \n",
" ])\n",
"\n",
2016-10-31 23:51:01 +03:00
"do_train()\n",
"do_test()"
2016-10-26 06:35:09 +03:00
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Solution 3: Bidirectional Recurrent Model"
]
},
{
"cell_type": "code",
2017-02-03 04:40:20 +03:00
"execution_count": 18,
2016-10-26 06:35:09 +03:00
"metadata": {
"collapsed": false
},
2017-02-03 04:40:20 +03:00
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Training 541479 parameters in 9 parameter tensors.\n",
2017-03-29 12:07:15 +03:00
"Finished Epoch[1 of 16]: [Training] loss = 1.066098 * 18010, metric = 0.00% * 18010 6.280s (2867.8 samples/s);\n",
"Finished Epoch[2 of 16]: [Training] loss = 0.398866 * 18051, metric = 0.00% * 18051 6.111s (2953.9 samples/s);\n",
"Finished Epoch[3 of 16]: [Training] loss = 0.256761 * 17941, metric = 0.00% * 17941 6.036s (2972.3 samples/s);\n",
"Finished Epoch[4 of 16]: [Training] loss = 0.179482 * 18059, metric = 0.00% * 18059 6.233s (2897.3 samples/s);\n",
"Finished Epoch[5 of 16]: [Training] loss = 0.130943 * 17957, metric = 0.00% * 17957 6.140s (2924.6 samples/s);\n",
"Finished Epoch[6 of 16]: [Training] loss = 0.115195 * 18021, metric = 0.00% * 18021 6.050s (2978.7 samples/s);\n",
"Finished Epoch[7 of 16]: [Training] loss = 0.095112 * 17980, metric = 0.00% * 17980 6.009s (2992.2 samples/s);\n",
"Finished Epoch[8 of 16]: [Training] loss = 0.094233 * 18025, metric = 0.00% * 18025 6.143s (2934.2 samples/s);\n",
"Finished Epoch[9 of 16]: [Training] loss = 0.062660 * 17956, metric = 0.00% * 17956 6.010s (2987.7 samples/s);\n",
"Finished Epoch[10 of 16]: [Training] loss = 0.063548 * 18039, metric = 0.00% * 18039 6.121s (2947.1 samples/s);\n",
"Finished Epoch[11 of 16]: [Training] loss = 0.063781 * 17966, metric = 0.00% * 17966 6.054s (2967.6 samples/s);\n",
"Finished Epoch[12 of 16]: [Training] loss = 0.046256 * 18041, metric = 0.00% * 18041 6.104s (2955.6 samples/s);\n",
"Finished Epoch[13 of 16]: [Training] loss = 0.048350 * 17984, metric = 0.00% * 17984 6.316s (2847.4 samples/s);\n",
"Finished Epoch[14 of 16]: [Training] loss = 0.054151 * 17976, metric = 0.00% * 17976 6.018s (2987.0 samples/s);\n",
"Finished Epoch[15 of 16]: [Training] loss = 0.041818 * 18030, metric = 0.00% * 18030 6.241s (2889.0 samples/s);\n",
"Finished Epoch[16 of 16]: [Training] loss = 0.040104 * 18014, metric = 0.00% * 18014 6.159s (2924.8 samples/s);\n",
2017-03-16 08:07:51 +03:00
"Finished Evaluation [1]: Minibatch[1-23]: metric = 2.04% * 10984;\n"
2017-02-03 04:40:20 +03:00
]
}
],
2016-10-26 06:35:09 +03:00
"source": [
"def BiRecurrence(fwd, bwd):\n",
" F = Recurrence(fwd)\n",
" G = Recurrence(bwd, go_backwards=True)\n",
2017-03-29 12:07:15 +03:00
" x = C.placeholder()\n",
2017-02-10 04:06:09 +03:00
" apply_x = splice (F(x), G(x))\n",
2016-10-26 06:35:09 +03:00
" return apply_x \n",
"\n",
"def create_model():\n",
2016-10-31 23:51:01 +03:00
" with default_options(initial_state=0.1):\n",
2016-10-26 06:35:09 +03:00
" return Sequential([\n",
" Embedding(emb_dim),\n",
2016-10-31 23:51:01 +03:00
" BiRecurrence(LSTM(hidden_dim//2), LSTM(hidden_dim//2)),\n",
2016-10-26 06:35:09 +03:00
" Dense(num_labels)\n",
" ])\n",
"\n",
2016-10-31 23:51:01 +03:00
"do_train()\n",
"do_test()"
2016-10-26 06:35:09 +03:00
]
2016-10-31 23:51:01 +03:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
2016-10-26 06:35:09 +03:00
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
2017-03-16 08:07:51 +03:00
"display_name": "Python [default]",
2016-10-26 06:35:09 +03:00
"language": "python",
2016-11-18 21:15:15 +03:00
"name": "python3"
2016-10-26 06:35:09 +03:00
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
2017-02-03 04:40:20 +03:00
"version": "3.5.2"
2016-10-26 06:35:09 +03:00
}
},
"nbformat": 4,
"nbformat_minor": 1
}