Hi all, This Blog is an English archive of my PhD experience in Imperial College London, mainly logging my research and working process, as well as some visual records.

Showing posts with label Statistics. Show all posts
Showing posts with label Statistics. Show all posts

Monday, 3 September 2007

Spearman Correlation - Example

Example of Statistical Test using the Spearman Rank-Difference Correlation Coefficient

Is there a significant positive correlation between the rankings of 10 children on a reading test and their teacher's ranking of their reading ability? In this problem we are relating a set of scores (interval level of measurement) with the teacher's ranking of the children in reading (ordinal level of measurement). To do this we first convert the reading test scores to ranks by assigning the highest score a rank of 1, the next highest a rank of 2, etc. Now we are looking at rankings on two variables and can use the Spearman Rank-Difference Correlation Coefficient to test the significance of the relationship. The two set of ranks, as well as the difference between the pairs of ranks (D) and the differences squared (D2), are shown in the following table.

Worksheet to Calculate the Correlation between Students Ranks on a Reading Test and Teacher's Ranking of the Students on Reading
Reading Test
Score Rank
Teacher's Ranking
on Reading
D D2
1 3 -2 4
2 2 0 0
3 1 2 4
4 4 0 0
5 5 0 0
6 6 0 0
7 8 -1 1
8 7 1 1
9 10 -1 1
10 9 1 1
Total

12

From the table we can see that:

df = N - 2 = 10 - 2 = 8

We now have the information we need to complete the six step process for testing statistical hypotheses for our research problem.

  1. State the null hypothesis and the alternative hypothesis based on your research question.

    H0: rS = 0

    H1: rS > 0

    Note: Our null hypothesis states that there is no significant relationship between the two variables. The alternative hypothesis states that there is a significant positive correlation between the two variables.

  2. Set the alpha level.

    Note: As usual we will set our alpha level at .05, we have 5 chances in 100 of making a type I error.
  3. Calculate the value of the appropriate statistic. Also indicate the degrees of freedom for the statistical test if necessary.

    rS = .93

    df = N - 2 = 10 - 2 = 8

  4. Write the decision rule for rejecting the null hypothesis.

    Reject H0 if rS >= .549

    Note: To write the decision rule we had to know the critical value for rS, with an alpha level of .05, and 8 degrees of freedom. We can do this by looking at Appendix Table B, this is the same table we used for the Pearson r, and noting the tabled value for the column for the .10 level and the row for 8 df (.549).

    Note: We used the .10 column because we are doing a one-tailed test with an alpha of .05 As noted in our problem above the the Pearson r, in the table of critical values for r, the .10 column is used for alpha = .10 (two-tailed test) and for alpha = .05 (one-tailed test).

  5. Write a summary statement based on the decision.
    Reject H0, p < .05, one-tailed
    Note: Since our calculated value of rS (.93) is greater than .549, we reject the null hypothesis and accept the alternative hypothesis.
  6. Write a statement of results in standard English.
    There is a significant positive correlation between the children's ranks on a reading test and their teacher's ranking of them on reading.

Choosing the Proper Statistical Test


Let's finish our discussion of inferential statistics with a summary of all the inferential statistics we have discussed and look at the conditions under which we would use each of these statistics. Generally if we know the number of groups or samples in our research design and the level of measurement of the dependent variable we will know which inferential statistic to use.

First let us look at statistical hypotheses in research designs where the dependent variable is at the interval or ratio level. These statistics are known as parametric statistics and we have used the following:

  • If we are testing a statistical hypothesis, involving a single score (we are comparing the score with the population mean) we will use the z-score test (see lesson 9).
  • If we are testing a statistical hypothesis involving a single group (we are comparing the mean of the group with the population mean) and the standard deviation of the population is know use the z test (see lesson 10).
  • If we are testing a statistical hypothesis involving a single group (we are comparing the mean of the group with the population mean) and the standard deviation of the population is not known use the single sample t-test (see lesson 10).
  • If we are testing a statistical hypothesis involved two groups of subjects (we are comparing the means of the two groups) and the two groups are independent of one another, we use the independent t-test (see lesson 11).
  • If we are testing a statistical hypothesis involved two groups of subjects (we are comparing the means of the two groups) and the two groups are dependent on one another (pretest/posttest or matched samples), we use the dependent t-test (see lesson 12).
  • If we are testing a statistical hypothesis involved three or more groups of subjects (we are comparing the means of three or more groups) and there is a single dependent variable in the study, we use one-way analysis of variance (see lesson 13).
  • If we are testing a statistical hypothesis involved the relationship between two variables for one sample (we are measuring the relationship between the two variables) and the data is at the interval or ratio level of measurement), use the Pearson product moment correlation coefficient.

We also looked at two other statistics we could use with data that was not at the interval or ratio level of measurement. These statistics are called non-parametric statistics.

  • If we are testing a statistical hypothesis for one, two, or more groups with one or two variables where the data is catagorical (frequencies). The data is at the nominal level of measurement. For this type of study use chi-square (see lesson 14). We have discussed three different variants of the chi-square statistic.
    1. one variable chi-square with equal expected frequencies
    2. one variable chi-square with unequal (predetermined) expected frequencies
    3. two variable chi-square
  • If we are testing a statistical hypothesis involved the relationship between two variables for one sample (we are measuring the relationship between the two variables) and the data is at the ordinal level of measurement (ranks), use the Spearman rank-difference correlation coefficient (see lesson 15).

The information we have discussed above can be put into the following table. The table also includes other statistics that we have not included in this course. If you think you may need one of the statistics we did not cover in your research design, please send e-mail to the instructor and I will give you a reference to the calculation and interpretation of that statistic. I wish you the best as you complete the final examination for this course and as you apply the information from this course to your own research design.

