idx
int64
1
56k
question
stringlengths
15
155
answer
stringlengths
2
29.2k
question_cut
stringlengths
15
100
answer_cut
stringlengths
2
200
conversation
stringlengths
47
29.3k
conversation_cut
stringlengths
47
301
13,101
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ
This is a situation in which I like using path diagrams to illustrate direct effects and indirect effects, and how those two impact the overall correlations. Per the original description we have a correlation matrix below. Brain size has around a 0.3 correlation with IQ, female and IQ have a 0 correlation with each other. I fill in the negative correlation between female and brain size to be -0.3 (if I had to guess it is much smaller than that, but this will serve for illustration purposes). Brain Female IQ Brain 1 Female -0.3 1 IQ 0.3 0 1 If we fit a regression model where IQ is a function of brain size and being female we can illustrate this in terms of a path diagram. I have filled in the partial regression coefficients on the arrows, and the B node stands for brain size and the F node stands for female. Now how crazy is that -- when controlling for brain size, given these correlations, female's have a positive relationship with IQ. Why is this, when the marginal correlation is zero? Per rules with linear path diagrams (Wright, 1934), we can decompose the marginal correlation as a function of the direct effect when controlling for brain size and the indirect effect: $$\text{Total}_{\text{F},\text{IQ}} = \text{Direct}_{\text{F},\text{IQ}} + \text{Indirect}_{\text{F},\text{B},\text{IQ}}$$ In this notation $\text{Total}_{\text{F},\text{IQ}} = \text{Cor}(\text{F},\text{IQ})$. So per the original definition we know this total effect to be zero. So now we just need to figure out the direct effect and the indirect effect. The indirect effect in this diagram is simply following the other arrow from females to IQ through brain size, which is the correlation of females and brain size multiplied by the partial correlation of brain size and IQ. \begin{align} \text{Indirect}_{\text{F},\text{B},\text{IQ}} &= \text{Cor}(\text{F},\text{B}) \cdot \text{Cor}(\text{B},\text{IQ}|\text{F}) \\ -0.099 &= -0.3 \cdot 0.33 \end{align} Because the total effect is zero, we know that the direct effect must simply be the exact opposite sign and size of the indirect effect, hence the direct effect equals 0.099 in this example. Now, here we have a situation when assessing the expected IQ of females we get two different answers, although probably not what you initially expected when specifying the question. When simply assessing the marginal expected IQ of females versus males, the difference is zero as you defined it (by having a zero correlation). When assessing the expected difference conditional on brain size, females have a larger IQ than males. You can insert into this example either larger correlations between brain size and IQ (or smaller correlations between female and brain size), given the limits kjetil shows in his answer. Increasing the former makes the disparity between the conditional IQ of women and men even greater in favor of women, decreasing the latter makes the differences smaller.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a
This is a situation in which I like using path diagrams to illustrate direct effects and indirect effects, and how those two impact the overall correlations. Per the original description we have a cor
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ This is a situation in which I like using path diagrams to illustrate direct effects and indirect effects, and how those two impact the overall correlations. Per the original description we have a correlation matrix below. Brain size has around a 0.3 correlation with IQ, female and IQ have a 0 correlation with each other. I fill in the negative correlation between female and brain size to be -0.3 (if I had to guess it is much smaller than that, but this will serve for illustration purposes). Brain Female IQ Brain 1 Female -0.3 1 IQ 0.3 0 1 If we fit a regression model where IQ is a function of brain size and being female we can illustrate this in terms of a path diagram. I have filled in the partial regression coefficients on the arrows, and the B node stands for brain size and the F node stands for female. Now how crazy is that -- when controlling for brain size, given these correlations, female's have a positive relationship with IQ. Why is this, when the marginal correlation is zero? Per rules with linear path diagrams (Wright, 1934), we can decompose the marginal correlation as a function of the direct effect when controlling for brain size and the indirect effect: $$\text{Total}_{\text{F},\text{IQ}} = \text{Direct}_{\text{F},\text{IQ}} + \text{Indirect}_{\text{F},\text{B},\text{IQ}}$$ In this notation $\text{Total}_{\text{F},\text{IQ}} = \text{Cor}(\text{F},\text{IQ})$. So per the original definition we know this total effect to be zero. So now we just need to figure out the direct effect and the indirect effect. The indirect effect in this diagram is simply following the other arrow from females to IQ through brain size, which is the correlation of females and brain size multiplied by the partial correlation of brain size and IQ. \begin{align} \text{Indirect}_{\text{F},\text{B},\text{IQ}} &= \text{Cor}(\text{F},\text{B}) \cdot \text{Cor}(\text{B},\text{IQ}|\text{F}) \\ -0.099 &= -0.3 \cdot 0.33 \end{align} Because the total effect is zero, we know that the direct effect must simply be the exact opposite sign and size of the indirect effect, hence the direct effect equals 0.099 in this example. Now, here we have a situation when assessing the expected IQ of females we get two different answers, although probably not what you initially expected when specifying the question. When simply assessing the marginal expected IQ of females versus males, the difference is zero as you defined it (by having a zero correlation). When assessing the expected difference conditional on brain size, females have a larger IQ than males. You can insert into this example either larger correlations between brain size and IQ (or smaller correlations between female and brain size), given the limits kjetil shows in his answer. Increasing the former makes the disparity between the conditional IQ of women and men even greater in favor of women, decreasing the latter makes the differences smaller.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a This is a situation in which I like using path diagrams to illustrate direct effects and indirect effects, and how those two impact the overall correlations. Per the original description we have a cor
13,102
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ
To provide the purely abstract mathematical answer, denote $v$ the brain volume and $q$ the IQ index. Use $1$ to index men and $2$ to index women. Let's assume that the following are facts: $$E(v_1) > E(v_2) = \beta E(v_1), 0< \beta <1, \;\; \rho(v_1,q_1) >0, \;\; \rho(v_2,q_2)>0 \tag{1}$$ Note that while the quoted text talks about "correlation between brain volume and IQ" in general, the supplied image makes a distinction with the two trend-lines (i.e. it shows the correlation for the two subgroups separately). So we consider them separately (which is the correct way to go). Then $$\rho(v_1,q_1) >0 \Rightarrow {\rm Cov}(v_1,q_1)>0 \Rightarrow E(v_1q_1) > E(v_1)E(q_1)$$ $$\Rightarrow \frac {E(v_1q_1)}{E(q_1)} > E(v_1) \tag{2}$$ and $$\rho(v_2,q_2) >0 \Rightarrow {\rm Cov}(v_2,q_2)>0 \Rightarrow E(v_2q_2) > E(v_2)E(q_2)$$ $$\Rightarrow \frac {E(v_2q_2)}{\beta E(q_2)} > E(v_1) \tag{3}$$ Does the above obtained inequalities necessitate $E(q_1) > E(q_2)$?? To check this assume on the contrary that $E(q_1) = E(q_2) = \bar q \tag {4}$ Then it must be the case that $$(2),(4) \Rightarrow \frac {E(v_1q_1)}{\bar q} > E(v_1) \tag{5}$$ and that $$(3),(4) \Rightarrow \frac {E(v_2q_2)}{\beta \bar q} > E(v_1) \tag{6}$$ Well, it certainly can be the case, that inequalities $(5)$ and $(6)$ hold at the same time, and so "equal IQ on average" is perfectly compatible with the initial assumptions that we took as facts. In fact it could very well happen that we could have a higher average IQ from women than for men, for the same set of facts in $(1)$. In other words, the correlation assumptions/facts in $(1)$ do not impose any constraint whatsoever about the relation between average IQ's at all. All possible relation between $E(q_1)$ and $E(q_2)$ may hold, and be compatible with the assumptions in $(1)$.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a
To provide the purely abstract mathematical answer, denote $v$ the brain volume and $q$ the IQ index. Use $1$ to index men and $2$ to index women. Let's assume that the following are facts: $$E(v_1)
Non-transitivity of correlation: correlations between gender and brain size and between brain size and IQ, but no correlation between gender and IQ To provide the purely abstract mathematical answer, denote $v$ the brain volume and $q$ the IQ index. Use $1$ to index men and $2$ to index women. Let's assume that the following are facts: $$E(v_1) > E(v_2) = \beta E(v_1), 0< \beta <1, \;\; \rho(v_1,q_1) >0, \;\; \rho(v_2,q_2)>0 \tag{1}$$ Note that while the quoted text talks about "correlation between brain volume and IQ" in general, the supplied image makes a distinction with the two trend-lines (i.e. it shows the correlation for the two subgroups separately). So we consider them separately (which is the correct way to go). Then $$\rho(v_1,q_1) >0 \Rightarrow {\rm Cov}(v_1,q_1)>0 \Rightarrow E(v_1q_1) > E(v_1)E(q_1)$$ $$\Rightarrow \frac {E(v_1q_1)}{E(q_1)} > E(v_1) \tag{2}$$ and $$\rho(v_2,q_2) >0 \Rightarrow {\rm Cov}(v_2,q_2)>0 \Rightarrow E(v_2q_2) > E(v_2)E(q_2)$$ $$\Rightarrow \frac {E(v_2q_2)}{\beta E(q_2)} > E(v_1) \tag{3}$$ Does the above obtained inequalities necessitate $E(q_1) > E(q_2)$?? To check this assume on the contrary that $E(q_1) = E(q_2) = \bar q \tag {4}$ Then it must be the case that $$(2),(4) \Rightarrow \frac {E(v_1q_1)}{\bar q} > E(v_1) \tag{5}$$ and that $$(3),(4) \Rightarrow \frac {E(v_2q_2)}{\beta \bar q} > E(v_1) \tag{6}$$ Well, it certainly can be the case, that inequalities $(5)$ and $(6)$ hold at the same time, and so "equal IQ on average" is perfectly compatible with the initial assumptions that we took as facts. In fact it could very well happen that we could have a higher average IQ from women than for men, for the same set of facts in $(1)$. In other words, the correlation assumptions/facts in $(1)$ do not impose any constraint whatsoever about the relation between average IQ's at all. All possible relation between $E(q_1)$ and $E(q_2)$ may hold, and be compatible with the assumptions in $(1)$.
Non-transitivity of correlation: correlations between gender and brain size and between brain size a To provide the purely abstract mathematical answer, denote $v$ the brain volume and $q$ the IQ index. Use $1$ to index men and $2$ to index women. Let's assume that the following are facts: $$E(v_1)
13,103
Should I use t-test on highly skewed data ? Scientific proof, please?
I wouldn't call 'exponential' particularly highly skew. Its log is distinctly left-skew, for example, and its moment-skewness is only 2. 1) Using the t-test with exponential data and $n$ near 500 is fine: a) The numerator of the test statistic should be fine: If the data are independent exponential with common scale (and not substantially heavier-tailed than that), then their averages are gamma-distributed with shape parameter equal to the number of observations. Its distribution looks very normal for shape parameter greater than about 40 or so (depending on how far out into the tail you need accuracy). This is capable of mathematical proof, but mathematics is not science. You can check it empirically via simulation, of course, but if you're wrong about the exponentiality you may need larger samples. This is what the distribution of sample sums (and hence, sample means) of exponential data look like when n=40: Very slightly skew. This skewness decreases as the square root of the sample size. So at n=160, it's half as skew. At n=640 it's one quarter as skew: That this is effectively symmetric can be seen by flipping it over about the mean and plotting it over the top: Blue is the original, red is flipped. As you see, they're almost coincidental. - b) Even more importantly, the difference of two such gamma-distributed variables (such as you'd get with means of exponentials) is more nearly normal, and under the null (which is where you need it) the skewness will be zero. Here's that for $n=40$: That is, the numerator of the t-statistic is very close to normal at far smaller sample sizes than $n=500$. - c) What really matters, however, is the distribution of the entire statistic under the null. Normality of the numerator is not sufficient to make the t-statistic have a t-distribution. However, in the exponential-data case, that's also not much of a problem: The red curve is the distribution of the t-statistic with df=78, the histogram is what using the Welch t-test on exponential samples gets you (under the null of equal mean; the actual Welch-Satterthwaite degrees-of-freedom in a given sample will tend to be a little smaller than 78). In particular, the tail areas in the region of your significance level should be similar (unless you have some very unusual significance levels, they are). Remember, this is at $n=40$, not $n=500$. It's much better at $n=500$. Note, however, that for actually exponential data, the standard deviation will only be different if the means are different. If the exponential presumption is the case, then under the null, there's no particular need to worry about different population variances, since they only occur under the alternative. So a equal-variance t-test should still be okay (in which case the above good approximation you see in the histogram may even be slightly better). 2) Taking logs may still allow you to make sense of it, though If the null is true, and you have exponential distributions, you're testing equality of the scale parameters. Location-testing the means of the logs will test equality of logs of the scale parameters against a location shift alternative in the logs (change of scale in the original values). If you conclude that $\log\lambda_1\neq\log\lambda_2$ in a location test in the logs, that's logically the same as concluding that $\lambda_1\neq\lambda_2$. So testing the logs with a t-test works perfectly well as a test of the original hypothesis. [If you do that test in the logs, I'd be inclined to suggest doing an equal-variance test in that case.] So - with the mere intervention of perhaps a sentence or two justifying the connection, similar to what I have above - you should be able write your conclusions not about the log of the participation metric, but about the participation metric itself. 3) There's plenty of other things you can do! a) you can do a test suitable for exponential data. It's easy to derive a likelihood ratio based test. As it happens, for exponential data you get a small-sample F-test (based off a ratio of means) for this situation in the one tailed case; the two tailed LRT would not generally have an equal proportion in each tail for small sample sizes. (This should have better power than the t-test, but the power for the t-test should be quite reasonable, and I'd expect there not to be much difference at your sample sizes.) b) you can do a permutation-test - even base it on the t-test if you like. So the only thing that changes is the computation of the p-value. Or you might do some other resampling test such as a bootstrap-based test. This should have good power, though it will depend partly on what test statistic you choose relative to the distribution you have. c) you can do a rank-based nonparametric test (such as the Wilcoxon-Mann-Whitney). If you assume that if the distributions differ, then they differ only by a scale factor (appropriate for a variety of skewed distributions including the exponential), then you can even obtain a confidence interval for the ratio of the scale parameters. [For that purpose, I'd suggest working on the log-scale (the location shift in the logs being the log of the scale shift). It won't change the p-value, but it will allow you to exponentiate the point estimate and the CI limits to obtain an interval for the scale shift.] This, too, should tend to have pretty good power if you're in the exponential situation, but likely not as good as using the t-test. A reference which considers a considerably broader set of cases for the location shift alternative (with both variance and skewness heterogeneity under the null, for example) is Fagerland, M.W. and L. Sandvik (2009), "Performance of five two-sample location tests for skewed distributions with unequal variances," Contemporary Clinical Trials, 30, 490–496 It generally tends to recommend the Welch U-test (a particular one of the several tests considered by Welch and the only one they tested). If you're not using exactly the same Welch statistic the recommendations may vary somewhat (though probably not by much). [Note that if your distributions are exponential you're interested in a scale alternative unless you take logs ... in which case you won't have unequal variances.]
Should I use t-test on highly skewed data ? Scientific proof, please?
I wouldn't call 'exponential' particularly highly skew. Its log is distinctly left-skew, for example, and its moment-skewness is only 2. 1) Using the t-test with exponential data and $n$ near 500 is f
Should I use t-test on highly skewed data ? Scientific proof, please? I wouldn't call 'exponential' particularly highly skew. Its log is distinctly left-skew, for example, and its moment-skewness is only 2. 1) Using the t-test with exponential data and $n$ near 500 is fine: a) The numerator of the test statistic should be fine: If the data are independent exponential with common scale (and not substantially heavier-tailed than that), then their averages are gamma-distributed with shape parameter equal to the number of observations. Its distribution looks very normal for shape parameter greater than about 40 or so (depending on how far out into the tail you need accuracy). This is capable of mathematical proof, but mathematics is not science. You can check it empirically via simulation, of course, but if you're wrong about the exponentiality you may need larger samples. This is what the distribution of sample sums (and hence, sample means) of exponential data look like when n=40: Very slightly skew. This skewness decreases as the square root of the sample size. So at n=160, it's half as skew. At n=640 it's one quarter as skew: That this is effectively symmetric can be seen by flipping it over about the mean and plotting it over the top: Blue is the original, red is flipped. As you see, they're almost coincidental. - b) Even more importantly, the difference of two such gamma-distributed variables (such as you'd get with means of exponentials) is more nearly normal, and under the null (which is where you need it) the skewness will be zero. Here's that for $n=40$: That is, the numerator of the t-statistic is very close to normal at far smaller sample sizes than $n=500$. - c) What really matters, however, is the distribution of the entire statistic under the null. Normality of the numerator is not sufficient to make the t-statistic have a t-distribution. However, in the exponential-data case, that's also not much of a problem: The red curve is the distribution of the t-statistic with df=78, the histogram is what using the Welch t-test on exponential samples gets you (under the null of equal mean; the actual Welch-Satterthwaite degrees-of-freedom in a given sample will tend to be a little smaller than 78). In particular, the tail areas in the region of your significance level should be similar (unless you have some very unusual significance levels, they are). Remember, this is at $n=40$, not $n=500$. It's much better at $n=500$. Note, however, that for actually exponential data, the standard deviation will only be different if the means are different. If the exponential presumption is the case, then under the null, there's no particular need to worry about different population variances, since they only occur under the alternative. So a equal-variance t-test should still be okay (in which case the above good approximation you see in the histogram may even be slightly better). 2) Taking logs may still allow you to make sense of it, though If the null is true, and you have exponential distributions, you're testing equality of the scale parameters. Location-testing the means of the logs will test equality of logs of the scale parameters against a location shift alternative in the logs (change of scale in the original values). If you conclude that $\log\lambda_1\neq\log\lambda_2$ in a location test in the logs, that's logically the same as concluding that $\lambda_1\neq\lambda_2$. So testing the logs with a t-test works perfectly well as a test of the original hypothesis. [If you do that test in the logs, I'd be inclined to suggest doing an equal-variance test in that case.] So - with the mere intervention of perhaps a sentence or two justifying the connection, similar to what I have above - you should be able write your conclusions not about the log of the participation metric, but about the participation metric itself. 3) There's plenty of other things you can do! a) you can do a test suitable for exponential data. It's easy to derive a likelihood ratio based test. As it happens, for exponential data you get a small-sample F-test (based off a ratio of means) for this situation in the one tailed case; the two tailed LRT would not generally have an equal proportion in each tail for small sample sizes. (This should have better power than the t-test, but the power for the t-test should be quite reasonable, and I'd expect there not to be much difference at your sample sizes.) b) you can do a permutation-test - even base it on the t-test if you like. So the only thing that changes is the computation of the p-value. Or you might do some other resampling test such as a bootstrap-based test. This should have good power, though it will depend partly on what test statistic you choose relative to the distribution you have. c) you can do a rank-based nonparametric test (such as the Wilcoxon-Mann-Whitney). If you assume that if the distributions differ, then they differ only by a scale factor (appropriate for a variety of skewed distributions including the exponential), then you can even obtain a confidence interval for the ratio of the scale parameters. [For that purpose, I'd suggest working on the log-scale (the location shift in the logs being the log of the scale shift). It won't change the p-value, but it will allow you to exponentiate the point estimate and the CI limits to obtain an interval for the scale shift.] This, too, should tend to have pretty good power if you're in the exponential situation, but likely not as good as using the t-test. A reference which considers a considerably broader set of cases for the location shift alternative (with both variance and skewness heterogeneity under the null, for example) is Fagerland, M.W. and L. Sandvik (2009), "Performance of five two-sample location tests for skewed distributions with unequal variances," Contemporary Clinical Trials, 30, 490–496 It generally tends to recommend the Welch U-test (a particular one of the several tests considered by Welch and the only one they tested). If you're not using exactly the same Welch statistic the recommendations may vary somewhat (though probably not by much). [Note that if your distributions are exponential you're interested in a scale alternative unless you take logs ... in which case you won't have unequal variances.]
Should I use t-test on highly skewed data ? Scientific proof, please? I wouldn't call 'exponential' particularly highly skew. Its log is distinctly left-skew, for example, and its moment-skewness is only 2. 1) Using the t-test with exponential data and $n$ near 500 is f
13,104
Why does the t-distribution become more normal as sample size increases?
I'll try to give an intuitive explanation. The t-statistic* has a numerator and a denominator. For example, the statistic in the one sample t-test is $$\frac{\bar{x}-\mu_0}{s/\sqrt{n}}$$ *(there are several, but this discussion should hopefully be general enough to cover the ones you are asking about) Under the assumptions, the numerator has a normal distribution with mean 0 and some unknown standard deviation. Under the same set of assumptions, the denominator is an estimate of the standard deviation of the distribution of the numerator (the standard error of the statistic on the numerator). It is independent of the numerator. Its square is a chi-square random variable divided by its degrees of freedom (which is also the d.f. of the t-distribution) times $\sigma_\text{numerator}$. When the degrees of freedom are small, the denominator tends to be fairly right-skew. It has a high chance of being less than its mean, and a relatively good chance of being quite small. At the same time, it also has some chance of being much, much larger than its mean. Under the assumption of normality, the numerator and denominator are independent. So if we draw randomly from the distribution of this t-statistic we have a normal random number divided by a second randomly* chosen value from a right-skew distribution that's on average around 1. * without regard to the normal term Because it's on the denominator, the small values in the distribution of the denominator produce very large t-values. The right-skew in the denominator make the t-statistic heavy-tailed. The right tail of the distribution, when on the denominator makes the t-distribution more sharply peaked than a normal with the same standard deviation as the t. However, as the degrees of freedom become large, the distribution becomes much more normal-looking and much more "tight" around its mean. As such, the effect of dividing by the denominator on the shape of the distribution of the numerator reduces as the degrees of freedom increase. Eventually - as Slutsky's theorem might suggest to us could happen - the effect of the denominator becomes more like dividing by a constant and the distribution of the t-statistic is very close to normal. Considered in terms of the reciprocal of the denominator whuber suggested in comments that it might be more illuminating to look at the reciprocal of the denominator. That is, we could write our t-statistics as numerator (normal) times reciprocal-of-denominator (right-skew). For example, our one-sample-t statistic above would become: $${\sqrt{n}(\bar{x}-\mu_0)}\cdot{1/s}$$ Now consider the population standard deviation of the original $X_i$, $\sigma_x$. We can multiply and divide by it, like so: $${\sqrt{n}(\bar{x}-\mu_0)/\sigma_x}\cdot{\sigma_x/s}$$ The first term is standard normal. The second term (the square root of a scaled inverse-chi-squared random variable) then scales that standard normal by values that are either larger or smaller than 1, "spreading it out". Under the assumption of normality, the two terms in the product are independent. So if we draw randomly from the distribution of this t-statistic we have a normal random number (the first term in the product) times a second randomly-chosen value (without regard to the normal term) from a right-skew distribution that's 'typically' around 1. When the d.f. are large, the value tends to be very close to 1, but when the df are small, it's quite skew and the spread is large, with the big right tail of this scaling factor making the tail quite fat:
Why does the t-distribution become more normal as sample size increases?
I'll try to give an intuitive explanation. The t-statistic* has a numerator and a denominator. For example, the statistic in the one sample t-test is $$\frac{\bar{x}-\mu_0}{s/\sqrt{n}}$$ *(there are
Why does the t-distribution become more normal as sample size increases? I'll try to give an intuitive explanation. The t-statistic* has a numerator and a denominator. For example, the statistic in the one sample t-test is $$\frac{\bar{x}-\mu_0}{s/\sqrt{n}}$$ *(there are several, but this discussion should hopefully be general enough to cover the ones you are asking about) Under the assumptions, the numerator has a normal distribution with mean 0 and some unknown standard deviation. Under the same set of assumptions, the denominator is an estimate of the standard deviation of the distribution of the numerator (the standard error of the statistic on the numerator). It is independent of the numerator. Its square is a chi-square random variable divided by its degrees of freedom (which is also the d.f. of the t-distribution) times $\sigma_\text{numerator}$. When the degrees of freedom are small, the denominator tends to be fairly right-skew. It has a high chance of being less than its mean, and a relatively good chance of being quite small. At the same time, it also has some chance of being much, much larger than its mean. Under the assumption of normality, the numerator and denominator are independent. So if we draw randomly from the distribution of this t-statistic we have a normal random number divided by a second randomly* chosen value from a right-skew distribution that's on average around 1. * without regard to the normal term Because it's on the denominator, the small values in the distribution of the denominator produce very large t-values. The right-skew in the denominator make the t-statistic heavy-tailed. The right tail of the distribution, when on the denominator makes the t-distribution more sharply peaked than a normal with the same standard deviation as the t. However, as the degrees of freedom become large, the distribution becomes much more normal-looking and much more "tight" around its mean. As such, the effect of dividing by the denominator on the shape of the distribution of the numerator reduces as the degrees of freedom increase. Eventually - as Slutsky's theorem might suggest to us could happen - the effect of the denominator becomes more like dividing by a constant and the distribution of the t-statistic is very close to normal. Considered in terms of the reciprocal of the denominator whuber suggested in comments that it might be more illuminating to look at the reciprocal of the denominator. That is, we could write our t-statistics as numerator (normal) times reciprocal-of-denominator (right-skew). For example, our one-sample-t statistic above would become: $${\sqrt{n}(\bar{x}-\mu_0)}\cdot{1/s}$$ Now consider the population standard deviation of the original $X_i$, $\sigma_x$. We can multiply and divide by it, like so: $${\sqrt{n}(\bar{x}-\mu_0)/\sigma_x}\cdot{\sigma_x/s}$$ The first term is standard normal. The second term (the square root of a scaled inverse-chi-squared random variable) then scales that standard normal by values that are either larger or smaller than 1, "spreading it out". Under the assumption of normality, the two terms in the product are independent. So if we draw randomly from the distribution of this t-statistic we have a normal random number (the first term in the product) times a second randomly-chosen value (without regard to the normal term) from a right-skew distribution that's 'typically' around 1. When the d.f. are large, the value tends to be very close to 1, but when the df are small, it's quite skew and the spread is large, with the big right tail of this scaling factor making the tail quite fat:
Why does the t-distribution become more normal as sample size increases? I'll try to give an intuitive explanation. The t-statistic* has a numerator and a denominator. For example, the statistic in the one sample t-test is $$\frac{\bar{x}-\mu_0}{s/\sqrt{n}}$$ *(there are
13,105
Why does the t-distribution become more normal as sample size increases?
@Glen_b gave you the intuition on why the t statistic looks more normal as the sample size increases. Now, I will give you a slightly more technical explanation for the case when you already got the distribution of the statistic. It is well-known that the t-statistic is distributed as a student t dsitribution with $n-1$ degrees of freedom, where $n$ is the sample size. The corresponding density looks as follows: $$\frac{\left(1+\frac{x^2}{n-1}\right)^{-n/2}}{\sqrt{n-1} B\left(\frac{n-1}{2},\frac{1}{2}\right)}.$$ It is possible to show that $$\frac{1}{\sqrt{n-1} B\left(\frac{n-1}{2},\frac{1}{2}\right)}\rightarrow \frac{1}{\sqrt{2\pi}},$$ and $$\left(1+\frac{x^2}{n-1}\right)^{-n/2}\rightarrow \exp(-x^2/2),$$ as $n\rightarrow \infty$. By taking the product of these two limits you can see that the Student-t density converges exactly to the standard normal density.
Why does the t-distribution become more normal as sample size increases?
@Glen_b gave you the intuition on why the t statistic looks more normal as the sample size increases. Now, I will give you a slightly more technical explanation for the case when you already got the d
Why does the t-distribution become more normal as sample size increases? @Glen_b gave you the intuition on why the t statistic looks more normal as the sample size increases. Now, I will give you a slightly more technical explanation for the case when you already got the distribution of the statistic. It is well-known that the t-statistic is distributed as a student t dsitribution with $n-1$ degrees of freedom, where $n$ is the sample size. The corresponding density looks as follows: $$\frac{\left(1+\frac{x^2}{n-1}\right)^{-n/2}}{\sqrt{n-1} B\left(\frac{n-1}{2},\frac{1}{2}\right)}.$$ It is possible to show that $$\frac{1}{\sqrt{n-1} B\left(\frac{n-1}{2},\frac{1}{2}\right)}\rightarrow \frac{1}{\sqrt{2\pi}},$$ and $$\left(1+\frac{x^2}{n-1}\right)^{-n/2}\rightarrow \exp(-x^2/2),$$ as $n\rightarrow \infty$. By taking the product of these two limits you can see that the Student-t density converges exactly to the standard normal density.
Why does the t-distribution become more normal as sample size increases? @Glen_b gave you the intuition on why the t statistic looks more normal as the sample size increases. Now, I will give you a slightly more technical explanation for the case when you already got the d
13,106
Why does the t-distribution become more normal as sample size increases?
I just wanted to share something that helped my intuition as a beginner (though it's less rigorous than the other answers). If $Z, Z_1, ..., Z_n$ are iid standard normal RVs then the following RV, $$\frac{Z}{\sqrt{\frac{Z_1^2+...+Z_n^2}{n}}}$$ has a t-distribution with $n$ degrees of freedom. As $n$ gets really big, using the law of large numbers we can see that the denominator goes to $1$. So you're just left with $Z$ which is standard normal which is why the t-distribution looks normal as $n$ gets big. To elaborate... note that $E[Z^2] = 1$ which says the expected value of a chi squared RV is one. The fraction in the square root is just the sample mean of $n$ iid $Z_i^2$ RVs. The sample mean as $n$ gets super big will equal the expected value of just one of the $Z_i^2$'s which is one. So as $n$ gets really big you're just left with $\frac{Z}{\sqrt{1}} = Z$
Why does the t-distribution become more normal as sample size increases?
I just wanted to share something that helped my intuition as a beginner (though it's less rigorous than the other answers). If $Z, Z_1, ..., Z_n$ are iid standard normal RVs then the following RV, $$\
Why does the t-distribution become more normal as sample size increases? I just wanted to share something that helped my intuition as a beginner (though it's less rigorous than the other answers). If $Z, Z_1, ..., Z_n$ are iid standard normal RVs then the following RV, $$\frac{Z}{\sqrt{\frac{Z_1^2+...+Z_n^2}{n}}}$$ has a t-distribution with $n$ degrees of freedom. As $n$ gets really big, using the law of large numbers we can see that the denominator goes to $1$. So you're just left with $Z$ which is standard normal which is why the t-distribution looks normal as $n$ gets big. To elaborate... note that $E[Z^2] = 1$ which says the expected value of a chi squared RV is one. The fraction in the square root is just the sample mean of $n$ iid $Z_i^2$ RVs. The sample mean as $n$ gets super big will equal the expected value of just one of the $Z_i^2$'s which is one. So as $n$ gets really big you're just left with $\frac{Z}{\sqrt{1}} = Z$
Why does the t-distribution become more normal as sample size increases? I just wanted to share something that helped my intuition as a beginner (though it's less rigorous than the other answers). If $Z, Z_1, ..., Z_n$ are iid standard normal RVs then the following RV, $$\
13,107
How to display error bars for cross-over (paired) experiments
You are totally correct in your assumption that error bars representing the standard error of the mean are totally inappropriate for within-subject designs. However, the question of overlapping error bars and significance is yet another topic, to which I will come back at the end of this commented reference list. There is rich literature from Psychology on within-subject confidence intervals or error bars which do exactly what you want. The reference work is clearly: Loftus, G. R., & Masson, M. E. J. (1994). Using confidence intervals in within-subject designs. Psychonomic Bulletin & Review, 1(4), 476–490. doi:10.3758/BF03210951 However, their problem is that they use the same error term for all levels of a within-subject factor. This does not seem to be a huge problem for your case (2 levels). But there are more modern approaches solving this problem. Most notably: Franz, V., & Loftus, G. (2012). Standard errors and confidence intervals in within-subjects designs: Generalizing Loftus and Masson (1994) and avoiding the biases of alternative accounts. Psychonomic Bulletin & Review, 1–10. doi:10.3758/s13423-012-0230-1 Baguley, T. (2011). Calculating and graphing within-subject confidence intervals for ANOVA. Behavior Research Methods. doi:10.3758/s13428-011-0123-7 [can be found here] Further references can be found in the latter two papers (which I think are both worth a read). How do researchers interpret CIs? Bad according to the following paper: Belia, S., Fidler, F., Williams, J., & Cumming, G. (2005). Researchers Misunderstand Confidence Intervals and Standard Error Bars. Psychological Methods, 10(4), 389–396. doi:10.1037/1082-989X.10.4.389 How should we interpret overlapping and non-overlapping CIs? Cumming, G., & Finch, S. (2005). Inference by Eye: Confidence Intervals and How to Read Pictures of Data. American Psychologist, 60(2), 170–180. doi:10.1037/0003-066X.60.2.170 One final thought (although this is not relevant to your case): If you have a split-plot design (i.e., within- and between-subject factors) in one plot, you can forget about error bars all together. I would (humbly) recommend my raw.means.plot function in the R package plotrix.
How to display error bars for cross-over (paired) experiments
You are totally correct in your assumption that error bars representing the standard error of the mean are totally inappropriate for within-subject designs. However, the question of overlapping error
How to display error bars for cross-over (paired) experiments You are totally correct in your assumption that error bars representing the standard error of the mean are totally inappropriate for within-subject designs. However, the question of overlapping error bars and significance is yet another topic, to which I will come back at the end of this commented reference list. There is rich literature from Psychology on within-subject confidence intervals or error bars which do exactly what you want. The reference work is clearly: Loftus, G. R., & Masson, M. E. J. (1994). Using confidence intervals in within-subject designs. Psychonomic Bulletin & Review, 1(4), 476–490. doi:10.3758/BF03210951 However, their problem is that they use the same error term for all levels of a within-subject factor. This does not seem to be a huge problem for your case (2 levels). But there are more modern approaches solving this problem. Most notably: Franz, V., & Loftus, G. (2012). Standard errors and confidence intervals in within-subjects designs: Generalizing Loftus and Masson (1994) and avoiding the biases of alternative accounts. Psychonomic Bulletin & Review, 1–10. doi:10.3758/s13423-012-0230-1 Baguley, T. (2011). Calculating and graphing within-subject confidence intervals for ANOVA. Behavior Research Methods. doi:10.3758/s13428-011-0123-7 [can be found here] Further references can be found in the latter two papers (which I think are both worth a read). How do researchers interpret CIs? Bad according to the following paper: Belia, S., Fidler, F., Williams, J., & Cumming, G. (2005). Researchers Misunderstand Confidence Intervals and Standard Error Bars. Psychological Methods, 10(4), 389–396. doi:10.1037/1082-989X.10.4.389 How should we interpret overlapping and non-overlapping CIs? Cumming, G., & Finch, S. (2005). Inference by Eye: Confidence Intervals and How to Read Pictures of Data. American Psychologist, 60(2), 170–180. doi:10.1037/0003-066X.60.2.170 One final thought (although this is not relevant to your case): If you have a split-plot design (i.e., within- and between-subject factors) in one plot, you can forget about error bars all together. I would (humbly) recommend my raw.means.plot function in the R package plotrix.
How to display error bars for cross-over (paired) experiments You are totally correct in your assumption that error bars representing the standard error of the mean are totally inappropriate for within-subject designs. However, the question of overlapping error
13,108
How to display error bars for cross-over (paired) experiments
The question does not seem to be about error bars so much as about the best ways of plotting paired data. In essence error bars here are at most a way of summarizing uncertainty: they do not, and they necessarily cannot, say much about any fine structure in the data. Parallel coordinate plots -- sometimes called profile plots, a term that means different things in different fields -- have been mentioned in the question. Basic scatter plots have already been suggested by @Ray Koopman. A specialized scatter plot popular here and there is a plot of difference (here $A - B$, say) versus mean (or sum) $(A + B)/2$ or $A + B$. In medicine this is often known as a bland-altman-plot (perhaps because it was earlier used by Oldham) and in statistics it is often known as a Tukey mean-difference plot. Another source for this plot is Neyman, J., Scott, E. L. and Shane, C. D. 1953. On the spatial distribution of galaxies: a specific model. Astrophysical Journal 117: 92–133. In broad terms such plots resemble the idea of plotting residuals versus fitted, also popularised by Tukey and his brother-in-law-squared Anscombe. The key idea of such plots is that the horizontal line of no difference $A - B = 0$ is naturally equivalent to the line of equality $A = B$, but it is often easier psychologically to work with a horizontal reference line. In addition, if $A$ and $B$ are broadly similar, a scatter plot uses much of its space in emphasising that fact, whereas the structure of the differences should be of greater interest. A neglected design is the parallel-line plot of McNeil, D.R. 1992. On graphing paired data. American Statistician 46: 307–310. This is also discussed in the two references below. Stata-linked reviews, with several references, are in 2004, Graphing agreement and disagreement. Stata Journal 4: 329-349. .pdf accessible at http://www.stata-journal.com/sjpdf.html?articlenum=gr0005 Paired, parallel, or profile plots for changes, correlations, and other comparisons. Stata Journal 9: 621-639. .pdf accessible at http://www.stata-journal.com/sjpdf.html?articlenum=gr0041 Non-Stata users should able to skip and hum their way through the Stata code while working out how to implement the graphs in their own favourite software. In all cases if the ratio of $A$ and $B$ is of interest rather than its difference, exactly the same ideas should be used, but employing logarithmic scales.
How to display error bars for cross-over (paired) experiments
The question does not seem to be about error bars so much as about the best ways of plotting paired data. In essence error bars here are at most a way of summarizing uncertainty: they do not, and the
How to display error bars for cross-over (paired) experiments The question does not seem to be about error bars so much as about the best ways of plotting paired data. In essence error bars here are at most a way of summarizing uncertainty: they do not, and they necessarily cannot, say much about any fine structure in the data. Parallel coordinate plots -- sometimes called profile plots, a term that means different things in different fields -- have been mentioned in the question. Basic scatter plots have already been suggested by @Ray Koopman. A specialized scatter plot popular here and there is a plot of difference (here $A - B$, say) versus mean (or sum) $(A + B)/2$ or $A + B$. In medicine this is often known as a bland-altman-plot (perhaps because it was earlier used by Oldham) and in statistics it is often known as a Tukey mean-difference plot. Another source for this plot is Neyman, J., Scott, E. L. and Shane, C. D. 1953. On the spatial distribution of galaxies: a specific model. Astrophysical Journal 117: 92–133. In broad terms such plots resemble the idea of plotting residuals versus fitted, also popularised by Tukey and his brother-in-law-squared Anscombe. The key idea of such plots is that the horizontal line of no difference $A - B = 0$ is naturally equivalent to the line of equality $A = B$, but it is often easier psychologically to work with a horizontal reference line. In addition, if $A$ and $B$ are broadly similar, a scatter plot uses much of its space in emphasising that fact, whereas the structure of the differences should be of greater interest. A neglected design is the parallel-line plot of McNeil, D.R. 1992. On graphing paired data. American Statistician 46: 307–310. This is also discussed in the two references below. Stata-linked reviews, with several references, are in 2004, Graphing agreement and disagreement. Stata Journal 4: 329-349. .pdf accessible at http://www.stata-journal.com/sjpdf.html?articlenum=gr0005 Paired, parallel, or profile plots for changes, correlations, and other comparisons. Stata Journal 9: 621-639. .pdf accessible at http://www.stata-journal.com/sjpdf.html?articlenum=gr0041 Non-Stata users should able to skip and hum their way through the Stata code while working out how to implement the graphs in their own favourite software. In all cases if the ratio of $A$ and $B$ is of interest rather than its difference, exactly the same ideas should be used, but employing logarithmic scales.
How to display error bars for cross-over (paired) experiments The question does not seem to be about error bars so much as about the best ways of plotting paired data. In essence error bars here are at most a way of summarizing uncertainty: they do not, and the
13,109
How to display error bars for cross-over (paired) experiments
Try a scatter plot of the individual (A,B) points. Most of them should lie on only one side of the diagonal (the line A = B). There are two analogs of error bars. The conventional one, equivalent to a CI for the mean difference, would be a confidence band for the mean difference. The band would be the region between two lines, both of which are parallel to the diagonal. A paired t-test would be significant if and only if both edges of the band are on the same side of the diagonal. A more conservative error-bar analog would be a confidence ellipse for the centroid.
How to display error bars for cross-over (paired) experiments
Try a scatter plot of the individual (A,B) points. Most of them should lie on only one side of the diagonal (the line A = B). There are two analogs of error bars. The conventional one, equivalent to
How to display error bars for cross-over (paired) experiments Try a scatter plot of the individual (A,B) points. Most of them should lie on only one side of the diagonal (the line A = B). There are two analogs of error bars. The conventional one, equivalent to a CI for the mean difference, would be a confidence band for the mean difference. The band would be the region between two lines, both of which are parallel to the diagonal. A paired t-test would be significant if and only if both edges of the band are on the same side of the diagonal. A more conservative error-bar analog would be a confidence ellipse for the centroid.
How to display error bars for cross-over (paired) experiments Try a scatter plot of the individual (A,B) points. Most of them should lie on only one side of the diagonal (the line A = B). There are two analogs of error bars. The conventional one, equivalent to
13,110
How to display error bars for cross-over (paired) experiments
Preliminary summary: Masson/Loftus is very exhaustive, and not an easy reading to give to my medical colleagues who would not accept something like an "interaction". They also have some suggestions for multiple comparisons, which show that pairwise confidence intervals are difficult to illustrate when one does not want to simplify heavily. I don't like this style: the bars with error bars look last millennium Excelish. However, they also use a slightly more elegant style: Cumming/Finch and Belia et al. are must readings. The first is the perfect choice to give your friend who shudders when (s)he sees the word interaction. I ordered Cumming's book after reading that article. The second shows a test I will implement in Shiny for the next medical investigator meeting. I like this plot, even if there is a second axis which I never used before; check Henrik's and some other's contribution on StackOverflow for an R-base graphics method to obtain it. I would prefer to put the second axis to the left of the difference to make absolutely clear that the values changed, and maybe add a p-value axis. Anybody from the lattice/ggplot fraction taking a shot? All supplied solutions are base graphics and not panelizable/facetable. However: note that comments and papers are mostly from the psychology department (and @cbeleites from hardcore chemistry). It would good to get comments from reviewers of medical journals.
How to display error bars for cross-over (paired) experiments
Preliminary summary: Masson/Loftus is very exhaustive, and not an easy reading to give to my medical colleagues who would not accept something like an "interaction". They also have some suggestions fo
How to display error bars for cross-over (paired) experiments Preliminary summary: Masson/Loftus is very exhaustive, and not an easy reading to give to my medical colleagues who would not accept something like an "interaction". They also have some suggestions for multiple comparisons, which show that pairwise confidence intervals are difficult to illustrate when one does not want to simplify heavily. I don't like this style: the bars with error bars look last millennium Excelish. However, they also use a slightly more elegant style: Cumming/Finch and Belia et al. are must readings. The first is the perfect choice to give your friend who shudders when (s)he sees the word interaction. I ordered Cumming's book after reading that article. The second shows a test I will implement in Shiny for the next medical investigator meeting. I like this plot, even if there is a second axis which I never used before; check Henrik's and some other's contribution on StackOverflow for an R-base graphics method to obtain it. I would prefer to put the second axis to the left of the difference to make absolutely clear that the values changed, and maybe add a p-value axis. Anybody from the lattice/ggplot fraction taking a shot? All supplied solutions are base graphics and not panelizable/facetable. However: note that comments and papers are mostly from the psychology department (and @cbeleites from hardcore chemistry). It would good to get comments from reviewers of medical journals.
How to display error bars for cross-over (paired) experiments Preliminary summary: Masson/Loftus is very exhaustive, and not an easy reading to give to my medical colleagues who would not accept something like an "interaction". They also have some suggestions fo
13,111
How to display error bars for cross-over (paired) experiments
Why not just plot the difference* for each patient? You could then use a histogram, a box plot or a normal probability plot and overlay a 95% confidence interval for the difference. In some scenarios it might be the difference of the logarithms. See, for example, Patterson & Jones, "Bioequivalence and Statistics in Clinical Pharmacology", Chapman, 2006.
How to display error bars for cross-over (paired) experiments
Why not just plot the difference* for each patient? You could then use a histogram, a box plot or a normal probability plot and overlay a 95% confidence interval for the difference. In some scenario
How to display error bars for cross-over (paired) experiments Why not just plot the difference* for each patient? You could then use a histogram, a box plot or a normal probability plot and overlay a 95% confidence interval for the difference. In some scenarios it might be the difference of the logarithms. See, for example, Patterson & Jones, "Bioequivalence and Statistics in Clinical Pharmacology", Chapman, 2006.
How to display error bars for cross-over (paired) experiments Why not just plot the difference* for each patient? You could then use a histogram, a box plot or a normal probability plot and overlay a 95% confidence interval for the difference. In some scenario
13,112
Crash course in robust mean estimation
Are you looking for the theory, or something practical? If you are looking for books, here are some that I found helpful: F.R. Hampel, E.M. Ronchetti, P.J.Rousseeuw, W.A. Stahel, Robust Statistics: The Approach Based on In fluence Functions, John Wiley & Sons, 1986. P.J. Huber, Robust Statistics, John Wiley & Sons, 1981. P.J. Rousseeuw, A.M. Leroy, Robust Regression and Outlier Detection, John Wiley & Sons, 1987. R.G. Staudte, S.J. Sheather, Robust Estimation and Testing, John Wiley & Sons, 1990. If you are looking for practical methods, here are few robust methods of estimating the mean ("estimators of location" is I guess the more principled term): The median is simple, well-known, and pretty powerful. It has excellent robustness to outliers. The "price" of robustness is about 25%. The 5%-trimmed average is another possible method. Here you throw away the 5% highest and 5% lowest values, and then take the mean (average) of the result. This is less robust to outliers: as long as no more than 5% of your data points are corrupted, it is good, but if more than 5% are corrupted, it suddenly turns awful (it doesn't degrade gracefully). The "price" of robustness is less than the median, though I don't know what it is exactly. The Hodges-Lehmann estimator computes the median of the set $\{(x_i+x_j)/2 : 1 \le i \le j \le n\}$ (a set containing $n(n+1)/2$ values), where $x_1,\dots,x_n$ are the observations. This has very good robustness: it can handle corruption of up to about 29% of the data points without totally falling apart. And the "price" of robustness is low: about 5%. It is a plausible alternative to the median. The interquartile mean is another estimator that is sometimes used. It computes the average of the first and third quartiles, and thus is simple to compute. It has very good robustness: it can tolerate corruption of up to 25% of the data points. However, the "price" of robustness is non-trivial: about 25%. As a result, this seems inferior to the median. There are many other measures that have been proposed, but the ones above seem reasonable. In short, I would suggest the median or possibly the Hodges-Lehmann estimator. P.S. Oh, I should explain what I mean by the "price" of robustness. A robust estimator is designed to still work decently well even if some of your data points have been corrupted or are otherwise outliers. But what if you use a robust estimator on a data set that has no outliers and no corruption? Ideally, we'd like the robust estimator to be as efficient at making use of the data as possible. Here we can measure the efficiency by the standard error (intuitively, the typical amount of error in the estimate produced by the estimator). It is known that if your observations come from a Gaussian distribution (iid), and if you know you won't need robustness, then the mean is optimal: it has the smallest possible estimation error. The "price" of robustness, above, is how much the standard error increases if we apply a particular robust estimator to this situation. A price of robustness of 25% for the median means that the size of the typical estimation error with the median will be about 25% larger than the size of the typical estimation error with the mean. Obviously, the lower the "price" is, the better.
Crash course in robust mean estimation
Are you looking for the theory, or something practical? If you are looking for books, here are some that I found helpful: F.R. Hampel, E.M. Ronchetti, P.J.Rousseeuw, W.A. Stahel, Robust Statistics: T
Crash course in robust mean estimation Are you looking for the theory, or something practical? If you are looking for books, here are some that I found helpful: F.R. Hampel, E.M. Ronchetti, P.J.Rousseeuw, W.A. Stahel, Robust Statistics: The Approach Based on In fluence Functions, John Wiley & Sons, 1986. P.J. Huber, Robust Statistics, John Wiley & Sons, 1981. P.J. Rousseeuw, A.M. Leroy, Robust Regression and Outlier Detection, John Wiley & Sons, 1987. R.G. Staudte, S.J. Sheather, Robust Estimation and Testing, John Wiley & Sons, 1990. If you are looking for practical methods, here are few robust methods of estimating the mean ("estimators of location" is I guess the more principled term): The median is simple, well-known, and pretty powerful. It has excellent robustness to outliers. The "price" of robustness is about 25%. The 5%-trimmed average is another possible method. Here you throw away the 5% highest and 5% lowest values, and then take the mean (average) of the result. This is less robust to outliers: as long as no more than 5% of your data points are corrupted, it is good, but if more than 5% are corrupted, it suddenly turns awful (it doesn't degrade gracefully). The "price" of robustness is less than the median, though I don't know what it is exactly. The Hodges-Lehmann estimator computes the median of the set $\{(x_i+x_j)/2 : 1 \le i \le j \le n\}$ (a set containing $n(n+1)/2$ values), where $x_1,\dots,x_n$ are the observations. This has very good robustness: it can handle corruption of up to about 29% of the data points without totally falling apart. And the "price" of robustness is low: about 5%. It is a plausible alternative to the median. The interquartile mean is another estimator that is sometimes used. It computes the average of the first and third quartiles, and thus is simple to compute. It has very good robustness: it can tolerate corruption of up to 25% of the data points. However, the "price" of robustness is non-trivial: about 25%. As a result, this seems inferior to the median. There are many other measures that have been proposed, but the ones above seem reasonable. In short, I would suggest the median or possibly the Hodges-Lehmann estimator. P.S. Oh, I should explain what I mean by the "price" of robustness. A robust estimator is designed to still work decently well even if some of your data points have been corrupted or are otherwise outliers. But what if you use a robust estimator on a data set that has no outliers and no corruption? Ideally, we'd like the robust estimator to be as efficient at making use of the data as possible. Here we can measure the efficiency by the standard error (intuitively, the typical amount of error in the estimate produced by the estimator). It is known that if your observations come from a Gaussian distribution (iid), and if you know you won't need robustness, then the mean is optimal: it has the smallest possible estimation error. The "price" of robustness, above, is how much the standard error increases if we apply a particular robust estimator to this situation. A price of robustness of 25% for the median means that the size of the typical estimation error with the median will be about 25% larger than the size of the typical estimation error with the mean. Obviously, the lower the "price" is, the better.
Crash course in robust mean estimation Are you looking for the theory, or something practical? If you are looking for books, here are some that I found helpful: F.R. Hampel, E.M. Ronchetti, P.J.Rousseeuw, W.A. Stahel, Robust Statistics: T
13,113
Crash course in robust mean estimation
If you like something short and easy to digest, then have a look at the following paper from the psychological literature: Erceg-Hurn, D. M., & Mirosevich, V. M. (2008). Modern robust statistical methods: An easy way to maximize the accuracy and power of your research. American Psychologist, 63(7), 591–601. doi:10.1037/0003-066X.63.7.591 They mainly rely on the books by Rand R Wilcox (which are admittedly also not too mathematical): Wilcox, R. R. (2001). Fundamentals of modern statistical methods : substantially improving power and accuracy. New York; Berlin: Springer. Wilcox, R. R. (2003). Applying contemporary statistical techniques. Amsterdam; Boston: Academic Press. Wilcox, R. R. (2005). Introduction to robust estimation and hypothesis testing. Academic Press.
Crash course in robust mean estimation
If you like something short and easy to digest, then have a look at the following paper from the psychological literature: Erceg-Hurn, D. M., & Mirosevich, V. M. (2008). Modern robust statistical meth
Crash course in robust mean estimation If you like something short and easy to digest, then have a look at the following paper from the psychological literature: Erceg-Hurn, D. M., & Mirosevich, V. M. (2008). Modern robust statistical methods: An easy way to maximize the accuracy and power of your research. American Psychologist, 63(7), 591–601. doi:10.1037/0003-066X.63.7.591 They mainly rely on the books by Rand R Wilcox (which are admittedly also not too mathematical): Wilcox, R. R. (2001). Fundamentals of modern statistical methods : substantially improving power and accuracy. New York; Berlin: Springer. Wilcox, R. R. (2003). Applying contemporary statistical techniques. Amsterdam; Boston: Academic Press. Wilcox, R. R. (2005). Introduction to robust estimation and hypothesis testing. Academic Press.
Crash course in robust mean estimation If you like something short and easy to digest, then have a look at the following paper from the psychological literature: Erceg-Hurn, D. M., & Mirosevich, V. M. (2008). Modern robust statistical meth
13,114
Crash course in robust mean estimation
One book that combines theory with practice pretty well is Robust Statistical Methods with R, by Jurečková and Picek. I also like Robust Statistics, by Maronna et al. Both of these may have more math than you'd care for, however. For a more applied tutorial focused on R, this BelVenTutorial pdf may help.
Crash course in robust mean estimation
One book that combines theory with practice pretty well is Robust Statistical Methods with R, by Jurečková and Picek. I also like Robust Statistics, by Maronna et al. Both of these may have more mat
Crash course in robust mean estimation One book that combines theory with practice pretty well is Robust Statistical Methods with R, by Jurečková and Picek. I also like Robust Statistics, by Maronna et al. Both of these may have more math than you'd care for, however. For a more applied tutorial focused on R, this BelVenTutorial pdf may help.
Crash course in robust mean estimation One book that combines theory with practice pretty well is Robust Statistical Methods with R, by Jurečková and Picek. I also like Robust Statistics, by Maronna et al. Both of these may have more mat
13,115
Generate random numbers following a distribution within an interval
It sounds like you want to simulate from a truncated distribution, and in your specific example, a truncated normal. There are a variety of methods for doing so, some simple, some relatively efficient. I'll illustrate some approaches on your normal example. Here's one very simple method for generating one at a time (in some kind of pseudocode): $\tt{repeat}$ generate $x_i$ from N(mean,sd) $\tt{until}$ lower $\leq x_i\leq$ upper If most of the distribution is within the bounds, this is pretty reasonable but it can get quite slow if you nearly always generate outside the limits. In R you could avoid the one-at-a-time loop by computing the area within the bounds and generate enough values that you could be almost certain that after throwing out the values outside the bounds you still had as many values as needed. You could use accept-reject with some suitable majorizing function over the interval (in some cases uniform will be good enough). If the limits were reasonably narrow relative to the s.d. but you weren't far into the tail, a uniform majorizing would work okay with the normal, for example. If you have a reasonably efficient cdf and inverse cdf (such as pnorm and qnorm for the normal distribution in R) you can use the inverse-cdf method described in the first paragraph of the simulating section of the Wikipedia page on the truncated normal. [In effect this is the same as taking a truncated uniform (truncated at the required quantiles, which actually requires no rejections at all, since that's just another uniform) and apply the inverse normal cdf to that. Note that this can fail if you're far into the tail] There are other approaches; the same Wikipedia page mentions adapting the ziggurat method, that should work for a variety of distributions. The same Wikipedia link mentions two specific packages (both on CRAN) with functions for generating truncated normals: The MSM package in R has a function, rtnorm, that calculates draws from a truncated normal. The truncnorm package in R also has functions to draw from a truncated normal. Looking around, a lot of this is covered in answers on other questions (but not exactly duplicates since this question is more general than just the truncated normal) ... see additional discussion in a. This answer b. Xi'an's answer here, which has a link to his arXiv paper (along with some other worthwhile responses).
Generate random numbers following a distribution within an interval
It sounds like you want to simulate from a truncated distribution, and in your specific example, a truncated normal. There are a variety of methods for doing so, some simple, some relatively efficient
Generate random numbers following a distribution within an interval It sounds like you want to simulate from a truncated distribution, and in your specific example, a truncated normal. There are a variety of methods for doing so, some simple, some relatively efficient. I'll illustrate some approaches on your normal example. Here's one very simple method for generating one at a time (in some kind of pseudocode): $\tt{repeat}$ generate $x_i$ from N(mean,sd) $\tt{until}$ lower $\leq x_i\leq$ upper If most of the distribution is within the bounds, this is pretty reasonable but it can get quite slow if you nearly always generate outside the limits. In R you could avoid the one-at-a-time loop by computing the area within the bounds and generate enough values that you could be almost certain that after throwing out the values outside the bounds you still had as many values as needed. You could use accept-reject with some suitable majorizing function over the interval (in some cases uniform will be good enough). If the limits were reasonably narrow relative to the s.d. but you weren't far into the tail, a uniform majorizing would work okay with the normal, for example. If you have a reasonably efficient cdf and inverse cdf (such as pnorm and qnorm for the normal distribution in R) you can use the inverse-cdf method described in the first paragraph of the simulating section of the Wikipedia page on the truncated normal. [In effect this is the same as taking a truncated uniform (truncated at the required quantiles, which actually requires no rejections at all, since that's just another uniform) and apply the inverse normal cdf to that. Note that this can fail if you're far into the tail] There are other approaches; the same Wikipedia page mentions adapting the ziggurat method, that should work for a variety of distributions. The same Wikipedia link mentions two specific packages (both on CRAN) with functions for generating truncated normals: The MSM package in R has a function, rtnorm, that calculates draws from a truncated normal. The truncnorm package in R also has functions to draw from a truncated normal. Looking around, a lot of this is covered in answers on other questions (but not exactly duplicates since this question is more general than just the truncated normal) ... see additional discussion in a. This answer b. Xi'an's answer here, which has a link to his arXiv paper (along with some other worthwhile responses).
Generate random numbers following a distribution within an interval It sounds like you want to simulate from a truncated distribution, and in your specific example, a truncated normal. There are a variety of methods for doing so, some simple, some relatively efficient
13,116
Generate random numbers following a distribution within an interval
None of the answers here give an efficient method of generating truncated normal variables that does not involve rejection of arbitrarily large numbers of generated values. If you want to generate values from a truncated normal distribution, with specified lower and upper bounds $a<b$, this can be done ---without rejection--- by generating uniform quantiles over the quantile range allowed by the truncation, and using inverse transformation sampling to get corresponding normal values. Let $\Phi$ denote the CDF of the standard normal distribution. We want to generate $X_1,...,X_N$ from a truncated normal distribution (with mean parameter $\mu$ and variance parameter $\sigma^2$)$^\dagger$ with lower and upper truncation bounds $a<b$. This can be done as follows: $$X_i = \mu + \sigma \cdot \Phi^{-1}(U_i) \quad \quad \quad U_1,...,U_N \sim \text{IID U} \Big[ \Phi \Big( \frac{a-\mu}{\sigma} \Big), \Phi \Big( \frac{b-\mu}{\sigma} \Big) \Big].$$ There is no inbuilt function for generated values from the truncated distribution, but it is trivial to program this method using the ordinary functions for generating random variables. Here is a simple R function rtruncnorm that implements this method in a few lines of code. rtruncnorm <- function(N, mean = 0, sd = 1, a = -Inf, b = Inf) { if (a > b) stop('Error: Truncation range is empty'); U <- runif(N, pnorm(a, mean, sd), pnorm(b, mean, sd)); qnorm(U, mean, sd); } This is a vectorised function that will generate N IID random variables from the truncated normal distribution. It would be easy to program functions for other truncated distributions via the same method. It would also not be too difficult to program associated density and quantile functions for the truncated distribution. $^\dagger$ Note that the truncation alters the mean and variance of the distribution, so $\mu$ and $\sigma^2$ are not the mean and variance of the truncated distribution.
Generate random numbers following a distribution within an interval
None of the answers here give an efficient method of generating truncated normal variables that does not involve rejection of arbitrarily large numbers of generated values. If you want to generate v
Generate random numbers following a distribution within an interval None of the answers here give an efficient method of generating truncated normal variables that does not involve rejection of arbitrarily large numbers of generated values. If you want to generate values from a truncated normal distribution, with specified lower and upper bounds $a<b$, this can be done ---without rejection--- by generating uniform quantiles over the quantile range allowed by the truncation, and using inverse transformation sampling to get corresponding normal values. Let $\Phi$ denote the CDF of the standard normal distribution. We want to generate $X_1,...,X_N$ from a truncated normal distribution (with mean parameter $\mu$ and variance parameter $\sigma^2$)$^\dagger$ with lower and upper truncation bounds $a<b$. This can be done as follows: $$X_i = \mu + \sigma \cdot \Phi^{-1}(U_i) \quad \quad \quad U_1,...,U_N \sim \text{IID U} \Big[ \Phi \Big( \frac{a-\mu}{\sigma} \Big), \Phi \Big( \frac{b-\mu}{\sigma} \Big) \Big].$$ There is no inbuilt function for generated values from the truncated distribution, but it is trivial to program this method using the ordinary functions for generating random variables. Here is a simple R function rtruncnorm that implements this method in a few lines of code. rtruncnorm <- function(N, mean = 0, sd = 1, a = -Inf, b = Inf) { if (a > b) stop('Error: Truncation range is empty'); U <- runif(N, pnorm(a, mean, sd), pnorm(b, mean, sd)); qnorm(U, mean, sd); } This is a vectorised function that will generate N IID random variables from the truncated normal distribution. It would be easy to program functions for other truncated distributions via the same method. It would also not be too difficult to program associated density and quantile functions for the truncated distribution. $^\dagger$ Note that the truncation alters the mean and variance of the distribution, so $\mu$ and $\sigma^2$ are not the mean and variance of the truncated distribution.
Generate random numbers following a distribution within an interval None of the answers here give an efficient method of generating truncated normal variables that does not involve rejection of arbitrarily large numbers of generated values. If you want to generate v
13,117
Generate random numbers following a distribution within an interval
The quick-and-dirty approach is to use the 68-95-99.7 rule. In a normal distribution, 99.7% of values fall within 3 standard deviations of the mean. So, if you set your mean to the middle of your desired minimum value and maximum value, and set your standard deviation to 1/3 of your mean, you get (mostly) values that fall within the desired interval. Then you can just clean up the rest. minVal <- 0 maxVal <- 100 mn <- (maxVal - minVal)/2 # Generate numbers (mostly) from min to max x <- rnorm(count, mean = mn, sd = mn/3) # Do something about the out-of-bounds generated values x <- pmax(minVal, x) x <- pmin(maxVal, x) I recently faced this same problem, trying to generate random student grades for test data. In the code above, I've used pmax and pmin to replace out-of-bounds values with the min or max in-bounds value. This works for my purpose, because I'm generating fairly small amounts of data, but for larger amounts it will give you noticeable bumps at the min and max values. So depending on your purposes it may be better to discard those values, replace them with NAs, or "re-roll" them until they're in-bounds.
Generate random numbers following a distribution within an interval
The quick-and-dirty approach is to use the 68-95-99.7 rule. In a normal distribution, 99.7% of values fall within 3 standard deviations of the mean. So, if you set your mean to the middle of your desi
Generate random numbers following a distribution within an interval The quick-and-dirty approach is to use the 68-95-99.7 rule. In a normal distribution, 99.7% of values fall within 3 standard deviations of the mean. So, if you set your mean to the middle of your desired minimum value and maximum value, and set your standard deviation to 1/3 of your mean, you get (mostly) values that fall within the desired interval. Then you can just clean up the rest. minVal <- 0 maxVal <- 100 mn <- (maxVal - minVal)/2 # Generate numbers (mostly) from min to max x <- rnorm(count, mean = mn, sd = mn/3) # Do something about the out-of-bounds generated values x <- pmax(minVal, x) x <- pmin(maxVal, x) I recently faced this same problem, trying to generate random student grades for test data. In the code above, I've used pmax and pmin to replace out-of-bounds values with the min or max in-bounds value. This works for my purpose, because I'm generating fairly small amounts of data, but for larger amounts it will give you noticeable bumps at the min and max values. So depending on your purposes it may be better to discard those values, replace them with NAs, or "re-roll" them until they're in-bounds.
Generate random numbers following a distribution within an interval The quick-and-dirty approach is to use the 68-95-99.7 rule. In a normal distribution, 99.7% of values fall within 3 standard deviations of the mean. So, if you set your mean to the middle of your desi
13,118
Generate random numbers following a distribution within an interval
Three ways has worked for me: using sample() with rnorm(): sample(x=min:max, replace= TRUE, rnorm(n, mean)) using the msm package and the rtnorm function: rtnorm(n, mean, lower=min, upper=max) using the rnorm() and specifying the lower and upper limits, as Hugh has posted above: sample <- rnorm(n, mean=mean); sample <- sample[x > min & x < max]
Generate random numbers following a distribution within an interval
Three ways has worked for me: using sample() with rnorm(): sample(x=min:max, replace= TRUE, rnorm(n, mean)) using the msm package and the rtnorm function: rtnorm(n, mean, lower=min, upper=max) using
Generate random numbers following a distribution within an interval Three ways has worked for me: using sample() with rnorm(): sample(x=min:max, replace= TRUE, rnorm(n, mean)) using the msm package and the rtnorm function: rtnorm(n, mean, lower=min, upper=max) using the rnorm() and specifying the lower and upper limits, as Hugh has posted above: sample <- rnorm(n, mean=mean); sample <- sample[x > min & x < max]
Generate random numbers following a distribution within an interval Three ways has worked for me: using sample() with rnorm(): sample(x=min:max, replace= TRUE, rnorm(n, mean)) using the msm package and the rtnorm function: rtnorm(n, mean, lower=min, upper=max) using
13,119
Is there an R equivalent of SAS PROC FREQ?
I use table and prop.table, but CrossTable in the gmodels package might give you results even closer to SAS. See this link. Also, to generate "descriptive statistics for multiple variables at once," you would use the summary function; e.g., summary(mydata).
Is there an R equivalent of SAS PROC FREQ?
I use table and prop.table, but CrossTable in the gmodels package might give you results even closer to SAS. See this link. Also, to generate "descriptive statistics for multiple variables at once," y
Is there an R equivalent of SAS PROC FREQ? I use table and prop.table, but CrossTable in the gmodels package might give you results even closer to SAS. See this link. Also, to generate "descriptive statistics for multiple variables at once," you would use the summary function; e.g., summary(mydata).
Is there an R equivalent of SAS PROC FREQ? I use table and prop.table, but CrossTable in the gmodels package might give you results even closer to SAS. See this link. Also, to generate "descriptive statistics for multiple variables at once," y
13,120
Is there an R equivalent of SAS PROC FREQ?
Summarising data in base R is just a headache. This is one of the areas where SAS works quite well. For R, I recommend the plyr package. In SAS: /* tabulate by a and b, with summary stats for x and y in each cell */ proc summary data=dat nway; class a b; var x y; output out=smry mean(x)=xmean mean(y)=ymean var(y)=yvar; run; with plyr: smry <- ddply(dat, .(a, b), summarise, xmean=mean(x), ymean=mean(y), yvar=var(y))
Is there an R equivalent of SAS PROC FREQ?
Summarising data in base R is just a headache. This is one of the areas where SAS works quite well. For R, I recommend the plyr package. In SAS: /* tabulate by a and b, with summary stats for x and y
Is there an R equivalent of SAS PROC FREQ? Summarising data in base R is just a headache. This is one of the areas where SAS works quite well. For R, I recommend the plyr package. In SAS: /* tabulate by a and b, with summary stats for x and y in each cell */ proc summary data=dat nway; class a b; var x y; output out=smry mean(x)=xmean mean(y)=ymean var(y)=yvar; run; with plyr: smry <- ddply(dat, .(a, b), summarise, xmean=mean(x), ymean=mean(y), yvar=var(y))
Is there an R equivalent of SAS PROC FREQ? Summarising data in base R is just a headache. This is one of the areas where SAS works quite well. For R, I recommend the plyr package. In SAS: /* tabulate by a and b, with summary stats for x and y
13,121
Is there an R equivalent of SAS PROC FREQ?
I don't use SAS; so I can't comment on whether the following replicate SAS PROC FREQ, but these are two quick strategies for describing variables in a data.frame that I often use: describe in Hmisc provides a useful summary of variables including numeric and non-numeric data describe in psych provides descriptive statistics for numeric data R Example > library(MASS) # provides dataset called "survey" > library(Hmisc) # Hmisc describe > library(psych) # psych describe The following is the output of Hmisc describe: > Hmisc::describe(survey) survey 12 Variables 237 Observations ---------------------------------------------------------------------------------------------------------------------- Sex n missing unique 236 1 2 Female (118, 50%), Male (118, 50%) ---------------------------------------------------------------------------------------------------------------------- Wr.Hnd n missing unique Mean .05 .10 .25 .50 .75 .90 .95 236 1 60 18.67 16.00 16.50 17.50 18.50 19.80 21.15 22.05 lowest : 13.0 14.0 15.0 15.4 15.5, highest: 22.5 22.8 23.0 23.1 23.2 ---------------------------------------------------------------------------------------------------------------------- NW.Hnd n missing unique Mean .05 .10 .25 .50 .75 .90 .95 236 1 68 18.58 15.50 16.30 17.50 18.50 19.72 21.00 22.22 lowest : 12.5 13.0 13.3 13.5 15.0, highest: 22.7 23.0 23.2 23.3 23.5 ---------------------------------------------------------------------------------------------------------------------- [ABBREVIATED OUTPUT] Then below is the output of psych describe for the numeric variables: > psych::describe(survey[,sapply(survey, class) %in% c("numeric", "integer") ]) var n mean sd median trimmed mad min max range skew kurtosis se Wr.Hnd 1 236 18.67 1.88 18.50 18.61 1.48 13.00 23.2 10.20 0.18 0.36 0.12 NW.Hnd 2 236 18.58 1.97 18.50 18.55 1.63 12.50 23.5 11.00 0.02 0.51 0.13 Pulse 3 192 74.15 11.69 72.50 74.02 11.12 35.00 104.0 69.00 -0.02 0.41 0.84 Height 4 209 172.38 9.85 171.00 172.19 10.08 150.00 200.0 50.00 0.22 -0.39 0.68 Age 5 237 20.37 6.47 18.58 18.99 1.61 16.75 73.0 56.25 5.16 34.53 0.42
Is there an R equivalent of SAS PROC FREQ?
I don't use SAS; so I can't comment on whether the following replicate SAS PROC FREQ, but these are two quick strategies for describing variables in a data.frame that I often use: describe in Hmisc p
Is there an R equivalent of SAS PROC FREQ? I don't use SAS; so I can't comment on whether the following replicate SAS PROC FREQ, but these are two quick strategies for describing variables in a data.frame that I often use: describe in Hmisc provides a useful summary of variables including numeric and non-numeric data describe in psych provides descriptive statistics for numeric data R Example > library(MASS) # provides dataset called "survey" > library(Hmisc) # Hmisc describe > library(psych) # psych describe The following is the output of Hmisc describe: > Hmisc::describe(survey) survey 12 Variables 237 Observations ---------------------------------------------------------------------------------------------------------------------- Sex n missing unique 236 1 2 Female (118, 50%), Male (118, 50%) ---------------------------------------------------------------------------------------------------------------------- Wr.Hnd n missing unique Mean .05 .10 .25 .50 .75 .90 .95 236 1 60 18.67 16.00 16.50 17.50 18.50 19.80 21.15 22.05 lowest : 13.0 14.0 15.0 15.4 15.5, highest: 22.5 22.8 23.0 23.1 23.2 ---------------------------------------------------------------------------------------------------------------------- NW.Hnd n missing unique Mean .05 .10 .25 .50 .75 .90 .95 236 1 68 18.58 15.50 16.30 17.50 18.50 19.72 21.00 22.22 lowest : 12.5 13.0 13.3 13.5 15.0, highest: 22.7 23.0 23.2 23.3 23.5 ---------------------------------------------------------------------------------------------------------------------- [ABBREVIATED OUTPUT] Then below is the output of psych describe for the numeric variables: > psych::describe(survey[,sapply(survey, class) %in% c("numeric", "integer") ]) var n mean sd median trimmed mad min max range skew kurtosis se Wr.Hnd 1 236 18.67 1.88 18.50 18.61 1.48 13.00 23.2 10.20 0.18 0.36 0.12 NW.Hnd 2 236 18.58 1.97 18.50 18.55 1.63 12.50 23.5 11.00 0.02 0.51 0.13 Pulse 3 192 74.15 11.69 72.50 74.02 11.12 35.00 104.0 69.00 -0.02 0.41 0.84 Height 4 209 172.38 9.85 171.00 172.19 10.08 150.00 200.0 50.00 0.22 -0.39 0.68 Age 5 237 20.37 6.47 18.58 18.99 1.61 16.75 73.0 56.25 5.16 34.53 0.42
Is there an R equivalent of SAS PROC FREQ? I don't use SAS; so I can't comment on whether the following replicate SAS PROC FREQ, but these are two quick strategies for describing variables in a data.frame that I often use: describe in Hmisc p
13,122
Is there an R equivalent of SAS PROC FREQ?
You can check out my summarytools package (CRAN link) which includes a codebook-like function, with markdown and html formatting options. install.packages("summarytools") library(summarytools) dfSummary(CO2, style = "grid", plain.ascii = TRUE) Dataframe Summary CO2 +------------+---------------+-------------------------------------+--------------------+-----------+ | Variable | Properties | Stats / Values | Freqs, % Valid | N Valid | +============+===============+=====================================+====================+===========+ | Plant | type:integer | 1. Qn1 | 1: 7 (8.3%) | 84/84 | | | class:ordered | 2. Qn2 | 2: 7 (8.3%) | (100.0%) | | | + factor | 3. Qn3 | 3: 7 (8.3%) | | | | | 4. Qc1 | 4: 7 (8.3%) | | | | | 5. Qc3 | 5: 7 (8.3%) | | | | | 6. Qc2 | 6: 7 (8.3%) | | | | | 7. Mn3 | 7: 7 (8.3%) | | | | | 8. Mn2 | 8: 7 (8.3%) | | | | | 9. Mn1 | 9: 7 (8.3%) | | | | | 10. Mc2 | 10: 7 (8.3%) | | | | | ... 2 other levels | others: 14 (16.7%) | | +------------+---------------+-------------------------------------+--------------------+-----------+ | Type | type:integer | 1. Quebec | 1: 42 (50%) | 84/84 | | | class:factor | 2. Mississippi | 2: 42 (50%) | (100.0%) | +------------+---------------+-------------------------------------+--------------------+-----------+ | Treatment | type:integer | 1. nonchilled | 1: 42 (50%) | 84/84 | | | class:factor | 2. chilled | 2: 42 (50%) | (100.0%) | +------------+---------------+-------------------------------------+--------------------+-----------+ | conc | type:double | mean (sd) = 435 (295.92) | 95: 12 (14.3%) | 84/84 | | | class:numeric | min < med < max = 95 < 350 < 1000 | 175: 12 (14.3%) | (100.0%) | | | | IQR (CV) = 500 (0.68) | 250: 12 (14.3%) | | | | | | 350: 12 (14.3%) | | | | | | 500: 12 (14.3%) | | | | | | 675: 12 (14.3%) | | | | | | 1000: 12 (14.3%) | | +------------+---------------+-------------------------------------+--------------------+-----------+ | uptake | type:double | mean (sd) = 27.21 (10.81) | 76 distinct values | 84/84 | | | class:numeric | min < med < max = 7.7 < 28.3 < 45.5 | | (100.0%) | | | | IQR (CV) = 19.23 (0.4) | | | +------------+---------------+-------------------------------------+--------------------+-----------+ EDIT In newer versions of summarytools, the freq() function (which produces straightforward frequency tables, more to-the-point as regards to the original question) accepts data frames as well as single variables. For cross-tabulations (which proc freq also does), see the ctable() function. freq(CO2) Frequencies CO2$Plant Type: Ordered Factor Freq % Valid % Valid Cum % Total % Total Cum Qn1 7 8.33 8.33 8.33 8.33 Qn2 7 8.33 16.67 8.33 16.67 Qn3 7 8.33 25.00 8.33 25.00 Qc1 7 8.33 33.33 8.33 33.33 Qc3 7 8.33 41.67 8.33 41.67 Qc2 7 8.33 50.00 8.33 50.00 Mn3 7 8.33 58.33 8.33 58.33 Mn2 7 8.33 66.67 8.33 66.67 Mn1 7 8.33 75.00 8.33 75.00 Mc2 7 8.33 83.33 8.33 83.33 Mc3 7 8.33 91.67 8.33 91.67 Mc1 7 8.33 100.00 8.33 100.00 <NA> 0 0.00 100.00 Total 84 100.00 100.00 100.00 100.00 CO2$Type Type: Factor Freq % Valid % Valid Cum % Total % Total Cum Quebec 42 50.00 50.00 50.00 50.00 Mississippi 42 50.00 100.00 50.00 100.00 <NA> 0 0.00 100.00 Total 84 100.00 100.00 100.00 100.00 CO2$Treatment Type: Factor Freq % Valid % Valid Cum % Total % Total Cum nonchilled 42 50.00 50.00 50.00 50.00 chilled 42 50.00 100.00 50.00 100.00 <NA> 0 0.00 100.00 Total 84 100.00 100.00 100.00 100.00
Is there an R equivalent of SAS PROC FREQ?
You can check out my summarytools package (CRAN link) which includes a codebook-like function, with markdown and html formatting options. install.packages("summarytools") library(summarytools) dfSumma
Is there an R equivalent of SAS PROC FREQ? You can check out my summarytools package (CRAN link) which includes a codebook-like function, with markdown and html formatting options. install.packages("summarytools") library(summarytools) dfSummary(CO2, style = "grid", plain.ascii = TRUE) Dataframe Summary CO2 +------------+---------------+-------------------------------------+--------------------+-----------+ | Variable | Properties | Stats / Values | Freqs, % Valid | N Valid | +============+===============+=====================================+====================+===========+ | Plant | type:integer | 1. Qn1 | 1: 7 (8.3%) | 84/84 | | | class:ordered | 2. Qn2 | 2: 7 (8.3%) | (100.0%) | | | + factor | 3. Qn3 | 3: 7 (8.3%) | | | | | 4. Qc1 | 4: 7 (8.3%) | | | | | 5. Qc3 | 5: 7 (8.3%) | | | | | 6. Qc2 | 6: 7 (8.3%) | | | | | 7. Mn3 | 7: 7 (8.3%) | | | | | 8. Mn2 | 8: 7 (8.3%) | | | | | 9. Mn1 | 9: 7 (8.3%) | | | | | 10. Mc2 | 10: 7 (8.3%) | | | | | ... 2 other levels | others: 14 (16.7%) | | +------------+---------------+-------------------------------------+--------------------+-----------+ | Type | type:integer | 1. Quebec | 1: 42 (50%) | 84/84 | | | class:factor | 2. Mississippi | 2: 42 (50%) | (100.0%) | +------------+---------------+-------------------------------------+--------------------+-----------+ | Treatment | type:integer | 1. nonchilled | 1: 42 (50%) | 84/84 | | | class:factor | 2. chilled | 2: 42 (50%) | (100.0%) | +------------+---------------+-------------------------------------+--------------------+-----------+ | conc | type:double | mean (sd) = 435 (295.92) | 95: 12 (14.3%) | 84/84 | | | class:numeric | min < med < max = 95 < 350 < 1000 | 175: 12 (14.3%) | (100.0%) | | | | IQR (CV) = 500 (0.68) | 250: 12 (14.3%) | | | | | | 350: 12 (14.3%) | | | | | | 500: 12 (14.3%) | | | | | | 675: 12 (14.3%) | | | | | | 1000: 12 (14.3%) | | +------------+---------------+-------------------------------------+--------------------+-----------+ | uptake | type:double | mean (sd) = 27.21 (10.81) | 76 distinct values | 84/84 | | | class:numeric | min < med < max = 7.7 < 28.3 < 45.5 | | (100.0%) | | | | IQR (CV) = 19.23 (0.4) | | | +------------+---------------+-------------------------------------+--------------------+-----------+ EDIT In newer versions of summarytools, the freq() function (which produces straightforward frequency tables, more to-the-point as regards to the original question) accepts data frames as well as single variables. For cross-tabulations (which proc freq also does), see the ctable() function. freq(CO2) Frequencies CO2$Plant Type: Ordered Factor Freq % Valid % Valid Cum % Total % Total Cum Qn1 7 8.33 8.33 8.33 8.33 Qn2 7 8.33 16.67 8.33 16.67 Qn3 7 8.33 25.00 8.33 25.00 Qc1 7 8.33 33.33 8.33 33.33 Qc3 7 8.33 41.67 8.33 41.67 Qc2 7 8.33 50.00 8.33 50.00 Mn3 7 8.33 58.33 8.33 58.33 Mn2 7 8.33 66.67 8.33 66.67 Mn1 7 8.33 75.00 8.33 75.00 Mc2 7 8.33 83.33 8.33 83.33 Mc3 7 8.33 91.67 8.33 91.67 Mc1 7 8.33 100.00 8.33 100.00 <NA> 0 0.00 100.00 Total 84 100.00 100.00 100.00 100.00 CO2$Type Type: Factor Freq % Valid % Valid Cum % Total % Total Cum Quebec 42 50.00 50.00 50.00 50.00 Mississippi 42 50.00 100.00 50.00 100.00 <NA> 0 0.00 100.00 Total 84 100.00 100.00 100.00 100.00 CO2$Treatment Type: Factor Freq % Valid % Valid Cum % Total % Total Cum nonchilled 42 50.00 50.00 50.00 50.00 chilled 42 50.00 100.00 50.00 100.00 <NA> 0 0.00 100.00 Total 84 100.00 100.00 100.00 100.00
Is there an R equivalent of SAS PROC FREQ? You can check out my summarytools package (CRAN link) which includes a codebook-like function, with markdown and html formatting options. install.packages("summarytools") library(summarytools) dfSumma
13,123
Is there an R equivalent of SAS PROC FREQ?
I use the codebook function from {EPICALC} which gives summary statistics for a numeric variable and a frequency table with level labels and codes for factors. http://cran.r-project.org/doc/contrib/Epicalc_Book.pdf (see p.50) Moreover, this is very useful because it provides sd for quantitative variables. Enjoy !
Is there an R equivalent of SAS PROC FREQ?
I use the codebook function from {EPICALC} which gives summary statistics for a numeric variable and a frequency table with level labels and codes for factors. http://cran.r-project.org/doc/contrib/Ep
Is there an R equivalent of SAS PROC FREQ? I use the codebook function from {EPICALC} which gives summary statistics for a numeric variable and a frequency table with level labels and codes for factors. http://cran.r-project.org/doc/contrib/Epicalc_Book.pdf (see p.50) Moreover, this is very useful because it provides sd for quantitative variables. Enjoy !
Is there an R equivalent of SAS PROC FREQ? I use the codebook function from {EPICALC} which gives summary statistics for a numeric variable and a frequency table with level labels and codes for factors. http://cran.r-project.org/doc/contrib/Ep
13,124
Is there an R equivalent of SAS PROC FREQ?
Thanks for all the suggestions everyone. I ended up using either table or Rcmdr's numSummary function plus apply: apply(dataframe[,c('need_rbcs','need_platelets','need_ffp')],2,table) This works pretty well and is not too inconvenient. However I will definitely give some of these other solutions a try!
Is there an R equivalent of SAS PROC FREQ?
Thanks for all the suggestions everyone. I ended up using either table or Rcmdr's numSummary function plus apply: apply(dataframe[,c('need_rbcs','need_platelets','need_ffp')],2,table) This works pre
Is there an R equivalent of SAS PROC FREQ? Thanks for all the suggestions everyone. I ended up using either table or Rcmdr's numSummary function plus apply: apply(dataframe[,c('need_rbcs','need_platelets','need_ffp')],2,table) This works pretty well and is not too inconvenient. However I will definitely give some of these other solutions a try!
Is there an R equivalent of SAS PROC FREQ? Thanks for all the suggestions everyone. I ended up using either table or Rcmdr's numSummary function plus apply: apply(dataframe[,c('need_rbcs','need_platelets','need_ffp')],2,table) This works pre
13,125
R package for multilevel structural equation modeling?
It seems that OpenMx (based on Mx but it's now an R package) can do what you are looking for: "Multi Level Analysis"
R package for multilevel structural equation modeling?
It seems that OpenMx (based on Mx but it's now an R package) can do what you are looking for: "Multi Level Analysis"
R package for multilevel structural equation modeling? It seems that OpenMx (based on Mx but it's now an R package) can do what you are looking for: "Multi Level Analysis"
R package for multilevel structural equation modeling? It seems that OpenMx (based on Mx but it's now an R package) can do what you are looking for: "Multi Level Analysis"
13,126
R package for multilevel structural equation modeling?
You can do multilevel SEM in any package that supports multiple group analysis using Muthen's MUML method. You model 2 groups, the first with the within-covariance matrix and the second with the between covariance matrix as data. Then you restrict the relevant parameters to be equal across groups (which depends on the model). So yes, you can do multilevel SEM in lavaan and OpenMx. See http://smr.sagepub.com/content/22/3/376.short
R package for multilevel structural equation modeling?
You can do multilevel SEM in any package that supports multiple group analysis using Muthen's MUML method. You model 2 groups, the first with the within-covariance matrix and the second with the betw
R package for multilevel structural equation modeling? You can do multilevel SEM in any package that supports multiple group analysis using Muthen's MUML method. You model 2 groups, the first with the within-covariance matrix and the second with the between covariance matrix as data. Then you restrict the relevant parameters to be equal across groups (which depends on the model). So yes, you can do multilevel SEM in lavaan and OpenMx. See http://smr.sagepub.com/content/22/3/376.short
R package for multilevel structural equation modeling? You can do multilevel SEM in any package that supports multiple group analysis using Muthen's MUML method. You model 2 groups, the first with the within-covariance matrix and the second with the betw
13,127
R package for multilevel structural equation modeling?
If your model is complicated, I would recommend xxM, a package for R by Paras Mehta. http://xxm.times.uh.edu/ Mehta, P. D. (2013). n-level structural equation modeling. In Y. Petscher, C. Schatschneider & D. L. Compton (Eds.), Applied quantitative analysis in the social sciences (pp. 329-362). New York: Routledge.
R package for multilevel structural equation modeling?
If your model is complicated, I would recommend xxM, a package for R by Paras Mehta. http://xxm.times.uh.edu/ Mehta, P. D. (2013). n-level structural equation modeling. In Y. Petscher, C. Schatschnei
R package for multilevel structural equation modeling? If your model is complicated, I would recommend xxM, a package for R by Paras Mehta. http://xxm.times.uh.edu/ Mehta, P. D. (2013). n-level structural equation modeling. In Y. Petscher, C. Schatschneider & D. L. Compton (Eds.), Applied quantitative analysis in the social sciences (pp. 329-362). New York: Routledge.
R package for multilevel structural equation modeling? If your model is complicated, I would recommend xxM, a package for R by Paras Mehta. http://xxm.times.uh.edu/ Mehta, P. D. (2013). n-level structural equation modeling. In Y. Petscher, C. Schatschnei
13,128
R package for multilevel structural equation modeling?
In regards to the ability to pull this off in any SEM program....yes, you don't always need specialized SEM software, but you might have a hell of a data wrangling job if you don't use SEM software that is specialized for this task. FYI: I don't find openmx to be intuitive. Here's a reference for pulling this off in most any software, which wasn't referenced previously.
R package for multilevel structural equation modeling?
In regards to the ability to pull this off in any SEM program....yes, you don't always need specialized SEM software, but you might have a hell of a data wrangling job if you don't use SEM software th
R package for multilevel structural equation modeling? In regards to the ability to pull this off in any SEM program....yes, you don't always need specialized SEM software, but you might have a hell of a data wrangling job if you don't use SEM software that is specialized for this task. FYI: I don't find openmx to be intuitive. Here's a reference for pulling this off in most any software, which wasn't referenced previously.
R package for multilevel structural equation modeling? In regards to the ability to pull this off in any SEM program....yes, you don't always need specialized SEM software, but you might have a hell of a data wrangling job if you don't use SEM software th
13,129
R package for multilevel structural equation modeling?
Try searching for "structural equation modeling" on http://rseek.org. You'll find several helpful links, including links to several possible packages. You might also check out the Task View for the social sciences, there's a section for structural equation modeling maybe a third of the way down. See http://cran.r-project.org/web/views/SocialSciences.html. One package in particular you might find helpful is John Fox's sem package. http://cran.r-project.org/web/packages/sem/index.html
R package for multilevel structural equation modeling?
Try searching for "structural equation modeling" on http://rseek.org. You'll find several helpful links, including links to several possible packages. You might also check out the Task View for the
R package for multilevel structural equation modeling? Try searching for "structural equation modeling" on http://rseek.org. You'll find several helpful links, including links to several possible packages. You might also check out the Task View for the social sciences, there's a section for structural equation modeling maybe a third of the way down. See http://cran.r-project.org/web/views/SocialSciences.html. One package in particular you might find helpful is John Fox's sem package. http://cran.r-project.org/web/packages/sem/index.html
R package for multilevel structural equation modeling? Try searching for "structural equation modeling" on http://rseek.org. You'll find several helpful links, including links to several possible packages. You might also check out the Task View for the
13,130
R package for multilevel structural equation modeling?
This post is old, but I thought I'd link the question I posted with the solution. It provides a description on how OpenMx can be used for fitting multilevel SEM.
R package for multilevel structural equation modeling?
This post is old, but I thought I'd link the question I posted with the solution. It provides a description on how OpenMx can be used for fitting multilevel SEM.
R package for multilevel structural equation modeling? This post is old, but I thought I'd link the question I posted with the solution. It provides a description on how OpenMx can be used for fitting multilevel SEM.
R package for multilevel structural equation modeling? This post is old, but I thought I'd link the question I posted with the solution. It provides a description on how OpenMx can be used for fitting multilevel SEM.
13,131
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental variables (to deal with endogenity)
To answer your first question, you are correct that sample selection is a specific form of endogeneity (See Antonakis et al. 2010 for a good basic review of endogeneity and common remedies), however you are not correct in saying that the likelihood of being treated is the endogenous variable, as it is the treatment variable itself ("non-random treatment assignment")--rather than the likelihood of being treated--that is endogenous in sample selection. Recall that endogeneity refers to a situation where you have incorrectly identified a causal relationship between factor X and factor Y, when the observed “relationship” is actually due to another factor Z that affects both X and Y. Put another way, given a regression model: $y_i=\beta_0+\beta_1x_i+...+\epsilon_i$ endogeneity occurs when one or more than one of your predictors is related to the error term in the model. That is, when $Cov(x,\epsilon)\ne0$. The common causes of endogenity include: Omitted variables (some things we just can’t measure) Motivation/choice Ability/talent Self-selection Measurement error (we would like to include $x_j$, but we only observe $x_j*$) Simultaneity/bidirectionality (in children under 5, the relationship between the nutritional status indicator “weight for age” and whether the child had a recent illness might be simultaneous. Different types of problems require slightly different solutions, which is where the difference between IV and Heckman-type corrections lie. Of course there are differences in the underlying mechanics of these methods, but the premise is the same: which is to remove endogeneity, ideally via an exclusion restriction, i.e. one or more instruments in the case of IV or a variable that affects selection but not the outcome in the case of Heckman. To answer your second question, you have to think about the differences in the types of data limitations that gave rise to the development of these solutions. I like to think that the instrumental variable (IV) approach is used when one or more variables is endogenous, and there are simply no good proxies to stick in the model to remove the endogeneity, but the covariates and outcomes are observed for all observations. Heckman-type corrections, on the other hand, are used when you have truncation, i.e. the information is not observed for those in sample where the value of the selection variable == 0. The instrumental variable (IV) approach Think of the classic econometric example for IV regression with the two-stage least squares (2SLS) estimator: the effect of education on earnings. $Earnings_i=\beta_0+ \beta_1OwnEd_i + \epsilon_i$ (1) Here level of educational achievement is endogenous because it is determined partly by the individual's motivation and ability, both of which also affect a person's earnings. Motivation and Ability are not typically measured in household or economic surveys. Equation 1 can therefore be written to explicitly include motivation and ability: $Earnings_i=\beta_0+ \{\beta_1OwnEd_i + \beta_2Motiv_i + \beta_3Abil_i\} + \epsilon_i$ (2) Since $Motiv$ and $Abil$ are not actually observed, Equation 2 can be written as: $Earnings_i=\beta_0+ \beta_1OwnEd_i + u_i$ (3), where $u_i=\beta_2Motiv_i + \beta_3Abil_i + \epsilon_i$ (4). Therefore a naïve estimation of the effect of education on earnings via OLS would be biased. This part you already know. In the past, people have used parents' education as instruments for the subject's own level of education, as they fit the 3 requirements for a valid instrument ($z$): $z$ must be related to the endogenous predictor – $𝐶𝑜𝑣(𝑧,𝑥)≠0$, $z$ cannot be directly related to the outcome – $𝐶𝑜𝑣(𝑧,𝑦)=0$, and $z$ cannot be related to the unobservable (u) characteristic (that is, $z$ is exogenous) – $𝐶𝑜𝑣(𝑧,𝑢)=0$ When you estimate the subject's education ($OwnEd$) using parents' education ($MomEd$ and $DadEd$) at first stage and use the predicted value of education ($\widehat{OwnEd}$) to estimate $Earnings$ at second stage, you are (in very simplistic terms), estimating $Earnings$ based on the portion of $OwnEd$ that is not determined by motivation/ability. Heckman-type corrections As we have established before, non-random sample selection is a specific type of endogeneity. In this case, the omitted variable is how people were selected into the sample. Typically, when you have a sample selection problem, your outcome is observed only for those for whom the sample selection variable == 1. This problem is also known as "incidental truncation," and the solution is commonly known as a Heckman correction. The classic example in econometrics is the wage offer of married women: $Wage_i = \beta_0 + \beta_1Educ_i + \beta_2Experience_i + \beta_3Experience^2_i+\epsilon_i$ (5) The problem here is that $Wage$ is only observed for women who worked for wages, so a naïve estimator would be biased, as we do not know what the wage offer is for those who do not participate in the labor force, the selection variable $s$. Equation 5 can be rewritten to show that it is jointly determined by two latent models: $Wage_i^* = X\beta^\prime+\epsilon_i$ (6) $LaborForce_i^* = Z\gamma^\prime+\nu_i$ (7) That is, $Wage = Wage_i^*$ IFF $LaborForce_i^*>0$ and $Wage = . $ IFF $LaborForce_i^*\leq 0$ The solution here is therefore to predict the likelihood of participation in the labor force at first stage using a probit model and the exclusion restriction (the same criteria for valid instruments apply here), calculate the predicted inverse Mills ratio ($\hat{\lambda}$) for each observation, and in second stage, estimate the wage offer using the $\hat{\lambda}$ as a predictor in the model (Wooldridge 2009). If the coefficient on $\hat{\lambda}$ is statistically equal to zero, there is no evidence of sample selection (endogeneity), and OLS results are consistent and can be presented. If the coefficient on $\hat{\lambda}$ is statistically significantly different from zero, you will need to report the coefficients from the corrected model. References Antonakis, John, Samuel Bendahan, Philippe Jacquart, and Rafael Lalive. 2010. “On Making Causal Claims: A Review and Recommendations.” The Leadership Quarterly 21 (6): 1086–1120. doi:10.1016/j.leaqua.2010.10.010. Wooldridge, Jeffrey M. 2009. Introductory Econometrics: A Modern Approach. 4th ed. Mason, OH, USA: South-Western, Cengage Learning.
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental
To answer your first question, you are correct that sample selection is a specific form of endogeneity (See Antonakis et al. 2010 for a good basic review of endogeneity and common remedies), however y
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental variables (to deal with endogenity) To answer your first question, you are correct that sample selection is a specific form of endogeneity (See Antonakis et al. 2010 for a good basic review of endogeneity and common remedies), however you are not correct in saying that the likelihood of being treated is the endogenous variable, as it is the treatment variable itself ("non-random treatment assignment")--rather than the likelihood of being treated--that is endogenous in sample selection. Recall that endogeneity refers to a situation where you have incorrectly identified a causal relationship between factor X and factor Y, when the observed “relationship” is actually due to another factor Z that affects both X and Y. Put another way, given a regression model: $y_i=\beta_0+\beta_1x_i+...+\epsilon_i$ endogeneity occurs when one or more than one of your predictors is related to the error term in the model. That is, when $Cov(x,\epsilon)\ne0$. The common causes of endogenity include: Omitted variables (some things we just can’t measure) Motivation/choice Ability/talent Self-selection Measurement error (we would like to include $x_j$, but we only observe $x_j*$) Simultaneity/bidirectionality (in children under 5, the relationship between the nutritional status indicator “weight for age” and whether the child had a recent illness might be simultaneous. Different types of problems require slightly different solutions, which is where the difference between IV and Heckman-type corrections lie. Of course there are differences in the underlying mechanics of these methods, but the premise is the same: which is to remove endogeneity, ideally via an exclusion restriction, i.e. one or more instruments in the case of IV or a variable that affects selection but not the outcome in the case of Heckman. To answer your second question, you have to think about the differences in the types of data limitations that gave rise to the development of these solutions. I like to think that the instrumental variable (IV) approach is used when one or more variables is endogenous, and there are simply no good proxies to stick in the model to remove the endogeneity, but the covariates and outcomes are observed for all observations. Heckman-type corrections, on the other hand, are used when you have truncation, i.e. the information is not observed for those in sample where the value of the selection variable == 0. The instrumental variable (IV) approach Think of the classic econometric example for IV regression with the two-stage least squares (2SLS) estimator: the effect of education on earnings. $Earnings_i=\beta_0+ \beta_1OwnEd_i + \epsilon_i$ (1) Here level of educational achievement is endogenous because it is determined partly by the individual's motivation and ability, both of which also affect a person's earnings. Motivation and Ability are not typically measured in household or economic surveys. Equation 1 can therefore be written to explicitly include motivation and ability: $Earnings_i=\beta_0+ \{\beta_1OwnEd_i + \beta_2Motiv_i + \beta_3Abil_i\} + \epsilon_i$ (2) Since $Motiv$ and $Abil$ are not actually observed, Equation 2 can be written as: $Earnings_i=\beta_0+ \beta_1OwnEd_i + u_i$ (3), where $u_i=\beta_2Motiv_i + \beta_3Abil_i + \epsilon_i$ (4). Therefore a naïve estimation of the effect of education on earnings via OLS would be biased. This part you already know. In the past, people have used parents' education as instruments for the subject's own level of education, as they fit the 3 requirements for a valid instrument ($z$): $z$ must be related to the endogenous predictor – $𝐶𝑜𝑣(𝑧,𝑥)≠0$, $z$ cannot be directly related to the outcome – $𝐶𝑜𝑣(𝑧,𝑦)=0$, and $z$ cannot be related to the unobservable (u) characteristic (that is, $z$ is exogenous) – $𝐶𝑜𝑣(𝑧,𝑢)=0$ When you estimate the subject's education ($OwnEd$) using parents' education ($MomEd$ and $DadEd$) at first stage and use the predicted value of education ($\widehat{OwnEd}$) to estimate $Earnings$ at second stage, you are (in very simplistic terms), estimating $Earnings$ based on the portion of $OwnEd$ that is not determined by motivation/ability. Heckman-type corrections As we have established before, non-random sample selection is a specific type of endogeneity. In this case, the omitted variable is how people were selected into the sample. Typically, when you have a sample selection problem, your outcome is observed only for those for whom the sample selection variable == 1. This problem is also known as "incidental truncation," and the solution is commonly known as a Heckman correction. The classic example in econometrics is the wage offer of married women: $Wage_i = \beta_0 + \beta_1Educ_i + \beta_2Experience_i + \beta_3Experience^2_i+\epsilon_i$ (5) The problem here is that $Wage$ is only observed for women who worked for wages, so a naïve estimator would be biased, as we do not know what the wage offer is for those who do not participate in the labor force, the selection variable $s$. Equation 5 can be rewritten to show that it is jointly determined by two latent models: $Wage_i^* = X\beta^\prime+\epsilon_i$ (6) $LaborForce_i^* = Z\gamma^\prime+\nu_i$ (7) That is, $Wage = Wage_i^*$ IFF $LaborForce_i^*>0$ and $Wage = . $ IFF $LaborForce_i^*\leq 0$ The solution here is therefore to predict the likelihood of participation in the labor force at first stage using a probit model and the exclusion restriction (the same criteria for valid instruments apply here), calculate the predicted inverse Mills ratio ($\hat{\lambda}$) for each observation, and in second stage, estimate the wage offer using the $\hat{\lambda}$ as a predictor in the model (Wooldridge 2009). If the coefficient on $\hat{\lambda}$ is statistically equal to zero, there is no evidence of sample selection (endogeneity), and OLS results are consistent and can be presented. If the coefficient on $\hat{\lambda}$ is statistically significantly different from zero, you will need to report the coefficients from the corrected model. References Antonakis, John, Samuel Bendahan, Philippe Jacquart, and Rafael Lalive. 2010. “On Making Causal Claims: A Review and Recommendations.” The Leadership Quarterly 21 (6): 1086–1120. doi:10.1016/j.leaqua.2010.10.010. Wooldridge, Jeffrey M. 2009. Introductory Econometrics: A Modern Approach. 4th ed. Mason, OH, USA: South-Western, Cengage Learning.
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental To answer your first question, you are correct that sample selection is a specific form of endogeneity (See Antonakis et al. 2010 for a good basic review of endogeneity and common remedies), however y
13,132
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental variables (to deal with endogenity)
One should make a distinction between the specific Heckman sample selection model (where only one sample is observed) and Heckman-type corrections for self-selection, which can also work for the case where the two samples are observed. The latter is referred to as control function approach, and amounts to include into your second stage a term controlling for the endogeneity. Let us have a standard case with an endogeneous dummy variable D, an instrument Z: $$Y= \beta + \beta_1 D +\epsilon$$ $$D= \gamma + \gamma_1 Z +u$$ Both approaches run a first stage (D on Z). IV uses a standard OLS (even if D is a dummy) Heckman uses a probit. But besides this, the main difference is in the way they use this first stage into the main equation: IV: break the endogeneity by decomposing D into parts uncorrelated with $\epsilon$, given by the prediction of D: $Y= \beta + \beta_1 \hat{D}+\epsilon$ Heckman: model the endogeneity: keep the endogenous D, but add a function of the predicted values of the first stage. For this case, it is a pretty complicated function: $Y= \beta + \beta_1 D + \beta_2 \left[\lambda(\hat{D})-\lambda(-\hat{D})\right ] +\epsilon$ where $\lambda()$ is the inverse Mills ratio The advantage of the Heckman procedure is that it provides a direct test for endogeneity: the coefficient $\beta_2$. On the other side, the Heckman procedure relies on the assumption of joint normality of the errors, while the IV does not make any such assumption. So you have the standard story that with normal errors, the control function will be more efficient (especially if ones uses the MLE instead of the two-step shown here) than the IV, but that if the assumption does not hold, IV would be better. As researchers have become more suspicious about the assumption of normality, the IV is used more often.
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental
One should make a distinction between the specific Heckman sample selection model (where only one sample is observed) and Heckman-type corrections for self-selection, which can also work for the case
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental variables (to deal with endogenity) One should make a distinction between the specific Heckman sample selection model (where only one sample is observed) and Heckman-type corrections for self-selection, which can also work for the case where the two samples are observed. The latter is referred to as control function approach, and amounts to include into your second stage a term controlling for the endogeneity. Let us have a standard case with an endogeneous dummy variable D, an instrument Z: $$Y= \beta + \beta_1 D +\epsilon$$ $$D= \gamma + \gamma_1 Z +u$$ Both approaches run a first stage (D on Z). IV uses a standard OLS (even if D is a dummy) Heckman uses a probit. But besides this, the main difference is in the way they use this first stage into the main equation: IV: break the endogeneity by decomposing D into parts uncorrelated with $\epsilon$, given by the prediction of D: $Y= \beta + \beta_1 \hat{D}+\epsilon$ Heckman: model the endogeneity: keep the endogenous D, but add a function of the predicted values of the first stage. For this case, it is a pretty complicated function: $Y= \beta + \beta_1 D + \beta_2 \left[\lambda(\hat{D})-\lambda(-\hat{D})\right ] +\epsilon$ where $\lambda()$ is the inverse Mills ratio The advantage of the Heckman procedure is that it provides a direct test for endogeneity: the coefficient $\beta_2$. On the other side, the Heckman procedure relies on the assumption of joint normality of the errors, while the IV does not make any such assumption. So you have the standard story that with normal errors, the control function will be more efficient (especially if ones uses the MLE instead of the two-step shown here) than the IV, but that if the assumption does not hold, IV would be better. As researchers have become more suspicious about the assumption of normality, the IV is used more often.
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental One should make a distinction between the specific Heckman sample selection model (where only one sample is observed) and Heckman-type corrections for self-selection, which can also work for the case
13,133
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental variables (to deal with endogenity)
From Heckman, Urzua and Vytlacil (2006): Example of selection bias: Consider the effects of a policy on the outcome of a country (e.g. GDP). If the countries that would have done well in terms of the unobservable even in the absence of the policy are the ones that adopt the policy, then the OLS estimates are biased. Two main approaches have been adopted to solve this problem: (a) selection models and (b) instrumental variable models. The selection approach models levels of conditional means. The IV approach models the slopes of the conditional means. IV does not identify the constants estimated in selection models. The IV approach does not condition on D (the treatment). The selection (control function) estimator identifies the conditional means using control functions. When using control functions with curvature assumptions, one does not require an exclusion restriction (does not require $Z\neq X$) in the selection model. By assuming a functional form for the distribution of the error terms, one rules out the possibility that the conditional mean of the outcome equation equals the conditional control function, and thus you can correct for selection without exclusion restrictions. See also Heckman and Navarro (2004).
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental
From Heckman, Urzua and Vytlacil (2006): Example of selection bias: Consider the effects of a policy on the outcome of a country (e.g. GDP). If the countries that would have done well in terms of the
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental variables (to deal with endogenity) From Heckman, Urzua and Vytlacil (2006): Example of selection bias: Consider the effects of a policy on the outcome of a country (e.g. GDP). If the countries that would have done well in terms of the unobservable even in the absence of the policy are the ones that adopt the policy, then the OLS estimates are biased. Two main approaches have been adopted to solve this problem: (a) selection models and (b) instrumental variable models. The selection approach models levels of conditional means. The IV approach models the slopes of the conditional means. IV does not identify the constants estimated in selection models. The IV approach does not condition on D (the treatment). The selection (control function) estimator identifies the conditional means using control functions. When using control functions with curvature assumptions, one does not require an exclusion restriction (does not require $Z\neq X$) in the selection model. By assuming a functional form for the distribution of the error terms, one rules out the possibility that the conditional mean of the outcome equation equals the conditional control function, and thus you can correct for selection without exclusion restrictions. See also Heckman and Navarro (2004).
Two stage models: Difference between Heckman models (to deal with sample selection) and Instrumental From Heckman, Urzua and Vytlacil (2006): Example of selection bias: Consider the effects of a policy on the outcome of a country (e.g. GDP). If the countries that would have done well in terms of the
13,134
hinge loss vs logistic loss advantages and disadvantages/limitations
Logarithmic loss minimization leads to well-behaved probabilistic outputs. Hinge loss leads to some (not guaranteed) sparsity on the dual, but it doesn't help at probability estimation. Instead, it punishes misclassifications (that's why it's so useful to determine margins): diminishing hinge-loss comes with diminishing across margin misclassifications. So, summarizing: Logarithmic loss leads to better probability estimation at the cost of accuracy Hinge loss leads to better accuracy and some sparsity at the cost of much less sensitivity regarding probabilities
hinge loss vs logistic loss advantages and disadvantages/limitations
Logarithmic loss minimization leads to well-behaved probabilistic outputs. Hinge loss leads to some (not guaranteed) sparsity on the dual, but it doesn't help at probability estimation. Instead, it pu
hinge loss vs logistic loss advantages and disadvantages/limitations Logarithmic loss minimization leads to well-behaved probabilistic outputs. Hinge loss leads to some (not guaranteed) sparsity on the dual, but it doesn't help at probability estimation. Instead, it punishes misclassifications (that's why it's so useful to determine margins): diminishing hinge-loss comes with diminishing across margin misclassifications. So, summarizing: Logarithmic loss leads to better probability estimation at the cost of accuracy Hinge loss leads to better accuracy and some sparsity at the cost of much less sensitivity regarding probabilities
hinge loss vs logistic loss advantages and disadvantages/limitations Logarithmic loss minimization leads to well-behaved probabilistic outputs. Hinge loss leads to some (not guaranteed) sparsity on the dual, but it doesn't help at probability estimation. Instead, it pu
13,135
hinge loss vs logistic loss advantages and disadvantages/limitations
@Firebug had a good answer (+1). In fact, I had a similar question here. What are the impacts of choosing different loss functions in classification to approximate 0-1 loss I just want to add more on another big advantages of logistic loss: probabilistic interpretation. An example, can be found here Specifically, logistic regression is a classical model in statistics literature. (See, What does the name "Logistic Regression" mean? for the naming.) There are many important concept related to logistic loss, such as maximize log likelihood estimation, likelihood ratio tests, as well as assumptions on binomial. Here are some related discussions. Likelihood ratio test in R Why isn't Logistic Regression called Logistic Classification? Is there i.i.d. assumption on logistic regression? Difference between logit and probit models
hinge loss vs logistic loss advantages and disadvantages/limitations
@Firebug had a good answer (+1). In fact, I had a similar question here. What are the impacts of choosing different loss functions in classification to approximate 0-1 loss I just want to add more on
hinge loss vs logistic loss advantages and disadvantages/limitations @Firebug had a good answer (+1). In fact, I had a similar question here. What are the impacts of choosing different loss functions in classification to approximate 0-1 loss I just want to add more on another big advantages of logistic loss: probabilistic interpretation. An example, can be found here Specifically, logistic regression is a classical model in statistics literature. (See, What does the name "Logistic Regression" mean? for the naming.) There are many important concept related to logistic loss, such as maximize log likelihood estimation, likelihood ratio tests, as well as assumptions on binomial. Here are some related discussions. Likelihood ratio test in R Why isn't Logistic Regression called Logistic Classification? Is there i.i.d. assumption on logistic regression? Difference between logit and probit models
hinge loss vs logistic loss advantages and disadvantages/limitations @Firebug had a good answer (+1). In fact, I had a similar question here. What are the impacts of choosing different loss functions in classification to approximate 0-1 loss I just want to add more on
13,136
hinge loss vs logistic loss advantages and disadvantages/limitations
Since @hxd1011 added a advantage of cross entropy, I'll be adding one drawback of it. Cross entropy error is one of many distance measures between probability distributions, but one drawback of it is that distributions with long tails can be modeled poorly with too much weight given to the unlikely events.
hinge loss vs logistic loss advantages and disadvantages/limitations
Since @hxd1011 added a advantage of cross entropy, I'll be adding one drawback of it. Cross entropy error is one of many distance measures between probability distributions, but one drawback of it is
hinge loss vs logistic loss advantages and disadvantages/limitations Since @hxd1011 added a advantage of cross entropy, I'll be adding one drawback of it. Cross entropy error is one of many distance measures between probability distributions, but one drawback of it is that distributions with long tails can be modeled poorly with too much weight given to the unlikely events.
hinge loss vs logistic loss advantages and disadvantages/limitations Since @hxd1011 added a advantage of cross entropy, I'll be adding one drawback of it. Cross entropy error is one of many distance measures between probability distributions, but one drawback of it is
13,137
What is the proper association measure of a variable with a PCA component (on a biplot / loading plot)?
Explanation of a loading plot of PCA or Factor analysis. Loading plot shows variables as points in the space of principal components (or factors). The coordinates of variables are, usually, the loadings. (If you properly combine loading plot with the corresponding scatterplot of data cases in the same components space, that would be biplot.) Let us have 3 somehow correlated variables, $V$, $W$, $U$. We center them and perform PCA, extracting 2 first principal components out of three: $F_1$ and $F_2$. We use loadings as the coordinates to do the loading plot below. Loadings are the unstandardized eigenvectors' elements, i.e. eigenvectors endowed by corresponding component variances, or eigenvalues. Loading plot is the plane on the picture. Let's consider only variable $V$. The arrow habitually drawn on a loading plot is what is labeled $h'$ here; the coordinates $a_1$, $a_2$ are the loadings of $V$ with $F_1$ and $F_2$, respectively (please know that terminologically is more correct to say "component loads a variable", not vice versa). Arrow $h'$ is the projection, on the component plane, of vector $h$ which is the true position of variable $V$ in the variables' space spanned by $V$, $W$, $U$. The squared length of the vector, $h^2$, is the variance$\bf^a$ of $V$. While $h'^2$ is the portion of that variance explained by the two components. Loading, correlation, projected correlation. Since variables were centered prior extraction of components, $\cos \phi$ is the Pearson correlation between $V$ and component $F_1$. That should not be confused with $\cos \alpha$ on the loading plot, which is another quantity: it is Pearson correlation between component $F_1$ and variable vectored here as $h'$. As a variable, $h'$ is the prediction of $V$ by the (standardized) components in linear regression (compare with drawing of linear regression geometry here) where loadings $a$'s are the regression coefficients (when components are kept orthogonal, as extracted). Further. We may remember (trigonometry) that $a_1 = h \cdot \cos \phi$. It can be understood as the scalar product between vector $V$ and unit-length vector $F_1$: $h \cdot 1 \cdot \cos \phi$. $F_1$ is set that unit-variance vector because it has no its own variance apart from that variance of $V$ which it explains (by amount $h'$): i.e. $F_1$ is an extracted-from-V,W,U and not an invited-from-outside entity. Then, clearly, $a_1 = \sqrt{var_{V} \cdot var_{F_1}} \cdot r = h \cdot 1 \cdot \cos \phi$ is the covariance between $V$ and standardized, unit-scaled$\bf^b$ (to set $s_1=\sqrt{var_{F_1}}=1$) component $F_1$. This covariance is directly comparable with the covariances between the input variables; for example, the covariance between $V$ and $W$ will be the product of their vector lengths multiplied by the cosine between them. To sum up: loading $a_1$ can be seen as the covariance between the standardized component and the observed variable, $h \cdot 1 \cdot \cos \phi$, or equivalently between the standardized component and the explained (by all the components defining the plot) image of the variable, $h' \cdot 1 \cdot \cos \alpha$. That $\cos \alpha$ could be called V-F1 correlation projected on the F1-F2 component subspace. The aforesaid correlation between a variable and a component, $\cos \phi = a_1/h$, is also called standardized or rescaled loading. It is convenient in interpretation of components because it in the range [-1,1]. Relation to eigenvectors. Rescaled loading $\cos \phi$ should not be confused with the eigenvector element which - as we know it - is the cosine of the angle between a variable and a principal component. Recall that loading is eigenvector element scaled up by the component's singular value (sq. root of the eigenvalue). I.e. for variable $V$ of our plot: $a_1= e_1s_1$, where $s_1$ is the st. deviation (not $1$ but original, i.e. the singular value) of $F_1$ latent variable. Then it comes that eigenvector element $e_1= \frac{a_1}{s_1}=\frac{h}{s_1}\cos \phi$, not the $\cos \phi$ itself. The confusion around two words "cosine" dissolves when we recall what kind of space representation we are in. Eigenvector value is cosine of the angle of rotation of a variable as axis into pr. component as axis within variable space (aka scatterplot view), such as here. While $\cos \phi$ on our loading plot is the cosine similarity measure between a variable as vector and a pr. component as ... well.. as vector too, if you like (albeit it is drawn as axis on the plot), - for we are currently in the subject space (which loading plot is) where correlated variables are fans of vectors - not are orthogonal axes, - and the vector angles are the measure of association - and not of space base rotation. Whereas loading is the angular (i.e. scalar product type) association measure between a variable and a unit-scaled component, and rescaled loading is the standardized loading where the scale of the variable is reduced to unit either, but eigenvector coefficient is the loading where the component is "overstandardized", i.e. was brought to scale $1/s$ (rather than 1); alternatively, it can be thought of as a rescaled loading where scale of the variable was brought to $h/s$ (instead of 1). So, what are associations between a variable and a component? You may choose what you like. It may be the loading (covariance with unit scaled component) $a$; the rescaled loading $\cos \phi$ (= variable-component correlation); correlation between the image (prediction) and the component (= projected correlation $\cos \alpha$). You might even choose eigenvector coefficient $e= a/s$ if you need (though I wonder what might be a reason). Or invent your own measure. Eigenvector value squared has the meaning of the contribution of a variable into a pr. component. Rescaled loading squared has the meaning of the contribution of a pr. component into a variable. Relation to PCA based on correlations. If we PCA-analyzed not just centered but standardized (centered then unit-variance scaled) variables, then the three variables vectors (not their projections on the plane) would be of the same, unit length. Then it automatically follows that a loading is correlation, not covariance, between a variable and a component. But that correlation won't be equal to "standardized loading" $\cos \phi$ of the picture above (based on the analysis of just centered variables), because PCA of standardized variables (correlations-based PCA) yields different components than PCA of centered variables (covariances-based PCA). In correlation-based PCA $a_1= \cos \phi$ because $h=1$, but principal components are not those same principal components as we get from covariances-based PCA (read, read). In factor analysis, loading plot has basically the same concept and interpretation as in PCA. The only (but important) difference is the substance of $h'$. In factor analysis, $h'$ - called then "communality" of the variable - is the portion of its variance that is explained by common factors which are responsible specifically for correlations among variables. While in PCA the explained portion $h'$ is gross "mixture" - it partly represents correlatedness and partly unrelatedness among variables. With factor analysis, the plane of loadings on our picture would be oriented differently (actually, it will even extend out of our 3d variables' space into the 4th dimension, which we cannot draw; the loadings plane won't be a subspace of our 3d space spanned by $V$ and the other two variables), and projection $h'$ will be of another length and with another angle $\alpha$. (The theoretical difference between PCA and factor analysis is explained geometrically here via subject space representation and here via variable space representation.) $\bf^{a,b}$ A reply to @Antoni Parellada's request in comments. It is equivalent whether you prefer to speak in terms of variance or in terms of scatter (SS of deviation): variance = scatter $/(n-1)$, where $n$ is the sample size. Because we are dealing with one dataset with same $n$, the constant changes nothing in the formulas. If $\bf X$ is the data (with variables V,W,U centered), then the eigendecomposition of its (A) covariance matrix yields same eigenvalues (component variances) and eigenvectors as the eigendecomposition of (B) scatter matrix $\bf X'X$ obtained after initial division of $\bf X$ by $\sqrt{n-1}$ factor. After that, in the formula of a loading (see the middle section of the answer), $a_1 = h \cdot s_1 \cdot \cos \phi$, term $h$ is st. deviation $\sqrt{var_{V}}$ in (A) but root scatter (i.e. norm) $\Vert V \Vert$ in (B). Term $s_1$, which equals $1$, is the standardized $F_1$ component's st. deviation $\sqrt{var_{F_1}}$ in (A) but root scatter $\Vert F_1 \Vert$ in (B). Finally, $\cos \phi = r$ is the correlation which is insensitive to the usage of $n-1$ in its calculations. Thus, we simply speak conceptually of variances (A) or of scatters (B), while the values themselves remain the same in the formula in both instances.
What is the proper association measure of a variable with a PCA component (on a biplot / loading plo
Explanation of a loading plot of PCA or Factor analysis. Loading plot shows variables as points in the space of principal components (or factors). The coordinates of variables are, usually, the loadin
What is the proper association measure of a variable with a PCA component (on a biplot / loading plot)? Explanation of a loading plot of PCA or Factor analysis. Loading plot shows variables as points in the space of principal components (or factors). The coordinates of variables are, usually, the loadings. (If you properly combine loading plot with the corresponding scatterplot of data cases in the same components space, that would be biplot.) Let us have 3 somehow correlated variables, $V$, $W$, $U$. We center them and perform PCA, extracting 2 first principal components out of three: $F_1$ and $F_2$. We use loadings as the coordinates to do the loading plot below. Loadings are the unstandardized eigenvectors' elements, i.e. eigenvectors endowed by corresponding component variances, or eigenvalues. Loading plot is the plane on the picture. Let's consider only variable $V$. The arrow habitually drawn on a loading plot is what is labeled $h'$ here; the coordinates $a_1$, $a_2$ are the loadings of $V$ with $F_1$ and $F_2$, respectively (please know that terminologically is more correct to say "component loads a variable", not vice versa). Arrow $h'$ is the projection, on the component plane, of vector $h$ which is the true position of variable $V$ in the variables' space spanned by $V$, $W$, $U$. The squared length of the vector, $h^2$, is the variance$\bf^a$ of $V$. While $h'^2$ is the portion of that variance explained by the two components. Loading, correlation, projected correlation. Since variables were centered prior extraction of components, $\cos \phi$ is the Pearson correlation between $V$ and component $F_1$. That should not be confused with $\cos \alpha$ on the loading plot, which is another quantity: it is Pearson correlation between component $F_1$ and variable vectored here as $h'$. As a variable, $h'$ is the prediction of $V$ by the (standardized) components in linear regression (compare with drawing of linear regression geometry here) where loadings $a$'s are the regression coefficients (when components are kept orthogonal, as extracted). Further. We may remember (trigonometry) that $a_1 = h \cdot \cos \phi$. It can be understood as the scalar product between vector $V$ and unit-length vector $F_1$: $h \cdot 1 \cdot \cos \phi$. $F_1$ is set that unit-variance vector because it has no its own variance apart from that variance of $V$ which it explains (by amount $h'$): i.e. $F_1$ is an extracted-from-V,W,U and not an invited-from-outside entity. Then, clearly, $a_1 = \sqrt{var_{V} \cdot var_{F_1}} \cdot r = h \cdot 1 \cdot \cos \phi$ is the covariance between $V$ and standardized, unit-scaled$\bf^b$ (to set $s_1=\sqrt{var_{F_1}}=1$) component $F_1$. This covariance is directly comparable with the covariances between the input variables; for example, the covariance between $V$ and $W$ will be the product of their vector lengths multiplied by the cosine between them. To sum up: loading $a_1$ can be seen as the covariance between the standardized component and the observed variable, $h \cdot 1 \cdot \cos \phi$, or equivalently between the standardized component and the explained (by all the components defining the plot) image of the variable, $h' \cdot 1 \cdot \cos \alpha$. That $\cos \alpha$ could be called V-F1 correlation projected on the F1-F2 component subspace. The aforesaid correlation between a variable and a component, $\cos \phi = a_1/h$, is also called standardized or rescaled loading. It is convenient in interpretation of components because it in the range [-1,1]. Relation to eigenvectors. Rescaled loading $\cos \phi$ should not be confused with the eigenvector element which - as we know it - is the cosine of the angle between a variable and a principal component. Recall that loading is eigenvector element scaled up by the component's singular value (sq. root of the eigenvalue). I.e. for variable $V$ of our plot: $a_1= e_1s_1$, where $s_1$ is the st. deviation (not $1$ but original, i.e. the singular value) of $F_1$ latent variable. Then it comes that eigenvector element $e_1= \frac{a_1}{s_1}=\frac{h}{s_1}\cos \phi$, not the $\cos \phi$ itself. The confusion around two words "cosine" dissolves when we recall what kind of space representation we are in. Eigenvector value is cosine of the angle of rotation of a variable as axis into pr. component as axis within variable space (aka scatterplot view), such as here. While $\cos \phi$ on our loading plot is the cosine similarity measure between a variable as vector and a pr. component as ... well.. as vector too, if you like (albeit it is drawn as axis on the plot), - for we are currently in the subject space (which loading plot is) where correlated variables are fans of vectors - not are orthogonal axes, - and the vector angles are the measure of association - and not of space base rotation. Whereas loading is the angular (i.e. scalar product type) association measure between a variable and a unit-scaled component, and rescaled loading is the standardized loading where the scale of the variable is reduced to unit either, but eigenvector coefficient is the loading where the component is "overstandardized", i.e. was brought to scale $1/s$ (rather than 1); alternatively, it can be thought of as a rescaled loading where scale of the variable was brought to $h/s$ (instead of 1). So, what are associations between a variable and a component? You may choose what you like. It may be the loading (covariance with unit scaled component) $a$; the rescaled loading $\cos \phi$ (= variable-component correlation); correlation between the image (prediction) and the component (= projected correlation $\cos \alpha$). You might even choose eigenvector coefficient $e= a/s$ if you need (though I wonder what might be a reason). Or invent your own measure. Eigenvector value squared has the meaning of the contribution of a variable into a pr. component. Rescaled loading squared has the meaning of the contribution of a pr. component into a variable. Relation to PCA based on correlations. If we PCA-analyzed not just centered but standardized (centered then unit-variance scaled) variables, then the three variables vectors (not their projections on the plane) would be of the same, unit length. Then it automatically follows that a loading is correlation, not covariance, between a variable and a component. But that correlation won't be equal to "standardized loading" $\cos \phi$ of the picture above (based on the analysis of just centered variables), because PCA of standardized variables (correlations-based PCA) yields different components than PCA of centered variables (covariances-based PCA). In correlation-based PCA $a_1= \cos \phi$ because $h=1$, but principal components are not those same principal components as we get from covariances-based PCA (read, read). In factor analysis, loading plot has basically the same concept and interpretation as in PCA. The only (but important) difference is the substance of $h'$. In factor analysis, $h'$ - called then "communality" of the variable - is the portion of its variance that is explained by common factors which are responsible specifically for correlations among variables. While in PCA the explained portion $h'$ is gross "mixture" - it partly represents correlatedness and partly unrelatedness among variables. With factor analysis, the plane of loadings on our picture would be oriented differently (actually, it will even extend out of our 3d variables' space into the 4th dimension, which we cannot draw; the loadings plane won't be a subspace of our 3d space spanned by $V$ and the other two variables), and projection $h'$ will be of another length and with another angle $\alpha$. (The theoretical difference between PCA and factor analysis is explained geometrically here via subject space representation and here via variable space representation.) $\bf^{a,b}$ A reply to @Antoni Parellada's request in comments. It is equivalent whether you prefer to speak in terms of variance or in terms of scatter (SS of deviation): variance = scatter $/(n-1)$, where $n$ is the sample size. Because we are dealing with one dataset with same $n$, the constant changes nothing in the formulas. If $\bf X$ is the data (with variables V,W,U centered), then the eigendecomposition of its (A) covariance matrix yields same eigenvalues (component variances) and eigenvectors as the eigendecomposition of (B) scatter matrix $\bf X'X$ obtained after initial division of $\bf X$ by $\sqrt{n-1}$ factor. After that, in the formula of a loading (see the middle section of the answer), $a_1 = h \cdot s_1 \cdot \cos \phi$, term $h$ is st. deviation $\sqrt{var_{V}}$ in (A) but root scatter (i.e. norm) $\Vert V \Vert$ in (B). Term $s_1$, which equals $1$, is the standardized $F_1$ component's st. deviation $\sqrt{var_{F_1}}$ in (A) but root scatter $\Vert F_1 \Vert$ in (B). Finally, $\cos \phi = r$ is the correlation which is insensitive to the usage of $n-1$ in its calculations. Thus, we simply speak conceptually of variances (A) or of scatters (B), while the values themselves remain the same in the formula in both instances.
What is the proper association measure of a variable with a PCA component (on a biplot / loading plo Explanation of a loading plot of PCA or Factor analysis. Loading plot shows variables as points in the space of principal components (or factors). The coordinates of variables are, usually, the loadin
13,138
Can the MIC algorithm for detecting non-linear correlations be explained intuitively?
Is it not telling that this was published in a non-statistical journal whose statistical peer review we are unsure of? This problem was solved by Hoeffding in 1948 (Annals of Mathematical Statistics 19:546) who developed a straightforward algorithm requiring no binning nor multiple steps. Hoeffding's work was not even referenced in the Science article. This has been in the R hoeffd function in the Hmisc package for many years. Here's an example (type example(hoeffd) in R): # Hoeffding's test can detect even one-to-many dependency set.seed(1) x <- seq(-10,10,length=200) y <- x*sign(runif(200,-1,1)) plot(x,y) # an X hoeffd(x,y) # also accepts a numeric matrix D x y x 1.00 0.06 y 0.06 1.00 n= 200 P x y x 0 # P-value is very small y 0 hoeffd uses a fairly efficient Fortran implementation of Hoeffding's method. The basic idea of his test is to consider the difference between joint ranks of X and Y and the product of the marginal rank of X and the marginal rank of Y, suitably scaled. Update I have since been corresponding with the authors (who are very nice by the way, and are open to other ideas and are continuing to research their methods). They originally had the Hoeffding reference in their manuscript but cut it (with regrets, now) for lack of space. While Hoeffding's $D$ test seems to perform well for detecting dependence in their examples, it does not provide an index that meets their criteria of ordering degrees of dependence the way the human eye is able to. In an upcoming release of the R Hmisc package I've added two additional outputs related to $D$, namely the mean and max $|F(x,y) - G(x)H(y)|$ which are useful measures of dependence. However these measures, like $D$, do not have the property that the creators of MIC were seeking.
Can the MIC algorithm for detecting non-linear correlations be explained intuitively?
Is it not telling that this was published in a non-statistical journal whose statistical peer review we are unsure of? This problem was solved by Hoeffding in 1948 (Annals of Mathematical Statistics
Can the MIC algorithm for detecting non-linear correlations be explained intuitively? Is it not telling that this was published in a non-statistical journal whose statistical peer review we are unsure of? This problem was solved by Hoeffding in 1948 (Annals of Mathematical Statistics 19:546) who developed a straightforward algorithm requiring no binning nor multiple steps. Hoeffding's work was not even referenced in the Science article. This has been in the R hoeffd function in the Hmisc package for many years. Here's an example (type example(hoeffd) in R): # Hoeffding's test can detect even one-to-many dependency set.seed(1) x <- seq(-10,10,length=200) y <- x*sign(runif(200,-1,1)) plot(x,y) # an X hoeffd(x,y) # also accepts a numeric matrix D x y x 1.00 0.06 y 0.06 1.00 n= 200 P x y x 0 # P-value is very small y 0 hoeffd uses a fairly efficient Fortran implementation of Hoeffding's method. The basic idea of his test is to consider the difference between joint ranks of X and Y and the product of the marginal rank of X and the marginal rank of Y, suitably scaled. Update I have since been corresponding with the authors (who are very nice by the way, and are open to other ideas and are continuing to research their methods). They originally had the Hoeffding reference in their manuscript but cut it (with regrets, now) for lack of space. While Hoeffding's $D$ test seems to perform well for detecting dependence in their examples, it does not provide an index that meets their criteria of ordering degrees of dependence the way the human eye is able to. In an upcoming release of the R Hmisc package I've added two additional outputs related to $D$, namely the mean and max $|F(x,y) - G(x)H(y)|$ which are useful measures of dependence. However these measures, like $D$, do not have the property that the creators of MIC were seeking.
Can the MIC algorithm for detecting non-linear correlations be explained intuitively? Is it not telling that this was published in a non-statistical journal whose statistical peer review we are unsure of? This problem was solved by Hoeffding in 1948 (Annals of Mathematical Statistics
13,139
Can the MIC algorithm for detecting non-linear correlations be explained intuitively?
The MIC method is based on mutual information (MI), which quantifies the dependence between the joint distribution of $X$ and $Y$ and what the joint distribution would be if $X$ and $Y$ were independent (see, e.g., the Wikipedia entry). Mathematically, MI is defined as $$MI=H(X)+H(Y)-H(X,Y)$$ where $$H(X)=-\sum_i p(z_i)\log p(z_i)$$ is the entropy of a single variable and $$H(X,Y)=-\sum_{i,j} p(x_i,y_j)\log p(x_i,y_j)$$ is the joint entropy of two variables. The authors' main idea is to discretize the data onto many different two-dimensional grids and calculate normalized scores that represents the mutual information of the two variables on each grid. The scores are normalized to ensure a fair comparison between different grids and vary between 0 (uncorrelated) and 1 (high correlations). MIC is defined as the highest score obtained and is an indication of how strongly the two variables are correlated. In fact, the authors claim that for noiseless functional relationships MIC values are comparable to the coefficient of determination ($R^2$).
Can the MIC algorithm for detecting non-linear correlations be explained intuitively?
The MIC method is based on mutual information (MI), which quantifies the dependence between the joint distribution of $X$ and $Y$ and what the joint distribution would be if $X$ and $Y$ were independe
Can the MIC algorithm for detecting non-linear correlations be explained intuitively? The MIC method is based on mutual information (MI), which quantifies the dependence between the joint distribution of $X$ and $Y$ and what the joint distribution would be if $X$ and $Y$ were independent (see, e.g., the Wikipedia entry). Mathematically, MI is defined as $$MI=H(X)+H(Y)-H(X,Y)$$ where $$H(X)=-\sum_i p(z_i)\log p(z_i)$$ is the entropy of a single variable and $$H(X,Y)=-\sum_{i,j} p(x_i,y_j)\log p(x_i,y_j)$$ is the joint entropy of two variables. The authors' main idea is to discretize the data onto many different two-dimensional grids and calculate normalized scores that represents the mutual information of the two variables on each grid. The scores are normalized to ensure a fair comparison between different grids and vary between 0 (uncorrelated) and 1 (high correlations). MIC is defined as the highest score obtained and is an indication of how strongly the two variables are correlated. In fact, the authors claim that for noiseless functional relationships MIC values are comparable to the coefficient of determination ($R^2$).
Can the MIC algorithm for detecting non-linear correlations be explained intuitively? The MIC method is based on mutual information (MI), which quantifies the dependence between the joint distribution of $X$ and $Y$ and what the joint distribution would be if $X$ and $Y$ were independe
13,140
Can the MIC algorithm for detecting non-linear correlations be explained intuitively?
I found two good articles explaining more clearly the idea of MIC. In particular the blog post "large-scale data exploration, MIC-style", and Gelman's blog post "Mr. Pearson, meet Mr. Mandelbrot: Detecting Novel Associations in Large Data Sets". As I understood from these reads is that you can zoom in to different complexities and scales of relationships between two variables by exploring different combinations of grids; these grids are used to split the 2 dimensional space into cells. By choosing the grid that holds the most information on how the cells partition the space you are choosing the MIC. I would like to ask @mbq if he could expand what he called "plot-all-scatterplots-and-peak-those-with-biggest-white-area" and unreal complexity of $O(M^2)$.
Can the MIC algorithm for detecting non-linear correlations be explained intuitively?
I found two good articles explaining more clearly the idea of MIC. In particular the blog post "large-scale data exploration, MIC-style", and Gelman's blog post "Mr. Pearson, meet Mr. Mandelbrot: Dete
Can the MIC algorithm for detecting non-linear correlations be explained intuitively? I found two good articles explaining more clearly the idea of MIC. In particular the blog post "large-scale data exploration, MIC-style", and Gelman's blog post "Mr. Pearson, meet Mr. Mandelbrot: Detecting Novel Associations in Large Data Sets". As I understood from these reads is that you can zoom in to different complexities and scales of relationships between two variables by exploring different combinations of grids; these grids are used to split the 2 dimensional space into cells. By choosing the grid that holds the most information on how the cells partition the space you are choosing the MIC. I would like to ask @mbq if he could expand what he called "plot-all-scatterplots-and-peak-those-with-biggest-white-area" and unreal complexity of $O(M^2)$.
Can the MIC algorithm for detecting non-linear correlations be explained intuitively? I found two good articles explaining more clearly the idea of MIC. In particular the blog post "large-scale data exploration, MIC-style", and Gelman's blog post "Mr. Pearson, meet Mr. Mandelbrot: Dete
13,141
Why uppercase for $X$ and lowercase for $y$?
The question about why $X$ and $y$ are popular choices in mathematical notions has been answered in the History of Science and Mathematics SE website: Why are X and Y commonly used as mathematical placeholders? (In short: cause Descartes said so!) In terms of Linear Algebra, it is extremely common to use capital Latin letters for matrices (e.g. design matrix $X$) and lowercase Latin letters for vectors (response vector $y$). Standard textbooks on the use of matrices in Statistics (e.g. Matrix Algebra Useful for Statistics by Searle, Matrix Algebra From a Statistician's Perspective by Harville and Matrix Algebra: Theory, Computations, and Applications in Statistics by Gentle) utilise this convention too, so it has become a standard way to denote things.
Why uppercase for $X$ and lowercase for $y$?
The question about why $X$ and $y$ are popular choices in mathematical notions has been answered in the History of Science and Mathematics SE website: Why are X and Y commonly used as mathematical pla
Why uppercase for $X$ and lowercase for $y$? The question about why $X$ and $y$ are popular choices in mathematical notions has been answered in the History of Science and Mathematics SE website: Why are X and Y commonly used as mathematical placeholders? (In short: cause Descartes said so!) In terms of Linear Algebra, it is extremely common to use capital Latin letters for matrices (e.g. design matrix $X$) and lowercase Latin letters for vectors (response vector $y$). Standard textbooks on the use of matrices in Statistics (e.g. Matrix Algebra Useful for Statistics by Searle, Matrix Algebra From a Statistician's Perspective by Harville and Matrix Algebra: Theory, Computations, and Applications in Statistics by Gentle) utilise this convention too, so it has become a standard way to denote things.
Why uppercase for $X$ and lowercase for $y$? The question about why $X$ and $y$ are popular choices in mathematical notions has been answered in the History of Science and Mathematics SE website: Why are X and Y commonly used as mathematical pla
13,142
Why uppercase for $X$ and lowercase for $y$?
Before you collect any data values on the feature and target variables, these variables can be considered to be random variables provided a random mechanism will be used to select the subjects who will generate these values. In that case, the correct notation for these variables is Y and X (i.e., upper case letters for both). Recall that the value of a random variable is unknown prior to collecting the data, though its behaviour in the long run can be predicted using probability laws. However, once we collect the data, that value becomes known. After you collect all desired data values on the feature and target variables, you can use the lower case notation to denote the collection of data values corresponding to the target variable (y) and the feature variables (x). If you have a single feature variable, x is a vector of data values. If you have multiple feature variables, x is a matrix of data values, having one column per feature variable. Usually, y is a vector of data values. So the upper case notation refers to "random (hence unknown)", while the lower case notation refers to "known". Alternatively, the upper case notation refers to "before collecting the data", while the lower case notation refers to "after collecting the data". Sadly, the literature is not at all consistent in the use of this notation, which is why you see the (y,X) notation you mention in your question.
Why uppercase for $X$ and lowercase for $y$?
Before you collect any data values on the feature and target variables, these variables can be considered to be random variables provided a random mechanism will be used to select the subjects who wil
Why uppercase for $X$ and lowercase for $y$? Before you collect any data values on the feature and target variables, these variables can be considered to be random variables provided a random mechanism will be used to select the subjects who will generate these values. In that case, the correct notation for these variables is Y and X (i.e., upper case letters for both). Recall that the value of a random variable is unknown prior to collecting the data, though its behaviour in the long run can be predicted using probability laws. However, once we collect the data, that value becomes known. After you collect all desired data values on the feature and target variables, you can use the lower case notation to denote the collection of data values corresponding to the target variable (y) and the feature variables (x). If you have a single feature variable, x is a vector of data values. If you have multiple feature variables, x is a matrix of data values, having one column per feature variable. Usually, y is a vector of data values. So the upper case notation refers to "random (hence unknown)", while the lower case notation refers to "known". Alternatively, the upper case notation refers to "before collecting the data", while the lower case notation refers to "after collecting the data". Sadly, the literature is not at all consistent in the use of this notation, which is why you see the (y,X) notation you mention in your question.
Why uppercase for $X$ and lowercase for $y$? Before you collect any data values on the feature and target variables, these variables can be considered to be random variables provided a random mechanism will be used to select the subjects who wil
13,143
Why uppercase for $X$ and lowercase for $y$?
To understand when to use lowercase or uppercase, we need to know what is represented in X_train or X_test. It is a capital letter X to represent a 2-D matrix. And for y_train and y_test, it is a small letter y to represent a 1-D vector. Mathematically, it is a common notation for Linear Algebra to use uppercase Latin letters for matrices (e.g. matrix X) and lowercase Latin letters for vectors (vector y). In data science, the feature matrix X is a collection of many columns of feature values. For example a df with 1 target, 20 features and 1000 data records will have the shape of shape (1000, 21). So we will define the feature matrix X to have the shape (1000, 20). Whereas the target label y is a column of values having the shape (1000, 1). After applying train_test_split() on X and y with test_size=0.25, I would expect: X_train to be a 2-D matrix (750, 20) y_train to be a 1-D vector (750, 1)
Why uppercase for $X$ and lowercase for $y$?
To understand when to use lowercase or uppercase, we need to know what is represented in X_train or X_test. It is a capital letter X to represent a 2-D matrix. And for y_train and y_test, it is a smal
Why uppercase for $X$ and lowercase for $y$? To understand when to use lowercase or uppercase, we need to know what is represented in X_train or X_test. It is a capital letter X to represent a 2-D matrix. And for y_train and y_test, it is a small letter y to represent a 1-D vector. Mathematically, it is a common notation for Linear Algebra to use uppercase Latin letters for matrices (e.g. matrix X) and lowercase Latin letters for vectors (vector y). In data science, the feature matrix X is a collection of many columns of feature values. For example a df with 1 target, 20 features and 1000 data records will have the shape of shape (1000, 21). So we will define the feature matrix X to have the shape (1000, 20). Whereas the target label y is a column of values having the shape (1000, 1). After applying train_test_split() on X and y with test_size=0.25, I would expect: X_train to be a 2-D matrix (750, 20) y_train to be a 1-D vector (750, 1)
Why uppercase for $X$ and lowercase for $y$? To understand when to use lowercase or uppercase, we need to know what is represented in X_train or X_test. It is a capital letter X to represent a 2-D matrix. And for y_train and y_test, it is a smal
13,144
Does this discrete distribution have a name?
You have a discretized version of the negative log distribution, that is, the distribution whose support is $[0, 1]$ and whose pdf is $f(t) = - \log t$. To see this, I'm going to redefine your random variable to take values in the set $\{ 0, 1/N, 2/N, \ldots, 1 \}$ instead of $\{0, 1, 2, \ldots, N \}$ and call the resulting distribution $T$. Then, my claim is that $$ Pr\left( T = \frac{t}{N} \right) \rightarrow - \frac{1}{N} \log \left( \frac{t}{N} \right) $$ as $N, t \rightarrow \infty$ while $\frac{t}{N}$ is held (approximately) constant. First, a little simulation experiment demonstrating this convergence. Here's a small implementation of a sampler from your distribution: t_sample <- function(N, size) { bounds <- sample(1:N, size=size, replace=TRUE) samples <- sapply(bounds, function(t) {sample(1:t, size=1)}) samples / N } Here's a histogram of a large sample taken from your distribution: ss <- t_sample(100, 200000) hist(ss, freq=FALSE, breaks=50) and here's the logarithmic pdf overlaid: linsp <- 1:100 / 100 lines(linsp, -log(linsp)) To see why this convergence occurs, start with your expression $$ Pr \left( T = \frac{t}{N} \right) = \frac{1}{N} \sum_{j=t}^N \frac{1}{j} $$ and multiply and divide by $N$ $$ Pr \left( T = \frac{t}{N} \right) = \frac{1}{N} \sum_{j=t}^N \frac{N}{j} \frac{1}{N} $$ The summation is now a Riemann sum for the function $g(x) = \frac{1}{x}$, integrated from $\frac{t}{N}$ to $1$. That is, for large $N$, $$ Pr \left( T = \frac{t}{N} \right) \approx \frac{1}{N} \int_{\frac{t}{N}}^1 \frac{1}{x} dx = - \frac{1}{N} \log \left( \frac{t}{N} \right)$$ which is the expression I wanted to arrive at.
Does this discrete distribution have a name?
You have a discretized version of the negative log distribution, that is, the distribution whose support is $[0, 1]$ and whose pdf is $f(t) = - \log t$. To see this, I'm going to redefine your random
Does this discrete distribution have a name? You have a discretized version of the negative log distribution, that is, the distribution whose support is $[0, 1]$ and whose pdf is $f(t) = - \log t$. To see this, I'm going to redefine your random variable to take values in the set $\{ 0, 1/N, 2/N, \ldots, 1 \}$ instead of $\{0, 1, 2, \ldots, N \}$ and call the resulting distribution $T$. Then, my claim is that $$ Pr\left( T = \frac{t}{N} \right) \rightarrow - \frac{1}{N} \log \left( \frac{t}{N} \right) $$ as $N, t \rightarrow \infty$ while $\frac{t}{N}$ is held (approximately) constant. First, a little simulation experiment demonstrating this convergence. Here's a small implementation of a sampler from your distribution: t_sample <- function(N, size) { bounds <- sample(1:N, size=size, replace=TRUE) samples <- sapply(bounds, function(t) {sample(1:t, size=1)}) samples / N } Here's a histogram of a large sample taken from your distribution: ss <- t_sample(100, 200000) hist(ss, freq=FALSE, breaks=50) and here's the logarithmic pdf overlaid: linsp <- 1:100 / 100 lines(linsp, -log(linsp)) To see why this convergence occurs, start with your expression $$ Pr \left( T = \frac{t}{N} \right) = \frac{1}{N} \sum_{j=t}^N \frac{1}{j} $$ and multiply and divide by $N$ $$ Pr \left( T = \frac{t}{N} \right) = \frac{1}{N} \sum_{j=t}^N \frac{N}{j} \frac{1}{N} $$ The summation is now a Riemann sum for the function $g(x) = \frac{1}{x}$, integrated from $\frac{t}{N}$ to $1$. That is, for large $N$, $$ Pr \left( T = \frac{t}{N} \right) \approx \frac{1}{N} \int_{\frac{t}{N}}^1 \frac{1}{x} dx = - \frac{1}{N} \log \left( \frac{t}{N} \right)$$ which is the expression I wanted to arrive at.
Does this discrete distribution have a name? You have a discretized version of the negative log distribution, that is, the distribution whose support is $[0, 1]$ and whose pdf is $f(t) = - \log t$. To see this, I'm going to redefine your random
13,145
Does this discrete distribution have a name?
This appears to be related to the Whitworth distribution. (I don't believe it is the Whitworth distribution, since if I remember right, that's the distribution of a set of ordered values, but it seems to be connected to it, and relies on the same summation-scheme.) There's some discussion of the Whitworth (and numerous references) in Anthony Lawrance and Robert Marks, (2008) "Firm size distributions in an industry with constrained resources," Applied Economics, vol. 40, issue 12, pages 1595-1607 (There looks to be a working paper version here) Also see Nancy L Geller, (1979) A test of significance for the Whitworth distribution, Journal of the American Society for Information Science, Vol.30(4), pp.229-231
Does this discrete distribution have a name?
This appears to be related to the Whitworth distribution. (I don't believe it is the Whitworth distribution, since if I remember right, that's the distribution of a set of ordered values, but it seems
Does this discrete distribution have a name? This appears to be related to the Whitworth distribution. (I don't believe it is the Whitworth distribution, since if I remember right, that's the distribution of a set of ordered values, but it seems to be connected to it, and relies on the same summation-scheme.) There's some discussion of the Whitworth (and numerous references) in Anthony Lawrance and Robert Marks, (2008) "Firm size distributions in an industry with constrained resources," Applied Economics, vol. 40, issue 12, pages 1595-1607 (There looks to be a working paper version here) Also see Nancy L Geller, (1979) A test of significance for the Whitworth distribution, Journal of the American Society for Information Science, Vol.30(4), pp.229-231
Does this discrete distribution have a name? This appears to be related to the Whitworth distribution. (I don't believe it is the Whitworth distribution, since if I remember right, that's the distribution of a set of ordered values, but it seems
13,146
Is KNN a discriminative learning algorithm?
KNN is a discriminative algorithm since it models the conditional probability of a sample belonging to a given class. To see this just consider how one gets to the decision rule of kNNs. A class label corresponds to a set of points which belong to some region in the feature space $R$. If you draw sample points from the actual probability distribution, $p(x)$, independently, then the probability of drawing a sample from that class is, $$ P = \int_{R} p(x) dx $$ What if you have $N$ points? The probability that $K$ points of those $N$ points fall in the region $R$ follows the binomial distribution, $$ Prob(K) = {{N} \choose {K}}P^{K}(1-P)^{N-K} $$ As $N \to \infty$ this distribution is sharply peaked, so that the probability can be approximated by its mean value $\frac{K}{N}$. An additional approximation is that the probability distribution over $R$ remains approximately constant, so that one can approximate the integral by, $$ P = \int_{R} p(x) dx \approx p(x)V $$ where $V$ is the total volume of the region. Under this approximations $p(x) \approx \frac{K}{NV}$. Now, if we had several classes, we could repeat the same analysis for each one, which would give us, $$ p(x|C_{k}) = \frac{K_{k}}{N_{k}V} $$ where $K_{k}$ is the amount of points from class $k$ which falls within that region and $N_{k}$ is the total number of points belonging to class $C_k$. Notice $\sum_{k}N_{k}=N$. Repeating the analysis with the binomial distribution, it is easy to see that we can estimate the prior $P(C_{k}) = \frac{N_{k}}{N}$. Using Bayes rule, $$ P(C_{k}|x) = \frac{p(x|C_{k})p(C_{k})}{p(x)} = \frac{K_{k}}{K} $$ which is the rule for kNNs.
Is KNN a discriminative learning algorithm?
KNN is a discriminative algorithm since it models the conditional probability of a sample belonging to a given class. To see this just consider how one gets to the decision rule of kNNs. A class label
Is KNN a discriminative learning algorithm? KNN is a discriminative algorithm since it models the conditional probability of a sample belonging to a given class. To see this just consider how one gets to the decision rule of kNNs. A class label corresponds to a set of points which belong to some region in the feature space $R$. If you draw sample points from the actual probability distribution, $p(x)$, independently, then the probability of drawing a sample from that class is, $$ P = \int_{R} p(x) dx $$ What if you have $N$ points? The probability that $K$ points of those $N$ points fall in the region $R$ follows the binomial distribution, $$ Prob(K) = {{N} \choose {K}}P^{K}(1-P)^{N-K} $$ As $N \to \infty$ this distribution is sharply peaked, so that the probability can be approximated by its mean value $\frac{K}{N}$. An additional approximation is that the probability distribution over $R$ remains approximately constant, so that one can approximate the integral by, $$ P = \int_{R} p(x) dx \approx p(x)V $$ where $V$ is the total volume of the region. Under this approximations $p(x) \approx \frac{K}{NV}$. Now, if we had several classes, we could repeat the same analysis for each one, which would give us, $$ p(x|C_{k}) = \frac{K_{k}}{N_{k}V} $$ where $K_{k}$ is the amount of points from class $k$ which falls within that region and $N_{k}$ is the total number of points belonging to class $C_k$. Notice $\sum_{k}N_{k}=N$. Repeating the analysis with the binomial distribution, it is easy to see that we can estimate the prior $P(C_{k}) = \frac{N_{k}}{N}$. Using Bayes rule, $$ P(C_{k}|x) = \frac{p(x|C_{k})p(C_{k})}{p(x)} = \frac{K_{k}}{K} $$ which is the rule for kNNs.
Is KNN a discriminative learning algorithm? KNN is a discriminative algorithm since it models the conditional probability of a sample belonging to a given class. To see this just consider how one gets to the decision rule of kNNs. A class label
13,147
Is KNN a discriminative learning algorithm?
Answer by @jpmuc doesn't seem to be accurate. Generative models model the underlying distribution P(x/Ci) and then later use Bayes theorem to find the posterior probabilities. That is exactly what has been shown in that answer and then concludes the exact opposite. :O For KNN to be a generative model, we should be able to generate synthetic data. It seems that this is possible once we have some initial training data. But starting from no training data and generating synthetic data is not possible. So KNN doesn't fit nicely with generative models. One may argue that KNN is a discriminative model because we can draw discriminant boundary for classification, or we can compute the posterior P(Ci/x). But all these are true in the case of generative models as well. A true discriminative model doesn't tell anything about the underlying distribution. But in the case of KNN we know a lot about the underlying distribution, infact we are storing the entire training set. So it seems KNN is mid-way between generative and discriminative models. Probably that is why KNN is not categorized under any of generative or discriminative models in reputed articles. Let's just call them non-parametric models.
Is KNN a discriminative learning algorithm?
Answer by @jpmuc doesn't seem to be accurate. Generative models model the underlying distribution P(x/Ci) and then later use Bayes theorem to find the posterior probabilities. That is exactly what has
Is KNN a discriminative learning algorithm? Answer by @jpmuc doesn't seem to be accurate. Generative models model the underlying distribution P(x/Ci) and then later use Bayes theorem to find the posterior probabilities. That is exactly what has been shown in that answer and then concludes the exact opposite. :O For KNN to be a generative model, we should be able to generate synthetic data. It seems that this is possible once we have some initial training data. But starting from no training data and generating synthetic data is not possible. So KNN doesn't fit nicely with generative models. One may argue that KNN is a discriminative model because we can draw discriminant boundary for classification, or we can compute the posterior P(Ci/x). But all these are true in the case of generative models as well. A true discriminative model doesn't tell anything about the underlying distribution. But in the case of KNN we know a lot about the underlying distribution, infact we are storing the entire training set. So it seems KNN is mid-way between generative and discriminative models. Probably that is why KNN is not categorized under any of generative or discriminative models in reputed articles. Let's just call them non-parametric models.
Is KNN a discriminative learning algorithm? Answer by @jpmuc doesn't seem to be accurate. Generative models model the underlying distribution P(x/Ci) and then later use Bayes theorem to find the posterior probabilities. That is exactly what has
13,148
Is KNN a discriminative learning algorithm?
I have come accross a book which says the opposite (i.e. a Generative Nonparametric Classification Model) This is the online link: Machine Learning A Probabilistic Perspective by Murphy, Kevin P. (2012) Here the excerpt from the book:
Is KNN a discriminative learning algorithm?
I have come accross a book which says the opposite (i.e. a Generative Nonparametric Classification Model) This is the online link: Machine Learning A Probabilistic Perspective by Murphy, Kevin P. (201
Is KNN a discriminative learning algorithm? I have come accross a book which says the opposite (i.e. a Generative Nonparametric Classification Model) This is the online link: Machine Learning A Probabilistic Perspective by Murphy, Kevin P. (2012) Here the excerpt from the book:
Is KNN a discriminative learning algorithm? I have come accross a book which says the opposite (i.e. a Generative Nonparametric Classification Model) This is the online link: Machine Learning A Probabilistic Perspective by Murphy, Kevin P. (201
13,149
Is KNN a discriminative learning algorithm?
I agree that kNN is discriminative. The reason is that it does not explicitly store or tries to learn a (probabilistic) model that explains the data (as opposed to, e.g. Naive Bayes). The answer by juampa confuses me since, to my understanding, a generative classifier is one that attempts to explain how the data is generated (e.g. using a model), and that answer says that it is discriminative because of this reason...
Is KNN a discriminative learning algorithm?
I agree that kNN is discriminative. The reason is that it does not explicitly store or tries to learn a (probabilistic) model that explains the data (as opposed to, e.g. Naive Bayes). The answer by j
Is KNN a discriminative learning algorithm? I agree that kNN is discriminative. The reason is that it does not explicitly store or tries to learn a (probabilistic) model that explains the data (as opposed to, e.g. Naive Bayes). The answer by juampa confuses me since, to my understanding, a generative classifier is one that attempts to explain how the data is generated (e.g. using a model), and that answer says that it is discriminative because of this reason...
Is KNN a discriminative learning algorithm? I agree that kNN is discriminative. The reason is that it does not explicitly store or tries to learn a (probabilistic) model that explains the data (as opposed to, e.g. Naive Bayes). The answer by j
13,150
Does adding more variables into a multivariable regression change coefficients of existing variables?
A parameter estimate in a regression model (e.g., $\hat\beta_i$) will change if a variable, $X_j$, is added to the model that is: correlated with that parameter's corresponding variable, $X_i$ (which was already in the model), and correlated with the response variable, $Y$ An estimated beta will not change when a new variable is added, if either of the above are uncorrelated. Note that whether they are uncorrelated in the population (i.e., $\rho_{(X_i, X_j)}=0$, or $\rho_{(X_j, Y)}=0$) is irrelevant. What matters is that both sample correlations are exactly $0$. This will essentially never be the case in practice unless you are working with experimental data where the variables were manipulated such that they are uncorrelated by design. Note also that the amount the parameters change may not be terribly meaningful (that depends, at least in part, on your theory). Moreover, the amount they can change is a function of the magnitudes of the two correlations above. On a different note, it is not really correct to think of this phenomenon as "the coefficient of a given variable [being] influenced by the coefficient of another variable". It isn't the betas that are influencing each other. This phenomenon is a natural result of the algorithm that statistical software uses to estimate the slope parameters. Imagine a situation where $Y$ is caused by both $X_i$ and $X_j$, which in turn are correlated with each other. If only $X_i$ is in the model, some of the variation in $Y$ that is due to $X_j$ will be inappropriately attributed to $X_i$. This means that the value of $X_i$ is biased; this is called the omitted variable bias.
Does adding more variables into a multivariable regression change coefficients of existing variables
A parameter estimate in a regression model (e.g., $\hat\beta_i$) will change if a variable, $X_j$, is added to the model that is: correlated with that parameter's corresponding variable, $X_i$ (whi
Does adding more variables into a multivariable regression change coefficients of existing variables? A parameter estimate in a regression model (e.g., $\hat\beta_i$) will change if a variable, $X_j$, is added to the model that is: correlated with that parameter's corresponding variable, $X_i$ (which was already in the model), and correlated with the response variable, $Y$ An estimated beta will not change when a new variable is added, if either of the above are uncorrelated. Note that whether they are uncorrelated in the population (i.e., $\rho_{(X_i, X_j)}=0$, or $\rho_{(X_j, Y)}=0$) is irrelevant. What matters is that both sample correlations are exactly $0$. This will essentially never be the case in practice unless you are working with experimental data where the variables were manipulated such that they are uncorrelated by design. Note also that the amount the parameters change may not be terribly meaningful (that depends, at least in part, on your theory). Moreover, the amount they can change is a function of the magnitudes of the two correlations above. On a different note, it is not really correct to think of this phenomenon as "the coefficient of a given variable [being] influenced by the coefficient of another variable". It isn't the betas that are influencing each other. This phenomenon is a natural result of the algorithm that statistical software uses to estimate the slope parameters. Imagine a situation where $Y$ is caused by both $X_i$ and $X_j$, which in turn are correlated with each other. If only $X_i$ is in the model, some of the variation in $Y$ that is due to $X_j$ will be inappropriately attributed to $X_i$. This means that the value of $X_i$ is biased; this is called the omitted variable bias.
Does adding more variables into a multivariable regression change coefficients of existing variables A parameter estimate in a regression model (e.g., $\hat\beta_i$) will change if a variable, $X_j$, is added to the model that is: correlated with that parameter's corresponding variable, $X_i$ (whi
13,151
Does adding more variables into a multivariable regression change coefficients of existing variables?
It is mathematically possible that the coefficients will not change, but it is unlikely that there will be no change at all with real data, even if all the independent variables are independent of each other. But, when this is the case, the changes (other than in the intercept) will tend to 0: set.seed(129231) x1 <- rnorm(100) x2 <- rnorm(100) x3 <- rnorm(100) x4 <- rnorm(100) y <- x1 + x2 + x3 + x4 + rnorm(100, 0, .2) lm1 <- lm(y~x1+x2+x3) coef(lm1) lm2 <- lm(y~x1+x2+x3+x4) coef(lm2) In the real world, though, independent variables are often related to each other. In this case, adding a 4th variable to the equation will change the other coefficients, sometimes by a lot. Then there are possible interactions.... but that's another question.
Does adding more variables into a multivariable regression change coefficients of existing variables
It is mathematically possible that the coefficients will not change, but it is unlikely that there will be no change at all with real data, even if all the independent variables are independent of eac
Does adding more variables into a multivariable regression change coefficients of existing variables? It is mathematically possible that the coefficients will not change, but it is unlikely that there will be no change at all with real data, even if all the independent variables are independent of each other. But, when this is the case, the changes (other than in the intercept) will tend to 0: set.seed(129231) x1 <- rnorm(100) x2 <- rnorm(100) x3 <- rnorm(100) x4 <- rnorm(100) y <- x1 + x2 + x3 + x4 + rnorm(100, 0, .2) lm1 <- lm(y~x1+x2+x3) coef(lm1) lm2 <- lm(y~x1+x2+x3+x4) coef(lm2) In the real world, though, independent variables are often related to each other. In this case, adding a 4th variable to the equation will change the other coefficients, sometimes by a lot. Then there are possible interactions.... but that's another question.
Does adding more variables into a multivariable regression change coefficients of existing variables It is mathematically possible that the coefficients will not change, but it is unlikely that there will be no change at all with real data, even if all the independent variables are independent of eac
13,152
Does adding more variables into a multivariable regression change coefficients of existing variables?
Generally speaking, yes, adding a variable changes the earlier coefficients, almost always. Indeed, this is essentially the cause of Simpson's paradox, where relations between effects can change, even reverse sign, because of omitted covariates. For that not to happen, we'd need that the new variables were orthogonal to the previous ones. This often happens in designed experiments, but is very unlikely to happen in data where the pattern of the independent variables is unplanned.
Does adding more variables into a multivariable regression change coefficients of existing variables
Generally speaking, yes, adding a variable changes the earlier coefficients, almost always. Indeed, this is essentially the cause of Simpson's paradox, where relations between effects can change, even
Does adding more variables into a multivariable regression change coefficients of existing variables? Generally speaking, yes, adding a variable changes the earlier coefficients, almost always. Indeed, this is essentially the cause of Simpson's paradox, where relations between effects can change, even reverse sign, because of omitted covariates. For that not to happen, we'd need that the new variables were orthogonal to the previous ones. This often happens in designed experiments, but is very unlikely to happen in data where the pattern of the independent variables is unplanned.
Does adding more variables into a multivariable regression change coefficients of existing variables Generally speaking, yes, adding a variable changes the earlier coefficients, almost always. Indeed, this is essentially the cause of Simpson's paradox, where relations between effects can change, even
13,153
How does a Poisson distribution work when modeling continuous data and does it result in information loss?
I've been estimating continuous positive outcome Poisson regressions with the Huber/White/Sandwich linearized estimator of variance fairly frequently. However, that's not a particularly good reason to do anything, so here are some actual references. From the theory side, $y$ does not need to be an integer for for the estimator based on the Poisson likelihood function to be consistent. This is shown in Gourieroux, Monfort and Trognon (1984). This is called Poisson PMLE or QMLE, for Pseudo/Quasi Maximum Likelihood. There's also some encouraging simulation evidence from Santos Silva and Tenreyro (2006), where the Poisson comes in best-in-show. It also does well in a simulation with lots of zeros in the outcome. You can also easily do your own simulation to convince yourself that this works in your snowflake case. Finally, you can also use a GLM with a log link function and Poisson family. This yields identical results and placates the count-data-only knee jerk reactions. References Without Ungated Links: Gourieroux, C., A. Monfort and A. Trognon (1984). “Pseudo Maximum Likelihood Methods: Applications to Poisson Models,” Econometrica, 52, 701-720.
How does a Poisson distribution work when modeling continuous data and does it result in information
I've been estimating continuous positive outcome Poisson regressions with the Huber/White/Sandwich linearized estimator of variance fairly frequently. However, that's not a particularly good reason to
How does a Poisson distribution work when modeling continuous data and does it result in information loss? I've been estimating continuous positive outcome Poisson regressions with the Huber/White/Sandwich linearized estimator of variance fairly frequently. However, that's not a particularly good reason to do anything, so here are some actual references. From the theory side, $y$ does not need to be an integer for for the estimator based on the Poisson likelihood function to be consistent. This is shown in Gourieroux, Monfort and Trognon (1984). This is called Poisson PMLE or QMLE, for Pseudo/Quasi Maximum Likelihood. There's also some encouraging simulation evidence from Santos Silva and Tenreyro (2006), where the Poisson comes in best-in-show. It also does well in a simulation with lots of zeros in the outcome. You can also easily do your own simulation to convince yourself that this works in your snowflake case. Finally, you can also use a GLM with a log link function and Poisson family. This yields identical results and placates the count-data-only knee jerk reactions. References Without Ungated Links: Gourieroux, C., A. Monfort and A. Trognon (1984). “Pseudo Maximum Likelihood Methods: Applications to Poisson Models,” Econometrica, 52, 701-720.
How does a Poisson distribution work when modeling continuous data and does it result in information I've been estimating continuous positive outcome Poisson regressions with the Huber/White/Sandwich linearized estimator of variance fairly frequently. However, that's not a particularly good reason to
13,154
How does a Poisson distribution work when modeling continuous data and does it result in information loss?
Poisson distribution is for count data only, trying to feed it with continuous data is nasty and I believe should not be done. One of the reasons is that you don't know how to scale your continuous variable. And the Poisson depends very much on the scale! I tried to explain it with a simple example here. So For this reason alone I'd not use Poisson for anything other than count data. Also remember that GLM does 2 things - link function (transforming the response var., log in Poisson case), and residuals (Poisson distrubution in this case). Think about the biological task, about the residuals, and then select proper method. Sometimes it makes sense to use log transform, but stay with normally distributed residuals. "but it seems like conventional wisdom is that you shouldn't transform data entering into a mixed model" I hear this first time! Doesn't make any sense to me at all. Mixed model can be just like a normal linear model, just with added random effects. Can you put an exact citation here? In my opinion, if log transform clears things up, just use it!
How does a Poisson distribution work when modeling continuous data and does it result in information
Poisson distribution is for count data only, trying to feed it with continuous data is nasty and I believe should not be done. One of the reasons is that you don't know how to scale your continuous va
How does a Poisson distribution work when modeling continuous data and does it result in information loss? Poisson distribution is for count data only, trying to feed it with continuous data is nasty and I believe should not be done. One of the reasons is that you don't know how to scale your continuous variable. And the Poisson depends very much on the scale! I tried to explain it with a simple example here. So For this reason alone I'd not use Poisson for anything other than count data. Also remember that GLM does 2 things - link function (transforming the response var., log in Poisson case), and residuals (Poisson distrubution in this case). Think about the biological task, about the residuals, and then select proper method. Sometimes it makes sense to use log transform, but stay with normally distributed residuals. "but it seems like conventional wisdom is that you shouldn't transform data entering into a mixed model" I hear this first time! Doesn't make any sense to me at all. Mixed model can be just like a normal linear model, just with added random effects. Can you put an exact citation here? In my opinion, if log transform clears things up, just use it!
How does a Poisson distribution work when modeling continuous data and does it result in information Poisson distribution is for count data only, trying to feed it with continuous data is nasty and I believe should not be done. One of the reasons is that you don't know how to scale your continuous va
13,155
How does a Poisson distribution work when modeling continuous data and does it result in information loss?
Here's another great discussion of how to use the Poisson model to fit the log-regressions: http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/ (I am telling a friend, just as the blog entry suggests). The basic thrust is that we only use the part of the Poisson model that is the log link. The part that requires the variance to be equal to the mean can be overridden with a sandwich estimate of the variance. This is all for i.i.d. data, however; the clustered/mixed-model extensions have been properly referenced by Dimitriy Masterov.
How does a Poisson distribution work when modeling continuous data and does it result in information
Here's another great discussion of how to use the Poisson model to fit the log-regressions: http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/ (I am telling a friend, just
How does a Poisson distribution work when modeling continuous data and does it result in information loss? Here's another great discussion of how to use the Poisson model to fit the log-regressions: http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/ (I am telling a friend, just as the blog entry suggests). The basic thrust is that we only use the part of the Poisson model that is the log link. The part that requires the variance to be equal to the mean can be overridden with a sandwich estimate of the variance. This is all for i.i.d. data, however; the clustered/mixed-model extensions have been properly referenced by Dimitriy Masterov.
How does a Poisson distribution work when modeling continuous data and does it result in information Here's another great discussion of how to use the Poisson model to fit the log-regressions: http://blog.stata.com/2011/08/22/use-poisson-rather-than-regress-tell-a-friend/ (I am telling a friend, just
13,156
How does a Poisson distribution work when modeling continuous data and does it result in information loss?
If the problem is the variance scaling with the mean, but you have continuous data, have you thought about using continuous distributions that can accomodate the issues you're having. Perhaps a Gamma? The variance will have a quadratic relationship with the mean - much like a negative binomial, actually.
How does a Poisson distribution work when modeling continuous data and does it result in information
If the problem is the variance scaling with the mean, but you have continuous data, have you thought about using continuous distributions that can accomodate the issues you're having. Perhaps a Gamma
How does a Poisson distribution work when modeling continuous data and does it result in information loss? If the problem is the variance scaling with the mean, but you have continuous data, have you thought about using continuous distributions that can accomodate the issues you're having. Perhaps a Gamma? The variance will have a quadratic relationship with the mean - much like a negative binomial, actually.
How does a Poisson distribution work when modeling continuous data and does it result in information If the problem is the variance scaling with the mean, but you have continuous data, have you thought about using continuous distributions that can accomodate the issues you're having. Perhaps a Gamma
13,157
How to test the statistical significance for categorical variable in linear regression?
You are correct that those $p$-values only tell you whether each level's mean is significantly different from the reference level's mean. Therefore, they only tell you about the pairwise differences between the levels. To test whether the categorical predictor, as a whole, is significant is equivalent to testing whether there is any heterogeneity in the means of the levels of the predictor. When there are no other predictors in the model, this is a classical ANOVA problem. When there are other predictors in the model. you have two options to test for the significance of a categorical predictor: (1) The likelihood ratio test: Suppose you have an outcome $Y_i$, quantitative predictors $X_{i1}, ..., X_{ip}$ and the categorical predictor $C_i$ with $k$ levels. The model without the categorical predictor is $$ Y_i = \beta_0 + \beta_1 X_{i1} + ... + \beta_p X_{ip} + \varepsilon_i $$ In R you can fit this model with the lm() command and extract the log likelihood with the logLik command. Call this log-likelihood $L_0$. Next, you can fit the model with the categorical predictor: $$ Y_i = \beta_0 + \beta_1 X_{i1} + ... + \beta_p X_{ip} + \sum_{j=1}^{k-1} \alpha_j B_j + \varepsilon_i $$ where $B_j$ is a dummy variable which is $1$ if $D_i = j$ and $0$ otherwise. The $k$'th level is the reference level, which is why there are only $k-1$ terms in the sum. R will automatically do this dummy coding for you if you pass the categorical variable to lm(). You can fit this model similarly and extract the log likelihood as above. Call this log-likelihood $L_1$. Then, under the null hypothesis that $D_i$ has no effect, $$ \lambda = 2 \left( L_1 - L_0 \right ) $$ has a $\chi^2$ distribution with $k-1$ degrees of freedom. So, you can calculate the $p$-value using 1-pchisq(2*(L1-L0),df=k-1) in R to test for significance. (2) $F$-test: Without going into the details (which are similar to the LRT except sums of squares are used rather than log-likelihoods), I'll explain how to do this in R. If you fit the "full" model (i.e. the model with all of the predictors, including the categorical predictor) in R using the lm() command (call this g1) and the model without the categorical predictor (call this g0), then the anova(g1,g0) will test this hypothesis for you as well. Note: both of the approaches I've mentioned here require normality of the errors. Also, the likelihood ratio test is a very general tool used for nested comparisons, which is why I mention it here (and why it occurs to me first), although the $F$-test is more familiar in comparing linear regression models.
How to test the statistical significance for categorical variable in linear regression?
You are correct that those $p$-values only tell you whether each level's mean is significantly different from the reference level's mean. Therefore, they only tell you about the pairwise differences b
How to test the statistical significance for categorical variable in linear regression? You are correct that those $p$-values only tell you whether each level's mean is significantly different from the reference level's mean. Therefore, they only tell you about the pairwise differences between the levels. To test whether the categorical predictor, as a whole, is significant is equivalent to testing whether there is any heterogeneity in the means of the levels of the predictor. When there are no other predictors in the model, this is a classical ANOVA problem. When there are other predictors in the model. you have two options to test for the significance of a categorical predictor: (1) The likelihood ratio test: Suppose you have an outcome $Y_i$, quantitative predictors $X_{i1}, ..., X_{ip}$ and the categorical predictor $C_i$ with $k$ levels. The model without the categorical predictor is $$ Y_i = \beta_0 + \beta_1 X_{i1} + ... + \beta_p X_{ip} + \varepsilon_i $$ In R you can fit this model with the lm() command and extract the log likelihood with the logLik command. Call this log-likelihood $L_0$. Next, you can fit the model with the categorical predictor: $$ Y_i = \beta_0 + \beta_1 X_{i1} + ... + \beta_p X_{ip} + \sum_{j=1}^{k-1} \alpha_j B_j + \varepsilon_i $$ where $B_j$ is a dummy variable which is $1$ if $D_i = j$ and $0$ otherwise. The $k$'th level is the reference level, which is why there are only $k-1$ terms in the sum. R will automatically do this dummy coding for you if you pass the categorical variable to lm(). You can fit this model similarly and extract the log likelihood as above. Call this log-likelihood $L_1$. Then, under the null hypothesis that $D_i$ has no effect, $$ \lambda = 2 \left( L_1 - L_0 \right ) $$ has a $\chi^2$ distribution with $k-1$ degrees of freedom. So, you can calculate the $p$-value using 1-pchisq(2*(L1-L0),df=k-1) in R to test for significance. (2) $F$-test: Without going into the details (which are similar to the LRT except sums of squares are used rather than log-likelihoods), I'll explain how to do this in R. If you fit the "full" model (i.e. the model with all of the predictors, including the categorical predictor) in R using the lm() command (call this g1) and the model without the categorical predictor (call this g0), then the anova(g1,g0) will test this hypothesis for you as well. Note: both of the approaches I've mentioned here require normality of the errors. Also, the likelihood ratio test is a very general tool used for nested comparisons, which is why I mention it here (and why it occurs to me first), although the $F$-test is more familiar in comparing linear regression models.
How to test the statistical significance for categorical variable in linear regression? You are correct that those $p$-values only tell you whether each level's mean is significantly different from the reference level's mean. Therefore, they only tell you about the pairwise differences b
13,158
Narrow confidence interval -- higher accuracy?
The 95% is not numerically attached to how confident you are that you've covered the true effect in your experiment. Perhaps recognizing that 95% is attached to the procedure that produced the interval, and not the interval itself, would help. Part of the procedure is that you decide that the interval contains the true value. You'll be right if you do that consistently 95% of the time. But you really don't know how likely it is for your particular experiment without more information. Q1: Your first query conflates two things and misuses a term. A narrower confidence interval may be more precise but it's accuracy is fixed by the procedure backing it, be it 89%, 95%, etc. As long as that procedure was correctly designed, the true value will be contained in the interval at the prescribed rate. (see @Michael R Chernick's answer for a discussion on coverage and a different sense of accuracy) Whether an observation falls in a CI isn't something to consider. A confidence interval is about estimating the mean. If you had an extraordinary large sample size and could estimate the mean very well then the chances of an observation being in the CI would be miniscule. Nevertheless, your question does raise some points and it's important to think about why a CI is narrow. Just because it's narrow doesn't mean you're less likely to encounter an observation that falls within that CI. Keep in mind, a narrow CI can be achieved in one of three ways. The most common way researchers make the CI narrow is by increasing the sample size. Another way they can be narrow is because the experimental method or nature of the data yields very low variance. For example, the confidence interval around the boiling point of water at sea level is small, regardless of the sample size. Finally, it could be narrow because your sample is unrepresentative. In that case, you are actually more likely to have one of the 5% of intervals that do not contain the true value. It's a bit of a paradox regarding CI width that the ones in that 5% of misses tend to be narrow. It's something you should check by knowing the literature and how variable this data typically is. Q2: A 99% confidence interval is wider than a 95%, all else being equal. Therefore, it's more likely that it will contain the true value. See the distinction above between precise and accurate. If I make a confidence interval narrower with lower variability and higher sample size it becomes more precise because the values cover a smaller range. If I increase the coverage by using a 99% calculation it becomes more accurate because the true value is more likely to be within the range.
Narrow confidence interval -- higher accuracy?
The 95% is not numerically attached to how confident you are that you've covered the true effect in your experiment. Perhaps recognizing that 95% is attached to the procedure that produced the interva
Narrow confidence interval -- higher accuracy? The 95% is not numerically attached to how confident you are that you've covered the true effect in your experiment. Perhaps recognizing that 95% is attached to the procedure that produced the interval, and not the interval itself, would help. Part of the procedure is that you decide that the interval contains the true value. You'll be right if you do that consistently 95% of the time. But you really don't know how likely it is for your particular experiment without more information. Q1: Your first query conflates two things and misuses a term. A narrower confidence interval may be more precise but it's accuracy is fixed by the procedure backing it, be it 89%, 95%, etc. As long as that procedure was correctly designed, the true value will be contained in the interval at the prescribed rate. (see @Michael R Chernick's answer for a discussion on coverage and a different sense of accuracy) Whether an observation falls in a CI isn't something to consider. A confidence interval is about estimating the mean. If you had an extraordinary large sample size and could estimate the mean very well then the chances of an observation being in the CI would be miniscule. Nevertheless, your question does raise some points and it's important to think about why a CI is narrow. Just because it's narrow doesn't mean you're less likely to encounter an observation that falls within that CI. Keep in mind, a narrow CI can be achieved in one of three ways. The most common way researchers make the CI narrow is by increasing the sample size. Another way they can be narrow is because the experimental method or nature of the data yields very low variance. For example, the confidence interval around the boiling point of water at sea level is small, regardless of the sample size. Finally, it could be narrow because your sample is unrepresentative. In that case, you are actually more likely to have one of the 5% of intervals that do not contain the true value. It's a bit of a paradox regarding CI width that the ones in that 5% of misses tend to be narrow. It's something you should check by knowing the literature and how variable this data typically is. Q2: A 99% confidence interval is wider than a 95%, all else being equal. Therefore, it's more likely that it will contain the true value. See the distinction above between precise and accurate. If I make a confidence interval narrower with lower variability and higher sample size it becomes more precise because the values cover a smaller range. If I increase the coverage by using a 99% calculation it becomes more accurate because the true value is more likely to be within the range.
Narrow confidence interval -- higher accuracy? The 95% is not numerically attached to how confident you are that you've covered the true effect in your experiment. Perhaps recognizing that 95% is attached to the procedure that produced the interva
13,159
Narrow confidence interval -- higher accuracy?
For a given dataset, increasing the confidence level of a confidence interval will only result in larger intervals (or at least not smaller). That's not about accuracy or precision but rather about how much risk you're willing to take about missing the true value. If you're comparing confidence intervals for the same sort of parameter from multiple data sets and one is smaller than the other, you could say that the smaller one is more precise. I prefer to talk about precision rather than accuracy in this situation (see this relevant Wikipedia article).
Narrow confidence interval -- higher accuracy?
For a given dataset, increasing the confidence level of a confidence interval will only result in larger intervals (or at least not smaller). That's not about accuracy or precision but rather about h
Narrow confidence interval -- higher accuracy? For a given dataset, increasing the confidence level of a confidence interval will only result in larger intervals (or at least not smaller). That's not about accuracy or precision but rather about how much risk you're willing to take about missing the true value. If you're comparing confidence intervals for the same sort of parameter from multiple data sets and one is smaller than the other, you could say that the smaller one is more precise. I prefer to talk about precision rather than accuracy in this situation (see this relevant Wikipedia article).
Narrow confidence interval -- higher accuracy? For a given dataset, increasing the confidence level of a confidence interval will only result in larger intervals (or at least not smaller). That's not about accuracy or precision but rather about h
13,160
Narrow confidence interval -- higher accuracy?
First of all, a CI for a given confidence percentage (e.g.95%) means, for all practical purposes (though technically it is not correct) that you are confident that the true value is in the interval. If this is interval is "narrow" (note that this can only be regarded in a relative fashion, so, for comparison with what follows, say it is 1 unit wide), it means that there is not much room to play: whichever value you pick in that interval is going to be close to the true value (because the interval is narrow), and you are quite certain of that (95%). Compare this to a relatively wide 95% CI (to match the example before, say it is 100 units wide): here, you are still 95% certain that the true value will be within this interval, yet that doesn't tell you very much, since there are relatively many values in the interval (about a factor 100 as opposed to 1 - and I ask, again, of purists to ignore the simplification). Typically, you are going to need a bigger interval when you want to be 99% certain that the true value is in it, than when you only need to be 95% certain (note: this may not be true if the intervals are not nested), so indeed, the more confidence you need, the broader the interval you will need to pick. On the other hand, you are more certain with the higher confidence interval. So, If I give you 2 intervals of the same width, and I say one is a 95% CI and the other is a 99% CI, I hope you will prefer the 99% one. In this sense, 99% CIs are more accurate: you have less doubt that you will have missed the truth.
Narrow confidence interval -- higher accuracy?
First of all, a CI for a given confidence percentage (e.g.95%) means, for all practical purposes (though technically it is not correct) that you are confident that the true value is in the interval. I
Narrow confidence interval -- higher accuracy? First of all, a CI for a given confidence percentage (e.g.95%) means, for all practical purposes (though technically it is not correct) that you are confident that the true value is in the interval. If this is interval is "narrow" (note that this can only be regarded in a relative fashion, so, for comparison with what follows, say it is 1 unit wide), it means that there is not much room to play: whichever value you pick in that interval is going to be close to the true value (because the interval is narrow), and you are quite certain of that (95%). Compare this to a relatively wide 95% CI (to match the example before, say it is 100 units wide): here, you are still 95% certain that the true value will be within this interval, yet that doesn't tell you very much, since there are relatively many values in the interval (about a factor 100 as opposed to 1 - and I ask, again, of purists to ignore the simplification). Typically, you are going to need a bigger interval when you want to be 99% certain that the true value is in it, than when you only need to be 95% certain (note: this may not be true if the intervals are not nested), so indeed, the more confidence you need, the broader the interval you will need to pick. On the other hand, you are more certain with the higher confidence interval. So, If I give you 2 intervals of the same width, and I say one is a 95% CI and the other is a 99% CI, I hope you will prefer the 99% one. In this sense, 99% CIs are more accurate: you have less doubt that you will have missed the truth.
Narrow confidence interval -- higher accuracy? First of all, a CI for a given confidence percentage (e.g.95%) means, for all practical purposes (though technically it is not correct) that you are confident that the true value is in the interval. I
13,161
Narrow confidence interval -- higher accuracy?
I am adding to some good answers here that I gave upvotes to. I think there is a little more that should be said to completely clear up the conclusion. I like the terms accurate and correct as Efron defines them. I gave a lengthy discussion on this very recently on a different question. The moderator whuber really liked that answer. I will not go to the same length to repeat that here. However, to Efron accuracy relates to the confidence level and correctness of the width or tightness of the interval. But you can't talk about tightness without considering accuracy first. Some confidence intervals are exact; those are accurate because they have the actual coverage that they advertise. A 95% confidence interval can also be approximate because it uses an asymptotic distribution. Approximate intervals based on asymptotics are for a finite sample size $n$ not going to have the advertised coverage, which is the coverage you would get if the asymptotic distribution were the exact distribution. So an approximate interval could undercover (i.e. advertise 95% when its actual coverage is only 91%) or in the rare but less serious case overcover (i.e. advertised coverage is 95% but actual in 98%). In the former case, we worry about how close the actual coverage is to the advertised coverage). A measure of closeness is the order of accuracy which could be say $1/\sqrt{n}$ or $1/n$. If the actual confidence level is close, we call it accurate. Accuracy is important with bootstrap confidence intervals which are never exact but some variants are more accurate than others. This definition of accuracy may be different to the one the OP is referring to but it should be clear now what Efron's definition is and why it is important to be accurate. Now if you have two methods that are exact, we can prefer one over the other if for any confidence level it has the smaller expected width. A confidence interval that is best in this sense (sometimes called the shortest) would be the one to choose. But this required exactness. If the confidence level is only approximate we could be comparing apples and oranges. One could be narrower than another only because it is less accurate and hence has a lower actual coverage than its advertised coverage. If two confidence intervals are both very accurate or one is exact and the other very accurate comparing expected width may be okay because at least now we are looking at just two varieties of apples.
Narrow confidence interval -- higher accuracy?
I am adding to some good answers here that I gave upvotes to. I think there is a little more that should be said to completely clear up the conclusion. I like the terms accurate and correct as Efron d
Narrow confidence interval -- higher accuracy? I am adding to some good answers here that I gave upvotes to. I think there is a little more that should be said to completely clear up the conclusion. I like the terms accurate and correct as Efron defines them. I gave a lengthy discussion on this very recently on a different question. The moderator whuber really liked that answer. I will not go to the same length to repeat that here. However, to Efron accuracy relates to the confidence level and correctness of the width or tightness of the interval. But you can't talk about tightness without considering accuracy first. Some confidence intervals are exact; those are accurate because they have the actual coverage that they advertise. A 95% confidence interval can also be approximate because it uses an asymptotic distribution. Approximate intervals based on asymptotics are for a finite sample size $n$ not going to have the advertised coverage, which is the coverage you would get if the asymptotic distribution were the exact distribution. So an approximate interval could undercover (i.e. advertise 95% when its actual coverage is only 91%) or in the rare but less serious case overcover (i.e. advertised coverage is 95% but actual in 98%). In the former case, we worry about how close the actual coverage is to the advertised coverage). A measure of closeness is the order of accuracy which could be say $1/\sqrt{n}$ or $1/n$. If the actual confidence level is close, we call it accurate. Accuracy is important with bootstrap confidence intervals which are never exact but some variants are more accurate than others. This definition of accuracy may be different to the one the OP is referring to but it should be clear now what Efron's definition is and why it is important to be accurate. Now if you have two methods that are exact, we can prefer one over the other if for any confidence level it has the smaller expected width. A confidence interval that is best in this sense (sometimes called the shortest) would be the one to choose. But this required exactness. If the confidence level is only approximate we could be comparing apples and oranges. One could be narrower than another only because it is less accurate and hence has a lower actual coverage than its advertised coverage. If two confidence intervals are both very accurate or one is exact and the other very accurate comparing expected width may be okay because at least now we are looking at just two varieties of apples.
Narrow confidence interval -- higher accuracy? I am adding to some good answers here that I gave upvotes to. I think there is a little more that should be said to completely clear up the conclusion. I like the terms accurate and correct as Efron d
13,162
Why is step function not used in activation functions in machine learning?
There are two main reasons why we cannot use the Heaviside step function in (deep) Neural Net: At the moment, one of the most efficient ways to train a multi-layer neural network is by using gradient descent with backpropagation. A requirement for backpropagation algorithm is a differentiable activation function. However, the Heaviside step function is non-differentiable at x = 0 and it has 0 derivative elsewhere. This means that gradient descent won’t be able to make a progress in updating the weights. Recall that the main objective of the neural network is to learn the values of the weights and biases so that the model could produce a prediction as close as possible to the real value. In order to do this, as in many optimisation problems, we’d like a small change in the weight or bias to cause only a small corresponding change in the output from the network. By doing this, we can continuously tweaked the values of weights and bias towards resulting the best approximation. Having a function that can only generate either 0 or 1 (or yes and no), won't help us to achieve this objective.
Why is step function not used in activation functions in machine learning?
There are two main reasons why we cannot use the Heaviside step function in (deep) Neural Net: At the moment, one of the most efficient ways to train a multi-layer neural network is by using gradient
Why is step function not used in activation functions in machine learning? There are two main reasons why we cannot use the Heaviside step function in (deep) Neural Net: At the moment, one of the most efficient ways to train a multi-layer neural network is by using gradient descent with backpropagation. A requirement for backpropagation algorithm is a differentiable activation function. However, the Heaviside step function is non-differentiable at x = 0 and it has 0 derivative elsewhere. This means that gradient descent won’t be able to make a progress in updating the weights. Recall that the main objective of the neural network is to learn the values of the weights and biases so that the model could produce a prediction as close as possible to the real value. In order to do this, as in many optimisation problems, we’d like a small change in the weight or bias to cause only a small corresponding change in the output from the network. By doing this, we can continuously tweaked the values of weights and bias towards resulting the best approximation. Having a function that can only generate either 0 or 1 (or yes and no), won't help us to achieve this objective.
Why is step function not used in activation functions in machine learning? There are two main reasons why we cannot use the Heaviside step function in (deep) Neural Net: At the moment, one of the most efficient ways to train a multi-layer neural network is by using gradient
13,163
Why is step function not used in activation functions in machine learning?
As answered by the others, the primary reason is that it would not work well during backpropagation. However, adding to what the others wrote, it is important to note that differentiability everywhere is not a necessary condition for backpropagation in neural networks, as one may use subderivatives as well. For example, see the ReLU activation function, which is also non-differentiable at 0 (https://en.wikipedia.org/wiki/Rectifier_(neural_networks))
Why is step function not used in activation functions in machine learning?
As answered by the others, the primary reason is that it would not work well during backpropagation. However, adding to what the others wrote, it is important to note that differentiability everywhere
Why is step function not used in activation functions in machine learning? As answered by the others, the primary reason is that it would not work well during backpropagation. However, adding to what the others wrote, it is important to note that differentiability everywhere is not a necessary condition for backpropagation in neural networks, as one may use subderivatives as well. For example, see the ReLU activation function, which is also non-differentiable at 0 (https://en.wikipedia.org/wiki/Rectifier_(neural_networks))
Why is step function not used in activation functions in machine learning? As answered by the others, the primary reason is that it would not work well during backpropagation. However, adding to what the others wrote, it is important to note that differentiability everywhere
13,164
Why is step function not used in activation functions in machine learning?
Why isn't step function used? What is bad about using a step function in an activation function for neural networks? I assume you mean the Heaviside step function $$ H(x)= \begin{cases} 1 & x \ge 0 \\ 0 & x< 0 \end{cases}. $$ The key feature of $H$ is not that the gradients are sometimes zero, it's that the gradients are almost always zero. $H$ has gradient 0 everywhere except at $x=0$. This means that optimizing a model (e.g. neural network) using gradient-based methods because the gradient is almost always zero. (Indeed, its derivative is the Dirac delta function.) This means that the weights will almost always never move because the gradient step has zero length. Contrasting $H$ to other functions such as ReLU should make it clear why $H$ is unsuitable but other functions with 0 gradient portions can succeed nonetheless. Models using the ReLU have shown marked success, even though the gradient is zero whenever $x<0$. This is because usually not all inputs attain 0 gradient, so weights and biases for $x > 0$ will still update as usual. (However, having 0 gradient "on the left" does give rise to a problem similar to the problems with the Heaviside step function: some weight configurations will always be zero, so these weights are "stuck" and never updated. This is called the dying ReLU phenomenon.) A function having a negligible set where the gradient is not defined is not fatal. The ReLU derivative is not defined at $x=0$ (though the ReLU function is subdifferentiable), but this is inconsequential, both because (1) it rarely happens that floating point arithmetic gives $x=0$ exactly and (2) we can just fudge it by using some number in $[0,1]$ as the gradient for that solitary point -- this arbitrary choice does not make an enormous difference to the final model. (Of course, using a smoother function instead of ReLU will avoid this entirely.) What are the effects of using step function? There are steep shifts from 0 to 1, which may not fit the data well. The network is not differentiable, so gradient-based training is impossible. In what ways are sigmoid/tanh superior over step? The sigmoid layer which combines the affine transformation and the nonlinear activation can be written as $$ \sigma(x) = \frac{1}{1 + \exp(-ax-b)}. $$ For certain $a$, we can view $\sigma$ as a smooth approximation to the step function. A special case of $\sigma$ which has $a$ very large will behave very similarly to $H$, in the sense that there is a rapid increase from 0 to 1, just as we have with $H$. Likewise, if we need a decreasing function or a constant function, these are also special cases of $\sigma$ for different values of $a$. Successful model training will find $a,b$ that achieve a low loss, i.e. choose the parameters which are shallow or steep as required to fit the data well. But when using $\sigma$, we still get differentiability, which is the key to training the network.
Why is step function not used in activation functions in machine learning?
Why isn't step function used? What is bad about using a step function in an activation function for neural networks? I assume you mean the Heaviside step function $$ H(x)= \begin{cases} 1 & x \ge 0 \
Why is step function not used in activation functions in machine learning? Why isn't step function used? What is bad about using a step function in an activation function for neural networks? I assume you mean the Heaviside step function $$ H(x)= \begin{cases} 1 & x \ge 0 \\ 0 & x< 0 \end{cases}. $$ The key feature of $H$ is not that the gradients are sometimes zero, it's that the gradients are almost always zero. $H$ has gradient 0 everywhere except at $x=0$. This means that optimizing a model (e.g. neural network) using gradient-based methods because the gradient is almost always zero. (Indeed, its derivative is the Dirac delta function.) This means that the weights will almost always never move because the gradient step has zero length. Contrasting $H$ to other functions such as ReLU should make it clear why $H$ is unsuitable but other functions with 0 gradient portions can succeed nonetheless. Models using the ReLU have shown marked success, even though the gradient is zero whenever $x<0$. This is because usually not all inputs attain 0 gradient, so weights and biases for $x > 0$ will still update as usual. (However, having 0 gradient "on the left" does give rise to a problem similar to the problems with the Heaviside step function: some weight configurations will always be zero, so these weights are "stuck" and never updated. This is called the dying ReLU phenomenon.) A function having a negligible set where the gradient is not defined is not fatal. The ReLU derivative is not defined at $x=0$ (though the ReLU function is subdifferentiable), but this is inconsequential, both because (1) it rarely happens that floating point arithmetic gives $x=0$ exactly and (2) we can just fudge it by using some number in $[0,1]$ as the gradient for that solitary point -- this arbitrary choice does not make an enormous difference to the final model. (Of course, using a smoother function instead of ReLU will avoid this entirely.) What are the effects of using step function? There are steep shifts from 0 to 1, which may not fit the data well. The network is not differentiable, so gradient-based training is impossible. In what ways are sigmoid/tanh superior over step? The sigmoid layer which combines the affine transformation and the nonlinear activation can be written as $$ \sigma(x) = \frac{1}{1 + \exp(-ax-b)}. $$ For certain $a$, we can view $\sigma$ as a smooth approximation to the step function. A special case of $\sigma$ which has $a$ very large will behave very similarly to $H$, in the sense that there is a rapid increase from 0 to 1, just as we have with $H$. Likewise, if we need a decreasing function or a constant function, these are also special cases of $\sigma$ for different values of $a$. Successful model training will find $a,b$ that achieve a low loss, i.e. choose the parameters which are shallow or steep as required to fit the data well. But when using $\sigma$, we still get differentiability, which is the key to training the network.
Why is step function not used in activation functions in machine learning? Why isn't step function used? What is bad about using a step function in an activation function for neural networks? I assume you mean the Heaviside step function $$ H(x)= \begin{cases} 1 & x \ge 0 \
13,165
Why is step function not used in activation functions in machine learning?
Since we differentiate the activation function in back propagation process to find optimal weight values, we need to have an activation function that is suitable for differentiation. There mainly 2 types of activation functions: *Linear Functions *Non Linear Functions Linear Functions: 1.Identity function:f(x)=x, f'(x)=1 It is too simple 2.Step function:f(x)=1 if x>=0, f(x)=0 if x<0 It is discontinous so cannot be differentiated Also linear functions only work on linearly separable inputs. So we use non linear functions like sigmoid,tanh,ReLU which are continous and have good differentiation results.
Why is step function not used in activation functions in machine learning?
Since we differentiate the activation function in back propagation process to find optimal weight values, we need to have an activation function that is suitable for differentiation. There mainly 2 ty
Why is step function not used in activation functions in machine learning? Since we differentiate the activation function in back propagation process to find optimal weight values, we need to have an activation function that is suitable for differentiation. There mainly 2 types of activation functions: *Linear Functions *Non Linear Functions Linear Functions: 1.Identity function:f(x)=x, f'(x)=1 It is too simple 2.Step function:f(x)=1 if x>=0, f(x)=0 if x<0 It is discontinous so cannot be differentiated Also linear functions only work on linearly separable inputs. So we use non linear functions like sigmoid,tanh,ReLU which are continous and have good differentiation results.
Why is step function not used in activation functions in machine learning? Since we differentiate the activation function in back propagation process to find optimal weight values, we need to have an activation function that is suitable for differentiation. There mainly 2 ty
13,166
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
This is IMHO a complex issue and I would like to make three comments about this situation. First and generally, I would more focus on whether you face a confirmatory study with a set of well-shaped hypotheses defined in a argumentative context or an explanatory study in which many likely indicators are observed than whether they are planned or not (because you can simply plan to make all possible comparisons). Second, I would also focus on how the resulting p-values are then discussed. Are they individually used to serve a set of definitive conclusions, or are they jointly discussed as evidence and lack of evidence? Finally, I would discuss the possibility that the >15 hypothesis resulting from the >15 separate chi-squared tests are in fact the expression of a single few hypotheses (maybe a single one) that may be summarized. More generally, regardless of whether hypothesis are prespecified or not, correcting for multiple comparisons or not is a matter of what you include in the type I error. By not correcting for MC, you only keep a per comparison type I error rate control. So in case of numerous comparisons, you have a high family-wise type I error rate and thus are more false discovery prone.
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
This is IMHO a complex issue and I would like to make three comments about this situation. First and generally, I would more focus on whether you face a confirmatory study with a set of well-shaped hy
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? This is IMHO a complex issue and I would like to make three comments about this situation. First and generally, I would more focus on whether you face a confirmatory study with a set of well-shaped hypotheses defined in a argumentative context or an explanatory study in which many likely indicators are observed than whether they are planned or not (because you can simply plan to make all possible comparisons). Second, I would also focus on how the resulting p-values are then discussed. Are they individually used to serve a set of definitive conclusions, or are they jointly discussed as evidence and lack of evidence? Finally, I would discuss the possibility that the >15 hypothesis resulting from the >15 separate chi-squared tests are in fact the expression of a single few hypotheses (maybe a single one) that may be summarized. More generally, regardless of whether hypothesis are prespecified or not, correcting for multiple comparisons or not is a matter of what you include in the type I error. By not correcting for MC, you only keep a per comparison type I error rate control. So in case of numerous comparisons, you have a high family-wise type I error rate and thus are more false discovery prone.
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? This is IMHO a complex issue and I would like to make three comments about this situation. First and generally, I would more focus on whether you face a confirmatory study with a set of well-shaped hy
13,167
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
If you substitute the word 'premeditated' for 'planned', this may help dispel the argument offered by the authors. Consider two different statistical analyses of the same data: A 'premeditated crime' in which every possible hypothesis test is laid out combinatorially in advance by a 'statistical criminal mastermind', the plan being to try each one systematically, and pick the test with the smallest p-value as the 'key finding' to promote in the Results, Discussion and Conclusion sections of the paper, and indeed the Title as well. A 'crime of passion' in which the initial intention was merely to confront the data with one hypothesis, but "well...one thing leads to another" and multiple ad hoc hypothesis tests "just happen" in the heat of scientific passion to learn "something ... anything!" from the data. Either way, it's 'murder' — the question is whether it's in the First Degree or Second Degree. Clearly, the first is morally more problematic. It sounds to me as if the authors here are attempting to claim something to the effect that it wasn't murder because it was premeditated.
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
If you substitute the word 'premeditated' for 'planned', this may help dispel the argument offered by the authors. Consider two different statistical analyses of the same data: A 'premeditated crime'
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? If you substitute the word 'premeditated' for 'planned', this may help dispel the argument offered by the authors. Consider two different statistical analyses of the same data: A 'premeditated crime' in which every possible hypothesis test is laid out combinatorially in advance by a 'statistical criminal mastermind', the plan being to try each one systematically, and pick the test with the smallest p-value as the 'key finding' to promote in the Results, Discussion and Conclusion sections of the paper, and indeed the Title as well. A 'crime of passion' in which the initial intention was merely to confront the data with one hypothesis, but "well...one thing leads to another" and multiple ad hoc hypothesis tests "just happen" in the heat of scientific passion to learn "something ... anything!" from the data. Either way, it's 'murder' — the question is whether it's in the First Degree or Second Degree. Clearly, the first is morally more problematic. It sounds to me as if the authors here are attempting to claim something to the effect that it wasn't murder because it was premeditated.
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? If you substitute the word 'premeditated' for 'planned', this may help dispel the argument offered by the authors. Consider two different statistical analyses of the same data: A 'premeditated crime'
13,168
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
Given your update on the design I would suggest that they do some form of log-linear model to use all of the data at once. Doing the piece-meal analyses they have done seems (a) inefficient (b) unscientific as it tests 15 hypotheses where surely there are fewer real hypotheses. I am not a fan of correcting for multiplicity as a conditioned reflex but in this case if they reject a deeper analytic approach then I would suggest they correct.
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
Given your update on the design I would suggest that they do some form of log-linear model to use all of the data at once. Doing the piece-meal analyses they have done seems (a) inefficient (b) unscie
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? Given your update on the design I would suggest that they do some form of log-linear model to use all of the data at once. Doing the piece-meal analyses they have done seems (a) inefficient (b) unscientific as it tests 15 hypotheses where surely there are fewer real hypotheses. I am not a fan of correcting for multiplicity as a conditioned reflex but in this case if they reject a deeper analytic approach then I would suggest they correct.
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? Given your update on the design I would suggest that they do some form of log-linear model to use all of the data at once. Doing the piece-meal analyses they have done seems (a) inefficient (b) unscie
13,169
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
This paper directly addresses your question: http://jrp.icaap.org/index.php/jrp/article/view/514/417 (Frane, A.V., "Planned Hypothesis Tests Are Not Necessarily Exempt From Multiplicity Adjustment", Journal of Research Practice, 2015)
If multiple comparisons are "planned", do you still need to correct for multiple comparisons?
This paper directly addresses your question: http://jrp.icaap.org/index.php/jrp/article/view/514/417 (Frane, A.V., "Planned Hypothesis Tests Are Not Necessarily Exempt From Multiplicity Adjustment", J
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? This paper directly addresses your question: http://jrp.icaap.org/index.php/jrp/article/view/514/417 (Frane, A.V., "Planned Hypothesis Tests Are Not Necessarily Exempt From Multiplicity Adjustment", Journal of Research Practice, 2015)
If multiple comparisons are "planned", do you still need to correct for multiple comparisons? This paper directly addresses your question: http://jrp.icaap.org/index.php/jrp/article/view/514/417 (Frane, A.V., "Planned Hypothesis Tests Are Not Necessarily Exempt From Multiplicity Adjustment", J
13,170
From a statistical perspective: Fourier transform vs regression with Fourier basis
They're the same. Here's how... Doing a Regression Say you fit the model $$ y_t = \sum_{j=1}^n A_j \cos(2 \pi t [j/N] + \phi_j) $$ where $t=1,\ldots,N$ and $n = \text{floor}(N/2)$. This isn't suitable for linear regression, though, so instead you use some trigonometry ( $\cos(a + b) = \cos(a)\cos(b) - \sin(a)\sin(b)$) and fit the equivalent model: $$ y_t = \sum_{j=1}^n \beta_{1,j} \cos(2 \pi t [j/N]) + \beta_{2,j}\sin(2 \pi t [j/N]). $$ Running linear regression on all of the Fourier frequencies $\{j/N : j = 1, \ldots, n \}$ gives you a bunch ($2n$) of betas: $\{\hat{\beta}_{i,j}\}$, $i=1,2$. For any $j$, if you wanted to calculate the pair by hand, you could use: $$ \hat{\beta}_{1,j} = \frac{\sum_{t=1}^N y_t \cos(2 \pi t [j/N])}{\sum_{t=1}^N \cos^2(2 \pi t [j/N])} $$ and $$ \hat{\beta}_{2,j} = \frac{\sum_{t=1}^N y_t \sin(2 \pi t [j/N])}{\sum_{t=1}^N \sin^2(2 \pi t [j/N])}. $$ These are standard regression formulas. Doing a Discrete Fourier Transform When you run a Fourier transform, you calculate, for $j=1, \ldots, n$: \begin{align*} d(j/N) &= N^{-1/2}\sum_{t=1}^N y_t \exp[- 2 \pi i t [j/N]] \\ &= N^{-1/2}\left(\sum_{t=1}^N y_t\cos(2 \pi t [j/N]) - i \sum_{t=1}^N y_t\sin(2 \pi t [j/N])\right) . \end{align*} This is a complex number (notice the $i$). To see why that equality holds, keep in mind that $e^{ix} = \cos(x) + i\sin(x)$, $\cos(-x) = \cos(x)$ and $\sin(-x) = -\sin(x)$. For each $j$, taking the square of the complex conjugate gives you the "periodogram:" $$ |d(j/N)|^2 = N^{-1}\left(\sum_{t=1}^N y_t\cos(2 \pi t [j/N])\right)^2 + N^{-1}\left(\sum_{t=1}^N y_t\sin(2 \pi t [j/N])\right)^2. $$ In R, calculating this vector would be I <- abs(fft(Y))^2/length(Y), which is sort of weird, because you have to scale it. Also you can define the "scaled periodogram" $$ P(j/N) = \left(\frac{2}{N}\sum_{t=1}^N y_t \cos(2 \pi t [j/N]) \right)^2 + \left(\frac{2}{N}\sum_{t=1}^N y_t \sin(2 \pi t [j/N]) \right)^2. $$ Clearly $P(j/N) = \frac{4}{N}|d(j/N)|^2$. In R this would be P <- (4/length(Y))*I[(1:floor(length(Y)/2))]. The Connection Between the Two It turns out the connection between the regression and the two periodograms is: $$ P(j/N) = \hat{\beta}_{1,j}^2 + \hat{\beta}_{2,j}^2. $$ Why? Because the basis you chose is orthogonal/orthonormal. You can show for each $j$ that $\sum_{t=1}^N \cos^2(2 \pi t [j/N]) = \sum_{t=1}^N \sin^2(2 \pi t [j/N]) = N/2$. Plug that in to the denominators of your formulas for the regression coefficients and voila. Source: https://www.amazon.com/Time-Analysis-Its-Applications-Statistics/dp/144197864X
From a statistical perspective: Fourier transform vs regression with Fourier basis
They're the same. Here's how... Doing a Regression Say you fit the model $$ y_t = \sum_{j=1}^n A_j \cos(2 \pi t [j/N] + \phi_j) $$ where $t=1,\ldots,N$ and $n = \text{floor}(N/2)$. This isn't suitabl
From a statistical perspective: Fourier transform vs regression with Fourier basis They're the same. Here's how... Doing a Regression Say you fit the model $$ y_t = \sum_{j=1}^n A_j \cos(2 \pi t [j/N] + \phi_j) $$ where $t=1,\ldots,N$ and $n = \text{floor}(N/2)$. This isn't suitable for linear regression, though, so instead you use some trigonometry ( $\cos(a + b) = \cos(a)\cos(b) - \sin(a)\sin(b)$) and fit the equivalent model: $$ y_t = \sum_{j=1}^n \beta_{1,j} \cos(2 \pi t [j/N]) + \beta_{2,j}\sin(2 \pi t [j/N]). $$ Running linear regression on all of the Fourier frequencies $\{j/N : j = 1, \ldots, n \}$ gives you a bunch ($2n$) of betas: $\{\hat{\beta}_{i,j}\}$, $i=1,2$. For any $j$, if you wanted to calculate the pair by hand, you could use: $$ \hat{\beta}_{1,j} = \frac{\sum_{t=1}^N y_t \cos(2 \pi t [j/N])}{\sum_{t=1}^N \cos^2(2 \pi t [j/N])} $$ and $$ \hat{\beta}_{2,j} = \frac{\sum_{t=1}^N y_t \sin(2 \pi t [j/N])}{\sum_{t=1}^N \sin^2(2 \pi t [j/N])}. $$ These are standard regression formulas. Doing a Discrete Fourier Transform When you run a Fourier transform, you calculate, for $j=1, \ldots, n$: \begin{align*} d(j/N) &= N^{-1/2}\sum_{t=1}^N y_t \exp[- 2 \pi i t [j/N]] \\ &= N^{-1/2}\left(\sum_{t=1}^N y_t\cos(2 \pi t [j/N]) - i \sum_{t=1}^N y_t\sin(2 \pi t [j/N])\right) . \end{align*} This is a complex number (notice the $i$). To see why that equality holds, keep in mind that $e^{ix} = \cos(x) + i\sin(x)$, $\cos(-x) = \cos(x)$ and $\sin(-x) = -\sin(x)$. For each $j$, taking the square of the complex conjugate gives you the "periodogram:" $$ |d(j/N)|^2 = N^{-1}\left(\sum_{t=1}^N y_t\cos(2 \pi t [j/N])\right)^2 + N^{-1}\left(\sum_{t=1}^N y_t\sin(2 \pi t [j/N])\right)^2. $$ In R, calculating this vector would be I <- abs(fft(Y))^2/length(Y), which is sort of weird, because you have to scale it. Also you can define the "scaled periodogram" $$ P(j/N) = \left(\frac{2}{N}\sum_{t=1}^N y_t \cos(2 \pi t [j/N]) \right)^2 + \left(\frac{2}{N}\sum_{t=1}^N y_t \sin(2 \pi t [j/N]) \right)^2. $$ Clearly $P(j/N) = \frac{4}{N}|d(j/N)|^2$. In R this would be P <- (4/length(Y))*I[(1:floor(length(Y)/2))]. The Connection Between the Two It turns out the connection between the regression and the two periodograms is: $$ P(j/N) = \hat{\beta}_{1,j}^2 + \hat{\beta}_{2,j}^2. $$ Why? Because the basis you chose is orthogonal/orthonormal. You can show for each $j$ that $\sum_{t=1}^N \cos^2(2 \pi t [j/N]) = \sum_{t=1}^N \sin^2(2 \pi t [j/N]) = N/2$. Plug that in to the denominators of your formulas for the regression coefficients and voila. Source: https://www.amazon.com/Time-Analysis-Its-Applications-Statistics/dp/144197864X
From a statistical perspective: Fourier transform vs regression with Fourier basis They're the same. Here's how... Doing a Regression Say you fit the model $$ y_t = \sum_{j=1}^n A_j \cos(2 \pi t [j/N] + \phi_j) $$ where $t=1,\ldots,N$ and $n = \text{floor}(N/2)$. This isn't suitabl
13,171
From a statistical perspective: Fourier transform vs regression with Fourier basis
They are strongly related. Your example is not reproducible because you didn't include your data, thus I'll make a new one. First of all, let's create a periodic function: T <- 10 omega <- 2*pi/T N <- 21 x <- seq(0, T, len = N) sum_sines_cosines <- function(x, omega){ sin(omega*x)+2*cos(2*omega*x)+3*sin(4*omega*x)+4*cos(4*omega*x) } Yper <- sum_sines_cosines(x, omega) Yper[N]-Yper[1] # numerically 0 x2 <- seq(0, T, len = 1000) Yper2 <- sum_sines_cosines(x2, omega) plot(x2, Yper2, col = "red", type = "l", xlab = "x", ylab = "Y") points(x, Yper) Now, let's create a Fourier basis for regression. Note that, with $N = 2k+1$, it doesn't really make sense to create more than $N-2$ basis functions, i.e., $N-3=2(k-1)$ non-constant sines and cosines, because higher frequency components are aliased on such a grid. For example, a sine of frequency $k\omega$ is indistinguishable from a costant (sine): consider the case of $N=3$, i.e., $k=1$. Anyway, if you want to double check, just change N-2 to N in the snippet below and look at the last two columns: you'll see that they're actually useless (and they create issues for the fit, because the design matrix is now singular). # Fourier Regression with fda library(fda) mybasis <- create.fourier.basis(c(0,T),N-2) basisMat <- eval.basis(x, mybasis) FDA_regression <- lm(Yper ~ basisMat-1) FDA_coef <-coef(FDA_regression) barplot(FDA_coef) Note that the frequencies are exactly the right ones, but the amplitudes of nonzero components are not (1,2,3,4). The reason is that the fda Fourier basis functions are scaled in a weird way: their maximum value is not 1, as it would be for the usual Fourier basis ${1,\sin{ \omega x},\cos{ \omega x},\dots}$. It's not $\frac{1}{\sqrt \pi}$ either, as it would have been for the orthonormal Fourier basis, ${\frac{1}{\sqrt {2\pi}},\frac{\sin{ \omega x}}{\sqrt \pi},\frac{\cos{ \omega x}}{\sqrt \pi},\dots}$. # FDA basis has a weird scaling max(abs(basisMat)) plot(mybasis) You clearly see that: the maximum value is less than $\frac{1}{\sqrt \pi}$ the Fourier basis (truncated to the first $N-2$ terms) contains a constant function (the black line), sines of increasing frequency (the curves which are equal to 0 at the domain boundaries) and cosines of increasing frequency (the curves which are equal to 1 at the domain boundaries), as it should be Simply scaling the Fourier basis given by fda, so that the usual Fourier basis is obtained, leads to regression coefficients having the expected values: basisMat <- basisMat/max(abs(basisMat)) FDA_regression <- lm(Yper ~ basisMat-1) FDA_coef <-coef(FDA_regression) barplot(FDA_coef, names.arg = colnames(basisMat), main = "rescaled FDA coefficients") Let's try fft now: note that since Yper is a periodic sequence, the last point doesn't really add any information (the DFT of a sequence is always periodic). Thus we can discard the last point when computing the FFT. Also, the FFT is just a fast numerical algorithm to compute the DFT, and the DFT of a sequence of real or complex numbers is complex. Thus, we really want the moduluses of the FFT coefficients: # FFT fft_coef <- Mod(fft(Yper[1:(N-1)]))*2/(N-1) We multiply by $\frac{2}{N-1}$ in order to have the same scaling as with the Fourier basis ${1,\sin{ \omega x},\cos{ \omega x},\dots}$. If we didn't scale, we would still recover the correct frequencies, but the amplitudes would all be scaled by the same factor with respect to what we found before. Let's now plot the fft coefficients: fft_coef <- fft_coef[1:((N-1)/2)] terms <- paste0("exp",seq(0,(N-1)/2-1)) barplot(fft_coef, names.arg = terms, main = "FFT coefficients") Ok: the frequencies are correct, but note that now the basis functions are not sines and cosines any more (they're complex exponentials $\exp{ni\omega x}$, where with $i$ I denote the imaginary unit). Note also that instead than a set of nonzero frequencies (1,2,3,4) as before, we got a set (1,2,5). The reason is that a term $x_n\exp{ni\omega x}$ in this complex coefficient expansion (thus $x_n$ is complex) corresponds to two real terms $a_n sin(n\omega x)+b_n cos(n\omega x)$ in the trigonometric basis expansion, because of the Euler formula $\exp{ix}=\cos{x}+i\sin{x}$. The modulus of the complex coefficient is equal to the sum in quadrature of the two real coefficients, i.e., $|x_n|=\sqrt{a_n^2+b_n^2}$. As a matter of fact, $5=\sqrt{3^3+4^2}$.
From a statistical perspective: Fourier transform vs regression with Fourier basis
They are strongly related. Your example is not reproducible because you didn't include your data, thus I'll make a new one. First of all, let's create a periodic function: T <- 10 omega <- 2*pi/T N <-
From a statistical perspective: Fourier transform vs regression with Fourier basis They are strongly related. Your example is not reproducible because you didn't include your data, thus I'll make a new one. First of all, let's create a periodic function: T <- 10 omega <- 2*pi/T N <- 21 x <- seq(0, T, len = N) sum_sines_cosines <- function(x, omega){ sin(omega*x)+2*cos(2*omega*x)+3*sin(4*omega*x)+4*cos(4*omega*x) } Yper <- sum_sines_cosines(x, omega) Yper[N]-Yper[1] # numerically 0 x2 <- seq(0, T, len = 1000) Yper2 <- sum_sines_cosines(x2, omega) plot(x2, Yper2, col = "red", type = "l", xlab = "x", ylab = "Y") points(x, Yper) Now, let's create a Fourier basis for regression. Note that, with $N = 2k+1$, it doesn't really make sense to create more than $N-2$ basis functions, i.e., $N-3=2(k-1)$ non-constant sines and cosines, because higher frequency components are aliased on such a grid. For example, a sine of frequency $k\omega$ is indistinguishable from a costant (sine): consider the case of $N=3$, i.e., $k=1$. Anyway, if you want to double check, just change N-2 to N in the snippet below and look at the last two columns: you'll see that they're actually useless (and they create issues for the fit, because the design matrix is now singular). # Fourier Regression with fda library(fda) mybasis <- create.fourier.basis(c(0,T),N-2) basisMat <- eval.basis(x, mybasis) FDA_regression <- lm(Yper ~ basisMat-1) FDA_coef <-coef(FDA_regression) barplot(FDA_coef) Note that the frequencies are exactly the right ones, but the amplitudes of nonzero components are not (1,2,3,4). The reason is that the fda Fourier basis functions are scaled in a weird way: their maximum value is not 1, as it would be for the usual Fourier basis ${1,\sin{ \omega x},\cos{ \omega x},\dots}$. It's not $\frac{1}{\sqrt \pi}$ either, as it would have been for the orthonormal Fourier basis, ${\frac{1}{\sqrt {2\pi}},\frac{\sin{ \omega x}}{\sqrt \pi},\frac{\cos{ \omega x}}{\sqrt \pi},\dots}$. # FDA basis has a weird scaling max(abs(basisMat)) plot(mybasis) You clearly see that: the maximum value is less than $\frac{1}{\sqrt \pi}$ the Fourier basis (truncated to the first $N-2$ terms) contains a constant function (the black line), sines of increasing frequency (the curves which are equal to 0 at the domain boundaries) and cosines of increasing frequency (the curves which are equal to 1 at the domain boundaries), as it should be Simply scaling the Fourier basis given by fda, so that the usual Fourier basis is obtained, leads to regression coefficients having the expected values: basisMat <- basisMat/max(abs(basisMat)) FDA_regression <- lm(Yper ~ basisMat-1) FDA_coef <-coef(FDA_regression) barplot(FDA_coef, names.arg = colnames(basisMat), main = "rescaled FDA coefficients") Let's try fft now: note that since Yper is a periodic sequence, the last point doesn't really add any information (the DFT of a sequence is always periodic). Thus we can discard the last point when computing the FFT. Also, the FFT is just a fast numerical algorithm to compute the DFT, and the DFT of a sequence of real or complex numbers is complex. Thus, we really want the moduluses of the FFT coefficients: # FFT fft_coef <- Mod(fft(Yper[1:(N-1)]))*2/(N-1) We multiply by $\frac{2}{N-1}$ in order to have the same scaling as with the Fourier basis ${1,\sin{ \omega x},\cos{ \omega x},\dots}$. If we didn't scale, we would still recover the correct frequencies, but the amplitudes would all be scaled by the same factor with respect to what we found before. Let's now plot the fft coefficients: fft_coef <- fft_coef[1:((N-1)/2)] terms <- paste0("exp",seq(0,(N-1)/2-1)) barplot(fft_coef, names.arg = terms, main = "FFT coefficients") Ok: the frequencies are correct, but note that now the basis functions are not sines and cosines any more (they're complex exponentials $\exp{ni\omega x}$, where with $i$ I denote the imaginary unit). Note also that instead than a set of nonzero frequencies (1,2,3,4) as before, we got a set (1,2,5). The reason is that a term $x_n\exp{ni\omega x}$ in this complex coefficient expansion (thus $x_n$ is complex) corresponds to two real terms $a_n sin(n\omega x)+b_n cos(n\omega x)$ in the trigonometric basis expansion, because of the Euler formula $\exp{ix}=\cos{x}+i\sin{x}$. The modulus of the complex coefficient is equal to the sum in quadrature of the two real coefficients, i.e., $|x_n|=\sqrt{a_n^2+b_n^2}$. As a matter of fact, $5=\sqrt{3^3+4^2}$.
From a statistical perspective: Fourier transform vs regression with Fourier basis They are strongly related. Your example is not reproducible because you didn't include your data, thus I'll make a new one. First of all, let's create a periodic function: T <- 10 omega <- 2*pi/T N <-
13,172
From a statistical perspective: Fourier transform vs regression with Fourier basis
I want to say that the first answer has an overflow error since the second formula for DFT coefficients is infinite when j = N/2 at this value the argumment for sine is π * t making the value zero for all t's. β^2,j=∑Nt=1ytsin(2πt[j/N])∑Nt=1sin2(2πt[j/N]) There are others DFT Data Regressions in published papers out there in google but i've not analyzed them correctly as they are confusing me. Perhaps the author of the first answer may help us as I'm tanglemessed up with this. Thanks in advance
From a statistical perspective: Fourier transform vs regression with Fourier basis
I want to say that the first answer has an overflow error since the second formula for DFT coefficients is infinite when j = N/2 at this value the argumment for sine is π * t making the value zero for
From a statistical perspective: Fourier transform vs regression with Fourier basis I want to say that the first answer has an overflow error since the second formula for DFT coefficients is infinite when j = N/2 at this value the argumment for sine is π * t making the value zero for all t's. β^2,j=∑Nt=1ytsin(2πt[j/N])∑Nt=1sin2(2πt[j/N]) There are others DFT Data Regressions in published papers out there in google but i've not analyzed them correctly as they are confusing me. Perhaps the author of the first answer may help us as I'm tanglemessed up with this. Thanks in advance
From a statistical perspective: Fourier transform vs regression with Fourier basis I want to say that the first answer has an overflow error since the second formula for DFT coefficients is infinite when j = N/2 at this value the argumment for sine is π * t making the value zero for
13,173
The sum of independent lognormal random variables appears lognormal?
This approximate lognormality of sums of lognormals is a well-known rule of thumb; it's mentioned in numerous papers -- and in a number of posts on site. A lognormal approximation for a sum of lognormals by matching the first two moments is sometimes called a Fenton-Wilkinson approximation. You may find this document by Dufresne useful (available here, or here). I have also in the past sometimes pointed people to Mitchell's paper Mitchell, R.L. (1968), "Permanence of the log-normal distribution." J. Optical Society of America. 58: 1267-1272. But that's now covered in the references of Dufresne. But while it holds in a fairly wide set of not-too-skew cases, it doesn't hold in general, not even for i.i.d. lognormals, not even as $n$ gets quite large. Here's a histogram of 1000 simulated values, each the log of the sum of fifty-thousand i.i.d lognormals: As you see ... the log is quite skew, so the sum is not very close to lognormal. Indeed, this example would also count as a useful example for people thinking (because of the central limit theorem) that some $n$ in the hundreds or thousands will give very close to normal averages; this one is so skew that its log is considerably right skew, but the central limit theorem nevertheless applies here; an $n$ of many millions* would be necessary before it begins to look anywhere near symmetric. * I have not tried to figure out how many but, because of the way that skewness of sums (equivalently, averages) behaves, a few million will clearly be insufficient Since more details were requested in comments, you can get a similar-looking result to the example with the following code, which produces 1000 replicates of the sum of 50,000 lognormal random variables with scale parameter $\mu=0$ and shape parameter $\sigma=4$: res <- replicate(1000,sum(rlnorm(50000,0,4))) hist(log(res),n=100) (I have since tried $n=10^6$. Its log is still heavily right skew)
The sum of independent lognormal random variables appears lognormal?
This approximate lognormality of sums of lognormals is a well-known rule of thumb; it's mentioned in numerous papers -- and in a number of posts on site. A lognormal approximation for a sum of lognor
The sum of independent lognormal random variables appears lognormal? This approximate lognormality of sums of lognormals is a well-known rule of thumb; it's mentioned in numerous papers -- and in a number of posts on site. A lognormal approximation for a sum of lognormals by matching the first two moments is sometimes called a Fenton-Wilkinson approximation. You may find this document by Dufresne useful (available here, or here). I have also in the past sometimes pointed people to Mitchell's paper Mitchell, R.L. (1968), "Permanence of the log-normal distribution." J. Optical Society of America. 58: 1267-1272. But that's now covered in the references of Dufresne. But while it holds in a fairly wide set of not-too-skew cases, it doesn't hold in general, not even for i.i.d. lognormals, not even as $n$ gets quite large. Here's a histogram of 1000 simulated values, each the log of the sum of fifty-thousand i.i.d lognormals: As you see ... the log is quite skew, so the sum is not very close to lognormal. Indeed, this example would also count as a useful example for people thinking (because of the central limit theorem) that some $n$ in the hundreds or thousands will give very close to normal averages; this one is so skew that its log is considerably right skew, but the central limit theorem nevertheless applies here; an $n$ of many millions* would be necessary before it begins to look anywhere near symmetric. * I have not tried to figure out how many but, because of the way that skewness of sums (equivalently, averages) behaves, a few million will clearly be insufficient Since more details were requested in comments, you can get a similar-looking result to the example with the following code, which produces 1000 replicates of the sum of 50,000 lognormal random variables with scale parameter $\mu=0$ and shape parameter $\sigma=4$: res <- replicate(1000,sum(rlnorm(50000,0,4))) hist(log(res),n=100) (I have since tried $n=10^6$. Its log is still heavily right skew)
The sum of independent lognormal random variables appears lognormal? This approximate lognormality of sums of lognormals is a well-known rule of thumb; it's mentioned in numerous papers -- and in a number of posts on site. A lognormal approximation for a sum of lognor
13,174
The sum of independent lognormal random variables appears lognormal?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. It's probably too late, but I've found the following paper on the sums of lognormal distributions, which covers the topic. It's not lognormal, but something quite different and difficult to work with.
The sum of independent lognormal random variables appears lognormal?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
The sum of independent lognormal random variables appears lognormal? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. It's probably too late, but I've found the following paper on the sums of lognormal distributions, which covers the topic. It's not lognormal, but something quite different and difficult to work with.
The sum of independent lognormal random variables appears lognormal? Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
13,175
The sum of independent lognormal random variables appears lognormal?
Lognormal law is widely present on physical phenomena, sums of this kind of variable distributions are needed for instance to study any scaling behavior of a system. I know this article (very long and very strong, the beginning can be undertood if you are not specilist!), "Broad distribution effects in sums of lognormal random variables" published in 2003, (the European Physical Journal B-Condensed Matter and Complex Systems 32, 513) and is available https://arxiv.org/pdf/physics/0211065.pdf .
The sum of independent lognormal random variables appears lognormal?
Lognormal law is widely present on physical phenomena, sums of this kind of variable distributions are needed for instance to study any scaling behavior of a system. I know this article (very long and
The sum of independent lognormal random variables appears lognormal? Lognormal law is widely present on physical phenomena, sums of this kind of variable distributions are needed for instance to study any scaling behavior of a system. I know this article (very long and very strong, the beginning can be undertood if you are not specilist!), "Broad distribution effects in sums of lognormal random variables" published in 2003, (the European Physical Journal B-Condensed Matter and Complex Systems 32, 513) and is available https://arxiv.org/pdf/physics/0211065.pdf .
The sum of independent lognormal random variables appears lognormal? Lognormal law is widely present on physical phenomena, sums of this kind of variable distributions are needed for instance to study any scaling behavior of a system. I know this article (very long and
13,176
The sum of independent lognormal random variables appears lognormal?
The adviced paper by Dufresne of 2009 and this one from 2004 together with this useful paper cover the history on the approximations of the sum of log-normal distribution and gives sum mathematical result. The problem is that all the approximations cited there are found by supposing from the depart that you are in a case in which the sum of log-normal distributions is still log-normal. Then you can compute the $\mu$ and the $\sigma$ of the global sum in some approximated way. But this doesn't give you the conditions that you have to fulfill if you want that the sum is still log-normal. Maybe [this paper] (http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6029348) give you in a particular case a kind of central limit theorem for the sum of log-normals but there is still a lack of generality. Anyway the example given by Glen_b it's not really appropriate, because it's a case where you can easily apply the classic central limit theorem, and of course in that case the sum of log-normal is Gaussian. But is true as said in the paper cited just above that even in the limit $n\to \infty$ you can have a log-normal sum (for example if variables are correlated or sufficiently not i.i.d.)
The sum of independent lognormal random variables appears lognormal?
The adviced paper by Dufresne of 2009 and this one from 2004 together with this useful paper cover the history on the approximations of the sum of log-normal distribution and gives sum mathematical r
The sum of independent lognormal random variables appears lognormal? The adviced paper by Dufresne of 2009 and this one from 2004 together with this useful paper cover the history on the approximations of the sum of log-normal distribution and gives sum mathematical result. The problem is that all the approximations cited there are found by supposing from the depart that you are in a case in which the sum of log-normal distributions is still log-normal. Then you can compute the $\mu$ and the $\sigma$ of the global sum in some approximated way. But this doesn't give you the conditions that you have to fulfill if you want that the sum is still log-normal. Maybe [this paper] (http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6029348) give you in a particular case a kind of central limit theorem for the sum of log-normals but there is still a lack of generality. Anyway the example given by Glen_b it's not really appropriate, because it's a case where you can easily apply the classic central limit theorem, and of course in that case the sum of log-normal is Gaussian. But is true as said in the paper cited just above that even in the limit $n\to \infty$ you can have a log-normal sum (for example if variables are correlated or sufficiently not i.i.d.)
The sum of independent lognormal random variables appears lognormal? The adviced paper by Dufresne of 2009 and this one from 2004 together with this useful paper cover the history on the approximations of the sum of log-normal distribution and gives sum mathematical r
13,177
Random forest vs regression
I don't know exactly what you did, so your source code would help me to guess less. Many random forests are essentially windows within which the average is assumed to represent the system. It is an over-glorified CAR-tree. Lets say you have a two-leaf CAR-tree. Your data will be split into two piles. The (constant) output of each pile will be its average. Now lets do it 1000 times with random subsets of the data. You will still have discontinuous regions with outputs that are averages. The winner in a RF is the most frequent outcome. That only "Fuzzies" the border between categories. Example of piecewise linear output of CART tree: Let us say, for instance, that our function is y=0.5*x+2. A plot of that looks like the following: If we were to model this using a single classification tree with only two leaves then we would first find the point of best split, split at that point, and then approximate the function output at each leaf as the average output over the leaf. If we were to do this again with more leaves on the CART tree then we might get the following: Why CAR-forests? You can see that, in the limit of infinite leaves the CART tree would be an acceptable approximator. The problem is that the real world is noisy. We like to think in means, but the world likes both the central tendency (mean) and the tendency of variation (std dev). There is noise. The same thing that gives a CAR-tree its great strength, its ability to handle discontinuity, makes it vulnerable to modeling noise as if it were signal. So Leo Breimann made a simple but powerful proposition: use Ensemble methods to make Classification and Regression trees robust. He takes random subsets (a cousin of bootstrap resampling) and uses them to train a forest of CAR-trees. When you ask a question of the forest, the whole forest speaks, and the most common answer is taken as the output. If you are dealing with numeric data, it can be useful to look at the expectation as the output. So for the second plot, think about modeling using a random forest. Each tree will have a random subset of the data. That means that the location of the "best" split point will vary from tree to tree. If you were to make a plot of the output of the random forest, as you approach the discontinuity, first few branches will indicate a jump, then many. The mean value in that region will traverse a smooth sigmoid path. Bootstrapping is convolving with a Gaussian, and the Gaussian blur on that step function becomes a sigmoid. Bottom lines: You need a lot of branches per tree to get a good approximation to a very linear function. There are many "dials" that you could change to impact the answer, and it is unlikely that you have set them all to the proper values. References: http://www.mathworks.com/help/stats/classification-trees-and-regression-trees.html#bsw6p25 http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm http://userwww.service.emory.edu/~tyu8/740/Lecture%207.pptx http://www.stanford.edu/~stephsus/R-randomforest-guide.pdf
Random forest vs regression
I don't know exactly what you did, so your source code would help me to guess less. Many random forests are essentially windows within which the average is assumed to represent the system. It is an o
Random forest vs regression I don't know exactly what you did, so your source code would help me to guess less. Many random forests are essentially windows within which the average is assumed to represent the system. It is an over-glorified CAR-tree. Lets say you have a two-leaf CAR-tree. Your data will be split into two piles. The (constant) output of each pile will be its average. Now lets do it 1000 times with random subsets of the data. You will still have discontinuous regions with outputs that are averages. The winner in a RF is the most frequent outcome. That only "Fuzzies" the border between categories. Example of piecewise linear output of CART tree: Let us say, for instance, that our function is y=0.5*x+2. A plot of that looks like the following: If we were to model this using a single classification tree with only two leaves then we would first find the point of best split, split at that point, and then approximate the function output at each leaf as the average output over the leaf. If we were to do this again with more leaves on the CART tree then we might get the following: Why CAR-forests? You can see that, in the limit of infinite leaves the CART tree would be an acceptable approximator. The problem is that the real world is noisy. We like to think in means, but the world likes both the central tendency (mean) and the tendency of variation (std dev). There is noise. The same thing that gives a CAR-tree its great strength, its ability to handle discontinuity, makes it vulnerable to modeling noise as if it were signal. So Leo Breimann made a simple but powerful proposition: use Ensemble methods to make Classification and Regression trees robust. He takes random subsets (a cousin of bootstrap resampling) and uses them to train a forest of CAR-trees. When you ask a question of the forest, the whole forest speaks, and the most common answer is taken as the output. If you are dealing with numeric data, it can be useful to look at the expectation as the output. So for the second plot, think about modeling using a random forest. Each tree will have a random subset of the data. That means that the location of the "best" split point will vary from tree to tree. If you were to make a plot of the output of the random forest, as you approach the discontinuity, first few branches will indicate a jump, then many. The mean value in that region will traverse a smooth sigmoid path. Bootstrapping is convolving with a Gaussian, and the Gaussian blur on that step function becomes a sigmoid. Bottom lines: You need a lot of branches per tree to get a good approximation to a very linear function. There are many "dials" that you could change to impact the answer, and it is unlikely that you have set them all to the proper values. References: http://www.mathworks.com/help/stats/classification-trees-and-regression-trees.html#bsw6p25 http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm http://userwww.service.emory.edu/~tyu8/740/Lecture%207.pptx http://www.stanford.edu/~stephsus/R-randomforest-guide.pdf
Random forest vs regression I don't know exactly what you did, so your source code would help me to guess less. Many random forests are essentially windows within which the average is assumed to represent the system. It is an o
13,178
Random forest vs regression
I notice that this is an old question, but I think more should be added. As @Manoel Galdino said in the comments, usually you are interested in predictions on unseen data. But this question is about performance on the training data and the question is why does random forest perform badly on the training data? The answer highlights an interesting problem with bagged classifiers which has often caused me trouble: regression to the mean. The problem is that bagged classifiers like random forest, which are made by taking bootstrap samples from your data set, tend to perform badly in the extremes. Because there is not much data in the extremes, they tend to get smoothed out. In more detail, recall that a random forest for regression averages the predictions of a large number of classifiers. If you have a single point which is far from the others, many of the classifiers will not see it, and these will essentially be making an out-of-sample prediction, which might not be very good. In fact, these out-of-sample predictions will tend to pull the prediction for the data point towards the overall mean. If you use a single decision tree, you won't have the same problem with extreme values, but the fitted regression won't be very linear either. Here is an illustration in R. Some data is generated in which y is a perfect liner combination of five x variables. Then predictions are made with a linear model and a random forest. Then the values of y on the training data are plotted against the predictions. You can clearly see that random forest is doing badly in the extremes because data points with very large or very small values of y are rare. You will see the same pattern for predictions on unseen data when random forests are used for regression. I am not sure how to avoid it. The randomForest function in R has a crude bias correction option corr.bias which uses linear regression on the bias, but it doesn't really work. Suggestions are welcome! beta <- runif(5) x <- matrix(rnorm(500), nc=5) y <- drop(x %*% beta) dat <- data.frame(y=y, x1=x[,1], x2=x[,2], x3=x[,3], x4=x[,4], x5=x[,5]) model1 <- lm(y~., data=dat) model2 <- randomForest(y ~., data=dat) pred1 <- predict(model1 ,dat) pred2 <- predict(model2 ,dat) plot(y, pred1) points(y, pred2, col="blue")
Random forest vs regression
I notice that this is an old question, but I think more should be added. As @Manoel Galdino said in the comments, usually you are interested in predictions on unseen data. But this question is about p
Random forest vs regression I notice that this is an old question, but I think more should be added. As @Manoel Galdino said in the comments, usually you are interested in predictions on unseen data. But this question is about performance on the training data and the question is why does random forest perform badly on the training data? The answer highlights an interesting problem with bagged classifiers which has often caused me trouble: regression to the mean. The problem is that bagged classifiers like random forest, which are made by taking bootstrap samples from your data set, tend to perform badly in the extremes. Because there is not much data in the extremes, they tend to get smoothed out. In more detail, recall that a random forest for regression averages the predictions of a large number of classifiers. If you have a single point which is far from the others, many of the classifiers will not see it, and these will essentially be making an out-of-sample prediction, which might not be very good. In fact, these out-of-sample predictions will tend to pull the prediction for the data point towards the overall mean. If you use a single decision tree, you won't have the same problem with extreme values, but the fitted regression won't be very linear either. Here is an illustration in R. Some data is generated in which y is a perfect liner combination of five x variables. Then predictions are made with a linear model and a random forest. Then the values of y on the training data are plotted against the predictions. You can clearly see that random forest is doing badly in the extremes because data points with very large or very small values of y are rare. You will see the same pattern for predictions on unseen data when random forests are used for regression. I am not sure how to avoid it. The randomForest function in R has a crude bias correction option corr.bias which uses linear regression on the bias, but it doesn't really work. Suggestions are welcome! beta <- runif(5) x <- matrix(rnorm(500), nc=5) y <- drop(x %*% beta) dat <- data.frame(y=y, x1=x[,1], x2=x[,2], x3=x[,3], x4=x[,4], x5=x[,5]) model1 <- lm(y~., data=dat) model2 <- randomForest(y ~., data=dat) pred1 <- predict(model1 ,dat) pred2 <- predict(model2 ,dat) plot(y, pred1) points(y, pred2, col="blue")
Random forest vs regression I notice that this is an old question, but I think more should be added. As @Manoel Galdino said in the comments, usually you are interested in predictions on unseen data. But this question is about p
13,179
Random forest vs regression
Random forest tries to find localities among lots of features and lots of data points. It splits the features and gives them to different trees, as you have low number of features the overall result is not as good as logistic regression. Random forest can handle numeric and categorical variables but is not good at handling missing values.
Random forest vs regression
Random forest tries to find localities among lots of features and lots of data points. It splits the features and gives them to different trees, as you have low number of features the overall result i
Random forest vs regression Random forest tries to find localities among lots of features and lots of data points. It splits the features and gives them to different trees, as you have low number of features the overall result is not as good as logistic regression. Random forest can handle numeric and categorical variables but is not good at handling missing values.
Random forest vs regression Random forest tries to find localities among lots of features and lots of data points. It splits the features and gives them to different trees, as you have low number of features the overall result i
13,180
Random forest vs regression
I think that Random Forest (RF) is a good tool when the functional form of the relation between Xs and y is complicated (because of nonlinear relations and interaction effect). RF categorizes Xs based on the best cutpoint (in term of minimum SSE) and doesn't apply the researcher information about the functional form of relationship. On the oothe hand, OLS regression use this information. In your example, you know what exactly is the type of relationship between Xs and y and use all of this information in your regression model but RF don't use this information.
Random forest vs regression
I think that Random Forest (RF) is a good tool when the functional form of the relation between Xs and y is complicated (because of nonlinear relations and interaction effect). RF categorizes Xs based
Random forest vs regression I think that Random Forest (RF) is a good tool when the functional form of the relation between Xs and y is complicated (because of nonlinear relations and interaction effect). RF categorizes Xs based on the best cutpoint (in term of minimum SSE) and doesn't apply the researcher information about the functional form of relationship. On the oothe hand, OLS regression use this information. In your example, you know what exactly is the type of relationship between Xs and y and use all of this information in your regression model but RF don't use this information.
Random forest vs regression I think that Random Forest (RF) is a good tool when the functional form of the relation between Xs and y is complicated (because of nonlinear relations and interaction effect). RF categorizes Xs based
13,181
Random forest vs regression
For the basics, Regression perform well over continuous variables and Random Forest over discrete variables. You need to provide more details about the problem and about the nature of the variables in order to be more specific...
Random forest vs regression
For the basics, Regression perform well over continuous variables and Random Forest over discrete variables. You need to provide more details about the problem and about the nature of the variables in
Random forest vs regression For the basics, Regression perform well over continuous variables and Random Forest over discrete variables. You need to provide more details about the problem and about the nature of the variables in order to be more specific...
Random forest vs regression For the basics, Regression perform well over continuous variables and Random Forest over discrete variables. You need to provide more details about the problem and about the nature of the variables in
13,182
Confounder - definition
Why must the confounder be causally related to the outcome? Would it be enough for the confounder to be associated with the outcome? No, it's not enough. Let's start with the case where you can have a variable which is both associated with the outcome and the treatment, but controlling for it would bias your estimate. For example, consider the following causal graph, taken from Pearl, where $Z$ is a pre-treatment collider: In this case, there's no confounding, you can estimate the effect of X on Y directly. Notice, however, that Z is associated both with the treatment and with the outcome. But it's still not a confounder. In fact, if you control for Z in this case you would bias your estimate. This situation is called M-bias (because of the graph structure). Another similar, more straightforward, case where you should not control is when the variable is a result both of the treatment $X$ and of the outcome $Y$. Take this simple collider graph: Here, again, Z is associated with X and Y, but it's not a cofounder. You should not control for it. Now, it's worth noticing that even if a variable is causally related to the outcome, it's also not necessarily a confounder. Let's take the case of mediators, in the simple graph below: If you want to measure the total effect of D on Y, you should not control for things that mediate the effect --- in this case M. That is, M is causally related to Y, yet it's not a confounder with respect to the total effect of D on Y either. Notice however, that defining confouding is much easier than defining what a confounder is. For a more strict discussion of the definition of confouder, you might want to read this paper by VanderWeele and Shpitser. Why is this the case? Because the primary concept here is that of the confounding itself, not of confounder. For you research question, you should ask yourself "how can I eliminate confounding?" instead of "is this variable a confounder?". And as a final note, it's worth mentioning that these misconceptions are still widespread. Just to illustrate, take this citation from a 2016 paper: Causal inference in the absence of a randomized experiment or strong quasi-experimental design requires appropriately conditioning on all pre-treatment variables that predict both treatment and outcome, also known as confounding covariates. As we have shown in the previous examples, this is incorrect. Confounders are not "all pre-treatment variables that predict both treatment and outcome". Controlling for all them might not be necessary for eliminating confounding or it could even bias your results. Pearl has a very good overview on confounding here.
Confounder - definition
Why must the confounder be causally related to the outcome? Would it be enough for the confounder to be associated with the outcome? No, it's not enough. Let's start with the case where you can hav
Confounder - definition Why must the confounder be causally related to the outcome? Would it be enough for the confounder to be associated with the outcome? No, it's not enough. Let's start with the case where you can have a variable which is both associated with the outcome and the treatment, but controlling for it would bias your estimate. For example, consider the following causal graph, taken from Pearl, where $Z$ is a pre-treatment collider: In this case, there's no confounding, you can estimate the effect of X on Y directly. Notice, however, that Z is associated both with the treatment and with the outcome. But it's still not a confounder. In fact, if you control for Z in this case you would bias your estimate. This situation is called M-bias (because of the graph structure). Another similar, more straightforward, case where you should not control is when the variable is a result both of the treatment $X$ and of the outcome $Y$. Take this simple collider graph: Here, again, Z is associated with X and Y, but it's not a cofounder. You should not control for it. Now, it's worth noticing that even if a variable is causally related to the outcome, it's also not necessarily a confounder. Let's take the case of mediators, in the simple graph below: If you want to measure the total effect of D on Y, you should not control for things that mediate the effect --- in this case M. That is, M is causally related to Y, yet it's not a confounder with respect to the total effect of D on Y either. Notice however, that defining confouding is much easier than defining what a confounder is. For a more strict discussion of the definition of confouder, you might want to read this paper by VanderWeele and Shpitser. Why is this the case? Because the primary concept here is that of the confounding itself, not of confounder. For you research question, you should ask yourself "how can I eliminate confounding?" instead of "is this variable a confounder?". And as a final note, it's worth mentioning that these misconceptions are still widespread. Just to illustrate, take this citation from a 2016 paper: Causal inference in the absence of a randomized experiment or strong quasi-experimental design requires appropriately conditioning on all pre-treatment variables that predict both treatment and outcome, also known as confounding covariates. As we have shown in the previous examples, this is incorrect. Confounders are not "all pre-treatment variables that predict both treatment and outcome". Controlling for all them might not be necessary for eliminating confounding or it could even bias your results. Pearl has a very good overview on confounding here.
Confounder - definition Why must the confounder be causally related to the outcome? Would it be enough for the confounder to be associated with the outcome? No, it's not enough. Let's start with the case where you can hav
13,183
Are linear regression and least squares regression necessarily the same thing?
An explanation rather depends on what your background is. Suppose you have some so-called independent variables $x_1,x_2,\ldots, x_k$ (they do not have to be independent of each other) where each $x_i$ takes takes values $x_{i,1}, x_{i,2}\ldots, x_{i,n}$ and you want a regression for a dependent variable $y$ taking values $y_{1}, y_{2}\ldots, y_{n}$. Then you are trying to find a function $f(x_{1,j}, x_{2,j},\ldots, x_{k,j})$ of the independent variables which in some sense minimises the loss from using that function as some measure across the observations comparing all the $y_j$ and their corresponding $f(x_{1,j}, x_{2,j},\ldots, x_{k,j})$ Linear regression restricts the possible $f$ to those of the form $f(x_{1,j}, x_{2,j},\ldots, x_{k,j})=\beta_0+\beta_1x_{1,j}+\beta_2x_{2,j}+\ldots+\beta_kx_{k,j}$ for real values $\beta_0,\beta_1,\beta_2, \ldots ,\beta_k$. Least squares regression uses a loss function of the form $\sum\limits_{j=1}^n (y_j - f(x_{1,j}, x_{2,j},\ldots, x_{k,j}))^2$ which you want to minimise by choosing a suitable $f$. Ordinary Least Squares Linear Regression combines the linear form of estimator and minimising the sum of the squares of the differences, so both requirements. But other forms of regression may only use one or even neither of them. For example, logistic regression can be seen as not being linear (it is not least-squares either, instead using maximum likelihood techniques), while robust regression typically is not a simple least squares calculation though may be linear
Are linear regression and least squares regression necessarily the same thing?
An explanation rather depends on what your background is. Suppose you have some so-called independent variables $x_1,x_2,\ldots, x_k$ (they do not have to be independent of each other) where each $x_i
Are linear regression and least squares regression necessarily the same thing? An explanation rather depends on what your background is. Suppose you have some so-called independent variables $x_1,x_2,\ldots, x_k$ (they do not have to be independent of each other) where each $x_i$ takes takes values $x_{i,1}, x_{i,2}\ldots, x_{i,n}$ and you want a regression for a dependent variable $y$ taking values $y_{1}, y_{2}\ldots, y_{n}$. Then you are trying to find a function $f(x_{1,j}, x_{2,j},\ldots, x_{k,j})$ of the independent variables which in some sense minimises the loss from using that function as some measure across the observations comparing all the $y_j$ and their corresponding $f(x_{1,j}, x_{2,j},\ldots, x_{k,j})$ Linear regression restricts the possible $f$ to those of the form $f(x_{1,j}, x_{2,j},\ldots, x_{k,j})=\beta_0+\beta_1x_{1,j}+\beta_2x_{2,j}+\ldots+\beta_kx_{k,j}$ for real values $\beta_0,\beta_1,\beta_2, \ldots ,\beta_k$. Least squares regression uses a loss function of the form $\sum\limits_{j=1}^n (y_j - f(x_{1,j}, x_{2,j},\ldots, x_{k,j}))^2$ which you want to minimise by choosing a suitable $f$. Ordinary Least Squares Linear Regression combines the linear form of estimator and minimising the sum of the squares of the differences, so both requirements. But other forms of regression may only use one or even neither of them. For example, logistic regression can be seen as not being linear (it is not least-squares either, instead using maximum likelihood techniques), while robust regression typically is not a simple least squares calculation though may be linear
Are linear regression and least squares regression necessarily the same thing? An explanation rather depends on what your background is. Suppose you have some so-called independent variables $x_1,x_2,\ldots, x_k$ (they do not have to be independent of each other) where each $x_i
13,184
Are linear regression and least squares regression necessarily the same thing?
Least squares is the processes of minimizing the sum of squared errors from some model. Given a function $f$ which depends on parameters $\theta$, the least squares estimates of $\theta$ are $$ \hat{\theta} = \underset{\theta \in \mathbb{R}^p}{\mbox{argmin}} \left\{ \sum_i (y_i - f(x_i ; \theta))^2 \right\}$$ If you look at the optimization for linear regression, it looks a lot like this. $$ \hat{\beta} = \underset{\beta \in \mathbb{R}^p}{\mbox{argmin}} \left\{ \sum_i (y_i - x_i^T \beta)^2 \right\}$$ An important difference being that the function in linear regression is linear in its parameters, whereas $f$ is not necessarily so. It is sensible to say that linear regression is fit via least squares. However, some things may apply to linear regression which may not apply to all functions fit via least squares. The assumptions of linear regression (normality of residuals, independence, homogeneity of variance, and getting the functional form right) permit inference via confidence intervals and hypothesis tests. If the data used to fit your model via least squares do not satisfy those assumptions, the inferences may not have the properties we wish them to have. If ever there was a time to say it, it is now; linear regression and least squares are same same but different.
Are linear regression and least squares regression necessarily the same thing?
Least squares is the processes of minimizing the sum of squared errors from some model. Given a function $f$ which depends on parameters $\theta$, the least squares estimates of $\theta$ are $$ \hat{
Are linear regression and least squares regression necessarily the same thing? Least squares is the processes of minimizing the sum of squared errors from some model. Given a function $f$ which depends on parameters $\theta$, the least squares estimates of $\theta$ are $$ \hat{\theta} = \underset{\theta \in \mathbb{R}^p}{\mbox{argmin}} \left\{ \sum_i (y_i - f(x_i ; \theta))^2 \right\}$$ If you look at the optimization for linear regression, it looks a lot like this. $$ \hat{\beta} = \underset{\beta \in \mathbb{R}^p}{\mbox{argmin}} \left\{ \sum_i (y_i - x_i^T \beta)^2 \right\}$$ An important difference being that the function in linear regression is linear in its parameters, whereas $f$ is not necessarily so. It is sensible to say that linear regression is fit via least squares. However, some things may apply to linear regression which may not apply to all functions fit via least squares. The assumptions of linear regression (normality of residuals, independence, homogeneity of variance, and getting the functional form right) permit inference via confidence intervals and hypothesis tests. If the data used to fit your model via least squares do not satisfy those assumptions, the inferences may not have the properties we wish them to have. If ever there was a time to say it, it is now; linear regression and least squares are same same but different.
Are linear regression and least squares regression necessarily the same thing? Least squares is the processes of minimizing the sum of squared errors from some model. Given a function $f$ which depends on parameters $\theta$, the least squares estimates of $\theta$ are $$ \hat{
13,185
Are linear regression and least squares regression necessarily the same thing?
Both "Linear Regression" and "Ordinary Least Squares" (OLS) regression are often used to refer to the same kind of statistical model, but for different reasons. We call the model "linear" because it assumes that the relationship between the independent and dependent variables can be described by a straight line. We call it "least squares" because we estimate the parameters of the model by finding the parameters that minimize the squared error terms ("least squares"). Technically we could use other, more complicated methods (like maximum likelihood estimation) to estimate a linear model, and sometimes we need to do this (like when you have a multilevel linear model) because there are other complexities in the model that make OLS estimation not possible. In those cases we have a linear regression model that is not estimated via least squares. On the other hand the least squares method really only works for linear models. So in practice we often treat "OLS" and "linear model" as meaning same thing, even though one refers to the assumptions of the model and the other refers to the way it is estimated.
Are linear regression and least squares regression necessarily the same thing?
Both "Linear Regression" and "Ordinary Least Squares" (OLS) regression are often used to refer to the same kind of statistical model, but for different reasons. We call the model "linear" because it a
Are linear regression and least squares regression necessarily the same thing? Both "Linear Regression" and "Ordinary Least Squares" (OLS) regression are often used to refer to the same kind of statistical model, but for different reasons. We call the model "linear" because it assumes that the relationship between the independent and dependent variables can be described by a straight line. We call it "least squares" because we estimate the parameters of the model by finding the parameters that minimize the squared error terms ("least squares"). Technically we could use other, more complicated methods (like maximum likelihood estimation) to estimate a linear model, and sometimes we need to do this (like when you have a multilevel linear model) because there are other complexities in the model that make OLS estimation not possible. In those cases we have a linear regression model that is not estimated via least squares. On the other hand the least squares method really only works for linear models. So in practice we often treat "OLS" and "linear model" as meaning same thing, even though one refers to the assumptions of the model and the other refers to the way it is estimated.
Are linear regression and least squares regression necessarily the same thing? Both "Linear Regression" and "Ordinary Least Squares" (OLS) regression are often used to refer to the same kind of statistical model, but for different reasons. We call the model "linear" because it a
13,186
Unconfoundedness in Rubin's Causal Model- Layman's explanation
I think you are getting hung up on the difference between potential outcomes $(Y^0,Y^1)$ and the observed outcome $Y$. The latter is very much influenced by treatment, but we hope the former pair is not. Here's the intuition (putting aside conditioning on $X$ for simplicity) about the observed outcome. For each observation, the realized outcome can be expressed as $$Y=T \cdot Y^1 + (1-T) \cdot Y^0.$$ This means that $Y$ and $T$ are dependent because the average value of $T \cdot Y^1$ will not equal the average $(1-T)\cdot Y^0$ (as long as the treatment effect is nonzero and treatment is randomized/ignorable). Here's the intuition for the second part. If we are going to learn about the causal effect of $T$, we will be comparing treated and untreated observations, while taking differences in $X$ into account. We are assuming that the control group is the counterfactual for the treatment group had they not received treatment. But if people choose their own treatment based on their potential outcomes (or expectations about the potential outcomes), this comparison is apples to orangutans. This is like a medical trial where only the healthier patients opt for the painful surgery because it is worth the cost for them. Our comparison will be contaminated if the choice to opt for treatment is not random after conditioning on $X$ (variables that measure current health status which should be observable to the doctor and the patients). One example of an unobservable variable might be having a spouse who loves you very much, so she urges you to get the surgery, but also makes sure you stick to the doctor's instructions post-op, thereby improving $Y^1$ outcome. The measured effect is now some combination of surgery and loving help, which is not what we want to measure. A better example is an $X$ that is affected by the treatment, either ex post or ex ante in anticipation of treatment.
Unconfoundedness in Rubin's Causal Model- Layman's explanation
I think you are getting hung up on the difference between potential outcomes $(Y^0,Y^1)$ and the observed outcome $Y$. The latter is very much influenced by treatment, but we hope the former pair is n
Unconfoundedness in Rubin's Causal Model- Layman's explanation I think you are getting hung up on the difference between potential outcomes $(Y^0,Y^1)$ and the observed outcome $Y$. The latter is very much influenced by treatment, but we hope the former pair is not. Here's the intuition (putting aside conditioning on $X$ for simplicity) about the observed outcome. For each observation, the realized outcome can be expressed as $$Y=T \cdot Y^1 + (1-T) \cdot Y^0.$$ This means that $Y$ and $T$ are dependent because the average value of $T \cdot Y^1$ will not equal the average $(1-T)\cdot Y^0$ (as long as the treatment effect is nonzero and treatment is randomized/ignorable). Here's the intuition for the second part. If we are going to learn about the causal effect of $T$, we will be comparing treated and untreated observations, while taking differences in $X$ into account. We are assuming that the control group is the counterfactual for the treatment group had they not received treatment. But if people choose their own treatment based on their potential outcomes (or expectations about the potential outcomes), this comparison is apples to orangutans. This is like a medical trial where only the healthier patients opt for the painful surgery because it is worth the cost for them. Our comparison will be contaminated if the choice to opt for treatment is not random after conditioning on $X$ (variables that measure current health status which should be observable to the doctor and the patients). One example of an unobservable variable might be having a spouse who loves you very much, so she urges you to get the surgery, but also makes sure you stick to the doctor's instructions post-op, thereby improving $Y^1$ outcome. The measured effect is now some combination of surgery and loving help, which is not what we want to measure. A better example is an $X$ that is affected by the treatment, either ex post or ex ante in anticipation of treatment.
Unconfoundedness in Rubin's Causal Model- Layman's explanation I think you are getting hung up on the difference between potential outcomes $(Y^0,Y^1)$ and the observed outcome $Y$. The latter is very much influenced by treatment, but we hope the former pair is n
13,187
Unconfoundedness in Rubin's Causal Model- Layman's explanation
How would you describe the uncoundedness/ignorability assumption to somebody who has not studied the RCM? Regarding intuition to somebody not versed in causal inference, I think this is where you could use graphs. They are intuitive in the sense that they visually show "flow" and they will also make clear what ignorability substantively means in the real world. Conditional ignorability is equivalent to claiming $X$ satisfies the backdoor-criterion. So, in intuitive terms, you can say to the person that the covariates you chose for $X$ "blocks" the effect of common causes of $T$ and $Y$ (and do not open any other spurious associations). If the only conceivable confounding variables of your problem are the variables on $X$ itself, then this is trivial to explain. You just say that since $X$ contais all the common causes of both $T$ and $Y$, that's all you need to control for. So you could say to her that's how you see the world: The more interesting case is when there might be other plausible confounders out there. To be more specific, you could even ask the person to name a potential confounder of your problem -- that is, ask her to name something that causes both $T$ and $Y$, but it's not in $X$. Say the person names a variable $Z$. Then you can say to that person that what your conditional ignorability assumption effectively means is that you think $X$ will "block" the effect of $Z$ on $T$ and/or $Y$. And you should give her a substantive reason why you think that's true. There are many graphs that could represent that, but say you come up with this explanation: "$Z$ will not bias the results because even though $Z$ causes $T$ and $Y$, its effect on $T$ goes only through $X$, which we are controlling for". And then show this graph: And you could think of other cofounders and show to her how $X$ is blocking them visually on the graphs. Now answering the conceptual questions: Specifically, if T is the treatment, shouldn't the potential outcome be very dependent on it? As well, if we have a randomized controlled trial, then automatically, . Why does this hold true? No. Think of $T$ as the treatment assignment. What it says is that you are assigning the treatment to people "ignoring" how they respond to the treatment (the counterfactual potential outcomes). A simple violation of this would be you tending to give the treatment to those who would potentially benefit the most from it. That's also why this automatically holds when you randomize. If you pick the treated at random, this means you did not check their potential responses to the treatment to select them. To complement the answer, it's worth noticing that understanding ignorability without talking about the causal process, that is, without invoking structural equations/graphical models is really hard. Most of the time you see researchers appealing to the idea of "the treatment was as-if random" but without justifying why that is or why that's plausible using real world mechanisms and processes. In fact, many researchers simply assume ignorability for convenience, in order to justify the use of statistical methods. This passage from Joffe, Yang and Feldman paper speaks an inconvenient truth most people know but do not say during conference presentations: "Ignorability assumptions are usually made because they justify the use of available statistical methods, and not because the are truly believed." But, as I have said in the beginning of the the answer, you can use graphs to argue about whether a treatment assignment is ignorable or not. While the concept of ignorability itself is hard to grasp, because it states judgements about counterfactual quantities, in the graphs you are basically making qualitative statements about causal processes (this variable causes that variable etc), which are easy to explain and visually appealing. As mentioned in a previous answer, there's a formal equivalency between graphs and potential outcomes. Hence, you can read potential outcomes from graphs too. Making this connection more formal (for more see Pearl's Causality, p.343), you could resort to the following definition: the potential outcomes would stand for the total of all variables (observed and error terms) that affect Y when T is held constant. Then it's easy to see why ignorability holds in RCT, but more importantly, it also allows you to easily spot situations where ignorability would not hold. For example, in the graph $T \rightarrow X \rightarrow Y$, T is ignorable , but T is not conditionally ignorable given X, because once you condition on X, you open a colliding path from the error term of X to T. To sum up, many researchers make the ignorability assumption by default, for convenience. It's a convenient way to assume the sufficiency of a set of controls without needing to formally justify why that's the case, but to explain what it means in a real context for a layman, you would need to invoke a causal story, that is causal assumptions, and you can formally tell that story with the help of causal graphs.
Unconfoundedness in Rubin's Causal Model- Layman's explanation
How would you describe the uncoundedness/ignorability assumption to somebody who has not studied the RCM? Regarding intuition to somebody not versed in causal inference, I think this is where you c
Unconfoundedness in Rubin's Causal Model- Layman's explanation How would you describe the uncoundedness/ignorability assumption to somebody who has not studied the RCM? Regarding intuition to somebody not versed in causal inference, I think this is where you could use graphs. They are intuitive in the sense that they visually show "flow" and they will also make clear what ignorability substantively means in the real world. Conditional ignorability is equivalent to claiming $X$ satisfies the backdoor-criterion. So, in intuitive terms, you can say to the person that the covariates you chose for $X$ "blocks" the effect of common causes of $T$ and $Y$ (and do not open any other spurious associations). If the only conceivable confounding variables of your problem are the variables on $X$ itself, then this is trivial to explain. You just say that since $X$ contais all the common causes of both $T$ and $Y$, that's all you need to control for. So you could say to her that's how you see the world: The more interesting case is when there might be other plausible confounders out there. To be more specific, you could even ask the person to name a potential confounder of your problem -- that is, ask her to name something that causes both $T$ and $Y$, but it's not in $X$. Say the person names a variable $Z$. Then you can say to that person that what your conditional ignorability assumption effectively means is that you think $X$ will "block" the effect of $Z$ on $T$ and/or $Y$. And you should give her a substantive reason why you think that's true. There are many graphs that could represent that, but say you come up with this explanation: "$Z$ will not bias the results because even though $Z$ causes $T$ and $Y$, its effect on $T$ goes only through $X$, which we are controlling for". And then show this graph: And you could think of other cofounders and show to her how $X$ is blocking them visually on the graphs. Now answering the conceptual questions: Specifically, if T is the treatment, shouldn't the potential outcome be very dependent on it? As well, if we have a randomized controlled trial, then automatically, . Why does this hold true? No. Think of $T$ as the treatment assignment. What it says is that you are assigning the treatment to people "ignoring" how they respond to the treatment (the counterfactual potential outcomes). A simple violation of this would be you tending to give the treatment to those who would potentially benefit the most from it. That's also why this automatically holds when you randomize. If you pick the treated at random, this means you did not check their potential responses to the treatment to select them. To complement the answer, it's worth noticing that understanding ignorability without talking about the causal process, that is, without invoking structural equations/graphical models is really hard. Most of the time you see researchers appealing to the idea of "the treatment was as-if random" but without justifying why that is or why that's plausible using real world mechanisms and processes. In fact, many researchers simply assume ignorability for convenience, in order to justify the use of statistical methods. This passage from Joffe, Yang and Feldman paper speaks an inconvenient truth most people know but do not say during conference presentations: "Ignorability assumptions are usually made because they justify the use of available statistical methods, and not because the are truly believed." But, as I have said in the beginning of the the answer, you can use graphs to argue about whether a treatment assignment is ignorable or not. While the concept of ignorability itself is hard to grasp, because it states judgements about counterfactual quantities, in the graphs you are basically making qualitative statements about causal processes (this variable causes that variable etc), which are easy to explain and visually appealing. As mentioned in a previous answer, there's a formal equivalency between graphs and potential outcomes. Hence, you can read potential outcomes from graphs too. Making this connection more formal (for more see Pearl's Causality, p.343), you could resort to the following definition: the potential outcomes would stand for the total of all variables (observed and error terms) that affect Y when T is held constant. Then it's easy to see why ignorability holds in RCT, but more importantly, it also allows you to easily spot situations where ignorability would not hold. For example, in the graph $T \rightarrow X \rightarrow Y$, T is ignorable , but T is not conditionally ignorable given X, because once you condition on X, you open a colliding path from the error term of X to T. To sum up, many researchers make the ignorability assumption by default, for convenience. It's a convenient way to assume the sufficiency of a set of controls without needing to formally justify why that's the case, but to explain what it means in a real context for a layman, you would need to invoke a causal story, that is causal assumptions, and you can formally tell that story with the help of causal graphs.
Unconfoundedness in Rubin's Causal Model- Layman's explanation How would you describe the uncoundedness/ignorability assumption to somebody who has not studied the RCM? Regarding intuition to somebody not versed in causal inference, I think this is where you c
13,188
Unconfoundedness in Rubin's Causal Model- Layman's explanation
I will add to above answers by providing an intuitive and easy memorable interpretation of the unconfoundedness/ignorability assumption. It helps to memorize the unconfoundedness assumption by swapping the order of the definition and writing $$T \perp (Y(0),Y(1))|X$$ instead. In this way, we can read the defintion as "the treatment assignment is independent of the potential outcomes (conditioned on pre-treatment variables)". This is easier to understand as it reflects the essence of RCTs, randomized controlled trials, where assigned treatment is not determined by the how well an individual might respond to the treatment.
Unconfoundedness in Rubin's Causal Model- Layman's explanation
I will add to above answers by providing an intuitive and easy memorable interpretation of the unconfoundedness/ignorability assumption. It helps to memorize the unconfoundedness assumption by swappin
Unconfoundedness in Rubin's Causal Model- Layman's explanation I will add to above answers by providing an intuitive and easy memorable interpretation of the unconfoundedness/ignorability assumption. It helps to memorize the unconfoundedness assumption by swapping the order of the definition and writing $$T \perp (Y(0),Y(1))|X$$ instead. In this way, we can read the defintion as "the treatment assignment is independent of the potential outcomes (conditioned on pre-treatment variables)". This is easier to understand as it reflects the essence of RCTs, randomized controlled trials, where assigned treatment is not determined by the how well an individual might respond to the treatment.
Unconfoundedness in Rubin's Causal Model- Layman's explanation I will add to above answers by providing an intuitive and easy memorable interpretation of the unconfoundedness/ignorability assumption. It helps to memorize the unconfoundedness assumption by swappin
13,189
Nice example where a series without a unit root is non stationary?
Here is an example of a non-stationary series that not even a white noise test can detect (let alone a Dickey-Fuller type test): Yes, this might be surprising but This is not white noise. Most non-stationary counter example are based on a violation of the first two conditions of stationary: deterministic trends (non-constant mean) or unit root / heteroskedastic time series (non-constant variance). However, you can also have non-stationary processes that have constant mean and variance, but they violate the third condition: the autocovariance function (ACVF) $cov(x_s, x_t)$ should be constant over time and a function of $|s-t|$ only. The time series above is an example of such a series, which has zero mean, unit variance, but the ACVF depends on time. More precisely, the process above is a locally stationary MA(1) process with parameters such that it becomes spurious white noise (see References below): the parameter of the MA process $x_t = \varepsilon_t + \theta_1 \varepsilon_{t-1}$ changes over time $$\theta_1(u) = 0.5 - 1 \cdot u,$$ where $u = t/ T$ is normalized time. The reason why this looks like white noise (even though by mathematical definition it clearly isn't), is that the time varying ACVF integrates out to zero over time. Since the sample ACVF converges to the average ACVF, this means that the sample autocovariance (and autocorrelation (ACF)) will converge to a function that looks like white noise. So even a Ljung-Box test won't be able to detect this non-stationarity. The paper (disclaimer: I am the author) on Testing for white noise against locally stationary alternatives proposes an extension of Box tests to deal with such locally stationary processes. For more R code and more details see also this blog post. Update after mpiktas comment: It is true that this might look just like a theoretically interesting case that is not seen in practice. I agree it is unlikely to see such spurious white noise in a real world dataset directly, but you will see this in almost any residuals of a stationary model fit. Without going into too much theoretical detail, just imagine a general time-varying model $\theta(u)$ with a time varying covariance function $\gamma_{\theta}(k, u)$. If you fit a constant model $\widehat{\theta}$, then this estimate will be close to the time average of the true model $\theta(u)$; and naturally the residuals will now be close to $\theta(u) - \widehat{\theta}$, which by construction of $\widehat{\theta}$ will integrate out to zero (approximately). See Goerg (2012) for details. Let's look at an example library(fracdiff) library(data.table) tree.ring <- ts(fread(file.path(data.path, "tree-rings.txt"))[, V1]) layout(matrix(1:4, ncol = 2)) plot(tree.ring) acf(tree.ring) mod.arfima <- fracdiff(tree.ring) mod.arfima$d ## [1] 0.236507 So we fit fractional noise with parameter $\widehat{d} = 0.23$ (since $\widehat{d} < 0.5$ we think everything is fine and we have a stationary model). Let's check residuals: arfima.res <- diffseries(tree.ring, mod.arfima$d) plot(arfima.res) acf(arfima.res) Looks good right? Well, the issue is that the residuals are spurious white noise. How do I know? First, I can test it Box.test(arfima.res, type = "Ljung-Box") ## ## Box-Ljung test ## ## data: arfima.res ## X-squared = 1.8757, df = 1, p-value = 0.1708 Box.test.ls(arfima.res, K = 4, type = "Ljung-Box") ## ## LS Ljung-Box test; Number of windows = 4; non-overlapping window ## size = 497 ## ## data: arfima.res ## X-squared = 39.361, df = 4, p-value = 5.867e-08 and second, we know from literature that the tree ring data is in fact locally stationary fractional noise: see Goerg (2012) and Ferreira, Olea, and Palma (2013). This shows that my -- admittedly -- theoretically looking example, is actually occurring in most real world examples.
Nice example where a series without a unit root is non stationary?
Here is an example of a non-stationary series that not even a white noise test can detect (let alone a Dickey-Fuller type test): Yes, this might be surprising but This is not white noise. Most non-
Nice example where a series without a unit root is non stationary? Here is an example of a non-stationary series that not even a white noise test can detect (let alone a Dickey-Fuller type test): Yes, this might be surprising but This is not white noise. Most non-stationary counter example are based on a violation of the first two conditions of stationary: deterministic trends (non-constant mean) or unit root / heteroskedastic time series (non-constant variance). However, you can also have non-stationary processes that have constant mean and variance, but they violate the third condition: the autocovariance function (ACVF) $cov(x_s, x_t)$ should be constant over time and a function of $|s-t|$ only. The time series above is an example of such a series, which has zero mean, unit variance, but the ACVF depends on time. More precisely, the process above is a locally stationary MA(1) process with parameters such that it becomes spurious white noise (see References below): the parameter of the MA process $x_t = \varepsilon_t + \theta_1 \varepsilon_{t-1}$ changes over time $$\theta_1(u) = 0.5 - 1 \cdot u,$$ where $u = t/ T$ is normalized time. The reason why this looks like white noise (even though by mathematical definition it clearly isn't), is that the time varying ACVF integrates out to zero over time. Since the sample ACVF converges to the average ACVF, this means that the sample autocovariance (and autocorrelation (ACF)) will converge to a function that looks like white noise. So even a Ljung-Box test won't be able to detect this non-stationarity. The paper (disclaimer: I am the author) on Testing for white noise against locally stationary alternatives proposes an extension of Box tests to deal with such locally stationary processes. For more R code and more details see also this blog post. Update after mpiktas comment: It is true that this might look just like a theoretically interesting case that is not seen in practice. I agree it is unlikely to see such spurious white noise in a real world dataset directly, but you will see this in almost any residuals of a stationary model fit. Without going into too much theoretical detail, just imagine a general time-varying model $\theta(u)$ with a time varying covariance function $\gamma_{\theta}(k, u)$. If you fit a constant model $\widehat{\theta}$, then this estimate will be close to the time average of the true model $\theta(u)$; and naturally the residuals will now be close to $\theta(u) - \widehat{\theta}$, which by construction of $\widehat{\theta}$ will integrate out to zero (approximately). See Goerg (2012) for details. Let's look at an example library(fracdiff) library(data.table) tree.ring <- ts(fread(file.path(data.path, "tree-rings.txt"))[, V1]) layout(matrix(1:4, ncol = 2)) plot(tree.ring) acf(tree.ring) mod.arfima <- fracdiff(tree.ring) mod.arfima$d ## [1] 0.236507 So we fit fractional noise with parameter $\widehat{d} = 0.23$ (since $\widehat{d} < 0.5$ we think everything is fine and we have a stationary model). Let's check residuals: arfima.res <- diffseries(tree.ring, mod.arfima$d) plot(arfima.res) acf(arfima.res) Looks good right? Well, the issue is that the residuals are spurious white noise. How do I know? First, I can test it Box.test(arfima.res, type = "Ljung-Box") ## ## Box-Ljung test ## ## data: arfima.res ## X-squared = 1.8757, df = 1, p-value = 0.1708 Box.test.ls(arfima.res, K = 4, type = "Ljung-Box") ## ## LS Ljung-Box test; Number of windows = 4; non-overlapping window ## size = 497 ## ## data: arfima.res ## X-squared = 39.361, df = 4, p-value = 5.867e-08 and second, we know from literature that the tree ring data is in fact locally stationary fractional noise: see Goerg (2012) and Ferreira, Olea, and Palma (2013). This shows that my -- admittedly -- theoretically looking example, is actually occurring in most real world examples.
Nice example where a series without a unit root is non stationary? Here is an example of a non-stationary series that not even a white noise test can detect (let alone a Dickey-Fuller type test): Yes, this might be surprising but This is not white noise. Most non-
13,190
Nice example where a series without a unit root is non stationary?
Unit root testing is notoriously difficult. Using one test is usually not enough and you must be very careful about the exact assumptions the test is using. The way ADF is constructed makes it vulnerable to a series which are simple non-linear trends with added white noise. Here is an example: library(dplyr) library(tseries) set.seed(1000) oo <- 1:1000 %>% lapply(function(n)adf.test(exp(seq(0, 2, by = 0.01)) + rnorm(201))) pp <- oo %>% sapply("[[","p.value") > sum(pp < 0.05) [1] 680 Here we have the exponential trend and we see that ADF performs quite poorly. It accepts the null of unit root 30% of the time and rejects it 70% of the time. Usually the result of any analysis is not to claim that the series is stationary or not. If the methods used in analysis require stationarity, the wrong assumption that the series is stationary when it is actually not, usually manifests in some way or other. So I personally look at the whole analysis, not only the unit root testing part. For example the OLS and NLS works fine for non-stationary data, where non-stationarity is in the mean, i.e. trend. So if somebody wrongly claims that the series is stationary and applies OLS/NLS, this claim might not be relevant.
Nice example where a series without a unit root is non stationary?
Unit root testing is notoriously difficult. Using one test is usually not enough and you must be very careful about the exact assumptions the test is using. The way ADF is constructed makes it vulner
Nice example where a series without a unit root is non stationary? Unit root testing is notoriously difficult. Using one test is usually not enough and you must be very careful about the exact assumptions the test is using. The way ADF is constructed makes it vulnerable to a series which are simple non-linear trends with added white noise. Here is an example: library(dplyr) library(tseries) set.seed(1000) oo <- 1:1000 %>% lapply(function(n)adf.test(exp(seq(0, 2, by = 0.01)) + rnorm(201))) pp <- oo %>% sapply("[[","p.value") > sum(pp < 0.05) [1] 680 Here we have the exponential trend and we see that ADF performs quite poorly. It accepts the null of unit root 30% of the time and rejects it 70% of the time. Usually the result of any analysis is not to claim that the series is stationary or not. If the methods used in analysis require stationarity, the wrong assumption that the series is stationary when it is actually not, usually manifests in some way or other. So I personally look at the whole analysis, not only the unit root testing part. For example the OLS and NLS works fine for non-stationary data, where non-stationarity is in the mean, i.e. trend. So if somebody wrongly claims that the series is stationary and applies OLS/NLS, this claim might not be relevant.
Nice example where a series without a unit root is non stationary? Unit root testing is notoriously difficult. Using one test is usually not enough and you must be very careful about the exact assumptions the test is using. The way ADF is constructed makes it vulner
13,191
Nice example where a series without a unit root is non stationary?
Example 1 Unit-root processes with a strong negative MA component are known to lead to ADF tests with empirical size far higher than the nominal one (e.g., Schwert, JBES 1989). That is, if $$ Y_t=Y_{t-1}+\epsilon_t+\theta\epsilon_{t-1}, $$ with $\theta\approx-1$, the roots of the AR and MA part will almost cancel, so that the process will resemble white noise in finite samples, leading to many false rejections of the null, as the process still has a unit root (is nonstationary). Below is an example for the ADF test that you mentioned. [Schwert simulates that much more extreme empirical sizes could be generated with less extreme MA structures if you looked at the coefficient statistic $T(\hat\rho-1)$ or the Phillips-Perron test instead, see his tables 5-10.] library(urca) reps <- 1000 n <- 100 rejections <- matrix(NA,nrow=reps) for (i in 1:reps){ y <- cumsum(arima.sim(n = n, list(ma = -0.98))) rejections[i] <- (summary(ur.df(y, type = "drift", selectlags="Fixed",lags=12*(n/100)^.25))@teststat[1] < -2.89) } mean(rejections) Example 2 Processes that are mean-reverting but not stationary. For example, $Y_t$ might be an AR(1) process with AR coefficient less than one in absolute value, but with an innovation process whose variance changes permanently at some point in time ("unconditional heteroskedasticity"). The process then does not have a unit root, but is also not stationary, as its unconditional distribution changes over time. Depending on the type of variance change, the ADF test will still reject frequently. In my example below, we have a downward variance break, which makes the test "believe" that the series converges, leading to a rejection of the null of a unit root. library(urca) reps <- 1000 n <- 100 rejections <- matrix(NA,nrow=reps) for (i in 1:reps){ u_1 <- rnorm(n/2,sd=5) u_2 <- rnorm(n/2,sd=1) u <- c(u_1,u_2) y <- arima.sim(n=n,list(ar = 0.8),innov=u) rejections[i] <- (summary(ur.df(y, type = "drift"))@teststat[1] < -2.89) } mean(rejections) (As an aside, the ADF test "loses" its pivotal asymptotic null distribution in the presence of unconditional heteroskedasticity.)
Nice example where a series without a unit root is non stationary?
Example 1 Unit-root processes with a strong negative MA component are known to lead to ADF tests with empirical size far higher than the nominal one (e.g., Schwert, JBES 1989). That is, if $$ Y_t=Y_{
Nice example where a series without a unit root is non stationary? Example 1 Unit-root processes with a strong negative MA component are known to lead to ADF tests with empirical size far higher than the nominal one (e.g., Schwert, JBES 1989). That is, if $$ Y_t=Y_{t-1}+\epsilon_t+\theta\epsilon_{t-1}, $$ with $\theta\approx-1$, the roots of the AR and MA part will almost cancel, so that the process will resemble white noise in finite samples, leading to many false rejections of the null, as the process still has a unit root (is nonstationary). Below is an example for the ADF test that you mentioned. [Schwert simulates that much more extreme empirical sizes could be generated with less extreme MA structures if you looked at the coefficient statistic $T(\hat\rho-1)$ or the Phillips-Perron test instead, see his tables 5-10.] library(urca) reps <- 1000 n <- 100 rejections <- matrix(NA,nrow=reps) for (i in 1:reps){ y <- cumsum(arima.sim(n = n, list(ma = -0.98))) rejections[i] <- (summary(ur.df(y, type = "drift", selectlags="Fixed",lags=12*(n/100)^.25))@teststat[1] < -2.89) } mean(rejections) Example 2 Processes that are mean-reverting but not stationary. For example, $Y_t$ might be an AR(1) process with AR coefficient less than one in absolute value, but with an innovation process whose variance changes permanently at some point in time ("unconditional heteroskedasticity"). The process then does not have a unit root, but is also not stationary, as its unconditional distribution changes over time. Depending on the type of variance change, the ADF test will still reject frequently. In my example below, we have a downward variance break, which makes the test "believe" that the series converges, leading to a rejection of the null of a unit root. library(urca) reps <- 1000 n <- 100 rejections <- matrix(NA,nrow=reps) for (i in 1:reps){ u_1 <- rnorm(n/2,sd=5) u_2 <- rnorm(n/2,sd=1) u <- c(u_1,u_2) y <- arima.sim(n=n,list(ar = 0.8),innov=u) rejections[i] <- (summary(ur.df(y, type = "drift"))@teststat[1] < -2.89) } mean(rejections) (As an aside, the ADF test "loses" its pivotal asymptotic null distribution in the presence of unconditional heteroskedasticity.)
Nice example where a series without a unit root is non stationary? Example 1 Unit-root processes with a strong negative MA component are known to lead to ADF tests with empirical size far higher than the nominal one (e.g., Schwert, JBES 1989). That is, if $$ Y_t=Y_{
13,192
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is it a LAPACK bug?
This is not a bug. As we have explored (extensively) in the comments, there are two things happening. The first is that the columns of $U$ are constrained to meet the SVD requirements: each must have unit length and be orthogonal to all the others. Viewing $U$ as a random variable created from a random matrix $X$ via a particular SVD algorithm, we thereby note that these $k(k+1)/2$ functionally independent constraints create statistical dependencies among the columns of $U$. These dependencies might be revealed to a greater or lesser extent by studying the correlations among the components of $U$, but a second phenomenon emerges: the SVD solution is not unique. At a minimum, each column of $U$ can be independently negated, giving at least $2^k$ distinct solutions with $k$ columns. Strong correlations (exceeding $1/2$) can be induced by changing the signs of the columns appropriately. (One way to do this is given in my first comment to Amoeba's answer in this thread: I force all the $u_{ii},i=1,\ldots, k$ to have the same sign, making them all negative or all positive with equal probability.) On the other hand, all correlations can be made to vanish by choosing the signs randomly, independently, with equal probabilities. (I give an example below in the "Edit" section.) With care, we can partially discern both these phenomena when reading scatterplot matrices of the components of $U$. Certain characteristics--such as the appearance of points nearly uniformly distributed within well-defined circular regions--belie a lack of independence. Others, such as scatterplots showing clear nonzero correlations, obviously depend on choices made in the algorithm--but such choices are possible only because of the lack of independence in the first place. The ultimate test of a decomposition algorithm like SVD (or Cholesky, LR, LU, etc.) is whether it does what it claims. In this circumstance it suffices to check that when SVD returns the triple of matrices $(U, D, V)$, that $X$ is recovered, up to anticipated floating point error, by the product $UDV^\prime$; that the columns of $U$ and of $V$ are orthonormal; and that $D$ is diagonal, its diagonal elements are non-negative, and are arranged in descending order. I have applied such tests to the svd algorithm in R and have never found it to be in error. Although that is no assurance it is perfectly correct, such experience--which I believe is shared by a great many people--suggests that any bug would require some extraordinary kind of input in order to be manifest. What follows is a more detailed analysis of specific points raised in the question. Using R's svd procedure, first you can check that as $k$ increases, the correlations among the coefficients of $U$ grow weaker, but they are still nonzero. If you simply were to perform a larger simulation, you would find they are significant. (When $k=3$, 50000 iterations ought to suffice.) Contrary to the assertion in the question, the correlations do not "disappear entirely." Second, a better way to study this phenomenon is to go back to the basic question of independence of the coefficients. Although the correlations tend to be near zero in most cases, the lack of independence is clearly evident. This is made most apparent by studying the full multivariate distribution of the coefficients of $U$. The nature of the distribution emerges even in small simulations in which the nonzero correlations cannot (yet) be detected. For instance, examine a scatterplot matrix of the coefficients. To make this practicable, I set the size of each simulated dataset to $4$ and kept $k=2$, thereby drawing $1000$ realizations of the $4\times 2$ matrix $U$, creating a $1000\times 8$ matrix. Here is its full scatterplot matrix, with the variables listed by their positions within $U$: Scanning down the first column reveals an interesting lack of independence between $u_{11}$ and the other $u_{ij}$: look at how the upper quadrant of the scatterplot with $u_{21}$ is nearly vacant, for instance; or examine the elliptical upward-sloping cloud describing the $(u_{11}, u_{22})$ relationship and the downward-sloping cloud for the $(u_{21}, u_{12})$ pair. A close look reveals a clear lack of independence among almost all of these coefficients: very few of them look remotely independent, even though most of them exhibit near-zero correlation. (NB: Most of the circular clouds are projections from a hypersphere created by the normalization condition forcing the sum of squares of all components of each column to be unity.) Scatterplot matrices with $k=3$ and $k=4$ exhibit similar patterns: these phenomena are not confined to $k=2$, nor do they depend on the size of each simulated dataset: they just get more difficult to generate and examine. The explanations for these patterns go to the algorithm used to obtain $U$ in the singular value decomposition, but we know such patterns of non-independence must exist by the very defining properties of $U$: since each successive column is (geometrically) orthogonal to the preceding ones, these orthogonality conditions impose functional dependencies among the coefficients, which thereby translate to statistical dependencies among the corresponding random variables. Edit In response to comments, it may be worth remarking on the extent to which these dependence phenomena reflect the underlying algorithm (to compute an SVD) and how much they are inherent in the nature of the process. The specific patterns of correlations among coefficients depend a great deal on arbitrary choices made by the SVD algorithm, because the solution is not unique: the columns of $U$ may always independently be multiplied by $-1$ or $1$. There is no intrinsic way to choose the sign. Thus, when two SVD algorithms make different (arbitrary or perhaps even random) choices of sign, they can result in different patterns of scatterplots of the $(u_{ij}, u_{i^\prime j^\prime})$ values. If you would like to see this, replace the stat function in the code below by stat <- function(x) { i <- sample.int(dim(x)[1]) # Make a random permutation of the rows of x u <- svd(x[i, ])$u # Perform SVD as.vector(u[order(i), ]) # Unpermute the rows of u } This first randomly re-orders the observations x, performs SVD, then applies the inverse ordering to u to match the original observation sequence. Because the effect is to form mixtures of reflected and rotated versions of the original scatterplots, the scatterplots in the matrix will look much more uniform. All sample correlations will be extremely close to zero (by construction: the underlying correlations are exactly zero). Nevertheless, the lack of independence will still be obvious (in the uniform circular shapes that appear, particularly between $u_{i,j}$ and $u_{i,j^\prime}$). The lack of data in some quadrants of some of the original scatterplots (shown in the figure above) arises from how the R SVD algorithm selects signs for the columns. Nothing changes about the conclusions. Because the second column of $U$ is orthogonal to the first, it (considered as a multivariate random variable) is dependent on the first (also considered as a multivariate random variable). You cannot have all the components of one column be independent of all the components of the other; all you can do is to look at the data in ways that obscure the dependencies--but the dependence will persist. Here is updated R code to handle the cases $k\gt 2$ and draw a portion of the scatterplot matrix. k <- 2 # Number of variables p <- 4 # Number of observations n <- 1e3 # Number of iterations stat <- function(x) as.vector(svd(x)$u) Sigma <- diag(1, k, k); Mu <- rep(0, k) set.seed(17) sim <- t(replicate(n, stat(MASS::mvrnorm(p, Mu, Sigma)))) colnames(sim) <- as.vector(outer(1:p, 1:k, function(i,j) paste0(i,",",j))) pairs(sim[, 1:min(11, p*k)], pch=".")
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is
This is not a bug. As we have explored (extensively) in the comments, there are two things happening. The first is that the columns of $U$ are constrained to meet the SVD requirements: each must have
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is it a LAPACK bug? This is not a bug. As we have explored (extensively) in the comments, there are two things happening. The first is that the columns of $U$ are constrained to meet the SVD requirements: each must have unit length and be orthogonal to all the others. Viewing $U$ as a random variable created from a random matrix $X$ via a particular SVD algorithm, we thereby note that these $k(k+1)/2$ functionally independent constraints create statistical dependencies among the columns of $U$. These dependencies might be revealed to a greater or lesser extent by studying the correlations among the components of $U$, but a second phenomenon emerges: the SVD solution is not unique. At a minimum, each column of $U$ can be independently negated, giving at least $2^k$ distinct solutions with $k$ columns. Strong correlations (exceeding $1/2$) can be induced by changing the signs of the columns appropriately. (One way to do this is given in my first comment to Amoeba's answer in this thread: I force all the $u_{ii},i=1,\ldots, k$ to have the same sign, making them all negative or all positive with equal probability.) On the other hand, all correlations can be made to vanish by choosing the signs randomly, independently, with equal probabilities. (I give an example below in the "Edit" section.) With care, we can partially discern both these phenomena when reading scatterplot matrices of the components of $U$. Certain characteristics--such as the appearance of points nearly uniformly distributed within well-defined circular regions--belie a lack of independence. Others, such as scatterplots showing clear nonzero correlations, obviously depend on choices made in the algorithm--but such choices are possible only because of the lack of independence in the first place. The ultimate test of a decomposition algorithm like SVD (or Cholesky, LR, LU, etc.) is whether it does what it claims. In this circumstance it suffices to check that when SVD returns the triple of matrices $(U, D, V)$, that $X$ is recovered, up to anticipated floating point error, by the product $UDV^\prime$; that the columns of $U$ and of $V$ are orthonormal; and that $D$ is diagonal, its diagonal elements are non-negative, and are arranged in descending order. I have applied such tests to the svd algorithm in R and have never found it to be in error. Although that is no assurance it is perfectly correct, such experience--which I believe is shared by a great many people--suggests that any bug would require some extraordinary kind of input in order to be manifest. What follows is a more detailed analysis of specific points raised in the question. Using R's svd procedure, first you can check that as $k$ increases, the correlations among the coefficients of $U$ grow weaker, but they are still nonzero. If you simply were to perform a larger simulation, you would find they are significant. (When $k=3$, 50000 iterations ought to suffice.) Contrary to the assertion in the question, the correlations do not "disappear entirely." Second, a better way to study this phenomenon is to go back to the basic question of independence of the coefficients. Although the correlations tend to be near zero in most cases, the lack of independence is clearly evident. This is made most apparent by studying the full multivariate distribution of the coefficients of $U$. The nature of the distribution emerges even in small simulations in which the nonzero correlations cannot (yet) be detected. For instance, examine a scatterplot matrix of the coefficients. To make this practicable, I set the size of each simulated dataset to $4$ and kept $k=2$, thereby drawing $1000$ realizations of the $4\times 2$ matrix $U$, creating a $1000\times 8$ matrix. Here is its full scatterplot matrix, with the variables listed by their positions within $U$: Scanning down the first column reveals an interesting lack of independence between $u_{11}$ and the other $u_{ij}$: look at how the upper quadrant of the scatterplot with $u_{21}$ is nearly vacant, for instance; or examine the elliptical upward-sloping cloud describing the $(u_{11}, u_{22})$ relationship and the downward-sloping cloud for the $(u_{21}, u_{12})$ pair. A close look reveals a clear lack of independence among almost all of these coefficients: very few of them look remotely independent, even though most of them exhibit near-zero correlation. (NB: Most of the circular clouds are projections from a hypersphere created by the normalization condition forcing the sum of squares of all components of each column to be unity.) Scatterplot matrices with $k=3$ and $k=4$ exhibit similar patterns: these phenomena are not confined to $k=2$, nor do they depend on the size of each simulated dataset: they just get more difficult to generate and examine. The explanations for these patterns go to the algorithm used to obtain $U$ in the singular value decomposition, but we know such patterns of non-independence must exist by the very defining properties of $U$: since each successive column is (geometrically) orthogonal to the preceding ones, these orthogonality conditions impose functional dependencies among the coefficients, which thereby translate to statistical dependencies among the corresponding random variables. Edit In response to comments, it may be worth remarking on the extent to which these dependence phenomena reflect the underlying algorithm (to compute an SVD) and how much they are inherent in the nature of the process. The specific patterns of correlations among coefficients depend a great deal on arbitrary choices made by the SVD algorithm, because the solution is not unique: the columns of $U$ may always independently be multiplied by $-1$ or $1$. There is no intrinsic way to choose the sign. Thus, when two SVD algorithms make different (arbitrary or perhaps even random) choices of sign, they can result in different patterns of scatterplots of the $(u_{ij}, u_{i^\prime j^\prime})$ values. If you would like to see this, replace the stat function in the code below by stat <- function(x) { i <- sample.int(dim(x)[1]) # Make a random permutation of the rows of x u <- svd(x[i, ])$u # Perform SVD as.vector(u[order(i), ]) # Unpermute the rows of u } This first randomly re-orders the observations x, performs SVD, then applies the inverse ordering to u to match the original observation sequence. Because the effect is to form mixtures of reflected and rotated versions of the original scatterplots, the scatterplots in the matrix will look much more uniform. All sample correlations will be extremely close to zero (by construction: the underlying correlations are exactly zero). Nevertheless, the lack of independence will still be obvious (in the uniform circular shapes that appear, particularly between $u_{i,j}$ and $u_{i,j^\prime}$). The lack of data in some quadrants of some of the original scatterplots (shown in the figure above) arises from how the R SVD algorithm selects signs for the columns. Nothing changes about the conclusions. Because the second column of $U$ is orthogonal to the first, it (considered as a multivariate random variable) is dependent on the first (also considered as a multivariate random variable). You cannot have all the components of one column be independent of all the components of the other; all you can do is to look at the data in ways that obscure the dependencies--but the dependence will persist. Here is updated R code to handle the cases $k\gt 2$ and draw a portion of the scatterplot matrix. k <- 2 # Number of variables p <- 4 # Number of observations n <- 1e3 # Number of iterations stat <- function(x) as.vector(svd(x)$u) Sigma <- diag(1, k, k); Mu <- rep(0, k) set.seed(17) sim <- t(replicate(n, stat(MASS::mvrnorm(p, Mu, Sigma)))) colnames(sim) <- as.vector(outer(1:p, 1:k, function(i,j) paste0(i,",",j))) pairs(sim[, 1:min(11, p*k)], pch=".")
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is This is not a bug. As we have explored (extensively) in the comments, there are two things happening. The first is that the columns of $U$ are constrained to meet the SVD requirements: each must have
13,193
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is it a LAPACK bug?
This answer presents a replication of @whuber's results in Matlab, and also a direct demonstration that the correlations are an "artifact" of how the SVD implementation chooses sign for components. Given the long chain of potentially confusing comments, I want to stress for the future readers that I fully agree with the following: In the context of this discussion, $\mathbf U$ certainly is a random variable. Columns of $\mathbf U$ have to be of length $1$. This means that the elements inside each column are not independent; their squares sum to one. However, this does not imply any correlation between $U_{i1}$ and $U_{j1}$ for $i\ne j$, and the sample correlation should be tiny for large number $N_\mathrm{rep}$ of random draws. Columns of $\mathbf U$ have to be orthogonal. This means that the elements from different columns are not independent; their dot product is zero. Again, this does not imply any correlation between $U_{i1}$ and $U_{j2}$, and the sample correlation should be tiny. My question was: why do we see high correlations of $\sim 0.2$ even the for large number of random draws $N_\mathrm{rep}=1000$? Here is a replication of @whuber's example with $n=4$, $k=2$, and $N_\mathrm{rep}=1000$ in Matlab: On the left is the correlation matrix, on the right -- scatter plots similar to @whuber's. The agreement between our simulations seems perfect. Now, following an ingenious suggestion by @ttnphns, I assign random signs to the columns of $U$, i.e. after this line: [U,S,V] = svd(X,0); I add the following two lines: U(:,1) = U(:,1) * sign(randn(1)); U(:,2) = U(:,2) * sign(randn(1)); Here is the outcome: All the correlations vanish, exactly as I expected from the beginning! As @whuber says, the lack of independence can be seen in the perfect circular shape of some scatter plots (because the length of each column must equal $1$, sum of squares of any two elements cannot exceed $1$). But the correlations do vanish. Summarizing the whole issue, we see that strong correlations appear because LAPACK chooses signs for columns of $\mathbf U$ in a specific way that seems to depend on the first two data points. It is certainly not a bug because the decomposition is correct. But LAPACK essentially creates these "artifact" correlations by exploiting the freedom to assign signs. These correlations do not reflect the dependence of the elements of $\mathbf U$; instead, they reflect the freedom in the SVD solution and a particular LAPACK's convention to fix it. PS. Congratulations to @whuber for passing 100k reputation today!
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is
This answer presents a replication of @whuber's results in Matlab, and also a direct demonstration that the correlations are an "artifact" of how the SVD implementation chooses sign for components. Gi
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is it a LAPACK bug? This answer presents a replication of @whuber's results in Matlab, and also a direct demonstration that the correlations are an "artifact" of how the SVD implementation chooses sign for components. Given the long chain of potentially confusing comments, I want to stress for the future readers that I fully agree with the following: In the context of this discussion, $\mathbf U$ certainly is a random variable. Columns of $\mathbf U$ have to be of length $1$. This means that the elements inside each column are not independent; their squares sum to one. However, this does not imply any correlation between $U_{i1}$ and $U_{j1}$ for $i\ne j$, and the sample correlation should be tiny for large number $N_\mathrm{rep}$ of random draws. Columns of $\mathbf U$ have to be orthogonal. This means that the elements from different columns are not independent; their dot product is zero. Again, this does not imply any correlation between $U_{i1}$ and $U_{j2}$, and the sample correlation should be tiny. My question was: why do we see high correlations of $\sim 0.2$ even the for large number of random draws $N_\mathrm{rep}=1000$? Here is a replication of @whuber's example with $n=4$, $k=2$, and $N_\mathrm{rep}=1000$ in Matlab: On the left is the correlation matrix, on the right -- scatter plots similar to @whuber's. The agreement between our simulations seems perfect. Now, following an ingenious suggestion by @ttnphns, I assign random signs to the columns of $U$, i.e. after this line: [U,S,V] = svd(X,0); I add the following two lines: U(:,1) = U(:,1) * sign(randn(1)); U(:,2) = U(:,2) * sign(randn(1)); Here is the outcome: All the correlations vanish, exactly as I expected from the beginning! As @whuber says, the lack of independence can be seen in the perfect circular shape of some scatter plots (because the length of each column must equal $1$, sum of squares of any two elements cannot exceed $1$). But the correlations do vanish. Summarizing the whole issue, we see that strong correlations appear because LAPACK chooses signs for columns of $\mathbf U$ in a specific way that seems to depend on the first two data points. It is certainly not a bug because the decomposition is correct. But LAPACK essentially creates these "artifact" correlations by exploiting the freedom to assign signs. These correlations do not reflect the dependence of the elements of $\mathbf U$; instead, they reflect the freedom in the SVD solution and a particular LAPACK's convention to fix it. PS. Congratulations to @whuber for passing 100k reputation today!
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is This answer presents a replication of @whuber's results in Matlab, and also a direct demonstration that the correlations are an "artifact" of how the SVD implementation chooses sign for components. Gi
13,194
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is it a LAPACK bug?
Check the norm of your singular vectors U and V, it's 1 by definition. You don't need to go through SVD to get the same exact matrix you plot by simply generating two random variables $x$ and $y$ with the constraint that the sum of their squares is 1: $$x^2+y^2=1$$ Assume that the means are zero, then $$Cov[x,y]=Var[xy]=E[x^2y^2]-E[xy]^2$$ This will not be equal to zero. You can plug the standard normal into $x$ and $y$ to see what's the value of covariance to be expected here.
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is
Check the norm of your singular vectors U and V, it's 1 by definition. You don't need to go through SVD to get the same exact matrix you plot by simply generating two random variables $x$ and $y$ with
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is it a LAPACK bug? Check the norm of your singular vectors U and V, it's 1 by definition. You don't need to go through SVD to get the same exact matrix you plot by simply generating two random variables $x$ and $y$ with the constraint that the sum of their squares is 1: $$x^2+y^2=1$$ Assume that the means are zero, then $$Cov[x,y]=Var[xy]=E[x^2y^2]-E[xy]^2$$ This will not be equal to zero. You can plug the standard normal into $x$ and $y$ to see what's the value of covariance to be expected here.
Weird correlations in the SVD results of random data; do they have a mathematical explanation or is Check the norm of your singular vectors U and V, it's 1 by definition. You don't need to go through SVD to get the same exact matrix you plot by simply generating two random variables $x$ and $y$ with
13,195
What's the difference between standardization and studentization?
A short recap. Given a model $y=X\beta+\varepsilon$, where $X$ is $n\times p$, $\hat\beta=(X'X)^{-1}X'y$ and $\hat y=X\hat\beta=X(X'X)^{-1}X'y=Hy$, where $H=X(X'X)^{-1}X'$ is the "hat matrix". Residuals are $$e=y-\hat y=y-Hy=(I-H)y$$ The population variance $\sigma^2$ is unknown and can be estimated by $MSE$, the mean square error. Semistudentized residuals are defined as $$e_i^*=\frac{e_i}{\sqrt{MSE}}$$ but, since the variance of residuals depends on both $\sigma^2$ and $X$, their estimated variance is: $$\widehat V(e_i)=MSE(1-h_{ii})$$ where $h_{ii}$ is the $i$th diagonal element of the hat matrix. Standardized residuals, also called internally studentized residuals, are: $$r_i=\frac{e_i}{\sqrt{MSE(1-h_{ii})}}$$ However the single $e_i$ and $MSE$ are non independent, so $r_i$ can't have a $t$ distribution. The procedure is then to delete the $i$th observation, fit the regression function to the remaining $n-1$ observations, and get new $\hat y$'s which can be denoted by $\hat y_{i(i)}$. The difference: $$d_i=y_i-\hat y_{i(i)}$$ is called deleted residual. An equivalent expression that does not require a recomputation is: $$d_i=\frac{e_i}{1-h_{ii}}$$ Denoting the new $X$ and $MSE$ by $X_{(i)}$ and $MSE_{(i)}$, since they do not depend on the $i$th observation, we get: $$t_i=\frac{d_i}{\sqrt{\frac{MSE_{(i)}}{1-h_{ii}}}} =\frac{e_i}{\sqrt{MSE_{(i)}(1-h_{ii})}}\sim t_{n-p-1}$$ The $t_i$'s are called studentized (deleted) residuals, or externally studentized residuals. See Kutner et al., Applied Linear Statistical Models, Chapter 10. Edit: I must say that the answer by rpierce is perfect. I thought that the OP was about standardized and studentized residuals (and dividing by the population standard deviation to get standardized residuals looked odd to me, of course), but I was wrong. I hope that my answer can help someone even if OT.
What's the difference between standardization and studentization?
A short recap. Given a model $y=X\beta+\varepsilon$, where $X$ is $n\times p$, $\hat\beta=(X'X)^{-1}X'y$ and $\hat y=X\hat\beta=X(X'X)^{-1}X'y=Hy$, where $H=X(X'X)^{-1}X'$ is the "hat matrix". Residua
What's the difference between standardization and studentization? A short recap. Given a model $y=X\beta+\varepsilon$, where $X$ is $n\times p$, $\hat\beta=(X'X)^{-1}X'y$ and $\hat y=X\hat\beta=X(X'X)^{-1}X'y=Hy$, where $H=X(X'X)^{-1}X'$ is the "hat matrix". Residuals are $$e=y-\hat y=y-Hy=(I-H)y$$ The population variance $\sigma^2$ is unknown and can be estimated by $MSE$, the mean square error. Semistudentized residuals are defined as $$e_i^*=\frac{e_i}{\sqrt{MSE}}$$ but, since the variance of residuals depends on both $\sigma^2$ and $X$, their estimated variance is: $$\widehat V(e_i)=MSE(1-h_{ii})$$ where $h_{ii}$ is the $i$th diagonal element of the hat matrix. Standardized residuals, also called internally studentized residuals, are: $$r_i=\frac{e_i}{\sqrt{MSE(1-h_{ii})}}$$ However the single $e_i$ and $MSE$ are non independent, so $r_i$ can't have a $t$ distribution. The procedure is then to delete the $i$th observation, fit the regression function to the remaining $n-1$ observations, and get new $\hat y$'s which can be denoted by $\hat y_{i(i)}$. The difference: $$d_i=y_i-\hat y_{i(i)}$$ is called deleted residual. An equivalent expression that does not require a recomputation is: $$d_i=\frac{e_i}{1-h_{ii}}$$ Denoting the new $X$ and $MSE$ by $X_{(i)}$ and $MSE_{(i)}$, since they do not depend on the $i$th observation, we get: $$t_i=\frac{d_i}{\sqrt{\frac{MSE_{(i)}}{1-h_{ii}}}} =\frac{e_i}{\sqrt{MSE_{(i)}(1-h_{ii})}}\sim t_{n-p-1}$$ The $t_i$'s are called studentized (deleted) residuals, or externally studentized residuals. See Kutner et al., Applied Linear Statistical Models, Chapter 10. Edit: I must say that the answer by rpierce is perfect. I thought that the OP was about standardized and studentized residuals (and dividing by the population standard deviation to get standardized residuals looked odd to me, of course), but I was wrong. I hope that my answer can help someone even if OT.
What's the difference between standardization and studentization? A short recap. Given a model $y=X\beta+\varepsilon$, where $X$ is $n\times p$, $\hat\beta=(X'X)^{-1}X'y$ and $\hat y=X\hat\beta=X(X'X)^{-1}X'y=Hy$, where $H=X(X'X)^{-1}X'$ is the "hat matrix". Residua
13,196
What's the difference between standardization and studentization?
In social sciences it is typically said that Studentizated scores uses Student's/Gosset's calculation for estimating the population variance/standard deviation from the sample variance/standard deviation ($s$). In contrast, Standardized scores (a noun, a particular type of statistic, the Z score) are said to use the population standard deviation ?($\sigma$). However, it appears there is some terminological differences across fields (please see the comments on this answer). Therefore, one ought to proceed with caution in making these distinctions. Moreover, studentized scores are rarely called such and one typically sees 'studentized' values in the context of regression. @Sergio provides details about those types of studentized deleted residuals in his answer.
What's the difference between standardization and studentization?
In social sciences it is typically said that Studentizated scores uses Student's/Gosset's calculation for estimating the population variance/standard deviation from the sample variance/standard deviat
What's the difference between standardization and studentization? In social sciences it is typically said that Studentizated scores uses Student's/Gosset's calculation for estimating the population variance/standard deviation from the sample variance/standard deviation ($s$). In contrast, Standardized scores (a noun, a particular type of statistic, the Z score) are said to use the population standard deviation ?($\sigma$). However, it appears there is some terminological differences across fields (please see the comments on this answer). Therefore, one ought to proceed with caution in making these distinctions. Moreover, studentized scores are rarely called such and one typically sees 'studentized' values in the context of regression. @Sergio provides details about those types of studentized deleted residuals in his answer.
What's the difference between standardization and studentization? In social sciences it is typically said that Studentizated scores uses Student's/Gosset's calculation for estimating the population variance/standard deviation from the sample variance/standard deviat
13,197
What's the difference between standardization and studentization?
I am very late in answering this question!!. But couldn't find the answer in very simple language so humble attempt to answer this. Why we do standardization? Imagine you have two models-one predicts craziness from amount of time spent on studying statistics while other predicts log(craziness) with amount of time on statistics. it would be hard to understand residuals are both are in different units. So we standardize them .(similar theory as Z-score ) Standardized residuals: - When residuals are divided by an estimate of standard deviation . In general if absolute value > 3 then it's cause of concern. We use this to investigate outliers in model. Studentized Residual: We use this to study stability of model. Process is simple. We remove individual test case from model and find out the new predicted value. Difference between new value and original observed value can be standardized by dividing standard error. this value is Studentized Residual For more infö discovering statics using R -http://www.statisticshell.com/html/dsur.html
What's the difference between standardization and studentization?
I am very late in answering this question!!. But couldn't find the answer in very simple language so humble attempt to answer this. Why we do standardization? Imagine you have two models-one predicts
What's the difference between standardization and studentization? I am very late in answering this question!!. But couldn't find the answer in very simple language so humble attempt to answer this. Why we do standardization? Imagine you have two models-one predicts craziness from amount of time spent on studying statistics while other predicts log(craziness) with amount of time on statistics. it would be hard to understand residuals are both are in different units. So we standardize them .(similar theory as Z-score ) Standardized residuals: - When residuals are divided by an estimate of standard deviation . In general if absolute value > 3 then it's cause of concern. We use this to investigate outliers in model. Studentized Residual: We use this to study stability of model. Process is simple. We remove individual test case from model and find out the new predicted value. Difference between new value and original observed value can be standardized by dividing standard error. this value is Studentized Residual For more infö discovering statics using R -http://www.statisticshell.com/html/dsur.html
What's the difference between standardization and studentization? I am very late in answering this question!!. But couldn't find the answer in very simple language so humble attempt to answer this. Why we do standardization? Imagine you have two models-one predicts
13,198
What's the difference between standardization and studentization?
Wikipedia has a good overview at https://en.wikipedia.org/wiki/Normalization_(statistics): Standard score $\frac{X - \mu}{\sigma}$ : Normalizing errors when population parameters are known. Works well for populations that are normally distributed Student's t-statistic $\frac{X - \overline{X}}{s}$ : Normalizing residuals when population parameters are unknown (estimated).
What's the difference between standardization and studentization?
Wikipedia has a good overview at https://en.wikipedia.org/wiki/Normalization_(statistics): Standard score $\frac{X - \mu}{\sigma}$ : Normalizing errors when population parameters are known. Works wel
What's the difference between standardization and studentization? Wikipedia has a good overview at https://en.wikipedia.org/wiki/Normalization_(statistics): Standard score $\frac{X - \mu}{\sigma}$ : Normalizing errors when population parameters are known. Works well for populations that are normally distributed Student's t-statistic $\frac{X - \overline{X}}{s}$ : Normalizing residuals when population parameters are unknown (estimated).
What's the difference between standardization and studentization? Wikipedia has a good overview at https://en.wikipedia.org/wiki/Normalization_(statistics): Standard score $\frac{X - \mu}{\sigma}$ : Normalizing errors when population parameters are known. Works wel
13,199
Is Benjamini-Hochberg correction more conservative as the number of comparisons increases?
First, you need to understand that these two multiple testing procedures do not control the same thing. Using your example, we have two groups with 18,000 observed variables, and you make 18,000 tests in order to identify some variables which are different from one group to the other. Bonferroni correction controls the Familywise error rate, that is the probability, assuming all the 18,000 variables have identical distribution in the two groups, that you are falsely claiming "here I have some significant differences". Usually, you decide that if this probability is < 5%, your claim is credible. Benjamini-Hochberg correction controls the False discovery rate, that is, the expected proportion of false positives among the variables for which you claim the existence of a difference. For example, if with FDR controlled to 5% 20 tests are positive, "in average" only 1 of these tests will be a false positive. Now, when the number of comparison increases... well, it depends on the number of marginal null hypotheses that are true. But basically, with both procedures, if you have a few, let’s says 5 or 10, truly associated variables, you have more chances to detect them among 100 variables than among 1,000,000 variables. That should be intuitive enough. There’s no way to avoid this.
Is Benjamini-Hochberg correction more conservative as the number of comparisons increases?
First, you need to understand that these two multiple testing procedures do not control the same thing. Using your example, we have two groups with 18,000 observed variables, and you make 18,000 tests
Is Benjamini-Hochberg correction more conservative as the number of comparisons increases? First, you need to understand that these two multiple testing procedures do not control the same thing. Using your example, we have two groups with 18,000 observed variables, and you make 18,000 tests in order to identify some variables which are different from one group to the other. Bonferroni correction controls the Familywise error rate, that is the probability, assuming all the 18,000 variables have identical distribution in the two groups, that you are falsely claiming "here I have some significant differences". Usually, you decide that if this probability is < 5%, your claim is credible. Benjamini-Hochberg correction controls the False discovery rate, that is, the expected proportion of false positives among the variables for which you claim the existence of a difference. For example, if with FDR controlled to 5% 20 tests are positive, "in average" only 1 of these tests will be a false positive. Now, when the number of comparison increases... well, it depends on the number of marginal null hypotheses that are true. But basically, with both procedures, if you have a few, let’s says 5 or 10, truly associated variables, you have more chances to detect them among 100 variables than among 1,000,000 variables. That should be intuitive enough. There’s no way to avoid this.
Is Benjamini-Hochberg correction more conservative as the number of comparisons increases? First, you need to understand that these two multiple testing procedures do not control the same thing. Using your example, we have two groups with 18,000 observed variables, and you make 18,000 tests
13,200
Computing the decision boundary of a linear SVM model
The Elements of Statistical Learning, from Hastie et al., has a complete chapter on support vector classifiers and SVMs (in your case, start page 418 on the 2nd edition). Another good tutorial is Support Vector Machines in R, by David Meyer. Unless I misunderstood your question, the decision boundary (or hyperplane) is defined by $x^T\beta + \beta_0=0$ (with $\|\beta\|=1$, and $\beta_0$ the intercept term), or as @ebony said a linear combination of the support vectors. The margin is then $2/\|\beta\|$, following Hastie et al. notations. From the on-line help of ksvm() in the kernlab R package, but see also kernlab – An S4 Package for Kernel Methods in R, here is a toy example: set.seed(101) x <- rbind(matrix(rnorm(120),,2),matrix(rnorm(120,mean=3),,2)) y <- matrix(c(rep(1,60),rep(-1,60))) svp <- ksvm(x,y,type="C-svc") plot(svp,data=x) Note that for the sake of clarity, we don't consider train and test samples. Results are shown below, where color shading helps visualizing the fitted decision values; values around 0 are on the decision boundary. Calling attributes(svp) gives you attributes that you can access, e.g. alpha(svp) # support vectors whose indices may be # found with alphaindex(svp) b(svp) # (negative) intercept So, to display the decision boundary, with its corresponding margin, let's try the following (in the rescaled space), which is largely inspired from a tutorial on SVM made some time ago by Jean-Philippe Vert: plot(scale(x), col=y+2, pch=y+2, xlab="", ylab="") w <- colSums(coef(svp)[[1]] * x[unlist(alphaindex(svp)),]) b <- b(svp) abline(b/w[1],-w[2]/w[1]) abline((b+1)/w[1],-w[2]/w[1],lty=2) abline((b-1)/w[1],-w[2]/w[1],lty=2) And here it is:
Computing the decision boundary of a linear SVM model
The Elements of Statistical Learning, from Hastie et al., has a complete chapter on support vector classifiers and SVMs (in your case, start page 418 on the 2nd edition). Another good tutorial is Supp
Computing the decision boundary of a linear SVM model The Elements of Statistical Learning, from Hastie et al., has a complete chapter on support vector classifiers and SVMs (in your case, start page 418 on the 2nd edition). Another good tutorial is Support Vector Machines in R, by David Meyer. Unless I misunderstood your question, the decision boundary (or hyperplane) is defined by $x^T\beta + \beta_0=0$ (with $\|\beta\|=1$, and $\beta_0$ the intercept term), or as @ebony said a linear combination of the support vectors. The margin is then $2/\|\beta\|$, following Hastie et al. notations. From the on-line help of ksvm() in the kernlab R package, but see also kernlab – An S4 Package for Kernel Methods in R, here is a toy example: set.seed(101) x <- rbind(matrix(rnorm(120),,2),matrix(rnorm(120,mean=3),,2)) y <- matrix(c(rep(1,60),rep(-1,60))) svp <- ksvm(x,y,type="C-svc") plot(svp,data=x) Note that for the sake of clarity, we don't consider train and test samples. Results are shown below, where color shading helps visualizing the fitted decision values; values around 0 are on the decision boundary. Calling attributes(svp) gives you attributes that you can access, e.g. alpha(svp) # support vectors whose indices may be # found with alphaindex(svp) b(svp) # (negative) intercept So, to display the decision boundary, with its corresponding margin, let's try the following (in the rescaled space), which is largely inspired from a tutorial on SVM made some time ago by Jean-Philippe Vert: plot(scale(x), col=y+2, pch=y+2, xlab="", ylab="") w <- colSums(coef(svp)[[1]] * x[unlist(alphaindex(svp)),]) b <- b(svp) abline(b/w[1],-w[2]/w[1]) abline((b+1)/w[1],-w[2]/w[1],lty=2) abline((b-1)/w[1],-w[2]/w[1],lty=2) And here it is:
Computing the decision boundary of a linear SVM model The Elements of Statistical Learning, from Hastie et al., has a complete chapter on support vector classifiers and SVMs (in your case, start page 418 on the 2nd edition). Another good tutorial is Supp