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
8,501
Why will ridge regression not shrink some coefficients to zero like lasso?
Ridge Regression $L_{2}=(y-x\beta)^2+\lambda\sum_{i=1}^{p}\beta_{i}^2$ Will solve this equation only for one β for now and latter you can generalize this: So, $(y-xβ)^2+λβ^2$ this is our equation for one β. Our goal is to minimize the above equation, to be able to do this, will equate this to zero and take the derivatives w.r.t $β$ $Y^2- 2xyβ+ x^2 β^2+ λβ^2=0$ --------Using $(a-b)^2$ expansion Partial derivatives w.r.t $-2xy+2x^2β+2βλ=0$ $2β (x^2+λ) = 2xy$ $β= 2xy/ 2(x^2 + λ)$ Finally $β= xy/(x^2 + λ)$ If you observe the denominator, it will become zero only if $\lambda \rightarrow \infty$ (see ISLR, pp. 215), since we are adding some value of $λ$ (i.e. hyperparameter). And therefore the value of $β$ will be as low as possible but will not become zero. LASSO Regression: $L_{1}=(y-x\beta)^2+\lambda\sum_{i=1}^{p}\left |\beta_{i} \right |$ Will solve this equation only for one β for now and latter you can generalize this to more $β$: So, $(y-xβ)^2+λβ$ this is our equation for one $β$, Here I have considered +ve value of $β$. Our goal is to minimize the above equation, to be able to do this, will equate this to zero and take the derivatives w.r.t $β$ $Y^2- 2xyβ+ x^2 β^2+ λβ=0$ -------Using $(a-b) ^2$ expansion Partial derivatives w.r.t $-2xy+2x^2β+λ=0$ $2x^2β+λ= 2xy$ $2x^2β=2xy-λ$ Finally $β= (2xy-λ)/ (2X^2)$ If you observe the numerator, it will become zero, since we are subtracting some value of $λ$ (i.e. hyperparameter). And therefore the value of $β$ will be set as zero.
Why will ridge regression not shrink some coefficients to zero like lasso?
Ridge Regression $L_{2}=(y-x\beta)^2+\lambda\sum_{i=1}^{p}\beta_{i}^2$ Will solve this equation only for one β for now and latter you can generalize this: So, $(y-xβ)^2+λβ^2$ this is our equation for
Why will ridge regression not shrink some coefficients to zero like lasso? Ridge Regression $L_{2}=(y-x\beta)^2+\lambda\sum_{i=1}^{p}\beta_{i}^2$ Will solve this equation only for one β for now and latter you can generalize this: So, $(y-xβ)^2+λβ^2$ this is our equation for one β. Our goal is to minimize the above equation, to be able to do this, will equate this to zero and take the derivatives w.r.t $β$ $Y^2- 2xyβ+ x^2 β^2+ λβ^2=0$ --------Using $(a-b)^2$ expansion Partial derivatives w.r.t $-2xy+2x^2β+2βλ=0$ $2β (x^2+λ) = 2xy$ $β= 2xy/ 2(x^2 + λ)$ Finally $β= xy/(x^2 + λ)$ If you observe the denominator, it will become zero only if $\lambda \rightarrow \infty$ (see ISLR, pp. 215), since we are adding some value of $λ$ (i.e. hyperparameter). And therefore the value of $β$ will be as low as possible but will not become zero. LASSO Regression: $L_{1}=(y-x\beta)^2+\lambda\sum_{i=1}^{p}\left |\beta_{i} \right |$ Will solve this equation only for one β for now and latter you can generalize this to more $β$: So, $(y-xβ)^2+λβ$ this is our equation for one $β$, Here I have considered +ve value of $β$. Our goal is to minimize the above equation, to be able to do this, will equate this to zero and take the derivatives w.r.t $β$ $Y^2- 2xyβ+ x^2 β^2+ λβ=0$ -------Using $(a-b) ^2$ expansion Partial derivatives w.r.t $-2xy+2x^2β+λ=0$ $2x^2β+λ= 2xy$ $2x^2β=2xy-λ$ Finally $β= (2xy-λ)/ (2X^2)$ If you observe the numerator, it will become zero, since we are subtracting some value of $λ$ (i.e. hyperparameter). And therefore the value of $β$ will be set as zero.
Why will ridge regression not shrink some coefficients to zero like lasso? Ridge Regression $L_{2}=(y-x\beta)^2+\lambda\sum_{i=1}^{p}\beta_{i}^2$ Will solve this equation only for one β for now and latter you can generalize this: So, $(y-xβ)^2+λβ^2$ this is our equation for
8,502
Does it make sense to combine PCA and LDA?
Summary: PCA can be performed before LDA to regularize the problem and avoid over-fitting. Recall that LDA projections are computed via eigendecomposition of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Sigma_B$, where $\boldsymbol \Sigma_W$ and $\boldsymbol \Sigma_B$ are within- and between-class covariance matrices. If there are less than $N$ data points (where $N$ is the dimensionality of your space, i.e. the number of features/variables), then $\boldsymbol \Sigma_W$ will be singular and therefore cannot be inverted. In this case there is simply no way to perform LDA directly, but if one applies PCA first, it will work. @Aaron made this remark in the comments to his reply, and I agree with that (but disagree with his answer in general, as you will see now). However, this is only part of the problem. The bigger picture is that LDA very easily tends to overfit the data. Note that within-class covariance matrix gets inverted in the LDA computations; for high-dimensional matrices inversion is a really sensitive operation that can only be reliably done if the estimate of $\boldsymbol \Sigma_W$ is really good. But in high dimensions $N \gg 1$, it is really difficult to obtain a precise estimate of $\boldsymbol \Sigma_W$, and in practice one often has to have a lot more than $N$ data points to start hoping that the estimate is good. Otherwise $\boldsymbol \Sigma_W$ will be almost-singular (i.e. some of the eigenvalues will be very low), and this will cause over-fitting, i.e. near-perfect class separation on the training data with chance performance on the test data. To tackle this issue, one needs to regularize the problem. One way to do it is to use PCA to reduce dimensionality first. There are other, arguably better ones, e.g. regularized LDA (rLDA) method which simply uses $(1-\lambda)\boldsymbol \Sigma_W + \lambda \boldsymbol I$ with small $\lambda$ instead of $\boldsymbol \Sigma_W$ (this is called shrinkage estimator), but doing PCA first is conceptually the simplest approach and often works just fine. Illustration Here is an illustration of the over-fitting problem. I generated 60 samples per class in 3 classes from standard Gaussian distribution (mean zero, unit variance) in 10-, 50-, 100-, and 150-dimensional spaces, and applied LDA to project the data on 2D: Note how as the dimensionality grows, classes become better and better separated, whereas in reality there is no difference between the classes. We can see how PCA helps to prevent the overfitting if we make classes slightly separated. I added 1 to the first coordinate of the first class, 2 to the first coordinate of the second class, and 3 to the first coordinate of the third class. Now they are slightly separated, see top left subplot: Overfitting (top row) is still obvious. But if I pre-process the data with PCA, always keeping 10 dimensions (bottom row), overfitting disappears while the classes remain near-optimally separated. PS. To prevent misunderstandings: I am not claiming that PCA+LDA is a good regularization strategy (on the contrary, I would advice to use rLDA), I am simply demonstrating that it is a possible strategy. Update. Very similar topic has been previously discussed in the following threads with interesting and comprehensive answers provided by @cbeleites: Should PCA be performed before I do classification? Does it make sense to run LDA on several principal components and not on all variables? See also this question with some good answers: What can cause PCA to worsen results of a classifier?
Does it make sense to combine PCA and LDA?
Summary: PCA can be performed before LDA to regularize the problem and avoid over-fitting. Recall that LDA projections are computed via eigendecomposition of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Si
Does it make sense to combine PCA and LDA? Summary: PCA can be performed before LDA to regularize the problem and avoid over-fitting. Recall that LDA projections are computed via eigendecomposition of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Sigma_B$, where $\boldsymbol \Sigma_W$ and $\boldsymbol \Sigma_B$ are within- and between-class covariance matrices. If there are less than $N$ data points (where $N$ is the dimensionality of your space, i.e. the number of features/variables), then $\boldsymbol \Sigma_W$ will be singular and therefore cannot be inverted. In this case there is simply no way to perform LDA directly, but if one applies PCA first, it will work. @Aaron made this remark in the comments to his reply, and I agree with that (but disagree with his answer in general, as you will see now). However, this is only part of the problem. The bigger picture is that LDA very easily tends to overfit the data. Note that within-class covariance matrix gets inverted in the LDA computations; for high-dimensional matrices inversion is a really sensitive operation that can only be reliably done if the estimate of $\boldsymbol \Sigma_W$ is really good. But in high dimensions $N \gg 1$, it is really difficult to obtain a precise estimate of $\boldsymbol \Sigma_W$, and in practice one often has to have a lot more than $N$ data points to start hoping that the estimate is good. Otherwise $\boldsymbol \Sigma_W$ will be almost-singular (i.e. some of the eigenvalues will be very low), and this will cause over-fitting, i.e. near-perfect class separation on the training data with chance performance on the test data. To tackle this issue, one needs to regularize the problem. One way to do it is to use PCA to reduce dimensionality first. There are other, arguably better ones, e.g. regularized LDA (rLDA) method which simply uses $(1-\lambda)\boldsymbol \Sigma_W + \lambda \boldsymbol I$ with small $\lambda$ instead of $\boldsymbol \Sigma_W$ (this is called shrinkage estimator), but doing PCA first is conceptually the simplest approach and often works just fine. Illustration Here is an illustration of the over-fitting problem. I generated 60 samples per class in 3 classes from standard Gaussian distribution (mean zero, unit variance) in 10-, 50-, 100-, and 150-dimensional spaces, and applied LDA to project the data on 2D: Note how as the dimensionality grows, classes become better and better separated, whereas in reality there is no difference between the classes. We can see how PCA helps to prevent the overfitting if we make classes slightly separated. I added 1 to the first coordinate of the first class, 2 to the first coordinate of the second class, and 3 to the first coordinate of the third class. Now they are slightly separated, see top left subplot: Overfitting (top row) is still obvious. But if I pre-process the data with PCA, always keeping 10 dimensions (bottom row), overfitting disappears while the classes remain near-optimally separated. PS. To prevent misunderstandings: I am not claiming that PCA+LDA is a good regularization strategy (on the contrary, I would advice to use rLDA), I am simply demonstrating that it is a possible strategy. Update. Very similar topic has been previously discussed in the following threads with interesting and comprehensive answers provided by @cbeleites: Should PCA be performed before I do classification? Does it make sense to run LDA on several principal components and not on all variables? See also this question with some good answers: What can cause PCA to worsen results of a classifier?
Does it make sense to combine PCA and LDA? Summary: PCA can be performed before LDA to regularize the problem and avoid over-fitting. Recall that LDA projections are computed via eigendecomposition of $\boldsymbol \Sigma_W^{-1} \boldsymbol \Si
8,503
Does it make sense to combine PCA and LDA?
If you have a two class problem then LDA will take you down to 1 dimension. There is no reason to do PCA first.
Does it make sense to combine PCA and LDA?
If you have a two class problem then LDA will take you down to 1 dimension. There is no reason to do PCA first.
Does it make sense to combine PCA and LDA? If you have a two class problem then LDA will take you down to 1 dimension. There is no reason to do PCA first.
Does it make sense to combine PCA and LDA? If you have a two class problem then LDA will take you down to 1 dimension. There is no reason to do PCA first.
8,504
Comparing smoothing splines vs loess for smoothing?
Here is some R code/example that will let you compare the fits for a loess fit and a spline fit: library(TeachingDemos) library(splines) tmpfun <- function(x,y,span=.75,df=3) { plot(x,y) fit1 <- lm(y ~ ns(x,df)) xx <- seq( min(x), max(x), length.out=250 ) yy <- predict(fit1, data.frame(x=xx)) lines(xx,yy, col='blue') fit2 <- loess(y~x, span=span) yy <- predict(fit2, data.frame(x=xx)) lines(xx,yy, col='green') invisible(NULL) } tmplst <- list( span=list('slider', from=0.1, to=1.5, resolution=0.05, init=0.75), df=list('slider', from=3, to=25, resolution=1, init=3)) tkexamp( tmpfun(ethanol$E, ethanol$NOx), tmplst ) You can try it with your data and change the code to try other types or options. You may also want to look at the loess.demo function in the TeachingDemos package for a better understanding of what the loess algorythm does. Note that what you see from loess is often a combination of loess with a second interpolation smoothing (sometimes itself a spline), the loess.demo function actually shows both the smoothed and the raw loess fit. Theoretically you can always find a spline that approximates another continuous function as close as you want, but it is unlikely that there will be a simple choice of knots that will reliably give a close approximation to a loess fit for any data set.
Comparing smoothing splines vs loess for smoothing?
Here is some R code/example that will let you compare the fits for a loess fit and a spline fit: library(TeachingDemos) library(splines) tmpfun <- function(x,y,span=.75,df=3) { plot(x,y) fit1
Comparing smoothing splines vs loess for smoothing? Here is some R code/example that will let you compare the fits for a loess fit and a spline fit: library(TeachingDemos) library(splines) tmpfun <- function(x,y,span=.75,df=3) { plot(x,y) fit1 <- lm(y ~ ns(x,df)) xx <- seq( min(x), max(x), length.out=250 ) yy <- predict(fit1, data.frame(x=xx)) lines(xx,yy, col='blue') fit2 <- loess(y~x, span=span) yy <- predict(fit2, data.frame(x=xx)) lines(xx,yy, col='green') invisible(NULL) } tmplst <- list( span=list('slider', from=0.1, to=1.5, resolution=0.05, init=0.75), df=list('slider', from=3, to=25, resolution=1, init=3)) tkexamp( tmpfun(ethanol$E, ethanol$NOx), tmplst ) You can try it with your data and change the code to try other types or options. You may also want to look at the loess.demo function in the TeachingDemos package for a better understanding of what the loess algorythm does. Note that what you see from loess is often a combination of loess with a second interpolation smoothing (sometimes itself a spline), the loess.demo function actually shows both the smoothed and the raw loess fit. Theoretically you can always find a spline that approximates another continuous function as close as you want, but it is unlikely that there will be a simple choice of knots that will reliably give a close approximation to a loess fit for any data set.
Comparing smoothing splines vs loess for smoothing? Here is some R code/example that will let you compare the fits for a loess fit and a spline fit: library(TeachingDemos) library(splines) tmpfun <- function(x,y,span=.75,df=3) { plot(x,y) fit1
8,505
Comparing smoothing splines vs loess for smoothing?
The actual results from a smoothing spline or loess are going to be pretty similar. They might look a little different at the edges of the support, but as long as you make sure it's a "natural" smoothing spline they will look really similar. If you are just using one to add a "smoother" to a scatterplot, there's no real reason to prefer one over the other. If instead you want to make predictions on new data, it's generally much easier to use a smoothing spline. This is because the smoothing spline is a direct basis expansion of the original data; if you used 100 knots to make it that means you created ~100 new variables from the original variable. Loess instead just estimates the response at all the values experienced (or a stratified subset for large data). In general, there are established algorithms to optimize the penalty value for smoothing splines (mgcv in R probably does this the best). Loess isn't quite as clear cut, but you'll generally still get reasonable output from any implementation. MGCV also gives you a feel for equivalent Degrees of Freedom so you can get a feel for how "non-linear" your data is. I find that when modeling on very large data, a simpler natural spline often provides similar results for minimal calculation compared to either a smoothing spline or loess.
Comparing smoothing splines vs loess for smoothing?
The actual results from a smoothing spline or loess are going to be pretty similar. They might look a little different at the edges of the support, but as long as you make sure it's a "natural" smoot
Comparing smoothing splines vs loess for smoothing? The actual results from a smoothing spline or loess are going to be pretty similar. They might look a little different at the edges of the support, but as long as you make sure it's a "natural" smoothing spline they will look really similar. If you are just using one to add a "smoother" to a scatterplot, there's no real reason to prefer one over the other. If instead you want to make predictions on new data, it's generally much easier to use a smoothing spline. This is because the smoothing spline is a direct basis expansion of the original data; if you used 100 knots to make it that means you created ~100 new variables from the original variable. Loess instead just estimates the response at all the values experienced (or a stratified subset for large data). In general, there are established algorithms to optimize the penalty value for smoothing splines (mgcv in R probably does this the best). Loess isn't quite as clear cut, but you'll generally still get reasonable output from any implementation. MGCV also gives you a feel for equivalent Degrees of Freedom so you can get a feel for how "non-linear" your data is. I find that when modeling on very large data, a simpler natural spline often provides similar results for minimal calculation compared to either a smoothing spline or loess.
Comparing smoothing splines vs loess for smoothing? The actual results from a smoothing spline or loess are going to be pretty similar. They might look a little different at the edges of the support, but as long as you make sure it's a "natural" smoot
8,506
Difference between Cohen's d and Hedges' g for effect size metrics
Both Cohen's d and Hedges' g pool variances on the assumption of equal population variances, but g pools using n - 1 for each sample instead of n, which provides a better estimate, especially the smaller the sample sizes. Both d and g are somewhat positively biased, but only negligibly for moderate or larger sample sizes. The bias is reduced using g*. The d by Glass does not assume equal variances, so it uses the sd of a control group or baseline comparison group as the standardizer for the difference between the two means. These effect sizes and Cliff's and other nonparametric effect sizes are discussed in detail in my book: Grissom, R. J., & Kim, J, J. (2005). Effect sizes for research: A broad practical approach. Mahwah, NJ: Erlbaum.
Difference between Cohen's d and Hedges' g for effect size metrics
Both Cohen's d and Hedges' g pool variances on the assumption of equal population variances, but g pools using n - 1 for each sample instead of n, which provides a better estimate, especially the smal
Difference between Cohen's d and Hedges' g for effect size metrics Both Cohen's d and Hedges' g pool variances on the assumption of equal population variances, but g pools using n - 1 for each sample instead of n, which provides a better estimate, especially the smaller the sample sizes. Both d and g are somewhat positively biased, but only negligibly for moderate or larger sample sizes. The bias is reduced using g*. The d by Glass does not assume equal variances, so it uses the sd of a control group or baseline comparison group as the standardizer for the difference between the two means. These effect sizes and Cliff's and other nonparametric effect sizes are discussed in detail in my book: Grissom, R. J., & Kim, J, J. (2005). Effect sizes for research: A broad practical approach. Mahwah, NJ: Erlbaum.
Difference between Cohen's d and Hedges' g for effect size metrics Both Cohen's d and Hedges' g pool variances on the assumption of equal population variances, but g pools using n - 1 for each sample instead of n, which provides a better estimate, especially the smal
8,507
Difference between Cohen's d and Hedges' g for effect size metrics
It seems when people say Cohen's d they mostly mean: $$d = \frac{\bar{x}_1 - \bar{x}_2}{s}$$ Where $s$ is the pooled standard deviation, $$s = \sqrt{\frac{\sum(x_1 - \bar{x}_1)^2 + (x_2 - \bar{x}_2)^2}{n_1 + n_2 - 2}}$$ There are other estimators for the pooled standard deviation, probably the most common apart from the above being: $$s^* = \sqrt{\frac{\sum(x_1 - \bar{x}_1)^2 + (x_2 - \bar{x}_2)^2}{n_1 + n_2}}$$ Notation here is remarkably inconsistent, but sometimes people say that the the $s^*$ (i.e., the $n_1 + n_2$ version) version is called Cohen's $d$, and reserve the name Hedge's $g$ for the version that uses $s$ (i.e., with Bessel’s correction, the n1+n2−2 version). This is a bit weird as Cohen outlined both estimators for the pooled standard deviation (e.g., $s$ version on p. 67, Cohen, 1977) before Hedges wrote about them (Hedges, 1981). Other times Hedge's g is reserved to refer to either of the bias corrected versions of a standardised mean difference that Hedges developed. Hedges (1981) showed that Cohen's d was upwardly biased (i.e., its expected value is higher than the true population parameter value), especially in small samples, and proposed a correction factor to correct for Cohen's d's bias: Hedges's g (the unbiased estimator): $$g = d * (\frac{\Gamma(df/2)}{\sqrt{df/2 \,}\,\Gamma((df-1)/2)})$$ Where $df = n_1 + n_2 -2$ for an independent groups design, and $\Gamma$ is the gamma function. (originally Hedges 1981, this version developed from Hedges and Olkin 1985, p. 104) However, this correction factor is fairly computationally complex, so Hedges also provided a computationally trivial approximation that, while still slightly biased, is fine for almost all conceivable purposes: Hedges' $g^*$ (the computationally trivial approximation): $$ g^* = d*(1 - \frac{3}{4(df) - 1})$$ Where $df = n_1 + n_2 -2$ for an independent groups design. (Originally from Hedges, 1981, this version from Borenstein, Hedges, Higgins, & Rothstein, 2011, p. 27) But, as for what people mean when they say Cohen's d vs. Hedges' g vs. g*, people seem to refer to any of these three estimators as Hedge's g or Cohen's d interchangeably, although I've never seen someone write "$g^*$" in a non-methodology/stats research paper. If someone says "unbiased Cohen's d", you're just going to have to take your best guess at either of the last two (and I think there might even be another approximation that has been used for Hedge's $g^*$ too!). They are all virtually identical if $n > 20$ or so, and all can be interpreted in the same way. For all practical purposes, unless you're dealing with really small sample sizes, it probably doesn't matter which you use (although if you can pick, you may as well use the one that I've called Hedges' g, as it is unbiased). References: Borenstein, M., Hedges, L. V., Higgins, J. P., & Rothstein, H. R. (2011). Introduction to Meta-Analysis. West Sussex, United Kingdom: John Wiley & Sons. Cohen, J. (1977). Statistical power analysis for the behavioral sciences (2nd ed.). Hillsdale, NJ, US: Lawrence Erlbaum Associates, Inc. Hedges, L. V. (1981). Distribution Theory for Glass's Estimator of Effect size and Related Estimators. Journal of Educational Statistics, 6(2), 107-128. doi:10.3102/10769986006002107 Hedges L. V., Olkin I. (1985). Statistical methods for meta-analysis. San Diego, CA: Academic Press
Difference between Cohen's d and Hedges' g for effect size metrics
It seems when people say Cohen's d they mostly mean: $$d = \frac{\bar{x}_1 - \bar{x}_2}{s}$$ Where $s$ is the pooled standard deviation, $$s = \sqrt{\frac{\sum(x_1 - \bar{x}_1)^2 + (x_2 - \bar{x}_2
Difference between Cohen's d and Hedges' g for effect size metrics It seems when people say Cohen's d they mostly mean: $$d = \frac{\bar{x}_1 - \bar{x}_2}{s}$$ Where $s$ is the pooled standard deviation, $$s = \sqrt{\frac{\sum(x_1 - \bar{x}_1)^2 + (x_2 - \bar{x}_2)^2}{n_1 + n_2 - 2}}$$ There are other estimators for the pooled standard deviation, probably the most common apart from the above being: $$s^* = \sqrt{\frac{\sum(x_1 - \bar{x}_1)^2 + (x_2 - \bar{x}_2)^2}{n_1 + n_2}}$$ Notation here is remarkably inconsistent, but sometimes people say that the the $s^*$ (i.e., the $n_1 + n_2$ version) version is called Cohen's $d$, and reserve the name Hedge's $g$ for the version that uses $s$ (i.e., with Bessel’s correction, the n1+n2−2 version). This is a bit weird as Cohen outlined both estimators for the pooled standard deviation (e.g., $s$ version on p. 67, Cohen, 1977) before Hedges wrote about them (Hedges, 1981). Other times Hedge's g is reserved to refer to either of the bias corrected versions of a standardised mean difference that Hedges developed. Hedges (1981) showed that Cohen's d was upwardly biased (i.e., its expected value is higher than the true population parameter value), especially in small samples, and proposed a correction factor to correct for Cohen's d's bias: Hedges's g (the unbiased estimator): $$g = d * (\frac{\Gamma(df/2)}{\sqrt{df/2 \,}\,\Gamma((df-1)/2)})$$ Where $df = n_1 + n_2 -2$ for an independent groups design, and $\Gamma$ is the gamma function. (originally Hedges 1981, this version developed from Hedges and Olkin 1985, p. 104) However, this correction factor is fairly computationally complex, so Hedges also provided a computationally trivial approximation that, while still slightly biased, is fine for almost all conceivable purposes: Hedges' $g^*$ (the computationally trivial approximation): $$ g^* = d*(1 - \frac{3}{4(df) - 1})$$ Where $df = n_1 + n_2 -2$ for an independent groups design. (Originally from Hedges, 1981, this version from Borenstein, Hedges, Higgins, & Rothstein, 2011, p. 27) But, as for what people mean when they say Cohen's d vs. Hedges' g vs. g*, people seem to refer to any of these three estimators as Hedge's g or Cohen's d interchangeably, although I've never seen someone write "$g^*$" in a non-methodology/stats research paper. If someone says "unbiased Cohen's d", you're just going to have to take your best guess at either of the last two (and I think there might even be another approximation that has been used for Hedge's $g^*$ too!). They are all virtually identical if $n > 20$ or so, and all can be interpreted in the same way. For all practical purposes, unless you're dealing with really small sample sizes, it probably doesn't matter which you use (although if you can pick, you may as well use the one that I've called Hedges' g, as it is unbiased). References: Borenstein, M., Hedges, L. V., Higgins, J. P., & Rothstein, H. R. (2011). Introduction to Meta-Analysis. West Sussex, United Kingdom: John Wiley & Sons. Cohen, J. (1977). Statistical power analysis for the behavioral sciences (2nd ed.). Hillsdale, NJ, US: Lawrence Erlbaum Associates, Inc. Hedges, L. V. (1981). Distribution Theory for Glass's Estimator of Effect size and Related Estimators. Journal of Educational Statistics, 6(2), 107-128. doi:10.3102/10769986006002107 Hedges L. V., Olkin I. (1985). Statistical methods for meta-analysis. San Diego, CA: Academic Press
Difference between Cohen's d and Hedges' g for effect size metrics It seems when people say Cohen's d they mostly mean: $$d = \frac{\bar{x}_1 - \bar{x}_2}{s}$$ Where $s$ is the pooled standard deviation, $$s = \sqrt{\frac{\sum(x_1 - \bar{x}_1)^2 + (x_2 - \bar{x}_2
8,508
Difference between Cohen's d and Hedges' g for effect size metrics
To my understanding, Hedges's g is a somewhat more accurate version of Cohen's d (with pooled SD) in that we add a correction factor for small sample. Both measures generally agree when the homoscedasticity assumption is not violated, but we may found situations where this is not the case, see e.g. McGrath & Meyer, Psychological Methods 2006, 11(4): 386-401. Other papers are listed at the end of my reply. I generally found that in almost every psychological or biomedical studies, this is the Cohen's d that is reported; this probably stands from the well-known rule of thumb for interpreting its magnitude (Cohen, 1988). I don't know about any recent paper considering Hedges's g (or Cliff delta as a non-parametric alternative). Bruce Thompson has a revised version of the APA section on effect size. Googling about Monte Carlo studies around effect size measures, I found this paper which might be interesting (I only read the abstract and the simulation setup): Robust Confidence Intervals for Effect Sizes: A Comparative Study of Cohen’s d and Cliff’s Delta Under Non-normality and Heterogeneous Variances (pdf). About your 2nd comment, the MBESS R package includes various utilities for ES calculation (e.g., smd and related functions). Other references Zakzanis, K.K. (2001). Statistics to tell the truth, the whole truth, and nothing but the truth: Formulae, illustrative numerical examples, and heuristic interpretation of effect size analyses for neuropsychological researchers. Archives of Clinical Neuropsychology, 16(7), 653-667. Durlak, J.A. (2009). How to Select, Calculate, and Interpret Effect Sizes. Journal of Pediatric Psychology
Difference between Cohen's d and Hedges' g for effect size metrics
To my understanding, Hedges's g is a somewhat more accurate version of Cohen's d (with pooled SD) in that we add a correction factor for small sample. Both measures generally agree when the homoscedas
Difference between Cohen's d and Hedges' g for effect size metrics To my understanding, Hedges's g is a somewhat more accurate version of Cohen's d (with pooled SD) in that we add a correction factor for small sample. Both measures generally agree when the homoscedasticity assumption is not violated, but we may found situations where this is not the case, see e.g. McGrath & Meyer, Psychological Methods 2006, 11(4): 386-401. Other papers are listed at the end of my reply. I generally found that in almost every psychological or biomedical studies, this is the Cohen's d that is reported; this probably stands from the well-known rule of thumb for interpreting its magnitude (Cohen, 1988). I don't know about any recent paper considering Hedges's g (or Cliff delta as a non-parametric alternative). Bruce Thompson has a revised version of the APA section on effect size. Googling about Monte Carlo studies around effect size measures, I found this paper which might be interesting (I only read the abstract and the simulation setup): Robust Confidence Intervals for Effect Sizes: A Comparative Study of Cohen’s d and Cliff’s Delta Under Non-normality and Heterogeneous Variances (pdf). About your 2nd comment, the MBESS R package includes various utilities for ES calculation (e.g., smd and related functions). Other references Zakzanis, K.K. (2001). Statistics to tell the truth, the whole truth, and nothing but the truth: Formulae, illustrative numerical examples, and heuristic interpretation of effect size analyses for neuropsychological researchers. Archives of Clinical Neuropsychology, 16(7), 653-667. Durlak, J.A. (2009). How to Select, Calculate, and Interpret Effect Sizes. Journal of Pediatric Psychology
Difference between Cohen's d and Hedges' g for effect size metrics To my understanding, Hedges's g is a somewhat more accurate version of Cohen's d (with pooled SD) in that we add a correction factor for small sample. Both measures generally agree when the homoscedas
8,509
Difference between Cohen's d and Hedges' g for effect size metrics
If you're just trying to understand the basic meaning of Hedges' g, as I am, you might also find this helpful: The magnitude of Hedges’ g may be interpreted using Cohen's (1988 [2]) convention as small (0.2), medium (0.5), and large (0.8). [1] Their definition is short and clear: Hedges’ g is a variation of Cohen's d that corrects for biases due to small sample sizes (Hedges & Olkin, 1985). [1] footnote I would appreciate statistics experts editing this to add any important caveats to the small (0.2) medium (0.5) and large (0.8) claim, to help nonexperts avoid misinterpreting Hedges' g numbers used in social science and psychology research. [1] http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2848393/ The Effect of Mindfulness-Based Therapy on Anxiety and Depression: A Meta-Analytic Review Stefan G. Hofmann, Alice T. Sawyer, Ashley A. Witt, and Diana Oh. J Consult Clin Psychol. 2010 April; 78(2): 169–183. doi: 10.1037/a0018555 [2] Cohen J. Statistical power analysis for the behavioral sciences. 2nd ed. Erlbaum; Hillsdale, NJ: 1988 (cited in [1])
Difference between Cohen's d and Hedges' g for effect size metrics
If you're just trying to understand the basic meaning of Hedges' g, as I am, you might also find this helpful: The magnitude of Hedges’ g may be interpreted using Cohen's (1988 [2]) convention as s
Difference between Cohen's d and Hedges' g for effect size metrics If you're just trying to understand the basic meaning of Hedges' g, as I am, you might also find this helpful: The magnitude of Hedges’ g may be interpreted using Cohen's (1988 [2]) convention as small (0.2), medium (0.5), and large (0.8). [1] Their definition is short and clear: Hedges’ g is a variation of Cohen's d that corrects for biases due to small sample sizes (Hedges & Olkin, 1985). [1] footnote I would appreciate statistics experts editing this to add any important caveats to the small (0.2) medium (0.5) and large (0.8) claim, to help nonexperts avoid misinterpreting Hedges' g numbers used in social science and psychology research. [1] http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2848393/ The Effect of Mindfulness-Based Therapy on Anxiety and Depression: A Meta-Analytic Review Stefan G. Hofmann, Alice T. Sawyer, Ashley A. Witt, and Diana Oh. J Consult Clin Psychol. 2010 April; 78(2): 169–183. doi: 10.1037/a0018555 [2] Cohen J. Statistical power analysis for the behavioral sciences. 2nd ed. Erlbaum; Hillsdale, NJ: 1988 (cited in [1])
Difference between Cohen's d and Hedges' g for effect size metrics If you're just trying to understand the basic meaning of Hedges' g, as I am, you might also find this helpful: The magnitude of Hedges’ g may be interpreted using Cohen's (1988 [2]) convention as s
8,510
Difference between Cohen's d and Hedges' g for effect size metrics
The other posters have covered the issue of similarities and differences between g and d. Just to add to this, some scholars do feel that the effect size values offered by Cohen are far too generous leading to overinterpretation of weak effects. They are also not tied to r leading to the possibility scholars may convert back and forth to obtain more favorably interpretable effect sizes. Ferguson (2009, Professional Psychology: Research and PRactice) suggested using the following values for interpretation for g: .41, as the recommended minimum for "practical significance." 1.15, moderate effect 2.70, strong effect These are obviously more rigorous/difficult to achieve and not many social science experiments are going to get to strong effects...which is probably how it should be.
Difference between Cohen's d and Hedges' g for effect size metrics
The other posters have covered the issue of similarities and differences between g and d. Just to add to this, some scholars do feel that the effect size values offered by Cohen are far too generous
Difference between Cohen's d and Hedges' g for effect size metrics The other posters have covered the issue of similarities and differences between g and d. Just to add to this, some scholars do feel that the effect size values offered by Cohen are far too generous leading to overinterpretation of weak effects. They are also not tied to r leading to the possibility scholars may convert back and forth to obtain more favorably interpretable effect sizes. Ferguson (2009, Professional Psychology: Research and PRactice) suggested using the following values for interpretation for g: .41, as the recommended minimum for "practical significance." 1.15, moderate effect 2.70, strong effect These are obviously more rigorous/difficult to achieve and not many social science experiments are going to get to strong effects...which is probably how it should be.
Difference between Cohen's d and Hedges' g for effect size metrics The other posters have covered the issue of similarities and differences between g and d. Just to add to this, some scholars do feel that the effect size values offered by Cohen are far too generous
8,511
Difference between Cohen's d and Hedges' g for effect size metrics
Bruce Thompson did warn about using Cohen's (0.2) as small (0.5) as medium and (0.8) as large. Cohen never meant for these to be used as rigid interpretations. All effect sizes must be interpreted based on the context of the related literature. If you are analyzing the related effect sizes reported on your topic and they are (0.1) (0.3) (0.24) and you produce an effect of (0.4) then that may be "large". Conversely, if all the related literature has effects of (0.5) (0.6) (0.7) and you have the effect of (0.4) it may be considered small. I know this is a trivial example but imperatively important. I believe Thompson once stated in a paper, "We would merely be stupid in a different metric" when comparing interpretations of effect sizes to how social scientists were interpreting p values at the time.
Difference between Cohen's d and Hedges' g for effect size metrics
Bruce Thompson did warn about using Cohen's (0.2) as small (0.5) as medium and (0.8) as large. Cohen never meant for these to be used as rigid interpretations. All effect sizes must be interpreted bas
Difference between Cohen's d and Hedges' g for effect size metrics Bruce Thompson did warn about using Cohen's (0.2) as small (0.5) as medium and (0.8) as large. Cohen never meant for these to be used as rigid interpretations. All effect sizes must be interpreted based on the context of the related literature. If you are analyzing the related effect sizes reported on your topic and they are (0.1) (0.3) (0.24) and you produce an effect of (0.4) then that may be "large". Conversely, if all the related literature has effects of (0.5) (0.6) (0.7) and you have the effect of (0.4) it may be considered small. I know this is a trivial example but imperatively important. I believe Thompson once stated in a paper, "We would merely be stupid in a different metric" when comparing interpretations of effect sizes to how social scientists were interpreting p values at the time.
Difference between Cohen's d and Hedges' g for effect size metrics Bruce Thompson did warn about using Cohen's (0.2) as small (0.5) as medium and (0.8) as large. Cohen never meant for these to be used as rigid interpretations. All effect sizes must be interpreted bas
8,512
Difference between Cohen's d and Hedges' g for effect size metrics
Effect size is measure of association, we should always describe the results in terms of measures of magnitude- our study result must be able to tell not just if treatment is effective or not but how much it is effective. Hedges’ g and Cohen's d are incredibly comparable. Both have an upwards predisposition (a swelling) in aftereffects of up to about 4%. The two insights are fundamentally the same as with the exception of when test sizes are underneath 20, when Hedges' g beats Cohen's d. Supports' g is consequently now and again called the remedied impact size. For very small sample sizes (<20) choose Hedges’ g over Cohen’s d. For sample sizes >20, the results for both statistics are roughly equivalent. Both Cohen’s d and Hedges g has same interpretation: Small effect (cannot be discerned by the naked eye) = 0.2 Medium Effect = 0.5 Large Effect (can be seen by the naked eye) = 0.8
Difference between Cohen's d and Hedges' g for effect size metrics
Effect size is measure of association, we should always describe the results in terms of measures of magnitude- our study result must be able to tell not just if treatment is effective or not but how
Difference between Cohen's d and Hedges' g for effect size metrics Effect size is measure of association, we should always describe the results in terms of measures of magnitude- our study result must be able to tell not just if treatment is effective or not but how much it is effective. Hedges’ g and Cohen's d are incredibly comparable. Both have an upwards predisposition (a swelling) in aftereffects of up to about 4%. The two insights are fundamentally the same as with the exception of when test sizes are underneath 20, when Hedges' g beats Cohen's d. Supports' g is consequently now and again called the remedied impact size. For very small sample sizes (<20) choose Hedges’ g over Cohen’s d. For sample sizes >20, the results for both statistics are roughly equivalent. Both Cohen’s d and Hedges g has same interpretation: Small effect (cannot be discerned by the naked eye) = 0.2 Medium Effect = 0.5 Large Effect (can be seen by the naked eye) = 0.8
Difference between Cohen's d and Hedges' g for effect size metrics Effect size is measure of association, we should always describe the results in terms of measures of magnitude- our study result must be able to tell not just if treatment is effective or not but how
8,513
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
It's safe to assume that without explicit base $\log=\ln$ in statistics, because base 10 log is not used very often in statistics. However, other posters bring up a point that $\log_{10}$ or other bases can be common in some other fields, where statistics is applied, e.g. information theory. So, when you read papers in other fields, it gets confusing at times. Wikipedia's entropy page is a good example of confusing usage of $\log$. In the same page they mean base 2, $e$ and any base. You can figure out by the context which one is meant, but it requires reading the text. This is not a good way to present the material. Compare it to Logarithm page where the base is clearly shown in every formula or $\ln$ is used. I personally think this is the way to go: always show the base when $\log$ sign is used. This would also be ISO compliant for the standard doesn't define usage of unspecified base with $\log$ symbol as @Henry pointed out. Finally, ISO 31-11 standard prescribes $\text{lb}$ and $\lg$ signs for base 2 and 10 logarithms. Both are rarely used these days. I remember that we used $\lg$ in high school, but that was in another century in another world. I have never seen it since used in a statistical context. There isn't even the tag for $\text{lb}$ in LaTeX.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
It's safe to assume that without explicit base $\log=\ln$ in statistics, because base 10 log is not used very often in statistics. However, other posters bring up a point that $\log_{10}$ or other bas
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? It's safe to assume that without explicit base $\log=\ln$ in statistics, because base 10 log is not used very often in statistics. However, other posters bring up a point that $\log_{10}$ or other bases can be common in some other fields, where statistics is applied, e.g. information theory. So, when you read papers in other fields, it gets confusing at times. Wikipedia's entropy page is a good example of confusing usage of $\log$. In the same page they mean base 2, $e$ and any base. You can figure out by the context which one is meant, but it requires reading the text. This is not a good way to present the material. Compare it to Logarithm page where the base is clearly shown in every formula or $\ln$ is used. I personally think this is the way to go: always show the base when $\log$ sign is used. This would also be ISO compliant for the standard doesn't define usage of unspecified base with $\log$ symbol as @Henry pointed out. Finally, ISO 31-11 standard prescribes $\text{lb}$ and $\lg$ signs for base 2 and 10 logarithms. Both are rarely used these days. I remember that we used $\lg$ in high school, but that was in another century in another world. I have never seen it since used in a statistical context. There isn't even the tag for $\text{lb}$ in LaTeX.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? It's safe to assume that without explicit base $\log=\ln$ in statistics, because base 10 log is not used very often in statistics. However, other posters bring up a point that $\log_{10}$ or other bas
8,514
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
It depends. Base 10 logarithms are pretty rare in equations. However, log-scale plots are often in base-10, though this should be pretty easy to verify from the labels on the axes. In a mathematical context, an unadorned $\log$ is likely to be the natural log (i.e., $\log_{e}$ or $\ln$). On the other hand, computer science often uses base-2 logarithms ($\log_2$), and they're not always clearly marked as such. The good news is that you can convert between bases trivially and using the "wrong" base will only make your answer off by a constant factor. In Gale's 1995 "Good-Turing Without Tears" paper, the logarithms in the text actually are $\log_{10}$ (it says so on page 5), but the R/S+ code in the appendix uses the log function, which is actually $\log_e$ or $\ln$. As @Henry points out below, this makes no practical difference. If I were forced to guess, here are some heuristics: If powers of 2, $e$, or 10 are also present, the logs are likely to have the corresponding base. If it arises from integrating $1/x$ (or, more generally, involves calculus), it's likely to be a natural log. If it arises from repeatedly dividing something in half (as in binary search), it's likely to be $\log_2$. More generally, something can be divided by $n$ approximately $\log_n$ times. Information-theoretic calculations typically use $\log_2$, especially in modern work. However, you can check the units to be sure: $\textrm{bits} \rightarrow \log_2$, $\textrm{nats} \rightarrow \ln$, and $\textrm{bans} \rightarrow \log_{10}$. Other unit-related clues include decibels (dB), which indicate $\log_{10}$ and octaves, which suggest $\log_2$. Finding the point where a function falls or rises to $\frac{1}{e} \textrm{ or } 1- \frac{1}{e}$, (37% and 63%, respectively) of an initial value suggests a natural log.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
It depends. Base 10 logarithms are pretty rare in equations. However, log-scale plots are often in base-10, though this should be pretty easy to verify from the labels on the axes. In a mathematical c
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? It depends. Base 10 logarithms are pretty rare in equations. However, log-scale plots are often in base-10, though this should be pretty easy to verify from the labels on the axes. In a mathematical context, an unadorned $\log$ is likely to be the natural log (i.e., $\log_{e}$ or $\ln$). On the other hand, computer science often uses base-2 logarithms ($\log_2$), and they're not always clearly marked as such. The good news is that you can convert between bases trivially and using the "wrong" base will only make your answer off by a constant factor. In Gale's 1995 "Good-Turing Without Tears" paper, the logarithms in the text actually are $\log_{10}$ (it says so on page 5), but the R/S+ code in the appendix uses the log function, which is actually $\log_e$ or $\ln$. As @Henry points out below, this makes no practical difference. If I were forced to guess, here are some heuristics: If powers of 2, $e$, or 10 are also present, the logs are likely to have the corresponding base. If it arises from integrating $1/x$ (or, more generally, involves calculus), it's likely to be a natural log. If it arises from repeatedly dividing something in half (as in binary search), it's likely to be $\log_2$. More generally, something can be divided by $n$ approximately $\log_n$ times. Information-theoretic calculations typically use $\log_2$, especially in modern work. However, you can check the units to be sure: $\textrm{bits} \rightarrow \log_2$, $\textrm{nats} \rightarrow \ln$, and $\textrm{bans} \rightarrow \log_{10}$. Other unit-related clues include decibels (dB), which indicate $\log_{10}$ and octaves, which suggest $\log_2$. Finding the point where a function falls or rises to $\frac{1}{e} \textrm{ or } 1- \frac{1}{e}$, (37% and 63%, respectively) of an initial value suggests a natural log.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? It depends. Base 10 logarithms are pretty rare in equations. However, log-scale plots are often in base-10, though this should be pretty easy to verify from the labels on the axes. In a mathematical c
8,515
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
To answer your question: no, you cannot assume a general fixed notation for the logarithm. A similar question was recently discussed in SE.Math: What is the difference between the three types of logarithms? from a mathematical point of view. Generally, there are different notations that depend on habits ($\log_{10}$ seems of use in medical research) or language (for instance in German, Russian, French). Unfortunately, the same notation sometimes ends up representing different definitions. Quoting from the above SE.Math link: Notation $\ln x$ (almost) unambiguously denotes the natural logarithm $\log_e x$ (latin: logarithmus naturalis), or logarithm in base $e$. The notation $\log x$ should be the adopted notation for the natural logarithm, and it is so in mathematics. However, it often represents the "most natural" depending on the field: I learned it as the base-$*10$ logarithm ($\log_{10}$) at school, and it is often used this way in engineering (for instance in the definition of decibels) Quite often, if you are not concerned with the meaning of physical units (like decibels @Matt Krause), nor interested in specific rates of change (in biostatistics, the $\log$-ratio for fold-change often denotes the base-$2$ logarithm $\log_2$), it is likely that the natural logarithm ($\log_e$) is used. For instance, in power or Box-Cox transforms (for variance stabilization), the natural logarithm appears as a limit when the exponent tends to $0$. Going back to your initial motivation, the Good-Turing Frequency Estimation, it is interesting to read The Population Frequencies of Species and the Estimation of Population Parameters, I. J. Good, Biometrika, 1953. Here, he used logarithmms in different contexts: variable transformation for variance stabilisation (mentioning Bartlett and Anscombe), sum of harmonic series, entropy. We see that he generally uses $\log$ as the natural logarithm, and once in a while in the paper specifies $\log_e$ or $\log_{10}$, when the context requires it. For variance stabilization, or basic entropy estimation, a factor on the logarithm does not change much the result, as the outcome allows a linear change.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
To answer your question: no, you cannot assume a general fixed notation for the logarithm. A similar question was recently discussed in SE.Math: What is the difference between the three types of logar
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? To answer your question: no, you cannot assume a general fixed notation for the logarithm. A similar question was recently discussed in SE.Math: What is the difference between the three types of logarithms? from a mathematical point of view. Generally, there are different notations that depend on habits ($\log_{10}$ seems of use in medical research) or language (for instance in German, Russian, French). Unfortunately, the same notation sometimes ends up representing different definitions. Quoting from the above SE.Math link: Notation $\ln x$ (almost) unambiguously denotes the natural logarithm $\log_e x$ (latin: logarithmus naturalis), or logarithm in base $e$. The notation $\log x$ should be the adopted notation for the natural logarithm, and it is so in mathematics. However, it often represents the "most natural" depending on the field: I learned it as the base-$*10$ logarithm ($\log_{10}$) at school, and it is often used this way in engineering (for instance in the definition of decibels) Quite often, if you are not concerned with the meaning of physical units (like decibels @Matt Krause), nor interested in specific rates of change (in biostatistics, the $\log$-ratio for fold-change often denotes the base-$2$ logarithm $\log_2$), it is likely that the natural logarithm ($\log_e$) is used. For instance, in power or Box-Cox transforms (for variance stabilization), the natural logarithm appears as a limit when the exponent tends to $0$. Going back to your initial motivation, the Good-Turing Frequency Estimation, it is interesting to read The Population Frequencies of Species and the Estimation of Population Parameters, I. J. Good, Biometrika, 1953. Here, he used logarithmms in different contexts: variable transformation for variance stabilisation (mentioning Bartlett and Anscombe), sum of harmonic series, entropy. We see that he generally uses $\log$ as the natural logarithm, and once in a while in the paper specifies $\log_e$ or $\log_{10}$, when the context requires it. For variance stabilization, or basic entropy estimation, a factor on the logarithm does not change much the result, as the outcome allows a linear change.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? To answer your question: no, you cannot assume a general fixed notation for the logarithm. A similar question was recently discussed in SE.Math: What is the difference between the three types of logar
8,516
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
In the Akaike Information Criterion the base is $e$, and $\ln(\hat L)$ of the maximum likelihood $\hat L$ is being compared additively to the number of parameters $k$: $$ \mathrm{AIC} = 2(k-\ln(L)).$$ Thus it seems that if you use any other base for the logarithm in the AIC, you may end up drawing the wrong conclusion and selecting the wrong model.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
In the Akaike Information Criterion the base is $e$, and $\ln(\hat L)$ of the maximum likelihood $\hat L$ is being compared additively to the number of parameters $k$: $$ \mathrm{AIC} = 2(k-\ln(L)).$$
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? In the Akaike Information Criterion the base is $e$, and $\ln(\hat L)$ of the maximum likelihood $\hat L$ is being compared additively to the number of parameters $k$: $$ \mathrm{AIC} = 2(k-\ln(L)).$$ Thus it seems that if you use any other base for the logarithm in the AIC, you may end up drawing the wrong conclusion and selecting the wrong model.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? In the Akaike Information Criterion the base is $e$, and $\ln(\hat L)$ of the maximum likelihood $\hat L$ is being compared additively to the number of parameters $k$: $$ \mathrm{AIC} = 2(k-\ln(L)).$$
8,517
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
For many applications, the natural logarithm of the likelihood function, called the log-likelihood, is more convenient to work with in our case." In statistics we often work with likelihood function, it is usually the ln that is considered. However, the two are related: log(x) = ln(x) / ln(10) = ln(x) / 2.303, and the ln-likelihood function reaches the extremum at the same point as log10-likelihood function. Note that an unadorned log even in the book by Hoggs means natural log. In(x) and loga(x) are identical up to a scaling factor. So they are the same only that you measure in another unit. . The unit is important , which I agree with. I also wrote loga to explicitly indicate the base. For (some) applications in statistics like maximimum likelihood, this scaling factor is however irrelavant hence yielding the same results as most statisticians allude.The maximum will not change after adding the scaling factor. This means that the unit changes on both axes of the plot so the plotted ''curve'' does not change. Unless you're writing a paper, even when using log-likelihood the scale (base of logarithm) usually matters. For instance, the log likelihood ratio test statistics uses ln, you'd have to adjust from other base to use the critical values. If you're writing software, it's important to get the base right when using log likelihood functions from papers etc😅. There's just too many cases where base is important to state that it doesn't matter.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
For many applications, the natural logarithm of the likelihood function, called the log-likelihood, is more convenient to work with in our case." In statistics we often work with likelihood function,
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? For many applications, the natural logarithm of the likelihood function, called the log-likelihood, is more convenient to work with in our case." In statistics we often work with likelihood function, it is usually the ln that is considered. However, the two are related: log(x) = ln(x) / ln(10) = ln(x) / 2.303, and the ln-likelihood function reaches the extremum at the same point as log10-likelihood function. Note that an unadorned log even in the book by Hoggs means natural log. In(x) and loga(x) are identical up to a scaling factor. So they are the same only that you measure in another unit. . The unit is important , which I agree with. I also wrote loga to explicitly indicate the base. For (some) applications in statistics like maximimum likelihood, this scaling factor is however irrelavant hence yielding the same results as most statisticians allude.The maximum will not change after adding the scaling factor. This means that the unit changes on both axes of the plot so the plotted ''curve'' does not change. Unless you're writing a paper, even when using log-likelihood the scale (base of logarithm) usually matters. For instance, the log likelihood ratio test statistics uses ln, you'd have to adjust from other base to use the critical values. If you're writing software, it's important to get the base right when using log likelihood functions from papers etc😅. There's just too many cases where base is important to state that it doesn't matter.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? For many applications, the natural logarithm of the likelihood function, called the log-likelihood, is more convenient to work with in our case." In statistics we often work with likelihood function,
8,518
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
it completely depends. and it is sometimes confusing! for example in the process of derivation of logistic regression cost function... Remember, when talking about log odds with logistic regression, we always mean the natural logarithm of the odds (Ln[Odds]). Natural log is often abbreviated as “log” or “ln,” which can cause some confusion. In some contexts (not in logistic regression), “log” can be used as an abbreviation for base 10 logarithms. However, if used in the context of logistic regression, “log” means the natural logarithm! Why is the natural log used instead of log base 10? Or log base 2? The short answer is tradition; that’s just the way it’s been done and so that’s how everyone does it. However, there are some interesting properties of the natural logarithm (and its inverse - the exponential function) that have contributed to its use over potential alternatives. For example, take the exponential function: exp(x) = ex The derivative of this function is… itself! Additionally, the derivative of Ln(x) = 1/x. These properties - among some other convenient attributes when dealing with growth rates, interest rates, decay rates, etc. - have made the natural logarithm the log of choice.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$?
it completely depends. and it is sometimes confusing! for example in the process of derivation of logistic regression cost function... Remember, when talking about log odds with logistic regression, w
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? it completely depends. and it is sometimes confusing! for example in the process of derivation of logistic regression cost function... Remember, when talking about log odds with logistic regression, we always mean the natural logarithm of the odds (Ln[Odds]). Natural log is often abbreviated as “log” or “ln,” which can cause some confusion. In some contexts (not in logistic regression), “log” can be used as an abbreviation for base 10 logarithms. However, if used in the context of logistic regression, “log” means the natural logarithm! Why is the natural log used instead of log base 10? Or log base 2? The short answer is tradition; that’s just the way it’s been done and so that’s how everyone does it. However, there are some interesting properties of the natural logarithm (and its inverse - the exponential function) that have contributed to its use over potential alternatives. For example, take the exponential function: exp(x) = ex The derivative of this function is… itself! Additionally, the derivative of Ln(x) = 1/x. These properties - among some other convenient attributes when dealing with growth rates, interest rates, decay rates, etc. - have made the natural logarithm the log of choice.
In statistics, should I assume $\log$ to mean $\log_{10}$ or the natural logarithm $\ln$? it completely depends. and it is sometimes confusing! for example in the process of derivation of logistic regression cost function... Remember, when talking about log odds with logistic regression, w
8,519
Imputation of missing values for PCA
There is in fact a well documented way to deal with gappy matrices - you can decompose a covariance matrix $\textbf{C}$ contructed from of your data $\textbf{X}$, which is scaled by the number of shared values $n$: $$ \textbf{C}=\frac{1}{n} \textbf{X} ^ {\text{T}} \textbf{X},~~~~~~~~~~~~~~~~ C_{jl} = \overline{X_{.j}Y_{.l}} $$ and then expand the principal coefficients via a least squares fit (as @user969113 mentions). Here's an example. However, there are several problems with this method relating to the fact that the covariance matrix is no longer semipositive definite and the eigen/singular values tend to be inflated. A nice review of these problems can be found in Beckers and Rixen (2003), where they also propose a method of optimally interpolating the missing gaps - DINEOF (Data Interpolating Empirical Orthogonal Functions). I have recently written a function that performs DINEOF, and it really seems to be a much better way to go. You could perform DINEOF on your your dataset $\textbf{X}$ directly, and then use the interpolated dataset as input into prcomp. Update Another option for conducting PCA on a gappy dataset is "Recursively Subtracted Empirical Orthogonal Functions" (Taylor et al. 2013). It also corrects for some of the problems in the least squares approach, and is computationally much faster than DINEOF. This post compares the all three approaches in terms of the accuracy of the data reconstruction using the PCs. References Beckers, Jean-Marie, and M. Rixen. "EOF Calculations and Data Filling from Incomplete Oceanographic Datasets." Journal of Atmospheric and Oceanic Technology 20.12 (2003): 1839-1856. Taylor, M., Losch, M., Wenzel, M., & Schröter, J. (2013). On the sensitivity of field reconstruction and prediction using Empirical Orthogonal Functions derived from gappy data. Journal of Climate, 26(22), 9194-9205.
Imputation of missing values for PCA
There is in fact a well documented way to deal with gappy matrices - you can decompose a covariance matrix $\textbf{C}$ contructed from of your data $\textbf{X}$, which is scaled by the number of shar
Imputation of missing values for PCA There is in fact a well documented way to deal with gappy matrices - you can decompose a covariance matrix $\textbf{C}$ contructed from of your data $\textbf{X}$, which is scaled by the number of shared values $n$: $$ \textbf{C}=\frac{1}{n} \textbf{X} ^ {\text{T}} \textbf{X},~~~~~~~~~~~~~~~~ C_{jl} = \overline{X_{.j}Y_{.l}} $$ and then expand the principal coefficients via a least squares fit (as @user969113 mentions). Here's an example. However, there are several problems with this method relating to the fact that the covariance matrix is no longer semipositive definite and the eigen/singular values tend to be inflated. A nice review of these problems can be found in Beckers and Rixen (2003), where they also propose a method of optimally interpolating the missing gaps - DINEOF (Data Interpolating Empirical Orthogonal Functions). I have recently written a function that performs DINEOF, and it really seems to be a much better way to go. You could perform DINEOF on your your dataset $\textbf{X}$ directly, and then use the interpolated dataset as input into prcomp. Update Another option for conducting PCA on a gappy dataset is "Recursively Subtracted Empirical Orthogonal Functions" (Taylor et al. 2013). It also corrects for some of the problems in the least squares approach, and is computationally much faster than DINEOF. This post compares the all three approaches in terms of the accuracy of the data reconstruction using the PCs. References Beckers, Jean-Marie, and M. Rixen. "EOF Calculations and Data Filling from Incomplete Oceanographic Datasets." Journal of Atmospheric and Oceanic Technology 20.12 (2003): 1839-1856. Taylor, M., Losch, M., Wenzel, M., & Schröter, J. (2013). On the sensitivity of field reconstruction and prediction using Empirical Orthogonal Functions derived from gappy data. Journal of Climate, 26(22), 9194-9205.
Imputation of missing values for PCA There is in fact a well documented way to deal with gappy matrices - you can decompose a covariance matrix $\textbf{C}$ contructed from of your data $\textbf{X}$, which is scaled by the number of shar
8,520
Imputation of missing values for PCA
A recent paper which reviews approaches for dealing with missing values in PCA analyses is "Principal component analysis with missing values: a comparative survey of methods" by Dray & Josse (2015). Two of the best known methods of PCA methods that allow for missing values are the NIPALS algorithm, implemented in the nipals function of the ade4 package, and the iterative PCA (Ipca or EM-PCA), implemented in the imputePCA function of the missMDA package. The paper concluded that the Ipca method performed best under the widest range of conditions. For your example syntax is : For NIPALS : library(ade4) nipals(d[,c(1,2)]) For Ipca : library(missMDA) imputePCA(d[,c(1,2)],method="EM",ncp=1)
Imputation of missing values for PCA
A recent paper which reviews approaches for dealing with missing values in PCA analyses is "Principal component analysis with missing values: a comparative survey of methods" by Dray & Josse (2015).
Imputation of missing values for PCA A recent paper which reviews approaches for dealing with missing values in PCA analyses is "Principal component analysis with missing values: a comparative survey of methods" by Dray & Josse (2015). Two of the best known methods of PCA methods that allow for missing values are the NIPALS algorithm, implemented in the nipals function of the ade4 package, and the iterative PCA (Ipca or EM-PCA), implemented in the imputePCA function of the missMDA package. The paper concluded that the Ipca method performed best under the widest range of conditions. For your example syntax is : For NIPALS : library(ade4) nipals(d[,c(1,2)]) For Ipca : library(missMDA) imputePCA(d[,c(1,2)],method="EM",ncp=1)
Imputation of missing values for PCA A recent paper which reviews approaches for dealing with missing values in PCA analyses is "Principal component analysis with missing values: a comparative survey of methods" by Dray & Josse (2015).
8,521
Imputation of missing values for PCA
My suggestion depends on how much data is missing and why it is missing. But this has nothing to do with PCA, really. If there is very little data missing, then it won't much matter what you do. Replacing with the median isn't ideal, but if there is not much missing, it won't be much different from a better solution. You could try doing PCA with both median replacement and listwise deletion and see if there are major differences in the results. Next, if there is more data missing, you should consider whether it is missing completely at random, missing at random, or not missing at random. I would suggest multiple imputation in the first two cases and some of the time in the third case - unless the data is highly distorted by its NMAR status, I think multiple imputation will be better than listwise deletion (Joe Schafer of Penn State has done a lot of work on missing data - I recall some work of his showing that multiple imputation worked pretty well even in some NMAR cases). However, if the data are MCAR or MAR, the properties of multiple imputation can be proven. If you do decide to go with MI, one note is to be careful because the signs of the components in PCA are arbitrary, and a small change in the data can flip a sign. Then when you do the PCA you will get nonsense. A long time ago I worked out a solution in SAS - it isn't hard, but it's something to be careful about.
Imputation of missing values for PCA
My suggestion depends on how much data is missing and why it is missing. But this has nothing to do with PCA, really. If there is very little data missing, then it won't much matter what you do. Repla
Imputation of missing values for PCA My suggestion depends on how much data is missing and why it is missing. But this has nothing to do with PCA, really. If there is very little data missing, then it won't much matter what you do. Replacing with the median isn't ideal, but if there is not much missing, it won't be much different from a better solution. You could try doing PCA with both median replacement and listwise deletion and see if there are major differences in the results. Next, if there is more data missing, you should consider whether it is missing completely at random, missing at random, or not missing at random. I would suggest multiple imputation in the first two cases and some of the time in the third case - unless the data is highly distorted by its NMAR status, I think multiple imputation will be better than listwise deletion (Joe Schafer of Penn State has done a lot of work on missing data - I recall some work of his showing that multiple imputation worked pretty well even in some NMAR cases). However, if the data are MCAR or MAR, the properties of multiple imputation can be proven. If you do decide to go with MI, one note is to be careful because the signs of the components in PCA are arbitrary, and a small change in the data can flip a sign. Then when you do the PCA you will get nonsense. A long time ago I worked out a solution in SAS - it isn't hard, but it's something to be careful about.
Imputation of missing values for PCA My suggestion depends on how much data is missing and why it is missing. But this has nothing to do with PCA, really. If there is very little data missing, then it won't much matter what you do. Repla
8,522
Imputation of missing values for PCA
You could solve the problem of the missing value in different way. Below I'm going to illustrate them. You should use the mean of the variable that includes NA values or impute the missing values with a linear regression. You should use missMDA and then FactoMineR or the pcaMethods. Below an example. library(missMDA) nPCs <- estim_ncpPCA(VIM::sleep) Output nPCS$ncp 3 completed_sleep <- imputePCA(VIM::sleep, ncp = nPCs$ncp, scale = TRUE) PCA(completed_sleep$completeObs) The other example is: library(pcaMethods) sleep_pca_methods <- pca(sleep, nPcs=2, method="ppca", center = TRUE) imp_air_pcamethods <- completeObs(sleep_pca_methods) If you'd like to deep the PCA or the factoMiner package you should visit its website http://factominer.free.fr/
Imputation of missing values for PCA
You could solve the problem of the missing value in different way. Below I'm going to illustrate them. You should use the mean of the variable that includes NA values or impute the missing values wi
Imputation of missing values for PCA You could solve the problem of the missing value in different way. Below I'm going to illustrate them. You should use the mean of the variable that includes NA values or impute the missing values with a linear regression. You should use missMDA and then FactoMineR or the pcaMethods. Below an example. library(missMDA) nPCs <- estim_ncpPCA(VIM::sleep) Output nPCS$ncp 3 completed_sleep <- imputePCA(VIM::sleep, ncp = nPCs$ncp, scale = TRUE) PCA(completed_sleep$completeObs) The other example is: library(pcaMethods) sleep_pca_methods <- pca(sleep, nPcs=2, method="ppca", center = TRUE) imp_air_pcamethods <- completeObs(sleep_pca_methods) If you'd like to deep the PCA or the factoMiner package you should visit its website http://factominer.free.fr/
Imputation of missing values for PCA You could solve the problem of the missing value in different way. Below I'm going to illustrate them. You should use the mean of the variable that includes NA values or impute the missing values wi
8,523
Imputation of missing values for PCA
There is no correct solution to the problem. Every coordinate in the vector has to be specified to get the correct set of principal components. If a coordinate is missing and replaced by some imputed value you will get a result but it will be dependent on the imputed value. so if there are two reasonable choices for the imputed value the different choices will give different answers.
Imputation of missing values for PCA
There is no correct solution to the problem. Every coordinate in the vector has to be specified to get the correct set of principal components. If a coordinate is missing and replaced by some impute
Imputation of missing values for PCA There is no correct solution to the problem. Every coordinate in the vector has to be specified to get the correct set of principal components. If a coordinate is missing and replaced by some imputed value you will get a result but it will be dependent on the imputed value. so if there are two reasonable choices for the imputed value the different choices will give different answers.
Imputation of missing values for PCA There is no correct solution to the problem. Every coordinate in the vector has to be specified to get the correct set of principal components. If a coordinate is missing and replaced by some impute
8,524
Why does Bayesian Optimization perform poorly in more than 20 Dimensions?
To be completely honest, it's because everything performs poorly in more than 20 dimensions. Bayesian optimization isn't special here. Trying to optimize any function in a lot of dimensions is hard, because the volume of a high-dimensional space goes up exponentially with the number of dimensions. Consider a line segment on $[0, k]$; that has length $k$. A unit square? That has area $k^2$. And so on. So the amount of space that you have to search when you're looking for a possible solution goes up very, very, fast. I recommend looking up the term "Curse of Dimensionality" for more. This will always be true, regardless of what algorithm you use -- unless you're willing to make some strong simplifying assumptions about the shape of that function. For example, gradient descent can do quite well in high dimensions -- as long as your function is convex and differentiable. If you have a function where the gradient is 0 somewhere besides the minimum, you're screwed. And if you have a function with multiple minima, you're screwed. Bayesian optimization is exactly the same. The papers you've linked point out that if your function has an interesting structure, you can exploit this by picking good priors. Namely, you need to assume sparsity (that only a few of those dimensions are important and the rest can be ignored), or differentiability, in which case you can use gradient-enhanced Gaussian processes. But if you don't have that structure, you're screwed. As for 20 dimensions, that's a rule of thumb. There's no "threshold" or anything, but it gets hard exponentially quickly.
Why does Bayesian Optimization perform poorly in more than 20 Dimensions?
To be completely honest, it's because everything performs poorly in more than 20 dimensions. Bayesian optimization isn't special here. Trying to optimize any function in a lot of dimensions is hard, b
Why does Bayesian Optimization perform poorly in more than 20 Dimensions? To be completely honest, it's because everything performs poorly in more than 20 dimensions. Bayesian optimization isn't special here. Trying to optimize any function in a lot of dimensions is hard, because the volume of a high-dimensional space goes up exponentially with the number of dimensions. Consider a line segment on $[0, k]$; that has length $k$. A unit square? That has area $k^2$. And so on. So the amount of space that you have to search when you're looking for a possible solution goes up very, very, fast. I recommend looking up the term "Curse of Dimensionality" for more. This will always be true, regardless of what algorithm you use -- unless you're willing to make some strong simplifying assumptions about the shape of that function. For example, gradient descent can do quite well in high dimensions -- as long as your function is convex and differentiable. If you have a function where the gradient is 0 somewhere besides the minimum, you're screwed. And if you have a function with multiple minima, you're screwed. Bayesian optimization is exactly the same. The papers you've linked point out that if your function has an interesting structure, you can exploit this by picking good priors. Namely, you need to assume sparsity (that only a few of those dimensions are important and the rest can be ignored), or differentiability, in which case you can use gradient-enhanced Gaussian processes. But if you don't have that structure, you're screwed. As for 20 dimensions, that's a rule of thumb. There's no "threshold" or anything, but it gets hard exponentially quickly.
Why does Bayesian Optimization perform poorly in more than 20 Dimensions? To be completely honest, it's because everything performs poorly in more than 20 dimensions. Bayesian optimization isn't special here. Trying to optimize any function in a lot of dimensions is hard, b
8,525
Why does Bayesian Optimization perform poorly in more than 20 Dimensions?
You will not find a theoretical/scientific justification for this statement as there is none! The difficulty of optimisation is related to a lot of things, dimension being just one of them and most likely not even a very important one. For example, if you just assume continuity and not differentiability of your objective function the question of the dimension of the domain becomes completely moot anyway. Using space filling curves you can always reparametrise an $n$-dimensional function to one of a single variable. So it is really easy to find one-dimensional functions which are impossible to optimise using BO. And it is also easy to find functions in hundreds or even thousands dimension which are simple to optimise, be it Bayesian or otherwise. Then why do some people make such statements and why do others believe them? I think there are two reasons for this: They are (in those cases the researcher is interested in or knows about) a good heuristic. The full qualification of those statements is just too long and would contain too many complicated "purely theoretical" qualifications. And many of those qualifications are probably "obvious" to people working in the field, they "go without saying".
Why does Bayesian Optimization perform poorly in more than 20 Dimensions?
You will not find a theoretical/scientific justification for this statement as there is none! The difficulty of optimisation is related to a lot of things, dimension being just one of them and most li
Why does Bayesian Optimization perform poorly in more than 20 Dimensions? You will not find a theoretical/scientific justification for this statement as there is none! The difficulty of optimisation is related to a lot of things, dimension being just one of them and most likely not even a very important one. For example, if you just assume continuity and not differentiability of your objective function the question of the dimension of the domain becomes completely moot anyway. Using space filling curves you can always reparametrise an $n$-dimensional function to one of a single variable. So it is really easy to find one-dimensional functions which are impossible to optimise using BO. And it is also easy to find functions in hundreds or even thousands dimension which are simple to optimise, be it Bayesian or otherwise. Then why do some people make such statements and why do others believe them? I think there are two reasons for this: They are (in those cases the researcher is interested in or knows about) a good heuristic. The full qualification of those statements is just too long and would contain too many complicated "purely theoretical" qualifications. And many of those qualifications are probably "obvious" to people working in the field, they "go without saying".
Why does Bayesian Optimization perform poorly in more than 20 Dimensions? You will not find a theoretical/scientific justification for this statement as there is none! The difficulty of optimisation is related to a lot of things, dimension being just one of them and most li
8,526
Why does Bayesian Optimization perform poorly in more than 20 Dimensions?
Yes, high dimensional space is tough in general, but there a couple things that make Bayesian optimization with Gaussian processes particularly perplexing on those prickly problems. In my view, there isn't a single reason high dimension makes BO difficult, but the difficulty is rather due to a confluence of multiple factors. Firstly, Bayesian optimization is classically conducted with a Gaussian process using something like a squared exponential kernel. This is a kernel which gives great flexibility which is perfect in low dimension but can become a liability in high dimension, as it puts reasonable probability mass on too many explanations of the point cloud. So the first issue is that the model we're using is already struggling to understand what's going on. This is related to the volume argument from the other answer. Since GPs depend explicitly on distances, when all interpoint distances are equal and large, the GP has little discrimination power. See how as we go into higher dimension, the distances between random points vary less than in low dimension: ["A survey on high-dimensional Gaussian process modeling with application to Bayesian optimization" by Mickaël Binois and Nathan Wycoff ] As you mention, putting structure into the kernel function so that we are learning a mapping into a low dimensional space onto which we put a "standard" gaussian process is a good way to go here. Another option is to assume a kernel function which combines information from input dimensions in a more frugal manner, such as additive (Additive Gaussian Processes Part of Advances in Neural Information Processing Systems 24 (NIPS 2011) by David K. Duvenaud, Hannes Nickisch, Carl Rasmussen) or ANOVA kernels ("ANOVA decomposition of conditional Gaussian processes for sensitivity analysis with dependent inputs" Gaëlle Chastaing, Loic Le Gratiet). Secondly, we can't forget about the fact that BO is a nested optimization procedure: every time a BO algorithm wants to suggest a next point to optimize, it has to solve an entire sub-optimization problem over the entire space! Unlike the original optimization problem, the acquisition function defined by our Gaussian process (whose optimizing point is our next candidate in our outer search) usually has a known gradient and Hessian, which is indeed helpful in finding a local solution. However, the acquisition function is notoriously nonconvex, which means that in high dimensional spaces, however quickly we can find a local optimum, we may have little chance of finding anything close to a global optimum without considerable effort. Though this doesn't impact the ability of the Gaussian process to model the unknown objective, it does impact our ability to exploit its knowledge for optimization. When combined with kernel shenanigans, sometimes the acquisition function can be optimized in a lower dimensional space, which can make things easier (or sometimes harder in practice; linear dimension reduction means we're doing linear programming rather than unconstrained optimization now and also doesn't vibe well with hyperbox constraints). And third is the hyperparameter estimation risk. Most popular these days are "separable", "ARD", "tensor product" or otherwise axis-aligned anisotropic kernels which look something like $k(\mathbf{x}_1,\mathbf{x}_2) = \sigma^2 e^{\sum_{p=1}^P \frac{(x_{1,p}-x_{2,p})^2}{2\ell_p}}$, so we have one additional thing to estimate for each input dimension, and estimating gaussian process hyperparameters is tough, both from a statistical inference perspective and numerical analytic one. Using a parameterized mapping into low dimension only makes the estimation risk worse (but may be offset by a substantially lower variance class of functions a priori). Fourth: Computation Time. GPs are known for their small data statistical efficiency (in terms of error/data) and large data computational inefficiency (in terms of inference / second). In high dimension, if we really want to find a global optimum, we are probably going to have to evaluate the objective function tons of times, and thus have a large dataset for our GP to consider. This is simply not been the GPs historical niche, as classical, decomposition-based GP (i.e. where you actually take a Cholesky of the kernel matrix) inference scales with $n^3$ so gets intractable quickly. Optimization of the acquisition function also only gets more expensive as $n$ goes up too. And keep in mind that you have to do this between every optimization iteration. So if we have an optimization budget of $10,000$, naively we would need to do all this numerical optimization literally $10,000-n_{\textrm{init}}$ times (though of course in practice we would evaluate batches of points at a time as well as only optimize hyperparams every few iters). Large scale GP inference in high dimension has really matured over the last few decades, however, and have been the engine of some of the recent large scale GP-BO papers recently.
Why does Bayesian Optimization perform poorly in more than 20 Dimensions?
Yes, high dimensional space is tough in general, but there a couple things that make Bayesian optimization with Gaussian processes particularly perplexing on those prickly problems. In my view, there
Why does Bayesian Optimization perform poorly in more than 20 Dimensions? Yes, high dimensional space is tough in general, but there a couple things that make Bayesian optimization with Gaussian processes particularly perplexing on those prickly problems. In my view, there isn't a single reason high dimension makes BO difficult, but the difficulty is rather due to a confluence of multiple factors. Firstly, Bayesian optimization is classically conducted with a Gaussian process using something like a squared exponential kernel. This is a kernel which gives great flexibility which is perfect in low dimension but can become a liability in high dimension, as it puts reasonable probability mass on too many explanations of the point cloud. So the first issue is that the model we're using is already struggling to understand what's going on. This is related to the volume argument from the other answer. Since GPs depend explicitly on distances, when all interpoint distances are equal and large, the GP has little discrimination power. See how as we go into higher dimension, the distances between random points vary less than in low dimension: ["A survey on high-dimensional Gaussian process modeling with application to Bayesian optimization" by Mickaël Binois and Nathan Wycoff ] As you mention, putting structure into the kernel function so that we are learning a mapping into a low dimensional space onto which we put a "standard" gaussian process is a good way to go here. Another option is to assume a kernel function which combines information from input dimensions in a more frugal manner, such as additive (Additive Gaussian Processes Part of Advances in Neural Information Processing Systems 24 (NIPS 2011) by David K. Duvenaud, Hannes Nickisch, Carl Rasmussen) or ANOVA kernels ("ANOVA decomposition of conditional Gaussian processes for sensitivity analysis with dependent inputs" Gaëlle Chastaing, Loic Le Gratiet). Secondly, we can't forget about the fact that BO is a nested optimization procedure: every time a BO algorithm wants to suggest a next point to optimize, it has to solve an entire sub-optimization problem over the entire space! Unlike the original optimization problem, the acquisition function defined by our Gaussian process (whose optimizing point is our next candidate in our outer search) usually has a known gradient and Hessian, which is indeed helpful in finding a local solution. However, the acquisition function is notoriously nonconvex, which means that in high dimensional spaces, however quickly we can find a local optimum, we may have little chance of finding anything close to a global optimum without considerable effort. Though this doesn't impact the ability of the Gaussian process to model the unknown objective, it does impact our ability to exploit its knowledge for optimization. When combined with kernel shenanigans, sometimes the acquisition function can be optimized in a lower dimensional space, which can make things easier (or sometimes harder in practice; linear dimension reduction means we're doing linear programming rather than unconstrained optimization now and also doesn't vibe well with hyperbox constraints). And third is the hyperparameter estimation risk. Most popular these days are "separable", "ARD", "tensor product" or otherwise axis-aligned anisotropic kernels which look something like $k(\mathbf{x}_1,\mathbf{x}_2) = \sigma^2 e^{\sum_{p=1}^P \frac{(x_{1,p}-x_{2,p})^2}{2\ell_p}}$, so we have one additional thing to estimate for each input dimension, and estimating gaussian process hyperparameters is tough, both from a statistical inference perspective and numerical analytic one. Using a parameterized mapping into low dimension only makes the estimation risk worse (but may be offset by a substantially lower variance class of functions a priori). Fourth: Computation Time. GPs are known for their small data statistical efficiency (in terms of error/data) and large data computational inefficiency (in terms of inference / second). In high dimension, if we really want to find a global optimum, we are probably going to have to evaluate the objective function tons of times, and thus have a large dataset for our GP to consider. This is simply not been the GPs historical niche, as classical, decomposition-based GP (i.e. where you actually take a Cholesky of the kernel matrix) inference scales with $n^3$ so gets intractable quickly. Optimization of the acquisition function also only gets more expensive as $n$ goes up too. And keep in mind that you have to do this between every optimization iteration. So if we have an optimization budget of $10,000$, naively we would need to do all this numerical optimization literally $10,000-n_{\textrm{init}}$ times (though of course in practice we would evaluate batches of points at a time as well as only optimize hyperparams every few iters). Large scale GP inference in high dimension has really matured over the last few decades, however, and have been the engine of some of the recent large scale GP-BO papers recently.
Why does Bayesian Optimization perform poorly in more than 20 Dimensions? Yes, high dimensional space is tough in general, but there a couple things that make Bayesian optimization with Gaussian processes particularly perplexing on those prickly problems. In my view, there
8,527
Can I trust ANOVA results for a non-normally distributed DV?
Like other parametric tests, the analysis of variance assumes that the data fit the normal distribution. If your measurement variable is not normally distributed, you may be increasing your chance of a false positive result if you analyze the data with an anova or other test that assumes normality. Fortunately, an anova is not very sensitive to moderate deviations from normality; simulation studies, using a variety of non-normal distributions, have shown that the false positive rate is not affected very much by this violation of the assumption (Glass et al. 1972, Harwell et al. 1992, Lix et al. 1996). This is because when you take a large number of random samples from a population, the means of those samples are approximately normally distributed even when the population is not normal. It is possible to test the goodness-of-fit of a data set to the normal distribution. I do not suggest that you do this, because many data sets that are significantly non-normal would be perfectly appropriate for an anova. Instead, if you have a large enough data set, I suggest you just look at the frequency histogram. If it looks more-or-less normal, go ahead and perform an anova. If it looks like a normal distribution that has been pushed to one side, like the sulphate data above, you should try different data transformations and see if any of them make the histogram look more normal. If that doesn't work, and the data still look severely non-normal, it's probably still okay to analyze the data using an anova. However, you may want to analyze it using a non-parametric test. Just about every parametric statistical test has a non-parametric substitute, such as the Kruskal–Wallis test instead of a one-way anova, Wilcoxon signed-rank test instead of a paired t-test, and Spearman rank correlation instead of linear regression. These non-parametric tests do not assume that the data fit the normal distribution. They do assume that the data in different groups have the same distribution as each other, however; if different groups have different shaped distributions (for example, one is skewed to the left, another is skewed to the right), a non-parametric test may not be any better than a parametric one. References Glass, G.V., P.D. Peckham, and J.R. Sanders. 1972. Consequences of failure to meet assumptions underlying fixed effects analyses of variance and covariance. Rev. Educ. Res. 42: 237-288. Harwell, M.R., E.N. Rubinstein, W.S. Hayes, and C.C. Olds. 1992. Summarizing Monte Carlo results in methodological research: the one- and two-factor fixed effects ANOVA cases. J. Educ. Stat. 17: 315-339. Lix, L.M., J.C. Keselman, and H.J. Keselman. 1996. Consequences of assumption violations revisited: A quantitative review of alternatives to the one-way analysis of variance F test. Rev. Educ. Res. 66: 579-619.
Can I trust ANOVA results for a non-normally distributed DV?
Like other parametric tests, the analysis of variance assumes that the data fit the normal distribution. If your measurement variable is not normally distributed, you may be increasing your chance of
Can I trust ANOVA results for a non-normally distributed DV? Like other parametric tests, the analysis of variance assumes that the data fit the normal distribution. If your measurement variable is not normally distributed, you may be increasing your chance of a false positive result if you analyze the data with an anova or other test that assumes normality. Fortunately, an anova is not very sensitive to moderate deviations from normality; simulation studies, using a variety of non-normal distributions, have shown that the false positive rate is not affected very much by this violation of the assumption (Glass et al. 1972, Harwell et al. 1992, Lix et al. 1996). This is because when you take a large number of random samples from a population, the means of those samples are approximately normally distributed even when the population is not normal. It is possible to test the goodness-of-fit of a data set to the normal distribution. I do not suggest that you do this, because many data sets that are significantly non-normal would be perfectly appropriate for an anova. Instead, if you have a large enough data set, I suggest you just look at the frequency histogram. If it looks more-or-less normal, go ahead and perform an anova. If it looks like a normal distribution that has been pushed to one side, like the sulphate data above, you should try different data transformations and see if any of them make the histogram look more normal. If that doesn't work, and the data still look severely non-normal, it's probably still okay to analyze the data using an anova. However, you may want to analyze it using a non-parametric test. Just about every parametric statistical test has a non-parametric substitute, such as the Kruskal–Wallis test instead of a one-way anova, Wilcoxon signed-rank test instead of a paired t-test, and Spearman rank correlation instead of linear regression. These non-parametric tests do not assume that the data fit the normal distribution. They do assume that the data in different groups have the same distribution as each other, however; if different groups have different shaped distributions (for example, one is skewed to the left, another is skewed to the right), a non-parametric test may not be any better than a parametric one. References Glass, G.V., P.D. Peckham, and J.R. Sanders. 1972. Consequences of failure to meet assumptions underlying fixed effects analyses of variance and covariance. Rev. Educ. Res. 42: 237-288. Harwell, M.R., E.N. Rubinstein, W.S. Hayes, and C.C. Olds. 1992. Summarizing Monte Carlo results in methodological research: the one- and two-factor fixed effects ANOVA cases. J. Educ. Stat. 17: 315-339. Lix, L.M., J.C. Keselman, and H.J. Keselman. 1996. Consequences of assumption violations revisited: A quantitative review of alternatives to the one-way analysis of variance F test. Rev. Educ. Res. 66: 579-619.
Can I trust ANOVA results for a non-normally distributed DV? Like other parametric tests, the analysis of variance assumes that the data fit the normal distribution. If your measurement variable is not normally distributed, you may be increasing your chance of
8,528
Can I trust ANOVA results for a non-normally distributed DV?
Specifically regarding error rates as a DV, Dixon (2008) very cogently demonstrates that null hypothesis testing via ANOVA can cause both increased false alarm rates (calling effects "significant" when they're not) and increased miss rates (missing real effects). He also shows that mixed effects modelling, specifying binomially distributed error, is the more appropriate approach to analyzing rate data.
Can I trust ANOVA results for a non-normally distributed DV?
Specifically regarding error rates as a DV, Dixon (2008) very cogently demonstrates that null hypothesis testing via ANOVA can cause both increased false alarm rates (calling effects "significant" whe
Can I trust ANOVA results for a non-normally distributed DV? Specifically regarding error rates as a DV, Dixon (2008) very cogently demonstrates that null hypothesis testing via ANOVA can cause both increased false alarm rates (calling effects "significant" when they're not) and increased miss rates (missing real effects). He also shows that mixed effects modelling, specifying binomially distributed error, is the more appropriate approach to analyzing rate data.
Can I trust ANOVA results for a non-normally distributed DV? Specifically regarding error rates as a DV, Dixon (2008) very cogently demonstrates that null hypothesis testing via ANOVA can cause both increased false alarm rates (calling effects "significant" whe
8,529
Can I trust ANOVA results for a non-normally distributed DV?
You cannot trust your ANOVA with that much skew and a large number of 0s. A more appropriate method would be to use number of errors as your DV (thus turning your DV into count data) and doing a Poisson analysis. This approach would require using a mixed effects analysis and specifying the error distribution family as Poisson. The Dixon (2008)* article mentioned by Mike Lawrence uses mixed effects analysis in R but with binomial outcomes. I have completely moved to doing R for most of my repeated measures analyses because so many of my outcome variables are binomial. The appropriate R package is lme4. $*$ Dixon, P. (2008). Models of accuracy in repeated-measures designs. Journal of Memory and Language, 59(4), 447-456.
Can I trust ANOVA results for a non-normally distributed DV?
You cannot trust your ANOVA with that much skew and a large number of 0s. A more appropriate method would be to use number of errors as your DV (thus turning your DV into count data) and doing a Pois
Can I trust ANOVA results for a non-normally distributed DV? You cannot trust your ANOVA with that much skew and a large number of 0s. A more appropriate method would be to use number of errors as your DV (thus turning your DV into count data) and doing a Poisson analysis. This approach would require using a mixed effects analysis and specifying the error distribution family as Poisson. The Dixon (2008)* article mentioned by Mike Lawrence uses mixed effects analysis in R but with binomial outcomes. I have completely moved to doing R for most of my repeated measures analyses because so many of my outcome variables are binomial. The appropriate R package is lme4. $*$ Dixon, P. (2008). Models of accuracy in repeated-measures designs. Journal of Memory and Language, 59(4), 447-456.
Can I trust ANOVA results for a non-normally distributed DV? You cannot trust your ANOVA with that much skew and a large number of 0s. A more appropriate method would be to use number of errors as your DV (thus turning your DV into count data) and doing a Pois
8,530
Can I trust ANOVA results for a non-normally distributed DV?
Juan has offered a lot, although I'll echo others and repeat that for best accuracy the variables themselves can be nonnormal as long as their residuals aren't. Also, a simplified and slightly more structured answer (via an annotated flow chart) is available at yellowbrickstats.com.
Can I trust ANOVA results for a non-normally distributed DV?
Juan has offered a lot, although I'll echo others and repeat that for best accuracy the variables themselves can be nonnormal as long as their residuals aren't. Also, a simplified and slightly more s
Can I trust ANOVA results for a non-normally distributed DV? Juan has offered a lot, although I'll echo others and repeat that for best accuracy the variables themselves can be nonnormal as long as their residuals aren't. Also, a simplified and slightly more structured answer (via an annotated flow chart) is available at yellowbrickstats.com.
Can I trust ANOVA results for a non-normally distributed DV? Juan has offered a lot, although I'll echo others and repeat that for best accuracy the variables themselves can be nonnormal as long as their residuals aren't. Also, a simplified and slightly more s
8,531
Can I trust ANOVA results for a non-normally distributed DV?
Ceiling effects are the problem here. A non parametric test is your safest bet, although ANOVAs are robust to this violation of normality if n is large. Typically people just use a histogram to test this, but if the issue is with residuals it might be more advanced than that. Also bear in mind HOW this effects your results (not just that it does). Pallant (2007) would probably say this increases your chance of type one error, so if you reduce your critical alpha you mitigate that.
Can I trust ANOVA results for a non-normally distributed DV?
Ceiling effects are the problem here. A non parametric test is your safest bet, although ANOVAs are robust to this violation of normality if n is large. Typically people just use a histogram to test t
Can I trust ANOVA results for a non-normally distributed DV? Ceiling effects are the problem here. A non parametric test is your safest bet, although ANOVAs are robust to this violation of normality if n is large. Typically people just use a histogram to test this, but if the issue is with residuals it might be more advanced than that. Also bear in mind HOW this effects your results (not just that it does). Pallant (2007) would probably say this increases your chance of type one error, so if you reduce your critical alpha you mitigate that.
Can I trust ANOVA results for a non-normally distributed DV? Ceiling effects are the problem here. A non parametric test is your safest bet, although ANOVAs are robust to this violation of normality if n is large. Typically people just use a histogram to test t
8,532
When should we discretize/bin continuous independent variables/features and when should not?
Aggregation is substantively meaningful (whether or not the researcher is aware of that). One should bin data, including independent variables, based on the data itself when one wants: To hemorrhage statistical power. To bias measures of association. A literature starting, I believe, with Ghelke and Biehl (1934—definitely worth a read, and suggestive of some easy enough computer simulations that one can run for one's self), and continuing especially in the 'modifiable areal unit problem' literature (Openshaw, 1983; Dudley, 1991; Lee and Kemp, 2000) makes both these points clear. Unless one has an a priori theory of the scale of aggregation (how many units to aggregate to) and the categorization function of aggregation (which individual observations will end up in which aggregate units), one should not aggregate. For example, in epidemiology, we care about the health of individuals, and about the health of populations. The latter are not simply random collections of the former, but defined by, for example, geopolitical boundaries, social circumstances like race-ethnic categorization, carceral status and history categories, etc. (See, for example Krieger, 2012) References Dudley, G. (1991). Scale, aggregation, and the modifiable areal unit problem. [pay-walled] The Operational Geographer, 9(3):28–33. Gehlke, C. E. and Biehl, K. (1934). Certain Effects of Grouping Upon the Size of the Correlation Coefficient in Census Tract Material. [pay-walled] Journal of the American Statistical Association, 29(185):169–170. Krieger, N. (2012). Who and what is a “population”? historical debates, current controversies, and implications for understanding “population health” and rectifying health inequities. The Milbank Quarterly, 90(4):634–681. Lee, H. T. K. and Kemp, Z. (2000). Hierarchical reasoning and on-line analytical processing of spatial and temporal data. In Proceedings of the 9th International Symposium on Spatial Data Handling, Beijing, P.R. China. International Geographic Union. Openshaw, S. (1983). The modifiable areal unit problem. Concepts and Techniques in Modern Geography. Geo Books, Norwich, UK.
When should we discretize/bin continuous independent variables/features and when should not?
Aggregation is substantively meaningful (whether or not the researcher is aware of that). One should bin data, including independent variables, based on the data itself when one wants: To hemorrhage
When should we discretize/bin continuous independent variables/features and when should not? Aggregation is substantively meaningful (whether or not the researcher is aware of that). One should bin data, including independent variables, based on the data itself when one wants: To hemorrhage statistical power. To bias measures of association. A literature starting, I believe, with Ghelke and Biehl (1934—definitely worth a read, and suggestive of some easy enough computer simulations that one can run for one's self), and continuing especially in the 'modifiable areal unit problem' literature (Openshaw, 1983; Dudley, 1991; Lee and Kemp, 2000) makes both these points clear. Unless one has an a priori theory of the scale of aggregation (how many units to aggregate to) and the categorization function of aggregation (which individual observations will end up in which aggregate units), one should not aggregate. For example, in epidemiology, we care about the health of individuals, and about the health of populations. The latter are not simply random collections of the former, but defined by, for example, geopolitical boundaries, social circumstances like race-ethnic categorization, carceral status and history categories, etc. (See, for example Krieger, 2012) References Dudley, G. (1991). Scale, aggregation, and the modifiable areal unit problem. [pay-walled] The Operational Geographer, 9(3):28–33. Gehlke, C. E. and Biehl, K. (1934). Certain Effects of Grouping Upon the Size of the Correlation Coefficient in Census Tract Material. [pay-walled] Journal of the American Statistical Association, 29(185):169–170. Krieger, N. (2012). Who and what is a “population”? historical debates, current controversies, and implications for understanding “population health” and rectifying health inequities. The Milbank Quarterly, 90(4):634–681. Lee, H. T. K. and Kemp, Z. (2000). Hierarchical reasoning and on-line analytical processing of spatial and temporal data. In Proceedings of the 9th International Symposium on Spatial Data Handling, Beijing, P.R. China. International Geographic Union. Openshaw, S. (1983). The modifiable areal unit problem. Concepts and Techniques in Modern Geography. Geo Books, Norwich, UK.
When should we discretize/bin continuous independent variables/features and when should not? Aggregation is substantively meaningful (whether or not the researcher is aware of that). One should bin data, including independent variables, based on the data itself when one wants: To hemorrhage
8,533
When should we discretize/bin continuous independent variables/features and when should not?
Looks like you're also looking for an answer from a predictive standpoint, so I put together a short demonstration of two approaches in R Binning a variable into equal sized factors. Natural cubic splines. Below, I've given the code for a function that will compare the two methods automatically for any given true signal function test_cuts_vs_splines <- function(signal, N, noise, range=c(0, 1), max_parameters=50, seed=154) This function will create noisy training and testing datasets from a given signal, and then fit a series of linear regressions to the training data of two types The cuts model includes binned predictors, formed by segmenting the range of the data into equal sized half open intervals, and then creating binary predictors indicating to which interval each training point belongs. The splines model includes a natural cubic spline basis expansion, with knots equally spaced throughout the range of the predictor. The arguments are signal: A one variable function representing the truth to be estimated. N: The number of samples to include in both training and testing data. noise: The amound of random gaussian noise to add to the training and testing signal. range: The range of the training and testing x data, data this is generated uniformly within this range. max_paramters: The maximum number of parameters to estimate in a model. This is both the maximum number of segments in the cuts model, and the maximum number of knots in the splines model. Note that the number of parameters estimated in the splines model is the same as the number of knots, so the two models are fairly compared. The return object from the function has a few components signal_plot: A plot of the signal function. data_plot: A scatter plot of the training and testing data. errors_comparison_plot: A plot showing the evolution of the sum of squared error rate for both models over a range of the number of estiamted parameters. I'll demonstrate with two signal functions. The first is a sin wave with an increasing linear trend superimposed true_signal_sin <- function(x) { x + 1.5*sin(3*2*pi*x) } obj <- test_cuts_vs_splines(true_signal_sin, 250, 1) Here is how the error rates evolve The second example is a nutty function I keep around just for this kind of thing, plot it and see true_signal_weird <- function(x) { x*x*x*(x-1) + 2*(1/(1+exp(-.5*(x-.5)))) - 3.5*(x > .2)*(x < .5)*(x - .2)*(x - .5) } obj <- test_cuts_vs_splines(true_signal_weird, 250, .05) And for fun, here is a boring linear function obj <- test_cuts_vs_splines(function(x) {x}, 250, .2) You can see that: Splines give overall better overall test performance when the model complexity is properly tuned for both. Splines give optimal test performance with much fewer estimated parameters. Overall the performance of splines is much more stable as the number of estimated parameters is varied. So splines are always to be prefered from a predictive standpoint. Code Here's the code I used to produce these comparisons. I've wrapped it all in a function so that you can try it out with your own signal functions. You will need to import the ggplot2 and splines R libraries. test_cuts_vs_splines <- function(signal, N, noise, range=c(0, 1), max_parameters=50, seed=154) { if(max_parameters < 8) { stop("Please pass max_parameters >= 8, otherwise the plots look kinda bad.") } out_obj <- list() set.seed(seed) x_train <- runif(N, range[1], range[2]) x_test <- runif(N, range[1], range[2]) y_train <- signal(x_train) + rnorm(N, 0, noise) y_test <- signal(x_test) + rnorm(N, 0, noise) # A plot of the true signals df <- data.frame( x = seq(range[1], range[2], length.out = 100) ) df$y <- signal(df$x) out_obj$signal_plot <- ggplot(data = df) + geom_line(aes(x = x, y = y)) + labs(title = "True Signal") # A plot of the training and testing data df <- data.frame( x = c(x_train, x_test), y = c(y_train, y_test), id = c(rep("train", N), rep("test", N)) ) out_obj$data_plot <- ggplot(data = df) + geom_point(aes(x=x, y=y)) + facet_wrap(~ id) + labs(title = "Training and Testing Data") #----- lm with various groupings ------------- models_with_groupings <- list() train_errors_cuts <- rep(NULL, length(models_with_groupings)) test_errors_cuts <- rep(NULL, length(models_with_groupings)) for (n_groups in 3:max_parameters) { cut_points <- seq(range[1], range[2], length.out = n_groups + 1) x_train_factor <- cut(x_train, cut_points) factor_train_data <- data.frame(x = x_train_factor, y = y_train) models_with_groupings[[n_groups]] <- lm(y ~ x, data = factor_train_data) # Training error rate train_preds <- predict(models_with_groupings[[n_groups]], factor_train_data) soses <- (1/N) * sum( (y_train - train_preds)**2) train_errors_cuts[n_groups - 2] <- soses # Testing error rate x_test_factor <- cut(x_test, cut_points) factor_test_data <- data.frame(x = x_test_factor, y = y_test) test_preds <- predict(models_with_groupings[[n_groups]], factor_test_data) soses <- (1/N) * sum( (y_test - test_preds)**2) test_errors_cuts[n_groups - 2] <- soses } # We are overfitting error_df_cuts <- data.frame( x = rep(3:max_parameters, 2), e = c(train_errors_cuts, test_errors_cuts), id = c(rep("train", length(train_errors_cuts)), rep("test", length(test_errors_cuts))), type = "cuts" ) out_obj$errors_cuts_plot <- ggplot(data = error_df_cuts) + geom_line(aes(x = x, y = e)) + facet_wrap(~ id) + labs(title = "Error Rates with Grouping Transformations", x = ("Number of Estimated Parameters"), y = ("Average Squared Error")) #----- lm with natural splines ------------- models_with_splines <- list() train_errors_splines <- rep(NULL, length(models_with_groupings)) test_errors_splines <- rep(NULL, length(models_with_groupings)) for (deg_freedom in 3:max_parameters) { knots <- seq(range[1], range[2], length.out = deg_freedom + 1)[2:deg_freedom] train_data <- data.frame(x = x_train, y = y_train) models_with_splines[[deg_freedom]] <- lm(y ~ ns(x, knots=knots), data = train_data) # Training error rate train_preds <- predict(models_with_splines[[deg_freedom]], train_data) soses <- (1/N) * sum( (y_train - train_preds)**2) train_errors_splines[deg_freedom - 2] <- soses # Testing error rate test_data <- data.frame(x = x_test, y = y_test) test_preds <- predict(models_with_splines[[deg_freedom]], test_data) soses <- (1/N) * sum( (y_test - test_preds)**2) test_errors_splines[deg_freedom - 2] <- soses } error_df_splines <- data.frame( x = rep(3:max_parameters, 2), e = c(train_errors_splines, test_errors_splines), id = c(rep("train", length(train_errors_splines)), rep("test", length(test_errors_splines))), type = "splines" ) out_obj$errors_splines_plot <- ggplot(data = error_df_splines) + geom_line(aes(x = x, y = e)) + facet_wrap(~ id) + labs(title = "Error Rates with Natural Cubic Spline Transformations", x = ("Number of Estimated Parameters"), y = ("Average Squared Error")) error_df <- rbind(error_df_cuts, error_df_splines) out_obj$error_df <- error_df # The training error for the first cut model is always an outlier, and # messes up the y range of the plots. y_lower_bound <- min(c(train_errors_cuts, train_errors_splines)) y_upper_bound = train_errors_cuts[2] out_obj$errors_comparison_plot <- ggplot(data = error_df) + geom_line(aes(x = x, y = e)) + facet_wrap(~ id*type) + scale_y_continuous(limits = c(y_lower_bound, y_upper_bound)) + labs( title = ("Binning vs. Natural Splines"), x = ("Number of Estimated Parameters"), y = ("Average Squared Error")) out_obj }
When should we discretize/bin continuous independent variables/features and when should not?
Looks like you're also looking for an answer from a predictive standpoint, so I put together a short demonstration of two approaches in R Binning a variable into equal sized factors. Natural cubic sp
When should we discretize/bin continuous independent variables/features and when should not? Looks like you're also looking for an answer from a predictive standpoint, so I put together a short demonstration of two approaches in R Binning a variable into equal sized factors. Natural cubic splines. Below, I've given the code for a function that will compare the two methods automatically for any given true signal function test_cuts_vs_splines <- function(signal, N, noise, range=c(0, 1), max_parameters=50, seed=154) This function will create noisy training and testing datasets from a given signal, and then fit a series of linear regressions to the training data of two types The cuts model includes binned predictors, formed by segmenting the range of the data into equal sized half open intervals, and then creating binary predictors indicating to which interval each training point belongs. The splines model includes a natural cubic spline basis expansion, with knots equally spaced throughout the range of the predictor. The arguments are signal: A one variable function representing the truth to be estimated. N: The number of samples to include in both training and testing data. noise: The amound of random gaussian noise to add to the training and testing signal. range: The range of the training and testing x data, data this is generated uniformly within this range. max_paramters: The maximum number of parameters to estimate in a model. This is both the maximum number of segments in the cuts model, and the maximum number of knots in the splines model. Note that the number of parameters estimated in the splines model is the same as the number of knots, so the two models are fairly compared. The return object from the function has a few components signal_plot: A plot of the signal function. data_plot: A scatter plot of the training and testing data. errors_comparison_plot: A plot showing the evolution of the sum of squared error rate for both models over a range of the number of estiamted parameters. I'll demonstrate with two signal functions. The first is a sin wave with an increasing linear trend superimposed true_signal_sin <- function(x) { x + 1.5*sin(3*2*pi*x) } obj <- test_cuts_vs_splines(true_signal_sin, 250, 1) Here is how the error rates evolve The second example is a nutty function I keep around just for this kind of thing, plot it and see true_signal_weird <- function(x) { x*x*x*(x-1) + 2*(1/(1+exp(-.5*(x-.5)))) - 3.5*(x > .2)*(x < .5)*(x - .2)*(x - .5) } obj <- test_cuts_vs_splines(true_signal_weird, 250, .05) And for fun, here is a boring linear function obj <- test_cuts_vs_splines(function(x) {x}, 250, .2) You can see that: Splines give overall better overall test performance when the model complexity is properly tuned for both. Splines give optimal test performance with much fewer estimated parameters. Overall the performance of splines is much more stable as the number of estimated parameters is varied. So splines are always to be prefered from a predictive standpoint. Code Here's the code I used to produce these comparisons. I've wrapped it all in a function so that you can try it out with your own signal functions. You will need to import the ggplot2 and splines R libraries. test_cuts_vs_splines <- function(signal, N, noise, range=c(0, 1), max_parameters=50, seed=154) { if(max_parameters < 8) { stop("Please pass max_parameters >= 8, otherwise the plots look kinda bad.") } out_obj <- list() set.seed(seed) x_train <- runif(N, range[1], range[2]) x_test <- runif(N, range[1], range[2]) y_train <- signal(x_train) + rnorm(N, 0, noise) y_test <- signal(x_test) + rnorm(N, 0, noise) # A plot of the true signals df <- data.frame( x = seq(range[1], range[2], length.out = 100) ) df$y <- signal(df$x) out_obj$signal_plot <- ggplot(data = df) + geom_line(aes(x = x, y = y)) + labs(title = "True Signal") # A plot of the training and testing data df <- data.frame( x = c(x_train, x_test), y = c(y_train, y_test), id = c(rep("train", N), rep("test", N)) ) out_obj$data_plot <- ggplot(data = df) + geom_point(aes(x=x, y=y)) + facet_wrap(~ id) + labs(title = "Training and Testing Data") #----- lm with various groupings ------------- models_with_groupings <- list() train_errors_cuts <- rep(NULL, length(models_with_groupings)) test_errors_cuts <- rep(NULL, length(models_with_groupings)) for (n_groups in 3:max_parameters) { cut_points <- seq(range[1], range[2], length.out = n_groups + 1) x_train_factor <- cut(x_train, cut_points) factor_train_data <- data.frame(x = x_train_factor, y = y_train) models_with_groupings[[n_groups]] <- lm(y ~ x, data = factor_train_data) # Training error rate train_preds <- predict(models_with_groupings[[n_groups]], factor_train_data) soses <- (1/N) * sum( (y_train - train_preds)**2) train_errors_cuts[n_groups - 2] <- soses # Testing error rate x_test_factor <- cut(x_test, cut_points) factor_test_data <- data.frame(x = x_test_factor, y = y_test) test_preds <- predict(models_with_groupings[[n_groups]], factor_test_data) soses <- (1/N) * sum( (y_test - test_preds)**2) test_errors_cuts[n_groups - 2] <- soses } # We are overfitting error_df_cuts <- data.frame( x = rep(3:max_parameters, 2), e = c(train_errors_cuts, test_errors_cuts), id = c(rep("train", length(train_errors_cuts)), rep("test", length(test_errors_cuts))), type = "cuts" ) out_obj$errors_cuts_plot <- ggplot(data = error_df_cuts) + geom_line(aes(x = x, y = e)) + facet_wrap(~ id) + labs(title = "Error Rates with Grouping Transformations", x = ("Number of Estimated Parameters"), y = ("Average Squared Error")) #----- lm with natural splines ------------- models_with_splines <- list() train_errors_splines <- rep(NULL, length(models_with_groupings)) test_errors_splines <- rep(NULL, length(models_with_groupings)) for (deg_freedom in 3:max_parameters) { knots <- seq(range[1], range[2], length.out = deg_freedom + 1)[2:deg_freedom] train_data <- data.frame(x = x_train, y = y_train) models_with_splines[[deg_freedom]] <- lm(y ~ ns(x, knots=knots), data = train_data) # Training error rate train_preds <- predict(models_with_splines[[deg_freedom]], train_data) soses <- (1/N) * sum( (y_train - train_preds)**2) train_errors_splines[deg_freedom - 2] <- soses # Testing error rate test_data <- data.frame(x = x_test, y = y_test) test_preds <- predict(models_with_splines[[deg_freedom]], test_data) soses <- (1/N) * sum( (y_test - test_preds)**2) test_errors_splines[deg_freedom - 2] <- soses } error_df_splines <- data.frame( x = rep(3:max_parameters, 2), e = c(train_errors_splines, test_errors_splines), id = c(rep("train", length(train_errors_splines)), rep("test", length(test_errors_splines))), type = "splines" ) out_obj$errors_splines_plot <- ggplot(data = error_df_splines) + geom_line(aes(x = x, y = e)) + facet_wrap(~ id) + labs(title = "Error Rates with Natural Cubic Spline Transformations", x = ("Number of Estimated Parameters"), y = ("Average Squared Error")) error_df <- rbind(error_df_cuts, error_df_splines) out_obj$error_df <- error_df # The training error for the first cut model is always an outlier, and # messes up the y range of the plots. y_lower_bound <- min(c(train_errors_cuts, train_errors_splines)) y_upper_bound = train_errors_cuts[2] out_obj$errors_comparison_plot <- ggplot(data = error_df) + geom_line(aes(x = x, y = e)) + facet_wrap(~ id*type) + scale_y_continuous(limits = c(y_lower_bound, y_upper_bound)) + labs( title = ("Binning vs. Natural Splines"), x = ("Number of Estimated Parameters"), y = ("Average Squared Error")) out_obj }
When should we discretize/bin continuous independent variables/features and when should not? Looks like you're also looking for an answer from a predictive standpoint, so I put together a short demonstration of two approaches in R Binning a variable into equal sized factors. Natural cubic sp
8,534
Is Kernel PCA with linear kernel equivalent to standard PCA?
Summary: kernel PCA with linear kernel is exactly equivalent to the standard PCA. Let $\mathbf{X}$ be the centered data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in rows. Then the $D \times D$ covariance matrix is given by $\mathbf{X}^\top\mathbf{X}/(n-1)$, its eigenvectors are principal axes and eigenvalues are PC variances. At the same time, one can consider the so called Gram matrix $\mathbf{X}\mathbf{X}^\top$ of the $N \times N$ size. It is easy to see that it has the same eigenvalues (i.e. PC variances) up to the $n-1$ factor, and its eigenvectors are principal components scaled to unit norm. This was standard PCA. Now, in kernel PCA we consider some function $\phi(x)$ that maps each data point to another vector space that usually has larger dimensionality $D_\mathrm{new}$, possibly even infinite. The idea of kernel PCA is to perform the standard PCA in this new space. Since the dimensionality of this new space is very large (or infinite), it is hard or impossible to compute a covariance matrix. However, we can apply the second approach to PCA outlined above. Indeed, Gram matrix will still be of the same manageable $N \times N$ size. Elements of this matrix are given by $\phi(\mathbf{x}_i)\phi(\mathbf{x}_j)$, which we will call kernel function $K(\mathbf{x}_i,\mathbf{x}_j)=\phi(\mathbf{x}_i)\phi(\mathbf{x}_j)$. This is what is known as the kernel trick: one actually does not ever need to compute $\phi()$, but only $K()$. Eigenvectors of this Gram matrix will be the principal components in the target space, the ones we are interested in. The answer to your question now becomes obvious. If $K(x,y)=\mathbf{x}^\top \mathbf{y}$, then the kernel Gram matrix reduces to $\mathbf{X} \mathbf{X}^\top$ which is equal to the standard Gram matrix, and hence the principal components will not change. A very readable reference is Scholkopf B, Smola A, and Müller KR, Kernel principal component analysis, 1999, and note that e.g. in Figure 1 they explicitly refer to standard PCA as the one using dot product as a kernel function:
Is Kernel PCA with linear kernel equivalent to standard PCA?
Summary: kernel PCA with linear kernel is exactly equivalent to the standard PCA. Let $\mathbf{X}$ be the centered data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in
Is Kernel PCA with linear kernel equivalent to standard PCA? Summary: kernel PCA with linear kernel is exactly equivalent to the standard PCA. Let $\mathbf{X}$ be the centered data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in rows. Then the $D \times D$ covariance matrix is given by $\mathbf{X}^\top\mathbf{X}/(n-1)$, its eigenvectors are principal axes and eigenvalues are PC variances. At the same time, one can consider the so called Gram matrix $\mathbf{X}\mathbf{X}^\top$ of the $N \times N$ size. It is easy to see that it has the same eigenvalues (i.e. PC variances) up to the $n-1$ factor, and its eigenvectors are principal components scaled to unit norm. This was standard PCA. Now, in kernel PCA we consider some function $\phi(x)$ that maps each data point to another vector space that usually has larger dimensionality $D_\mathrm{new}$, possibly even infinite. The idea of kernel PCA is to perform the standard PCA in this new space. Since the dimensionality of this new space is very large (or infinite), it is hard or impossible to compute a covariance matrix. However, we can apply the second approach to PCA outlined above. Indeed, Gram matrix will still be of the same manageable $N \times N$ size. Elements of this matrix are given by $\phi(\mathbf{x}_i)\phi(\mathbf{x}_j)$, which we will call kernel function $K(\mathbf{x}_i,\mathbf{x}_j)=\phi(\mathbf{x}_i)\phi(\mathbf{x}_j)$. This is what is known as the kernel trick: one actually does not ever need to compute $\phi()$, but only $K()$. Eigenvectors of this Gram matrix will be the principal components in the target space, the ones we are interested in. The answer to your question now becomes obvious. If $K(x,y)=\mathbf{x}^\top \mathbf{y}$, then the kernel Gram matrix reduces to $\mathbf{X} \mathbf{X}^\top$ which is equal to the standard Gram matrix, and hence the principal components will not change. A very readable reference is Scholkopf B, Smola A, and Müller KR, Kernel principal component analysis, 1999, and note that e.g. in Figure 1 they explicitly refer to standard PCA as the one using dot product as a kernel function:
Is Kernel PCA with linear kernel equivalent to standard PCA? Summary: kernel PCA with linear kernel is exactly equivalent to the standard PCA. Let $\mathbf{X}$ be the centered data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in
8,535
Is Kernel PCA with linear kernel equivalent to standard PCA?
In addition to amoeba's nice answer, there is an even simpler way to see the equivalence. Again let $X$ be the data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in rows. Standard PCA corresponds to taking a singular value decomposition of the matrix $X = U \Sigma V^\top$ with $U$ the principal components of $X$. The singular value decomposition of the linear kernel $XX^\top = U \Sigma^2 U^\top$ has the same left singular vectors and so the same principal components.
Is Kernel PCA with linear kernel equivalent to standard PCA?
In addition to amoeba's nice answer, there is an even simpler way to see the equivalence. Again let $X$ be the data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in row
Is Kernel PCA with linear kernel equivalent to standard PCA? In addition to amoeba's nice answer, there is an even simpler way to see the equivalence. Again let $X$ be the data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in rows. Standard PCA corresponds to taking a singular value decomposition of the matrix $X = U \Sigma V^\top$ with $U$ the principal components of $X$. The singular value decomposition of the linear kernel $XX^\top = U \Sigma^2 U^\top$ has the same left singular vectors and so the same principal components.
Is Kernel PCA with linear kernel equivalent to standard PCA? In addition to amoeba's nice answer, there is an even simpler way to see the equivalence. Again let $X$ be the data matrix of $N \times D$ size with $D$ variables in columns and $N$ data points in row
8,536
Is Kernel PCA with linear kernel equivalent to standard PCA?
It seems to me that that a KPCA with linear kernel should be the same as the simple PCA. The covariance matrix that you are going to get the eigenvalues from is the same: $$ linearKPCA_{matrix} = \frac{1}{l} \sum_{j=1}^{l}K(x_{j},x_{j}) = \frac{1}{l} \sum_{j=1}^{l}x_{j}x_{j}^T = PCA_{matrix} $$ You can check with more details here.
Is Kernel PCA with linear kernel equivalent to standard PCA?
It seems to me that that a KPCA with linear kernel should be the same as the simple PCA. The covariance matrix that you are going to get the eigenvalues from is the same: $$ linearKPCA_{matrix} = \f
Is Kernel PCA with linear kernel equivalent to standard PCA? It seems to me that that a KPCA with linear kernel should be the same as the simple PCA. The covariance matrix that you are going to get the eigenvalues from is the same: $$ linearKPCA_{matrix} = \frac{1}{l} \sum_{j=1}^{l}K(x_{j},x_{j}) = \frac{1}{l} \sum_{j=1}^{l}x_{j}x_{j}^T = PCA_{matrix} $$ You can check with more details here.
Is Kernel PCA with linear kernel equivalent to standard PCA? It seems to me that that a KPCA with linear kernel should be the same as the simple PCA. The covariance matrix that you are going to get the eigenvalues from is the same: $$ linearKPCA_{matrix} = \f
8,537
Implementation of CRF in python
CRF++ is a popular choice in general, and has Python bindings. CRFSuite also has bindings documented here, but doesn't seem to have seen as much widespread use as CRF++. As of this writing, higher level machine learning frameworks such as scikit-learn lack CRF support (see this pull request).
Implementation of CRF in python
CRF++ is a popular choice in general, and has Python bindings. CRFSuite also has bindings documented here, but doesn't seem to have seen as much widespread use as CRF++. As of this writing, higher lev
Implementation of CRF in python CRF++ is a popular choice in general, and has Python bindings. CRFSuite also has bindings documented here, but doesn't seem to have seen as much widespread use as CRF++. As of this writing, higher level machine learning frameworks such as scikit-learn lack CRF support (see this pull request).
Implementation of CRF in python CRF++ is a popular choice in general, and has Python bindings. CRFSuite also has bindings documented here, but doesn't seem to have seen as much widespread use as CRF++. As of this writing, higher lev
8,538
Implementation of CRF in python
CRF++ has more incoming links because it is an older library. CRFSuite is superior in my opinion. CRFSuite's author's claim that it is 20x faster than CRF++ at training a model. Less rigid requirements for the input data. If you are looking for Python bindings CRFSuite is also better because you can train a model in Python, while in CRF++ you can only test existing models in Python. (That was the deal breaker for me.) CRFSuite also comes with a bunch of example code in Python, such as NER, Chunking, and POS tagging.
Implementation of CRF in python
CRF++ has more incoming links because it is an older library. CRFSuite is superior in my opinion. CRFSuite's author's claim that it is 20x faster than CRF++ at training a model. Less rigid requi
Implementation of CRF in python CRF++ has more incoming links because it is an older library. CRFSuite is superior in my opinion. CRFSuite's author's claim that it is 20x faster than CRF++ at training a model. Less rigid requirements for the input data. If you are looking for Python bindings CRFSuite is also better because you can train a model in Python, while in CRF++ you can only test existing models in Python. (That was the deal breaker for me.) CRFSuite also comes with a bunch of example code in Python, such as NER, Chunking, and POS tagging.
Implementation of CRF in python CRF++ has more incoming links because it is an older library. CRFSuite is superior in my opinion. CRFSuite's author's claim that it is 20x faster than CRF++ at training a model. Less rigid requi
8,539
Implementation of CRF in python
Here are some other wrappers/implementations: https://github.com/adsva/python-wapiti - Python wrapper for http://wapiti.limsi.fr/. Wapiti is fast; crfsuite benchmarks are not fair to wapiti because wapiti can parallelize L-BFGS training to multiple CPU cores, and this feature was not used in benchmarks. The problem with Wapiti is that it is not written as a library. The wrapper tries hard to overcome that, but you can still get an uncatchable exit(), and I've seen memory leaks during the training. Also, wapiti is limited in a type of features it can represent, but CRFsuite is also limited (in a different way). Wapiti is bundled in a wrapper, no need to install it separately. https://github.com/jakevdp/pyCRFsuite - a wrapper for crfsuite. The wrapper is quite advanced and allows using scipy sparse matrices as an input, but it seems there are some unresolved issues, it is possible to get a segfault in some cases. https://github.com/tpeng/python-crfsuite - another crfsuite wrapper. This one is rather simple; it bundles crfsuite for easier installation and can be installed just with 'pip install python-crfsuite'. https://github.com/larsmans/seqlearn provides Structured Perceptron which can be a replacement for CRF in many cases. Structured Perceptron implementation is very fast in seqlearn. There is a PR (not merged at the time of writing) which adds CRF support to seqlearn; it looks solid. https://github.com/timvieira/crf - it is quite basic and doesn't have some essential features, but it requires only numpy. I'd recommend to use seqlearn if you can, python-crfsuite if you need CRFsuite training algorithms and training speed, pyCRFsuite if you need more advanced CRFsuite integration and ready to face some inconveniences, python-wapiti if you need Wapiti training algorithms or features not available in CRFsuite (like conditioning individual observations on transitions) and timvieira's crf if there is no way to get a C/C++ compiler working, but a prebuilt numpy is available.
Implementation of CRF in python
Here are some other wrappers/implementations: https://github.com/adsva/python-wapiti - Python wrapper for http://wapiti.limsi.fr/. Wapiti is fast; crfsuite benchmarks are not fair to wapiti because w
Implementation of CRF in python Here are some other wrappers/implementations: https://github.com/adsva/python-wapiti - Python wrapper for http://wapiti.limsi.fr/. Wapiti is fast; crfsuite benchmarks are not fair to wapiti because wapiti can parallelize L-BFGS training to multiple CPU cores, and this feature was not used in benchmarks. The problem with Wapiti is that it is not written as a library. The wrapper tries hard to overcome that, but you can still get an uncatchable exit(), and I've seen memory leaks during the training. Also, wapiti is limited in a type of features it can represent, but CRFsuite is also limited (in a different way). Wapiti is bundled in a wrapper, no need to install it separately. https://github.com/jakevdp/pyCRFsuite - a wrapper for crfsuite. The wrapper is quite advanced and allows using scipy sparse matrices as an input, but it seems there are some unresolved issues, it is possible to get a segfault in some cases. https://github.com/tpeng/python-crfsuite - another crfsuite wrapper. This one is rather simple; it bundles crfsuite for easier installation and can be installed just with 'pip install python-crfsuite'. https://github.com/larsmans/seqlearn provides Structured Perceptron which can be a replacement for CRF in many cases. Structured Perceptron implementation is very fast in seqlearn. There is a PR (not merged at the time of writing) which adds CRF support to seqlearn; it looks solid. https://github.com/timvieira/crf - it is quite basic and doesn't have some essential features, but it requires only numpy. I'd recommend to use seqlearn if you can, python-crfsuite if you need CRFsuite training algorithms and training speed, pyCRFsuite if you need more advanced CRFsuite integration and ready to face some inconveniences, python-wapiti if you need Wapiti training algorithms or features not available in CRFsuite (like conditioning individual observations on transitions) and timvieira's crf if there is no way to get a C/C++ compiler working, but a prebuilt numpy is available.
Implementation of CRF in python Here are some other wrappers/implementations: https://github.com/adsva/python-wapiti - Python wrapper for http://wapiti.limsi.fr/. Wapiti is fast; crfsuite benchmarks are not fair to wapiti because w
8,540
Implementation of CRF in python
I think what you are looking for is PyStruct. PyStruct aims at being an easy-to-use structured learning and prediction library. Currently it implements only max-margin methods and a perceptron, but other algorithms might follow. The goal of PyStruct is to provide a well-documented tool for researchers as well as non-experts to make use of structured prediction algorithms. The design tries to stay as close as possible to the interface and conventions of scikit-learn. PyStruct comes with good documentation, and it is actively developed on github. Below is a table comparing PyStruct with CRFsuite and other packages, extracted from PyStruct - Structured prediction in Python:
Implementation of CRF in python
I think what you are looking for is PyStruct. PyStruct aims at being an easy-to-use structured learning and prediction library. Currently it implements only max-margin methods and a perceptron, but o
Implementation of CRF in python I think what you are looking for is PyStruct. PyStruct aims at being an easy-to-use structured learning and prediction library. Currently it implements only max-margin methods and a perceptron, but other algorithms might follow. The goal of PyStruct is to provide a well-documented tool for researchers as well as non-experts to make use of structured prediction algorithms. The design tries to stay as close as possible to the interface and conventions of scikit-learn. PyStruct comes with good documentation, and it is actively developed on github. Below is a table comparing PyStruct with CRFsuite and other packages, extracted from PyStruct - Structured prediction in Python:
Implementation of CRF in python I think what you are looking for is PyStruct. PyStruct aims at being an easy-to-use structured learning and prediction library. Currently it implements only max-margin methods and a perceptron, but o
8,541
How could stochastic gradient descent save time compared to standard gradient descent?
Short answer: In many big data setting (say several million data points), calculating cost or gradient takes very long time, because we need to sum over all data points. We do NOT need to have exact gradient to reduce the cost in a given iteration. Some approximation of gradient would work OK. Stochastic gradient decent (SGD) approximate the gradient using only one data point. So, evaluating gradient saves a lot of time compared to summing over all data. With "reasonable" number of iterations (this number could be couple of thousands, and much less than the number of data points, which may be millions), stochastic gradient decent may get a reasonable good solution. Long answer: My notation follows Andrew NG's machine learning Coursera course. If you are not familiar with it, you can review the lecture series here. Let's assume regression on squared loss, the cost function is \begin{align} J(\theta)= \frac 1 {2m} \sum_{i=1}^m (h_{\theta}(x^{(i)})-y^{(i)})^2 \end{align} and the gradient is \begin{align} \frac {d J(\theta)}{d \theta}= \frac 1 {m} \sum_{i=1}^m (h_{\theta}(x^{(i)})-y^{(i)})x^{(i)} \end{align} for gradient decent (GD), we update the parameter by \begin{align} \theta_{new} &=\theta_{old} - \alpha \frac 1 {m} \sum_{i=1}^m (h_{\theta}(x^{(i)})-y^{(i)})x^{(i)} \end{align} For stochastic gradient decent we get rid of the sum and $1/m$ constant, but get the gradient for current data point $x^{(i)},y^{(i)}$, where comes time saving. \begin{align} \theta_{new}=\theta_{old} - \alpha \cdot (h_{\theta}(x^{(i)})-y^{(i)})x^{(i)} \end{align} Here is why we are saving time: Suppose we have 1 billion data points. In GD, in order to update the parameters once, we need to have the (exact) gradient. This requires to sum up these 1 billion data points to perform 1 update. In SGD, we can think of it as trying to get an approximated gradient instead of exact gradient. The approximation is coming from one data point (or several data points called mini batch). Therefore, in SGD, we can update the parameters very quickly. In addition, if we "loop" over all data (called one epoch), we actually have 1 billion updates. The trick is that, in SGD you do not need to have 1 billion iterations/updates, but much less iterations/updates, say 1 million, and you will have "good enough" model to use. I am writing a code to demo the idea. We first solve the linear system by normal equation, then solve it with SGD. Then we compare the results in terms of parameter values and final objective function values. In order to visualize it later, we will have 2 parameters to tune. set.seed(0);n_data=1e3;n_feature=2; A=matrix(runif(n_data*n_feature),ncol=n_feature) b=runif(n_data) res1=solve(t(A) %*% A, t(A) %*% b) sq_loss<-function(A,b,x){ e=A %*% x -b v=crossprod(e) return(v[1]) } sq_loss_gr_approx<-function(A,b,x){ # note, in GD, we need to sum over all data # here i is just one random index sample i=sample(1:n_data, 1) gr=2*(crossprod(A[i,],x)-b[i])*A[i,] return(gr) } x=runif(n_feature) alpha=0.01 N_iter=300 loss=rep(0,N_iter) for (i in 1:N_iter){ x=x-alpha*sq_loss_gr_approx(A,b,x) loss[i]=sq_loss(A,b,x) } The results: as.vector(res1) [1] 0.4368427 0.3991028 x [1] 0.3580121 0.4782659 Note, although the parameters are not too close, the loss values are $124.1343$ and $123.0355$ which are very close. Here is the cost function values over iterations, we can see it can effectively decrease the loss, which illustrates the idea: we can use a subset of data to approximate the gradient and get "good enough" results. Now let's check the computational efforts between two approaches. In the experiment, we have $1000$ data points, using SD, evaluate gradient once needs to sum over them data. BUT in SGD, sq_loss_gr_approx function only sum up 1 data point, and overall we see, the algorithm converges less than $300$ iterations (note, not $1000$ iterations.) This is the computational savings.
How could stochastic gradient descent save time compared to standard gradient descent?
Short answer: In many big data setting (say several million data points), calculating cost or gradient takes very long time, because we need to sum over all data points. We do NOT need to have exact
How could stochastic gradient descent save time compared to standard gradient descent? Short answer: In many big data setting (say several million data points), calculating cost or gradient takes very long time, because we need to sum over all data points. We do NOT need to have exact gradient to reduce the cost in a given iteration. Some approximation of gradient would work OK. Stochastic gradient decent (SGD) approximate the gradient using only one data point. So, evaluating gradient saves a lot of time compared to summing over all data. With "reasonable" number of iterations (this number could be couple of thousands, and much less than the number of data points, which may be millions), stochastic gradient decent may get a reasonable good solution. Long answer: My notation follows Andrew NG's machine learning Coursera course. If you are not familiar with it, you can review the lecture series here. Let's assume regression on squared loss, the cost function is \begin{align} J(\theta)= \frac 1 {2m} \sum_{i=1}^m (h_{\theta}(x^{(i)})-y^{(i)})^2 \end{align} and the gradient is \begin{align} \frac {d J(\theta)}{d \theta}= \frac 1 {m} \sum_{i=1}^m (h_{\theta}(x^{(i)})-y^{(i)})x^{(i)} \end{align} for gradient decent (GD), we update the parameter by \begin{align} \theta_{new} &=\theta_{old} - \alpha \frac 1 {m} \sum_{i=1}^m (h_{\theta}(x^{(i)})-y^{(i)})x^{(i)} \end{align} For stochastic gradient decent we get rid of the sum and $1/m$ constant, but get the gradient for current data point $x^{(i)},y^{(i)}$, where comes time saving. \begin{align} \theta_{new}=\theta_{old} - \alpha \cdot (h_{\theta}(x^{(i)})-y^{(i)})x^{(i)} \end{align} Here is why we are saving time: Suppose we have 1 billion data points. In GD, in order to update the parameters once, we need to have the (exact) gradient. This requires to sum up these 1 billion data points to perform 1 update. In SGD, we can think of it as trying to get an approximated gradient instead of exact gradient. The approximation is coming from one data point (or several data points called mini batch). Therefore, in SGD, we can update the parameters very quickly. In addition, if we "loop" over all data (called one epoch), we actually have 1 billion updates. The trick is that, in SGD you do not need to have 1 billion iterations/updates, but much less iterations/updates, say 1 million, and you will have "good enough" model to use. I am writing a code to demo the idea. We first solve the linear system by normal equation, then solve it with SGD. Then we compare the results in terms of parameter values and final objective function values. In order to visualize it later, we will have 2 parameters to tune. set.seed(0);n_data=1e3;n_feature=2; A=matrix(runif(n_data*n_feature),ncol=n_feature) b=runif(n_data) res1=solve(t(A) %*% A, t(A) %*% b) sq_loss<-function(A,b,x){ e=A %*% x -b v=crossprod(e) return(v[1]) } sq_loss_gr_approx<-function(A,b,x){ # note, in GD, we need to sum over all data # here i is just one random index sample i=sample(1:n_data, 1) gr=2*(crossprod(A[i,],x)-b[i])*A[i,] return(gr) } x=runif(n_feature) alpha=0.01 N_iter=300 loss=rep(0,N_iter) for (i in 1:N_iter){ x=x-alpha*sq_loss_gr_approx(A,b,x) loss[i]=sq_loss(A,b,x) } The results: as.vector(res1) [1] 0.4368427 0.3991028 x [1] 0.3580121 0.4782659 Note, although the parameters are not too close, the loss values are $124.1343$ and $123.0355$ which are very close. Here is the cost function values over iterations, we can see it can effectively decrease the loss, which illustrates the idea: we can use a subset of data to approximate the gradient and get "good enough" results. Now let's check the computational efforts between two approaches. In the experiment, we have $1000$ data points, using SD, evaluate gradient once needs to sum over them data. BUT in SGD, sq_loss_gr_approx function only sum up 1 data point, and overall we see, the algorithm converges less than $300$ iterations (note, not $1000$ iterations.) This is the computational savings.
How could stochastic gradient descent save time compared to standard gradient descent? Short answer: In many big data setting (say several million data points), calculating cost or gradient takes very long time, because we need to sum over all data points. We do NOT need to have exact
8,542
How could stochastic gradient descent save time compared to standard gradient descent?
First of all, if you do the same number of epochs, SGD won't be faster than GD, because the per-epoch computation complexity is same for SGD and GD, as you pointed out. However, GD only does one iteration of gradient descent per epoch while SGD does n/m iterations. Those n/m iterations brings greater improvement than the single iteration of GD, even though each of the n/m iterations is probably worse than the single iteration of GD due to sampling. So, SGD is faster in the sense that it reaches the same accuracy quicker, with fewer epochs, than GD.
How could stochastic gradient descent save time compared to standard gradient descent?
First of all, if you do the same number of epochs, SGD won't be faster than GD, because the per-epoch computation complexity is same for SGD and GD, as you pointed out. However, GD only does one itera
How could stochastic gradient descent save time compared to standard gradient descent? First of all, if you do the same number of epochs, SGD won't be faster than GD, because the per-epoch computation complexity is same for SGD and GD, as you pointed out. However, GD only does one iteration of gradient descent per epoch while SGD does n/m iterations. Those n/m iterations brings greater improvement than the single iteration of GD, even though each of the n/m iterations is probably worse than the single iteration of GD due to sampling. So, SGD is faster in the sense that it reaches the same accuracy quicker, with fewer epochs, than GD.
How could stochastic gradient descent save time compared to standard gradient descent? First of all, if you do the same number of epochs, SGD won't be faster than GD, because the per-epoch computation complexity is same for SGD and GD, as you pointed out. However, GD only does one itera
8,543
How could stochastic gradient descent save time compared to standard gradient descent?
Not only does SGD iterate gradients much faster, the stochasticity (noise from randomly picking samples) itself can be an asset for generalization: see ex. On the Generalization Benefit of Noise in Stochastic Gradient Descent (Smith, Elsen, De, ICML 2020)
How could stochastic gradient descent save time compared to standard gradient descent?
Not only does SGD iterate gradients much faster, the stochasticity (noise from randomly picking samples) itself can be an asset for generalization: see ex. On the Generalization Benefit of Noise in St
How could stochastic gradient descent save time compared to standard gradient descent? Not only does SGD iterate gradients much faster, the stochasticity (noise from randomly picking samples) itself can be an asset for generalization: see ex. On the Generalization Benefit of Noise in Stochastic Gradient Descent (Smith, Elsen, De, ICML 2020)
How could stochastic gradient descent save time compared to standard gradient descent? Not only does SGD iterate gradients much faster, the stochasticity (noise from randomly picking samples) itself can be an asset for generalization: see ex. On the Generalization Benefit of Noise in St
8,544
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables?
I don't believe there is anything wrong with using LASSO for variable selection and then using OLS. From "Elements of Statistical Learning" (pg. 91) ...the lasso shrinkage causes the estimates of the non-zero coefficients to be biased towards zero and in general they are not consistent [Added Note: This means that, as the sample size grows, the coefficient estimates do not converge]. One approach for reducing this bias is to run the lasso to identify the set of non-zero coefficients, and then fit an un-restricted linear model to the selected set of features. This is not always feasible, if the selected set is large. Alternatively, one can use the lasso to select the set of non-zero predictors, and then apply the lasso again, but using only the selected predictors from the first step. This is known as the relaxed lasso (Meinshausen, 2007). The idea is to use cross-validation to estimate the initial penalty parameter for the lasso, and then again for a second penalty parameter applied to the selected set of predictors. Since the variables in the second step have less "competition" from noise variables, cross-validation will tend to pick a smaller value for $\lambda$ [the penalty parameter], and hence their coefficients will be shrunken less than those in the initial estimate. Another reasonable approach similar in spirit to the relaxed lasso, would be to use lasso once (or several times in tandem) to identify a group of candidate predictor variables. Then use best subsets regression to select the best predictor variables to consider (also see "Elements of Statistical Learning" for this). For this to work, you would need to refine the group of candidate predictors down to around 35, which won't always be feasible. You can use cross-validation or AIC as a criterion to prevent over-fitting.
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables?
I don't believe there is anything wrong with using LASSO for variable selection and then using OLS. From "Elements of Statistical Learning" (pg. 91) ...the lasso shrinkage causes the estimates of the
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables? I don't believe there is anything wrong with using LASSO for variable selection and then using OLS. From "Elements of Statistical Learning" (pg. 91) ...the lasso shrinkage causes the estimates of the non-zero coefficients to be biased towards zero and in general they are not consistent [Added Note: This means that, as the sample size grows, the coefficient estimates do not converge]. One approach for reducing this bias is to run the lasso to identify the set of non-zero coefficients, and then fit an un-restricted linear model to the selected set of features. This is not always feasible, if the selected set is large. Alternatively, one can use the lasso to select the set of non-zero predictors, and then apply the lasso again, but using only the selected predictors from the first step. This is known as the relaxed lasso (Meinshausen, 2007). The idea is to use cross-validation to estimate the initial penalty parameter for the lasso, and then again for a second penalty parameter applied to the selected set of predictors. Since the variables in the second step have less "competition" from noise variables, cross-validation will tend to pick a smaller value for $\lambda$ [the penalty parameter], and hence their coefficients will be shrunken less than those in the initial estimate. Another reasonable approach similar in spirit to the relaxed lasso, would be to use lasso once (or several times in tandem) to identify a group of candidate predictor variables. Then use best subsets regression to select the best predictor variables to consider (also see "Elements of Statistical Learning" for this). For this to work, you would need to refine the group of candidate predictors down to around 35, which won't always be feasible. You can use cross-validation or AIC as a criterion to prevent over-fitting.
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables? I don't believe there is anything wrong with using LASSO for variable selection and then using OLS. From "Elements of Statistical Learning" (pg. 91) ...the lasso shrinkage causes the estimates of the
8,545
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables?
If your aim is optimal in-sample performance (wrt highest R-squared), then just use OLS on every available variable. Dropping variables will decrease R-squared. If your aim is good out-of-sample performance (which is usually what is much more important), then your proposed strategy will suffer from two sources of overfitting: Selection of variables based on correlations with the response variable OLS estimates The purpose of LASSO is to shrink parameter estimates towards zero in order to fight above two sources of overfitting. In-sample predictions will be always worse than OLS, but the hope is (depending on the strength of the penalization) to get more realistic out-of-sample behaviour. Regarding $p > n$: This (probably) depends on the implementation of LASSO you are using. A variant, Lars (least angle regression), does easily work for $p > n$.
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables?
If your aim is optimal in-sample performance (wrt highest R-squared), then just use OLS on every available variable. Dropping variables will decrease R-squared. If your aim is good out-of-sample perfo
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables? If your aim is optimal in-sample performance (wrt highest R-squared), then just use OLS on every available variable. Dropping variables will decrease R-squared. If your aim is good out-of-sample performance (which is usually what is much more important), then your proposed strategy will suffer from two sources of overfitting: Selection of variables based on correlations with the response variable OLS estimates The purpose of LASSO is to shrink parameter estimates towards zero in order to fight above two sources of overfitting. In-sample predictions will be always worse than OLS, but the hope is (depending on the strength of the penalization) to get more realistic out-of-sample behaviour. Regarding $p > n$: This (probably) depends on the implementation of LASSO you are using. A variant, Lars (least angle regression), does easily work for $p > n$.
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables? If your aim is optimal in-sample performance (wrt highest R-squared), then just use OLS on every available variable. Dropping variables will decrease R-squared. If your aim is good out-of-sample perfo
8,546
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables?
Regarding the OPs question of why Lasso can select at most n features: Consider why an OLS might be biased: this is when there are more predictors (p) than observations (n). Thus $X^{T}X$ is of size [p,p] in $\beta = (X^{T} X)^{-1}X^{T}Y$. Taking an inverse of such a matrix is not possible (it may be singular). Lasso is forced to shrink the coefficients of the variables so that this does not happen, thus it never selects more than n features so that $X^{T}X$ is always invertible.
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables?
Regarding the OPs question of why Lasso can select at most n features: Consider why an OLS might be biased: this is when there are more predictors (p) than observations (n). Thus $X^{T}X$ is of size [
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables? Regarding the OPs question of why Lasso can select at most n features: Consider why an OLS might be biased: this is when there are more predictors (p) than observations (n). Thus $X^{T}X$ is of size [p,p] in $\beta = (X^{T} X)^{-1}X^{T}Y$. Taking an inverse of such a matrix is not possible (it may be singular). Lasso is forced to shrink the coefficients of the variables so that this does not happen, thus it never selects more than n features so that $X^{T}X$ is always invertible.
Why use Lasso estimates over OLS estimates on the Lasso-identified subset of variables? Regarding the OPs question of why Lasso can select at most n features: Consider why an OLS might be biased: this is when there are more predictors (p) than observations (n). Thus $X^{T}X$ is of size [
8,547
How to know if a data follows a Poisson Distribution in R?
There are an infinite number of ways for a distribution to be slightly different from a Poisson distribution; you can't identify that a set of data is drawn from a Poisson distribution. What you can do is look for inconsistency with what you should see with a Poisson, but a lack of obvious inconsistency doesn't make it Poisson. However, what you're talking about there by checking those three criteria isn't checking that the data come from a Poisson distribution by statistical means (i.e. by looking at data), but by assessing whether the process the data are generated by satisfies the conditions of a Poisson process; if the conditions all held or almost held (and that's a consideration of the data generating process), you could have something from or very close to a Poisson process, which would in turn be a way of getting data that's drawn from something close to a Poisson distribution. But the conditions don't hold in several ways... and the furthest from being true is number 3. There's no particular reason on that basis to assert a Poisson process, though the violations may not be so bad that the resulting data are far from Poisson. So we're back to statistical arguments that come from examining the data itself. As mentioned at the start, what you can do is check whether the data aren't obviously inconsistent with the underlying distribution being Poisson, but that doesn't tell you they are drawn from a Poisson (you can already be confident that they're not). You could do this check via goodness of fit tests. The chi-square that was mentioned is one such, but I wouldn't recommend the chi-square test for this situation myself**; it has low power against what many people would see as the most relevant deviations (e.g. a change in dispersion relative to a Poisson with the same mean, changes in skewness etc). If your aim is to have good power against those sort of effects, you won't get it that way. The main value of the chi-squared is in simplicity, and it has pedagogical value; outside that, it's usually not seen as particularly competitive as a goodness of fit test. ** Added in later edit: Now that it's clear this is homework, the chances that you're expected to do a chi-squared test to check the data are not inconsistent with a Poisson goes up quite a lot. See my example chi-square goodness of fit test, done below the first Poissonness plot People often do these tests for the wrong reason (e.g. because they want to say 'therefore it's okay to do some other statistical thing with the data that assumes that the data are Poisson'). The real question there is 'how badly wrong could that go?' ... and the goodness of fit tests aren't really much help with that question. Often the answer to that question is at best one that's independent (/nearly independent) of sample size —— and in some cases, one with consequences that tend to go away with sample size ... while a goodness of fit test is useless with small samples (where your risk from violations of assumptions is often at its largest). If you must test for a Poisson distribution there are a few reasonable alternatives. One would be to do something akin to an Anderson-Darling test, based on the AD statistic but using a simulated distribution under the null (to account for the twin problems of a discrete distribution and that you must estimate parameters). A simpler alternative might be a Smooth Test for goodness of fit - these are a collection of tests designed for individual distributions by modelling the data using a family of polynomials which are orthogonal with respect to the probability function in the null. Low order (i.e. interesting) alternatives are tested by testing whether the coefficients of the polynomials above the base one are different from zero, and these can usually deal with parameter estimation by omitting the lowest order terms from the test. There's such a test for the Poisson. I can dig up a reference if you need it. You might also use the correlation (or, to be more like a Shapiro-Francia test, perhaps $n(1-r^2)$) in a Poissonness plot - e.g. a plot of $\log(x_k)+\log(k!)$ vs $k$ (see Hoaglin, 1980) - as a test statistic. Here's an example of that calculation (and plot), done in R: y=rpois(100,5) n=length(y) (x=table(y)) y 0 1 2 3 4 5 6 7 8 9 10 1 2 7 15 19 25 14 7 5 1 4 k=as.numeric(names(x)) plot(k,c(log(x)+lfactorial(k))) Here's the statistic that I suggested could be used for a goodness of fit test of a Poisson: n*(1-cor(k,log(x)+lfactorial(k))^2) [1] 1.0599 Of course, to compute the p-value, you'd also need to simulate the distribution of the test statistic under the null (and I haven't discussed how one might deal with zero-counts inside the range of values). This should yield a reasonably powerful test. There are numerous other alternative tests. Here's an example of doing a Poissonness plot on a sample of size 50 from a geometric distribution (p=.3): As you see, it displays a clear 'kink', indicating nonlinearity References for the Poissonness plot would be: David C. Hoaglin (1980), "A Poissonness Plot", The American Statistician Vol. 34, No. 3 (Aug., ), pp. 146-149 and Hoaglin, D. and J. Tukey (1985), "9. Checking the Shape of Discrete Distributions", Exploring Data Tables, Trends and Shapes, (Hoaglin, Mosteller & Tukey eds) John Wiley & Sons The second reference contains an adjustment to the plot for small counts; you would probably want to incorporate it (but I don't have the reference to hand). Example of doing a chi-square goodness of fit test: Aside on performing the chi-square goodness of fit, the way it would usually be expected to be done in a lot of classes (though not the way I'd do it): 1: starting with your data, (which I will take to be the data I randomly generated in 'y' above, generate the table of counts: (x=table(y)) y 0 1 2 3 4 5 6 7 8 9 10 1 2 7 15 19 25 14 7 5 1 4 2: compute the expected value in each cell, assuming a Poisson fitted by ML: (expec=dpois(0:10,lambda=mean(y))*length(y)) [1] 0.7907054 3.8270142 9.2613743 14.9416838 18.0794374 17.5008954 14.1173890 9.7611661 [9] 5.9055055 3.1758496 1.5371112 3: note that the end categories are small; this makes the chi-square distribution less good as an approximation to the distribution of the test statistic (a common rule is you want expected values of at least 5, though numerous papers have shown that rule to be unnecessarily restrictive; I'll take it close, but the general approach can be adapted to a stricter rule). Collapse adjacent categories, so that minimum expected values are at least not too far below 5 (one category with an expected count down near 1 out of more than 10 categories isn't too bad, two is pretty borderline). Also note that we haven't yet accounted for the probability beyond "10", so we also need to incorporate that: expec[1]=sum(expec[1:2]) expec[2:8]=expec[3:9] expec[9]=length(y)-sum(expec[1:8]) expec=expec[1:9] expec sum(expec) # now adds to n 4: similarly, collapse categories on the observed: (obs=table(y)) obs[1]=sum(obs[1:2]) obs[2:8]=obs[3:9] obs[9]=sum(obs[10:11]) obs=obs[1:9] 5: Put into a table, (optionally) along with the contribution to chi-square $(O_i-E_i)^2/E_i$ and the Pearson residual (the signed square root of the contribution), these can be useful when trying to see where it doesn't fit so well: print(cbind(obs,expec,PearsonRes=(obs-expec)/sqrt(expec),ContribToChisq=(obs-expec)^2/expec),d=4) obs expec PearsonRes ContribToChisq 0 3 4.618 -0.75282 0.5667335 1 7 9.261 -0.74308 0.5521657 2 15 14.942 0.01509 0.0002276 3 19 18.079 0.21650 0.0468729 4 25 17.501 1.79258 3.2133538 5 14 14.117 -0.03124 0.0009761 6 7 9.761 -0.88377 0.7810581 7 5 5.906 -0.37262 0.1388434 8 5 5.815 -0.33791 0.1141816 6: Compute $X^2 = \sum_i (E_i-O_i)^2/E_i$, with loss of 1df for expected total matching the observed total, and 1 more for estimating the parameter: (chisq = sum((obs-expec)^2/expec)) [1] 5.414413 (df = length(obs)-1-1) # lose an additional df for parameter estimate [1] 7 (pvalue=pchisq(chisq,df)) [1] 0.3904736 Both the diagnostics and the p-value show no lack of fit here ... which we'd expect, since the data we generated actually were Poisson. Edit: here's a link to Rick Wicklin's blog which discusses the Poissonness plot, and talks about implementations in SAS and Matlab http://blogs.sas.com/content/iml/2012/04/12/the-poissonness-plot-a-goodness-of-fit-diagnostic/ Edit2: If I have it right, the modified Poissonness plot from the 1985 reference would be*: y=rpois(100,5) n=length(y) (x=table(y)) k=as.numeric(names(x)) x=as.vector(x) x1 = ifelse(x==0,NA,ifelse(x>1,x-.8*x/n-.67,exp(-1))) plot(k,log(x1)+lfactorial(k)) * They actually adjust the intercept as well, but I haven't done so here; it doesn't affect the appearance of the plot, but you have to take care if you implement anything else from the reference (such as the confidence intervals) if you do it at all differently from their approach. (For the above example the appearance hardly changes from the first Poissonness plot.)
How to know if a data follows a Poisson Distribution in R?
There are an infinite number of ways for a distribution to be slightly different from a Poisson distribution; you can't identify that a set of data is drawn from a Poisson distribution. What you can d
How to know if a data follows a Poisson Distribution in R? There are an infinite number of ways for a distribution to be slightly different from a Poisson distribution; you can't identify that a set of data is drawn from a Poisson distribution. What you can do is look for inconsistency with what you should see with a Poisson, but a lack of obvious inconsistency doesn't make it Poisson. However, what you're talking about there by checking those three criteria isn't checking that the data come from a Poisson distribution by statistical means (i.e. by looking at data), but by assessing whether the process the data are generated by satisfies the conditions of a Poisson process; if the conditions all held or almost held (and that's a consideration of the data generating process), you could have something from or very close to a Poisson process, which would in turn be a way of getting data that's drawn from something close to a Poisson distribution. But the conditions don't hold in several ways... and the furthest from being true is number 3. There's no particular reason on that basis to assert a Poisson process, though the violations may not be so bad that the resulting data are far from Poisson. So we're back to statistical arguments that come from examining the data itself. As mentioned at the start, what you can do is check whether the data aren't obviously inconsistent with the underlying distribution being Poisson, but that doesn't tell you they are drawn from a Poisson (you can already be confident that they're not). You could do this check via goodness of fit tests. The chi-square that was mentioned is one such, but I wouldn't recommend the chi-square test for this situation myself**; it has low power against what many people would see as the most relevant deviations (e.g. a change in dispersion relative to a Poisson with the same mean, changes in skewness etc). If your aim is to have good power against those sort of effects, you won't get it that way. The main value of the chi-squared is in simplicity, and it has pedagogical value; outside that, it's usually not seen as particularly competitive as a goodness of fit test. ** Added in later edit: Now that it's clear this is homework, the chances that you're expected to do a chi-squared test to check the data are not inconsistent with a Poisson goes up quite a lot. See my example chi-square goodness of fit test, done below the first Poissonness plot People often do these tests for the wrong reason (e.g. because they want to say 'therefore it's okay to do some other statistical thing with the data that assumes that the data are Poisson'). The real question there is 'how badly wrong could that go?' ... and the goodness of fit tests aren't really much help with that question. Often the answer to that question is at best one that's independent (/nearly independent) of sample size —— and in some cases, one with consequences that tend to go away with sample size ... while a goodness of fit test is useless with small samples (where your risk from violations of assumptions is often at its largest). If you must test for a Poisson distribution there are a few reasonable alternatives. One would be to do something akin to an Anderson-Darling test, based on the AD statistic but using a simulated distribution under the null (to account for the twin problems of a discrete distribution and that you must estimate parameters). A simpler alternative might be a Smooth Test for goodness of fit - these are a collection of tests designed for individual distributions by modelling the data using a family of polynomials which are orthogonal with respect to the probability function in the null. Low order (i.e. interesting) alternatives are tested by testing whether the coefficients of the polynomials above the base one are different from zero, and these can usually deal with parameter estimation by omitting the lowest order terms from the test. There's such a test for the Poisson. I can dig up a reference if you need it. You might also use the correlation (or, to be more like a Shapiro-Francia test, perhaps $n(1-r^2)$) in a Poissonness plot - e.g. a plot of $\log(x_k)+\log(k!)$ vs $k$ (see Hoaglin, 1980) - as a test statistic. Here's an example of that calculation (and plot), done in R: y=rpois(100,5) n=length(y) (x=table(y)) y 0 1 2 3 4 5 6 7 8 9 10 1 2 7 15 19 25 14 7 5 1 4 k=as.numeric(names(x)) plot(k,c(log(x)+lfactorial(k))) Here's the statistic that I suggested could be used for a goodness of fit test of a Poisson: n*(1-cor(k,log(x)+lfactorial(k))^2) [1] 1.0599 Of course, to compute the p-value, you'd also need to simulate the distribution of the test statistic under the null (and I haven't discussed how one might deal with zero-counts inside the range of values). This should yield a reasonably powerful test. There are numerous other alternative tests. Here's an example of doing a Poissonness plot on a sample of size 50 from a geometric distribution (p=.3): As you see, it displays a clear 'kink', indicating nonlinearity References for the Poissonness plot would be: David C. Hoaglin (1980), "A Poissonness Plot", The American Statistician Vol. 34, No. 3 (Aug., ), pp. 146-149 and Hoaglin, D. and J. Tukey (1985), "9. Checking the Shape of Discrete Distributions", Exploring Data Tables, Trends and Shapes, (Hoaglin, Mosteller & Tukey eds) John Wiley & Sons The second reference contains an adjustment to the plot for small counts; you would probably want to incorporate it (but I don't have the reference to hand). Example of doing a chi-square goodness of fit test: Aside on performing the chi-square goodness of fit, the way it would usually be expected to be done in a lot of classes (though not the way I'd do it): 1: starting with your data, (which I will take to be the data I randomly generated in 'y' above, generate the table of counts: (x=table(y)) y 0 1 2 3 4 5 6 7 8 9 10 1 2 7 15 19 25 14 7 5 1 4 2: compute the expected value in each cell, assuming a Poisson fitted by ML: (expec=dpois(0:10,lambda=mean(y))*length(y)) [1] 0.7907054 3.8270142 9.2613743 14.9416838 18.0794374 17.5008954 14.1173890 9.7611661 [9] 5.9055055 3.1758496 1.5371112 3: note that the end categories are small; this makes the chi-square distribution less good as an approximation to the distribution of the test statistic (a common rule is you want expected values of at least 5, though numerous papers have shown that rule to be unnecessarily restrictive; I'll take it close, but the general approach can be adapted to a stricter rule). Collapse adjacent categories, so that minimum expected values are at least not too far below 5 (one category with an expected count down near 1 out of more than 10 categories isn't too bad, two is pretty borderline). Also note that we haven't yet accounted for the probability beyond "10", so we also need to incorporate that: expec[1]=sum(expec[1:2]) expec[2:8]=expec[3:9] expec[9]=length(y)-sum(expec[1:8]) expec=expec[1:9] expec sum(expec) # now adds to n 4: similarly, collapse categories on the observed: (obs=table(y)) obs[1]=sum(obs[1:2]) obs[2:8]=obs[3:9] obs[9]=sum(obs[10:11]) obs=obs[1:9] 5: Put into a table, (optionally) along with the contribution to chi-square $(O_i-E_i)^2/E_i$ and the Pearson residual (the signed square root of the contribution), these can be useful when trying to see where it doesn't fit so well: print(cbind(obs,expec,PearsonRes=(obs-expec)/sqrt(expec),ContribToChisq=(obs-expec)^2/expec),d=4) obs expec PearsonRes ContribToChisq 0 3 4.618 -0.75282 0.5667335 1 7 9.261 -0.74308 0.5521657 2 15 14.942 0.01509 0.0002276 3 19 18.079 0.21650 0.0468729 4 25 17.501 1.79258 3.2133538 5 14 14.117 -0.03124 0.0009761 6 7 9.761 -0.88377 0.7810581 7 5 5.906 -0.37262 0.1388434 8 5 5.815 -0.33791 0.1141816 6: Compute $X^2 = \sum_i (E_i-O_i)^2/E_i$, with loss of 1df for expected total matching the observed total, and 1 more for estimating the parameter: (chisq = sum((obs-expec)^2/expec)) [1] 5.414413 (df = length(obs)-1-1) # lose an additional df for parameter estimate [1] 7 (pvalue=pchisq(chisq,df)) [1] 0.3904736 Both the diagnostics and the p-value show no lack of fit here ... which we'd expect, since the data we generated actually were Poisson. Edit: here's a link to Rick Wicklin's blog which discusses the Poissonness plot, and talks about implementations in SAS and Matlab http://blogs.sas.com/content/iml/2012/04/12/the-poissonness-plot-a-goodness-of-fit-diagnostic/ Edit2: If I have it right, the modified Poissonness plot from the 1985 reference would be*: y=rpois(100,5) n=length(y) (x=table(y)) k=as.numeric(names(x)) x=as.vector(x) x1 = ifelse(x==0,NA,ifelse(x>1,x-.8*x/n-.67,exp(-1))) plot(k,log(x1)+lfactorial(k)) * They actually adjust the intercept as well, but I haven't done so here; it doesn't affect the appearance of the plot, but you have to take care if you implement anything else from the reference (such as the confidence intervals) if you do it at all differently from their approach. (For the above example the appearance hardly changes from the first Poissonness plot.)
How to know if a data follows a Poisson Distribution in R? There are an infinite number of ways for a distribution to be slightly different from a Poisson distribution; you can't identify that a set of data is drawn from a Poisson distribution. What you can d
8,548
How to know if a data follows a Poisson Distribution in R?
Perform the chi-squared goodness of fit test. In case of count data, we can use goodfit() included in the vcd package. Note that if the p value is larger than 0.05, we can not reject h0: the process is a Poisson process. Or else, it is not a Poisson process. # load the vcd package library(vcd) ## loading vcd package # generate two processes for test set.seed(2014);y=rpois(200,5) set.seed(2014);y=rnorm(100, 5, 0.3) # goodfit asks for non-negative values # output the results gf = goodfit(y,type= "poisson",method= "ML") plot(gf,main="Count data vs Poisson distribution") summary(gf) # to automatically get the pvalue gf.summary = capture.output(summary(gf))[[5]] pvalue = unlist(strsplit(gf.summary, split = " ")) pvalue = as.numeric(pvalue[length(pvalue)]); pvalue # to mannualy compute the pvalue chisq = sum( (gf$observed-gf$fitted)^2/gf$fitted ) df = length(gf$observed)-1-1 pvalue = pchisq(chisq,df) pvalue
How to know if a data follows a Poisson Distribution in R?
Perform the chi-squared goodness of fit test. In case of count data, we can use goodfit() included in the vcd package. Note that if the p value is larger than 0.05, we can not reject h0: the process i
How to know if a data follows a Poisson Distribution in R? Perform the chi-squared goodness of fit test. In case of count data, we can use goodfit() included in the vcd package. Note that if the p value is larger than 0.05, we can not reject h0: the process is a Poisson process. Or else, it is not a Poisson process. # load the vcd package library(vcd) ## loading vcd package # generate two processes for test set.seed(2014);y=rpois(200,5) set.seed(2014);y=rnorm(100, 5, 0.3) # goodfit asks for non-negative values # output the results gf = goodfit(y,type= "poisson",method= "ML") plot(gf,main="Count data vs Poisson distribution") summary(gf) # to automatically get the pvalue gf.summary = capture.output(summary(gf))[[5]] pvalue = unlist(strsplit(gf.summary, split = " ")) pvalue = as.numeric(pvalue[length(pvalue)]); pvalue # to mannualy compute the pvalue chisq = sum( (gf$observed-gf$fitted)^2/gf$fitted ) df = length(gf$observed)-1-1 pvalue = pchisq(chisq,df) pvalue
How to know if a data follows a Poisson Distribution in R? Perform the chi-squared goodness of fit test. In case of count data, we can use goodfit() included in the vcd package. Note that if the p value is larger than 0.05, we can not reject h0: the process i
8,549
What is an acceptable value of the Calinski & Harabasz (CH) criterion?
There are a few things one should be aware of. Like most internal clustering criteria, Calinski-Harabasz is a heuristic device. The proper way to use it is to compare clustering solutions obtained on the same data, - solutions which differ either by the number of clusters or by the clustering method used. There is no "acceptable" cut-off value. You simply compare CH values by eye. The higher the value, the "better" is the solution. If on the line-plot of CH values there appears that one solution give a peak or at least an abrupt elbow, choose it. If, on the contrary, the line is smooth - horizontal or ascending or descending - then there is no reason to prefer one solution to others. CH criterion is based on ANOVA ideology. Hence, it implies that the clustered objects lie in Euclidean space of scale (not ordinal or binary or nominal) variables. If the data clustered were not objects X variables but a matrix of dissimilarities between objects then the dissimilarity measure should be (squared) euclidean distance (or, at worse, am other metric distance approaching euclidean distance by properties). CH criterion is most suitable in case when clusters are more or less spherical and compact in their middle (such as normally distributed, for instance)$^1$. Other conditions being equal, CH tends to prefer cluster solutions with clusters consisting of roughly the same number of objects. Let's observe an example. Below is a scatterplot of data that were generated as 5 normally distributed clusters which lie quite close to each other. These data were clustered by hierarchical average-linkage method, and all cluster solutions (cluster memberships) from 15-cluster through 2-cluster solution were saved. Then two clustering criteria were applied to compare the solutions and to select the "better" one, if there is any. Plot for Calinski-Harabasz is on the left. We see that - in this example - CH plainly indicates 5-cluster solution (labelled CLU5_1) as the best one. Plot for another clustering criterion, C-Index (which is not based on ANOVA ideology and is more universal in its application than CH) is on the right. For C-Index, a lower value indicates a "better" solution. As the plot shows, 15-cluster solution is formally the best. But remember that with clustering criteria rugged topography is more important in decision than the magnitude itself. Note there is the elbow at 5-cluster solution; 5-cluster solution is still relatively good while 4- or 3-cluster solutions deteriorate by leaps. Since we usually wish to get "a better solution with less clusters", the choice of 5-cluster solution appears to be reasonable under C-Index testing, too. P.S. This post also brings up the question whether we should trust more the actual maximum (or minimum) of a clustering criterion or rather a landscape of the plot of its values. $^1$ Later note. Not quite so as written. My probes on simulated datasets convince me that CH has no preference to bell shape distribution over platykurtic one (such as in a ball) or to circular clusters over ellipsoidal ones, - if keeping intracluster overall variances and intercluster centroid separation the same. One nuance worth to keep in mind, however, is that if clusters are required (as usual) to be nonoverlapping in space then a good cluster configuration with round clusters is just easier to encounter in real practice as a similarly good configuration with oblong clusters ("pencils in a case" effect); that has nothing to do with a clustering criterion's biases. An overview of internal clustering criteria and how to use them.
What is an acceptable value of the Calinski & Harabasz (CH) criterion?
There are a few things one should be aware of. Like most internal clustering criteria, Calinski-Harabasz is a heuristic device. The proper way to use it is to compare clustering solutions obtained on
What is an acceptable value of the Calinski & Harabasz (CH) criterion? There are a few things one should be aware of. Like most internal clustering criteria, Calinski-Harabasz is a heuristic device. The proper way to use it is to compare clustering solutions obtained on the same data, - solutions which differ either by the number of clusters or by the clustering method used. There is no "acceptable" cut-off value. You simply compare CH values by eye. The higher the value, the "better" is the solution. If on the line-plot of CH values there appears that one solution give a peak or at least an abrupt elbow, choose it. If, on the contrary, the line is smooth - horizontal or ascending or descending - then there is no reason to prefer one solution to others. CH criterion is based on ANOVA ideology. Hence, it implies that the clustered objects lie in Euclidean space of scale (not ordinal or binary or nominal) variables. If the data clustered were not objects X variables but a matrix of dissimilarities between objects then the dissimilarity measure should be (squared) euclidean distance (or, at worse, am other metric distance approaching euclidean distance by properties). CH criterion is most suitable in case when clusters are more or less spherical and compact in their middle (such as normally distributed, for instance)$^1$. Other conditions being equal, CH tends to prefer cluster solutions with clusters consisting of roughly the same number of objects. Let's observe an example. Below is a scatterplot of data that were generated as 5 normally distributed clusters which lie quite close to each other. These data were clustered by hierarchical average-linkage method, and all cluster solutions (cluster memberships) from 15-cluster through 2-cluster solution were saved. Then two clustering criteria were applied to compare the solutions and to select the "better" one, if there is any. Plot for Calinski-Harabasz is on the left. We see that - in this example - CH plainly indicates 5-cluster solution (labelled CLU5_1) as the best one. Plot for another clustering criterion, C-Index (which is not based on ANOVA ideology and is more universal in its application than CH) is on the right. For C-Index, a lower value indicates a "better" solution. As the plot shows, 15-cluster solution is formally the best. But remember that with clustering criteria rugged topography is more important in decision than the magnitude itself. Note there is the elbow at 5-cluster solution; 5-cluster solution is still relatively good while 4- or 3-cluster solutions deteriorate by leaps. Since we usually wish to get "a better solution with less clusters", the choice of 5-cluster solution appears to be reasonable under C-Index testing, too. P.S. This post also brings up the question whether we should trust more the actual maximum (or minimum) of a clustering criterion or rather a landscape of the plot of its values. $^1$ Later note. Not quite so as written. My probes on simulated datasets convince me that CH has no preference to bell shape distribution over platykurtic one (such as in a ball) or to circular clusters over ellipsoidal ones, - if keeping intracluster overall variances and intercluster centroid separation the same. One nuance worth to keep in mind, however, is that if clusters are required (as usual) to be nonoverlapping in space then a good cluster configuration with round clusters is just easier to encounter in real practice as a similarly good configuration with oblong clusters ("pencils in a case" effect); that has nothing to do with a clustering criterion's biases. An overview of internal clustering criteria and how to use them.
What is an acceptable value of the Calinski & Harabasz (CH) criterion? There are a few things one should be aware of. Like most internal clustering criteria, Calinski-Harabasz is a heuristic device. The proper way to use it is to compare clustering solutions obtained on
8,550
How to obtain a confidence interval for a percentile?
This question, which covers a common situation, deserves a simple, non-approximate answer. Fortunately, there is one. Suppose $X_1, \ldots, X_n$ are independent values from an unknown distribution $F$ whose $q^\text{th}$ quantile I will write $F^{-1}(q)$. This means each $X_i$ has a chance of (at least) $q$ of being less than or equal to $F^{-1}(q)$. Consequently the number of $X_i$ less than or equal to $F^{-1}(q)$ has a Binomial$(n,q)$ distribution. Motivated by this simple consideration, Gerald Hahn and William Meeker in their handbook Statistical Intervals (Wiley 1991) write A two-sided distribution-free conservative $100(1-\alpha)\%$ confidence interval for $F^{-1}(q)$ is obtained ... as $[X_{(l)}, X_{(u)}]$ where $X_{(1)}\le X_{(2)}\le \cdots \le X_{(n)}$ are the order statistics of the sample. They proceed to say One can choose integers $0 \le l \le u \le n$ symmetrically (or nearly symmetrically) around $q(n+1)$ and as close together as possible subject to the requirements that $$B(u-1;n,q) - B(l-1;n,q) \ge 1-\alpha.\tag{1}$$ The expression at the left is the chance that a Binomial$(n,q)$ variable has one of the values $\{l, l+1, \ldots, u-1\}$. Evidently, this is the chance that the number of data values $X_i$ falling within the lower $100q\%$ of the distribution is neither too small (less than $l$) nor too large ($u$ or greater). Hahn and Meeker follow with some useful remarks, which I will quote. The preceding interval is conservative because the actual confidence level, given by the left-hand side of Equation $(1)$, is greater than the specified value $1-\alpha$. ... It is sometimes impossible to construct a distribution-free statistical interval that has at least the desired confidence level. This problem is particularly acute when estimating percentiles in the tail of a distribution from a small sample. ... In some cases, the analyst can cope with this problem by choosing $l$ and $u$ nonsymmetrically. Another alternative may be to use a reduced confidence level. Let's work through an example (also provided by Hahn & Meeker). They supply an ordered set of $n=100$ "measurements of a compound from a chemical process" and ask for a $100(1-\alpha)=95\%$ confidence interval for the $q=0.90$ percentile. They claim $l=85$ and $u=97$ will work. The total probability of this interval, as shown by the blue bars in the figure, is $95.3\%$: that's as close as one can get to $95\%$, yet still be above it, by choosing two cutoffs and eliminating all chances in the left tail and the right tail that are beyond those cutoffs. Here are the data, shown in order, leaving out $81$ of the values from the middle: $$\matrix{ 1.49&1.66&2.05&\ldots&\mathbf {24.33}&24.72&25.46&25.67&25.77&26.64\\ 28.28&28.28&29.07&29.16&31.14&31.83&\mathbf{33.24}&37.32&53.43&58.11}$$ The $85^\text{th}$ largest is $24.33$ and the $97^\text{th}$ largest is $33.24$. The interval therefore is $[24.33, 33.24]$. Let's re-interpret that. This procedure was supposed to have at least a $95\%$ chance of covering the $90^\text{th}$ percentile. If that percentile actually exceeds $33.24$, that means we will have observed $97$ or more out of $100$ values in our sample that are below the $90^\text{th}$ percentile. That's too many. If that percentile is less than $24.33$, that means we will have observed $84$ or fewer values in our sample that are below the $90^\text{th}$ percentile. That's too few. In either case--exactly as indicated by the red bars in the figure--it would be evidence against the $90^\text{th}$ percentile lying within this interval. One way to find good choices of $l$ and $u$ is to search according to your needs. Here is a method that starts with a symmetric approximate interval and then searches by varying both $l$ and $u$ by up to $2$ in order to find an interval with good coverage (if possible). It is illustrated with R code. It is set up to check the coverage in the preceding example for a Normal distribution. Its output is Simulation mean coverage was 0.9503; expected coverage is 0.9523 The agreement between simulation and expectation is excellent. # # Near-symmetric distribution-free confidence interval for a quantile `q`. # Returns indexes into the order statistics. # quantile.CI <- function(n, q, alpha=0.05) { # # Search over a small range of upper and lower order statistics for the # closest coverage to 1-alpha (but not less than it, if possible). # u <- qbinom(1-alpha/2, n, q) + (-2:2) + 1 l <- qbinom(alpha/2, n, q) + (-2:2) u[u > n] <- Inf l[l < 0] <- -Inf coverage <- outer(l, u, function(a,b) pbinom(b-1,n,q) - pbinom(a-1,n,q)) if (max(coverage) < 1-alpha) i <- which(coverage==max(coverage)) else i <- which(coverage == min(coverage[coverage >= 1-alpha])) i <- i[1] # # Return the order statistics and the actual coverage. # u <- rep(u, each=5)[i] l <- rep(l, 5)[i] return(list(Interval=c(l,u), Coverage=coverage[i])) } # # Example: test coverage via simulation. # n <- 100 # Sample size q <- 0.90 # Percentile # # You only have to compute the order statistics once for any given (n,q). # lu <- quantile.CI(n, q)$Interval # # Generate many random samples from a known distribution and compute # CIs from those samples. # set.seed(17) n.sim <- 1e4 index <- function(x, i) ifelse(i==Inf, Inf, ifelse(i==-Inf, -Inf, x[i])) sim <- replicate(n.sim, index(sort(rnorm(n)), lu)) # # Compute the proportion of those intervals that cover the percentile. # F.q <- qnorm(q) covers <- sim[1, ] <= F.q & F.q <= sim[2, ] # # Report the result. # message("Simulation mean coverage was ", signif(mean(covers), 4), "; expected coverage is ", signif(quantile.CI(n,q)$Coverage, 4))
How to obtain a confidence interval for a percentile?
This question, which covers a common situation, deserves a simple, non-approximate answer. Fortunately, there is one. Suppose $X_1, \ldots, X_n$ are independent values from an unknown distribution $F
How to obtain a confidence interval for a percentile? This question, which covers a common situation, deserves a simple, non-approximate answer. Fortunately, there is one. Suppose $X_1, \ldots, X_n$ are independent values from an unknown distribution $F$ whose $q^\text{th}$ quantile I will write $F^{-1}(q)$. This means each $X_i$ has a chance of (at least) $q$ of being less than or equal to $F^{-1}(q)$. Consequently the number of $X_i$ less than or equal to $F^{-1}(q)$ has a Binomial$(n,q)$ distribution. Motivated by this simple consideration, Gerald Hahn and William Meeker in their handbook Statistical Intervals (Wiley 1991) write A two-sided distribution-free conservative $100(1-\alpha)\%$ confidence interval for $F^{-1}(q)$ is obtained ... as $[X_{(l)}, X_{(u)}]$ where $X_{(1)}\le X_{(2)}\le \cdots \le X_{(n)}$ are the order statistics of the sample. They proceed to say One can choose integers $0 \le l \le u \le n$ symmetrically (or nearly symmetrically) around $q(n+1)$ and as close together as possible subject to the requirements that $$B(u-1;n,q) - B(l-1;n,q) \ge 1-\alpha.\tag{1}$$ The expression at the left is the chance that a Binomial$(n,q)$ variable has one of the values $\{l, l+1, \ldots, u-1\}$. Evidently, this is the chance that the number of data values $X_i$ falling within the lower $100q\%$ of the distribution is neither too small (less than $l$) nor too large ($u$ or greater). Hahn and Meeker follow with some useful remarks, which I will quote. The preceding interval is conservative because the actual confidence level, given by the left-hand side of Equation $(1)$, is greater than the specified value $1-\alpha$. ... It is sometimes impossible to construct a distribution-free statistical interval that has at least the desired confidence level. This problem is particularly acute when estimating percentiles in the tail of a distribution from a small sample. ... In some cases, the analyst can cope with this problem by choosing $l$ and $u$ nonsymmetrically. Another alternative may be to use a reduced confidence level. Let's work through an example (also provided by Hahn & Meeker). They supply an ordered set of $n=100$ "measurements of a compound from a chemical process" and ask for a $100(1-\alpha)=95\%$ confidence interval for the $q=0.90$ percentile. They claim $l=85$ and $u=97$ will work. The total probability of this interval, as shown by the blue bars in the figure, is $95.3\%$: that's as close as one can get to $95\%$, yet still be above it, by choosing two cutoffs and eliminating all chances in the left tail and the right tail that are beyond those cutoffs. Here are the data, shown in order, leaving out $81$ of the values from the middle: $$\matrix{ 1.49&1.66&2.05&\ldots&\mathbf {24.33}&24.72&25.46&25.67&25.77&26.64\\ 28.28&28.28&29.07&29.16&31.14&31.83&\mathbf{33.24}&37.32&53.43&58.11}$$ The $85^\text{th}$ largest is $24.33$ and the $97^\text{th}$ largest is $33.24$. The interval therefore is $[24.33, 33.24]$. Let's re-interpret that. This procedure was supposed to have at least a $95\%$ chance of covering the $90^\text{th}$ percentile. If that percentile actually exceeds $33.24$, that means we will have observed $97$ or more out of $100$ values in our sample that are below the $90^\text{th}$ percentile. That's too many. If that percentile is less than $24.33$, that means we will have observed $84$ or fewer values in our sample that are below the $90^\text{th}$ percentile. That's too few. In either case--exactly as indicated by the red bars in the figure--it would be evidence against the $90^\text{th}$ percentile lying within this interval. One way to find good choices of $l$ and $u$ is to search according to your needs. Here is a method that starts with a symmetric approximate interval and then searches by varying both $l$ and $u$ by up to $2$ in order to find an interval with good coverage (if possible). It is illustrated with R code. It is set up to check the coverage in the preceding example for a Normal distribution. Its output is Simulation mean coverage was 0.9503; expected coverage is 0.9523 The agreement between simulation and expectation is excellent. # # Near-symmetric distribution-free confidence interval for a quantile `q`. # Returns indexes into the order statistics. # quantile.CI <- function(n, q, alpha=0.05) { # # Search over a small range of upper and lower order statistics for the # closest coverage to 1-alpha (but not less than it, if possible). # u <- qbinom(1-alpha/2, n, q) + (-2:2) + 1 l <- qbinom(alpha/2, n, q) + (-2:2) u[u > n] <- Inf l[l < 0] <- -Inf coverage <- outer(l, u, function(a,b) pbinom(b-1,n,q) - pbinom(a-1,n,q)) if (max(coverage) < 1-alpha) i <- which(coverage==max(coverage)) else i <- which(coverage == min(coverage[coverage >= 1-alpha])) i <- i[1] # # Return the order statistics and the actual coverage. # u <- rep(u, each=5)[i] l <- rep(l, 5)[i] return(list(Interval=c(l,u), Coverage=coverage[i])) } # # Example: test coverage via simulation. # n <- 100 # Sample size q <- 0.90 # Percentile # # You only have to compute the order statistics once for any given (n,q). # lu <- quantile.CI(n, q)$Interval # # Generate many random samples from a known distribution and compute # CIs from those samples. # set.seed(17) n.sim <- 1e4 index <- function(x, i) ifelse(i==Inf, Inf, ifelse(i==-Inf, -Inf, x[i])) sim <- replicate(n.sim, index(sort(rnorm(n)), lu)) # # Compute the proportion of those intervals that cover the percentile. # F.q <- qnorm(q) covers <- sim[1, ] <= F.q & F.q <= sim[2, ] # # Report the result. # message("Simulation mean coverage was ", signif(mean(covers), 4), "; expected coverage is ", signif(quantile.CI(n,q)$Coverage, 4))
How to obtain a confidence interval for a percentile? This question, which covers a common situation, deserves a simple, non-approximate answer. Fortunately, there is one. Suppose $X_1, \ldots, X_n$ are independent values from an unknown distribution $F
8,551
How to obtain a confidence interval for a percentile?
Derivation The $\tau$-quantile $q_\tau$ (this is the more general concept than percentile) of a random variable $X$ is given by $F_X^{-1}(\tau)$. The sample counterpart can be written as $\hat{q}_\tau = \hat{F}^{-1}(\tau)$ -- this is just the sample quantile. We are interested in the distribution of: $\sqrt{n}(\hat{q}_\tau - q_\tau)$ First, we need the asymptotic distribution of the empirical cdf. Since $\hat{F}(x) = \frac{1}{n} \sum 1\{X_i < x\}$, you can use the central limit theorem. $1\{X_i < x\}$ is a bernoulli random variable, so the mean is $P(X_i < x) = F(x)$ and the variance is $F(x)(1-F(x))$. $\sqrt{n}(\hat{F}(x) - F(x)) \rightarrow N(0, F(x)(1-F(x))) \qquad (1)$ Now, because inverse is a continuous function, we can use the delta method. [**The delta method says that if $\sqrt{n}(\overline{y} - \mu_y) \rightarrow N(0,\sigma^2)$, and $g(\cdot)$ is a continuous function, then $\sqrt{n}(g(\overline{y}) - g(\mu_y)) \rightarrow N(0, \sigma^2 (g'(\mu_y))^2)$ **] In the left hand side of (1), take $x=q_\tau$, and $g(\cdot) = F^{-1}(\cdot)$ $\sqrt{n}(F^{-1}(\hat{F}(q_\tau)) - F^{-1}(F(q_\tau))) = \sqrt{n}(\hat{q}_\tau - q_\tau)$ [** note that there is a bit of a slight of hand in the last step because $F^{-1}(\hat{F}(q_\tau)) \neq \hat{F}^{-1}(\hat{F}(q_\tau)) = \hat{q}_\tau$, but they are the asymptotically equal if tedious to show **] Now, apply the delta method mentioned above. Since $\frac{\textrm{d}}{\textrm{d}x} F^{-1}(x) = \frac{1}{f(F^{-1}(x))}$ (inverse function theorem) $\sqrt{n}(\hat{q}_\tau - q_\tau) \rightarrow N\left(0, \frac{F(q_\tau)(1-F(q_\tau))}{f(F^{-1}(F(q_\tau)))^2}\right) = N\left(0, \frac{F(q_\tau)(1-F(q_\tau))}{f(q_\tau)^2}\right)$ Then, to construct the confidence interval, we need to calculate the standard error by plugging in sample counterparts of each of the terms in the variance above: Result So $se(\hat{q}_\tau) = \sqrt{\frac{\hat{F}(\hat{q}_\tau)(1-\hat{F}(\hat{q}_\tau))}{n \hat{f}(\hat{q}_\tau)^2}} =$ $\sqrt{\frac{\tau (1 - \tau)}{n \hat{f}(\hat{q}_\tau)^2}}$ And $CI_{0.95}(\hat{q}_\tau) = \hat{q}_\tau \pm 1.96 se(\hat{q}_\tau)$ This will require you to estimate the density of $X$, but this should be pretty straightforward. Alternatively, you could bootstrap the CI pretty easily too.
How to obtain a confidence interval for a percentile?
Derivation The $\tau$-quantile $q_\tau$ (this is the more general concept than percentile) of a random variable $X$ is given by $F_X^{-1}(\tau)$. The sample counterpart can be written as $\hat{q}_\ta
How to obtain a confidence interval for a percentile? Derivation The $\tau$-quantile $q_\tau$ (this is the more general concept than percentile) of a random variable $X$ is given by $F_X^{-1}(\tau)$. The sample counterpart can be written as $\hat{q}_\tau = \hat{F}^{-1}(\tau)$ -- this is just the sample quantile. We are interested in the distribution of: $\sqrt{n}(\hat{q}_\tau - q_\tau)$ First, we need the asymptotic distribution of the empirical cdf. Since $\hat{F}(x) = \frac{1}{n} \sum 1\{X_i < x\}$, you can use the central limit theorem. $1\{X_i < x\}$ is a bernoulli random variable, so the mean is $P(X_i < x) = F(x)$ and the variance is $F(x)(1-F(x))$. $\sqrt{n}(\hat{F}(x) - F(x)) \rightarrow N(0, F(x)(1-F(x))) \qquad (1)$ Now, because inverse is a continuous function, we can use the delta method. [**The delta method says that if $\sqrt{n}(\overline{y} - \mu_y) \rightarrow N(0,\sigma^2)$, and $g(\cdot)$ is a continuous function, then $\sqrt{n}(g(\overline{y}) - g(\mu_y)) \rightarrow N(0, \sigma^2 (g'(\mu_y))^2)$ **] In the left hand side of (1), take $x=q_\tau$, and $g(\cdot) = F^{-1}(\cdot)$ $\sqrt{n}(F^{-1}(\hat{F}(q_\tau)) - F^{-1}(F(q_\tau))) = \sqrt{n}(\hat{q}_\tau - q_\tau)$ [** note that there is a bit of a slight of hand in the last step because $F^{-1}(\hat{F}(q_\tau)) \neq \hat{F}^{-1}(\hat{F}(q_\tau)) = \hat{q}_\tau$, but they are the asymptotically equal if tedious to show **] Now, apply the delta method mentioned above. Since $\frac{\textrm{d}}{\textrm{d}x} F^{-1}(x) = \frac{1}{f(F^{-1}(x))}$ (inverse function theorem) $\sqrt{n}(\hat{q}_\tau - q_\tau) \rightarrow N\left(0, \frac{F(q_\tau)(1-F(q_\tau))}{f(F^{-1}(F(q_\tau)))^2}\right) = N\left(0, \frac{F(q_\tau)(1-F(q_\tau))}{f(q_\tau)^2}\right)$ Then, to construct the confidence interval, we need to calculate the standard error by plugging in sample counterparts of each of the terms in the variance above: Result So $se(\hat{q}_\tau) = \sqrt{\frac{\hat{F}(\hat{q}_\tau)(1-\hat{F}(\hat{q}_\tau))}{n \hat{f}(\hat{q}_\tau)^2}} =$ $\sqrt{\frac{\tau (1 - \tau)}{n \hat{f}(\hat{q}_\tau)^2}}$ And $CI_{0.95}(\hat{q}_\tau) = \hat{q}_\tau \pm 1.96 se(\hat{q}_\tau)$ This will require you to estimate the density of $X$, but this should be pretty straightforward. Alternatively, you could bootstrap the CI pretty easily too.
How to obtain a confidence interval for a percentile? Derivation The $\tau$-quantile $q_\tau$ (this is the more general concept than percentile) of a random variable $X$ is given by $F_X^{-1}(\tau)$. The sample counterpart can be written as $\hat{q}_\ta
8,552
How to obtain a confidence interval for a percentile?
A brute-force computing intensive solution is to use the bootstrap resampling method. The following function returns the bootstrap confidence intervals of a quantile. quantile.CI.via.bootstrap <- function(x, p, alpha = 0.1) { ## Purpose: ## Calculate a two-sided confidence interval with confidence level of (1 - alpha) for ## a quantile, based on the (computing intensive) bootstrap resampling method. ## ## Arguments: ## - x: a vector of values, representing a data sample. ## - p: probability cutpoint for the quantile (between 0 and 1). ## - alpha: type I error level (default to 0.1 so a 90% CI is calculated) ## ## Return: ## - CI: the lower and upper limits of the two-sided CI. q <- quantile(x, probs = p) message("Quantile Point Estimate = ", q, " (Probability Cutpoint = ", p, ")\n") ## Bootstrap resampling with 2000 replications library(boot) set.seed(1) b <- boot(x, function(x, i) quantile(x[i], probs = p), R = 2000) boot.ci(b, conf = 1 - alpha, type = c("norm", "basic", "perc", "bca")) } if (F) { # Unit Test x <- 1:100 p <- 0.9 alpha <- 0.05 quantile.CI.via.bootstrap(x, p, alpha) ## Intervals : ## Level Normal Basic ## 95% (84.50, 96.34 ) (85.10, 97.10 ) ## Level Percentile BCa ## 95% (83.1, 95.1 ) (83.3, 95.1 ) } You may note the "Basic" bootstrap method returns an interval [85, 97] that aligns with the analytical method (binomial distribution) in the previous post.
How to obtain a confidence interval for a percentile?
A brute-force computing intensive solution is to use the bootstrap resampling method. The following function returns the bootstrap confidence intervals of a quantile. quantile.CI.via.bootstrap <- func
How to obtain a confidence interval for a percentile? A brute-force computing intensive solution is to use the bootstrap resampling method. The following function returns the bootstrap confidence intervals of a quantile. quantile.CI.via.bootstrap <- function(x, p, alpha = 0.1) { ## Purpose: ## Calculate a two-sided confidence interval with confidence level of (1 - alpha) for ## a quantile, based on the (computing intensive) bootstrap resampling method. ## ## Arguments: ## - x: a vector of values, representing a data sample. ## - p: probability cutpoint for the quantile (between 0 and 1). ## - alpha: type I error level (default to 0.1 so a 90% CI is calculated) ## ## Return: ## - CI: the lower and upper limits of the two-sided CI. q <- quantile(x, probs = p) message("Quantile Point Estimate = ", q, " (Probability Cutpoint = ", p, ")\n") ## Bootstrap resampling with 2000 replications library(boot) set.seed(1) b <- boot(x, function(x, i) quantile(x[i], probs = p), R = 2000) boot.ci(b, conf = 1 - alpha, type = c("norm", "basic", "perc", "bca")) } if (F) { # Unit Test x <- 1:100 p <- 0.9 alpha <- 0.05 quantile.CI.via.bootstrap(x, p, alpha) ## Intervals : ## Level Normal Basic ## 95% (84.50, 96.34 ) (85.10, 97.10 ) ## Level Percentile BCa ## 95% (83.1, 95.1 ) (83.3, 95.1 ) } You may note the "Basic" bootstrap method returns an interval [85, 97] that aligns with the analytical method (binomial distribution) in the previous post.
How to obtain a confidence interval for a percentile? A brute-force computing intensive solution is to use the bootstrap resampling method. The following function returns the bootstrap confidence intervals of a quantile. quantile.CI.via.bootstrap <- func
8,553
How do I decide what span to use in LOESS regression in R?
A cross-validation is often used, for example k-fold, if the aim is to find a fit with lowest RMSEP. Split your data into k groups and, leaving each group out in turn, fit a loess model using the k-1 groups of data and a chosen value of the smoothing parameter, and use that model to predict for the left out group. Store the predicted values for the left out group and then repeat until each of the k groups has been left out once. Using the set of predicted values, compute RMSEP. Then repeat the whole thing for each value of the smoothing parameter you wish to tune over. Select that smoothing parameter that gives lowest RMSEP under CV. This is, as you can see, fairly computationally heavy. I would be surprised if there wasn't a generalised cross-validation (GCV) alternative to true CV that you could use with LOESS - Hastie et al (section 6.2) indicate this is quite simple to do and is covered in one of their exercises. I suggest you read section 6.1.1, 6.1.2 and 6.2, plus the sections on regularisation of smoothing splines (as the content applies here too) in Chapter 5 of Hastie et al. (2009) The Elements of Statistical Learning: Data mining, inference, and prediction. 2nd Edition. Springer. The PDF can be downloaded for free.
How do I decide what span to use in LOESS regression in R?
A cross-validation is often used, for example k-fold, if the aim is to find a fit with lowest RMSEP. Split your data into k groups and, leaving each group out in turn, fit a loess model using the k-1
How do I decide what span to use in LOESS regression in R? A cross-validation is often used, for example k-fold, if the aim is to find a fit with lowest RMSEP. Split your data into k groups and, leaving each group out in turn, fit a loess model using the k-1 groups of data and a chosen value of the smoothing parameter, and use that model to predict for the left out group. Store the predicted values for the left out group and then repeat until each of the k groups has been left out once. Using the set of predicted values, compute RMSEP. Then repeat the whole thing for each value of the smoothing parameter you wish to tune over. Select that smoothing parameter that gives lowest RMSEP under CV. This is, as you can see, fairly computationally heavy. I would be surprised if there wasn't a generalised cross-validation (GCV) alternative to true CV that you could use with LOESS - Hastie et al (section 6.2) indicate this is quite simple to do and is covered in one of their exercises. I suggest you read section 6.1.1, 6.1.2 and 6.2, plus the sections on regularisation of smoothing splines (as the content applies here too) in Chapter 5 of Hastie et al. (2009) The Elements of Statistical Learning: Data mining, inference, and prediction. 2nd Edition. Springer. The PDF can be downloaded for free.
How do I decide what span to use in LOESS regression in R? A cross-validation is often used, for example k-fold, if the aim is to find a fit with lowest RMSEP. Split your data into k groups and, leaving each group out in turn, fit a loess model using the k-1
8,554
How do I decide what span to use in LOESS regression in R?
I suggest checking out generalized additive models (GAM, see the mgcv package in R). I'm just learning about them myself, but they seem to automatically figure out how much "wiggly-ness" is justified by the data. I also see that you're dealing with binomial data (strike vs not a strike), so be sure to analyze the raw data (i.e. don't aggregate to proportions, use the raw pitch-by-pitch data) and use family='binomial' (assuming that you're going to use R). If you have information about what individual pitchers and hitters are contributing to the data, you can probably increase your power by doing a generalized additive mixed model (GAMM, see the gamm4 package in R) and specifying pitcher and hitter as random effects (and again, setting family='binomial'). Finally, you probably want to allow for an interaction between the smooths of X & Y, but I've never tried this myself so I don't know how to go about that. A gamm4 model without the X*Y interaction would look like: fit = gamm4( formula = strike ~ s(X) + s(Y) + pitch_type*batter_handedness + (1|pitcher) + (1|batter) , data = my_data , family = 'binomial' ) summary(fit$gam) Come to think of it, you probably want to let the smooths vary within each level of pitch type and batter handedness. This makes the problem more difficult as I've not yet found out how to let the smooths vary by multiple variables in a way that subsequently produces meaninful analytic tests (see my queries to the R-SIG-Mixed-Models list). You could try: my_data$dummy = factor(paste(my_data$pitch_type,my_data$batter_handedness)) fit = gamm4( formula = strike ~ s(X,by=dummy) + s(Y,by=dummy) + pitch_type*batter_handedness + (1|pitcher) + (1|batter) , data = my_data , family = 'binomial' ) summary(fit$gam) But this won't give meaningful tests of the smooths. In attempting to solve this problem myself, I've used bootstrap resampling where on each iteration I obtain the model predictions for the full data space then compute the bootstap 95% CIs for each point in the space and any effects I care to compute.
How do I decide what span to use in LOESS regression in R?
I suggest checking out generalized additive models (GAM, see the mgcv package in R). I'm just learning about them myself, but they seem to automatically figure out how much "wiggly-ness" is justified
How do I decide what span to use in LOESS regression in R? I suggest checking out generalized additive models (GAM, see the mgcv package in R). I'm just learning about them myself, but they seem to automatically figure out how much "wiggly-ness" is justified by the data. I also see that you're dealing with binomial data (strike vs not a strike), so be sure to analyze the raw data (i.e. don't aggregate to proportions, use the raw pitch-by-pitch data) and use family='binomial' (assuming that you're going to use R). If you have information about what individual pitchers and hitters are contributing to the data, you can probably increase your power by doing a generalized additive mixed model (GAMM, see the gamm4 package in R) and specifying pitcher and hitter as random effects (and again, setting family='binomial'). Finally, you probably want to allow for an interaction between the smooths of X & Y, but I've never tried this myself so I don't know how to go about that. A gamm4 model without the X*Y interaction would look like: fit = gamm4( formula = strike ~ s(X) + s(Y) + pitch_type*batter_handedness + (1|pitcher) + (1|batter) , data = my_data , family = 'binomial' ) summary(fit$gam) Come to think of it, you probably want to let the smooths vary within each level of pitch type and batter handedness. This makes the problem more difficult as I've not yet found out how to let the smooths vary by multiple variables in a way that subsequently produces meaninful analytic tests (see my queries to the R-SIG-Mixed-Models list). You could try: my_data$dummy = factor(paste(my_data$pitch_type,my_data$batter_handedness)) fit = gamm4( formula = strike ~ s(X,by=dummy) + s(Y,by=dummy) + pitch_type*batter_handedness + (1|pitcher) + (1|batter) , data = my_data , family = 'binomial' ) summary(fit$gam) But this won't give meaningful tests of the smooths. In attempting to solve this problem myself, I've used bootstrap resampling where on each iteration I obtain the model predictions for the full data space then compute the bootstap 95% CIs for each point in the space and any effects I care to compute.
How do I decide what span to use in LOESS regression in R? I suggest checking out generalized additive models (GAM, see the mgcv package in R). I'm just learning about them myself, but they seem to automatically figure out how much "wiggly-ness" is justified
8,555
How do I decide what span to use in LOESS regression in R?
For a loess regression, my understanding as a non-statistician, is that you can choose your span based on visual interpretation (plot with numerous span values can choose the one with the least amount of smoothing that seems appropriate) or you can use cross validation (CV) or generalized cross validation (GCV). Below is code I used for GCV of a loess regression based on code from Takezawa's excellent book, Introduction to Nonparametric Regression (from p219). locv1 <- function(x1, y1, nd, span, ntrial) { locvgcv <- function(sp, x1, y1) { nd <- length(x1) assign("data1", data.frame(xx1 = x1, yy1 = y1)) fit.lo <- loess(yy1 ~ xx1, data = data1, span = sp, family = "gaussian", degree = 2, surface = "direct") res <- residuals(fit.lo) dhat2 <- function(x1, sp) { nd2 <- length(x1) diag1 <- diag(nd2) dhat <- rep(0, length = nd2) for(jj in 1:nd2){ y2 <- diag1[, jj] assign("data1", data.frame(xx1 = x1, yy1 = y2)) fit.lo <- loess(yy1 ~ xx1, data = data1, span = sp, family = "gaussian", degree = 2, surface = "direct") ey <- fitted.values(fit.lo) dhat[jj] <- ey[jj] } return(dhat) } dhat <- dhat2(x1, sp) trhat <- sum(dhat) sse <- sum(res^2) cv <- sum((res/(1 - dhat))^2)/nd gcv <- sse/(nd * (1 - (trhat/nd))^2) return(gcv) } gcv <- lapply(as.list(span1), locvgcv, x1 = x1, y1 = y1) #cvgcv <- unlist(cvgcv) #cv <- cvgcv[attr(cvgcv, "names") == "cv"] #gcv <- cvgcv[attr(cvgcv, "names") == "gcv"] return(gcv) } and with my data, I did the following: nd <- length(Edge2$Distance) xx <- Edge2$Distance yy <- lcap ntrial <- 50 span1 <- seq(from = 0.5, by = 0.01, length = ntrial) output.lo <- locv1(xx, yy, nd, span1, ntrial) #cv <- output.lo gcv <- output.lo plot(span1, gcv, type = "n", xlab = "span", ylab = "GCV") points(span1, gcv, pch = 3) lines(span1, gcv, lwd = 2) gpcvmin <- seq(along = gcv)[gcv == min(gcv)] spangcv <- span1[pgcvmin] gcvmin <- cv[pgcvmin] points(spangcv, gcvmin, cex = 1, pch = 15) Sorry the code is rather sloppy, this was one of my first times using R, but it should give you an idea of how to do GSV for loess regression to find the best span to use in a more objective way than simple visual inspection. On the above plot, you are interested in the span that minimizes the function (lowest on the plotted "curve").
How do I decide what span to use in LOESS regression in R?
For a loess regression, my understanding as a non-statistician, is that you can choose your span based on visual interpretation (plot with numerous span values can choose the one with the least amount
How do I decide what span to use in LOESS regression in R? For a loess regression, my understanding as a non-statistician, is that you can choose your span based on visual interpretation (plot with numerous span values can choose the one with the least amount of smoothing that seems appropriate) or you can use cross validation (CV) or generalized cross validation (GCV). Below is code I used for GCV of a loess regression based on code from Takezawa's excellent book, Introduction to Nonparametric Regression (from p219). locv1 <- function(x1, y1, nd, span, ntrial) { locvgcv <- function(sp, x1, y1) { nd <- length(x1) assign("data1", data.frame(xx1 = x1, yy1 = y1)) fit.lo <- loess(yy1 ~ xx1, data = data1, span = sp, family = "gaussian", degree = 2, surface = "direct") res <- residuals(fit.lo) dhat2 <- function(x1, sp) { nd2 <- length(x1) diag1 <- diag(nd2) dhat <- rep(0, length = nd2) for(jj in 1:nd2){ y2 <- diag1[, jj] assign("data1", data.frame(xx1 = x1, yy1 = y2)) fit.lo <- loess(yy1 ~ xx1, data = data1, span = sp, family = "gaussian", degree = 2, surface = "direct") ey <- fitted.values(fit.lo) dhat[jj] <- ey[jj] } return(dhat) } dhat <- dhat2(x1, sp) trhat <- sum(dhat) sse <- sum(res^2) cv <- sum((res/(1 - dhat))^2)/nd gcv <- sse/(nd * (1 - (trhat/nd))^2) return(gcv) } gcv <- lapply(as.list(span1), locvgcv, x1 = x1, y1 = y1) #cvgcv <- unlist(cvgcv) #cv <- cvgcv[attr(cvgcv, "names") == "cv"] #gcv <- cvgcv[attr(cvgcv, "names") == "gcv"] return(gcv) } and with my data, I did the following: nd <- length(Edge2$Distance) xx <- Edge2$Distance yy <- lcap ntrial <- 50 span1 <- seq(from = 0.5, by = 0.01, length = ntrial) output.lo <- locv1(xx, yy, nd, span1, ntrial) #cv <- output.lo gcv <- output.lo plot(span1, gcv, type = "n", xlab = "span", ylab = "GCV") points(span1, gcv, pch = 3) lines(span1, gcv, lwd = 2) gpcvmin <- seq(along = gcv)[gcv == min(gcv)] spangcv <- span1[pgcvmin] gcvmin <- cv[pgcvmin] points(spangcv, gcvmin, cex = 1, pch = 15) Sorry the code is rather sloppy, this was one of my first times using R, but it should give you an idea of how to do GSV for loess regression to find the best span to use in a more objective way than simple visual inspection. On the above plot, you are interested in the span that minimizes the function (lowest on the plotted "curve").
How do I decide what span to use in LOESS regression in R? For a loess regression, my understanding as a non-statistician, is that you can choose your span based on visual interpretation (plot with numerous span values can choose the one with the least amount
8,556
How do I decide what span to use in LOESS regression in R?
If you switch to a generlized additive model, you could use the gam() function from the mgcv package, in which the author assures us: So, exact choice of k is not generally critical: it should be chosen to be large enough that you are reasonably sure of having enough degrees of freedom to represent the underlying ‘truth’ reasonably well, but small enough to maintain reasonable computational efficiency. Clearly ‘large’ and ‘small’ are dependent on the particular problem being addressed. (k here is the degrees of freedom parameter for the smoother, which is akin to loess' smoothness parameter)
How do I decide what span to use in LOESS regression in R?
If you switch to a generlized additive model, you could use the gam() function from the mgcv package, in which the author assures us: So, exact choice of k is not generally critical: it should be cho
How do I decide what span to use in LOESS regression in R? If you switch to a generlized additive model, you could use the gam() function from the mgcv package, in which the author assures us: So, exact choice of k is not generally critical: it should be chosen to be large enough that you are reasonably sure of having enough degrees of freedom to represent the underlying ‘truth’ reasonably well, but small enough to maintain reasonable computational efficiency. Clearly ‘large’ and ‘small’ are dependent on the particular problem being addressed. (k here is the degrees of freedom parameter for the smoother, which is akin to loess' smoothness parameter)
How do I decide what span to use in LOESS regression in R? If you switch to a generlized additive model, you could use the gam() function from the mgcv package, in which the author assures us: So, exact choice of k is not generally critical: it should be cho
8,557
How do I decide what span to use in LOESS regression in R?
You could write your own cross validation loop from scratch that uses the loess() function from the stats package. Set up a toy data frame. set.seed(4) x <- rnorm(n = 500) y <- (x)^3 + (x - 3)^2 + (x - 8) - 1 + rnorm(n = 500, sd = 0.5) plot(x, y) df <- data.frame(x, y) Set up useful variables to handle cross-validation loop. span.seq <- seq(from = 0.15, to = 0.95, by = 0.05) #explores range of spans k <- 10 #number of folds set.seed(1) # replicate results folds <- sample(x = 1:k, size = length(x), replace = TRUE) cv.error.mtrx <- matrix(rep(x = NA, times = k * length(span.seq)), nrow = length(span.seq), ncol = k) Run a nested for loop iterating over each span possibility in span.seq, and each fold in folds. for(i in 1:length(span.seq)) { for(j in 1:k) { loess.fit <- loess(formula = y ~ x, data = df[folds != j, ], span = span.seq[i]) preds <- predict(object = loess.fit, newdata = df[folds == j, ]) cv.error.mtrx[i, j] <- mean((df$y[folds == j] - preds)^2, na.rm = TRUE) # some predictions result in `NA` because of the `x` ranges in each fold } } Calculate average cross-validation mean square error from each of the 10 folds: $$CV_{(10)} = \frac{1}{10} \sum_{i=1}^{10} MSE_i$$ cv.errors <- rowMeans(cv.error.mtrx) Find which span resulted in the lowest $MSE$. best.span.i <- which.min(cv.errors) best.span.i span.seq[best.span.i] Plot your results. plot(x = span.seq, y = cv.errors, type = "l", main = "CV Plot") points(x = span.seq, y = cv.errors, pch = 20, cex = 0.75, col = "blue") points(x = span.seq[best.span.i], y = cv.errors[best.span.i], pch = 20, cex = 1, col = "red") best.loess.fit <- loess(formula = y ~ x, data = df, span = span.seq[best.span.i]) x.seq <- seq(from = min(x), to = max(x), length = 100) plot(x = df$x, y = df$y, main = "Best Span Plot") lines(x = x.seq, y = predict(object = best.loess.fit, newdata = data.frame(x = x.seq)), col = "red", lwd = 2)
How do I decide what span to use in LOESS regression in R?
You could write your own cross validation loop from scratch that uses the loess() function from the stats package. Set up a toy data frame. set.seed(4) x <- rnorm(n = 500) y <- (x)^3 + (x - 3)^2 + (x
How do I decide what span to use in LOESS regression in R? You could write your own cross validation loop from scratch that uses the loess() function from the stats package. Set up a toy data frame. set.seed(4) x <- rnorm(n = 500) y <- (x)^3 + (x - 3)^2 + (x - 8) - 1 + rnorm(n = 500, sd = 0.5) plot(x, y) df <- data.frame(x, y) Set up useful variables to handle cross-validation loop. span.seq <- seq(from = 0.15, to = 0.95, by = 0.05) #explores range of spans k <- 10 #number of folds set.seed(1) # replicate results folds <- sample(x = 1:k, size = length(x), replace = TRUE) cv.error.mtrx <- matrix(rep(x = NA, times = k * length(span.seq)), nrow = length(span.seq), ncol = k) Run a nested for loop iterating over each span possibility in span.seq, and each fold in folds. for(i in 1:length(span.seq)) { for(j in 1:k) { loess.fit <- loess(formula = y ~ x, data = df[folds != j, ], span = span.seq[i]) preds <- predict(object = loess.fit, newdata = df[folds == j, ]) cv.error.mtrx[i, j] <- mean((df$y[folds == j] - preds)^2, na.rm = TRUE) # some predictions result in `NA` because of the `x` ranges in each fold } } Calculate average cross-validation mean square error from each of the 10 folds: $$CV_{(10)} = \frac{1}{10} \sum_{i=1}^{10} MSE_i$$ cv.errors <- rowMeans(cv.error.mtrx) Find which span resulted in the lowest $MSE$. best.span.i <- which.min(cv.errors) best.span.i span.seq[best.span.i] Plot your results. plot(x = span.seq, y = cv.errors, type = "l", main = "CV Plot") points(x = span.seq, y = cv.errors, pch = 20, cex = 0.75, col = "blue") points(x = span.seq[best.span.i], y = cv.errors[best.span.i], pch = 20, cex = 1, col = "red") best.loess.fit <- loess(formula = y ~ x, data = df, span = span.seq[best.span.i]) x.seq <- seq(from = min(x), to = max(x), length = 100) plot(x = df$x, y = df$y, main = "Best Span Plot") lines(x = x.seq, y = predict(object = best.loess.fit, newdata = data.frame(x = x.seq)), col = "red", lwd = 2)
How do I decide what span to use in LOESS regression in R? You could write your own cross validation loop from scratch that uses the loess() function from the stats package. Set up a toy data frame. set.seed(4) x <- rnorm(n = 500) y <- (x)^3 + (x - 3)^2 + (x
8,558
How do I decide what span to use in LOESS regression in R?
Use locfit package. Its a slightly modified version of the loess but way faster. It also has an inbuilt function to calculate gcv. Reference.
How do I decide what span to use in LOESS regression in R?
Use locfit package. Its a slightly modified version of the loess but way faster. It also has an inbuilt function to calculate gcv. Reference.
How do I decide what span to use in LOESS regression in R? Use locfit package. Its a slightly modified version of the loess but way faster. It also has an inbuilt function to calculate gcv. Reference.
How do I decide what span to use in LOESS regression in R? Use locfit package. Its a slightly modified version of the loess but way faster. It also has an inbuilt function to calculate gcv. Reference.
8,559
How do I decide what span to use in LOESS regression in R?
The fANCOVA package provides an automated way to compute the ideal span using gcv or aic: FTSE.lo3 <- loess.as(Index, FTSE_close, degree = 1, criterion = c("aicc", "gcv")[2], user.span = NULL, plot = F) FTSE.lo.predict3 <- predict(FTSE.lo3, data.frame(Index=Index))
How do I decide what span to use in LOESS regression in R?
The fANCOVA package provides an automated way to compute the ideal span using gcv or aic: FTSE.lo3 <- loess.as(Index, FTSE_close, degree = 1, criterion = c("aicc", "gcv")[2], user.span = NULL, plot =
How do I decide what span to use in LOESS regression in R? The fANCOVA package provides an automated way to compute the ideal span using gcv or aic: FTSE.lo3 <- loess.as(Index, FTSE_close, degree = 1, criterion = c("aicc", "gcv")[2], user.span = NULL, plot = F) FTSE.lo.predict3 <- predict(FTSE.lo3, data.frame(Index=Index))
How do I decide what span to use in LOESS regression in R? The fANCOVA package provides an automated way to compute the ideal span using gcv or aic: FTSE.lo3 <- loess.as(Index, FTSE_close, degree = 1, criterion = c("aicc", "gcv")[2], user.span = NULL, plot =
8,560
How can a statistician who has the data for a non-normal distribution guess better than one who only has the mean?
For a uniform distribution between $0$ and $2 \mu$, the player who guesses the sample mean would do worse than one which guesses $\frac{3}{5} \max(x_i)$ (the sample maximum is a sufficient statistic for the mean of a uniform distribution lower bounded by 0). In this particular case, it can be verified numerically. Without loss of generality, we set $\mu = 0.5$ in the simulation. It turns out that about 2/3rds of the time, the 3/5 max estimator does better. Here is a Python simulation demonstrating this. import numpy as np Ntrials = 1000000 xs = np.random.random((5,Ntrials)) sample_mean_error = np.abs(xs.mean(axis=0)-0.5) better_estimator_error = np.abs(0.6*xs.max(axis=0)-0.5) print((sample_mean_error > better_estimator_error).sum())
How can a statistician who has the data for a non-normal distribution guess better than one who only
For a uniform distribution between $0$ and $2 \mu$, the player who guesses the sample mean would do worse than one which guesses $\frac{3}{5} \max(x_i)$ (the sample maximum is a sufficient statistic f
How can a statistician who has the data for a non-normal distribution guess better than one who only has the mean? For a uniform distribution between $0$ and $2 \mu$, the player who guesses the sample mean would do worse than one which guesses $\frac{3}{5} \max(x_i)$ (the sample maximum is a sufficient statistic for the mean of a uniform distribution lower bounded by 0). In this particular case, it can be verified numerically. Without loss of generality, we set $\mu = 0.5$ in the simulation. It turns out that about 2/3rds of the time, the 3/5 max estimator does better. Here is a Python simulation demonstrating this. import numpy as np Ntrials = 1000000 xs = np.random.random((5,Ntrials)) sample_mean_error = np.abs(xs.mean(axis=0)-0.5) better_estimator_error = np.abs(0.6*xs.max(axis=0)-0.5) print((sample_mean_error > better_estimator_error).sum())
How can a statistician who has the data for a non-normal distribution guess better than one who only For a uniform distribution between $0$ and $2 \mu$, the player who guesses the sample mean would do worse than one which guesses $\frac{3}{5} \max(x_i)$ (the sample maximum is a sufficient statistic f
8,561
How can a statistician who has the data for a non-normal distribution guess better than one who only has the mean?
The sum of observations is not sufficient for estimating the mean of a uniform population. The midrange has a smaller expectation of absolute error. Approximation by simulation in R: set.seed(2021) a = replicate(10^6, mean(runif(5))) mr = replicate(10^6, mean(range(runif(5)))) mean(a); mean(mr) [1] 0.5000905 [1] 0.5000926 mean(abs(a-.5)); mean(abs(mr-.5)) [1] 0.1040754 [1] 0.0833201 par(mfrow=c(2,1)) hdr1 = "UNIF(0,1): Simulated Dist'n of Mean of 5" hist(a, prob=T, xlim=0:1, br=30, col="skyblue2", main=hdr1) hdr2 = "UNIF(0,1): Sim. Dist'n of Midrange of 5" hist(mr, prob=T, xlim=0:1, br=30, col="skyblue2", main=hdr2) par(mfrow=c(1,1)) Note per Comment: Using mean squared error instead of absolute error. Also, with RMSE for comparable units. mean((a-.5)^2); mean((mr-.5)^2) [1] 0.01665874 [1] 0.01190478 sqrt(mean((a-.5)^2)); sqrt(mean((mr-.5)^2)) [1] 0.1290687 [1] 0.109109
How can a statistician who has the data for a non-normal distribution guess better than one who only
The sum of observations is not sufficient for estimating the mean of a uniform population. The midrange has a smaller expectation of absolute error. Approximation by simulation in R: set.seed(2021
How can a statistician who has the data for a non-normal distribution guess better than one who only has the mean? The sum of observations is not sufficient for estimating the mean of a uniform population. The midrange has a smaller expectation of absolute error. Approximation by simulation in R: set.seed(2021) a = replicate(10^6, mean(runif(5))) mr = replicate(10^6, mean(range(runif(5)))) mean(a); mean(mr) [1] 0.5000905 [1] 0.5000926 mean(abs(a-.5)); mean(abs(mr-.5)) [1] 0.1040754 [1] 0.0833201 par(mfrow=c(2,1)) hdr1 = "UNIF(0,1): Simulated Dist'n of Mean of 5" hist(a, prob=T, xlim=0:1, br=30, col="skyblue2", main=hdr1) hdr2 = "UNIF(0,1): Sim. Dist'n of Midrange of 5" hist(mr, prob=T, xlim=0:1, br=30, col="skyblue2", main=hdr2) par(mfrow=c(1,1)) Note per Comment: Using mean squared error instead of absolute error. Also, with RMSE for comparable units. mean((a-.5)^2); mean((mr-.5)^2) [1] 0.01665874 [1] 0.01190478 sqrt(mean((a-.5)^2)); sqrt(mean((mr-.5)^2)) [1] 0.1290687 [1] 0.109109
How can a statistician who has the data for a non-normal distribution guess better than one who only The sum of observations is not sufficient for estimating the mean of a uniform population. The midrange has a smaller expectation of absolute error. Approximation by simulation in R: set.seed(2021
8,562
How can a statistician who has the data for a non-normal distribution guess better than one who only has the mean?
It might be worth adding that while you can often do better for low-dimensional parametric families, you can't do better if the distribution is completely unknown (or completely unknown apart from knowing it has a finite mean). The mean is the only estimator of the mean that works over all distributions.
How can a statistician who has the data for a non-normal distribution guess better than one who only
It might be worth adding that while you can often do better for low-dimensional parametric families, you can't do better if the distribution is completely unknown (or completely unknown apart from kno
How can a statistician who has the data for a non-normal distribution guess better than one who only has the mean? It might be worth adding that while you can often do better for low-dimensional parametric families, you can't do better if the distribution is completely unknown (or completely unknown apart from knowing it has a finite mean). The mean is the only estimator of the mean that works over all distributions.
How can a statistician who has the data for a non-normal distribution guess better than one who only It might be worth adding that while you can often do better for low-dimensional parametric families, you can't do better if the distribution is completely unknown (or completely unknown apart from kno
8,563
Why are random walks intercorrelated?
Your independent processes are not correlated! If $X_t$ and $Y_t$ are independent random walks: A correlation coefficient unconditional on time does not exist. (Don't talk about $\operatorname{Corr}(X, Y)$.) For any time $t$, $\operatorname{Corr}(X_t, Y_t)$ is indeed 0. But sample statistics based upon time-series averages will not converge to anything! The sample correlation coefficient you calculated based upon averaging multiple observations over time is meaningless. Intuitively, you might guess (incorrectly) that: Independence between two processes $\{X_t\}$ and $\{Y_t\}$ implies they have zero correlation. (For two random walks, $\operatorname{Corr}(X, Y)$ doesn't exist.) The time series, sample correlation $\hat{\rho}_{XY}$ (i.e. the correlation coefficient calculated using time-series, sample statistics such as $\hat{\mu_X} = \frac{1}{T} \sum_{\tau = 1}^T X_\tau$) will converge on the population correlation coefficient $\rho_{XY}$ as $T \rightarrow \infty$. The problem is that neither of these statements are true for random walks! (They are true for better behaved processes.) For non-stationary processes: You can talk about the correlation between processes $\{X_t\}$ and $\{Y_t\}$ at any two particular points of time (eg. $\operatorname{Corr}(X_2, Y_3)$ is a perfectly sensible statement.) But it doesn't make sense to talk about correlation between the two series unconditional on time! $\operatorname{Corr}(X, Y)$ does not have a well-defined meaning. The problems in the case of a random walk? For a random walk, unconditional population moments (i.e. which don't depend on time $t$), such as $\operatorname{E}[X]$, don't exist. (In some loose sense, they are infinite.) Similarly, the unconditional correlation coefficient $\rho_{XY}$ between two independent random walks isn't zero; it in fact doesn't exist! The assumptions of ergodic theorems don't apply and various time-series averages (eg. $\frac{1}{T} \sum_\tau X_\tau$) don't converge towards anything as $T \rightarrow \infty$. For a stationary sequence, the time series average will eventually converge on the mean that's unconditional on time. But for a non-stationary sequence, there is no mean that's unconditional on time! If you have various observations of two independent random walks over time (eg. $X_1$, $X_2$, etc... and $Y_1$, $Y_2$, ....) and you calculate the sample correlation coefficient, you will get a number between $-1$ and $1$. But it won't be an approximation of the population correlation coefficient (which doesn't exist). Instead, $\hat{\rho}_{XY}(T)$ (calculated using time-series averages from $t=1$ to $t=T$) is going to basically be a random variable (taking values in $[-1, 1]$) which reflects the two particular paths the random walks took by chance (i.e. the paths defined by the draw $\omega$ drawn from sample space $\Omega$.) Speaking extremely loosely (and imprecisely): If both $X_t$ and $Y_t$ happened to wander off in the same direction, you'll detect a spurious positive relationship. If $X_t$ and $Y_t$ wandered off in different directions, you'll detect a spurious negative relationship. If $X_t$ and $Y_t$ happened to wander across each other enough, you'll detect a near zero relationship. You can Google more about this with the terms spurious regression random walk. A random walk isn't stationary and taking averages over time $t$ won't converge on what you would get by taking iid draws $\omega$ from in sample space $\Omega$. As mentioned in the comments above, you can take first differences $\Delta x_t = x_t - x_{t-1}$ and for a random walk, that process $\{\Delta x_t\}$ is stationary. Big picture idea: Multiple observations over time IS NOT the same as multiple draws from a sample space! Recall that a discrete time stochastic process $\{ X_t \}$ is a function of both time ($t \in \mathbb{N}$) and a sample space $\Omega$. For averages over time $t$ to converge towards expectations over a sample space $\Omega$, you need stationarity and ergodicity. This is a core issue in much time-series analysis. And a random-walk isn't a stationary process. Connection to WHuber's answer: If you can take averages across multiple simulations (i.e. take multiple draws from $\Omega$) instead of being forced to take averages across time $t$, a number of your issues disappear. You can of course define $\hat{\rho}_{XY}(t)$ as the sample correlation coefficient computed on $X_1\ldots X_t$ and $Y_1 \ldots Y_t$ and this will also be a stochastic process. You can define some random variable $Z_t$ as: $$Z_t = |\hat{\rho}_{XY}(t)|$$ For two random walks starting at $0$ with $\mathcal{N}(0,1)$ increments, it's easy to find $E[Z_{10000}]$ by simulation (i.e. taking multiple draws from $\Omega$.) Below, I ran a simulation of 10,000 calculations of a sample Pearson correlation coefficient. Each time I: Simulated two 10,000 length random walks (with normally distributed increments draw from $\mathcal{N}(0,1)$). Calculated the sample correlation coefficient between them. Below is a histogram showing the empirical distribution over the 10000 calculated correlation coefficients. You can clearly observe that the random variable $\hat{\rho}_{XY}(10000)$ can be all over the place in the interval $[-1, 1]$. For two fixed paths of $X$ and $Y$, the sample correlation coefficient doesn't converge to anything as the length of the time series increases. On the other hand, for a particular time (eg. $t=10,000$), the sample correlation coefficient is a random variable with a finite mean etc... If I take the absolute value and compute the mean over all the simulations, I calculate approximately .42. I'm not sure why you want to do this or why this is at all meaningful??, but of course you can. Code: for i=1:10000 X = randn(10000,2); Y = cumsum(X); z(i) = corr(Y(:,1), Y(:,2)); end; histogram(z,20); mean(abs(z))
Why are random walks intercorrelated?
Your independent processes are not correlated! If $X_t$ and $Y_t$ are independent random walks: A correlation coefficient unconditional on time does not exist. (Don't talk about $\operatorname{Corr}(
Why are random walks intercorrelated? Your independent processes are not correlated! If $X_t$ and $Y_t$ are independent random walks: A correlation coefficient unconditional on time does not exist. (Don't talk about $\operatorname{Corr}(X, Y)$.) For any time $t$, $\operatorname{Corr}(X_t, Y_t)$ is indeed 0. But sample statistics based upon time-series averages will not converge to anything! The sample correlation coefficient you calculated based upon averaging multiple observations over time is meaningless. Intuitively, you might guess (incorrectly) that: Independence between two processes $\{X_t\}$ and $\{Y_t\}$ implies they have zero correlation. (For two random walks, $\operatorname{Corr}(X, Y)$ doesn't exist.) The time series, sample correlation $\hat{\rho}_{XY}$ (i.e. the correlation coefficient calculated using time-series, sample statistics such as $\hat{\mu_X} = \frac{1}{T} \sum_{\tau = 1}^T X_\tau$) will converge on the population correlation coefficient $\rho_{XY}$ as $T \rightarrow \infty$. The problem is that neither of these statements are true for random walks! (They are true for better behaved processes.) For non-stationary processes: You can talk about the correlation between processes $\{X_t\}$ and $\{Y_t\}$ at any two particular points of time (eg. $\operatorname{Corr}(X_2, Y_3)$ is a perfectly sensible statement.) But it doesn't make sense to talk about correlation between the two series unconditional on time! $\operatorname{Corr}(X, Y)$ does not have a well-defined meaning. The problems in the case of a random walk? For a random walk, unconditional population moments (i.e. which don't depend on time $t$), such as $\operatorname{E}[X]$, don't exist. (In some loose sense, they are infinite.) Similarly, the unconditional correlation coefficient $\rho_{XY}$ between two independent random walks isn't zero; it in fact doesn't exist! The assumptions of ergodic theorems don't apply and various time-series averages (eg. $\frac{1}{T} \sum_\tau X_\tau$) don't converge towards anything as $T \rightarrow \infty$. For a stationary sequence, the time series average will eventually converge on the mean that's unconditional on time. But for a non-stationary sequence, there is no mean that's unconditional on time! If you have various observations of two independent random walks over time (eg. $X_1$, $X_2$, etc... and $Y_1$, $Y_2$, ....) and you calculate the sample correlation coefficient, you will get a number between $-1$ and $1$. But it won't be an approximation of the population correlation coefficient (which doesn't exist). Instead, $\hat{\rho}_{XY}(T)$ (calculated using time-series averages from $t=1$ to $t=T$) is going to basically be a random variable (taking values in $[-1, 1]$) which reflects the two particular paths the random walks took by chance (i.e. the paths defined by the draw $\omega$ drawn from sample space $\Omega$.) Speaking extremely loosely (and imprecisely): If both $X_t$ and $Y_t$ happened to wander off in the same direction, you'll detect a spurious positive relationship. If $X_t$ and $Y_t$ wandered off in different directions, you'll detect a spurious negative relationship. If $X_t$ and $Y_t$ happened to wander across each other enough, you'll detect a near zero relationship. You can Google more about this with the terms spurious regression random walk. A random walk isn't stationary and taking averages over time $t$ won't converge on what you would get by taking iid draws $\omega$ from in sample space $\Omega$. As mentioned in the comments above, you can take first differences $\Delta x_t = x_t - x_{t-1}$ and for a random walk, that process $\{\Delta x_t\}$ is stationary. Big picture idea: Multiple observations over time IS NOT the same as multiple draws from a sample space! Recall that a discrete time stochastic process $\{ X_t \}$ is a function of both time ($t \in \mathbb{N}$) and a sample space $\Omega$. For averages over time $t$ to converge towards expectations over a sample space $\Omega$, you need stationarity and ergodicity. This is a core issue in much time-series analysis. And a random-walk isn't a stationary process. Connection to WHuber's answer: If you can take averages across multiple simulations (i.e. take multiple draws from $\Omega$) instead of being forced to take averages across time $t$, a number of your issues disappear. You can of course define $\hat{\rho}_{XY}(t)$ as the sample correlation coefficient computed on $X_1\ldots X_t$ and $Y_1 \ldots Y_t$ and this will also be a stochastic process. You can define some random variable $Z_t$ as: $$Z_t = |\hat{\rho}_{XY}(t)|$$ For two random walks starting at $0$ with $\mathcal{N}(0,1)$ increments, it's easy to find $E[Z_{10000}]$ by simulation (i.e. taking multiple draws from $\Omega$.) Below, I ran a simulation of 10,000 calculations of a sample Pearson correlation coefficient. Each time I: Simulated two 10,000 length random walks (with normally distributed increments draw from $\mathcal{N}(0,1)$). Calculated the sample correlation coefficient between them. Below is a histogram showing the empirical distribution over the 10000 calculated correlation coefficients. You can clearly observe that the random variable $\hat{\rho}_{XY}(10000)$ can be all over the place in the interval $[-1, 1]$. For two fixed paths of $X$ and $Y$, the sample correlation coefficient doesn't converge to anything as the length of the time series increases. On the other hand, for a particular time (eg. $t=10,000$), the sample correlation coefficient is a random variable with a finite mean etc... If I take the absolute value and compute the mean over all the simulations, I calculate approximately .42. I'm not sure why you want to do this or why this is at all meaningful??, but of course you can. Code: for i=1:10000 X = randn(10000,2); Y = cumsum(X); z(i) = corr(Y(:,1), Y(:,2)); end; histogram(z,20); mean(abs(z))
Why are random walks intercorrelated? Your independent processes are not correlated! If $X_t$ and $Y_t$ are independent random walks: A correlation coefficient unconditional on time does not exist. (Don't talk about $\operatorname{Corr}(
8,564
Why are random walks intercorrelated?
The math needed to obtain an exact result is messy, but we can derive an exact value for the expected squared correlation coefficient relatively painlessly. It helps explain why a value near $1/2$ keeps showing up and why increasing the length $n$ of the random walk won't change things. There is potential for confusion about standard terms. The absolute correlation referred to in the question, along with the statistics that make it up--variances and covariances--are formulas that one can apply to any pair of realizations of random walks. The question concern what happens when we look at many independent realizations. For that, we need to take expectations over the random walk process. (Edit) Before we proceed, I want to share some graphical insights with you. A pair of independent random walks $(X,Y)$ is a random walk in two dimensions. We can plot the path that steps from each $(X_t,Y_t)$ to $X_{t+1},Y_{t+1}$. If this path tends downwards (from left to right, plotted on the usual X-Y axes) then in order to study the absolute value of the correlation, let's negate all the $Y$ values. Plot the walks on axes sized to give the $X$ and $Y$ values equal standard deviations and superimpose the least-squares fit of $Y$ to $X$. The slopes of these lines will be the absolute values of the correlation coefficients, lying always between $0$ and $1$. This figure shows $15$ such walks, each of length $960$ (with standard Normal differences). Little open circles mark their starting points. Dark circles mark their final locations. These slopes tend to be pretty large. Perfectly random scatterplots of this many points would always have slopes very close to zero. If we had to describe the patterns emerging here, we might say that most 2D random walks gradually migrate from one location to another. (These aren't necessarily their starting and endpoint locations, however!) About half the time, then, that migration occurs in a diagonal direction--and the slope is accordingly high. The rest of this post sketches an analysis of this situation. A random walk $(X_i)$ is a sequence of partial sums of $(W_1, W_2, \ldots, W_n)$ where the $W_i$ are independent identically distributed zero-mean variables. Let their common variance be $\sigma^2$. In a realization $x = (x_1, \ldots, x_n)$ of such a walk, the "variance" would be computed as if this were any dataset: $$\operatorname{V}(x) = \frac{1}{n}\sum (x_i-\bar x)^2.$$ A nice way to compute this value is to take half the average of all the squared differences: $$\operatorname{V}(x) = \frac{1}{n(n-1)}\sum_{j \gt i} (x_j-x_i)^2.$$ When $x$ is viewed as the outcome of a random walk $X$ of $n$ steps, the expectation of this is $$\mathbb{E}(\operatorname{V}(X)) = \frac{1}{n(n-1)}\sum_{j \gt i} \mathbb{E}(X_j-X_i)^2.$$ The differences are sums of iid variables, $$X_j - X_i = W_{i+1} + W_{i+2} + \cdots + W_j.$$ Expand the square and take expectations. Because the $W_k$ are independent and have zero means, the expectations of all cross terms are zero. That leaves only terms like $W_k$, whose expectation is $\sigma^2$. Thus $$\mathbb{E}\left((X_j - X_i)^2\right) =\mathbb{E}\left((W_{i+1} + W_{i+2} + \cdots + W_j)^2\right)= (j-i)\sigma^2.$$ It easily follows that $$\mathbb{E}(\operatorname{V}(X)) = \frac{1}{n(n-1)}\sum_{j \gt i} (j-i)\sigma^2 = \frac{n+1}{6}\sigma^2.$$ The covariance between two independent realizations $x$ and $y$--again in the sense of datasets, not random variables--can be computed with the same technique (but it requires more algebraic work; a quadruple sum is involved). The result is that the expected square of the covariance is $$\mathbb{E}(\operatorname{C}(X,Y)^2) = \frac{3n^6-2n^5-3n^2+2n}{480n^2(n-1)^2}\sigma^4.$$ Consequently the expectation of the squared correlation coefficient between $X$ and $Y$, taken out to $n$ steps, is $$\rho^2(n) = \frac{\mathbb{E}(\operatorname{C}(X,Y)^2)}{\mathbb{E}(\operatorname{V}(X))^2} = \frac{3}{40}\frac{3n^3-2n^2+3n-2}{n^3-n} = \frac{9}{40}\left(1+O\left(\frac{1}{n}\right)\right).$$ Although this is not constant, it rapidly approaches a limiting value of $9/40$. Its square root, approximately $0.47$, therefore approximates the expected absolute value of $\rho(n)$ (and underestimates it). I am sure I have made computational errors, but simulations bear out the asymptotic accuracy. In the following results showing the histograms of $\rho^2(n)$ for $1000$ simulations each, the vertical red lines show the means while the dashed blue lines show the formula's value. Clearly it's incorrect, but asymptotically it is right. Evidently the entire distribution of $\rho^2(n)$ is approaching a limit as $n$ increases. Similarly, the distribution of $|\rho(n)|$ (which is the quantity of interest) will approach a limit. This is the R code to produce the figure. f <- function(n){ m <- (2 - 3* n + 2* n^2 -3 * n^3)/(n - n^3) * 3/40 } n.sim <- 1e4 par(mfrow=c(1,4)) for (n in c(3, 10, 30, 100)) { u <- matrix(rnorm(n*n.sim), nrow=n) v <- matrix(rnorm(n*n.sim), nrow=n) x <- apply(u, 2, cumsum) y <- apply(v, 2, cumsum) sim <- rep(NA_real_, n.sim) for (i in 1:n.sim) sim[i] <- cor(x[,i], y[,i])^2 z <- signif(sqrt(n.sim)*(mean(sim) - f(n)) / sd(sim), 3) hist(sim,xlab="rho(n)^2", main=paste("n =", n), sub=paste("Z =", z)) abline(v=mean(sim), lwd=2, col="Red") abline(v=f(n), col="Blue", lwd=2, lty=3) }
Why are random walks intercorrelated?
The math needed to obtain an exact result is messy, but we can derive an exact value for the expected squared correlation coefficient relatively painlessly. It helps explain why a value near $1/2$ ke
Why are random walks intercorrelated? The math needed to obtain an exact result is messy, but we can derive an exact value for the expected squared correlation coefficient relatively painlessly. It helps explain why a value near $1/2$ keeps showing up and why increasing the length $n$ of the random walk won't change things. There is potential for confusion about standard terms. The absolute correlation referred to in the question, along with the statistics that make it up--variances and covariances--are formulas that one can apply to any pair of realizations of random walks. The question concern what happens when we look at many independent realizations. For that, we need to take expectations over the random walk process. (Edit) Before we proceed, I want to share some graphical insights with you. A pair of independent random walks $(X,Y)$ is a random walk in two dimensions. We can plot the path that steps from each $(X_t,Y_t)$ to $X_{t+1},Y_{t+1}$. If this path tends downwards (from left to right, plotted on the usual X-Y axes) then in order to study the absolute value of the correlation, let's negate all the $Y$ values. Plot the walks on axes sized to give the $X$ and $Y$ values equal standard deviations and superimpose the least-squares fit of $Y$ to $X$. The slopes of these lines will be the absolute values of the correlation coefficients, lying always between $0$ and $1$. This figure shows $15$ such walks, each of length $960$ (with standard Normal differences). Little open circles mark their starting points. Dark circles mark their final locations. These slopes tend to be pretty large. Perfectly random scatterplots of this many points would always have slopes very close to zero. If we had to describe the patterns emerging here, we might say that most 2D random walks gradually migrate from one location to another. (These aren't necessarily their starting and endpoint locations, however!) About half the time, then, that migration occurs in a diagonal direction--and the slope is accordingly high. The rest of this post sketches an analysis of this situation. A random walk $(X_i)$ is a sequence of partial sums of $(W_1, W_2, \ldots, W_n)$ where the $W_i$ are independent identically distributed zero-mean variables. Let their common variance be $\sigma^2$. In a realization $x = (x_1, \ldots, x_n)$ of such a walk, the "variance" would be computed as if this were any dataset: $$\operatorname{V}(x) = \frac{1}{n}\sum (x_i-\bar x)^2.$$ A nice way to compute this value is to take half the average of all the squared differences: $$\operatorname{V}(x) = \frac{1}{n(n-1)}\sum_{j \gt i} (x_j-x_i)^2.$$ When $x$ is viewed as the outcome of a random walk $X$ of $n$ steps, the expectation of this is $$\mathbb{E}(\operatorname{V}(X)) = \frac{1}{n(n-1)}\sum_{j \gt i} \mathbb{E}(X_j-X_i)^2.$$ The differences are sums of iid variables, $$X_j - X_i = W_{i+1} + W_{i+2} + \cdots + W_j.$$ Expand the square and take expectations. Because the $W_k$ are independent and have zero means, the expectations of all cross terms are zero. That leaves only terms like $W_k$, whose expectation is $\sigma^2$. Thus $$\mathbb{E}\left((X_j - X_i)^2\right) =\mathbb{E}\left((W_{i+1} + W_{i+2} + \cdots + W_j)^2\right)= (j-i)\sigma^2.$$ It easily follows that $$\mathbb{E}(\operatorname{V}(X)) = \frac{1}{n(n-1)}\sum_{j \gt i} (j-i)\sigma^2 = \frac{n+1}{6}\sigma^2.$$ The covariance between two independent realizations $x$ and $y$--again in the sense of datasets, not random variables--can be computed with the same technique (but it requires more algebraic work; a quadruple sum is involved). The result is that the expected square of the covariance is $$\mathbb{E}(\operatorname{C}(X,Y)^2) = \frac{3n^6-2n^5-3n^2+2n}{480n^2(n-1)^2}\sigma^4.$$ Consequently the expectation of the squared correlation coefficient between $X$ and $Y$, taken out to $n$ steps, is $$\rho^2(n) = \frac{\mathbb{E}(\operatorname{C}(X,Y)^2)}{\mathbb{E}(\operatorname{V}(X))^2} = \frac{3}{40}\frac{3n^3-2n^2+3n-2}{n^3-n} = \frac{9}{40}\left(1+O\left(\frac{1}{n}\right)\right).$$ Although this is not constant, it rapidly approaches a limiting value of $9/40$. Its square root, approximately $0.47$, therefore approximates the expected absolute value of $\rho(n)$ (and underestimates it). I am sure I have made computational errors, but simulations bear out the asymptotic accuracy. In the following results showing the histograms of $\rho^2(n)$ for $1000$ simulations each, the vertical red lines show the means while the dashed blue lines show the formula's value. Clearly it's incorrect, but asymptotically it is right. Evidently the entire distribution of $\rho^2(n)$ is approaching a limit as $n$ increases. Similarly, the distribution of $|\rho(n)|$ (which is the quantity of interest) will approach a limit. This is the R code to produce the figure. f <- function(n){ m <- (2 - 3* n + 2* n^2 -3 * n^3)/(n - n^3) * 3/40 } n.sim <- 1e4 par(mfrow=c(1,4)) for (n in c(3, 10, 30, 100)) { u <- matrix(rnorm(n*n.sim), nrow=n) v <- matrix(rnorm(n*n.sim), nrow=n) x <- apply(u, 2, cumsum) y <- apply(v, 2, cumsum) sim <- rep(NA_real_, n.sim) for (i in 1:n.sim) sim[i] <- cor(x[,i], y[,i])^2 z <- signif(sqrt(n.sim)*(mean(sim) - f(n)) / sd(sim), 3) hist(sim,xlab="rho(n)^2", main=paste("n =", n), sub=paste("Z =", z)) abline(v=mean(sim), lwd=2, col="Red") abline(v=f(n), col="Blue", lwd=2, lty=3) }
Why are random walks intercorrelated? The math needed to obtain an exact result is messy, but we can derive an exact value for the expected squared correlation coefficient relatively painlessly. It helps explain why a value near $1/2$ ke
8,565
What is the probability that this person is female?
Many people find it helpful to think in terms of a "population," subgroups within it, and proportions (rather than probabilities). This lends itself to visual reasoning. I will explain the figures in detail, but the intention is that a quick comparison of the two figures should immediately and convincingly indicate how and why no specific answer to the question can be given. A slightly longer examination will suggest what additional information would be useful for determining an answer or at least obtaining bounds on the answers. Legend Cross-hatching: female / Solid background: male. Top: long-haired / Bottom: short-haired. Right (and colored): AX3 / Left (uncolored): non-AX3. Data Top cross-hatching is 90% of the top rectangle ("90% of all people with long hair are female"). Total cross-hatching in the right colored rectangle is 80% of that rectangle ("80% of all people with this blood type are female.") Explanation This diagram shows schematically how the population (of all females and non-females under consideration) can simultaneously be partitioned into females/non-females, AX3/non-AX3, and long haired/non-long haired ("short"). It uses area, at least approximately, to represent proportions (there's some exaggeration to make the picture clearer). It is evident that these three binary classifications create eight possible groups. Each group appears here. The information given states that the upper cross-hatched rectangle (long-haired females) comprises 90% of the upper rectangle (all long-haired people). It also states that the combined cross-hatched parts of the colored rectangles (long-haired females with AX3 and short-haired females with AX3) comprise 80% of the colored region at the right (all people with AX3). We are told that someone lies in the upper right corner (arrow): long-haired people with AX3. What proportion of this rectangle is cross-hatched (female)? I have also (implicitly) assumed that blood type and hair length are independent: the proportion of the upper rectangle (long hair) that is colored (AX3) equals the proportion of the lower rectangle (short hair) that is colored (AX3). That's what independence means. It is a fair and natural assumption to make when addressing such questions like this, but of course it needs to be stated. The position of the upper cross-hatched rectangle (long-haired females)is unknown. We can imagine sliding the top cross-hatched rectangle side-to-side and sliding the bottom cross-hatched rectangle side-to-side and possibly changing its width. If we do this so that 80% of the colored rectangle remains cross-hatched, such an alteration will change none of the stated information, yet it can alter the proportion of females in the upper right rectangle. Evidently the proportion could be anywhere between 0% and 100% and still be consistent with the information given, as in this image: One strength of this method is it establishes the existence of multiple answers to the question. One could translate all this algebraically and, by means of stipulating probabilities, offer specific situations as possible examples, but then the question would arise whether such examples are really consistent with the data. For instance, if someone were to suggest that perhaps 50% of long-haired people are AX3, at the outset it is not evident that this is even possible given all the information available. These (Venn) diagrams of the population and its subgroups make such things clear.
What is the probability that this person is female?
Many people find it helpful to think in terms of a "population," subgroups within it, and proportions (rather than probabilities). This lends itself to visual reasoning. I will explain the figures in
What is the probability that this person is female? Many people find it helpful to think in terms of a "population," subgroups within it, and proportions (rather than probabilities). This lends itself to visual reasoning. I will explain the figures in detail, but the intention is that a quick comparison of the two figures should immediately and convincingly indicate how and why no specific answer to the question can be given. A slightly longer examination will suggest what additional information would be useful for determining an answer or at least obtaining bounds on the answers. Legend Cross-hatching: female / Solid background: male. Top: long-haired / Bottom: short-haired. Right (and colored): AX3 / Left (uncolored): non-AX3. Data Top cross-hatching is 90% of the top rectangle ("90% of all people with long hair are female"). Total cross-hatching in the right colored rectangle is 80% of that rectangle ("80% of all people with this blood type are female.") Explanation This diagram shows schematically how the population (of all females and non-females under consideration) can simultaneously be partitioned into females/non-females, AX3/non-AX3, and long haired/non-long haired ("short"). It uses area, at least approximately, to represent proportions (there's some exaggeration to make the picture clearer). It is evident that these three binary classifications create eight possible groups. Each group appears here. The information given states that the upper cross-hatched rectangle (long-haired females) comprises 90% of the upper rectangle (all long-haired people). It also states that the combined cross-hatched parts of the colored rectangles (long-haired females with AX3 and short-haired females with AX3) comprise 80% of the colored region at the right (all people with AX3). We are told that someone lies in the upper right corner (arrow): long-haired people with AX3. What proportion of this rectangle is cross-hatched (female)? I have also (implicitly) assumed that blood type and hair length are independent: the proportion of the upper rectangle (long hair) that is colored (AX3) equals the proportion of the lower rectangle (short hair) that is colored (AX3). That's what independence means. It is a fair and natural assumption to make when addressing such questions like this, but of course it needs to be stated. The position of the upper cross-hatched rectangle (long-haired females)is unknown. We can imagine sliding the top cross-hatched rectangle side-to-side and sliding the bottom cross-hatched rectangle side-to-side and possibly changing its width. If we do this so that 80% of the colored rectangle remains cross-hatched, such an alteration will change none of the stated information, yet it can alter the proportion of females in the upper right rectangle. Evidently the proportion could be anywhere between 0% and 100% and still be consistent with the information given, as in this image: One strength of this method is it establishes the existence of multiple answers to the question. One could translate all this algebraically and, by means of stipulating probabilities, offer specific situations as possible examples, but then the question would arise whether such examples are really consistent with the data. For instance, if someone were to suggest that perhaps 50% of long-haired people are AX3, at the outset it is not evident that this is even possible given all the information available. These (Venn) diagrams of the population and its subgroups make such things clear.
What is the probability that this person is female? Many people find it helpful to think in terms of a "population," subgroups within it, and proportions (rather than probabilities). This lends itself to visual reasoning. I will explain the figures in
8,566
What is the probability that this person is female?
This is a question of conditional probability. You know that the person has long hair and blood type Ax3 . Let$$\ \ \ \ \ A =\{\text{'The person has long hair'}\}\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ B = \{\text{'The person has blood type Ax3'}\} \\ C =\{\text{'The person is female'}\}.$$ So you seek $P(C|A\ \text{and}\ B)$. You know that $P(C|A)=0.9$ and $P(C|B)=0.8$. Is that enough to calculate $P(C|A\ \text{and}\ B)$? Suppose $P(A\ \text{and}\ B\ \text{and}\ C)=0.7$. Then $$P(C|A\ \text{and}\ B)=P(A\ \text{and}\ B\ \text{and}\ C)/ P(A\ \text{and}\ B)=0.7/P(A\ \text{and}\ B).$$ Suppose $P(A\ \text{and}\ B)=0.8$. Then, by the above, $P(C|A\ \text{and}\ B)=0.875$. On the other hand if $P(A\ \text{and}\ B)=0.9$ we would then have $P(C|A\ \text{and}\ B)$=0.78. Now both are possible when $P(C|A)=0.9$ and $P(C|B)=0.8$. So we can't tell for sure what $P(C|A\ \text{and}\ B)$ is.
What is the probability that this person is female?
This is a question of conditional probability. You know that the person has long hair and blood type Ax3 . Let$$\ \ \ \ \ A =\{\text{'The person has long hair'}\}\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ B = \
What is the probability that this person is female? This is a question of conditional probability. You know that the person has long hair and blood type Ax3 . Let$$\ \ \ \ \ A =\{\text{'The person has long hair'}\}\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ B = \{\text{'The person has blood type Ax3'}\} \\ C =\{\text{'The person is female'}\}.$$ So you seek $P(C|A\ \text{and}\ B)$. You know that $P(C|A)=0.9$ and $P(C|B)=0.8$. Is that enough to calculate $P(C|A\ \text{and}\ B)$? Suppose $P(A\ \text{and}\ B\ \text{and}\ C)=0.7$. Then $$P(C|A\ \text{and}\ B)=P(A\ \text{and}\ B\ \text{and}\ C)/ P(A\ \text{and}\ B)=0.7/P(A\ \text{and}\ B).$$ Suppose $P(A\ \text{and}\ B)=0.8$. Then, by the above, $P(C|A\ \text{and}\ B)=0.875$. On the other hand if $P(A\ \text{and}\ B)=0.9$ we would then have $P(C|A\ \text{and}\ B)$=0.78. Now both are possible when $P(C|A)=0.9$ and $P(C|B)=0.8$. So we can't tell for sure what $P(C|A\ \text{and}\ B)$ is.
What is the probability that this person is female? This is a question of conditional probability. You know that the person has long hair and blood type Ax3 . Let$$\ \ \ \ \ A =\{\text{'The person has long hair'}\}\\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ B = \
8,567
What is the probability that this person is female?
Fascinating discussion ! I am wondering if we specified P(A) and P(B) as well whether the ranges of P(C| A,B) will not be much narrower than the full interval [0,1], simply because of the many constraints we have. Sticking to the notation introduced above: A = the event that the person has long hair B = the event that the person has blood type AX3 C = the event that person is female P(C|A) = 0.9 P(C|B) = 0.8 P(C) = 0.5 (i.e. let's assume an equal ratio of men and women in the population at large) it does not seem possible to assume that events A and B are conditionally independent given C ! That leads directly to a contradiction: if $P(A \wedge B | C) = P(A| C) \cdot P(B| C) = P(C| A) \frac{P(A)}{P(C)} \cdot P(C| B) \frac{P(B)}{P(C)}$ then $P(C| A \wedge B ) = P(A \wedge B | C) \cdot \left( \frac{P(C)}{P(A \wedge B)} \right) = P(C| A) \frac{P(A)}{P(C)} \cdot P(C| B) \frac{P(B)}{P(C)} \cdot \left( \frac{P(C)}{P(A \wedge B)} \right) $ If we now assume that A and B are independent as well: $P(A \wedge B) = P(A) P(B)$ most terms cancel and we end up with $P(C| A \wedge B ) = \frac{P(C| A) \cdot P(C| B)}{P(C)} = \frac{0.9 \cdot 0.8}{0.5} > 1$ Following up on whuber's wonderful geometric representation of the problem: While it is true that generally speaking $P(C | A \wedge B)$ can assume any value in the interval $[0,1]$ the geometric constraints do narrow the range of possible values significantly for values of $P(A)$ and $P(B)$ that are not "too small". (Though we can also upper bound the marginals: $P(A)$ and $P(B)$) Let us compute the {\bf smallest possible value} for $P(C | A \wedge B)$ under the following geometric constraints: 1. The fraction of the upper area (A TRUE) covered by the upper rectangle must be equal to $P(C|A)=0.9$ 2. The sum of the areas of the two rectangles must be equal to $P(C)=0.5$ 3. The sum of the fraction of the areas of the two colored rectangles (i.e. their overlap with event B) must be equal to $P(C|B)=0.8$ 4. (trivial) The upper rectangle cannot be moved beyond the left boundary and should not be moved beyond its minimum overlap to the left. 5. (trivial) The lower rectangle cannot be moved beyond the right boundary and should not be moved beyond its maximum overlap to the right. These constraints limit how freely we can slide the hashed rectangles and in turn generate lower bounds for $P(C | A \wedge B)$. The figure below (created with this R script ) shows two examples Running through a range of possible values for P(A) and P(B) (R script) generates this graph In conclusion, we can lower bound the conditional probability P(c|A,B) for given P(A), P(B)
What is the probability that this person is female?
Fascinating discussion ! I am wondering if we specified P(A) and P(B) as well whether the ranges of P(C| A,B) will not be much narrower than the full interval [0,1], simply because of the many constra
What is the probability that this person is female? Fascinating discussion ! I am wondering if we specified P(A) and P(B) as well whether the ranges of P(C| A,B) will not be much narrower than the full interval [0,1], simply because of the many constraints we have. Sticking to the notation introduced above: A = the event that the person has long hair B = the event that the person has blood type AX3 C = the event that person is female P(C|A) = 0.9 P(C|B) = 0.8 P(C) = 0.5 (i.e. let's assume an equal ratio of men and women in the population at large) it does not seem possible to assume that events A and B are conditionally independent given C ! That leads directly to a contradiction: if $P(A \wedge B | C) = P(A| C) \cdot P(B| C) = P(C| A) \frac{P(A)}{P(C)} \cdot P(C| B) \frac{P(B)}{P(C)}$ then $P(C| A \wedge B ) = P(A \wedge B | C) \cdot \left( \frac{P(C)}{P(A \wedge B)} \right) = P(C| A) \frac{P(A)}{P(C)} \cdot P(C| B) \frac{P(B)}{P(C)} \cdot \left( \frac{P(C)}{P(A \wedge B)} \right) $ If we now assume that A and B are independent as well: $P(A \wedge B) = P(A) P(B)$ most terms cancel and we end up with $P(C| A \wedge B ) = \frac{P(C| A) \cdot P(C| B)}{P(C)} = \frac{0.9 \cdot 0.8}{0.5} > 1$ Following up on whuber's wonderful geometric representation of the problem: While it is true that generally speaking $P(C | A \wedge B)$ can assume any value in the interval $[0,1]$ the geometric constraints do narrow the range of possible values significantly for values of $P(A)$ and $P(B)$ that are not "too small". (Though we can also upper bound the marginals: $P(A)$ and $P(B)$) Let us compute the {\bf smallest possible value} for $P(C | A \wedge B)$ under the following geometric constraints: 1. The fraction of the upper area (A TRUE) covered by the upper rectangle must be equal to $P(C|A)=0.9$ 2. The sum of the areas of the two rectangles must be equal to $P(C)=0.5$ 3. The sum of the fraction of the areas of the two colored rectangles (i.e. their overlap with event B) must be equal to $P(C|B)=0.8$ 4. (trivial) The upper rectangle cannot be moved beyond the left boundary and should not be moved beyond its minimum overlap to the left. 5. (trivial) The lower rectangle cannot be moved beyond the right boundary and should not be moved beyond its maximum overlap to the right. These constraints limit how freely we can slide the hashed rectangles and in turn generate lower bounds for $P(C | A \wedge B)$. The figure below (created with this R script ) shows two examples Running through a range of possible values for P(A) and P(B) (R script) generates this graph In conclusion, we can lower bound the conditional probability P(c|A,B) for given P(A), P(B)
What is the probability that this person is female? Fascinating discussion ! I am wondering if we specified P(A) and P(B) as well whether the ranges of P(C| A,B) will not be much narrower than the full interval [0,1], simply because of the many constra
8,568
What is the probability that this person is female?
Make the hypotheses is that the person behind a curtain is a woman. We area given 2 pieces of evidence, namely: Evidence 1: We know the person has long hair (and we're told that 90% of all people with long hair are female) Evidence 2: We know the person has a rare blood type AX3 (and we're told that 80% of all people with this blood type are female) Given just Evidence 1, we can state that the person behind a curtain has a 0.9 probability value of being a woman (assuming 50:50 split between men and women). Regarding the question posed earlier in the thread, namely "Would you agree that the answer must be GREATER than 0.9?", without doing any Math, I would say intuitively, the answer must be "yes" (it is GREATER than 0.9). The logic is that Evidence 2 is supporting evidence (again, assuming a 50:50 split for the number of men and women in the world). If we were told that 50% of all people with AX3 type blood were female, then Evidence 2 would be neutral and have no bearing. But since we're told that 80% of all people with this blood type are female, Evidence 2 is supporting evidence and logically should push the final probability of a woman above 0.9. To calculate a specific probability, we can apply Bayes' rule for Evidence 1 and then use Bayesian updating to apply Evidence 2 to the new hypothesis. Suppose: A = the event that the person has long hair B = the event that the person has blood type AX3 C = the event that person is female (assume 50%) Applying Bayes rule to Evidence 1: P(C|A) = (P(A|C) * P(C)) / P(A) In this case, again if we assume 50:50 split between men and women: P(A) = (0.5 * 0.9) + (0.5 * 0.1) = 0.5 So, P(C|A) = (0.9 * 0.5) / 0.5 = 0.9 (Not surprising, but it would be different if we didn't have 50:50 split between men and women) Using Bayesian updating to apply Evidence 2 and plugging in 0.9 as the new prior probability, we have: P(C|A AND B) = (P(B|C) * 0.9) / P(E) Here, P(E) is the probability of Evidence 2, given the hypotheses that the person already has a 90% chance of being female. P(E) = (0.9 * 0.8) + (0.1 * 0.2) [this is law of total probability: (P(woman)*P(AX3|woman) + P(man)*P(AX3|man)] So, P(E) = 0.74 So, P(C|A AND B) = (0.8 * 0.9) / 0.74 = 0.97297
What is the probability that this person is female?
Make the hypotheses is that the person behind a curtain is a woman. We area given 2 pieces of evidence, namely: Evidence 1: We know the person has long hair (and we're told that 90% of all people with
What is the probability that this person is female? Make the hypotheses is that the person behind a curtain is a woman. We area given 2 pieces of evidence, namely: Evidence 1: We know the person has long hair (and we're told that 90% of all people with long hair are female) Evidence 2: We know the person has a rare blood type AX3 (and we're told that 80% of all people with this blood type are female) Given just Evidence 1, we can state that the person behind a curtain has a 0.9 probability value of being a woman (assuming 50:50 split between men and women). Regarding the question posed earlier in the thread, namely "Would you agree that the answer must be GREATER than 0.9?", without doing any Math, I would say intuitively, the answer must be "yes" (it is GREATER than 0.9). The logic is that Evidence 2 is supporting evidence (again, assuming a 50:50 split for the number of men and women in the world). If we were told that 50% of all people with AX3 type blood were female, then Evidence 2 would be neutral and have no bearing. But since we're told that 80% of all people with this blood type are female, Evidence 2 is supporting evidence and logically should push the final probability of a woman above 0.9. To calculate a specific probability, we can apply Bayes' rule for Evidence 1 and then use Bayesian updating to apply Evidence 2 to the new hypothesis. Suppose: A = the event that the person has long hair B = the event that the person has blood type AX3 C = the event that person is female (assume 50%) Applying Bayes rule to Evidence 1: P(C|A) = (P(A|C) * P(C)) / P(A) In this case, again if we assume 50:50 split between men and women: P(A) = (0.5 * 0.9) + (0.5 * 0.1) = 0.5 So, P(C|A) = (0.9 * 0.5) / 0.5 = 0.9 (Not surprising, but it would be different if we didn't have 50:50 split between men and women) Using Bayesian updating to apply Evidence 2 and plugging in 0.9 as the new prior probability, we have: P(C|A AND B) = (P(B|C) * 0.9) / P(E) Here, P(E) is the probability of Evidence 2, given the hypotheses that the person already has a 90% chance of being female. P(E) = (0.9 * 0.8) + (0.1 * 0.2) [this is law of total probability: (P(woman)*P(AX3|woman) + P(man)*P(AX3|man)] So, P(E) = 0.74 So, P(C|A AND B) = (0.8 * 0.9) / 0.74 = 0.97297
What is the probability that this person is female? Make the hypotheses is that the person behind a curtain is a woman. We area given 2 pieces of evidence, namely: Evidence 1: We know the person has long hair (and we're told that 90% of all people with
8,569
What is the probability that this person is female?
Question Restatement and Generalisation $A$, $B$, and $C$ are binary unknowns whose possible values are $0$ and $1$. Let $Z_i$ stand for the proposition, "The value of $Z$ is $i$". Also let $(X | Y)$ stand for "The probability that $X$, given that $Y$". What is $(A_a | B_b C_c I)$, given that $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ and $(B C | I) = (B | I)(C | I)$ $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ and $(A_0 | I) = \frac{1}{2}$ $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ and $(A_0 | I) = \frac{1}{2}$ and $(B C | I) = (B | I)(C | I)$ and that $I$ contains no relevant information besides what is implicit in the assignments? The last conjunct of conditions 2 and 4 is shorthand for the independence statement $$ (B_j C_k | I) = (B_j | I)(C_k | I) \quad , \quad j = 0, 1 \quad k = 0,1 $$ Treat each of the four cases in turn. Answers Case 1 We have to specify the distribution $(ABC | I)$. The problem is underdetermined, because $(ABC | I)$ requires eight numbers, but we have only three equations---the two given conditions and the normalisation condition. It has been shown by various esoteric means that the distribution to assign when the information doesn't otherwise determine a solution is the one that, of all distributions consistent with the known information, has the greatest entropy. Any other distribution implies that we know more than the known information, which of course is a contradiction. All we need to do, therefore, is assign the maximum entropy distribution. This is more easily said than done, and I have not found a general closed-form solution. But particular solutions can be found using a numerical optimiser. We maximise $$ - \sum_{i,j,k} (A_i B_j C_k | I) \ln (A_i B_j C_k | I) $$ subject to the constraints $$ \sum_{i,j,k} (A_i B_j C_k | I) = 1 $$ and $$ (A_{a_1} | B_{b_1} I) = u_1 \quad\quad \text{i.e.} \quad \frac{\sum\limits_k (A_{a_1} B_{b_1} C_k | I )}{\sum\limits_{i,k} (A_i B_{b_1} C_k | I)} = u_1 $$ and $$ (A_{a_2} | C_{c_2} I) = u_2 \quad\quad \text{i.e.} \quad \frac{\sum\limits_j (A_{a_2} B_j C_{c_2} | I)}{\sum\limits_{i,j} (A_i B_j C_{c_2} | I)} = u_2 $$ Now let's apply this to the question. If we have "The person is female" $\longleftrightarrow A_1$ "The person has long hair" $\longleftrightarrow B_1$ "The person has blood type AX3" $\longleftrightarrow C_1$ then $a = 1$, $b = 1$, $c = 1$, $a_1 = 1$, $b_1 = 1$, $a_2 = 1$, $c_2 = 1$, $u_1 = 0.9$, $u_2 = 0.8$, and we find that for the maximum entropy solution, $(A_1 | B_1 C_1 I) \simeq 0.932$. Therefore the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.932. Case 2 Now we repeat the exercise with the extra constraint that for a given person, knowing the value of $B$ (the hair state) does not affect our estimate of the value of $C$ (the blood type state), and vice versa. Everything is the same as in Case 1, except there are two extra constraints in the optimisation, namely: \begin{align*} (B_0 | C_l I) &= (B_0 | I) \quad , \quad l = 0, 1 \\ \end{align*} i.e. \begin{align*} \frac{\sum\limits_i (A_i B_0 C_l | I)}{\sum\limits_{i,j} (A_i B_j C_l | I)} &= \sum_{i,k} (A_i B_0 C_k | I) \quad , \quad l = 0, 1 \end{align*} This gives $(A_1 | B_1 C_1 I) \simeq 0.936$, so the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.936. Case 3 Now we remove the independence condition and replace it with the prior condition that there is an equal chance that a given person is male or female: $$ (A_0 | I) = \frac{1}{2} \quad \quad \text{i.e.} \quad \sum_{j,k} (A_0 B_j C_k | I) = \frac{1}{2} $$ This time $(A_1 | B_1 C_1 I) \simeq 0.973$, so the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.973. Case 4 Finally we reintroduce the independence constraints of Case 2, and find that $(A_1 | B_1 C_1 I) \simeq 0.989$. Therefore the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.989.
What is the probability that this person is female?
Question Restatement and Generalisation $A$, $B$, and $C$ are binary unknowns whose possible values are $0$ and $1$. Let $Z_i$ stand for the proposition, "The value of $Z$ is $i$". Also let $(X | Y)$
What is the probability that this person is female? Question Restatement and Generalisation $A$, $B$, and $C$ are binary unknowns whose possible values are $0$ and $1$. Let $Z_i$ stand for the proposition, "The value of $Z$ is $i$". Also let $(X | Y)$ stand for "The probability that $X$, given that $Y$". What is $(A_a | B_b C_c I)$, given that $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ and $(B C | I) = (B | I)(C | I)$ $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ and $(A_0 | I) = \frac{1}{2}$ $(A_{a_1} | B_{b_1} I) = u_1$ and $(A_{a_2} | C_{c_2} I) = u_2$ and $(A_0 | I) = \frac{1}{2}$ and $(B C | I) = (B | I)(C | I)$ and that $I$ contains no relevant information besides what is implicit in the assignments? The last conjunct of conditions 2 and 4 is shorthand for the independence statement $$ (B_j C_k | I) = (B_j | I)(C_k | I) \quad , \quad j = 0, 1 \quad k = 0,1 $$ Treat each of the four cases in turn. Answers Case 1 We have to specify the distribution $(ABC | I)$. The problem is underdetermined, because $(ABC | I)$ requires eight numbers, but we have only three equations---the two given conditions and the normalisation condition. It has been shown by various esoteric means that the distribution to assign when the information doesn't otherwise determine a solution is the one that, of all distributions consistent with the known information, has the greatest entropy. Any other distribution implies that we know more than the known information, which of course is a contradiction. All we need to do, therefore, is assign the maximum entropy distribution. This is more easily said than done, and I have not found a general closed-form solution. But particular solutions can be found using a numerical optimiser. We maximise $$ - \sum_{i,j,k} (A_i B_j C_k | I) \ln (A_i B_j C_k | I) $$ subject to the constraints $$ \sum_{i,j,k} (A_i B_j C_k | I) = 1 $$ and $$ (A_{a_1} | B_{b_1} I) = u_1 \quad\quad \text{i.e.} \quad \frac{\sum\limits_k (A_{a_1} B_{b_1} C_k | I )}{\sum\limits_{i,k} (A_i B_{b_1} C_k | I)} = u_1 $$ and $$ (A_{a_2} | C_{c_2} I) = u_2 \quad\quad \text{i.e.} \quad \frac{\sum\limits_j (A_{a_2} B_j C_{c_2} | I)}{\sum\limits_{i,j} (A_i B_j C_{c_2} | I)} = u_2 $$ Now let's apply this to the question. If we have "The person is female" $\longleftrightarrow A_1$ "The person has long hair" $\longleftrightarrow B_1$ "The person has blood type AX3" $\longleftrightarrow C_1$ then $a = 1$, $b = 1$, $c = 1$, $a_1 = 1$, $b_1 = 1$, $a_2 = 1$, $c_2 = 1$, $u_1 = 0.9$, $u_2 = 0.8$, and we find that for the maximum entropy solution, $(A_1 | B_1 C_1 I) \simeq 0.932$. Therefore the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.932. Case 2 Now we repeat the exercise with the extra constraint that for a given person, knowing the value of $B$ (the hair state) does not affect our estimate of the value of $C$ (the blood type state), and vice versa. Everything is the same as in Case 1, except there are two extra constraints in the optimisation, namely: \begin{align*} (B_0 | C_l I) &= (B_0 | I) \quad , \quad l = 0, 1 \\ \end{align*} i.e. \begin{align*} \frac{\sum\limits_i (A_i B_0 C_l | I)}{\sum\limits_{i,j} (A_i B_j C_l | I)} &= \sum_{i,k} (A_i B_0 C_k | I) \quad , \quad l = 0, 1 \end{align*} This gives $(A_1 | B_1 C_1 I) \simeq 0.936$, so the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.936. Case 3 Now we remove the independence condition and replace it with the prior condition that there is an equal chance that a given person is male or female: $$ (A_0 | I) = \frac{1}{2} \quad \quad \text{i.e.} \quad \sum_{j,k} (A_0 B_j C_k | I) = \frac{1}{2} $$ This time $(A_1 | B_1 C_1 I) \simeq 0.973$, so the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.973. Case 4 Finally we reintroduce the independence constraints of Case 2, and find that $(A_1 | B_1 C_1 I) \simeq 0.989$. Therefore the probability that the person behind the curtain is female, given that he/she has long hair and blood type AX3, is 0.989.
What is the probability that this person is female? Question Restatement and Generalisation $A$, $B$, and $C$ are binary unknowns whose possible values are $0$ and $1$. Let $Z_i$ stand for the proposition, "The value of $Z$ is $i$". Also let $(X | Y)$
8,570
What is the probability that this person is female?
I believe now that, if we assume a ratio of men and women in the population at large, then there is a single indisputable answer. A = the event that the person has long hair B = the event that the person has blood type AX3 C = the event that person is female P(C|A) = 0.9 P(C|B) = 0.8 P(C) = 0.5 (i.e. let's assume an equal ratio of men and women in the population at large) Then P(C|A and B) = [P(C|A) x P(C|B) / P(C)] / [[P(C|A) x P(C|B) / P(C)] + [[1-P(C|A)] x [1-P(C|B)] / [1-P(C)]]] in this case, P(C|A and B) = 0.972973
What is the probability that this person is female?
I believe now that, if we assume a ratio of men and women in the population at large, then there is a single indisputable answer. A = the event that the person has long hair B = the event that the per
What is the probability that this person is female? I believe now that, if we assume a ratio of men and women in the population at large, then there is a single indisputable answer. A = the event that the person has long hair B = the event that the person has blood type AX3 C = the event that person is female P(C|A) = 0.9 P(C|B) = 0.8 P(C) = 0.5 (i.e. let's assume an equal ratio of men and women in the population at large) Then P(C|A and B) = [P(C|A) x P(C|B) / P(C)] / [[P(C|A) x P(C|B) / P(C)] + [[1-P(C|A)] x [1-P(C|B)] / [1-P(C)]]] in this case, P(C|A and B) = 0.972973
What is the probability that this person is female? I believe now that, if we assume a ratio of men and women in the population at large, then there is a single indisputable answer. A = the event that the person has long hair B = the event that the per
8,571
What is the probability that this person is female?
Note: In order to get a definitive answer, the below answers assume that the probability of a person, a long-haired man, and a long-haired women having AX3 are approximately the same. If more accuracy is desired, this should be verified. You start out with the knowledge that the person has long hair, so at this point the odds are: 90:10 Note: The ratio of males to females in the general population does not matter to us once we find out the person has long hair. For example, if there were 1 female in a hundred in the general population, a randomly-selected long-haired person would still be a female 90% of the time. The ratio of females to males DOES matter! (see the update below for details) Next, we learn that the person has AX3. Because AX3 is unrelated to long hair, the ratio of men to women is known to be 50:50, and because of our assumption of the probabilities being the same, we can simply multiply each side of the probability and normalize so that the sum of the sides of the probability equals 100: (90:10) * (80:20) ==> 7200:200 Normalize by dividing each side by (7200+200)/100 = 74 ==> 7200/74:200/74 ==> 97.297.. : 2.702.. Thus, the chance that the person behind the curtain is female is approximately 97.297%. UPDATE Here's a further exploration of the problem: Definitions: f - number of females m - number of males fl - number of females with long hair ml - number of males with long hair fx - number of females with AX3 mx - number of males with AX3 flx - number of females with long hair and AX3 mlx - number of males with long hair and AX3 pfl - probability that a female has long hair pml - probability that a male has long hair pfx - probability that a female has AX3 pmx - probability that a male has AX3 First, we are given that 90% of long-haired people are females, and 80% of people with AX3 are female, so: fl = 9 * ml pfl = fl / f pml = ml / m = fl / (9 * m) fx = 4 * mx pfx = fx / f pmx = mx / m = fx / (4 * m) Because we assumed that the probability of AX3 is independent of gender and long hair, our calculated pfx will apply to women with long hair, and pmx will apply to men with long-hair to find the number of them that likely have AX3: flx = fl * pfx = fl * (fx / f) = (fl * fx) / f mlx = ml * pmx = (fl / 9) * (fx / (4 * m)) = (fl * fx) / (36 * m) Thus, the likely ratio of the number of females with long-hair and AX3 to the number of males with long-hair and AX3 is: flx : mlx (fl * fx) / f : (fl * fx) / (36 * m) 1/f : 1 / (36m) 36m : f Because it is given that there is an equal number of 50:50, you can cancel both sides and end with 36 females to every male. Otherwise, there are 36*m/f females for every male in the specified subgroup. For example, if there were twice as many women as men, there would be 72 females to each male of those that have long-hair and AX3.
What is the probability that this person is female?
Note: In order to get a definitive answer, the below answers assume that the probability of a person, a long-haired man, and a long-haired women having AX3 are approximately the same. If more accura
What is the probability that this person is female? Note: In order to get a definitive answer, the below answers assume that the probability of a person, a long-haired man, and a long-haired women having AX3 are approximately the same. If more accuracy is desired, this should be verified. You start out with the knowledge that the person has long hair, so at this point the odds are: 90:10 Note: The ratio of males to females in the general population does not matter to us once we find out the person has long hair. For example, if there were 1 female in a hundred in the general population, a randomly-selected long-haired person would still be a female 90% of the time. The ratio of females to males DOES matter! (see the update below for details) Next, we learn that the person has AX3. Because AX3 is unrelated to long hair, the ratio of men to women is known to be 50:50, and because of our assumption of the probabilities being the same, we can simply multiply each side of the probability and normalize so that the sum of the sides of the probability equals 100: (90:10) * (80:20) ==> 7200:200 Normalize by dividing each side by (7200+200)/100 = 74 ==> 7200/74:200/74 ==> 97.297.. : 2.702.. Thus, the chance that the person behind the curtain is female is approximately 97.297%. UPDATE Here's a further exploration of the problem: Definitions: f - number of females m - number of males fl - number of females with long hair ml - number of males with long hair fx - number of females with AX3 mx - number of males with AX3 flx - number of females with long hair and AX3 mlx - number of males with long hair and AX3 pfl - probability that a female has long hair pml - probability that a male has long hair pfx - probability that a female has AX3 pmx - probability that a male has AX3 First, we are given that 90% of long-haired people are females, and 80% of people with AX3 are female, so: fl = 9 * ml pfl = fl / f pml = ml / m = fl / (9 * m) fx = 4 * mx pfx = fx / f pmx = mx / m = fx / (4 * m) Because we assumed that the probability of AX3 is independent of gender and long hair, our calculated pfx will apply to women with long hair, and pmx will apply to men with long-hair to find the number of them that likely have AX3: flx = fl * pfx = fl * (fx / f) = (fl * fx) / f mlx = ml * pmx = (fl / 9) * (fx / (4 * m)) = (fl * fx) / (36 * m) Thus, the likely ratio of the number of females with long-hair and AX3 to the number of males with long-hair and AX3 is: flx : mlx (fl * fx) / f : (fl * fx) / (36 * m) 1/f : 1 / (36m) 36m : f Because it is given that there is an equal number of 50:50, you can cancel both sides and end with 36 females to every male. Otherwise, there are 36*m/f females for every male in the specified subgroup. For example, if there were twice as many women as men, there would be 72 females to each male of those that have long-hair and AX3.
What is the probability that this person is female? Note: In order to get a definitive answer, the below answers assume that the probability of a person, a long-haired man, and a long-haired women having AX3 are approximately the same. If more accura
8,572
What is the probability that this person is female?
98% Female, simple interpolation. First premise 90% female, leaves 10%, second premise only leaves 2% of the existing 10%, hence 98% female
What is the probability that this person is female?
98% Female, simple interpolation. First premise 90% female, leaves 10%, second premise only leaves 2% of the existing 10%, hence 98% female
What is the probability that this person is female? 98% Female, simple interpolation. First premise 90% female, leaves 10%, second premise only leaves 2% of the existing 10%, hence 98% female
What is the probability that this person is female? 98% Female, simple interpolation. First premise 90% female, leaves 10%, second premise only leaves 2% of the existing 10%, hence 98% female
8,573
One-vs-All and One-vs-One in svm?
The difference is the number of classifiers you have to learn, which strongly correlates with the decision boundary they create. Assume you have $N$ different classes. One vs all will train one classifier per class in total $N$ classifiers. For class $i$ it will assume $i$-labels as positive and the rest as negative. This often leads to imbalanced datasets meaning generic SVM might not work, but still there are some workarounds. In one vs one you have to train a separate classifier for each different pair of labels. This leads to $\frac{N(N-1)}{2}$ classifiers. This is much less sensitive to the problems of imbalanced datasets but is much more computationally expensive.
One-vs-All and One-vs-One in svm?
The difference is the number of classifiers you have to learn, which strongly correlates with the decision boundary they create. Assume you have $N$ different classes. One vs all will train one classi
One-vs-All and One-vs-One in svm? The difference is the number of classifiers you have to learn, which strongly correlates with the decision boundary they create. Assume you have $N$ different classes. One vs all will train one classifier per class in total $N$ classifiers. For class $i$ it will assume $i$-labels as positive and the rest as negative. This often leads to imbalanced datasets meaning generic SVM might not work, but still there are some workarounds. In one vs one you have to train a separate classifier for each different pair of labels. This leads to $\frac{N(N-1)}{2}$ classifiers. This is much less sensitive to the problems of imbalanced datasets but is much more computationally expensive.
One-vs-All and One-vs-One in svm? The difference is the number of classifiers you have to learn, which strongly correlates with the decision boundary they create. Assume you have $N$ different classes. One vs all will train one classi
8,574
Strategies for teaching the sampling distribution
In my opinion, sampling distributions are the key idea of statistics 101. You might as well skip the course as skip that issue. However, I am very familiar with the fact that students just don't get it, seemingly no matter what you do. I have a series of strategies. These can take up a lot of time, but I recommend skipping / abbreviating other topics, so as to ensure that they get the idea of the sampling distribution. Here are some tips: Say it distinctly: I first explicitly mention that there 3 different distributions that we are concerned with: the population distribution, the sample distribution, and the sampling distribution. I say this over and over throughout the lesson, and then over and over throughout the course. Every time I say these terms I emphasize the distinctive ending: sam-ple, samp-ling. (Yes, students do get sick of this; they also get the concept.) Use pictures (figures): I have a set of standard figures that I use every time I talk about this. It has the three distributions pictured distinctly and typically labeled. (The labels that go with this figure are on the PowerPoint slide and include short descriptions, so they don't show up here, but obviously it's: the population at the top, then samples, then sampling distribution.) Give the students activities: The first time you introduce this concept, either bring in a roll of nickles (some quarters may disappear) or a bunch of 6-sided dice. Have the students form into small groups and generate a set of 10 values and average them. Then you can make a histogram on the board or with Excel. Use animations (simulations): I write some (comically inefficient) code in R to generate data & display it in action. This part is especially helpful when you transition to explaining the Central Limit Theorem. (Notice the Sys.sleep() statements, these pauses give me a moment to explain what is going on at each stage.) N = 10 number_of_samples = 1000 iterations = c(3, 7, number_of_samples) breakpoints = seq(10, 91, 3) meanVect = vector() x = seq(10, 90) height = 30/dnorm(50, mean=50, sd=10) y = height*dnorm(x, mean=50, sd=10) windows(height=7, width=5) par(mfrow=c(3,1), omi=c(0.5,0,0,0), mai=c(0.1, 0.1, 0.2, 0.1)) for(i in 1:iterations[3]) { plot(x,y, type="l", col="blue", axes=F, xlab="", ylab="") segments(x0=20, y0=0, x1=20, y1=y[11], col="lightgray") segments(x0=30, y0=0, x1=30, y1=y[21], col="gray") segments(x0=40, y0=0, x1=40, y1=y[31], col="darkgray") segments(x0=50, y0=0, x1=50, y1=y[41]) segments(x0=60, y0=0, x1=60, y1=y[51], col="darkgray") segments(x0=70, y0=0, x1=70, y1=y[61], col="gray") segments(x0=80, y0=0, x1=80, y1=y[71], col="lightgray") abline(h=0) if(i==1) { Sys.sleep(2) } sample = rnorm(N, mean=50, sd=10) points(x=sample, y=rep(1,N), col="green", pch="*") if(i<=iterations[1]) { Sys.sleep(2) } xhist1 = hist(sample, breaks=breakpoints, plot=F) hist(sample, breaks=breakpoints, axes=F, col="green", xlim=c(10,90), ylim=c(0,N), main="", xlab="", ylab="") if(i==iterations[3]) { abline(v=50) } if(i<=iterations[2]) { Sys.sleep(2) } sampleMean = mean(sample) segments(x0=sampleMean, y0=0, x1=sampleMean, y1=max(xhist1$counts)+1, col="red", lwd=3) if(i<=iterations[1]) { Sys.sleep(2) } meanVect = c(meanVect, sampleMean) hist(meanVect, breaks=x, axes=F, col="red", main="", xlab="", ylab="", ylim=c(0,((N/3)+(0.2*i)))) if(i<=iterations[2]) { Sys.sleep(2) } } Sys.sleep(2) xhist2 = hist(meanVect, breaks=x, plot=F) xMean = round(mean(meanVect), digits=3) xSD = round(sd(meanVect), digits=3) histHeight = (max(xhist2$counts)/dnorm(xMean, mean=xMean, sd=xSD)) lines(x=x, y=(histHeight*dnorm(x, mean=xMean, sd=xSD)), col="yellow", lwd=2) abline(v=50) txt1 = paste("population mean = 50 sampling distribution mean = ", xMean, sep="") txt2 = paste("SD = 10 10/sqrt(", N,") = 3.162 SE = ", xSD, sep="") mtext(txt1, side=1, outer=T) mtext(txt2, side=1, line=1.5, outer=T) Reinstantiate these concepts throughout the semester: I bring the idea of the sampling distribution up again each time we talk about the next subject (albeit typically only very briefly). The most important place for this is when you teach ANOVA, as the null hypothesis case there really is the situation in which you sampled from the same population distribution several times, and your set of group means really is an empirical sampling distribution. (For an example of this, see my answer here: How does the standard error work?.)
Strategies for teaching the sampling distribution
In my opinion, sampling distributions are the key idea of statistics 101. You might as well skip the course as skip that issue. However, I am very familiar with the fact that students just don't get
Strategies for teaching the sampling distribution In my opinion, sampling distributions are the key idea of statistics 101. You might as well skip the course as skip that issue. However, I am very familiar with the fact that students just don't get it, seemingly no matter what you do. I have a series of strategies. These can take up a lot of time, but I recommend skipping / abbreviating other topics, so as to ensure that they get the idea of the sampling distribution. Here are some tips: Say it distinctly: I first explicitly mention that there 3 different distributions that we are concerned with: the population distribution, the sample distribution, and the sampling distribution. I say this over and over throughout the lesson, and then over and over throughout the course. Every time I say these terms I emphasize the distinctive ending: sam-ple, samp-ling. (Yes, students do get sick of this; they also get the concept.) Use pictures (figures): I have a set of standard figures that I use every time I talk about this. It has the three distributions pictured distinctly and typically labeled. (The labels that go with this figure are on the PowerPoint slide and include short descriptions, so they don't show up here, but obviously it's: the population at the top, then samples, then sampling distribution.) Give the students activities: The first time you introduce this concept, either bring in a roll of nickles (some quarters may disappear) or a bunch of 6-sided dice. Have the students form into small groups and generate a set of 10 values and average them. Then you can make a histogram on the board or with Excel. Use animations (simulations): I write some (comically inefficient) code in R to generate data & display it in action. This part is especially helpful when you transition to explaining the Central Limit Theorem. (Notice the Sys.sleep() statements, these pauses give me a moment to explain what is going on at each stage.) N = 10 number_of_samples = 1000 iterations = c(3, 7, number_of_samples) breakpoints = seq(10, 91, 3) meanVect = vector() x = seq(10, 90) height = 30/dnorm(50, mean=50, sd=10) y = height*dnorm(x, mean=50, sd=10) windows(height=7, width=5) par(mfrow=c(3,1), omi=c(0.5,0,0,0), mai=c(0.1, 0.1, 0.2, 0.1)) for(i in 1:iterations[3]) { plot(x,y, type="l", col="blue", axes=F, xlab="", ylab="") segments(x0=20, y0=0, x1=20, y1=y[11], col="lightgray") segments(x0=30, y0=0, x1=30, y1=y[21], col="gray") segments(x0=40, y0=0, x1=40, y1=y[31], col="darkgray") segments(x0=50, y0=0, x1=50, y1=y[41]) segments(x0=60, y0=0, x1=60, y1=y[51], col="darkgray") segments(x0=70, y0=0, x1=70, y1=y[61], col="gray") segments(x0=80, y0=0, x1=80, y1=y[71], col="lightgray") abline(h=0) if(i==1) { Sys.sleep(2) } sample = rnorm(N, mean=50, sd=10) points(x=sample, y=rep(1,N), col="green", pch="*") if(i<=iterations[1]) { Sys.sleep(2) } xhist1 = hist(sample, breaks=breakpoints, plot=F) hist(sample, breaks=breakpoints, axes=F, col="green", xlim=c(10,90), ylim=c(0,N), main="", xlab="", ylab="") if(i==iterations[3]) { abline(v=50) } if(i<=iterations[2]) { Sys.sleep(2) } sampleMean = mean(sample) segments(x0=sampleMean, y0=0, x1=sampleMean, y1=max(xhist1$counts)+1, col="red", lwd=3) if(i<=iterations[1]) { Sys.sleep(2) } meanVect = c(meanVect, sampleMean) hist(meanVect, breaks=x, axes=F, col="red", main="", xlab="", ylab="", ylim=c(0,((N/3)+(0.2*i)))) if(i<=iterations[2]) { Sys.sleep(2) } } Sys.sleep(2) xhist2 = hist(meanVect, breaks=x, plot=F) xMean = round(mean(meanVect), digits=3) xSD = round(sd(meanVect), digits=3) histHeight = (max(xhist2$counts)/dnorm(xMean, mean=xMean, sd=xSD)) lines(x=x, y=(histHeight*dnorm(x, mean=xMean, sd=xSD)), col="yellow", lwd=2) abline(v=50) txt1 = paste("population mean = 50 sampling distribution mean = ", xMean, sep="") txt2 = paste("SD = 10 10/sqrt(", N,") = 3.162 SE = ", xSD, sep="") mtext(txt1, side=1, outer=T) mtext(txt2, side=1, line=1.5, outer=T) Reinstantiate these concepts throughout the semester: I bring the idea of the sampling distribution up again each time we talk about the next subject (albeit typically only very briefly). The most important place for this is when you teach ANOVA, as the null hypothesis case there really is the situation in which you sampled from the same population distribution several times, and your set of group means really is an empirical sampling distribution. (For an example of this, see my answer here: How does the standard error work?.)
Strategies for teaching the sampling distribution In my opinion, sampling distributions are the key idea of statistics 101. You might as well skip the course as skip that issue. However, I am very familiar with the fact that students just don't get
8,575
Strategies for teaching the sampling distribution
I have had some luck with reminding students that the sampling distribution is the distribution of the test statistic based on a random sample. I have students think about what would happen in the sampling process itself was biased - focusing on extreme cases. For example, what would the "sampling distribution" look like if our sampling process always picked the same (special) subset? Then I would consider what the "sampling distribution" would look like if our sampling process only picked two specific (special) subsets (each with probability 1/2). These are pretty simple to work out with the sample mean (especially for particular choices of "special" for the underlying population). I think for some (clearly not all) students this seems to help them with the idea that the sampling distribution can be very different from the population distribution. I have also used the central limit theorem example that Michael Chernick mentioned with some success - especially with distributions that are clearly not normal (simulations really do seem to help).
Strategies for teaching the sampling distribution
I have had some luck with reminding students that the sampling distribution is the distribution of the test statistic based on a random sample. I have students think about what would happen in the sam
Strategies for teaching the sampling distribution I have had some luck with reminding students that the sampling distribution is the distribution of the test statistic based on a random sample. I have students think about what would happen in the sampling process itself was biased - focusing on extreme cases. For example, what would the "sampling distribution" look like if our sampling process always picked the same (special) subset? Then I would consider what the "sampling distribution" would look like if our sampling process only picked two specific (special) subsets (each with probability 1/2). These are pretty simple to work out with the sample mean (especially for particular choices of "special" for the underlying population). I think for some (clearly not all) students this seems to help them with the idea that the sampling distribution can be very different from the population distribution. I have also used the central limit theorem example that Michael Chernick mentioned with some success - especially with distributions that are clearly not normal (simulations really do seem to help).
Strategies for teaching the sampling distribution I have had some luck with reminding students that the sampling distribution is the distribution of the test statistic based on a random sample. I have students think about what would happen in the sam
8,576
Strategies for teaching the sampling distribution
I start back with the teaching of probability. I don't go into a lot of the formal definitions and rules (just not enough time), but show probability by simulation. The Monty Hall problem is a great example to use, I show through simulation (and then follow-up with the logic) that the strategy to switch gives a higher probability of winning. I point out that by simulation we were able to play the game many times (without risk or reward) to evaluate the strategies and that lets us choose the better strategy (if we are ever in that situation). Choosing the better strategy does not guarentee a win, but it gives us a better chance and helps choose between strategies. I then point out that how this will apply to the rest of the course is that it will help us choose strategies where there is a random component, but more realistic situations that we will be in. Then when I introduce the sampling distribution I again start with simulation and say we want to develop strategies. Just like with the Monty Hall problem, in real life we will only be able to take 1 sample, but we can simulate a bunch of samples to help us develop a strategy. I then show simulations of many samples from the same population (known population in this case) and show the relationships that we learn from the simulations (histogram of the sample means), i.e. sample means clustered around true mean (mean of means is mean), smaller standard deviation of sampling distribution for bigger samples, more normal for bigger samples. The whole time I talk about repeating the ideas of simulation to choose strategies, just the same idea as the Monty Hall problem applied now to sample means instead of game shows. I then show the official rules and say that in addition to the simulations they can be proved mathematically, but I will not inflict the proofs on the entire class. I offer that if they really want to see the mathematical proofs they can come to an office hour and I will show them the math (nobody from the intro classes has taken me up on this yet). Then when we get to inference I say that we will only be able to take 1 sample in the real world, just like we would only get to play the game 1 time (at most), but we can use the strategies we learned from simulating many samples to develop a strategy (z-test, t-test, or CI formula) that will give us the chosen properties (chance of being correct). Just like with the game, we don't know before we start if our final conclusion will be correct (and usually we still don't know afterwards), but we do know from the simulations and sampling distribution what the long term probability is using that strategy. Do 100% of students have a perfect understanding? no, but I think more of them get the general idea that we can use simulation and math rules (that they are glad they don't have to look at, just trust the book/instructor) to choose a strategy/formula that has the desired properties.
Strategies for teaching the sampling distribution
I start back with the teaching of probability. I don't go into a lot of the formal definitions and rules (just not enough time), but show probability by simulation. The Monty Hall problem is a great
Strategies for teaching the sampling distribution I start back with the teaching of probability. I don't go into a lot of the formal definitions and rules (just not enough time), but show probability by simulation. The Monty Hall problem is a great example to use, I show through simulation (and then follow-up with the logic) that the strategy to switch gives a higher probability of winning. I point out that by simulation we were able to play the game many times (without risk or reward) to evaluate the strategies and that lets us choose the better strategy (if we are ever in that situation). Choosing the better strategy does not guarentee a win, but it gives us a better chance and helps choose between strategies. I then point out that how this will apply to the rest of the course is that it will help us choose strategies where there is a random component, but more realistic situations that we will be in. Then when I introduce the sampling distribution I again start with simulation and say we want to develop strategies. Just like with the Monty Hall problem, in real life we will only be able to take 1 sample, but we can simulate a bunch of samples to help us develop a strategy. I then show simulations of many samples from the same population (known population in this case) and show the relationships that we learn from the simulations (histogram of the sample means), i.e. sample means clustered around true mean (mean of means is mean), smaller standard deviation of sampling distribution for bigger samples, more normal for bigger samples. The whole time I talk about repeating the ideas of simulation to choose strategies, just the same idea as the Monty Hall problem applied now to sample means instead of game shows. I then show the official rules and say that in addition to the simulations they can be proved mathematically, but I will not inflict the proofs on the entire class. I offer that if they really want to see the mathematical proofs they can come to an office hour and I will show them the math (nobody from the intro classes has taken me up on this yet). Then when we get to inference I say that we will only be able to take 1 sample in the real world, just like we would only get to play the game 1 time (at most), but we can use the strategies we learned from simulating many samples to develop a strategy (z-test, t-test, or CI formula) that will give us the chosen properties (chance of being correct). Just like with the game, we don't know before we start if our final conclusion will be correct (and usually we still don't know afterwards), but we do know from the simulations and sampling distribution what the long term probability is using that strategy. Do 100% of students have a perfect understanding? no, but I think more of them get the general idea that we can use simulation and math rules (that they are glad they don't have to look at, just trust the book/instructor) to choose a strategy/formula that has the desired properties.
Strategies for teaching the sampling distribution I start back with the teaching of probability. I don't go into a lot of the formal definitions and rules (just not enough time), but show probability by simulation. The Monty Hall problem is a great
8,577
Strategies for teaching the sampling distribution
This is a very important and well-thought out issue on your part. I do think the concept of the sampling distribution is very basic to understanding inference and definitely should be taught. I have taught many introductory statistics courses, particularly in biostatistics. I teach the concept of sampling distribution and have approaches that I think are good but don't really have good feedback to determine how successful I have been with them. Anyway here is what I do. First I try to give a simple definition. The sampling distribution is the distribution that the test statistic would have if the sampling process were repeated many times. It depends on the population distribution that the data are assumed to be generated from. Although I think this is about as simple a definition as I can give I realize, it is not very simple and understanding of the concept will not come immediately in most cases. So follow this up with a basic example that reinforces what is said with the definition. The example I would use is a sample of size $n$ that is independent and identically distributed as a normal distribution with mean $\mu$ and variance $\sigma^2$. The sample average, which is used as a point estimate or to form a test statistic for the population mean $\mu$, has a sampling distribution which is normal with mean $\mu$ and variance $\sigma^2$/n. Then I would follow this up with an important application, the central limit theorem. In the simplest terms, the central limit theorem says that for many distributions that are not normal, the sampling distribution for the sample mean will be close to a normal distribution when the sample size $n$ is large. To illustrate this take distributions like the uniform (a bimodal distribution would also be good to look at) and show what the sampling distribution for the mean looks like for sample sizes of 3, 4, 5, 10 and 100. The student can see how the shape of the distribution changes from something that does not look normal at all for small $n$ to something that looks very much like a normal distribution for large $n$. To convince the student that these sampling distributions really do have these shapes have the students conduct simulations generating many samples of various sizes and compute the sample means. Then have them generate histograms for these estimates of the mean. I would also suggest applying a physical demonstration showing how this works using a quincunx board. While doing this you point out how the device generates samples of the sum of independent Bernoulli trials where the probability of going left or right at each level equals 1/2. The resulting stacks at the bottom represent a histogram for this sampling distribution (the binomial) and its shape can be seen to look approximately normal after a large number of balls land at the bottom of the quincunx, a demonstration of the DeMoivre-Laplace version of the central limit theorem through sampling distributions.
Strategies for teaching the sampling distribution
This is a very important and well-thought out issue on your part. I do think the concept of the sampling distribution is very basic to understanding inference and definitely should be taught. I have
Strategies for teaching the sampling distribution This is a very important and well-thought out issue on your part. I do think the concept of the sampling distribution is very basic to understanding inference and definitely should be taught. I have taught many introductory statistics courses, particularly in biostatistics. I teach the concept of sampling distribution and have approaches that I think are good but don't really have good feedback to determine how successful I have been with them. Anyway here is what I do. First I try to give a simple definition. The sampling distribution is the distribution that the test statistic would have if the sampling process were repeated many times. It depends on the population distribution that the data are assumed to be generated from. Although I think this is about as simple a definition as I can give I realize, it is not very simple and understanding of the concept will not come immediately in most cases. So follow this up with a basic example that reinforces what is said with the definition. The example I would use is a sample of size $n$ that is independent and identically distributed as a normal distribution with mean $\mu$ and variance $\sigma^2$. The sample average, which is used as a point estimate or to form a test statistic for the population mean $\mu$, has a sampling distribution which is normal with mean $\mu$ and variance $\sigma^2$/n. Then I would follow this up with an important application, the central limit theorem. In the simplest terms, the central limit theorem says that for many distributions that are not normal, the sampling distribution for the sample mean will be close to a normal distribution when the sample size $n$ is large. To illustrate this take distributions like the uniform (a bimodal distribution would also be good to look at) and show what the sampling distribution for the mean looks like for sample sizes of 3, 4, 5, 10 and 100. The student can see how the shape of the distribution changes from something that does not look normal at all for small $n$ to something that looks very much like a normal distribution for large $n$. To convince the student that these sampling distributions really do have these shapes have the students conduct simulations generating many samples of various sizes and compute the sample means. Then have them generate histograms for these estimates of the mean. I would also suggest applying a physical demonstration showing how this works using a quincunx board. While doing this you point out how the device generates samples of the sum of independent Bernoulli trials where the probability of going left or right at each level equals 1/2. The resulting stacks at the bottom represent a histogram for this sampling distribution (the binomial) and its shape can be seen to look approximately normal after a large number of balls land at the bottom of the quincunx, a demonstration of the DeMoivre-Laplace version of the central limit theorem through sampling distributions.
Strategies for teaching the sampling distribution This is a very important and well-thought out issue on your part. I do think the concept of the sampling distribution is very basic to understanding inference and definitely should be taught. I have
8,578
Strategies for teaching the sampling distribution
I think it would be good to put a 'population' of numbers in a bag ( ranging for example from 1-10). You could make your own tiles, or use coins, playing cards etc. Get students to sit in groups (5 or more) and each picks a number out of the bag. Each group then calculates the mean value for their group. Tell them that earlier you worked out the population mean, plot it on a histogram and get a member of each group to come and plot their sample mean on a histogram around this. Get them to do this exercise a few times to 'build up the histogram'. You will then be able to graphically show the variation in sample means around the population mean. Work out the variation in sample means compared to the population mean. I think students distinctly remember doing such a practical exercise and the concept of sampling variation will come back to them more easily as a result. It might sound a bit babyish but students sometimes just like a chance to do something active....there aren't many opportunities to do this in statistics.
Strategies for teaching the sampling distribution
I think it would be good to put a 'population' of numbers in a bag ( ranging for example from 1-10). You could make your own tiles, or use coins, playing cards etc. Get students to sit in groups (5 o
Strategies for teaching the sampling distribution I think it would be good to put a 'population' of numbers in a bag ( ranging for example from 1-10). You could make your own tiles, or use coins, playing cards etc. Get students to sit in groups (5 or more) and each picks a number out of the bag. Each group then calculates the mean value for their group. Tell them that earlier you worked out the population mean, plot it on a histogram and get a member of each group to come and plot their sample mean on a histogram around this. Get them to do this exercise a few times to 'build up the histogram'. You will then be able to graphically show the variation in sample means around the population mean. Work out the variation in sample means compared to the population mean. I think students distinctly remember doing such a practical exercise and the concept of sampling variation will come back to them more easily as a result. It might sound a bit babyish but students sometimes just like a chance to do something active....there aren't many opportunities to do this in statistics.
Strategies for teaching the sampling distribution I think it would be good to put a 'population' of numbers in a bag ( ranging for example from 1-10). You could make your own tiles, or use coins, playing cards etc. Get students to sit in groups (5 o
8,579
How can you account for COVID-19 in your models?
We do forecasting for retail: supermarkets, drugstores etc. We add predictors to explain our sales time series, specifically different predictors for different phases of the lockdowns. On the one hand, that will cleanse the time series, so we don't misinterpret higher sales of cat litter boxes as a seasonal effect that will recur next year. On the other hand, this allows us to forecast the possible effect of new rounds of lockdowns. In addition, we remove periods of censored zero sales due to stockouts, like the empty toilet paper shelves in my local supermarket: Of course, there is a bit of an art to this, or rather a subjective dimension. Which part of COVID-19 influenced sales is a one-off event, and which part reflects a "new normal"? Depending on this, you will want to let your predictors run out, or keep them for the foreseeable future, essentially a "structural break" type of thing. Shameless piece of self-promotion: I actually briefly mentioned this at a webinar I gave last Friday. Here is the recording. My short remarks on COVID start at 15:45, right after the earthquakes. And yes, I do go into cat litter boxes.
How can you account for COVID-19 in your models?
We do forecasting for retail: supermarkets, drugstores etc. We add predictors to explain our sales time series, specifically different predictors for different phases of the lockdowns. On the one hand
How can you account for COVID-19 in your models? We do forecasting for retail: supermarkets, drugstores etc. We add predictors to explain our sales time series, specifically different predictors for different phases of the lockdowns. On the one hand, that will cleanse the time series, so we don't misinterpret higher sales of cat litter boxes as a seasonal effect that will recur next year. On the other hand, this allows us to forecast the possible effect of new rounds of lockdowns. In addition, we remove periods of censored zero sales due to stockouts, like the empty toilet paper shelves in my local supermarket: Of course, there is a bit of an art to this, or rather a subjective dimension. Which part of COVID-19 influenced sales is a one-off event, and which part reflects a "new normal"? Depending on this, you will want to let your predictors run out, or keep them for the foreseeable future, essentially a "structural break" type of thing. Shameless piece of self-promotion: I actually briefly mentioned this at a webinar I gave last Friday. Here is the recording. My short remarks on COVID start at 15:45, right after the earthquakes. And yes, I do go into cat litter boxes.
How can you account for COVID-19 in your models? We do forecasting for retail: supermarkets, drugstores etc. We add predictors to explain our sales time series, specifically different predictors for different phases of the lockdowns. On the one hand
8,580
How can you account for COVID-19 in your models?
That's an interesting question and I'm sure that there are dozens of different approaches. This is a "there is no wrong answer" type of question. From my perspective, I've been dealing with the Covid-19 when I think about revenue, which is almost as seeing the sales (as shown by Stephan), but not entirely, since there are things like price involved. These are the strategies I'm working on it and please let me know if anyone see a problem in any of them: Use a dummy in order to account for this pandemic. So this is useful in order to know the impact of the event, and we can just set it to zero once the problem is solved. The dummy may correspond to the lockdown or other variable you believe it's fair to use. You just gotta be careful so the "jump" of your prediction isn't too high; Use social networks to predict some market behaviour and incorporate it to your model; I do not recommend using deaths because this does not correspond to fear of leaving the house to do something. I believe there is no good correlation between this events, unfortunately. I suppose you could check for your city/country; You could also try to find what is the impact of the lockdowns in your country, maybe running a diff-in-diff if the strategy is different for each neighbourhood or city. Then, you would apply this change to fix the predictions your model is making. Honestly, I'm still figuring this out. This is what I can contribute for now, hopefully, I can bring new insights soon.
How can you account for COVID-19 in your models?
That's an interesting question and I'm sure that there are dozens of different approaches. This is a "there is no wrong answer" type of question. From my perspective, I've been dealing with the Covid-
How can you account for COVID-19 in your models? That's an interesting question and I'm sure that there are dozens of different approaches. This is a "there is no wrong answer" type of question. From my perspective, I've been dealing with the Covid-19 when I think about revenue, which is almost as seeing the sales (as shown by Stephan), but not entirely, since there are things like price involved. These are the strategies I'm working on it and please let me know if anyone see a problem in any of them: Use a dummy in order to account for this pandemic. So this is useful in order to know the impact of the event, and we can just set it to zero once the problem is solved. The dummy may correspond to the lockdown or other variable you believe it's fair to use. You just gotta be careful so the "jump" of your prediction isn't too high; Use social networks to predict some market behaviour and incorporate it to your model; I do not recommend using deaths because this does not correspond to fear of leaving the house to do something. I believe there is no good correlation between this events, unfortunately. I suppose you could check for your city/country; You could also try to find what is the impact of the lockdowns in your country, maybe running a diff-in-diff if the strategy is different for each neighbourhood or city. Then, you would apply this change to fix the predictions your model is making. Honestly, I'm still figuring this out. This is what I can contribute for now, hopefully, I can bring new insights soon.
How can you account for COVID-19 in your models? That's an interesting question and I'm sure that there are dozens of different approaches. This is a "there is no wrong answer" type of question. From my perspective, I've been dealing with the Covid-
8,581
How can you account for COVID-19 in your models?
I work for a large airline in the revenue and pricing area where we forecast revenue and bookings and other things. We tried 2 approaches. One was effectively scaling from pre-covid data. We tried predicting a lower quantile instead of the mean and having a dynamic scaling factor from 2019. This worked ok. What has worked best for me is just dropping all the pre-covid data and starting from around May. We add in a feature of 'days since the massive covid drop' and that's been very effective. Since airline revenues dropped by > 90% in some cases when covid started we basically had no ability to adjust since everything was wiped out. Plus there were so many last minute schedule changes and policies that we struggled to incorporate those quickly enough. Our current accuracy is near where it was pre-covid for many models but it varies depending on the approach and problem type. For the very beginning of covid when we had no data or idea what was happening, I actually just built a Markov Chain model showing how erratic bookings and cancellations were when our directors were asking for forecasts. It opened their eyes to the amount of uncertainty and variance that was present in the pre and post covid environment.
How can you account for COVID-19 in your models?
I work for a large airline in the revenue and pricing area where we forecast revenue and bookings and other things. We tried 2 approaches. One was effectively scaling from pre-covid data. We tried pre
How can you account for COVID-19 in your models? I work for a large airline in the revenue and pricing area where we forecast revenue and bookings and other things. We tried 2 approaches. One was effectively scaling from pre-covid data. We tried predicting a lower quantile instead of the mean and having a dynamic scaling factor from 2019. This worked ok. What has worked best for me is just dropping all the pre-covid data and starting from around May. We add in a feature of 'days since the massive covid drop' and that's been very effective. Since airline revenues dropped by > 90% in some cases when covid started we basically had no ability to adjust since everything was wiped out. Plus there were so many last minute schedule changes and policies that we struggled to incorporate those quickly enough. Our current accuracy is near where it was pre-covid for many models but it varies depending on the approach and problem type. For the very beginning of covid when we had no data or idea what was happening, I actually just built a Markov Chain model showing how erratic bookings and cancellations were when our directors were asking for forecasts. It opened their eyes to the amount of uncertainty and variance that was present in the pre and post covid environment.
How can you account for COVID-19 in your models? I work for a large airline in the revenue and pricing area where we forecast revenue and bookings and other things. We tried 2 approaches. One was effectively scaling from pre-covid data. We tried pre
8,582
How can you account for COVID-19 in your models?
I hope I can tell some interesting stories here just as the others: I worked on a project for a pharmaceutical company, which wanted to have their dementia and cold cough products to be modeled, especially during coronavirus/COVID-19 infection. For the dementia product, we already saw a decreasing trend that were already active before the crisis. In the end we were 10% past the original sales outcome in our sales forecast, but COVID-19 not really influenced the use of dementia. Although these dementia products are normally also taken in case of sudden deafness (caused by stress) we saw no clear sign of COVID-19, or in other words unusual product specifics that may lead to a higher consumption due to stressful times during COVID-19 and homeschooling. Thus, the negative trend in the year before was stronger than anticipated, but that was all. We decided to not incorporate any COVID-19 effects and it seemed right. Due to product specifics, we thought it was not correlated so high with COVID-19 lockdowns. In case of the cold/cough product, you can imagine two scenarios: people get less sick because of lockdowns, and thus even in the main season of influenza, sales would break down people are stockpiling We measured effects of coronavirus with dummies, and we already saw unusual activity in January, but I had not enough data to go on much more. The dummies aggregated to 3.000.000 € in sales. No one could have expected what happened: Hell, after the modeling, the client had a target mismatch of about 50%, but not down; it was going up in early 2020. You can see that the time between January and March 2020 people got crazy on stockpiling. Man, every month they had 2/3 more this aggregated to nearly over 12,000,000!!! For all three month in average, if we calculated normal seasonal sales we were under 10% in range of our target forecast in sales, but with coronavirus, phew.... And if you remember when coronavirus COVID-19 broke loose, people hoarded toilet paper like Stephan already pointed out, but hell they stockpiled everything that could help against symptoms. After that I calculated several scenarios for, in Germany we would say: rumdümpeln von Infektionszahlen, by which I mean a shilly-shally of infection cases raising a little bit then going down and again the same thing little wave, up and down. The other scenario was a lockdown that was lifted right before Christmas eve so that the retailers should profit from late Christmas business. I linked sales to the amount of infected cases. I relatively naively forecasted infected cases based on a Gaussian distribution for sales and infected cases, from week to week, where the top of the Gaussian distribution were already a negative sales impact, and showed a high infection of roughly a few thousand, as our highest number of infected cases up to there were solely 6,000 in Germany. That resulted in very high negative sales during late October till December. Well, it seems that this modeling was correct in term of lockdown prediction, but as I now leave my company I will never know, how 'low' the sales really were in late 2020. Maybe someday someone will tell me if my amount of negative sales and my big lockdown scenario pointed in the correct direction. I hope this was entertaining.
How can you account for COVID-19 in your models?
I hope I can tell some interesting stories here just as the others: I worked on a project for a pharmaceutical company, which wanted to have their dementia and cold cough products to be modeled, espec
How can you account for COVID-19 in your models? I hope I can tell some interesting stories here just as the others: I worked on a project for a pharmaceutical company, which wanted to have their dementia and cold cough products to be modeled, especially during coronavirus/COVID-19 infection. For the dementia product, we already saw a decreasing trend that were already active before the crisis. In the end we were 10% past the original sales outcome in our sales forecast, but COVID-19 not really influenced the use of dementia. Although these dementia products are normally also taken in case of sudden deafness (caused by stress) we saw no clear sign of COVID-19, or in other words unusual product specifics that may lead to a higher consumption due to stressful times during COVID-19 and homeschooling. Thus, the negative trend in the year before was stronger than anticipated, but that was all. We decided to not incorporate any COVID-19 effects and it seemed right. Due to product specifics, we thought it was not correlated so high with COVID-19 lockdowns. In case of the cold/cough product, you can imagine two scenarios: people get less sick because of lockdowns, and thus even in the main season of influenza, sales would break down people are stockpiling We measured effects of coronavirus with dummies, and we already saw unusual activity in January, but I had not enough data to go on much more. The dummies aggregated to 3.000.000 € in sales. No one could have expected what happened: Hell, after the modeling, the client had a target mismatch of about 50%, but not down; it was going up in early 2020. You can see that the time between January and March 2020 people got crazy on stockpiling. Man, every month they had 2/3 more this aggregated to nearly over 12,000,000!!! For all three month in average, if we calculated normal seasonal sales we were under 10% in range of our target forecast in sales, but with coronavirus, phew.... And if you remember when coronavirus COVID-19 broke loose, people hoarded toilet paper like Stephan already pointed out, but hell they stockpiled everything that could help against symptoms. After that I calculated several scenarios for, in Germany we would say: rumdümpeln von Infektionszahlen, by which I mean a shilly-shally of infection cases raising a little bit then going down and again the same thing little wave, up and down. The other scenario was a lockdown that was lifted right before Christmas eve so that the retailers should profit from late Christmas business. I linked sales to the amount of infected cases. I relatively naively forecasted infected cases based on a Gaussian distribution for sales and infected cases, from week to week, where the top of the Gaussian distribution were already a negative sales impact, and showed a high infection of roughly a few thousand, as our highest number of infected cases up to there were solely 6,000 in Germany. That resulted in very high negative sales during late October till December. Well, it seems that this modeling was correct in term of lockdown prediction, but as I now leave my company I will never know, how 'low' the sales really were in late 2020. Maybe someday someone will tell me if my amount of negative sales and my big lockdown scenario pointed in the correct direction. I hope this was entertaining.
How can you account for COVID-19 in your models? I hope I can tell some interesting stories here just as the others: I worked on a project for a pharmaceutical company, which wanted to have their dementia and cold cough products to be modeled, espec
8,583
How can you account for COVID-19 in your models?
Other answers here give some good advice. However, I just wanted to add that economic models should usually be able to incorporate generic "shocks" that affect one or more of the variables of interest. How you incorporat this really depends on what you are interested in explaining, but often the "shocks" will be treated as exogenous events that occur at random times. (Of course, if your goal is to predict the onset of shocks from related observations, you will need to treat them endogenously.) In the context of a model for sales, it would be usual tfor economic models to incorporate allowance for exogenous "shocks" that can reduce (or increase) the demand for the product at any given price --- i.e., move the "demand curve" up or down. The specifics of how you choose to model this largely depends on whether you want to treat the shock as exogenous or try to explain its onset in terms of other observable things in the model. If you are happy to treat is as exogenous then a simple "random shock" model, where the shock dissipates over time, should give you a starting point.
How can you account for COVID-19 in your models?
Other answers here give some good advice. However, I just wanted to add that economic models should usually be able to incorporate generic "shocks" that affect one or more of the variables of interes
How can you account for COVID-19 in your models? Other answers here give some good advice. However, I just wanted to add that economic models should usually be able to incorporate generic "shocks" that affect one or more of the variables of interest. How you incorporat this really depends on what you are interested in explaining, but often the "shocks" will be treated as exogenous events that occur at random times. (Of course, if your goal is to predict the onset of shocks from related observations, you will need to treat them endogenously.) In the context of a model for sales, it would be usual tfor economic models to incorporate allowance for exogenous "shocks" that can reduce (or increase) the demand for the product at any given price --- i.e., move the "demand curve" up or down. The specifics of how you choose to model this largely depends on whether you want to treat the shock as exogenous or try to explain its onset in terms of other observable things in the model. If you are happy to treat is as exogenous then a simple "random shock" model, where the shock dissipates over time, should give you a starting point.
How can you account for COVID-19 in your models? Other answers here give some good advice. However, I just wanted to add that economic models should usually be able to incorporate generic "shocks" that affect one or more of the variables of interes
8,584
How to perform dimensionality reduction with PCA in R
I believe what you are getting at in your question concerns data truncation using a smaller number of principal components (PC). For such operations, I think the function prcompis more illustrative in that it is easier to visualize the matrix multiplication used in reconstruction. First, give a synthetic dataset, Xt, you perform the PCA (typically you would center samples in order to describe PC's relating to a covariance matrix: #Generate data m=50 n=100 frac.gaps <- 0.5 # the fraction of data with NaNs N.S.ratio <- 0.25 # the Noise to Signal ratio for adding noise to data x <- (seq(m)*2*pi)/m t <- (seq(n)*2*pi)/n #True field Xt <- outer(sin(x), sin(t)) + outer(sin(2.1*x), sin(2.1*t)) + outer(sin(3.1*x), sin(3.1*t)) + outer(tanh(x), cos(t)) + outer(tanh(2*x), cos(2.1*t)) + outer(tanh(4*x), cos(0.1*t)) + outer(tanh(2.4*x), cos(1.1*t)) + tanh(outer(x, t, FUN="+")) + tanh(outer(x, 2*t, FUN="+")) Xt <- t(Xt) #PCA res <- prcomp(Xt, center = TRUE, scale = FALSE) names(res) In the results or prcomp, you can see the PC's (res$x), the eigenvalues (res$sdev) giving information on the magnitude of each PC, and the loadings (res$rotation). res$sdev length(res$sdev) res$rotation dim(res$rotation) res$x dim(res$x) By squaring the eigenvalues, you get the variance explained by each PC: plot(cumsum(res$sdev^2/sum(res$sdev^2))) #cumulative explained variance Finally, you can create a truncated version of your data by using only the leading (important) PCs: pc.use <- 3 # explains 93% of variance trunc <- res$x[,1:pc.use] %*% t(res$rotation[,1:pc.use]) #and add the center (and re-scale) back to data if(all(res$scale != FALSE)){ trunc <- scale(trunc, center = FALSE , scale=1/res$scale) } if(all(res$center != FALSE)){ trunc <- scale(trunc, center = -1 * res$center, scale=FALSE) } dim(trunc); dim(Xt) You can see that the result is a slightly smoother data matrix, with small scale features filtered out: RAN <- range(cbind(Xt, trunc)) BREAKS <- seq(RAN[1], RAN[2],,100) COLS <- rainbow(length(BREAKS)-1) par(mfcol=c(1,2), mar=c(1,1,2,1)) image(Xt, main="Original matrix", xlab="", ylab="", xaxt="n", yaxt="n", breaks=BREAKS, col=COLS) box() image(trunc, main="Truncated matrix (3 PCs)", xlab="", ylab="", xaxt="n", yaxt="n", breaks=BREAKS, col=COLS) box() And here is a very basic approach that you can do outside of the prcomp function: #alternate approach Xt.cen <- scale(Xt, center=TRUE, scale=FALSE) C <- cov(Xt.cen, use="pair") E <- svd(C) A <- Xt.cen %*% E$u #To remove units from principal components (A) #function for the exponent of a matrix "%^%" <- function(S, power) with(eigen(S), vectors %*% (values^power * t(vectors))) Asc <- A %*% (diag(E$d) %^% -0.5) # scaled principal components #Relationship between eigenvalues from both approaches plot(res$sdev^2, E$d) #PCA via a covariance matrix - the eigenvalues now hold variance, not stdev abline(0,1) # same results Now, deciding which PCs to retain is a separate question - one that I was interested in a while back. Hope that helps.
How to perform dimensionality reduction with PCA in R
I believe what you are getting at in your question concerns data truncation using a smaller number of principal components (PC). For such operations, I think the function prcompis more illustrative in
How to perform dimensionality reduction with PCA in R I believe what you are getting at in your question concerns data truncation using a smaller number of principal components (PC). For such operations, I think the function prcompis more illustrative in that it is easier to visualize the matrix multiplication used in reconstruction. First, give a synthetic dataset, Xt, you perform the PCA (typically you would center samples in order to describe PC's relating to a covariance matrix: #Generate data m=50 n=100 frac.gaps <- 0.5 # the fraction of data with NaNs N.S.ratio <- 0.25 # the Noise to Signal ratio for adding noise to data x <- (seq(m)*2*pi)/m t <- (seq(n)*2*pi)/n #True field Xt <- outer(sin(x), sin(t)) + outer(sin(2.1*x), sin(2.1*t)) + outer(sin(3.1*x), sin(3.1*t)) + outer(tanh(x), cos(t)) + outer(tanh(2*x), cos(2.1*t)) + outer(tanh(4*x), cos(0.1*t)) + outer(tanh(2.4*x), cos(1.1*t)) + tanh(outer(x, t, FUN="+")) + tanh(outer(x, 2*t, FUN="+")) Xt <- t(Xt) #PCA res <- prcomp(Xt, center = TRUE, scale = FALSE) names(res) In the results or prcomp, you can see the PC's (res$x), the eigenvalues (res$sdev) giving information on the magnitude of each PC, and the loadings (res$rotation). res$sdev length(res$sdev) res$rotation dim(res$rotation) res$x dim(res$x) By squaring the eigenvalues, you get the variance explained by each PC: plot(cumsum(res$sdev^2/sum(res$sdev^2))) #cumulative explained variance Finally, you can create a truncated version of your data by using only the leading (important) PCs: pc.use <- 3 # explains 93% of variance trunc <- res$x[,1:pc.use] %*% t(res$rotation[,1:pc.use]) #and add the center (and re-scale) back to data if(all(res$scale != FALSE)){ trunc <- scale(trunc, center = FALSE , scale=1/res$scale) } if(all(res$center != FALSE)){ trunc <- scale(trunc, center = -1 * res$center, scale=FALSE) } dim(trunc); dim(Xt) You can see that the result is a slightly smoother data matrix, with small scale features filtered out: RAN <- range(cbind(Xt, trunc)) BREAKS <- seq(RAN[1], RAN[2],,100) COLS <- rainbow(length(BREAKS)-1) par(mfcol=c(1,2), mar=c(1,1,2,1)) image(Xt, main="Original matrix", xlab="", ylab="", xaxt="n", yaxt="n", breaks=BREAKS, col=COLS) box() image(trunc, main="Truncated matrix (3 PCs)", xlab="", ylab="", xaxt="n", yaxt="n", breaks=BREAKS, col=COLS) box() And here is a very basic approach that you can do outside of the prcomp function: #alternate approach Xt.cen <- scale(Xt, center=TRUE, scale=FALSE) C <- cov(Xt.cen, use="pair") E <- svd(C) A <- Xt.cen %*% E$u #To remove units from principal components (A) #function for the exponent of a matrix "%^%" <- function(S, power) with(eigen(S), vectors %*% (values^power * t(vectors))) Asc <- A %*% (diag(E$d) %^% -0.5) # scaled principal components #Relationship between eigenvalues from both approaches plot(res$sdev^2, E$d) #PCA via a covariance matrix - the eigenvalues now hold variance, not stdev abline(0,1) # same results Now, deciding which PCs to retain is a separate question - one that I was interested in a while back. Hope that helps.
How to perform dimensionality reduction with PCA in R I believe what you are getting at in your question concerns data truncation using a smaller number of principal components (PC). For such operations, I think the function prcompis more illustrative in
8,585
How to perform dimensionality reduction with PCA in R
These other answers are very good and detailed, but I'm wondering if you're actually asking a much more basic question: what do you do once you have your PCs? Each PC simply becomes a new variable. Say PC1 accounts for 60 % of the total variation and PC2 accounts for 30 %. As that's 90 % of the total variation accounted for, you could simply take these two new variables (PCs) as a simplified version of your original variables. This means fitting them to models, if that's what you're interested in. When it comes time to interpret your results, you do so in the context of the original variables that are correlated with each PC. Sorry if I've underestimated the scope of the question!
How to perform dimensionality reduction with PCA in R
These other answers are very good and detailed, but I'm wondering if you're actually asking a much more basic question: what do you do once you have your PCs? Each PC simply becomes a new variable. Sa
How to perform dimensionality reduction with PCA in R These other answers are very good and detailed, but I'm wondering if you're actually asking a much more basic question: what do you do once you have your PCs? Each PC simply becomes a new variable. Say PC1 accounts for 60 % of the total variation and PC2 accounts for 30 %. As that's 90 % of the total variation accounted for, you could simply take these two new variables (PCs) as a simplified version of your original variables. This means fitting them to models, if that's what you're interested in. When it comes time to interpret your results, you do so in the context of the original variables that are correlated with each PC. Sorry if I've underestimated the scope of the question!
How to perform dimensionality reduction with PCA in R These other answers are very good and detailed, but I'm wondering if you're actually asking a much more basic question: what do you do once you have your PCs? Each PC simply becomes a new variable. Sa
8,586
How to perform dimensionality reduction with PCA in R
I believe your original question stems from being a bit uncertain about what PCA is doing. Principal Component Analysis allows you to identify the principal mode of variation in your sample. Those modes are emperically calculated as the eigenvectors of your sample's covariance matrix (the "loadings"). Subsequently those vectors serve as the new "coordinate system" of your sample as you project your original sample in the space they define (the "scores"). The proportion of variation associated with the $i$-th eigenvector/ mode of variation/ loading/ principal component equals $\frac{\lambda_i}{\Sigma_{k=1}^{p} \lambda_k}$ where $p$ is your sample's original dimensionality ($p =784$ in your case). [Remember because your covariance matrix is non-negative Definite you'll have no negative eigenvalues $\lambda$.] Now, by definition the eigenvectors are orthogonal to each other. That means that their respective projections are also orthogonal and where originally you had a big possibly correlated sample of variables, now you have a (hopefully significantly) smaller linearly independent sample (the "scores"). Practically with PCA you are using the projections of the PCs (the "scores") as surrogate data for your original sample. You do all your analysis on the scores, and afterwards you reconstruct your original sample back using the PCs to find out out what happened on your original space (that's basically Principal Component Regression). Clearly, if you are able to meaningful interpreter your eigenvectors ("loadings") then you are in an even better position: You can describe what happens to your sample in the mode of variation presented by that loading by doing inference on that loading directly and not care about reconstruction at all. :) In general what do you "after calculating the PCA" depends on the target of your analysis. PCA just gives you a linearly independent sub-sample of your data that is the optimal under an RSS reconstruction criterion. You might use it for classification, or regression, or both, or as I mentioned you might want to recognise meaningful orthogonal modes of variations in your sample. A comment : I think the best naive way to decide the number of components to retain is to base your estimate on some threshold of sample variation you would like to retain in your reduced dimensionality sample rather than just some arbitrary number eg. 3, 100, 200. As user4959 explained you can check that cumulative variation by checking the relevant field of the list under the $loadingsfield in the list object produced by princomp.
How to perform dimensionality reduction with PCA in R
I believe your original question stems from being a bit uncertain about what PCA is doing. Principal Component Analysis allows you to identify the principal mode of variation in your sample. Those mod
How to perform dimensionality reduction with PCA in R I believe your original question stems from being a bit uncertain about what PCA is doing. Principal Component Analysis allows you to identify the principal mode of variation in your sample. Those modes are emperically calculated as the eigenvectors of your sample's covariance matrix (the "loadings"). Subsequently those vectors serve as the new "coordinate system" of your sample as you project your original sample in the space they define (the "scores"). The proportion of variation associated with the $i$-th eigenvector/ mode of variation/ loading/ principal component equals $\frac{\lambda_i}{\Sigma_{k=1}^{p} \lambda_k}$ where $p$ is your sample's original dimensionality ($p =784$ in your case). [Remember because your covariance matrix is non-negative Definite you'll have no negative eigenvalues $\lambda$.] Now, by definition the eigenvectors are orthogonal to each other. That means that their respective projections are also orthogonal and where originally you had a big possibly correlated sample of variables, now you have a (hopefully significantly) smaller linearly independent sample (the "scores"). Practically with PCA you are using the projections of the PCs (the "scores") as surrogate data for your original sample. You do all your analysis on the scores, and afterwards you reconstruct your original sample back using the PCs to find out out what happened on your original space (that's basically Principal Component Regression). Clearly, if you are able to meaningful interpreter your eigenvectors ("loadings") then you are in an even better position: You can describe what happens to your sample in the mode of variation presented by that loading by doing inference on that loading directly and not care about reconstruction at all. :) In general what do you "after calculating the PCA" depends on the target of your analysis. PCA just gives you a linearly independent sub-sample of your data that is the optimal under an RSS reconstruction criterion. You might use it for classification, or regression, or both, or as I mentioned you might want to recognise meaningful orthogonal modes of variations in your sample. A comment : I think the best naive way to decide the number of components to retain is to base your estimate on some threshold of sample variation you would like to retain in your reduced dimensionality sample rather than just some arbitrary number eg. 3, 100, 200. As user4959 explained you can check that cumulative variation by checking the relevant field of the list under the $loadingsfield in the list object produced by princomp.
How to perform dimensionality reduction with PCA in R I believe your original question stems from being a bit uncertain about what PCA is doing. Principal Component Analysis allows you to identify the principal mode of variation in your sample. Those mod
8,587
How to perform dimensionality reduction with PCA in R
After doing the PCA then you may select the first two components and plot.. You can see the variation of the components using a scree plot in R. Also using summary function with loadings=T you can fins the variation of features with the components. You can also look at this http://www.statmethods.net/advstats/factor.html and http://statmath.wu.ac.at/~hornik/QFS1/principal_component-vignette.pdf Try to think what you want. You can interpret lots of things from PCA analysis. Best Abhik
How to perform dimensionality reduction with PCA in R
After doing the PCA then you may select the first two components and plot.. You can see the variation of the components using a scree plot in R. Also using summary function with loadings=T you can fin
How to perform dimensionality reduction with PCA in R After doing the PCA then you may select the first two components and plot.. You can see the variation of the components using a scree plot in R. Also using summary function with loadings=T you can fins the variation of features with the components. You can also look at this http://www.statmethods.net/advstats/factor.html and http://statmath.wu.ac.at/~hornik/QFS1/principal_component-vignette.pdf Try to think what you want. You can interpret lots of things from PCA analysis. Best Abhik
How to perform dimensionality reduction with PCA in R After doing the PCA then you may select the first two components and plot.. You can see the variation of the components using a scree plot in R. Also using summary function with loadings=T you can fin
8,588
About CNN, kernels and scale/rotation invariance
1) The features extracted using CNN are scale and rotation invariant? A feature in itself in a CNN is not scale or rotation invariant. For more details, see: Deep Learning. Ian Goodfellow and Yoshua Bengio and Aaron Courville. 2016: http://egrcc.github.io/docs/dl/deeplearningbook-convnets.pdf ; http://www.deeplearningbook.org/contents/convnets.html: Convolution is not naturally equivariant to some other transformations, such as changes in the scale or rotation of an image. Other mechanisms are necessary for handling these kinds of transformations. It is the max pooling layer that introduces such invariants: 2) The Kernels we use to convolution with our data are already defined in the literature? what kind of these kernels are? is it different for every application? The kernels are learnt during the training phase of the ANN.
About CNN, kernels and scale/rotation invariance
1) The features extracted using CNN are scale and rotation invariant? A feature in itself in a CNN is not scale or rotation invariant. For more details, see: Deep Learning. Ian Goodfellow and Yoshua
About CNN, kernels and scale/rotation invariance 1) The features extracted using CNN are scale and rotation invariant? A feature in itself in a CNN is not scale or rotation invariant. For more details, see: Deep Learning. Ian Goodfellow and Yoshua Bengio and Aaron Courville. 2016: http://egrcc.github.io/docs/dl/deeplearningbook-convnets.pdf ; http://www.deeplearningbook.org/contents/convnets.html: Convolution is not naturally equivariant to some other transformations, such as changes in the scale or rotation of an image. Other mechanisms are necessary for handling these kinds of transformations. It is the max pooling layer that introduces such invariants: 2) The Kernels we use to convolution with our data are already defined in the literature? what kind of these kernels are? is it different for every application? The kernels are learnt during the training phase of the ANN.
About CNN, kernels and scale/rotation invariance 1) The features extracted using CNN are scale and rotation invariant? A feature in itself in a CNN is not scale or rotation invariant. For more details, see: Deep Learning. Ian Goodfellow and Yoshua
8,589
About CNN, kernels and scale/rotation invariance
I think there are a couple of things confusing you, so first things first. Given a signal $x[n]$, and a kernel (also called a filter) $h[n]$, then the convolution of $x[n]$ with $h[n]$ is written as $y[n] = (x \star h)[n]$, and is computed via a sliding dot-product, mathematically given by: $$ y[n] = \sum_{m=-\infty}^{\infty}x[m] \ h[n-m] $$ The above if for one-dimensional signals, but the same can be said for images, which are just two-dimensional signals. In that case, the equation becomes: $$ I_{new}[r,c] = \sum_{u=-\infty}^{\infty}\sum_{v=-\infty}^{\infty} I_{old}[u,v] \ k[r-u, c-v] $$ Pictorially, this is what is happening: At any rate, the thing to keep in mind, is that the kernel, in actually learned during training a Deep Neural Network (DNN). A kernel is just going to be what you convolve your input with. The DNN will learn the kernel, such that it brings out certain facets of the image (or previous image), that are going to be good for lowering the loss of your target objective. This is the first crucial point to understand: Traditionally people have designed kernels, but in Deep Learning, we let the network decide what the best kernel should be. The one thing we do specify however, is the kernel dimensions. (This is called a hyperparameter, for example, 5x5, or 3x3, etc).
About CNN, kernels and scale/rotation invariance
I think there are a couple of things confusing you, so first things first. Given a signal $x[n]$, and a kernel (also called a filter) $h[n]$, then the convolution of $x[n]$ with $h[n]$ is written as
About CNN, kernels and scale/rotation invariance I think there are a couple of things confusing you, so first things first. Given a signal $x[n]$, and a kernel (also called a filter) $h[n]$, then the convolution of $x[n]$ with $h[n]$ is written as $y[n] = (x \star h)[n]$, and is computed via a sliding dot-product, mathematically given by: $$ y[n] = \sum_{m=-\infty}^{\infty}x[m] \ h[n-m] $$ The above if for one-dimensional signals, but the same can be said for images, which are just two-dimensional signals. In that case, the equation becomes: $$ I_{new}[r,c] = \sum_{u=-\infty}^{\infty}\sum_{v=-\infty}^{\infty} I_{old}[u,v] \ k[r-u, c-v] $$ Pictorially, this is what is happening: At any rate, the thing to keep in mind, is that the kernel, in actually learned during training a Deep Neural Network (DNN). A kernel is just going to be what you convolve your input with. The DNN will learn the kernel, such that it brings out certain facets of the image (or previous image), that are going to be good for lowering the loss of your target objective. This is the first crucial point to understand: Traditionally people have designed kernels, but in Deep Learning, we let the network decide what the best kernel should be. The one thing we do specify however, is the kernel dimensions. (This is called a hyperparameter, for example, 5x5, or 3x3, etc).
About CNN, kernels and scale/rotation invariance I think there are a couple of things confusing you, so first things first. Given a signal $x[n]$, and a kernel (also called a filter) $h[n]$, then the convolution of $x[n]$ with $h[n]$ is written as
8,590
About CNN, kernels and scale/rotation invariance
Many authors including Geoffrey Hinton (who proposes Capsule net) try to solve the issue, but qualitatively. We try to address this issue quantitatively. By having all convolution kernels be symmetric (dihedral symmetry of order 8 [Dih4] or 90-degree increment rotation symmetric, et al) in the CNN, we would provide a platform for the input vector and resultant vector on each convolution hidden layer be rotated synchronously with the same symmetric property (i.e., Dih4 or 90-increment rotation symmetric, et al). Additionally, by having the same symmetric property for each filter (i.e., fully connected but weighs sharing with the same symmetric pattern) on the first flatten layer, the resultant value on each node would be quantitatively identical and lead to the CNN output vector the same as well. I called it transformation-identical CNN (or TI-CNN-1). There are other methods that can also construct transformation-identical CNN using symmetric input or operations inside the CNN (TI-CNN-2). Based on the TI-CNN, a geared rotation-identical CNNs (GRI-CNN) can be constructed by multiple TI-CNNs with the input vector rotated by a small step angle. Furthermore, a composed quantitatively identical CNN can also be constructed by combining multiple GRI-CNNs with various transformed input vectors. "Transformationally Identical and Invariant Convolutional Neural Networks through Symmetric Element Operators” https://arxiv.org/abs/1806.03636 (June 2018) “Transformationally Identical and Invariant Convolutional Neural Networks by Combining Symmetric Operations or Input Vectors” https://arxiv.org/abs/1807.11156 (July 2018) "Geared Rotationally Identical and Invariant Convolutional Neural Network Systems" https://arxiv.org/abs/1808.01280 (August 2018)
About CNN, kernels and scale/rotation invariance
Many authors including Geoffrey Hinton (who proposes Capsule net) try to solve the issue, but qualitatively. We try to address this issue quantitatively. By having all convolution kernels be symmetric
About CNN, kernels and scale/rotation invariance Many authors including Geoffrey Hinton (who proposes Capsule net) try to solve the issue, but qualitatively. We try to address this issue quantitatively. By having all convolution kernels be symmetric (dihedral symmetry of order 8 [Dih4] or 90-degree increment rotation symmetric, et al) in the CNN, we would provide a platform for the input vector and resultant vector on each convolution hidden layer be rotated synchronously with the same symmetric property (i.e., Dih4 or 90-increment rotation symmetric, et al). Additionally, by having the same symmetric property for each filter (i.e., fully connected but weighs sharing with the same symmetric pattern) on the first flatten layer, the resultant value on each node would be quantitatively identical and lead to the CNN output vector the same as well. I called it transformation-identical CNN (or TI-CNN-1). There are other methods that can also construct transformation-identical CNN using symmetric input or operations inside the CNN (TI-CNN-2). Based on the TI-CNN, a geared rotation-identical CNNs (GRI-CNN) can be constructed by multiple TI-CNNs with the input vector rotated by a small step angle. Furthermore, a composed quantitatively identical CNN can also be constructed by combining multiple GRI-CNNs with various transformed input vectors. "Transformationally Identical and Invariant Convolutional Neural Networks through Symmetric Element Operators” https://arxiv.org/abs/1806.03636 (June 2018) “Transformationally Identical and Invariant Convolutional Neural Networks by Combining Symmetric Operations or Input Vectors” https://arxiv.org/abs/1807.11156 (July 2018) "Geared Rotationally Identical and Invariant Convolutional Neural Network Systems" https://arxiv.org/abs/1808.01280 (August 2018)
About CNN, kernels and scale/rotation invariance Many authors including Geoffrey Hinton (who proposes Capsule net) try to solve the issue, but qualitatively. We try to address this issue quantitatively. By having all convolution kernels be symmetric
8,591
About CNN, kernels and scale/rotation invariance
I think max pooling can reserve translational and rotational invariances only for translations and rotations smaller than the stride size. If greater, no invariance
About CNN, kernels and scale/rotation invariance
I think max pooling can reserve translational and rotational invariances only for translations and rotations smaller than the stride size. If greater, no invariance
About CNN, kernels and scale/rotation invariance I think max pooling can reserve translational and rotational invariances only for translations and rotations smaller than the stride size. If greater, no invariance
About CNN, kernels and scale/rotation invariance I think max pooling can reserve translational and rotational invariances only for translations and rotations smaller than the stride size. If greater, no invariance
8,592
How to calculate the prediction interval for an OLS multiple regression?
Take a regression model with $N$ observations and $k$ regressors: $$\mathbf{y=X\beta+u} \newcommand{\Var}{\rm Var}$$ Given a vector $\mathbf{x_0}$, the predicted value for that observation would be $$E[y \vert \mathbf{x_0}]=\hat y_0 = \mathbf{x_0} \hat \beta.$$ A consistent estimator of the variance of this prediction is $$\hat V_p=s^2 \cdot \mathbf{x_0} \cdot(\mathbf{X'X})^{-1}\mathbf{x'_0},$$ where $$s^2=\frac{\Sigma_{i=1}^{N} \hat u_i^2}{N-k}.$$ The forecast error for a particular $y_0$ is $$\hat e=y_0-\hat y_0=\mathbf{x_0}\beta+u_0-\hat y_0.$$ The zero covariance between $u_0$ and $\hat \beta$ implies that $$\Var[\hat e]=\Var[\hat y_0]+\Var[u_0],$$ and a consistent estimator of that is $$\hat V_f=s^2 \cdot \mathbf{x_0} \cdot(\mathbf{X'X})^{-1}\mathbf{x'_0} + s^2.$$ The $1-\alpha$ $\rm confidence$ interval will be: $$y_0 \pm t_{1-\alpha/2}\cdot \sqrt{\hat V_{p}}.$$ The $1-\alpha$ $\rm prediction$ interval will be wider: $$y_0 \pm t_{1-\alpha/2}\cdot \sqrt{\hat V_{f}}.$$
How to calculate the prediction interval for an OLS multiple regression?
Take a regression model with $N$ observations and $k$ regressors: $$\mathbf{y=X\beta+u} \newcommand{\Var}{\rm Var}$$ Given a vector $\mathbf{x_0}$, the predicted value for that observation would be $$
How to calculate the prediction interval for an OLS multiple regression? Take a regression model with $N$ observations and $k$ regressors: $$\mathbf{y=X\beta+u} \newcommand{\Var}{\rm Var}$$ Given a vector $\mathbf{x_0}$, the predicted value for that observation would be $$E[y \vert \mathbf{x_0}]=\hat y_0 = \mathbf{x_0} \hat \beta.$$ A consistent estimator of the variance of this prediction is $$\hat V_p=s^2 \cdot \mathbf{x_0} \cdot(\mathbf{X'X})^{-1}\mathbf{x'_0},$$ where $$s^2=\frac{\Sigma_{i=1}^{N} \hat u_i^2}{N-k}.$$ The forecast error for a particular $y_0$ is $$\hat e=y_0-\hat y_0=\mathbf{x_0}\beta+u_0-\hat y_0.$$ The zero covariance between $u_0$ and $\hat \beta$ implies that $$\Var[\hat e]=\Var[\hat y_0]+\Var[u_0],$$ and a consistent estimator of that is $$\hat V_f=s^2 \cdot \mathbf{x_0} \cdot(\mathbf{X'X})^{-1}\mathbf{x'_0} + s^2.$$ The $1-\alpha$ $\rm confidence$ interval will be: $$y_0 \pm t_{1-\alpha/2}\cdot \sqrt{\hat V_{p}}.$$ The $1-\alpha$ $\rm prediction$ interval will be wider: $$y_0 \pm t_{1-\alpha/2}\cdot \sqrt{\hat V_{f}}.$$
How to calculate the prediction interval for an OLS multiple regression? Take a regression model with $N$ observations and $k$ regressors: $$\mathbf{y=X\beta+u} \newcommand{\Var}{\rm Var}$$ Given a vector $\mathbf{x_0}$, the predicted value for that observation would be $$
8,593
Can overfitting and underfitting occur simultaneously?
Your reasoning makes sense to me. Here is an extremely simple example. Suppose that $X$ consists of only two columns $x_1$ and $x_2$, and the true DGP is $$ y=\beta_1x_1+\beta_2x_2+\epsilon $$ with nonzero $\beta_1$ and $\beta_2$, and noise $\epsilon$. Next, assume that $Z$ contains columns $x_1, x_1^2, x_1^3, \dots$ - but not $x_2$. If we now fit $g(Z)$ (using OLS, or any other approach), we cannot capture the effect of $x_2$, simply because $x_2$ is unknown to $g(Z)$, so we will have underfitting. But conversely, including spurious powers of $x_1$ (or any other spurious predictors) means that we can overfit, and usually will do so, unless we regularize in some way.
Can overfitting and underfitting occur simultaneously?
Your reasoning makes sense to me. Here is an extremely simple example. Suppose that $X$ consists of only two columns $x_1$ and $x_2$, and the true DGP is $$ y=\beta_1x_1+\beta_2x_2+\epsilon $$ with no
Can overfitting and underfitting occur simultaneously? Your reasoning makes sense to me. Here is an extremely simple example. Suppose that $X$ consists of only two columns $x_1$ and $x_2$, and the true DGP is $$ y=\beta_1x_1+\beta_2x_2+\epsilon $$ with nonzero $\beta_1$ and $\beta_2$, and noise $\epsilon$. Next, assume that $Z$ contains columns $x_1, x_1^2, x_1^3, \dots$ - but not $x_2$. If we now fit $g(Z)$ (using OLS, or any other approach), we cannot capture the effect of $x_2$, simply because $x_2$ is unknown to $g(Z)$, so we will have underfitting. But conversely, including spurious powers of $x_1$ (or any other spurious predictors) means that we can overfit, and usually will do so, unless we regularize in some way.
Can overfitting and underfitting occur simultaneously? Your reasoning makes sense to me. Here is an extremely simple example. Suppose that $X$ consists of only two columns $x_1$ and $x_2$, and the true DGP is $$ y=\beta_1x_1+\beta_2x_2+\epsilon $$ with no
8,594
Can overfitting and underfitting occur simultaneously?
I like the idea of having a bad fit of the deterministic part and also overly fitting the noise as being both overfitting and underfitting, but that is not how I view those terminologies. I consider the issue of overfitting versus underfitting as related to the trade-off between bias and variance. Sure you can have situations that are both with high bias and high variance, but that is not the point of expressing the situation overfitting (relatively high variance) versus underfitting (relatively high bias). These concepts are relative to some ideal point. In practice this ideal point may be still biased and also with variance. We are never (completely) without bias and/or variance. (Actually, I would say that often the most efficient answer, with lowest error, is often always with some bias, and therefore both underfitting and overfitting) So with overfitting versus underfitting, I always think of these graphs like Bias versus variance. Like in this question: Bias / variance tradeoff math Or training error and test error. Like in these questions (a b c d) and summarized in this question: How to know if model is overfitting or underfitting? So to me this overfitting versus underfitting is something that is relative, relative to some parameter and we can plot it as a function of that parameter. But sure, this plot, where one side (left/right) is overfitting and the other side (right/left) is underfitting, can also be considered to be shifted up and down relating to the question of the total error (bias + variance) being both inceased or decreased.
Can overfitting and underfitting occur simultaneously?
I like the idea of having a bad fit of the deterministic part and also overly fitting the noise as being both overfitting and underfitting, but that is not how I view those terminologies. I consider t
Can overfitting and underfitting occur simultaneously? I like the idea of having a bad fit of the deterministic part and also overly fitting the noise as being both overfitting and underfitting, but that is not how I view those terminologies. I consider the issue of overfitting versus underfitting as related to the trade-off between bias and variance. Sure you can have situations that are both with high bias and high variance, but that is not the point of expressing the situation overfitting (relatively high variance) versus underfitting (relatively high bias). These concepts are relative to some ideal point. In practice this ideal point may be still biased and also with variance. We are never (completely) without bias and/or variance. (Actually, I would say that often the most efficient answer, with lowest error, is often always with some bias, and therefore both underfitting and overfitting) So with overfitting versus underfitting, I always think of these graphs like Bias versus variance. Like in this question: Bias / variance tradeoff math Or training error and test error. Like in these questions (a b c d) and summarized in this question: How to know if model is overfitting or underfitting? So to me this overfitting versus underfitting is something that is relative, relative to some parameter and we can plot it as a function of that parameter. But sure, this plot, where one side (left/right) is overfitting and the other side (right/left) is underfitting, can also be considered to be shifted up and down relating to the question of the total error (bias + variance) being both inceased or decreased.
Can overfitting and underfitting occur simultaneously? I like the idea of having a bad fit of the deterministic part and also overly fitting the noise as being both overfitting and underfitting, but that is not how I view those terminologies. I consider t
8,595
Can degrees of freedom be a non-integer number?
Degrees of freedom are non-integer in a number of contexts. Indeed in a few circumstances you can establish that the degrees of freedom to fit the data for some particular models must be between some value $k$ and $k+1$. We usually think of degrees of freedom as the number of free parameters, but there are situations where the parameters are not completely free and they can then be difficult to count. This can happen when smoothing / regularizing, for example. The cases of locally weighted regression / kernel methods an smoothing splines are examples of such a situation -- a total number of free parameters is not something you can readily count by adding up predictors, so a more general idea of degrees of freedom is needed. In Generalized Additive Models on which gam is partly based, Hastie and Tibshirani (1990) [1] (and indeed in numerous other references) for some models where we can write $\hat y = Ay$, the degrees of freedom is sometimes taken to be $\operatorname{tr}(A)$ (they also discuss $\operatorname{tr}(AA^T)$ or $\operatorname{tr}(2A-AA^T)$). The first is consistent with the more usual approach where both work (e.g. in regression, where in normal situations $\operatorname{tr}(A)$ will be the column dimension of $X$), but when $A$ is symmetric and idempotent, all three of those formulas are the same. [I don't have this reference handy to check enough of the details; an alternative by the same authors (plus Friedman) that's easy to get hold of is Elements of Statistical Learning [2]; see for example equation 5.16, which defines the effective degrees of freedom of a smoothing spline as $\operatorname{tr}(A)$ (in my notation)] More generally still, Ye (1998) [3] defined generalized degrees of freedom as $\sum_i \frac{\partial \hat y_i}{\partial y_i}$, which is the sum of the sensitivities of fitted values to their corresponding observations. In turn, this is consistent with $\operatorname{tr}(A)$ where that definition works. To use Ye's definition you need only be able to compute $\hat y$ and to perturb the data by some small amount (in order to compute $\frac{\partial \hat y_i}{\partial y_i}$ numerically). This makes it very broadly applicable. For models like those fitted by gam, those various measures are generally not integer. (I highly recommend reading these references' discussion on this issue, though the story can get rather more complicated in some situations. See, for example [4]) [1] Hastie, T. and Tibshirani, R. (1990), Generalized Additive Models London: Chapman and Hall. [2] Hastie, T., Tibshirani, R. and Friedman, J. (2009), The Elements of Statistical Learning: Data Mining, Inference, and Prediction, 2ndEd Springer-Verlag. https://statweb.stanford.edu/~tibs/ElemStatLearn/ [3] Ye, J. (1998), "On Measuring and Correcting the Effects of Data Mining and Model Selection" Journal of the American Statistical Association, Vol. 93, No. 441, pp 120-131 [4] Janson, L., Fithian, W., and Hastie, T. (2013), "Effective Degrees of Freedom: A Flawed Metaphor" https://arxiv.org/abs/1312.7851
Can degrees of freedom be a non-integer number?
Degrees of freedom are non-integer in a number of contexts. Indeed in a few circumstances you can establish that the degrees of freedom to fit the data for some particular models must be between some
Can degrees of freedom be a non-integer number? Degrees of freedom are non-integer in a number of contexts. Indeed in a few circumstances you can establish that the degrees of freedom to fit the data for some particular models must be between some value $k$ and $k+1$. We usually think of degrees of freedom as the number of free parameters, but there are situations where the parameters are not completely free and they can then be difficult to count. This can happen when smoothing / regularizing, for example. The cases of locally weighted regression / kernel methods an smoothing splines are examples of such a situation -- a total number of free parameters is not something you can readily count by adding up predictors, so a more general idea of degrees of freedom is needed. In Generalized Additive Models on which gam is partly based, Hastie and Tibshirani (1990) [1] (and indeed in numerous other references) for some models where we can write $\hat y = Ay$, the degrees of freedom is sometimes taken to be $\operatorname{tr}(A)$ (they also discuss $\operatorname{tr}(AA^T)$ or $\operatorname{tr}(2A-AA^T)$). The first is consistent with the more usual approach where both work (e.g. in regression, where in normal situations $\operatorname{tr}(A)$ will be the column dimension of $X$), but when $A$ is symmetric and idempotent, all three of those formulas are the same. [I don't have this reference handy to check enough of the details; an alternative by the same authors (plus Friedman) that's easy to get hold of is Elements of Statistical Learning [2]; see for example equation 5.16, which defines the effective degrees of freedom of a smoothing spline as $\operatorname{tr}(A)$ (in my notation)] More generally still, Ye (1998) [3] defined generalized degrees of freedom as $\sum_i \frac{\partial \hat y_i}{\partial y_i}$, which is the sum of the sensitivities of fitted values to their corresponding observations. In turn, this is consistent with $\operatorname{tr}(A)$ where that definition works. To use Ye's definition you need only be able to compute $\hat y$ and to perturb the data by some small amount (in order to compute $\frac{\partial \hat y_i}{\partial y_i}$ numerically). This makes it very broadly applicable. For models like those fitted by gam, those various measures are generally not integer. (I highly recommend reading these references' discussion on this issue, though the story can get rather more complicated in some situations. See, for example [4]) [1] Hastie, T. and Tibshirani, R. (1990), Generalized Additive Models London: Chapman and Hall. [2] Hastie, T., Tibshirani, R. and Friedman, J. (2009), The Elements of Statistical Learning: Data Mining, Inference, and Prediction, 2ndEd Springer-Verlag. https://statweb.stanford.edu/~tibs/ElemStatLearn/ [3] Ye, J. (1998), "On Measuring and Correcting the Effects of Data Mining and Model Selection" Journal of the American Statistical Association, Vol. 93, No. 441, pp 120-131 [4] Janson, L., Fithian, W., and Hastie, T. (2013), "Effective Degrees of Freedom: A Flawed Metaphor" https://arxiv.org/abs/1312.7851
Can degrees of freedom be a non-integer number? Degrees of freedom are non-integer in a number of contexts. Indeed in a few circumstances you can establish that the degrees of freedom to fit the data for some particular models must be between some
8,596
Should I make decisions based on micro-averaged or macro-averaged evaluation measures?
If you think all the labels are more or less equally sized (have roughly the same number of instances), use any. If you think there are labels with more instances than others and if you want to bias your metric towards the most populated ones, use micromedia. If you think there are labels with more instances than others and if you want to bias your metric toward the least populated ones (or at least you don't want to bias toward the most populated ones), use macromedia. If the micromedia result is significantly lower than the macromedia one, it means that you have some gross misclassification in the most populated labels, whereas your smaller labels are probably correctly classified. If the macromedia result is significantly lower than the micromedia one, it means your smaller labels are poorly classified, whereas your larger ones are probably correctly classified. If you're not sure what to do, carry on with the comparisons on both micro- and macroaverage :) This is a good paper on the subject.
Should I make decisions based on micro-averaged or macro-averaged evaluation measures?
If you think all the labels are more or less equally sized (have roughly the same number of instances), use any. If you think there are labels with more instances than others and if you want to bias y
Should I make decisions based on micro-averaged or macro-averaged evaluation measures? If you think all the labels are more or less equally sized (have roughly the same number of instances), use any. If you think there are labels with more instances than others and if you want to bias your metric towards the most populated ones, use micromedia. If you think there are labels with more instances than others and if you want to bias your metric toward the least populated ones (or at least you don't want to bias toward the most populated ones), use macromedia. If the micromedia result is significantly lower than the macromedia one, it means that you have some gross misclassification in the most populated labels, whereas your smaller labels are probably correctly classified. If the macromedia result is significantly lower than the micromedia one, it means your smaller labels are poorly classified, whereas your larger ones are probably correctly classified. If you're not sure what to do, carry on with the comparisons on both micro- and macroaverage :) This is a good paper on the subject.
Should I make decisions based on micro-averaged or macro-averaged evaluation measures? If you think all the labels are more or less equally sized (have roughly the same number of instances), use any. If you think there are labels with more instances than others and if you want to bias y
8,597
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distribution?
This question has likely been considered already on this forum. When you state that you "have the posterior distribution", what exactly do you mean? "Having" an available$-$in the sense I can compute it everywhere$-$function of $\theta$ that I know to be proportional to the posterior density, namely$$\pi(\theta|x) \propto \pi(\theta) \times f(x|\theta)$$as for instance with the completely artificial target$$\pi(\theta|x)\propto\exp\{-\|\theta-x\|^2-\|\theta+x\|^4-\|\theta-2x\|^6-100\|\theta\|^5\},\ \ x,\theta\in\mathbb{R}^{18}\tag{1},$$does not tell me what is the posterior expectation of a function of $\theta$, e.g., $\mathbb{E}[\mathfrak{h}(\theta)|x]$, posterior mean that operates as a Bayesian estimator under standard losses; the optimal decision under an arbitrary utility function, decision that minimizes the expected posterior loss; a 90% or 95% range of uncertainty on the parameter(s), a sub-vector of the parameter(s), or a function of the parameter(s), aka HPD region$$\{h=\mathfrak{h}(\theta);\ \pi^\mathfrak{h}(h)\ge \underline{h}\}$$ the most likely model to choose between setting some components of the parameter(s) to specific values versus keeping them unknown (and random). For instance, the fact that the rhs of (1) is known does not tell how to solve $$\int_{\mathcal H} \exp\{-\|\theta-x\|^2-\|\theta+x\|^4-\|\theta-2x\|^6-100\|\theta\|^5\}\,\text d\theta=\qquad\\0.95\int_{\mathbb R^{18}} \exp\{-\|\theta-x\|^2-\|\theta+x\|^4-\|\theta-2x\|^6-100\|\theta\|^5\}\,\text d\theta$$ and optimize over all such $\mathcal H$'s. These items are only examples of many usages of the posterior distribution. In all cases but the simplest ones, one cannot provide answers by solely staring at the posterior distribution density as an available function and one does need to proceed through numerical resolutions like Monte Carlo and Markov chain Monte Carlo methods.
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distr
This question has likely been considered already on this forum. When you state that you "have the posterior distribution", what exactly do you mean? "Having" an available$-$in the sense I can compute
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distribution? This question has likely been considered already on this forum. When you state that you "have the posterior distribution", what exactly do you mean? "Having" an available$-$in the sense I can compute it everywhere$-$function of $\theta$ that I know to be proportional to the posterior density, namely$$\pi(\theta|x) \propto \pi(\theta) \times f(x|\theta)$$as for instance with the completely artificial target$$\pi(\theta|x)\propto\exp\{-\|\theta-x\|^2-\|\theta+x\|^4-\|\theta-2x\|^6-100\|\theta\|^5\},\ \ x,\theta\in\mathbb{R}^{18}\tag{1},$$does not tell me what is the posterior expectation of a function of $\theta$, e.g., $\mathbb{E}[\mathfrak{h}(\theta)|x]$, posterior mean that operates as a Bayesian estimator under standard losses; the optimal decision under an arbitrary utility function, decision that minimizes the expected posterior loss; a 90% or 95% range of uncertainty on the parameter(s), a sub-vector of the parameter(s), or a function of the parameter(s), aka HPD region$$\{h=\mathfrak{h}(\theta);\ \pi^\mathfrak{h}(h)\ge \underline{h}\}$$ the most likely model to choose between setting some components of the parameter(s) to specific values versus keeping them unknown (and random). For instance, the fact that the rhs of (1) is known does not tell how to solve $$\int_{\mathcal H} \exp\{-\|\theta-x\|^2-\|\theta+x\|^4-\|\theta-2x\|^6-100\|\theta\|^5\}\,\text d\theta=\qquad\\0.95\int_{\mathbb R^{18}} \exp\{-\|\theta-x\|^2-\|\theta+x\|^4-\|\theta-2x\|^6-100\|\theta\|^5\}\,\text d\theta$$ and optimize over all such $\mathcal H$'s. These items are only examples of many usages of the posterior distribution. In all cases but the simplest ones, one cannot provide answers by solely staring at the posterior distribution density as an available function and one does need to proceed through numerical resolutions like Monte Carlo and Markov chain Monte Carlo methods.
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distr This question has likely been considered already on this forum. When you state that you "have the posterior distribution", what exactly do you mean? "Having" an available$-$in the sense I can compute
8,598
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distribution?
Yes you might have an analytical posterior distribution. But the core of Bayesian analysis is to marginalize over the posterior distribution of parameters so that you get a better prediction result both in terms of accuracy and generalization capability. Basically, you want to obtain a predictive distribution which has the following form. $p(x|D)=\int p(x|w) p(w|D)dw$ where $p(w|D)$ is the posterior distribution which you might have an analytical form for. But in many cases, $p(w|D)$ has a complex form that does not belong to any known distribution family nor in conjugacy with $p(x|w)$. This makes the above integrand impossible to calculate analytically. Then you have to resort to sampling approximation of the integrand which is the entire purpose of the advanced sampling technique such as markov chain monte carlo
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distr
Yes you might have an analytical posterior distribution. But the core of Bayesian analysis is to marginalize over the posterior distribution of parameters so that you get a better prediction result bo
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distribution? Yes you might have an analytical posterior distribution. But the core of Bayesian analysis is to marginalize over the posterior distribution of parameters so that you get a better prediction result both in terms of accuracy and generalization capability. Basically, you want to obtain a predictive distribution which has the following form. $p(x|D)=\int p(x|w) p(w|D)dw$ where $p(w|D)$ is the posterior distribution which you might have an analytical form for. But in many cases, $p(w|D)$ has a complex form that does not belong to any known distribution family nor in conjugacy with $p(x|w)$. This makes the above integrand impossible to calculate analytically. Then you have to resort to sampling approximation of the integrand which is the entire purpose of the advanced sampling technique such as markov chain monte carlo
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distr Yes you might have an analytical posterior distribution. But the core of Bayesian analysis is to marginalize over the posterior distribution of parameters so that you get a better prediction result bo
8,599
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distribution?
A short answer: Sampling is not only used to estimate a distribution function*, it is also used to perform computations with a density function and MCMC is just one of many ways of sampling. Often such computations are a way of Monte Carlo integration. Computing a posterior average, a 95% highest density interval, marginal distributions*, etcetera, if the density function is a complex function then such values can be difficult to derive analytically and manual integration might require a lot of computations to perform. A sampling method is an alternative to approximate the desired quantity. *In the case of nuisance parameters, then Bayes rule doesn't give the posterior of the parameter, but of a joint distribution with the nuisance parameter. So the statement "if we already KNOW the posterior distribution?" must be nuanced and the marginal posterior distribution is not even known. In these cases the MCMC can also be used to compute the density function (which is unknown).
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distr
A short answer: Sampling is not only used to estimate a distribution function*, it is also used to perform computations with a density function and MCMC is just one of many ways of sampling. Often suc
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distribution? A short answer: Sampling is not only used to estimate a distribution function*, it is also used to perform computations with a density function and MCMC is just one of many ways of sampling. Often such computations are a way of Monte Carlo integration. Computing a posterior average, a 95% highest density interval, marginal distributions*, etcetera, if the density function is a complex function then such values can be difficult to derive analytically and manual integration might require a lot of computations to perform. A sampling method is an alternative to approximate the desired quantity. *In the case of nuisance parameters, then Bayes rule doesn't give the posterior of the parameter, but of a joint distribution with the nuisance parameter. So the statement "if we already KNOW the posterior distribution?" must be nuanced and the marginal posterior distribution is not even known. In these cases the MCMC can also be used to compute the density function (which is unknown).
Why is it necessary to sample from the posterior distribution if we already KNOW the posterior distr A short answer: Sampling is not only used to estimate a distribution function*, it is also used to perform computations with a density function and MCMC is just one of many ways of sampling. Often suc
8,600
XGBoost vs Python Sklearn gradient boosted trees
You are correct, XGBoost ('eXtreme Gradient Boosting') and sklearn's GradientBoost are fundamentally the same as they are both gradient boosting implementations. However, there are very significant differences under the hood in a practical sense. XGBoost is a lot faster (see http://machinelearningmastery.com/gentle-introduction-xgboost-applied-machine-learning/) than sklearn's. XGBoost is quite memory-efficient and can be parallelized (I think sklearn's cannot do so by default, I don't know exactly about sklearn's memory-efficiency but I am pretty confident it is below XGBoost's). Having used both, XGBoost's speed is quite impressive and its performance is superior to sklearn's GradientBoosting.
XGBoost vs Python Sklearn gradient boosted trees
You are correct, XGBoost ('eXtreme Gradient Boosting') and sklearn's GradientBoost are fundamentally the same as they are both gradient boosting implementations. However, there are very significant di
XGBoost vs Python Sklearn gradient boosted trees You are correct, XGBoost ('eXtreme Gradient Boosting') and sklearn's GradientBoost are fundamentally the same as they are both gradient boosting implementations. However, there are very significant differences under the hood in a practical sense. XGBoost is a lot faster (see http://machinelearningmastery.com/gentle-introduction-xgboost-applied-machine-learning/) than sklearn's. XGBoost is quite memory-efficient and can be parallelized (I think sklearn's cannot do so by default, I don't know exactly about sklearn's memory-efficiency but I am pretty confident it is below XGBoost's). Having used both, XGBoost's speed is quite impressive and its performance is superior to sklearn's GradientBoosting.
XGBoost vs Python Sklearn gradient boosted trees You are correct, XGBoost ('eXtreme Gradient Boosting') and sklearn's GradientBoost are fundamentally the same as they are both gradient boosting implementations. However, there are very significant di