Selecting a Statistical Test
Level of
Measurement
Sample Characteristics
One-Sample
Statistical
Tests
Two-Sample
Statistical
Tests
Multiple Sample
Statistical
Tests
Measures of
Association
(one-sample, more
than one variable)
Independent
Samples
Non-independent
Samples
Nominal or
Categorical
(frequencies)
Chi-Square Chi-Square McNemar
Change Test
Chi-Square Phi Coefficient
Ordinal
(Ranks)
Kolmagorov-Smirnov
One-Sample
Test
Mann Whitney
U-Test
Wilcoxon
Matched Pairs
Signed-Rank
Test
Krushcal-Wallis
One-Way
Analysis of
Variance
Spearman rho
rS
Interval
or Ratio
Z test

One-Sample
t-Test
Independent
t-test
Dependent
t-test
Simple
Analysis of Variance

Factorial
Analysis of Variance

Scheffe Tests

Analysis of Covariance
Pearson r

Multiple
Regression

Saturday, 1 September 2007

Spearman Correlation

Spearman's rank correlation coefficient, named after Charles Spearman and often denoted by the Greek letter ρ (rho), is a non-parametric measure of correlation – that is, it assesses how well an arbitrary monotonic function could describe the relationship between two variables, without making any assumptions about the frequency distribution of the variables. Unlike the Pearson product-moment correlation coefficient, it does not require the assumption that the relationship between the variables is linear, nor does it require the variables to be measured on interval scales; it can be used for variables measured at the ordinal level.

In principle, ρ is simply a special case of the Pearson product-moment coefficient in which the data are converted to rankings before calculating the coefficient. In practice, however, a simpler procedure is normally used to calculate ρ. The raw scores are converted to ranks, and the differences d between the ranks of each observation on the two variables are calculated.

If there are no tied ranks, i.e. \neg\exists_{i,j} i\ne j \wedge (x_i=x_j \vee y_i=y_j)

then ρ is given by:

 \rho = 1- {\frac {6 \sum d_i^2}{n(n^2 - 1)}}

where:

di = the difference between each rank of corresponding values of x and y, and
n = the number of pairs of values.

If tied ranks exist, classic Pearson's correlation coefficient between ranks has to be used instead of this formula. You have to assign the same rank to each of the equal values. It is an average of their positions in the ascending order of the values:


An Example of Averaging Ranks

Variable Position in the decending order Rank
0.8 5 5
1.2 4 \frac{4+3}{2}=3.5\
1.2 3 \frac{4+3}{2}=3.5\
2.3 2 2
18 1 1

Spearman's rank correlation coefficient is equivalent to Pearson correlation on ranks. The formula above is a short-cut to its product-moment form, assuming no tie. The product-moment form can be used in both tied and untied cases.

A version of this correlation is called Spearman's rho. In this case ranks are calculated as above, but in the formula of Pearson's correlation a standard deviation is taken as there were no ties.

Another popular method for computing rank correlation is the Kendall tau rank correlation coefficient.

Example

The raw data used in this example is shown below.

IQ Hours of TV per week.
106 7
86 0
100 27
101 50
99 28
103 29
97 20
113 12
112 6
110 17

The first step is to sort this data by the first column. Next, two more columns are created. Both of these are for ranking the first two columns. Notice how the rank of values that are the same is the mean of what their ranks would otherwise be. Then a column "d" is created to hold the differences between the two rank columns. Finally another column "d2" should be created. This is just column d squared.

After doing this process with the example data you should end up with something like:

IQ (i) Hours of TV per week (t) rank (i) rank (t) d d2
86 0 1 1 0 0
97 20 2 6 4 16
99 28 3 8 5 25
100 27 4 7 3 9
101 50 5 10 5 25
103 29 6 9 3 9
106 7 7 3 4 16
110 17 8 5 3 9
112 6 9 2 7 49
113 12 10 4 6 36

The values in the d2 column can now be added to find \sum d_i^2 = 194. The value of n is 10. So these values can now be substituted back into the equation,

 \rho = 1- {\frac {6\times194}{10(10^2 - 1)}}

which evaluates to ρ = − 0.175758. In the case of ties in the original values, then this formula should not be used. Instead, the Pearson correlation coefficient should be calculated on the ranks (where ties are given ranks, as described above).

Statistics: Another Syllabus

STATISTICAL METHODS FOR RESEARCH WORKERS

Referenced from Christopher D. Green's Website: http://psychclassics.yorku.ca/Fisher/Methods/



STATISTICAL METHODS FOR RESEARCH WORKERS

By Ronald A. Fisher (1925)
Originally published in Edinburgh by Oliver and Boyd.

Posted March 2000
Modified Sept. 2005


TITLE PAGE

PREFACES

Image of original TABLE OF CONTENTS

I. INTRODUCTION

II. DIAGRAMS

III. DISTRIBUTIONS

Image of TECHNICAL APPENDIX: p. 74, p. 75

IV. TESTS OF GOODNESS OF FIT, INDEPENDENCE AND HOMOGENEITY; WITH TABLE OF χ2

V. TESTS OF SIGNIFICANCE OF MEANS, DIFFERENCE OF MEANS, AND REGRESSION COEFFICIENTS

VI. THE CORRELATION COEFFICIENT

VII. INTRACLASS CORRELATIONS AND THE ANALYSIS OF VARIANCE

VIII. FURTHER APPLICATIONS OF THE ANALYSIS OF VARIANCE

SOURCES USED FOR DATA AND METHODS INDEX

INDEX

TABLES

I. and II. NORMAL DISTRIBUTION

