程序代写代做代考 android deep learning AI Java c++ chain python GPU algorithm Approximate Computing for Deep Learning in TensorFlow

Approximate Computing for Deep Learning in TensorFlow

Approximate Computing for Deep Learning in TensorFlow
Chiang Chi-An
First of all, I would like to thank my dissertation supervisor, Dr. Pramod Bhatotia, for teaching me how to conduct rigorous research, organize my thoughts, and produce a well-structured thesis. From beginning the proposal to finishing the dissertation, He provided me with precious and invaluable intellectual advice. Thanks to him, I did not have to learn through trial and error, and had the freedom to explore the areas that I found most interesting and satisfying while I was doing my dissertation. I would also like to thank Dr. Bob Fisher, my personal tutor. In both our one-on-one meetings and our group meetings, he demonstrated his investment in me. In addition, the courses that he advised me to take were very practical and provided me with a comprehensive course schedule, enabling me to learn all that I could in this MSc program. Finally, I would like to thank my mother, whose financial and mental support allowed me to focus on my studies without worry.
Introduction
Motivation
In recent years, machine learning techniques, especially deep learning which uses multiple layers of artificial neural networks, have achieved remarkable breakthroughs in many fields. From image classification to Go game AI player AlphaGo , deep learning exhibits the best performance.
At the same time, more and more people use smartphone. Undoubtedly, AI techniques such as deep learning will make smartphones even smarter. Functions such as face recognition, audio recognition and image classification will be added to many mobile apps.
The deep learning model training part can be done offline in the server clusters. For the inference part, although we can send the data to the server, and let the server do the prediction job and reply with the result. In some cases, if the data is sensitive, the client may wish not to send out to servers. One example is the bank card number recognition application. Even without privacy or security concerns, network traffic can be slow and expensive and building reliable servers increases the operation cost.
Thus, if the prediction computation is done locally on the smart phone, then there is no data security concern, no network traffic delay and cost and no need to maintain a potentially expensive server cluster. However, this approach also has its drawbacks. It requires the model to be stored in the smart phone’s limited storage and inference computing in the mobile can be slow and cost battery power.
A deep neural network typically has many layers with a large number of parameters. It requires large storage and a large number of math operations. For example, one traditional image classification model VGG has about 100 million parameters, need more than 1GB to store the model and takes more than 10000 million math operations. Thus it is not fit in the mobile phone.
To use deep learning models in the mobile phone, we must find a way to significantly decrease the model size and the number of computing operations to make the model file reasonably small and computing fast with less power. In the meantime, performance should be maintained as high as possible. We need to find a suitable trade-off between them.
Objective
MobileNet is a new deep neural network model proposed by Google that are specially designed for mobile and embedded devices using approximate computing techniques. Although the experiments in its paper show that it has strong performance compared to other popular models on ImageNet classification, a useful model should also have good performance on new datasets using the transfer learning technique.
In this project, we will compare MobileNet with other popular models in accuracy, model size and inference time in mobile devices to investigate whether approximate computing used in MobileNet can achieve a better trade off between accuracy and efficiency to be suitable for mobile device. We will also investigate how the two parameters width multiplier and resolution multiplier of MobileNet affect the accuracy, model size and inference time.
Achieved results
MobileNets with different width multipliers and resolution multipliers are successfully trained on the CIFAR-100 using transfer learning with pre-trained model on ImageNet. GoogLeNet Inception V3 and ResNet models are also trained on the CIFAR-100 using transfer learning. The following metrics are computed for each model: top-1 and top-5 accuracy on test set, number of parameters, size of model file and inference time in mobile device. Comparison of the results shows that MobileNet with width multiplier 1 and resolution multiplier 1 has speedup more than and shrinks the model file more than both compared with GoogLeNet Inception V3 and ResNet models. It has 18.3% loss in top-1 accuracy and 8.5% loss in top-5 accuracy compared with GoogLeNet Inception V3 and with almost no loss in both top-1 and top-5 accuracy compared with ResNet. The results also show that as we decrease width multiplier, model size becomes smaller and inference time quicker but with more accuracy loss. The resolution multiplier has the similar effect except that it doesn’t affect model size.
Dissertation outline
Chapter 2 will introduce various approximate computing techniques for deep learning which can be divided into 3 general categories such as low rank approximation to which techniques used in this project belong, network pruning and quantization. The introduction of Tensorflow which is the deep learning framework used in this project is also included in Chapter 1.
Chapter 3 will elaborate both the theory and implementation of the deep learning models in detail. They include loss function, optimization algorithm, regularization method, various kinds of layers used, transfer learning and the particular approximate computing technique used in this project: approximating traditional convolutional layer with depth-wise separable convolution layer.
Chapter 4 describes experiment setup, results and analysis.
Chapter 5 gives the project conclusion and discussion, then future work.
Background
Relevant work
Deep Learning
Deep learning techniques have achieved state-of-art results in many areas of machine learning. The achievements are remarkable, especially for the success of deep convolutional neural network (CNNs) in image classification. CNNs have the best results in all the standard image datasets such as MNIST , CIFAR-10 , CIFAR-100 and ImageNet . Many different CNNs models such as VGG , ResNet and Inception V3 have been developed. Because convolutional layers can make better use of image spatial information, these models typically have a sequence of many convolutional layers.
Approximate Computing
Until recently, deep learning researchers have been primarily focused on improving model’s accuracy. However, the use of multiple convolutional layers also results in large number of parameters requiring large memory for model storage and increases the computational cost.
With the widespread use of mobile devices and the application of deep learning in mobile apps, more and more researchers are aware that to have a good mobile user experience, accuracy is not enough – the model must also be efficient: less memory, quicker inference and less energy consumption. Because mobile consumers do not want a single app to take too much space of limited memory and want the app to respond instantly.
They resort to approximate computing techniques to make a better trade-off between accuracy and efficiency. The goal is to make model size smaller and inference time quicker to be suitable for mobile device while at the same keep as much accuracy as possible.
shows that significant redundancy often exists in deep learning models. Through approximate computing, we can remove the redundancy, saving both memory and computation cost. The approximate computing for deep learning can be divided into roughly three general approaches: low rank approximation, network pruning and quantization.
Low Rank Approximation of Filters
This approach decomposes the filters in convolutional layers into a series of separable smaller filters which are a low-rank approximation of original filters and reduce time complexity. The optimal decomposition can be found by minimizing the reconstruction error of the filters or the layer output. Since convolutional layers are the most time-consuming parts in CNNs, this low-rank decomposition will generate significant speed up.
uses SVD decomposition to make convolutional layers 1.6 times faster while sacrificing 1% accuracy. uses rank 1 filter basis approximation that achieves speedup by factor 2.5 without sacrifice of accuracy and by factor 4.5 with less than 1% accuracy decrease for a text character recognition network. and can only decompose linear filters in a single layer. further develops this method to take into account the nonlinearity, such as Rectified Linear Units (ReLU), which makes the approximation more accurate. It also invents new algorithms to optimize the whole network to reduce the accumulated errors when approximating multiple convolutional layers. It achieves speed up of factor 4 on a large pre-trained model on ImageNet with only 0.9% top-5 error rate increase.
Instead of modifying pre-trained networks by finding low-rank approximation of the convolutional layers, some papers invent new architectures with traditional convolutional layers replaced by layers that has similar function but with smaller computation cost and then train from scratch. Flattened networks replaces 3D filters in conventional convolutional networks with consecutive sequence of 1-D filters in all 3 dimensions which reduces the parameters significantly and make the feedforward computation about 2 times faster. Factorized networks factor the convolution operation by unravelling the convolutional layer with a sequence of combination of single channel convolution and linear channel projection. It achieves similar accuracy but with much less computation compared with traditional deep convolutional neural networks models. MobileNet uses a similar approach to those of flattened networks and factorized networks . Its model is based on depthwise separable convolutions which separate traditional convolutions into depthwise convolutions that apply a single filter for each input channel and pointwise convolutions that combine the results linearly. The MobileNet model has smaller size and comparable accuracy with models such as GoogleNet and VGG-16 . It provides two hyperparameters width multiplier and resolution multiplier to adjust the trade-off between latency and accuracy.
Network Pruning
This approach tries to remove parts of the models that are not important to reduce number of parameters and computation.
first learns the importance of network connections and removes those that are not important, then retrains the connections left. Its experiments show that the number of parameters in VGG-16 model can be reduced by and AlexNet model by with no loss of accuracy using this method.
and aim to prune whole filters together instead of weights, which can induce more speedup in the convolutional layers. reports inference time
decreases by 34% for VGG-16 and 38% for ResNet-110 on CIFAR-10 almost without loss of accuracy. reports FLOPs reduction and compression on VGG-16 with 0.52% top-5 accuracy drop.
’s pruning algorithm aims specifically at reducing energy consumption of CNNs instead of computation and memory cost. It reports energy consumption for AlexNet decreases by and GoogLeNet decreases both with top-5 accuracy loss less than 1%.
Network Quantization
Network Quantization quantizes the parameters of neural network models and encodes them with fewer bits to reduce their memory storage. For example, using 8 bits instead of 32 bits will require only about 25% of previously needed storage. Another benefit of quantization is to make the inference computation faster and use less power. Because using fewer bits saves memory bandwidth and RAM access time and allows more operations done in one cycle for SIMD instructions.
During the training phase, in each step, the parameters of neural networks adjust a little using back propagation and gradient descent algorithm, which requires high-precision number format such as 32 bits floating number. Thus, instead of training a quantized model from scratch, we usually quantize a pre-trained model.
Quantization for deep networks typically doesn’t decrease the accuracy of inference too much. Because deep networks are often very robust and good at ignoring the noise including the precision error noise introduced by quantization.
One simple way to quantize is to store the minimum and maximum values of the floating numbers set, then using an integer to represent the floating number. For example, if we use 8 bits to represent floating numbers in the range [-20.0, 50], then 0 represents -20.0, 255 represents 50.0, 128 represents 35.0 and so on.
uses k-means clustering algorithm and product quantization method to quantize the network parameters layer by layer. It achieves 16-24 times compression of CNN on ImageNet with 1% loss of accuracy.
uses Hessian-weighted k-means clustering and fixed-length binary encoding to do the quantization. Hessian-weighting also takes into account the across layers impact of quantization errors aside from within impact and thus can quantize the whole network at once. This paper also employs Huffman coding to further compress the network. It reports that the quantize models are 1.95%, 4.51% and 2.46% respectively of the original model sizes for LeNet, ResNet and AlexNet at no or marginal performance loss.
Network quantization can also be combined with other approximate computing techniques. Deep compression combines network pruning and quantization. It first prunes the model connections and only keeps most important connections to reduce parameters by 9-13 times. Then it quantizes the weights so that we can use only 5 bits to represent a weight instead of 32 bits. Finally it uses Huffman coding to reduce the model size further. This method compresses AlexNet model by 35 times, from 240MB to 6.9MB, increases the speed by 3-4 times and costs 3-7 times less power.
TensorFlow
Introduction
TensorFlow is the second generation machine learning system published by Google. It is a successor for Google’s previous DistBelief system . Its computation is based on data flow graph which takes math operations as nodes and multidimensional data arrays (tensors) flows through edges.
It is open-sourced and can be run in CPU, GPU and TPU (Tensor Processing Unit) which is ,specialized computation device developed by Google. It enables the researchers to easily implement various deep learning algorithms and has attracted much attention from research communities.
The main components of TensorFlow consist of client, master and working processes. Client sends request to the master and the master schedules the working processes to do computation in available devices. TensorFlow can be used either in a single machine or distributed clusters where client, master and working processes run in different machines .
Advantage
One of the many useful features is that TensorFlow can differentiate symbolic expressions and derive the backpropagation automatically for neural network training which greatly reduce the workload on programmers and the chance to make mistakes.
The TensorFlow is designed based on dataflow graph model. It provides python and C++ interface for programmers to easily construct the graph, which greatly facilitates the experimentations of network architecture, optimization algorithm and network parameters.
After the user constructs the dataflow graph, the TensorFlow system will optimize the graph and actually execute the operations in machines. Through this approach of first constructing the graph and then actually executing the operations, it enables the TensorFlow to know the whole information before execution and thus can do optimization as much as possible.
All computations are encoded as nodes in a data graph. The dependency of the data between different operations are explicitly encoded in the graph. Thus, the TensorFlow can partition the graph according to the dependencies and run the subgraph computations in parallel in different devices. The TensorFlow allows the user to specify the subgraphs that need to be computed. The user can feed tensors to none or some of the input place holders. The TensorFlow system only runs the computation that is necessary and prune the irrelevant graph away.
The tensor flow’s data graph model not only makes it easy to run concurrently and also easy to distribute computation to multiple devices. In TensorFlow, the data flowing through graph are called tensors. A tensor is a multi-dimensional array of primitive types such as int32. It represents the input and the output of the operations, which are represented in the vertices. Every operation has a type and none or more attributes. An operation that contains mutable state is called a stateful operation. Variable is one of such kind of operation. Another special operation is queue operation
User can use TensorFlow’s checkpoint files to periodically save training models and reload the model later. This facility not only improves the fault tolerance, it also can be used for transfer learning.
Architecture
The TensorFlow adopts a layered architecture. On the top level are training and inference libraries. The next level is python and C++ API which are built on the C API. Below C API level are distributed master and dataflow executor.
The distributed master accepts a data flow graph as input, it will prune the unnecessary part of the graph and divide the graph into subgraphs to distribute computation to different devices. Many optimizations, such as constant folding and subexpression elimination, are done by it. The dataflow executor’s task is to execute the computation of the subgraph distributed by the distributed master.
The next level is kernel implementations which have more than 200 operations implemented including most commonly used operations such as Const, Var, MatMul, Conv2D and ReLU.
Apart from above core components, the TensorFlow system also includes several useful tools such as a dashboard to visualize the data flow graph and training progress and a profiler that shows the running time of different tasks in different devices.
Performance
In Chintala’s benchmark of convolutional models testing, the results show that TensorFlow has shorter training step time than Caffe and with a similar one to Torch . Experiments have shown that TensorFlow can scale well in problems such as image classification and language modelling.
Methods
Network Architecture
The neural networks are organized as layers of neurons with input layer as the first layer, output layer as the last and hidden layers between them. A simple neural network is shown in Figure [fig:simpleNet].

