<jupyter_start><jupyter_text>CNTK 201B: Hands On Labs Image Recognition This hands-on lab shows how to implement image recognition task using [convolution network][] with CNTK v2 Python API. You will start with a basic feedforward CNN architecture in order to classify Cifar dataset, then you will keep adding advanced feature to your network. Finally, you will implement a VGG net and residual net similar to the one that won ImageNet competition but smaller in size.[convolution network]:https://en.wikipedia.org/wiki/Convolutional_neural_network IntroductionIn this hands-on, you will practice the following:* Understanding subset of CNTK python API needed for image classification task.* Write a custom convolution network to classify Cifar dataset.* Modifying the network structure by adding: * [Dropout][] layer. * Batchnormalization layer.* Implement a [VGG][] style network.* Introduction to Residual Nets (RESNET).* Implement and train [RESNET network][].[RESNET network]:https://github.com/Microsoft/CNTK/wiki/Hands-On-Labs-Image-Recognition[VGG]:http://www.robots.ox.ac.uk/~vgg/research/very_deep/[Dropout]:https://en.wikipedia.org/wiki/Dropout_(neural_networks) PrerequisitesCNTK 201A hands-on lab, in which you will download and prepare Cifar dataset is a prerequisites for this lab. This tutorial depends on CNTK v2, so before starting this lab you will need to install CNTK v2. Furthermore, all the tutorials in this lab are done in python, therefore, you will need a basic knowledge of Python.CNTK 102 lab is recommended but not a prerequisites for this tutorials. However, a basic understanding of Deep Learning is needed. DatasetYou will use Cifar 10 dataset, from https://www.cs.toronto.edu/~kriz/cifar.html, during this tutorials. The dataset  contains 50000 training images and 10000 test images, all images are 32x32x3. Each image is classified as one of 10 classes as shown below:<jupyter_code># Figure 1
Image(url="https://cntk.ai/jup/201/cifar-10.png", width=500, height=500)<jupyter_output><empty_output><jupyter_text>The above image is from: https://www.cs.toronto.edu/~kriz/cifar.html Convolution Neural Network (CNN)Convolution Neural Network (CNN) is a feedforward network comprise of a bunch of layers in such a way that the output of one layer is fed to the next layer (There are more complex architecture that skip layers, we will discuss one of those at the end of this lab). Usually, CNN start with alternating between convolution layer and pooling layer (downsample), then end up with fully connected layer for the classification part. Convolution layerConvolution layer consist of multiple 2D convolution kernels applied on the input image or the previous layer, each convolution kernel output a feature map.<jupyter_code># Figure 2
Image(url="https://cntk.ai/jup/201/Conv2D.png")<jupyter_output><empty_output><jupyter_text>The stack of feature maps output are the input to the next layer.<jupyter_code># Figure 3
Image(url="https://cntk.ai/jup/201/Conv2DFeatures.png")<jupyter_output><empty_output><jupyter_text>> Gradient-Based Learning Applied to Document Recognition, Proceedings of the IEEE, 86(11):2278-2324, November 1998> <NAME>, <NAME>, <NAME> and <NAME> In CNTK:Here the [convolution][] layer in Python:```pythondef Convolution(filter_shape,         e.g. (3,3)                num_filters,          e.g. 64                activation,           relu or None...etc.                init,                 Random initialization                pad,                  True or False                strides)              strides e.g. (1,1)```[convolution]:https://www.cntk.ai/pythondocs/layerref.htmlconvolution Pooling layerIn most CNN vision architecture, each convolution layer is succeeded by a pooling layer, so they keep alternating until the fully connected layer. The purpose of the pooling layer is as follow:* Reduce the dimensionality of the previous layer, which speed up the network.* Provide a limited translation invariant.Here an example of max pooling with a stride of 2:<jupyter_code># Figure 4
Image(url="https://cntk.ai/jup/201/MaxPooling.png", width=400, height=400)<jupyter_output><empty_output><jupyter_text>In CNTK:Here the [pooling][] layer in Python:```python Max poolingdef MaxPooling(filter_shape,   e.g. (3,3)               strides,        (2,2)               pad)            True or False Average poolingdef AveragePooling(filter_shape,   e.g. (3,3)                   strides,        (2,2)                   pad)            True or False```[pooling]:https://www.cntk.ai/pythondocs/layerref.htmlmaxpooling-averagepooling Dropout layerDropout layer takes a probability value as an input, the value is called the dropout rate. Let's say the dropu rate is 0.5, what this layer does it pick at random 50% of the nodes from the previous layer and drop them out of the nework. This behavior help regularize the network.> Dropout: A Simple Way to Prevent Neural Networks from Overfitting> <NAME>, <NAME>, <NAME>, <NAME>, <NAME> In CNTK:Dropout layer in Python:```python Dropoutdef Dropout(prob)     dropout rate e.g. 0.5``` Batch normalization (BN)Batch normalization is a way to make the input to each layer has zero mean and unit variance. BN help the network converge faster and keep the input of each layer around zero. BN has two learnable parameters called gamma and beta, the purpose of those parameters is for the network to decide for itself if the normalized input is what is best or the raw input.> Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift> <NAME>, <NAME> In CNTK:[Batch normalization][] layer in Python:```python Batch normalizationdef BatchNormalization(map_rank)   For image map_rank=1```[Batch normalization]:https://www.cntk.ai/pythondocs/layerref.htmlbatchnormalization-layernormalization-stabilizer Microsoft Cognitive Network Toolkit (CNTK)CNTK is a highly flexible computation graphs, each node take inputs as tensors and produce tensors as the result of the computation. Each node is exposed in Python API, which give you the flexibility of creating any custom graphs, you can also define your own node in Python or C++ using CPU, GPU or both.For Deep learning, you can use the low level API directly or you can use CNTK layered API. We will start with the low level API, then switch to the layered API in this lab.So let's first import the needed modules for this lab.<jupyter_code>from __future__ import print_function
import os
import numpy as np
import matplotlib.pyplot as plt
import math

