<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Pyevolve</title>
	
	<link>http://pyevolve.sourceforge.net/wordpress</link>
	<description>by Christian S. Perone</description>
	<lastBuildDate>Thu, 02 Feb 2012 18:23:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/pyevolve" /><feedburner:info uri="pyevolve" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Accessing HP Cloud OpenStack Nova using Python and Requests</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/9BU1OtLc0w4/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2232#comments</comments>
		<pubDate>Thu, 02 Feb 2012 18:23:48 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[HP Cloud]]></category>
		<category><![CDATA[hpcloud]]></category>
		<category><![CDATA[Nova]]></category>
		<category><![CDATA[OpenStack]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Requests]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2232</guid>
		<description><![CDATA[So, my request to enter on the free and private beta season of the new HP Cloud Services was gently accepted by the HP Cloud team, and today I finally got some time to play with the OpenStack API at HP Cloud. I&#8217;ll start with the first impressions I had with the service: The user [...]]]></description>
			<content:encoded><![CDATA[<p>So, my request to enter on the free and private beta season of the new HP Cloud Services was gently accepted by the <a title="Twitter :: hpcloud" href="https://twitter.com/hpcloud" target="_blank">HP Cloud team</a>, and today I finally got some time to play with the OpenStack API at HP Cloud. I&#8217;ll start with the first impressions I had with the service:</p>
<p>The user interface of the management is very user-friendly, the design is much like of the Twitter Bootstrap, see the screenshot below of the &#8220;Compute&#8221; page from the &#8220;Manage&#8221; section:</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_images_xss.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2248" title="compute_images_xss" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_images_xss.png" alt="" width="540" height="307" /></a></p>
<p>As you can see, they have a set of 4 Ubuntu images and a CentOS, I think that since they are still in the beta period, soon we&#8217;ll have more default images to use.</p>
<p>Here is a screenshot of the instance size set:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_sizes_ss.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2239" title="compute_sizes_ss" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/compute_sizes_ss.png" alt="" width="428" height="178" /></a></p>
<p>Since they are using OpenStack, I really think that they should have imported the vocabulary of the OpenStack into the user interface, and instead of calling it &#8220;Size&#8221;, it would be more sensible to use &#8220;<a title="OpenStack :: Wiki :: Flavour" href="http://docs.openstack.org/cactus/openstack-compute/developer/openstack-compute-api-1.1/content/ch04s04.html" target="_blank">Flavour</a>&#8220;.</p>
<p>The user interface still doesn&#8217;t have many features, something that I would really like to have is a &#8220;Stop&#8221; or something like that for the instances, only the &#8220;Terminate&#8221; function is present on the Manage interface, but those are details that they should be still working on since they&#8217;re only in beta.</p>
<p>Another important info to cite is that the access to the instances are done through SSH using a generated RSA key that they provide to you.</p>
<p>Let&#8217;s dig into the OpenStack API now.</p>
<h2>OpenStack API</h2>
<p>To access the OpenStack API you&#8217;ll need the credentials for the authentication, HP Cloud services provide these keys on the Manage interface for each zone/service you have, see the screenshot below (with keys <em>anonymized</em> of course):</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/api_keys_ss.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2255" title="api_keys_ss" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/api_keys_ss.png" alt="" width="672" height="187" /></a>Now, <a title="OpenStack :: Authentication" href="http://docs.openstack.org/api/openstack-compute/1.1/content/Authentication-d1e444.html" target="_blank">OpenStack authentication</a> could be done in different schemes, the scheme that I know that HP supports is the token authentication. I know that there is a lot of clients already supporting the OpenStack API (some have no documentation, some have weird API design, etc.), but the aim of this post is to show how easy would be to create a simple interface to access the OpenStack API using Python and <a title="Python Requests" href="http://docs.python-requests.org/" target="_blank">Requests</a> (HTTP for Humans !).</p>
<p>Let&#8217;s start defining our authentication scheme by sub-classing Requests <strong>AuthBase</strong>:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> OpenStackAuth<span style="color: black;">&#40;</span>AuthBase<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, auth_user, auth_key<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">auth_key</span> = auth_key<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">auth_user</span> = auth_user<br />
<br />
<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, r<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; r.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'X-Auth-User'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">auth_user</span><br />
&nbsp; &nbsp; r.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'X-Auth-Key'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">auth_key</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> r</div></td></tr></tbody></table></div>
<p>As you can see, we&#8217;re defining the X-Auth-User and the X-Auth-Key in the header of the request with the parameters. These parameters are respectively your Account ID and  Access Key we cited earlier. Now, all you have to do is to make the request itself using the authentication scheme, which is pretty easy using Requests:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">ENDPOINT_URL = <span style="color: #483d8b;">'https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/'</span><br />
ACCESS_KEY = <span style="color: #483d8b;">'Your Access Key'</span><br />
ACCOUNT_ID = <span style="color: #483d8b;">'Your Account ID'</span><br />
response = requests.<span style="color: black;">get</span><span style="color: black;">&#40;</span>ENDPOINT_URL, auth=OpenStackAuth<span style="color: black;">&#40;</span>ACCOUNT_ID, ACCESS_KEY<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>And that is it, you&#8217;re done with the authentication mechanism using just a few lines of code, and this is how the request is going to be sent to the HP Cloud service server:</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_request.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2260" style="border: 0pt none;" title="auth_request" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_request.png" alt="" width="464" height="314" /></a></p>
<p> This request is sent to the HP Cloud Endpoint URL (https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/). Let&#8217;s see now how the server answered this authentication request:</p>
<p style="text-align: center;"><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_response.png" rel="lightbox[2232]"><img class="aligncenter size-full wp-image-2264" style="border: 0pt none;" title="auth_response" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2012/02/auth_response.png" alt="" width="478" height="314" /></a></p>
<p style="text-align: left;">You can show this authentication response using Requests by printing the <strong>header</strong> attribute of the request Response object. You can see that the server answered our request with two important header items: X-Server-Management-URL and the X-Auth-Token. The management URL is now our new endpoint, is the URL we should use to do further requests to the HP Cloud services and the X-Auth-Token is the authentication Token that the server generated based on our credentials, these tokens are usually valid for 24 hours, although I haven&#8217;t tested it.</p>
<p style="text-align: left;">What we need to do now is to sub-class the Requests AuthBase class again but this time defining only the authentication token that we need to use on each new request we&#8217;re going to make to the management URL:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> OpenStackAuthToken<span style="color: black;">&#40;</span>AuthBase<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, request<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">auth_token</span> = request.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'x-auth-token'</span><span style="color: black;">&#93;</span><br />
<br />
<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, r<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; r.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'X-Auth-Token'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">self</span>.<span style="color: black;">auth_token</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> r</div></td></tr></tbody></table></div>
<p style="text-align: left;">Note that the OpenStackAuthToken is receiving now a response request as parameter, copying the X-Auth-Token and setting it on the request.</p>
<p style="text-align: left;">Let&#8217;s consume a service from the OpenStack API v.1.1, I&#8217;m going to call the <a title="OpenStack :: API :: List Servers" href="http://docs.openstack.org/api/openstack-compute/1.1/content/List_Servers-d1e2078.html" target="_blank">List Servers API</a> function, parse the results using JSON and then show the results on the screen:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;"># Get the management URL from the response header</span><br />
mgmt_url = response.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'x-server-management-url'</span><span style="color: black;">&#93;</span><br />
<br />
<span style="color: #808080; font-style: italic;"># Create a new request to the management URL using the /servers path</span><br />
<span style="color: #808080; font-style: italic;"># and the OpenStackAuthToken scheme we created</span><br />
r_server = requests.<span style="color: black;">get</span><span style="color: black;">&#40;</span>mgmt_url + <span style="color: #483d8b;">'/servers'</span>, auth=OpenStackAuthToken<span style="color: black;">&#40;</span>response<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
<br />
<span style="color: #808080; font-style: italic;"># Parse the response and show it to the screen</span><br />
json_parse = json.<span style="color: black;">loads</span><span style="color: black;">&#40;</span>r_server.<span style="color: black;">text</span><span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> json.<span style="color: black;">dumps</span><span style="color: black;">&#40;</span>json_parse, indent=<span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p style="text-align: left;">And this is what we get in response to this request:</p>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">{<br />
&nbsp; &nbsp; &quot;servers&quot;: [<br />
&nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;id&quot;: 22378,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;uuid&quot;: &quot;e2964d51-fe98-48f3-9428-f3083aa0318e&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;links&quot;: [<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/20817201684751/servers/22378&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;self&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/20817201684751/servers/22378&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;bookmark&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;name&quot;: &quot;Server 22378&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; },<br />
&nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;id&quot;: 11921,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;uuid&quot;: &quot;312ff473-3d5d-433e-b7ee-e46e4efa0e5e&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;links&quot;: [<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/20817201684751/servers/11921&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;self&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;href&quot;: &quot;https://az-1.region-a.geo-1.compute.hpcloudsvc.com/20817201684751/servers/11921&quot;,<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;rel&quot;: &quot;bookmark&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;name&quot;: &quot;Server 11921&quot;<br />
&nbsp; &nbsp; &nbsp; &nbsp; }<br />
&nbsp; &nbsp; ]<br />
}</div></td></tr></tbody></table></div>
<p style="text-align: left;">And that is it, now you know how to use Requests and Python to consume OpenStack API. If you wish to read more information about the API and how does it works, you can read the <a title="OpenStack :: Documentation" href="http://docs.openstack.org/" target="_blank">documentation here</a>.</p>
<p style="text-align: left;"><em>- Christian S. Perone</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/9BU1OtLc0w4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2232</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2232</feedburner:origLink></item>
		<item>
		<title>Announce: Stallion v0.2 released !</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/GKni4Uhz3QM/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2220#comments</comments>
		<pubDate>Fri, 16 Dec 2011 00:20:29 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[announce]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[package manager]]></category>
		<category><![CDATA[pypi]]></category>
		<category><![CDATA[screenshots]]></category>
		<category><![CDATA[stallion]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2220</guid>
		<description><![CDATA[I just tagged and released the v0.2 version of the Stallion. In the change log (Github project page), you can see that a lot of bugs were fixed and some new features were introduced in this release. I added compatibility with almost all Python 2.x versions, PyPy 1.7+ (and probably older versions too), I also [...]]]></description>
			<content:encoded><![CDATA[<p>I just tagged and released the v0.2 version of the Stallion. In the change log (<a title="Github :: Stallion" href="https://github.com/perone/stallion" target="_blank">Github project page)</a>, you can see that a lot of bugs were fixed and some new features were introduced in this release. I added compatibility with almost all Python 2.x versions, PyPy 1.7+ (and probably older versions too), I also fixed the compatibility with the Internet Explorer browser, now you should be able to use Stallion with Chrome, Firefox and IE.</p>
<p>The most important feature introduced is the global checking for updates (a lot of people requested it):</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers.png" rel="lightbox[2220]"><img class="aligncenter size-full wp-image-2221" title="classifiers" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers.png" alt="" width="273" height="202" /></a></p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates_avail.png" rel="lightbox[2220]"><img class="aligncenter size-full wp-image-2227" title="updates_avail" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates_avail.png" alt="" width="270" height="325" /></a></p>
<p>The new checking is under the menu &#8220;PyPI Repository&#8221;. Another new feature is the refactoring on the visual appearance of the package classifiers:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers2.png" rel="lightbox[2220]"><img class="aligncenter size-medium wp-image-2222" title="classifiers2" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/classifiers2-298x300.png" alt="" width="298" height="300" /></a></p>
<p>Some small visual enhancements were also introduced, like the little gray marker next to the selected package:</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/selected_package.png" rel="lightbox[2220]"><img class="aligncenter size-full wp-image-2223" title="selected_package" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/selected_package.png" alt="" width="163" height="94" /></a></p>
<p>I hope you liked, I&#8217;m looking forward to implement more features as soon as possible, but a new version shouldn&#8217;t be released until next year.</p>
<p><strong>Visit the <a title="Github :: Stallion" href="https://github.com/perone/stallion" target="_blank">project page at Github</a> to get instructions on how to update or install Stallion.</strong></p>
<p>- Christian S. Perone</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/GKni4Uhz3QM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2220</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2220</feedburner:origLink></item>
		<item>
		<title>Announce: ‘Stallion’ – Python Package Manager</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/TJ5AXHMX0IM/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2200#comments</comments>
		<pubDate>Sun, 04 Dec 2011 17:35:57 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[announce]]></category>
		<category><![CDATA[distribute]]></category>
		<category><![CDATA[package manager]]></category>
		<category><![CDATA[pip]]></category>
		<category><![CDATA[stallion]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2200</guid>
		<description><![CDATA[I&#8217;m happy to announce the first release v.0.1 of the Stallion project. Stallion is a visual Python package manager compatible with Python 2.6 and 2.7 (I still haven&#8217;t tested it with Python 2.5). The motivation behind Stallion is to provide an user friendly visualization with some management features (most of them are still under development) [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m happy to announce the first release v.0.1 of the Stallion project. Stallion is a visual Python package manager compatible with Python 2.6 and 2.7 (I still haven&#8217;t tested it with Python 2.5).</p>
<p>The motivation behind Stallion is to provide an user friendly visualization with some management features (most of them are still under development) for Python packages installed on your local Python distribution. Stallion is intended to be used specially for Python newcomers.</p>
<p>The project is <a title="Github :: Stallion" href="https://github.com/perone/stallion" target="_blank">currently hosted at Github</a>, so feel free to<strong> fork, contribute, make suggestion, report bugs, etc.</strong></p>
<h3>Installation</h3>
<p>All you need to do to install Stallion is to use your favorite Python distribution system, examples:</p>
<blockquote>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">user@machine:~/$ pip install stallion<br />
or<br />
user@machine:~/$ easy_install stallion</div></td></tr></tbody></table></div>
</blockquote>
<p>By doing this on your prompt (Windows/Linux), the pip/setuptools will download and install external dependencies (Flask, Jinja, docutils, etc.).<br />
After installing Stallion, you need to start the local server by using:</p>
<blockquote>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">user@machine:~/$ python -m stallion.main</div></td></tr></tbody></table></div>
</blockquote>
<p>And if it&#8217;s all ok, Stallion will start the server on localhost only at the port 5000, so all you need to do now is to browse into the URL <strong>http://localhost:5000</strong></p>
<p>You can also download install packages from the <a title="PyPI :: Stallion" href="http://pypi.python.org/pypi/Stallion/0.1" target="_blank">PyPI repository</a>.</p>
<h3>See some screenshots (click to enlarge)</h3>
<p>Click on the screenshots below to enlarge.</p>
<p style="text-align: center;">Home</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/main_page.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2207" title="main_page" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/main_page-300x162.png" alt="" width="300" height="162" /></a></p>
<p style="text-align: center;">Installed package information</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/distr.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2209" title="distr" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/distr-300x254.png" alt="" width="300" height="254" /></a></p>
<p style="text-align: center;">Package metadata</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/metadata.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2210" title="metadata" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/metadata-190x300.png" alt="" width="190" height="300" /></a></p>
<p style="text-align: center;">Check PyPI for updates available</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2211" title="updates" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates-300x218.png" alt="" width="300" height="218" /></a><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates2.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2212" title="updates2" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/updates2-300x204.png" alt="" width="300" height="204" /></a></p>
<p style="text-align: center;">PyPI version mismatch diagnosis<a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/diagnosis.png" rel="lightbox[2200]"><img class="aligncenter size-medium wp-image-2213" title="diagnosis" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/12/diagnosis-300x217.png" alt="" width="300" height="217" /></a></p>
<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/TJ5AXHMX0IM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2200</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2200</feedburner:origLink></item>
		<item>
		<title>Hacking into Python objects internals</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/ecB1PeGDVFA/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2171#comments</comments>
		<pubDate>Thu, 24 Nov 2011 00:26:52 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[c]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[internals]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2171</guid>
		<description><![CDATA[You know, Python represents every object using the low-level C API PyObject (or PyVarObject for variable-size objects) structure, so, concretely, you can cast any Python object pointer to this type; this inheritance is built by hand, every new object must have a leading macro called PyObject_HEAD which defines the PyObject header for the object. The [...]]]></description>
			<content:encoded><![CDATA[<p>You know, Python represents every object using the low-level C API <strong>PyObject </strong>(or <strong>PyVarObject</strong> for variable-size objects) structure, so, concretely, you can cast any Python object pointer to this type; this inheritance is built by hand, every new object must have a leading macro called <strong>PyObject_HEAD</strong> which defines the <strong>PyObject</strong> header for the object. The <strong>PyObject</strong> structure is declared in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Include/object.h#l106" target="_blank"><span style="color: #008080;">Include/object.h</span></a> as:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> _object <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; PyObject_HEAD<br />
<span style="color: #009900;">&#125;</span> PyObject<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>and the PyObject_HEAD macro is defined as:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339933;">#define PyObject_HEAD                   \<br />
&nbsp; &nbsp; _PyObject_HEAD_EXTRA                \<br />
&nbsp; &nbsp; Py_ssize_t ob_refcnt;               \<br />
&nbsp; &nbsp; struct _typeobject *ob_type;</span></div></td></tr></tbody></table></div>
<p>&#8230; with two fields (<em>forget the<strong> _PyObject_HEAD_EXTRA</strong>, it&#8217;s only used for a tracing debug feature</em>) called <strong>ob_refcnt</strong> and <strong>ob_type</strong>, representing the reference counting for the object and the type of the object. I know you can use <strong>sys.getrefcount</strong> to get the reference counting of an object, but hacking the object memory using ctypes is by far more powerful, since you can get the contents of any field of the object (in cases where you don&#8217;t have a native API for that), I&#8217;ll show more examples later, but lets focus on the reference counting field of the object.</p>
<h3>Getting the reference count (ob_refcnt)</h3>
<p>So, in Python, we have the built-in function <strong>id()</strong>, this function returns the identity of the object, but, looking at its definition on CPython implementation, you&#8217;ll notice that <strong>id()</strong> returns the memory address of the object, see the source in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Python/bltinmodule.c#l904" target="_blank"><span style="color: #008080;">Python/bltinmodule.c</span></a>:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">static</span> PyObject <span style="color: #339933;">*</span><br />
builtin_id<span style="color: #009900;">&#40;</span>PyObject <span style="color: #339933;">*</span>self<span style="color: #339933;">,</span> PyObject <span style="color: #339933;">*</span>v<span style="color: #009900;">&#41;</span><br />
<span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">return</span> PyLong_FromVoidPtr<span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>&#8230; the function <strong>PyLong_FromVoidPtr</strong> returns a Python long object from a void pointer. So, in CPython, this value is the address of the object in the memory as shown below:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value = <span style="color: #ff4500;">666</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">hex</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><br />
<span style="color: #483d8b;">'0x8998e50'</span> <span style="color: #808080; font-style: italic;"># memory address of the 'value' object</span></div></td></tr></tbody></table></div>
<p>Now that we have the memory address of the object, we can use the Python ctypes module to get the reference counting by accessing the attribute <strong>ob_refcnt</strong>, here is the code needed to do that:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value = <span style="color: #ff4500;">666</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> value_address = <span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_refcnt = ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span>value_address<span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_refcnt<br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>What I&#8217;m doing here is getting the integer value from the <strong>ob_refcnt</strong> attribute of the <strong>PyObject</strong> in memory.  Let&#8217;s add a new reference for the object &#8216;value&#8217; we created, and then check the reference count again:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value_ref = value<br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value_ref<span style="color: black;">&#41;</span> == <span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span><br />
<span style="color: #008000;">True</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_refcnt<br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Note that the reference counting was increased by 1 due to the new reference variable called &#8216;value_ref&#8217;.</p>
<h3>Interned strings state (ob_sstate)</h3>
<p>Now, getting the reference count wasn&#8217;t even funny, we already had the <strong>sys.getrefcount</strong> API for that, but what about the <a title="Wikipedia :: String Interning" href="http://en.wikipedia.org/wiki/String_interning" target="_blank">interned state of the strings</a> ? In order to avoid the creation of different allocations for the same string (and to speed comparisons), Python uses a dictionary that works like a &#8220;cache&#8221; for strings, this dictionary is defined in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Objects/stringobject.c#l16" target="_blank"><span style="color: #008080;">Objects/stringobject.c</span></a>:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #808080; font-style: italic;">/* This dictionary holds all interned strings.  Note that references to<br />
strings in this dictionary are *not* counted in the string's ob_refcnt.<br />
When the interned string reaches a refcnt of 0 the string deallocation<br />
function will delete the reference from this dictionary.<br />
<br />
Another way to look at this is that to say that the actual reference<br />
count of a string is:  s-&amp;gt;ob_refcnt + (s-&amp;gt;ob_sstate?2:0)<br />
*/</span><br />
<span style="color: #993333;">static</span> PyObject <span style="color: #339933;">*</span>interned<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>I also copied here the comment about the dictionary, because is interesting to note that the strings in the dictionary aren&#8217;t counted in the string&#8217;s <strong>ob_refcnt</strong>.</p>
<p>So, the interned state of a string object is hold in the attribute <strong>ob_sstate</strong> of the string object, let&#8217;s see the definition of the Python string object:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; PyObject_VAR_HEAD<br />
&nbsp; &nbsp; <span style="color: #993333;">long</span> ob_shash<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #993333;">int</span> ob_sstate<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #993333;">char</span> ob_sval<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #808080; font-style: italic;">/* Invariants:<br />
&nbsp; &nbsp; *     ob_sval contains space for 'ob_size+1' elements.<br />
&nbsp; &nbsp; *     ob_sval[ob_size] == 0.<br />
&nbsp; &nbsp; *     ob_shash is the hash of the string or -1 if not computed yet.<br />
&nbsp; &nbsp; *     ob_sstate != 0 iff the string object is in stringobject.c's<br />
&nbsp; &nbsp; *       'interned' dictionary; in this case the two references<br />
&nbsp; &nbsp; *       from 'interned' to this object are *not counted* in ob_refcnt.<br />
&nbsp; &nbsp; */</span><br />
<span style="color: #009900;">&#125;</span> PyStringObject<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>As you can note, strings objects inherit from the PyObject_VAR_HEAD macro, which defines another header attribute, let&#8217;s see the definition to get the complete idea of the structure:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #339933;">#define PyObject_VAR_HEAD               \<br />
&nbsp; &nbsp; PyObject_HEAD                       \<br />
&nbsp; &nbsp; Py_ssize_t ob_size; /* Number of items in variable part */</span></div></td></tr></tbody></table></div>
<p>The <strong>PyObject_VAR_HEAD</strong> macro adds another field called <strong>ob_size</strong>, which is the number of items on the variable part of the Python object (i.e. the number of items on a list object). So, before getting to the <strong>ob_sstate</strong> field, we need to shift our offset to skip the fields<strong> ob_refcnt (long)</strong>, <strong>ob_type (void*)</strong> (from <strong>PyObject_HEAD</strong>), the field <strong>ob_size (long)</strong> (from <strong>PyObject_VAR_HEAD</strong>) and the field <strong>ob_shash</strong> <strong>(long)</strong> from the <strong>PyStringObject</strong>. Concretely, we need to skip this offset (3 fields with size <strong>long</strong> and one field with size <strong>void*</strong>) of bytes:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_sstate_offset = ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_long</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">*</span><span style="color: #ff4500;">3</span> + ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_voidp</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_sstate_offset<br />
<span style="color: #ff4500;">16</span></div></td></tr></tbody></table></div>
<p>Now, let&#8217;s prepare two cases, one that we know that isn&#8217;t interned and another that is surely interned, then we&#8217;ll force the interned state of the other non-interned string to check the result of the <strong>ob_sstate</strong> attribute:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> a = <span style="color: #483d8b;">&quot;lero&quot;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> b = <span style="color: #483d8b;">&quot;&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;l&quot;</span>, <span style="color: #483d8b;">&quot;e&quot;</span>, <span style="color: #483d8b;">&quot;r&quot;</span>, <span style="color: #483d8b;">&quot;o&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>a<span style="color: black;">&#41;</span> + ob_sstate_offset<span style="color: black;">&#41;</span><br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>b<span style="color: black;">&#41;</span> + ob_sstate_offset<span style="color: black;">&#41;</span><br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ctypes.<span style="color: black;">c_long</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>intern<span style="color: black;">&#40;</span>b<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> + ob_sstate_offset<span style="color: black;">&#41;</span><br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Note that the interned state for the object &#8220;a&#8221; is 1 and for the object &#8220;b&#8221; is 0. After forcing the interned state of the variable &#8220;b&#8221;, we can see that the field <strong>ob_sstate</strong> has changed to 1.</p>
<h3>Changing internal states (evil mode)</h3>
<p>Now, let&#8217;s suppose we want to change some internal state of a Python object through the interpreter. Let&#8217;s try to change the value of an int object. Int objects are defined in <a href="http://hg.python.org/cpython/file/d1bdafa161e7/Include/intobject.h#l22" target="_blank"><span style="color: #008080;">Include/intobject.h</span></a>:</p>
<div class="codecolorer-container c railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; PyObject_HEAD<br />
&nbsp; &nbsp; <span style="color: #993333;">long</span> ob_ival<span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span> PyIntObject<span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>As you can see, the internal value of an int is stored in the field <strong>ob_ival</strong>, to change it, we just need to skip the <strong>ob_refcnt</strong> <strong>(long)</strong> and the <strong>ob_type (void*)</strong> from the <strong>PyObject_HEAD</strong>:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> value = <span style="color: #ff4500;">666</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival_offset = ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_long</span><span style="color: black;">&#41;</span> + ctypes.<span style="color: black;">sizeof</span><span style="color: black;">&#40;</span>ctypes.<span style="color: black;">c_voidp</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival = ctypes.<span style="color: black;">c_int</span>.<span style="color: black;">from_address</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span><span style="color: black;">&#40;</span>value<span style="color: black;">&#41;</span>+ob_ival_offset<span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival<br />
c_long<span style="color: black;">&#40;</span><span style="color: #ff4500;">666</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> ob_ival.<span style="color: black;">value</span> = <span style="color: #ff4500;">8</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> value<br />
<span style="color: #ff4500;">8</span></div></td></tr></tbody></table></div>
<p>And that is it, we have changed the value of the int value directly in the memory.</p>
<p>I hope you liked it, you can play with lots of other Python objects like lists and dicts, note that this method is just intended to show how the Python objects are structured in the memory and how you can change them using the native API, but obviously, you&#8217;re not supposed to use this to change the value of ints lol.</p>
<p><strong>Update 11/29/11</strong>: <em>you&#8217;re not supposed to do such things on your production code or something like that, in this post I&#8217;m doing lazy assumptions about arch details like sizes of primitives, etc. <strong>Be warned</strong>.</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/ecB1PeGDVFA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2171</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2171</feedburner:origLink></item>
		<item>
		<title>C++11 user-defined literals and some constructions</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/gsv4C4Q0CDs/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=2104#comments</comments>
		<pubDate>Mon, 21 Nov 2011 23:39:20 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[CPP]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[c++0x]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[literals]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[user-defined literals]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=2104</guid>
		<description><![CDATA[I was taking a look at the proposal N2765 (user-defined literals) already implemented on the development snapshots of the GCC 4.7 and I was thinking in how user-defined literals can be used to create some interesting and sometimes strange constructions. Introduction to user-defined literals C++03 has some literals, like the &#8220;f&#8221; in &#8220;12.2f&#8221; that converts [...]]]></description>
			<content:encoded><![CDATA[<p>I was taking a look at the proposal <a title="User-define literals" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf" target="_blank">N2765</a> (<strong>user-defined literals</strong>) already implemented on the development snapshots of the <a title="GCC 4.7 Changelog" href="http://gcc.gnu.org/gcc-4.7/changes.html" target="_blank">GCC 4.7</a> and I was thinking in how user-defined literals can be used to create some interesting and sometimes strange constructions.</p>
<h3>Introduction to user-defined literals</h3>
<p>C++03 has some literals, like the &#8220;f&#8221; in &#8220;12.2f&#8221; that converts the double value to float. The problem is that these literals aren&#8217;t very flexible since they&#8217;re pretty fixed, so you can&#8217;t change them or create new ones. To overcome this situation, C++11 introduced the concept of <strong>&#8220;user-defined literals&#8221;</strong> that will give to the user, the ability to create new custom literal modifiers. The new user-defined literals can create either built-in types (e.g. int) or user-define types (e.g. classes), and the fact that they could be very useful is an effect that they can return objects instead of only primitives.</p>
<p>The new syntax for the user-defined literals is:</p>
<div class="codecolorer-container cpp railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">OutputType operator <span style="color: #FF0000;">&quot;&quot;</span> _suffix<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>literal_string<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span></div></td></tr></tbody></table></div>
<p>&#8230; in the case of a literal string. The <strong>OutputType</strong> is anything you want (object or primitive), the &#8220;_suffix&#8221; is the name of the literal modifier, isn&#8217;t required to use the underline in front of it, but if you don&#8217;t use you&#8217;ll get some warnings telling you that suffixes not preceded by the underline are reserved for future standardization.</p>
<h3>Examples</h3>
<h4>Kmh to Mph converter</h4>
<div class="codecolorer-container cpp railscasts codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666;">// stupid converter class</span><br />
<span style="color: #0000ff;">class</span> Converter<br />
<span style="color: #008000;">&#123;</span><br />
<span style="color: #0000ff;">public</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; Converter<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">double</span> kmph<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span> m_kmph<span style="color: #008000;">&#40;</span>kmph<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; ~Converter<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">double</span> to_mph<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> m_kmph <span style="color: #000040;">/</span> <span style="color:#800080;">1.609344</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">private</span><span style="color: #008080;">:</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">double</span> m_kmph<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #666666;">// user-defined literal</span><br />
Converter operator <span style="color: #FF0000;">&quot;&quot;</span> kmph<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">long</span> <span style="color: #0000ff;">double</span> kmph<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> Converter<span style="color: #008000;">&#40;</span>kmph<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;Converter: &quot;</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #008000;">&#40;</span>80kmph<span style="color: #008000;">&#41;</span>.<span style="color: #007788;">to_mph</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// note that I'm using parenthesis in order to</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// be able to call the 'to_mph' method</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<p>Note that the literal for for numeric types should be either <strong>long double</strong> (for floating point literals) or <strong>unsigned long long</strong> (for integral literals). There is no signed type, because a signed literal is parsed as an expression with a sign as unary prefix and the unsigned number part.</p>
<h4>std::string literal</h4>
<div class="codecolorer-container cpp railscasts codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">std<span style="color: #008080;">::</span><span style="color: #007788;">string</span> operator <span style="color: #FF0000;">&quot;&quot;</span> s <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span><span style="color: #000040;">*</span> p, <span style="color: #0000ff;">size_t</span> n<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> std<span style="color: #008080;">::</span><span style="color: #007788;">string</span><span style="color: #008000;">&#40;</span>p,n<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;convert me to a string&quot;</span>s.<span style="color: #007788;">length</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// here you don't need the parenthesis, note that the</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// c-string was automagically converted to std::string</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<h4>system() call</h4>
<div class="codecolorer-container cpp railscasts codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">int</span> operator <span style="color: #FF0000;">&quot;&quot;</span> ex<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>cmd, <span style="color: #0000ff;">size_t</span> num_chars<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">system</span><span style="color: #008000;">&#40;</span>cmd<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #FF0000;">&quot;ls -lah&quot;</span>ex<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<h4>alias and std::map</h4>
<div class="codecolorer-container cpp railscasts codecolorer-noborder" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br /></div></td><td><div class="cpp codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff;">typedef</span> std<span style="color: #008080;">::</span><span style="color: #007788;">map</span><span style="color: #000080;">&lt;</span>std<span style="color: #008080;">::</span><span style="color: #007788;">string</span>, <span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> MyMap<span style="color: #008080;">;</span><br />
MyMap create_map<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; MyMap m<span style="color: #008080;">;</span><br />
&nbsp; &nbsp; m<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">&quot;lol&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">7</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> m<span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span><br />
<span style="color: #0000ff;">auto</span> m <span style="color: #000080;">=</span> create_map<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span><br />
<br />
<span style="color: #0000ff;">int</span><span style="color: #000040;">&amp;</span> operator <span style="color: #FF0000;">&quot;&quot;</span> m<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span>key, <span style="color: #0000ff;">size_t</span> length<span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> m<span style="color: #008000;">&#91;</span>key<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span><br />
<br />
<span style="color: #0000ff;">int</span> main<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #008000;">&#41;</span><br />
<span style="color: #008000;">&#123;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;lol&quot;</span>m <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// 7</span><br />
&nbsp; &nbsp; <span style="color: #FF0000;">&quot;lol&quot;</span>m <span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; std<span style="color: #008080;">::</span><span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> <span style="color: #FF0000;">&quot;lol&quot;</span>m <span style="color: #000080;">&lt;&lt;</span> std<span style="color: #008080;">::</span><span style="color: #007788;">endl</span><span style="color: #008080;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666;">// 2</span><br />
&nbsp; &nbsp; <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span><br />
<span style="color: #008000;">&#125;</span></div></td></tr></tbody></table></div>
<h3>References</h3>
<p><a href="http://en.wikipedia.org/wiki/C%2B%2B11#User-defined_literals" title="Wikipedia :: C++11 (User-defined literals)" target="_blank">Wikipedia :: C++11 (User-defined literals)</a></p>
<p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf" title="Proposal N2765" target="_blank">Proposal N2765</a></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/gsv4C4Q0CDs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=2104</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=2104</feedburner:origLink></item>
		<item>
		<title>Machine Learning :: Text feature extraction (tf-idf) – Part II</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/YoTmygrjMTM/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=1747#comments</comments>
		<pubDate>Mon, 03 Oct 2011 18:43:56 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[feature extraction]]></category>
		<category><![CDATA[inverse document frequency]]></category>
		<category><![CDATA[machine learning]]></category>
		<category><![CDATA[scikit.learn]]></category>
		<category><![CDATA[sklearn]]></category>
		<category><![CDATA[term frequency]]></category>
		<category><![CDATA[text mining]]></category>
		<category><![CDATA[tf-idf]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=1747</guid>
		<description><![CDATA[Read the first part of this tutorial: Text feature extraction (tf-idf) &#8211; Part I. This post is a continuation of the first part where we started to learn the theory and practice about text feature extraction and vector space model representation. I really recommend you to read the first part of the post series in [...]]]></description>
			<content:encoded><![CDATA[<p>Read the first part of this tutorial: <a title="Machine Learning :: Text feature extraction (tf-idf) – Part I" href="http://pyevolve.sourceforge.net/wordpress/?p=1589">Text feature extraction (tf-idf) &#8211; Part I</a>.</p>
<p>This post is a <strong>continuation</strong> of the first part where we started to learn the theory and practice about text feature extraction and vector space model representation. I really recommend you<strong> to read the first part</strong> of the post series in order to follow this second post.</p>
<p>Since a lot of people liked the first part of this tutorial, this second part is a little longer than the first.</p>
<h3>Introduction</h3>
<p>In the first post, we learned how to use the <strong>term-frequency</strong> to represent textual information in the vector space. However, the main problem with the term-frequency approach is that it scales up frequent terms and scales down rare terms which are empirically more informative than the high frequency terms. The basic intuition is that a term that occurs frequently in many documents is not a good discriminator, and really makes sense (at least in many experimental tests); the important question here is: why would you, in a classification problem for instance, emphasize a term which is almost present in the entire corpus of your documents ?</p>
<p>The tf-idf weight comes to solve this problem. What tf-idf gives is how important is a word to a document in a collection, and that&#8217;s why tf-idf incorporates local and global parameters, because it takes in consideration not only the isolated term but also the term within the document collection. What tf-idf then does to solve that problem, is to scale down the frequent terms while scaling up the rare terms; a term that occurs 10 times more than another isn&#8217;t 10 times more important than it, that&#8217;s why tf-idf uses the logarithmic scale to do that.</p>
<p>But let&#8217;s go back to our definition of the <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Btf%7D%28t%2Cd%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{tf}(t,d)' title='\mathrm{tf}(t,d)' class='latex' /> which is actually the term count of the term <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' /> in the document <img src='http://s.wordpress.com/latex.php?latex=d&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d' title='d' class='latex' />. The use of this simple term frequency could lead us to problems like <em>keyword spamming</em>, which is when we have a repeated term in a document with the purpose of improving its ranking on an IR (<em>Information Retrieval</em>) system or even create a bias towards long documents, making them look more important than they are just because of the high frequency of the term in the document.</p>
<p>To overcome this problem, the term frequency <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Btf%7D%28t%2Cd%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{tf}(t,d)' title='\mathrm{tf}(t,d)' class='latex' /> of a document on a vector space is usually also normalized. Let&#8217;s see how we normalize this vector.</p>
<h3>Vector normalization</h3>
<p>Suppose we are going to normalize the term-frequency vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_4%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_4}}' title='\vec{v_{d_4}}' class='latex' /> that we have calculated in the first part of this tutorial. The document <img src='http://s.wordpress.com/latex.php?latex=d4&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d4' title='d4' class='latex' /> from the first part of this tutorial had this textual representation:</p>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">d4: We can see the shining sun, the bright sun.</div></td></tr></tbody></table></div>
<p>And the vector space representation using the non-normalized term-frequency of that document was:</p>
<img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_4%7D%7D%20%3D%20%280%2C2%2C1%2C0%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_4}} = (0,2,1,0)' title='\vec{v_{d_4}} = (0,2,1,0)' class='latex' />
<p>To normalize the vector, is the same as calculating the <a title="Wikipedia: Unit Vector" href="http://en.wikipedia.org/wiki/Unit_vector" target="_blank">Unit Vector</a> of the vector, and they are denoted using the &#8220;hat&#8221; notation: <img src='http://s.wordpress.com/latex.php?latex=%5Chat%7Bv%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\hat{v}' title='\hat{v}' class='latex' />. The definition of the unit vector <img src='http://s.wordpress.com/latex.php?latex=%5Chat%7Bv%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\hat{v}' title='\hat{v}' class='latex' /> of a vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v}' title='\vec{v}' class='latex' /> is:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cdisplaystyle%20%5Chat%7Bv%7D%20%3D%20%5Cfrac%7B%5Cvec%7Bv%7D%7D%7B%5C%7C%5Cvec%7Bv%7D%5C%7C_p%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \displaystyle \hat{v} = \frac{\vec{v}}{\|\vec{v}\|_p}   ' title='   \displaystyle \hat{v} = \frac{\vec{v}}{\|\vec{v}\|_p}   ' class='latex' />
<p>Where the <img src='http://s.wordpress.com/latex.php?latex=%5Chat%7Bv%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\hat{v}' title='\hat{v}' class='latex' /> is the unit vector, or the normalized vector, the <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v}' title='\vec{v}' class='latex' /> is the vector going to be normalized and the <img src='http://s.wordpress.com/latex.php?latex=%5C%7C%5Cvec%7Bv%7D%5C%7C_p&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\|\vec{v}\|_p' title='\|\vec{v}\|_p' class='latex' /> is the norm (magnitude, length) of the vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v}' title='\vec{v}' class='latex' /> in the <img src='http://s.wordpress.com/latex.php?latex=L%5Ep&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L^p' title='L^p' class='latex' /> space (don&#8217;t worry, I&#8217;m going to explain it all).</p>
<p>The unit vector is actually nothing more than a normalized version of the vector, is a vector which the length is 1.</p>
<div class="mceTemp mceIEcenter">
<dl id="" class="wp-caption aligncenter" style="width: 429px;">
<dt class="wp-caption-dt"><img title="Vector Normalization" src="http://processing.org/learning/pvector/imgs/normalize1.jpg" alt="" width="419" height="186" /></dt>
</dl>
</div>
<p style="text-align: center;"><em>Source: http://processing.org/learning/pvector/</em></p>
<p>But the important question here is how the length of the vector is calculated and to understand this, you must understand the motivation of the <img src='http://s.wordpress.com/latex.php?latex=L%5Ep&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='L^p' title='L^p' class='latex' /> spaces, also called <a title="Wikipedia: Lp Space" href="http://en.wikipedia.org/wiki/Lp_space" target="_blank">Lebesgue spaces</a>.</p>
<h3>Lebesgue spaces</h3>
<div class="mceTemp mceIEcenter">
<dl id="" class="wp-caption aligncenter" style="width: 298px;">
<dt class="wp-caption-dt"><img title="Vector Magnitude" src="http://processing.org/learning/pvector/imgs/mag.jpg" alt="" width="288" height="206" /></dt>
</dl>
</div>
<p style="text-align: center;"><em>Source: http://processing.org/learning/pvector/</em></p>
<p>Usually, the length of a vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bu%7D%20%3D%20%28u_1%2C%20u_2%2C%20u_3%2C%20%5Cldots%2C%20u_n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{u} = (u_1, u_2, u_3, \ldots, u_n)' title='\vec{u} = (u_1, u_2, u_3, \ldots, u_n)' class='latex' /> is calculated using the <a title="Wolfram :: Mathworld :: L2 Norm" href="http://mathworld.wolfram.com/L2-Norm.html" target="_blank">Euclidean norm</a> &#8211; <em>a norm is a function that assigns a strictly positive length or size to all vectors in a vector space</em> -, which is defined by:</p>
<div class="mceTemp mceIEcenter">
<dl id="" class="wp-caption aligncenter" style="width: 247px;">
<dt class="wp-caption-dt"><img title="Vector Pythagorean" src="http://processing.org/learning/pvector/imgs/pythagorean.jpg" alt="" width="237" height="135" /></dt>
</dl>
</div>
<p style="text-align: center;"> <em>Source: http://processing.org/learning/pvector/</em></p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5C%7C%5Cvec%7Bu%7D%5C%7C%20%3D%20%5Csqrt%7Bu%5E2_1%20%2B%20u%5E2_2%20%2B%20u%5E2_3%20%2B%20%5Cldots%20%2B%20u%5E2_n%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \|\vec{u}\| = \sqrt{u^2_1 + u^2_2 + u^2_3 + \ldots + u^2_n}   ' title='   \|\vec{u}\| = \sqrt{u^2_1 + u^2_2 + u^2_3 + \ldots + u^2_n}   ' class='latex' />
<p>But this isn&#8217;t the only way to define length, and that&#8217;s why you see (sometimes) a number <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' /> together with the norm notation, like in <img src='http://s.wordpress.com/latex.php?latex=%5C%7C%5Cvec%7Bu%7D%5C%7C_p&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\|\vec{u}\|_p' title='\|\vec{u}\|_p' class='latex' />. That&#8217;s because it could be generalized as:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cdisplaystyle%20%5C%7C%5Cvec%7Bu%7D%5C%7C_p%20%3D%20%28%20%5Cleft%7Cu_1%5Cright%7C%5Ep%20%2B%20%5Cleft%7Cu_2%5Cright%7C%5Ep%20%2B%20%5Cleft%7Cu_3%5Cright%7C%5Ep%20%2B%20%5Cldots%20%2B%20%5Cleft%7Cu_n%5Cright%7C%5Ep%20%29%5E%5Cfrac%7B1%7D%7Bp%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \displaystyle \|\vec{u}\|_p = ( \left|u_1\right|^p + \left|u_2\right|^p + \left|u_3\right|^p + \ldots + \left|u_n\right|^p )^\frac{1}{p}   ' title='   \displaystyle \|\vec{u}\|_p = ( \left|u_1\right|^p + \left|u_2\right|^p + \left|u_3\right|^p + \ldots + \left|u_n\right|^p )^\frac{1}{p}   ' class='latex' />
<p>and simplified as:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cdisplaystyle%20%5C%7C%5Cvec%7Bu%7D%5C%7C_p%20%3D%20%28%5Csum%5Climits_%7Bi%3D1%7D%5E%7Bn%7D%5Cleft%7C%5Cvec%7Bu%7D_i%5Cright%7C%5Ep%29%5E%5Cfrac%7B1%7D%7Bp%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \displaystyle \|\vec{u}\|_p = (\sum\limits_{i=1}^{n}\left|\vec{u}_i\right|^p)^\frac{1}{p}   ' title='   \displaystyle \|\vec{u}\|_p = (\sum\limits_{i=1}^{n}\left|\vec{u}_i\right|^p)^\frac{1}{p}   ' class='latex' />
<p>So when you read about a <strong>L2-norm</strong>, you&#8217;re reading about the <a title="Wikipedia: Norm :: Euclidian Norm" href="http://en.wikipedia.org/wiki/Norm_%28mathematics%29#Euclidean_norm" target="_blank"><strong>Euclidean norm</strong></a>, a norm with <img src='http://s.wordpress.com/latex.php?latex=p%3D2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p=2' title='p=2' class='latex' />, the most common norm used to measure the length of a vector, typically called &#8220;magnitude&#8221;; actually, when you have an unqualified length measure (without the <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' /> number), you have the <strong>L2-norm</strong> (Euclidean norm).</p>
<p>When you read about a<strong> L1-norm</strong>, you&#8217;re reading about the norm with <img src='http://s.wordpress.com/latex.php?latex=p%3D1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p=1' title='p=1' class='latex' />, defined as:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cdisplaystyle%20%5C%7C%5Cvec%7Bu%7D%5C%7C_1%20%3D%20%28%20%5Cleft%7Cu_1%5Cright%7C%20%2B%20%5Cleft%7Cu_2%5Cright%7C%20%2B%20%5Cleft%7Cu_3%5Cright%7C%20%2B%20%5Cldots%20%2B%20%5Cleft%7Cu_n%5Cright%7C%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \displaystyle \|\vec{u}\|_1 = ( \left|u_1\right| + \left|u_2\right| + \left|u_3\right| + \ldots + \left|u_n\right|)   ' title='   \displaystyle \|\vec{u}\|_1 = ( \left|u_1\right| + \left|u_2\right| + \left|u_3\right| + \ldots + \left|u_n\right|)   ' class='latex' />
<p>Which is nothing more than a simple sum of the components of the vector, also known as <a title="Wikipedia: Taxicab Geometry" href="http://en.wikipedia.org/wiki/Taxicab_geometry" target="_blank">Taxicab distance</a>, also called Manhattan distance.</p>
<p style="text-align: center;"><img class="aligncenter" title="Manhattan Distance" src="http://upload.wikimedia.org/wikipedia/commons/0/08/Manhattan_distance.svg" alt="" width="226" height="226" /></p>
<p style="text-align: center;"><em>Taxicab geometry versus Euclidean distance: In taxicab geometry all three pictured lines have the same length (12) for the same route. In Euclidean geometry, the green line has length <img src='http://s.wordpress.com/latex.php?latex=6%20%5Ctimes%20%5Csqrt%7B2%7D%20%5Capprox%208.48&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='6 \times \sqrt{2} \approx 8.48' title='6 \times \sqrt{2} \approx 8.48' class='latex' />, and is the unique shortest path.<br />
Source: <a title="Wikipedia :: Taxicab Geometry" href="http://en.wikipedia.org/wiki/Taxicab_geometry">Wikipedia :: Taxicab Geometry</a><br />
</em></p>
<p>Note that you can also use any norm to normalize the vector, but we&#8217;re going to use the most common norm, the L2-Norm, which is also the default in the 0.9 release of the <a title="Scikit.learn" href="http://scikit-learn.sourceforge.net/" target="_blank">scikits.learn</a>. You can also find papers comparing the performance of the two approaches among other methods to normalize the document vector, actually you can use any other method, but you have to be concise, once you&#8217;ve used a norm, you have to use it for the whole process directly involving the norm (<em>a unit vector that used a L1-norm isn&#8217;t going to have the length 1 if you&#8217;re going to take its L2-norm later</em>).</p>
<h3>Back to vector normalization</h3>
<p>Now that you know what the vector normalization process is, we can try a concrete example, the process of using the L2-norm (we&#8217;ll use the right terms now) to normalize our vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_4%7D%7D%20%3D%20%280%2C2%2C1%2C0%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_4}} = (0,2,1,0)' title='\vec{v_{d_4}} = (0,2,1,0)' class='latex' /> in order to get its unit vector <img src='http://s.wordpress.com/latex.php?latex=%5Chat%7Bv_%7Bd_4%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\hat{v_{d_4}}' title='\hat{v_{d_4}}' class='latex' />. To do that, we&#8217;ll simple plug it into the definition of the unit vector to evaluate it:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Chat%7Bv%7D%20%3D%20%5Cfrac%7B%5Cvec%7Bv%7D%7D%7B%5C%7C%5Cvec%7Bv%7D%5C%7C_p%7D%20%5C%5C%20%5C%5C%20%20%20%5Chat%7Bv_%7Bd_4%7D%7D%20%3D%20%5Cfrac%7B%5Cvec%7Bv_%7Bd_4%7D%7D%7D%7B%7C%7C%5Cvec%7Bv_%7Bd_4%7D%7D%7C%7C_2%7D%20%5C%5C%20%5C%5C%20%5C%5C%20%20%20%5Chat%7Bv_%7Bd_4%7D%7D%20%3D%20%5Cfrac%7B%280%2C2%2C1%2C0%29%7D%7B%5Csqrt%7B0%5E2%20%2B%202%5E2%20%2B%201%5E2%20%2B%200%5E2%7D%7D%20%5C%5C%20%5C%5C%20%20%20%5Chat%7Bv_%7Bd_4%7D%7D%20%3D%20%5Cfrac%7B%280%2C2%2C1%2C0%29%7D%7B%5Csqrt%7B5%7D%7D%20%5C%5C%20%5C%5C%20%20%20%5Csmall%20%5Chat%7Bv_%7Bd_4%7D%7D%20%3D%20%280.0%2C%200.89442719%2C%200.4472136%2C%200.0%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=1' alt='   \hat{v} = \frac{\vec{v}}{\|\vec{v}\|_p} \\ \\   \hat{v_{d_4}} = \frac{\vec{v_{d_4}}}{||\vec{v_{d_4}}||_2} \\ \\ \\   \hat{v_{d_4}} = \frac{(0,2,1,0)}{\sqrt{0^2 + 2^2 + 1^2 + 0^2}} \\ \\   \hat{v_{d_4}} = \frac{(0,2,1,0)}{\sqrt{5}} \\ \\   \small \hat{v_{d_4}} = (0.0, 0.89442719, 0.4472136, 0.0)   ' title='   \hat{v} = \frac{\vec{v}}{\|\vec{v}\|_p} \\ \\   \hat{v_{d_4}} = \frac{\vec{v_{d_4}}}{||\vec{v_{d_4}}||_2} \\ \\ \\   \hat{v_{d_4}} = \frac{(0,2,1,0)}{\sqrt{0^2 + 2^2 + 1^2 + 0^2}} \\ \\   \hat{v_{d_4}} = \frac{(0,2,1,0)}{\sqrt{5}} \\ \\   \small \hat{v_{d_4}} = (0.0, 0.89442719, 0.4472136, 0.0)   ' class='latex' />
<p>And that is it ! Our normalized vector <img src='http://s.wordpress.com/latex.php?latex=%5Chat%7Bv_%7Bd_4%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\hat{v_{d_4}}' title='\hat{v_{d_4}}' class='latex' /> has now a L2-norm <img src='http://s.wordpress.com/latex.php?latex=%5C%7C%5Chat%7Bv_%7Bd_4%7D%7D%5C%7C_2%20%3D%201.0&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\|\hat{v_{d_4}}\|_2 = 1.0' title='\|\hat{v_{d_4}}\|_2 = 1.0' class='latex' />.</p>
<p><strong>Note that here we have normalized our term frequency document vector, but later we&#8217;re going to do that after the calculation of the tf-idf.</strong></p>
<h3> The term frequency &#8211; inverse document frequency (tf-idf) weight</h3>
<p>Now you have understood how the vector normalization works in theory and practice, let&#8217;s continue our tutorial. Suppose you have the following documents in your collection (taken from the first part of tutorial):</p>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Train Document Set:<br />
<br />
d1: The sky is blue.<br />
d2: The sun is bright.<br />
<br />
Test Document Set:<br />
<br />
d3: The sun in the sky is bright.<br />
d4: We can see the shining sun, the bright sun.</div></td></tr></tbody></table></div>
<p>Your document space can be defined then as <img src='http://s.wordpress.com/latex.php?latex=D%20%3D%20%5C%7B%20d_1%2C%20d_2%2C%20%5Cldots%2C%20d_n%20%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D = \{ d_1, d_2, \ldots, d_n \}' title='D = \{ d_1, d_2, \ldots, d_n \}' class='latex' /> where <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 the number of documents in your corpus, and in our case as <img src='http://s.wordpress.com/latex.php?latex=D_%7Btrain%7D%20%3D%20%5C%7Bd_1%2C%20d_2%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D_{train} = \{d_1, d_2\}' title='D_{train} = \{d_1, d_2\}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=D_%7Btest%7D%20%3D%20%5C%7Bd_3%2C%20d_4%5C%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='D_{test} = \{d_3, d_4\}' title='D_{test} = \{d_3, d_4\}' class='latex' />. The cardinality of our document space is defined by <img src='http://s.wordpress.com/latex.php?latex=%5Cleft%7C%7BD_%7Btrain%7D%7D%5Cright%7C%20%3D%202&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\left|{D_{train}}\right| = 2' title='\left|{D_{train}}\right| = 2' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Cleft%7C%7BD_%7Btest%7D%7D%5Cright%7C%20%3D%202&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\left|{D_{test}}\right| = 2' title='\left|{D_{test}}\right| = 2' class='latex' />, since we have only 2 two documents for training and testing, but they obviously don&#8217;t need to have the same cardinality.</p>
<p>Let&#8217;s see now, how idf (inverse document frequency) is then defined:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cdisplaystyle%20%5Cmathrm%7Bidf%7D%28t%29%20%3D%20%5Clog%7B%5Cfrac%7B%5Cleft%7CD%5Cright%7C%7D%7B1%2B%5Cleft%7C%5C%7Bd%20%3A%20t%20%5Cin%20d%5C%7D%5Cright%7C%7D%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \displaystyle \mathrm{idf}(t) = \log{\frac{\left|D\right|}{1+\left|\{d : t \in d\}\right|}}   ' title='   \displaystyle \mathrm{idf}(t) = \log{\frac{\left|D\right|}{1+\left|\{d : t \in d\}\right|}}   ' class='latex' />
<p>where <img src='http://s.wordpress.com/latex.php?latex=%5Cleft%7C%5C%7Bd%20%3A%20t%20%5Cin%20d%5C%7D%5Cright%7C&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\left|\{d : t \in d\}\right|' title='\left|\{d : t \in d\}\right|' class='latex' /> is the <strong>number of documents</strong> where the term <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' /> appears, when the term-frequency function satisfies <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Btf%7D%28t%2Cd%29%20%5Cneq%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{tf}(t,d) \neq 0' title='\mathrm{tf}(t,d) \neq 0' class='latex' />, we&#8217;re only adding 1 into the formula to avoid zero-division.</p>
<p>The formula for the tf-idf is then:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Btf%5Cmbox%7B-%7Didf%7D%28t%29%20%3D%20%5Cmathrm%7Btf%7D%28t%2C%20d%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{tf\mbox{-}idf}(t) = \mathrm{tf}(t, d) \times \mathrm{idf}(t)   ' title='   \mathrm{tf\mbox{-}idf}(t) = \mathrm{tf}(t, d) \times \mathrm{idf}(t)   ' class='latex' />
<p>and this formula has an important consequence: a high weight of the tf-idf calculation is reached when you have a high term frequency (tf) in the given document (<em>local parameter</em>) and a low document frequency of the term in the whole collection (<em>global parameter</em>).</p>
<p>Now let&#8217;s calculate the idf for each feature present in the feature matrix with the term frequency we have calculated in the first tutorial:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20M_%7Btrain%7D%20%3D%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%200%20%26%201%20%26%201%20%26%201%5C%5C%20%20%200%20%26%202%20%26%201%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   M_{train} =   \begin{bmatrix}   0 &amp; 1 &amp; 1 &amp; 1\\   0 &amp; 2 &amp; 1 &amp; 0   \end{bmatrix}   ' title='   M_{train} =   \begin{bmatrix}   0 &amp; 1 &amp; 1 &amp; 1\\   0 &amp; 2 &amp; 1 &amp; 0   \end{bmatrix}   ' class='latex' />
<p>Since we have 4 features, we have to calculate <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Bidf%7D%28t_1%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{idf}(t_1)' title='\mathrm{idf}(t_1)' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Bidf%7D%28t_2%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{idf}(t_2)' title='\mathrm{idf}(t_2)' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Bidf%7D%28t_3%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{idf}(t_3)' title='\mathrm{idf}(t_3)' class='latex' />, <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Bidf%7D%28t_4%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{idf}(t_4)' title='\mathrm{idf}(t_4)' class='latex' />:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Bidf%7D%28t_1%29%20%3D%20%5Clog%7B%5Cfrac%7B%5Cleft%7CD%5Cright%7C%7D%7B1%2B%5Cleft%7C%5C%7Bd%20%3A%20t_1%20%5Cin%20d%5C%7D%5Cright%7C%7D%7D%20%3D%20%5Clog%7B%5Cfrac%7B2%7D%7B1%7D%7D%20%3D%200.69314718%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{idf}(t_1) = \log{\frac{\left|D\right|}{1+\left|\{d : t_1 \in d\}\right|}} = \log{\frac{2}{1}} = 0.69314718   ' title='   \mathrm{idf}(t_1) = \log{\frac{\left|D\right|}{1+\left|\{d : t_1 \in d\}\right|}} = \log{\frac{2}{1}} = 0.69314718   ' class='latex' />
<p>&nbsp;</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Bidf%7D%28t_2%29%20%3D%20%5Clog%7B%5Cfrac%7B%5Cleft%7CD%5Cright%7C%7D%7B1%2B%5Cleft%7C%5C%7Bd%20%3A%20t_2%20%5Cin%20d%5C%7D%5Cright%7C%7D%7D%20%3D%20%5Clog%7B%5Cfrac%7B2%7D%7B3%7D%7D%20%3D%20-0.40546511%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{idf}(t_2) = \log{\frac{\left|D\right|}{1+\left|\{d : t_2 \in d\}\right|}} = \log{\frac{2}{3}} = -0.40546511   ' title='   \mathrm{idf}(t_2) = \log{\frac{\left|D\right|}{1+\left|\{d : t_2 \in d\}\right|}} = \log{\frac{2}{3}} = -0.40546511   ' class='latex' />
<p>&nbsp;</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Bidf%7D%28t_3%29%20%3D%20%5Clog%7B%5Cfrac%7B%5Cleft%7CD%5Cright%7C%7D%7B1%2B%5Cleft%7C%5C%7Bd%20%3A%20t_3%20%5Cin%20d%5C%7D%5Cright%7C%7D%7D%20%3D%20%5Clog%7B%5Cfrac%7B2%7D%7B3%7D%7D%20%3D%20-0.40546511%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{idf}(t_3) = \log{\frac{\left|D\right|}{1+\left|\{d : t_3 \in d\}\right|}} = \log{\frac{2}{3}} = -0.40546511   ' title='   \mathrm{idf}(t_3) = \log{\frac{\left|D\right|}{1+\left|\{d : t_3 \in d\}\right|}} = \log{\frac{2}{3}} = -0.40546511   ' class='latex' />
<p>&nbsp;</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Bidf%7D%28t_4%29%20%3D%20%5Clog%7B%5Cfrac%7B%5Cleft%7CD%5Cright%7C%7D%7B1%2B%5Cleft%7C%5C%7Bd%20%3A%20t_4%20%5Cin%20d%5C%7D%5Cright%7C%7D%7D%20%3D%20%5Clog%7B%5Cfrac%7B2%7D%7B2%7D%7D%20%3D%200.0%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{idf}(t_4) = \log{\frac{\left|D\right|}{1+\left|\{d : t_4 \in d\}\right|}} = \log{\frac{2}{2}} = 0.0   ' title='   \mathrm{idf}(t_4) = \log{\frac{\left|D\right|}{1+\left|\{d : t_4 \in d\}\right|}} = \log{\frac{2}{2}} = 0.0   ' class='latex' />
<p>These idf weights can be represented by a vector as:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cvec%7Bidf_%7Btrain%7D%7D%20%3D%20%280.69314718%2C%20-0.40546511%2C%20-0.40546511%2C%200.0%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \vec{idf_{train}} = (0.69314718, -0.40546511, -0.40546511, 0.0)   ' title='   \vec{idf_{train}} = (0.69314718, -0.40546511, -0.40546511, 0.0)   ' class='latex' />
<p>Now that we have our matrix with the term frequency (<img src='http://s.wordpress.com/latex.php?latex=M_%7Btrain%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{train}' title='M_{train}' class='latex' />) and the vector representing the idf for each feature of our matrix (<img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bidf_%7Btrain%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{idf_{train}}' title='\vec{idf_{train}}' class='latex' />), we can calculate our tf-idf weights. What we have to do is a simple multiplication of each column of the matrix <img src='http://s.wordpress.com/latex.php?latex=M_%7Btrain%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{train}' title='M_{train}' class='latex' /> with the respective <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bidf_%7Btrain%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{idf_{train}}' title='\vec{idf_{train}}' class='latex' /> vector dimension. To do that, we can create a square <a title="Wikipedia: Diagonal matrix" href="http://en.wikipedia.org/wiki/Diagonal_matrix" target="_blank">diagonal matrix</a> called <img src='http://s.wordpress.com/latex.php?latex=M_%7Bidf%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{idf}' title='M_{idf}' class='latex' /> with both the vertical and horizontal dimensions equal to the vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bidf_%7Btrain%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{idf_{train}}' title='\vec{idf_{train}}' class='latex' /> dimension:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20M_%7Bidf%7D%20%3D%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%200.69314718%20%26%200%20%26%200%20%26%200%5C%5C%20%20%200%20%26%20-0.40546511%20%26%200%20%26%200%5C%5C%20%20%200%20%26%200%20%26%20-0.40546511%20%26%200%5C%5C%20%20%200%20%26%200%20%26%200%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   M_{idf} =   \begin{bmatrix}   0.69314718 &amp; 0 &amp; 0 &amp; 0\\   0 &amp; -0.40546511 &amp; 0 &amp; 0\\   0 &amp; 0 &amp; -0.40546511 &amp; 0\\   0 &amp; 0 &amp; 0 &amp; 0   \end{bmatrix}   ' title='   M_{idf} =   \begin{bmatrix}   0.69314718 &amp; 0 &amp; 0 &amp; 0\\   0 &amp; -0.40546511 &amp; 0 &amp; 0\\   0 &amp; 0 &amp; -0.40546511 &amp; 0\\   0 &amp; 0 &amp; 0 &amp; 0   \end{bmatrix}   ' class='latex' />
<p>and then multiply it to the term frequency matrix, so the final result can be defined then as:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20M_%7Btf%5Cmbox%7B-%7Didf%7D%20%3D%20M_%7Btrain%7D%20%5Ctimes%20M_%7Bidf%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   M_{tf\mbox{-}idf} = M_{train} \times M_{idf}   ' title='   M_{tf\mbox{-}idf} = M_{train} \times M_{idf}   ' class='latex' />
<p>Please note that the matrix multiplication isn&#8217;t commutative, the result of <img src='http://s.wordpress.com/latex.php?latex=A%20%5Ctimes%20B&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='A \times B' title='A \times B' class='latex' /> will be different than the result of the <img src='http://s.wordpress.com/latex.php?latex=B%20%5Ctimes%20A&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='B \times A' title='B \times A' class='latex' />, and this is why the <img src='http://s.wordpress.com/latex.php?latex=M_%7Bidf%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{idf}' title='M_{idf}' class='latex' /> is on the right side of the multiplication, to accomplish the desired effect of multiplying each idf value to its corresponding feature:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%20%5Cmathrm%7Btf%7D%28t_1%2C%20d_1%29%20%26%20%5Cmathrm%7Btf%7D%28t_2%2C%20d_1%29%20%26%20%5Cmathrm%7Btf%7D%28t_3%2C%20d_1%29%20%26%20%5Cmathrm%7Btf%7D%28t_4%2C%20d_1%29%5C%5C%20%20%20%5Cmathrm%7Btf%7D%28t_1%2C%20d_2%29%20%26%20%5Cmathrm%7Btf%7D%28t_2%2C%20d_2%29%20%26%20%5Cmathrm%7Btf%7D%28t_3%2C%20d_2%29%20%26%20%5Cmathrm%7Btf%7D%28t_4%2C%20d_2%29%20%20%20%5Cend%7Bbmatrix%7D%20%20%20%5Ctimes%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%20%5Cmathrm%7Bidf%7D%28t_1%29%20%26%200%20%26%200%20%26%200%5C%5C%20%20%200%20%26%20%5Cmathrm%7Bidf%7D%28t_2%29%20%26%200%20%26%200%5C%5C%20%20%200%20%26%200%20%26%20%5Cmathrm%7Bidf%7D%28t_3%29%20%26%200%5C%5C%20%20%200%20%26%200%20%26%200%20%26%20%5Cmathrm%7Bidf%7D%28t_4%29%20%20%20%5Cend%7Bbmatrix%7D%20%20%20%5C%5C%20%3D%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%20%5Cmathrm%7Btf%7D%28t_1%2C%20d_1%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_1%29%20%26%20%5Cmathrm%7Btf%7D%28t_2%2C%20d_1%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_2%29%20%26%20%5Cmathrm%7Btf%7D%28t_3%2C%20d_1%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_3%29%20%26%20%5Cmathrm%7Btf%7D%28t_4%2C%20d_1%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_4%29%5C%5C%20%20%20%5Cmathrm%7Btf%7D%28t_1%2C%20d_2%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_1%29%20%26%20%5Cmathrm%7Btf%7D%28t_2%2C%20d_2%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_2%29%20%26%20%5Cmathrm%7Btf%7D%28t_3%2C%20d_2%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_3%29%20%26%20%5Cmathrm%7Btf%7D%28t_4%2C%20d_2%29%20%5Ctimes%20%5Cmathrm%7Bidf%7D%28t_4%29%20%20%20%5Cend%7Bbmatrix%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \begin{bmatrix}   \mathrm{tf}(t_1, d_1) &amp; \mathrm{tf}(t_2, d_1) &amp; \mathrm{tf}(t_3, d_1) &amp; \mathrm{tf}(t_4, d_1)\\   \mathrm{tf}(t_1, d_2) &amp; \mathrm{tf}(t_2, d_2) &amp; \mathrm{tf}(t_3, d_2) &amp; \mathrm{tf}(t_4, d_2)   \end{bmatrix}   \times   \begin{bmatrix}   \mathrm{idf}(t_1) &amp; 0 &amp; 0 &amp; 0\\   0 &amp; \mathrm{idf}(t_2) &amp; 0 &amp; 0\\   0 &amp; 0 &amp; \mathrm{idf}(t_3) &amp; 0\\   0 &amp; 0 &amp; 0 &amp; \mathrm{idf}(t_4)   \end{bmatrix}   \\ =   \begin{bmatrix}   \mathrm{tf}(t_1, d_1) \times \mathrm{idf}(t_1) &amp; \mathrm{tf}(t_2, d_1) \times \mathrm{idf}(t_2) &amp; \mathrm{tf}(t_3, d_1) \times \mathrm{idf}(t_3) &amp; \mathrm{tf}(t_4, d_1) \times \mathrm{idf}(t_4)\\   \mathrm{tf}(t_1, d_2) \times \mathrm{idf}(t_1) &amp; \mathrm{tf}(t_2, d_2) \times \mathrm{idf}(t_2) &amp; \mathrm{tf}(t_3, d_2) \times \mathrm{idf}(t_3) &amp; \mathrm{tf}(t_4, d_2) \times \mathrm{idf}(t_4)   \end{bmatrix}   ' title='   \begin{bmatrix}   \mathrm{tf}(t_1, d_1) &amp; \mathrm{tf}(t_2, d_1) &amp; \mathrm{tf}(t_3, d_1) &amp; \mathrm{tf}(t_4, d_1)\\   \mathrm{tf}(t_1, d_2) &amp; \mathrm{tf}(t_2, d_2) &amp; \mathrm{tf}(t_3, d_2) &amp; \mathrm{tf}(t_4, d_2)   \end{bmatrix}   \times   \begin{bmatrix}   \mathrm{idf}(t_1) &amp; 0 &amp; 0 &amp; 0\\   0 &amp; \mathrm{idf}(t_2) &amp; 0 &amp; 0\\   0 &amp; 0 &amp; \mathrm{idf}(t_3) &amp; 0\\   0 &amp; 0 &amp; 0 &amp; \mathrm{idf}(t_4)   \end{bmatrix}   \\ =   \begin{bmatrix}   \mathrm{tf}(t_1, d_1) \times \mathrm{idf}(t_1) &amp; \mathrm{tf}(t_2, d_1) \times \mathrm{idf}(t_2) &amp; \mathrm{tf}(t_3, d_1) \times \mathrm{idf}(t_3) &amp; \mathrm{tf}(t_4, d_1) \times \mathrm{idf}(t_4)\\   \mathrm{tf}(t_1, d_2) \times \mathrm{idf}(t_1) &amp; \mathrm{tf}(t_2, d_2) \times \mathrm{idf}(t_2) &amp; \mathrm{tf}(t_3, d_2) \times \mathrm{idf}(t_3) &amp; \mathrm{tf}(t_4, d_2) \times \mathrm{idf}(t_4)   \end{bmatrix}   ' class='latex' />
<p>Let&#8217;s see now a concrete example of this multiplication:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20M_%7Btf%5Cmbox%7B-%7Didf%7D%20%3D%20M_%7Btrain%7D%20%5Ctimes%20M_%7Bidf%7D%20%3D%20%5C%5C%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%200%20%26%201%20%26%201%20%26%201%5C%5C%20%20%200%20%26%202%20%26%201%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%20%20%5Ctimes%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%200.69314718%20%26%200%20%26%200%20%26%200%5C%5C%20%20%200%20%26%20-0.40546511%20%26%200%20%26%200%5C%5C%20%20%200%20%26%200%20%26%20-0.40546511%20%26%200%5C%5C%20%20%200%20%26%200%20%26%200%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%5C%5C%20%20%20%3D%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%200%20%26%20-0.40546511%20%26%20-0.40546511%20%26%200%5C%5C%20%20%200%20%26%20-0.81093022%20%26%20-0.40546511%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   M_{tf\mbox{-}idf} = M_{train} \times M_{idf} = \\   \begin{bmatrix}   0 &amp; 1 &amp; 1 &amp; 1\\   0 &amp; 2 &amp; 1 &amp; 0   \end{bmatrix}   \times   \begin{bmatrix}   0.69314718 &amp; 0 &amp; 0 &amp; 0\\   0 &amp; -0.40546511 &amp; 0 &amp; 0\\   0 &amp; 0 &amp; -0.40546511 &amp; 0\\   0 &amp; 0 &amp; 0 &amp; 0   \end{bmatrix} \\   =   \begin{bmatrix}   0 &amp; -0.40546511 &amp; -0.40546511 &amp; 0\\   0 &amp; -0.81093022 &amp; -0.40546511 &amp; 0   \end{bmatrix}   ' title='   M_{tf\mbox{-}idf} = M_{train} \times M_{idf} = \\   \begin{bmatrix}   0 &amp; 1 &amp; 1 &amp; 1\\   0 &amp; 2 &amp; 1 &amp; 0   \end{bmatrix}   \times   \begin{bmatrix}   0.69314718 &amp; 0 &amp; 0 &amp; 0\\   0 &amp; -0.40546511 &amp; 0 &amp; 0\\   0 &amp; 0 &amp; -0.40546511 &amp; 0\\   0 &amp; 0 &amp; 0 &amp; 0   \end{bmatrix} \\   =   \begin{bmatrix}   0 &amp; -0.40546511 &amp; -0.40546511 &amp; 0\\   0 &amp; -0.81093022 &amp; -0.40546511 &amp; 0   \end{bmatrix}   ' class='latex' />
<p>And finally, we can apply our L2 normalization process to the <img src='http://s.wordpress.com/latex.php?latex=M_%7Btf%5Cmbox%7B-%7Didf%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{tf\mbox{-}idf}' title='M_{tf\mbox{-}idf}' class='latex' /> matrix. Please note that this normalization is <strong>&#8220;row-wise&#8221;</strong> because we&#8217;re going to handle each row of the matrix as a separated vector to be normalized, and not the matrix as a whole:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20M_%7Btf%5Cmbox%7B-%7Didf%7D%20%3D%20%5Cfrac%7BM_%7Btf%5Cmbox%7B-%7Didf%7D%7D%7B%5C%7CM_%7Btf%5Cmbox%7B-%7Didf%7D%5C%7C_2%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=2' alt='   M_{tf\mbox{-}idf} = \frac{M_{tf\mbox{-}idf}}{\|M_{tf\mbox{-}idf}\|_2}   ' title='   M_{tf\mbox{-}idf} = \frac{M_{tf\mbox{-}idf}}{\|M_{tf\mbox{-}idf}\|_2}   ' class='latex' />
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%3D%20%5Cbegin%7Bbmatrix%7D%20%20%200%20%26%20-0.70710678%20%26%20-0.70710678%20%26%200%5C%5C%20%20%200%20%26%20-0.89442719%20%26%20-0.4472136%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   = \begin{bmatrix}   0 &amp; -0.70710678 &amp; -0.70710678 &amp; 0\\   0 &amp; -0.89442719 &amp; -0.4472136 &amp; 0   \end{bmatrix}   ' title='   = \begin{bmatrix}   0 &amp; -0.70710678 &amp; -0.70710678 &amp; 0\\   0 &amp; -0.89442719 &amp; -0.4472136 &amp; 0   \end{bmatrix}   ' class='latex' />
<p>And that is our pretty normalized tf-idf weight of our testing document set, which is actually a collection of unit vectors. If you take the L2-norm of each row of the matrix, you&#8217;ll see that they all have a L2-norm of 1.</p>
<h3> Python practice</h3>
<p><strong>Environment Used</strong>: <a title="Python :: Download" href="http://www.python.org/download/" target="_blank">Python v.2.7.2</a>, <a title="Numpy &amp; Scipy" href="http://new.scipy.org/download.html" target="_blank">Numpy 1.6.1</a>, <a title="Numpy &amp; Scipy" href="http://new.scipy.org/download.html" target="_blank">Scipy v.0.9.0</a>, <a title="Sklearn :: Install" href="http://scikit-learn.sourceforge.net/stable/install.html" target="_blank">Sklearn (Scikits.learn) v.0.9</a>.</p>
<p>Now the section you were waiting for ! In this section I&#8217;ll use Python to show each step of the tf-idf calculation using the <a title="Scikit.learn" href="http://scikit-learn.sourceforge.net" target="_blank">Scikit.learn</a> feature extraction module.</p>
<p>The first step is to create our training and testing document set and computing the term frequency matrix:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">from</span> sklearn.<span style="color: black;">feature_extraction</span>.<span style="color: black;">text</span> <span style="color: #ff7700;font-weight:bold;">import</span> CountVectorizer<br />
<br />
train_set = <span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;The sky is blue.&quot;</span>, <span style="color: #483d8b;">&quot;The sun is bright.&quot;</span><span style="color: black;">&#41;</span><br />
test_set = <span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;The sun in the sky is bright.&quot;</span>,<br />
<span style="color: #483d8b;">&quot;We can see the shining sun, the bright sun.&quot;</span><span style="color: black;">&#41;</span><br />
<br />
count_vectorizer = CountVectorizer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
count_vectorizer.<span style="color: black;">fit_transform</span><span style="color: black;">&#40;</span>train_set<span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Vocabulary:&quot;</span>, count_vectorizer.<span style="color: black;">vocabulary</span><br />
<br />
<span style="color: #808080; font-style: italic;"># Vocabulary: {'blue': 0, 'sun': 1, 'bright': 2, 'sky': 3}</span><br />
<br />
freq_term_matrix = count_vectorizer.<span style="color: black;">transform</span><span style="color: black;">&#40;</span>test_set<span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> freq_term_matrix.<span style="color: black;">todense</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<br />
<span style="color: #808080; font-style: italic;">#[[0 1 1 1]</span><br />
<span style="color: #808080; font-style: italic;">#[0 2 1 0]]</span></div></td></tr></tbody></table></div>
<p>Now that we have the frequency term matrix (called <strong>freq_term_matrix</strong>), we can instantiate the <strong>TfidfTransformer</strong>, which is going to be responsible to calculate the tf-idf weights for our term frequency matrix:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">from</span> sklearn.<span style="color: black;">feature_extraction</span>.<span style="color: black;">text</span> <span style="color: #ff7700;font-weight:bold;">import</span> TfidfTransformer<br />
<br />
tfidf = TfidfTransformer<span style="color: black;">&#40;</span>norm=<span style="color: #483d8b;">&quot;l2&quot;</span><span style="color: black;">&#41;</span><br />
tfidf.<span style="color: black;">fit</span><span style="color: black;">&#40;</span>freq_term_matrix<span style="color: black;">&#41;</span><br />
<br />
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;IDF:&quot;</span>, tfidf.<span style="color: black;">idf_</span><br />
<br />
<span style="color: #808080; font-style: italic;"># IDF: [ 0.69314718 -0.40546511 -0.40546511  0.        ]</span></div></td></tr></tbody></table></div>
<p>Note that I&#8217;ve specified the norm as L2, this is optional (actually the default is L2-norm), but I&#8217;ve added the parameter to make it explicit to you that it it&#8217;s going to use the L2-norm. Also note that you can see the calculated idf weight by accessing the internal attribute called <strong>idf_</strong>. Now that <strong>fit()</strong> method has calculated the idf for the matrix, let&#8217;s transform the <strong>freq_term_matrix</strong> to the tf-idf weight matrix:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">tf_idf_matrix = tfidf.<span style="color: black;">transform</span><span style="color: black;">&#40;</span>freq_term_matrix<span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> tf_idf_matrix.<span style="color: black;">todense</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<br />
<span style="color: #808080; font-style: italic;"># [[ 0.         -0.70710678 -0.70710678  0.        ]</span><br />
<span style="color: #808080; font-style: italic;"># [ 0.         -0.89442719 -0.4472136   0.        ]]</span></div></td></tr></tbody></table></div>
<p>And that is it, the <strong>tf_idf_matrix</strong> is actually our previous <img src='http://s.wordpress.com/latex.php?latex=M_%7Btf%5Cmbox%7B-%7Didf%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{tf\mbox{-}idf}' title='M_{tf\mbox{-}idf}' class='latex' /> matrix. You can accomplish the same effect by using the <strong>Vectorizer</strong> class of the Scikit.learn which is a vectorizer that automatically combines the <strong>CountVectorizer</strong> and the <strong>TfidfTransformer</strong> to you. See <a title="Classification of text documents" href="http://scikit-learn.sourceforge.net/stable/auto_examples/document_classification_20newsgroups.html#example-document-classification-20newsgroups-py" target="_blank">this example</a> to know how to use it for the text classification process.</p>
<p>I really hope you liked the post, I tried to make it simple as possible even for people without the required mathematical background of linear algebra, etc. In the next Machine Learning post I&#8217;m expecting to show how you can use the tf-idf to calculate the cosine similarity.</p>
<p>If you liked it, feel free to comment and make suggestions, corrections, etc.</p>
<h3>References</h3>
<p><a href="http://www.soi.city.ac.uk/%7Eser/idfpapers/Robertson_idf_JDoc.pdf" target="_blank">Understanding Inverse Document Frequency: on theoretical arguments for IDF</a></p>
<p><a href="http://en.wikipedia.org/wiki/Tf%E2%80%93idf" target="_blank">Wikipedia :: tf-idf</a></p>
<p><a title="The classic Vector Space Model" href="http://www.miislita.com/term-vector/term-vector-4.html" target="_blank"> The classic Vector Space Model</a></p>
<p><a title="Scikit.learn :: Feature Extraction :: Text" href="https://github.com/scikit-learn/scikit-learn/blob/0.9.X/sklearn/feature_extraction/text.py" target="_blank">Sklearn text feature extraction code</a></p>
<h3>Updates</h3>
<p><strong>03 Oct 2011</strong> -<em> Added the info about the environment used for Python examples</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/YoTmygrjMTM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=1747</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=1747</feedburner:origLink></item>
		<item>
		<title>Machine Learning :: Text feature extraction (tf-idf) – Part I</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/BXtMKwW53wQ/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=1589#comments</comments>
		<pubDate>Sun, 18 Sep 2011 17:37:50 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[feature extraction]]></category>
		<category><![CDATA[machine learning]]></category>
		<category><![CDATA[text mining]]></category>
		<category><![CDATA[tf-idf]]></category>
		<category><![CDATA[vector space model]]></category>
		<category><![CDATA[vsm]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=1589</guid>
		<description><![CDATA[Short introduction to Vector Space Model (VSM) In information retrieval or text mining, the term frequency &#8211; inverse document frequency also called tf-idf, is a well know method to evaluate how important is a word in a document. tf-idf are also a very interesting way to convert the textual representation of information into a Vector [...]]]></description>
			<content:encoded><![CDATA[<h3>Short introduction to Vector Space Model (VSM)</h3>
<p>In information retrieval or text mining, the <a title="Wikipedia: tf-idf" href="http://en.wikipedia.org/wiki/Tf%E2%80%93idf" target="_blank">term frequency &#8211; inverse document frequency</a> also called <strong>tf-idf</strong>, is a well know method to evaluate how important is a word in a document. tf-idf are also a very interesting way to convert the textual representation of information into a <a title="Wikipedia: Vector Space Model" href="http://en.wikipedia.org/wiki/Vector_space_model" target="_blank">Vector Space Model</a> (VSM), or into sparse features, we&#8217;ll discuss more about it later, but first, let&#8217;s try to understand what is tf-idf and the VSM.</p>
<p>VSM has a very confusing past, see for example the paper <a title="Paper: The most influential paper Gerard Salton Never Wrote" href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.184.910&amp;rep=rep1&amp;type=pdf" target="_blank">The most influential paper Gerard Salton Never Wrote</a> that explains the history behind the ghost cited paper which in fact never existed; in sum, VSM is an algebraic model representing textual information as a vector, the components of this vector could represent the importance of a term (tf–idf) or even the absence or presence (<a title="Wikipedia: Bag of words model" href="http://en.wikipedia.org/wiki/Bag_of_words_model" target="_blank">Bag of Words</a>) of it in a document; it is important to note that the classical VSM proposed by Salton incorporates local and global parameters/information (in a sense that it uses both the isolated term being analyzed as well the entire collection of documents). VSM, interpreted in a <em>lato sensu,</em> is a space where text is represented as a vector of numbers instead of its original string textual representation; the VSM represents the features extracted from the document.</p>
<p>Let&#8217;s try to mathematically define the VSM and tf-idf together with concrete examples, for the concrete examples I&#8217;ll be using Python (as well the amazing <a title="Scikit.learn" href="http://scikit-learn.sourceforge.net/stable/" target="_blank">scikits.learn</a> Python module).</p>
<h3>Going to the vector space</h3>
<p>The first step in modeling the document into a vector space is to create a dictionary of terms present in documents. To do that, you can simple select all terms from the document and convert it to a dimension in the vector space, but we know that there are some kind of words (stop words) that are present in almost all documents, and what we&#8217;re doing is extracting important features from documents, features do identify them among other similar documents, so using terms like &#8220;the, is, at, on&#8221;, etc.. isn&#8217;t going to help us, so in the information extraction, we&#8217;ll just ignore them.</p>
<p>Let&#8217;s take the documents below to define our (stupid) document space:</p>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Train Document Set:<br />
<br />
d1: The sky is blue.<br />
d2: The sun is bright.<br />
<br />
Test Document Set:<br />
<br />
d3: The sun in the sky is bright.<br />
d4: We can see the shining sun, the bright sun.</div></td></tr></tbody></table></div>
<p>Now, what we have to do is to create a index vocabulary (dictionary) of the words of the train document set, using the documents <img src='http://s.wordpress.com/latex.php?latex=d1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d1' title='d1' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=d2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d2' title='d2' class='latex' /> from the document set, we&#8217;ll have the following index vocabulary denoted as <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7BE%7D%28t%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{E}(t)' title='\mathrm{E}(t)' class='latex' /> where the <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' /> is the term:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7BE%7D%28t%29%20%3D%20%20%20%5Cbegin%7Bcases%7D%20%20%201%2C%20%26%20%5Cmbox%7Bif%20%7D%20t%5Cmbox%7B%20is%20%60%60blue%27%27%7D%20%5C%5C%20%20%202%2C%20%26%20%5Cmbox%7Bif%20%7D%20t%5Cmbox%7B%20is%20%60%60sun%27%27%7D%20%5C%5C%20%20%203%2C%20%26%20%5Cmbox%7Bif%20%7D%20t%5Cmbox%7B%20is%20%60%60bright%27%27%7D%20%5C%5C%20%20%204%2C%20%26%20%5Cmbox%7Bif%20%7D%20t%5Cmbox%7B%20is%20%60%60sky%27%27%7D%20%5C%5C%20%20%20%5Cend%7Bcases%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{E}(t) =   \begin{cases}   1, &amp; \mbox{if } t\mbox{ is ``blue&#039;&#039;} \\   2, &amp; \mbox{if } t\mbox{ is ``sun&#039;&#039;} \\   3, &amp; \mbox{if } t\mbox{ is ``bright&#039;&#039;} \\   4, &amp; \mbox{if } t\mbox{ is ``sky&#039;&#039;} \\   \end{cases}   ' title='   \mathrm{E}(t) =   \begin{cases}   1, &amp; \mbox{if } t\mbox{ is ``blue&#039;&#039;} \\   2, &amp; \mbox{if } t\mbox{ is ``sun&#039;&#039;} \\   3, &amp; \mbox{if } t\mbox{ is ``bright&#039;&#039;} \\   4, &amp; \mbox{if } t\mbox{ is ``sky&#039;&#039;} \\   \end{cases}   ' class='latex' />
<p>Note that the terms like &#8220;is&#8221; and &#8220;the&#8221; were ignored as cited before. Now that we have an index vocabulary, we can convert the test document set into a vector space where each term of the vector is indexed as our index vocabulary, so the first term of the vector represents the &#8220;blue&#8221; term of our vocabulary, the second represents &#8220;sun&#8221; and so on. Now, we&#8217;re going to use the <strong>term-frequency</strong> to represent each term in our vector space; the term-frequency is nothing more than a measure of how many times the terms present in our vocabulary <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7BE%7D%28t%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{E}(t)' title='\mathrm{E}(t)' class='latex' /> are present in the documents <img src='http://s.wordpress.com/latex.php?latex=d3&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d3' title='d3' class='latex' /> or <img src='http://s.wordpress.com/latex.php?latex=d4&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d4' title='d4' class='latex' />, we define the term-frequency as a couting function:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Btf%7D%28t%2Cd%29%20%3D%20%5Csum%5Climits_%7Bx%5Cin%20d%7D%20%5Cmathrm%7Bfr%7D%28x%2C%20t%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{tf}(t,d) = \sum\limits_{x\in d} \mathrm{fr}(x, t)   ' title='   \mathrm{tf}(t,d) = \sum\limits_{x\in d} \mathrm{fr}(x, t)   ' class='latex' />
<p>where the <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Bfr%7D%28x%2C%20t%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{fr}(x, t)' title='\mathrm{fr}(x, t)' class='latex' /> is a simple function defined as:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cmathrm%7Bfr%7D%28x%2Ct%29%20%3D%20%20%20%5Cbegin%7Bcases%7D%20%20%201%2C%20%26%20%5Cmbox%7Bif%20%7D%20x%20%3D%20t%20%5C%5C%20%20%200%2C%20%26%20%5Cmbox%7Botherwise%7D%20%5C%5C%20%20%20%5Cend%7Bcases%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \mathrm{fr}(x,t) =   \begin{cases}   1, &amp; \mbox{if } x = t \\   0, &amp; \mbox{otherwise} \\   \end{cases}   ' title='   \mathrm{fr}(x,t) =   \begin{cases}   1, &amp; \mbox{if } x = t \\   0, &amp; \mbox{otherwise} \\   \end{cases}   ' class='latex' />
<p>So, what the <img src='http://s.wordpress.com/latex.php?latex=tf%28t%2Cd%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='tf(t,d)' title='tf(t,d)' class='latex' /> returns is how many times is the term <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' /> is present in the document <img src='http://s.wordpress.com/latex.php?latex=d&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d' title='d' class='latex' />. An example of this, could be <img src='http://s.wordpress.com/latex.php?latex=%20tf%28%60%60sun%27%27%2C%20d4%29%20%3D%202%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt=' tf(``sun&#039;&#039;, d4) = 2 ' title=' tf(``sun&#039;&#039;, d4) = 2 ' class='latex' /> since we have only two occurrences of the term &#8220;sun&#8221; in the document <img src='http://s.wordpress.com/latex.php?latex=d4&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d4' title='d4' class='latex' />. Now you understood how the term-frequency works, we can go on into the creation of the document vector, which is represented by:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cdisplaystyle%20%5Cvec%7Bv_%7Bd_n%7D%7D%20%3D%28%5Cmathrm%7Btf%7D%28t_1%2Cd_n%29%2C%20%5Cmathrm%7Btf%7D%28t_2%2Cd_n%29%2C%20%5Cmathrm%7Btf%7D%28t_3%2Cd_n%29%2C%20%5Cldots%2C%20%5Cmathrm%7Btf%7D%28t_n%2Cd_n%29%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \displaystyle \vec{v_{d_n}} =(\mathrm{tf}(t_1,d_n), \mathrm{tf}(t_2,d_n), \mathrm{tf}(t_3,d_n), \ldots, \mathrm{tf}(t_n,d_n))   ' title='   \displaystyle \vec{v_{d_n}} =(\mathrm{tf}(t_1,d_n), \mathrm{tf}(t_2,d_n), \mathrm{tf}(t_3,d_n), \ldots, \mathrm{tf}(t_n,d_n))   ' class='latex' />
<p>Each dimension of the document vector is represented by the term of the vocabulary, for example, the <img src='http://s.wordpress.com/latex.php?latex=%5Cmathrm%7Btf%7D%28t_1%2Cd_2%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\mathrm{tf}(t_1,d_2)' title='\mathrm{tf}(t_1,d_2)' class='latex' /> represents the frequency-term of the term 1 or <img src='http://s.wordpress.com/latex.php?latex=t_1&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='t_1' title='t_1' class='latex' /> (which is our &#8220;blue&#8221; term of the vocabulary) in the document <img src='http://s.wordpress.com/latex.php?latex=d_2&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_2' title='d_2' class='latex' />.</p>
<p>Let&#8217;s now show a concrete example of how the documents <img src='http://s.wordpress.com/latex.php?latex=d_3&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_3' title='d_3' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=d_4&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_4' title='d_4' class='latex' /> are represented as vectors:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cvec%7Bv_%7Bd_3%7D%7D%20%3D%20%28%5Cmathrm%7Btf%7D%28t_1%2Cd_3%29%2C%20%5Cmathrm%7Btf%7D%28t_2%2Cd_3%29%2C%20%5Cmathrm%7Btf%7D%28t_3%2Cd_3%29%2C%20%5Cldots%2C%20%5Cmathrm%7Btf%7D%28t_n%2Cd_3%29%29%20%5C%5C%20%20%20%5Cvec%7Bv_%7Bd_4%7D%7D%20%3D%20%28%5Cmathrm%7Btf%7D%28t_1%2Cd_4%29%2C%20%5Cmathrm%7Btf%7D%28t_2%2Cd_4%29%2C%20%5Cmathrm%7Btf%7D%28t_3%2Cd_4%29%2C%20%5Cldots%2C%20%5Cmathrm%7Btf%7D%28t_n%2Cd_4%29%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \vec{v_{d_3}} = (\mathrm{tf}(t_1,d_3), \mathrm{tf}(t_2,d_3), \mathrm{tf}(t_3,d_3), \ldots, \mathrm{tf}(t_n,d_3)) \\   \vec{v_{d_4}} = (\mathrm{tf}(t_1,d_4), \mathrm{tf}(t_2,d_4), \mathrm{tf}(t_3,d_4), \ldots, \mathrm{tf}(t_n,d_4))   ' title='   \vec{v_{d_3}} = (\mathrm{tf}(t_1,d_3), \mathrm{tf}(t_2,d_3), \mathrm{tf}(t_3,d_3), \ldots, \mathrm{tf}(t_n,d_3)) \\   \vec{v_{d_4}} = (\mathrm{tf}(t_1,d_4), \mathrm{tf}(t_2,d_4), \mathrm{tf}(t_3,d_4), \ldots, \mathrm{tf}(t_n,d_4))   ' class='latex' />
<p>which evaluates to:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20%5Cvec%7Bv_%7Bd_3%7D%7D%20%3D%20%280%2C%201%2C%201%2C%201%29%20%5C%5C%20%20%20%5Cvec%7Bv_%7Bd_4%7D%7D%20%3D%20%280%2C%202%2C%201%2C%200%29%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   \vec{v_{d_3}} = (0, 1, 1, 1) \\   \vec{v_{d_4}} = (0, 2, 1, 0)   ' title='   \vec{v_{d_3}} = (0, 1, 1, 1) \\   \vec{v_{d_4}} = (0, 2, 1, 0)   ' class='latex' />
<p>As you can see, since the documents <img src='http://s.wordpress.com/latex.php?latex=d_3&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_3' title='d_3' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=d_4&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='d_4' title='d_4' class='latex' /> are:</p>
<div class="codecolorer-container text railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">d3: The sun in the sky is bright.<br />
d4: We can see the shining sun, the bright sun.</div></td></tr></tbody></table></div>
<p>The resulting vector <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_3%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_3}}' title='\vec{v_{d_3}}' class='latex' /> shows that we have, in order, 0 occurrences of the term &#8220;blue&#8221;, 1 occurrence of the term &#8220;sun&#8221;, and so on. In the <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_3%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_3}}' title='\vec{v_{d_3}}' class='latex' />, we have 0 occurences of the term &#8220;blue&#8221;, 2 occurrences of the term &#8220;sun&#8221;, etc.</p>
<p>But wait, since we have a collection of documents, now represented by vectors, we can represent them as a matrix with <img src='http://s.wordpress.com/latex.php?latex=%7CD%7C%20%5Ctimes%20F&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='|D| \times F' title='|D| \times F' class='latex' /> shape, where <img src='http://s.wordpress.com/latex.php?latex=%7CD%7C&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='|D|' title='|D|' class='latex' /> is the cardinality of the document space, or how many documents we have and the <img src='http://s.wordpress.com/latex.php?latex=F&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F' title='F' class='latex' /> is the number of features, in our case represented by the vocabulary size. An example of the matrix representation of the vectors described above is:</p>
<img src='http://s.wordpress.com/latex.php?latex=%20%20%20M_%7B%7CD%7C%20%5Ctimes%20F%7D%20%3D%20%20%20%5Cbegin%7Bbmatrix%7D%20%20%200%20%26%201%20%26%201%20%26%201%5C%5C%20%20%200%20%26%202%20%26%201%20%26%200%20%20%20%5Cend%7Bbmatrix%7D%20%20%20&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='   M_{|D| \times F} =   \begin{bmatrix}   0 &amp; 1 &amp; 1 &amp; 1\\   0 &amp; 2 &amp; 1 &amp; 0   \end{bmatrix}   ' title='   M_{|D| \times F} =   \begin{bmatrix}   0 &amp; 1 &amp; 1 &amp; 1\\   0 &amp; 2 &amp; 1 &amp; 0   \end{bmatrix}   ' class='latex' />
<p>As you may have noted, these matrices representing the term frequencies tend to be very <a title="Wikipedia: Sparse Matrix" href="http://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse</a> (with majority of terms zeroed), and that&#8217;s why you&#8217;ll see a common representation of these matrix as sparse matrices.</p>
<h3>Python practice</h3>
<p><strong>Environment Used</strong>: <a title="Python :: Download" href="http://www.python.org/download/" target="_blank">Python v.2.7.2</a>, <a title="Numpy &amp; Scipy" href="http://new.scipy.org/download.html" target="_blank">Numpy 1.6.1</a>, <a title="Numpy &amp; Scipy" href="http://new.scipy.org/download.html" target="_blank">Scipy v.0.9.0</a>, <a title="Sklearn :: Install" href="http://scikit-learn.sourceforge.net/stable/install.html" target="_blank">Sklearn (Scikits.learn) v.0.9</a>.</p>
<p>Since we know the  theory behind the term frequency and the vector space conversion, let&#8217;s show how easy is to do that using the amazing <a title="Scikit.learn" href="http://scikit-learn.sourceforge.net/" target="_blank">scikit.learn </a>Python module.</p>
<p>Scikit.learn comes with <a title="Scikit.learn :: Examples" href="http://scikit-learn.sourceforge.net/stable/auto_examples/index.html" target="_blank">lots of examples</a> as well real-life interesting <a title="Scikit.learn :: Datasets" href="http://scikit-learn.sourceforge.net/stable/modules/datasets.html#datasets-shipped-with-the-scikit-learn" target="_blank">datasets</a> you can use and also some<a title="Scikit.learn :: Datasets" href="http://scikit-learn.sourceforge.net/stable/modules/datasets.html#the-20-newsgroups-text-dataset" target="_blank"> helper functions</a> to download 18k newsgroups posts for instance.</p>
<p>Since we already defined our small train/test dataset before, let&#8217;s use them to define the dataset in a way that scikit.learn can use:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">train_set = <span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;The sky is blue.&quot;</span>, <span style="color: #483d8b;">&quot;The sun is bright.&quot;</span><span style="color: black;">&#41;</span><br />
test_set = <span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;The sun in the sky is bright.&quot;</span>,<br />
<span style="color: #483d8b;">&quot;We can see the shining sun, the bright sun.&quot;</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>In scikit.learn, what we have presented as the term-frequency, is called <strong>CountVectorizer</strong>, so we need to import it and create a news instance:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">from</span> sklearn.<span style="color: black;">feature_extraction</span>.<span style="color: black;">text</span> <span style="color: #ff7700;font-weight:bold;">import</span> CountVectorizer<br />
vectorizer = CountVectorizer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>The <strong>CountVectorizer</strong> already uses as default &#8220;analyzer&#8221; called <strong>WordNGramAnalyzer</strong>, which is responsible to convert the text to lowercase, accents removal, token extraction, filter stop words, etc&#8230; you can see more information by printing the class information:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">print</span> vectorizer<br />
CountVectorizer<span style="color: black;">&#40;</span>analyzer__min_n=<span style="color: #ff4500;">1</span>,<br />
analyzer__stop_words=<span style="color: #008000;">set</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'all'</span>, <span style="color: #483d8b;">'six'</span>, <span style="color: #483d8b;">'less'</span>, <span style="color: #483d8b;">'being'</span>, <span style="color: #483d8b;">'indeed'</span>, <span style="color: #483d8b;">'over'</span>, <span style="color: #483d8b;">'move'</span>, <span style="color: #483d8b;">'anyway'</span>, <span style="color: #483d8b;">'four'</span>, <span style="color: #483d8b;">'not'</span>, <span style="color: #483d8b;">'own'</span>, <span style="color: #483d8b;">'through'</span>, <span style="color: #483d8b;">'yourselves'</span>, <span style="color: black;">&#40;</span>...<span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Let&#8217;s create now the vocabulary index:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">vectorizer.<span style="color: black;">fit_transform</span><span style="color: black;">&#40;</span>train_set<span style="color: black;">&#41;</span><br />
<span style="color: #ff7700;font-weight:bold;">print</span> vectorizer.<span style="color: black;">vocabulary</span><br />
<span style="color: black;">&#123;</span><span style="color: #483d8b;">'blue'</span>: <span style="color: #ff4500;">0</span>, <span style="color: #483d8b;">'sun'</span>: <span style="color: #ff4500;">1</span>, <span style="color: #483d8b;">'bright'</span>: <span style="color: #ff4500;">2</span>, <span style="color: #483d8b;">'sky'</span>: <span style="color: #ff4500;">3</span><span style="color: black;">&#125;</span></div></td></tr></tbody></table></div>
<p>See that the vocabulary created is the same as <img src='http://s.wordpress.com/latex.php?latex=E%28t%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='E(t)' title='E(t)' class='latex' /> (except because it is zero-indexed).</p>
<p>Let&#8217;s use the same vectorizer now to create the sparse matrix of our <strong>test_set</strong> documents:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">smatrix = vectorizer.<span style="color: black;">transform</span><span style="color: black;">&#40;</span>test_set<span style="color: black;">&#41;</span><br />
<br />
<span style="color: #ff7700;font-weight:bold;">print</span> smatrix<br />
<br />
<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>        <span style="color: #ff4500;">1</span><br />
<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>        <span style="color: #ff4500;">1</span><br />
<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>        <span style="color: #ff4500;">1</span><br />
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>        <span style="color: #ff4500;">2</span><br />
<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>        <span style="color: #ff4500;">1</span></div></td></tr></tbody></table></div>
<p>Note that the sparse matrix created called <strong>smatrix</strong> is a <a title="Scipy API Docs :: COOrdinate format" href="http://www.scipy.org/doc/api_docs/SciPy.sparse.sparse.coo_matrix.html" target="_blank">Scipy sparse matrix</a> with elements stored in a <a title="Wikipedia: Sparse Matrix :: Coordinate list format" href="http://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_.28COO.29" target="_blank">Coordinate format</a>. But you can convert it into a dense format:</p>
<div class="codecolorer-container python railscasts" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">smatrix.<span style="color: black;">todense</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<br />
matrix<span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>,<br />
........<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span>, dtype=int64<span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Note that the sparse matrix created is the same matrix <img src='http://s.wordpress.com/latex.php?latex=M_%7B%7CD%7C%20%5Ctimes%20F%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='M_{|D| \times F}' title='M_{|D| \times F}' class='latex' /> we cited earlier in this post, which represents the two document vectors <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_3%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_3}}' title='\vec{v_{d_3}}' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=%5Cvec%7Bv_%7Bd_4%7D%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\vec{v_{d_4}}' title='\vec{v_{d_4}}' class='latex' />.</p>
<p>We&#8217;ll see in the next post how we define the <strong>idf</strong> (<em>inverse document frequency</em>) instead of the simple term-frequency, as well how logarithmic scale is used to adjust the measurement of term frequencies according to its importance, and how we can use it to classify documents using some of the well-know machine learning approaches.</p>
<p>I hope you liked this post, and if you really liked, leave a comment so I&#8217;ll able to know if there are enough people interested in these series of posts in Machine Learning topics.</p>
<p>As promised, <a title="Machine Learning :: Text feature extraction (tf-idf) – Part II" href="http://pyevolve.sourceforge.net/wordpress/?p=1747">here is the second part</a> of this tutorial series.</p>
<h3>References</h3>
<p><a href="http://www.miislita.com/term-vector/term-vector-3.html" target="_blank">The classic Vector Space Model</a></p>
<p><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.184.910&amp;rep=rep1&amp;type=pdf" target="_blank">The most influential paper Gerard Salton never wrote</a></p>
<p><a href="http://en.wikipedia.org/wiki/Tf%E2%80%93idf" target="_blank">Wikipedia: tf-idf</a></p>
<p><a href="http://en.wikipedia.org/wiki/Vector_space_model" target="_blank">Wikipedia: Vector space model</a></p>
<p><a href="http://scikit-learn.sourceforge.net/stable/auto_examples/index.html" target="_blank">Scikits.learn Examples</a></p>
<h3>Updates</h3>
<p><strong>21 Sep 11</strong> -<em> fixed some typos and the vector notation<br />
</em><strong>22 Sep 11</strong><em> &#8211; fixed import of sklearn according to the new 0.9 release and added the environment section<br />
</em><strong>02 Oct 11</strong><em> &#8211; fixed Latex math typos<br />
</em><strong>18 Oct 11</strong><em> &#8211; added link to the second part of the tutorial series<br />
</em></p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/BXtMKwW53wQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=1589</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=1589</feedburner:origLink></item>
		<item>
		<title>The Interactive Robotic Painting Machine !</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/w8C_ncDtERI/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=1575#comments</comments>
		<pubDate>Thu, 18 Aug 2011 00:15:21 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Genetic Algorithms]]></category>
		<category><![CDATA[Pyevolve]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[art]]></category>
		<category><![CDATA[ga]]></category>
		<category><![CDATA[genetic algorithm]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[machine]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=1575</guid>
		<description><![CDATA[I&#8217;m glad to announce a project created by Benjamin Grosser called &#8220;Interactive Robotic Painting Machine&#8220;. The machine uses Python and Pyevolve as it&#8217;s Genetic Algorithm core, the concept is very interesting: What I’ve built to consider these questions is an interactive robotic painting machine that uses artificial intelligence to paint its own body of work [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/08/machine1.jpg" rel="lightbox[1575]"><img class="size-medium wp-image-1576 aligncenter" title="Interactive Robotic Painting Machine" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/08/machine1-300x199.jpg" alt="" width="300" height="199" /></a></p>
<p>I&#8217;m glad to announce a project created by <a title="Benjamin Grosser website" href="http://bengrosser.com" target="_blank">Benjamin Grosser</a> called &#8220;<a title="Benjamin Grosser :: Interactive Robotic Painting Machine" href="http://bengrosser.com/projects/interactive-robotic-painting-machine/" target="_blank">Interactive Robotic Painting Machine</a>&#8220;. The machine uses Python and Pyevolve as it&#8217;s Genetic Algorithm core, the concept is very interesting:</p>
<blockquote><p>What I’ve built to consider these questions is an interactive robotic painting machine that uses artificial intelligence to paint its own body of work and to make its own decisions. While doing so, it listens to its environment and considers what it hears as input into the painting process. In the absence of someone or something else making sound in its presence, the machine, like many artists, listens to itself. But when it does hear others, it changes what it does just as we subtly (or not so subtly) are influenced by what others tell us.</p></blockquote>
<p><iframe src="http://player.vimeo.com/video/23998286" frameborder="0" width="400" height="225"></iframe></p>
<p>Read more about the project in the <a title="Benjamin Grosser :: Interactive Robotic Painting Machine" href="http://bengrosser.com/projects/interactive-robotic-painting-machine/" target="_blank">Benjamin Grosser website</a>.</p>
<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/w8C_ncDtERI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=1575</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=1575</feedburner:origLink></item>
		<item>
		<title>Pyevolve – new repository at Github</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/x3yWbhdtSz4/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=1571#comments</comments>
		<pubDate>Thu, 11 Aug 2011 00:36:38 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[Pyevolve]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[repository]]></category>
		<category><![CDATA[svn]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=1571</guid>
		<description><![CDATA[I&#8217;ve moved the Pyevolve SVN repository hosted at sourceforge.net to a new Github repository. The new official Pyevolve repository is now located at https://github.com/perone/Pyevolve.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve moved the Pyevolve SVN repository hosted at sourceforge.net to a new Github repository.</p>
<p>The new official Pyevolve repository is now located at <a title="GitHub Pyevolve Repository" href="https://github.com/perone/Pyevolve" target="_blank">https://github.com/perone/Pyevolve</a>.</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/x3yWbhdtSz4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=1571</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=1571</feedburner:origLink></item>
		<item>
		<title>News: Algorithm searches for models that best explain experimental data</title>
		<link>http://feedproxy.google.com/~r/pyevolve/~3/9MXQI5TTPm4/</link>
		<comments>http://pyevolve.sourceforge.net/wordpress/?p=1562#comments</comments>
		<pubDate>Tue, 02 Aug 2011 23:20:19 +0000</pubDate>
		<dc:creator>Christian S. Perone</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Science]]></category>
		<category><![CDATA[evolutionary algorithm]]></category>
		<category><![CDATA[model]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://pyevolve.sourceforge.net/wordpress/?p=1562</guid>
		<description><![CDATA[From the original news article from PhysOrg: An evolutionary computation approach developed by Franklin University’s Esmail Bonakdarian, Ph.D., was used to analyze data from two classical economics experiments. As can be seen in this figure, optimization of the search over subsets of the maximum model proceeds initially at a quick rate and then slowly continues [...]]]></description>
			<content:encoded><![CDATA[<p>From the original <a title="Algorithm searches for models that best explain experimental data" href="http://www.physorg.com/news/2011-08-algorithm-experimental.html" target="_blank">news article</a> from PhysOrg:</p>
<blockquote><p>An evolutionary computation approach developed by Franklin University’s Esmail Bonakdarian, Ph.D., was used to analyze data from two classical economics experiments. As can be seen in this figure, optimization of the search over subsets of the maximum model proceeds initially at a quick rate and then slowly continues to improve over time until it converges. The top curve (red) shows the optimum value found so far, while the lower, jagged line (green) shows the current average fitness value for the population in each generation.</p>
<p><a href="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/08/algorithmsea.jpg" rel="lightbox[1562]"><img class="size-medium wp-image-1563 aligncenter" title="Generational Graph" src="http://pyevolve.sourceforge.net/wordpress/wp-content/uploads/2011/08/algorithmsea-300x222.jpg" alt="" width="300" height="222" /></a></p>
<p>(&#8230;)</p>
<p>Regression analysis has been the traditional tool for finding and establishing statistically significant relationships in research projects, such as for the economics examples Bonakdarian chose. As long as the number of independent variables is relatively small, or the experimenter has a fairly clear idea of the possible underlying relationship, it is feasible to derive the best model using standard software packages and methodologies.</p>
<p>However, Bonakdarian cautioned that if the number of independent variables is large, and there is no intuitive sense about the possible relationship between these variables and the dependent variable, “the experimenter may have to go on an automated ‘fishing expedition’ to discover the important and relevant independent variables.”</p></blockquote>
<p>You can see the original research <a title="Original Paper" href="http://cs.franklin.edu/~esmail/Papers/GEM11_Bonakdarian.pdf" target="_blank">paper here</a>.</p>
<img src="http://feeds.feedburner.com/~r/pyevolve/~4/9MXQI5TTPm4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pyevolve.sourceforge.net/wordpress/?feed=rss2&amp;p=1562</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pyevolve.sourceforge.net/wordpress/?p=1562</feedburner:origLink></item>
	</channel>
</rss>

