<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mathieu&#039;s log</title>
	<atom:link href="http://www.mblondel.org/journal/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mblondel.org/journal</link>
	<description>Machine Learning, Data Mining, Natural Language Processing…</description>
	<lastBuildDate>Mon, 16 Jan 2012 07:57:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Transparent system-wide proxy</title>
		<link>http://www.mblondel.org/journal/2011/06/27/transparent-system-wide-proxy/</link>
		<comments>http://www.mblondel.org/journal/2011/06/27/transparent-system-wide-proxy/#comments</comments>
		<pubDate>Sun, 26 Jun 2011 23:18:29 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Sysadmin]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=172</guid>
		<description><![CDATA[Proxies can be a powerful way to enforce anonymity or to bypass various kinds of restrictions on Internet (government censorship, regional contents, &#8230;). In this post, I&#8217;ll describe a simple technique to create a transparent proxy at the system level. It&#8217;s especially useful in cases when you want to make sure that all connections make [...]]]></description>
			<content:encoded><![CDATA[<p>Proxies can be a powerful way to enforce anonymity or to bypass various kinds of restrictions on Internet (government censorship, regional contents, &#8230;). In this post, I&#8217;ll describe a simple technique to create a transparent proxy at the system level. It&#8217;s especially useful in cases when you want to make sure that all connections make it through the proxy or when your application of interest doesn&#8217;t have proxy support. I don&#8217;t think this technique is that well-known, hence this post.<br />
<span id="more-172"></span></p>
<h3>1. Create SOCKS proxy with OpenSSH</h3>
<p>If you have a user account on a remote machine, the simplest way to create a proxy is to use the following command.</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">$ ssh -N -D 1080 username@serverhost</pre></div></div>

<p>It creates a <a href="http://en.wikipedia.org/wiki/SOCKS">SOCKS</a> proxy listening to port 1080 on your local machine. The main advantage of the SOCKS protocol is that it can route connections from any port between the client and the server.</p>
<h3>2. Forward connection transparently with iptables or ipfw</h3>
<p>Most modern browsers can let the user define a SOCKS proxy in their advanced networking preference section. Yet, many applications may not support the SOCKS protocol at all. The solution is to use system tools such as iptables (Linux) or ipfw (FreeBSD, OS X) to enforce the routing at the system level. For example, on OS X, I use the following command to redirect port 80 (HTTP).</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">$ sudo ipfw add 100 fwd 127.0.0.1,12345 dst-port 80</pre></div></div>

<h3>3. Redirect connections to SOCKS proxy with redsocks</h3>
<p>iptables and ipfw don&#8217;t have built-in support for the SOCKS protocol. It is thus necessary to use an additional program to transform the connections on the fly. This is where <a href="https://github.com/darkk/redsocks">redsocks</a> comes in.</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">$ redsocks -c config_file</pre></div></div>

<p>In the configuration file, you need to configure redsocks to listen to port 12345 and to redirect to port 1080. &#8220;generic&#8221; can be used as the redirector option. The github repository includes a sample configuration file. </p>
<p>And voila! We now have configured the system to transparently route connections for us. To summarize, here is the big picture:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">local machine -&gt; redsocks -&gt; SOCKS proxy -&gt; target server</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2011/06/27/transparent-system-wide-proxy/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Regularized Least Squares</title>
		<link>http://www.mblondel.org/journal/2011/02/09/regularized-least-squares/</link>
		<comments>http://www.mblondel.org/journal/2011/02/09/regularized-least-squares/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 14:20:28 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=135</guid>
		<description><![CDATA[Recently, I&#8217;ve contributed a bunch of improvements (sparse matrix support, classification, generalized cross-validation) to the ridge module in scikits.learn. Since I&#8217;m receiving good feedback regarding my posts on Machine Learning, I&#8217;m taking this as an opportunity to summarize some important points about Regularized Least Squares, and more precisely Ridge regression. Ridge regression Given a centered [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I&#8217;ve contributed a bunch of improvements (sparse matrix support, classification, generalized cross-validation) to the ridge module in <a href="http://scikit-learn.sourceforge.net/">scikits.learn</a>. Since I&#8217;m receiving good feedback regarding my posts on Machine Learning, I&#8217;m taking this as an opportunity to summarize some important points about Regularized Least Squares, and more precisely Ridge regression.</p>
<h3>Ridge regression</h3>
<p>Given a centered input <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D%5E%2A%20%5Cin%20%5Cmathbf%7BR%7D%5ED&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}^* \in \mathbf{R}^D' title='\mathbf{x}^* \in \mathbf{R}^D' class='latex' />, a linear regression model predicts the output <img src='http://s.wordpress.com/latex.php?latex=y%5E%2A%20%5Cin%20%5Cmathbf%7BR%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y^* \in \mathbf{R}' title='y^* \in \mathbf{R}' class='latex' /> by</p>
<img src='http://s.wordpress.com/latex.php?latex=y%5E%2A%20%3D%20f%28%5Cmathbf%7Bx%7D%5E%2A%29%20%3D%20%5Cmathbf%7Bx%7D%5E%2A%20%5Ccdot%20%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y^* = f(\mathbf{x}^*) = \mathbf{x}^* \cdot \mathbf{w}' title='y^* = f(\mathbf{x}^*) = \mathbf{x}^* \cdot \mathbf{w}' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D%20%5Cin%20%5Cmathbf%7BR%7D%5ED&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w} \in \mathbf{R}^D' title='\mathbf{w} \in \mathbf{R}^D' class='latex' /> is a weight vector.</p>
<p>Given a set of training instances <img src='http://s.wordpress.com/latex.php?latex=X%20%3D%20%28%5Cmathbf%7Bx%7D_1%2C%5Cdots%2C%5Cmathbf%7Bx%7D_N%29%5ET&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='X = (\mathbf{x}_1,\dots,\mathbf{x}_N)^T' title='X = (\mathbf{x}_1,\dots,\mathbf{x}_N)^T' class='latex' /> and its associated set of outputs <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D%20%3D%20%28y_1%2C%5Cdots%2Cy_N%29%5ET&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y} = (y_1,\dots,y_N)^T' title='\mathbf{y} = (y_1,\dots,y_N)^T' class='latex' />, the method of least-squares finds the weight vector <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> which minimizes the sum of square differences between the predictions and the actual labels. </p>
<img src='http://s.wordpress.com/latex.php?latex=L_%7BLS%7D%28%5Cmathbf%7Bw%7D%29%20%3D%20%5Csum_%7Bi%3D1%7D%5EN%20%28y_i%20-%20f%28%5Cmathbf%7Bx%7D_i%29%29%5E2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L_{LS}(\mathbf{w}) = \sum_{i=1}^N (y_i - f(\mathbf{x}_i))^2' title='L_{LS}(\mathbf{w}) = \sum_{i=1}^N (y_i - f(\mathbf{x}_i))^2' class='latex' />
<p>However, minizing the sum of square errors on the training set doesn&#8217;t necessarily mean that the model will do well on new data. For this reason, Ridge regression adds a regularization term, which controls the complexity of the weight vector. The objective function becomes </p>
<img src='http://s.wordpress.com/latex.php?latex=L_%7BRidge%7D%28%5Cmathbf%7Bw%7D%29%20%3D%20%5Csum_%7Bi%3D1%7D%5EN%20%28y_i%20-%20f%28%5Cmathbf%7Bx%7D_i%29%29%5E2%20%2B%20%5Cfrac%7B%5Clambda%7D%7B2%7D%20%5C%7C%5Cmathbf%7Bw%7D%5C%7C%5E2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L_{Ridge}(\mathbf{w}) = \sum_{i=1}^N (y_i - f(\mathbf{x}_i))^2 + \frac{\lambda}{2} \|\mathbf{w}\|^2' title='L_{Ridge}(\mathbf{w}) = \sum_{i=1}^N (y_i - f(\mathbf{x}_i))^2 + \frac{\lambda}{2} \|\mathbf{w}\|^2' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' /> is a parameter which controls the regularization strength. Minimizing <img src='http://s.wordpress.com/latex.php?latex=L_%7BRidge%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L_{Ridge}' title='L_{Ridge}' class='latex' /> is thus a trade-off between minimizing the sum of errors and keeping the weight vector simple (i.e., small). Put differently, by introducing some <em>bias</em> (the regularization), we are purposely limiting the freedom of the model and thus reducing the <em>variance</em> of the weight vector.  Regularization is a simple way to avoid overfitting and often improves the prediction accuracy on new data, especially if the training set is small.</p>
<p>Calculating the gradient of <img src='http://s.wordpress.com/latex.php?latex=L_%7BRidge%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L_{Ridge}' title='L_{Ridge}' class='latex' /> with respect to <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> and solving for <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' />, we find that <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> has a closed-form solution</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D%20%3D%20H%5E%7B-1%7D%20X%5ET%20%5Cmathbf%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w} = H^{-1} X^T \mathbf{y}' title='\mathbf{w} = H^{-1} X^T \mathbf{y}' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=H%20%3D%20%28X%5ET%20X%20%2B%20%5Clambda%20I%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='H = (X^T X + \lambda I)' title='H = (X^T X + \lambda I)' class='latex' />. Note that the matrix inverse is just notational convenience. In practice, we simply solve the corresponding system of linear equations <img src='http://s.wordpress.com/latex.php?latex=H%5Cmathbf%7Bw%7D%3D%20X%5ET%20%5Cmathbf%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='H\mathbf{w}= X^T \mathbf{y}' title='H\mathbf{w}= X^T \mathbf{y}' class='latex' />. Since <img src='http://s.wordpress.com/latex.php?latex=H&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='H' title='H' class='latex' /> is symmetric positive-definite, one typically first finds the <a href="http://en.wikipedia.org/wiki/Cholesky_decomposition">Cholesky decomposition</a> <img src='http://s.wordpress.com/latex.php?latex=H%3DLL%5ET&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='H=LL^T' title='H=LL^T' class='latex' />. Then since <img src='http://s.wordpress.com/latex.php?latex=L&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L' title='L' class='latex' /> is lower triangular, solving the system is simply a matter of applying <a href="http://en.wikipedia.org/wiki/Triangular_matrix#Forward_and_back_substitution">forward and backward substitution</a>. Another commonly used method is the <a href="http://en.wikipedia.org/wiki/Conjugate_gradient_method">conjugate gradient</a>.</p>
<p>Note that not only does regularization improve accuracy, it is often necessary because it makes <img src='http://s.wordpress.com/latex.php?latex=H&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='H' title='H' class='latex' /> invertible when <img src='http://s.wordpress.com/latex.php?latex=X%5ET%20X&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='X^T X' title='X^T X' class='latex' /> is not. See <a href="http://en.wikipedia.org/wiki/Tikhonov_regularization">Tikhonov regularization</a>.</p>
<h3>Kernel ridge</h3>
<p>As per the representer theorem, just like we did for <a href="http://www.mblondel.org/journal/2010/10/31/kernel-perceptron-in-python/">kernel perceptron</a>, we can replace <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> with <img src='http://s.wordpress.com/latex.php?latex=X%5ET%5Cboldsymbol%7B%5Calpha%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='X^T\boldsymbol{\alpha}' title='X^T\boldsymbol{\alpha}' class='latex' />. Substituting into <img src='http://s.wordpress.com/latex.php?latex=L_%7BRidge%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L_{Ridge}' title='L_{Ridge}' class='latex' /> then deriving with respect to <img src='http://s.wordpress.com/latex.php?latex=%5Cboldsymbol%7B%5Calpha%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\boldsymbol{\alpha}' title='\boldsymbol{\alpha}' class='latex' /> and solving for <img src='http://s.wordpress.com/latex.php?latex=%5Cboldsymbol%7B%5Calpha%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\boldsymbol{\alpha}' title='\boldsymbol{\alpha}' class='latex' />, we find</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cboldsymbol%7B%5Calpha%7D%20%3D%20G%5E%7B-1%7D%20%5Cmathbf%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\boldsymbol{\alpha} = G^{-1} \mathbf{y}' title='\boldsymbol{\alpha} = G^{-1} \mathbf{y}' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=G%20%3D%28K%20%2B%20%5Clambda%20I%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='G =(K + \lambda I)' title='G =(K + \lambda I)' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=K&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='K' title='K' class='latex' /> is the kernel matrix. The prediction function becomes</p>
<img src='http://s.wordpress.com/latex.php?latex=y%5E%2A%20%3D%20f%28%5Cmathbf%7Bx%7D%5E%2A%29%20%3D%20%5Csum_%7Bi%3D1%7D%5EN%20%5Calpha_i%20k%28%5Cmathbf%7Bx%7D%5E%2A%2C%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y^* = f(\mathbf{x}^*) = \sum_{i=1}^N \alpha_i k(\mathbf{x}^*,\mathbf{x}_i)' title='y^* = f(\mathbf{x}^*) = \sum_{i=1}^N \alpha_i k(\mathbf{x}^*,\mathbf{x}_i)' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=k&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='k' title='k' class='latex' /> is the kernel function. However, in contrast to SVM, <img src='http://s.wordpress.com/latex.php?latex=%5Cboldsymbol%7B%5Calpha%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\boldsymbol{\alpha}' title='\boldsymbol{\alpha}' class='latex' /> is not sparse. This means that the whole training set needs to be used at prediction time. </p>
<h3>Multiple output</h3>
<p>So far we have considered the case when there is only one output <img src='http://s.wordpress.com/latex.php?latex=y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y' title='y' class='latex' /> per instance. We can easily extend to the <img src='http://s.wordpress.com/latex.php?latex=M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M' title='M' class='latex' /> output case. To do that, we simply need to solve <img src='http://s.wordpress.com/latex.php?latex=HW%3D%20X%5ET%20Y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='HW= X^T Y' title='HW= X^T Y' class='latex' />, where <img src='http://s.wordpress.com/latex.php?latex=W&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='W' title='W' class='latex' /> is <img src='http://s.wordpress.com/latex.php?latex=D%20%5Ctimes%20M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D \times M' title='D \times M' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=Y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Y' title='Y' class='latex' /> is <img src='http://s.wordpress.com/latex.php?latex=N%20%5Ctimes%20M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N \times M' title='N \times M' class='latex' />. Note that the Cholesky decomposition needs to be computed only once. Since it takes <img src='http://s.wordpress.com/latex.php?latex=O%28D%5E3%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(D^3)' title='O(D^3)' class='latex' /> time, it is much more efficient to solve <img src='http://s.wordpress.com/latex.php?latex=HW%3DX%5ET%20Y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='HW=X^T Y' title='HW=X^T Y' class='latex' /> directly than to solve <img src='http://s.wordpress.com/latex.php?latex=H%5Cmathbf%7Bw%7D%3DX%5ET%20%5Cmathbf%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='H\mathbf{w}=X^T \mathbf{y}' title='H\mathbf{w}=X^T \mathbf{y}' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M' title='M' class='latex' /> times. </p>
<h3>Classification</h3>
<p>M-class classification can easily be achieved by combining multiple-output ridge regression and the 1-of-M coding scheme. This is sometimes referred by some authors as Regularized Least Square Classifier (RLSC). Concretely, we just need to construct a matrix <img src='http://s.wordpress.com/latex.php?latex=Y&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Y' title='Y' class='latex' /> by setting <img src='http://s.wordpress.com/latex.php?latex=Y_%7Bij%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='Y_{ij}' title='Y_{ij}' class='latex' /> to <img src='http://s.wordpress.com/latex.php?latex=1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='1' title='1' class='latex' /> if the <img src='http://s.wordpress.com/latex.php?latex=i%5E%7Bth%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='i^{th}' title='i^{th}' class='latex' /> instance is associated with the <img src='http://s.wordpress.com/latex.php?latex=j%5E%7Bth%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='j^{th}' title='j^{th}' class='latex' /> label and to <img src='http://s.wordpress.com/latex.php?latex=-1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='-1' title='-1' class='latex' /> otherwise. Then prediction is just a matter of  taking the most confident label for each instance, just like one-vs-all SVM.</p>
<p>Note that the square error is sometimes criticized for classification because it penalizes overconfident predictions. For example, predicting 3 instead of 1 is penalized just as much as predicting -1 instead of 1, even though 3 would still give the correct prediction and -1 would not. However, in practice, RLSC often achieves accuracy on a par with other classifiers such as SVM.</p>
<h3>Efficient leave-one-out cross-validation</h3>
<p>Estimating <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' /> is a model selection problem, usually performed by k-fold or leave-one-out cross-validation. The naive approach to leave-one-out is to learn <img src='http://s.wordpress.com/latex.php?latex=N&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N' title='N' class='latex' /> models by holding out one instance at a time. Obviously, this is computationally very expensive. Fortunately, there exist nice computational tricks. Below, I show how to use them in the kernel case but they can equally be applied to the normal case.</p>
<p>The first trick is to take the eigendecomposition </p>
<img src='http://s.wordpress.com/latex.php?latex=K%3DQ%20%5CLambda%20Q%5ET.&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='K=Q \Lambda Q^T.' title='K=Q \Lambda Q^T.' class='latex' />
<p>Using basic linear algebra, we obtain</p>
<img src='http://s.wordpress.com/latex.php?latex=G%5E%7B-1%7D%3DQ%28%5CLambda%20%2B%20%5Clambda%20I%29%5E%7B-1%7D%20Q%5ET.&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='G^{-1}=Q(\Lambda + \lambda I)^{-1} Q^T.' title='G^{-1}=Q(\Lambda + \lambda I)^{-1} Q^T.' class='latex' />
<p>Since <img src='http://s.wordpress.com/latex.php?latex=%28%5CLambda%20%2B%20%5Clambda%20I%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(\Lambda + \lambda I)' title='(\Lambda + \lambda I)' class='latex' /> is diagonal, it can easily be inverted by taking its reciprocal. Therefore by first paying the price of an eigendecomposition, <img src='http://s.wordpress.com/latex.php?latex=G&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='G' title='G' class='latex' /> can thus be inverted inexpensively for many different <img src='http://s.wordpress.com/latex.php?latex=%5Clambda&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\lambda' title='\lambda' class='latex' />.</p>
<p>Let <img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i)' title='f_i(\mathbf{x}_i)' class='latex' /> be the prediction value when the model was fitted to all training instances but <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_i' title='\mathbf{x}_i' class='latex' />. The second trick, sometimes called generalized cross-validation, will allow us to calculate the <img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i)' title='f_i(\mathbf{x}_i)' class='latex' /> almost for free.</p>
<p>First, let <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D%5Ei&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}^i' title='\mathbf{y}^i' class='latex' /> be the label vector of the model when <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_i' title='\mathbf{x}_i' class='latex' /> is held out.</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D%5Ei%20%3D%20%28y_1%2C%5Cdots%2Cf_i%28%5Cmathbf%7Bx%7D_i%29%2C%5Cdots%2Cy_N%29%5ET&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}^i = (y_1,\dots,f_i(\mathbf{x}_i),\dots,y_N)^T' title='\mathbf{y}^i = (y_1,\dots,f_i(\mathbf{x}_i),\dots,y_N)^T' class='latex' />
<p>When we replace <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}' title='\mathbf{y}' class='latex' /> by <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D%5Ei&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}^i' title='\mathbf{y}^i' class='latex' /> in <img src='http://s.wordpress.com/latex.php?latex=L_%7BRidge%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L_{Ridge}' title='L_{Ridge}' class='latex' />, clearly, <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx_i%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x_i}' title='\mathbf{x_i}' class='latex' /> doesn&#8217;t affect the solution (as desired) and we have</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cboldsymbol%7B%5Calpha%7D%5Ei%20%3D%20G%5E%7B-1%7D%20%5Cmathbf%7By%7D%5Ei&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\boldsymbol{\alpha}^i = G^{-1} \mathbf{y}^i' title='\boldsymbol{\alpha}^i = G^{-1} \mathbf{y}^i' class='latex' /><br />
<br/><br />
<img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29%20%3D%20%28K%20%5Cboldsymbol%7B%5Calpha%7D%5Ei%29_i.&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i) = (K \boldsymbol{\alpha}^i)_i.' title='f_i(\mathbf{x}_i) = (K \boldsymbol{\alpha}^i)_i.' class='latex' />
<p>However, this is a circular definition, since <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D%5Ei&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}^i' title='\mathbf{y}^i' class='latex' /> itself depends on <img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i)' title='f_i(\mathbf{x}_i)' class='latex' />. We can calculate the difference with <img src='http://s.wordpress.com/latex.php?latex=f%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(\mathbf{x}_i)' title='f(\mathbf{x}_i)' class='latex' />, which will allow us to factorize <img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i)' title='f_i(\mathbf{x}_i)' class='latex' />.</p>
<img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29%20-%20f%28%5Cmathbf%7Bx%7D_i%29%20%3D%20%28K%20G%5E%7B-1%7D%20%5Cmathbf%7By%7D%5Ei%29_i%20-%20%28KG%5E%7B-1%7D%5Cmathbf%7By%7D%29_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i) - f(\mathbf{x}_i) = (K G^{-1} \mathbf{y}^i)_i - (KG^{-1}\mathbf{y})_i' title='f_i(\mathbf{x}_i) - f(\mathbf{x}_i) = (K G^{-1} \mathbf{y}^i)_i - (KG^{-1}\mathbf{y})_i' class='latex' />
<p>By definition, the <img src='http://s.wordpress.com/latex.php?latex=i%5E%7Bth%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='i^{th}' title='i^{th}' class='latex' /> element of <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D%5Ei&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}^i' title='\mathbf{y}^i' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7By%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{y}' title='\mathbf{y}' class='latex' /> are <img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i)' title='f_i(\mathbf{x}_i)' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=y_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_i' title='y_i' class='latex' />, respectively. Therefore,</p>
<img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29%20-%20f%28%5Cmathbf%7Bx%7D_i%29%20%3D%20%28K%20G%5E%7B-1%7D%29_%7Bii%7D%20%28f_i%28%5Cmathbf%7Bx%7D_i%29%20-%20y_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f_i(\mathbf{x}_i) - f(\mathbf{x}_i) = (K G^{-1})_{ii} (f_i(\mathbf{x}_i) - y_i)' title='f_i(\mathbf{x}_i) - f(\mathbf{x}_i) = (K G^{-1})_{ii} (f_i(\mathbf{x}_i) - y_i)' class='latex' />
<p>and finally, by simplifying, we obtain</p>
<img src='http://s.wordpress.com/latex.php?latex=f_i%28%5Cmathbf%7Bx%7D_i%29%20%3D%20%5Cfrac%7Bf%28%5Cmathbf%7Bx%7D_i%29%20-%28K%20G%5E%7B-1%7D%29_%7Bii%7D%20y_i%7D%7B1%20-%20%28K%20G%5E%7B-1%7D%29_%7Bii%7D%7D.&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='f_i(\mathbf{x}_i) = \frac{f(\mathbf{x}_i) -(K G^{-1})_{ii} y_i}{1 - (K G^{-1})_{ii}}.' title='f_i(\mathbf{x}_i) = \frac{f(\mathbf{x}_i) -(K G^{-1})_{ii} y_i}{1 - (K G^{-1})_{ii}}.' class='latex' />
<p>Similar computational tricks exist for Gaussian Process Regression as well.</p>
<h3>References</h3>
<p><a href="http://www.mit.edu/~9.520/spring07/Classes/rlsslides.pdf">Regularized Least Squares</a>, Ryan Rifkin</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2011/02/09/regularized-least-squares/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Kernel Perceptron in Python</title>
		<link>http://www.mblondel.org/journal/2010/10/31/kernel-perceptron-in-python/</link>
		<comments>http://www.mblondel.org/journal/2010/10/31/kernel-perceptron-in-python/#comments</comments>
		<pubDate>Sun, 31 Oct 2010 05:36:32 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=129</guid>
		<description><![CDATA[The Perceptron (Rosenblatt, 1957) is one of the oldest and simplest Machine Learning algorithms. It&#8217;s also trivial to kernelize, which makes it an ideal candidate to gain insights on kernel methods. Perceptron The Perceptron predicts the class of an input with the function where sign(y) = +1 if y > 0 and -1 if y [...]]]></description>
			<content:encoded><![CDATA[<p>The Perceptron (Rosenblatt, 1957) is one of the oldest and simplest Machine Learning algorithms. It&#8217;s also trivial to <em>kernelize</em>, which makes it an ideal candidate to gain insights on kernel methods.</p>
<h3>Perceptron</h3>
<p>The Perceptron predicts the class of an input <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D%20%5Cin%20%5Cmathcal%7BX%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x} \in \mathcal{X}' title='\mathbf{x} \in \mathcal{X}' class='latex' /> with the function</p>
<img src='http://s.wordpress.com/latex.php?latex=f%28%5Cmathbf%7Bx%7D%29%20%3D%20sign%28%5Cmathbf%7Bw%7D%5Ccdot%5Cphi%28%5Cmathbf%7Bx%7D%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(\mathbf{x}) = sign(\mathbf{w}\cdot\phi(\mathbf{x}))' title='f(\mathbf{x}) = sign(\mathbf{w}\cdot\phi(\mathbf{x}))' class='latex' />
<p>where sign(y) = +1 if y > 0 and -1 if y < 0, <img src='http://s.wordpress.com/latex.php?latex=%5Cphi&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi' title='\phi' class='latex' /> is a feature-space transformation and  <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> is a feature weight vector. If  <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}' title='\mathbf{x}' class='latex' /> is already a feature vector and a projection to another space is not needed, then <img src='http://s.wordpress.com/latex.php?latex=%5Cphi%28%5Cmathbf%7Bx%7D%29%3D%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi(\mathbf{x})=\mathbf{x}' title='\phi(\mathbf{x})=\mathbf{x}' class='latex' />.</p>
<p>Given a data set comprising <img src='http://s.wordpress.com/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='n' title='n' class='latex' /> training examples <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_1%2C%5Cdots%2C%5Cmathbf%7Bx%7D_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_1,\dots,\mathbf{x}_n' title='\mathbf{x}_1,\dots,\mathbf{x}_n' class='latex' /> and their corresponding labels <img src='http://s.wordpress.com/latex.php?latex=y_1%2C%5Cdots%2Cy_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_1,\dots,y_n' title='y_1,\dots,y_n' class='latex' />, where <img src='http://s.wordpress.com/latex.php?latex=y_n%20%5Cin%20%5C%7B-1%2C%2B1%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_n \in \{-1,+1\}' title='y_n \in \{-1,+1\}' class='latex' />, the Perceptron makes a prediction for each <img src='http://s.wordpress.com/latex.php?latex=%28%5Cmathbf%7Bx%7D_i%2C%20y_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(\mathbf{x}_i, y_i)' title='(\mathbf{x}_i, y_i)' class='latex' /> using the current estimate of <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' />. When the prediction is correct (equal to the label <img src='http://s.wordpress.com/latex.php?latex=y_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_i' title='y_i' class='latex' />), the algorithm jumps to the next example. When the prediction is incorrect, in order to correct for the mistake, if <img src='http://s.wordpress.com/latex.php?latex=y_i%20%3D%20%2B1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_i = +1' title='y_i = +1' class='latex' /> then <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> is incremented by <img src='http://s.wordpress.com/latex.php?latex=%5Cphi%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi(\mathbf{x}_i)' title='\phi(\mathbf{x}_i)' class='latex' />, otherwise it is decremented by <img src='http://s.wordpress.com/latex.php?latex=%5Cphi%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi(\mathbf{x}_i)' title='\phi(\mathbf{x}_i)' class='latex' />. Since <img src='http://s.wordpress.com/latex.php?latex=y_i%20%5Cin%20%5C%7B-1%2C%2B1%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_i \in \{-1,+1\}' title='y_i \in \{-1,+1\}' class='latex' />, the update rule is thus:</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D%20%3D%20%5Cmathbf%7Bw%7D%20%2B%20y_i%20%5Cphi%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w} = \mathbf{w} + y_i \phi(\mathbf{x}_i)' title='\mathbf{w} = \mathbf{w} + y_i \phi(\mathbf{x}_i)' class='latex' />
<p>This procedure can be repeated by doing <img src='http://s.wordpress.com/latex.php?latex=T&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='T' title='T' class='latex' /> passes over the data set. Ideally <img src='http://s.wordpress.com/latex.php?latex=T&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='T' title='T' class='latex' /> must be optimized. This can be done efficiently by measuring the performance after each pass on a validation set.</p>
<p><center><img src="http://www.mblondel.org/images/perceptron_update.png" /></center><br />
Figure 1: The decision boundary (hyperplane), to which <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> is normal, partitions the vector space into two sets, one for each class. An update changes the direction of the decision boundary to correct for the incorrect prediction. (From this <a href="http://www.cse.wustl.edu/~mgeorg/readPapers/kernelTrick/kernels.pdf">document</a>)</p>
<p><center><img src="http://www.mblondel.org/images/perceptron_linear.png" /></center><br />
Figure 2: Decision boundary in the linear case. </p>
<h3>Kernel Perceptron</h3>
<p>From the update rule above, we clearly see that, if <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> is initialized to the zero vector, it is a linear combination of the training examples.</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D%20%3D%20%5Csum_i%20%5Calpha_i%20y_i%20%5Cphi%28%5Cmathbf%7Bx%7D_i%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w} = \sum_i \alpha_i y_i \phi(\mathbf{x}_i)' title='\mathbf{w} = \sum_i \alpha_i y_i \phi(\mathbf{x}_i)' class='latex' />
<p>Injecting <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> into the prediction function <img src='http://s.wordpress.com/latex.php?latex=f%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(\mathbf{x})' title='f(\mathbf{x})' class='latex' />, we get</p>
<img src='http://s.wordpress.com/latex.php?latex=f%28%5Cmathbf%7Bx%7D%29%20%3D%20sign%28%5Csum_i%20%5Calpha_i%20y_i%20%5Cphi%28%5Cmathbf%7Bx%7D_i%29%5Ccdot%5Cphi%28%5Cmathbf%7Bx%7D%29%29%20%3D%20sign%28%5Csum_i%20%5Calpha_i%20y_i%20K%28%5Cmathbf%7Bx%7D_i%2C%5Cmathbf%7Bx%7D%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='f(\mathbf{x}) = sign(\sum_i \alpha_i y_i \phi(\mathbf{x}_i)\cdot\phi(\mathbf{x})) = sign(\sum_i \alpha_i y_i K(\mathbf{x}_i,\mathbf{x}))' title='f(\mathbf{x}) = sign(\sum_i \alpha_i y_i \phi(\mathbf{x}_i)\cdot\phi(\mathbf{x})) = sign(\sum_i \alpha_i y_i K(\mathbf{x}_i,\mathbf{x}))' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=K%28%5Cmathbf%7Bx%7D_i%2C%5Cmathbf%7Bx%7D%29%20%3D%20%5Cphi%28%5Cmathbf%7Bx%7D_i%29%5Ccdot%5Cphi%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='K(\mathbf{x}_i,\mathbf{x}) = \phi(\mathbf{x}_i)\cdot\phi(\mathbf{x})' title='K(\mathbf{x}_i,\mathbf{x}) = \phi(\mathbf{x}_i)\cdot\phi(\mathbf{x})' class='latex' /> is a Mercer kernel.</p>
<p>The update rule for when a mistake is made predicting <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_i' title='\mathbf{x}_i' class='latex' /> now simply becomes</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Calpha_i%20%3D%20%5Calpha_i%20%2B%201&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\alpha_i = \alpha_i + 1' title='\alpha_i = \alpha_i + 1' class='latex' />
<p>i.e., <img src='http://s.wordpress.com/latex.php?latex=%5Calpha_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\alpha_i' title='\alpha_i' class='latex' /> is the number of times a mistake has been made with respect to <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_i' title='\mathbf{x}_i' class='latex' />.</p>
<p>A few remarks:</p>
<ul>
<li>Instead of learning a weight vector <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> with respect to features, we&#8217;re now learning a weight vector <img src='http://s.wordpress.com/latex.php?latex=%5Cboldsymbol%7B%5Calpha%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\boldsymbol{\alpha}' title='\boldsymbol{\alpha}' class='latex' /> with respect to examples. The feature and kernel representations are duals (they are interchangeable).</li>
<li>To predict the class of an input <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}' title='\mathbf{x}' class='latex' />, we need to store the training examples <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_i' title='\mathbf{x}_i' class='latex' />. Kernel methods are memory-based methods, like k-NN. However, we only need to store examples for which a mistake has been made, i.e. <img src='http://s.wordpress.com/latex.php?latex=%7B%5Calpha%7D_i%20%5Cneq%200%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='{\alpha}_i \neq 0 ' title='{\alpha}_i \neq 0 ' class='latex' />. In the context of Support Vector Machines (SVMs), these are called support vectors. SVMs, however, not only store examples for which a mistake has been made, they also store examples that lie inside the margin, i.e. <img src='http://s.wordpress.com/latex.php?latex=y_i%20%28%5Cmathbf%7Bw%7D%20%5Ccdot%20%5Cphi%28%5Cmathbf%7Bx%7D_i%29%29%20%5Cle%201&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y_i (\mathbf{w} \cdot \phi(\mathbf{x}_i)) \le 1' title='y_i (\mathbf{w} \cdot \phi(\mathbf{x}_i)) \le 1' class='latex' />. (See Figure 4 from my <a href="http://www.mblondel.org/journal/2010/09/19/support-vector-machines-in-python/">post on SVMs</a>)</li>
<li>In the online learning setting, the number of support vectors can grow and grow as more mistakes are made. The Forgetron is an extension of the Kernel Perceptron which can learn with a &#8220;memory budget&#8221;. When the budget is exceeded, some support vectors are &#8220;forgotten&#8221;.</li>
<li>For some kinds of objects like sequences, trees and graphs, it might be difficult to map objects to feature vectors while it is easy to come up with a similarity measure <img src='http://s.wordpress.com/latex.php?latex=K%28%5Cmathbf%7Bx%7D_i%2C%5Cmathbf%7Bx%7D_j%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='K(\mathbf{x}_i,\mathbf{x}_j)' title='K(\mathbf{x}_i,\mathbf{x}_j)' class='latex' /> between any two objects <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_i&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_i' title='\mathbf{x}_i' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_j&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_j' title='\mathbf{x}_j' class='latex' />. In this case, kernel methods are very useful, since they can be used &#8220;as is&#8221;.</li>
</ul>
<p>For a brief and intuitive introduction to kernel classifiers, I highly recommend <a href="http://128.148.32.110/courses/csci1950-f/docs/lecture_10-27.pdf">these slides</a>, by Mark Johnson.</p>
<p><center><img src="http://www.mblondel.org/images/perceptron_gaussian.png" /></center><br />
Figure 3: Decision boundary when using a gaussian kernel. Green dots indicate support vectors.</p>
<p>The voted and average Perceptrons are two straightforward extensions to the Perceptron, which for some applications are competitive with SVMs. For details, see &#8220;Large Margin Classiﬁcation Using the Perceptron Algorithm&#8221; by Freund and Schapire.</p>
<h3>Source</h3>
<p><a href="http://gist.github.com/656147">http://gist.github.com/656147</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/10/31/kernel-perceptron-in-python/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Support Vector Machines in Python</title>
		<link>http://www.mblondel.org/journal/2010/09/19/support-vector-machines-in-python/</link>
		<comments>http://www.mblondel.org/journal/2010/09/19/support-vector-machines-in-python/#comments</comments>
		<pubDate>Sun, 19 Sep 2010 14:07:15 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=128</guid>
		<description><![CDATA[Support Vector Machines (SVM) are the state-of-the-art classifier in many applications and have become ubiquitous thanks to the wealth of open-source libraries implementing them. However, you learn a lot more by actually doing than by just reading, so let&#8217;s play a little bit with SVM in Python! To make it easier to read, we will [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Support_vector_machine">Support Vector Machines</a> (SVM) are the state-of-the-art classifier in many applications and have become ubiquitous thanks to the wealth of open-source libraries implementing them. However, you learn a lot more by actually doing than by just reading, so let&#8217;s play a little bit with SVM in Python! To make it easier to read, we will use the same notation as in Christopher Bishop&#8217;s book &#8220;Pattern Recognition and Machine Learning&#8221;.</p>
<h3>Maximum margin</h3>
<p>In SVM, the class of an input vector <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}' title='\mathbf{x}' class='latex' /> can be decided by evaluating the sign of <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x})' title='y(\mathbf{x})' class='latex' />.</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.1%29%7Ey%28%5Cmathbf%7Bx%7D%29%20%3D%20%5Cmathbf%7Bw%7D%5ET%5Cphi%28%5Cmathbf%7Bx%7D%29%2Bb&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.1)~y(\mathbf{x}) = \mathbf{w}^T\phi(\mathbf{x})+b' title='(7.1)~y(\mathbf{x}) = \mathbf{w}^T\phi(\mathbf{x})+b' class='latex' />
<p>If <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D%29%20%3E%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x}) &gt; 0' title='y(\mathbf{x}) &gt; 0' class='latex' /> we assign <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}' title='\mathbf{x}' class='latex' />  to class +1 and if <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D%29%20%3C%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x}) &lt; 0' title='y(\mathbf{x}) &lt; 0' class='latex' />, we assign it to class -1. Here <img src='http://s.wordpress.com/latex.php?latex=%5Cphi%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi(\mathbf{x})' title='\phi(\mathbf{x})' class='latex' /> is a feature-space transformation, which can map <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}' title='\mathbf{x}' class='latex' /> to a space of higher, possibly infinite, dimensions.</p>
<p>Given a data set comprising <img src='http://s.wordpress.com/latex.php?latex=N&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N' title='N' class='latex' /> input vectors <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_1%2C%5Cdots%2C%5Cmathbf%7Bx%7D_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_1,\dots,\mathbf{x}_n' title='\mathbf{x}_1,\dots,\mathbf{x}_n' class='latex' /> and their corresponding labels <img src='http://s.wordpress.com/latex.php?latex=t_1%2C%5Cdots%2Ct_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='t_1,\dots,t_n' title='t_1,\dots,t_n' class='latex' />, where <img src='http://s.wordpress.com/latex.php?latex=t_n%20%5Cin%20%5C%7B-1%2C%2B1%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='t_n \in \{-1,+1\}' title='t_n \in \{-1,+1\}' class='latex' />, we would like to find <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> such that it explains the training data: <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D_n%29%20%5Cge%201&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x}_n) \ge 1' title='y(\mathbf{x}_n) \ge 1' class='latex' /> when <img src='http://s.wordpress.com/latex.php?latex=t_n%3D%2B1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='t_n=+1' title='t_n=+1' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D_n%29%20%5Cle%201&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x}_n) \le 1' title='y(\mathbf{x}_n) \le 1' class='latex' /> when <img src='http://s.wordpress.com/latex.php?latex=t_n%3D-1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='t_n=-1' title='t_n=-1' class='latex' />. This can be rewritten in a single constraint:</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.5%29%7Et_n%20%28%5Cmathbf%7Bw%7D%5ET%5Cphi%28%5Cmathbf%7Bx%7D%29%2Bb%29%20%5Cge%201%2C%7En%3D1%2C%5Cdots%2CN&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.5)~t_n (\mathbf{w}^T\phi(\mathbf{x})+b) \ge 1,~n=1,\dots,N' title='(7.5)~t_n (\mathbf{w}^T\phi(\mathbf{x})+b) \ge 1,~n=1,\dots,N' class='latex' />
<p>In addition, <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> are chosen so that the distance between the decision boundary <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D%5ET%5Cphi%28%5Cmathbf%7Bx%7D%29%2Bb%3D0&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}^T\phi(\mathbf{x})+b=0' title='\mathbf{w}^T\phi(\mathbf{x})+b=0' class='latex' /> (a line in the 2-d case, a plane in the 3-d case, a hyperplane in the n-d case) and the closest points to it is maximized. This distance is called the margin, hence the name <em>maximum margin</em> classifier. Geometrically, the margin is found to be <img src='http://s.wordpress.com/latex.php?latex=2%2F%5C%7C%5Cmathbf%7Bw%7D%5C%7C%5E2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2/\|\mathbf{w}\|^2' title='2/\|\mathbf{w}\|^2' class='latex' /> and so the maximum margin problem can be equivalently expressed as the minimization problem:</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.6%29%7Earg%20min_%7B%5Cmathbf%7Bw%7D%2Cb%7D%5Cfrac%7B1%7D%7B2%7D%5C%7C%5Cmathbf%7Bw%7D%5C%7C%5E2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.6)~arg min_{\mathbf{w},b}\frac{1}{2}\|\mathbf{w}\|^2' title='(7.6)~arg min_{\mathbf{w},b}\frac{1}{2}\|\mathbf{w}\|^2' class='latex' />
<p>subject to constraint (7.5).</p>
<p><img src="http://www.mblondel.org/images/svm_linear.png" /></p>
<p>Figure 1: The linearly separable case. The decision line is the plain line and the margin is the gap between the two dotted lines. Only 3 support vectors (green dots) out of 180 training examples are necessary.</p>
<h3>Dual representation</h3>
<p>Since this is a constrained optimization problem, we can introduce <a href="http://en.wikipedia.org/wiki/Lagrange_multipliers">Lagrange multipliers</a> <img src='http://s.wordpress.com/latex.php?latex=a_n%20%5Cge%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='a_n \ge 0' title='a_n \ge 0' class='latex' /> (one per training example), differentiate the Lagrangian function with respect to <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> and inject the solution back in the Lagrangian function (equations (7.7) to (7.9) in Bishop&#8217;s book), so that it depends only on the Lagrange multipliers. Doing so, we find that the maximum margin equivalently emerges from the maximization of</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.10%29%7E%5Ctilde%7BL%7D%28%5Cmathbf%7Ba%7D%29%20%3D%20%5Csum_%7Bn%3D1%7D%5ENa_n-%5Cfrac%7B1%7D%7B2%7D%5Csum_%7Bn%3D1%7D%5EN%5Csum_%7Bm%3D1%7D%5EN%20a_n%20a_m%20t_n%20t_m%20k%28%5Cmathbf%7Bx%7D_n%2C%5Cmathbf%7Bx%7D_m%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.10)~\tilde{L}(\mathbf{a}) = \sum_{n=1}^Na_n-\frac{1}{2}\sum_{n=1}^N\sum_{m=1}^N a_n a_m t_n t_m k(\mathbf{x}_n,\mathbf{x}_m)' title='(7.10)~\tilde{L}(\mathbf{a}) = \sum_{n=1}^Na_n-\frac{1}{2}\sum_{n=1}^N\sum_{m=1}^N a_n a_m t_n t_m k(\mathbf{x}_n,\mathbf{x}_m)' class='latex' />
<p>subject to the constraints</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.11%29%7Ea_n%20%5Cge%200%2C%7En%3D1%2C%5Cdots%2CN&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.11)~a_n \ge 0,~n=1,\dots,N' title='(7.11)~a_n \ge 0,~n=1,\dots,N' class='latex' /><br />
</br><br />
<img src='http://s.wordpress.com/latex.php?latex=%287.12%29%7E%5Csum_%7Bn%3D1%7D%5ENa_nt_n%20%3D%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.12)~\sum_{n=1}^Na_nt_n = 0' title='(7.12)~\sum_{n=1}^Na_nt_n = 0' class='latex' />
<p>This is the so-called <em>dual representation</em> and is a <a href="http://en.wikipedia.org/wiki/Quadratic_programming">quadratic programming</a> (QP) problem. <img src='http://s.wordpress.com/latex.php?latex=k%28%5Cmathbf%7Bx%7D_n%2C%5Cmathbf%7Bx%7D_m%29%3D%20%5Cphi%28%5Cmathbf%7Bx%7D_n%29%5ET%5Cphi%28%5Cmathbf%7Bx%7D_m%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='k(\mathbf{x}_n,\mathbf{x}_m)= \phi(\mathbf{x}_n)^T\phi(\mathbf{x}_m)' title='k(\mathbf{x}_n,\mathbf{x}_m)= \phi(\mathbf{x}_n)^T\phi(\mathbf{x}_m)' class='latex' /> is called the kernel function.</p>
<p>Similarly to the objective function, <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x})' title='y(\mathbf{x})' class='latex' /> can also be re-expressed solely in terms of the Lagrange multipliers.</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.13%29%7Ey%28%5Cmathbf%7Bx%7D%29%3D%20%5Csum_%7Bn%3D1%7D%5EN%20a_n%20t_n%20k%28%5Cmathbf%7Bx%7D%2C%5Cmathbf%7Bx%7D_n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.13)~y(\mathbf{x})= \sum_{n=1}^N a_n t_n k(\mathbf{x},\mathbf{x}_n)' title='(7.13)~y(\mathbf{x})= \sum_{n=1}^N a_n t_n k(\mathbf{x},\mathbf{x}_n)' class='latex' />
<p>The important thing to notice here is that we&#8217;ve gone from a sum over <img src='http://s.wordpress.com/latex.php?latex=M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M' title='M' class='latex' /> dimensions (the <a href="http://en.wikipedia.org/wiki/Dot_product">dot product</a> in equation (7.1)) to a sum over <img src='http://s.wordpress.com/latex.php?latex=N&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N' title='N' class='latex' /> points. This may seem like a disadvantage as the number of training examples <img src='http://s.wordpress.com/latex.php?latex=N&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N' title='N' class='latex' /> is usually bigger than the number of dimensions <img src='http://s.wordpress.com/latex.php?latex=M&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M' title='M' class='latex' />. However, this is very useful and is called the <a href="http://en.wikipedia.org/wiki/Kernel_trick">kernel trick</a>: this allows to use SVM, originally a linear classifier, to solve a non-linear problem by mapping the original non-linear observations into a higher-dimensional space, but without explicitly computing <img src='http://s.wordpress.com/latex.php?latex=%5Cphi%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi(\mathbf{x})' title='\phi(\mathbf{x})' class='latex' />.</p>
<p>In many situations, only a small proportion of the Lagrange multipliers <img src='http://s.wordpress.com/latex.php?latex=a_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='a_n' title='a_n' class='latex' /> will be non-zero, therefore we only need to store the corresponding training examples <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}_n' title='\mathbf{x}_n' class='latex' />. These are called the <em>support vectors</em> and this is why SVMs are sometimes called sparse kernel machines.</p>
<p>That being said, in the linear case, i.e. when <img src='http://s.wordpress.com/latex.php?latex=%5Cphi%28%5Cmathbf%7Bx%7D%29%3D%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\phi(\mathbf{x})=\mathbf{x}' title='\phi(\mathbf{x})=\mathbf{x}' class='latex' />, it is faster to directly compute <img src='http://s.wordpress.com/latex.php?latex=y%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='y(\mathbf{x})' title='y(\mathbf{x})' class='latex' /> from equation (7.1). <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> can be computed in terms of the Lagrange multipliers by equations (7.8) and (7.18) in Bishop&#8217;s book.</p>
<p><img src="http://www.mblondel.org/images/svm_non_linear.png" /></p>
<p>Figure 2: The non-linearly separable case. Example of a gaussian kernel with parameter sigma=5.0. Perfect prediction is achieved on the held-out 20 data points.</p>
<h3>QP solver</h3>
<p>We want to find the Lagrange multipliers <img src='http://s.wordpress.com/latex.php?latex=a_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='a_n' title='a_n' class='latex' /> maximizing equation (7.10) subject to the constraints (7.11) and (7.11). This can be done by a standard QP solver such as <a href="http://abel.ee.ucla.edu/cvxopt/">cvxopt</a>.</p>
<p>Minimize</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cfrac%7B1%7D%7B2%7D%20%5Cmathbf%7Bx%7D%5ET%20P%5Cmathbf%7Bx%7D%20%2B%20%5Cmathbf%7Bq%7D%5ET%20%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\frac{1}{2} \mathbf{x}^T P\mathbf{x} + \mathbf{q}^T \mathbf{x}' title='\frac{1}{2} \mathbf{x}^T P\mathbf{x} + \mathbf{q}^T \mathbf{x}' class='latex' />
<p>subject to</p>
<img src='http://s.wordpress.com/latex.php?latex=G%5Cmathbf%7Bx%7D%20%5Cleq%20%5Cmathbf%20h&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='G\mathbf{x} \leq \mathbf h' title='G\mathbf{x} \leq \mathbf h' class='latex' /> (inequality constraint)<br />
</br><br />
<img src='http://s.wordpress.com/latex.php?latex=A%5Cmathbf%7Bx%7D%20%3D%20%5Cmathbf%20b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='A\mathbf{x} = \mathbf b' title='A\mathbf{x} = \mathbf b' class='latex' /> (equality constraint)</p>
<p>The unknow is <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{x}' title='\mathbf{x}' class='latex' />, which in our case correspond to the Lagrange multipliers <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Ba%7D%3Da_1%2C%5Cdots%2Ca_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{a}=a_1,\dots,a_n' title='\mathbf{a}=a_1,\dots,a_n' class='latex' />. We just need to rework the formulation a little bit to use matrix notation and be a minimization (hence the -1 multiplicative factors).</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Gram matrix</span>
K = np.<span style="color: black;">zeros</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>n_samples, n_samples<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>n_samples<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">for</span> j <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>n_samples<span style="color: black;">&#41;</span>:
        K<span style="color: black;">&#91;</span>i,j<span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">kernel</span><span style="color: black;">&#40;</span>X<span style="color: black;">&#91;</span>i<span style="color: black;">&#93;</span>, X<span style="color: black;">&#91;</span>j<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