from cntk.layers import default_options, Convolution, MaxPooling, AveragePooling, Dropout, BatchNormalization, Dense, Sequential, For
from cntk.io import MinibatchSource, ImageDeserializer, StreamDef, StreamDefs
import cntk.io.transforms as xforms 
from cntk.initializer import glorot_uniform, he_normal
from cntk import Trainer
from cntk.learner import momentum_sgd, learning_rate_schedule, UnitType, momentum_as_time_constant_schedule
from cntk.ops import cross_entropy_with_softmax, classification_error, relu, input_variable, softmax, element_times
from cntk.utils import *
# Figure 5
Image(url="https://cntk.ai/jup/201/CNN.png")<jupyter_output><empty_output><jupyter_text>Now that we imported the needed modules, let's implement our first CNN, as shown in Figure 5 above.Let's implement the above network using CNTK layer API:<jupyter_code>def create_basic_model(input, out_dims):
    
    net = Convolution((5,5), 32, init=glorot_uniform(), activation=relu, pad=True)(input)
    net = MaxPooling((3,3), strides=(2,2))(net)

    net = Convolution((5,5), 32, init=glorot_uniform(), activation=relu, pad=True)(net)
    net = MaxPooling((3,3), strides=(2,2))(net)

    net = Convolution((5,5), 64, init=glorot_uniform(), activation=relu, pad=True)(net)
    net = MaxPooling((3,3), strides=(2,2))(net)
    
    net = Dense(64, init=glorot_uniform())(net)
    net = Dense(out_dims, init=glorot_uniform(), activation=None)(net)
    
    return net<jupyter_output><empty_output><jupyter_text>To train the above model we need two things:* Read the training images and their corresponding labels.* Define a cost function, compute the cost for each mini-batch and update the model weights according to the cost value.To read the data in CNTK, we will use CNTK readers which handle data augmentation and can fetch data in parallel.Example of a map text file:    S:\data\CIFAR-10\train\00001.png	9    S:\data\CIFAR-10\train\00002.png	9    S:\data\CIFAR-10\train\00003.png	4    S:\data\CIFAR-10\train\00004.png	1    S:\data\CIFAR-10\train\00005.png	1<jupyter_code># model dimensions
image_height = 32
image_width  = 32
num_channels = 3
num_classes  = 10

