<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-83055021305463025</id><updated>2024-10-02T08:28:30.091-07:00</updated><category term="Calculating the integral of a Gaussian"/><category term="n-sphere"/><category term="volume of an n-dimensional sphere"/><title type='text'>Journey into Machine Learning</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>21</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-2150801296095561646</id><published>2020-03-08T23:50:00.001-07:00</published><updated>2020-03-08T23:50:43.122-07:00</updated><title type='text'>Variational Autoencoders</title><content type='html'>&lt;br /&gt;
&lt;h3&gt;
What is an autoencoder?&lt;/h3&gt;
&lt;div&gt;
An autoencoder is a neural network which is used to learn efficient (read: lower dimensional) encodings of input data in an unsupervised manner. This just means that we design the architecture of a neural network which takes an input of $k$ dimensions and train it to output that very input (e.g. the output layer has the same dimensions $k$ as the input). That is, the loss that we try to minimise isn&#39;t base on the difference of the prediction and some label or value (as in the supervised case) but the difference between the prediction and the &lt;i&gt;input (&lt;/i&gt;also known as the &lt;b&gt;reconstruction error)&lt;/b&gt;;&lt;i&gt;&amp;nbsp;&lt;/i&gt;we are training the network to recreate the $k$ dimensional input vector as closely as possible. &lt;i&gt;But Why?&lt;/i&gt;&amp;nbsp;I hear you ask.&lt;/div&gt;
&lt;h3&gt;
Dense Representation&lt;/h3&gt;
&lt;div&gt;
Study the architecture of the network below, you can see it is naturally broken up into two parts; an &lt;b&gt;encoder&lt;/b&gt;&amp;nbsp;and a &lt;b&gt;decoder.&lt;/b&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div&gt;
The &lt;b&gt;encoder&lt;/b&gt;&amp;nbsp;takes the aforementioned $k$ dimensional input vector and successively feeds it through hidden layers with dimension $&amp;lt; k$ (there are two in the image below). This results in the middle layer of the network, which is a key part in an autoencoder and its associated uses - more on that later.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The &lt;b&gt;decoder&lt;/b&gt;&amp;nbsp;takes takes the middle layer and feeds it through additional hidden layers - upscaling the dimensionality - to result in the output vector of dimension $k$.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr3pu634FNR1QNUC6q7HT-aLU6xzW2GIswHRyL5BzM_9yhTXrvkpHQgnww5c865-3dcOjj2yf1HABww5nwQYeAjL9osIBV0PBo_y_H8WYfNTh0BlfJwNlAMyvuDcRZgOgB3Jc_wlRE_mw1/s1600/autoencoder.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;896&quot; data-original-width=&quot;1574&quot; height=&quot;227&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr3pu634FNR1QNUC6q7HT-aLU6xzW2GIswHRyL5BzM_9yhTXrvkpHQgnww5c865-3dcOjj2yf1HABww5nwQYeAjL9osIBV0PBo_y_H8WYfNTh0BlfJwNlAMyvuDcRZgOgB3Jc_wlRE_mw1/s400/autoencoder.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The idea is that in a sufficiently trained network which has minimal error between the input and output vectors, the middle layer will have captured the essence (e.g. the signal) of the input in a lower dimensional, or &lt;b&gt;dense representation&lt;/b&gt; vector, stripping the input of irrelevant noise. The &lt;b&gt;dense&amp;nbsp;representation &lt;/b&gt;is also called a &lt;b&gt;latent representation&lt;/b&gt;&amp;nbsp;which generally lives in a &lt;b&gt;latent vector space&lt;/b&gt;.&amp;nbsp;&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;So what?&lt;/b&gt;&lt;/div&gt;
&lt;div&gt;
That&#39;s all nice and dandy but what can we actually use autoencoders for?&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Outlier detection&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;By definition, outliers have some characteristics of features distinct from the rest of the dataset - they are in the vast minority. Thus we can feed a given dataset through an autoencoder - training it to minimise the reconstruction error between input and output. We then feed through a previously unseen observation; the autoencoder will then hopefully be able to identify this observation as either&amp;nbsp;&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;similar to &quot;typical&quot; observations it was trained on; characterised by small reconstruction error or&lt;/li&gt;
&lt;li&gt;as an outlier; characterised by the relatively large reconstruction error.&lt;/li&gt;
&lt;/ul&gt;
&lt;/ul&gt;
&lt;li&gt;De-noising inputs / dimensionality reduction of inputs&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Autoencoders can be used to reduce noise from inputs to create a &quot;de-noised&quot; and lower dimensional version ready for use in machine learning pipelines. This can be seen as a form of regularisation.&lt;/li&gt;
&lt;/ul&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;b&gt;Latent vector space&lt;/b&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
One natural curiosity that may arise is how we can characterise or better understand the latent vector space. I&#39;ve borrowed the results below from [2], which shows a 2 dimensional dense representation of MNIST trained on an autoencoder.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifOhnjKceK1zA9JtFZjhQmfvyLE-6Gn57JUn43MPMuTIoE9HBSTlzgKHOHvHeyNYTBV4d63C1EAxRlBuIl4BZxldzrD99jMiKqxl0trHiidvGSqXJWP5sswXi8midrRhXxeLVPbxenpzah/s1600/1_-i8cp3ry4XS-05OWPAJLPg.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;785&quot; data-original-width=&quot;721&quot; height=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifOhnjKceK1zA9JtFZjhQmfvyLE-6Gn57JUn43MPMuTIoE9HBSTlzgKHOHvHeyNYTBV4d63C1EAxRlBuIl4BZxldzrD99jMiKqxl0trHiidvGSqXJWP5sswXi8midrRhXxeLVPbxenpzah/s400/1_-i8cp3ry4XS-05OWPAJLPg.png&quot; width=&quot;366&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
What we can see are &lt;i&gt;distinct&lt;/i&gt; and &lt;i&gt;disjoint&lt;/i&gt;&amp;nbsp;regions for each of digits [0-9] - this makes it easy for the decoder to perform it&#39;s job. However, this causes problems if we ever want to sample from this space to &lt;b&gt;generate&lt;/b&gt;&amp;nbsp;realistic examples. Because each digit&#39;s latent vector is clustered locally, the decoder would likely decode a vector taken from (-15, 5) into junk - it would not resemble any of the digits from [0-9] - as it hasn&#39;t seen any training examples from this local region. Hence we are very limited to sampling local regions of the latent space which have seen training data in that region - the generated samples will likely replicate the training samples, this is not very intelligent generation! If we were to sample &lt;i&gt;within&lt;/i&gt;&amp;nbsp;a cluster but in a region that wasn&#39;t in the training data - for example (-22,-10) - there is no guarantee that the decoded image would make sense! If we started at the &lt;b&gt;1 &lt;/b&gt;indicated in the image and traveled along the vector toward &lt;b&gt;7&lt;/b&gt;, intuitively we would expect the output of the decoder to continuously deform from a 1 to a 7, however this is not the case with the autoencoder - no such guarantee exists - and it is more than likell non intelligible outputs would be created.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The&amp;nbsp;&lt;b&gt;disjoint &lt;/b&gt;and &lt;b&gt;discontinuous&lt;/b&gt;&amp;nbsp;nature of the representations created by an autoencoder make it a poor candidate for &lt;b&gt;generating &lt;/b&gt;realistic&amp;nbsp;samples, if we want to do so, we must use a&amp;nbsp;&lt;b&gt;Variational Autoencoder.&lt;/b&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;
&lt;h3&gt;
&lt;b&gt;Variational Autoencoder (VAE)&lt;/b&gt;&lt;/h3&gt;
&lt;div&gt;
The distinguishing feature of a VAE compared to an autoencoder is that - by design - the latent spaces are continuous, in the sense that two reprensentations which are &lt;i&gt;close&lt;/i&gt; in the latent space will result in similar looking outputs when decoded. &lt;i&gt;Close&lt;/i&gt; here can be any metric, but let&#39;s consider the Euclidean metric for intuitive understanding. This is achieved via borrowing some machinery from Bayesian analysis (hence the &lt;b&gt;variational &lt;/b&gt;part of the name) and cleverly manipulating the loss function.&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;The loss function&lt;/b&gt;&lt;/h3&gt;
In the regular autoencoder, for vectors $(x_i,y_i)$ we define the loss function as the standard sum of squares&lt;br /&gt;
&lt;br /&gt;
$$ L(y, \hat{y}) = \sum_{i=1}^{n} (y_i - \hat{y}_{i})^2 $$&lt;br /&gt;
&lt;br /&gt;
where $(y_i = x_i)$ for an autoencoder and $ \hat{y}_{i}$ is the attempted reconstruction of the input $x_i$ by the autoencoder. This loss function has a single job - to minimise the reconstruction error, it as no constraints as to how the latent vectors are represented or distributed in the latent space.&lt;br /&gt;
&lt;br /&gt;
The trick is to introduce some form of penalty into this loss function such that we coerce the latent vectors to be drawn from a &lt;b&gt;continuous&lt;/b&gt;&amp;nbsp;probability distribution, thus ensuring it has the aforementioned desirable properties for generating samples. This is achieved by using the &lt;a href=&quot;https://www.countbayesie.com/blog/2017/5/9/kullback-leibler-divergence-explained&quot;&gt;Kullback Leibler (KL) divergence&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
The KL divergence is a very important piece of machinery, often used in Bayesian analysis. It gives a (non-symmetric) measure of how similar or dissimilar two probability distributions are. We can use it to ensure our latent vectors are somewhat drawn from a distribution of our choice - this is almost always a Gaussian distribution due to the tractability of the math and the existence of closed form solutions [3].&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;&lt;b&gt;ADDITIONAL MATERIAL TO FOLLOW.&lt;/b&gt;&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
[1]&lt;a href=&quot;https://towardsdatascience.com/applied-deep-learning-part-3-autoencoders-1c083af4d798&quot;&gt;https://towardsdatascience.com/applied-deep-learning-part-3-autoencoders-1c083af4d798&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
[2]&lt;a href=&quot;https://towardsdatascience.com/intuitively-understanding-variational-autoencoders-1bfe67eb5daf&quot;&gt;https://towardsdatascience.com/intuitively-understanding-variational-autoencoders-1bfe67eb5daf&lt;/a&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
[3]&lt;a href=&quot;https://arxiv.org/pdf/1907.08956.pdf&quot;&gt;https://arxiv.org/pdf/1907.08956.pdf&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/2150801296095561646/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2020/03/variational-autoencoders.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/2150801296095561646'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/2150801296095561646'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2020/03/variational-autoencoders.html' title='Variational Autoencoders'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr3pu634FNR1QNUC6q7HT-aLU6xzW2GIswHRyL5BzM_9yhTXrvkpHQgnww5c865-3dcOjj2yf1HABww5nwQYeAjL9osIBV0PBo_y_H8WYfNTh0BlfJwNlAMyvuDcRZgOgB3Jc_wlRE_mw1/s72-c/autoencoder.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-7373920183940463938</id><published>2018-02-02T17:09:00.000-08:00</published><updated>2018-07-19T03:32:02.981-07:00</updated><title type='text'>Recommender Systems: Collaborative Filtering and matrix factorization: Part 2</title><content type='html'>The previous post looked at the mechanics of SVD and how we can interpret and use it in the collaborating filtering approach to building a recommender system. I&#39;ve borrowed heavily from [1] for the blog below -&amp;nbsp; I&#39;ve followed it step by step. As I&#39;ve mentioned before, this blog is geared toward my continued education and understanding of machine learning topics so I&#39;ll likely be implementing ideas that already exist to get a better understanding of the underlying mechanics.&lt;br /&gt;
&lt;h3&gt;
User and Items rating matrix&lt;/h3&gt;
&lt;div&gt;
Suppose we have a matrix $r \in \mathbb{R}^{m \times n}$ which each row corresponds to a single user (i.e. person) and each column corresponds to a single item (i.e. movie) such that $r_{ui}$ corresponds to the rating user $u$ gave rating $i$. Now this matrix will generally be constructed from all user and rating information that is available and it is quite obvious that not every user will have rated every item available. In fact when we use the MovieLens dataset we&#39;ll see that only about 6% of the matrix $r$ are valid entries - the rest are missing and are the ratings we would like to predict by using our recommender system once it is built.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The sparsity of the matrix $r$ poses an issue using the SVD approach covered previously, as SVD aims to reconstruct a matrix as is; it considers all entries in the matrix $r$ as valid in the reconstruction process. So we need to make a slight tweak to our approach to building the recommender system. We still want a latent variable representation, but we only want to use the 6% of ratings that are populated.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Latent space representation&lt;/h3&gt;
&lt;div&gt;
In order to define the latent space representations, we make the following assumptions:&lt;/div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;Each user can be described by a $k$ dimensional latent vector $\textbf{x}_u =&amp;nbsp;&amp;nbsp;\left[ x_{u1} \dots x_{uk} \right] \in \mathbb{R}^k$&lt;/li&gt;
&lt;li&gt;Each item can be described by a $k$ dimensional latent vector $\textbf{y}_i =&amp;nbsp; \left[ y_{i1} \dots y_{ik} \right]\in \mathbb{R}^k$&lt;/li&gt;
&lt;/ol&gt;
Hence we can approximate the rating user $u$ gave item $j$ as $$\hat{r}_{ui} = \textbf{x}_{u}^{T} \cdot \textbf{y}_{i}$$&lt;/div&gt;
&lt;div&gt;
Hence we can define the loss function (with some regularisation) as trying to minimise the difference between the predicted and actual ratings a every user gave each item:&lt;/div&gt;
&lt;div&gt;
$$ L = \sum_{u,i \in S}\left( r_{ui} - \textbf{x}_{u}^{T} \cdot \textbf{y}_{i}\right)^2 + \lambda_x \sum_{u} ||\textbf{x}_u||^2 + \lambda_y \sum_{i} ||\textbf{y}_i||^2$$ where $S$ is the set of valid ratings and $\lambda_x$, $\lambda_y$ are regularisation hyperparameters. We can rewrite a little more succinctly using matrix notation: $$ L = \left( \textbf{r}_u - \textbf{x}^T_uY^T \right)^2 + \lambda_x \sum_{u} ||\textbf{x}_u||^2 + \lambda_y \sum_{i} ||\textbf{y}_i||^2 $$ where $$\textbf{r}_u = \left[ r_{u_1} \dots r_{u_m} \right]$$ is the rating vector for user &lt;b&gt;u&lt;/b&gt;&#39;s ratings of the &lt;i&gt;m&lt;/i&gt;&amp;nbsp;items and $$Y = \left[ \begin{array}{ccc} -&amp;amp; y^{T}_{1} &amp;amp; - \\ - &amp;amp; y^{T}_{2} &amp;amp; - \\ &amp;amp; \vdots&amp;nbsp; &amp;nbsp; &amp;amp;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; \\ - &amp;amp; y^{T}_{m} &amp;amp; - \end{array} \right] $$ is a composite vector of the $y_i$&#39;s. Now this equation looks quite familiar (recall the definition of the OLS loss function...) hence if we fix one of the $\textbf{x}^T_u$ or $\textbf{y}_{i}$ then we have effectively reduced the cost function to that of an OLS problem. The procedure is simple, we fix $\textbf{y}_i$ and find the corresponding&amp;nbsp; $\textbf{x}^T_u$ which minimises the loss function, this then feeds into the next iteration where we fix&amp;nbsp; $\textbf{x}^T_u$ and find the&amp;nbsp; $\textbf{y}_i$ which minimises the updated loss function and continue until convergence (or some other appropriate stopping criteria). This process is known as (for obvious reasons) as &lt;i&gt;Alternating Least Squares&lt;/i&gt;&amp;nbsp;and we&#39;ll derive the close form solution in the next section.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Alternating Least Squares&lt;/h3&gt;
&lt;br /&gt;
We can then minimize $L$ by differentiating with respect to the components of our user vector $x_u$ and setting to $0$. Using summation notation:&lt;br /&gt;
$$ \frac{\partial L}{\partial x_{ua}} = \sum_{i}^{m} -2 \left(r_{ui} - \sum_{j}^k x_{uj} Y_{ij} \right)Y_{ai} + 2 \lambda_x x_{ua}$$ Hence for a minimum and in matrix form $$ 0 = -\left( \textbf{r}_u - \textbf{x}^T_uY^T \right) Y + \lambda_x \textbf{x}_{u}$$ we can re-arrange to get $$ \textbf{x}_{u}^T = \textbf{r}_u Y \left(&amp;nbsp;I \lambda_x + Y^TY\right)^{-1}$$ We can perform an analogous calculation for $\textbf{y}_i$ which yields $$ \textbf{y}_i^T = r_i X \left( I \lambda_y + X^TX \right)^{-1} $$ where $I$ is the $k \times k$ identity matrix. Hence we have derived the updates for our parameters required at each iteration - the next section looks at the results.&lt;br /&gt;
&lt;br /&gt;
Next time we&#39;ll have a look at the python implementation and results to see how well our recommendation system works!&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;/h3&gt;
&lt;h3&gt;
Results&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
See my &lt;a href=&quot;https://github.com/adammtong/ExplicitMatrixFactorisation&quot;&gt;github&lt;/a&gt;&amp;nbsp;for the python implementation in a jupyter notebook. I have run the model with the following parameters:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;$k = 10$ latent features&lt;/li&gt;
&lt;li&gt;$\lambda_x = 0.01$ user regularisation&lt;/li&gt;
&lt;li&gt;$\lambda_y = 0.01$ item regularisation&lt;/li&gt;
&lt;li&gt;$100$ iterations&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
You can see the training and test error plot for each iteration below:&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUNvBRblpD2GngvQ29ofE88YxNI4Xk4JcuJxkMPZrY1lwhFBleHBYhRhpeSyGvukhWOTrSjuu8pfVAKfG1qfMPHpcPGdjB9r07Ppsk5n2xR_oBHIDl4ienDQa9bS-oTHMHbmHv1NHg9L-G/s1600/ALS.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;265&quot; data-original-width=&quot;385&quot; height=&quot;275&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUNvBRblpD2GngvQ29ofE88YxNI4Xk4JcuJxkMPZrY1lwhFBleHBYhRhpeSyGvukhWOTrSjuu8pfVAKfG1qfMPHpcPGdjB9r07Ppsk5n2xR_oBHIDl4ienDQa9bS-oTHMHbmHv1NHg9L-G/s400/ALS.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
We can see that learning occurs very quickly and after approximately the fifth&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
iteration, there is not much reduction in the training or test MSE. The training MSE error sits around $5.5$ and the test hovers just above $8$.&lt;br /&gt;
&lt;div&gt;
&lt;h3&gt;
Additional flexibility and SGD&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
So far we&#39;ve only considered a linear model which does not allow for the idiosyncrasies of individual user rating behaviour i.e. a given user might tend to rate movies more highly in general, compared to another user. Concretely, consider a movie I don&#39;t particularly like - I might give it a 3/5 because I&#39;m a nice guy, however someone else might be more punitive and assign the movie a 1/5. Even though we have the same sentiment toward the movie, our individual rating philosophies differ. Similarly we can address the fact that certain movies tend to be rated lower compared to another movie even though the average sentimentality towards each movie might be similar.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
We can address this by normalising each movie/rating pair by refining our rating estimate:&lt;br /&gt;
$$\hat{r}_{ui} = \mu + b_i + b_u + \textbf{x}_{u}^{T} \cdot \textbf{y}_{i}$$ where $b_i$ is the &lt;i&gt;user bias, &lt;/i&gt;$b_u$&lt;i&gt;&amp;nbsp;&lt;/i&gt;is the &lt;i&gt;item bias&lt;/i&gt;&amp;nbsp;and $\mu$ is the &lt;i&gt;global bias&lt;/i&gt;. This global bias term just adds additional flexibility (another parameter = another degree of freedom) for our model. Hence our loss function is now defined as:&lt;br /&gt;
&lt;br /&gt;
$$ L = \sum_{u,i \in S}\left( r_{ui} - \mu - b_i - b_u - \textbf{x}_{u}^{T} \cdot \textbf{y}_{i}\right)^2 + \lambda_x \sum_{u} ||\textbf{x}_u||^2 + \lambda_y \sum_{i} ||\textbf{y}_i||^2 + \lambda_{bi} \sum_{i} ||b_i||^2&amp;nbsp; + \lambda_{bu} \sum_{u} ||b_u||^2&amp;nbsp; $$&lt;br /&gt;
&lt;br /&gt;
where we have just substituted our new definition for $$\hat{r}_{ui}$$ and added regularisation terms for our $b_i$ and $b_u$ biases.&lt;br /&gt;
&lt;br /&gt;
The form of this loss function is no longer comparable to OLS, due to our new bias terms. In order to minimise, we turn to our old friend SGD. There&#39;s enough maths on this page so I won&#39;t go through the gory details of the updates for each parameter - if you&#39;re interested you can see the details here [1].&lt;br /&gt;
&lt;br /&gt;
Optimising this new loss function using SGD with the same parameters above:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;$k = 10$ latent features&lt;/li&gt;
&lt;li&gt;$\lambda_x = 0.01$ user regularisation&lt;/li&gt;
&lt;li&gt;$\lambda_y = 0.01$ item regularisation&lt;/li&gt;
&lt;li&gt;$\lambda_bu = 0.01$ user bias regularisation&lt;/li&gt;
&lt;li&gt;$\lambda_bi = 0.01$ item bias regularisation&lt;/li&gt;
&lt;li&gt;$100$ iterations&lt;/li&gt;
&lt;li&gt;$\eta =&amp;nbsp;0.005$ learning rate&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibFC7QioH8irVKc7Bp-tHRQquw1aCZgW4dXUGrAZrwtYfXwVfks7_d8UYfbH7k9UCArVa-ZdRh9m40ImxZLfXUPdJ2SXyryTC5x4BmLAUYb9JiN22JVxN4BCFsmtCpgoqQSYsAWsPoYHbI/s1600/SGD.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;265&quot; data-original-width=&quot;388&quot; height=&quot;272&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibFC7QioH8irVKc7Bp-tHRQquw1aCZgW4dXUGrAZrwtYfXwVfks7_d8UYfbH7k9UCArVa-ZdRh9m40ImxZLfXUPdJ2SXyryTC5x4BmLAUYb9JiN22JVxN4BCFsmtCpgoqQSYsAWsPoYHbI/s400/SGD.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
We can see that the training error shrinks to zero whilst the test error starts increasing with the number of iterations - these are the classic signs of overfitting! Looking at the plot, cutting off training at around iteration $25$ seems like a good idea. Comparing this to our ALS results, the test error is now around $1$, which is markedly better than the $8$ we observed earlier - this model fits the data a lot better, as expected with the additional flexibility.&lt;br /&gt;
Ok we have fit our models, now what? The whole purpose of this exercise was to make recommendations! What we&#39;re going to do is use the cosine-similarity to compare each of our latent vectors - given an input vector representation of a movie, we&#39;ll find the most &#39;similar&#39; in our latent space to provide the user with recommendations!&lt;br /&gt;
&lt;br /&gt;
On the right below we have the recommendations based on the bond movie &lt;i&gt;Independence Day&amp;nbsp;&lt;/i&gt;provided by our SGD model and on the left the ALS model.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGgu5JK64JTMTVY_o0GMVwAd6XtALeQfRBUJHgYqs_q-_DftyDYD6bFvU_ADOrkgYMb45sEvmXPBR_STxJn2IPQS8-S_4coJ0d23nhP36VaEkiykyBSzeKoX94FbtKJaHwfdtno51OpPKn/s1600/Screen+Shot+2018-07-19+at+7.55.24+pm.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;620&quot; data-original-width=&quot;514&quot; height=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGgu5JK64JTMTVY_o0GMVwAd6XtALeQfRBUJHgYqs_q-_DftyDYD6bFvU_ADOrkgYMb45sEvmXPBR_STxJn2IPQS8-S_4coJ0d23nhP36VaEkiykyBSzeKoX94FbtKJaHwfdtno51OpPKn/s200/Screen+Shot+2018-07-19+at+7.55.24+pm.png&quot; width=&quot;165&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjotfl8rzggEIPmXaLXzUxee4nHkt8kJdvOjKwlD0r1oMBVxmBqEgYZmL-5N6iQb11hDDVyFCyb0sSSXbgv0pGbfoEpEVyqjIzvuLCgQpgI4rPFyGi0WrrXGg4zPuAwod_zQhMdqNBsejhI/s1600/Screen+Shot+2018-07-19+at+8.06.33+pm.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;604&quot; data-original-width=&quot;498&quot; height=&quot;200&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjotfl8rzggEIPmXaLXzUxee4nHkt8kJdvOjKwlD0r1oMBVxmBqEgYZmL-5N6iQb11hDDVyFCyb0sSSXbgv0pGbfoEpEVyqjIzvuLCgQpgI4rPFyGi0WrrXGg4zPuAwod_zQhMdqNBsejhI/s200/Screen+Shot+2018-07-19+at+8.06.33+pm.png&quot; width=&quot;163&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Which do you think is better? There is some common recommendations - The Rock, Twister and the recommendations seem reasonable for the most part, aside from a stray &lt;i&gt;Toy Story&lt;/i&gt;. In reality you&#39;d probably combine these recommendations in the final model and perhaps supplement with some content based filtering to get the &#39;best&#39; recommendation.&lt;br /&gt;
&lt;br /&gt;
Until next time...&lt;br /&gt;
&lt;br /&gt;
&lt;h4 style=&quot;background-color: white; color: #222222; font-family: Arial, Tahoma, Helvetica, FreeSans, sans-serif; margin: 0px; position: relative;&quot;&gt;
References&lt;/h4&gt;
[1]&amp;nbsp;https://blog.insightdatascience.com/explicit-matrix-factorization-als-sgd-and-all-that-jazz-b00e4d9b21ea&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/7373920183940463938/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2018/02/recommender-systems-collaborative.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/7373920183940463938'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/7373920183940463938'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2018/02/recommender-systems-collaborative.html' title='Recommender Systems: Collaborative Filtering and matrix factorization: Part 2'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUNvBRblpD2GngvQ29ofE88YxNI4Xk4JcuJxkMPZrY1lwhFBleHBYhRhpeSyGvukhWOTrSjuu8pfVAKfG1qfMPHpcPGdjB9r07Ppsk5n2xR_oBHIDl4ienDQa9bS-oTHMHbmHv1NHg9L-G/s72-c/ALS.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-1209169806519402281</id><published>2017-10-26T02:37:00.000-07:00</published><updated>2017-10-26T02:37:26.089-07:00</updated><title type='text'>Recommender Systems: Collaborative Filtering and matrix factorization</title><content type='html'>&lt;h3&gt;
What is a recommender system?&lt;/h3&gt;
&lt;div&gt;
Think about any website which has a community of &lt;i&gt;users&lt;/i&gt;&amp;nbsp;who purchase/interact with content &lt;i&gt;(items) &lt;/i&gt;on that website. Based on users&#39; interactions with the items, various personalised recommendations can be tailored to specific user behaviour. More concretely, consider the purchase suggestions Amazon offers you, or movies that Netflix recommend you watch based on your past viewing behaviour. The machinery behind these recommendations is the basis of recommender systems.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Companies are looking to personalise a user&#39;s experience in a way that resonates with them - to make the user experience feel unique and tailored to their needs. These days websites capture all sorts of attributes from a user&#39;s experience/interaction - time spent on pages, scroll speed, viewing behaviour, purchasing behaviour etc... One may ask how we can use such detailed information to offer a better user experience; through the construction of a recommender system.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Now recommender systems are generally based on two types of user behaviour:&lt;/div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;Implicit feedback&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Information based on user behaviour such as viewing/purchasing/click behaviour; user preferences can be inferred.&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Explicit feedback&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Where the user has given an &lt;i&gt;explicit&lt;/i&gt;&amp;nbsp;rating to a movie or item (a 5 star rating for example).&lt;/li&gt;
&lt;/ul&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div&gt;
There are generally two approaches to building a recommender system, &lt;i&gt;content based filtering&lt;/i&gt;&amp;nbsp;and &lt;i&gt;collaborative filtering.&lt;/i&gt;&lt;/div&gt;
&lt;div&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;&lt;/div&gt;
&lt;h3&gt;
&lt;i&gt;Content based filtering&lt;/i&gt;&lt;/h3&gt;
&lt;div&gt;
The approach of content based filtering is as follows:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Each item is characterised by a series of properties or features. For example if we are using content based filtering to build a movie recommendation system then each movie could have attributes such as lead actor, director, genre, etc.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;A profile based on these attributes is built for each user and hence new items can be recommended to the user via a similarity measure between the user&#39;s profile and a specific items profile.&lt;/li&gt;
&lt;/ul&gt;
This approach requires the features of each item to be defined explicitly and hence it is limited to the level of feature engineering. It also means that as new items are added - which have new characteristics - these must be calculated for each of the existing items too and the dimensionality of our feature space will rise exponentially. We will not focus on this approach in the remainder of the blog.&lt;/div&gt;
&lt;h3&gt;
&lt;/h3&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
&lt;i&gt;
Collaborative Filtering&lt;/i&gt;&lt;/h3&gt;
&lt;div&gt;
As its name suggests, collaborative filtering uses an aggregate (or collaborative) approach to suggests new items, based on the premise that users who share a common interest in certain items will also share a common interest in other items. Unlike content based filtering, this approach doesn&#39;t require hand crafted features for each item and hence can be more easily scaled to larger and even different domains. We will focus on the collaborative filtering approach in building our recommender system and will use the MovieLens dataset in our example [1].&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The approach we take in building the collaborative filter borrows from some linear algebra results, namely the Singular Value Decomposition (SVD) of a matrix. I will first define exactly what SVD is and then I&#39;ll add some context into how it helps us with creating a recommender system.&lt;/div&gt;
&lt;h3&gt;
&lt;/h3&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
&lt;i&gt;
Singular Value Decomposition (SVD)&lt;/i&gt;&lt;/h3&gt;
&lt;div&gt;
Given a matrix $M \in \mathbb{R}^{m \times n}$ there exists a factorisation $ M = U \Sigma V^{*}$ where&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;$U \in \mathbb{R}^{m \times m}$ us a unitary matrix (i.e&amp;nbsp; $UU^{*} = U^{*}U = I$)&lt;/li&gt;
&lt;li&gt;$\Sigma \in \mathbb{R}^{m \times n}$ is diagonal, with non-negative numbers (singular values)&amp;nbsp;&lt;/li&gt;
&lt;li&gt;$V^{*} \in \mathbb{R}^{n \times n}$ is the conjugate transpose of a unitary matrix $V$&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;
Note that since I&#39;ve taken $\mathbb{R}$ as the field the matrix entries come from, the conjugate transpose is just the transpose (i.e. $V^{*} \equiv V^{T}$) and the unitary matrices are also known as &lt;i&gt;orthogonal&lt;/i&gt;&amp;nbsp;matrices.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
What this is telling us, is that &lt;i&gt;any&lt;/i&gt;&amp;nbsp;matrix can be decomposed into the above structure. If you think about the eigenvalue decomposition (EVD) of a matrix, it only exists for a square matrix, whereas the SVD of an arbitrarily (non-square) shaped matrix exists. There is a deep connection between the SVD and EVD of a matrix - the non zero entries of $\Sigma$ are the square root of the eigenvalues of $MM^T$. See section 3.2 of [2].&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Yeah, yeah that&#39;s a cool result, but how does that help us with the recommender system? Well, the motivation is borrowed from Latent Semantic Analysis&amp;nbsp; (LSA) - a topic in Natural Language Processing which aims to understand relationships between documents and the words they contain. In LSA, a term-document matrix is created in which each entry contains the number of occurrences of a particular word in a particular document. This term-document matrix is then decomposed via SVD with the resultant matrices representing documents and terms which capture the pattern of term usage among documents. The top $k$ singular values are kept, such that the decomposition results in a representation of the original matrix in a lower dimensional space. The idea is that this lower dimensional representation captures the structure of the relationship between documents and terms, whilst filtering out the noise. In this lower dimensional &#39;latent&#39; space one can simply find the similarity of documents or terms by using our $U$ and $V$ matrices.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
So in our case, the analogy of a term-document matrix is a user-item matrix in which each row of the matrix is a user, and each column is an item. For our example the items will be movies. Each entry $(i,j)$ corresponds to the rating the $i^{th}$ user gave to the $j^{th}$ movie. The SVD will result in a latent space in which user and item vectors reside and we can calculate their similarities.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h3&gt;
&lt;i&gt;Interpretation of SVD&lt;/i&gt;&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h4&gt;
&lt;i&gt;Geometric Interpretation&lt;/i&gt;&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
In the case of $M \in \mathbb{R}^{n \times n}$ - aka a linear map within the same space - then there is a nice geometrical interpretation of the action of $M$, the image below illustrates this&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;$V$ is an orthogonal matrix - which corresponds to a reflection or rotation&lt;/li&gt;
&lt;li&gt;$\Sigma$ is diagonal and hence is a scaling matrix&lt;/li&gt;
&lt;li&gt;$U$ is also an orthogonal matrix - which is another reflection or rotation&lt;/li&gt;
&lt;/ul&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUHJ3Mb5MPk4KVll64jaM_WWXeGQRlJCFIyR4ex_g99tMveQ5RI5ZmPE_JPd6YiA1J2D40MxtSyOt3gV1MmdevdVdjd1KjDhKySWXLERHiVq0eouaAB8F6FLqlIWpjH2bUw46SXnKi4Uo6/s1600/Singular-Value-Decomposition.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;298&quot; data-original-width=&quot;330&quot; height=&quot;288&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUHJ3Mb5MPk4KVll64jaM_WWXeGQRlJCFIyR4ex_g99tMveQ5RI5ZmPE_JPd6YiA1J2D40MxtSyOt3gV1MmdevdVdjd1KjDhKySWXLERHiVq0eouaAB8F6FLqlIWpjH2bUw46SXnKi4Uo6/s320/Singular-Value-Decomposition.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
More generally, consider $M \in \mathbb{R}^{m \times n}$, a bilinear map between spaces, we can rewrite the SVD equation as $$ MV = U \Sigma $$ If we consider each of the $j$ columns of $V$ separately then it is apparent $Mv_{j} = \sigma_j u_{j}$. Recalling that since $U$ and $V$ are orthogonal matrices and hence their rows form orthonormal bases, the action of $M$ is as follows: the basis of a coordinate system $\{v_1, \dots, v_n \}$ is mapped to a &#39;scaled&#39; basis of a different coordinate system $\{\sigma_{1} u_{1}, \dots, \sigma_{m} u_{m} \}$. In words, every matrix $M \in \mathbb{R}^{m \times n}$ can be interpreted as having the following action&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;A first rotation in the input space&lt;/li&gt;
&lt;li&gt;A simple positive scaling that takes a vector in the input space to the output space&lt;/li&gt;
&lt;li&gt;And another rotation in the output space&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4&gt;
&lt;i&gt;SVD as an approximation&lt;/i&gt;&lt;/h4&gt;
Note that in the SVD decomposition there is an equality; the matrix $M$ is&amp;nbsp;&lt;i&gt;exactly&lt;/i&gt;&amp;nbsp;reconstructed. In practice, we don&#39;t actually want the exact matrix, instead we want a lower&amp;nbsp;&lt;i&gt;k&lt;/i&gt;-dimensional approximation which will have less noise and (hopefully) have captured the latent structure of the user/item relationships. Now it turns out through SVD -if we keep only the top&amp;nbsp;&lt;i&gt;k singular&amp;nbsp;&lt;/i&gt;values - the resulting matrix is the best&amp;nbsp;&lt;i&gt;k&lt;/i&gt;-rank approximation of $M$, where the notion of &#39;best&#39; is defined by the Frobenius norm. See Section 2.1 of [2] for details.&lt;br /&gt;
&lt;br /&gt;
We can think of the rank&amp;nbsp;&lt;i&gt;k&lt;/i&gt;&amp;nbsp;approximation via SVD of a real matrix $M$ as the decomposition of $M$ into the sum of&amp;nbsp;&lt;i&gt;k&lt;/i&gt;&amp;nbsp;rank 1 matrices. That is&lt;/div&gt;
&lt;div&gt;
$$ M = \sum_{j=1}^{k} \sigma_j u_j v_{j}^{*}$$&lt;/div&gt;
&lt;div&gt;
with $\sigma_1 &amp;gt; \sigma_2 &amp;gt; \dots &amp;gt;\sigma_k &amp;gt; 0$. This is a kind of expansion of $M$ in terms of rank 1 matrices, with the first term capturing the &#39;most&#39; of $M$, followed by the second term and so on, with each including term adding to the accuracy of the approximation.&lt;br /&gt;
&lt;br /&gt;
For a great exposition on SVD and some various angles on interpretation, check out [3] by Jeremy Kun which should help you gain some intuition.&lt;br /&gt;
&lt;br /&gt;
Well, that wraps up a short summary on the techniques we&#39;ll use to build our recommender system! Next post will be focused some of the subtleties of the implementation and some tweaks which have been used to win competitions in the past!&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h3&gt;
References&lt;/h3&gt;
&lt;/div&gt;
&lt;ul&gt;&lt;ul&gt;&lt;ul&gt;
&lt;/ul&gt;
&lt;/ul&gt;
&lt;/ul&gt;
[1] https://grouplens.org/datasets/movielens/&lt;br /&gt;
[2] http://www.math.ucla.edu/~dakuang/cse6040/lectures/6040_lecture15.pdf&lt;br /&gt;
&lt;div&gt;
[3] https://jeremykun.com/2016/04/18/singular-value-decomposition-part-1-perspectives-on-linear-algebra/&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/1209169806519402281/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/10/recommender-systems-collaborative.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1209169806519402281'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1209169806519402281'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/10/recommender-systems-collaborative.html' title='Recommender Systems: Collaborative Filtering and matrix factorization'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUHJ3Mb5MPk4KVll64jaM_WWXeGQRlJCFIyR4ex_g99tMveQ5RI5ZmPE_JPd6YiA1J2D40MxtSyOt3gV1MmdevdVdjd1KjDhKySWXLERHiVq0eouaAB8F6FLqlIWpjH2bUw46SXnKi4Uo6/s72-c/Singular-Value-Decomposition.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-3916508403818902508</id><published>2017-06-22T04:48:00.000-07:00</published><updated>2017-06-22T04:50:27.765-07:00</updated><title type='text'>Transfer learning and hotdog classification!</title><content type='html'>Inspired by a &lt;a href=&quot;https://www.youtube.com/watch?v=ACmydtFDTGs&quot;&gt;recent episode&lt;/a&gt; of Silicon Valley where Jian Yang builds an app to classify pictures as either &lt;i&gt;Hotdog&lt;/i&gt;&amp;nbsp;or &lt;i&gt;Not Hotdog&lt;/i&gt;, I decided to have a crack at retraining the final layer of the Inception V3 network to do so.&lt;br /&gt;
&lt;br /&gt;
Thankfully, the lovely folks at Google make it &lt;a href=&quot;https://www.tensorflow.org/tutorials/image_retraining&quot;&gt;ridiculously easy to do so&lt;/a&gt;. So instead of maxing out my poor little Macbook pro for weeks (or months :/) of training - we can utilise the already trained network and simply adjust the final layer for our use, more on this below.&lt;br /&gt;
&lt;br /&gt;
Note that this post assumes familiarity of CNN architecture and its use in computer vision - see this great course at Stanford for a great introduction to CNNs - &lt;a href=&quot;http://cs231n.stanford.edu/&quot;&gt;CS231n: Convolutional Neural Networks for Visual Recognition.&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;
Background&lt;/h2&gt;
&lt;div&gt;
The Inception v3 image recognition neural network came out of Google at the end of 2015. The focus of the architecture builds upon the original inception architecture of GoogLeNet [1] which &lt;i&gt;was also designed to perform well even under strict constraints
on memory and computational budget &lt;/i&gt;[2].&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Inception v1&lt;/h3&gt;
The basis of this (at the time) new architecture was the so called &lt;i&gt;inception&lt;/i&gt;&amp;nbsp;module. It builds on the traditional convolutional layer which has a fixed height and width. Instead it applies and assortment of different size filters to the input, allowing the model to perform multi-level feature extraction on each input:&lt;/div&gt;
&lt;div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgobkkGou6jGkkSktRVUjcD9OqZ65zLqdJMdg9aMATmrg30ZRdJWyRrU9kbhfNVSdItbmLrhZS9oGuyy_H7qTwPTmgGjXzwO7deuLzBwbq-_Sng8Zgy1EoFWfnMLIfKyK83gLdlDe6cOtQE/s1600/inception.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;254&quot; data-original-width=&quot;549&quot; height=&quot;185&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgobkkGou6jGkkSktRVUjcD9OqZ65zLqdJMdg9aMATmrg30ZRdJWyRrU9kbhfNVSdItbmLrhZS9oGuyy_H7qTwPTmgGjXzwO7deuLzBwbq-_Sng8Zgy1EoFWfnMLIfKyK83gLdlDe6cOtQE/s400/inception.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;i&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/i&gt;
&lt;i&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Figure 1: &lt;span class=&quot;qlink_container&quot;&gt;Taken from Rethinking the inception architecture for computer vision[1] - the naive inception module.&lt;/span&gt;&lt;/span&gt;&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;span class=&quot;qlink_container&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/i&gt;
As you can see above, there are $1 \times 1$, $3 \times 3$ and $5 \times 5$ convolutions as well as a $3 \times 3$ max pooling applied to the input. In theory, this is great - as we are able to exploit multiple level spatial correlations in the input, however using a large number of $5 \times 5$ filters can be computationally expensive.&lt;br /&gt;
&lt;br /&gt;
This train of thought led to the next iteration of the inception module:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhExh19H-qEF0SWPy-z-L6lO6ntJme5ZGpWW8hkFAdSfd0JCJKOd1hwTg4tIDiLGbhQAbVUGxyElSrAMk6O0SFbYhX_mDedeEqeoNZVM4k4-YVemwrXx2uiTxH1l3wOS4l3Kla2yy0g8gts/s1600/inception1a.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;279&quot; data-original-width=&quot;550&quot; height=&quot;202&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhExh19H-qEF0SWPy-z-L6lO6ntJme5ZGpWW8hkFAdSfd0JCJKOd1hwTg4tIDiLGbhQAbVUGxyElSrAMk6O0SFbYhX_mDedeEqeoNZVM4k4-YVemwrXx2uiTxH1l3wOS4l3Kla2yy0g8gts/s400/inception1a.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;i&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;Figure 2:&amp;nbsp;&lt;span class=&quot;qlink_container&quot;&gt;Taken from Rethinking the inception architecture for computer vision[1] - inception module with dimension reductions.&lt;/span&gt;&lt;/span&gt;&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;span class=&quot;qlink_container&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/i&gt;
This architecture is essentially the same as the initial proposal except that each of the larger filters is preceded by a $1 \times 1$ convolution. These &amp;nbsp;$1 \times 1$&amp;nbsp;convolutions act as a dimension reduction tool in the &lt;i&gt;channel&lt;/i&gt;&amp;nbsp;dimension, leaving the spatial dimension untouched. The idea is that the important cross channel information will be captured without explicitly keeping every channel. Once the channel dimension reduction has been performed, these results feed into the larger filters which will capture both spatial and channel correlations. The $1 \times 1$ filters also have ReLU activation functions which introduce additional non-linearities into the system.&lt;br /&gt;
&lt;br /&gt;
Put simply in [1]:&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;i&gt;One of the main beneficial aspects of this architecture is that it allows for increasing the number of
units at each stage significantly without an uncontrolled blow-up in computational complexity. The
ubiquitous use of dimension reduction allows for shielding the large number of input filters of the
last stage to the next layer, first reducing their dimension before convolving over them with a large
patch size. Another practically useful aspect of this design is that it aligns with the intuition that
visual information should be processed at various scales and then aggregated so that the next stage
can abstract features from different scales simultaneously.&amp;nbsp;&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;br /&gt;
&lt;h3&gt;
Inception v2/3&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
A key realisation of the earlier iterations of Inception was that the improved performance compared to its peers was driven by dimensionality reduction using the $1 \times 1$ filters. This has a natural interpretation in computer vision; as the authors put it [2]:&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
&lt;i&gt;In a vision network,
it is expected that the outputs of near-by activations
are highly correlated. Therefore, we can expect that their
activations can be reduced before aggregation and that this
should result in similarly expressive local representations.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
With reducing computational complexity in mind (hence the number of parameters in the network) the authors sought a way to keep the power of the larger filters, but reduce how expensive the operations involving them were. Thus they investigated replacing the larger filters with a multi-layer network that has the same input/output size but less parameters.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiipFKPZehD-04ZmqvDAyDd0rKmi_EOyoqeHcvbiSeX2F4xF5KFZ3MMSIj8ji2_cbhq8p6p9adzcbAQnptdbvSmf4UUd4FA7Nn2qkWYKYGOafOoDYhuHlWMw886MbdXeWsjyLu4RofGEPDX/s1600/5x5replacement.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;202&quot; data-original-width=&quot;263&quot; height=&quot;245&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiipFKPZehD-04ZmqvDAyDd0rKmi_EOyoqeHcvbiSeX2F4xF5KFZ3MMSIj8ji2_cbhq8p6p9adzcbAQnptdbvSmf4UUd4FA7Nn2qkWYKYGOafOoDYhuHlWMw886MbdXeWsjyLu4RofGEPDX/s320/5x5replacement.PNG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;i&gt;Figure 3: Replacing a $5 \times 5$ filter with a network of $3 \times 3$ and a $1 \times 1$ filter.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
Thus the inception module now looks like&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLCxAegaVCN9cEGEjRWET0WgCuvohvqNKFc9W52Alm2Ztyir6W9zSFjNCNGkVhUe2W8NLMV_XXzq2qsy1GVbimYqOzjkLlmPTKzw-uMZrLtHy5uL60HsqA7SYJP-lREI7zoc0FEcSQVed_/s1600/inceptionaa.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;319&quot; data-original-width=&quot;325&quot; height=&quot;314&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLCxAegaVCN9cEGEjRWET0WgCuvohvqNKFc9W52Alm2Ztyir6W9zSFjNCNGkVhUe2W8NLMV_XXzq2qsy1GVbimYqOzjkLlmPTKzw-uMZrLtHy5uL60HsqA7SYJP-lREI7zoc0FEcSQVed_/s320/inceptionaa.PNG&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;i&gt;Figure 4: Inception module where each $5 \times 5$ filter has been replaced by two $3 \times 3$ filters.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;
This replacement results in a 28% saving in computational efficiency [2]. Inception v2 and v3 share the same inception module architecture, the different arises in differences in training - namely batch normalization of the fully connected layer of the auxiliary classifier.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Transfer Learning&lt;/h3&gt;
&lt;div&gt;
Now that we have a (very) high level understanding of the architecture of Inception v3, let&#39;s talk about transfer learning.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Given how computationally expensive it is to train a CNN from scratch - a task which can take months - we can use the results of a pre-trained CNN to do the feature extraction for us. The idea is that the generic features of an image (edges, shapes, etc) which are captured in the early layers of the CNN are common to most images. That is, we can utilise a CNN that has been trained for a specific task on millions of images to do the feature extraction for our image recognition task.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
We then strip the CNN of the final fully connected layer (which feeds to the softmax classifier) and replace it with a fully connected layer built for our own task and train that. There are several approaches to transfer learning which are dependent on the task, such as we can use the pre-trained CNN as a feature extractor as detailed above, or we can use it as a starting point and retrain the weights in the convolutional layers. The amount of training data you have for your task and the details of the task will generally dictate the approach. See [3] for a detailed study on transfer learning.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The pre-trained CNN we&#39;ll be utilising an Inception v3 network as described above, trained on the ImageNet 2012 dataset which contained 1.2million images and 1000 categories.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Implementation&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
Thankfully Google had the foresight to make it dead easy to perform the aforementioned transfer learning using Tensorflow.&lt;br /&gt;
For my training images, I utilised the work done in [4] which provided around 350 hotdog images and around 50 not hotdog (notdog) images. We then utilise the script &lt;i&gt;&lt;a href=&quot;https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/image_retraining/retrain.py&quot;&gt;retrain.py&lt;/a&gt;&lt;/i&gt;&amp;nbsp;which we&#39;ll pass parameters to from the terminal.&lt;br /&gt;
&lt;br /&gt;
The script will determine the number of classes based on the number of folders in the parent folder. You don&#39;t need to worry about specific names for the images, you just need to make sure the folders contained the correctly labeled images.&lt;br /&gt;
&lt;br /&gt;
The rest of the parameters are fairly self explanatory and are explained on the &lt;a href=&quot;https://www.tensorflow.org/tutorials/image_retraining&quot;&gt;tutorial&lt;/a&gt;. One interesting set of parameters to note are the &lt;i&gt;random_crop&lt;/i&gt; and &lt;i&gt;random_scale, &lt;/i&gt;these distort the training images as to preserve their meaning but add new training examples. For example a picture of a hotdog rotated 90 degrees is still a hotdog; instead of sourcing additional hotdog pictures we can just rotate an existing training example to teach the classifier something new.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Results&lt;/h3&gt;
&lt;div&gt;
After running retrain.py with 500 training steps, I received the below training summary&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEix5nuevtJC4Hgy5wVAEEyW5xqi-soor4D16Am78RQXVK3KTdzpW0Gl31oaujYOOh4_5yzH-SlXtOqkZQEoU53VoJMU1C1_bKPGJ8STuvnQ2ehE23pu8OGTo_3QXnmgetJeERFtsrut3OP0/s1600/Screen+Shot+2017-06-20+at+9.10.34+PM.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;750&quot; data-original-width=&quot;1168&quot; height=&quot;256&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEix5nuevtJC4Hgy5wVAEEyW5xqi-soor4D16Am78RQXVK3KTdzpW0Gl31oaujYOOh4_5yzH-SlXtOqkZQEoU53VoJMU1C1_bKPGJ8STuvnQ2ehE23pu8OGTo_3QXnmgetJeERFtsrut3OP0/s400/Screen+Shot+2017-06-20+at+9.10.34+PM.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;99% Validation accuracy - not bad at all!&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;Let&#39;s have a look at a specific example and try the below hotdog&lt;/span&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwcMqLfiKtZD_AHSKGw-E9sJCfF1rUtfyFiMU9WhWTQgqOUKnhbFitxg96H5pqabkrZkOCkjLAC67Qw01q5MKUwoIB52I4OUzgOwC5Oy9dJ_3R2-iQapG0JbORr6wh8p1ARxTLIBbFp2N-/s1600/hotdog.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwcMqLfiKtZD_AHSKGw-E9sJCfF1rUtfyFiMU9WhWTQgqOUKnhbFitxg96H5pqabkrZkOCkjLAC67Qw01q5MKUwoIB52I4OUzgOwC5Oy9dJ_3R2-iQapG0JbORr6wh8p1ARxTLIBbFp2N-/s320/hotdog.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;
&lt;b&gt;&lt;span style=&quot;text-align: start;&quot;&gt;hotdogs (score = 0.99956)&lt;/span&gt;&lt;span style=&quot;text-align: start;&quot;&gt;&amp;nbsp;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;&lt;b&gt;random (score = 0.00044)&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
Great news, this image is in fact a hotdog and our CNN recognises it as such with a high degree of confidence. What about a notdog?&lt;/div&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;
&lt;/span&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizYKzzN7JaX8usZVDOLWseIE0wOC6i8sG6clFVJ3pJExURwKFgWwY8IfdMkEQrQjboQ44nMxGvtYfyDqS4zYYYYdNHMA-TzEZbbLJdNNK31SbMdFSUgoRwPxlGYM8wpEkOzFmp77KfxMLB/s1600/35477171_13cb52115c_n.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizYKzzN7JaX8usZVDOLWseIE0wOC6i8sG6clFVJ3pJExURwKFgWwY8IfdMkEQrQjboQ44nMxGvtYfyDqS4zYYYYdNHMA-TzEZbbLJdNNK31SbMdFSUgoRwPxlGYM8wpEkOzFmp77KfxMLB/s1600/35477171_13cb52115c_n.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br style=&quot;text-align: start;&quot; /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;&lt;b&gt;random (score = 0.92311)&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;&lt;b&gt;hotdogs (score = 0.07689)&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;This is a sunflower not a hotdog! Yet the classifier is only rather confident rather than completely confident that it is a notdog. This can be attributed to the limited number of training examples that were used in training the final layer before classification.&lt;/span&gt;&lt;br /&gt;
What about if we try to trick it - with a HOTDOG CAR!?&lt;/div&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;
&lt;/span&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: justify;&quot;&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;text-align: start;&quot;&gt;
&lt;/span&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5L4vLsSA99ObQArzgCeqs_hTekuUG8_oyva9BJx8cssl5CVhkEtf5zoxP25jHInzKiJiGqaqFhlcdfnNyBtqdT_1dpNvlSX0PM27iNoRPv5t4ufIEpi7rQRBhkTtn9MvjgaPyBHGEGNy_/s1600/hotdogcar.jpg&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5L4vLsSA99ObQArzgCeqs_hTekuUG8_oyva9BJx8cssl5CVhkEtf5zoxP25jHInzKiJiGqaqFhlcdfnNyBtqdT_1dpNvlSX0PM27iNoRPv5t4ufIEpi7rQRBhkTtn9MvjgaPyBHGEGNy_/s320/hotdogcar.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;&lt;br /&gt;random (score = 0.70404)&lt;br /&gt;hotdogs (score = 0.29596)&lt;/b&gt;&lt;br /&gt;
Not too bad at all, obviously the shape is similar to that of a hot dog but the chassis, wheels and other car-like features offer enough difference for our CNN to make the distinction.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;p2&quot;&gt;
&lt;h3&gt;
What&#39;s next?&lt;/h3&gt;
&lt;div&gt;
I haven&#39;t decided if I&#39;ll build some CNNs or have a crack at an LSTM implementation next - both will be using Tensorflow but I&#39;ve got some ideas I want to play around with first which will shape which direction I head in.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
References&lt;/h3&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;[1]&amp;nbsp;Szegedy, C. et al. 2014.&amp;nbsp;&lt;em style=&quot;box-sizing: inherit; line-height: inherit;&quot;&gt;Going deeper with convolutions,&lt;/em&gt;&amp;nbsp;&lt;u style=&quot;box-sizing: inherit;&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1409.4842.pdf&quot; style=&quot;box-sizing: inherit; cursor: pointer; line-height: inherit; text-decoration-line: none;&quot;&gt;https://arxiv.org/pdf/1409.4842.pdf&lt;/a&gt;&lt;/u&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;[2]&amp;nbsp;Szegedy, C. et al. 2015.&amp;nbsp;&lt;em style=&quot;box-sizing: inherit; line-height: inherit;&quot;&gt;Rethinking the Inception Architecture for Computer Vision,&lt;/em&gt;&amp;nbsp;&lt;u style=&quot;box-sizing: inherit;&quot;&gt;&lt;a href=&quot;https://arxiv.org/pdf/1512.00567.pdf&quot; style=&quot;box-sizing: inherit; cursor: pointer; line-height: inherit; text-decoration-line: none;&quot;&gt;https://arxiv.org/pdf/1512.00567.pdf&lt;/a&gt;&lt;/u&gt;.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;&lt;span style=&quot;background-color: white; font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;[3]&amp;nbsp;Donahue, J. et al. 2013.&amp;nbsp;&lt;em style=&quot;box-sizing: inherit; line-height: inherit;&quot;&gt;DeCAF: A Deep Convolutional Activation Feature for Generic Visual Recognition,&amp;nbsp;&lt;/em&gt;&amp;nbsp;&lt;u style=&quot;box-sizing: inherit;&quot;&gt;&lt;a href=&quot;https://arxiv.org/abs/1310.1531&quot; style=&quot;box-sizing: inherit; cursor: pointer; line-height: inherit; text-decoration-line: none;&quot;&gt;https://arxiv.org/abs/1310.1531&lt;/a&gt;&lt;/u&gt;.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;times&amp;quot; , &amp;quot;times new roman&amp;quot; , serif;&quot;&gt;[4]&amp;nbsp;&lt;a href=&quot;https://github.com/Fazelesswhite/Hotdog-Classification&quot;&gt;https://github.com/Fazelesswhite/Hotdog-Classification&lt;/a&gt;&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;style type=&quot;text/css&quot;&gt;
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo}
span.s1 {font-variant-ligatures: no-common-ligatures}
&lt;/style&gt;&lt;style type=&quot;text/css&quot;&gt;
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo}
span.s1 {font-variant-ligatures: no-common-ligatures}
&lt;/style&gt;&lt;style type=&quot;text/css&quot;&gt;
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo}
span.s1 {font-variant-ligatures: no-common-ligatures}
&lt;/style&gt;&lt;br /&gt;
&lt;style type=&quot;text/css&quot;&gt;
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo}
span.s1 {font-variant-ligatures: no-common-ligatures}
&lt;/style&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/3916508403818902508/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/06/transfer-learning-and-hotdog.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/3916508403818902508'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/3916508403818902508'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/06/transfer-learning-and-hotdog.html' title='Transfer learning and hotdog classification!'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgobkkGou6jGkkSktRVUjcD9OqZ65zLqdJMdg9aMATmrg30ZRdJWyRrU9kbhfNVSdItbmLrhZS9oGuyy_H7qTwPTmgGjXzwO7deuLzBwbq-_Sng8Zgy1EoFWfnMLIfKyK83gLdlDe6cOtQE/s72-c/inception.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-1717186798918110580</id><published>2017-03-31T16:16:00.000-07:00</published><updated>2017-03-31T16:16:43.972-07:00</updated><title type='text'>word2vec and word embeddings</title><content type='html'>&lt;h3&gt;
Where to now?&lt;/h3&gt;
&lt;div&gt;
Now that we&#39;ve got the basics of neural networks down pat, this opens up a world of related techniques that can build on this knowledge. I thought to myself that I&#39;d get stuck into some Natural Language Processing (NLP) with a view to eventually implement some sort of Recurrent Neural Network using TensorFlow.&lt;br /&gt;
&lt;br /&gt;
The wonderful folks at Stanford have all the lecture notes and assignments up online at&amp;nbsp;&lt;a href=&quot;http://web.stanford.edu/class/cs224n/syllabus.html&quot;&gt;http://web.stanford.edu/class/cs224n/syllabus.html&lt;/a&gt;&amp;nbsp;which is a fantastic resource.&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Anyway before we can even begin to think of the applications, we must understand how to represent our text for input into any machine learning algorithm.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
One-hot encoding&lt;/h3&gt;
&lt;div&gt;
Naively, we may think to take our entire vocabulary (i.e all words in the training set - size $V$) and make a huge vector, with each entry in the vector corresponding to a word in our vocabulary. Thus each word is represented by a $V \times 1$ vector with exactly one entry equal to $1$ and all other entries $0$. For example, a word $x_i$ would be represented as&lt;/div&gt;
&lt;div&gt;
$$ x_i = \left[ \begin{array}{c} 0 \\ \vdots \\ 1 \\ \vdots \\ 0 \end{array} \right]$$This is called one-hot encoding. The representation seems simple enough, but it has one problem - there is no natural way to embed the contextual similarity of words. Imagine we had three words; $x_1$ = dog, $x_2$ = cat and $x_3$ = pencil. Intuitively, if you were asked which two words were &quot;similar&quot;, you would say in a given context, $x_1$ and $x_2$ are similar, whilst $x_3$ shares less similarity with $x_1$ or $x_2$. Now supposed our three words have the following one-hot encoded representation $$ x_1 = \left[\begin{array}{c} \vdots &amp;nbsp;\\ 0 \\ \vdots \\ 1 \\ \vdots \\ 0 &amp;nbsp;\\ \vdots\end{array} \right], x_2 = \left[ \begin{array}{c} \vdots &amp;nbsp;\\ 1 \\ \vdots \\ 0 \\ \vdots \\ 0 \\\vdots \end{array} \right], x_3 = \left[ \begin{array}{c} \vdots &amp;nbsp;\\ 0 \\ \vdots \\ 0 \\ \vdots \\ 1 \\\vdots \end{array} \right]$$ We could hope that the dot product between vectors would give us a notion of similarity, but each of the $w_i$ are orthogonal, that is $x_i \cdot x_j = 0 \hspace{.1in} \forall i \neq j$ This representation also isn&#39;t all that great given that our vocabulary could be of the order of hundreds of millions of words, which would result in humongous one-hot encoded vector representations in which almost all (except for one) entry is a 0. This called a &lt;i&gt;sparse &lt;/i&gt;representation for obvious reasons. We&#39;ll now have a look at some more computationally efficient (and more accurate!) &lt;i&gt;dense&lt;/i&gt;&amp;nbsp;word representations.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Efficient Estimation of Word Representations in Vector Space&lt;/h3&gt;
&lt;div&gt;
In 2013, Mikolov et al. presented &lt;a href=&quot;https://arxiv.org/pdf/1301.3781.pdf&quot;&gt;Efficient Estimation of Word representations in Vector Space&lt;/a&gt;&amp;nbsp;which proposed two architectures:&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Continuous Bag of Words (CBOW) and&lt;/li&gt;
&lt;li&gt;Skip-gram model&lt;/li&gt;
&lt;/ul&gt;
with the aim of minimizing the computational complexity traditionally associated with NLP models. These representations somewhat surprisingly capture a lot of syntactic and semantic information in the structure of the vector space. That is, that similar words tend to be near one another (in terms of Euclidean distance) and that vector operations can be used to analogously relate pairs of words. There is the famous $\text{king} - \text{man} + \text{woman} \approx \text{queen}$ equation which is quite remarkable. In the one-hot view of the world, all of our vectors were orthogonal so dot products or any sort of vector addition/subtraction had no intuitive meaning or captured any relationship between words. See &lt;a href=&quot;https://lamyiowce.github.io/word2viz/&quot;&gt;here&lt;/a&gt; for a cool visualisation.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Continuous Bag of words&lt;/h3&gt;
&lt;div&gt;
Simply put, the CBOW aims to predict a word given an input context. For example, we would like a CBOW model to predict the word &lt;i&gt;fox&lt;/i&gt;&amp;nbsp;from an input context &quot;&lt;i&gt;The quick brown...&lt;/i&gt;&quot;. To perform such a task, it was proposed to use a simple feedforward neural network (wait - we know all about those now!) &lt;i&gt;without&lt;/i&gt;&amp;nbsp;an activation function in each neuron in the hidden layer. The idea is to train the NN on this classification task and then simply pick out the weight matrix in the hidden layer - this will be our &lt;i&gt;dense representation.&lt;/i&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h4&gt;
Architecture of CBOW&lt;/h4&gt;
&lt;div&gt;
The CBOW model looks at &lt;i&gt;m&lt;/i&gt;&amp;nbsp;words either side (or $C$ total as in the diagram below) of the target/center word $w_c$ in order to predict it . Below is an image the architecture of a CBOW model - notice that each input word is a one-hot encoded vector of dimension $V \times 1$ where $V$ is the size of our vocabulary. $W$ is a $N \times V$ matrix, where $N$ is the dimension of the representation of our input vectors $x_1, \dots, x_c$, where $x_{i}$ is the one hot encoded vector of the $i^{th}$ context word. We define $W x_{i} \equiv v_{i}$ which is a single column of $W$ due to the one hot encoding. Below is a visual representation of a CBOW model.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpSPalEwXny6hD1DXojy48rqLGmKCkRo3_D2-3btZVR60C_1idSnq-mrEITRaqahqZ3dyqHmJk4keHFk5KejTZ5jKMCr0z0b2b9FfbpKFP3F6jjv0WK9hHV3wzxKIHgH9AoVkBzuEm0K9n/s1600/cbow2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpSPalEwXny6hD1DXojy48rqLGmKCkRo3_D2-3btZVR60C_1idSnq-mrEITRaqahqZ3dyqHmJk4keHFk5KejTZ5jKMCr0z0b2b9FfbpKFP3F6jjv0WK9hHV3wzxKIHgH9AoVkBzuEm0K9n/s400/cbow2.png&quot; width=&quot;329&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;b&gt;Forward propagation:&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&amp;nbsp;We have $C$ one hot encoded input vectors which feed into the hidden layer via the weight matrix $W$.&lt;/li&gt;
&lt;li&gt;Since we have $C$ inputs acting on $W$, the resulting matrix $\bar{v}$ is computed from the average as follows: $$ \hat{v} = \frac{1}{C} W \left( x_{1} + x_{2} + \dots + x_{C} \right) = \frac{1}{C} \left ( v_{1} + v_{2} + \dots + v_{C} \right)$$&lt;/li&gt;
&lt;li&gt;We actually don&#39;t have an activation function here (it is the identity mapping). So from the hidden layer to the output layer, we propagate forward via weight matrix $W&#39;$ which is $V \times N$&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Define the $j^{th}$ row of $W&#39;$ as $u^T_{j}$.&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Thus the $j^{th}$ entry of the unnormalised output (a $V \times 1$ vector) is simply $z_j = u^{T}_{j} \hat{v}$&lt;/li&gt;
&lt;li&gt;Finally, we apply our old friend the softmax function to obtain our output: $$\hat{y}_j = \frac{e^{z_j}}{\sum_{k=1}^{V} e^{z_k}}$$&lt;/li&gt;
&lt;li&gt;To measure the loss of our network, we&#39;ll use the cross entropy loss function, which we saw in the derivation of a &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2017/01/feedforward-artificial-neural-network.html&quot;&gt;feedforward neural network.&lt;/a&gt;&amp;nbsp;$$l = - \sum_{j=1}^{V} y_j \log(\hat{y}_j)$$&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;This is just the negative of the log likelihood $p \left( w_k | w_{I_1}, \dots , w_{I_C} \right)$ where $w_{I_j}$ represents the $j^{th}$ word of input context $I$.&lt;/li&gt;
&lt;li&gt;Thus we have $$l = - u^{T}_{c} \hat{v} + \log \left(\sum_{k=1}^V e^{ u^{T}_k \hat{v}} \right)$$&lt;/li&gt;
&lt;li&gt;where &lt;i&gt;c&lt;/i&gt;&amp;nbsp;is the index of the correct word - the one hot vector for the correct word as a $1$ at the $c^{th}$ position.&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;We now just need to optimise the loss function to recover our &lt;i&gt;input&lt;/i&gt;&amp;nbsp;representation $\hat{v}$ and the &lt;i&gt;output&lt;/i&gt;&amp;nbsp;representation $u^{T}_j$ for $j = 1, \dots, V$.&lt;/li&gt;
&lt;ul&gt;
&lt;/ul&gt;
&lt;/ul&gt;
Let&#39;s now take a look at how we optimise our loss function $L$ via gradient descent using backpropagation. We won&#39;t go through algebra, but it is exactly analogous to what we&#39;ve seen &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2017/01/feedforward-artificial-neural-network.html&quot;&gt;before&lt;/a&gt;. Now $$\frac{\partial J}{\partial u_j} = \left\{ \begin{array}{ll} (\hat{y}_j-1)\hat{v} &amp;amp; j = c \\ \hat{y}_j \hat{v} &amp;amp; \text{otherwise} \end{array} \right. $$ and $$\frac{\partial J}{\partial \hat{v}} = -u_c + \sum_{k=1}^{V} \hat{y}_k u_k$$&lt;br /&gt;
These define the update rules for stochastic gradient descent. Note the sum over $V$, the size of our vocabulary, which can contain potentially millions of tokens.&amp;nbsp; This isn&#39;t computationally efficient and will result in terrible performance if we have do do this when training the model. Suspend your disbelief for now and I&#39;ll cover some methods that people have come up with to tackle this problem in my next blogpost. We&#39;ll carry on for now and introduce the skip-gram model.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Skip-Gram&lt;/h3&gt;
&lt;div&gt;
The skip-gram does somewhat the opposite of the CBOW. A skip-gram model takes a single word (the &lt;i&gt;center&lt;/i&gt;&amp;nbsp;word) as input and predicts surrounding words (context). It uses the same approach in that we&#39;ll train an ANN to perform the prediction task and we&#39;ll just pick up the weight matrices it learns as our dense representation of our words.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h4&gt;
Architecture of the Skip-Gram model&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
The Skip-Gram model takes an input (context) word $x_k$ and will predict the context from it. The input word is a single one-hot encoded vector. We denote the output by $C$ - &amp;nbsp;a collection of vectors ${\hat{y_1}, \dots, \hat{y_C}}$. Each $\hat{y_j}$ is a vector of probabilities for each word in the vocabulary occurring. Below is an image the architecture of a Skip-Gram model - notice that we have the same matrices $W$ and $W&#39;$ as in CBOW - these operate the same way on our single input as they did on $\hat{v}$ in CBOW.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn9l6-gx4AXGsCPkOF054sD74nzrcH38deqF64d2u8L0iDFn8wZx9ZPfMMUmOh5xLGJsIjtx0T0oJhksXsj7ELMWrROx0NpwpjhkC-JeAoIbYT5K2zdKbdPGo4tElGtVs-3GIAXWzIpnyK/s1600/skipgram.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn9l6-gx4AXGsCPkOF054sD74nzrcH38deqF64d2u8L0iDFn8wZx9ZPfMMUmOh5xLGJsIjtx0T0oJhksXsj7ELMWrROx0NpwpjhkC-JeAoIbYT5K2zdKbdPGo4tElGtVs-3GIAXWzIpnyK/s400/skipgram.PNG&quot; width=&quot;356&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;b&gt;Forward propagation:&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&amp;nbsp;We have a single one hot encoded input vector $x_k$ which feeds into the hidden layer via the weight matrix $W$. Define $W x_k \equiv v_c$ - this is also called the center word &lt;i&gt;input representation&lt;/i&gt;.&lt;/li&gt;
&lt;li&gt;Again, We actually don&#39;t have an activation function here (it is the identity mapping). So from the hidden layer to the output layer, we propagate forward via weight matrix $W&#39;$ which is $V \times N$&lt;/li&gt;
&lt;li&gt;Thus the $j^th$ element of the unnormalised output (a $V \times 1$ vector) is simply $z_j = u^{T}_j v_c$. $C$ copies of the output vector are output - one vector for each of the words in the context we are trying to predict.&lt;/li&gt;
&lt;li&gt;Again, we apply the softmax function to each of the $C$ output vectors (to obtain our output: $$\hat{y}_{i,j} = \frac{e^{z_j}}{\sum_{k=1}^{V} e^{z_k}} = &amp;nbsp;\frac{e^{u^{T}_j v_c}}{\sum_{k=1}^{V} e^{u^{T}_k v_c}}$$ where $i \in \{1, \dots , C\}$ indexes each of the output vectors.&lt;/li&gt;
&lt;li&gt;Note that since we used $C$ copies of the same output matrix for the prediction of each surrounding word, this amounts to a conditional independence assumption. That is the probability of each surrounding word occurring given the center word is independent of it&#39;s relative positioning to it.&lt;/li&gt;
&lt;li&gt;To measure the loss of our network, we&#39;ll again use the cross entropy loss function. However, now that there are $C$ copies of the output, we need to sum over them&amp;nbsp;$$l = - \sum_{j=1}^{V} \sum_{i=1}^{C}&amp;nbsp;&amp;nbsp;y_{i,j} \log(\hat{y}_{i,j}) $$ represents the index of the actual output word. For example if the actual output words for a center word &lt;i&gt;like&lt;/i&gt;&amp;nbsp;were &lt;i&gt;I &lt;/i&gt;and &lt;i&gt;ice-cream &lt;/i&gt;then there are two one hot encoded vectors $y_{1}, y_{2}$. Suppose &lt;i&gt;I &lt;/i&gt;has position $10,000$ in our vocabulary then $y_{1,10000}$ would be the only non zero entry of $y_{1}$. Similarly $y_{2,5000}$ would be the only non-zero entry of $y_{2}$ if &lt;i&gt;ice-cream&lt;/i&gt;&amp;nbsp;had position $5000$ in the vocabulary.&lt;/li&gt;
&lt;li&gt;This is just the negative of the log likelihood $p \left( w_{c-m},\dots, w_{c-1}, w_{c+1}, \dots , w_{c+m} | w_c \right)$ where $w_{j}$ where $(j \neq c)$ represents the $j^{th}$ word of surrounding window and $w_c$ is the center word. &amp;nbsp;We have introduced the index $m$ to index the words surrounding the center word. That is, the window of sized $C$ is symmetric about the center word $v_c$ such that there are $m$ words to the left and right of $v_c$.&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Thus we have $$l = - \sum_{j=0, j\neq m}^{2m} u^{T}_{c-m+j} v_c + 2m \log{\sum_{j=1}^{V} e^{u^{T}_j v_c }} $$&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;It&#39;s important to see that this loss function also suffers from the problem that we need to sum over our entire vocabulary $V$ at each parameter update step - which is computationally far too expensive and sometimes not even possible.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
Results&lt;/h4&gt;
&lt;div&gt;
There are some interesting remarks on the &lt;a href=&quot;https://code.google.com/archive/p/word2vec/&quot;&gt;word2vec Google Code page&lt;/a&gt;&amp;nbsp;regarding model selection (skip-gram vs CBOW) and hyper parameter selection. We won&#39;t get into the details until we&#39;ve covered the aforementioned sampling approaches for evaluating the models, but one point to note is&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;ul style=&quot;background-color: white; color: #444444; font-family: arial, sans-serif; font-size: 13px; margin: 10px 10px 10px 30px; padding: 0px;&quot;&gt;
&lt;li&gt;&lt;i&gt;architecture: skip-gram (slower, better for infrequent words) vs CBOW (fast)&lt;/i&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
We can understand the skip-gram performing better for infrequent words as the embedded words are not averaged as they are in CBOW (i.e when we define $\hat{v}$ in CBOW). The averaging process will dampen information from infrequently occurring words, contrasted with the skip-gram model where no such process takes place.&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
In a second paper published by Mikolov et al&amp;nbsp;&lt;a href=&quot;https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf&quot;&gt;Distributed Representations of Words and Phrasesand their Compositionality&lt;/a&gt;&amp;nbsp;they published the following results for a $1000$ dimensional skip-gram model. Taking the first two principal components, the following image was created&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2UwQMUnd1HlYee6SImkATR6X4TrKuiHfHTvf-aGkt8HoS_-z8g_DdQHghi6Dufx5GC3jhvTRDJNNGifuym6Uz74m-mT_sIk70ktK3ZcVnAahtr0JR1IzLZyRA2E0rXuWgaHCaxORcMUC-/s1600/Capture.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;301&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2UwQMUnd1HlYee6SImkATR6X4TrKuiHfHTvf-aGkt8HoS_-z8g_DdQHghi6Dufx5GC3jhvTRDJNNGifuym6Uz74m-mT_sIk70ktK3ZcVnAahtr0JR1IzLZyRA2E0rXuWgaHCaxORcMUC-/s400/Capture.PNG&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
The caption says it all really - note the geometric similarity of differences between capital cities and their countries! This was captured by the skip-gram model &lt;i&gt;without&lt;/i&gt;&amp;nbsp;providing any supervised information regarding these relationships. You can imagine simple vector addition holding approximately true in this 2D vector space: $$\text{Portugal} - \text{Lisbon} + \text{Beijing} \approx \text{China}$$&lt;/div&gt;
&lt;ul&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;h4&gt;
Conclusion&lt;/h4&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
In the next blog I&#39;ll look at some clever sampling based approaches that people have come up with to tackle the problem of having to normalise over the entire vocabulary $V$ in order to efficiently train the model. Then we can mess around with some text classification tasks, by using our word embeddings in our favourite ML techniques! The hope is that once we&#39;ve played around with some toy problems to get a strong handle of the implementations of word2vec, then I&#39;ll introduce Recurrent Neural Networks and then we can get into the nitty gritty of some super interesting deep learning architectures :)&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/1717186798918110580/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/03/word2vec-and-word-embeddings.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1717186798918110580'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1717186798918110580'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/03/word2vec-and-word-embeddings.html' title='word2vec and word embeddings'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpSPalEwXny6hD1DXojy48rqLGmKCkRo3_D2-3btZVR60C_1idSnq-mrEITRaqahqZ3dyqHmJk4keHFk5KejTZ5jKMCr0z0b2b9FfbpKFP3F6jjv0WK9hHV3wzxKIHgH9AoVkBzuEm0K9n/s72-c/cbow2.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-2299751441745092489</id><published>2017-02-24T02:38:00.000-08:00</published><updated>2017-02-24T02:38:01.670-08:00</updated><title type='text'>Optimisation routines</title><content type='html'>Now that we are able to train the Neural Network, let&#39;s take a look at how we can optimise the training as in reality we will be dealing with deep (many hidden neurons) networks which will potentially take days to train. I&#39;m going to take a step back and have a look at how we might generally attack a&amp;nbsp;&lt;i&gt;convex&lt;/i&gt;&amp;nbsp;optimisation problem. Convex optimisation problems are very well researched and understood area, so it makes sense to have a look at these first.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
The problem&lt;/h3&gt;
&lt;div&gt;
We are going to fit a simple logistic regression to the following data&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;http://cs229.stanford.edu/ps/ps1/logistic_x.txt&lt;/li&gt;
&lt;li&gt;http://cs229.stanford.edu/ps/ps1/logistic_y.txt&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
There are two predictors (columns) in the first file and 1 outcome ($ y = \pm 1$) in the second. Note that I&#39;ve borrowed these from the cs229 class that I&#39;m currently working through. Our task is to&amp;nbsp;&lt;i&gt;minimise&amp;nbsp;&lt;/i&gt;&amp;nbsp;the average empirical loss: $$ L(\theta) = \frac{1}{m} \sum_{i=1}^{m} \log (1 + \exp^{-y^{(i)} \theta^{T} x^{(i)}}) $$ where $y^{(i)}$ is the actual outcome for observation $x^{(i)}$. Note that $x^{(i)}$ is a vector containing the predictors for that observation.&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Is this a convex optimisation problem?&lt;/h3&gt;
&lt;div&gt;
It turns out that if we can show that the Hessian $H$ for this loss function satisfies $$z^{T} H z \ge 0$$ $ \forall z \in \mathbb{R}^{3}$ then $L(\theta) $ is a convex function (more generally if $H \in \mathbb{R}^{n \times n}$ then this result must hold true $\forall z \in \mathbb{R}^{n}$. Using the definition of $H$, we have $$ H_{pq} = \frac{\partial^2 L(\theta)}{\partial \theta_p \partial \theta_q}$$ The details of the calculation are quite straightforward, so I&#39;ll omit them but the result yields $$H_{pq} = \frac{1}{m} \sum_{i=1}^{m} \frac{1}{1 + \exp^{-\theta^T x^{(i)}}} \times \left( 1 - \frac{1}{1 + \exp^{-\theta^T x^{(i)}}} \right) \times x^{(i)}_p x^{(i)}_q $$ where the sum is over all of our training examples. We can write the last two terms as a matrix product (and subsequently drop the indices) as $x^{(i)} x^{(i)^{T}}$. Since the first two terms are $\in (0, 1]$ and $[0,1)$ respectively, then the product is $\in [0, 1]$, thus we can ignore this term when assessing if $z^T H z \ge 0 \hspace{.1in} \forall z$. Thus $$z^T H z \propto \sum_{i=1}^{m} z^T x^{(i)} x^{(i)^{T}} z = \sum_{i=1}^{m} (z^T x^{(i)})^2 \ge 0 \hspace{0.1in} \forall z$$ Hence $H$ is positive semidefinite which implies that $L(\theta) is a convex problem. This means it has a&lt;i&gt;&amp;nbsp;&lt;/i&gt;global optima, which makes our lives a lot easier. Since calculating the Hessian is rather easy in this setting, we can use&amp;nbsp;&lt;a href=&quot;https://en.wikipedia.org/wiki/Newton&#39;s_method_in_optimization&quot;&gt;Newton&#39;s method&lt;/a&gt;.&lt;/div&gt;
&lt;h3&gt;
Newton&#39;s method&lt;/h3&gt;
&lt;div&gt;
Newton&#39;s method utilises the Hessian and hence the curvature of the loss surface to find an optimal path to the minima. With this additional information, we can expect the algorithm to converge faster than gradient descent, which only uses first derivative information. The update rule is as follows $$ \theta \rightarrow \theta - H^{-1} \nabla_{\theta} L(\theta) $$&lt;/div&gt;
&lt;div&gt;
Let&#39;s see the performance of Newton&#39;s method vs Gradient descent:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkeKCx789Urj5Z72Oo_pvJID7L_5O4YXfd2CqY3zu9UAJCQxzT3fRqToJ7RJ00kytD8A4100unV-LWZk_TN8o-i5X3FWNH9rsLNWPVTSFFdnC8tX-191D-qjFr_SopFEr537oKdIHvWVuX/s1600/newtonvgraddescent.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;295&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkeKCx789Urj5Z72Oo_pvJID7L_5O4YXfd2CqY3zu9UAJCQxzT3fRqToJ7RJ00kytD8A4100unV-LWZk_TN8o-i5X3FWNH9rsLNWPVTSFFdnC8tX-191D-qjFr_SopFEr537oKdIHvWVuX/s400/newtonvgraddescent.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
I&#39;ve performed 20 iterations for both Newton&#39;s method and gradient descent - clearly Newton&#39;s method converges &lt;i&gt;a lot&lt;/i&gt;&amp;nbsp;faster than gradient descent. Looking at the update step, it is obvious that this method won&#39;t scale well with more parameters since each step requires the calculation of the matrix of first derivatives &lt;i&gt;and &lt;/i&gt;the Hessian. Furthermore, it&#39;s obvious that this method will fall apart if $H$ is singular. So in our toy example above which had a convex loss function, minimal parameters to estimate - Newton&#39;s method was king, but obviously in our neural network we couldn&#39;t apply such an algorithm. The beauty of backpropagation was that after a forward pass through the network, we had all of the first order derivatives we required in the update step. This fortune does not however extend to the second derivatives we would require to calculate $H$. It seems we&#39;re stuck with regular old batch gradient descent to train or neural network...or are we?&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3 style=&quot;clear: both; text-align: left;&quot;&gt;
Stochastic Gradient Descent (SGD)&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
Recall our update step for batch gradient descent: $$\theta_j \rightarrow \theta_j - \eta \frac{\partial}{\partial \theta_j}L(\theta)$$ where &amp;nbsp;$$ L(\theta) = \frac{1}{m} \sum_{i=1}^{m} \log (1 + \exp^{-y^{(i)} \theta^{T} x^{(i)}}) $$$L(\theta)$ is a function of all&lt;i&gt;&amp;nbsp;m&lt;/i&gt;&amp;nbsp;training examples. That is, for a single update to parameter $\theta_j$ we need to use &lt;i&gt;all&lt;/i&gt;&amp;nbsp;of our training data. What if we could calculate our loss on a subset of the training data? The hope is that this subset is &quot;representative enough&quot; of the entire dataset such that resulting update to $\theta_j$ is generally in the same direction to that of the update calculated on the entire dataset. This is the essence of Stochastic Gradient Descent.&lt;br /&gt;
&lt;br /&gt;
Consider the fact when the training dataset has several hundred million rows, we may not even be able to fit all the data in memory to perform a batch gradient descent!&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
I&#39;ll define the following terms commonly found when talking about SGD&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Epoch - once every datapoint in the training set has been used, &lt;i&gt;one epoch&lt;/i&gt;&amp;nbsp;has occurred.&lt;/li&gt;
&lt;li&gt;Mini batch - the subset of training data that is used in the parameter update&lt;/li&gt;
&lt;li&gt;Batch size - the size of the mini batch&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
So per epoch, we will be able to update the parameters $\frac{N}{\text{batch size}}$ times. Compare this to batch gradient descent which by definition, the parameters are updated once per epoch.&lt;/div&gt;
&lt;div&gt;
The pseudocode is as follows&lt;/div&gt;
&lt;div&gt;
&lt;code class=&quot;prettify&quot;&gt;for epoch in num_epochs:&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;&amp;nbsp; &amp;nbsp; shuffle(data)&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;&amp;nbsp; &amp;nbsp; for mini_batch in data:&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; evaluate derivative of loss on mini_batch&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/code&gt;&lt;span style=&quot;font-family: monospace;&quot;&gt;update parameters&lt;/span&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;&lt;br /&gt;&lt;/code&gt;
Since we are taking a subset of our training data to update our parameters, the results may be volatile as each subset may contain slightly different information about our loss surface. This is slightly troublesome as we approach the optima, as in SGD the path of optimisation will tend to oscillate around the minimum we seek. In order to remedy this, we use a &lt;i&gt;learning rate schedule&lt;/i&gt;&amp;nbsp;which is simply a scaling (generally based on heuristics) of our learning rate at each iteration. The hope is that by the time the algorithm is near the minimum, the learning rate has been scaled down such that the successive parameter updates are relatively stable from this point forward. This process is also called &lt;i&gt;annealing&lt;/i&gt;&amp;nbsp;the learning rate. The trick is getting the balance between timing the schedule such that the learning rate is small enough when the algorithm is near the minimum - if you are too aggressive with the schedule, the learning rate will become too small too soon and you won&#39;t get near the minimum as the update to the parameters will tend to zero.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s have a look at the performance of SGD vs batch gradient descent on our &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2017/01/feedforward-artificial-neural-network_12.html&quot;&gt;neural network&lt;/a&gt;. If implemented SGD on the aforementioned neural network and have run the make moons dataset with 100000 data points and 10 neurons in the hidden layer. See below for a plot of the loss vs. epoch for both SGD and batch gradient descent.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3JTVSgzkYf0BsFzh5eIic973DhjrqAwniGm6K2cE_MRjSRPgvN7uwBGtraafKUTjMiGMgFpRj9Ozbfbs2syPsT-jaHPJn7-Kr8HmdZisTjMvq8Y02PAgjE9CZq-51Dke2K6tfRNQNsGjO/s1600/batch_v_sgd_LOSS.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;285&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3JTVSgzkYf0BsFzh5eIic973DhjrqAwniGm6K2cE_MRjSRPgvN7uwBGtraafKUTjMiGMgFpRj9Ozbfbs2syPsT-jaHPJn7-Kr8HmdZisTjMvq8Y02PAgjE9CZq-51Dke2K6tfRNQNsGjO/s400/batch_v_sgd_LOSS.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Batch gradient descent:&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Epochs: 200 (i.e 200 updates to the parameters, each based on the full training set)&lt;/li&gt;
&lt;li&gt;Execution time: 17s&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
SGD:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Epochs: 1&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Mini batch size: 500 (i.e 200 updates to the parameters, each based on mini batch of size 500)&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Execution time: 6s&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
We can see that SGD actually outperforms batch gradient descent here and takes about a third of the time to run! I haven&#39;t actually applied any learning rate schedule here, you can see an egregious spike in the loss from SGD at around the $160^{th}$ epoch. See what happens below when I simply set $\eta \rightarrow \frac{\eta}{10}$ at the $150^{th}$ epoch:&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMe7iDTwi-qRakTnvmU9welkJxGmtUvf92YrPPmbRdA-9H9FHcg6m3aiy36pDwP6_WiMvHl37lcNnhzSsSMLdYpAX6hcdldQM7m-JSKf7M0SHxkvDwR6sCaO69CUpz9e4uJpvDdekusvev/s1600/batch_V_sgd_NN_annealed.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;285&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMe7iDTwi-qRakTnvmU9welkJxGmtUvf92YrPPmbRdA-9H9FHcg6m3aiy36pDwP6_WiMvHl37lcNnhzSsSMLdYpAX6hcdldQM7m-JSKf7M0SHxkvDwR6sCaO69CUpz9e4uJpvDdekusvev/s400/batch_V_sgd_NN_annealed.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Notice that the aforementioned spike is now gone and the SGD results look very promising given the accuracy and performance (compared to batch gradient descent). In practice, batch gradient descent will never be used due to the memory constraints and the fact that the randomness of SGD can help the algorithm escape local minima that batch gradient descent would naturally get stuck in.&lt;br /&gt;
&lt;h3&gt;
Momentum&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
We can introduce the concept of &lt;i&gt;momentum&lt;/i&gt;&amp;nbsp;to our parameter updates. It is applied as follows:&lt;br /&gt;
Recall the usual update to our parameters is as follows $$\theta_j \rightarrow \theta_j - \eta \frac{\partial}{\partial \theta_j}L(\theta)$$ which we can write in two steps, define&lt;br /&gt;
$$\Delta \theta_j = \frac{\partial}{\partial \theta_j}L(\theta)$$ such that the update becomes $$\theta_j \rightarrow \theta_j - \eta \Delta \theta_j$$ We&#39;ll now modify our definition of $\Delta \theta_j$ as $$\Delta \theta_j = \gamma \Delta \theta_j - \eta \frac{\partial}{\partial \theta_j}L(\theta)$$ and our update is $$\theta_j \rightarrow \theta_j + \Delta \theta_j$$ What we&#39;ve done is influenced our current update of $\theta_j$ by the amount it was updated by in the previous step. Yes we&#39;ve introduced yet &lt;i&gt;another&lt;/i&gt;&amp;nbsp;hyperparameter, but the idea here is to give it some &quot;momentum&quot; such that the updates are influenced by previous updates and the optimsation continues towards the minimum. Consider the case when the loss surface is a long narrow ravine with steep walls - SGD will typically oscillate across the ravine as the update will point down the steep walls, the momentum term will help move the algorithm down the ravine towards to minimum we seek. See the effect of momentum on training our neural network below&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzOUyBG6s9D9KuXcSMXnz7hq2uEl7d2CnILuj2giSZn8BwsiNmZSDeMpwF76FcPvqVg3-sJgaBPJ3apaxts9NNSUHaAfnAO3I0Bus7urxwzdZbVfb1jb-6bdClEzYpaKgAYdvDu6p02rmF/s1600/batch_V_sgd_NN_momentum.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;285&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzOUyBG6s9D9KuXcSMXnz7hq2uEl7d2CnILuj2giSZn8BwsiNmZSDeMpwF76FcPvqVg3-sJgaBPJ3apaxts9NNSUHaAfnAO3I0Bus7urxwzdZbVfb1jb-6bdClEzYpaKgAYdvDu6p02rmF/s400/batch_V_sgd_NN_momentum.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
We see that momentum allows the algorithm to descend very quickly and hits the minimum loss around 40 epochs in - compared to ~140 in our previous iteration.&lt;br /&gt;
&lt;br /&gt;
Hopefully you&#39;ve now got a good grasp of batch gradient descent vs SGD and some of the subtleties and hyperparameters that need to be considered when training a model with SGD. For a more in depth exploration of various optimisation techniques, including some more advanced methods see &lt;a href=&quot;http://sebastianruder.com/optimizing-gradient-descent/index.html#momentum&quot;&gt;here&lt;/a&gt;. In production, we&#39;ll rely on the built in SGD routines which have been highly tuned for performance.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/2299751441745092489/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/02/optimisation-routines.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/2299751441745092489'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/2299751441745092489'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/02/optimisation-routines.html' title='Optimisation routines'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkeKCx789Urj5Z72Oo_pvJID7L_5O4YXfd2CqY3zu9UAJCQxzT3fRqToJ7RJ00kytD8A4100unV-LWZk_TN8o-i5X3FWNH9rsLNWPVTSFFdnC8tX-191D-qjFr_SopFEr537oKdIHvWVuX/s72-c/newtonvgraddescent.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-1482087110535948747</id><published>2017-01-27T13:39:00.002-08:00</published><updated>2017-01-27T13:39:59.534-08:00</updated><title type='text'>Feedforward Artificial Neural Network pt5: Additional analysis</title><content type='html'>Now that we&#39;ve finally implemented our ANN, let&#39;s have a play around some of the parameters to get an understanding of how they affect our network and its results.&lt;br /&gt;
The tricky part about training ANNs is that the loss function isn&#39;t necessarily convex, which means that we can&#39;t use our usual optimisation routines. The fact that the loss function isn&#39;t necessarily convex means that just because we find a local minimum, it doesn&#39;t mean it&#39;s the global minimum. Thus non convex problems may converge on different local minima depending on the parameters of the optimisation routine. We&#39;ll explore some of these parameters below.&lt;br /&gt;
&lt;h3&gt;
Learning Rate&lt;/h3&gt;
Recall how the learning rate $\eta$ enters our optimisation procedure via the weight updates in gradient descent; $$ w \rightarrow w - \eta \frac{\partial L}{\partial w}$$ It essentially controls the step size at each update. Recall we had some funny bumps in our loss function at certain iterations, let&#39;s take a closer look: I&#39;ve plotted the results of two different iterations of training the ANN below&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfBVz2vKGxuk1Vx6edheWzNknSafKat2ViUNWXI8JzYbUnLXibPChgeyd58Al0fNI_J2JpSPmm3xygR8rvTtAhdtEjXRhpNNcCEgTJbxRRSEl6is6HSa1LbHNLXYFY6O683B8Sq37BT9pQ/s1600/loss.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;281&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfBVz2vKGxuk1Vx6edheWzNknSafKat2ViUNWXI8JzYbUnLXibPChgeyd58Al0fNI_J2JpSPmm3xygR8rvTtAhdtEjXRhpNNcCEgTJbxRRSEl6is6HSa1LbHNLXYFY6O683B8Sq37BT9pQ/s400/loss.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
The two lines correspond to the total loss as a function of the number of iterations in our training of the ANN. The blue line has $\eta = 0.001$ and the green line has $\eta = 0.01$. You can see that the green line has those funny bumps we witnessed before - this is the training example with a larger learning rate. The spikes occur when the step size is too large and we overshoot the minimum. Notice that the blue line doesn&#39;t have these overshoots, however it takes more iterations to approach the minimum. If we take a step size which is &lt;i&gt;too large, &lt;/i&gt;then we consistently overshoot the minima - never converging on the minimum:&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHJkH2TqnH24sYJY84pnu97_2B7biWzVfE6YwXLbdYeHxdWKOb2nyfGL5tTVACQpg1bYcoIwsjxmWrjwQQ4QH8bcQ02mjK5xhzHNVtmIDs3zYOpKK_u4Z4Ff7d-SuKLiEqZcVrrCyoqUld/s1600/loss3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;282&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHJkH2TqnH24sYJY84pnu97_2B7biWzVfE6YwXLbdYeHxdWKOb2nyfGL5tTVACQpg1bYcoIwsjxmWrjwQQ4QH8bcQ02mjK5xhzHNVtmIDs3zYOpKK_u4Z4Ff7d-SuKLiEqZcVrrCyoqUld/s400/loss3.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
The key is finding a learning rate which will find the minimum within a reasonable timeframe. Although our selection ($\eta = 0.001$ vs $\eta = 0.01$) didn&#39;t make a huge difference in this case, consider an ANN with multiple hidden layers and thousands of neurons in each layer. This network may take hours (or days) to train depending on how we choose our learning rate.&lt;br /&gt;
Depending on the problem at hand, you may value accuracy more than efficiency or vice versa, this will dictate how you choose your learning rate, of which you will usually calculate using cross validation.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Regularisation / Weight Decay&lt;/h3&gt;
Say we have our initial loss function (the cross entropy Loss) $L_0$ and we add a &lt;i&gt;regularisation&lt;/i&gt;&amp;nbsp;term such that we now have $$L = L_0 + \frac{\lambda}{2n} \sum_{w} w^2$$ where the sum is over all weights. Now if $\lambda$ is large then the second term will dominate $L$ and the task of optimising the entire expression will be reduced to minimising $\sum_w w^2$. If $\lambda$ is small then the first term dominates and there are less restrictions place on $w$. This regularisation term controls $w$ by preventing it from becoming overly large and helps us from overfitting the model. If we want to use gradient descent to minimise this regularised loss function we have $$ \frac{\partial L}{\partial w} = \frac{\partial L_0}{\partial w} + \frac{\lambda}{n} \sum_w w$$ so our update at each iteration is $$ w \rightarrow w - \eta \frac{\partial L}{\partial w}$$ becomes $$ w \rightarrow w - \eta \frac{\partial L_0}{\partial w} - \frac{\eta \lambda}{n} w$$ $$\implies w \rightarrow \left(1 - \frac{\eta \lambda}{n} \right) w - \eta \frac{\partial L_0}{\partial w}$$ That is at each update, the weight $w$ is rescaled by a factor of $\left( 1 - \frac{\eta \lambda}{n} \right)$ at each iteration; this is referred to as &lt;i&gt;weight decay&lt;/i&gt;&amp;nbsp;and as mentioned before, limits the magnitude of $w$.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Weight initialisation&lt;/h3&gt;
In this section we&#39;ll take a look at why we chose to intialise our values as we did (from a normal distribution with specific parameters). Recall the definition of the weight update from our gradient descent algorithm $$ w \rightarrow w - \eta \frac{\partial L}{\partial w}$$, if the second term in this expression is small or zero, then there is effectively no (or very little) weight update to $w$. This causes our training to slow down incredibly, such that after each iteration our weight $w$ is only changing ever so slightly; obviously we would like to avoid this situation at the start of the procedure. Recall the backpropagation rules for $W^{(1)}$:&lt;br /&gt;
&lt;br /&gt;
&lt;li&gt;$\delta^{(1)} = (1-\tanh^{2}(Z^{(1)}) \odot \delta^{(2)}{W^{(2)}}^T$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial W^{(1)}} = {x}^T \delta^{(1)}$&lt;/li&gt;
&lt;br /&gt;
&lt;div&gt;
we see that $(1-\tanh^{2}(Z^{(1)})$ term enters the equation (more generally, this will be the derivative of the activation function). So we have our update to the weight $w$ as $$w \rightarrow w - \eta (1-\tanh^{2}(Z^{(1)})) \odot {x}^T &amp;nbsp;\delta^{(2)}{W^{(2)}}^T$$ That is the amount we update $w$ by is proportional to the derivative of our activation function. Thus we want to avoid initialising our weights in a region where this derivative is close to zero. Below is a plot of the function&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBavtGcb_jVNctP30bJCoOWCaGmXDgXYH_r-P_vjM-P03fxbwJMwJsN4LRATX1yfy6hpQEr7EShC2NCydLHHkCNQqUQ4Wc_CfL2wV9JMnUleiUs98PLttbhzdjOEEvjodKMtZ-OIyx4oJ1/s1600/tanh.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;280&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBavtGcb_jVNctP30bJCoOWCaGmXDgXYH_r-P_vjM-P03fxbwJMwJsN4LRATX1yfy6hpQEr7EShC2NCydLHHkCNQqUQ4Wc_CfL2wV9JMnUleiUs98PLttbhzdjOEEvjodKMtZ-OIyx4oJ1/s400/tanh.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
We can see that this activation function has its derivative approach zero at both extremes: as $x \rightarrow \infty$ and as $x \rightarrow -\infty$. Let&#39;s think about a more general ANN for a moment - suppose we have an ANN with 1000 inputs and a single training example where each input is equal to $1$. We have as usual $$Z^{(1)} = x W^{(1)} +b^{(1)}$$ If we have intialised each entry $W^{(1)}_{ij}$ and $b^{(1)}_j$ as selected from a standard normal distribution (iid), then each entry $Z^{(1)}_{i}$ will be the sum of 1001 iid standard normal variables. Then since the sum of $N$ standard normal variables will have mean $0$ and standard deviation $\sqrt{1001}$ i.e a very wide distribution with a relatively high probability of giving a large negative or positive result (this almost looks like a uniform distribution), the derivative of the activation function will be very close to zero! This isn&#39;t what we want.&lt;/div&gt;
&lt;div&gt;
What about if we initialise with a random normal with mean $0$ and standard deviation $\frac{1}{\sqrt{1000}}$? Now we know that the variance of a sum of iid random normal variances is the sum of the variances so we now have each entry in $Z^{(1)}_{ij}$ has mean $0$ and standard deviation $$\sigma = \sqrt{\frac{1000}{1000}+1} = \sqrt{2}$$ which is a lot narrower than our distribution before - there is a lot smaller chance intialising at values where the derivative of the activation function is close to $0$. Below is a comparison of the resulting initialisation distributions from the toy example - the green line is the resulting distribution for the refined initialisation, where the red line results from initialisation by standard normal variables.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0ZDBo1Ca-lqHEdVa1D_-qnLVRBTiPBKercfKHx0PbJy62ZCLTbCsz9pdnlqvavC5xd0H46XYromxDlSXPnsX_C0r6fvXAkv7rB1I0EaVp5O_WCKXIGlfNFoyxTzYl3n63wfRYgOItAxcc/s1600/initdists.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;283&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0ZDBo1Ca-lqHEdVa1D_-qnLVRBTiPBKercfKHx0PbJy62ZCLTbCsz9pdnlqvavC5xd0H46XYromxDlSXPnsX_C0r6fvXAkv7rB1I0EaVp5O_WCKXIGlfNFoyxTzYl3n63wfRYgOItAxcc/s400/initdists.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
More generally for a given network we will initialise from a Gaussian distribution with mean $0$ and standard deviation $\frac{1}{\sqrt{N_{in}}}$ where $N_{in}$ is the number of inputs into the neural network.&lt;br /&gt;
Next time we&#39;ll have a look at optimising our network using stochastic gradient descent and maybe play around with some different datasets.&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/1482087110535948747/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/01/feedforward-artificial-neural-network_27.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1482087110535948747'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1482087110535948747'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/01/feedforward-artificial-neural-network_27.html' title='Feedforward Artificial Neural Network pt5: Additional analysis'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfBVz2vKGxuk1Vx6edheWzNknSafKat2ViUNWXI8JzYbUnLXibPChgeyd58Al0fNI_J2JpSPmm3xygR8rvTtAhdtEjXRhpNNcCEgTJbxRRSEl6is6HSa1LbHNLXYFY6O683B8Sq37BT9pQ/s72-c/loss.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-9119604523160243591</id><published>2017-01-12T01:04:00.000-08:00</published><updated>2017-02-13T02:45:56.813-08:00</updated><title type='text'>Feedforward Artificial Neural Network pt4: Implementation!</title><content type='html'>So if you&#39;ve survived this far, it&#39;s all worth it! We&#39;ve done &lt;i&gt;all&lt;/i&gt;&amp;nbsp;the groundwork required to code up our ANN to classify our toy example (&lt;i&gt;make moons&lt;/i&gt;&amp;nbsp;dataset kindly provided by sklearn).&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
Recap&lt;/h3&gt;
&lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2016/11/back-again-artificial-neural-networks.html&quot;&gt;Recall&lt;/a&gt; that a motivation for exploring ANN&#39;s was that our standard Logistic Regression classification technique could only ever give us a &lt;i&gt;linear&lt;/i&gt;&amp;nbsp;separating boundary:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsjYU3bfQxr-qn-IA9zYvhl1gZ3onYN0oOHYKVuu1jVTSvCIZtSRgJFy7Pz6rQAkkVI0bISbKXWnCRwpvrVNP-GYhcRE4eQyV_P21XDXSI8F_4KpRc0yjJ0Bg5N9tRa23MSOjlC5UI2f6k/s1600/LogReg_boundary.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;309&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsjYU3bfQxr-qn-IA9zYvhl1gZ3onYN0oOHYKVuu1jVTSvCIZtSRgJFy7Pz6rQAkkVI0bISbKXWnCRwpvrVNP-GYhcRE4eQyV_P21XDXSI8F_4KpRc0yjJ0Bg5N9tRa23MSOjlC5UI2f6k/s320/LogReg_boundary.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
ANN structure and Matrices&lt;/h3&gt;
&lt;div&gt;
In the &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2017/01/feedforward-artificial-neural-network.html&quot;&gt;last blog post&lt;/a&gt;&amp;nbsp;we derived general expressions for a single hidden layer feedforward ANN. The results were;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
For a network with the following features:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;2 inputs, $x_1$, $x_2$&lt;/li&gt;
&lt;li&gt;1 Hidden Layer with &lt;i&gt;n&lt;/i&gt; neurons - we will treat &lt;i&gt;n&lt;/i&gt;&amp;nbsp;as a parameter and see how it affects the output classification&lt;/li&gt;
&lt;li&gt;2 outputs, $\hat{y}_1$, $\hat{y}_2$&lt;/li&gt;
&lt;li&gt;Activation function: $\sigma(x) = \tanh(x)$&lt;/li&gt;
&lt;li&gt;Softmax output&lt;/li&gt;
&lt;li&gt;Loss function: Cross entropy loss $$L = - \frac{1}{N} \sum_{n \in N} \sum_{i \in C} y_{n,i} \ln{\hat{y}_{n,i}}$$&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4&gt;
Forward Propagation Summary&lt;/h4&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;$Z^{(1)} = xW^{(1)} + b^{(1)}$&lt;/li&gt;
&lt;li&gt;$a^{(1)} = \tanh(Z^{(1)})$&lt;/li&gt;
&lt;li&gt;$Z^{(2)} = a^{(1)}W^{(2)} + b^{(2)}$&lt;/li&gt;
&lt;li&gt;$\hat{y} \equiv a^{(2)} = softmax(Z^{(2)})$&lt;/li&gt;
&lt;/ul&gt;
Backpropagation Summary&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;$\delta^{(2)} = \hat{y} - y$&lt;/li&gt;
&lt;li&gt;$\delta^{(1)} = (1-\tanh^{2}(Z^{(1)}) \odot \delta^{(2)}{W^{(2)}}^T$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial W^{(2)}} = {a^{(1)}}^T \delta^{(2)}$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial b^{(2)}} = \sum_{rows} \delta^{(2)}$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial W^{(1)}} = {x}^T \delta^{(1)}$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial b^{(1)}} = \sum_{rows} \delta^{(1)}$&lt;/li&gt;
&lt;/ul&gt;
With the above, we have entirely defined how our ANN classifies training examples, how the weights and biases of the network affect the loss function and hence have our gradient descent update rule completely specified (up to the learning rate parameter).&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h3&gt;
Implementation in Python&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
Now instead of defining our network and neurons as a class, I&#39;ve decided to closely follow &lt;a href=&quot;http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/&quot;&gt;this page&lt;/a&gt;&amp;nbsp;(which actually inspired all of these ANN related posts) as it is more transparent and easier to grasp what is going on in the code. So without further delay, I present the code for an ANN with a single hidden layer of size 3:&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h3&gt;
Code&lt;/h3&gt;
&lt;/div&gt;
&lt;code class=&quot;prettify&quot;&gt;
import numpy as np
import sklearn.datasets&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;import pandas as pd
import matplotlib.pyplot as plt&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;np.random.seed(0)&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;X, y = sklearn.datasets.make_moons(200, noise=0.20)&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df = pd.DataFrame()&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df[&#39;x1&#39;] = X[:,0]&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df[&#39;x2&#39;] = X[:,1]&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df[&#39;z&#39;] = y&lt;/code&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;##define ANN which takes inputs X and y with parameters n_iter as number of iterations and learning_rating the rate used in gradient descent&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;def calculate(X ,y, num_hidden_neurons, n_iter=2000, learning_rate = 0.01, regularisation_rate = 0):&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; loss = [];&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; #initialise weights and biases&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; X_size = len(X)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; np.random.seed(0)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; W1 = np.random.randn(2, num_hidden_neurons) / np.sqrt(2)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; b1 = np.zeros((1, num_hidden_neurons))&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; W2 = np.random.randn(num_hidden_neurons, 2) / np.sqrt(num_hidden_neurons)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; b2 = np.zeros((1, 2))&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; model = {}&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; for i in xrange(n_iter):&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; #feedforward&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; Z1 = X.dot(W1)+b1&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; a1 = np.tanh(Z1)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; Z2 = a1.dot(W2)+b2&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; yhat = softmax(Z2)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; #backpropagation&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; d2 = yhat&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; d2[range(X_size),y] -= 1&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; d1 = (1-a1**2)*d2.dot(W2.T)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; dW2 = a1.T.dot(d2)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; db2 = np.sum(d2, axis=0, keepdims = True)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; dW1 = X.T.dot(d1)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; db1 = np.sum(d1, axis=0)&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; #regularisation&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; dW1 += regularisation_rate * W1 &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; dW2 += regularisation_rate * W2 &amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; #gradient descent &amp;nbsp; &amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; W1 = W1 - learning_rate * dW1&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; b1 = b1 - learning_rate * db1&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; W2 = W2 - learning_rate * dW2&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; b2 = b2 - learning_rate * db2&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; model = {&#39;W1&#39; : W1, &#39;b1&#39; : b1, &#39;W2&#39; : W2, &#39;b2&#39; : b2}&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; loss.append(predict(model,X,y,True))&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; return loss, model&lt;/span&gt;&lt;br /&gt;
&lt;h3&gt;
Comments&lt;/h3&gt;
&lt;div&gt;
The code is fairly self explanatory, but I&#39;ll walk through the steps&lt;/div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;Importing all the libraries we need&lt;/li&gt;
&lt;li&gt;Initialisation of the weights and biases (more on this later)&lt;/li&gt;
&lt;li&gt;Feedforward step - implemented via matrices exactly how we calculated them in the previous blog post&lt;/li&gt;
&lt;li&gt;Backpropagation step, again - implemented just how we derived them before. Note as the $b^{(i)}$ matrices consist of a single unique row each, we let python &lt;a href=&quot;https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html&quot;&gt;broadcast&lt;/a&gt;&amp;nbsp;them into the appropriate dimensions when it does the matrix addition in the calculation of $Z^{(1)}$ and $Z^{(2)}$.&lt;/li&gt;
&lt;li&gt;Gradient descent to alter the weights after each iteration in order to minimize the loss function.&lt;/li&gt;
&lt;li&gt;Regularisation rate - I haven&#39;t mentioned this before, I&#39;ve put it in there but set it to $0$ as to have no effect on the results. I will discuss this term later.&lt;/li&gt;
&lt;li&gt;Output a dictionary &lt;i&gt;Model&lt;/i&gt;&amp;nbsp;which contains our weight and bias matrices $W^{(1)}$, $b^{(1)}$, $W^{(2)}$, $b^{(2)}$.&lt;/li&gt;
&lt;li&gt;Note that I call a function (that&#39;s not defined here) called &lt;i&gt;predict&lt;/i&gt;&amp;nbsp;which will make predictions based on the input $X$ or return the cross entropy loss of a set of weights and biases when applied to $X$. The calculation of the cross entropy loss is the reason that $y$ is an input into the overall &lt;i&gt;calculate&lt;/i&gt;&amp;nbsp;function; if we were just calculating the weights and biases we would only require $X$ as an input. See code for &lt;i&gt;predict&lt;/i&gt;&amp;nbsp;at the bottom of this post.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
Results&lt;/h3&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;#function call - 3 neurons in the hidden layer&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;loss, model = calculate(X, y, 3)&lt;/span&gt;&lt;br /&gt;
The decision boundary is plotted below&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9-FTssu8YrG8lBPn_PqWhlofxS8-ehln0zXqVeQREz4Mk6JaMpjKwUWn4PiCivu74TKAm0tHWL62jx5L5UWsmT2OFamnH0NjQ8zyAN_oLumh5n1C4rpxjBykw571kbHOIGq3gjA-OLkYS/s1600/ANN_3Neurons_boundary.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;382&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9-FTssu8YrG8lBPn_PqWhlofxS8-ehln0zXqVeQREz4Mk6JaMpjKwUWn4PiCivu74TKAm0tHWL62jx5L5UWsmT2OFamnH0NjQ8zyAN_oLumh5n1C4rpxjBykw571kbHOIGq3gjA-OLkYS/s400/ANN_3Neurons_boundary.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Notice the non-linear decision boundary, and how well it captures the separation of data points! This gives us great hope that if the data generating process is distinctly non-linear then even though the standard GLM (i.e logistic regression) decision boundaries are crude, with an ANN we can potentially get a good fit!&lt;br /&gt;
The corresponding cross entropy loss as a function of iterations is also plotted below:&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDv6p4qtbU1QhxIJ-XfnC9GrUXCu8FziyM7axgQsrzm7oFrK28XdZS0JRnqzsGtbMYZQ5t6OSHGv8yMs_K5xNCn22a2RmzTBusztiW1b7mc9zw4vozqAN2VqI0a4x20QQc6deCGTa5E46s/s1600/ANN_3Neurons_Loss.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;218&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDv6p4qtbU1QhxIJ-XfnC9GrUXCu8FziyM7axgQsrzm7oFrK28XdZS0JRnqzsGtbMYZQ5t6OSHGv8yMs_K5xNCn22a2RmzTBusztiW1b7mc9zw4vozqAN2VqI0a4x20QQc6deCGTa5E46s/s320/ANN_3Neurons_Loss.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Ok, the overall trend of the loss looks alright, but what the hell are the spikes??? Stay tuned...&lt;br /&gt;
&lt;br /&gt;
What about if we have 10 neurons in the hidden layer?&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;#function call - 10 neurons in the hidden layer&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;loss, model = calculate(X, y, 10)&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdsY_rQDI3Z70M5tGSJPtS3it__LvlqATQwudnwDxcP8lZdgCvkOItt-OyX5W6fga4c-ewE8IFAhoD13TPc8n4YJE-twHDQK_TG5mC1t78hMYzpXq6JsrMpITbrc7w5WrnalGAl3NvK_Ps/s1600/ANN_10Neurons_Loss.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;382&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdsY_rQDI3Z70M5tGSJPtS3it__LvlqATQwudnwDxcP8lZdgCvkOItt-OyX5W6fga4c-ewE8IFAhoD13TPc8n4YJE-twHDQK_TG5mC1t78hMYzpXq6JsrMpITbrc7w5WrnalGAl3NvK_Ps/s400/ANN_10Neurons_Loss.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
and the corresponding loss:&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuc6Ug2WtYuOJCRsVV6A1UzBztVdwSQsYcKQ-LTKB9WPSpufKjPSHoGGd46VOvKqZidaHa19ok7sT_WoAl5f4NQud_NuzRN06CgDmrikb0sKMJpZiWtkH3uf3dOVbdHHjYfJL5WaVzN7Hw/s1600/ANN_10Neurons_Loss.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;221&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuc6Ug2WtYuOJCRsVV6A1UzBztVdwSQsYcKQ-LTKB9WPSpufKjPSHoGGd46VOvKqZidaHa19ok7sT_WoAl5f4NQud_NuzRN06CgDmrikb0sKMJpZiWtkH3uf3dOVbdHHjYfJL5WaVzN7Hw/s320/ANN_10Neurons_Loss.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Now the spikes are gone and the loss is lower than in the 3 neuron case. Whoa this is a &lt;i&gt;really&lt;/i&gt;&amp;nbsp;good fit, or is it? How good is too good? Obviously here, with the 10 neurons the ANN is not only fitting the overall general shape of the data, but its capturing the noise from the input too. Just looking at the data (ignoring the decision boundary) we can imagine a kind of smooth sinusoidal shape separating the classes (as in the 3 neuron case above). Notice the jagged edge near the long red dot amongst the blue dots at coordinates (-0.5, 0.7), you can see that the single red training example has &#39;pulled&#39; the decision boundary towards it. This is an ominous sign as the decision boundary is far too sensitive to a single data point, remember the idea is to capture the essence of the data generating process &lt;i&gt;excluding&lt;/i&gt;&amp;nbsp;noise.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
If we were to assess the performance of our ANN purely on the cross entropy loss - it would seem that the network with 10 neurons in the hidden layer outperforms the one with 3. However we &lt;i&gt;always&lt;/i&gt;&amp;nbsp;need to test the &lt;span style=&quot;background-color: white;&quot;&gt;ANN&lt;/span&gt;&amp;nbsp;on data it hasn&#39;t seen before - cross validation is usually employed to do so.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Well there it is, if you&#39;ve followed the posts from pt.1 of this series knowing the bare minimum about ANNs only armed with a pen, paper and a desire to learn, then you should be able to implement your own feedforward ANN from scratch! It was a laborious task (all the matrix algebra, etc) but I hope it provided insight into the construction and architecture of ANNs.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3 style=&quot;clear: both; text-align: left;&quot;&gt;
Useful functions&lt;/h3&gt;
&lt;div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;# Predict y_hat from input X or calculate loss&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;def predict(model, X, y, calc_loss = False):&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; W1, b1, W2, b2 = model[&#39;W1&#39;], model[&#39;b1&#39;], model[&#39;W2&#39;], model[&#39;b2&#39;]&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; # Forward propagation&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; Z1 = X.dot(W1) + b1&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; a1 = np.tanh(Z1)&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; Z2 = a1.dot(W2) + b2&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; probs = softmax(Z2)&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; if calc_loss:&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; loss = -np.log(probs[range(len(X)), y])&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; tot_loss = np.sum(loss)&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return 1./len(X) * tot_loss&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; return np.argmax(probs, axis=1) &amp;nbsp;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;#Compute softmax values for each sets of scores in x.&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;def softmax(x):&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&amp;nbsp; &amp;nbsp; return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims = True)&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
Given a model, the&amp;nbsp;&lt;i&gt;predict&lt;/i&gt; function returns a classification (0 or 1) for our input data X or the cross entropy loss. This is used to keep track of the loss at each iteration of the weight updates. Note that this is just for illustrative purposes, since it is an expensive calculation in reality, it isn&#39;t wise to call it &lt;i&gt;every&lt;/i&gt;&amp;nbsp;iteration - maybe every 100, or 1000 or so.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;i&gt;Softmax &lt;/i&gt;is used to calculate the softmax of the entries of a vector - used to calculate our $\hat{y}$.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3 style=&quot;clear: both; text-align: left;&quot;&gt;
Next steps&lt;/h3&gt;
&lt;div&gt;
Currently I&#39;m working my way through the &lt;a href=&quot;http://cs229.stanford.edu/&quot;&gt;CS229&lt;/a&gt;&amp;nbsp;Machine Learning course by Andrew Ng which takes up the majority of my spare time. It&#39;s a fantastic course which has accompanying lectures available on youtube and is a great introduction to ML techniques.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
However, in the future I am to continue with this implementation but tweak it to explore the following&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Why the weights were initialised in such a peculiar way (why not just set them all to 0?)&lt;/li&gt;
&lt;li&gt;Extending to more than 1 hidden layer&lt;/li&gt;
&lt;li&gt;How to prevent overfitting&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;Regularisation (I mentioned it above, but did not explain what/how/why)&lt;/li&gt;
&lt;li&gt;Drop out techniques&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Stochastic gradient descent&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;A variant of our &lt;i&gt;batch gradient descent&lt;/i&gt;&amp;nbsp;which is industry practise when training an ANN (due to massive datasets)&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Different applications - when I get around to it, I&#39;ll implement an ANN for the classic&amp;nbsp;MNIST handwritten digit recognition problem.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h3&gt;
&lt;span style=&quot;font-family: monospace;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;/div&gt;
&lt;ol&gt;
&lt;/ol&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/9119604523160243591/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/01/feedforward-artificial-neural-network_12.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/9119604523160243591'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/9119604523160243591'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/01/feedforward-artificial-neural-network_12.html' title='Feedforward Artificial Neural Network pt4: Implementation!'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsjYU3bfQxr-qn-IA9zYvhl1gZ3onYN0oOHYKVuu1jVTSvCIZtSRgJFy7Pz6rQAkkVI0bISbKXWnCRwpvrVNP-GYhcRE4eQyV_P21XDXSI8F_4KpRc0yjJ0Bg5N9tRa23MSOjlC5UI2f6k/s72-c/LogReg_boundary.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-6927706914469176965</id><published>2017-01-04T02:02:00.000-08:00</published><updated>2017-01-11T23:59:15.467-08:00</updated><title type='text'>Feedforward Artificial Neural Network pt3: Matrices!</title><content type='html'>So far we&#39;ve looked at the building blocks of an ANN - the different layers, weights, activation functions and error functions. We know have a decent understanding of what the objects are and how they relate, but so far we&#39;ve only looked at relatively small parts of the network in isolation for individual training samples. We&#39;ll look at implementing the aforementioned ideas using matrices, which will be very helpful when we build our full network and have hundreds (or thousands) of training samples. This is a very natural thing to do - if we can set up the propagation of our network and training samples through matrix multiplication then the computer can do the work in optimising the calculations. The other option is the old fashioned way of using for loops to iterate through each neuron and each training example in our network, this way is markedly slower and inefficient.&lt;br /&gt;
&lt;h3&gt;
Sample ANN - using matrices&lt;/h3&gt;
&lt;div&gt;
We&#39;ll use the below network to demonstrate the power of the matrix implementation. Note that we will do this step by step, so it can be rather laborious/repetitive but it&#39;s important to understand how each element of the matrix relates to the inputs and is propagated through the network.&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF5KTkSb7cnTwxizBaevCHW-JPOr5T8-6UI4HEhuYh4g_NzLlljlJBE7mrLx58eynnUtMNVYoVfFGoBPVT4NsZVD_OVNGcOJkmUHSik_G4DCh4-OiCeLpxKwqf5Ux3usiIE9jxpOFvJAjx/s1600/ANN.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;190&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF5KTkSb7cnTwxizBaevCHW-JPOr5T8-6UI4HEhuYh4g_NzLlljlJBE7mrLx58eynnUtMNVYoVfFGoBPVT4NsZVD_OVNGcOJkmUHSik_G4DCh4-OiCeLpxKwqf5Ux3usiIE9jxpOFvJAjx/s400/ANN.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
The network has the following features:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;2 inputs, $x_1$, $x_2$&lt;/li&gt;
&lt;li&gt;1 Hidden Layer with 3 neurons&lt;/li&gt;
&lt;li&gt;2 outputs, $\hat{y}_1$, $\hat{y}_2$&lt;/li&gt;
&lt;li&gt;Activation function: $\sigma(x) = \tanh(x)$&lt;/li&gt;
&lt;li&gt;Softmax output&lt;/li&gt;
&lt;li&gt;Loss function: Cross entropy loss $$L = - \frac{1}{N} \sum_{n \in N} \sum_{i \in C} y_{n,i} \ln{\hat{y}_{n,i}}$$&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
Inputs&lt;/h3&gt;
&lt;div&gt;
We define our input matrix based on two training samples: $$x = \left[ \begin{array}{cc} x_{11} &amp;amp; x_{12} \\ x_{21} &amp;amp; x_{22} \\ \end{array} \right]$$&amp;nbsp;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
where the matrix is defined such that $x_{ij}$ is the $j^{th}$ input of the $i^{th}$ training sample.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
Weights&lt;/h3&gt;
&lt;div&gt;
Now we define a matrix $W^{(1)}$ of weights for the neurons in the Hidden Layer;&lt;/div&gt;
&lt;div&gt;
$$W^{(1)} = \left[ \begin{array}{ccc} w_{11}^{(1)} w_{12}^{(1)} w_{13}^{(1)} \\ w_{21}^{(1)} w_{22}^{(1)} w_{23}^{(1)} \end{array} \right]$$ where $w_{ij}^{(1)}$ is the weight for the $i^{th}$ input in the $j^{th}$ neuron in the hidden layer. Thus each column of $W^{(1)}$ represents the weight each input receives from each neuron in the hidden layer.&lt;/div&gt;
&lt;h3&gt;
Bias&lt;/h3&gt;
&lt;div&gt;
We introduce the concept of &lt;i&gt;bias&lt;/i&gt;&amp;nbsp;in an activation function. The bias is a translation of the entire activation function and is implemented as the following $$\sigma(w \cdot x +b)$$ where $w$ is the weight, $x$ is the input into the particular neuron and $b$ is the bias. The bias adds flexibility to the activation function; we can achieve any output from any input.&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
For example consider an activation function &lt;i&gt;without &lt;/i&gt;bias $$\sigma(x) = \tanh(w \cdot x)$$ and say we want to achieve an output of $0.5$ when $x=0$. There is no such $w$ that will allow us to achieve this result, as $\tanh(0) = 0$. However if we introduce bias we have $$\sigma(x) = \tanh(w \cdot x + b)$$ we can set $b \approx 0.549$ to achieve the desired result. Now we introduce the bias matrix - the matrix of biases for the hidden layer $$b^{(1)} = \left[ \begin{array}{ccc} b_{11}^{(1)} b_{12}^{(1)} b_{13}^{(1)} \\ b_{21}^{(1)} b_{22}^{(1)} b_{23}^{(1)} \end{array} \right]$$ with the $b^{(1)}_{ij} = b^{(1)}_{kj}$ for all $k$ i.e $b^{(1)}$ has a single unique row; all other rows in the matrix are a copy of this one. This is just to ensure that the matrix multiplication works as intended.&lt;br /&gt;
&lt;h3&gt;
Forward Propagation&lt;/h3&gt;
&lt;/div&gt;
We&#39;ll now work our way through the network, starting at the input, traversing through the hidden layer and arriving at the output.&lt;br /&gt;
&lt;br /&gt;
Using the notation described in &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2016/12/feedforward-artificial-neural-network.html&quot;&gt;this&lt;/a&gt; previous blog post, we get our matrix $Z^{(1)}$ which contains the results of applying the weights and biases to our inputs. Thus $$Z^{(1)} = x W^{(1)}+b^{(1)}$$ is a $2 \times 3$ matrix with the following structure&lt;br /&gt;
$$Z^{(1)} = \left[ \begin{array}{ccc} x_{11}w_{11}^{(1)}+x_{12}w_{21}^{(1)}+b_{11}^{(1)} \hspace{.3in} \cdots \hspace{.3in} \cdots \\ x_{21}w_{11}^{(1)}+x_{22}w_{21}^{(1)}+b_{21}^{(1)} \hspace{.3in} \cdots \hspace{.3in} \cdots \end{array} \right]$$ where I&#39;ve only included the first column of the matrix. In matrix index notation we have $$Z_{ij}^{(1)} = \sum_{k} x_{ik} W^{(1)}_{kj} + b_{ij}^{(1)}$$We can interpret $Z_{ij}^{(1)}$ as the input the the $j^{th}$ hidden neuron receives from the $i^{th}$ test sample.&lt;br /&gt;
&lt;br /&gt;
Once at the hidden layer, the activation function is applied (elementwise) to $Z^{(1)}$ as $$a^{(1)} = \left[ \begin{array}{ccc} a_{11}^{(1)} a_{12}^{(1)} a_{13}^{(1)} &amp;nbsp;\\ a_{21}^{(1)} a_{22}^{(1)} a_{23}^{(1)} \end{array} \right] \equiv \tanh{Z^{(1)}} $$&lt;br /&gt;
&lt;br /&gt;
We now propagate these values through the hidden layer, applying the weights and biases resulting in a $2 \times 2$ matrix $Z^{(2)}$ defined as $$Z^{(2)} = a^{(1)}W^{(2)}+b^{(2)}$$ where $$W^{(2)} = \left[ \begin{array}{cc} w_{11}^{(2)} w_{12}^{(2)} \\ w_{21}^{(2)} w_{22}^{(2)} \\ w_{31}^{(2)} w_{32}^{(2)} \end{array} \right]$$ and $$b^{(2)} = \left[ \begin{array}{cc} b_{11}^{(1)} b_{12}^{(2)} \\ b_{21}^{(2)} b_{22}^{(2)} \end{array} \right]$$ Similarly to $b^{(1)}$, this matrix has a unique single row, with the rest of the rows of the matrix being exact copies. &amp;nbsp;Explicitly, $Z^{(2)}$ has the following entries&lt;br /&gt;
$$\left[ \begin{array}{cc} a_{11}^{(1)}w_{11}^{(2)}+a_{12}^{(1)}w_{21}^{(2)}+a_{13}^{(1)}w_{31}^{(2)}+b_{11}^{(2)} \hspace{.3in} a_{11}^{(1)}w_{12}^{(2)}+a_{12}^{(1)}w_{22}^{(2)}+a_{13}^{(1)}w_{23}^{(2)}+b_{12}^{(2)} \\ a_{21}^{(1)}w_{11}^{(2)}+a_{22}^{(1)}w_{21}^{(2)}+a_{23}^{(1)}w_{31}^{(2)}+b_{21}^{(2)} \hspace{.3in} a_{21}^{(1)}w_{12}^{(2)}+a_{22}^{(1)}w_{22}^{(2)}+a_{23}^{(1)}w_{23}^{(2)}+b_{22}^{(2)} \end{array} \right]$$ More compactly, we have $$Z_{ij}^{(2)} = \sum_{k} a^{(1)}_{ik} W^{(2)}_{kj} + b^{(2)}_{ij} $$ where $Z_{ij}^{(2)}$ can be considered the input to the $j^{th}$ output neuron from the $i^{th}$ training sample.&lt;br /&gt;
&lt;br /&gt;
Finally, applying the softmax function in the output neurons we end up with $$a^{(2)} = \text{softmax}(Z^{(2)}) \equiv \left[ \begin{array}{cc} \hat{y}_{11} \hspace{.15in} \hat{y}_{12} \\ \hat{y}_{21} \hspace{.15in} \hat{y}_{22} \end{array} \right]$$ where $a_{ij}^{(2)}$ is the output of the $j^{th}$ output neuron of the $i^{th}$ training sample. Hopefully the explicit matrix multiplication helps illuminate how the input values are propagated through the network and how their values are affected by the various weights in the input/hidden/output layers. Next we&#39;ll take an explicit look at backpropagation and establish similar matrix results which will allow us to train the network in a relatively efficient manner.&lt;br /&gt;
&lt;h3&gt;
Backpropagation&lt;/h3&gt;
&lt;div&gt;
In this section we&#39;ll derive the backpropagation rules for the network. Make sure you understand matrix index notation as we&#39;ll use it here to succinctly write the results.&lt;/div&gt;
&lt;div&gt;
Recall our definition $$\delta_j \equiv \frac{\partial L}{\partial z_j} = &amp;nbsp;\sigma &#39; (z_j) \sum_{k \in path(j)} \delta_k w_{j \rightarrow k}$$ We&#39;ll slightly alter our notation to make it easier to track all of the indices floating around $ \delta^{(j)} \equiv \delta_j$ Starting at our output neurons and using the result from the &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2016/12/derivative-of-cross-entropy-loss-with.html&quot;&gt;previous blog post&lt;/a&gt;&amp;nbsp;we have $$\delta^{(2)}_{ij} \equiv &amp;nbsp;\frac{\partial L}{\partial Z^{(2)}_{ij}} = \hat{y}_{ij} - y_{ij}$$ or in full matrix form&lt;br /&gt;
$$\left[ \begin{array}{cc} \hat{y}_{11}-y_{11} \hspace{.3in} \hat{y}_{12}-y_{12} \\ \hat{y}_{21}-y_{21} \hspace{.3in} \hat{y}_{22}-y_{22} \end{array} \right]$$ Now $$\delta^{(1)}_{ij} \equiv &amp;nbsp;\frac{\partial L}{\partial Z^{(1)}_{ij}}$$ using the chain rule we can decompose this into $$ \frac{\partial L}{\partial Z^{(1)}_{ij}} = \sum_{m,n,p,q} \frac{\partial L}{\partial{Z^{(2)}_{mn}}} \times \frac{\partial{Z^{(2)}_{mn}}}{\partial{a^{(1)}_{pq}}}\times \frac{\partial{a^{(1)}_{pq}}}{\partial {Z^{(1)}_{ij}}}$$ The first term is simply $\delta^{(2)}_{mn}$. For the second term, recall above $$Z^{(2)}_{mn} = \sum_{k} a^{(1)}_{mk} W^{(2)}_{kn} + b^{(2)}_{mn} $$ $$\implies \frac{\partial Z^{(1)}_{mn}}{\partial a^{(1)}_{pq}} = W^{(2)}_{qn}$$ where the sum over k has been collapsed since the derivative is only non-zero when $m=p$ and $k=q$. Now, the third term $$\frac{\partial a^{(1)}_{pq}}{\partial Z^{(1)}_{ij}} = \frac{\partial}{\partial Z^{(1)}_{ij}} \left( \tanh(Z^{(1)}_{pq}) \right) = 1 - \tanh^{2}(Z^{(1)}_{ij})$$ where the only non-zero elements of the above expression are when $p=i$ and $q=j$. Putting this all together we have $$\frac{\partial L}{\partial Z^{(1)}_{ij}} = \left( 1 - \tanh^{2}(Z^{(1)}_{ij}) \right)&amp;nbsp;&amp;nbsp;\sum_{n} \delta^{(2)}_{in} W^{(2)}_{jn} $$ note the sum is only over $n$ now, instead of $m, n, p, q$ make sure you understand why this is. We can now write this in full matrix form (as we will use in the implementation) as&lt;br /&gt;
$$\delta^{(1)} = \left( 1 - \tanh^{2}(Z^{(1)}) \right) \odot \delta^{(2)} {W^{(2)}}^T$$ where $\odot$ is the elemetwise multiplication of the matrices (Hadamard product) and $T$ indicates the transpose of the matrix.&lt;br /&gt;
Now we can use the above results for $\delta^{(1)}$ and $\delta^{(2)}$ to calculate how the loss function changes with respect to the weights - recall this is the value we use to alter our weights at each iteration in our gradient descent routine. Now $$\frac{\partial L}{\partial W^{(2)}_{ij}} = \sum_{p,q} \frac{\partial L}{\partial Z^{(2)}_{pq}} \times \frac{\partial Z^{(2)}_{pq}}{\partial W^{(2)}_{ij}}$$ The first term is simply $\delta^{(2)}_{pq}$ and the second term is $$\frac{\partial}{\partial W^{(2)}_{ij}} \left[ \sum_{k} a^{(1)}_{pk} W^{(2)}_{kq} + b^{(2)}_{pq} \right]$$ $\implies k=i$ and $q=j$ hence the sum collapses and the term evaluates to $a^{(1)}_{pi}$. Hence $$\frac{\partial L}{\partial W^{(2)}_{ij}} = \sum_{p} \delta^{(2)}_{pj} a^{(1)}_{pi}$$ or in matrix form, this is represented as $$ \frac{\partial L}{\partial W^{(2)}} = {a^{(1)}}^T \delta^{(2)}$$ Similarly $$\frac{\partial L}{ \partial b^{(2)}_{ij}} = \sum_{p,q} \frac{\partial L}{\partial Z^{(2)}_{pq}} \times \frac{\partial Z^{(2)}_{pq}}{\partial b^{(2)}_{ij}} $$ the second term forces $q=j$ resulting in $$\frac{\partial L}{ \partial b^{(2)}_{ij}} = \sum_p \delta^{(2)}_{pj}$$ i.e a sum over the rows of $\delta^{(2)}$ note the right hand side of the expression is indendent of $i$ this implies that every row in $\frac{\partial L}{ \partial b^{(2)}}$ is the same. Similar analysis yields $$\frac{\partial L}{\partial W^{(1)}_{ij}} = \sum_{p} \delta^{(1)}_{pj} x_{pi} $$ and $$\frac{\partial L}{\partial b^{(1)}_{ij}} = \sum_p \delta^{(1)}_{pj}$$&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;Recap&lt;/b&gt;&lt;/h3&gt;
Relax. Take a breath. The derivations are over (for now). I think going through all the derivations in detail at least once is paramount to understanding the inner workings of the neural network. Once you get your head around the notation, there actually isn&#39;t anything that fancy going on - just repeated applications of the chain rule. They key for me was attacking this problem via matrix index notation which illustrated exactly how values are propagated (backwards and forwards) in the network via matrix multiplication.&lt;br /&gt;
&lt;h4&gt;
Forward Propagation Summary&lt;/h4&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;$Z^{(1)} = xW^{(1)} + b^{(1)}$&lt;/li&gt;
&lt;li&gt;$a^{(1)} = \tanh(Z^{(1)})$&lt;/li&gt;
&lt;li&gt;$Z^{(2)} = a^{(1)}W^{(2)} + b^{(2)}$&lt;/li&gt;
&lt;li&gt;$\hat{y} \equiv a^{(2)} = softmax(Z^{(2)})$&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;h4&gt;
Backpropagation Summary&lt;/h4&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;li&gt;$\delta^{(2)} = \hat{y} - y$&lt;/li&gt;
&lt;li&gt;$\delta^{(1)} = (1-\tanh^{2}(Z^{(1)}) \odot \delta^{(2)}{W^{(2)}}^T$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial W^{(2)}} = {a^{(1)}}^T \delta^{(2)}$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial b^{(2)}} = \sum_{rows} \delta^{(2)}$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial W^{(1)}} = {x}^T \delta^{(1)}$&lt;/li&gt;
&lt;li&gt;$\frac{\partial L}{\partial b^{(1)}} = \sum_{rows} \delta^{(1)}$&lt;/li&gt;
Note that the $\frac{\partial L}{\partial W^{(i)}}$ and $\frac{\partial L}{\partial b^{(i)}}$ are &lt;b&gt;not&lt;/b&gt;&amp;nbsp;actually derivatives with respect to matrices, these are just labels for the matrices containing the derivatives with respect to the various weights and biases. The $\sum_rows \delta^{(i)}$ indicates that we sum over the rows of the matrix $\delta^{(i)}$ such that the matrices $$\frac{\partial L}{\partial b^{(i)}}$$ consist of a single unique row repeated $m$ times, where $n$ is the number of training examples.&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
With these matrices we are now in a position to &lt;i&gt;finally&lt;/i&gt;&amp;nbsp;implement our ANN to classify our dataset! The next blog will detail the implementation in python and the associated results.&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/6927706914469176965/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2017/01/feedforward-artificial-neural-network.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/6927706914469176965'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/6927706914469176965'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2017/01/feedforward-artificial-neural-network.html' title='Feedforward Artificial Neural Network pt3: Matrices!'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF5KTkSb7cnTwxizBaevCHW-JPOr5T8-6UI4HEhuYh4g_NzLlljlJBE7mrLx58eynnUtMNVYoVfFGoBPVT4NsZVD_OVNGcOJkmUHSik_G4DCh4-OiCeLpxKwqf5Ux3usiIE9jxpOFvJAjx/s72-c/ANN.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-3884072015403501383</id><published>2016-12-07T02:32:00.001-08:00</published><updated>2016-12-07T02:37:47.719-08:00</updated><title type='text'>Derivative of cross entropy loss with softmax</title><content type='html'>&lt;h2&gt;
Derivative of the softmax function&lt;/h2&gt;
&lt;div&gt;
I&#39;ve dedicated a separate post for the derivation of the derivative of the cross entropy loss function with softmax as the activation function in the output layer, which I&#39;ll reference in the future. It&#39;s nothing groundbreaking but sometimes it&#39;s nice to work through some of the results which are often quoted without derivation.&amp;nbsp;&lt;/div&gt;
&lt;h3&gt;
The softmax function&lt;/h3&gt;
&lt;div&gt;
The softmax function is often used as the activation function for neurons in the output layer of an ANN. We borrow the notation from a previous &lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2016/12/feedforward-artificial-neural-network.html&quot;&gt;blog post&lt;/a&gt;, where $\hat{y}$ is the output of a particular neuron in the output layer and $$z_o = \sum_{j \in input(o)} z_j w_{j \rightarrow o}$$ i.e. we sum over all paths $j$ which are an input into our output neuron $o$.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
It is defined as the following:&lt;/div&gt;
&lt;div&gt;
$$ \hat{y}_o = \frac{e^{z_o}}{\sum_k e^{z_k}}$$ where the sum is over the $k$ output neurons in the network. The softmax essentially takes an input $z_o \in \mathbb{R}$ and maps it to the interval $(0,1)$ such that the sum of all outputs is 1 - it gives us a probability distribution over our $k$ outputs (i.e. $k$ different classifications).&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;/div&gt;
&lt;h3&gt;
Cross entropy loss function&lt;/h3&gt;
&lt;div&gt;
Recalling the definition of the cross entropy loss function from a previous&amp;nbsp;&lt;a href=&quot;http://edgeofabandon.blogspot.com.au/2016/12/feedforward-artificial-neural-network.html&quot;&gt;blog post&lt;/a&gt;&amp;nbsp;we have&lt;/div&gt;
&lt;div&gt;
$$L = - \frac{1}{N} \sum_{n \in N} \sum_{i \in C} y_{n,i} \ln{\hat{y}_{n,i}}$$&lt;/div&gt;
&lt;div&gt;
where $N$ is the number of training examples and $C$ is the number of classifications (i.e 2 for binary classification, etc...). Let us assume $N = 1$ without loss of generality, thus&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
$$L = - \sum_{o} y_{o} \ln{\hat{y}_{o}}$$ where the sum is over the output neurons in our network (given that we have 1 output neuron for each class, the sum over $i \in C$ and $o$ are equivalent). Note that $y_o$ is the actual classification of our data, i.e. $y_o \in \{0,1\}$ and that if $y_o=1$ then all other $y_j =0$ where $ i \neq o$ see a description of &lt;a href=&quot;https://www.quora.com/What-is-one-hot-encoding-and-when-is-it-used-in-data-science&quot;&gt;one hot encoding&lt;/a&gt;. Now our object of interest is $$ \frac{ \partial L}{\partial z_i} = \frac{\partial L}{\partial \hat{y}_o} \times \frac{\partial \hat{y}_o}{\partial z_i}$$ Let&#39;s focus on the second term $\frac{\partial \hat{y}_o}{\partial z_i}$ for now and split it into two cases.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Case 1: $ i = o$&lt;/li&gt;
&lt;/ul&gt;
$$\frac{\partial \hat{y}_o}{\partial z_i} = \frac{\partial \hat{y}_o}{\partial z_o} = &amp;nbsp;\frac{\partial}{\partial z_o} \left( \frac{e^{z_o}}{\sum_k e^{z_k}} \right) = \frac{e^{z_o}}{\sum_k e^{z_k}} - e^{z_o} (\sum_k e^{z_k})^{-2}e^{z_o}$$&lt;/div&gt;
&lt;div&gt;
$$= \frac{e^{z_o}}{\sum_k e^{z_k}} \left ( 1 - \frac{e^{z_o}}{\sum_k e^{z_k}} \right) = \hat{y}_o (1 - \hat{y}_o)$$&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Case 2: $ i \neq o $&lt;/li&gt;
&lt;/ul&gt;
$$ \frac{\partial \hat{y}_i}{\partial z_i} = \frac{\partial}{\partial z_i} \left( \frac{e^{z_o}}{\sum_k e^{z_k}} \right) = -e^{z_o}(\sum_k e^{z_k})^{-2} e^{z_i}$$&lt;/div&gt;
&lt;div&gt;
$$= -\hat{y}_o \hat{y}_i$$ Now $$\frac{\partial L}{\partial \hat{y}_o} = - \sum_o \frac{1}{\hat{y}_o} y_o$$ Therefore $$ \frac{\partial L}{\partial z_i} = -\sum_o \frac{1}{\hat{y}_o} y_o &amp;nbsp;\times \frac{\partial \hat{y}_o}{\partial z_i}$$ Substituting in our above computations and splitting out the $i=o$ case from the sum we get&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
$$\frac{\partial L}{\partial z_i} = -\frac{1}{\hat{y}_i} y_i \times \hat{y}_i(1-\hat{y}_i) - \sum_{o \neq i} \frac{1}{\hat{y}_o} y_o \times (- \hat{y}_o \hat{y}_i)$$&lt;/div&gt;
&lt;div&gt;
$$ = -y_i(1-\hat{y}_i) + \sum_{o \neq i} y_o \hat{y}_i$$ $$= y_i \hat{y}_i -y_i + \sum_{o \neq i} y_o \hat{y}_i$$ Moving the first term inside the sum and summing over all $o$ we get&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
$$\frac{\partial L}{\partial z_i} = -y_i + \sum_{o} y_o \hat{y}_i$$ $$ = \hat{y}_i \sum_o y_o - y_i$$ But $\sum_o y_o$ is the sum over all the actual labels of our data which is one hot encoded (as mentioned above). Thus $y_o = 1$ for exactly one class and $0$ for all else - hence $\sum_o y_o = 1$. We &lt;i&gt;finally&lt;/i&gt;&amp;nbsp;arrive at a result we&#39;ll use in the future in constructing and implementing our ANN to classify the &lt;i&gt;make moons&lt;/i&gt;&amp;nbsp;dataset&lt;/div&gt;
&lt;div&gt;
$$ \frac{\partial L}{\partial z_i} &amp;nbsp;= \hat{y}_i - y_i$$&lt;/div&gt;
&lt;div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/3884072015403501383/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2016/12/derivative-of-cross-entropy-loss-with.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/3884072015403501383'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/3884072015403501383'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2016/12/derivative-of-cross-entropy-loss-with.html' title='Derivative of cross entropy loss with softmax'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-5313394170303213997</id><published>2016-12-05T01:50:00.001-08:00</published><updated>2016-12-14T02:07:53.275-08:00</updated><title type='text'>Feedforward Artificial Neural Network pt2</title><content type='html'>&lt;h2&gt;
Feedforward Artificial Neural Network pt2&lt;/h2&gt;
In the previous post, we briefly looked at the general structure of a Feedforward ANN and why such a construction should be useful. Now that we have a general handle of the idea behind a Feedforward ANN, we need to &lt;i&gt;train&lt;/i&gt;&amp;nbsp;the network - find a method to calculate the appropriate weights for our hidden layer neurons. In the context of our classification case, we want to train the network by providing it a dataset with labels so that it can predict the labels of new data once trained - a classic supervised learning scenario.&lt;br /&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;h4&gt;
Backpropagation&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Backpropagation is the algorithm we&#39;ll use to train (i.e minimize the error function of) our ANN. It is essentially repeated applications of the chain rule - chaining together all possible paths in the network to establish how the error changes as a function of the inputs and outputs of each neuron. This may not seem like a very profound approach, nor may it be clear that this use of the chain rule should deserve it&#39;s own name, however the power from this method comes from the implementation. The set up of backpropagation allows the derivatives we use in the chain rule to be calculated using intermediate results in our network. This becomes especially important when the size of our network grows - it is efficient in that it saves the recalculation of derivatives.&lt;br /&gt;
&lt;h4&gt;
&lt;/h4&gt;
&lt;h4&gt;
Some notation&lt;/h4&gt;
&lt;h4&gt;
&lt;div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Suppose we have two neurons labelled by $i$ and $j$ respectively, as depicted below:&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/h4&gt;
&lt;h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEBOmxVjcVQlfP1-3by5_rWKvGyJoBLmLnTlcNWBV4hpYaULH9gw2tqghqTnRtHmSkO2ZIvl36tkPeGtH3KvGUnDia2p26qI8zLPWqXFVH4aWyvJqzDeKR4ZdALKgdVjB_mBDg2K9yn6G2/s1600/simpleNeuron.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;41&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEBOmxVjcVQlfP1-3by5_rWKvGyJoBLmLnTlcNWBV4hpYaULH9gw2tqghqTnRtHmSkO2ZIvl36tkPeGtH3KvGUnDia2p26qI8zLPWqXFVH4aWyvJqzDeKR4ZdALKgdVjB_mBDg2K9yn6G2/s200/simpleNeuron.png&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;where $\sigma_j$ is a label for the neuron with the following meaning:&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span style=&quot;font-weight: normal;&quot;&gt;We define the activation function for neuron $i$ as $a_j(w_{i \rightarrow j} \cdot a_i)$, where&amp;nbsp;&lt;/span&gt;&lt;span style=&quot;font-weight: normal;&quot;&gt;$w_{i \rightarrow j}$ is the weight applied to the input $a_i$ of neuron $j$.&amp;nbsp;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/h4&gt;
&lt;h4&gt;
&lt;div&gt;
&lt;div&gt;
&lt;/div&gt;
&lt;b&gt;Gradient Descent&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div style=&quot;font-weight: normal;&quot;&gt;
In order to minimize the Loss function, one might think to simply take the derivatives and throw them into a prebuilt optimisation routine from your favourite library. This approach is fine when the network is small, but when it scales to millions of neurons it becomes computationally intractable. We will in fact use a standard optimisation routine, but it is the clever implementation which makes it so attractive. The optimisation method we&#39;ll be using is called the&amp;nbsp;&lt;a href=&quot;https://en.wikipedia.org/wiki/Gradient_descent&quot;&gt;batch&amp;nbsp;gradient descent&lt;/a&gt;&amp;nbsp;method, this is in contrast to the&lt;a href=&quot;https://en.wikipedia.org/wiki/Stochastic_gradient_descent&quot;&gt;&amp;nbsp;stochastic gradient descent&lt;/a&gt;&amp;nbsp;method. It is a fairly standard iterative method to minmize a loss function $L\left(w_{i \rightarrow j} \right)$ by updating the target variables by&lt;/div&gt;
&lt;div style=&quot;font-weight: normal;&quot;&gt;
$$ w_{i\rightarrow&amp;nbsp;j} \rightarrow w_{i\rightarrow&amp;nbsp;j} - \eta \frac{\partial L}{\partial w_{i\rightarrow&amp;nbsp;j}} $$&lt;/div&gt;
&lt;div style=&quot;font-weight: normal;&quot;&gt;
at each iteration. $\eta$ is the so called &lt;i&gt;learning rate&lt;/i&gt;&amp;nbsp;which determines how big/small the steps are at each iteration. Intuitively small steps will take a longer time for the algorithm to converge, while larger steps cover more ground, they may overshoot the true minimum - the ideal value is dependent on the loss function and is somewhere in between.&lt;/div&gt;
&lt;div style=&quot;font-weight: normal;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/h4&gt;
&lt;h4&gt;
The Loss Function&lt;/h4&gt;
&lt;h4&gt;
&lt;div&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Once we have the architecture of our ANN set up, we need to measure its performance. In order to do so, we borrow from information theory, a loss function which is commonly found in ANN classification tasks: the&amp;nbsp;&lt;a href=&quot;https://en.wikipedia.org/wiki/Cross_entropy&quot;&gt;cross entropy loss&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$ L = -\frac{1}{N} \sum_{n \in N} \sum_{ i \in C} y_{n,i} \ln \hat{y}_{n,i} $$&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;where we sum over N, the number of training examples and C, the number of classes in our classification problem. The hat $\hat{y}$ indicates an output classification from our network, where $y$ is the actual classification of the training sample. This is the Loss function we will use once we begin to classify the examples from the previous blog post. Note that if we were building the ANN with a continuous output (i.e. regression) we could use the usual Residual Sum of Squares&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$L_{reg} = \sum_{i=1}^{N} \frac{1}{2} \left( \hat{y_{i}} - y_{i} \right)^{2} $$&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;where the factor of a half is chosen for convenience (it prevents stray factors of $\frac{1}{2}$ floating around when we differentiate).&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Thus the task of training our neural network then becomes an optimisation problem; minimize the classification error function $L$ with respect to the weights $w_{i \rightarrow j}$ of each neuron in the hidden layer - &amp;nbsp;see below for an explanation of the notation. Note this is ignoring any potential problems of overfitting.&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/h4&gt;
&lt;/div&gt;
&lt;h4&gt;
Illuminating example - a sample ANN&lt;/h4&gt;
&lt;h4&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;I&#39;m still working my way around TikZ which will allow me to make nice diagrams in LaTeX, but in the interest of time I&#39;ve borrowed the below image from &lt;a href=&quot;http://briandolhansky.com/blog/2013/9/27/artificial-neural-networks-backpropagation-part-4&quot;&gt;here&lt;/a&gt;. The network pictured has a single input $x_i$, 2 hidden layers and a single output. We will not assume the functional form of the loss function $L$ or the activation functions $\sigma$.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0BAZlOZTmmN_C_c1ri3MUVQLr8Y4n_HsnitJPgQZqY9X8hEmVsfE6JFr7aMsQtuWAk4kkAHIFSaQQMoqrcQ70EjZ2m_7TjI8pZwmJZxJcdsQr6_umk1sCQkFO7VC_FAtFLIKm_6O1r-F0/s1600/download.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;171&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0BAZlOZTmmN_C_c1ri3MUVQLr8Y4n_HsnitJPgQZqY9X8hEmVsfE6JFr7aMsQtuWAk4kkAHIFSaQQMoqrcQ70EjZ2m_7TjI8pZwmJZxJcdsQr6_umk1sCQkFO7VC_FAtFLIKm_6O1r-F0/s320/download.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;We want to understand how the output $\hat{y}_i$ changes with respect to the input weight $w_{in \rightarrow i}$, we can use the chain rule to get this relationship. Noting that there are two paths from the input layer to the output, we need to consider each path separately.&amp;nbsp;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;We define the following in the network, where $i$, $j$, $k$, $o$ index the neurons&amp;nbsp;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$z_i = w_{in \rightarrow i} x_i, &amp;nbsp;\quad a_i = \sigma(z_i)$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$z_j = w_{i \rightarrow j} a_i, \quad a_j = \sigma(z_j)$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$z_k = w_{i \rightarrow k} a_i, \quad a_j = \sigma(z_k)$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$z_o = w_{k \rightarrow o} a_k + w_{j \rightarrow o} a_j, \quad \hat{y} \equiv a_j = output(z_o)$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;where $output(x)$ is the output function, which for now we will keep generic and $\sigma(x)$ is the activation function, which is the same for each neuron in the network.&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;We decompose $\frac{\partial L}{\partial w_{in \rightarrow j}}$: starting at the right side of the graph and moving through $o \rightarrow k \rightarrow i$ as below:&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$\frac{\partial L}{\partial z_o} \times \frac{\partial z_o}{\partial z_k} \times \frac{\partial z_k}{\partial z_i} \times \frac{\partial z_i}{\partial w_{in \rightarrow j}}$$&lt;/span&gt;&lt;/div&gt;
&lt;/h4&gt;
&lt;h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Let&#39;s look at an individual component $$\frac{\partial z_o}{ \partial z_k} = \frac{\partial}{\partial z_k} \left( w_{k \rightarrow o} a_k + w_{j \rightarrow o} a_j \right)$$ noting the second term does not depend on $z_k$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$\frac{\partial}{\partial z_k} &amp;nbsp;w_{k \rightarrow o} \sigma(z_k) &amp;nbsp;= w_{k \rightarrow o} \sigma &#39; (z_k)$$With a similar analysis we see that the product of derivatives can be expressed as&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$\frac{\partial L}{\partial z_o} \times w_{k \rightarrow o} \sigma &#39; (z_k) \times w_{i \rightarrow k} \sigma &#39; (z_i) \times x_i$$&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;and now moving through $o \rightarrow j \rightarrow i$&lt;/span&gt;&lt;/div&gt;
&lt;/h4&gt;
&lt;h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$\frac{\partial L}{\partial z_o} \times \frac{\partial z_o}{\partial z_j} \times \frac{\partial z_j}{\partial z_i} \times \frac{\partial z_i}{\partial w_{in \rightarrow j}}$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;$$=\frac{\partial L}{\partial z_o} \times w_{j \rightarrow o} \sigma &#39; (z_j) \times w_{i \rightarrow k} \sigma &#39; (z_i) \times x_i$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Putting this all together we have $$\frac{\partial L}{\partial w_{in \rightarrow i}} = \frac{\partial L}{\partial z_o} \left[ w_{k \rightarrow o} \sigma &#39; (z_k) \times w_{i \rightarrow k} \sigma &#39;(z_i) + w_{j \rightarrow o} \sigma &#39; (z_j) \times w_{i \rightarrow j} \sigma &#39;(z_i) \right] x_i$$&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;where we have yet to specify the exact form of the loss function $L$ and activation function $\sigma(x)$ in this example. Once these are specified, we can just plug them in to the above formula. Hopefully this simplified example illuminates how the derivatives of the loss function wrt to each neuron is calculated. In terms of backpropagation, we can think of starting out the output and working backwards through each neuron in the path leading to it and understanding how the error changes at each point. In the next section I will generalise these results so they are easily extendable to a larger network.&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;/h4&gt;
&lt;h3 style=&quot;clear: both;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Error propagation&lt;/span&gt;&lt;/h3&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;We will now generalise the above computation, in order to get the derivative of the loss function with respect to any $z_j$ in any of the layers of the network. We define the error signal $$\delta_j = \frac{\partial L}{\partial z_j}$$ Now, using the chain rule as in the example above we have $$\delta_j = \frac{\partial L}{\partial \hat{y}} \times \frac{\partial \hat{y}}{\partial z_j}$$ Once we specify our loss function $L$ we&#39;ll have a nice expression for the first term in the expression above, for now let&#39;s keep it generic. Now using the definitions of the $z_i$ and $a_i$ above: $$\frac{\partial \hat{y}}{\partial z_j} = \frac{\partial \hat{y}}{\partial a_j} \times \frac{\partial a_j}{\partial z_j} = \sigma &#39; (z_j) \sum_{k \in path(j)} \frac{\partial \hat{y}}{\partial z_k} \frac{\partial z_k}{\partial a_j}$$ where the sum is over the $k$ paths which are connected to the output of neuron $j$. We have $z_k = a_j w_{j \rightarrow k}$ so our expression becomes $$\frac{ \partial \hat{y}}{\partial z_j} = \sigma &#39;(z_j) \sum_{k \in path(j)} \frac{\partial \hat{y}}{\partial z_k} w_{j \rightarrow k}$$ $$\implies \delta_j = \sigma &#39;(z_j) \sum_{k \in path(j)} \frac{\partial L}{\partial \hat{y}} \frac{\partial \hat{y}}{\partial z_k} w_{j \rightarrow k}$$ Note the first two terms in the summation are actually $\delta_k$ in disguise! Thus we have a recursive definition for our error propagation: $$\delta_j = &amp;nbsp;\sigma &#39; (z_j) \sum_{k \in path(j)} \delta_k w_{j \rightarrow k}$$&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;Thus if we have $\delta_\text{output}$, we can work our way backwards through the neural network, calculating the error for each neuron as a function of the error of the neurons that its output is connected to. This is the key concept of back propagation - although it is just an application of the chain rule, because we can &lt;i&gt;propagate&lt;/i&gt;&amp;nbsp;the error at each point in the network through subsequent neurons, the calculations can be done on the fly by utilising calculations that have already been performed.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
Next time we&#39;ll describe the architecture of the actual ANN we&#39;ll use to classify the &lt;i&gt;make moons&lt;/i&gt;&amp;nbsp;example detailted in pt1. To be honest, these concepts didn&#39;t fully sink in until the first time I implemented an ANN, going through the details of the calculations, I suggest you work through this and the next blog post by hand in order to ensure you have a handle on how the feedforward and error propagations are affected by different topologies of ANNs.&lt;br /&gt;
&lt;h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;h4&gt;
&lt;div&gt;
&lt;span style=&quot;font-weight: normal;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;/h4&gt;
</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/5313394170303213997/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2016/12/feedforward-artificial-neural-network.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/5313394170303213997'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/5313394170303213997'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2016/12/feedforward-artificial-neural-network.html' title='Feedforward Artificial Neural Network pt2'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEBOmxVjcVQlfP1-3by5_rWKvGyJoBLmLnTlcNWBV4hpYaULH9gw2tqghqTnRtHmSkO2ZIvl36tkPeGtH3KvGUnDia2p26qI8zLPWqXFVH4aWyvJqzDeKR4ZdALKgdVjB_mBDg2K9yn6G2/s72-c/simpleNeuron.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-8499382141014907937</id><published>2016-11-15T02:49:00.001-08:00</published><updated>2016-11-16T00:54:39.607-08:00</updated><title type='text'>Feedforward Artificial Neural Network pt1</title><content type='html'>&lt;h2&gt;
Architecture of an ANN&lt;/h2&gt;
&lt;div&gt;
The history of ANNs can be traced back to&amp;nbsp;&lt;span style=&quot;background-color: white;&quot;&gt;Warren McCulloch, who proposed a mechanism of how neurons might work by modelling a simple neural network with an electrical circuit. This line of thinking was reinforced by Donald Hebb, who discovered that neural pathways between neurons were strengthened through repetitive use. Understanding the motivation behind ANNs will help us understand why they are structured&amp;nbsp;the way they are, particularly the &lt;a href=&quot;https://en.wikipedia.org/wiki/Action_potential&quot;&gt;action potential&lt;/a&gt; of a neuron.&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
An ANN consists of three major components;&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Input Layer&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;This layer takes the inputs as is - they do &lt;i&gt;not&lt;/i&gt; modify the data at all; they push it into the hidden layers.&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Hidden Layer(s)&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;In line with the aforementioned action potential of a neuron in the brain, the hidden layer neurons take an input, applies an &lt;i&gt;activation function&lt;/i&gt;&amp;nbsp;and pushes the result to the next layer in the network.&lt;/li&gt;
&lt;li&gt;The activation function $\phi : &amp;nbsp;\mathbb{R} \rightarrow \mathbb{R}$ takes $\sum_{i=1}^{n} x_i w_i + b$ as an argument, where $n$ is the number of inputs flowing into the particular hidden layer neuron, $w_{i}$ is the associated weight with input $x_{i}$ and $b$ is called the &lt;i&gt;bias. &lt;/i&gt;Our task is to find the $w_{i}$ and $b$ for each neuron in the hidden layer which minimize our error function (more on this later).&lt;/li&gt;
&lt;li&gt;The choice of activation function is entirely up to you. Obviously there are some standard choices for certain tasks. See below for a (by no means exhaustive) list of activation functions&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBVBTyrbaRnGPL0U8zMkE5jeBVDTf2IUzRIahVh5ALeQS7bpPdBCKUruhpa-tE_yyA-Qgqt4KI9wX-DoZpcjeZcVoc09m_ASQGj9GTaOOCmi4agFrZAthCiEpL9DvNwFY5FHnlDoaasmae/s1600/main-qimg-01c26eabd976b027e49015428b7fcf01.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;300&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBVBTyrbaRnGPL0U8zMkE5jeBVDTf2IUzRIahVh5ALeQS7bpPdBCKUruhpa-tE_yyA-Qgqt4KI9wX-DoZpcjeZcVoc09m_ASQGj9GTaOOCmi4agFrZAthCiEpL9DvNwFY5FHnlDoaasmae/s400/main-qimg-01c26eabd976b027e49015428b7fcf01.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&amp;nbsp;&lt;/li&gt;
&lt;li&gt;The activation functions are they key to capturing non-linearities in our decision boundary.&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;Output Layer&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;The output of the neural network. In our case (classification) it will be a label classifying our input data to one of two classes.&lt;/li&gt;
&lt;/ul&gt;
&lt;/ul&gt;
&lt;div&gt;
These three components together with the topology of the network will define the entire structure of our ANN. Below is a stock image of a typical ANN&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjj2ePvulpN4jjUF0KWzGFAXgPWjOpuf1jLKdIbGP3vSCFvgvivxtLQLKd3Bj57OzeomUxVahxaKcTBSijXVfJjNUug0BaNn16fn-Nqc1lB7amV138AJPRorawBRCDWD0WmpC0jZniiyqxk/s1600/structure.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;192&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjj2ePvulpN4jjUF0KWzGFAXgPWjOpuf1jLKdIbGP3vSCFvgvivxtLQLKd3Bj57OzeomUxVahxaKcTBSijXVfJjNUug0BaNn16fn-Nqc1lB7amV138AJPRorawBRCDWD0WmpC0jZniiyqxk/s320/structure.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
On the left there are 3 inputs which flow into the hidden layers (more on these below) which then in turn flow into the outputs. There are two hidden layers in this setup, each with 4 neurons - these are hyper parameters we can tune to increase performance and reduce overfitting.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Note that the flow of the network is strictly left to right, none of the neurons in the hidden layer are connected to one another and none of the neurons in the network loop back into themselves. This single direction of information flow and the fact that there are no loops or cycles in the network define a &lt;i style=&quot;font-weight: bold;&quot;&gt;Feedforward Artificial Neural Network.&lt;/i&gt;&amp;nbsp;Also note that the number of inputs and outputs are fixed once we define the network under this architecture. Other types of neural networks exist that are able to handle inputs with multiple lengths, but our focus for now will be Feedforward ANNs.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h3&gt;
By why &lt;i&gt;this&lt;/i&gt;&amp;nbsp;structure?&lt;/h3&gt;
&lt;div&gt;
The above structure of a neural network may seem like an arbitrary construction - how can we guarantee that it can be trained in such a way to produce our desired output?&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Well..luckily for us there exists a theorem called the &lt;i&gt;Universal Approximation Theorem&lt;/i&gt;&amp;nbsp;which states that under reasonable circumstances, a feedforward network containing a finite number of neurons can approximate continuous functions on compact subsets of $\mathbb{R}^{n}$.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h4&gt;
Statement&lt;/h4&gt;
&lt;div&gt;
Let $\phi \left( \cdot \right)$ be a nonconstant, bounded and monotonically-increasing continuous function. Let $I_{m}$ denote the $m$-dimensional unit hypercube $\left[ 0, 1 \right]$. The space of continuous functions on $I_{m}$ is $C \left( I_{m} \right)$. Then $\forall f \in C \left( I_{m} \right)$ and $ \epsilon &amp;gt; 0$ $\exists N \in \mathbb{Z}$, $v_{i}, b_{i} \in \mathbb{R}$ and $w_i \in \mathbb{R}^{m}$ where $ i = 1, \dots, N$ such that we may define&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
$$F(x) \equiv \sum_{i=1}^{N} v_{i} \phi \left( w_{i}^{T}x + b_{i} \right)$$&lt;/div&gt;
&lt;div&gt;
such that $$\left| F(x) - f(x) \right| &amp;lt; \epsilon \quad \forall x \in I_{m}$$&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
Which is quite fascinating really, that we can essentially approximate &lt;i&gt;any&lt;/i&gt;&amp;nbsp;continuous function to an arbitrary degree using a linear combination of our activation functions. Please note that this tells us nothing of actually &lt;i&gt;how&lt;/i&gt;&amp;nbsp;to approximate the function; what the parameters $N, v_{i}, b_{i}$ or $w_{i}$ are - only that they exist.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h4&gt;
Summary&lt;/h4&gt;
&lt;div&gt;
So there it is, a whirlwind introduction to Feedforward Artificial Networks. By no means is this supposed to be a comprehensive introduction, but to set the scene for the next few blog posts. In my next blog I&#39;ll define the error functions and consequently the &lt;i&gt;Backpropogation algorithm&lt;/i&gt;&amp;nbsp;which we will use to train our Feedforward ANN to find the weights and biases of our hidden layer neurons.&lt;/div&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/8499382141014907937/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2016/11/feedforward-artificial-neural-network.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/8499382141014907937'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/8499382141014907937'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2016/11/feedforward-artificial-neural-network.html' title='Feedforward Artificial Neural Network pt1'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBVBTyrbaRnGPL0U8zMkE5jeBVDTf2IUzRIahVh5ALeQS7bpPdBCKUruhpa-tE_yyA-Qgqt4KI9wX-DoZpcjeZcVoc09m_ASQGj9GTaOOCmi4agFrZAthCiEpL9DvNwFY5FHnlDoaasmae/s72-c/main-qimg-01c26eabd976b027e49015428b7fcf01.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-2935816822874471313</id><published>2016-11-14T01:30:00.001-08:00</published><updated>2016-11-14T01:30:58.472-08:00</updated><title type='text'>Back.. again! Artificial neural networks have tickled my fancy</title><content type='html'>&lt;script src=&quot;https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js&quot;&gt;&lt;/script&gt;
I&#39;m really impressed with my foresight when naming this blog all those years ago, it truly does live on the edge of abandon as I haven&#39;t touched it in 3 years! I&#39;ve decided to fire it back up again and will (at least try) to actively post as I delve into the world of statistical / machine learning! I just want a place to document my thoughts/learnings/projects as I delve into this fascinating area. I&#39;ve decided to use Python as my language of choice as I&#39;ve always wanted to learn it but never got around to it or had the chance. Now I have no excuses!&lt;br /&gt;
&lt;br /&gt;
So, without further ado...&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;Artificial Neural Networks&lt;/b&gt;&lt;/h3&gt;
I&#39;m going to assume &lt;i&gt;some &lt;/i&gt;familiarity with ANNs - what they are, their general structure/philosophy. See &lt;a href=&quot;https://www.doc.ic.ac.uk/~nd/surprise_96/journal/vol4/cs11/report.html&quot;&gt;here&lt;/a&gt;&amp;nbsp;for a comprehensive introduction.&lt;br /&gt;
As a first pass, I&#39;ll introduce a motivating example, go through the math and then implement (in Python) an ANN from scratch.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;Definition of the problem&lt;/b&gt;&lt;/h3&gt;
We&#39;ll look at a classification problem in 2 dimensions (to make visualisation easier, read: possible) where our old friend Logistic Regression struggles. It will highlight a key fact that needs to be understood in any sort of machine learning / statistical problem; understanding when and what tools to use to attack a problem.&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;
The data:&lt;/h4&gt;
&lt;div&gt;
We&#39;ll use a toy dataset from sklearn called &lt;i&gt;make_moons&lt;/i&gt;, with the following call:&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;code class=&quot;prettify&quot;&gt;
import pandas as pd&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;import sklearn.datasets&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;import seaborn as sb&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;import sklearn.linear_model&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;&lt;br /&gt;&lt;/code&gt;
&lt;code class=&quot;prettify&quot;&gt;X,y = sklearn.datasets.make_moons(200, noise=0.2)&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df = pd.DataFrame()&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df[&#39;x1&#39;] = X[:,0]&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df[&#39;x2&#39;] = X[:,1]&amp;nbsp;&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;df[&#39;z&#39;] = y&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;prettify&quot;&gt;sb.lmplot(&#39;x1&#39;,&#39;x2&#39;,hue=&#39;z&#39;, data=df, fit_reg = False)
&lt;/code&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkJK8RYn18MywTpU_lqYtEMW0lTYuQNS3NuH7mrcRUnIeoSIX5CptTTLZklpJ8GuW4RSIAO_gED1pV0Ld4hLP92yoCrD0gPaOBt-L0ZUbkpWQ_TKvwYiE8EiPsJABbyDvGD1osKPgBuIJ2/s1600/make_moons.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;309&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkJK8RYn18MywTpU_lqYtEMW0lTYuQNS3NuH7mrcRUnIeoSIX5CptTTLZklpJ8GuW4RSIAO_gED1pV0Ld4hLP92yoCrD0gPaOBt-L0ZUbkpWQ_TKvwYiE8EiPsJABbyDvGD1osKPgBuIJ2/s320/make_moons.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;h4&gt;
&lt;b&gt;The task:&lt;/b&gt;&lt;/h4&gt;
&lt;div&gt;
We want to calculate the decision boundary between the two (blue and green) classes. At a glance it&#39;s clearly non-linear, so let&#39;s see how a Logistic Regression classification goes!&lt;br /&gt;
&lt;h4&gt;
&lt;b&gt;Results:&lt;/b&gt;&lt;/h4&gt;
&lt;div&gt;
We can see that the Logistic Regression can only fit a linear decision boundary (see below) - even though the actual decision boundary is decidedly non-linear.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiX6o5pW7hV88Q9UWQX9gS8rV0l2ZOKmds9pEMdJu5vCCyve4XH_fmUJ4YNjJL18DlM4FGRmRZ-k_lkjk_nas-YjSEsFzDjdkXTqGDCBj4EcIwJpCQDQMfFubx4jwao_YFmiMpaROaEyi0-/s1600/LogReg_boundary.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;309&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiX6o5pW7hV88Q9UWQX9gS8rV0l2ZOKmds9pEMdJu5vCCyve4XH_fmUJ4YNjJL18DlM4FGRmRZ-k_lkjk_nas-YjSEsFzDjdkXTqGDCBj4EcIwJpCQDQMfFubx4jwao_YFmiMpaROaEyi0-/s320/LogReg_boundary.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/div&gt;
&lt;br /&gt;&lt;/div&gt;
We can see why the Logistic Regression decision boundary is linear from the following:&lt;br /&gt;
$$ P_{boundary} \equiv \frac{1}{1+e^{- \theta \cdot x}} = 0.5 $$&lt;br /&gt;
$$ \implies 1 = e^{- \theta \cdot x}$$&lt;br /&gt;
$$ \implies \theta \cdot x = 0 $$ which defines a plane (line in 2 dimensions).&lt;br /&gt;
&lt;br /&gt;
In part 2 I will define an ANN that we will work through to establish exactly how it works and how it is trained. We will then construct and implement it in python to get an idea of the decision boundaries it can produce.</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/2935816822874471313/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2016/11/back-again-artificial-neural-networks.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/2935816822874471313'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/2935816822874471313'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2016/11/back-again-artificial-neural-networks.html' title='Back.. again! Artificial neural networks have tickled my fancy'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkJK8RYn18MywTpU_lqYtEMW0lTYuQNS3NuH7mrcRUnIeoSIX5CptTTLZklpJ8GuW4RSIAO_gED1pV0Ld4hLP92yoCrD0gPaOBt-L0ZUbkpWQ_TKvwYiE8EiPsJABbyDvGD1osKPgBuIJ2/s72-c/make_moons.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-4539997338698919942</id><published>2013-08-25T01:05:00.000-07:00</published><updated>2013-09-04T01:44:56.757-07:00</updated><title type='text'>(Weak) Law of Large Numbers and the Central Limit Theorem</title><content type='html'>Following the definitions of &lt;i&gt;convergence in probability &lt;/i&gt;and &lt;i&gt;convergence in distribution&lt;/i&gt; in the previous post - we now state two fundamental theorems which incorporate these concepts.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;(Weak) Law of Large Numbers:&lt;/b&gt;&lt;br /&gt;
Let $\left\{X_i \right\}$ be a sequence of iid (independent and identically distributed) random variables with $\mathbb{E}\left[X_i\right] = \mu \lt \infty$ and $\text{Var}\left(X_i \right) = \sigma^2 $. Now define $$S_n:=\sum_{i=1}^{n} X_i$$ then $$\frac{S_n}{n}\rightarrow \mu$$ as $n\rightarrow \infty$.&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;&lt;b&gt;Proof:&lt;/b&gt;&lt;/i&gt;&lt;br /&gt;
Since the random variables&amp;nbsp;&lt;i&gt;&lt;b&gt; &lt;/b&gt;&lt;/i&gt;are all iid then $$\mathbb{E}\left[\frac{S_n}{n} \right] = \frac{1}{n} \mathbb{E}\left[S_n\right] = \frac{n \mu}{n} = \mu$$ Similarly $$\text{Var}\left( \frac{S_n}{n} \right) = \frac{1}{n^2} \left(\mathbb{E}[S_n^2]- \mathbb{E}[S_n]^2 \right)=\frac{n \sigma^2}{n^2} = \frac{\sigma^2}{n}$$ We now call upon the &lt;a href=&quot;http://en.wikipedia.org/wiki/Chebyshev%27s_inequality#Probabilistic_statement&quot;&gt;Chebyshev&#39;s Inequality&lt;/a&gt; which states if $X$ is a random variable with finite expectation $\mu$ and non-zero variance $\sigma^2$ then $$P\left( \left|X-\mu \right| \ge n \sigma \right) \le \frac{1}{n^2}$$It gives a bound on the distributions values in terms of the variance - this is completely distribution agnostic.&lt;br /&gt;
&lt;br /&gt;
We can now use Chebyshev&#39;s Inequality and re-write it using $X=S_n$ and $n \sigma = \epsilon$:&lt;br /&gt;
$$P\left( \left|S_n-\mu \right| \ge \epsilon \right) \le \frac{\sigma^2}{n \epsilon^2}$$Hence&lt;br /&gt;
$$ P\left( \left|S_n-\mu \right| \lt \epsilon \right) = 0$$ as $n \rightarrow \infty$. Which is precisely the definition of convergence in probability.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Central Limit Theorem (CLT):&lt;/b&gt;&lt;br /&gt;
We shall state a slightly restricted version of the CLT which is fine for illustrative purposes. Taking our $S_n$ from above, then the CLT states:&lt;br /&gt;
Let $\left\{X_1, X_2, . . . \right\}$ be a sequence of i.i.d random variables with finite expectation $\mathbb{E}[X_i]&amp;nbsp; = \mu &amp;lt; \infty$ and finite non-zero variance $\text{Var}\left(X_i\right) = \sigma^2 &amp;lt; \infty$. Then&lt;br /&gt;
&lt;br /&gt;
$$ P \left( \frac{S_n-n \mu}{\sigma \sqrt{n}} \leq x \right) \rightarrow \Phi(x)$$&lt;br /&gt;
as $n \rightarrow \infty$ and the convergence is &lt;i&gt;in distribution&lt;/i&gt; and $\Phi(x)$ is the cumulative density function of of a Standard Normal variable. We shall not prove the CLT as only an understanding of what it says and how it can be applied is required.&lt;br /&gt;
&lt;br /&gt;
This explains why Normal distributions are so common in modelling (and even nature) since under these mild conditions, regardless of distribution - if this combination of random variables is formed then it will tend to the normal distribution for large enough n.</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/4539997338698919942/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2013/08/weak-law-of-large-numbers-and-central.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/4539997338698919942'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/4539997338698919942'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2013/08/weak-law-of-large-numbers-and-central.html' title='(Weak) Law of Large Numbers and the Central Limit Theorem'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-3785553264773544600</id><published>2013-08-22T02:23:00.000-07:00</published><updated>2013-08-22T02:23:31.454-07:00</updated><title type='text'>Convergence of Random Variables</title><content type='html'>&lt;pre&gt;
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Before moving on to scaling a random walk into a Wiener process, we must understand the notion of &lt;i&gt;convergence &lt;/i&gt;of random variables.&lt;br /&gt;
&lt;br /&gt;
We won&#39;t cover the notions of &lt;i&gt;uniform &lt;/i&gt;and &lt;i&gt;pointwise&lt;/i&gt; convergence of a sequence of functions here - these are covered in any undergraduate analysis class. We will delve right into &lt;i&gt;Convergence of random variables.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Convergence in probability:&lt;/b&gt;&lt;br /&gt;
Let $\left\{X_n\right\}$ be a sequence of of random variables and $X$ be a random variable. $\left\{X_n\right\}$&amp;nbsp; is said to&lt;i&gt; converge in probability &lt;/i&gt;to $X$ if $\forall \epsilon \lt 0$&lt;br /&gt;
$$P\left(\left| X_n-X \right| \lt \epsilon \right)=0$$ as $n \rightarrow \infty$.&lt;br /&gt;
&lt;br /&gt;
Another notion of convergence of random variables is &lt;i&gt;Convergence in distribution.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Convergence in distribution:&lt;/b&gt;&lt;br /&gt;
Given random variables $\{X_1, X_2, ...\}$ and the cumulative distribution functions $F_i(x)$ of $X_i$ then we say that $X_n$ &lt;i&gt;converges to the distribution &lt;/i&gt;of $X$ if&lt;br /&gt;
$$\lim_{n \rightarrow \infty} F_n(x) = F(x)$$ for every $x \in \mathbb{R}$ at which $F(x)$ is continuous.&lt;br /&gt;
&lt;br /&gt;
Note that only the&lt;i&gt; distributions&lt;/i&gt; of the variables matter - so they random variables themselves could in fact be defined on different probability spaces.&lt;br /&gt;
&lt;br /&gt;
These may seem like fairly elementary definitions, but they hold great importance in applications of probability, namely through the &lt;i&gt;(Weak) Law of Large numbers &lt;/i&gt;and the &lt;i&gt;Central Limit Theorem - &lt;/i&gt;which will be covered in the next post.</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/3785553264773544600/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2013/08/convergence-of-random-variables.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/3785553264773544600'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/3785553264773544600'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2013/08/convergence-of-random-variables.html' title='Convergence of Random Variables'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-1449253006263643499</id><published>2013-08-19T04:11:00.002-07:00</published><updated>2013-08-22T02:25:33.807-07:00</updated><title type='text'>I&#39;ve returned with a random walk</title><content type='html'>So after two years absent from blogging, I am now back with a rejuvenated interest in mathematics, more specifically financial mathematics. So from now on, this blog will serve as my workbook as I endeavour to learn more about portfolio valuation, solving stochastic differential equations and other such fun. Such posts will not be rigorous in the mathematical sense, but will serve as a heuristic survey of the different tools available and how they are used in a financial context. The posts may also seem scattered content wise as I really haven&#39;t planned a syllabus - I&#39;m just learning things as I come across them.&lt;br /&gt;
&lt;br /&gt;
With that in mind - I will start with the very basics; introducing my first blog in over two years, I give a quick overview of Random Walks in $\mathbb{Z}$&lt;br /&gt;
&lt;br /&gt;
Let $X_0 := 0$ be our starting position and for each $i \in \mathbb{N}$ let $$X_i:=X_{i-1}+dX_i$$ where $dX_i = \pm 1$ with equal probability - i.e is a Bernoulli distributed random variable with $p=q=\frac{1}{2}$. Therefore our position at step $N$ is just the sum of the &lt;i&gt;independent &lt;/i&gt;Bernoulli variables;&lt;br /&gt;
$$X_N= \sum_{i=0}^{N} dX_i$$.&lt;br /&gt;
We can calculated the expectation: $$\mathbb{E}[X_N]= \mathbb{E}\left[ \sum_{i=0}^{N} dX_i\right]=  \sum_{i=0}^{N} \mathbb{E} [ dX_i]=0$$ by using the definition of the expectation of a discrete random variable and the fact that $dX_i$ and $dX_j$ are independent for $i \neq j$. Now&lt;br /&gt;
$$Var(X)=\mathbb{E}[X^2]- \mathbb{E}[X]^2$$ we can calculate $$\mathbb{E}[X_N^2] = \sum_{i=0}^N 1 = N$$That is, the variance of $X_N$ is the jump size times the total steps $N$.&lt;br /&gt;
Below I have simulated the aforementioned random walk for $N=100$ and $N=100000$ respectively. &lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPCxHIMjwDX9OBOCPsycOP-eofgEQXq4kpBHOlYOTc0pd-AOpcN7tJkJHKlqLgEowhnjRU__1pvuV3g9c2syXqvi-kBfN11U7nFLFE5XgFb5i49MPbmIOi-XbLyghr7RF6_GYFUaI4LP88/s1600/n100.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;240&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPCxHIMjwDX9OBOCPsycOP-eofgEQXq4kpBHOlYOTc0pd-AOpcN7tJkJHKlqLgEowhnjRU__1pvuV3g9c2syXqvi-kBfN11U7nFLFE5XgFb5i49MPbmIOi-XbLyghr7RF6_GYFUaI4LP88/s320/n100.jpg&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9AegaRNcqs2GEnFSVmfJT6zrFHTQHii97i1uue8L4CgguXCeZ0L9ei1YfbQbLgGnvO2-Oe5f5NTE5wep690evqS0dPnXdwLMYMQl9kqTlYeERdpDk6WVed6DqFec1WwgYG6_xeYGuEyzL/s1600/n100000.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;240&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9AegaRNcqs2GEnFSVmfJT6zrFHTQHii97i1uue8L4CgguXCeZ0L9ei1YfbQbLgGnvO2-Oe5f5NTE5wep690evqS0dPnXdwLMYMQl9kqTlYeERdpDk6WVed6DqFec1WwgYG6_xeYGuEyzL/s320/n100000.jpg&quot; width=&quot;320&quot; /&gt;&amp;nbsp;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Next we&#39;ll look at a specific scaling of these random walks to obtain a &lt;i&gt;Wiener Process &lt;/i&gt;and eventually talk about Stochastic Integrals and Ito&#39;s lemma.&lt;/div&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/1449253006263643499/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2013/08/ive-returned-with-random-walk.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1449253006263643499'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1449253006263643499'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2013/08/ive-returned-with-random-walk.html' title='I&#39;ve returned with a random walk'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPCxHIMjwDX9OBOCPsycOP-eofgEQXq4kpBHOlYOTc0pd-AOpcN7tJkJHKlqLgEowhnjRU__1pvuV3g9c2syXqvi-kBfN11U7nFLFE5XgFb5i49MPbmIOi-XbLyghr7RF6_GYFUaI4LP88/s72-c/n100.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-1270516589004060451</id><published>2011-03-24T03:21:00.000-07:00</published><updated>2011-03-24T03:21:54.803-07:00</updated><title type='text'>I&#39;ve been missing.</title><content type='html'>Ok so since my university work has ramped up - I&#39;ve had little time for blogging/let alone myself; thus the absence of &lt;i&gt;interesting &lt;/i&gt;updates.&lt;br /&gt;
&lt;br /&gt;
Hopefully, when my assignments are done I shall devote my time to making some more thought provoking posts.&lt;br /&gt;
&lt;br /&gt;
But for now I&#39;ll leave you to ponder &lt;i&gt;Russel&#39;s Paradox&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;
&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-style: italic;&quot;&gt;&lt;b&gt;Pre-reading:&lt;/b&gt;&amp;nbsp;&lt;/span&gt;The following assumes that you are all familiar with a set, if not then put simply;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;A set is a collection of objects.&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Generally there will be a rule discerning whether an object is included in a set or not. for example;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;A set of all shoe brands does not have colgate as a member (since colgate is a toothpaste brand).&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;The members of a set can also be sets themselves, for example;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;The set of all forks is a member of the set of all cutlery.&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Now make a proposal;&lt;/div&gt;&lt;i&gt;Let F be the set of all forks, F itself is not a fork therefore F does not contain itself as a member.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;We can call F as a &lt;b&gt;normal &lt;/b&gt;set.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;
&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;Now suppose we have a set NF - this is the set of all things that are &lt;b&gt;not&lt;/b&gt;&amp;nbsp;forks. NF itself is not a fork, therefore it contains itself as a member. We can call NF an &lt;b&gt;abnormal&lt;/b&gt;&amp;nbsp;set.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;
&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;Suppose we have a new set &lt;b&gt;G &lt;/b&gt;- with all of its elements &lt;b&gt;normal sets.&lt;/b&gt;&amp;nbsp;Now, if &lt;b&gt;G&lt;/b&gt;&amp;nbsp;is &lt;b&gt;normal&lt;/b&gt;&amp;nbsp;then it should contain itself as a member - but the instant it contains itself, &lt;b&gt;G&lt;/b&gt;&amp;nbsp;becomes abnormal.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;
&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;This is known as &lt;b&gt;Russel&#39;s Paradox.&lt;/b&gt;&lt;/i&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/1270516589004060451/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/ive-been-missing.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1270516589004060451'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/1270516589004060451'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/ive-been-missing.html' title='I&#39;ve been missing.'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-979815529286724504</id><published>2011-03-09T18:24:00.000-08:00</published><updated>2013-08-15T06:02:07.028-07:00</updated><title type='text'>Integral of a Gaussian (continued)</title><content type='html'>Ok, so last post we derived (not so rigorously) that the integral of a standard Gaussian as;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;$$\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;and using a substitution of&amp;nbsp;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt; &lt;br /&gt;
$$x=\sqrt{a}y$$ and $$dx=\sqrt{a}dy$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&amp;nbsp;we obtain;$$\int_{-\infty}^{\infty} e^{-ax^2} dx = \sqrt{\frac{\pi}{a}}$$.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Now let&#39;s extend that to the more general form of;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I=\int_{-\infty}^{\infty} x^2 e^{-ax^2} dx $$ where a is some constant.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;We can recognise (or at least be told to recognise) that the argument of the integral; $$x^2 e^{-ax^2}$$ is equal to&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt; $$-\frac{\partial}{\partial a} e^{-ax^2}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Putting this together, we get;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I=\int_{-\infty}^{\infty}-\frac{\partial}{\partial a} e^{-ax^2} dx$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;We can swap the partial derivative and Integration sign (provided the variable we are integrating over is independent of a and the integrand is continuous)&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt; &lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;We get; $$I= -\frac{\partial}{\partial a} \int_{-\infty}^{\infty} e^{-ax^2} dx = -\frac{\partial}{\partial a}\sqrt{\frac{\pi}{a}}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$=\frac{1}{2a} \sqrt{\frac{\pi}{a}}$$ &lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Therefore;&amp;nbsp; $$\int_{-\infty}^{\infty} x^2 e^{-ax^2} dx =\frac{1}{2a} \sqrt{\frac{\pi}{a}}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;This technique can be extended for different powers of x - provided they are even. &lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/979815529286724504/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/integral-of-gaussian-continued.html#comment-form' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/979815529286724504'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/979815529286724504'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/integral-of-gaussian-continued.html' title='Integral of a Gaussian (continued)'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-8503466376546347248</id><published>2011-03-08T22:12:00.000-08:00</published><updated>2011-03-08T22:40:56.831-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Calculating the integral of a Gaussian"/><title type='text'>Evaluating the integral of a Gaussian</title><content type='html'>Okay, so I thought I&#39;d take a step back from the quite technical blog about finding the &lt;a href=&quot;http://edgeofabandon.blogspot.com/2011/03/volume-of-n-sphere.html&quot;&gt;Volume of an n-sphere&lt;/a&gt; and look at some of the (often overlooked) techniques that were used.&lt;br /&gt;
&lt;br /&gt;
First, is evaluating the following integral of a gaussian - which occurs very commonly in branches of physics and engineering;&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;$$I=\int_{-\infty}^{\infty} e^{-x^2} dx$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Let&#39;s now have a look at what $$I^2$$ looks like;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I^2=\left(\int_{-\infty}^{\infty} e^{-x^2} dx\right)^2=\int_{-\infty}^{\infty} e^{-x^2}dx \cdot \int_{-\infty}^{\infty} e^{-x^2}dx$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Now, using a dummy variable &lt;i&gt;y &lt;/i&gt;in the second integral , we get;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I^2=\int_{-\infty}^{\infty} e^{-x^2}dx \cdot \int_{-\infty}^{\infty} e^{-y^2}dy$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Note: We can use dummy variables since they are exactly that; a variable which is only used to integrate over and (presumably) does not appear in the evaluated integral. &lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;We can bring the exponents together - the integrals are independent.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I^2=\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} e^{-(x^2+y^2)}dxdy$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Now we use a change of variable from cartesian coordinates to polar with;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$x=rcos(\theta)$$ and&lt;br /&gt;
$$y=rsin(\theta)$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;With the determinant of the Jacobian matrix being $$r d\theta dr$$ and noting the change of terminals of integration.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Hence $$I^2=\int_{0}^{2\pi}\int_{0}^{\infty} e^{-r^2} r dr d\theta$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Noting that nothing in the integrand depends on theta.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Now, letting $$u=r^2$$ we get $$\frac{du}{dr}=2r$$ so $$dr=\frac{du}{2r}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;We get $$I^2= 2\pi \int_{u=0}^{u=\infty} e^{-u} r \frac{du}{2r}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Finally; $$I^2= \frac{2\pi}{2} \left[-e^{-u}\right]_{u=0}^{u=\infty}=\pi \left[-\left(e^{-\infty}-e^0\right)\right]=\pi$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
Hence $$I^2=\pi \rightarrow I=\sqrt{\pi}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Note: This isn&#39;t really a &lt;i&gt;strict &lt;/i&gt;or &lt;i&gt;rigorous&lt;/i&gt; derivation - as I just dealt with the Improper Integrals without taking limits and checking their convergence. This was intended just to get the general idea across.&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;To be continued...&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/8503466376546347248/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/evaluating-integral-of-gaussian.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/8503466376546347248'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/8503466376546347248'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/evaluating-integral-of-gaussian.html' title='Evaluating the integral of a Gaussian'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-5405052320633456362</id><published>2011-03-07T22:52:00.000-08:00</published><updated>2011-03-08T22:41:10.430-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="n-sphere"/><category scheme="http://www.blogger.com/atom/ns#" term="volume of an n-dimensional sphere"/><title type='text'>The Volume of an n-sphere</title><content type='html'>Here I present a (fairly common) derivation for the volume of an n sphere.&lt;br /&gt;
Where an n-sphere is defined by&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;$S^n=\left\{x \epsilon \mathbb{R}^{n+1}: ||x||)=r\right\}$&lt;/div&gt;&lt;br /&gt;
We first start by calling on what we already know;&lt;br /&gt;
&lt;br /&gt;
$V_{1}=2 \pi r$ for $S^0$ $V=\pi r^2$ for $S^{1}$ and $V=\frac{4}{3} \pi r^3$ for $S^2$ These can both be obtained most easily via usual methods of integrating in polar and spherical coordinates, respectively.&lt;br /&gt;
&lt;br /&gt;
By inspection - and&amp;nbsp;intuition&amp;nbsp;- we should think that the volume is proportional to $r^{n+1}$ i.e some constant times r to the power of the dimension we are in.&lt;br /&gt;
Therefore we should expect that the formula for the volume of a sphere in &lt;i&gt;m-dimensions&lt;/i&gt;&amp;nbsp;looks a little like&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;$V_{m}=\nu_{m} r^m$&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;where $\nu_{m}$ is the constant of proportionality that we are after.&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Hence the volume element (in &lt;i&gt;m-dimensions &lt;/i&gt;and spherical coordinates&lt;i&gt;)&lt;/i&gt;&amp;nbsp;is given by; $dV_{m}= m \nu_{m} r^{m-1} dr$&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Now this seems like a leap of faith, or unjustified - but let&#39;s take a look at some Gaussian Integrals;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I_m=\int \! e^{-\left(x_{1}^2+...+x_m^{2}\right)} dx_1....dx_m=$$ where the integral is over all of &amp;nbsp;$\mathbb{R}^m$&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;From our knowledge of a standard Gaussian Integral;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$I=\int_{- \infty}^{\infty} \! e^{-x^2} dx=\sqrt{\pi}$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;and recognising the fact that the $x_i$ are independent, we can factorise the integral;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I_m=\int \! e^{-x_1^2} dx_1...\int \! e^{-x_m^2} dx_m = I^m $$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Therefore $$I_m=\sqrt{\pi}^m = \pi^\frac{m}{2}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Now, transforming into &lt;i&gt;m-dimensional &lt;/i&gt;spherical coordinates so that;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$x_1^2+....+x_m^2=r^2$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Which gives $$I_m=\int \! e^{-r^2} dV_{m} $$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;and using our definition for the spherical volume element we got before;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$\int_{0}^{\infty} \! e^{-r^2} m\nu_m r^{m-1} dr=\pi^\frac{m}{2}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Taking out the variables which aren&#39;t dependent on &lt;i&gt;r&lt;/i&gt;&amp;nbsp;from the integrand we get;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$I_m=m\nu_m \int_{0}^{\infty} \! e^{-r^2} r^{m-1} dr =\pi^\frac{m}{2}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;You math geeks out there should recognise the form of the integral as somewhat close to the gamma function;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$\Gamma(z+1)= \int_{0}^{\infty} u^{z}e^{-u} du $$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Now, substituting $$u=r^2$$ then $$\frac{du}{dr}=2r$$ or in terms of u; $$\frac{du}{dr}=2\sqrt{u}$$&lt;br /&gt;
$$V_m=\nu_m m \int_{0}^{\infty} e^{-u}\left(\sqrt{u}\right)^{m-1}\frac{1}{2\sqrt{u}} du$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
$$\pi^{\frac{m}{2}}=\frac{\nu_m m}{2} \int_{0}^{\infty}e^{-u} \left(\sqrt{u}\right)^{m-2} du$$&lt;br /&gt;
$$=\frac{\nu_m m}{2} \int_{0}^{\infty}e^{-u} u^{\frac{m}{2}-1} du$$&lt;br /&gt;
Which we can almost assimilate with the above form of the Gamma function;&lt;br /&gt;
&lt;br /&gt;
A simple substitution provides us with;&lt;br /&gt;
$$\frac{m}{2}-1=z \rightarrow \frac{m}{2}=z+1$$&lt;br /&gt;
Hence $$\Gamma(z+1)= \int_{0}^{\infty} u^{z}e^{-u} du $$ becomes;&lt;br /&gt;
$$\Gamma(\frac{m}{2})=\int_{0}^{\infty} u^{\frac{m}{2}-1} e^{-u} du$$&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Therefore; $$\pi^{\frac{m}{2}}=\frac{ \nu_m m \Gamma(\frac{m}{2}) }{2}$$&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;So putting it all together, we recover our unknown coefficient $\nu_m$;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$\nu_m= \frac{\pi^\frac{m}{2}}{\frac{m}{2}\Gamma(\frac{m}{2})}$$&lt;/div&gt;&lt;br /&gt;
Or you can obtain an equivalent formula by looking at $$\Gamma(\frac{m}{2}+1)= \int_{0}^{\infty} u^{\frac{n}{2}} e^{-u} du $$ and integrating by parts to recognise that;&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;$$\Gamma(\frac{m}{2}+1)=\frac{m}{2}\Gamma(\frac{m}{2})$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;Hence putting it all together, we recover the &lt;i&gt;Volume of an n-dimensional sphere of radius r as;&lt;/i&gt;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$V_m=\frac{\pi^{\frac{m}{2}} r^m}{\frac{m}{2} \Gamma(\frac{m}{2})}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;= $$\frac{\pi^\frac{m}{2} r^m}{\Gamma(\frac{m}{2}+1)}$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Having done all that, it could be an interesting idea to see how the volume of the unit n-sphere changes as we increase the number of dimensions;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;In dimension 2; $$V=\pi$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;In dimension 3; $$V=\frac{4}{3}\pi$$&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;.&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;and so on.&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;Below is a plot of volume vs dimension for the unit sphere - constructed using the volume formula we obtained above;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&amp;nbsp; &lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj64bkqNpP4NEPeIOKSkIea2iqd6EYu80dKjWgFEVWAmHLMwMabUPXaxV4RuZWpxzVnj9X1Rri3dSxmqNHkGW7G-bzXZtgrPiJUZzz6FyTsNYw9Mj5yLveh2a_hQrUD1mEoirz3XBQ83s_W/s1600/nsphere.jpeg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;398&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj64bkqNpP4NEPeIOKSkIea2iqd6EYu80dKjWgFEVWAmHLMwMabUPXaxV4RuZWpxzVnj9X1Rri3dSxmqNHkGW7G-bzXZtgrPiJUZzz6FyTsNYw9Mj5yLveh2a_hQrUD1mEoirz3XBQ83s_W/s400/nsphere.jpeg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
I find it quite amazing that there is a maximum! That is that there is a point (around n=5) that when you start adding dimensions to the sphere; its volume &lt;i&gt;decreases&lt;/i&gt;!&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;b&gt;Final Word:&lt;/b&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;It may not seem like there are any real world applications for the use of n-dimensional spheres, but there actually are! In statistical mechanics, a system of N independent particles may be confined to the surface or within a volume of an N dimensional sphere in phase space (due to energy considerations)- where here we don&#39;t think of N as spatial dimensions, but &lt;i&gt;degrees of freedom. &lt;/i&gt;So when N becomes large (as it does in the thermodynamic limit) we are required to use the above formula and it is just as well that the volume decreases to zero as N becomes large, otherwise it would be indicating that the thermodynamic properties (which in general depend on the statistical behaviour of the particles) of our ensemble have would become infinite - which is an indication that something has gone wrong in the math!&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/5405052320633456362/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/volume-of-n-sphere.html#comment-form' title='15 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/5405052320633456362'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/5405052320633456362'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/volume-of-n-sphere.html' title='The Volume of an n-sphere'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj64bkqNpP4NEPeIOKSkIea2iqd6EYu80dKjWgFEVWAmHLMwMabUPXaxV4RuZWpxzVnj9X1Rri3dSxmqNHkGW7G-bzXZtgrPiJUZzz6FyTsNYw9Mj5yLveh2a_hQrUD1mEoirz3XBQ83s_W/s72-c/nsphere.jpeg" height="72" width="72"/><thr:total>15</thr:total></entry><entry><id>tag:blogger.com,1999:blog-83055021305463025.post-6107957762339288738</id><published>2011-03-04T04:30:00.000-08:00</published><updated>2011-03-08T22:27:50.532-08:00</updated><title type='text'>Introduction to the blog world</title><content type='html'>This is my first ever blog! Hello!&lt;br /&gt;
&lt;br /&gt;
I am currently enrolled in a Masters of Mathematics and Statistics - Majoring in Applied Maths and&amp;nbsp;I intend to use this as a place where I can use  $\LaTeX$&lt;br /&gt;
and write up some notes/workings outs from any problems that I&#39;m working on.&lt;br /&gt;
&lt;br /&gt;
This blog will also serve as a place to document some incoherent ramblings that fill my head from time to time.&lt;br /&gt;
&lt;br /&gt;
But currently it will mostly be a playground for me to get familiar with $$\LaTeX$$.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;&lt;b&gt;For Example;&lt;/b&gt;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;$$\Gamma(z)=\int_{0}^{\infty}t^{z-1}e^{-t}dt$$&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://edgeofabandon.blogspot.com/feeds/6107957762339288738/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/introduction-to-blog-world.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/6107957762339288738'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/83055021305463025/posts/default/6107957762339288738'/><link rel='alternate' type='text/html' href='http://edgeofabandon.blogspot.com/2011/03/introduction-to-blog-world.html' title='Introduction to the blog world'/><author><name>Incoherent Ramblings</name><uri>http://www.blogger.com/profile/16873840468463648925</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='20' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHcLSsms19l-BhkB_7ERI16u0ZRCOE_pe5_8ut3-rqZPJotlz8U1v9t0d1tsmaJ5PR-cVgl7SMgMNVW4BiB-gMVppQJtGYhdnjAdJ65jkh6s7ygso3kgA5lw1Lkz8ALw/s1600/220px-WPint.svg.png'/></author><thr:total>3</thr:total></entry></feed>