III. TABLE OF c2

IV. TABLE OF t

V.A. CORRELATION COEFFICIENT -- SIGNIFICANT VALUES

V.B. CORRELATION COEFFICIENT -- TRANSFORMED VALUES

VI. TABLE OF z

Correlation ratio

In statistics, the correlation ratio is a measure of the relationship between the statistical dispersion within individual categories and the dispersion across the whole population or sample.

Suppose each observation is yxi where x indicates the category that observation is in and i is the label of the particular observation. We will write nx for the number of observations in category x (not necessarily the same for different values of x) and

\overline{y}_x=\frac{\sum_i y_{xi}}{n_x} and \overline{y}=\frac{\sum_x n_x \overline{y}_x}{\sum_x n_x}

then the correlation ratio η (eta) is defined so as to satisfy

\eta^2 = \frac{\sum_x n_x (\overline{y}_x-\overline{y})^2}{\sum_{xi} (y_{xi}-\overline{y})^2}

which might be written as

\frac{{\sigma_{\overline{y}}}^2}{{\sigma_{y}}^2}.

It is worth noting that if the relationship between values of x \;\ and values of \overline{y}_x is linear (which is certainly true when there are only two possibilities for x) this will give the same result as the square of the correlation coefficient; if not then the correlation ratio will be larger in magnitude, though still no more than 1 in magnitude. It can therefore be used for judging non-linear relationships.

Correlation, Pearson Correlation

In probability theory and statistics, correlation, also called correlation coefficient, indicates the strength and direction of a linear relationship between two random variables. In general statistical usage, correlation or co-relation refers to the departure of two variables from independence. In this broad sense there are several coefficients, measuring the degree of correlation, adapted to the nature of data.

A number of different coefficients are used for different situations. The best known is the Pearson product-moment correlation coefficient, which is obtained by dividing the covariance of the two variables by the product of their standard deviations. Despite its name, it was first introduced by Francis Galton.

Pearson's product-moment coefficient

Mathematical properties

The correlation coefficient ρX, Y between two random variables X and Y with expected values μX and μY and standard deviations σX and σY is defined as:

\rho_{X,Y}={\mathrm{cov}(X,Y) \over \sigma_X \sigma_Y} ={E((X-\mu_X)(Y-\mu_Y)) \over \sigma_X\sigma_Y},

where E is the expected value operator and cov means covariance. Since μX = E(X), σX2 = E(X2) − E2(X) and likewise for Y, we may also write

\rho_{X,Y}=\frac{E(XY)-E(X)E(Y)}{\sqrt{E(X^2)-E^2(X)}~\sqrt{E(Y^2)-E^2(Y)}}.

The correlation is defined only if both of the standard deviations are finite and both of them are nonzero. It is a corollary of the Cauchy-Schwarz inequality that the correlation cannot exceed 1 in absolute value.

The correlation is 1 in the case of an increasing linear relationship, −1 in the case of a decreasing linear relationship, and some value in between in all other cases, indicating the degree of linear dependence between the variables. The closer the coefficient is to either −1 or 1, the stronger the correlation between the variables.

If the variables are independent then the correlation is 0, but the converse is not true because the correlation coefficient detects only linear dependencies between two variables. Here is an example: Suppose the random variable X is uniformly distributed on the interval from −1 to 1, and Y = X2. Then Y is completely determined by X, so that X and Y are dependent, but their correlation is zero; they are uncorrelated. However, in the special case when X and Y are jointly normal, independence is equivalent to uncorrelatedness.

A correlation between two variables is diluted in the presence of measurement error around estimates of one or both variables, in which case disattenuation provides a more accurate coefficient .



Positive linear correlations between 1000 pairs of numbers.  The data are graphed on the lower left and their correlation coefficients listed on the upper right.  Each square in the upper right corresponds to its mirror-image square in the lower left, the "mirror" being the diagonal of the whole array.  Each set of points correlates maximally with itself, as shown on the diagonal (all correlations = +1).
Positive linear correlations between 1000 pairs of numbers. The data are graphed on the lower left and their correlation coefficients listed on the upper right. Each square in the upper right corresponds to its mirror-image square in the lower left, the "mirror" being the diagonal of the whole array. Each set of points correlates maximally with itself, as shown on the diagonal (all correlations = +1).

The sample correlation

If we have a series of n measurements of X and Y written as xi and yi where i = 1, 2, ..., n, then the Pearson product-moment correlation coefficient can be used to estimate the correlation of X and Y . The Pearson coefficient is also known as the "sample correlation coefficient". It is especially important if X and Y are both normally distributed. The Pearson correlation coefficient is then the best estimate of the correlation of X and Y . The Pearson correlation coefficient is written:

r_{xy}=\frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{(n-1) s_x s_y},

where \bar{x} and \bar{y} are the sample means of X and Y , sx and sy are the sample standard deviations of X and Y and the sum is from i = 1 to n. As with the population correlation, we may rewrite this as

r_{xy}=\frac{n\sum x_iy_i-\sum x_i\sum y_i} {\sqrt{n\sum x_i^2-(\sum x_i)^2}~\sqrt{n\sum y_i^2-(\sum y_i)^2}}.

Again, as is true with the population correlation, the absolute value of the sample correlation must be less than or equal to 1. Though the above formula conveniently suggests a single-pass algorithm for calculating sample correlations, it is notorious for its numerical instability (see below for something more accurate).

The square of the sample correlation coefficient, which is also known as the coefficient of determination, is the fraction of the variance in yi that is accounted for by a linear fit of xi to yi . This is written

r_{xy}^2=1-\frac{s_{y|x}^2}{s_y^2},