#
# Define the reader for both training and evaluation action.
#
def create_reader(map_file, mean_file, train):
    if not os.path.exists(map_file) or not os.path.exists(mean_file):
        raise RuntimeError("This tutorials depends 201A tutorials, please run 201A first.")

    # transformation pipeline for the features has jitter/crop only when training
    transforms = []
    if train:
        transforms += [
            xforms.crop(crop_type='randomside', side_ratio=0.8) # train uses data augmentation (translation only)
        ]
    transforms += [
        xforms.scale(width=image_width, height=image_height, channels=num_channels, interpolations='linear'),
        xforms.mean(mean_file)
    ]
    # deserializer
    return MinibatchSource(ImageDeserializer(map_file, StreamDefs(
        features = StreamDef(field='image', transforms=transforms), # first column in map file is referred to as 'image'
        labels   = StreamDef(field='label', shape=num_classes)      # and second as 'label'
    )))<jupyter_output><empty_output><jupyter_text>Now let us write the the training and validation loop.<jupyter_code>#
# Train and evaluate the network.
#
def train_and_evaluate(reader_train, reader_test, max_epochs, model_func):
    # Input variables denoting the features and label data
    input_var = input_variable((num_channels, image_height, image_width))
    label_var = input_variable((num_classes))

    # Normalize the input
    feature_scale = 1.0 / 256.0
    input_var_norm = element_times(feature_scale, input_var)
    
    # apply model to input
    z = model_func(input_var_norm, out_dims=10)

    #
    # Training action
    #

    # loss and metric
    ce = cross_entropy_with_softmax(z, label_var)
    pe = classification_error(z, label_var)

    # training config
    epoch_size     = 50000
    minibatch_size = 64

    # Set training parameters
    lr_per_minibatch       = learning_rate_schedule([0.01]*10 + [0.003]*10 + [0.001], UnitType.minibatch, epoch_size)
    momentum_time_constant = momentum_as_time_constant_schedule(-minibatch_size/np.log(0.9))
    l2_reg_weight          = 0.001
    
    # trainer object
    learner = momentum_sgd(z.parameters, 
                           lr = lr_per_minibatch, momentum = momentum_time_constant, 
                           l2_regularization_weight=l2_reg_weight)
    progress_printer = ProgressPrinter(tag='Training', num_epochs=max_epochs)
    trainer = Trainer(z, (ce, pe), [learner], [progress_printer])

    # define mapping from reader streams to network inputs
    input_map = {
        input_var: reader_train.streams.features,
        label_var: reader_train.streams.labels
    }

    log_number_of_parameters(z) ; print()

    # perform model training
    batch_index = 0
    plot_data = {'batchindex':[], 'loss':[], 'error':[]}
    for epoch in range(max_epochs):       # loop over epochs
        sample_count = 0
        while sample_count < epoch_size:  # loop over minibatches in the epoch
            data = reader_train.next_minibatch(min(minibatch_size, epoch_size - sample_count), input_map=input_map) # fetch minibatch.
            trainer.train_minibatch(data)                                   # update model with it

            sample_count += data[label_var].num_samples                     # count samples processed so far
            
            # For visualization...            
            plot_data['batchindex'].append(batch_index)
            plot_data['loss'].append(trainer.previous_minibatch_loss_average)
            plot_data['error'].append(trainer.previous_minibatch_evaluation_average)
            
            batch_index += 1
        trainer.summarize_training_progress()
        
    #
    # Evaluation action
    #
    epoch_size     = 10000
    minibatch_size = 16

    # process minibatches and evaluate the model
    metric_numer    = 0
    metric_denom    = 0
    sample_count    = 0
    minibatch_index = 0

    while sample_count < epoch_size:
        current_minibatch = min(minibatch_size, epoch_size - sample_count)

        # Fetch next test min batch.
        data = reader_test.next_minibatch(current_minibatch, input_map=input_map)

        # minibatch data to be trained with
        metric_numer += trainer.test_minibatch(data) * current_minibatch
        metric_denom += current_minibatch

        # Keep track of the number of samples processed so far.
        sample_count += data[label_var].num_samples
        minibatch_index += 1

    print("")
    print("Final Results: Minibatch[1-{}]: errs = {:0.1f}% * {}".format(minibatch_index+1, (metric_numer*100.0)/metric_denom, metric_denom))
    print("")
    
    # Visualize training result:
    window_width            = 32
    loss_cumsum             = np.cumsum(np.insert(plot_data['loss'], 0, 0)) 
    error_cumsum            = np.cumsum(np.insert(plot_data['error'], 0, 0)) 

    # Moving average.
    plot_data['batchindex'] = np.insert(plot_data['batchindex'], 0, 0)[window_width:]
    plot_data['avg_loss']   = (loss_cumsum[window_width:] - loss_cumsum[:-window_width]) / window_width
    plot_data['avg_error']  = (error_cumsum[window_width:] - error_cumsum[:-window_width]) / window_width
    
    plt.figure(1)
    plt.subplot(211)
    plt.plot(plot_data["batchindex"], plot_data["avg_loss"], 'b--')
    plt.xlabel('Minibatch number')
    plt.ylabel('Loss')
    plt.title('Minibatch run vs. Training loss ')

    plt.show()

    plt.subplot(212)
    plt.plot(plot_data["batchindex"], plot_data["avg_error"], 'r--')
    plt.xlabel('Minibatch number')
    plt.ylabel('Label Prediction Error')
    plt.title('Minibatch run vs. Label Prediction Error ')
    plt.show()
    
    return softmax(z)