A simple neural network.
Activation Function
Each neuron is a computing unit that applies linear transformation to its inputs, followed by an activation function to generate the output (Figure [fig:singleNeuron]).

Computation in a single neuron. is the weight for input , is the bias and is the activation function.
We typically use a non-linear function as the activation function, because if the activation function is linear, it can be incorporated into the previous linear transformation. There are many different activation functions. The most commonly used are sigmoid, tanh and rectified linear unit (ReLU). Sigmoid (Equation [SigmoidFun]) and tanh (Equation [tanhFun]) functions involve exponential operation and division, whereas ReLU (Equation [ReLUFun]) only involves max operation. Thus, it is much easier and faster to compute ReLU activation function value and its derivative during backpropagation. ReLU can also reduce the vanishing gradient problem (when is too large or too small, the gradient of sigmoid or tanh is approximate to 0). found that it is much faster to train deep neural networks using ReLU as activation function than sigmoid or tanh. Thus, in this project activation functions of all neurons are ReLU.
· Sigmoid

·
· sigmoid plot
· Tanh

·
· Tanh plot
· ReLU

·
· ReLU plot
Fully Connected Layer
The neurons in the neighbouring layers are fully connected, which means every pair of neurons has a connection (Figure [fig:fully]). If the two layers have neurons and neurons respectively, then there are connections between them each with different weight parameters. This is the traditional layer type often used in regular neural network. In this project, we use the fully connected layer as the last layer to compute class scores in the deep convolutional neural networks.