where sy|x2 is the square of the error of a linear regression of xi on yi by the equation y = a + bx:

s_{y|x}^2=\frac{1}{n-1}\sum_{i=1}^n (y_i-a-bx_i)^2,

and sy2 is just the variance of y:

s_y^2=\frac{1}{n-1}\sum_{i=1}^n (y_i-\bar{y})^2.

Note that since the sample correlation coefficient is symmetric in xi and yi , we will get the same value for a fit of xi to yi :

r_{xy}^2=1-\frac{s_{x|y}^2}{s_x^2}.

This equation also gives an intuitive idea of the correlation coefficient for higher dimensions. Just as the above described sample correlation coefficient is the fraction of variance accounted for by the fit of a 1-dimensional linear submanifold to a set of 2-dimensional vectors (xi , yi ), so we can define a correlation coefficient for a fit of an m-dimensional linear submanifold to a set of n-dimensional vectors. For example, if we fit a plane z = a + bx + cy to a set of data (xi , yi , zi ) then the correlation coefficient of z to x and y is

r^2=1-\frac{\sigma_{z|xy}^2}{s_z^2}.

Geometric Interpretation of correlation

The correlation coefficient can also be viewed as the cosine of the angle between the two vectors of samples drawn from the two random variables.

Caution: This method only works with centered data, i.e., data which have been shifted by the sample mean so as to have an average of zero. Some practitioners prefer an uncentered (non-Pearson-compliant) correlation coefficient. See the example below for a comparison.

As an example, suppose five countries are found to have gross national products of 1, 2, 3, 5, and 8 billion dollars, respectively. Suppose these same five countries (in the same order) are found to have 11%, 12%, 13%, 15%, and 18% poverty. Then let x and y be ordered 5-element vectors containing the above data: x = (1, 2, 3, 5, 8) and y = (0.11, 0.12, 0.13, 0.15, 0.18).

By the usual procedure for finding the angle between two vectors (see dot product), the uncentered correlation coefficient is:

 \cos \theta = \frac { \bold{x} \cdot \bold{y} } { \left\| \bold{x} \right\| \left\| \bold{y} \right\| } = \frac { 2.93 } { \sqrt { 103 } \sqrt { 0.0983 } } = 0.920814711.

Note that the above data were deliberately chosen to be perfectly correlated: y = 0.10 + 0.01 x. The Pearson correlation coefficient must therefore be exactly one. Centering the data (shifting x by E(x) = 3.8 and y by E(y) = 0.138) yields x = (-2.8, -1.8, -0.8, 1.2, 4.2) and y = (-0.028, -0.018, -0.008, 0.012, 0.042), from which

 \cos \theta = \frac { \bold{x} \cdot \bold{y} } { \left\| \bold{x} \right\| \left\| \bold{y} \right\| } = \frac { 0.308 } { \sqrt { 30.8 } \sqrt { 0.00308 } } = 1,

as expected.

Interpretation of the size of a correlation

Correlation Negative Positive
Small −0.29 to −0.10 0.10 to 0.29
Medium −0.49 to −0.30 0.30 to 0.49
Large −1.00 to −0.50 0.50 to 1.00

Several authors have offered guidelines for the interpretation of a correlation coefficient. Cohen (1988),[1] for example, has suggested the following interpretations for correlations in psychological research, in the table on the right.

As Cohen himself has observed, however, all such criteria are in some ways arbitrary and should not be observed too strictly. This is because the interpretation of a correlation coefficient depends on the context and purposes. A correlation of 0.9 may be very low if one is verifying a physical law using high-quality instruments, but may be regarded as very high in the social sciences where there may be a greater contribution from complicating factors.

Non-parametric correlation coefficients

Pearson's correlation coefficient is a parametric statistic, and it may be less useful if the underlying assumption of normality is violated. Non-parametric correlation methods, such as Chi-square, Point biserial correlation, Spearman's ρ and Kendall's τ may be useful when distributions are not normal; they are a little less powerful than parametric methods if the assumptions underlying the latter are met, but are less likely to give distorted results when the assumptions fail.

Other measures of dependence among random variables

To get a measure for more general dependencies in the data (also nonlinear) it is better to use the correlation ratio which is able to detect almost any functional dependency, or mutual information/total correlation which is capable of detecting even more general dependencies.

Copulas and correlation