data_path = os.path.join('data', 'CIFAR-10')
reader_train = create_reader(os.path.join(data_path, 'train_map.txt'), os.path.join(data_path, 'CIFAR-10_mean.xml'), True)
reader_test  = create_reader(os.path.join(data_path, 'test_map.txt'), os.path.join(data_path, 'CIFAR-10_mean.xml'), False)

pred = train_and_evaluate(reader_train, reader_test, max_epochs=5, model_func=create_basic_model)<jupyter_output>Training 116906 parameters in 10 parameter tensors.

Finished Epoch[1 of 300]: [Training] loss = 2.062444 * 50000, metric = 75.3% * 50000 13.316s (3754.8 samples per second);
Finished Epoch[2 of 300]: [Training] loss = 1.675133 * 50000, metric = 61.7% * 50000 13.772s (3630.5 samples per second);
Finished Epoch[3 of 300]: [Training] loss = 1.520789 * 50000, metric = 55.4% * 50000 13.674s (3656.7 samples per second);
Finished Epoch[4 of 300]: [Training] loss = 1.421881 * 50000, metric = 51.4% * 50000 13.668s (3658.2 samples per second);
Finished Epoch[5 of 300]: [Training] loss = 1.338381 * 50000, metric = 48.0% * 50000 13.675s (3656.3 samples per second);

Final Results: Minibatch[1-626]: errs = 43.3% * 10000<jupyter_text>Although, this model is very simple, it still has too much code, we can do better. Here the same model in more terse format:<jupyter_code>def create_basic_model_terse(input, out_dims):

    with default_options(activation=relu):
        model = Sequential([
            For(range(3), lambda i: [
                Convolution((5,5), [32,32,64][i], init=glorot_uniform(), pad=True),
                MaxPooling((3,3), strides=(2,2))
            ]),
            Dense(64, init=glorot_uniform()),
            Dense(out_dims, init=glorot_uniform(), activation=None)
        ])

    return model(input)
pred_basic_model = train_and_evaluate(reader_train, reader_test, max_epochs=10, model_func=create_basic_model_terse)<jupyter_output>Training 116906 parameters in 10 parameter tensors.