An example of fully connected layer
Convolutional Layer
This project stacks multiple convolutional layers in the deep neural networks to learn features automatically from image data. Because for image and other high-dimensional data, convolutional layer is often preferable to fully connected layer which can be slow to train and easy to overfit due to the large number of connections and parameters. For example, if the input image is 30x30x3 and fully connected layer is used as the first hidden layer, then every neuron in the fully connected layer will connect to 30x30x3=2700 neurons in the input layer. For such small image, it may not be a problem. But for larger image such as 300x300x3, there will be 270000 connections for a single neuron which is difficult to handle. In addition, high-dimensional data such as image often has inherent spatial structure. But for fully connected layer, the input is just a vector of pixel values. The relative position of the pixels has no effect and the spatial structure information is lost.
To address these problems, convolutional layer is invented. To be suitable for image data, the layout of neurons in convolutional layer is three-dimensional instead of one-dimensional in the fully connected layer. The three dimensions are width, height and depth respectively. Each neuron in the convolutional layer now only connects to a small regions of neurons of previous layer. The small region is small in width and height but includes all depth. The width and height of the region is called receptive field or filter size. So the receptive field controls how large the connection region will be. In this way, we reduce the connections dramatically. For example, If the receptive field is 3×3, the input volume is 300x300x3, then one neuron will connect to 3x3x3=27 neurons of the previous layer instead of 270000 in a fully connected layer. Apart from the benefit of reducing the number of connections, it is also helpful for learning the local features of the image.
To reduce the number of parameters further, the convolutional layer let neurons in the same depth slice share the same weights. Thus, for different positions in the image, the filter uses the same weights to extract the features, which makes the feature extracting translation invariant.
During forward propagation phase, we slide a window of size defined by receptive field over all the input volume and compute the dot product of filter weights and the pixel values in the window to get a single number in the output volume. The dot products of all positions constitute the activation map. And the activation maps for all filters are stacked in the depth dimension to constitute the total output volume.
In summary, by arranging layer of neurons in 3D space, constraining the connections to local area and sharing the weights (Figure [fig:conv]), convolutional layer can make better use of spatial information with much less parameters.

