blob: 49b7cfa748f29d8928ee65838e6db5f3d2c72e68 [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>MADlib: k-Means Clustering</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<script src="../mathjax/MathJax.js">
MathJax.Hub.Config({
extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">MADlib
&#160;<span id="projectnumber">0.6</span> <span style="font-size:10pt; font-style:italic"><a href="../latest/./group__grp__kmeans.html"> A newer version is available</a></span>
</div>
<div id="projectbrief">User Documentation</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.5.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="dynsections.js"></script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main&#160;Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('group__grp__kmeans.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">k-Means Clustering</div> </div>
<div class="ingroups"><a class="el" href="group__grp__unsuplearn.html">Unsupervised Learning</a></div></div>
<div class="contents">
<div id="dynsection-0" onclick="return toggleVisibility(this)" class="dynheader closed" style="cursor:pointer;">
<img id="dynsection-0-trigger" src="closed.png" alt="+"/> Collaboration diagram for k-Means Clustering:</div>
<div id="dynsection-0-summary" class="dynsummary" style="display:block;">
</div>
<div id="dynsection-0-content" class="dyncontent" style="display:none;">
<center><table><tr><td><div class="center"><iframe scrolling="no" frameborder="0" src="group__grp__kmeans.svg" width="371" height="40"><p><b>This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.</b></p></iframe>
</div>
</td></tr></table></center>
</div>
<dl class="user"><dt><b>About:</b></dt><dd></dd></dl>
<p>Clustering refers to the problem of partitioning a set of objects according to some problem-dependent measure of <em>similarity</em>. In the k-means variant, one is given \( n \) points \( x_1, \dots, x_n \in \mathbb R^d \), and the goal is to position \( k \) centroids \( c_1, \dots, c_k \in \mathbb R^d \) so that the sum of <em>distances</em> between each point and its closest centroid is minimized. Each centroid represents a cluster that consists of all points to which this centroid is closest. Formally, we wish to minimize the following objective function: </p>
<p class="formulaDsp">
\[ (c_1, \dots, c_k) \mapsto \sum_{i=1}^n \min_{j=1}^k \operatorname{dist}(x_i, c_j) \]
</p>
<p> In the most common case, \( \operatorname{dist} \) is the square of the Euclidean distance.</p>
<p>This problem is computationally difficult (NP-hard), yet the local-search heuristic proposed by Lloyd [4] performs reasonably well in practice. In fact, it is so ubiquitous today that it is often referred to as the <em>standard algorithm</em> or even just the <em>k-means algorithm</em> [1]. It works as follows:</p>
<ol type="1">
<li>Seed the \( k \) centroids (see below)</li>
<li>Repeat until convergence:<ol type="a">
<li>Assign each point to its closest centroid</li>
<li>Move each centroid to a position that minimizes the sum of distances in this cluster</li>
</ol>
</li>
<li>Convergence is achieved when no points change their assignments during step 2a.</li>
</ol>
<p>Since the objective function decreases in every step, this algorithm is guaranteed to converge to a local optimum.</p>
<dl class="user"><dt><b>Implementation Notes:</b></dt><dd></dd></dl>
<p>Data points and predefined centroids (if used) are expected to be stored row-wise, in a column of type <code><a class="el" href="group__grp__svec.html">SVEC</a></code> (or any type convertible to <code><a class="el" href="group__grp__svec.html">SVEC</a></code>, like <code>FLOAT[]</code> or <code>INTEGER[]</code>). Data points with non-finite values (NULL, NaN, infinity) in any component will be skipped during analysis.</p>
<p>The following methods are available for the centroid seeding:</p>
<ul>
<li><b>random selection</b>: Select \( k \) centroids randomly among the input points.</li>
<li><b>kmeans++</b> [2]: Start with a single centroid chosen randomly among the input points. Then iteratively choose new centroids from the input points until there is a total of \( k \) centroids. The probability for picking a particular point is proportional to its minimum distance to any existing centroid. <br/>
Intuitively, kmeans++ favors seedings where centroids are spread out over the whole range of the input points, while at the same time not being too susceptible to outliers [2].</li>
<li><b>user-specified set of initial centroids</b>: See below for a description of the expected format of the set of initial centroids.</li>
</ul>
<p>The following distance functions can be used (computation of barycenter/mean in parentheses):</p>
<ul>
<li><b><a class="el" href="linalg_8sql__in.html#aad193850e79c4b9d811ca9bc53e13476">dist_norm1</a></b>: 1-norm/Manhattan (element-wise median [Note that MADlib does not provide a median aggregate function for support and performance reasons.])</li>
<li><b><a class="el" href="linalg_8sql__in.html#aa58e51526edea6ea98db30b6f250adb4">dist_norm2</a></b>: 2-norm/Euclidean (element-wise mean)</li>
<li><b><a class="el" href="linalg_8sql__in.html#a00a08e69f27524f2096032214e15b668">squared_dist_norm2</a></b>: squared Euclidean distance (element-wise mean)</li>
<li><b><a class="el" href="linalg_8sql__in.html#a8c7b9281a72ff22caf06161701b27e84">dist_angle</a></b>: angle (element-wise mean of normalized points)</li>
<li><b><a class="el" href="linalg_8sql__in.html#afa13b4c6122b99422d666dedea136c18">dist_tanimoto</a></b>: tanimoto (element-wise mean of normalized points [5])</li>
<li><b>user defined function</b> with signature DOUBLE PRECISION[] x DOUBLE PRECISION[] -&gt; DOUBLE PRECISION</li>
</ul>
<p>The following aggregate functions for determining centroids can be used:</p>
<ul>
<li><b><a class="el" href="linalg_8sql__in.html#a1aa37f73fb1cd8d7d106aa518dd8c0b4">avg</a></b>: average</li>
<li><b><a class="el" href="linalg_8sql__in.html#a0b04663ca206f03e66aed5ea2b4cc461">normalized_avg</a></b>: normalized average</li>
</ul>
<p>The algorithm stops when one of the following conditions is met:</p>
<ul>
<li>The fraction of updated points is smaller than the convergence threshold (default: 0.001).</li>
<li>The algorithm reaches the maximum number of allowed iterations (default: 20).</li>
</ul>
<p>A popular method to assess the quality of the clustering is the <em>silhouette coefficient</em>, a simplified version of which is provided as part of the k-means module. Note that for large data sets, this computation is expensive.</p>
<dl class="user"><dt><b>Input:</b></dt><dd>The <b>source relation</b> is expected to be of the following form (or to be implicitly convertible into the following form): <pre>{TABLE|VIEW} <em>rel_source</em> (
...
<em>expr_points</em> FLOAT8[],
...
)</pre> where:<ul>
<li><em>expr_points</em> is the name of a column with point coordinates. Types such as <code>svec</code> or <code>INTEGER[]</code> are implicitly converted to <code>FLOAT8[]</code>.</li>
</ul>
</dd></dl>
<p>If kmeans is called with a set of initial centroids, the centroid relation is expected to be of the following form: </p>
<pre>{TABLE|VIEW} <em>rel_initial_centroids</em> (
...
<em>expr_centroid</em> DOUBLE PRECISION[],
...
)</pre><p> where:</p>
<ul>
<li><em>expr_centroid</em> is the name of a column with coordinates.</li>
</ul>
<dl class="user"><dt><b>Usage:</b></dt><dd>The k-means algorithm can be invoked in four possible ways:</dd></dl>
<ul>
<li>using <em>random</em> centroid seeding method for a provided \( k \): <pre>SELECT * FROM <a class="el" href="kmeans_8sql__in.html#aeec5efd06aca50f4830aa10d522dc5ed">kmeans_random</a>(
'<em>rel_source</em>', '<em>expr_point</em>', k,
[ '<em>fn_dist</em>', '<em>agg_centroid</em>',
<em>max_num_iterations</em>, <em>min_frac_reassigned</em> ]
);</pre></li>
</ul>
<ul>
<li>using <em>kmeans++</em> centroid seeding method for a provided \( k \): <pre>SELECT * FROM <a class="el" href="kmeans_8sql__in.html#ac6c26c8e6b4643acfa79a87bd3ab0fe4">kmeanspp</a>(
'<em>rel_source</em>', '<em>expr_point</em>', k,
[ '<em>fn_dist</em>', '<em>agg_centroid</em>',
<em>max_num_iterations</em>, <em>min_frac_reassigned</em> ]
);</pre></li>
</ul>
<ul>
<li>with a provided centroid set: <pre>SELECT * FROM <a class="el" href="kmeans_8sql__in.html#a6e1a47f006bc0576f56eabcd6903086f">kmeans</a>(
'<em>rel_source</em>', '<em>expr_point</em>',
'<em>rel_initial_centroids</em>', '<em>expr_centroid</em>',
[ '<em>fn_dist</em>', '<em>agg_centroid</em>',
<em>max_num_iterations</em>, <em>min_frac_reassigned</em> ]
);</pre> ------------ OR --------------- <pre>SELECT * FROM <a class="el" href="kmeans_8sql__in.html#a6e1a47f006bc0576f56eabcd6903086f">kmeans</a>(
'<em>rel_source</em>', '<em>expr_point</em>',
initial_centroids,
[ '<em>fn_dist</em>', '<em>agg_centroid</em>',
<em>max_num_iterations</em>, <em>min_frac_reassigned</em> ]
);</pre> where:<ul>
<li><em>initial_centroids</em> is of type <code>DOUBLE PRECISION[][]</code>.</li>
</ul>
</li>
</ul>
<p>The output of the k-means module is a table that includes the final centroid positions (DOUBLE PRECISION[][]), the objective function, the fraction of reassigned points in the last iteration, and the number of total iterations: </p>
<pre>
centroids | objective_fn | frac_reassigned | num_iterations
----------------------------------+------------------+-----------------+----------------
...
</pre><dl class="user"><dt><b>Examples:</b></dt><dd></dd></dl>
<ol type="1">
<li>Prepare some input data. <div class="fragment"><pre class="fragment">sql&gt; SELECT * FROM <span class="keyword">public</span>.km_sample LIMIT 5;
points
-------------------------------------------
{1,1}:{15.8822241332382,105.945462542586}
{1,1}:{34.5065216883086,72.3126099305227}
{1,1}:{22.5074400822632,95.3209559689276}
{1,1}:{70.2589857042767,68.7395178806037}
{1,1}:{30.9844257542863,25.3213323024102}
(5 rows)
</pre></div> Note: the example <em>points</em> is type <code><a class="el" href="group__grp__svec.html">SVEC</a></code>.</li>
<li>Run k-means clustering using kmeans++ for centroid seeding: <div class="fragment"><pre class="fragment">sql&gt; SELECT * FROM madlib.kmeanspp(<span class="stringliteral">&#39;km_sample&#39;</span>, <span class="stringliteral">&#39;points&#39;</span>, 2, <span class="stringliteral">&#39;madlib.squared_dist_norm2&#39;</span>, <span class="stringliteral">&#39;madlib.avg&#39;</span>, 20, 0.001);
);
centroids | objective_fn | frac_reassigned | num_iterations
-------------------------------------------------------------------------+------------------+-----------------+----------------
{{68.01668579784,48.9667382972952},{28.1452167573446,84.5992507653263}} | 586729.010675982 | 0.001 | 5
</pre></div></li>
<li>Calculate the simplified silhouette coefficient: <div class="fragment"><pre class="fragment">sql&gt; SELECT * from madlib.simple_silhouette(<span class="stringliteral">&#39;km_test_svec&#39;</span>,<span class="stringliteral">&#39;points&#39;</span>,
(select centroids from madlib.kmeanspp(<span class="stringliteral">&#39;km_test_svec&#39;</span>,<span class="stringliteral">&#39;points&#39;</span>,2,<span class="stringliteral">&#39;madlib.squared_dist_norm2&#39;</span>,<span class="stringliteral">&#39;madlib.avg&#39;</span>,20,0.001)),
<span class="stringliteral">&#39;madlib.dist_norm2&#39;</span>);
<a class="code" href="kmeans_8sql__in.html#a71e7675758c99acbe7785819b6a85a8f" title="Compute a simplified version of the silhouette coefficient.">simple_silhouette</a>
-------------------
0.611022970398174
</pre></div></li>
</ol>
<dl class="user"><dt><b>Literature:</b></dt><dd></dd></dl>
<p>[1] Wikipedia, K-means Clustering, <a href="http://en.wikipedia.org/wiki/K-means_clustering">http://en.wikipedia.org/wiki/K-means_clustering</a></p>
<p>[2] David Arthur, Sergei Vassilvitskii: k-means++: the advantages of careful seeding, Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA'07), pp. 1027-1035, <a href="http://www.stanford.edu/~darthur/kMeansPlusPlus.pdf">http://www.stanford.edu/~darthur/kMeansPlusPlus.pdf</a></p>
<p>[3] E. R. Hruschka, L. N. C. Silva, R. J. G. B. Campello: Clustering Gene-Expression Data: A Hybrid Approach that Iterates Between k-Means and Evolutionary Search. In: Studies in Computational Intelligence - Hybrid Evolutionary Algorithms. pp. 313-335. Springer. 2007.</p>
<p>[4] Lloyd, Stuart: Least squares quantization in PCM. Technical Note, Bell Laboratories. Published much later in: IEEE Transactions on Information Theory 28(2), pp. 128-137. 1982.</p>
<p>[5] Leisch, Friedrich: A Toolbox for K-Centroids Cluster Analysis. In: Computational Statistics and Data Analysis, 51(2). pp. 526-544. 2006.</p>
<dl class="see"><dt><b>See also:</b></dt><dd>File <a class="el" href="kmeans_8sql__in.html" title="Set of functions for k-means clustering.">kmeans.sql_in</a> documenting the SQL functions. </dd></dl>
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<li class="footer">Generated on Tue Apr 2 2013 14:57:03 for MADlib by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.5.1 </li>
</ul>
</div>
</body>
</html>