Finished Epoch[1 of 300]: [Training] loss = 2.054147 * 50000, metric = 75.0% * 50000 13.674s (3656.6 samples per second);
Finished Epoch[2 of 300]: [Training] loss = 1.695077 * 50000, metric = 62.6% * 50000 14.271s (3503.7 samples per second);
Finished Epoch[3 of 300]: [Training] loss = 1.542115 * 50000, metric = 56.3% * 50000 13.872s (3604.3 samples per second);
Finished Epoch[4 of 300]: [Training] loss = 1.450798 * 50000, metric = 52.3% * 50000 13.823s (3617.3 samples per second);
Finished Epoch[5 of 300]: [Training] loss = 1.373555 * 50000, metric = 49.2% * 50000 13.857s (3608.4 samples per second);
Finished Epoch[6 of 300]: [Training] loss = 1.300828 * 50000, metric = 46.6% * 50000 13.965s (3580.3 samples per second);
Finished Epoch[7 of 300]: [Training] loss = 1.232516 * 50000, metric = 43.7% * 50000 13.827s (3616.0 samples per second);
Finished Epoch[8 of 300]: [Training] loss = 1.189415 * 50000, metric = 42.0% * 50000 13.885s [...]<jupyter_text>Now that we have a trained model, let's classify the following image:<jupyter_code># Figure 6
Image(url="https://cntk.ai/jup/201/00014.png", width=64, height=64)
import PIL

def eval(pred_op, image_path):
    label_lookup = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
    image_mean   = 133.0
    image_data   = np.array(PIL.Image.open(image_path), dtype=np.float32)
    image_data  -= image_mean
    image_data   = np.ascontiguousarray(np.transpose(image_data, (2, 0, 1)))
    
    result       = np.squeeze(pred_op.eval({pred_op.arguments[0]:[image_data]}))
    
    # Return top 3 results:
    top_count = 3
    result_indices = (-np.array(result)).argsort()[:top_count]

    print("Top 3 predictions:")
    for i in range(top_count):
        print("\tLabel: {:10s}, confidence: {:.2f}%".format(label_lookup[result_indices[i]], result[result_indices[i]] * 100))
eval(pred_basic_model, "data/CIFAR-10/test/00014.png")<jupyter_output>Top 3 predictions:
	Label: truck     , confidence: 98.95%
	Label: ship      , confidence: 0.46%
	Label: automobile, confidence: 0.26%<jupyter_text>Adding dropout layer, with drop rate of 0.25, before the last dense layer:<jupyter_code>def create_basic_model_with_dropout(input, out_dims):

    with default_options(activation=relu):
        model = Sequential([
            For(range(3), lambda i: [
                Convolution((5,5), [32,32,64][i], init=glorot_uniform(), pad=True),
                MaxPooling((3,3), strides=(2,2))
            ]),
            Dense(64, init=glorot_uniform()),
            Dropout(0.25),
            Dense(out_dims, init=glorot_uniform(), activation=None)
        ])

    return model(input)
pred_basic_model_dropout = train_and_evaluate(reader_train, reader_test, max_epochs=5, model_func=create_basic_model_with_dropout)<jupyter_output>Training 116906 parameters in 10 parameter tensors.

Finished Epoch[1 of 300]: [Training] loss = 2.123667 * 50000, metric = 78.7% * 50000 16.391s (3050.5 samples per second);
Finished Epoch[2 of 300]: [Training] loss = 1.817045 * 50000, metric = 67.9% * 50000 16.894s (2959.5 samples per second);
Finished Epoch[3 of 300]: [Training] loss = 1.678272 * 50000, metric = 62.2% * 50000 17.006s (2940.1 samples per second);
Finished Epoch[4 of 300]: [Training] loss = 1.583182 * 50000, metric = 58.1% * 50000 16.644s (3004.1 samples per second);
Finished Epoch[5 of 300]: [Training] loss = 1.514311 * 50000, metric = 55.3% * 50000 16.790s (2977.9 samples per second);

Final Results: Minibatch[1-626]: errs = 49.2% * 10000<jupyter_text>Add batch normalization after each convolution and before the last dense layer:<jupyter_code>def create_basic_model_with_batch_normalization(input, out_dims):

    with default_options(activation=relu):
        model = Sequential([
            For(range(3), lambda i: [
                Convolution((5,5), [32,32,64][i], init=glorot_uniform(), pad=True),
                BatchNormalization(map_rank=1),
                MaxPooling((3,3), strides=(2,2))
            ]),
            Dense(64, init=glorot_uniform()),
            BatchNormalization(map_rank=1),
            Dense(out_dims, init=glorot_uniform(), activation=None)
        ])

    return model(input)