An example of 1D convolutional layer that illustrates local connection and weights sharing. The connections with the same color share the same weight.
Convert Fully connected layer to Convolutional Layer
Fully connected layer can be converted to convolutional layer. For example, if the fully connected layer accepts input volume and outputs volume, then a convolutional layer with 10 filters of size will give the same effect. Replacing the fully connected layer with a convolutional layer has the advantage that when the input image has a larger size than the trained image, we can process multiple areas of the input image in a single forward pass instead of multiple forward passes to get multiple class score vectors and the final prediction can be done using their average, which can improve the prediction accuracy.
Pooling layer
Pooling layer is often used in the convolutional neural networks and can decrease the size of features significantly. In this project, the average pooling layers are used before the fully connected layers. It works by sliding a small window over input volume, using a non-linear function to computing a number with the values in the small window as input. The computation is conducted for each input depth independently. The most commonly used non-linear function is max function. Other functions, such as average (Figure [fig:averagePool]) and L2-norm, are also used. By reducing multiple values in a local region to only one number, the pooling layer has the effect of extracting more abstract features which helps the model to generalize and reduce overfitting. The pooling layer introduces no additional parameters and it will reduce the width and height by factor 2 or more with depth unchanged. Thus, the number of parameters of the later layers is reduced. The most commonly used filter size is 2×2, which results in output volume of 1/4 input volume size. Larger filter size is rarely used, because it will discard too much information and often result in bad performance.

An example of average pooling operation for a single depth slice with a 2×2 filter and stride of 2.
Loss function
Suppose we have classes, for sample , we have computed a score vector of elements. is the class score of sample for class . Larger score indicates it is more likely for to belong that class. The loss function takes the score vector as input and outputs a single number to indicate how well the score outcome matches with the true class label. Intuitively, if the score for the true class is relatively higher than others’, then the loss function value should be smaller.
Cross Entropy loss
We can use the softmax function (Equation [softmaxEquation]) to convert class score vector to class probability vector with each value in range and the total sum as 1. The probability of data sample belonging to class given the class score vector is:

That is, for each score, take its exponentiation and then divided by sum of exponentiations to normalize the value to 0-1. We want the loss to be small when the predicted probability for the correct class is larger. Thus, we take negative log of where is the correct class for to get the loss. The loss for sample is:

Hinge Loss
Another commonly used loss function is hinge loss. The loss for sample given class score vector is:

Intuitively, this loss function wants the score for the true class to be larger than others at least by 1. Otherwise, the loss will increase for each violation.
Loss Functions Comparison
The cross-entropy unlike hinge loss provides probability for each class which is easier for human to interpret than raw class score. Another difference is that, once the margins between score of true class and scores of other classes are large enough, the hinge loss becomes zero and cannot decrease further, whereas the cross-entropy loss can always decrease. The hinge loss and cross-entropy loss often have similar performance. The cross-entropy loss is used for all the models in this project.
Regularization
L1 and L2 Regularization
We often use regularization methods to reduce overfitting. One way of regularization is to add weight penalty to the loss. The new loss is the sum of original data loss and the added regularization loss. The most commonly used are L1 (Equation [L1Equation]) and L2 (Equation [L2Equation]) regularization.

The regularization parameter controls the regularization strength. A large will put more weight to regularization loss and thus stronger regularization. Small will put more weight to data loss and thus weaker regularization. Different datasets or network architectures may require very different value of . There is no simple way to decide suitable . It is usually set through cross-validation. By adding regularization loss which penalizes large weights, it helps to result in networks with smaller weights.
Smaller weights mean a few change of the inputs won’t change the output of the network too much. A few outliers won’t matter too much for the regularized networks which make the network less sensitive to the noise in the data. On the other hand, a little change on some of the inputs may cause the output of network with large weights change a lot. So large weights will make the model easily adapt to all the training data including noise.
In summary, unregularized networks with large weights tend to be more complex, easy to learn the noise and more likely to overfit. In contrast, regularized networks with small weights tend to be simpler, robust to noise, less likely to overfit and better to generalize.
The L2 regularization and L1 regularization are similar. Both penalize large weights. But they have different form of weight updating in gradient descent algorithm. For L2 regularization, the additional update of because of added regularization loss is

For L1 regularization, it is

From above we can see that the updating amount is constant for L1 regularization and proportional to for L2 regularization. Thus, the penalty is much larger for L2 regularization when is large and much larger for L1 regularization when is small. The effect is that weights in L1 are sparse with a small number of relatively large weights and others driven to . On the other hand, L2 regularization weights are more diffuse. The sparsity feature of L1 regularization makes L1 a better choice for feature selection purpose. In other situations, L2 regularization is found usually better than L1 regularization. Thus, we use L2 regularization in this project to reduce overfitting.
We can also combine these two regularizations (Equation [elasticEquation]) which is called elastic net regularization .