&nbsp;
P = cvxopt.<span style="color: black;">matrix</span><span style="color: black;">&#40;</span>np.<span style="color: black;">outer</span><span style="color: black;">&#40;</span>y,y<span style="color: black;">&#41;</span> <span style="color: #66cc66;">*</span> K<span style="color: black;">&#41;</span>
q = cvxopt.<span style="color: black;">matrix</span><span style="color: black;">&#40;</span>np.<span style="color: black;">ones</span><span style="color: black;">&#40;</span>n_samples<span style="color: black;">&#41;</span> <span style="color: #66cc66;">*</span> -<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
A = cvxopt.<span style="color: black;">matrix</span><span style="color: black;">&#40;</span>y, <span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,n_samples<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
b = cvxopt.<span style="color: black;">matrix</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0.0</span><span style="color: black;">&#41;</span>
G = cvxopt.<span style="color: black;">matrix</span><span style="color: black;">&#40;</span>np.<span style="color: black;">diag</span><span style="color: black;">&#40;</span>np.<span style="color: black;">ones</span><span style="color: black;">&#40;</span>n_samples<span style="color: black;">&#41;</span> <span style="color: #66cc66;">*</span> -<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
h = cvxopt.<span style="color: black;">matrix</span><span style="color: black;">&#40;</span>np.<span style="color: black;">zeros</span><span style="color: black;">&#40;</span>n_samples<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Solve QP problem</span>
solution = cvxopt.<span style="color: black;">solvers</span>.<span style="color: black;">qp</span><span style="color: black;">&#40;</span>P, q, G, h, A, b<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Lagrange multipliers</span>
a = np.<span style="color: black;">ravel</span><span style="color: black;">&#40;</span>solution<span style="color: black;">&#91;</span><span style="color: #483d8b;">'x'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Note here that <img src='http://s.wordpress.com/latex.php?latex=P&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P' title='P' class='latex' /> is a <img src='http://s.wordpress.com/latex.php?latex=N%20%5Ctimes%20N&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='N \times N' title='N \times N' class='latex' /> matrix. Thus, a standard QP solver can&#8217;t be used for a large number of training examples, as P needs to be stored in memory. There exists a number of algorithms in order to decompose the original QP problem into smaller QP problems that target only a few training samples at a time. One such algorithm is <a href="http://en.wikipedia.org/wiki/Sequential_Minimal_Optimization">Sequential Minimal Optimization</a> (SMO). One advantage of SMO is that the smaller QP problems can be solved analytically and so SMO doesn&#8217;t even need a QP solver.</p>
<h3>Soft margin</h3>
<p>The problem with the formulation we have used thus far is that it doesn&#8217;t allow for misclassification of the training examples. This can lead to poor generalization if there is overlap between the distributions of the two classes. To solve this problem, we can rework constraint (7.5) as</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%287.20%29%7Et_n%20y%28%5Cmathbf%7Bx%7D_n%29%20%5Cge%201%20-%20%5Cxi_n%2C%7En%3D1%2C%5Cdots%2CN&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.20)~t_n y(\mathbf{x}_n) \ge 1 - \xi_n,~n=1,\dots,N' title='(7.20)~t_n y(\mathbf{x}_n) \ge 1 - \xi_n,~n=1,\dots,N' class='latex' /><br />
</br><br />
<img src='http://s.wordpress.com/latex.php?latex=%5Cxi_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\xi_n' title='\xi_n' class='latex' /> are called slack variables and are introduced to allow the misclassification of some examples. If <img src='http://s.wordpress.com/latex.php?latex=%5Cxi_n%3D0&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\xi_n=0' title='\xi_n=0' class='latex' />, the corresponding training example is correctly classified. If <img src='http://s.wordpress.com/latex.php?latex=0%20%3C%20%5Cxi_n%20%5Cle%201&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='0 &lt; \xi_n \le 1' title='0 &lt; \xi_n \le 1' class='latex' />, the training example lies inside the margin but is still on the correct side of the decision boundary. If <img src='http://s.wordpress.com/latex.php?latex=%5Cxi_n%20%3E%201&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\xi_n &gt; 1' title='\xi_n &gt; 1' class='latex' />, the training example is misclassified. Equation (7.6) then becomes</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%287.21%29%7EC%20%5Csum_%7Bn%3D1%7D%5EN%20%5Cxi_n%20%2B%20%5Cfrac%7B1%7D%7B2%7D%5C%7C%5Cmathbf%7Bw%7D%5C%7C%5E2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.21)~C \sum_{n=1}^N \xi_n + \frac{1}{2}\|\mathbf{w}\|^2' title='(7.21)~C \sum_{n=1}^N \xi_n + \frac{1}{2}\|\mathbf{w}\|^2' class='latex' /><br />
</br></p>
<p><img src='http://s.wordpress.com/latex.php?latex=C%20%3E%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='C &gt; 0' title='C &gt; 0' class='latex' /> is the parameter which controls the trade-off between the slack variable penality and the margin. Again, we can introduce Lagrange multipliers, derive the Lagrangian function with respect to <img src='http://s.wordpress.com/latex.php?latex=%5Cmathbf%7Bw%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathbf{w}' title='\mathbf{w}' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Cxi_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\xi_n' title='\xi_n' class='latex' />, and inject the solutions back in the Lagragian function (equations (7.22) to (7.31) in Bishop&#8217;s book).</p>
<p><img src='http://s.wordpress.com/latex.php?latex=%287.32%29%7E%5Ctilde%7BL%7D%28%5Cmathbf%7Ba%7D%29%20%3D%20%5Csum_%7Bn%3D1%7D%5ENa_n-%5Cfrac%7B1%7D%7B2%7D%5Csum_%7Bn%3D1%7D%5EN%5Csum_%7Bm%3D1%7D%5EN%20a_n%20a_m%20t_n%20t_m%20k%28%5Cmathbf%7Bx%7D_n%2C%5Cmathbf%7Bx%7D_m%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.32)~\tilde{L}(\mathbf{a}) = \sum_{n=1}^Na_n-\frac{1}{2}\sum_{n=1}^N\sum_{m=1}^N a_n a_m t_n t_m k(\mathbf{x}_n,\mathbf{x}_m)' title='(7.32)~\tilde{L}(\mathbf{a}) = \sum_{n=1}^Na_n-\frac{1}{2}\sum_{n=1}^N\sum_{m=1}^N a_n a_m t_n t_m k(\mathbf{x}_n,\mathbf{x}_m)' class='latex' />
<p>Which is identical to the hard margin case! The constraints become:</p>
<img src='http://s.wordpress.com/latex.php?latex=%287.33%29%7E0%20%5Cle%20a_n%20%5Cle%20C&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.33)~0 \le a_n \le C' title='(7.33)~0 \le a_n \le C' class='latex' /><br />
</br><br />
<img src='http://s.wordpress.com/latex.php?latex=%287.34%29%7E%5Csum_%7Bn%3D1%7D%5EN%20a_n%20t_n%20%3D%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(7.34)~\sum_{n=1}^N a_n t_n = 0' title='(7.34)~\sum_{n=1}^N a_n t_n = 0' class='latex' />
<p>Interestingly, the slack variables <img src='http://s.wordpress.com/latex.php?latex=%5Cxi_n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\xi_n' title='\xi_n' class='latex' /> have vanished and the only difference with the hard margin is that the inequality constraint now has an upper bound, <img src='http://s.wordpress.com/latex.php?latex=C&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='C' title='C' class='latex' />.</p>
<p>The attentive reader will have noticed that the inequality constraints in cvxopt have an upper bound but no lower bound.</p>
<img src='http://s.wordpress.com/latex.php?latex=G%5Cmathbf%7Bx%7D%20%5Cleq%20%5Cmathbf%20h&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='G\mathbf{x} \leq \mathbf h' title='G\mathbf{x} \leq \mathbf h' class='latex' />
<p>The trick is to rewrite constraint (7.33) as a system of inequations, in matrix notation. Example with 2 training examples:</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cbegin%7Bpmatrix%7D-1%20%26%200%20%5C%5C%200%20%26%20-1%20%5C%5C%201%20%26%200%20%20%5C%5C%200%20%26%201%5Cend%7Bpmatrix%7D%5Cbegin%7Bpmatrix%7Da_1%5C%5C%20a_2%5Cend%7Bpmatrix%7D%20%5Cle%20%5Cbegin%7Bpmatrix%7D0%20%5C%5C%200%20%5C%5C%20C%20%5C%5C%20C%5Cend%7Bpmatrix%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\begin{pmatrix}-1 &amp; 0 \\ 0 &amp; -1 \\ 1 &amp; 0  \\ 0 &amp; 1\end{pmatrix}\begin{pmatrix}a_1\\ a_2\end{pmatrix} \le \begin{pmatrix}0 \\ 0 \\ C \\ C\end{pmatrix}' title='\begin{pmatrix}-1 &amp; 0 \\ 0 &amp; -1 \\ 1 &amp; 0  \\ 0 &amp; 1\end{pmatrix}\begin{pmatrix}a_1\\ a_2\end{pmatrix} \le \begin{pmatrix}0 \\ 0 \\ C \\ C\end{pmatrix}' class='latex' />
<p><img src="http://www.mblondel.org/images/svm_hard.png" /></p>
<p>Figure 3: The hard margin case. 180 vectors out of 180 are support vectors! And the classifier only achieves 11 correct predictions out of 20, on held-out data.</p>
<p><img src="http://www.mblondel.org/images/svm_soft.png" /></p>
<p>Figure 4: The soft margin case (C=0.1). 36 vectors out of 180 are support vectors. The classifier achieves 19 correct predictions out of 20!</p>
<h3>Source</h3>
<p><a href="http://gist.github.com/586753">http://gist.github.com/586753</a></p>
<h3>References</h3>
<p>Pattern Recognition and Machine Learning, Christopher Bishop, 2006.</p>
<p><a href="http://d.hatena.ne.jp/aidiary/20100503/1272889097">ソフトマージンSVM</a>, 人工知能に関する断想録</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/09/19/support-vector-machines-in-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Latent Dirichlet Allocation in Python</title>
		<link>http://www.mblondel.org/journal/2010/08/21/latent-dirichlet-allocation-in-python/</link>
		<comments>http://www.mblondel.org/journal/2010/08/21/latent-dirichlet-allocation-in-python/#comments</comments>
		<pubDate>Sat, 21 Aug 2010 20:52:00 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=127</guid>
		<description><![CDATA[Like Latent Semantic Analysis (LSA) and probabilistic LSA (pLSA) &#8211; see my previous post &#8220;LSA and pLSA in Python&#8220;, Latent Dirichlet Allocation (LDA) is an algorithm which, given a collection of documents and nothing more (no supervision needed), can uncover the &#8220;topics&#8221; expressed by documents in that collection. LDA can be seen as a Bayesian [...]]]></description>
			<content:encoded><![CDATA[<p>Like Latent Semantic Analysis (LSA) and probabilistic LSA (pLSA) &#8211; see my previous post &#8220;<a href="http://www.mblondel.org/journal/2010/06/13/lsa-and-plsa-in-python/">LSA and pLSA in Python</a>&#8220;, Latent Dirichlet Allocation (LDA) is an algorithm which, given a collection of documents and nothing more (no supervision needed), can uncover the &#8220;topics&#8221; expressed by documents in that collection. LDA can be seen as a <a href="http://en.wikipedia.org/wiki/Bayesian_inference">Bayesian</a> extension of pLSA. </p>
<p>As Blei, the author of LDA, points out, the topic proportions in pLSA are tied with the training documents. This is problematic: 1) the number of parameters grows linearly with the number of training documents, which can cause serious <a href="http://en.wikipedia.org/wiki/Overfitting">overfitting</a> 2) it is difficult to generalize to new documents and requires so-called &#8220;folding-in&#8221;. LDA fixes those issues by being a fully generative model: where pLSA uses a matrix of P(topic|document) probabilities, LDA uses a distribution over topics.</p>
<p>To date, there exists several parameter estimation schemes for LDA: variational Bayes, expectation propagation and Gibbs sampling. I&#8217;ve chosen to implement the latter. It has first been described in a paper entitled &#8220;Finding scientific topics&#8221;, by Griffiths and Steyvers.</p>
<h3>Artificial data</h3>
<p>As with all model-based algorithms, during the early development phase, it is useful to work with artificial data, generated by following the model assumptions. In the case of LDA (and pLSA), the core assumption is that words (w) in documents are generated by mixture of topics (z). In other words, the probability of a word is:</p>
<img src='http://s.wordpress.com/latex.php?latex=P%28w%29%20%3D%20%5Csum_%7Bz%7D%20P%28w%7Cz%29%20P%28z%29&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='P(w) = \sum_{z} P(w|z) P(z)' title='P(w) = \sum_{z} P(w|z) P(z)' class='latex' />
<p>The generative process can be summarized as follows: 1) set the topic proportions once for all when the collection is instantiated and 2) for each document and for as many words as needed, sample a topic from the topic distribution and sample a word from the word distribution of the selected topic. Obviously, this is only an approximation of how documents are created in reality.</p>
<p>To generate an artificial dataset, we can fix the word distribution of each topic and then generate documents as explained above. Since we generated documents by sticking to the generative assumption of the model, if the algorithm is correctly implemented, it should be able to recover the word distribution of each topic, from the generated documents.</p>
<h3>Graphical example</h3>
<p>To gain insight and intuition, we can reuse the graphical example from Griffiths and Steyvers&#8217; paper. </p>
<p>In the <a href="http://en.wikipedia.org/wiki/Bag_of_words_model">bag-of-words model</a>, documents are represented by vectors of dimension <img src='http://s.wordpress.com/latex.php?latex=V&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='V' title='V' class='latex' />, where <img src='http://s.wordpress.com/latex.php?latex=V&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='V' title='V' class='latex' /> is the vocabulary size. Moreover, an image of size <img src='http://s.wordpress.com/latex.php?latex=%5Csqrt%7BV%7D%20%5Ctimes%20%5Csqrt%7BV%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\sqrt{V} \times \sqrt{V}' title='\sqrt{V} \times \sqrt{V}' class='latex' /> has <img src='http://s.wordpress.com/latex.php?latex=V&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='V' title='V' class='latex' /> pixels: it can thus be stored as a string/vector of length/size <img src='http://s.wordpress.com/latex.php?latex=V&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='V' title='V' class='latex' />. This means that a document in the bag-of-words model can be represented as an image, where pixels correspond to words and pixel intensities correspond to word counts!</p>
<p>As put previously, we first need to fix the word distribution of each topic. Let&#8217;s arbitrarily create <strong>10</strong> topics.</p>
<p><strong>5</strong> with &#8220;vertical&#8221; bars:</p>
<table border="0" cellspacing="10">
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic0.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic1.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic2.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic3.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic4.png" style="border:1px solid" /></td>
</tr>
</table>
<p>and another <strong>5</strong> with &#8220;horizontal&#8221; bars:</p>
<table border="0" cellspacing="10">
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic5.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic6.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic7.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic8.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic9.png" style="border:1px solid" /></td>
</tr>
</table>
<p>Each topic distribution is represented by a <strong>5&#215;5</strong> image, so the vocabulary is of size <strong>25</strong>. Black pixels correspond to words that the topic will never possibly generate. White pixels correspond to words that the topic can generate with probability 1/5.</p>
<p>Now let&#8217;s generate <strong>500</strong> documents using the generative process previously described. Here are 3 examples of such generated documents.</p>
<table border="0" cellspacing="10">
<tr>
<td><img src="http://www.mblondel.org/images/lda/doc0.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/doc1.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/doc2.png" style="border:1px solid" /></td>
</tr>
</table>
<p>We clearly see bars emerging from the documents and can thus confirm that documents are mixtures of topics.</p>
<p>We can now use the generated documents as training data. If the Gibbs sampler is correctly implemented, we should be able to recover the original topics. Here are the results for the 1st, 6th and 26th iterations. The number between brackets is the log-likelihood.</p>
<p>1st iteration (-278541.7835):</p>
<table border="0" cellspacing="10">
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic0-0.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-1.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-2.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-3.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-4.png" style="border:1px solid" /></td>
</tr>
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic0-5.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-6.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-7.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-8.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic0-9.png" style="border:1px solid" /></td>
</tr>
</table>
<p>5th iteration (-165139.56193):</p>
<table border="0" cellspacing="10">
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic5-0.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-1.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-2.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-3.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-4.png" style="border:1px solid" /></td>
</tr>
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic5-5.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-6.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-7.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-8.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic5-9.png" style="border:1px solid" /></td>
</tr>
</table>
<p>[...]</p>
<p>26th iteration (-129272.328181):</p>
<table border="0" cellspacing="10">
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic25-0.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-1.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-2.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-3.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-4.png" style="border:1px solid" /></td>
</tr>
<tr>
<td><img src="http://www.mblondel.org/images/lda/topic25-5.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-6.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-7.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-8.png" style="border:1px solid" /></td>
<td><img src="http://www.mblondel.org/images/lda/topic25-9.png" style="border:1px solid" /></td>
</tr>
</table>
<p>After a few iterations, we see that the algorithm recovered the topics correctly. Also, the log-likelihood increases: as the number of iterations increases, it becomes more and more likely that the model generated the data. The fact that it works pretty well is not surprising: the data used were generated by sticking to the model assumptions.</p>
<h3>Gibbs sampling</h3>
<p>The <a href="http://en.wikipedia.org/wiki/Gibbs_sampling">Gibbs sampler</a> used is said to be collapsed: the parameters of interest are not sampled directly. Instead we sample the topic assignments and the parameters can be computed in terms of those.</p>
<p>It is not necessarily obvious from the equation of the full conditional distribution (from which the topic assignments are sampled) but the sampler is naturally sparse: it doesn&#8217;t need to iterate over words with zero-count. This is a nice property, given that sampling algorithms are often considered slow.</p>
<h3>Source code</h3>
<p><a href="http://gist.github.com/542786">http://gist.github.com/542786</a></p>
<p>Fairly readable and compact code but to be considered a toy implementation.</p>
<h3>Useful Resources</h3>
<h4>MCMC</h4>
<p>- &#8220;<a href="http://videolectures.net/mlss09uk_murray_mcmc/">MCMC lecture at MLSS09</a>&#8221; (Iain Murray). Nice for a first general overview and the insights.</p>
<p>- &#8220;Gibbs sampling for the uninitiated&#8221; (Resnik and Hardisty). Nice for a first general overview and the insights.</p>
<p>- &#8220;Pattern Recognition and Machine Learning&#8221; (Bishop), Chapters 8 and 11 on graphical models and sampling methods. Excellent chapters.</p>
<p>- &#8220;<a href="http://users.aims.ac.za/~ioana/">Review Course: Markov Chains and Monte Carlo Methods</a>&#8221; (Cosma and Evers). Very nice free online course and solutions to exercises in Python and R!</p>
<h4>LDA</h4>
<p>- &#8220;Latent Dirichlet Allocation&#8221; (Blei et al, 2003). By Blei himself.</p>
<p>- &#8220;Finding scientific topics&#8221; (Griffiths and Steyvers). Insightful comments and nice intuitive graphical example.</p>
<p>- &#8220;Parameter Estimation for text analysis&#8221; (Heinrich). Very nice introduction to Bayesian thinking. Pseudo-code for the LDA Gibbs sampler.</p>
<p>- &#8220;On an equivalence between PLSI and LDA&#8221; (Girolami and Kaban). Connections between pLSA and LDA.</p>
<p>- &#8220;Integrating Out Multinomial Parameters in Latent Dirichlet Allocation and Naive Bayes for Collapsed Gibbs Sampling&#8221; (Carpenter). Very detailed, step-by-step derivation of the collapsed Gibbs samplers for LDA and NB.</p>
<p>- &#8220;Distributed Gibbs Sampling of Latent Dirichlet Allocation: The Gritty Details&#8221; (Wang). Insightful comments and pseudo-code of the LDA Gibbs sampler.</p>
<h4>Other Python implementations</h4>
<p>- <a href="http://github.com/nrolland/pyLDA">nrolland&#8217;s pyLDA</a>. Works fine but mixes Python-style and Numpy-style.</p>
<p>- <a href="http://github.com/alextp/pylda">alextp&#8217;s pylda</a>. Numpy-style but not tested.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/08/21/latent-dirichlet-allocation-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Semi-supervised Naive Bayes in Python</title>
		<link>http://www.mblondel.org/journal/2010/06/21/semi-supervised-naive-bayes-in-python/</link>
		<comments>http://www.mblondel.org/journal/2010/06/21/semi-supervised-naive-bayes-in-python/#comments</comments>
		<pubDate>Mon, 21 Jun 2010 17:47:50 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=126</guid>
		<description><![CDATA[Expectation-Maximization The Expectation-Maximization (EM) algorithm is a popular algorithm in statistics and machine learning to estimate the parameters of a model that depends on latent variables. (A latent variable is a variable that is not expressed in the dataset and thus that you can&#8217;t directly count. For example, in pLSA, the document topics z are [...]]]></description>
			<content:encoded><![CDATA[<h3>Expectation-Maximization</h3>
<p>The <a href="http://en.wikipedia.org/wiki/Expectation-maximization_algorithm">Expectation-Maximization</a> (EM) algorithm is a popular algorithm in statistics and machine learning to estimate the parameters of a model that depends on latent variables. (A latent variable is a variable that is not expressed in the dataset and thus that you can&#8217;t directly count. For example, in <a href="http://www.mblondel.org/journal/2010/06/13/lsa-and-plsa-in-python/">pLSA</a>, the document topics z are latent variables.) EM is very intuitive. It works by pretending that we know what we&#8217;re looking for: the model parameters. First, we make an initial guess, which can be either random or &#8220;our best bet&#8221;. Then, in the E-step, we use our current model parameters to estimate some &#8220;measures&#8221;, the ones we would have used to compute the parameters, had they been available to us. In the M-step, we use these measures to compute the model parameters. The beauty of EM is that by iteratively repeating these two steps, the algorithm will provably converge to a local maximum for the likelihood that the model generated the data.</p>
<h3>Naive Bayes trained with EM</h3>
<p>In their paper &#8220;Semi-supervised Text Classification Using EM&#8221;, Nigam et al. describe how to use EM to train a Naive Bayes classifier in a <a href="http://en.wikipedia.org/wiki/Semi-supervised_learning">semi-supervised</a> fashion, that is with both labeled and unlabeled data. The algorithm is very intuitive:</p>
<ul>
<li>Train a classifier with your labeled data</li>
<li>While the model likelihood increases:
<ul>
<li>E-step: Use your current classifier to find P(c|x) for all classes c and all unlabeled examples x. These can be thought as probabilistic/fractional labels.</li>
<li>M-step: Train your classifier with the union of your labeled and probabilistically-labeled data.</li>
</ul>
</ul>
<p>The hope is that using (abundantly available) unlabeled data, in addition to (labor-intensive) labeled data, improves the quality of the classifier.</p>
<h3>Code</h3>
<p>I made a simple implementation of it in Python + Numpy. The code is fairly optimized.</p>
<p>$ git clone http://www.mblondel.org/code/seminb.git</p>
<p><a href="http://www.mblondel.org/gitweb?p=seminb.git">web interface</a></p>
<h3>Implementation details</h3>
<p>Here are implementation details that were not mentioned in the original paper and that I found necessary to get a correct implementation.</p>
<p>Naive Bayes is called naive because of the (obviously wrong) assumption that words are conditionally independent given the class:</p>
<img src='http://s.wordpress.com/latex.php?latex=P%28x_i%7Cc_j%29%20%3D%20%5Cprod_%7Bt%7D%5EV%20P%28w_t%7Cc_j%29%5E%7Bx_%7Bit%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='P(x_i|c_j) = \prod_{t}^V P(w_t|c_j)^{x_{it}}' title='P(x_i|c_j) = \prod_{t}^V P(w_t|c_j)^{x_{it}}' class='latex' />
<p>However, since the vocabulary size V can be pretty big and the probabilities P(w|c) can be pretty small, P(x|c) can quickly exceed the precision of the computer and become zero. The solution is to perform the computations in the log domain:</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Clog%20P%28x_i%7Cc_j%29%20%3D%20%5Csum_%7Bt%7D%5EV%20x_%7Bit%7D%20%5Clog%20P%28w_t%7Cc_j%29&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='\log P(x_i|c_j) = \sum_{t}^V x_{it} \log P(w_t|c_j)' title='\log P(x_i|c_j) = \sum_{t}^V x_{it} \log P(w_t|c_j)' class='latex' />
<p>To turn around P(x|c), we use Bayes&#8217;rule:</p>
<img src='http://s.wordpress.com/latex.php?latex=P%28y_i%3Dc_j%7Cx_i%29%20%3D%20%5Cfrac%7BP%28c_j%29P%28x_i%7Cc_j%29%7D%7BP%28x_i%29%7D%20%3D%20%5Cfrac%7BP%28c_j%29P%28x_i%7Cc_j%29%7D%7B%5Csum_k%20P%28c_k%29P%28x_i%7Cc_k%29%7D&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='P(y_i=c_j|x_i) = \frac{P(c_j)P(x_i|c_j)}{P(x_i)} = \frac{P(c_j)P(x_i|c_j)}{\sum_k P(c_k)P(x_i|c_k)}' title='P(y_i=c_j|x_i) = \frac{P(c_j)P(x_i|c_j)}{P(x_i)} = \frac{P(c_j)P(x_i|c_j)}{\sum_k P(c_k)P(x_i|c_k)}' class='latex' />
<p>By posing <img src='http://s.wordpress.com/latex.php?latex=z_j%20%3D%20%5Clog%20P%28c_j%29%20%2B%20%5Clog%20P%28x_i%7Cc_j%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='z_j = \log P(c_j) + \log P(x_i|c_j)' title='z_j = \log P(c_j) + \log P(x_i|c_j)' class='latex' />, we get:</p>
<img src='http://s.wordpress.com/latex.php?latex=P%28y_i%3Dc_j%7Cx_i%29%20%3D%20%5Cfrac%7Be%5E%7Bz_j%7D%7D%7B%5Csum_k%20e%5E%7Bz_k%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='P(y_i=c_j|x_i) = \frac{e^{z_j}}{\sum_k e^{z_k}}' title='P(y_i=c_j|x_i) = \frac{e^{z_j}}{\sum_k e^{z_k}}' class='latex' />
<p>This is the <a href="http://en.wikipedia.org/wiki/Softmax_activation_function">softmax</a> function. However, we are back to our initial problem because, since the <img src='http://s.wordpress.com/latex.php?latex=z_j&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='z_j' title='z_j' class='latex' /> are likely to tend to -inf, the exponentials are likely to in turn underflow. The trick is to multiply the numerator and denominator by the same constant <img src='http://s.wordpress.com/latex.php?latex=e%5E%7B-m%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='e^{-m}' title='e^{-m}' class='latex' />:</p>
<img src='http://s.wordpress.com/latex.php?latex=P%28y_i%3Dc_j%7Cx_i%29%20%3D%20%5Cfrac%7Be%5E%7Bz_j-m%7D%7D%7B%5Csum_k%20e%5E%7Bz_k-m%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='P(y_i=c_j|x_i) = \frac{e^{z_j-m}}{\sum_k e^{z_k-m}}' title='P(y_i=c_j|x_i) = \frac{e^{z_j-m}}{\sum_k e^{z_k-m}}' class='latex' />
<p>Setting m to <img src='http://s.wordpress.com/latex.php?latex=max_j%7Ez_j&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='max_j~z_j' title='max_j~z_j' class='latex' />, the <img src='http://s.wordpress.com/latex.php?latex=z_j-m&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='z_j-m' title='z_j-m' class='latex' /> values will get closer to zero. The rationale for this is that computation of the exponential overflows earlier and is less precise for big values (positive or negative) than for small values.</p>
<p>This trick will improve the situation quite a lot but in case this is not enough:</p>
<img src='http://s.wordpress.com/latex.php?latex=P%28y_i%3Dc_j%7Cx_i%29%20%3D%20%5Cbegin%7Bcases%7D%200%2C%20%26%20%5Cmbox%7Bif%20%7D%20%20z_j%20-%20m%20%20%5Cle%20t%20%20%5C%5C%20%5Cfrac%7Be%5E%7Bz_j-m%7D%7D%7B%5Csum_%7B%5C%7Bk%7E%3A%7Ez_k-m%20%3E%20t%5C%7D%7D%20e%5E%7Bz_k-m%7D%7D%2C%20%20%26%20%5Cmbox%7Botherwise%7D%20%5Cend%7Bcases%7D&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='P(y_i=c_j|x_i) = \begin{cases} 0, &amp; \mbox{if }  z_j - m  \le t  \\ \frac{e^{z_j-m}}{\sum_{\{k~:~z_k-m &gt; t\}} e^{z_k-m}},  &amp; \mbox{otherwise} \end{cases}' title='P(y_i=c_j|x_i) = \begin{cases} 0, &amp; \mbox{if }  z_j - m  \le t  \\ \frac{e^{z_j-m}}{\sum_{\{k~:~z_k-m &gt; t\}} e^{z_k-m}},  &amp; \mbox{otherwise} \end{cases}' class='latex' />
<p>This sets the exponentials to zero when <img src='http://s.wordpress.com/latex.php?latex=e%5E%7Bz_j-m%7D%20%5Cle%20e%5Et&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='e^{z_j-m} \le e^t' title='e^{z_j-m} \le e^t' class='latex' />. For t=-10, this is 0.000045. Equivalently this corresponds to setting the exponentials to zero when <img src='http://s.wordpress.com/latex.php?latex=e%5E%7Bz_j%7D%20%5Cle%20e%5E%7Bt%2Bm%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='e^{z_j} \le e^{t+m}' title='e^{z_j} \le e^{t+m}' class='latex' />. Since both t and and m are negative, this shows that subtracting the maximum m, as explained before, does help improving the precision.</p>
<h3>Reference</h3>
<blockquote><p>Kamal Nigam, Andrew McCallum and Tom Mitchell. Semi-supervised Text Classification Using EM. In Chapelle, O., Zien, A., and Scholkopf, B. (Eds.) Semi-Supervised Learning. MIT Press: Boston. 2006.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/06/21/semi-supervised-naive-bayes-in-python/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>LSA and pLSA in Python</title>
		<link>http://www.mblondel.org/journal/2010/06/13/lsa-and-plsa-in-python/</link>
		<comments>http://www.mblondel.org/journal/2010/06/13/lsa-and-plsa-in-python/#comments</comments>
		<pubDate>Sun, 13 Jun 2010 17:42:58 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Natural Language Processing]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=125</guid>
		<description><![CDATA[Latent Semantic Analysis (LSA) and its probabilistic counterpart pLSA are two well known techniques in Natural Language Processing that aim to analyze the co-occurrences of terms in a corpus of documents in order to find hidden/latent factors, regarded as topics or concepts. Since the number of topics/concepts is usually greatly inferior to the number of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Latent_semantic_analysis">Latent Semantic Analysis</a> (LSA) and its <a href="http://en.wikipedia.org/wiki/Probabilistic_latent_semantic_analysis">probabilistic counterpart</a> pLSA are two well known techniques in Natural Language Processing that aim to analyze the co-occurrences of terms in a corpus of documents in order to find hidden/latent factors, regarded as topics or concepts. Since the number of topics/concepts is usually greatly inferior to the number of words and since it is not necessary to know the document categories/classes, LSA and pLSA are thus <a href="http://en.wikipedia.org/wiki/Unsupervised_learning">unsupervised</a> <a href="http://en.wikipedia.org/wiki/Dimension_reduction">dimensionality reduction</a> techniques. Applications include <a href="http://en.wikipedia.org/wiki/Information_Retrieval">information retrieval</a>, document classification and <a href="http://en.wikipedia.org/wiki/Collaborative_filtering">collaborative filtering</a>.</p>
<p>Note: LSA and pLSA are also known in the Information Retrieval community as LSI and pLSI, where I stands for Indexing. </p>
<h3>Comparison</h3>
<table border="1" style="margin-top:10px">
<tr>
<th>&nbsp;</th>
<th>LSA</th>
<th>pLSA</th>
</tr>
<tr>
<td>1. Theoretical background</td>
<td>Linear Algebra</td>
<td>Probabilities and Statistics</td>
</tr>
<tr>
<td>2. Objective function</td>
<td>Frobenius norm</td>
<td>Likelihood function</td>
</tr>
<tr>
<td>3. Polysemy</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>4. Folding-in</td>
<td>Straightforward</td>
<td>Complicated</td>
</tr>
</table>
<p>1. LSA stems from Linear Algebra as it is nothing more than a <a href="http://en.wikipedia.org/wiki/Singular_value_decomposition">Singular Value Decomposition</a>. On the other hand, pLSA has a strong probabilistic grounding (latent variable models).</p>
<p>2. SVD is a least squares method (it finds a low-rank matrix approximation that minimizes the <a href="http://en.wikipedia.org/wiki/Matrix_norm">Frobenius norm</a> of the difference with the original matrix). Moreover, as it is well known in Machine Learning, the <a href="http://en.wikipedia.org/wiki/Least_squares">least squares</a> solution corresponds to the <a href="http://en.wikipedia.org/wiki/Maximum_likelihood">Maximum Likelihood</a> solution when experimental errors are gaussian. Therefore, LSA makes an implicit assumption of gaussian noise on the term counts. On the other hand, the objective function maximized in pLSA is the likelihood function of multinomial sampling. </p>
<p>The values in the concept-term matrix found by LSA are not normalized and may even contain negative values. On the other hand, values found by pLSA are probabilities which means they are interpretable and can be combined with other models.</p>
<p>Note: SVD is equivalent to PCA (Principal Component Analysis) when the data is centered (has zero-mean).</p>
<p>3. Both LSA and pLSA can handle synonymy but LSA cannot handle polysemy, as words are defined by a unique point in a space.</p>
<p>4. LSA and pLSA analyze a corpus of documents in order to find a new low-dimensional representation of it. In order to be comparable, new documents that were not originally in the corpus must be projected in the lower-dimensional space too. This is called &#8220;folding-in&#8221;. Clearly, new documents folded-in don&#8217;t contribute to learning the factored representation so it is necessary to rebuild the model using all the documents from time to time. </p>
<p>In LSA, folding-in is as easy as a matrix-vector product. In pLSA, this requires several iterations of the EM algorithm. </p>
<h3>Implementation in Python</h3>
<p>LSA is straightforward to implement as it is nothing more than a SVD and Numpy&#8217;s Linear Algebra module has a function &#8220;svd&#8221; already. This function has an argument full_matrices which when set to False greatly reduces the time required. This argument doesn&#8217;t mean that the SVD is not full, just that the returned matrices don&#8217;t contain vectors corresponding to zero singular values. Scipy&#8217;s Linear Algebra package unfortunately doesn&#8217;t seem to have a sparse SVD. Likewise, there&#8217;s no truncated SVD (there exists fast algorithms to directly compute a truncated SVD rather than computing the full SVD then taking the top K singular values).</p>
<p>pLSA&#8217;s source code is a bit longer although quite compact too. Although the Python/Numpy code was quite optimized, it took half a day to compute on a 50000 x 8000 term-document matrix. I rewrote the training part in C and it now takes half an hour. Keeping the Python version is quite nice for checking the correctness of the C version and as a reference as the C version is a straightforward port of it.</p>
<p>The implementation is sparse. It works with both Numpy&#8217;s ndarrays and Scipy&#8217;s sparse matrices.</p>
<p>$ git clone http://www.mblondel.org/code/plsa.git</p>
<p><a href=" http://www.mblondel.org/gitweb?p=plsa.git">web interface</a></p>
<p>Next, I would like to explore Fisher Kernels as there seems to have nice interactions with pLSA. I would also like to implement Latent Dirichlet Allocation (LDA), although it&#8217;s more challenging. LDA is a Bayesian extension of pLSA : pLSA is equivalent to LDA under a uniform Dirichlet prior distribution.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/06/13/lsa-and-plsa-in-python/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>The Little Machine Learner</title>
		<link>http://www.mblondel.org/journal/2010/02/18/the-little-machine-learner/</link>
		<comments>http://www.mblondel.org/journal/2010/02/18/the-little-machine-learner/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 11:57:16 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Machine Learning]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=124</guid>
		<description><![CDATA[The idea I&#8217;ve been having this idea on my mind for quite some time: wouldn&#8217;t it be nice to write a book about Machine Learning where each chapter is a literate program? From Wikipedia: The literate programming paradigm, as conceived by Knuth, represents a move away from writing programs in the manner and order imposed [...]]]></description>
			<content:encoded><![CDATA[<h3>The idea</h3>
<p>I&#8217;ve been having this idea on my mind for quite some time: wouldn&#8217;t it be nice to write a book about <a href="http://en.wikipedia.org/wiki/Machine_learning">Machine Learning</a> where each chapter is a <a href="http://en.wikipedia.org/wiki/Literate_programming">literate program</a>?</p>
<p>From Wikipedia:</p>
<blockquote><p>
The literate programming paradigm, as conceived by Knuth, represents a move away from writing programs in the manner and order imposed by the computer, and instead enables programmers to develop programs in the order demanded by the logic and flow of their thoughts.
</p></blockquote>
<p>From the <a href="http://pylit.berlios.de/">PyLit</a> homepage:</p>
<blockquote><p>
The idea is that you do not document programs (after the fact), but write documents that contain the programs.
</p></blockquote>
<p>There are plenty of great textbooks about Machine Learning out there, so the point would not be to write yet another one, but write something <em>different</em>.  Here&#8217;s what I had been thinking.</p>
<ul>
<li>Each chapter written as a literate program, organized so as to maximize understanding</li>
<li>Code in Python (+Numpy + Scipy but without any additional dependencies)</li>
<li>Readability over Performance</li>
<li>Intuitions, nice figures, useful tips or tricks</li>
<li>Real-world applications at the end of each chapter</li>
<li>Don&#8217;t shy away from the maths, especially if at high-school or undergraduate level&#8230;</li>
</ul>
<p>I bet that quite a few algorithms can be written this way, yet remain very concise!</p>
<p>Except for the maths part, the closest book to this idea that I know of is probably &#8220;Programming Collective Intelligence: Building Smart Web 2.0 Applications&#8221;, by Toby Segaran.</p>
<h3>An example with logistic regression</h3>
<p>So, in order to experiment with what such a book could look like, I&#8217;ve decided to write a chapter about <a href="http://en.wikipedia.org/wiki/Logistic_regression">Logistic Regression</a>. Topics I cover include Maximum Likelihood Estimation, Regularization and Cross-validation. At the end, I use heart disease prediction as an example of real-world application. Probably many things could be improved or added but the point for now is mainly to show <em>what it could look like</em>.</p>
<ul>
<li><strong><a href="http://www.mblondel.org/tlml/logreg.py.html">HTML</a></strong></li>
<li><strong><a href="http://www.mblondel.org/tlml/tlml.pdf">PDF</a></strong></li>
<li><strong><a href="http://www.mblondel.org/gitweb?p=tlml.git;a=blob;f=logreg.py">Code</a></strong>
</ul>
<h3>Tools</h3>
<p>For the documentation tool, I&#8217;ve decided to go for <a href="http://sphinx.pocoo.org/">Sphinx</a>, which seems to be emerging as the de-facto documentation tool in the Python community. It has nice features like syntax highlighting, latex support and <a href="http://matplotlib.sourceforge.net/">matplotlib</a> plots support and can output to HTML and PDF.</p>
<p>Normally, in literate programming, there&#8217;s the literate source, which uses some kind of markup-language and tools are used to generate either code or documentation from it. I took a different approach. In my case, the source file is the code and the documentation is extracted from the comments in the code. Technically, it&#8217;s therefore closer to extensively documented code than actual literate programming. It has some limitations but the main advantages are that the program is runnable directly (since Python is interpreted) and the programmer can benefit from syntax highlighting. I wrote a simple program that converts Python source code to reStructuredText, as necessary for integration in Sphinx.</p>
<h3>Interested?</h3>
<p>It took quite some time to collect the information and do the actual writing but I feel like I improved my own understanding in the process, so I&#8217;m thinking of writing a chapter from time to time. If I do so, at the end of my PhD, I may have gathered enough material to make it a real book! The book could affectionately be entitled &#8220;The Little Machine Learner&#8221;, hence the title of this post.</p>
<p>Since Machine Learning is a very large field and to write a better book than I could possibly write alone, I&#8217;m also thinking that it could actually be a collaborative effort (by researchers, students and practitioners). If you&#8217;re interested, please leave a comment. I will create a discussion group if there&#8217;s enough interest.</p>
<p>As usual, the source code is available in my git repo:</p>
<p>$ git clone http://www.mblondel.org/code/tlml.git</p>
<p><a href="http://www.mblondel.org/gitweb?p=tlml.git;a=tree">web interface</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/02/18/the-little-machine-learner/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Seam Carving in Python</title>
		<link>http://www.mblondel.org/journal/2010/02/09/seam-carving-in-python/</link>
		<comments>http://www.mblondel.org/journal/2010/02/09/seam-carving-in-python/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 15:57:20 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[In English]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=123</guid>
		<description><![CDATA[Seam Carving is an algorithm for image resizing introduced in 2007 by S. Avidan and A. Shamir in their paper &#8220;Seam Carving for Content-Aware Image Resizing&#8220;. Miyako Island, Okinawa, Japan. The principle is very simple. Find the connected paths of low energy pixels (&#8220;the seams&#8221;). This can be done efficiently by dynamic programming (see my [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Seam_carving">Seam Carving</a> is an algorithm for image resizing introduced in 2007 by S. Avidan and A. Shamir in their paper &#8220;<a href="http://www.shaiavidan.org/papers/imretFinal.pdf">Seam Carving for Content-Aware Image Resizing</a>&#8220;.</p>
<p><a href="http://www.flickr.com/photos/ippei-janine/2165260667/"><img src="http://www.mblondel.org/images/seam-carving/okinawa.jpg" style="border: 1px solid black" /></a><br />
<em>Miyako Island, Okinawa, Japan.</em></p>
<p>The principle is very simple. Find the connected paths of low energy pixels (&#8220;the seams&#8221;). This can be done efficiently by <a href="http://en.wikipedia.org/wiki/Dynamic_programming">dynamic programming</a> (see my post on <a href="http://www.mblondel.org/journal/2009/08/31/dynamic-time-warping-theory/">DTW</a>). </p>
<p><img src="http://www.mblondel.org/images/seam-carving/okinawa_gradient.jpg" /><br />
<em>Same image in the gradient domain showing the vertical and horizontal seams of lowest cumulated energy.</em></p>
<p>The seams of lowest cumulated energy can be seen as the pixels contributing the least to an image. By repeatedly removing or adding seams, it is thus possible to perform &#8220;content-aware&#8221; image reduction or extension. The resulting images feel more natural, less &#8220;streched&#8221;.</p>
<p><img src="http://www.mblondel.org/images/seam-carving/okinawa_good.jpg" style="border: 1px solid black" /><br />
<em>Height reduced by 50% by seam carving.</em></p>
<p><img src="http://www.mblondel.org/images/seam-carving/okinawa_bad.jpg" style="border: 1px solid black"  /><br />
<em>Height reduced by 50% by traditional rescaling.</em></p>
<p>Although seam carving doesn&#8217;t need human intervention, in the original paper, a graphical user interface (GUI) was also developed to let the user define areas that can&#8217;t be removed, or conversely, that must be removed.</p>
<p>In my opinion, seam carving is simple and elegant. No sophisticated object recognition algorithm was used, yet the results are quite impressive.</p>
<p>You can find my implementation in 250 lines of Python in my git repo:</p>
<p>$ git clone http://www.mblondel.org/code/seam-carving.git</p>
<p><a href="http://www.mblondel.org/gitweb?p=seam-carving.git;a=tree">web interface</a></p>
<p>Unfortunately, it&#8217;s too slow to be real-time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/02/09/seam-carving-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Caching computation tasks</title>
		<link>http://www.mblondel.org/journal/2010/01/27/caching-computation-tasks/</link>
		<comments>http://www.mblondel.org/journal/2010/01/27/caching-computation-tasks/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 14:12:37 +0000</pubDate>
		<dc:creator>Mathieu</dc:creator>
				<category><![CDATA[In English]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.mblondel.org/journal/?p=121</guid>
		<description><![CDATA[When I work on computationally expensive projects (e.g., Machine Learning), I always find myself in the same situation: my programs can be broken down into a chain of tasks, where tasks may depend on the results of other tasks. A typical such chain would be: preprocessing -> feature-extraction -> training -> evaluation If I make [...]]]></description>
			<content:encoded><![CDATA[<p>When I work on computationally expensive projects (e.g., Machine Learning), I always find myself in the same situation: my programs can be broken down into a chain of tasks, where tasks may depend on the results of other tasks. A typical such chain would be:</p>
<p>preprocessing -> feature-extraction -> training -> evaluation</p>
<p>If I make a modification in my training algorithm and want to re-evaluate it, I do need to re-run the &#8220;training&#8221; and &#8220;evaluation&#8221; tasks, but I don&#8217;t need and don&#8217;t want to re-run the &#8220;processing&#8221; and &#8220;feature-extraction&#8221; tasks, especially if they take time to compute.</p>
<p>At first, I tried to save and load task results manually. This quickly proved unmanageable so I started to think of ways to automate this. Since I had quite a precise idea of what I wanted, I&#8217;ve decided to write my own tool, at the risk of reinventing the wheel. (I suspect it&#8217;s quite hard to come up with a universal tool, though) To keep things simple, I&#8217;ve decided to limit the tool&#8217;s scope to projects that can be run on a single computer, typically with multi-cores. In particular, it won&#8217;t support any kind of distributed computing.<br />
<span id="more-121"></span></p>
<h3>Dependency resolution &#038; Object persistence</h3>
<p>Basically, the tool boils down to <a href="http://en.wikipedia.org/wiki/Topological_sorting">dependency resolution</a> and <a href="http://en.wikipedia.org/wiki/Object_persistence">object persistence</a>. <em>make</em> is an obvious possibility for dependency resolution, but it can only use file modification time to decide whether to recompute tasks or not. In my tool, I check cache availability for a task based on the task inputs (these can be outputs from previous tasks, files, algorithm parameters&#8230;) as well as source code. The source code is also taken into consideration because a task&#8217;s result is likely to change if the task source code has changed.</p>
<p>To store objects on the filesystem or in a database, you need a way to serialize and deserialize objects. In the python world, the obvious choice is <a href="http://docs.python.org/library/pickle.html">pickle</a>, which is also used by the module <a href="http://docs.python.org/library/shelve.html">shelve</a> to store objects in a dbm database with a dict-like interface. Pickle is quite slow to load and save big lists of objects though, so I created two sqlite-based stores called KeyListStore and ListStore, to address this issue. A difficulty is how to efficiently compute a hash that identifies objects uniquely. To make things simple, I just took the hash of pickled objects. This is wrong, since pickle doesn&#8217;t guarantee to return twice the same strings for two same objects. However, while this can lead to incorrectly invalidating a cache, forcing the task to be recomputed, hopefully, it&#8217;s very unlikely that a cache is mistaken for the cache of another object. In practice, I haven&#8217;t had any problem with cache so far.</p>
<p>One feature in Python that was particularly useful for this tool was decorators. They can be used to change the behavior of a function, in a declarative style.</p>
<h3>Example</h3>
<p>Here&#8217;s a concrete example of a program written with my tool:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> numpy <span style="color: #ff7700;font-weight:bold;">as</span> np
<span style="color: #ff7700;font-weight:bold;">import</span> taskmanager <span style="color: #ff7700;font-weight:bold;">as</span> tm
&nbsp;
DFLT_TRAIN = <span style="color: #483d8b;">&quot;/path/to/...&quot;</span>
DFLT_EVAL = <span style="color: #483d8b;">&quot;/path/to/...&quot;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Preprocessing</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> preprocess<span style="color: black;">&#40;</span>img_folder, normalize<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#91;</span>preprocess_img<span style="color: black;">&#40;</span>img, normalize<span style="color: black;">&#41;</span> \ 
                  <span style="color: #ff7700;font-weight:bold;">for</span> img <span style="color: #ff7700;font-weight:bold;">in</span> img_folder.<span style="color: black;">get_files</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>tm.<span style="color: black;">directory</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;*.jpg&quot;</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">bool</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">def</span> preproc_train<span style="color: black;">&#40;</span>img_folder=DFLT_TRAIN, normalize=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> preprocess<span style="color: black;">&#40;</span>img_folder, normalize<span style="color: black;">&#41;</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>tm.<span style="color: black;">directory</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;*.jpg&quot;</span><span style="color: black;">&#41;</span>, <span style="color: #008000;">bool</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">def</span> preproc_eval<span style="color: black;">&#40;</span>img_folder=DFLT_EVAL, normalize=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> preprocess<span style="color: black;">&#40;</span>img_folder, normalize<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Feature extraction</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>preproc_train<span style="color: black;">&#41;</span>:
<span style="color: #ff7700;font-weight:bold;">def</span> fextract_train<span style="color: black;">&#40;</span>images<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#91;</span>...<span style="color: black;">&#93;</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>preproc_eval<span style="color: black;">&#41;</span>:
<span style="color: #ff7700;font-weight:bold;">def</span> fextract_eval<span style="color: black;">&#40;</span>images<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#91;</span>...<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Training</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>fextract_train, <span style="color: #008000;">int</span>, <span style="color: #008000;">float</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">def</span> train<span style="color: black;">&#40;</span>features, maxiter=<span style="color: #ff4500;">10</span>, esp=<span style="color: #ff4500;">0.0001</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#91;</span>...<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Evaluation results</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>fextract_eval, train<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">def</span> evaluate<span style="color: black;">&#40;</span>features, models<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#91;</span>...<span style="color: black;">&#93;</span>
&nbsp;
@tm.<span style="color: black;">task</span><span style="color: black;">&#40;</span>evaluate<span style="color: black;">&#41;</span>
@nocache
<span style="color: #ff7700;font-weight:bold;">def</span> results<span style="color: black;">&#40;</span>eval_res<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: black;">&#91;</span>...<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        tm.<span style="color: black;">TaskManager</span>.<span style="color: black;">OUTPUT_FOLDER</span> = <span style="color: #483d8b;">&quot;./tmp&quot;</span>
        tm.<span style="color: black;">run_command</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span>:<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">except</span> tm.<span style="color: black;">TaskManagerError</span>, m:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #66cc66;">&gt;&gt;</span>sys.<span style="color: black;">stderr</span>, m
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<ul>
<li>The tool is quite unobtrusive.</li>
<li>There&#8217;s no need to deal with file names or file versions, this is all done transparently for you.</li>
<li>You get a command-line interface for free. Here, since all tasks have a default parameter, you could just run &#8220;./mypgm.py results&#8221; and it would work. If you wanted to try out different parameters for, e.g., &#8220;train&#8221;, you could run &#8220;./mypgm.py train:5 results&#8221;</li>
</ul>
<h3>Code</h3>
<p>Code available <a href="http://www.mblondel.org/gitweb?p=taskmanager.git;a=tree">here</a>. </p>
<p>Everything is kept in one file to make it easy to copy the tool to another project. The tool is quite usable already but of course, it&#8217;s a work in progress.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mblondel.org/journal/2010/01/27/caching-computation-tasks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