pred_basic_model_bn = train_and_evaluate(reader_train, reader_test, max_epochs=5, model_func=create_basic_model_with_batch_normalization)<jupyter_output>Training 117290 parameters in 18 parameter tensors.

Finished Epoch[1 of 300]: [Training] loss = 1.512835 * 50000, metric = 54.1% * 50000 15.499s (3226.1 samples per second);
Finished Epoch[2 of 300]: [Training] loss = 1.206524 * 50000, metric = 42.8% * 50000 16.071s (3111.2 samples per second);
Finished Epoch[3 of 300]: [Training] loss = 1.087695 * 50000, metric = 38.3% * 50000 16.160s (3094.1 samples per second);
Finished Epoch[4 of 300]: [Training] loss = 1.008182 * 50000, metric = 35.4% * 50000 16.057s (3113.8 samples per second);
Finished Epoch[5 of 300]: [Training] loss = 0.953168 * 50000, metric = 33.4% * 50000 16.247s (3077.4 samples per second);

Final Results: Minibatch[1-626]: errs = 30.8% * 10000<jupyter_text>Let's implement an inspired VGG style network, using layer API, here the architecture:| VGG9          || ------------- || conv3-64      || conv3-64      || max3          ||               || conv3-96      || conv3-96      || max3          ||               || conv3-128     || conv3-128     || max3          ||               || FC-1024       || FC-1024       ||               || FC-10         |<jupyter_code>def create_vgg9_model(input, out_dims):
    with default_options(activation=relu):
        model = Sequential([
            For(range(3), lambda i: [
                Convolution((3,3), [64,96,128][i], init=glorot_uniform(), pad=True),
                Convolution((3,3), [64,96,128][i], init=glorot_uniform(), pad=True),
                MaxPooling((3,3), strides=(2,2))
            ]),
            For(range(2), lambda : [
                Dense(1024, init=glorot_uniform())
            ]),
            Dense(out_dims, init=glorot_uniform(), activation=None)
        ])
        
    return model(input)
pred_vgg = train_and_evaluate(reader_train, reader_test, max_epochs=5, model_func=create_vgg9_model)<jupyter_output>Training 2675978 parameters in 18 parameter tensors.

Finished Epoch[1 of 300]: [Training] loss = 2.253115 * 50000, metric = 83.6% * 50000 46.007s (1086.8 samples per second);
Finished Epoch[2 of 300]: [Training] loss = 1.931100 * 50000, metric = 71.8% * 50000 46.236s (1081.4 samples per second);
Finished Epoch[3 of 300]: [Training] loss = 1.706618 * 50000, metric = 63.3% * 50000 46.271s (1080.6 samples per second);
Finished Epoch[4 of 300]: [Training] loss = 1.576171 * 50000, metric = 58.1% * 50000 46.348s (1078.8 samples per second);
Finished Epoch[5 of 300]: [Training] loss = 1.473403 * 50000, metric = 53.7% * 50000 46.386s (1077.9 samples per second);