Apart from adding regularization loss, another way to avoid weights with too large magnitude is to enforce max norm constraints . This method does the weights updating as usual using gradient descent algorithm and then clips the weights if needed to ensure each weight vector norm is below a preset maximum value.
Dropout Layer
Dropout is another regularization method to reduce overfitting. In the training stage, we randomly drop out the neurons and the associated connections according to probability (Figure [fig:dropout]). This has the effect of sampling from a large number of sub-networks. In the testing stage, we do not drop out neurons. Instead, we use the full networks but with the neuron’s output weighted with . In this way, we compute the average output of all the sub-networks approximately.
By randomly dropping out neurons, the dropout techniques trains over exponentially large number of sub-networks, and using the average prediction of them which is like a kind of ensemble learning, it reduces the overfitting and also increases the speed of training.

An example of dropout operation. The two neurons colored grey and their associated connections are dropped out.
Batch Normalization
During neural network training, the parameters change of one layer will change the distribution of inputs of the layers after it. This phenomenon called internal covariate shift is especially true for deep neural network, where the impact will be amplified by multiple layers. To adapt to the input distribution change, it usually requires a lower learning rate, which makes the training slow.
To solve this problem, we can transform the layer’s input to make it have mean 0 and variance 1. This transformation is called whitening. To make the computation fast and also differentiable required by the backpropagation, we can whiten each dimension of the input independently as in Equation [normEq] where the scalar is one dimension of the input.

To avoid changing the layer’s representation, we add a linear transformation (Equation [linearEq]) after the whitening transformation. The two transformations together are called batch normalization .

During training, the mean and variance of are estimated from mini-batch samples. The population means and variances are also estimated by taking moving averages of mini-batch statistics during training. During inference, the fixed population means and variances are used so that the output is only determined by the input.
For a layer in the original network:

We can apply batch normalization in this way:

The reason to remove is that it can be cancelled by parameter in the batch normalization.
In the convolutional layer, the activation map is got by using the same filter applied on different locations of previous layer. When we use batch normalization for the convolutional layer, we will normalize all the activations in the activation map together in the mini-batch. Thus, if the activation map has size and the batch size is , then the normalization is applied over values. Just like the activation map shares the same weights, we use the same parameter and for a activation map.
The batch normalization can reduce layer input distribution change and make the gradients less sensitive to parameter scales, thus higher learning rate can be used to speed up the training.
During training, the batch normalization depends on the whole mini-batch samples, the output of one training sample is not deterministic any more. In this way, batch normalization has the effect of regularization and can remove other regularization methods such as dropout. In the experiment, batch normalization is used in all models. In particular, for MobileNet model, it is used after each hidden layer.
Optimization
Mini-batch gradient descent
The training process is to use optimization algorithm to update the parameters so that the loss is minimized. The most commonly used optimization algorithm for neural network is gradient descent.

is the parameter vector, is the loss, is its gradient and is the learning rate. The gradient descent is an iterative algorithm that updates the parameters though the negative direction of gradient at each iteration and the step size is controlled by the learning rate.
When the training data is huge, for example ImageNet has over 10 million images, computing the gradient using the entire data set is costly. In this situation, we need to use mini-batch gradient descent. In this method, we take a small subset of samples (a mini-batch) from the data set at each step and then use this mini-batch instead of the whole data set in normal gradient descent algorithm to compute the gradient and do the parameter updating. Due to the correlation between samples in the training data set, the gradient of the loss function over the mini-batch is often very approximate to the gradient of the loss function over the whole training data set. Since the computation cost is much cheaper in the mini-batch gradient descent algorithm than the normal gradient descent algorithm at each parameter updating step, much more updates can be performed and thus, the loss function can converge much more quickly in mini-batch gradient descent algorithm
The learning rate in the mini-batch gradient descent algorithm is very important. When the learning rate is very small, although the loss is guaranteed to decrease, the converging speed may be too slow. We can increase the learning rate to speed up the learning, but this may lead to overstep that makes the loss increase. It is very difficult to set a suitable learning rate. Different datasets or different network architectures may require different learning rate. We may need to set different learning rate for different parameters and in different training phases. Learning rate decay and extensions of mini-batch gradient descent algorithms can be used to solve this problem.
Learning Rate Decay
At the start of training, we may want a relatively larger learning rate so that the loss function value can decrease quicker. In the later stage, with the improvement getting smaller in each step, we may want to decay the learning rate so that it can avoid overstepping and fine-tune the parameters. We can set the learning rate decay according to some rule – for example, multiply 0.9 every 1 epoch. Or set the decay manually, for example, when we see the training loss doesn’t decrease any more, we can try to half the learning rate.
Let is the initial learning rate, is decay rate and is the number of training steps. Three commonly used rules can be expressed as follows.
· Natural Exponential decay

· Exponential decay[exponential-decay]

· Inverse Time Decay[inverse-time-decay]

Mini-batch gradient descent extensions
Many extensions are proposed to improve over the basic mini-batch gradient descent algorithm. Algorithms such as Adagrad and RMSProp try to setting the learning rate adaptively during training. Algorithms such as Momentum and Nesterov Momentum try to adjust the parameter updating direction to reduce oscillations.
Adagrad
Adagrad algorithm can adapt the learning rate for each parameter automatically.

is used to avoid dividing 0 and it is set to a very small value such as .
The above formulae operations are element-wise for each parameter. So each parameter has its own effective learning rate. AdaGrad keeps track of the sum of gradients and uses it to adjust the learning rate.
RMSProp
One problem of Adagrad is that the effective learning rate is always decreasing, when it is approximate to 0, then the algorithm stops learning.
Another algorithm called RMSProp tries to solve this problem.

is the decay rate. RMSProp makes a simple change which makes C as the moving average of gradient square instead of accumulated sum in the Adagrad. Now the effective learning rate is no longer always decreasing. We train the models using RMSProp algorithm in this project.
Momentum