The information given by a correlation coefficient is not enough to define the dependence structure between random variables; to fully capture it we must consider a copula between them. The correlation coefficient completely defines the dependence structure only in very particular cases, for example when the cumulative distribution functions are the multivariate normal distributions. In the case of elliptic distributions it characterizes the (hyper-)ellipses of equal density, however, it does not completely characterize the dependence structure (for example, the a multivariate t-distribution's degrees of freedom determine the level of tail dependence).

Correlation matrices

The correlation matrix of n random variables X1, ..., Xn is the n × n matrix whose i,j entry is corr(Xi, Xj). If the measures of correlation used are product-moment coefficients, the correlation matrix is the same as the covariance matrix of the standardized random variables Xi /SD(Xi) for i = 1, ..., n. Consequently it is necessarily a positive-semidefinite matrix.

The correlation matrix is symmetric because the correlation between Xi and Xj is the same as the correlation between Xj and Xi.

Removing correlation

It is always possible to remove the correlation between zero-mean random variables with a linear transform, even if the relationship between the variables is nonlinear. Suppose a vector of n random variables is sampled m times. Let X be a matrix where Xi,j is the jth variable of sample i. Let Zr,c be an r by c matrix with every element 1. Then D is the data transformed so every random variable has zero mean, and T is the data transformed so all variables have zero mean, unit variance, and zero correlation with all other variables.

D = X -\frac{1}{m} Z_{m,m} X
T = D (D^T D)^{-\frac{1}{2}}

where an exponent of -1/2 represents the matrix square root of the inverse of a matrix. The covariance matrix of T will be the identity matrix. If a new data sample x is a row vector of n elements, then the same transform can be applied to x to get the transformed vectors d and t:

d = x - \frac{1}{m} Z_{1,m} X
t = d (D^T D)^{-\frac{1}{2}}.

Common misconceptions about correlation

Correlation and causality

The conventional dictum that "correlation does not imply causation" means that correlation cannot be validly used to infer a causal relationship between the variables. This dictum should not be taken to mean that correlations cannot indicate causal relations. However, the causes underlying the correlation, if any, may be indirect and unknown. Consequently, establishing a correlation between two variables is a not sufficient condition to establish a causal relationship (in either direction).

Here is a simple example: hot weather may cause both crime and ice-cream purchases. Therefore crime is correlated with ice-cream purchases. But crime does not cause ice-cream purchases and ice-cream purchases do not cause crime.

A correlation between age and height in children is fairly causally transparent, but a correlation between mood and health in people is less so. Does improved mood lead to improved health? Or does good health lead to good mood? Or does some other factor underlie both? Or is it pure coincidence? In other words, a correlation can be taken as evidence for a possible causal relationship, but cannot indicate what the causal relationship, if any, might be.

Correlation and linearity

Four sets of data with the same correlation of 0.81
Four sets of data with the same correlation of 0.81

While Pearson correlation indicates the strength of a linear relationship between two variables, its value alone may not be sufficient to evaluate this relationship, especially in the case where the assumption of normality is incorrect.

The image on the right shows scatterplots of Anscombe's quartet, a set of four different pairs of variables created by Francis Anscombe.[2] The four y variables have the same mean (7.5), standard deviation (4.12), correlation (0.81) and regression line (y = 3 + 0.5x). However, as can be seen on the plots, the distribution of the variables is very different. The first one (top left) seems to be distributed normally, and corresponds to what one would expect when considering two variables correlated and following the assumption of normality. The second one (top right) is not distributed normally; while an obvious relationship between the two variables can be observed, it is not linear, and the Pearson correlation coefficient is not relevant. In the third case (bottom left), the linear relationship is perfect, except for one outlier which exerts enough influence to lower the correlation coefficient from 1 to 0.81. Finally, the fourth example (bottom right) shows another example when one outlier is enough to produce a high correlation coefficient, even though the relationship between the two variables is not linear.

These examples indicate that the correlation coefficient, as a summary statistic, cannot replace the individual examination of the data.

Computing correlation accurately in a single pass

The following algorithm (in pseudocode) will estimate correlation with good numerical stability

sum_sq_x = 0
sum_sq_y = 0
sum_coproduct = 0
mean_x = x[1]
mean_y = y[1]
for i in 2 to N:
sweep = (i - 1.0) / i
delta_x = x[i] - mean_x
delta_y = y[i] - mean_y
sum_sq_x += delta_x * delta_x * sweep
sum_sq_y += delta_y * delta_y * sweep
sum_coproduct += delta_x * delta_y * sweep
mean_x += delta_x / i
mean_y += delta_y / i
pop_sd_x = sqrt( sum_sq_x / N )
pop_sd_y = sqrt( sum_sq_y / N )
cov_x_y = sum_coproduct / N
correlation = cov_x_y / (pop_sd_x * pop_sd_y)

For an enlightening experiment, check the correlation of {900,000,000 + i for i=1...100} with {900,000,000 - i for i=1...100}, perhaps with a few values modified. Poor algorithms will fail.

Currency correlation

Currency correlation is correlation between two currency pairs, or more generally, correlations between values of commodities, stocks and bonds markets. It is used as a tool to predict changes in market value.

Thursday, 30 August 2007

Overview of Statistical Test [***recommended***]

Choosing a statistical test

This is chapter 37 of Intuitive Biostatistics (ISBN 0-19-508607-4) by Harvey Motulsky. Copyright © 1995 by Oxford University Press Inc. All rights reserved. You may order the book from GraphPad Software with a software purchase, from any academic bookstore, or from amazon.com.

Learn how to interpret the results of statistical tests and about our programs GraphPad InStat and GraphPad Prism.

REVIEW OF AVAILABLE STATISTICAL TESTS

This book has discussed many different statistical tests. To select the right test, ask yourself two questions: What kind of data have you collected? What is your goal? Then refer to Table 37.1.

All tests are described in this book and are performed by InStat, except for tests marked with asterisks. Tests labeled with a single asterisk are briefly mentioned in this book, and tests labeled with two asterisks are not mentioned at all.

Table 37.1. Selecting a statistical test


Type of Data
Goal Measurement (from Gaussian Population) Rank, Score, or Measurement (from Non- Gaussian Population) Binomial
(Two Possible Outcomes)
Survival Time
Describe one group Mean, SD Median, interquartile range Proportion Kaplan Meier survival curve
Compare one group to a hypothetical value One-sample t test Wilcoxon test Chi-square
or
Binomial test **

Compare two unpaired groups Unpaired t test Mann-Whitney test Fisher's test
(chi-square for large samples)
Log-rank test or Mantel-Haenszel*
Compare two paired groups Paired t test Wilcoxon test McNemar's test Conditional proportional hazards regression*
Compare three or more unmatched groups One-way ANOVA Kruskal-Wallis test Chi-square test Cox proportional hazard regression**
Compare three or more matched groups Repeated-measures ANOVA Friedman test Cochrane Q** Conditional proportional hazards regression**
Quantify association between two variables Pearson correlation Spearman correlation Contingency coefficients**
Predict value from another measured variable Simple linear regression
or
Nonlinear regression
Nonparametric regression** Simple logistic regression* Cox proportional hazard regression*
Predict value from several measured or binomial variables Multiple linear regression*
or
Multiple nonlinear regression**

Multiple logistic regression* Cox proportional hazard regression*

REVIEW OF NONPARAMETRIC TESTS

Choosing the right test to compare measurements is a bit tricky, as you must choose between two families of tests: parametric and nonparametric. Many -statistical test are based upon the assumption that the data are sampled from a Gaussian distribution. These tests are referred to as parametric tests. Commonly used parametric tests are listed in the first column of the table and include the t test and analysis of variance.

Tests that do not make assumptions about the population distribution are referred to as nonparametric- tests. You've already learned a bit about nonparametric tests in previous chapters. All commonly used nonparametric tests rank the outcome variable from low to high and then analyze the ranks. These tests are listed in the second column of the table and include the Wilcoxon, Mann-Whitney test, and Kruskal-Wallis tests. These tests are also called distribution-free tests.

CHOOSING BETWEEN PARAMETRIC AND NONPARAMETRIC TESTS: THE EASY CASES

Choosing between parametric and nonparametric tests is sometimes easy. You should definitely choose a parametric test if you are sure that your data are sampled from a population that follows a Gaussian distribution (at least approximately). You should definitely select a nonparametric test in three situations:

    • The outcome is a rank or a score and the population is clearly not Gaussian. Examples include class ranking of students, the Apgar score for the health of newborn babies (measured on a scale of 0 to IO and where all scores are integers), the visual analogue score for pain (measured on a continuous scale where 0 is no pain and 10 is unbearable pain), and the star scale commonly used by movie and restaurant critics (* is OK, ***** is fantastic).
    • Some values are "off the scale," that is, too high or too low to measure. Even if the population is Gaussian, it is impossible to analyze such data with a parametric test since you don't know all of the values. Using a nonparametric test with these data is simple. Assign values too low to measure an arbitrary very low value and assign values too high to measure an arbitrary very high value. Then perform a nonparametric test. Since the nonparametric test only knows about the relative ranks of the values, it won't matter that you didn't know all the values exactly.
    • The data ire measurements, and you are sure that the population is not distributed in a Gaussian manner. If the data are not sampled from a Gaussian distribution, consider whether you can transformed the values to make the distribution become Gaussian. For example, you might take the logarithm or reciprocal of all values. There are often biological or chemical reasons (as well as statistical ones) for performing a particular transform.

CHOOSING BETWEEN PARAMETRIC AND NONPARAMETRIC TESTS: THE HARD CASES

It is not always easy to decide whether a sample comes from a Gaussian population. Consider these points:

    • If you collect many data points (over a hundred or so), you can look at the distribution of data and it will be fairly obvious whether the distribution is approximately bell shaped. A formal statistical test (Kolmogorov-Smirnoff test, not explained in this book) can be used to test whether the distribution of the data differs significantly from a Gaussian distribution. With few data points, it is difficult to tell whether the data are Gaussian by inspection, and the formal test has little power to discriminate between Gaussian and non-Gaussian distributions.
    • You should look at previous data as well. Remember, what matters is the distribution of the overall population, not the distribution of your sample. In deciding whether a population is Gaussian, look at all available data, not just data in the current experiment.
    • Consider the source of scatter. When the scatter comes from the sum of numerous sources (with no one source contributing most of the scatter), you expect to find a roughly Gaussian distribution.
    When in doubt, some people choose a parametric test (because they aren't sure the Gaussian assumption is violated), and others choose a nonparametric test (because they aren't sure the Gaussian assumption is met).

CHOOSING BETWEEN PARAMETRIC AND NONPARAMETRIC TESTS: DOES IT MATTER?

Does it matter whether you choose a parametric or nonparametric test? The answer depends on sample size. There are four cases to think about:

    • Large sample. What happens when you use a parametric test with data from a nongaussian population? The central limit theorem (discussed in Chapter 5) ensures that parametric tests work well with large samples even if the population is non-Gaussian. In other words, parametric tests are robust to deviations from Gaussian distributions, so long as the samples are large. The snag is that it is impossible to say how large is large enough, as it depends on the nature of the particular non-Gaussian distribution. Unless the population distribution is really weird, you are probably safe choosing a parametric test when there are at least two dozen data points in each group.
    • Large sample. What happens when you use a nonparametric test with data from a Gaussian population? Nonparametric tests work well with large samples from Gaussian populations. The P values tend to be a bit too large, but the discrepancy is small. In other words, nonparametric tests are only slightly less powerful than parametric tests with large samples.
    • Small samples. What happens when you use a parametric test with data from nongaussian populations? You can't rely on the central limit theorem, so the P value may be inaccurate.
    • Small samples. When you use a nonparametric test with data from a Gaussian population, the P values tend to be too high. The nonparametric tests lack statistical power with small samples.

Thus, large data sets present no problems. It is usually easy to tell if the data come from a Gaussian population, but it doesn't really matter because the nonparametric tests are so powerful and the parametric tests are so robust. Small data sets present a dilemma. It is difficult to tell if the data come from a Gaussian population, but it matters a lot. The nonparametric tests are not powerful and the parametric tests are not robust.

ONE- OR TWO-SIDED P VALUE?

With many tests, you must choose whether you wish to calculate a one- or two-sided P value (same as one- or two-tailed P value). The difference between one- and two-sided P values was discussed in Chapter 10. Let's review the difference in the context of a t test. The P value is calculated for the null hypothesis that the two population means are equal, and any discrepancy between the two sample means is due to chance. If this null hypothesis is true, the one-sided P value is the probability that two sample means would differ as much as was observed (or further) in the direction specified by the hypothesis just by chance, even though the means of the overall populations are actually equal. The two-sided P value also includes the probability that the sample means would differ that much in the opposite direction (i.e., the other group has the larger mean). The two-sided P value is twice the one-sided P value.

A one-sided P value is appropriate when you can state with certainty (and before collecting any data) that there either will be no difference between the means or that the difference will go in a direction you can specify in advance (i.e., you have specified which group will have the larger mean). If you cannot specify the direction of any difference before collecting data, then a two-sided P value is more appropriate. If in doubt, select a two-sided P value.

If you select a one-sided test, you should do so before collecting any data and you need to state the direction of your experimental hypothesis. If the data go the other way, you must be willing to attribute that difference (or association or correlation) to chance, no matter how striking the data. If you would be intrigued, even a little, by data that goes in the "wrong" direction, then you should use a two-sided P value. For reasons discussed in Chapter 10, I recommend that you always calculate a two-sided P value.

PAIRED OR UNPAIRED TEST?

When comparing two groups, you need to decide whether to use a paired test. When comparing three or more groups, the term paired is not apt and the term repeated measures is used instead.

Use an unpaired test to compare groups when the individual values are not paired or matched with one another. Select a paired or repeated-measures test when values represent repeated measurements on one subject (before and after an intervention) or measurements on matched subjects. The paired or repeated-measures tests are also appropriate for repeated laboratory experiments run at different times, each with its own control.

You should select a paired test when values in one group are more closely correlated with a specific value in the other group than with random values in the other group. It is only appropriate to select a paired test when the subjects were matched or paired before the data were collected. You cannot base the pairing on the data you are analyzing.

FISHER'S TEST OR THE CHI-SQUARE TEST?

When analyzing contingency tables with two rows and two columns, you can use either Fisher's exact test or the chi-square test. The Fisher's test is the best choice as it always gives the exact P value. The chi-square test is simpler to calculate but yields only an approximate P value. If a computer is doing the calculations, you should choose Fisher's test unless you prefer the familiarity of the chi-square test. You should definitely avoid the chi-square test when the numbers in the contingency table are very small (any number less than about six). When the numbers are larger, the P values reported by the chi-square and Fisher's test will he very similar.

The chi-square test calculates approximate P values, and the Yates' continuity correction is designed to make the approximation better. Without the Yates' correction, the P values are too low. However, the correction goes too far, and the resulting P value is too high. Statisticians give different recommendations regarding Yates' correction. With large sample sizes, the Yates' correction makes little difference. If you select Fisher's test, the P value is exact and Yates' correction is not needed and is not available.

REGRESSION OR CORRELATION?

Linear regression and correlation are similar and easily confused. In some situations it makes sense to perform both calculations. Calculate linear correlation if you measured both X and Y in each subject and wish to quantity how well they are associated. Select the Pearson (parametric) correlation coefficient if you can assume that both X and Y are sampled from Gaussian populations. Otherwise choose the Spearman nonparametric correlation coefficient. Don't calculate the correlation coefficient (or its confidence interval) if you manipulated the X variable.

Calculate linear regressions only if one of the variables (X) is likely to precede or cause the other variable (Y). Definitely choose linear regression if you manipulated the X variable. It makes a big difference which variable is called X and which is called Y, as linear regression calculations are not symmetrical with respect to X and Y. If you swap the two variables, you will obtain a different regression line. In contrast, linear correlation calculations are symmetrical with respect to X and Y. If you swap the labels X and Y, you will still get the same correlation coefficient.

Statistical Data Analysis: Elementary Concepts

Understanding Statistical Inference

Statistical inference is based upon mathematical laws of probability. The following example will give you the basic ideas.

Statistical Inference & The Coin Toss

Suppose we want to do a few coin tosses (sample) so that we can decide if a particular coin is equally likely to land head or tail over an infinite number of tosses (population).

If we toss the coin ten times and get 6 heads and 4 tails, we might suspect the coin is biased towards heads, but we wouldn't be very confident about this, because it's not that unusual (not that improbable) to get 6 heads out of 10.

On the other hand, if we toss the coin ten times and get 10 heads - we would be more confident that the coin is biased towards heads, because it is very unusual (not very probable at all) that we would get this result from an unbiased coin.

Statistical Data Analysis: Hypothesis Testing

The most common kind of statistical inference is hypothesis testing. Statistical data analysis allows us to use mathematical principles to decide how likely it is that our sample results match our hypothesis about a population. For example, if our research hypothesis is that the coin is not fair, but is actually biased towards heads - we can use principles of statistics to tell us how likely it is that we could get our sample results even if the coin were fair after all (null hypothesis).

If the probability of getting our sample results from a fair coin is very low, we feel confident in rejecting the null hypothesis (that the coin is fair). Even though we can't say for sure (because even a fair coin could produce our sample results), we can say that the results of our study support the hypothesis that the coin is indeed biased.

When we make this decision based on statistical data analysis, this is statistical inference.

Statistical Data Analysis: p-value

In statistical hypothesis testing we use a p-value (probability value) to decide whether we have enough evidence to reject the null hypothesis and say our research hypothesis is supported by the data.

The p-value is a numerical statement of how likely it is that we could have gotten our sample data (e.g., 10 heads) even if the null hypothesis is true (e.g., fair coin). By convention, if the p-value is less than 0.05 (p <>

KOLMOGOROV SMIRNOV Test (TWO SAMPLE) II

Purpose:
    Perform a Kolmogorov-Smirnov two sample test that two data samples come from the same distribution. Note that we are not specifying what that common distribution is.
Description: The one sample Kolmogorov-Smirnov (K-S) test is based on the empirical distribution function (ECDF). Given N data points Y1 Y2 ..., YN the ECDF is defined as

    E(i) = n(i)/N

where n(i) is the number of points less than Yi This is a step function that increases by 1/N at the value of each data point. We can graph a plot of the empirical distribution function with a cumulative distribution function for a given distribution. The one sample K-S test is based on the maximum distance between these two curves. That is,

    D = max |F(Y(i)) - E(i)|

where F is the theoretical cumulative distribution function.

The two sample K-S test is a variation of this. However, instead of comparing an empirical distribution function to a theoretical distribution function, we compare the two empirical distribution functions. That is,

    D = max |E1(i) - E2(i)|

where E1 and E2 are the empirical distribution functions for the two samples. Note that we compute E1 and E2 at each point in both samples (that is both E1 and E2 are computed at each point in each sample).

More formally, the Kolmogorov-Smirnov two sample test statistic can be defined as follows.

H0: The two samples come from a common distribution.
Ha: The two samples do not come from a common distribution.
Test Statistic: The Kolmogorov-Smirnov two sample test statistic is defined as

    D = max |E1(i) - E2(i)|

where E1 and E2 are the empirical distribution functions for the two samples.

Significance Level: alpha
Critical Region: The hypothesis regarding the distributional form is rejected if the test statistic, D, is greater than the critical value obtained from a table. There are several variations of these tables in the literature that use somewhat different scalings for the K-S test statistic and critical regions. These alternative formulations should be equivalent, but it is necessary to ensure that the test statistic is calculated in a way that is consistent with how the critical values were tabulated.

Wednesday, 29 August 2007

Kolmogorov-Smirnov test (One Sample) I

the Kolmogorov–Smirnov test (often called the K-S test) is used to determine whether two underlying one-dimensional

probability distributions differ, or whether an underlying probability distribution differs from a hypothesized distribution, in either case based on finite samples.

The one-sample KS test compares the empirical distribution function with the cumulative distribution function specified by the null hypothesis. The main applications are testing goodness of fit with the normal and uniform distributions. For normality testing, minor improvements made by Lilliefors lead to the Lilliefors test. In general the Shapiro-Wilk test or Anderson-Darling test are more powerful alternatives to the Lilliefors test for testing normality[citation needed].

The two-sample KS test is one of the most useful and general nonparametric methods for comparing two samples, as it is sensitive to differences in both location and shape of the empirical cumulative distribution functions of the two samples.

1. One-Sample

1. Introduction

A test for goodness of fit usually involves examining a random sample from some unknown distribution in order to test the null hypothesis that the unknown distribution function is in fact a known, specified function.

We usually use Kolmogorov-Smirnov test to check the normality assumption in Analysis of Variance.

A random sample X1,X2, . . . , Xn is drawn from some population and is compared with F∗(x) in some way to see if it is reasonable to say that F∗(x) is the true distribution function of the random sample.

One logical way of comparing the random sample with F∗(x) is by means of the empirical distribution function S(x)

2. Definition

Let X1,X2, . . . , Xn be a random sample. The empirical distribution function S(x) is a function of x, which equals the fraction of Xis that are less than or equal to x for each x, −∞<x<∞, i.e:

The empirical distribution function S(x) is useful as an estimator of F(x), the unknown distribution function of the Xis.

We can compare the empirical distribution function S(x) with hypothesized distribution function F∗(x) to see if there is good agreement.

One of the simplest measures is the largest distance between the two functions S(x) and F∗(x), measured in a vertical direction. This is the statistic suggested by Kolmogorov (1933).

3. Kolmogorov-Smirnov test (K-S test)

The data consist of a random sample X1,X2, . . . , Xn of size n associated with some unknown distribution function,denoted by F(x).

The sample is a random sample.

Let S(x) be the empirical distribution function based on the random sample X1,X2, . . . , Xn. Let F∗(x) be a completely specified hypothesized distribution function.

Let the test statistic T be the greatest (denoted by ”sup” for supremum) vertical distance between S(x) and F∗(x).In symbols we say

For testing

H0 : F(x) = F∗(x) for all x from −∞ to ∞

H1 : F(x) <> F∗(x) for at least one value of x

If T exceeds the 1-αquantile as given by Table then we reject H0 at the level of significance α. The approximate p-value can be found by interpolation in Table.

4. Example

A random sample of size 10 is obtained: X1 = 0.621,X2 = 0.503,X3 =0.203,X4 = 0.477,X5 = 0.710,X6 = 0.581,X7 = 0.329,X8 = 0.480,X9 =0.554,X10 = 0.382.The null hypothesis is that the distribution function is the uniform distribution function whose graph in Figure 1.The mathematical expression for the hypothesized distribution function is

Formally, the hypotheses are given by

H0 : F(x) = F∗(x) for all x from −∞ to ∞

H1 : F(x) _= F∗(x) for at least one value of x

where F(x) is the unknown distribution function common to the Xis and F∗(x) is given by above equation.

The Kolmogorov test for goodness of fit is used. The critical region of size α= 0.05 corresponds to values of T greater than the 0.95 quantile 0.409, obtained from Table for n=10.

The value of T is obtained by graphing the empirical distribution function S(x) on the top of the hypothesized distribution function F∗(x),as shown in Figure 2.The largest vertical distance separating the two graphs in Figure 2 is 0.290, which occurs at x = 0.710 because S(0.710) = 1.000 and F∗(0.710) = 0.710. In other words

Since T=0.290 is less than 0.409, the null hypothesis is accepted. The p-value is seen, from Table, to be larger than 0.20.