Final Results: Minibatch[1-626]: errs = 51.2% * 10000<jupyter_text>Residual Network (ResNet)One of the main problem of a Deep Neural Network is how to propagate the error all the way to the first layer. For a deep network, the gradient keep getting smaller until it has no effect on the network weights. [ResNet](https://arxiv.org/abs/1512.03385) was designed to overcome such problem, by defining a block with identity path, as shown below:<jupyter_code># Figure 7
Image(url="https://cntk.ai/jup/201/ResNetBlock2.png")<jupyter_output><empty_output><jupyter_text>The idea of the above block is 2 folds:* During back propagation the gradient have a path that doesn't affect its magnitude.* The network need to learn residual mapping (delta to x).So let's implements ResNet blocks using CNTK:            ResNetNode                   ResNetNodeInc                |                              |         +------+------+             +---------+----------+         |             |             |                    |         V             |             V                    V    +----------+       |      +--------------+   +----------------+    | Conv, BN |       |      | Conv x 2, BN |   | SubSample, BN  |    +----------+       |      +--------------+   +----------------+         |             |             |                    |         V             |             V                    |     +-------+         |         +-------+                |     | ReLU  |         |         | ReLU  |                |     +-------+         |         +-------+                |         |             |             |                    |         V             |             V                    |    +----------+       |        +----------+              |    | Conv, BN |       |        | Conv, BN |              |    +----------+       |        +----------+              |         |             |             |                    |         |    +---+    |             |       +---+        |         +--->| + |+ + +<-------+              +---+                          +---+                |                              |                V                              V            +-------+                      +-------+            | ReLU  |                      | ReLU  |            +-------+                      +-------+                |                              |                V                              V<jupyter_code>from cntk.ops import combine, times, element_times, AVG_POOLING

def convolution_bn(input, filter_size, num_filters, strides=(1,1), init=he_normal(), activation=relu):
    if activation is None:
        activation = lambda x: x
        
    r = Convolution(filter_size, num_filters, strides=strides, init=init, activation=None, pad=True, bias=False)(input)
    r = BatchNormalization(map_rank=1)(r)
    r = activation(r)
    
    return r

def resnet_basic(input, num_filters):
    c1 = convolution_bn(input, (3,3), num_filters)
    c2 = convolution_bn(c1, (3,3), num_filters, activation=None)
    p  = c2 + input
    return relu(p)

def resnet_basic_inc(input, num_filters):
    c1 = convolution_bn(input, (3,3), num_filters, strides=(2,2))
    c2 = convolution_bn(c1, (3,3), num_filters, activation=None)

    s = convolution_bn(input, (1,1), num_filters, strides=(2,2), activation=None)
    
    p = c2 + s
    return relu(p)

def resnet_basic_stack(input, num_filters, num_stack):
    assert (num_stack > 0)
    
    r = input
    for _ in range(num_stack):
        r = resnet_basic(r, num_filters)
    return r<jupyter_output><empty_output><jupyter_text>Let's write the full model:<jupyter_code>def create_resnet_model(input, out_dims):
    conv = convolution_bn(input, (3,3), 16)
    r1_1 = resnet_basic_stack(conv, 16, 3)

    r2_1 = resnet_basic_inc(r1_1, 32)
    r2_2 = resnet_basic_stack(r2_1, 32, 2)

    r3_1 = resnet_basic_inc(r2_2, 64)
    r3_2 = resnet_basic_stack(r3_1, 64, 2)

    # Global average pooling
    pool = AveragePooling(filter_shape=(8,8), strides=(1,1))(r3_2)    
    net = Dense(out_dims, init=he_normal(), activation=None)(pool)
    
    return net
pred_resnet = train_and_evaluate(reader_train, reader_test, max_epochs=5, model_func=create_resnet_model)<jupyter_output>Training 272474 parameters in 65 parameter tensors.

Finished Epoch[1 of 300]: [Training] loss = 1.859668 * 50000, metric = 69.3% * 50000 47.499s (1052.7 samples per second);
Finished Epoch[2 of 300]: [Training] loss = 1.583096 * 50000, metric = 58.7% * 50000 48.541s (1030.0 samples per second);
Finished Epoch[3 of 300]: [Training] loss = 1.453993 * 50000, metric = 53.4% * 50000 48.982s (1020.8 samples per second);
Finished Epoch[4 of 300]: [Training] loss = 1.347815 * 50000, metric = 49.2% * 50000 48.704s (1026.6 samples per second);
Finished Epoch[5 of 300]: [Training] loss = 1.269185 * 50000, metric = 45.8% * 50000 48.155s (1038.3 samples per second);

Final Results: Minibatch[1-626]: errs = 44.6% * 10000
{'fraction_non_alphanumeric': 0.11509997865224507, 'fraction_numerical': 0.062406603572190994, 'mean_word_length': 3.061705202312139, 'pattern_counts': {'":': 0, '<': 72, '<?xml version=': 0, '>': 77, 'https://': 16, 'lorem ipsum': 0, 'www.': 6, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 35, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '300', 'license': 'RSA-MD', 'n_tokens_mistral': 10080, 'n_tokens_neox': 8649, 'n_words': 2524, 'path': 'Tutorials/CNTK_201B_CIFAR-10_ImageHandsOn.ipynb', 'repo_name': 'StillKeepTry/CNTK', 'size': '28186'}