is another hyperparameter called momentum. is the velocity. We integrate previous velocity with gradient to get the current velocity and then using the velocity to update the . This is different from basic gradient descent where we directly update the parameters using gradient. This algorithm is helpful to reduce oscillating and speed up convergence.
Nesterov Momentum
The Nesterov momentum uses the gradient of the next position instead of current position and achieves better results over momentum.

Forward Propagation and Backpropagation
Let represents the activation values of layer . For the input layer, the values are directly from input , so we have . We can compute all neurons’ value layer by layer from input layer until output layer.

From the output layer’s values, we can compute the loss that measures the error between the model predicted value and the actual target value.
In the training process, we need to use gradient descent algorithm to update the parameters to reduce the loss. Backpropagation makes use of chain rule to compute gradients of all parameters with respect to the output efficiently.
Chain Rule
The derivative of composite functions can be computed using chain rule method. For example, if variable is a function of which in turn is a function of , then according to the chain rule:

Example
The following illustrates the forward propagation and backpropagation process of feeding one sample data to a neural network that has one hidden layer with ReLU activation and uses cross-entropy loss. are the weights and biases for hidden layer and output layer respectively. are the sample data and class label.
· Forward propagation
· Compute the affine transform for hidden layer.

· Compute the ReLU activation for hidden layer.

· Compute the affine transform for output layer which is the class score.

· Convert class score to probability using softmax function.

· Compute the loss

· Backpropagation
· Compute gradient of class score.
$$\frac{\partial L }{ \partial S_k } = p_k – \mathds{1}(y = k)$$
· Compute gradient of weight .

· Compute gradient of bias .

· Backpropagate to hidden layer.

· Set non-positive elements to 0 in . Because if and if .
$$\frac{\partial L }{ \partial Z } = \frac{\partial L }{ \partial H } \odot \mathds{1}(H > 0)$$
· Compute gradient of weight .

· Compute gradient of bias .

From above, we can see that during backpropagation, we use many intermediate results computed in forward propagation. Thus we often save the needed intermediate values in forward propagation to save computation time by avoiding duplicate computation in backpropagation.
Although above example is just for a simple neural network, it can be easily extended to a more complex network. During the forward propagation and backpropagation process, the computation is local to each layer. Each layer only needs to know the value propagated to it, compute the values and propagate the values to other layers. It doesn’t need to care about how other layers do the computation. Thus, different layers and operations can be used as components to construct deep and very complex neural networks in many different ways of combination.
Depthwise Separable Convolution
The depthwise separable convolutions factorize the conventional convolution (Figure [fig:conventionConv]) with a depthwise convolution (Figure [fig:depthwiseConvolution]) followed by a pointwise convolution (Figure [fig:pointwiseConvolution]).

Conventional convolution

Depthwise convolution

Pointwise convolution
The depthwise convolution is done independently for each channel of the input where a single filter is applied. The pointwise convolution is the same with conventional convolution operation but with kernel size 1×1, which is why it is called pointwise. It combines the features from depthwise convolution linearly to create new features. Thus the depth separable convolution has the same effect with conventional convolution. The difference is that conventional convolution achieves this using a single step, whereas depth separable convolution uses two separate steps. Through the separation of feature filtering and feature combining, depthwise separable convolution reduces the amount of computation tremendously.
Assume the input has size where is the input width, is the height and is the number of input channels. The filer has size and the number of filters is . With stride as 1 and zero padding, the output of conventional convolution will have size . The elements of are computed as in Equation [convEq] which takes .

For depthwise convolution, we use one filter for each input channel. The filter has size . The output of the depthwise convolution has size . It is computed as in [depEq] which takes :

Then for the pointwise convolution, it uses filters, takes the output of depthwise convolution and generates output of size which takes . In total, depthwise separable convolution takes .
The time ratio between depthwise separable convolution and conventional convolution is . For a typical convolution, where , we achieve about a 9-fold increase in speed.
Each filter in conventional convolution has weights. Thus, conventional convolution has total number of weights for filters. The total number of weights of depthwise separable convolution is the sum of for depthwise convolution and for pointwise convolution. Thus the ratio of number of weights between depthwise separable convolution and conventional convolution is which can be reduced to . Thus, the depthwise separable convolution has the same ratio in reducing number of parameters as in reducing computation cost.
In summary, depthwise separable convolution has almost the same effect of feature extraction with conventional convolution, but has much less computation cost and fewer parameters. It is heavily used in MobileNet model and its effectiveness is evaluated in the experiment.
Transfer Learning
Training a deep convolutional neural network model usually requires large computation resource and takes long time. For example, training a deep convolutional neural network model on ImageNet may takes weeks even with GPU clusters. If we cannot afford the computation resource or time, we can use transfer learning method. In this method, we take a pre-trained model (there are already many state of the art trained models available free from internet), replace the last fully-connected layer and retrain it. The previous layers of neural network model can be seen as a feature extractor. The last fully connected layer is used to compute class scores using extracted features. We can use the same features as the pre-trained model, but the classes are often different from pre-trained model, so we need to replace and retrain the last layer. If retraining only the last layer doesn’t have a satisfactory performance, we may also need to fine-tune previous layers: initializing weights with pre-trained model and updating them during training with smaller learning rate. The reason to use smaller learning rate is that we expect the weights of pre-trained model are not far from the final optimized weights and we want to update them little by little and not to overstep. Whether fine-tuning is needed often depends on the similarity between the new dataset and the dataset used by the pre-trained model in terms of both image data and class labels. If they are very similar, the kind of features extracted by the layers before last layer in the pre-trained model are likely to also suit the new model, and retraining only the last layer may be enough.
Apart from saving much training time and computation resources using transfer learning, it often has better results as reported in . Thus, the transfer learning technique is used to train the models in this project.
Results and Evaluation
Resource and tools
Software and Hardware Environments
The model training and accuracy evaluation is implemented using python with TensorFlow framework 1.0 on Ubuntu Linux system. We use Amazon Elastic Compute Cloud (EC2) G2 instance equipped with NVIDIA GRID K520 GPUs for training the deep neural networks.
The image classification Android mobile app is implemented in java with TensorFlow mobile library using Android Studio which is the official IDE. The TensorFlow mobile library provides APIs that let mobile app easily load pre-trained model and do inference with it. We use the image classification mobile app to measure the inference time in Nexus 6 Android phone.
Checkpoint File
During training, we use TensorFlow API to save the learned model parameters periodically to binary checkpoint files. Thereby, the model parameters are backed up. Next time, the model parameters can be restored by loading data from checkpoint file.
Model File
The model file is in Protocol Buffers format which can be saved and loaded using many different languages. Thus, we can save the model file using python and load the model using java in Android app.
The mobile file contains all the information about the model graph. Each node of the model graph stores various information including operation name such as “Add” and “Conv2D”, input nodes and other attributes such as filter size for “Conv2D”.
To make it suitable for deployment, we use the tool freeze_graph.py provided by TensorFlow to combine the graph definition file and checkpoint file containing learned parameters into a single model file. The tool achieves this by replacing Variable node with Const node that contains the parameters and it also removes nodes unnecessary for inference to simplify graph and decreases file size.
The resulting model file can then be shipped with Android app. In the Android app, upon starting, we first load the model file using TensorFlow Mobile java API and then do inference using the loaded model.
Dataset
We use CIFAR-100 dataset in the experiment. The CIFAR-100 dataset contains 60000 small images of size . They belong to 100 different classes, with each class containing 600 images. A sample of 100 images of this dataset is shown in Figure [fig:cifarImg].

