<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-4903856565127937599</id><updated>2024-09-26T20:22:43.071-04:00</updated><category term="Statistics"/><category term="Code-Examples"/><category term="Data-Mining"/><category term="General Info"/><category term="Product-Info"/><title type='text'>Numoracle Recipes</title><subtitle type='html'>Data Mining, Predictive Analytics, Statistics and Scientific Computing in the Oracle Database</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Ramkumar Krishnan (Ram)</name><uri>http://www.blogger.com/profile/16930865713058805668</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>11</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-2635060810034860318</id><published>2008-01-04T11:38:00.001-05:00</published><updated>2008-01-04T15:10:54.341-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Data-Mining"/><category scheme="http://www.blogger.com/atom/ns#" term="Product-Info"/><title type='text'>Talk at WPI - Oracle In-Database Mining</title><content type='html'>My plan was to finish a full series on Oracle tools for Basic Statistics, before moving on to typical &quot;blog-like&quot; postings - but I realize I&#39;ll need at least another month (or two) to get to topics like ANOVA and Multiple Regression. I feel compelled to get a basic feel for a technique/concept before writing up examples of the functions here (which anybody can quickly get from the Oracle SQL Reference Manual).&lt;br /&gt;&lt;br /&gt;So I am (reluctantly) breaking my rule to sneak in this note about a talk I gave in Nov &#39;07 at the &lt;a href=&quot;http://web.cs.wpi.edu/Flyers/2007/Krishnan30Nov07.html&quot;&gt;Worcester Polytechnic &#39;07 Colloqium Series&lt;/a&gt; - before it loses its relevance. The talk provides the motivation for in-database mining, and the &lt;a href=&quot;http://www.box.net/shared/q8wb4d04c4&quot;&gt;presentation slides offer a good intro &lt;/a&gt;to Oracle Data Mining in the 11gR1 Database release.&lt;br /&gt;&lt;br /&gt;Oracle has touted the benefits of in-database mining for over 4 years now, with steady improvements to the product and an expanding customer base. &lt;a href=&quot;http://www.sas.com/news/preleases/100807/IndatabaseProcessing.html&quot;&gt;The recent announcement from market leader SAS&lt;/a&gt; on integration with Teradata is a nice vindication of this approach. Details of the integration, whether this engineering effort pans out, and how the market receives the integrated product remains to be seen - but this is good for the industry. SAS still owns the bully pulpit in Analytics, and this move can hopefully lead to greater awareness of the benefits of this approach, and consolidation in this space. &lt;a href=&quot;http://oracledmt.blogspot.com/2007/12/recap-post.html&quot;&gt;Marcos has promised to write about these developments&lt;/a&gt; from his perspective as a scientist/developer - so I will hold off my thoughts in anticipation of that post.&lt;br /&gt;&lt;br /&gt;Impressions on WPI - good school with active AI and Database research groups. I had the pleasure of meeting Prof. Ruiz and Prof. Heffernan from the &lt;a href=&quot;http://web.cs.wpi.edu/Research/airg/&quot;&gt;AI research group&lt;/a&gt; - they have some interesting projects there, and Prof. Rundentstein and Prof. Mani from the &lt;a href=&quot;http://davis.wpi.edu/dsrg/&quot;&gt;database research group&lt;/a&gt;. Check these programs out if you are an aspiring CS student.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/2635060810034860318/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/2635060810034860318?isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/2635060810034860318'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/2635060810034860318'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2008/01/talk-at-wpi-oracle-in-database-mining.html' title='Talk at WPI - Oracle In-Database Mining'/><author><name>Ramkumar Krishnan (Ram)</name><uri>http://www.blogger.com/profile/16930865713058805668</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-8227606918913473196</id><published>2007-12-29T13:22:00.001-05:00</published><updated>2008-04-15T00:26:00.129-04:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Student&#39;s T-Distribution, Degrees of Freedom</title><content type='html'>In the &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/12/students-t-distribution-degrees-of.html&quot;&gt;previous post&lt;/a&gt;, we showed how to compute the confidence interval when &amp;sigma; - i.e. the population standard deviation, is known. But in a typical situation, &amp;sigma; is rarely known.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Computing confidence Interval for &amp;mu; when &amp;sigma; is Unknown:&lt;/b&gt; The solution then is to use the &lt;em&gt;sample&lt;/em&gt; standard deviation, and use a variant of the standardized statistic for normal distribution z = (X_bar - &amp;mu;)/&amp;sigma;.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Student&#39;s T Distribution:&lt;/b&gt;&lt;br /&gt;For a &lt;em&gt;normally distributed population&lt;/em&gt;, the Student&#39;s T distribution is given by this standardized statistic: &lt;b&gt;t = (X_bar - &amp;mu;)/(S/&amp;radic;n), with (n - 1) degrees of freedom (df) for the deviations&lt;/b&gt;, where S is the sample standard deviation, and &lt;b&gt;n&lt;/b&gt; is the sample size. Key points:&lt;ul&gt;&lt;li&gt;The t distribution resembles the bell-shaped z (normal) distribution, but with wider tails than z, with mean zero (the mean of z), and with variance tending to 1 (the variance of z) as df increases. For df &gt; 2, &lt;b&gt;&amp;sigma;&amp;sup2; = df/(df - 2)&lt;/b&gt;. &lt;/li&gt;&lt;li&gt;The z (normal) distribution deals with one unknown &lt;b&gt;&amp;mu;&lt;/b&gt; - estimated by the random variable X_bar, while the t distribution deals with two unknowns &lt;b&gt;&amp;mu;&lt;/b&gt; and &lt;b&gt;&amp;sigma;&lt;/b&gt; - estimated by random variables X_bar and S respectively. So it tacitly handles greater uncertainty in the data.&lt;/li&gt;&lt;li&gt;As a consequence, the t distribution has wider confidence intervals than z&lt;/li&gt;&lt;li&gt;There is a t-distribution for each df=1,..n.&lt;/li&gt;&lt;li&gt;A good &lt;a href=&quot;http://www.statsoft.com/textbook/sttable.html&quot;&gt;comparison of the distributions is provided here&lt;/a&gt;.&lt;/li&gt;&lt;li&gt;For a sample (n &lt; 30) taken from normally distributed population, a &lt;b&gt;(1 - &amp;alpha;) 100% confidence interval&lt;/b&gt; for &amp;mu; when &amp;sigma; is &lt;u&gt;unknown&lt;/u&gt; is &lt;b&gt;X_bar &amp;plusmn; t&lt;sub&gt;&amp;alpha;/2&lt;/sub&gt; s/&amp;radic;n&lt;/b&gt;. This is the better distribution to use for small samples - with (n - 1) df, and unknown &amp;mu; and &amp;sigma.&lt;/li&gt;&lt;li&gt;But larger samples (n &amp;ge; 30), and/or with larger df, the t distribution can be approximated by a z distribution, and the &lt;b&gt;(1 - &amp;alpha;)100% confidence interval&lt;/b&gt; for &amp;mu; is &lt;b&gt;X_bar &amp;plusmn; z&lt;sub&gt;&amp;alpha;/2&lt;/sub&gt; s/&amp;radic;n&lt;/b&gt; (Note: Using the sample sd itself).&lt;/li&gt;&lt;/ul&gt;We will pause to understand df in this context (based on Aczel&#39;s book). &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/12/sampling-distributions-introduction.html&quot;&gt;We noted earlier&lt;/a&gt; that the df helps as compensating factor - here is how. Assume a population of five numbers - 1, 2, 3, 4, 5. The (known) population mean is &amp;mu; = (1+2+3+4+5)/5 = 7.5. Assume we are asked to sample 5 numbers and find the squared standard deviation (ssd) based on &amp;mu;:&lt;pre&gt;x | x_bar | deviation | deviation_squared&lt;br /&gt;3 | 3     |  0.0      | 0&lt;br /&gt;2 | 3     | -1.0      | 1&lt;br /&gt;4 | 3     |  1.0      | 1&lt;br /&gt;1 | 3     | -2.0      | 4&lt;br /&gt;2 | 3     | -1.0      | 1&lt;br /&gt;Sum of Squared Deviation = 7&lt;/pre&gt;Given the mean, the deviation computation for the &lt;em&gt;random&lt;/em&gt; 5 samples effectively retain 5 degrees of freedom. Next, assume we &lt;em&gt;don&#39;t&lt;/em&gt; know the population mean, and instead are asked to compute the deviation from &lt;em&gt;one&lt;/em&gt; random number. Our goal is to choose a number that will minimize the deviation. A readily available number is the s sample mean (3+2+4+1+2)/5 = 2.4 - so we will use it:&lt;pre&gt;x | x_bar | deviation | deviation_squared&lt;br /&gt;3 | 2.4   |  0.6      | 0.36&lt;br /&gt;2 | 2.4   | -0.4      | 0.16&lt;br /&gt;4 | 2.4   |  1.6      | 2.56&lt;br /&gt;1 | 2.4   | -1.4      | 1.96&lt;br /&gt;2 | 2.4   | -0.4      | 0.16&lt;br /&gt;Sum of Squared Deviation = 5.2&lt;/pre&gt;The use of sample mean biases the SSD downward from 7 (actual) to 5.2. But given the choice of a mean, the deviation for the same random 5 samples retain df = (5 - 1) = 4 degrees of freedom.&lt;br /&gt;Subsequent choices of 2 means - (3+2)/2, (4+1+2)/3 - or 3 means, would reduce the SSD down further; at the same time, reducing the degrees of freedom for the deviation for the 5 random samples: df=(5-2), df=(5-3) and so on. As an extreme case, if we consider the sample mean of each sampled number as itself,  then we have:&lt;pre&gt;x | x_bar | deviation | deviation_squared&lt;br /&gt;3 | 3     |  0        | 0&lt;br /&gt;2 | 3     |  0        | 0&lt;br /&gt;4 | 4     |  0        | 0&lt;br /&gt;1 | 1     |  0        | 0&lt;br /&gt;2 | 2     |  0        | 0&lt;br /&gt;Sum of Squared Deviation = 0&lt;/pre&gt; which reduces SSD to 0, and the deviation df to (5-5) = 0. So in general,&lt;ul&gt;&lt;li&gt;deviations (and hence SSD) for a sample of size n taken from a known population mean &amp;mu; will have df = n&lt;/li&gt;&lt;li&gt;deviations for a sample of size n taken from the sample mean X_bar will have df = (n - 1)&lt;/li&gt;&lt;li&gt; deviations for a sample of size n taken from k &amp;le; n different numbers (typically mean of sample points) will have df = n - k.&lt;/li&gt;&lt;/ul&gt;Confidence interval using T-distribution applies for the narrow case of n &lt; 30, normal population; the Z distribution covers larger samples. The practical use this distribution appears more to be in comparing two populations using the &lt;b&gt;Student&#39;s T-Test&lt;/b&gt; - which requires understanding the concepts of Hypothesis Testing. So I will defer the code for an equivalent confidence_interval() routine based on T-distribution for later.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/8227606918913473196/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/8227606918913473196?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/8227606918913473196'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/8227606918913473196'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/12/students-t-distribution-degrees-of.html' title='Student&#39;s T-Distribution, Degrees of Freedom'/><author><name>Ramkumar Krishnan (Ram)</name><uri>http://www.blogger.com/profile/16930865713058805668</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-4690323076571691328</id><published>2007-12-21T14:08:00.001-05:00</published><updated>2008-04-15T00:22:21.752-04:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Code-Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Sampling Distributions, Confidence Interval</title><content type='html'>The key goal of inferential statistics is to make predictions/observations about the population (the whole) as a generalization of observations made on a random sample (the part). In the &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/11/sampling-and-sampling-distributions.html&quot;&gt;previous post&lt;/a&gt;, we discussed common techniques to derive samples from a population. In this post, we will discuss &lt;em&gt;sampling distributions&lt;/em&gt; - a key building block for the practice of statistical inference. These tools help answer questions such as: &quot;What should be the sample size to make a particular inference about this population?&quot; or &quot;100 random water samples along this river show an average of 50 ppm (parts per million) of this toxin, with standard deviation of 4.5 - how much is the river contaminated on average with 95% confidence interval&quot;, and so on.&lt;br /&gt;&lt;br /&gt;The objective in the next few posts is to discuss the use of Oracle SQL statistical functions for various sampling distributions. But if you are a typical DB developer with novice/intermediate knowledge of statistics (like me), spending some time on these foundational concepts may be worthwhile. I am currently using &lt;a href=&quot;http://www.amazon.com/gp/product/007287418X?ie=UTF8&amp;amp;tag=numoreci-20&amp;amp;link_code=as3&amp;amp;camp=211189&amp;amp;creative=373489&amp;amp;creativeASIN=007287418X&quot;&gt;Complete Business Statistics&lt;/a&gt; and the &lt;a href=&quot;http://www.amazon.com/gp/product/1592571999?ie=UTF8&amp;tag=numoreci-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1592571999&quot;&gt;Idiot&#39;s Guide to Statistics&lt;/a&gt;&lt;img border=&quot;0&quot; width=&quot;1&quot; alt=&quot;&quot; style=&quot;border:none !important; margin:0px !important;&quot; src=&quot;http://www.assoc-amazon.com/e/ir?t=numoreci-20&amp;l=as2&amp;o=1&amp;a=1592571999&quot; height=&quot;1&quot;/&gt;as my guides - you may use these or other books and/or the free online references on the right pane of this blog. &lt;ul&gt;&lt;li&gt;The various numerical measures - such as mean, variance etc - when applied to a &lt;em&gt;sample&lt;/em&gt;, are called &lt;b&gt;sample statistics&lt;/b&gt; or simply &lt;b&gt;statistics&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;When these numerical measures are applied to a &lt;em&gt;population&lt;/em&gt;, they are called &lt;b&gt;population parameters&lt;/b&gt; or simply &lt;b&gt;parameters&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;An &lt;b&gt;estimator&lt;/b&gt; of a population parameter is the sample statistic used to estimate the parameter. The sample statistic - mean, X_bar - estimates the population mean μ; the sample statistic - variance, S² - estimates the population variance σ².&lt;/li&gt;&lt;li&gt;When a single numerical value is the estimate, it is called a &lt;b&gt;point estimate&lt;/b&gt;. For example, when we sample a population and obtain a value for X_bar - the statistic - we get a &lt;em&gt;specific&lt;/em&gt; sample mean, denoted by x_bar (lower-case), which is the estimate for population mean μ. When the estimate covers a range or an interval, it is called an &lt;b&gt;interval estimate&lt;/b&gt; - the unknown population parameter is likely to be found in this interval&lt;/li&gt;&lt;li&gt;A sample statistic, such as X_bar, is a &lt;em&gt;random variable&lt;/em&gt;; the values of this randome variable depend on the values in the random sample from which the statistic is computed; the sample itself depends on the population from which it is drawn. This random variable has probability distribution, which is called the &lt;b&gt;sampling distribution&lt;/b&gt;&lt;/li&gt;&lt;li&gt;The principal use of sampling distributions and its related concepts is to help predict how close the estimate is to the population parameter, and with what probability.&lt;/li&gt;&lt;/ul&gt;&lt;b&gt;Central Limit theorem&lt;/b&gt;:&lt;br /&gt;The sample statistic sample mean X_bar exhibits a unique behavior - regardless of the population distribution (uniform, exponential, other), in the limit n → ∞ (&quot;n tends to infinity&quot;, where n is the sample size), the sampling distribution of X_bar tends to a normal distribution. The &lt;em&gt;rate&lt;/em&gt; at which the sampling distribution approaches normal distribution depends on the population distribution. Now, if the &lt;u&gt;population itself is normally distributed&lt;/u&gt;, then X_bar is normally distributed for &lt;em&gt;any&lt;/em&gt; sample size. This is the essence of what is called Central Limit theorem.&lt;br /&gt;&lt;br /&gt;Formally, when a population with mean μ and standard deviation σ is sampled, the sampling distribution of the sample mean X_bar will tend to a normal distribution with (the same) mean &lt;b&gt;μ&lt;/b&gt; and standard deviation &lt;b&gt;σ&lt;sub&gt;x_bar&lt;/sub&gt; = σ/√n&lt;/b&gt;, as the sample size &lt;b&gt;n&lt;/b&gt; becomes large. &quot;Large&quot; is empirically defined to be &lt;b&gt;n ≥ 30&lt;/b&gt;. The value &lt;b&gt;σ&lt;sub&gt;x_bar&lt;/sub&gt;&lt;/b&gt; is called the &lt;b&gt;standard error of the mean&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;&quot;Okay,... so what is the big deal?&quot;. The big deal is that we can now estimate the population mean (regardless of the population&#39;s distribution) using the familiar technique (&lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/09/st004-inferential-statistics-4.html&quot;&gt;that we saw in an earlier post&lt;/a&gt;) for standard normal distribution.&lt;br /&gt;&lt;br /&gt;Now, it is not common that one or more of the population parameters (like standard deviation) are always known. The computations have to be modified to accommodate these unknowns - which brings us to two more concepts associated with sampling distributions.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Degrees of Freedom (DF):&lt;/b&gt;&lt;br /&gt;If we are asked to choose three random numbers &lt;em&gt;a&lt;/em&gt;, &lt;em&gt;b&lt;/em&gt; and &lt;em&gt;c&lt;/em&gt;, we are free to choose any three numbers without any restrictions - in other words, we have 3 &lt;em&gt;degrees of freedom&lt;/em&gt;. But if the three numbers are put together in a model &lt;em&gt;a + b + c = 10&lt;/em&gt;, then we have just 2 degrees of freedom - choice of &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; can be arbitrary , but &lt;em&gt;c&lt;/em&gt; is constrained to take a specific value that satisfies the model. The use of &lt;em&gt;df&lt;/em&gt; appears to be a compensatory mechanism in the computations, specific to the context/situation in which is it applied - so we&#39;ll discuss this in the context of the technique we are illustrating.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Confidence Interval:&lt;/b&gt;&lt;br /&gt;An interval estimate, with its associated measure of confidence is called &lt;b&gt;confidence interval&lt;/b&gt;. It is a range of numbers that probably contains the unknown population parameter, with an adjoining &lt;em&gt;level of confidence&lt;/em&gt; that it indeed does. This is better than a point estimate in that it gives some indication of the &lt;em&gt;accuracy&lt;/em&gt; of the estimation.&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/09/st004-inferential-statistics-4.html&quot;&gt;In an earlier post&lt;/a&gt;, we briefly touched upon the transformation of a normal random variable (X, with arbitrary μ and σ) to a &lt;em&gt;standard&lt;/em&gt; normal variable (Z, with μ = 0 and σ = 1). The transformations are X to Z: Z = (X - μ)/σ and Z to X: X = μ + Zσ. Applying the latter transformation to standardized sampling distribution with mean μ and standard deviation σ/√n, the confidence interval for the population mean is μ ± Z σ/√n.&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-xdb5-fsQVSIbwpQlk9GQPWQNg4pPPcqsPzx8mtAJEZc018SZC3bvM20qWPRUlaR9f-7IfNpThcLnMzwfuuVgOrdh4qVe87fSqCU2GOEnio-tL2ZGZI0cP4Q9LCWSOq229hlK2-7mReEf/s1600-h/std_normal.png&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-xdb5-fsQVSIbwpQlk9GQPWQNg4pPPcqsPzx8mtAJEZc018SZC3bvM20qWPRUlaR9f-7IfNpThcLnMzwfuuVgOrdh4qVe87fSqCU2GOEnio-tL2ZGZI0cP4Q9LCWSOq229hlK2-7mReEf/s320/std_normal.png&quot; border=&quot;0&quot; alt=&quot;&quot;id=&quot;BLOGGER_PHOTO_ID_5149196979836410450&quot; /&gt;&lt;/a&gt;A typical question will be &quot;Give me the 95% confidence interval for the population mean&quot;. Given the confidence level, and the knowledge that the area under the standard normal curve is 1, we can obtain the value of Z from the &lt;a href=&quot;http://www.stat.tamu.edu/~mhasson/normal.pdf&quot;&gt;standard normal table&lt;/a&gt;. For example, a 95% confidence level translates to an area of 0.95 symmetrically distributed around the mean, leaving 0.025 as areas on the left and right tails. From the table, Z = -1.96 for P=0.025, and Z = 1.96 for P=(0.025+0.95). So the 95% confidence interval for the population mean, when the population standard deviation is known, is given by μ ± 1.96 σ/√n&lt;br /&gt;&lt;br /&gt;We&#39;ll wrap this section reinforcing some concepts for use later:&lt;ul&gt;&lt;li&gt;In probability-speak, the statement &quot;95% confidence interval for the population mean&quot; implies that &quot;there is a 95% probability that a given confidence interval from a given random sample from the same population will contain the population mean&quot;. It does &lt;u&gt;NOT&lt;/u&gt; imply a &quot;95% probability that the population mean is a value in the range of the interval&quot;. In the figure, sample mean x for a specific sample falls within the interval - based on this, the confidence interval is considered to contain the population mean μ. If x for another sample falls in the tail region, then that confidence interval cannot assert that it contains μ.&lt;/li&gt;&lt;li&gt;The quantity Z σ/√n is called &lt;b&gt;sampling error&lt;/b&gt; or &lt;b&gt;margin of error&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;The combined area under the curve in the tails (i.e. 1 - 0.95 = 0.05 in the above example) is called &lt;b&gt;level of significance &amp;alpha;&lt;/b&gt;, and/or &lt;b&gt;error probability&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;The area under the curve excluding the tails under the curve in the tails &lt;b&gt;(1 - &amp;alpha;)&lt;/b&gt; is called &lt;b&gt;confidence coefficient&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;The confidence coefficient x 100, expressed as a percentage, is the &lt;b&gt;confidence level&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;The Z value that cuts off the area under the right tail (i.e. the area &amp;alpha;/2 on the right of the curve, 1.96 in our example) is denoted as &lt;b&gt;z&lt;sub&gt;&amp;alpha;/2&lt;/sub&gt;&lt;/b&gt;.&lt;/li&gt;&lt;li&gt;For a small sample (n &lt; 30), or a sample taken from a normally distributed population, the &lt;b&gt;(1 - &amp;alpha;) 100% confidence interval&lt;/b&gt; for &amp;mu; with known &amp;sigma; is &lt;b&gt;X_bar &amp;plusmn; z&lt;sub&gt;&amp;alpha;/2&lt;/sub&gt; &amp;sigma;/&amp;radic;n&lt;/b&gt;&lt;/ul&gt;&lt;b&gt;Confidence Interval for Population Mean with Known σ:&lt;/b&gt;&lt;br /&gt;Excel has a CONFIDENCE() function to compute the confidence interval. See a simple equivalent for Oracle SQL below. The function takes in a table name, the column name representing the sampled quantity, and level of significance value of 0.05, 0.01, or 0.1 (that corresponds to the three popular confidence levels - 95%, 99%, and 90% - respectively), and returns an object that contains the sample mean, sample error, the lower and upper bounds of the interval.&lt;pre&gt;CREATE OR REPLACE TYPE conf_interval_t AS OBJECT (&lt;br /&gt;  pop_mean NUMBER, sample_err NUMBER, lower NUMBER, upper NUMBER);&lt;br /&gt;/&lt;br /&gt;CREATE OR REPLACE FUNCTION confidence_interval (&lt;br /&gt;  table_name     IN VARCHAR2,&lt;br /&gt;  column_name    IN VARCHAR2,&lt;br /&gt;  sample_percent IN NUMBER,&lt;br /&gt;  alpha          IN NUMBER DEFAULT 0.05,&lt;br /&gt;  seed           IN NUMBER DEFAULT NULL)&lt;br /&gt;RETURN conf_interval_t IS&lt;br /&gt;  pop_mean   NUMBER;&lt;br /&gt;  pop_stddev NUMBER;&lt;br /&gt;  sample_sz  NUMBER;&lt;br /&gt;  z          NUMBER;&lt;br /&gt;  err        NUMBER;&lt;br /&gt;  v_stmt     VARCHAR2(32767);&lt;br /&gt;BEGIN&lt;br /&gt;  v_stmt :=&lt;br /&gt;  &#39;SELECT AVG(&#39; || column_name || &#39;), count(*) &#39; ||&lt;br /&gt;    &#39;FROM (SELECT * &#39; ||&lt;br /&gt;            &#39;FROM &#39; || table_name ||&lt;br /&gt;                  &#39; SAMPLE(&#39; || sample_percent || &#39;)&#39;;&lt;br /&gt;  IF (seed IS NOT NULL) THEN&lt;br /&gt;    v_stmt := v_stmt || &#39; SEED(&#39; || seed || &#39;)&#39;;&lt;br /&gt;  END IF;&lt;br /&gt;  v_stmt := v_stmt || &#39;)&#39;;&lt;br /&gt;  EXECUTE IMMEDIATE v_stmt INTO pop_mean, sample_sz;&lt;br /&gt;&lt;br /&gt;  v_stmt :=&lt;br /&gt;  &#39;SELECT STDDEV(&#39; || column_name || &#39;) &#39; ||&lt;br /&gt;    &#39;FROM &#39; || table_name;&lt;br /&gt;  EXECUTE IMMEDIATE v_stmt INTO pop_stddev;&lt;br /&gt;  &lt;br /&gt;  IF (alpha = 0.05) THEN&lt;br /&gt;    z := 1.96;&lt;br /&gt;  ELSIF (alpha = 0.01) THEN&lt;br /&gt;    z := 2.57;&lt;br /&gt;  ELSIF (alpha = 0.1) THEN&lt;br /&gt;    z := 1.64;&lt;br /&gt;  ELSE&lt;br /&gt;    RETURN(NULL);&lt;br /&gt;  END IF;&lt;br /&gt;&lt;br /&gt;  err := z * pop_stddev / SQRT(sample_sz);&lt;br /&gt;  RETURN (conf_interval_t(pop_mean, err, (pop_mean - err), (pop_mean + err)));&lt;br /&gt;END confidence_interval;&lt;br /&gt;/&lt;/pre&gt; I used this function to find the 90%, 95%, and 99% confidence interval for the population mean of ORDERS_TOTAL in the ORDERS table, with an approx sample size of 15, with a seed to enable repeatable runs from the SQL sampler. Notice how the interval widens and becomes less precise as the confidence level increases. The true population mean is also shown to be contained in the interval&lt;pre&gt;SQL&gt; select confidence_interval(&#39;ORDERS&#39;, &#39;ORDER_TOTAL&#39;, 15, 0.1, 3) from dual;&lt;br /&gt;&lt;br /&gt;CONFIDENCE_INTERVAL(&#39;ORDERS&#39;,&#39;ORDER_TOTAL&#39;,15,0.1,3)(POP_MEAN, SAMPLE_ERR, LOWER, UPPER)&lt;br /&gt;-------------------------------------------------------------------------&lt;br /&gt;CONF_INTERVAL_T(24310.9188, 21444.6451, 2866.27368, 45755.5638)&lt;br /&gt;&lt;br /&gt;SQL&gt; select confidence_interval(&#39;ORDERS&#39;, &#39;ORDER_TOTAL&#39;, 15, 0.05, 3) from dual;&lt;br /&gt;&lt;br /&gt;CONFIDENCE_INTERVAL(&#39;ORDERS&#39;,&#39;ORDER_TOTAL&#39;,15,0.05,3)(POP_MEAN, SAMPLE_ERR, LOWER, UPPER)&lt;br /&gt;-------------------------------------------------------------------------&lt;br /&gt;CONF_INTERVAL_T(24310.9188, 25628.9661, -1318.0473, 49939.8848)&lt;br /&gt;&lt;br /&gt;SQL&gt; select confidence_interval(&#39;ORDERS&#39;, &#39;ORDER_TOTAL&#39;, 15, 0.01, 3) from dual;&lt;br /&gt;&lt;br /&gt;CONFIDENCE_INTERVAL(&#39;ORDERS&#39;,&#39;ORDER_TOTAL&#39;,15,0.01,3)(POP_MEAN, SAMPLE_ERR, LOWER, UPPER)&lt;br /&gt;-------------------------------------------------------------------------&lt;br /&gt;CONF_INTERVAL_T(24310.9188, 33605.3279, -9294.4092, 57916.2467)&lt;br /&gt;&lt;br /&gt;SQL&gt; select avg(order_total) from orders;&lt;br /&gt;&lt;br /&gt;AVG(ORDER_TOTAL)&lt;br /&gt;----------------&lt;br /&gt;      34933.8543&lt;br /&gt;&lt;br /&gt;SQL&gt;&lt;/pre&gt;Fine - but how do we find the confidence interval when σ is unknown (which is the norm in practice)? Enter &lt;b&gt;T (or Student&#39;s) Distribution&lt;/b&gt; - we will look at this in the &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/12/students-t-distribution-degrees-of.html&quot;&gt;next post&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/4690323076571691328/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/4690323076571691328?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/4690323076571691328'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/4690323076571691328'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/12/sampling-distributions-introduction.html' title='Sampling Distributions, Confidence Interval'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-xdb5-fsQVSIbwpQlk9GQPWQNg4pPPcqsPzx8mtAJEZc018SZC3bvM20qWPRUlaR9f-7IfNpThcLnMzwfuuVgOrdh4qVe87fSqCU2GOEnio-tL2ZGZI0cP4Q9LCWSOq229hlK2-7mReEf/s72-c/std_normal.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-7468332349201847805</id><published>2007-11-03T23:49:00.000-04:00</published><updated>2008-01-04T15:13:38.032-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Code-Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Sampling</title><content type='html'>The key goal of inferential statistics is to make predictions/observations about the &lt;em&gt;population&lt;/em&gt; (the whole) as a generalization of observations made on a random &lt;em&gt;sample&lt;/em&gt; (the part). In this post, we will present tools/techniques in Oracle for sampling data.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Sampling&lt;/b&gt;&lt;br /&gt;For ensuring high accuracy in the results of a statistical inference (technique), the sample dataset should minimally have these properties:&lt;ul&gt;&lt;li&gt;the sample must be drawn randomly from the population&lt;/li&gt;&lt;li&gt;every segment of the population must be adequately and proportionately represented&lt;/li&gt;&lt;li&gt;the sample should not be &lt;em&gt;biased&lt;/em&gt; - a classic example is the &lt;em&gt;non-response bias&lt;/em&gt; seen in survey/poll data - where the respondents ignore/refuse to answer a particular question (&quot;Have you smoked marijuana?&quot; in a health questionnaire).&lt;/li&gt;&lt;/ul&gt;We will use this &lt;a href=&quot;http://en.wikipedia.org/wiki/Sampling_%28statistics%29&quot;&gt;succinct introduction to sampling techniques&lt;/a&gt; (or alternatively, &lt;a href=&quot;http://www.statcan.ca/english/edu/power/ch13/first13.htm&quot;&gt;this resource&lt;/a&gt;) as a basis to discuss probabilistic (a.k.a random) sampling &lt;a href=&quot;http://www.ma.utexas.edu/users/parker/sampling/repl.htm&quot;&gt;with and without replacement&lt;/a&gt;, clustered sampling, and stratified sampling in Oracle.&lt;br /&gt;&lt;br /&gt;The &lt;a href=&quot;http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#i2065646&quot;&gt;SAMPLE clause in the SQL SELECT statement&lt;/a&gt; supports simple random sampling and clustered sampling. Note that the &lt;em&gt;sampling frame&lt;/em&gt; here is simply the set of rows returned by the statement - so you can control how many, and which, of the rows are sampled using filters in the WHERE clause. Here are some examples based on the OE.ORDERS table provided with the &lt;a href=&quot;http://st-doc.us.oracle.com/11/111/server.111/b28328/toc.htm&quot;&gt;Sample Schema&lt;/a&gt; (connect oe/oe in SQL*Plus to see this table).&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Example: Random Sampling without replacement:&lt;/b&gt;&lt;br /&gt;Get random samples from ORDERS table with each row having a 15% chance of being in the sample&lt;pre&gt;SQL&gt; select order_id,order_status,order_total from orders sample (15) seed (3);&lt;br /&gt;&lt;br /&gt;  ORDER_ID ORDER_STATUS ORDER_TOTAL&lt;br /&gt;---------- ------------ -----------&lt;br /&gt;      2354       0       46257&lt;br /&gt;      2360       4       990.4&lt;br /&gt;      2361       8    120131.3&lt;br /&gt;      2384       3     29249.1&lt;br /&gt;      2389       4       17620&lt;br /&gt;      2400       2     69286.4&lt;br /&gt;      2401       3       969.2&lt;br /&gt;      2402       8         600&lt;br /&gt;      2415       6         310&lt;br /&gt;      2416       6         384&lt;br /&gt;      2417       5      1926.6&lt;br /&gt;&lt;br /&gt;  ORDER_ID ORDER_STATUS ORDER_TOTAL&lt;br /&gt;---------- ------------ -----------&lt;br /&gt;      2419       3       31574&lt;br /&gt;      2423       3     10367.7&lt;br /&gt;      2427       7        9055&lt;br /&gt;      2429       9       50125&lt;br /&gt;      2453       0         129&lt;br /&gt;&lt;br /&gt;16 rows selected.&lt;br /&gt;&lt;br /&gt;SQL&gt;&lt;/pre&gt;The SEED clause in the above statement helps with repeatability of results from one run to the next. Next, achieving &lt;b&gt;clustered sampling&lt;/b&gt; requires a BLOCK qualifier in the SAMPLE clause, as in &lt;pre&gt;select order_id,order_status,order_total from orders sample block (15) seed (3);&lt;/pre&gt;&lt;b&gt;Example: Random Sampling with replacement:&lt;/b&gt; can be accomplished with some minimal coding. In the example below, we using a hashing function (&lt;a href=&quot;http://st-doc.us.oracle.com/11/111/server.111/b28286/functions109.htm#sthref1754&quot;&gt;ORA_HASH&lt;/a&gt;) on the sequence of enumerated (using &lt;a href=&quot;http://st-doc.us.oracle.com/11/111/server.111/b28286/pseudocolumns009.htm#SQLRF00255&quot;&gt;ROWNUM &lt;/a&gt;pseudo-column) rows to randomize the selection from the table to be sampled. Let&#39;s try this: &quot;Get me random samples with replacement with sample size 10 rows from the ORDERS table&quot;.&lt;pre&gt;-- stage a view with row numbers tacked on to original table&lt;br /&gt;create view orders_view as&lt;br /&gt;select rownum rnum, o.*&lt;br /&gt;  from orders o;&lt;br /&gt;&lt;br /&gt;-- create a sequence&lt;br /&gt;create sequence orders_seq10;&lt;br /&gt;&lt;br /&gt;-- create a mapping table&lt;br /&gt;create table orders_map(rnum number, rhsh number);&lt;br /&gt;&lt;br /&gt;-- the requested sample size is 10&lt;br /&gt;begin&lt;br /&gt;  for i in 1..10&lt;br /&gt;  loop&lt;br /&gt;    insert into orders_map (rnum) values (orders_seq10.nextval);&lt;br /&gt;  end loop;&lt;br /&gt;end;&lt;br /&gt;/&lt;br /&gt;commit;&lt;br /&gt;&lt;br /&gt;-- the complete orders table is the sampling frame&lt;br /&gt;-- mark random sampled entries in mapping table&lt;br /&gt;update orders_map set rhsh = ora_hash(rnum, (select count(*) from orders));&lt;br /&gt;&lt;br /&gt;-- use the mapping table and orders_view to create a view with sampled rows&lt;br /&gt;create view orders_sample10_view as&lt;br /&gt;select o.*&lt;br /&gt;  from orders_view o, orders_map m&lt;br /&gt; where o.rnum = m.rnum;&lt;/pre&gt;This is the result of the above code snippet, when run in the OE schema using SQL*Plus:&lt;pre&gt;SQL&gt; select * from orders_sample10_view;&lt;br /&gt;&lt;br /&gt;RNUM    ORDER_ID   ORDER_MO CUSTOMER_ID ORDER_STATUS ORDER_TOTAL SALES_REP_ID&lt;br /&gt;------  ---------- -------- ----------- ------------ ----------- ------------&lt;br /&gt;11 2455       direct       145       7     14087.5      160&lt;br /&gt;12 2379       direct       146       8     17848.2      161&lt;br /&gt;13 2396       direct       147       8       34930      161&lt;br /&gt;14 2406       direct       148       8      2854.2      161&lt;br /&gt;15 2434       direct       149       8    268651.8      161&lt;br /&gt;16 2436       direct       116       8      6394.8      161&lt;br /&gt;17 2446       direct       117       8    103679.3      161&lt;br /&gt;18 2447       direct       101       8     33893.6      161&lt;br /&gt;19 2432       direct       102      10       10523      163&lt;br /&gt;20 2433       direct       103      10   78      163&lt;br /&gt;&lt;br /&gt;10 rows selected.&lt;br /&gt;&lt;br /&gt;SQL&gt;&lt;/pre&gt;For repeatability of sampled results, change all &quot;create view&quot; statements above to &quot;create table&quot;. It is also useful if the data to be sampled is persisted in a table, rather than presented to the sampling queries as a view.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Stratified Sampling&lt;/b&gt; can also be coded using SQL. But rather than provide an example query that is specific to a given table, we will provide a query generator function here. This is adapted from the output of code generated by Oracle Data Miner for stratified sampling. The function accepts a source and result table name, the name of the stratifying column (a.k.a. &quot;variable&quot; in statistics, &quot;attribute&quot; in data mining), the sampling size as a percentage of the table size, a scalar comparison operator (&#39;&lt;&#39;, &#39;=&#39;, &#39;&gt;&#39;), and an indicator to specify if each strata should roughly have the same number of elements.&lt;br /&gt;&lt;br /&gt;An important note - Oracle Data Miner - the GUI interface for the Oracle Data Mining platform provides sampling features, &lt;em&gt;and&lt;/em&gt; generated SQL/PLSQL code that corresponds to the sampling input. This example has been adapted from this generated code.&lt;pre&gt;CREATE OR REPLACE TYPE TARGET_VALUES_LIST IS TABLE OF VARCHAR2(32);&lt;br /&gt;/&lt;br /&gt;CREATE OR REPLACE TYPE VALUE_COUNT_LIST IS TABLE OF NUMBER;&lt;br /&gt;/&lt;br /&gt;&lt;br /&gt;CREATE OR REPLACE&lt;br /&gt;FUNCTION GENERATE_STRATIFIED_SQL ( &lt;br /&gt;  result_table_name  IN VARCHAR2,&lt;br /&gt;  source_table_name  IN VARCHAR2, &lt;br /&gt;  strat_attr_name    IN VARCHAR2,&lt;br /&gt;  percentage         IN NUMBER,&lt;br /&gt;  op                 IN VARCHAR2,&lt;br /&gt;  equal_sized_strata IN BOOLEAN DEFAULT FALSE)&lt;br /&gt;RETURN VARCHAR2 IS&lt;br /&gt;  v_stmt                VARCHAR2(32767);&lt;br /&gt;  tmp_str               VARCHAR2(4000);&lt;br /&gt;  sample_count          PLS_INTEGER;&lt;br /&gt;  attr_names            TARGET_VALUES_LIST;&lt;br /&gt;  attr_values           TARGET_VALUES_LIST;&lt;br /&gt;  counts                VALUE_COUNT_LIST;&lt;br /&gt;  counts_sampled        VALUE_COUNT_LIST;&lt;br /&gt;  v_minvalue            NUMBER;&lt;br /&gt;BEGIN&lt;br /&gt;  v_stmt :=&lt;br /&gt;    &#39;SELECT column_name &#39; ||&lt;br /&gt;      &#39;FROM user_tab_columns &#39; ||&lt;br /&gt;     &#39;WHERE table_name = &#39; || &#39;&#39;&#39;&#39; || UPPER(source_table_name) || &#39;&#39;&#39;&#39;;&lt;br /&gt;  EXECUTE IMMEDIATE v_stmt BULK COLLECT INTO attr_names;&lt;br /&gt;&lt;br /&gt;  v_stmt := &lt;br /&gt;    &#39;SELECT /*+ noparallel(t)*/ &#39; || strat_attr_name || &#39;, count(*), &#39; ||&lt;br /&gt;            &#39;ROUND ((count(*) * &#39; || percentage || &#39;)/100.0) &#39; ||&lt;br /&gt;      &#39;FROM &#39; || source_table_name || &lt;br /&gt;    &#39; WHERE &#39; || strat_attr_name || &#39; IS NOT NULL &#39; ||&lt;br /&gt;    &#39;GROUP BY &#39; || strat_attr_name;&lt;br /&gt;  EXECUTE IMMEDIATE v_stmt&lt;br /&gt;  BULK COLLECT INTO attr_values, counts, counts_sampled;&lt;br /&gt;&lt;br /&gt;  IF (equal_sized_strata = TRUE) THEN&lt;br /&gt;    FOR i IN counts.FIRST..counts.LAST&lt;br /&gt;    LOOP&lt;br /&gt;      IF (i = counts.FIRST) THEN&lt;br /&gt;         v_minvalue := counts(i);&lt;br /&gt;      ELSIF (counts(i) &gt; 0 AND v_minvalue &gt; counts(i)) THEN&lt;br /&gt;         v_minvalue := counts(i);&lt;br /&gt;      END IF;&lt;br /&gt;    END LOOP;&lt;br /&gt;    FOR i IN counts.FIRST..counts.LAST&lt;br /&gt;    LOOP&lt;br /&gt;      counts(i) := v_minvalue;&lt;br /&gt;    END LOOP;&lt;br /&gt;  END IF;&lt;br /&gt;&lt;br /&gt;  v_stmt :=&lt;br /&gt;   &#39;CREATE TABLE &#39; || result_table_name || &#39; AS &#39; ||&lt;br /&gt;   &#39;SELECT &#39;;&lt;br /&gt;  FOR i IN attr_names.FIRST..attr_names.LAST &lt;br /&gt;  LOOP&lt;br /&gt;    IF (i != attr_names.FIRST) THEN&lt;br /&gt;       v_stmt := v_stmt || &#39;,&#39;;&lt;br /&gt;    END IF;&lt;br /&gt;    v_stmt := v_stmt || attr_names(i);&lt;br /&gt;  END LOOP;&lt;br /&gt;  &lt;br /&gt;  v_stmt := v_stmt ||&lt;br /&gt;    &#39; FROM (SELECT /*+ no_merge */ t.*, &#39; ||&lt;br /&gt;                  &#39;ROW_NUMBER() OVER &#39; ||&lt;br /&gt;                    &#39;(PARTITION BY &#39; || strat_attr_name ||&lt;br /&gt;                    &#39; ORDER BY ORA_HASH(ROWNUM)) RNUM &#39; ||&lt;br /&gt;             &#39;FROM &#39; || source_table_name || &#39; t) &#39; ||&lt;br /&gt;    &#39;WHERE RNUM = 1 OR &#39;;&lt;br /&gt;&lt;br /&gt;  FOR i IN attr_values.FIRST..attr_values.LAST &lt;br /&gt;  LOOP&lt;br /&gt;    IF (i != attr_values.FIRST) THEN&lt;br /&gt;       tmp_str := &#39; OR &#39;;&lt;br /&gt;    END IF;&lt;br /&gt;    IF (counts(i) &lt;= 2) THEN&lt;br /&gt;      sample_count := counts(i);&lt;br /&gt;    ELSE&lt;br /&gt;      sample_count := counts_sampled(i);&lt;br /&gt;    END IF;&lt;br /&gt;    tmp_str :=&lt;br /&gt;      tmp_str || &lt;br /&gt;      &#39;(&#39; || strat_attr_name || &#39; = &#39;&#39;&#39; || attr_values(i) || &#39;&#39;&#39;&#39; ||&lt;br /&gt;      &#39; AND ORA_HASH(RNUM, (&#39; || counts(i) || &#39; -1), 12345) &#39; ||&lt;br /&gt;      op || sample_count || &#39;) &#39;;&lt;br /&gt;    v_stmt := v_stmt || tmp_str;&lt;br /&gt;  END LOOP;&lt;br /&gt;&lt;br /&gt;  RETURN(v_stmt);&lt;br /&gt;END;&lt;br /&gt;/&lt;/pre&gt;Now, cut and paste the above code in a SQL*Plus session (for this example, the Sample Schema OE/OE session), and then invoke the function in a SQL*Plus session using this wrapper. The inputs are pretty self-explanatory - we are asking to sample roughly 20% of the ORDERS table, stratified based on values in the ORDERS_STATUS column, and to place the sampled output in the table SAMPLED_ORDERS.&lt;pre&gt;set serveroutput on&lt;br /&gt;BEGIN&lt;br /&gt;  DBMS_OUTPUT.PUT_LINE(&lt;br /&gt;    generate_stratified_sql(&lt;br /&gt;      result_table_name =&gt; &#39;sampled_orders&#39;,&lt;br /&gt;      source_table_name =&gt; &#39;orders&#39;,&lt;br /&gt;      strat_attr_name   =&gt; &#39;order_status&#39;,&lt;br /&gt;      percentage        =&gt; 20,&lt;br /&gt;      op                =&gt; &#39; &lt; &#39;));&lt;br /&gt;END;&lt;br /&gt;/&lt;/pre&gt;this will return the following sampling query (output formatted for easy readability):&lt;pre&gt;CREATE TABLE sampled_orders AS&lt;br /&gt;SELECT ORDER_ID,ORDER_MODE,CUSTOMER_ID,ORDER_STATUS,ORDER_TOTAL,&lt;br /&gt;       SALES_REP_ID,PROMOTION_ID&lt;br /&gt;  FROM (SELECT /*+ no_merge */ t.*,&lt;br /&gt;               ROW_NUMBER() OVER&lt;br /&gt;               (PARTITION BY order_status&lt;br /&gt;                ORDER BY ORA_HASH(ROWNUM)) RNUM&lt;br /&gt;          FROM orders t)&lt;br /&gt; WHERE RNUM = 1 OR&lt;br /&gt;       (order_status = &#39;1&#39; AND ORA_HASH(RNUM, (7 -1), 12345) &lt; 1)  OR&lt;br /&gt;       (order_status = &#39;6&#39; AND ORA_HASH(RNUM, (9 -1), 12345) &lt; 2)  OR&lt;br /&gt;       (order_status = &#39;2&#39; AND ORA_HASH(RNUM, (7 -1), 12345) &lt; 1)  OR&lt;br /&gt;       (order_status = &#39;5&#39; AND ORA_HASH(RNUM, (15 -1), 12345) &lt; 3) OR&lt;br /&gt;       (order_status = &#39;4&#39; AND ORA_HASH(RNUM, (12 -1), 12345) &lt; 2) OR&lt;br /&gt;       (order_status = &#39;8&#39; AND ORA_HASH(RNUM, (17 -1), 12345) &lt; 3) OR&lt;br /&gt;       (order_status = &#39;3&#39; AND ORA_HASH(RNUM, (9 -1), 12345) &lt; 2) OR&lt;br /&gt;       (order_status = &#39;7&#39; AND ORA_HASH(RNUM, (3 -1), 12345) &lt; 1) OR&lt;br /&gt;       (order_status = &#39;0&#39; AND ORA_HASH(RNUM, (11 -1), 12345) &lt; 2) OR&lt;br /&gt;       (order_status = &#39;10&#39; AND ORA_HASH(RNUM, (5 -1), 12345) &lt; 1) OR&lt;br /&gt;       (order_status = &#39;9&#39; AND ORA_HASH(RNUM, (10 -1), 12345) &lt; 2);&lt;/pre&gt;If you execute this SQL in the same OE session, the resulting table is:&lt;pre&gt;SQL&gt; select * from sampled_orders;&lt;br /&gt;&lt;br /&gt;  ORDER_ID ORDER_MO CUSTOMER_ID ORDER_STATUS ORDER_TOTAL SALES_REP_ID&lt;br /&gt;---------- -------- ----------- ------------ ----------- ------------&lt;br /&gt;      2363 online     144     0  10082.3&lt;br /&gt;      2369 online     116     0  11097.4&lt;br /&gt;      2403 direct     162     0      220   154&lt;br /&gt;      2439 direct     105     1  22150.1   159&lt;br /&gt;      2408 direct     166     1      309   158&lt;br /&gt;      2444 direct     109     1  77727.2   155&lt;br /&gt;      2358 direct     105     2     7826   155&lt;br /&gt;      2400 direct     159     2  69286.4   161&lt;br /&gt;      2375 online     122     2 103834.4&lt;br /&gt;      2450 direct     147     3     1636   159&lt;br /&gt;      2423 direct     145     3  10367.7   160&lt;br /&gt;&lt;br /&gt;  ORDER_ID ORDER_MO CUSTOMER_ID ORDER_STATUS ORDER_TOTAL SALES_REP_ID&lt;br /&gt;---------- -------- ----------- ------------ ----------- ------------&lt;br /&gt;      2385 online     147     4   295892&lt;br /&gt;      2437 direct     103     4    13550   163&lt;br /&gt;      2389 online     151     4    17620&lt;br /&gt;      2364 online     145     4     9500&lt;br /&gt;      2377 online     141     5  38017.8&lt;br /&gt;      2425 direct     147     5   1500.8   163&lt;br /&gt;      2394 direct     109     5    21863   158&lt;br /&gt;      2457 direct     118     5  21586.2   159&lt;br /&gt;      2426 direct     148     6     7200&lt;br /&gt;      2410 direct     168     6    45175   156&lt;br /&gt;      2427 direct     149     7     9055   163&lt;br /&gt;&lt;br /&gt;  ORDER_ID ORDER_MO CUSTOMER_ID ORDER_STATUS ORDER_TOTAL SALES_REP_ID&lt;br /&gt;---------- -------- ----------- ------------ ----------- ------------&lt;br /&gt;      2446 direct     117     8 103679.3   161&lt;br /&gt;      2402 direct     161     8      600   154&lt;br /&gt;      2434 direct     149     8 268651.8   161&lt;br /&gt;      2447 direct     101     8  33893.6   161&lt;br /&gt;      2365 online     146     9  27455.3&lt;br /&gt;      2372 online     119     9  16447.2&lt;br /&gt;      2359 online     106     9   5543.1&lt;br /&gt;      2368 online     149    10    60065&lt;br /&gt;&lt;br /&gt;30 rows selected.&lt;br /&gt;&lt;br /&gt;SQL&gt; select count(*) from orders;&lt;br /&gt;&lt;br /&gt;  COUNT(*)&lt;br /&gt;----------&lt;br /&gt;       105&lt;br /&gt;&lt;br /&gt;SQL&gt;&lt;/pre&gt;That is, 30 rows (a bit more than 20%) out of 105 are sampled, using order_status as the stratifying column.&lt;br /&gt;&lt;br /&gt;Try this example on your own schemas and tables, and send me some feedback. The maximum length of the string returned from GENERATE_STRATFIED_SQL() is 32767. Based on the interest, I can post another function that can handle SQL strings of &lt;= 64K in size.&lt;br /&gt;&lt;br /&gt;Given the explosive growth in data, sampling continues to remain an active, relevant research area in statistics, data mining, and computer science.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/7468332349201847805/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/7468332349201847805?isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/7468332349201847805'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/7468332349201847805'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/11/sampling-and-sampling-distributions.html' title='Sampling'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-7470536563606059942</id><published>2007-10-21T23:07:00.000-04:00</published><updated>2008-01-04T15:13:38.033-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Code-Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Analyzing your data for Distributions</title><content type='html'>In the &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/09/st004-inferential-statistics-4.html&quot;&gt;previous post&lt;/a&gt;, we looked at continuous probability distributions. You can determine if the data in a given column in a given table follows a particular distribution using routines in the &lt;a href=&quot;http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_stat_f.htm#i1000106&quot;&gt;DBMS_STAT_FUNCS package&lt;/a&gt;. The example shows a table with four columns - each pre-loaded with data synthesized to fit a particular continuous distribution.&lt;br /&gt;&lt;br /&gt;You can substitute the table name and column name for your experiment. A minor annoyance in the design of this API - most other Oracle packages will default to the current session name, but this one explicitly expects the schema name as input - which, in my case, is DMUSER - please change this to your schema name accordingly. &lt;pre&gt;set echo on;&lt;br /&gt;set serveroutput on;&lt;br /&gt;create table disttab (&lt;br /&gt;  num1 number, num2 number, num3 number, num4 number, cat1 varchar2(2));&lt;br /&gt;rem num1: Numbers generated based on normal distribution&lt;br /&gt;rem num2: Numbers generated based on exponential distribution&lt;br /&gt;rem num3: Numbers generated based on weibull distribution&lt;br /&gt;rem num4: Numbers generated based on uniform distribution&lt;br /&gt;insert into disttab values (9.604955,  1.05536,  4.126087, 22.950835, &#39;AA&#39;);&lt;br /&gt;insert into disttab values (13.022139, 1.714142, 4.999804, 32.598089, &#39;AA&#39;);&lt;br /&gt;insert into disttab values (11.572116, 3.697564, 2.81854,  24.552021, &#39;AA&#39;);&lt;br /&gt;insert into disttab values (9.817124,  1.530935, 2.131106, 6.359504,  &#39;AA&#39;);&lt;br /&gt;insert into disttab values (10.146569, 3.295829, 1.510639, 25.218639, &#39;AA&#39;);&lt;br /&gt;insert into disttab values (11.280488, 0.721109, 3.145515, 23.672146, &#39;BB&#39;);&lt;br /&gt;insert into disttab values (9.26679,   1.390282, 4.074397, 11.262112, &#39;BB&#39;);&lt;br /&gt;insert into disttab values (14.303472, 1.327971, 2.51907,  22.675373, &#39;BB&#39;);&lt;br /&gt;insert into disttab values (11.686556, 0.225337, 2.941825, 23.582254, &#39;BB&#39;);&lt;br /&gt;insert into disttab values (13.124479, 7.265271, 0.945059, 29.18001,  &#39;BB&#39;);&lt;br /&gt;insert into disttab values (8.601027,  7.060104, 6.078573, 14.878128, &#39;BB&#39;);&lt;br /&gt;insert into disttab values (12.241662, 0.257739, 3.395142, 31.148244, &#39;CC&#39;);&lt;br /&gt;insert into disttab values (13.781857, 4.281371, 1.349627, 23.862069, &#39;CC&#39;);&lt;br /&gt;insert into disttab values (7.827007,  1.347487, 5.836949, 10.76229,  &#39;CC&#39;);&lt;br /&gt;insert into disttab values (9.106408,  1.253113, 5.116857, 6.594224,  &#39;CC&#39;);&lt;br /&gt;insert into disttab values (11.066785, 4.56512,  3.393899, 22.435955, &#39;CC&#39;);&lt;br /&gt;insert into disttab values (10.71079,  2.700015, 1.922642, 7.635145,  &#39;DD&#39;);&lt;br /&gt;insert into disttab values (9.13019,   5.199126, 3.763481, 32.061213, &#39;DD&#39;);&lt;br /&gt;insert into disttab values (7.873859,  0.978657, 2.268487, 1.030052,  &#39;DD&#39;);&lt;br /&gt;insert into disttab values (7.731724,  2.382977, 2.639425, 5.676622,  &#39;DD&#39;);&lt;br /&gt;insert into disttab values (12.828234, 1.867099, 3.99808,  26.000458, &#39;DD&#39;);&lt;br /&gt;insert into disttab values (12.125892, 1.01285,  3.345311, 8.026281,  &#39;DD&#39;);&lt;br /&gt;insert into disttab values (9.800528,  5.869301, 3.840932, 29.928523, &#39;EE&#39;);&lt;br /&gt;insert into disttab values (10.605782, 3.145211, 2.13718,  27.398604, &#39;EE&#39;);&lt;br /&gt;insert into disttab values (14.054569, 4.089033, 2.436408, 4.483585,  &#39;EE&#39;);&lt;br /&gt;insert into disttab values (8.120606,  2.155303, 1.787835, 19.513588, &#39;EE&#39;);&lt;br /&gt;insert into disttab values (13.093059, 0.220456, 3.456848, 24.855135, &#39;EE&#39;);&lt;br /&gt;insert into disttab values (8.421441,  2.4819,   2.817669, 21.137668, &#39;FF&#39;);&lt;br /&gt;insert into disttab values (11.899697, 2.507618, 3.770983, 4.016285,  &#39;FF&#39;);&lt;br /&gt;insert into disttab values (9.601342,  1.12639,  3.21053,  28.643809, &#39;FF&#39;);&lt;br /&gt;insert into disttab values (9.32297,   10.003288,6.890515, 33.67171,  &#39;FF&#39;);&lt;br /&gt;insert into disttab values (6.896019,  10.76641, 3.123496, 29.077463, &#39;FF&#39;);&lt;br /&gt;insert into disttab values (12.542443, 0.228756, 4.081015, 33.542652, &#39;FF&#39;);&lt;br /&gt;insert into disttab values (14.038144, 7.326175, 3.53459,  11.731359, &#39;FF&#39;);&lt;/pre&gt;Let us first start with &lt;strong&gt;Normal Distribution&lt;/strong&gt;. The mean (same as E(x)) and  standard deviation are computed for the column &lt;em&gt;num1&lt;/em&gt; and provided as input.&lt;pre&gt;declare&lt;br /&gt; mean   number;&lt;br /&gt; stdev  number;&lt;br /&gt; sig    number;&lt;br /&gt;begin&lt;br /&gt; select avg(num1) into mean from disttab;&lt;br /&gt; select stddev(num1) into stdev from disttab;&lt;br /&gt; dbms_output.put_line(&#39;NORMAL DISTRIBUTION - SHAPIRO_WILKS&#39;);&lt;br /&gt; dbms_stat_funcs.normal_dist_fit(&lt;br /&gt;  &#39;dmuser&#39;, &#39;disttab&#39;, &#39;num1&#39;, &#39;SHAPIRO_WILKS&#39;, mean, stdev, sig);&lt;br /&gt; dbms_output.put_line(&#39;Mean    : &#39; || round(mean, 4));&lt;br /&gt; dbms_output.put_line(&#39;Stddev  : &#39; || round(stdev, 4));&lt;br /&gt; dbms_output.put_line(&#39;Sig     : &#39; || to_char(sig,&#39;9.9999&#39;));&lt;br /&gt;end;&lt;br /&gt;/&lt;/pre&gt;The output of this procedure looks like this:&lt;br /&gt;NORMAL DISTRIBUTION - SHAPIRO_WILKS&lt;br /&gt;W value : .9601472834631918774434537597940068448938&lt;br /&gt;Mean : 10.7426&lt;br /&gt;Stddev : 2.1094&lt;br /&gt;Sig :   .2456&lt;br /&gt;The high value for the W returned from the Shapiro-Wilks test (explained here) indicates an agreement with the null hypothesis that the data follows normal distribution. The significance (0.25) is also relatively high for the Shapiro-Wilks test (0.05 being the typical threshold).&lt;br /&gt;&lt;br /&gt;Next, &lt;strong&gt;Exponential distribution&lt;/strong&gt;. For the above dataset, lambda - i.e. the rate of arrival - is provided (Note that lambda is NOT simply 1/mean(num3), it is 1/E(x) and we don&#39;t know how the expected value was computed)&lt;pre&gt;declare&lt;br /&gt;  lambda number;&lt;br /&gt;  mu     number;&lt;br /&gt;  sig    number;&lt;br /&gt;begin&lt;br /&gt; lambda := 0.3194;&lt;br /&gt; -- select 1/mean into lambda from (select mean(num2) from disttab);&lt;br /&gt; mu     := NULL;&lt;br /&gt; sig    := NULL;&lt;br /&gt; dbms_output.put_line(&#39;EXPONENTIAL DISTRIBUTION - KOLMOGOROV_SMIRNOV&#39;);&lt;br /&gt; dbms_stat_funcs.exponential_dist_fit(&lt;br /&gt;  &#39;dmuser&#39;, &#39;disttab&#39;, &#39;num3&#39;, &#39;KOLMOGOROV_SMIRNOV&#39;, lambda, mu, sig);&lt;br /&gt; dbms_output.put_line(&#39;Lambda  : &#39; || lambda);&lt;br /&gt; dbms_output.put_line(&#39;Mu      : &#39; || mu);&lt;br /&gt; dbms_output.put_line(&#39;Sig     : &#39; || to_char(sig,&#39;9.9999&#39;));&lt;br /&gt;end;&lt;br /&gt;/&lt;/pre&gt;The output shows:&lt;br /&gt;EXPONENTIAL DISTRIBUTION - KOLMOGOROV_SMIRNOV&lt;br /&gt;D value : .0919745379005003387429254774811052604723&lt;br /&gt;Lambda  : .3194&lt;br /&gt;Mu      : 0&lt;br /&gt;Sig     :   .9237466160&lt;br /&gt;The low D value (0.09) and high significance (0.92) suggests that the data fits an exponential distribution well.&lt;br /&gt;&lt;br /&gt;Next, &lt;strong&gt;Weibull Distribution&lt;/strong&gt;. The alpha input parameter to the procedure corresponds to &lt;em&gt;&amp;#951;&lt;/em&gt; - the scale, and the mu to &lt;em&gt;&amp;#947;&lt;/em&gt; - the location - in the &lt;a href=&quot;http://www.weibull.com/LifeDataWeb/weibull_probability_density_function.htm&quot;&gt;Weibull probability density function&lt;/a&gt; discussed earlier.&lt;pre&gt;declare&lt;br /&gt;  alpha  number;&lt;br /&gt;  beta   number;&lt;br /&gt;begin&lt;br /&gt; alpha := 3;&lt;br /&gt; mu    := 0;&lt;br /&gt; beta  := 4; &lt;br /&gt; sig   := NULL;&lt;br /&gt; dbms_output.put_line(&#39;.&#39;);&lt;br /&gt; dbms_output.put_line(&#39;WEIBULL DISTRIBUTION - KOLMOGOROV_SMIRNOV&#39;);&lt;br /&gt; dbms_stat_funcs.weibull_dist_fit(&lt;br /&gt;  &#39;dmuser&#39;, &#39;disttab&#39;, &#39;num3&#39;, &#39;KOLMOGOROV_SMIRNOV&#39;, alpha, mu, beta, sig);&lt;br /&gt; dbms_output.put_line(&#39;Alpha   : &#39; || alpha);&lt;br /&gt; dbms_output.put_line(&#39;Mu      : &#39; || mu);&lt;br /&gt; dbms_output.put_line(&#39;Beta    : &#39; || beta);&lt;br /&gt; dbms_output.put_line(&#39;Sig     : &#39; || to_char(sig,&#39;9.9999&#39;));&lt;br /&gt;end;&lt;br /&gt;/&lt;/pre&gt;The output shows:&lt;br /&gt;WEIBULL DISTRIBUTION - KOLMOGOROV_SMIRNOV&lt;br /&gt;D value : .2575286246007637604103723582952313687414&lt;br /&gt;Alpha   : 3&lt;br /&gt;Mu      : 0&lt;br /&gt;Beta    : 4&lt;br /&gt;Sig     :   .0177026134&lt;br /&gt;The Kolmogorov-Smirnov test does not appear emphatic enough, we will try other tests later.&lt;br /&gt;&lt;br /&gt;Next, &lt;strong&gt;Uniform Distribution&lt;/strong&gt;.&lt;pre&gt;declare&lt;br /&gt;  A      number;&lt;br /&gt;  B      number;&lt;br /&gt;begin&lt;br /&gt; A   := 1;&lt;br /&gt; B   := 34;&lt;br /&gt; sig := NULL;&lt;br /&gt; dbms_output.put_line(&#39;.&#39;);&lt;br /&gt; dbms_output.put_line(&#39;UNIFORM DISTRIBUTION - KOLMOGOROV_SMIRNOV&#39;);&lt;br /&gt; dbms_stat_funcs.uniform_dist_fit(&lt;br /&gt;  &#39;dmuser&#39;, &#39;disttab&#39;, &#39;num4&#39;, &#39;CONTINUOUS&#39;, &#39;KOLMOGOROV_SMIRNOV&#39;, A, B, sig);&lt;br /&gt; dbms_output.put_line(&#39;A    : &#39; || A);&lt;br /&gt; dbms_output.put_line(&#39;B    : &#39; || B);&lt;br /&gt; dbms_output.put_line(&#39;Sig     : &#39; || to_char(sig,&#39;9.9999&#39;));&lt;br /&gt;end;&lt;br /&gt;/&lt;/pre&gt;The output shows:&lt;br /&gt;UNIFORM DISTRIBUTION - KOLMOGOROV_SMIRNOV&lt;br /&gt;D value : .2083979233511586452762923351158645276292&lt;br /&gt;A    : 1&lt;br /&gt;B    : 34&lt;br /&gt;Sig     :   .0904912415&lt;br /&gt;The Kolmogorov-Smirnov test does not appear emphatic enough, we will try other tests later.&lt;br /&gt;&lt;br /&gt;Finally, let us try fitting a small dataset to &lt;strong&gt;Poisson Distribution&lt;/strong&gt;.&lt;pre&gt;create table pdisttab (num1 number);&lt;br /&gt;insert into pdisttab values(1);&lt;br /&gt;insert into pdisttab values(2);&lt;br /&gt;insert into pdisttab values(3);&lt;br /&gt;insert into pdisttab values(4);&lt;br /&gt;insert into pdisttab values(5);&lt;br /&gt;declare&lt;br /&gt;  mean   number;&lt;br /&gt;  stdev  number;&lt;br /&gt;  sig    number;&lt;br /&gt;begin&lt;br /&gt; mean  := 3.0;&lt;br /&gt; stdev := 1.58114;&lt;br /&gt; dbms_output.put_line(&#39;.&#39;);&lt;br /&gt; dbms_output.put_line(&#39;POISSON DISTRIBUTION - KOLMOGOROV_SMIRNOV&#39;);&lt;br /&gt; dbms_stat_funcs.poisson_dist_fit(&lt;br /&gt;  &#39;dmuser&#39;, &#39;pdisttab&#39;, &#39;num1&#39;, &#39;KOLMOGOROV_SMIRNOV&#39;, mean, sig);&lt;br /&gt; dbms_output.put_line(&#39;Mean    : &#39; || mean);&lt;br /&gt; dbms_output.put_line(&#39;Stddev  : &#39; || stdev);&lt;br /&gt; dbms_output.put_line(&#39;Sig     : &#39; || to_char(sig,&#39;9.9999&#39;));&lt;br /&gt;end;&lt;br /&gt;/&lt;/pre&gt;The output of:&lt;br /&gt;POISSON DISTRIBUTION - KOLMOGOROV_SMIRNOV&lt;br /&gt;D value : .08391793845975204&lt;br /&gt;Mean    : 3&lt;br /&gt;Stddev  : 1.58114&lt;br /&gt;Sig     :   .9999999999&lt;br /&gt;emphatically is in agreement with the null hypothesis that the data fits a Poisson distribution.&lt;br /&gt;&lt;br /&gt;That was fun, was&#39;n&#39;t it? Now, we have introduced several new terms and concepts here (esp if you reviewed the DBMS_STAT_FUNCS docs) - viz. &lt;em&gt;goodness-of-fit testing&lt;/em&gt; if a given data sample &lt;em&gt;fits&lt;/em&gt; a particular distribution based on a &lt;em&gt;null hypothesis&lt;/em&gt;, using various &lt;em&gt;test types&lt;/em&gt;, the test metrics, and the &lt;em&gt;significance&lt;/em&gt; output of a test, and various other parameters. In the upcoming posts, we will try to understand these new concepts. I also presume that the various references in the &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/09/st004-inferential-statistics-4.html&quot;&gt;previous post&lt;/a&gt; and this one may have been useful to experienced/intermediate statisticians also.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/7470536563606059942/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/7470536563606059942?isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/7470536563606059942'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/7470536563606059942'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/10/analyzing-your-data-for-distributions.html' title='Analyzing your data for Distributions'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-2040581038507070088</id><published>2007-09-21T23:28:00.000-04:00</published><updated>2007-12-14T13:49:35.303-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Continuous Probability Distributions</title><content type='html'>&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6mD358VZAl_sZyQ_DIo-cHh53Me0YpJwlOBQYqapDVbRHOGNo1pNRMm5OPuIZfPCfZ8zifPiBuZZ8wKv6aKQ_nCkIpw3_5fQkxX9vFrWORNhuSL3NA6-dZbWQ2153HlFX3YAlgw3VOyfO/s1600-h/cont.png&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6mD358VZAl_sZyQ_DIo-cHh53Me0YpJwlOBQYqapDVbRHOGNo1pNRMm5OPuIZfPCfZ8zifPiBuZZ8wKv6aKQ_nCkIpw3_5fQkxX9vFrWORNhuSL3NA6-dZbWQ2153HlFX3YAlgw3VOyfO/s320/cont.png&quot; border=&quot;0&quot; alt=&quot;&quot;id=&quot;BLOGGER_PHOTO_ID_5118021061487389794&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;strong&gt;Continuous Probability Distributions&lt;/strong&gt;&lt;br /&gt;A &lt;em&gt;continuous probability distribution&lt;/em&gt; is a (infinitely large) table that lists the continuous variables (outcomes) of an experiment with the relative frequency (a.k.a probability) of each outcome. Consider a histogram that plots the probability (y axis) that a particular job will get done within a time interval (x axis). As you keep making the interval shorter and more fine-grained, the step-like top of the histogram eventually melds into a curve - called the continuous probability distribution. The total area under this probability curve is 1, the probability that the value of &lt;em&gt;x&lt;/em&gt; is between two values &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; is the area under &lt;em&gt;f(x)&lt;/em&gt; between &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; and &lt;em&gt;f(x) &lt;= 0&lt;/em&gt; for all &lt;em&gt;x&lt;/em&gt; For continuous distributions, the probability for any single point in the distribution is 0, you can compute a non-zero probability only for an interval between two values of the continuous variable &lt;em&gt;x&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;Oracle SQL provides statistical functions to determine if the values in a given column fit a particular distribution. Before we proceed to the examples, let us look at some of the popularly known distributions.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Normal (Gaussian) Probability Distribution&lt;/strong&gt;&lt;br /&gt;The most common continuous probability distribution - to the point of being synonymous with the concept is &lt;a href=&quot;http://en.wikipedia.org/wiki/Normal_distribution&quot;&gt;Normal Probability Distribution&lt;/a&gt;, represented graphically by a bell curve, plotted with the continuous value on the x axis, and the probability along the y axis, that is symmetric about the mean x value, with the two ends tapering off to infinity. The curve has these properties: &lt;ul&gt;&lt;li&gt;The mean, median and mode are the same&lt;/li&gt;&lt;li&gt;the distribution is bell-shaped and symmetrical about the mean&lt;/li&gt;&lt;li&gt;the area under this curve is always = 1&lt;/li&gt;&lt;/ul&gt;The &lt;em&gt;generic&lt;/em&gt; normal distribution  can have any mean value and standard deviation. For example, weather info may indicate an annual average rainfall in Boston of 38 inches with standard deviation 3 inches. The smaller the standard deviation (say, 2 inches instead of 3), the steeper the bell curve about the mean. Now if the mean were to shift to, say 40, the symmetric bell curve will shift two places to the right too. The &lt;em&gt;probability density function&lt;/em&gt; for normal distribution is given by:&lt;br /&gt;f(x) = 1/(&amp;#963;&amp;#8730;(2&amp;#960;))e&lt;sup&gt;-0.5 * ((x - &amp;#956;)/&amp;#963;)&amp;sup2;&lt;/sup&gt;&lt;br /&gt;&lt;br /&gt;The &lt;strong&gt;Standard Normal Distribution&lt;/strong&gt; is a special case of normal distribution with &amp;#963;=0 and &amp;#956;=1 as shown below (graph not to scale).&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSmkt-aAZ04ob6SchzCBV6EzxqvJramxiVOp2g-CH1MtP_OTCPquPaUvjcRBNoNUf12ve9ZKezQGEA3_cT9UgILJqtFeJDb9HUh5wDEYlGpvP_nfg47seON0N4IJDFEd4PKzihZ8RXcBOA/s1600-h/stdnormal.png&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSmkt-aAZ04ob6SchzCBV6EzxqvJramxiVOp2g-CH1MtP_OTCPquPaUvjcRBNoNUf12ve9ZKezQGEA3_cT9UgILJqtFeJDb9HUh5wDEYlGpvP_nfg47seON0N4IJDFEd4PKzihZ8RXcBOA/s320/stdnormal.png&quot; border=&quot;0&quot; alt=&quot;&quot;id=&quot;BLOGGER_PHOTO_ID_5118380064918760562&quot; /&gt;&lt;/a&gt;The &lt;em&gt;&lt;strong&gt;standard z-score&lt;/strong&gt;&lt;/em&gt; is a derivative of the standard normal distribution. It is given by &lt;em&gt;z = (x - &amp;#956;)/&amp;#963;&lt;/em&gt;. The value of &lt;em&gt;z&lt;/em&gt; is then cross-checked against a &lt;em&gt;standard normal table&lt;/em&gt; or grid, to arrive at the probability of a required interval - repeat &lt;em&gt;interval&lt;/em&gt;. Unlike discrete random variables in a discrete probability distribution, continuous variables can have infinite values for a given event - so the probability can be computed only for an interval or range of values. Continuing with the rainfall example, queried the probability that the annual rainfall next year at Boston will be &lt;= 40.5 inches - we will compute z = (40.5 - 38)/3 = 0.8333. Stated another way, this means that a rainfall of 40.5 inches is 0.8333 standard deviations away from the mean. From &lt;a href=&quot;http://www.stat.tamu.edu/~mhasson/normal.pdf&quot;&gt;the standard normal table&lt;/a&gt;, the probability is 0.7967 - that is, roughly 80%.&lt;br /&gt;&lt;br /&gt;Microsoft Excel&#39;s NORMDIST() function provides this functionality, but I was surprised to find &lt;u&gt;no function in Oracle SQL with equivalent simplicity&lt;/u&gt; - I&#39;ll file a feature bug after some more research. The &lt;a href=&quot;http://www.oracle.com/technology/products/bi/olap/index.html&quot;&gt;Oracle OLAP Option &lt;/a&gt;provides a NORMAL() function as part of its OLAP DML interface. This Calc-like interface is different from SQL - so we will defer this for later.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Application to Data Mining&lt;/strong&gt; A key use of the &lt;em&gt;z-score&lt;/em&gt; is as a &quot;normalizing&quot; data transformation for mining applications. &lt;u&gt;Note&lt;/u&gt; that this concept is &lt;em&gt;completely unrelated&lt;/em&gt; to &lt;a href=&quot;http://en.wikipedia.org/wiki/Database_normalization&quot;&gt;database normalization&lt;/a&gt;. The stolen car example in a &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/09/st002-inferential-stats-1-probability.html&quot;&gt;previous post&lt;/a&gt; was a simple example of prediction - we used a few &lt;em&gt;categorical&lt;/em&gt; attributes like a car&#39;s color, type to predict if a car will be stolen or not.&lt;br /&gt;&lt;br /&gt;In the business world, the applications are more grown-up and mission-critical. One example is &lt;strong&gt;churn prediction&lt;/strong&gt; - i.e. finding out if a (say, wireless) customer would stay loyal with the current provider, or move on (&quot;churn&quot;) to competitor (in which case, the current provider could try to entice him/her to stay with appropriate promos). The customer data used for such churn prediction applications contains &lt;em&gt;categorical&lt;/em&gt; (e.g. gender, education, occupation) and &lt;em&gt;numerical&lt;/em&gt; (e.g. age, salary, fico score, distance of residence from a metro) attributes/columns in a table. The data in these numeric columns will be widely dispersed, across different scales. For e.g. values within salary can be from 10s of thousands to several millions. Two numerical attributes will be in different scales - example salary (30K - 2 mil) vs age (1-100). Such disparity in scales, if left untreated, can throw most mining algorithms out of whack - the attributes with higher range of values will start outweighing those in the lower range during the computation of prediction. For such algorithms, the numerical data is &lt;em&gt;normalized&lt;/em&gt; to a smaller range [-1, 1] or [0, 1] using the z-transform, to enable uniform handling of numerical data by the algorithm.&lt;br /&gt;&lt;br /&gt;Min-max and decimal scaling are other data normalization techniques. &lt;a href=&quot;http://ir.iit.edu/~nazli/cs422/CS422-Slides/DM-Preprocessing.pdf&quot;&gt;Here is one primer on mining data transformations&lt;/a&gt;. We will discuss mining transformations using DBMS_DATA_MINING_TRANSFORM package and Oracle SQL in a separate post.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Uniform Distribution&lt;/strong&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghs4jgLjRfypzY75oxTQEeAkiQWN4mjYQdJ7FEqrfknlJjfuMaCYJgxfAGJQouonqEzUU8KL3cLbqpZwNpDr2EWi0N2PagUa0Un-UQ74xz9aWGXUjrDMSDLzK8G-9dmdjKsUfFUPK0G-T1/s1600-h/uniform.png&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghs4jgLjRfypzY75oxTQEeAkiQWN4mjYQdJ7FEqrfknlJjfuMaCYJgxfAGJQouonqEzUU8KL3cLbqpZwNpDr2EWi0N2PagUa0Un-UQ74xz9aWGXUjrDMSDLzK8G-9dmdjKsUfFUPK0G-T1/s320/uniform.png&quot; border=&quot;0&quot; alt=&quot;&quot;id=&quot;BLOGGER_PHOTO_ID_5118651811794545794&quot; /&gt;&lt;/a&gt;Ever waited outside a airport terminal under a sign that says &quot;Rental-Cars/Long-term Parking - Pickup Every 10 minutes&quot;? Your wait time is an example of uniform distribution - assuming a well-run airport, you arrive at the stop and expect to wait between 5 to max 15 minutes for your shuttle. This simplest of continuous distributions has the probability function&lt;br /&gt;&lt;em&gt;f(x) = 1/ (b - a) a &lt;= x &lt;= b, f(x) = 0 for all other values of x&lt;/em&gt;&lt;br /&gt;and is graphically represented as shown. The probability that a uniformly distributed random variable X will have values in the range x&lt;sub&gt;1&lt;/sub&gt; to x&lt;sub&gt;2&lt;/sub&gt; is:&lt;br /&gt;&lt;em&gt;P(x&lt;sub&gt;1&lt;/sub&gt; &lt;= X &lt;= x&lt;sub&gt;2&lt;/sub&gt;) = (x&lt;sub&gt;2&lt;/sub&gt; - x&lt;sub&gt;1&lt;/sub&gt;)/(b - a), a &lt;= x&lt;sub&gt;1&lt;/sub&gt; &lt; x&lt;sub&gt;2&lt;/sub&gt; &lt;= b&lt;/em&gt;.&lt;br /&gt;The mean &lt;em&gt;E(X) = (a+b)/2&lt;/em&gt; and variance &lt;em&gt;V(X) = (b - a)&amp;sup2;/12&lt;/em&gt;.&lt;br /&gt;To use the shuttle bus example, probability that the wait time will be 8 to 11 minutes is&lt;br /&gt;P(8 &lt;= X &lt;= 11) = (11 - 8)/(15 - 10) = 3/5 = 0.6&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Exponential Distribution&lt;/strong&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn-IDPVWjmtNcTySidBL6OZf7e27N3P62XrkPxHzZP4wxhhd56KelFr-aQysYk15SLIqRzK9aOuLzEuGCcjD5xTA0YSe7Wew4uwAsBqIV2T7ChPxKR34HeELjbM9LrkWIAK-1wnQCeZ2ZQ/s1600-h/exp.png&quot;&gt;&lt;img style=&quot;float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn-IDPVWjmtNcTySidBL6OZf7e27N3P62XrkPxHzZP4wxhhd56KelFr-aQysYk15SLIqRzK9aOuLzEuGCcjD5xTA0YSe7Wew4uwAsBqIV2T7ChPxKR34HeELjbM9LrkWIAK-1wnQCeZ2ZQ/s320/exp.png&quot; border=&quot;0&quot; alt=&quot;&quot;id=&quot;BLOGGER_PHOTO_ID_5120267587081235602&quot; /&gt;&lt;/a&gt; Consider that an event occurs with an average frequency (a.k.a. &lt;em&gt;rate&lt;/em&gt;) of &amp;#955; and this average frequency is constant. Consider that, from a given point in time, you wait for the event to occur. This &lt;em&gt;waiting time&lt;/em&gt; follows an &lt;em&gt;exponential distribution&lt;/em&gt; - depicted in the adjoining figure. The probability density function is given by: &lt;em&gt;f(x) = &amp;#955; e&lt;sup&gt;-&amp;#955;x&lt;/sup&gt;&lt;/em&gt; where &lt;em&gt;&amp;#955;&lt;/em&gt; is the frequency with which the event occurs - expressed as a particular number of times per time unit. The &lt;em&gt;mean&lt;/em&gt;, or more appropriately, the &lt;em&gt;expected value E(X)&lt;/em&gt; of the distribution is &lt;em&gt;&amp;#956; = 1/&amp;#955;&lt;/em&gt;, the &lt;em&gt;variance&lt;/em&gt; is &lt;em&gt;&amp;#963;&amp;sup2; = (1/&amp;#955;)&amp;sup2;&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;Take the same shuttle bus example. If the bus does not stick to any schedule and randomly goes about its business of picking up passengers, then the wait time is exponentially distributed. This sounds a bit weird, but there are several temporal phenomena in nature that exhibit such behavior:&lt;ul&gt;&lt;li&gt;The time between failure of the ordinary light bulb (which typically just blows out suddenly), or some electronic component, follows an exponential distribution. The &lt;em&gt;mean time between failure&lt;/em&gt;, &lt;em&gt;&amp;#956;&lt;/em&gt; is an important metric in the parts failure/warranty claims domain&lt;/li&gt;&lt;li&gt;The time between arrivals, i.e. &lt;em&gt;inter-arrival time&lt;/em&gt; of customers at any check-in counter is exponentially distributed.&lt;/li&gt;&lt;/ul&gt; A key property of an exponentially distributed phenomenon is that it is &lt;em&gt;memory-less&lt;/em&gt; - best explained with an example. Suppose you buy a 4-pack GE light at Walmart with a MTBF of 7000 hours (~ 10 months). Assume a bulb blows out, you plug in a new one, the time to next failure of this bulb will remain exponentially distributed.  Say, this second bulb fails, and you change the bulb a month (24x30=720 hours) later, the time to next failure will remain exponentially distributed. The time between failure is independent of &lt;em&gt;when&lt;/em&gt; the bulb failed and when (i.e. the passage of time before) it was replaced.&lt;br /&gt;&lt;br /&gt;The probability functions are best stated in terms of failure (survival). The probability that an item will survive until &lt;em&gt;x&lt;/em&gt; units of time, given a MTBF of &lt;em&gt;&amp;#956;&lt;/em&gt; units can be stated as:&lt;br /&gt;&lt;em&gt;P(X &gt;= x) = e&lt;sup&gt;-&amp;#955;x&lt;/sup&gt; x &gt;= 0&lt;/em&gt;&lt;br /&gt;and conversely, failing before &lt;em&gt;x&lt;/em&gt; units of time is given by&lt;br /&gt;&lt;em&gt;P(X &lt;= x) = 1 - e&lt;sup&gt;-&amp;#955;x&lt;/sup&gt; x &gt;= 0&lt;/em&gt;&lt;br /&gt;where &lt;em&gt;&amp;#955; = 1/&amp;#956;&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;For example - if Dell claims your laptop fails following an exponential distribution with MTBF 60 months, and the warranty period is 90 days (3 months), what percentage of laptops does Dell expect to fail within the warranty period?&lt;br /&gt;P(X &lt;= 3 months) = 1 - e&lt;sup&gt;-(1/60)*3)&lt;/sup&gt; = 0.048 ~ 5% of laptops.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Weibull Distribution&lt;/strong&gt;&lt;br /&gt;&lt;a href=&quot;http://www.weibull.com/LifeDataWeb/weibull_probability_density_function.htm&quot;&gt;Weibull distribution&lt;/a&gt; is a versatile distribution that can emulate other distributions based on its parameter settings, and is a widely used, important tool for reliability engineering/&lt;a href=&quot;http://en.wikipedia.org/wiki/Survival_analysis&quot;&gt;survival analysis&lt;/a&gt;. An extensive coverage on Reliability analysis is provided &lt;a href=&quot;http://www.weibull.com/&quot;&gt;here&lt;/a&gt;. I am mentioning this distribution here mainly to set up the next post. There are &lt;a href=&quot;http://en.wikipedia.org/wiki/Probability_distribution&quot;&gt;several other popular probability distributions&lt;/a&gt; - we will revisit them in the future on a needs-basis.&lt;br /&gt;&lt;br /&gt;For now, let us break off and look at some Oracle code in the &lt;a href=&quot;http://numoraclerecipes.blogspot.com/2007/10/analyzing-your-data-for-distributions.html&quot;&gt;next pos&lt;/a&gt;t.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/2040581038507070088/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/2040581038507070088?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/2040581038507070088'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/2040581038507070088'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/09/st004-inferential-statistics-4.html' title='Continuous Probability Distributions'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6mD358VZAl_sZyQ_DIo-cHh53Me0YpJwlOBQYqapDVbRHOGNo1pNRMm5OPuIZfPCfZ8zifPiBuZZ8wKv6aKQ_nCkIpw3_5fQkxX9vFrWORNhuSL3NA6-dZbWQ2153HlFX3YAlgw3VOyfO/s72-c/cont.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-7329718038733603792</id><published>2007-09-21T14:29:00.001-04:00</published><updated>2008-01-04T15:13:38.033-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Code-Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Discrete Probability Distributions</title><content type='html'>A &lt;b&gt;Probability Distribution&lt;/b&gt; is a table/graph that depicts the assignment of probabilities to the assumption of specific values by a given random variable.&lt;br /&gt;&lt;br /&gt;The following concepts are useful to understand probability distributions:&lt;ul&gt;&lt;li&gt;If Event A can occur in &lt;em&gt;p&lt;/em&gt; possible ways and Event B can occur in &lt;em&gt;q&lt;/em&gt; possible ways, then both A and B can occur in &lt;em&gt;p&lt;/em&gt; x &lt;em&gt;q&lt;/em&gt; ways.&lt;/li&gt;&lt;li&gt;The number of different ways that a set of objects can be arranged is called &lt;em&gt;Combination&lt;/em&gt;. The number of combinations of &lt;em&gt;n&lt;/em&gt; objects taken &lt;em&gt;r &lt;/em&gt;at a time is given by &lt;em&gt;nCr = n! / (n - r)! r!&lt;/em&gt;&lt;/li&gt;&lt;li&gt;The number of different ways that a set of objects can be arranged in order is called &lt;em&gt;Permutation&lt;/em&gt;. The number of permutations of &lt;em&gt;n&lt;/em&gt; objects taken &lt;em&gt;r&lt;/em&gt; at a time is given by&lt;br /&gt;&lt;em&gt;nPr = n! / (n - r)!&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt;Here is a PL/SQL code snippet to compute factorial:&lt;pre&gt;FUNCTION factorial(p_n IN NUMBER) RETURN NUMBER IS&lt;br /&gt;BEGIN&lt;br /&gt; IF p_n IS NULL OR p_n &lt; 0 THEN&lt;br /&gt;  RAISE_APPLICATION_ERROR(-20000, &#39;Invalid Input Value&#39;);&lt;br /&gt; ELSIF p_n &lt;= 1 THEN&lt;br /&gt;  RETURN 1;&lt;br /&gt; ELSE&lt;br /&gt;  RETURN factorial(p_n-1) * p_n;&lt;br /&gt; END IF;&lt;br /&gt;END;&lt;/pre&gt;EX&gt; Compute 9!&lt;pre&gt;select factorial(9) from dual;&lt;/pre&gt;I was curious to see how far I can push this function - the maximum value of &lt;em&gt;n&lt;/em&gt; was 83.7 with NUMBER types, and 84.7 when I changed the input parameter and return type to BINARY_DOUBLE&lt;pre&gt;SQL&gt; select factorial(83.7) from dual;&lt;br /&gt;FACTORIAL(83.7)&lt;br /&gt;---------------&lt;br /&gt;     9.642E+125&lt;br /&gt;SQL&gt; select factorial(83.71) from dual;&lt;br /&gt;FACTORIAL(83.71)&lt;br /&gt;---------------&lt;br /&gt;              ~&lt;br /&gt;SQL&gt; select factorial2(84.7) from dual;&lt;br /&gt;FACTORIAL2(84.7)&lt;br /&gt;----------------&lt;br /&gt;      8.167E+127&lt;br /&gt;SQL&gt; select factorial2(84.71) from dual;&lt;br /&gt;FACTORIAL2(84.71)&lt;br /&gt;-----------------&lt;br /&gt;               Inf&lt;/pre&gt; EX&gt; Compute the number of combinations of 9 objects taken 3 at a time.&lt;pre&gt;select factorial(9)/(factorial(9-3) * factorial(3)) from dual;&lt;/pre&gt;EX&gt; Compute the number of different ways of arranging 9 objects taken 3 at a time.&lt;pre&gt;select factorial(9)/factorial(9-3) from dual;&lt;/pre&gt;&lt;strong&gt;Discrete Probability Distributions&lt;/strong&gt;&lt;ul&gt;&lt;li&gt;The &lt;em&gt;discrete probability distribution&lt;/em&gt; is a table that lists the discrete variables (outcomes) of an experiment with the relative frequency (a k a probability) of each outcome.&lt;br /&gt;Example: Tossing a coin two times gives you the combinations (H,H), (H,T), (T,H), (T,T) and hence, the following tuples for (#Heads, Frequency, Relative_Frequency):&lt;br /&gt;(0, 1, 1/4=0.25), (1, 2, 2/4=0.5), (2, 1, 1/4=0.25).&lt;br /&gt;This is the probability distribution for # heads after flipping a coin twice.&lt;/li&gt;&lt;li&gt;&lt;em&gt;Mean&lt;/em&gt; or &lt;em&gt;Expected value&lt;/em&gt; of the discrete probability distribution &lt;em&gt;μ&lt;/em&gt; = ∑&lt;sub&gt;i=1_to_n&lt;/sub&gt; &lt;em&gt;x&lt;sub&gt;i&lt;/sub&gt; * P(x&lt;sub&gt;i&lt;/sub&gt;)&lt;/em&gt;  For the coin example, &lt;em&gt;μ&lt;/em&gt; = 0 * 0.25 + 1 * 0.5 + 2 * 0.25 = 1&lt;/li&gt;&lt;li&gt;&lt;em&gt;Variance&lt;/em&gt; of the discrete probability distribution &lt;em&gt;σ²&lt;/em&gt; = ∑&lt;sub&gt;i=1_to_n&lt;/sub&gt; &lt;em&gt;(x&lt;sub&gt;i&lt;/sub&gt; - μ)² * P(X&lt;sub&gt;i&lt;/sub&gt;)&lt;/em&gt;&lt;/li&gt;&lt;li&gt;&lt;em&gt;Standard deviation&lt;/em&gt; is the square root of the variance&lt;/li&gt;&lt;/ul&gt;&lt;strong&gt;&lt;em&gt;Binomial Probability Distribution&lt;br /&gt;&lt;/em&gt;&lt;/strong&gt;A &lt;em&gt;binomial&lt;/em&gt; or &lt;em&gt;Bernoulli&lt;/em&gt; experiment is one which consists of a fixed number of trials, each independent of the other, each with only two possible outcomes, with a fixed probability for success or failure representation in each outcome. The Bernoulli process counts the number of successes over a given number of attempts, or in other words, the random variable for a Binomial distribution is the number of successes over given number of attempts.&lt;ul&gt;&lt;li&gt;The probability of &lt;em&gt;r&lt;/em&gt; successes in &lt;em&gt;n&lt;/em&gt; trials with probability of success &lt;em&gt;p&lt;/em&gt; and probability of failure &lt;em&gt;q&lt;/em&gt; is given by &lt;em&gt;P(r, n) = (n! / (n - r)! r!) p&lt;sup&gt;r&lt;/sup&gt; q&lt;sup&gt;(n - r)&lt;/sup&gt;&lt;/em&gt;&lt;/li&gt;&lt;li&gt;The binomial probability distribution is a table of (r, P(r, n)) which can be subsequently graphed, as discussed in this example&lt;/li&gt;&lt;/ul&gt;EX&gt; Over the next 7 days, assume a 40% chance of rain and 60% chance of no rain. The probability that it will rain exactly 2 days over the next 7 days is P(2, 7) = (7! / (7 - 2)! 2!) 0.4&lt;sup&gt;2&lt;/sup&gt; 0.6&lt;sup&gt;(7 - 2)&lt;/sup&gt;, which can be computed using&lt;pre&gt;select factorial(7) * power(0.4,2) * power(0.6,(7-2))/&lt;br /&gt;       (factorial(7-2) * factorial(2)) p_2_7&lt;br /&gt;  from dual;&lt;/pre&gt;The probability that it will rain &lt;em&gt;at least&lt;/em&gt; 6 days over the next 7 days is P(r &gt;= 6) = P(6,7)+P(7,7), computed using&lt;pre&gt;select (factorial(7) * power(0.4,6) * power(0.6,(7-6))/&lt;br /&gt;       (factorial(7-6) * factorial(6))) +&lt;br /&gt;       (factorial(7) * power(0.4,7) * power(0.6,(7-7))/&lt;br /&gt;       (factorial(7-7) * factorial(7))) p_r_ge_6&lt;br /&gt;  from dual;&lt;/pre&gt;Finally, the probability that it will rain no more than 2 days over the next 7 days is P(r &lt;= 2) = P(0,7) + P(1,7) + P(2,7)&lt;ul&gt;&lt;li&gt;The &lt;em&gt;mean&lt;/em&gt; of a binomial distribution is &lt;em&gt;μ = np&lt;/em&gt;&lt;/li&gt;&lt;li&gt;The &lt;em&gt;standard deviation&lt;/em&gt; is &lt;em&gt;σ² = npq&lt;/em&gt;&lt;/li&gt;&lt;/ul&gt; Excel has a function &lt;em&gt;BINOMDIST(r, n, p, cumulative)&lt;/em&gt;. p is the probability of success, set cumulative=TRUE if you want the probability of r or fewer successes, set cumulative=FALSE if you want exactly r successes. Here is the PL/SQL version:&lt;pre&gt;FUNCTION binomdist(r NUMBER, n NUMBER, p NUMBER, cumulative BOOLEAN DEFAULT FALSE) RETURN NUMBER IS&lt;br /&gt; ri  NUMBER;&lt;br /&gt; ret NUMBER;&lt;br /&gt; fn  NUMBER;&lt;/br&gt;&lt;br /&gt;BEGIN&lt;br /&gt; ret := 0;&lt;br /&gt; fn := factorial(n);&lt;br /&gt; FOR ri IN REVERSE 0..r LOOP&lt;br /&gt;  ret := ret + (fn * power(p, ri) * power((1-p),(n - ri)))/&lt;br /&gt;               (factorial(n - ri) * factorial(ri));&lt;br /&gt;  IF NOT cumulative THEN&lt;br /&gt;   EXIT;&lt;br /&gt;  END IF;&lt;br /&gt; END LOOP;&lt;br /&gt; RETURN ret;&lt;br /&gt;END binomdist;&lt;/pre&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Poisson Probability Distribution&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt;The random variable for Poission distribution is the number of occurrences of the event over a measurable metric (time, space). In a Poisson process, the (measured) &lt;em&gt;mean&lt;/em&gt; number of occurences of an event is the same for each interval of measurement, and the number of occurrences in a particular interval are independent of number of occurrences in other intervals.&lt;/p&gt;&lt;ul&gt;&lt;li&gt;The probability of exactly &lt;em&gt;r&lt;/em&gt; occurrences over a given interval is given by &lt;em&gt;P(r) = μ&lt;sup&gt;r&lt;/sup&gt; * e&lt;sup&gt;(-μ)&lt;/sup&gt;/ r!&lt;/em&gt;&lt;/li&gt;&lt;li&gt;The &lt;em&gt;variance&lt;/em&gt; of the Poisson distribution is the same as the (observed) mean.&lt;/li&gt;&lt;li&gt;A &lt;em&gt;goodness of fit&lt;/em&gt; test helps verify if a given dataset fits the Poisson distribution&lt;/li&gt;&lt;/ul&gt;A simple example of a Poisson process is customer arrival at your favorite coffee shop. Assume that you know that an average of 25 customers walk into a Dunkin Donuts every hour, then the likelihood of exactly 31 customers walking into the customer in the next hour is&lt;pre&gt;select power(25,31) * exp(-25)/factorial(25) p_31&lt;br /&gt;  from dual;&lt;/pre&gt;Just as we saw in Binomial distribution, the probability that no more than 31 customers will walk into the coffee shop is P(r &lt;= 31) = P(0)+P(1)+..+P(31). Inversely, the probability that &lt;em&gt;at least&lt;/em&gt; 31 customers will walk into the coffee shop is P(r &gt;= 31) = 1 - P(r &lt; 31). Obviously, this leads up to the need for a function similar to POISSON(r, μ, cumulative) in Excel - where cumulative = FALSE indicates computation of exactly r occurrences, and cumulative = TRUE indicates r or fewer.&lt;pre&gt;FUNCTION poissondist(r NUMBER, mu NUMBER,&lt;br /&gt;                   cumulative BOOLEAN DEFAULT FALSE) RETURN NUMBER IS&lt;br /&gt; ri  NUMBER;&lt;br /&gt; ret NUMBER;&lt;br /&gt;BEGIN&lt;br /&gt; ret := 0;&lt;br /&gt; FOR ri IN REVERSE 0..r LOOP&lt;br /&gt;  ret := ret + (power(p, ri) * exp(-mu)/factorial(ri));&lt;br /&gt;  IF NOT cumulative THEN&lt;br /&gt;   EXIT;&lt;br /&gt;  END IF;&lt;br /&gt; END LOOP;&lt;br /&gt; RETURN ret;&lt;br /&gt;END poissondist;&lt;/pre&gt;&lt;p&gt;&lt;em&gt;Poisson approximation&lt;/em&gt; - a Poisson distribution can be used to approximate a Binomial distribution if the number of trials (in the binomial experiment) is &gt;= 20 and the probability of success &lt;em&gt;p&lt;/em&gt; is &lt;= 5%.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/7329718038733603792/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/7329718038733603792?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/7329718038733603792'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/7329718038733603792'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/09/st002-probability-distributions.html' title='Discrete Probability Distributions'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-1006439154827759594</id><published>2007-09-02T11:56:00.000-04:00</published><updated>2008-01-04T15:13:38.033-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Code-Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Data-Mining"/><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Random Variables, Probability, Bayes Theorem, Naive Bayes Models</title><content type='html'>In contrast to descriptive statistics, &lt;strong&gt;Inferential statistics&lt;/strong&gt; describes the &lt;em&gt;population&lt;/em&gt; based on information gleaned from a &lt;em&gt;sample&lt;/em&gt; taken from the population. Fundamental to understanding statistical inference is the concept of probability.&lt;br /&gt;&lt;br /&gt;An &lt;em&gt;experiment&lt;/em&gt; is the process of measuring/observing an activity. An &lt;em&gt;outcome&lt;/em&gt; is a particular result of the experiment - outcomes are also called &lt;b&gt;Random Variables&lt;/b&gt;. Random variables can be &lt;b&gt;discrete&lt;/b&gt; - when it can assume a countable number of values (e.g. one of six outcomes from rolling a dice) or &lt;b&gt;Continuous&lt;/b&gt; - when the variable can assume uncountably infinite values in a given range of values (time, a person&#39;s height). The &lt;b&gt;Sample space&lt;/b&gt; is all possible outcomes of the experiment. An &lt;b&gt;event&lt;/b&gt; is an outcome of interest.&lt;br /&gt;&lt;br /&gt;The &lt;strong&gt;Probability&lt;/strong&gt; of Event A occurring is: P(A) = # of possible outcomes in which Event A occurs/ Total # outcomes in the sample space.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Basic properties of probability:&lt;/strong&gt;&lt;ul&gt;&lt;li&gt;P(A) = 1 implies Event A will occur with certainty&lt;/li&gt;&lt;li&gt;P(A) = 0 implies Event A will not occur with certainty&lt;/li&gt;&lt;li&gt;0 &gt;= P(A) &gt;= 1&lt;/li&gt;&lt;li&gt;The sum of all probabilities for events in the sample space must be 1&lt;/li&gt;&lt;li&gt;All outcomes in the sample space that are not part of Event A is called the &lt;em&gt;complement&lt;/em&gt; of Event A (named A&#39;). P(A&#39;) = 1 - P(A)&lt;/li&gt;&lt;li&gt;Given two events A and B, P(A) or P(B) - i.e. probabilities of each of the events occuring - without the knowledge of the other events occurrence - is called the &lt;em&gt;prior probability&lt;/em&gt;.&lt;/li&gt;&lt;li&gt;Given two events A and B, the probability of event A occurring given that event B has occurred - denoted by P(A / B) - is called the &lt;em&gt;conditional probability&lt;/em&gt; or &lt;em&gt;posterior&lt;/em&gt; &lt;em&gt;probability &lt;/em&gt;of Event A given that Event B has occurred. On the flip side, if P(A / B) = P(A), then events A and B are termed &lt;em&gt;independent&lt;/em&gt;.&lt;/li&gt;&lt;li&gt;Given two events A and B, the probability of both A and B occurring at the same time is called the &lt;em&gt;joint probability&lt;/em&gt; for A and B, computed as P(A and B) = P(A) * P(B)&lt;/li&gt;&lt;li&gt;Given two events A and B, the probability of either A or B occurring is called the &lt;em&gt;union&lt;/em&gt; of events A and B. If events A and B do not occur at the same time (i.e. are &lt;em&gt;mutually &lt;/em&gt;&lt;em&gt;exclusive&lt;/em&gt;), then P(A or B) = P(A) + P(B). If events A and B occur at the same time, i.e. are not mutually exclusive, then P(A or B) = P(A) + P(B) - P(A and B)&lt;/li&gt;&lt;li&gt;Law of Total Probability: P(A) = P(A / B)P(B) + P(A / B&#39;)P(B&#39;)&lt;/li&gt;&lt;li&gt;The &lt;em&gt;Bayes Theorem&lt;/em&gt; for probabilities provides the ability to reverse the conditionality of events and compute the outcome:&lt;br /&gt;P(A / B) = P(A) * P(B / A) / (P(A) * P(B / A) + P(A&#39;) * P(B / A&#39;))&lt;/li&gt;&lt;/ul&gt;Note that the act of finding the probability for given event is tantamount to &lt;em&gt;predicting that a given event will occur with a given level of certainty or chance&lt;/em&gt; - quantified by the probability. This is a good segue to look at a real &lt;em&gt;business&lt;/em&gt; problem and its solution based on Bayes theorem.&lt;br /&gt;&lt;br /&gt;A modern, &lt;em&gt;predictive&lt;/em&gt;, loan processing application builds analytical models based on millions of historical loan applicant records (&lt;em&gt;training&lt;/em&gt; data), and uses these models to &lt;em&gt;predict&lt;/em&gt; the credit-worthiness (a k a risk of loan default) of an applicant by &lt;em&gt;classifying&lt;/em&gt; the applicant into &lt;em&gt;Low, Medium, High&lt;/em&gt; or such risk categories. In data mining lingo, a new applicant record is now &lt;em&gt;scored&lt;/em&gt; based on the model. At the time of this writing (Aug-Sep 2007), the sub-prime lending woes and its effect on US and world markets is the main story. The trillions lost in this mess is fodder for Quant skeptics/detractors, but as a BusinessWeek cover story (&quot;Not So Smart&quot; - Sep 3 2007) explains, the problem was not analytics per se - the problems were with how various managements (mis)used analytics or (mis)understood their data.&lt;br /&gt;&lt;br /&gt;Returning to probability concepts, instead of A and B, the events become A and B&lt;sub&gt;i&lt;/sub&gt;, i=1..n. The event A (or more appropriately for this example, the &lt;em&gt;target variable&lt;/em&gt; &lt;strong&gt;Risk&lt;/strong&gt;) is a dependent variable that assumes one of discrete values (called &lt;em&gt;classes&lt;/em&gt; - &lt;strong&gt;low, medium, high&lt;/strong&gt;) based on &lt;em&gt;predictor&lt;/em&gt; variables B&lt;sub&gt;i&lt;/sub&gt; through B&lt;sub&gt;n&lt;/sub&gt; (age, salary, gender, occupation, and so on). The probability model for this &lt;em&gt;classifier&lt;/em&gt; is P(A / B&lt;sub&gt;1&lt;/sub&gt;,..,B&lt;sub&gt;n&lt;/sub&gt;). We just shifted the language from statistics into the realm of data mining/predictive analytics. The Bayes theorem intrinsically assumes conditional dependence between B&lt;sub&gt;i&lt;/sub&gt; through B&lt;sub&gt;n&lt;/sub&gt;. Now if &lt;em&gt;n&lt;/em&gt; is large, or if each B&lt;sub&gt;i&lt;/sub&gt; takes on a large number of values, computing this model becomes intractable.&lt;br /&gt;&lt;br /&gt;The &lt;strong&gt;Naive Bayes&lt;/strong&gt; probabilistic model greatly simplifies this by making a naive/strong assumption that B&lt;sub&gt;i&lt;/sub&gt; through B&lt;sub&gt;n&lt;/sub&gt; are &lt;em&gt;conditionally independent&lt;/em&gt; - &lt;a href=&quot;http://en.wikipedia.org/wiki/Naive_Bayes_classifier&quot;&gt;the details are provided here&lt;/a&gt;. You can build a Naive Bayes model using the Oracle Data Mining Option, and predict the value for a target variable in new records using SQL Prediction Functions. The following example illustrates the process.&lt;br /&gt;EX&gt; Given a small, synthetic dataset about the attributes of stolen cars, predict if a particular car will be stolen - based on its attributes.&lt;pre&gt;create table stolen_cars(&lt;br /&gt;  id      varchar2(2),&lt;br /&gt;  color   varchar2(10),&lt;br /&gt;  ctype   varchar2(10),&lt;br /&gt;  corigin varchar2(10),&lt;br /&gt;  stolen  varchar2(3));&lt;/pre&gt;Table created.&lt;pre&gt;insert into stolen_cars values (&#39;1&#39;, &#39;Red&#39;,&#39;Sports&#39;,&#39;Domestic&#39;,&#39;yes&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;2&#39;, &#39;Red&#39;,&#39;Sports&#39;,&#39;Domestic&#39;,&#39;no&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;3&#39;, &#39;Red&#39;,&#39;Sports&#39;,&#39;Domestic&#39;,&#39;yes&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;4&#39;, &#39;Yellow&#39;,&#39;Sports&#39;,&#39;Domestic&#39;,&#39;no&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;5&#39;, &#39;Yellow&#39;,&#39;Sports&#39;,&#39;Imported&#39;,&#39;yes&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;6&#39;, &#39;Yellow&#39;,&#39;SUV&#39;,&#39;Imported&#39;,&#39;no&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;7&#39;, &#39;Yellow&#39;,&#39;SUV&#39;,&#39;Imported&#39;,&#39;yes&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;8&#39;, &#39;Yellow&#39;,&#39;SUV&#39;,&#39;Domestic&#39;,&#39;no&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;9&#39;, &#39;Red&#39;,&#39;SUV&#39;,&#39;Imported&#39;,&#39;no&#39;);&lt;br /&gt;insert into stolen_cars values (&#39;10&#39;, &#39;Red&#39;,&#39;Sports&#39;,&#39;Imported&#39;,&#39;yes&#39;);&lt;br /&gt;commit;&lt;/pre&gt;Commit complete.&lt;pre&gt;begin&lt;br /&gt;  dbms_data_mining.create_model(&lt;br /&gt;    model_name =&gt; &#39;cars&#39;,&lt;br /&gt;    mining_function =&gt; dbms_data_mining.classification,&lt;br /&gt;    data_table_name =&gt; &#39;stolen_cars&#39;,&lt;br /&gt;    case_id_column_name =&gt; &#39;id&#39;,&lt;br /&gt;    target_column_name =&gt; &#39;stolen&#39;);&lt;br /&gt;end;&lt;br /&gt;/&lt;/pre&gt;PL/SQL procedure successfully completed.&lt;pre&gt;create table new_stolen_cars (&lt;br /&gt;  id      varchar2(2),&lt;br /&gt;  color   varchar2(10),&lt;br /&gt;  ctype   varchar2(10),&lt;br /&gt;  corigin varchar2(10));&lt;/pre&gt;Table created.&lt;pre&gt;insert into new_stolen_cars values (&#39;1&#39;, &#39;Red&#39;,&#39;SUV&#39;,&#39;Domestic&#39;);&lt;br /&gt;insert into new_stolen_cars values (&#39;2&#39;, &#39;Yellow&#39;,&#39;SUV&#39;,&#39;Domestic&#39;);&lt;br /&gt;insert into new_stolen_cars values (&#39;3&#39;, &#39;Yellow&#39;,&#39;SUV&#39;,&#39;Imported&#39;);&lt;br /&gt;insert into new_stolen_cars values (&#39;4&#39;, &#39;Yellow&#39;,&#39;Sports&#39;,&#39;Domestic&#39;);&lt;br /&gt;insert into new_stolen_cars values (&#39;5&#39;, &#39;Red&#39;,&#39;Sports&#39;,&#39;Domestic&#39;);&lt;br /&gt;commit;&lt;/pre&gt;Commit complete.&lt;pre&gt;select prediction(cars using *) pred,&lt;br /&gt;       prediction_probability(cars using *) prob&lt;br /&gt;  from new_stolen_cars;&lt;br /&gt;-- Results&lt;br /&gt;PRE   PROB&lt;br /&gt;--- ----------&lt;br /&gt;no    .75&lt;br /&gt;no  .870967746&lt;br /&gt;no    .75&lt;br /&gt;no  .529411793&lt;br /&gt;yes .666666687&lt;/pre&gt;The query scores each row in the new_stolen_cars table, returning the prediction, and the certainty of this predition. This dataset is very small, but a cursory glance at the results indicates that the predictions are correct - based on the training data. For example, the model predicts &#39;No&#39; for a domestic yellow sports car - the training data has no such instance. The model predicts &#39;Yes&#39; for a domestic red sports car, with &gt; 50% certainty - the training data does support this prediction. You can obtain the details of this model using:&lt;pre&gt;select *&lt;br /&gt;  from table(dbms_data_mining.get_model_details_nb(&#39;cars&#39;));&lt;/pre&gt; The SQL output is a collection of objects and may not look pretty at first glance. But once you understand the schema of the output type - viz. &lt;pre&gt;dm_nb_details&lt;/pre&gt; - you can decipher the output to the following simple format:&lt;pre&gt;STOLEN&lt;br /&gt;no&lt;br /&gt;.5&lt;br /&gt;DM_CONDITIONALS(&lt;br /&gt;DM_CONDITIONAL(&#39;COLOR&#39;, NULL, &#39;Red&#39;, NULL, .4),&lt;br /&gt;DM_CONDITIONAL(&#39;COLOR&#39;, NULL, &#39;Yellow&#39;, NULL, .6),&lt;br /&gt;DM_CONDITIONAL(&#39;CTYPE&#39;, NULL, &#39;SUV&#39;, NULL, .6),&lt;br /&gt;DM_CONDITIONAL(&#39;CORIGIN&#39;, NULL, &#39;Domestic&#39;, NULL, .6),&lt;br /&gt;DM_CONDITIONAL(&#39;CORIGIN&#39;, NULL, &#39;Imported&#39;, NULL, .4),&lt;br /&gt;DM_CONDITIONAL(&#39;CTYPE&#39;, NULL, &#39;Sports&#39;, NULL, .4))&lt;br /&gt;&lt;br /&gt;STOLEN&lt;br /&gt;yes&lt;br /&gt;.5&lt;br /&gt;DM_CONDITIONALS(&lt;br /&gt;DM_CONDITIONAL(&#39;COLOR&#39;, NULL, &#39;Red&#39;, NULL, .6),&lt;br /&gt;DM_CONDITIONAL(&#39;CORIGIN&#39;, NULL, &#39;Imported&#39;, NULL, .6),&lt;br /&gt;DM_CONDITIONAL(&#39;CORIGIN&#39;, NULL, &#39;Domestic&#39;, NULL, .4),&lt;br /&gt;DM_CONDITIONAL(&#39;CTYPE&#39;, NULL, &#39;Sports&#39;, NULL, .8),&lt;br /&gt;DM_CONDITIONAL(&#39;CTYPE&#39;, NULL, &#39;SUV&#39;, NULL, .2),&lt;br /&gt;DM_CONDITIONAL(&#39;COLOR&#39;, NULL, &#39;Yellow&#39;, NULL, .4))&lt;/pre&gt;This shows the target variable (STOLEN), its value (&#39;yes&#39;, &#39;no&#39;), the prior probability (0.5), and the conditional probability contributed by each predictor/predictor value pair towards each target/class value.&lt;br /&gt;&lt;br /&gt;Such ability to score transactional customer data directly from the database (in other words, deploy the model right at the source of customer data) with such simplicity is a key Oracle differentiator and competitive advantage over standalone data mining tools. For more on ODM, consult the references provided in this blog.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/1006439154827759594/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/1006439154827759594?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/1006439154827759594'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/1006439154827759594'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/09/st002-inferential-stats-1-probability.html' title='Random Variables, Probability, Bayes Theorem, Naive Bayes Models'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-9057090841324358753</id><published>2007-09-01T21:16:00.000-04:00</published><updated>2008-01-04T15:13:38.033-05:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Code-Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Statistics"/><title type='text'>Descriptive Statistics</title><content type='html'>&lt;span style=&quot;font-style: italic;&quot;&gt;Descriptive&lt;/span&gt; &lt;a href=&quot;http://en.wikipedia.org/wiki/Statistics&quot;&gt;statistics&lt;/a&gt; summarizes and displays information about just the observations at hand - i.e. the sample and population are the same. Using data in the sample schema, we will quickly run through descriptive statistics concepts.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Displaying descriptive statistics&lt;/strong&gt;&lt;br /&gt;&lt;em&gt;Frequency distribution&lt;/em&gt; is a table that organizes a number of values into intervals (classes). A &lt;em&gt;histogram&lt;/em&gt; is the visual equivalent of frequency distribution - a bar graph that represents the number of observations in each class as the height of each bar.&lt;br /&gt;EX&gt; Compute the frequency distribution of all employee salaries - across 10 classes.&lt;pre&gt;select intvl, count(*) freq&lt;br /&gt; from (select width_bucket(salary,&lt;br /&gt;               (select min(salary) from employees),&lt;br /&gt;               (select max(salary)+1 from employees), 10) intvl&lt;br /&gt;         from HR.employees)&lt;br /&gt;group by intvl&lt;br /&gt;order by intvl;&lt;br /&gt;-- Result from this query&lt;br /&gt;INTVL FREQ&lt;br /&gt;----- --------&lt;br /&gt;1     46&lt;br /&gt;2     10&lt;br /&gt;3     23&lt;br /&gt;4     15&lt;br /&gt;5     8&lt;br /&gt;6     2&lt;br /&gt;7     2&lt;br /&gt;10    1&lt;br /&gt;8 rows selected.&lt;/pre&gt;&lt;em&gt;Relative frequency distribution&lt;/em&gt; provides the number of observations in each class as a percentage of the total number of observations.&lt;br /&gt;EX&gt; Compute the relative frequency distribution of all employee salaries - across 10 classes.&lt;pre&gt;with Q_freq_dist as&lt;br /&gt;(select intvl, count(*) freq&lt;br /&gt;  from (select width_bucket(salary,&lt;br /&gt;                (select min(salary) from employees),&lt;br /&gt;                (select max(salary)+1 from employees), 10) intvl&lt;br /&gt;          from HR.employees)&lt;br /&gt;group by intvl&lt;br /&gt;order by intvl)&lt;br /&gt;--&lt;br /&gt;select intvl, freq/(select count(*) from employees) rel_freq&lt;br /&gt; from Q_freq_dist;&lt;br /&gt;-- Result from this query&lt;br /&gt;INTVL REL_FREQ&lt;br /&gt;----- ----------&lt;br /&gt;1 .429906542&lt;br /&gt;2 .093457944&lt;br /&gt;3 .214953271&lt;br /&gt;4 .140186916&lt;br /&gt;5 .074766355&lt;br /&gt;6 .018691589&lt;br /&gt;7 .018691589&lt;br /&gt;10 .009345794&lt;br /&gt;8 rows selected.&lt;/pre&gt;&lt;em&gt;Cumulative frequency distribution&lt;/em&gt; provides the percentage of observations that are less than or equal to the class of interest.&lt;br /&gt;EX&gt; Compute the cumulative frequency distribution of all employee salaries - across 10 classes.&lt;pre&gt;with Q_freq_dist as&lt;br /&gt;(select intvl, count(*) freq&lt;br /&gt;  from (select width_bucket(salary,&lt;br /&gt;                (select min(salary) from employees),&lt;br /&gt;                (select max(salary)+1 from employees), 10) intvl&lt;br /&gt;          from HR.employees)&lt;br /&gt;group by intvl&lt;br /&gt;order by intvl),&lt;br /&gt;--&lt;br /&gt;Q_rel_freq_dist as&lt;br /&gt;(select intvl, freq/(select count(*) from employees) rel_freq&lt;br /&gt;  from Q_freq_dist)&lt;br /&gt;--&lt;br /&gt;select intvl,&lt;br /&gt;      sum(rel_freq) over (order by intvl&lt;br /&gt;      rows between unbounded preceding and current row) cum_freq&lt;br /&gt; from Q_rel_freq_dist;&lt;br /&gt;-- Result from this query&lt;br /&gt;INTVL CUM_FREQ&lt;br /&gt;----- ----------&lt;br /&gt;1     .429906542&lt;br /&gt;2     .523364486&lt;br /&gt;3     .738317757&lt;br /&gt;4     .878504673&lt;br /&gt;5     .953271028&lt;br /&gt;6     .971962617&lt;br /&gt;7     .990654206&lt;br /&gt;10    1&lt;br /&gt;8 rows selected.&lt;/pre&gt;The width_bucket function creates equi-width histograms. A complementary function, &lt;em&gt;NTILE&lt;/em&gt;, helps you bin values into intervals of equal height - i.e. with same count of values in each bin. This is useful for computing &lt;em&gt;quartiles&lt;/em&gt;, &lt;em&gt;quintiles&lt;/em&gt; etc.&lt;br /&gt;EX&gt; The following query bins the 107 records/observations into approx 10 &lt;em&gt;equi-height&lt;/em&gt; bins.&lt;pre&gt;select htbin, count(*) ht&lt;br /&gt; from (select ntile(10) over (order by salary) htbin&lt;br /&gt;         from hr.employees)&lt;br /&gt;group by htbin&lt;br /&gt;order by htbin;&lt;br /&gt;HTBIN HT&lt;br /&gt;----- ------&lt;br /&gt;1     11&lt;br /&gt;2     11&lt;br /&gt;3     11&lt;br /&gt;4     11&lt;br /&gt;5     11&lt;br /&gt;6     11&lt;br /&gt;7     11&lt;br /&gt;8     10&lt;br /&gt;9     10&lt;br /&gt;10    10&lt;br /&gt;10 rows selected.&lt;/pre&gt;Anyone who has given a competitive exam (SAT thro GRE/GMAT) should be familiar with the term &lt;em&gt;percentile&lt;/em&gt;. Given &lt;em&gt;n&lt;/em&gt; data points, the &lt;em&gt;P&lt;/em&gt;th percentile represents the value which resides above &lt;em&gt;P&lt;/em&gt;% of the values, and is given by &lt;em&gt;percentile = (n+1) * P/100&lt;/em&gt;&lt;br /&gt;EX&gt; Assume a student took the &lt;a href=&quot;http://www.ets.org/portal/site/ets/menuitem.fab2360b1645a1de9b3a0779f1751509/?vgnextoid=b195e3b5f64f4010VgnVCM10000022f95190RCRD&quot;&gt;GRE &lt;/a&gt;test in 2004 and received an overall GRE score is 2150 (out of the possible 2400) and ranked at 89th percentile. What does this mean? Based on information provided &lt;a href=&quot;http://www.ets.org/Media/Tests/GRE/pdf/04-05_factors.pdf&quot;&gt;here&lt;/a&gt;, it means, of the worldwide total of 408,948, the student ranked above (408948+1) * 89/100 ~= 363965 examinees, and conversely, 408948-363964= 44982 students ranked above this student. You can compute percentiles in Oracle SQL using CUME_DIST() as follows.&lt;br /&gt;EX&gt; Rank all sales reps and their managers by their salary percentile.&lt;pre&gt;select job_id, last_name, salary,&lt;br /&gt;       round(cume_dist() over&lt;br /&gt;              (partition by job_id order by salary) * 100) as pctile&lt;br /&gt;  from employees&lt;br /&gt; where job_id like &#39;%SA_%&#39;&lt;br /&gt;order by job_id, pctile desc, salary;&lt;br /&gt;JOB_ID    LAST_NAME    SALARY  PCTILE&lt;br /&gt;------ --------------  ------  ------&lt;br /&gt;SA_MAN    Russell      14000   100&lt;br /&gt;SA_MAN    Partners     13500    80&lt;br /&gt;SA_MAN    Errazuriz    12000    60&lt;br /&gt;SA_MAN    Cambrault    11000    40&lt;br /&gt;SA_MAN    Zlotkey      10500    20&lt;br /&gt;SA_REP    Ozer         11500   100&lt;br /&gt;SA_REP    Abel         11000    97&lt;br /&gt;SA_REP    Vishney      10500    93&lt;br /&gt;SA_REP    Tucker       10000    90&lt;br /&gt;SA_REP    Bloom        10000    90&lt;br /&gt;SA_REP    King         10000    90&lt;br /&gt;...&lt;/pre&gt;The &lt;em&gt;partition by job_id&lt;/em&gt; enables to rank within job_id. You can infer things like Ms. Bloom has 90% of her fellow sales rep earning as much or less than her (&lt;em&gt;order by salary&lt;/em&gt; clause), Mr. Zlotkey is in the last quintile for managers, and so on.&lt;br /&gt;EX&gt; Suppose a new job candidate names his salary requirements - say 7.5K - you can use the same function - in what Oracle calls its &lt;em&gt;aggregate&lt;/em&gt; usage to find out what percentile this salary number would fit in, as follows:&lt;pre&gt;select round(cume_dist(7500) within group order by (salary) * 100, 0) offer_pctile&lt;br /&gt;  from employees&lt;br /&gt;OFFER_PCTILE&lt;br /&gt;------------&lt;br /&gt;   64&lt;/pre&gt;If the new candidate joins the sales force (a.k.a when his record is entered into this table), his salary will be in the 64th percentile. The &lt;em&gt;PERCENT_RANK()&lt;/em&gt; function is similar to &lt;em&gt;CUME_DIST()&lt;/em&gt; function - see the SQL Reference Manual in the Oracle docs for details.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Measures of Central Tendency - Mean, Median, Mode&lt;/strong&gt;&lt;br /&gt;&lt;strong&gt;Mean or Average&lt;/strong&gt; = sum(all observations)/ count_of_observations. Note the difference between sample mean and population mean for use later.&lt;br /&gt;EX&gt; Compute average salary of employees in the company.&lt;pre&gt;&lt;br /&gt;select min(salary) min_s, max(salary) max_s,&lt;br /&gt;      round(&lt;strong&gt;avg&lt;/strong&gt;(salary),2) avg_s&lt;br /&gt; from HR.employees;&lt;/pre&gt;EX&gt; Compute average quantity sold of products from all sale transactions.&lt;pre&gt;select prod_id, count(*), sum(quantity_sold) sum_qty,&lt;br /&gt;      avg(quantity_sold) avg_qty&lt;br /&gt; from SH.sales&lt;br /&gt;group by prod_id&lt;br /&gt;order by prod_id;&lt;/pre&gt;We can also compute the &lt;strong&gt;Mean of grouped data from a frequency distribution&lt;/strong&gt; using&lt;br /&gt;x_bar = (Σ&lt;sub&gt;_1_to_m&lt;/sub&gt;(freq&lt;sub&gt;i&lt;/sub&gt; * x&lt;sub&gt;i&lt;/sub&gt;))/Σ&lt;sub&gt;_1_to_m&lt;/sub&gt;(freq&lt;sub&gt;i&lt;/sub&gt;) where &lt;span style=&quot;font-style: italic;&quot;&gt;m &lt;/span&gt;is the number of classes.&lt;br /&gt;EX&gt; Compute the mean of the frequency distribution discussed above.&lt;pre&gt;with Q_freq_dist as (&lt;br /&gt;select intvl, count(*) freq&lt;br /&gt; from (select width_bucket(salary,&lt;br /&gt;               (select min(salary) from employees),&lt;br /&gt;               (select max(salary)+1 from employees), 10) intvl&lt;br /&gt;         from HR.employees)&lt;br /&gt;group by intvl&lt;br /&gt;order by intvl)&lt;br /&gt;--&lt;br /&gt;select sum(intvl * freq)/sum(freq)&lt;br /&gt;  from Q_freq_dist&lt;/pre&gt;&lt;strong&gt;Median&lt;/strong&gt; is the value in a dataset in which half the observations have a higher value and the other half a lower value.&lt;br /&gt;EX&gt; Compute the median salary per department.&lt;pre&gt;select department_id, &lt;strong&gt;median&lt;/strong&gt;(salary)&lt;br /&gt;  from HR.employees&lt;br /&gt;group by department_id;&lt;/pre&gt;&lt;strong&gt;Mode&lt;/strong&gt; is the observation in the dataset that occurs most frequently.&lt;br /&gt;EX&gt; Compute the mode per department.&lt;pre&gt;select department_id, &lt;strong&gt;stats_mode&lt;/strong&gt;(salary)&lt;br /&gt;  from HR.employees&lt;br /&gt;group by department_id;&lt;/pre&gt;&lt;strong&gt;Measures of Dispersion&lt;/strong&gt;&lt;br /&gt;These metrics measure how a set of data values are dispersed around (a k a deviate from) the measure of central tendency (typically the mean). &lt;strong&gt;Variance&lt;/strong&gt; represents the relative distance between the data points and the mean of a dataset, and is computed as the sum of squared deviation of each data point from the mean. &amp;#963;&lt;sup&gt;2&lt;/sup&gt; = (Σ&lt;sub&gt;1_to_n&lt;/sub&gt; (x&lt;sub&gt;i&lt;/sub&gt; - x_bar)²)/(n-1)&lt;br /&gt;EX&gt; Compute the variance, sample variance, and population variance of employee salaries.&lt;pre&gt;select variance(salary), var_samp(salary), var_pop(salary)&lt;br /&gt;  from HR.employees;&lt;/pre&gt;&lt;strong&gt;Standard deviation&lt;/strong&gt; is the square root of variance, and generally more useful than variance because it is in units of the original data - rather than its square.&lt;br /&gt;EX&gt; Compute the standard deviation, sample standard deviation, and population standard deviation of employee salaries.&lt;pre&gt;select stddev(salary), stddev_samp(salary), stddev_pop(salary)&lt;br /&gt;  from HR.employees;&lt;/pre&gt;For several commonly occuring datasets, the values tend to cluster around the mean or median - so that the distribution takes on the shape of a symmetrical bell curve. In such situations, the &lt;em&gt;Chebyshev&#39;s Theorem&lt;/em&gt; states that &lt;em&gt;at least&lt;/em&gt; (1 - 1/k²) x 100%, k &gt; 1, will fall within k-standard-deviations from the mean. If the distribution is more or les symmetrical about the mean (i.e. closer to &lt;em&gt;normal distribution&lt;/em&gt;) then the more rigorous &lt;em&gt;empirical&lt;/em&gt; rule states that &lt;em&gt;approximately&lt;/em&gt; 68% of the data will fall within 1 standard deviation of the mean, and 95% of the data within 1 standard deviations of the mean, and 99.7% of the data within 3 standard deviations of the mean.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Skewness&lt;/strong&gt; is a measure of the unevenness or asymmetry of the distribution. For a perfectly symmetric distribution, the mean is the same as mode is same as the median. Generally, for a skewed distribution, it is observed that the mean is to side of the median is to the side of the mode - the side being right (=ve skew) or left (-ve skew) depending on the skew. Skewness of a given population is computed by Skew = Σ&lt;sub&gt;1_to_N&lt;/sub&gt; (x&lt;sub&gt;i&lt;/sub&gt; - &amp;#956;)/&amp;#963;)&amp;sup3;/N, where &amp;#956; is the population mean, or &amp;#963; is the standard deviation.&lt;br /&gt;&lt;strong&gt;Kurtosis&lt;/strong&gt; is the measure of peakedness of the distribution of the population. Kurtosis = Σ&lt;sub&gt;1_to_N&lt;/sub&gt;(x&lt;sub&gt;i&lt;/sub&gt; - &amp;#956;)/&amp;#963;)&lt;sup&gt;4&lt;/sup&gt;/N.&lt;br /&gt;EX&gt; Compute the skewness and kurtosis for the employee salary.&lt;pre&gt;-- Skewness&lt;br /&gt;select avg(val3)&lt;br /&gt;  from (select power((salary - avg(salary) over ())/&lt;br /&gt;                     stddev(salary) over (), 3) val3&lt;br /&gt;          from employee);&lt;br /&gt;--&lt;br /&gt;-- Kurtosis&lt;br /&gt;select avg(val4)&lt;br /&gt;  from (select power((salary - avg(salary) over ())/&lt;br /&gt;                     stddev(salary) over (), 4) val4&lt;br /&gt;          from employee);&lt;/pre&gt;This brevity is made possible thanks to Oracle SQL analytical functions (&lt;em&gt;avg(salary) over ()&lt;/em&gt; implies compute average over all rows in the employees). Note that you can use the partition and order by clauses inside the () to group data across different employee classes and scope the computation to the group if required. From a performance standpoint, note that the computation intrinsically demands multiple scans (2 at the least) over the employees table (or the tables behind the employees view) - so for a potentially large employees table, the computations may involve use of sort (i.e. on-disk) memory rather than just the PGA (the database&#39; equivalent of a PC&#39;s RAM). For more on such performance implications of SQL, begin your education with Oracle Concepts or SQL Tuning Guide, or look up the various references provided here.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/9057090841324358753/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/9057090841324358753?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/9057090841324358753'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/9057090841324358753'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/09/st001-descriptive-statistics.html' title='Descriptive Statistics'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-754433809962457782</id><published>2007-09-01T12:51:00.000-04:00</published><updated>2007-10-11T22:37:45.524-04:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="General Info"/><title type='text'>Dev Essentials</title><content type='html'>&lt;strong&gt;Pre-requisites&lt;/strong&gt;:&lt;br /&gt;This blog is aimed at an Oracle RDBMS user with a beginner to intermediate level understanding of SQL and PL/SQL languages, and basic Oracle Concepts. If you are an analyst weaned on Excel or other GUI workbenches with some basic programming ability, but know next to nothing about databases, &lt;a href=&quot;http://philip.greenspun.com/panda/databases-choosing&quot;&gt;read this friendly intro&lt;/a&gt; (ignore the author&#39;s controversial opinions), kick the tires on a &lt;a href=&quot;http://www.oracle.com/technology/products/database/xe/index.html&quot;&gt;free edition of Oracle&lt;/a&gt;, and return here.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Database&lt;/strong&gt;:&lt;br /&gt;This blog is based on Oracle10gR2 and higher. Oracle gives away an awful lot of analytics features as part of its free (XE/Express) or low-cost (Standard) editions - but if a highlighted feature is available only in a particular higher-end edition, we will mention it.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Datasets:&lt;/span&gt;&lt;br /&gt;We will use the data in the &lt;a href=&quot;http://download.oracle.com/docs/cd/B19306_01/server.102/b14198/toc.htm&quot;&gt;Sample Schema &lt;/a&gt;that ships with the Oracle database for most of our examples. Enable SELECT privileges on all the tables in the various sample schemas. When this data is inadequate to explain a concept, we will import data from other public sources.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Loading data:&lt;/strong&gt;&lt;br /&gt;For small datasets outside the sample schema, we will use INSERT statements. For larger tables, we&#39;ll use SQL*Loader and/or External Tables. &lt;a href=&quot;http://www.dbspecialists.com/presentations/load_faster.html&quot;&gt;Here &lt;/a&gt;is a quick primer on data load (Note: the extract_files_dir directory object should be created by the DBA using the&lt;a href=&quot;http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_5007.htm#i2061958&quot;&gt; CREATE DIRECTORY&lt;/a&gt; statement). For more details, consult Oracle docs.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;DevEnv&lt;/span&gt;:&lt;br /&gt;The baseline is Xemacs- SQL*Plus - Oracle10gR2 Enterprise Edition - RHEL on a 2-processor Core duo Dell COTS (common off-the-shelf) machine. Over time, we will try the free SQL*Developer tool for all development. Software downloads of the database and related products are available &lt;a href=&quot;http://www.oracle.com/technology/software/products/database/index.html&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Output, Visualization of results:&lt;br /&gt;&lt;/strong&gt;One major weakness of Oracle compared to best-of-breed statistical/scientific products is the charting and visualization capability in its disparate GUI products. Oracle has several of them - SQL*Developer, Application Express, Discoverer, Warehouse Builder, Data Miner, Enterprise Manager, and a whole slew of tools from the Siebel BI (a k a BI EE) and Hyperion acquisitions. These tools address specific areas of data or application management. As the #1 database company, it would be fantastic if Oracle makes a strategic investment to build modular, data visualization solutions across its product stack - integrating the best elements from it existing portfolio of GUI-based products, and third party tools like &lt;a href=&quot;http://www.tibco.com/software/business_intelligence/default.jsp&quot;&gt;Spotfire&lt;/a&gt;, &lt;a href=&quot;http://www.tableausoftware.com/&quot;&gt;Tableau&lt;/a&gt;, or &lt;a href=&quot;http://www.dundas.com/&quot;&gt;Dundas&lt;/a&gt; (now part of MSFT). But Visualization for BI is still in its nascent stages, so this may not happen soon. For purposes of this blog, we will embed screenshots from Excel, SQL*Dev, App Express, Data Miner, R and other Oracle GUIs as applicable. We will use &lt;a href=&quot;http://www.gnome.org/projects/dia/&quot;&gt;Dia &lt;/a&gt;for diagramming.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Code Quality:&lt;/strong&gt;&lt;br /&gt;I will test every code fragment I publish here, but I am not the best SQL or PL/SQL developer around - so I welcome comments/corrections on better-expressed and/or more efficient queries for a particular problem. Consult AskTom or search for &lt;a href=&quot;http://www.celko.com/articles.htm&quot;&gt;Celko&#39;s articles&lt;/a&gt; for SQL tips, and Steve Feuerstein&#39;s articles/books for PL/SQL coding tips.</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/754433809962457782/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/754433809962457782?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/754433809962457782'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/754433809962457782'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/09/essentials-post-legend-data-load-dev.html' title='Dev Essentials'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-4903856565127937599.post-73933076132595736</id><published>2007-09-01T09:07:00.000-04:00</published><updated>2007-10-18T17:56:36.656-04:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="General Info"/><title type='text'>Preface</title><content type='html'>Greetings.&lt;br /&gt;&lt;br /&gt;This blog is a personal quest to learn/discover/enable the Oracle RDBMS as an analytical/scientific computing engine. While Oracle does not (yet) match the breadth and depth of a popular, best-of-breed platform like SAS for analytics, or a scientific computing suite like Matlab, it offers enough facilities in Oracle SQL and PL/SQL to build a competent business analytics platform, if not yet a comprehensive platform for scientific research.&lt;br /&gt;&lt;br /&gt;The answer to the central question of &quot;I am an Oracle database professional ...Why Should I Know Analytics?&quot; is simply &quot;To keep yourself relevant ten years from now&quot;. A more lucid, lengthy answer can be found in the books in the Readings section. After a 10-15 year journey through database design, E-R diagrams, Certifications on every database technology, managing terabyte warehouses, you are bound to come to a juncture in your professional life where you ask &quot;We store at least 7-10 years worth of transactional data (as required by Sarbanes-Oxley).. is there anything I can learn about my customers/products/employees &lt;em&gt;implicitly&lt;/em&gt; from all this stored data - beyond what I code into my applications?&quot; At this point in time, you begin to become an analyst.&lt;br /&gt;&lt;br /&gt;The central question of &quot;Why &lt;strong&gt;In-Database&lt;/strong&gt; Analytics?&quot; deserves a dedicated post rather than a glib answer in this column. But the basic premise is this: The wider and deeper you &lt;em&gt;deploy&lt;/em&gt; intelligence across a company, the smarter the company. Any data-driven intelligence that you &lt;em&gt;compute at the source&lt;/em&gt; - i.e. where your enterprise data resides - becomes corporate intelligence consumable across the enterprise. The higher you go in your stack to compute this intelligence, the more insular this intelligence becomes to the rest of the company - SOA and other mid-tier technologies notwithstanding. So the proposition is simple - &#39;If you are an Oracle DBA/Developer/Analyst/CIO, explore the capabilities of the database as an analytical platform before you think about spending on tiered, best-of-breed products. Save that money for the best business analysis and data analysis talent that you can find&#39;.&lt;br /&gt;&lt;br /&gt;Over the years, customers/consultants have wanted to incorporate their own algorithms into the database. Oracle has been extensible since 8i, offering a framework to link your C-based Math/Analytics libraries into the database. But unlike Illustra (the competitive Object-relational database of the 8i era), Oracle (wisely) places a user application in its own process sandbox - it does not allow a user to link their &quot;untrusted&quot; C library directly into the Oracle binary - mainly to prevent some buggy/malicious C fragment from crashing a million dollar production system.&lt;br /&gt;&lt;br /&gt;The consequence is that your application has to marshal the data between your library and the database through an ExtProc interface. Obviously, this critical data pinch-point has not helped spawn a large collection of extensible third-party applications. However, internal to Oracle, the framework has been a great success, enabling an evolutionary development of products that manage unstructured data - Oracle&#39;s Spatial Option, Text, XML, Enterprise Search, PL/SQL Table functions and such features directly or indirectly use this framework or its design concepts.&lt;br /&gt;&lt;br /&gt;There is a secondary motivation to this blog. 47% of the world&#39;s corporate relational data is stored in Oracle. If even a fraction of this installed base begins to demand more foundational analytics infrastructure such as high performance matrix computation, concurrent processing, math libraries, and such building blocks for scientific computing - this may nudge Oracle towards becoming a world-class analytics engine.&lt;br /&gt;&lt;br /&gt;Returning to more humbler pragmatics for the blog, rather than take the classic extensibility route, we&#39;ll code techniques using Oracle10gR2 (and later) SQL and PL/SQL. PL/SQL as a language has dramatically matured over the past 5 years, with support for native compilation, IEEE floating point arithmetic, function/rowset caching, and improved scalability and performance. Where expedient/convenient, we will package any open-source Java libraries as Java stored procedures.&lt;br /&gt;&lt;br /&gt;If you have read thus far, and have the slightest inkling of the breadth and depth of quantitative techniques out there, you will agree that the mission statement for this blog is downright audacious, or Quixotic, or stupid, or pick your adjective... &lt;add&gt;So to quickly bootstrap the blog, and give myself a minimal chance of success, I have afforded myself these concessions:&lt;ul&gt;&lt;li&gt;I will scope my efforts to coding a particular technique, with a best-effort attempt to find an appropriate example of its applicability. I will try to provide pointers to relevant articles/case studies from domain experts (CRM/Retail/Supply Chain etc). Comments and discussions will hopefully add/illuminate the various use cases.&lt;/li&gt;&lt;li&gt;I will refer books, other blogs, websites for various topics, and credit the authors - either as links, or by including their books/publications in the References section below&lt;/li&gt;&lt;li&gt;Once I stabilize the blog content, I will welcome co-authors - there is a ton of material to cover. So if you are interested, ping me a mail.&lt;/li&gt;&lt;/ul&gt; Wish me luck, and hope you find this site interesting and useful.&lt;br /&gt;&lt;br /&gt;Best regards, Ram&lt;/add&gt;&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://numoraclerecipes.blogspot.com/feeds/73933076132595736/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/4903856565127937599/73933076132595736?isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/73933076132595736'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/4903856565127937599/posts/default/73933076132595736'/><link rel='alternate' type='text/html' href='http://numoraclerecipes.blogspot.com/2007/09/foreword.html' title='Preface'/><author><name>Ram Krishnan</name><uri>http://www.blogger.com/profile/01032962495745306728</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>