A sample of 100 images from CIFAR-100
Experimental Setup
Training set and test set
The CIFAR-100 dataset is divided into training set which contains 50000 images and test set which contains 10000 images.
Preprocessing
During the training, an image is randomly transformed before feeding to the neural networks. In this way, the neural networks will train on multiple versions of the same image and the actual training data set size is much larger than original data set size. This will make the model better generalize and reduce overfitting.
· Randomly Shift the Image[randomly-shift-the-image]
· First pad the image, and then randomly crop the image. In this way, the image will randomly shift in the four directions.
· Randomly Flip the Image[randomly-flip-the-image]
· The image is flipped left to right with 0.5 probability.
· Randomly adjust the image brightness[randomly-adjust-the-image-brightness]
· Randomly add a value between -63 and 63 to all RGB components of every pixel.
· Randomly change the image contrast[randomly-change-the-image-contrast]
· Randomly choose a contrast factor . For each RBG channel, compute the mean and update the corresponding component of each pixel with:

After above randomly changing steps of the image, lastly we normalize the image data to make it have zero mean and unit norm.
Neural Networks Training
The deep neural network models compared in the experiment are MobileNet , Inception V3 and ResNet . MobileNet model heavily makes use of depth separable convolution. As described in section [depthwise-separable-convolution], the depth separable convolution approximates conventional convolution but with fewer parameters and less computation cost. In this experiment, we will investigate whether this approximate computing technique used in MobileNet can achieve a better trade off between accuracy and efficiency than the Inception V3 and ResNet model.
To further reduce the computation cost, MobileNet uses two hyper-parameters width multiplier and resolution multiplier to control the model size. The MobileNet model with and is called base model. Models with smaller width multiplier will use fewer input and output channels in each layer. And models with smaller resolution multiplier will use input image of smaller size. For a layer with input size and output size in the base model, the input size becomes and output size becomes in the shrunk model. We will also investigate how the two parameters width multiplier and resolution multiplier of MobileNet affect the accuracy, model size and inference time.
Figure [fig:models] shows the architectures of the three models used in this experiment. The training process of each model is described in following sections [mobilenet], [inceptionv3] and [resnet].

The architectures of MobileNet, Inception V3 and ResNet.
MobileNet
Hyperparameters
· Batch Size: 128
· Momentum: 0.9
· Initial learning rate: 0.01
· Learning rate decay: decay with factor 0.94 every 2 epochs
· Weight decay parameter: 0.00004
· Optimizer: RMSProp optimization algorithm with decay rate of 0.9
The initial weights are loaded from MobileNet pre-trained model on ImageNet. In the first stage, train only on the last fully connected layer and keeping the parameters of previous layers unchanged. It trains 25000 steps in this phase. Then train all layers to fine-tune the model. It trains 55000 steps in this phase. During training, random minor changes are applied on the images to augment the data set.
After training finishes, we use the test set to evaluate the performance. Note that the prediction on each image is just done once. If average prediction of multiple randomly changes on an image is used, the performance is likely to improve.
The models are exported to TensorFlow model file. In the Android mobile image classification app, the model file is loaded and the inference time is computed by dividing the time it takes to classify 100 images one by one with 100. The inference time is measured in Nexus 6 Android phone.
The experiments are done for width multipliers 1.0, 0.75, 0.5 and 0.25, image sizes 32, 24 and 16. Thus, the above steps are done for a total of 12 models.
The change of losses with training steps for model with width multiplier 1.0 and image size 32 are in figures [fig:totalLossMobilenet], [fig:crossLossMobilenet] and [fig:regularizationLossMobilenet]. Loss changes for other models are similar. The red line is for the first stage and the green line for the second stage.
Figures [fig:totalLossMobilenet], [fig:crossLossMobilenet] and [fig:regularizationLossMobilenet] show the change of total loss, cross entropy loss and regularization loss with the training steps in both stages.

Total Loss for MobileNet

Cross Entropy Loss for MobileNet

Regularization Loss for MobileNet
Inception V3
Google Inception V3 model is proposed in . It adds an auxiliary logits layer in addition to usual logits layer to speedup convergence during training. The first stage trains on the auxiliary logits layer and logits layer 15000 steps with a fixed learning rate of 0.01. The second stage trains 30000 steps on all layers with a smaller fixed learning rate of 0.0001. Both stages use weight decay of 0.00004.
Figures [fig:totalLossInception], [fig:crossLossInception] and [fig:regularizationLossInception] show the change of total loss, cross entropy loss and regularization loss with the training steps in both training stages for the Inception V3 model.

Total Loss for Inception V3

Cross Entropy Loss for Inception V3

Regularization Loss for Inception V3
ResNet
The ReNet model is proposed in . For this model in the experiment, it undergoes the same process with the Inception V3 model during training.
Figures [fig:totalLossResnet], [fig:crossLossResnet] and [fig:regularizationLossResnet] shows the change of total loss, cross entropy loss and regularization loss with the training steps in both training stages for the ResNet model.

Total Loss for ResNet

Cross Entropy Loss for ResNet

Regularization Loss for ResNet
Metrics
· Top-1 Accuracy[top-1-accuracy]
· The ratio between the number of images that are predicted correctly and the total number of images in the test set.
· Top-5 Accuracy[top-5-accuracy]
· Same with top-1 accuracy, it is the ratio between the number of correct predictions and the total number of images. The difference is the meaning of correct prediction. For top-5 accuracy, classifier gives five candidate guesses instead of one guess. If the correct label is one of the five guesses, then the prediction is considered correct.
· Inference Time[inference-time]
· The average time model takes to classify a single image in mobile devices.
· Model File Size[model-file-size]
· The size of the model file in TensorFlow for deployment. The model file size is mainly determined by the number of parameters and the number of bits used to encode each parameter.
Results
Table [fig:diffWR] shows the performance for MobileNets with various width multipliers and resolution multipliers. Table [fig:diffM] shows performance for full MobileNet, Inception V3 and ResNet.

Analysis

For comparison purposes, the accuracy loss, inference time speedup and model size compression ratio of MobileNet model over Inception 3 and ResNet are computed in Table [fig:modelComparison].
Table [fig:modelComparison] shows that the MobileNet have significant inference speed up and model size compression over Inception V3 and ResNet. The reason for this is that depthwise separable convolutions used in MobileNet reduce computation cost and parameters dramatically compared with conventional convolution as analyzed in section [depthwise-separable-convolution]. Its accuracy is similar with ResNet and have a relatively larger loss compared with Inception V3.
Table [fig:diffWR] shows that we can achieve fast inference at the cost of greater accuracy loss by decreasing width multiplier and resolution multiplier. We can also have fewer number of parameters and smaller model file size by decreasing resolution multiplier. Models with smaller width multiplier will have fewer filters used in the convolution, which results in decreased feature extracting power and increased accuracy loss. Models with smaller resolution multiplier take smaller input image size. Thus, with less information used, their accuracies also decrease. The following quantitative analysis shows why width multiplier and resolution multiplier can reduce computation cost and number of parameters.
Since most computation and parameters are in depth separable convolutions for MobileNet, we can focus on the change in the depth separable convolutions. For the base model, as stated in section [depthwise-separable-convolution] the computation cost is and the number of weights is . For model with width multiplier and resolution multiplier , the number of input and output channels become and , and the input width and height become and . Thus, the computation cost becomes

and the number of weights becomes

Equation [computationCost] shows that decreasing width multiplier and resolution multiplier leads to less computation cost and Equation [numWeight] shows that decreasing width multiplier also reduces the number of parameters and resolution multiplier doesn’t affect the number of parameters.
Table [fig:diffWR] also shows that it is better to decrease width multiplier than resolution multiplier to speed up inference and shrink model file. For example, using width multiplier 0.75 and resolution multiplier 1.0 have higher accuracy, quicker inference and smaller model size than using width multiplier 1.0 and resolution multiplier 0.75.
Conclusion and Discussion
Remarks and observations
This project implements the MobileNet model using the TensorFlow framework. The approximate computing techniques, approximating traditional convolutional layer with depth-wise separable convolution layer, are used. An Android mobile image classification app is built to test the real inference time of each model. In the experiment, MobileNets with various width multipliers and resolution multipliers are successfully trained on the CIFAR-100 dataset to compare these two hyperparameters’ effect on the performance, which show that by adjusting them we can get different trade-offs between accuracy and efficiency. The decrease of width multiplier and resolution multiplier lead to smaller model size and quicker image classification on mobiles with greater accuracy loss. Thus, mobile developers can adjust them to find the best trade-off for their applications. Comparison with other models such as Inception V3 and ResNet are also done in the experiment, which shows that MobileNet has much speedup in inference time and smaller mobile size with reasonable accuracy sacrifice. The resulting model is more suitable for mobile deployment which takes much less memory space and inference time.
Limitation and Further work
More approximate computing techniques
Currently, the approximate computing technique used is depth-wise separable convolution which is approximation to traditional convolution. We would like to apply network pruning and quantization techniques on the resulting models to further decrease model size and inference time in future work.
More extensive Experiment
In this project, due to computing resource and time constraint, we use one dataset CIFAR-100 and two traditional popular models Inception V3 and ResNet in comparison. In future work, we will use more datasets and more models to do more extensive evaluation.
Application into Practice
In future work, we would like to put the approximate computing techniques used in this project into real practice. Many mobile applications would benefit from approximate computing techniques used in this project. Two examples are bank card number recognition and handwritten Chinese character recognition. The first one can be used in a payment app that let users avoid the hassle of entering card number manually. The second one can be used in Chinese input app. The computing techniques used in this project would make the recognition in the two applications much faster and the apps less memory-consuming.
Model Architecture Improvement
Although the MobileNet achieves significant inference speedup and model size shrinking, it has a relatively large accuracy loss compared with the Inception V3 model. Thus, we would like to adjust the model architecture to improve its accuracy in future work.