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
|
|---|---|---|---|---|---|---|
6,401
|
When to use fixed effects vs using cluster SEs?
|
These answers are fine, but the most recent and best answer is provided by Abadie et al. (2019) "When Should You Adjust Standard Errors for Clustering?" With fixed effects, a main reason to cluster is you have heterogeneity in treatment effects across the clusters. There are other reasons, for example if the clusters (e.g. firms, countries) are a subset of the clusters in the population (about which you are inferring). Clustering is a design issue is the main message of the paper. Don't do it blindly.
|
When to use fixed effects vs using cluster SEs?
|
These answers are fine, but the most recent and best answer is provided by Abadie et al. (2019) "When Should You Adjust Standard Errors for Clustering?" With fixed effects, a main reason to cluster i
|
When to use fixed effects vs using cluster SEs?
These answers are fine, but the most recent and best answer is provided by Abadie et al. (2019) "When Should You Adjust Standard Errors for Clustering?" With fixed effects, a main reason to cluster is you have heterogeneity in treatment effects across the clusters. There are other reasons, for example if the clusters (e.g. firms, countries) are a subset of the clusters in the population (about which you are inferring). Clustering is a design issue is the main message of the paper. Don't do it blindly.
|
When to use fixed effects vs using cluster SEs?
These answers are fine, but the most recent and best answer is provided by Abadie et al. (2019) "When Should You Adjust Standard Errors for Clustering?" With fixed effects, a main reason to cluster i
|
6,402
|
When to use fixed effects vs using cluster SEs?
|
@Kishore Gawande referenced the NBER working paper by Alberto Abadie, Susan Athey, Guido W. Imbens, and Jeffrey Wooldridge but I think it would be useful to repeat the key conclusions here as (per my reading) they do not necessarily align with every aspect of the the most accepted answers here.
First, clustered standard errors are a design rather than a model issue. Just because clustering standard errors makes a difference (results in larger standard errors than robust standard errors) is no reason that you should do it. Here's the top line: you should use clustered standard errors if you're working with a cluster sample or with an experiment where assignments have been clustered.
There's one exception. If there's no heterogeneity in the treatment effects and assignments have not been clustered, you don't have to use clustered standard errors. If you're using fixed effects, this requirement is looser. If there's no heterogeneity in the treatment effects, you don't have to use clustered standard errors. However, as Abadie et al. note, it's very unlikely that in practice there will be no heterogeneity in treatment effects, so this difference doesn't make much difference in practice. Hence, whether you're using fixed effects or not, if you're working with a cluster sample or clustered assignments, use clustered standard errors.
To quote Abadie et al. directly:
Without fixed effects, one should cluster if either (i) both $P_{C_n}$ < 1
(clustering in the sampling) and there is heterogeneity in the
treatment effects, or (ii) σ2 > 0 (clustering in the assignment). With
fixed effects, one should cluster if either (i) both PCn < 1
(clustering in the sampling) and there is heterogeneity in the
treatment effects, or (ii) σ2 > 0 (clustering in the assignment) and
there is heterogeneity in the treatment effects. In other words,
heterogeneity in the treatment effects is now a requirement for
clustering adjustments to be necessary, and beyond that, either
clustering in sampling or assignment makes the adjustments important
In his answer, @Alex's says "Clustered standard errors are for accounting for situations where observations WITHIN each group are not i.i.d. (independently and identically distributed)" and provides the following example:
Alternatively, if you have many observations per group for
non-experimental data, but each within-group observation can be
considered as an i.i.d. draw from their larger group (e.g., you have
observations from many schools, but each group is a randomly drawn
subset of students from their school), you would want to include fixed
effects but would not need clustered SEs.
This is misleading. If the sample is clustered and there is heterogeneity in the treatment effects (and there usually is), you need clustered standard errors.
To put this in the terms of survey sampling, if the design effect is greater than 1, i.e. observations from a group are not independent because they are more similar to each other than to observations from other groups, then you have to account for this. Ensuring that you sample from each group (e.g. school) is random, doesn't in any way bale you out here. Your effective sample size is less than your actual sample size. This is what leads to standard errors that are too narrow unless they are adjusted (via clustered standard errors) to account for this.
For all the fine print, include simulations and mathematical proofs, see Abadie et al. When Should You Adjust Standard Errors for Clustering.
|
When to use fixed effects vs using cluster SEs?
|
@Kishore Gawande referenced the NBER working paper by Alberto Abadie, Susan Athey, Guido W. Imbens, and Jeffrey Wooldridge but I think it would be useful to repeat the key conclusions here as (per my
|
When to use fixed effects vs using cluster SEs?
@Kishore Gawande referenced the NBER working paper by Alberto Abadie, Susan Athey, Guido W. Imbens, and Jeffrey Wooldridge but I think it would be useful to repeat the key conclusions here as (per my reading) they do not necessarily align with every aspect of the the most accepted answers here.
First, clustered standard errors are a design rather than a model issue. Just because clustering standard errors makes a difference (results in larger standard errors than robust standard errors) is no reason that you should do it. Here's the top line: you should use clustered standard errors if you're working with a cluster sample or with an experiment where assignments have been clustered.
There's one exception. If there's no heterogeneity in the treatment effects and assignments have not been clustered, you don't have to use clustered standard errors. If you're using fixed effects, this requirement is looser. If there's no heterogeneity in the treatment effects, you don't have to use clustered standard errors. However, as Abadie et al. note, it's very unlikely that in practice there will be no heterogeneity in treatment effects, so this difference doesn't make much difference in practice. Hence, whether you're using fixed effects or not, if you're working with a cluster sample or clustered assignments, use clustered standard errors.
To quote Abadie et al. directly:
Without fixed effects, one should cluster if either (i) both $P_{C_n}$ < 1
(clustering in the sampling) and there is heterogeneity in the
treatment effects, or (ii) σ2 > 0 (clustering in the assignment). With
fixed effects, one should cluster if either (i) both PCn < 1
(clustering in the sampling) and there is heterogeneity in the
treatment effects, or (ii) σ2 > 0 (clustering in the assignment) and
there is heterogeneity in the treatment effects. In other words,
heterogeneity in the treatment effects is now a requirement for
clustering adjustments to be necessary, and beyond that, either
clustering in sampling or assignment makes the adjustments important
In his answer, @Alex's says "Clustered standard errors are for accounting for situations where observations WITHIN each group are not i.i.d. (independently and identically distributed)" and provides the following example:
Alternatively, if you have many observations per group for
non-experimental data, but each within-group observation can be
considered as an i.i.d. draw from their larger group (e.g., you have
observations from many schools, but each group is a randomly drawn
subset of students from their school), you would want to include fixed
effects but would not need clustered SEs.
This is misleading. If the sample is clustered and there is heterogeneity in the treatment effects (and there usually is), you need clustered standard errors.
To put this in the terms of survey sampling, if the design effect is greater than 1, i.e. observations from a group are not independent because they are more similar to each other than to observations from other groups, then you have to account for this. Ensuring that you sample from each group (e.g. school) is random, doesn't in any way bale you out here. Your effective sample size is less than your actual sample size. This is what leads to standard errors that are too narrow unless they are adjusted (via clustered standard errors) to account for this.
For all the fine print, include simulations and mathematical proofs, see Abadie et al. When Should You Adjust Standard Errors for Clustering.
|
When to use fixed effects vs using cluster SEs?
@Kishore Gawande referenced the NBER working paper by Alberto Abadie, Susan Athey, Guido W. Imbens, and Jeffrey Wooldridge but I think it would be useful to repeat the key conclusions here as (per my
|
6,403
|
How to test hypothesis of no group differences?
|
I think you are asking about testing for equivalence. Essentially you need to decide how large a difference is acceptable for you to still conclude that the two groups are effectively equivalent. That decision defines the 95% (or other) confidence interval limits, and sample size calculations are made on this basis.
There is a whole book on the topic.
A very common clinical "equivalent" of equivalence tests is a non-inferiority test/ trial. In this case you "prefer" one group over the other (an established treatment) and design your test to show that the new treatment is not inferior to the established treatment at some level of statistical evidence.
I think I need to credit Harvey Motulsky for the GraphPad.com site (under "Library").
|
How to test hypothesis of no group differences?
|
I think you are asking about testing for equivalence. Essentially you need to decide how large a difference is acceptable for you to still conclude that the two groups are effectively equivalent. That
|
How to test hypothesis of no group differences?
I think you are asking about testing for equivalence. Essentially you need to decide how large a difference is acceptable for you to still conclude that the two groups are effectively equivalent. That decision defines the 95% (or other) confidence interval limits, and sample size calculations are made on this basis.
There is a whole book on the topic.
A very common clinical "equivalent" of equivalence tests is a non-inferiority test/ trial. In this case you "prefer" one group over the other (an established treatment) and design your test to show that the new treatment is not inferior to the established treatment at some level of statistical evidence.
I think I need to credit Harvey Motulsky for the GraphPad.com site (under "Library").
|
How to test hypothesis of no group differences?
I think you are asking about testing for equivalence. Essentially you need to decide how large a difference is acceptable for you to still conclude that the two groups are effectively equivalent. That
|
6,404
|
How to test hypothesis of no group differences?
|
Besides the already mentioned possibility of some kind of equivalence test, of which most of them, to the best of my knowledge, are mostly routed in the good old frequentist tradition, there is the possibility of conducting tests which really provide a quantification of evidence in favor of a null-hyptheses, namely bayesian tests.
An implementation of a bayesian t-test can be found here:
Wetzels, R., Raaijmakers, J. G. W., Jakab, E., & Wagenmakers, E.-J. (2009). How to quantify support for and against the null hypothesis: A flexible WinBUGS implementation of a default Bayesian t-test. Psychonomic Bulletin & Review, 16, 752-760.
There is also a tutorial on how to do all this in R:
http://www.ruudwetzels.com/index.php?src=SDtest
An alternative (perhaps more modern approach) of a Bayesian t-test is provided (with code) in this paper by Kruschke:
Kruschke, J. K. (2013). Bayesian estimation supersedes the t test. Journal of Experimental Psychology: General, 142(2), 573–603. doi:10.1037/a0029146
All props for this answer (before the addition of Kruschke) should go to my colleague David Kellen. I stole his answer from this question.
|
How to test hypothesis of no group differences?
|
Besides the already mentioned possibility of some kind of equivalence test, of which most of them, to the best of my knowledge, are mostly routed in the good old frequentist tradition, there is the po
|
How to test hypothesis of no group differences?
Besides the already mentioned possibility of some kind of equivalence test, of which most of them, to the best of my knowledge, are mostly routed in the good old frequentist tradition, there is the possibility of conducting tests which really provide a quantification of evidence in favor of a null-hyptheses, namely bayesian tests.
An implementation of a bayesian t-test can be found here:
Wetzels, R., Raaijmakers, J. G. W., Jakab, E., & Wagenmakers, E.-J. (2009). How to quantify support for and against the null hypothesis: A flexible WinBUGS implementation of a default Bayesian t-test. Psychonomic Bulletin & Review, 16, 752-760.
There is also a tutorial on how to do all this in R:
http://www.ruudwetzels.com/index.php?src=SDtest
An alternative (perhaps more modern approach) of a Bayesian t-test is provided (with code) in this paper by Kruschke:
Kruschke, J. K. (2013). Bayesian estimation supersedes the t test. Journal of Experimental Psychology: General, 142(2), 573–603. doi:10.1037/a0029146
All props for this answer (before the addition of Kruschke) should go to my colleague David Kellen. I stole his answer from this question.
|
How to test hypothesis of no group differences?
Besides the already mentioned possibility of some kind of equivalence test, of which most of them, to the best of my knowledge, are mostly routed in the good old frequentist tradition, there is the po
|
6,405
|
How to test hypothesis of no group differences?
|
Following Thylacoleo's answer, I did a little research.
The equivalence package in R has the tost() function.
See Robinson and Frose (2004) "Model validation using equivalence tests" for more info.
|
How to test hypothesis of no group differences?
|
Following Thylacoleo's answer, I did a little research.
The equivalence package in R has the tost() function.
See Robinson and Frose (2004) "Model validation using equivalence tests" for more info.
|
How to test hypothesis of no group differences?
Following Thylacoleo's answer, I did a little research.
The equivalence package in R has the tost() function.
See Robinson and Frose (2004) "Model validation using equivalence tests" for more info.
|
How to test hypothesis of no group differences?
Following Thylacoleo's answer, I did a little research.
The equivalence package in R has the tost() function.
See Robinson and Frose (2004) "Model validation using equivalence tests" for more info.
|
6,406
|
How to test hypothesis of no group differences?
|
There are a few papers I know of that could be helpful to you:
Tryon, W. W. (2001). Evaluating statistical difference, equivalence, and indeterminacy using inferential confidence intervals: An integrated alternative method of conducting null hypothesis statistical tests. Psychological Methods, 6, 371-386. (FREE PDF)
And a correction:
Tryon, W. W., & Lewis, C. (2008). An Inferential Confidence Interval Method of Establishing Statistical Equivalence That Corrects Tryon’s (2001) Reduction Factor. Psychological Methods, 13, 272-278. (FREE PDF)
Furthermore:
Seaman, M. A. & Serlin, R. C. (1998). Equivalence confidence intervals for two-group comparisons of means. Psychological Methods, Vol 3(4), 403-411.
|
How to test hypothesis of no group differences?
|
There are a few papers I know of that could be helpful to you:
Tryon, W. W. (2001). Evaluating statistical difference, equivalence, and indeterminacy using inferential confidence intervals: An integra
|
How to test hypothesis of no group differences?
There are a few papers I know of that could be helpful to you:
Tryon, W. W. (2001). Evaluating statistical difference, equivalence, and indeterminacy using inferential confidence intervals: An integrated alternative method of conducting null hypothesis statistical tests. Psychological Methods, 6, 371-386. (FREE PDF)
And a correction:
Tryon, W. W., & Lewis, C. (2008). An Inferential Confidence Interval Method of Establishing Statistical Equivalence That Corrects Tryon’s (2001) Reduction Factor. Psychological Methods, 13, 272-278. (FREE PDF)
Furthermore:
Seaman, M. A. & Serlin, R. C. (1998). Equivalence confidence intervals for two-group comparisons of means. Psychological Methods, Vol 3(4), 403-411.
|
How to test hypothesis of no group differences?
There are a few papers I know of that could be helpful to you:
Tryon, W. W. (2001). Evaluating statistical difference, equivalence, and indeterminacy using inferential confidence intervals: An integra
|
6,407
|
How to test hypothesis of no group differences?
|
I have recently thought about an alternative way of "equivalence testing" based on a distance between the two distributions rather than between their means.
There are some methods providing confidence intervals for the overlap of two Gaussian distributions:
The overlap $O(P_1,P_2)$ of (between?) two distributions $P_1$ and $P_2$ has a nice probabilistic interpretation: $$1-O(P_1,P_2)= TV(P_1,P_2)$$
where $TV(P_1,P_2) = \sup_A \big|P_1(A) - P_2(A) \big|$ is the total variation distance between $P_1$ and $P_2$.
That means that, for example, if $O(P_1,P_2)>0.9$ then the probabilities given by $P_1$ and $P_2$ of any event do not differ more than $0.1$. Roughly speaking, the two distributions make the same predictions up to $10\%$.
Thus, instead of using an acceptance criterion based on a critical value for the difference between the means $\mu_1$ and $\mu_2$, as in classical equivalence testing, we could base it on a critical value for the difference between the probabilities of the predictions given by the two distributions.
I think there's an advantage in terms of "objectiveness" of the criterion. The critical value of $|\mu_1 - \mu_2|$ should be given by an expert of the real problem: this should be a value beyond which the difference has a practical importance. But sometimes nobody has a solid knowledge about the real problem and there's no expert able to provide a critical value. Adopting a conventional critical value about $TV(P_1,P_2)$ could be a way to a criterion not depending on the physical problem under consideration.
In the Gaussian case with same variances, the overlap is one-to-one related to the standardized mean difference $\frac{|\mu_1-\mu_2|}{\sigma}$.
|
How to test hypothesis of no group differences?
|
I have recently thought about an alternative way of "equivalence testing" based on a distance between the two distributions rather than between their means.
There are some methods providing confidenc
|
How to test hypothesis of no group differences?
I have recently thought about an alternative way of "equivalence testing" based on a distance between the two distributions rather than between their means.
There are some methods providing confidence intervals for the overlap of two Gaussian distributions:
The overlap $O(P_1,P_2)$ of (between?) two distributions $P_1$ and $P_2$ has a nice probabilistic interpretation: $$1-O(P_1,P_2)= TV(P_1,P_2)$$
where $TV(P_1,P_2) = \sup_A \big|P_1(A) - P_2(A) \big|$ is the total variation distance between $P_1$ and $P_2$.
That means that, for example, if $O(P_1,P_2)>0.9$ then the probabilities given by $P_1$ and $P_2$ of any event do not differ more than $0.1$. Roughly speaking, the two distributions make the same predictions up to $10\%$.
Thus, instead of using an acceptance criterion based on a critical value for the difference between the means $\mu_1$ and $\mu_2$, as in classical equivalence testing, we could base it on a critical value for the difference between the probabilities of the predictions given by the two distributions.
I think there's an advantage in terms of "objectiveness" of the criterion. The critical value of $|\mu_1 - \mu_2|$ should be given by an expert of the real problem: this should be a value beyond which the difference has a practical importance. But sometimes nobody has a solid knowledge about the real problem and there's no expert able to provide a critical value. Adopting a conventional critical value about $TV(P_1,P_2)$ could be a way to a criterion not depending on the physical problem under consideration.
In the Gaussian case with same variances, the overlap is one-to-one related to the standardized mean difference $\frac{|\mu_1-\mu_2|}{\sigma}$.
|
How to test hypothesis of no group differences?
I have recently thought about an alternative way of "equivalence testing" based on a distance between the two distributions rather than between their means.
There are some methods providing confidenc
|
6,408
|
How to test hypothesis of no group differences?
|
In the medical sciences, it is preferable to use a confidence interval approach as opposed to two one-sided tests (tost). I also recommend graphing the point estimates, CIs, and a priori-determined equivalence margins to make things very clear.
Your question would likely be addressed by such an approach.
The CONSORT guidelines for non-inferiority/equivalence studies are quite useful in this regard.
See Piaggio G, Elbourne DR, Altman DG, Pocock SJ, Evans SJ, and CONSORT Group. Reporting of noninferiority and equivalence randomized trials: an extension of the CONSORT statement. JAMA. 2006, Mar 8;295(10):1152-60. (Link to full text.)
|
How to test hypothesis of no group differences?
|
In the medical sciences, it is preferable to use a confidence interval approach as opposed to two one-sided tests (tost). I also recommend graphing the point estimates, CIs, and a priori-determined eq
|
How to test hypothesis of no group differences?
In the medical sciences, it is preferable to use a confidence interval approach as opposed to two one-sided tests (tost). I also recommend graphing the point estimates, CIs, and a priori-determined equivalence margins to make things very clear.
Your question would likely be addressed by such an approach.
The CONSORT guidelines for non-inferiority/equivalence studies are quite useful in this regard.
See Piaggio G, Elbourne DR, Altman DG, Pocock SJ, Evans SJ, and CONSORT Group. Reporting of noninferiority and equivalence randomized trials: an extension of the CONSORT statement. JAMA. 2006, Mar 8;295(10):1152-60. (Link to full text.)
|
How to test hypothesis of no group differences?
In the medical sciences, it is preferable to use a confidence interval approach as opposed to two one-sided tests (tost). I also recommend graphing the point estimates, CIs, and a priori-determined eq
|
6,409
|
How to test hypothesis of no group differences?
|
Yes. This is equivalence testing. Basically you reverse the null and alternative hypothesis and base the sample size on the power to show that the difference of the means is within the window of equivalence. Blackwelder called it "Proving the null hypothesis." This is commonly done in pharmaceutical clinical trials where equivalence of a generic drug to the marketed drug is tested or an approved drug is compared to a new formulation (often called bioequivalence). The one sided version is called non-inferiority. Some times a drug can be approved by just showing that the new drug is not inferior to the marketed competitor. Shao and Pigeot have developed a consistent bootstrap approach to bioequivalence using crossover designs.
|
How to test hypothesis of no group differences?
|
Yes. This is equivalence testing. Basically you reverse the null and alternative hypothesis and base the sample size on the power to show that the difference of the means is within the window of equ
|
How to test hypothesis of no group differences?
Yes. This is equivalence testing. Basically you reverse the null and alternative hypothesis and base the sample size on the power to show that the difference of the means is within the window of equivalence. Blackwelder called it "Proving the null hypothesis." This is commonly done in pharmaceutical clinical trials where equivalence of a generic drug to the marketed drug is tested or an approved drug is compared to a new formulation (often called bioequivalence). The one sided version is called non-inferiority. Some times a drug can be approved by just showing that the new drug is not inferior to the marketed competitor. Shao and Pigeot have developed a consistent bootstrap approach to bioequivalence using crossover designs.
|
How to test hypothesis of no group differences?
Yes. This is equivalence testing. Basically you reverse the null and alternative hypothesis and base the sample size on the power to show that the difference of the means is within the window of equ
|
6,410
|
How to test hypothesis of no group differences?
|
Bootstrap differences (e.g. the difference between the means) between the 2 sample groups and check for statistical significance. A more detailed description of this approach, albeit in a different context, can be found here http://www.automated-trading-system.com/a-different-application-of-the-bootstrap/
|
How to test hypothesis of no group differences?
|
Bootstrap differences (e.g. the difference between the means) between the 2 sample groups and check for statistical significance. A more detailed description of this approach, albeit in a different co
|
How to test hypothesis of no group differences?
Bootstrap differences (e.g. the difference between the means) between the 2 sample groups and check for statistical significance. A more detailed description of this approach, albeit in a different context, can be found here http://www.automated-trading-system.com/a-different-application-of-the-bootstrap/
|
How to test hypothesis of no group differences?
Bootstrap differences (e.g. the difference between the means) between the 2 sample groups and check for statistical significance. A more detailed description of this approach, albeit in a different co
|
6,411
|
What test can I use to compare slopes from two or more regression models?
|
To answer these questions with R code, use the following:
1. How can I test the difference between slopes?
Answer: Examine the ANOVA p-value from the interaction of Petal.Width by Species, then compare the slopes using lsmeans::lstrends, as follows.
library(lsmeans)
m.interaction <- lm(Sepal.Length ~ Petal.Width*Species, data = iris)
anova(m.interaction)
Analysis of Variance Table
Response: Sepal.Length
Df Sum Sq Mean Sq F value Pr(>F)
Petal.Width 1 68.353 68.353 298.0784 <2e-16 ***
Species 2 0.035 0.017 0.0754 0.9274
Petal.Width:Species 2 0.759 0.380 1.6552 0.1947
Residuals 144 33.021 0.229
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# Obtain slopes
m.interaction$coefficients
m.lst <- lstrends(m.interaction, "Species", var="Petal.Width")
Species Petal.Width.trend SE df lower.CL upper.CL
setosa 0.9301727 0.6491360 144 -0.3528933 2.213239
versicolor 1.4263647 0.3459350 144 0.7425981 2.110131
virginica 0.6508306 0.2490791 144 0.1585071 1.143154
# Compare slopes
pairs(m.lst)
contrast estimate SE df t.ratio p.value
setosa - versicolor -0.4961919 0.7355601 144 -0.675 0.7786
setosa - virginica 0.2793421 0.6952826 144 0.402 0.9149
versicolor - virginica 0.7755341 0.4262762 144 1.819 0.1669
2. How can I test the difference between residual variances?
If I understand the question, you can compare Pearson correlations with a Fisher transform, also called a "Fisher's r-to-z", as follows.
library(psych)
library(data.table)
iris <- as.data.table(iris)
# Calculate Pearson's R
m.correlations <- iris[, cor(Sepal.Length, Petal.Width), by = Species]
m.correlations
# Compare R values with Fisher's R to Z
paired.r(m.correlations[Species=="setosa", V1], m.correlations[Species=="versicolor", V1],
n = iris[Species %in% c("setosa", "versicolor"), .N])
paired.r(m.correlations[Species=="setosa", V1], m.correlations[Species=="virginica", V1],
n = iris[Species %in% c("setosa", "virginica"), .N])
paired.r(m.correlations[Species=="virginica", V1], m.correlations[Species=="versicolor", V1],
n = iris[Species %in% c("virginica", "versicolor"), .N])
3. What is a simple, effective way to present these comparisons?
"We used linear regression to compare the relationship of Sepal Length to Petal Width for each Species. We did not find a significant interaction in the relationships of Sepal Length to Petal Width for I. Setosa (B = 0.9), I. Versicolor (B = 1.4), nor I. Virginica (B = 0.6); F (2, 144) = 1.6, p = 0.19. A Fisher's r-to-z comparison indicated that the Pearson correlation for I. Setosa (r = 0.28) was significantly lower (p = 0.02) than I. Versicolor (r = 0.55). Similarly, the correlation for I. Virginica (r = 0.28) was significantly weaker (p = 0.02) than the one observed for I. Versicolor."
Finally, always visualize your results!
plotly_interaction <- function(data, x, y, category, colors = col2rgb(viridis(nlevels(as.factor(data[[category]])))), ...) {
# Create Plotly scatter plot of x vs y, with separate lines for each level of the categorical variable.
# In other words, create an interaction scatter plot.
# The "colors" must be supplied in a RGB triplet, as produced by col2rgb().
require(plotly)
require(viridis)
require(broom)
groups <- unique(data[[category]])
p <- plot_ly(...)
for (i in 1:length(groups)) {
groupData = data[which(data[[category]]==groups[[i]]), ]
p <- add_lines(p, data = groupData,
y = fitted(lm(data = groupData, groupData[[y]] ~ groupData[[x]])),
x = groupData[[x]],
line = list(color = paste('rgb', '(', paste(colors[, i], collapse = ", "), ')')),
name = groups[[i]],
showlegend = FALSE)
p <- add_ribbons(p, data = augment(lm(data = groupData, groupData[[y]] ~ groupData[[x]])),
y = groupData[[y]],
x = groupData[[x]],
ymin = ~.fitted - 1.96 * .se.fit,
ymax = ~.fitted + 1.96 * .se.fit,
line = list(color = paste('rgba','(', paste(colors[, i], collapse = ", "), ', 0.05)')),
fillcolor = paste('rgba', '(', paste(colors[, i], collapse = ", "), ', 0.1)'),
showlegend = FALSE)
p <- add_markers(p, data = groupData,
x = groupData[[x]],
y = groupData[[y]],
symbol = groupData[[category]],
marker = list(color=paste('rgb','(', paste(colors[, i], collapse = ", "))))
}
p <- layout(p, xaxis = list(title = x), yaxis = list(title = y))
return(p)
}
plotly_interaction(iris, "Sepal.Length", "Petal.Width", "Species")
|
What test can I use to compare slopes from two or more regression models?
|
To answer these questions with R code, use the following:
1. How can I test the difference between slopes?
Answer: Examine the ANOVA p-value from the interaction of Petal.Width by Species, then comp
|
What test can I use to compare slopes from two or more regression models?
To answer these questions with R code, use the following:
1. How can I test the difference between slopes?
Answer: Examine the ANOVA p-value from the interaction of Petal.Width by Species, then compare the slopes using lsmeans::lstrends, as follows.
library(lsmeans)
m.interaction <- lm(Sepal.Length ~ Petal.Width*Species, data = iris)
anova(m.interaction)
Analysis of Variance Table
Response: Sepal.Length
Df Sum Sq Mean Sq F value Pr(>F)
Petal.Width 1 68.353 68.353 298.0784 <2e-16 ***
Species 2 0.035 0.017 0.0754 0.9274
Petal.Width:Species 2 0.759 0.380 1.6552 0.1947
Residuals 144 33.021 0.229
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
# Obtain slopes
m.interaction$coefficients
m.lst <- lstrends(m.interaction, "Species", var="Petal.Width")
Species Petal.Width.trend SE df lower.CL upper.CL
setosa 0.9301727 0.6491360 144 -0.3528933 2.213239
versicolor 1.4263647 0.3459350 144 0.7425981 2.110131
virginica 0.6508306 0.2490791 144 0.1585071 1.143154
# Compare slopes
pairs(m.lst)
contrast estimate SE df t.ratio p.value
setosa - versicolor -0.4961919 0.7355601 144 -0.675 0.7786
setosa - virginica 0.2793421 0.6952826 144 0.402 0.9149
versicolor - virginica 0.7755341 0.4262762 144 1.819 0.1669
2. How can I test the difference between residual variances?
If I understand the question, you can compare Pearson correlations with a Fisher transform, also called a "Fisher's r-to-z", as follows.
library(psych)
library(data.table)
iris <- as.data.table(iris)
# Calculate Pearson's R
m.correlations <- iris[, cor(Sepal.Length, Petal.Width), by = Species]
m.correlations
# Compare R values with Fisher's R to Z
paired.r(m.correlations[Species=="setosa", V1], m.correlations[Species=="versicolor", V1],
n = iris[Species %in% c("setosa", "versicolor"), .N])
paired.r(m.correlations[Species=="setosa", V1], m.correlations[Species=="virginica", V1],
n = iris[Species %in% c("setosa", "virginica"), .N])
paired.r(m.correlations[Species=="virginica", V1], m.correlations[Species=="versicolor", V1],
n = iris[Species %in% c("virginica", "versicolor"), .N])
3. What is a simple, effective way to present these comparisons?
"We used linear regression to compare the relationship of Sepal Length to Petal Width for each Species. We did not find a significant interaction in the relationships of Sepal Length to Petal Width for I. Setosa (B = 0.9), I. Versicolor (B = 1.4), nor I. Virginica (B = 0.6); F (2, 144) = 1.6, p = 0.19. A Fisher's r-to-z comparison indicated that the Pearson correlation for I. Setosa (r = 0.28) was significantly lower (p = 0.02) than I. Versicolor (r = 0.55). Similarly, the correlation for I. Virginica (r = 0.28) was significantly weaker (p = 0.02) than the one observed for I. Versicolor."
Finally, always visualize your results!
plotly_interaction <- function(data, x, y, category, colors = col2rgb(viridis(nlevels(as.factor(data[[category]])))), ...) {
# Create Plotly scatter plot of x vs y, with separate lines for each level of the categorical variable.
# In other words, create an interaction scatter plot.
# The "colors" must be supplied in a RGB triplet, as produced by col2rgb().
require(plotly)
require(viridis)
require(broom)
groups <- unique(data[[category]])
p <- plot_ly(...)
for (i in 1:length(groups)) {
groupData = data[which(data[[category]]==groups[[i]]), ]
p <- add_lines(p, data = groupData,
y = fitted(lm(data = groupData, groupData[[y]] ~ groupData[[x]])),
x = groupData[[x]],
line = list(color = paste('rgb', '(', paste(colors[, i], collapse = ", "), ')')),
name = groups[[i]],
showlegend = FALSE)
p <- add_ribbons(p, data = augment(lm(data = groupData, groupData[[y]] ~ groupData[[x]])),
y = groupData[[y]],
x = groupData[[x]],
ymin = ~.fitted - 1.96 * .se.fit,
ymax = ~.fitted + 1.96 * .se.fit,
line = list(color = paste('rgba','(', paste(colors[, i], collapse = ", "), ', 0.05)')),
fillcolor = paste('rgba', '(', paste(colors[, i], collapse = ", "), ', 0.1)'),
showlegend = FALSE)
p <- add_markers(p, data = groupData,
x = groupData[[x]],
y = groupData[[y]],
symbol = groupData[[category]],
marker = list(color=paste('rgb','(', paste(colors[, i], collapse = ", "))))
}
p <- layout(p, xaxis = list(title = x), yaxis = list(title = y))
return(p)
}
plotly_interaction(iris, "Sepal.Length", "Petal.Width", "Species")
|
What test can I use to compare slopes from two or more regression models?
To answer these questions with R code, use the following:
1. How can I test the difference between slopes?
Answer: Examine the ANOVA p-value from the interaction of Petal.Width by Species, then comp
|
6,412
|
What test can I use to compare slopes from two or more regression models?
|
How can I test the difference between slopes?
Include a dummy for species, let it interact with $P_i$, and see if this dummy is significant. Let $L_i$ be the sepal length and $P_i$ be the pedal width and $S_1, S_2, S_3$ be the dummy variables for the three species. The compare the model
$$ E(L_i) = \beta_0 + \beta_1 P_i $$
with the model that allows the effect of $P_i$ to be different for each species:
$$ E(L_i) = \alpha_0 + \alpha_1 S_2 + \alpha_2 S_3 + \alpha_4 P_i + \alpha_5 P_iS_2 + \alpha_6 P_i S_3 $$
The GLS estimators are MLEs and the first model is a submodel on the second, so you can use the likelihood ratio test here. The likelihoods can be extracted using the logLik function and the degrees of freedom for the test will be $4$ since you've deleted $4$ parameters to arrive at the submodel.
What is a simple, effective way to present the comparison?
I think the most appealing way would be to plot the regression lines for each species all on the same axes, maybe with error bars based on the standard errors. This would make the
difference (or non-difference) between the species and their relationship to $P_i$ very apparent.
Edit: I noticed another question has been added to the body. So, I'm adding an answer to that:
How can I test the difference between residual variances?
For this, you'll need to stratify the data set and fit separate models since, the interaction-based model I suggested will constraint the residual variance to be the same in every group. If you fit separate models, this constraint goes away. In that case, you can still use the likelihood ratio test (the likelihood for the larger model is now calculated by summing the likelihoods from the three separate models). The "null" model depends on what you want to compare it with
if you only want to test the variance, while leaving the main effects in, then the "null" model should be the model with the interactions I've written above. The degrees of freedom for the test are then $2$.
If you want to test the variance jointly with the coefficients, then the null model should be the first model I've written above. The degrees of freedom for the test is then $6$.
|
What test can I use to compare slopes from two or more regression models?
|
How can I test the difference between slopes?
Include a dummy for species, let it interact with $P_i$, and see if this dummy is significant. Let $L_i$ be the sepal length and $P_i$ be the pedal width
|
What test can I use to compare slopes from two or more regression models?
How can I test the difference between slopes?
Include a dummy for species, let it interact with $P_i$, and see if this dummy is significant. Let $L_i$ be the sepal length and $P_i$ be the pedal width and $S_1, S_2, S_3$ be the dummy variables for the three species. The compare the model
$$ E(L_i) = \beta_0 + \beta_1 P_i $$
with the model that allows the effect of $P_i$ to be different for each species:
$$ E(L_i) = \alpha_0 + \alpha_1 S_2 + \alpha_2 S_3 + \alpha_4 P_i + \alpha_5 P_iS_2 + \alpha_6 P_i S_3 $$
The GLS estimators are MLEs and the first model is a submodel on the second, so you can use the likelihood ratio test here. The likelihoods can be extracted using the logLik function and the degrees of freedom for the test will be $4$ since you've deleted $4$ parameters to arrive at the submodel.
What is a simple, effective way to present the comparison?
I think the most appealing way would be to plot the regression lines for each species all on the same axes, maybe with error bars based on the standard errors. This would make the
difference (or non-difference) between the species and their relationship to $P_i$ very apparent.
Edit: I noticed another question has been added to the body. So, I'm adding an answer to that:
How can I test the difference between residual variances?
For this, you'll need to stratify the data set and fit separate models since, the interaction-based model I suggested will constraint the residual variance to be the same in every group. If you fit separate models, this constraint goes away. In that case, you can still use the likelihood ratio test (the likelihood for the larger model is now calculated by summing the likelihoods from the three separate models). The "null" model depends on what you want to compare it with
if you only want to test the variance, while leaving the main effects in, then the "null" model should be the model with the interactions I've written above. The degrees of freedom for the test are then $2$.
If you want to test the variance jointly with the coefficients, then the null model should be the first model I've written above. The degrees of freedom for the test is then $6$.
|
What test can I use to compare slopes from two or more regression models?
How can I test the difference between slopes?
Include a dummy for species, let it interact with $P_i$, and see if this dummy is significant. Let $L_i$ be the sepal length and $P_i$ be the pedal width
|
6,413
|
What test can I use to compare slopes from two or more regression models?
|
I agree with the previous suggestion. You should fit a multiple regression model with a dummy variable for each data set. This will allow you to test whether the intercepts differ. If you also want to know if the slopes differ, then you need to also include interactions between the dummies and the variable in question. There is no problem with the fact that the data are independent. Note that if they are both independent and (for example) different species, then you would not be able to tell whether the difference you find is due to the differing species or the differing data sets, as they are perfectly confounded. However, there is no test / get-out-of-jail-free card that will get you around that problem without gathering a new sample and running your study again.
|
What test can I use to compare slopes from two or more regression models?
|
I agree with the previous suggestion. You should fit a multiple regression model with a dummy variable for each data set. This will allow you to test whether the intercepts differ. If you also want
|
What test can I use to compare slopes from two or more regression models?
I agree with the previous suggestion. You should fit a multiple regression model with a dummy variable for each data set. This will allow you to test whether the intercepts differ. If you also want to know if the slopes differ, then you need to also include interactions between the dummies and the variable in question. There is no problem with the fact that the data are independent. Note that if they are both independent and (for example) different species, then you would not be able to tell whether the difference you find is due to the differing species or the differing data sets, as they are perfectly confounded. However, there is no test / get-out-of-jail-free card that will get you around that problem without gathering a new sample and running your study again.
|
What test can I use to compare slopes from two or more regression models?
I agree with the previous suggestion. You should fit a multiple regression model with a dummy variable for each data set. This will allow you to test whether the intercepts differ. If you also want
|
6,414
|
Yolo Loss function explanation
|
Explanation of the different terms :
The 3 $\lambda$ constants are just constants to take into account more one aspect of the loss function. In the article $\lambda_{coord}$ is the highest in order to have the more importance in the first term
The prediction of YOLO is a $S*S*(B*5+C)$ vector : $B$ bbox predictions for each grid cells and $C$ class prediction for each grid cell (where $C$ is the number of classes). The 5 bbox outputs of the box j of cell i are coordinates of tte center of the bbox $x_{ij}$ $y_{ij}$ , height $h_{ij}$, width $w_{ij}$ and a confidence index $C_{ij}$
I imagine that the values with a hat are the real one read from the label and the one without hat are the predicted ones. So what is the real value from the label for the confidence score for each bbox $\hat{C}_{ij}$ ? It is the intersection over union of the predicted bounding box with the one from the label.
$\mathbb{1}_{i}^{obj}$ is $1$ when there is an object in cell $i$ and $0$ elsewhere
$\mathbb{1}_{ij}^{obj}$ "denotes that the $j$th bounding box predictor in cell $i$ is responsible for that prediction". In other words, it is equal to $1$ if there is an object in cell $i$ and confidence of the $j$th predictors of this cell is the highest among all the predictors of this cell. $\mathbb{1}_{ij}^{noobj}$ is almost the same except it values 1 when there are NO objects in cell $i$
Note that I used two indexes $i$ and $j$ for each bbox predictions, this is not the case in the article because there is always a factor $\mathbb{1}_{ij}^{obj}$ or $\mathbb{1}_{ij}^{noobj}$ so there is no ambigous interpretation : the $j$ chosen is the one corresponding to the highest confidence score in that cell.
More general explanation of each term of the sum :
this term penalize bad localization of center of cells
this term penalize the bounding box with inacurate height and width. The square root is present so that erors in small bounding boxes are more penalizing than errors in big bounding boxes.
this term tries to make the confidence score equal to the IOU between the object and the prediction when there is one object
Tries to make confidence score close to $0$ when there are no object in the cell
This is a simple classification loss (not explained in the article)
|
Yolo Loss function explanation
|
Explanation of the different terms :
The 3 $\lambda$ constants are just constants to take into account more one aspect of the loss function. In the article $\lambda_{coord}$ is the highest in order
|
Yolo Loss function explanation
Explanation of the different terms :
The 3 $\lambda$ constants are just constants to take into account more one aspect of the loss function. In the article $\lambda_{coord}$ is the highest in order to have the more importance in the first term
The prediction of YOLO is a $S*S*(B*5+C)$ vector : $B$ bbox predictions for each grid cells and $C$ class prediction for each grid cell (where $C$ is the number of classes). The 5 bbox outputs of the box j of cell i are coordinates of tte center of the bbox $x_{ij}$ $y_{ij}$ , height $h_{ij}$, width $w_{ij}$ and a confidence index $C_{ij}$
I imagine that the values with a hat are the real one read from the label and the one without hat are the predicted ones. So what is the real value from the label for the confidence score for each bbox $\hat{C}_{ij}$ ? It is the intersection over union of the predicted bounding box with the one from the label.
$\mathbb{1}_{i}^{obj}$ is $1$ when there is an object in cell $i$ and $0$ elsewhere
$\mathbb{1}_{ij}^{obj}$ "denotes that the $j$th bounding box predictor in cell $i$ is responsible for that prediction". In other words, it is equal to $1$ if there is an object in cell $i$ and confidence of the $j$th predictors of this cell is the highest among all the predictors of this cell. $\mathbb{1}_{ij}^{noobj}$ is almost the same except it values 1 when there are NO objects in cell $i$
Note that I used two indexes $i$ and $j$ for each bbox predictions, this is not the case in the article because there is always a factor $\mathbb{1}_{ij}^{obj}$ or $\mathbb{1}_{ij}^{noobj}$ so there is no ambigous interpretation : the $j$ chosen is the one corresponding to the highest confidence score in that cell.
More general explanation of each term of the sum :
this term penalize bad localization of center of cells
this term penalize the bounding box with inacurate height and width. The square root is present so that erors in small bounding boxes are more penalizing than errors in big bounding boxes.
this term tries to make the confidence score equal to the IOU between the object and the prediction when there is one object
Tries to make confidence score close to $0$ when there are no object in the cell
This is a simple classification loss (not explained in the article)
|
Yolo Loss function explanation
Explanation of the different terms :
The 3 $\lambda$ constants are just constants to take into account more one aspect of the loss function. In the article $\lambda_{coord}$ is the highest in order
|
6,415
|
Yolo Loss function explanation
|
\begin{align}
&\lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(x_i-\hat{x}_i)^2 + (y_i-\hat{y}_i)^2 ] \\&+ \lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(\sqrt{w_i}-\sqrt{\hat{w}_i})^2 +(\sqrt{h_i}-\sqrt{\hat{h}_i})^2 ]\\
&+ \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}(C_i - \hat{C}_i)^2 + \lambda_{noobj}\sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{noobj}(C_i - \hat{C}_i)^2 \\
&+ \sum_{i=0}^{S^2} \mathbb{1}_{i}^{obj}\sum_{c \in classes}(p_i(c) - \hat{p}_i(c))^2 \\
\end{align}
Doesn't the YOLOv2 Loss function looks scary? It's not actually! It is one of the boldest, smartest loss function around.
Let's first look at what the network actually predicts.
If we recap, YOLOv2 predicts detections on a 13x13 feature map, so in total, we have 169 maps/cells.
We have 5 anchor boxes. For each anchor box we need Objectness-Confidence Score (whether any object was found?), 4 Coordinates ($t_x, t_y, t_w,$ and $t_h$) for the anchor box, and 20 top classes. This can crudely be seen as 20 coordinates, 5 confidence scores, and 100 class probabilities for all 5 anchor box predictions put together.
We have few things to worry about:
$x_i, y_i$, which is the location of the centroid of the anchor box
$w_i, h_i$, which is the width and height of the anchor box
$C_i$, which is the Objectness, i.e. confidence score of whether there is an object or not, and
$p_i(c)$, which is the classification loss.
We not only need to train the network to detect an object if there is an object in a cell, we also need to punish the network, it if predicts an object in a cell, when there wasn't any. How do we do this? We use a mask ($𝟙_{i}^{obj}$ and $𝟙_{i}^{noobj}$) for each cell. If originally there was an object $𝟙_{i}^{obj}$ is 1 and other no-object cells are 0. $𝟙_{i}^{noobj}$ is just inverse of $𝟙_{i}^{obj}$, where it is 1 if there was no object in the cell and 0 if there was.
We need to do this for all 169 cells, and
We need to do this 5 times (for each anchor box).
All losses are mean-squared errors, except classification loss, which uses cross-entropy function.
Now, let's break the code in the image.
We need to compute losses for each Anchor Box (5 in total)
$\sum_{j=0}^B$ represents this part, where B = 4 (5 - 1, since the index starts from 0)
We need to do this for each of the 13x13 cells where S = 12 (since we start index from 0)
$\sum_{i=0}^{S^2}$ represents this part.
$𝟙_{ij}^{obj}$ is 1 when there is an object in the cell $i$, else 0.
$𝟙_{ij}^{noobj}$ is 1 when there is no object in the cell $i$, else 0.
$𝟙_{i}^{obj}$ is 1 when there is a particular class is predicted, else 0.
λs are constants. λ is highest for coordinates in order to focus more on detection (remember, in YOLOv2, we first train it for recognition and then for detection, penalizing heavily for recognition is waste of time, rather we focus on getting best bounding boxes!)
We can also notice that $w_i, h_i$ are under square-root. This is done to penalize the smaller bounding boxes as we need better prediction on smaller objects than on bigger objects (author's call). Check out the table below and observe how the smaller values are punished more if we follow "square-root" method (look at the inflection point when we have 0.3 and 0.2 as the input values) (PS: I have kept the ratio of var1 and var2 same just for explanation):
var1 | var2 | (var1 - var2)^2 | (sqrtvar1 - sqrtvar2)^2
0.0300 | 0.020 | 9.99e-05 | 0.001
0.0330 | 0.022 | 0.00012 | 0.0011
0.0693 | 0.046 | 0.000533 | 0.00233
0.2148 | 0.143 | 0.00512 | 0.00723
0.3030 | 0.202 | 0.01 | 0.01
0.8808 | 0.587 | 0.0862 | 0.0296
4.4920 | 2.994 | 2.2421 | 0.1512
Not that scary, right!
Read HERE for further details.
|
Yolo Loss function explanation
|
\begin{align}
&\lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(x_i-\hat{x}_i)^2 + (y_i-\hat{y}_i)^2 ] \\&+ \lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(\sqrt
|
Yolo Loss function explanation
\begin{align}
&\lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(x_i-\hat{x}_i)^2 + (y_i-\hat{y}_i)^2 ] \\&+ \lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(\sqrt{w_i}-\sqrt{\hat{w}_i})^2 +(\sqrt{h_i}-\sqrt{\hat{h}_i})^2 ]\\
&+ \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}(C_i - \hat{C}_i)^2 + \lambda_{noobj}\sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{noobj}(C_i - \hat{C}_i)^2 \\
&+ \sum_{i=0}^{S^2} \mathbb{1}_{i}^{obj}\sum_{c \in classes}(p_i(c) - \hat{p}_i(c))^2 \\
\end{align}
Doesn't the YOLOv2 Loss function looks scary? It's not actually! It is one of the boldest, smartest loss function around.
Let's first look at what the network actually predicts.
If we recap, YOLOv2 predicts detections on a 13x13 feature map, so in total, we have 169 maps/cells.
We have 5 anchor boxes. For each anchor box we need Objectness-Confidence Score (whether any object was found?), 4 Coordinates ($t_x, t_y, t_w,$ and $t_h$) for the anchor box, and 20 top classes. This can crudely be seen as 20 coordinates, 5 confidence scores, and 100 class probabilities for all 5 anchor box predictions put together.
We have few things to worry about:
$x_i, y_i$, which is the location of the centroid of the anchor box
$w_i, h_i$, which is the width and height of the anchor box
$C_i$, which is the Objectness, i.e. confidence score of whether there is an object or not, and
$p_i(c)$, which is the classification loss.
We not only need to train the network to detect an object if there is an object in a cell, we also need to punish the network, it if predicts an object in a cell, when there wasn't any. How do we do this? We use a mask ($𝟙_{i}^{obj}$ and $𝟙_{i}^{noobj}$) for each cell. If originally there was an object $𝟙_{i}^{obj}$ is 1 and other no-object cells are 0. $𝟙_{i}^{noobj}$ is just inverse of $𝟙_{i}^{obj}$, where it is 1 if there was no object in the cell and 0 if there was.
We need to do this for all 169 cells, and
We need to do this 5 times (for each anchor box).
All losses are mean-squared errors, except classification loss, which uses cross-entropy function.
Now, let's break the code in the image.
We need to compute losses for each Anchor Box (5 in total)
$\sum_{j=0}^B$ represents this part, where B = 4 (5 - 1, since the index starts from 0)
We need to do this for each of the 13x13 cells where S = 12 (since we start index from 0)
$\sum_{i=0}^{S^2}$ represents this part.
$𝟙_{ij}^{obj}$ is 1 when there is an object in the cell $i$, else 0.
$𝟙_{ij}^{noobj}$ is 1 when there is no object in the cell $i$, else 0.
$𝟙_{i}^{obj}$ is 1 when there is a particular class is predicted, else 0.
λs are constants. λ is highest for coordinates in order to focus more on detection (remember, in YOLOv2, we first train it for recognition and then for detection, penalizing heavily for recognition is waste of time, rather we focus on getting best bounding boxes!)
We can also notice that $w_i, h_i$ are under square-root. This is done to penalize the smaller bounding boxes as we need better prediction on smaller objects than on bigger objects (author's call). Check out the table below and observe how the smaller values are punished more if we follow "square-root" method (look at the inflection point when we have 0.3 and 0.2 as the input values) (PS: I have kept the ratio of var1 and var2 same just for explanation):
var1 | var2 | (var1 - var2)^2 | (sqrtvar1 - sqrtvar2)^2
0.0300 | 0.020 | 9.99e-05 | 0.001
0.0330 | 0.022 | 0.00012 | 0.0011
0.0693 | 0.046 | 0.000533 | 0.00233
0.2148 | 0.143 | 0.00512 | 0.00723
0.3030 | 0.202 | 0.01 | 0.01
0.8808 | 0.587 | 0.0862 | 0.0296
4.4920 | 2.994 | 2.2421 | 0.1512
Not that scary, right!
Read HERE for further details.
|
Yolo Loss function explanation
\begin{align}
&\lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(x_i-\hat{x}_i)^2 + (y_i-\hat{y}_i)^2 ] \\&+ \lambda_{coord} \sum_{i=0}^{S^2}\sum_{j=0}^B \mathbb{1}_{ij}^{obj}[(\sqrt
|
6,416
|
Yolo Loss function explanation
|
The loss formula you wrote is of the original YOLO paper loss, not the v2, or v3 loss.
There are some major differences between versions. I suggest reading the papers, or checking the code implementations. Papers: v2, v3.
Some major differences I noticed:
Class probability is calculated per bounding box (hence output is now S∗S∗B*(5+C) instead of SS(B*5 + C))
Bounding box coordinates now have a different representation
In v3 they use 3 boxes across 3 different "scales"
You can try getting into the nitty-gritty details of the loss, either by looking at the python/keras implementation v2, v3 (look for the function yolo_loss) or directly at the c implementation v3 (look for delta_yolo_box, and delta_yolo_class).
|
Yolo Loss function explanation
|
The loss formula you wrote is of the original YOLO paper loss, not the v2, or v3 loss.
There are some major differences between versions. I suggest reading the papers, or checking the code implementat
|
Yolo Loss function explanation
The loss formula you wrote is of the original YOLO paper loss, not the v2, or v3 loss.
There are some major differences between versions. I suggest reading the papers, or checking the code implementations. Papers: v2, v3.
Some major differences I noticed:
Class probability is calculated per bounding box (hence output is now S∗S∗B*(5+C) instead of SS(B*5 + C))
Bounding box coordinates now have a different representation
In v3 they use 3 boxes across 3 different "scales"
You can try getting into the nitty-gritty details of the loss, either by looking at the python/keras implementation v2, v3 (look for the function yolo_loss) or directly at the c implementation v3 (look for delta_yolo_box, and delta_yolo_class).
|
Yolo Loss function explanation
The loss formula you wrote is of the original YOLO paper loss, not the v2, or v3 loss.
There are some major differences between versions. I suggest reading the papers, or checking the code implementat
|
6,417
|
Yolo Loss function explanation
|
Your loss function is for YOLO v1 and not YOLO v2. I was also confused with the difference in the two loss functions and seems like many people are:
https://groups.google.com/forum/#!topic/darknet/TJ4dN9R4iJk
YOLOv2 paper explains the difference in architecture from YOLOv1 as follows:
We remove the fully connected layers from YOLO(v1) and use anchor
boxes to predict bounding boxes... When we move to anchor boxes we
also decouple the class prediction mechanism from the spatial location
and instead predict class and objectness for every anchorbox.
This means that the confidence probability $p_i(c)$ above should depend not only on $i$ and $c$ but also an anchor box index, say $j$. Therefore, the loss needs to be different from above. Unfortunately, YOLOv2 paper does not explicitly state its loss function.
I try to make a guess on the loss function of YOLOv2 and discuss it here:
https://fairyonice.github.io/Part_4_Object_Detection_with_Yolo_using_VOC_2012_data_loss.html
|
Yolo Loss function explanation
|
Your loss function is for YOLO v1 and not YOLO v2. I was also confused with the difference in the two loss functions and seems like many people are:
https://groups.google.com/forum/#!topic/darknet/TJ
|
Yolo Loss function explanation
Your loss function is for YOLO v1 and not YOLO v2. I was also confused with the difference in the two loss functions and seems like many people are:
https://groups.google.com/forum/#!topic/darknet/TJ4dN9R4iJk
YOLOv2 paper explains the difference in architecture from YOLOv1 as follows:
We remove the fully connected layers from YOLO(v1) and use anchor
boxes to predict bounding boxes... When we move to anchor boxes we
also decouple the class prediction mechanism from the spatial location
and instead predict class and objectness for every anchorbox.
This means that the confidence probability $p_i(c)$ above should depend not only on $i$ and $c$ but also an anchor box index, say $j$. Therefore, the loss needs to be different from above. Unfortunately, YOLOv2 paper does not explicitly state its loss function.
I try to make a guess on the loss function of YOLOv2 and discuss it here:
https://fairyonice.github.io/Part_4_Object_Detection_with_Yolo_using_VOC_2012_data_loss.html
|
Yolo Loss function explanation
Your loss function is for YOLO v1 and not YOLO v2. I was also confused with the difference in the two loss functions and seems like many people are:
https://groups.google.com/forum/#!topic/darknet/TJ
|
6,418
|
Yolo Loss function explanation
|
Here is my Study Note
Loss function: sum-squared error
a. Reason: Easy to optimize
b. Problem: (1) Does not perfectly align with our goal of maximize average precision. (2) In every image, many grid cells do not contain any object. This pushes the confidence scores of those cells towards 0, often overpowering the gradient from cells that do contain an object.
c. Solution: increase loss from bounding box coordinate predictions and decrease the loss from confidence predictions from boxes that don't contain objects. We use two parameters $$\lambda_{coord} = 5$$ and $\lambda_{noobj}$ = 0.5
d. Sum-squared error also equally weights errors in large boxes and small boxes
Only one bounding box should be responsible for each object. We assign one predictor to be responsible for predicting an object based on which prediction has the highest current IOU with the ground truth.
a. Loss from bound box coordinate (x, y) Note that the loss comes from one bounding box from one grid cell. Even if obj not in grid cell as ground truth.
$$
\begin{cases}
\lambda_{coord} \sum^{S^2}_{i=0} [(x_i - \hat{x}_i)^2 + (y_i - \hat{y_i})^2] &\text{responsible bounding box} \\
0 &\text{ other} \\
\end {cases}
$$
b. Loss from width w and height h. Note that the loss comes from one bounding box from one grid cell, even if the object is not in the grid cell as ground truth.
$$
\begin {cases}
\lambda_{coord} \sum^{S^2}_{i=0} [(\sqrt{w_i} - \sqrt{\hat{w}_i})^2 + (\sqrt{h_i} - \sqrt{\hat{h}_i})^2] &\text{responsible bounding box} \\
0 &\text{ other} \\
\end {cases}
$$
c. Loss from the confidence in each bound box. Not that the loss comes from one bounding box from one grid cell, even if the object is not in the grid cell as ground truth.
$$
\begin {cases}
\sum^{S^2}_{i=0}(C_i - \hat{C}_i)^2 &\text{obj in grid cell and responsible bounding box} \\
\lambda_{noobj} \sum^{S^2}_{i=0}(C_i - \hat{C}_i)^2 &\text{obj not in grid cell and responsible bounding box} \\
0 &\text{other}
\end {cases}
$$
d. Loss from the class probability of grid cell, only when object is in the grid cell as ground truth.
$$
\begin {cases}
\sum^{S^2}_{i=0} \sum_{c \in classes} (p_i(c) - \hat{p}_i(c))^2 &\text{obj in grid cell}\\
0 &\text{other} \\
\end {cases}
$$
Loss function only penalizes classification if obj is present in the grid cell.
It also penalize bounding box coordinate if that box is responsible for the ground box (highest IOU)
|
Yolo Loss function explanation
|
Here is my Study Note
Loss function: sum-squared error
a. Reason: Easy to optimize
b. Problem: (1) Does not perfectly align with our goal of maximize average precision. (2) In every image, many grid
|
Yolo Loss function explanation
Here is my Study Note
Loss function: sum-squared error
a. Reason: Easy to optimize
b. Problem: (1) Does not perfectly align with our goal of maximize average precision. (2) In every image, many grid cells do not contain any object. This pushes the confidence scores of those cells towards 0, often overpowering the gradient from cells that do contain an object.
c. Solution: increase loss from bounding box coordinate predictions and decrease the loss from confidence predictions from boxes that don't contain objects. We use two parameters $$\lambda_{coord} = 5$$ and $\lambda_{noobj}$ = 0.5
d. Sum-squared error also equally weights errors in large boxes and small boxes
Only one bounding box should be responsible for each object. We assign one predictor to be responsible for predicting an object based on which prediction has the highest current IOU with the ground truth.
a. Loss from bound box coordinate (x, y) Note that the loss comes from one bounding box from one grid cell. Even if obj not in grid cell as ground truth.
$$
\begin{cases}
\lambda_{coord} \sum^{S^2}_{i=0} [(x_i - \hat{x}_i)^2 + (y_i - \hat{y_i})^2] &\text{responsible bounding box} \\
0 &\text{ other} \\
\end {cases}
$$
b. Loss from width w and height h. Note that the loss comes from one bounding box from one grid cell, even if the object is not in the grid cell as ground truth.
$$
\begin {cases}
\lambda_{coord} \sum^{S^2}_{i=0} [(\sqrt{w_i} - \sqrt{\hat{w}_i})^2 + (\sqrt{h_i} - \sqrt{\hat{h}_i})^2] &\text{responsible bounding box} \\
0 &\text{ other} \\
\end {cases}
$$
c. Loss from the confidence in each bound box. Not that the loss comes from one bounding box from one grid cell, even if the object is not in the grid cell as ground truth.
$$
\begin {cases}
\sum^{S^2}_{i=0}(C_i - \hat{C}_i)^2 &\text{obj in grid cell and responsible bounding box} \\
\lambda_{noobj} \sum^{S^2}_{i=0}(C_i - \hat{C}_i)^2 &\text{obj not in grid cell and responsible bounding box} \\
0 &\text{other}
\end {cases}
$$
d. Loss from the class probability of grid cell, only when object is in the grid cell as ground truth.
$$
\begin {cases}
\sum^{S^2}_{i=0} \sum_{c \in classes} (p_i(c) - \hat{p}_i(c))^2 &\text{obj in grid cell}\\
0 &\text{other} \\
\end {cases}
$$
Loss function only penalizes classification if obj is present in the grid cell.
It also penalize bounding box coordinate if that box is responsible for the ground box (highest IOU)
|
Yolo Loss function explanation
Here is my Study Note
Loss function: sum-squared error
a. Reason: Easy to optimize
b. Problem: (1) Does not perfectly align with our goal of maximize average precision. (2) In every image, many grid
|
6,419
|
Interpretation of p-value in hypothesis testing
|
(Technically, the P-value is the probability of observing data at least as extreme as that actually observed, given the null hypothesis.)
Q1. A decision to reject the null hypothesis on the basis of a small P-value typically depends on 'Fisher's disjunction': Either a rare event has happened or the null hypothesis is false. In effect, it is rarity of the event is what the P-value tells you rather than the probability that the null is false.
The probability that the null is false can be obtained from the experimental data only by way of Bayes' theorem, which requires specification of the 'prior' probability of the null hypothesis (presumably what Gill is referring to as "marginal distributions").
Q2. This part of your question is much harder than it might seem. There is a great deal of confusion regarding P-values and error rates which is, presumably, what Gill is referring to with "but is typically treated as such." The combination of Fisherian P-values with Neyman-Pearsonian error rates has been called an incoherent mishmash, and it is unfortunately very widespread. No short answer is going to be completely adequate here, but I can point you to a couple of good papers (yes, one is mine). Both will help you make sense of the Gill paper.
Hurlbert, S., & Lombardi, C. (2009). Final collapse of the Neyman-Pearson decision theoretic framework and rise of the neoFisherian. Annales Zoologici Fennici, 46(5), 311–349. (Link to paper)
Lew, M. J. (2012). Bad statistical practice in pharmacology (and other basic biomedical disciplines): you probably don't know P. British Journal of Pharmacology, 166(5), 1559–1567. doi:10.1111/j.1476-5381.2012.01931.x (Link to paper)
|
Interpretation of p-value in hypothesis testing
|
(Technically, the P-value is the probability of observing data at least as extreme as that actually observed, given the null hypothesis.)
Q1. A decision to reject the null hypothesis on the basis of a
|
Interpretation of p-value in hypothesis testing
(Technically, the P-value is the probability of observing data at least as extreme as that actually observed, given the null hypothesis.)
Q1. A decision to reject the null hypothesis on the basis of a small P-value typically depends on 'Fisher's disjunction': Either a rare event has happened or the null hypothesis is false. In effect, it is rarity of the event is what the P-value tells you rather than the probability that the null is false.
The probability that the null is false can be obtained from the experimental data only by way of Bayes' theorem, which requires specification of the 'prior' probability of the null hypothesis (presumably what Gill is referring to as "marginal distributions").
Q2. This part of your question is much harder than it might seem. There is a great deal of confusion regarding P-values and error rates which is, presumably, what Gill is referring to with "but is typically treated as such." The combination of Fisherian P-values with Neyman-Pearsonian error rates has been called an incoherent mishmash, and it is unfortunately very widespread. No short answer is going to be completely adequate here, but I can point you to a couple of good papers (yes, one is mine). Both will help you make sense of the Gill paper.
Hurlbert, S., & Lombardi, C. (2009). Final collapse of the Neyman-Pearson decision theoretic framework and rise of the neoFisherian. Annales Zoologici Fennici, 46(5), 311–349. (Link to paper)
Lew, M. J. (2012). Bad statistical practice in pharmacology (and other basic biomedical disciplines): you probably don't know P. British Journal of Pharmacology, 166(5), 1559–1567. doi:10.1111/j.1476-5381.2012.01931.x (Link to paper)
|
Interpretation of p-value in hypothesis testing
(Technically, the P-value is the probability of observing data at least as extreme as that actually observed, given the null hypothesis.)
Q1. A decision to reject the null hypothesis on the basis of a
|
6,420
|
Interpretation of p-value in hypothesis testing
|
+1 to @MichaelLew, who has provided you with a good answer. Perhaps I can still contribute by providing a way of thinking about Q2. Consider the following situation:
The null hypothesis is true. (Note that if the null hypothesis is not true, no type I errors are possible, and it's not clear what meaning the $p$-value has.)
$\alpha$ has been set conventionally at $0.05$.
The computed $p$-value is $0.01$.
Now, the probability of getting data as extreme or more extreme than your data is 1% (that's what the $p$-value means). You have rejected the null hypothesis, making a type I error. Is it true that the long run type I error rate in this situation is also 1%, which many people might intuitively conclude? The answer is no. The reason is that if you had gotten a $p$-value of $0.02$, you would still have rejected the null. In fact, you would have rejected the null even if $p$ had been $0.04\bar{9}$, and in the long run, $p$'s up to this large will occur $\approx$5% of the time and all of such rejections will be type I errors. Thus, the long run type I error rate is 5% (where you had set $\alpha$).
(Disclosure: I have not read Gill's paper, so I cannot guarantee that this is what he meant, but it does make sense of the claim that the $p$-value is not [necessarily] the same as the long run type I error rate.)
|
Interpretation of p-value in hypothesis testing
|
+1 to @MichaelLew, who has provided you with a good answer. Perhaps I can still contribute by providing a way of thinking about Q2. Consider the following situation:
The null hypothesis is true.
|
Interpretation of p-value in hypothesis testing
+1 to @MichaelLew, who has provided you with a good answer. Perhaps I can still contribute by providing a way of thinking about Q2. Consider the following situation:
The null hypothesis is true. (Note that if the null hypothesis is not true, no type I errors are possible, and it's not clear what meaning the $p$-value has.)
$\alpha$ has been set conventionally at $0.05$.
The computed $p$-value is $0.01$.
Now, the probability of getting data as extreme or more extreme than your data is 1% (that's what the $p$-value means). You have rejected the null hypothesis, making a type I error. Is it true that the long run type I error rate in this situation is also 1%, which many people might intuitively conclude? The answer is no. The reason is that if you had gotten a $p$-value of $0.02$, you would still have rejected the null. In fact, you would have rejected the null even if $p$ had been $0.04\bar{9}$, and in the long run, $p$'s up to this large will occur $\approx$5% of the time and all of such rejections will be type I errors. Thus, the long run type I error rate is 5% (where you had set $\alpha$).
(Disclosure: I have not read Gill's paper, so I cannot guarantee that this is what he meant, but it does make sense of the claim that the $p$-value is not [necessarily] the same as the long run type I error rate.)
|
Interpretation of p-value in hypothesis testing
+1 to @MichaelLew, who has provided you with a good answer. Perhaps I can still contribute by providing a way of thinking about Q2. Consider the following situation:
The null hypothesis is true.
|
6,421
|
Interpretation of p-value in hypothesis testing
|
I'd like to make a comment related to "the insignificance of null hypothesis significance testing" but which does not answer the question of the OP.
In my opinion, the main problem is not the misinterpretation of the $p$-value. Many practitioners often test for a "significant difference" for instance, and they wrongly believe that a significant difference means that there is a "big" difference. More precisely they are in the context of a "precise" null hypothesis $H_0$ having form $H_0\colon\{\theta=0\}$. This hypothesis will be rejected when $\theta=\epsilon$ even for a very small $\epsilon$ when the sample size increases. But in the real world, there's no difference between a small $\epsilon$ and $0$ (we say there is equivalence between a small $\epsilon$ and $0$ and equivalence testing is the way to go in such a situation).
|
Interpretation of p-value in hypothesis testing
|
I'd like to make a comment related to "the insignificance of null hypothesis significance testing" but which does not answer the question of the OP.
In my opinion, the main problem is not the misinter
|
Interpretation of p-value in hypothesis testing
I'd like to make a comment related to "the insignificance of null hypothesis significance testing" but which does not answer the question of the OP.
In my opinion, the main problem is not the misinterpretation of the $p$-value. Many practitioners often test for a "significant difference" for instance, and they wrongly believe that a significant difference means that there is a "big" difference. More precisely they are in the context of a "precise" null hypothesis $H_0$ having form $H_0\colon\{\theta=0\}$. This hypothesis will be rejected when $\theta=\epsilon$ even for a very small $\epsilon$ when the sample size increases. But in the real world, there's no difference between a small $\epsilon$ and $0$ (we say there is equivalence between a small $\epsilon$ and $0$ and equivalence testing is the way to go in such a situation).
|
Interpretation of p-value in hypothesis testing
I'd like to make a comment related to "the insignificance of null hypothesis significance testing" but which does not answer the question of the OP.
In my opinion, the main problem is not the misinter
|
6,422
|
How to find a good fit for semi-sinusoidal model in R?
|
It can be done with linear regression -
You just need both a $\sin$ and a $\cos$ term at each frequency.
The reason why you can use a $\sin$ and $\cos$ term in a linear regression to handle seasonality with any amplitude and phase is because of the following trigonometric identity:
A 'general' sine wave with amplitude $A$ and phase $\varphi$, $A \sin (x + \varphi)$, can be written as the linear combination
$a\sin x+b\cos x$ where $a$ and $b$ are such that $A=\sqrt{a^2+b^2}$ and $\sin\varphi = \frac{b}{\sqrt{a^2+b^2}}$. Let's see that the two are equivalent:
\begin{eqnarray}
a \sin(x) + b \cos(x) &=& \sqrt{a^2+b^2} \left(\frac{a}{\sqrt{a^2+b^2}} \sin(x) + \frac{b}{\sqrt{a^2+b^2}} \cos(x)\right)\\
&=& A\left[\sin(x)\cos(\varphi) + \cos(x)\sin(\varphi)\right]\\
&=& A\sin(x+\varphi)\,\text{.}
\end{eqnarray}
Here's the 'basic' model:
SSTlm <- lm(Degrees ~ sin(2*pi*ToY)+cos(2*pi*ToY),data=SST)
summary(SSTlm)
[snip]
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.292 0.135 61.41 <2e-16 ***
sin(2 * pi * ToY) -5.916 0.191 -30.98 <2e-16 ***
cos(2 * pi * ToY) -4.046 0.191 -21.19 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.9355 on 45 degrees of freedom
Multiple R-squared: 0.969, Adjusted R-squared: 0.9677
F-statistic: 704.3 on 2 and 45 DF, p-value: < 2.2e-16
plot(Degrees~ToY,ylim=c(1.5,16.5),data=SST)
lines(SST$ToY,SSTlm$fitted,col=2)
Edit: Important note - the $2\pi\,t$ term works because the period of the function has been set up so that one period = 1 unit of $t$. If the period is different from 1, say the period is $\omega$, then you need $(2\pi/\omega)\, t$ instead.
Here's the model with the second harmonic:
SSTlm2 <- lm(Degrees ~ sin(2*pi*ToY)+cos(2*pi*ToY)
+sin(4*pi*ToY)+cos(4*pi*ToY),data=SST)
summary(SSTlm2)
[snip]
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.29167 0.02637 314.450 < 2e-16 ***
sin(2 * pi * ToY) -5.91562 0.03729 -158.634 < 2e-16 ***
cos(2 * pi * ToY) -4.04632 0.03729 -108.506 < 2e-16 ***
sin(4 * pi * ToY) 1.21244 0.03729 32.513 < 2e-16 ***
cos(4 * pi * ToY) 0.33333 0.03729 8.939 2.32e-11 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.1827 on 43 degrees of freedom
Multiple R-squared: 0.9989, Adjusted R-squared: 0.9988
F-statistic: 9519 on 4 and 43 DF, p-value: < 2.2e-16
plot(Degrees~ToY,ylab="Degrees",xlab="ToY",ylim=c(1.5,16.5),data=SST)
lines(SSTlm2$fitted~ToY,col=2,data=SST)
... and so forth, with 6*pi*ToY etc. If there was a tiny bit of noise in the data I'd probably stop with this second model though.
With enough terms, you can exactly fit asymmetric and even jagged periodic sequences, but the resulting fits may 'wiggle'. Here's an asymmetric function (it's a sawtooth -) added to a scaled version of your periodic function), with third (red) and fourth (green) harmonics. The green fit is on average a little closer but "wiggly" (even when the fit goes through every point, the fit may be very wiggly between points).
The periodicity here means there's only 12 d.f. available for a seasonal model in the data. With the intercept in the model, you only have enough degrees of freedom for 11 additional seasonal parameters. Since you are adding two terms with each harmonic, the last harmonic you can fit will only allow you one of them for the last term, the sixth harmonic (and that one has to be a $\cos$; the $\sin$ term will be all-zero, while the cos alternates between 1 and -1).
If you want fits that are smoother than this approach produces on non-smooth series, you may want to look into periodic spline fits.
Yet another approach is to use seasonal dummies, but the sin/cos approach is often better if it's a smooth periodic function.
This kind of approach to seasonality can also adapt to situations where seasonality is changing, such as using trigonometric or dummy seasonality with state-space models.
While the linear model approach discussed here is simple to use, one advantage of @COOLSerdash's nonlinear regression approach is that it can deal with a much wider range of situations - you don't have to change much before you're in a situation where linear regression is no longer suitable but nonlinear least-squares may still be used (having an unknown period would be one such case).
|
How to find a good fit for semi-sinusoidal model in R?
|
It can be done with linear regression -
You just need both a $\sin$ and a $\cos$ term at each frequency.
The reason why you can use a $\sin$ and $\cos$ term in a linear regression to handle seasonali
|
How to find a good fit for semi-sinusoidal model in R?
It can be done with linear regression -
You just need both a $\sin$ and a $\cos$ term at each frequency.
The reason why you can use a $\sin$ and $\cos$ term in a linear regression to handle seasonality with any amplitude and phase is because of the following trigonometric identity:
A 'general' sine wave with amplitude $A$ and phase $\varphi$, $A \sin (x + \varphi)$, can be written as the linear combination
$a\sin x+b\cos x$ where $a$ and $b$ are such that $A=\sqrt{a^2+b^2}$ and $\sin\varphi = \frac{b}{\sqrt{a^2+b^2}}$. Let's see that the two are equivalent:
\begin{eqnarray}
a \sin(x) + b \cos(x) &=& \sqrt{a^2+b^2} \left(\frac{a}{\sqrt{a^2+b^2}} \sin(x) + \frac{b}{\sqrt{a^2+b^2}} \cos(x)\right)\\
&=& A\left[\sin(x)\cos(\varphi) + \cos(x)\sin(\varphi)\right]\\
&=& A\sin(x+\varphi)\,\text{.}
\end{eqnarray}
Here's the 'basic' model:
SSTlm <- lm(Degrees ~ sin(2*pi*ToY)+cos(2*pi*ToY),data=SST)
summary(SSTlm)
[snip]
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.292 0.135 61.41 <2e-16 ***
sin(2 * pi * ToY) -5.916 0.191 -30.98 <2e-16 ***
cos(2 * pi * ToY) -4.046 0.191 -21.19 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.9355 on 45 degrees of freedom
Multiple R-squared: 0.969, Adjusted R-squared: 0.9677
F-statistic: 704.3 on 2 and 45 DF, p-value: < 2.2e-16
plot(Degrees~ToY,ylim=c(1.5,16.5),data=SST)
lines(SST$ToY,SSTlm$fitted,col=2)
Edit: Important note - the $2\pi\,t$ term works because the period of the function has been set up so that one period = 1 unit of $t$. If the period is different from 1, say the period is $\omega$, then you need $(2\pi/\omega)\, t$ instead.
Here's the model with the second harmonic:
SSTlm2 <- lm(Degrees ~ sin(2*pi*ToY)+cos(2*pi*ToY)
+sin(4*pi*ToY)+cos(4*pi*ToY),data=SST)
summary(SSTlm2)
[snip]
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.29167 0.02637 314.450 < 2e-16 ***
sin(2 * pi * ToY) -5.91562 0.03729 -158.634 < 2e-16 ***
cos(2 * pi * ToY) -4.04632 0.03729 -108.506 < 2e-16 ***
sin(4 * pi * ToY) 1.21244 0.03729 32.513 < 2e-16 ***
cos(4 * pi * ToY) 0.33333 0.03729 8.939 2.32e-11 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.1827 on 43 degrees of freedom
Multiple R-squared: 0.9989, Adjusted R-squared: 0.9988
F-statistic: 9519 on 4 and 43 DF, p-value: < 2.2e-16
plot(Degrees~ToY,ylab="Degrees",xlab="ToY",ylim=c(1.5,16.5),data=SST)
lines(SSTlm2$fitted~ToY,col=2,data=SST)
... and so forth, with 6*pi*ToY etc. If there was a tiny bit of noise in the data I'd probably stop with this second model though.
With enough terms, you can exactly fit asymmetric and even jagged periodic sequences, but the resulting fits may 'wiggle'. Here's an asymmetric function (it's a sawtooth -) added to a scaled version of your periodic function), with third (red) and fourth (green) harmonics. The green fit is on average a little closer but "wiggly" (even when the fit goes through every point, the fit may be very wiggly between points).
The periodicity here means there's only 12 d.f. available for a seasonal model in the data. With the intercept in the model, you only have enough degrees of freedom for 11 additional seasonal parameters. Since you are adding two terms with each harmonic, the last harmonic you can fit will only allow you one of them for the last term, the sixth harmonic (and that one has to be a $\cos$; the $\sin$ term will be all-zero, while the cos alternates between 1 and -1).
If you want fits that are smoother than this approach produces on non-smooth series, you may want to look into periodic spline fits.
Yet another approach is to use seasonal dummies, but the sin/cos approach is often better if it's a smooth periodic function.
This kind of approach to seasonality can also adapt to situations where seasonality is changing, such as using trigonometric or dummy seasonality with state-space models.
While the linear model approach discussed here is simple to use, one advantage of @COOLSerdash's nonlinear regression approach is that it can deal with a much wider range of situations - you don't have to change much before you're in a situation where linear regression is no longer suitable but nonlinear least-squares may still be used (having an unknown period would be one such case).
|
How to find a good fit for semi-sinusoidal model in R?
It can be done with linear regression -
You just need both a $\sin$ and a $\cos$ term at each frequency.
The reason why you can use a $\sin$ and $\cos$ term in a linear regression to handle seasonali
|
6,423
|
How to find a good fit for semi-sinusoidal model in R?
|
The temperature you provide in your question repeats exactly every year. I suspect this aren't really measured temperatures over four years. In your example, you wouldn't need a model, because the temperatures just repeat exactly. But otherwise you could use the nls function to fit a sine curve:
ToY <- c(1/12,2/12,3/12,4/12,5/12,6/12,7/12,8/12,9/12,10/12,11/12,12/12,13/12,14/12,15/12,16/12,17/12,18/12,19/12,20/12,21/12,22/12,23/12,24/12,25/12,26/12,27/12,28/12,29/12,30/12,31/12,32/12,33/12,34/12,35/12,36/12,37/12,38/12,39/12,40/12,41/12,42/12,43/12,44/12,45/12,46/12,47/12,48/12)
Degrees <- c(3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5,3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5,3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5,3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5)
SST <- data.frame(ToY, Degrees)
par(cex=1.5, bg="white")
plot(Degrees~ToY,xlim=c(0,4),ylim=c(0,17), pch=16, las=1)
nls.mod <-nls(Degrees ~ a + b*sin(2*pi*c*ToY), start=list(a = 1, b = 1, c=1))
co <- coef(nls.mod)
f <- function(x, a, b, c) {a + b*sin(2*pi*c*x) }
curve(f(x, a=co["a"], b=co["b"], c=co["c"]), add=TRUE ,lwd=2, col="steelblue")
But the fit isn't very good, especially at the beginning. It seems that your data cannot be adequately modelled by a simple sine curve. Maybe a more complex trigonometrical function will do the trick?
nls.mod2 <-nls(Degrees ~ a + b*sin(2*pi*c*ToY)+d*cos(2*pi*e*ToY), start=list(a = 1, b = 1, c=1, d=1, e=1))
co2 <- coef(nls.mod2)
f <- function(x, a, b, c, d, e) {a + b*sin(2*pi*c*x)+d*cos(2*pi*e*x) }
curve(f(x, a=co2["a"], b=co2["b"], c=co2["c"], d=co2["d"], e=co2["e"]), add=TRUE ,lwd=2, col="red")
The red curve fits the data better. With the nls function, you can put in the model that you think is appropriate.
Or maybe you could make use the the forecast package. In the example below, I have assumed that the time series started in January 2010:
library(forecast)
Degrees.ts <- ts(Degrees, start=c(2010,1), frequency=12)
Degree.trend <- auto.arima(Degrees.ts)
degrees.forecast <- forecast(Degree.trend, h=12, level=c(80,95), fan=F)
plot(degrees.forecast, las=1, main="", xlab="Time", ylab="Degrees")
Because the data is deterministic, no confidence bands are shown.
|
How to find a good fit for semi-sinusoidal model in R?
|
The temperature you provide in your question repeats exactly every year. I suspect this aren't really measured temperatures over four years. In your example, you wouldn't need a model, because the tem
|
How to find a good fit for semi-sinusoidal model in R?
The temperature you provide in your question repeats exactly every year. I suspect this aren't really measured temperatures over four years. In your example, you wouldn't need a model, because the temperatures just repeat exactly. But otherwise you could use the nls function to fit a sine curve:
ToY <- c(1/12,2/12,3/12,4/12,5/12,6/12,7/12,8/12,9/12,10/12,11/12,12/12,13/12,14/12,15/12,16/12,17/12,18/12,19/12,20/12,21/12,22/12,23/12,24/12,25/12,26/12,27/12,28/12,29/12,30/12,31/12,32/12,33/12,34/12,35/12,36/12,37/12,38/12,39/12,40/12,41/12,42/12,43/12,44/12,45/12,46/12,47/12,48/12)
Degrees <- c(3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5,3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5,3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5,3,2,2.2,4,7.6,13,16,16.1,14,10.1,7,4.5)
SST <- data.frame(ToY, Degrees)
par(cex=1.5, bg="white")
plot(Degrees~ToY,xlim=c(0,4),ylim=c(0,17), pch=16, las=1)
nls.mod <-nls(Degrees ~ a + b*sin(2*pi*c*ToY), start=list(a = 1, b = 1, c=1))
co <- coef(nls.mod)
f <- function(x, a, b, c) {a + b*sin(2*pi*c*x) }
curve(f(x, a=co["a"], b=co["b"], c=co["c"]), add=TRUE ,lwd=2, col="steelblue")
But the fit isn't very good, especially at the beginning. It seems that your data cannot be adequately modelled by a simple sine curve. Maybe a more complex trigonometrical function will do the trick?
nls.mod2 <-nls(Degrees ~ a + b*sin(2*pi*c*ToY)+d*cos(2*pi*e*ToY), start=list(a = 1, b = 1, c=1, d=1, e=1))
co2 <- coef(nls.mod2)
f <- function(x, a, b, c, d, e) {a + b*sin(2*pi*c*x)+d*cos(2*pi*e*x) }
curve(f(x, a=co2["a"], b=co2["b"], c=co2["c"], d=co2["d"], e=co2["e"]), add=TRUE ,lwd=2, col="red")
The red curve fits the data better. With the nls function, you can put in the model that you think is appropriate.
Or maybe you could make use the the forecast package. In the example below, I have assumed that the time series started in January 2010:
library(forecast)
Degrees.ts <- ts(Degrees, start=c(2010,1), frequency=12)
Degree.trend <- auto.arima(Degrees.ts)
degrees.forecast <- forecast(Degree.trend, h=12, level=c(80,95), fan=F)
plot(degrees.forecast, las=1, main="", xlab="Time", ylab="Degrees")
Because the data is deterministic, no confidence bands are shown.
|
How to find a good fit for semi-sinusoidal model in R?
The temperature you provide in your question repeats exactly every year. I suspect this aren't really measured temperatures over four years. In your example, you wouldn't need a model, because the tem
|
6,424
|
How does Factor Analysis explain the covariance while PCA explains the variance?
|
The distinction between Principal component analysis and Factor analysis is discussed in numerous textbooks and articles on multivariate techniques. You may find the full thread, and a newer one, and odd answers, on this site, too.
I'm not going to make it detailed. I've already given a concise answer and a longer one and would like now to clarify it with a pair of pictures.
Graphical representation
The picture below explains PCA. (This was borrowed from here where PCA is compared with Linear regression and Canonical correlations. The picture is the vector representation of variables in the subject space; to understand what it is you may want to read the 2nd paragraph there.)
PCA configuration on this picture was described there. I will repeat most principal things. Principal components $P_1$ and $P_2$ lie in the same space that is spanned by the variables $X_1$ and $X_2$, "plane X". Squared length of each of the four vectors is its variance. The covariance between $X_1$ and $X_2$ is $cov_{12}= |X_1||X_2|r$, where $r$ equals the cosine of the angle between their vectors.
The projections (coordinates) of the variables on the components, the $a$'s, are the loadings of the components on the variables: loadings are the regression coefficients in the linear combinations of modeling variables by standardized components. "Standardized" - because information about components' variances is already absorbed in loadings (remember, loadings are eigenvectors normalized to the respective eigenvalues). And due to that, and to the fact that components are uncorrelated, loadings are the covariances between the variables and the components.
Using PCA for dimensionality/data reduction aim compels us to retain only $P_1$ and to regard $P_2$ as the remainder, or error. $a_{11}^2+a_{21}^2= |P_1|^2$ is the variance captured (explained) by $P_1$.
The picture below demonstrates Factor analysis performed on the same variables $X_1$ and $X_2$ with which we did PCA above. (I will speak of common factor model, for there exist other: alpha factor model, image factor model.) Smiley sun helps with lighting.
The common factor is $F$. It is what is the analogue to the main component $P_1$ above. Can you see the difference between these two? Yes, clearly: the factor does not lie in the variables' space "plane X".
How to get that factor with one finger, i.e. to do factor analysis? Let's try. On the previous picture, hook the end of $P_1$ arrow by your nail tip and pull away from "plane X", while visualizing how two new planes appear, "plane U1" and "plane U2"; these connecting the hooked vector and the two variable vectors. The two planes form a hood, X1 - F - X2, above "plane X".
Continue to pull while contemplating the hood and stop when "plane U1" and "plane U2" form 90 degrees between them. Ready, factor analysis is done. Well, yes, but not yet optimally. To do it right, like packages do, repeat the whole excercise of pulling the arrow, now adding small left-right swings of your finger while you pull. Doing so, find the position of the arrow when the sum of squared projections of both variables onto it is maximized, while you attain to that 90 degree angle. Stop. You did factor analysis, found the position of the common factor $F$.
Again to remark, unlike principal component $P_1$, factor $F$ does not belong to variables' space "plane X". It therefore is not a function of the variables (principal component is, and you can make sure from the two top pictures here that PCA is fundamentally two-directional: predicts variables by components and vice versa). Factor analysis is thus not a description/simplification method, like PCA, it is modeling method whereby latent factor steeres observed variables, one-directionally.
Loadings $a$'s of the factor on the variables are like loadings in PCA; they are the covariances and they are the coefficients of modeling variables by the (standardized) factor. $a_{1}^2+a_{2}^2= |F|^2$ is the variance captured (explained) by $F$. The factor was found as to maximize this quantity - as if a principal component. However, that explained variance is no more variables' gross variance, - instead, it is their variance by which they co-vary (correlate). Why so?
Get back to the pic. We extracted $F$ under two requirements. One was the just mentioned maximized sum of squared loadings. The other was the creation of the two perpendicular planes, "plane U1" containing $F$ and $X_1$, and "plane U2" containing $F$ and $X_2$. This way each of the X variables appeared decomposed. $X_1$ was decomposed into variables $F$ and $U_1$, mutually orthogonal; $X_2$ was likewise decomposed into variables $F$ and $U_2$, also orthogonal. And $U_1$ is orthogonal to $U_2$. We know what is $F$ - the common factor. $U$'s are called unique factors. Each variable has its unique factor. The meaning is as follows. $U_1$ behind $X_1$ and $U_2$ behind $X_2$ are the forces that hinder $X_1$ and $X_2$ to correlate. But $F$ - the common factor - is the force behind both $X_1$ and $X_2$ that makes them to correlate. And the variance being explained lie along that common factor. So, it is pure collinearity variance. It is that variance that makes $cov_{12}>0$; the actual value of $cov_{12}$ being determined by inclinations of the variables towards the factor, by $a$'s.
A variable's variance (vector's length squared) thus consists of two additive disjoint parts: uniqueness $u^2$ and communality $a^2$. With two variables, like our example, we can extract at most one common factor, so communality = single loading squared. With many variables we might extract several common factors, and a variable's communality will be the sum of its squared loadings. On our picture, the common factors space is unidimensional (just $F$ itself); when m common factors exist, that space is m-dimensional, with communalities being variables' projections on the space and loadings being variables' as well as those projections' projections on the factors that span the space. Variance explained in factor analysis is the variance within that common factors' space, different from variables' space in which components explain variance. The space of the variables is in the belly of the combined space: m common + p unique factors.
Just glance at the current pic please. There were several (say, $X_1$, $X_2$, $X_3$) variables with which factor analysis was done, extracting two common factors. The factors $F_1$ and $F_2$ span the common factor space "factor plane". Of the bunch of analysed variables only one ($X_1$) is shown on the figure. The analysis decomposed it in two orthogonal parts, communality $C_1$ and unique factor $U_1$. Communality lies in the "factor plane" and its coordinates on the factors are the loadings by which the common factors load $X_1$ (= coordinates of $X_1$ itself on the factors). On the picture, communalities of the other two variables - projections of $X_2$ and of $X_3$ - are also displayed. It would be interesting to remark that the two common factors can, in a sense, be seen as the principal components of all those communality "variables". Whereas usual principal components summarize by seniority the multivariate total variance of the variables, the factors summarize likewise their multivariate common variance. $^1$
Why needed all that verbiage? I just wanted to give evidence to the claim that when you decompose each of the correlated variables into two orthogonal latent parts, one (A) representing uncorrelatedness (orthogonality) between the variables and the other part (B) representing their correlatedness (collinearity), and you extract factors from the combined B's only, you will find yourself explaining pairwise covariances, by those factors' loadings. In our factor model, $cov_{12} \approx a_1a_2$ - factors restore individual covariances by means of loadings. In PCA model, it is not so since PCA explains undecomposed, mixed collinear+orthogonal native variance. Both strong components that you retain and subsequent ones that you drop are fusions of (A) and (B) parts; hence PCA can tap, by its loadings, covariances only blindly and grossly.
Contrast list PCA vs FA
PCA: operates in the space of the variables. FA: trancsends the space of the variables.
PCA: takes variability as is. FA: segments variability into common and unique parts.
PCA: explains nonsegmented variance, i.e. trace of the covariance matrix. FA: explains common variance only, hence explains (restores by loadings) correlations/covariances, off-diagonal elements of the matrix. (PCA explains off-diagonal elements too - but in passing, offhand manner - simply because variances are shared in a form of covariances.)
PCA: components are theoretically linear functions of variables, variables are theoretically linear functions of components. FA: variables are theoretically linear functions of factors, only.
PCA: empirical summarizing method; it retains m components. FA: theoretical modeling method; it fits fixed number m factors to the data; FA can be tested (Confirmatory FA).
PCA: is simplest metric MDS, aims to reduce dimensionality while indirectly preserving distances between data points as much as possible. FA: Factors are essential latent traits behind variables which make them to correlate; the analysis aims to reduce data to those essences only.
PCA: rotation/interpretation of components - sometimes (PCA is not enough realistic as a latent-traits model). FA: rotation/interpretation of factors - routinely.
PCA: data reduction method only. FA: also a method to find clusters of coherent variables (this is because variables cannot correlate beyond a factor).
PCA: loadings and scores are independent of the number m of components "extracted". FA: loadings and scores depend on the number m of factors "extracted".
PCA: component scores are exact component values. FA: factor scores are approximates to true factor values, and several computational methods exist. Factor scores do lie in the space of the variables (like components do) while true factors (as embodied by factor loadings) do not.
PCA: usually no assumptions. FA: assumption of weak partial correlations; sometimes multivariate normality assumption; some datasets may be "bad" for analysis unless transformed.
PCA: noniterative algorithm; always successful. FA: iterative algorithm (typically); sometimes nonconvergence problem; singularity may be a problem.
$^1$ For meticulous. One might ask where are variables $X_2$ and $X_3$ themselves on the pic, why were they not drawn? The answer is that we can't draw them, even theoretically. The space on the picture is 3d (defined by "factor plane" and the unique vector $U_1$; $X_1$ lying on their mutual complement, plane shaded grey, that's what corresponds to one slope of the "hood" on the picture No.2), and so our graphic resources are exhausted. The three dimensional space spanned by three variables $X_1$, $X_2$, $X_3$ together is another space. Neither "factor plane" nor $U_1$ are the subspaces of it. It's what is different from PCA: factors do not belong to the variables' space. Each variable separately lies in its separate grey plane orthogonal to "factor plane" - just like $X_1$ shown on our pic, and that is all: if we were to add, say, $X_2$ to the plot we should have invented 4th dimension. (Just recall that all $U$s have to be mutually orthogonal; so, to add another $U$, you must expand dimensionality farther.)
Similarly as in regression the coefficients are the coordinates, on the predictors, both of the dependent variable(s) and of the prediction(s) (See pic under "Multiple Regression", and here, too), in FA loadings are the coordinates, on the factors, both of the observed variables and of their latent parts - the communalities. And exactly as in regression that fact did not make the dependent(s) and the predictors be subspaces of each other, - in FA the similar fact does not make the observed variables and the latent factors be subspaces of each other. A factor is "alien" to a variable in a quite similar sense as a predictor is "alien" to a dependent response. But in PCA, it is other way: principal components are derived from the observed variables and are confined to their space.
So, once again to repeat: m common factors of FA are not a subspace of the p input variables. On the contrary: the variables form a subspace in the m+p (m common factors + p unique factors) union hyperspace. When seen from this perspective (i.e. with the unique factors attracted too) it becomes clear that classic FA is not a dimensionality shrinkage technique, like classic PCA, but is a dimensionality expansion technique. Nevertheless, we give our attention only to a small (m dimensional common) part of that bloat, since this part solely explains correlations.
|
How does Factor Analysis explain the covariance while PCA explains the variance?
|
The distinction between Principal component analysis and Factor analysis is discussed in numerous textbooks and articles on multivariate techniques. You may find the full thread, and a newer one, and
|
How does Factor Analysis explain the covariance while PCA explains the variance?
The distinction between Principal component analysis and Factor analysis is discussed in numerous textbooks and articles on multivariate techniques. You may find the full thread, and a newer one, and odd answers, on this site, too.
I'm not going to make it detailed. I've already given a concise answer and a longer one and would like now to clarify it with a pair of pictures.
Graphical representation
The picture below explains PCA. (This was borrowed from here where PCA is compared with Linear regression and Canonical correlations. The picture is the vector representation of variables in the subject space; to understand what it is you may want to read the 2nd paragraph there.)
PCA configuration on this picture was described there. I will repeat most principal things. Principal components $P_1$ and $P_2$ lie in the same space that is spanned by the variables $X_1$ and $X_2$, "plane X". Squared length of each of the four vectors is its variance. The covariance between $X_1$ and $X_2$ is $cov_{12}= |X_1||X_2|r$, where $r$ equals the cosine of the angle between their vectors.
The projections (coordinates) of the variables on the components, the $a$'s, are the loadings of the components on the variables: loadings are the regression coefficients in the linear combinations of modeling variables by standardized components. "Standardized" - because information about components' variances is already absorbed in loadings (remember, loadings are eigenvectors normalized to the respective eigenvalues). And due to that, and to the fact that components are uncorrelated, loadings are the covariances between the variables and the components.
Using PCA for dimensionality/data reduction aim compels us to retain only $P_1$ and to regard $P_2$ as the remainder, or error. $a_{11}^2+a_{21}^2= |P_1|^2$ is the variance captured (explained) by $P_1$.
The picture below demonstrates Factor analysis performed on the same variables $X_1$ and $X_2$ with which we did PCA above. (I will speak of common factor model, for there exist other: alpha factor model, image factor model.) Smiley sun helps with lighting.
The common factor is $F$. It is what is the analogue to the main component $P_1$ above. Can you see the difference between these two? Yes, clearly: the factor does not lie in the variables' space "plane X".
How to get that factor with one finger, i.e. to do factor analysis? Let's try. On the previous picture, hook the end of $P_1$ arrow by your nail tip and pull away from "plane X", while visualizing how two new planes appear, "plane U1" and "plane U2"; these connecting the hooked vector and the two variable vectors. The two planes form a hood, X1 - F - X2, above "plane X".
Continue to pull while contemplating the hood and stop when "plane U1" and "plane U2" form 90 degrees between them. Ready, factor analysis is done. Well, yes, but not yet optimally. To do it right, like packages do, repeat the whole excercise of pulling the arrow, now adding small left-right swings of your finger while you pull. Doing so, find the position of the arrow when the sum of squared projections of both variables onto it is maximized, while you attain to that 90 degree angle. Stop. You did factor analysis, found the position of the common factor $F$.
Again to remark, unlike principal component $P_1$, factor $F$ does not belong to variables' space "plane X". It therefore is not a function of the variables (principal component is, and you can make sure from the two top pictures here that PCA is fundamentally two-directional: predicts variables by components and vice versa). Factor analysis is thus not a description/simplification method, like PCA, it is modeling method whereby latent factor steeres observed variables, one-directionally.
Loadings $a$'s of the factor on the variables are like loadings in PCA; they are the covariances and they are the coefficients of modeling variables by the (standardized) factor. $a_{1}^2+a_{2}^2= |F|^2$ is the variance captured (explained) by $F$. The factor was found as to maximize this quantity - as if a principal component. However, that explained variance is no more variables' gross variance, - instead, it is their variance by which they co-vary (correlate). Why so?
Get back to the pic. We extracted $F$ under two requirements. One was the just mentioned maximized sum of squared loadings. The other was the creation of the two perpendicular planes, "plane U1" containing $F$ and $X_1$, and "plane U2" containing $F$ and $X_2$. This way each of the X variables appeared decomposed. $X_1$ was decomposed into variables $F$ and $U_1$, mutually orthogonal; $X_2$ was likewise decomposed into variables $F$ and $U_2$, also orthogonal. And $U_1$ is orthogonal to $U_2$. We know what is $F$ - the common factor. $U$'s are called unique factors. Each variable has its unique factor. The meaning is as follows. $U_1$ behind $X_1$ and $U_2$ behind $X_2$ are the forces that hinder $X_1$ and $X_2$ to correlate. But $F$ - the common factor - is the force behind both $X_1$ and $X_2$ that makes them to correlate. And the variance being explained lie along that common factor. So, it is pure collinearity variance. It is that variance that makes $cov_{12}>0$; the actual value of $cov_{12}$ being determined by inclinations of the variables towards the factor, by $a$'s.
A variable's variance (vector's length squared) thus consists of two additive disjoint parts: uniqueness $u^2$ and communality $a^2$. With two variables, like our example, we can extract at most one common factor, so communality = single loading squared. With many variables we might extract several common factors, and a variable's communality will be the sum of its squared loadings. On our picture, the common factors space is unidimensional (just $F$ itself); when m common factors exist, that space is m-dimensional, with communalities being variables' projections on the space and loadings being variables' as well as those projections' projections on the factors that span the space. Variance explained in factor analysis is the variance within that common factors' space, different from variables' space in which components explain variance. The space of the variables is in the belly of the combined space: m common + p unique factors.
Just glance at the current pic please. There were several (say, $X_1$, $X_2$, $X_3$) variables with which factor analysis was done, extracting two common factors. The factors $F_1$ and $F_2$ span the common factor space "factor plane". Of the bunch of analysed variables only one ($X_1$) is shown on the figure. The analysis decomposed it in two orthogonal parts, communality $C_1$ and unique factor $U_1$. Communality lies in the "factor plane" and its coordinates on the factors are the loadings by which the common factors load $X_1$ (= coordinates of $X_1$ itself on the factors). On the picture, communalities of the other two variables - projections of $X_2$ and of $X_3$ - are also displayed. It would be interesting to remark that the two common factors can, in a sense, be seen as the principal components of all those communality "variables". Whereas usual principal components summarize by seniority the multivariate total variance of the variables, the factors summarize likewise their multivariate common variance. $^1$
Why needed all that verbiage? I just wanted to give evidence to the claim that when you decompose each of the correlated variables into two orthogonal latent parts, one (A) representing uncorrelatedness (orthogonality) between the variables and the other part (B) representing their correlatedness (collinearity), and you extract factors from the combined B's only, you will find yourself explaining pairwise covariances, by those factors' loadings. In our factor model, $cov_{12} \approx a_1a_2$ - factors restore individual covariances by means of loadings. In PCA model, it is not so since PCA explains undecomposed, mixed collinear+orthogonal native variance. Both strong components that you retain and subsequent ones that you drop are fusions of (A) and (B) parts; hence PCA can tap, by its loadings, covariances only blindly and grossly.
Contrast list PCA vs FA
PCA: operates in the space of the variables. FA: trancsends the space of the variables.
PCA: takes variability as is. FA: segments variability into common and unique parts.
PCA: explains nonsegmented variance, i.e. trace of the covariance matrix. FA: explains common variance only, hence explains (restores by loadings) correlations/covariances, off-diagonal elements of the matrix. (PCA explains off-diagonal elements too - but in passing, offhand manner - simply because variances are shared in a form of covariances.)
PCA: components are theoretically linear functions of variables, variables are theoretically linear functions of components. FA: variables are theoretically linear functions of factors, only.
PCA: empirical summarizing method; it retains m components. FA: theoretical modeling method; it fits fixed number m factors to the data; FA can be tested (Confirmatory FA).
PCA: is simplest metric MDS, aims to reduce dimensionality while indirectly preserving distances between data points as much as possible. FA: Factors are essential latent traits behind variables which make them to correlate; the analysis aims to reduce data to those essences only.
PCA: rotation/interpretation of components - sometimes (PCA is not enough realistic as a latent-traits model). FA: rotation/interpretation of factors - routinely.
PCA: data reduction method only. FA: also a method to find clusters of coherent variables (this is because variables cannot correlate beyond a factor).
PCA: loadings and scores are independent of the number m of components "extracted". FA: loadings and scores depend on the number m of factors "extracted".
PCA: component scores are exact component values. FA: factor scores are approximates to true factor values, and several computational methods exist. Factor scores do lie in the space of the variables (like components do) while true factors (as embodied by factor loadings) do not.
PCA: usually no assumptions. FA: assumption of weak partial correlations; sometimes multivariate normality assumption; some datasets may be "bad" for analysis unless transformed.
PCA: noniterative algorithm; always successful. FA: iterative algorithm (typically); sometimes nonconvergence problem; singularity may be a problem.
$^1$ For meticulous. One might ask where are variables $X_2$ and $X_3$ themselves on the pic, why were they not drawn? The answer is that we can't draw them, even theoretically. The space on the picture is 3d (defined by "factor plane" and the unique vector $U_1$; $X_1$ lying on their mutual complement, plane shaded grey, that's what corresponds to one slope of the "hood" on the picture No.2), and so our graphic resources are exhausted. The three dimensional space spanned by three variables $X_1$, $X_2$, $X_3$ together is another space. Neither "factor plane" nor $U_1$ are the subspaces of it. It's what is different from PCA: factors do not belong to the variables' space. Each variable separately lies in its separate grey plane orthogonal to "factor plane" - just like $X_1$ shown on our pic, and that is all: if we were to add, say, $X_2$ to the plot we should have invented 4th dimension. (Just recall that all $U$s have to be mutually orthogonal; so, to add another $U$, you must expand dimensionality farther.)
Similarly as in regression the coefficients are the coordinates, on the predictors, both of the dependent variable(s) and of the prediction(s) (See pic under "Multiple Regression", and here, too), in FA loadings are the coordinates, on the factors, both of the observed variables and of their latent parts - the communalities. And exactly as in regression that fact did not make the dependent(s) and the predictors be subspaces of each other, - in FA the similar fact does not make the observed variables and the latent factors be subspaces of each other. A factor is "alien" to a variable in a quite similar sense as a predictor is "alien" to a dependent response. But in PCA, it is other way: principal components are derived from the observed variables and are confined to their space.
So, once again to repeat: m common factors of FA are not a subspace of the p input variables. On the contrary: the variables form a subspace in the m+p (m common factors + p unique factors) union hyperspace. When seen from this perspective (i.e. with the unique factors attracted too) it becomes clear that classic FA is not a dimensionality shrinkage technique, like classic PCA, but is a dimensionality expansion technique. Nevertheless, we give our attention only to a small (m dimensional common) part of that bloat, since this part solely explains correlations.
|
How does Factor Analysis explain the covariance while PCA explains the variance?
The distinction between Principal component analysis and Factor analysis is discussed in numerous textbooks and articles on multivariate techniques. You may find the full thread, and a newer one, and
|
6,425
|
How does Factor Analysis explain the covariance while PCA explains the variance?
|
"Explaining covariance" vs. explaining variance
Bishop actually means a very simple thing. Under the factor analysis model (eq. 12.64) $$p(\mathbf x|\mathbf z) = \mathcal N(\mathbf x | \mathbf W \mathbf z + \boldsymbol \mu, \boldsymbol \Psi)$$ the covariance matrix of $\mathbf x$ is going to be (eq. 12.65) $$\mathbf C = \mathbf W \mathbf W^\top + \boldsymbol \Psi.$$ This is essentially what factor analysis does: it finds a matrix of loadings and a diagonal matrix of uniquenesses such that the actually observed covariance matrix $\boldsymbol \Sigma$ is as well as possible approximated by $\mathbf C$: $$\boldsymbol \Sigma \approx \mathbf W \mathbf W^\top + \boldsymbol \Psi.$$ Notice that diagonal elements of $\mathbf C$ will be exactly equal to the diagonal elements of $\boldsymbol \Sigma$ because we can always choose the diagonal matrix $\boldsymbol \Psi$ such that the reconstruction error on the diagonal is zero. The real challenge is then to find loadings $\mathbf W$ that would well approximate the off-diagonal part of $\boldsymbol \Sigma$.
The off-diagonal part of $\boldsymbol \Sigma$ consists of covariances between variables; hence Bishop's claim that factor loadings are capturing the covariances. The important bit here is that factor loadings do not care at all about individual variances (diagonal of $\boldsymbol \Sigma$).
In contrast, PCA loadings $\widetilde {\mathbf W}$ are eigenvectors of the covariance matrix $\boldsymbol \Sigma$ scaled up by square roots of their eigenvalues. If only $m<k$ principal components are chosen, then $$\boldsymbol \Sigma \approx \widetilde{\mathbf W} \widetilde{\mathbf W}^\top,$$ meaning that PCA loadings try to reproduce the whole covariance matrix (and not only its off-diagonal part as FA). This is the main difference between PCA and FA.
Further comments
I love the drawings in @ttnphns'es answer (+1), but I would like to stress that they deal with a very special situation of two variables. If there are only two variables under consideration, the covariance matrix is $2 \times 2$, has only one off-diagonal element and so one factor is always enough to reproduce it 100% (whereas PCA would need two components). However in general, if there are many variables (say, a dozen or more) then neither PCA nor FA with small number of components will be able to fully reproduce the covariance matrix; moreover, they will usually (even though not necessarily!) produce similar results. See my answer here for some simulations supporting this claim and for further explanations:
Is there any good reason to use PCA instead of EFA? Also, can PCA be a substitute for factor analysis?
So even though @ttnphns's drawings can make the impression that PCA and FA are very different, my opinion is that it is not the case, except with very few variables or in some other special situations.
See also:
Under which conditions do PCA and FA yield similar results?
What do the first $k$ factors from factor analysis maximize?
Finally:
For example, let's take a look at the first loading vector $w_1$, for $1\le i,j,k\le p$, if $w_{1i}=10$, $w_{1j}=11$ and $w_{1k}=0.1$, then I'd say $x_i$ and $x_j$ are highly correlated, whereas $x_k$ seems uncorrelated with them, am I right?
This is not necessarily correct. Yes, in this example $x_i$ and $x_j$ are likely to be correlated, but you are forgetting about other factors. Perhaps the loading vector $w_2$ of the second factor has large values for $x_i$ and $x_k$; this would mean that they are likely to be well correlated as well. You need to take all factors into account to make such conclusions.
|
How does Factor Analysis explain the covariance while PCA explains the variance?
|
"Explaining covariance" vs. explaining variance
Bishop actually means a very simple thing. Under the factor analysis model (eq. 12.64) $$p(\mathbf x|\mathbf z) = \mathcal N(\mathbf x | \mathbf W \math
|
How does Factor Analysis explain the covariance while PCA explains the variance?
"Explaining covariance" vs. explaining variance
Bishop actually means a very simple thing. Under the factor analysis model (eq. 12.64) $$p(\mathbf x|\mathbf z) = \mathcal N(\mathbf x | \mathbf W \mathbf z + \boldsymbol \mu, \boldsymbol \Psi)$$ the covariance matrix of $\mathbf x$ is going to be (eq. 12.65) $$\mathbf C = \mathbf W \mathbf W^\top + \boldsymbol \Psi.$$ This is essentially what factor analysis does: it finds a matrix of loadings and a diagonal matrix of uniquenesses such that the actually observed covariance matrix $\boldsymbol \Sigma$ is as well as possible approximated by $\mathbf C$: $$\boldsymbol \Sigma \approx \mathbf W \mathbf W^\top + \boldsymbol \Psi.$$ Notice that diagonal elements of $\mathbf C$ will be exactly equal to the diagonal elements of $\boldsymbol \Sigma$ because we can always choose the diagonal matrix $\boldsymbol \Psi$ such that the reconstruction error on the diagonal is zero. The real challenge is then to find loadings $\mathbf W$ that would well approximate the off-diagonal part of $\boldsymbol \Sigma$.
The off-diagonal part of $\boldsymbol \Sigma$ consists of covariances between variables; hence Bishop's claim that factor loadings are capturing the covariances. The important bit here is that factor loadings do not care at all about individual variances (diagonal of $\boldsymbol \Sigma$).
In contrast, PCA loadings $\widetilde {\mathbf W}$ are eigenvectors of the covariance matrix $\boldsymbol \Sigma$ scaled up by square roots of their eigenvalues. If only $m<k$ principal components are chosen, then $$\boldsymbol \Sigma \approx \widetilde{\mathbf W} \widetilde{\mathbf W}^\top,$$ meaning that PCA loadings try to reproduce the whole covariance matrix (and not only its off-diagonal part as FA). This is the main difference between PCA and FA.
Further comments
I love the drawings in @ttnphns'es answer (+1), but I would like to stress that they deal with a very special situation of two variables. If there are only two variables under consideration, the covariance matrix is $2 \times 2$, has only one off-diagonal element and so one factor is always enough to reproduce it 100% (whereas PCA would need two components). However in general, if there are many variables (say, a dozen or more) then neither PCA nor FA with small number of components will be able to fully reproduce the covariance matrix; moreover, they will usually (even though not necessarily!) produce similar results. See my answer here for some simulations supporting this claim and for further explanations:
Is there any good reason to use PCA instead of EFA? Also, can PCA be a substitute for factor analysis?
So even though @ttnphns's drawings can make the impression that PCA and FA are very different, my opinion is that it is not the case, except with very few variables or in some other special situations.
See also:
Under which conditions do PCA and FA yield similar results?
What do the first $k$ factors from factor analysis maximize?
Finally:
For example, let's take a look at the first loading vector $w_1$, for $1\le i,j,k\le p$, if $w_{1i}=10$, $w_{1j}=11$ and $w_{1k}=0.1$, then I'd say $x_i$ and $x_j$ are highly correlated, whereas $x_k$ seems uncorrelated with them, am I right?
This is not necessarily correct. Yes, in this example $x_i$ and $x_j$ are likely to be correlated, but you are forgetting about other factors. Perhaps the loading vector $w_2$ of the second factor has large values for $x_i$ and $x_k$; this would mean that they are likely to be well correlated as well. You need to take all factors into account to make such conclusions.
|
How does Factor Analysis explain the covariance while PCA explains the variance?
"Explaining covariance" vs. explaining variance
Bishop actually means a very simple thing. Under the factor analysis model (eq. 12.64) $$p(\mathbf x|\mathbf z) = \mathcal N(\mathbf x | \mathbf W \math
|
6,426
|
Variance of product of dependent variables
|
Well, using the familiar identity you pointed out,
$$ {\rm var}(XY) = E(X^{2}Y^{2}) - E(XY)^{2} $$
Using the analogous formula for covariance,
$$ E(X^{2}Y^{2}) = {\rm cov}(X^{2}, Y^{2}) + E(X^2)E(Y^2) $$
and
$$ E(XY)^{2} = [ {\rm cov}(X,Y) + E(X)E(Y) ]^{2} $$
which implies that, in general, ${\rm var}(XY)$ can be written as
$$ {\rm cov}(X^{2}, Y^{2}) + [{\rm var}(X) + E(X)^2] \cdot[{\rm var}(Y) + E(Y)^2] - [ {\rm cov}(X,Y) + E(X)E(Y) ]^{2} $$
Note that in the independence case, ${\rm cov}(X^2,Y^2) = {\rm cov}(X,Y) = 0$ and this reduces to
$$ [{\rm var}(X) + E(X)^2] \cdot[{\rm var}(Y) + E(Y)^2] - [ E(X)E(Y) ]^{2} $$
and the two $[ E(X)E(Y) ]^{2}$ terms cancel out and you get
$$ {\rm var}(X){\rm var}(Y) + {\rm var}(X)E(Y)^{2} + {\rm var}(Y)E(X)^{2} $$
as you pointed out above.
Edit: If all you observe is $XY$ and not $X$ and $Y$ separately, then I don't think there is a way for you to estimate ${\rm cov}(X,Y)$ or ${\rm cov}(X^2,Y^2)$ except in special cases (for example, if $X,Y$ have means that are known a priori)
|
Variance of product of dependent variables
|
Well, using the familiar identity you pointed out,
$$ {\rm var}(XY) = E(X^{2}Y^{2}) - E(XY)^{2} $$
Using the analogous formula for covariance,
$$ E(X^{2}Y^{2}) = {\rm cov}(X^{2}, Y^{2}) + E(X^2)E(Y
|
Variance of product of dependent variables
Well, using the familiar identity you pointed out,
$$ {\rm var}(XY) = E(X^{2}Y^{2}) - E(XY)^{2} $$
Using the analogous formula for covariance,
$$ E(X^{2}Y^{2}) = {\rm cov}(X^{2}, Y^{2}) + E(X^2)E(Y^2) $$
and
$$ E(XY)^{2} = [ {\rm cov}(X,Y) + E(X)E(Y) ]^{2} $$
which implies that, in general, ${\rm var}(XY)$ can be written as
$$ {\rm cov}(X^{2}, Y^{2}) + [{\rm var}(X) + E(X)^2] \cdot[{\rm var}(Y) + E(Y)^2] - [ {\rm cov}(X,Y) + E(X)E(Y) ]^{2} $$
Note that in the independence case, ${\rm cov}(X^2,Y^2) = {\rm cov}(X,Y) = 0$ and this reduces to
$$ [{\rm var}(X) + E(X)^2] \cdot[{\rm var}(Y) + E(Y)^2] - [ E(X)E(Y) ]^{2} $$
and the two $[ E(X)E(Y) ]^{2}$ terms cancel out and you get
$$ {\rm var}(X){\rm var}(Y) + {\rm var}(X)E(Y)^{2} + {\rm var}(Y)E(X)^{2} $$
as you pointed out above.
Edit: If all you observe is $XY$ and not $X$ and $Y$ separately, then I don't think there is a way for you to estimate ${\rm cov}(X,Y)$ or ${\rm cov}(X^2,Y^2)$ except in special cases (for example, if $X,Y$ have means that are known a priori)
|
Variance of product of dependent variables
Well, using the familiar identity you pointed out,
$$ {\rm var}(XY) = E(X^{2}Y^{2}) - E(XY)^{2} $$
Using the analogous formula for covariance,
$$ E(X^{2}Y^{2}) = {\rm cov}(X^{2}, Y^{2}) + E(X^2)E(Y
|
6,427
|
Variance of product of dependent variables
|
This is an addendum to @Macro's very nice answer which lays out
exactly what needs to known in order to determine the variance of
the product of two correlated random variables. Since
\begin{align}
\operatorname{var}(XY) &= E\left[(XY)^2\right] - \left(E[XY]\right)^2
\tag{1}\\
&= E[(XY)^2] - \left(\operatorname{cov}(X,Y)+E[X]E[Y]\right)^2\\
&= E[X^2Y^2] - \left(\operatorname{cov}(X,Y)+E[X]E[Y]\right)^2\tag{2}\\
&= \left(\operatorname{cov}(X^2,Y^2)+E[X^2]E[Y^2]\right)
- \left(\operatorname{cov}(X,Y)+E[X]E[Y]\right)^2\tag{3}\\
\end{align}
where $\operatorname{cov}(X,Y)$, $E[X]$, $E[Y]$, $E[X^2]$, and
$E[Y^2]$ can be assumed to
be known quantities, we need to be able to determine the value of
$E\left[X^2Y^2\right]$ in $(2)$ or $\operatorname{cov}(X^2,Y^2)$ in $(3)$.
This is not easy to do in general, but, as pointed out already, if
$X$ and $Y$ are independent random variables, then
$\operatorname{cov}(X,Y) = \operatorname{cov}(X^2,Y^2) = 0$.
In fact, dependence, not correlation (or lack thereof) is the
key issue. That we know that $\operatorname{cov}(X,Y)$ equals $0$
instead of some nonzero value does not, by itself, help in the
least in our efforts are determining the value of
$E\left[X^2Y^2\right]$ or $\operatorname{cov}(X^2,Y^2)$ even though it
does simplify the right sides of $(2)$ and $(3)$ a little.
When $X$ and $Y$ are dependent
random variables, then in at least one (fairly common
or fairly important) special
case, it is possible to find
the value of $E\left[X^2Y^2\right]$ relatively easily.
Suppose that $X$ and $Y$ are jointly normal random variables
with correlation coefficient $\rho$. Then, conditioned
on $X = x$, the conditional density of $Y$ is a normal
density with mean
$E[Y] + \rho\left.\left.\sqrt{\frac{\operatorname{var}(Y)}{\operatorname{var}(X)}}
\right(x-E[X]\right)$ and variance $\operatorname{var}(Y)(1-\rho^2)$. Thus,
\begin{align}E[X^2Y^2 \mid X] &= X^2E[Y^2 \mid X]\\
&= X^2\left[\operatorname{var}(Y)(1-\rho^2)
+ \left(E[Y] + \rho\left.\left.\sqrt{\frac{\operatorname{var}(Y)}{\operatorname{var}(X)}}
\right(X-E[X]\right)\right)^2\right]
\end{align}
which is a quartic function of $X$, say $g(X)$, and the Law of Iterated
Expectation tells us that
$$E[X^2Y^2] = E\left[E[X^2Y^2\mid X]\right] = E[g(X)]\tag{4}$$
where the right side of $(4)$ can be computed from knowledge of the
3rd and 4th moments of $X$ -- standard results that can be found
in many texts and reference books
(meaning that I am too lazy to look them up
and include them in this answer).
Further addendum: In a now-deleted answer, @Hydrologist gives the variance of $XY$ as
$$\mathrm{Var}\left[xy\right] = \left(\mathrm{E}\left[x\right]\right)^2\mathrm{Var}\left[y\right] + \left(\mathrm{E}\left[y\right]\right)^2\mathrm{Var}\left[x\right] + 2\mathrm{E}\left[x\right]\mathrm{Cov}\left[x,y^2\right] + 2\mathrm{E}\left[y\right]\mathrm{Cov}\left[x^2,y\right]\\ + 2\mathrm{E}\left[x\right]\mathrm{E}\left[y\right]\mathrm{Cov}\left[x,y\right] +\mathrm{Cov}\left[x^2,y^2\right] - \left(\mathrm{Cov}\left[x,y\right]\right)^2 \tag{5}$$
and claims that this formula is from two papers published a half-century ago in JASA. This formula is an incorrect transcription of the results in the paper(s) cited by Hydrologist. Specifically, $\mathrm{Cov}\left[x^2,y^2\right]$ is a mistranscription of
$E[(x-E[x])^2(y-E[y])^2]$ in the journal article, and similarly for $\mathrm{Cov}\left[x^2,y\right]$ and $\mathrm{Cov}\left[x,y^2\right]$.
|
Variance of product of dependent variables
|
This is an addendum to @Macro's very nice answer which lays out
exactly what needs to known in order to determine the variance of
the product of two correlated random variables. Since
\begin{align}
|
Variance of product of dependent variables
This is an addendum to @Macro's very nice answer which lays out
exactly what needs to known in order to determine the variance of
the product of two correlated random variables. Since
\begin{align}
\operatorname{var}(XY) &= E\left[(XY)^2\right] - \left(E[XY]\right)^2
\tag{1}\\
&= E[(XY)^2] - \left(\operatorname{cov}(X,Y)+E[X]E[Y]\right)^2\\
&= E[X^2Y^2] - \left(\operatorname{cov}(X,Y)+E[X]E[Y]\right)^2\tag{2}\\
&= \left(\operatorname{cov}(X^2,Y^2)+E[X^2]E[Y^2]\right)
- \left(\operatorname{cov}(X,Y)+E[X]E[Y]\right)^2\tag{3}\\
\end{align}
where $\operatorname{cov}(X,Y)$, $E[X]$, $E[Y]$, $E[X^2]$, and
$E[Y^2]$ can be assumed to
be known quantities, we need to be able to determine the value of
$E\left[X^2Y^2\right]$ in $(2)$ or $\operatorname{cov}(X^2,Y^2)$ in $(3)$.
This is not easy to do in general, but, as pointed out already, if
$X$ and $Y$ are independent random variables, then
$\operatorname{cov}(X,Y) = \operatorname{cov}(X^2,Y^2) = 0$.
In fact, dependence, not correlation (or lack thereof) is the
key issue. That we know that $\operatorname{cov}(X,Y)$ equals $0$
instead of some nonzero value does not, by itself, help in the
least in our efforts are determining the value of
$E\left[X^2Y^2\right]$ or $\operatorname{cov}(X^2,Y^2)$ even though it
does simplify the right sides of $(2)$ and $(3)$ a little.
When $X$ and $Y$ are dependent
random variables, then in at least one (fairly common
or fairly important) special
case, it is possible to find
the value of $E\left[X^2Y^2\right]$ relatively easily.
Suppose that $X$ and $Y$ are jointly normal random variables
with correlation coefficient $\rho$. Then, conditioned
on $X = x$, the conditional density of $Y$ is a normal
density with mean
$E[Y] + \rho\left.\left.\sqrt{\frac{\operatorname{var}(Y)}{\operatorname{var}(X)}}
\right(x-E[X]\right)$ and variance $\operatorname{var}(Y)(1-\rho^2)$. Thus,
\begin{align}E[X^2Y^2 \mid X] &= X^2E[Y^2 \mid X]\\
&= X^2\left[\operatorname{var}(Y)(1-\rho^2)
+ \left(E[Y] + \rho\left.\left.\sqrt{\frac{\operatorname{var}(Y)}{\operatorname{var}(X)}}
\right(X-E[X]\right)\right)^2\right]
\end{align}
which is a quartic function of $X$, say $g(X)$, and the Law of Iterated
Expectation tells us that
$$E[X^2Y^2] = E\left[E[X^2Y^2\mid X]\right] = E[g(X)]\tag{4}$$
where the right side of $(4)$ can be computed from knowledge of the
3rd and 4th moments of $X$ -- standard results that can be found
in many texts and reference books
(meaning that I am too lazy to look them up
and include them in this answer).
Further addendum: In a now-deleted answer, @Hydrologist gives the variance of $XY$ as
$$\mathrm{Var}\left[xy\right] = \left(\mathrm{E}\left[x\right]\right)^2\mathrm{Var}\left[y\right] + \left(\mathrm{E}\left[y\right]\right)^2\mathrm{Var}\left[x\right] + 2\mathrm{E}\left[x\right]\mathrm{Cov}\left[x,y^2\right] + 2\mathrm{E}\left[y\right]\mathrm{Cov}\left[x^2,y\right]\\ + 2\mathrm{E}\left[x\right]\mathrm{E}\left[y\right]\mathrm{Cov}\left[x,y\right] +\mathrm{Cov}\left[x^2,y^2\right] - \left(\mathrm{Cov}\left[x,y\right]\right)^2 \tag{5}$$
and claims that this formula is from two papers published a half-century ago in JASA. This formula is an incorrect transcription of the results in the paper(s) cited by Hydrologist. Specifically, $\mathrm{Cov}\left[x^2,y^2\right]$ is a mistranscription of
$E[(x-E[x])^2(y-E[y])^2]$ in the journal article, and similarly for $\mathrm{Cov}\left[x^2,y\right]$ and $\mathrm{Cov}\left[x,y^2\right]$.
|
Variance of product of dependent variables
This is an addendum to @Macro's very nice answer which lays out
exactly what needs to known in order to determine the variance of
the product of two correlated random variables. Since
\begin{align}
|
6,428
|
Bootstrapping vs Bayesian Bootstrapping conceptually?
|
The (frequentist) bootstrap takes the data as a reasonable approximation to the unknown population distribution. Therefore, the sampling distribution of a statistic (a function of the data) can be approximated by repeatedly resampling the observations with replacement and computing the statistic for each sample.
Let $y = (y_1,\ldots,y_n)$ denote the original data (In the example given, $n=5$). Let $y^b = (y_1^b, \ldots, y_n^b)$ denote a bootstrap sample. Such a sample will likely have some observations repeated one or more times and other observations will be absent. The mean of the bootstrap sample is given by $$m_b = \frac{1}{n} \sum_{i=1}^n y_i^b.$$ It is the distribution of $m_b$ over a number of bootstrap replications that is used to approximate the sampling distribution from the unknown population.
In order to understand the connection between the frequentist bootstrap and the Bayesian bootstrap, it is instructive to see how to compute $m_b$ from a different perspective.
In each bootstrap sample $y^b$, each observation $y_i$ occurs anywhere from 0 to $n$ times. Let $h_i^b$ denote the number of times $y_i$ occurs in $y^b$, and let $h^b = (h_1^b, \ldots, h_n^b)$. Thus $h_i^b \in \{0, 1, \ldots, n-1,n\}$ and $\sum_{i=1}^n h_i^b = n$. Given $h^b$, we can construct a collection of nonnegative weights that sum to one: $w^b = h^b/n$, where $w_i^b = h_i^b/n$. With this notation we can reexpress the mean of the bootstrap sample as
$$
m_b = \sum_{i=1}^n w_i^b\, y_i.
$$
The way in which the observations are chosen for a bootstrap sample determines the joint distribution for $w^b$. In particular, $h^b$ has a multinomial distribution and thus $$(n\,w^b) \sim \textsf{Multinomial}(n,(1/n)_{i=1}^n).$$ Therefore, we can compute $m_b$ by drawing $w^b$ from its distribution and computing the dot product with $y$. From this new perspective, it appears that the observations are fixed while the weights are varying.
In Bayesian inference, the observations are indeed taken as fixed, so this new perspective seems congenial to the Bayesian approach. Indeed, the calculation of the mean according to the Bayesian bootstrap differs only in the distribution of the weights. (Nevertheless, from a conceptual standpoint the Bayesian bootstrap is quite different from the frequentist version.) The data $y$ are fixed and the weights $w$ are the unknown parameters. We may be interested in some functional of the data that depends on the unknown parameters:
$$
\mu = \sum_{i=1}^n w_i\, y_i.
$$
Here is a thumbnail sketch of the model behind the Bayesian bootstrap: The sampling distribution for the observations is multinomial and the prior for the weights is a limiting Dirichlet distribution that puts all its weight on the vertices of the simplex. (Some authors refer to this model as the multinomial likelihood model.)
This model produces the following posterior distribution for the weights:
$$
w \sim \textsf{Dirichlet}(1,\ldots,1).
$$
(This distribution is flat over the simplex.) The two distributions for the weights (frequentist and Bayesian) are quite similar: They have the same means and similar covariances. The Dirichlet distribution is 'smoother' than the multinomial distribution, so the Bayesian bootstrap may be call the smoothed bootstrap. We may interpret the frequentist bootstrap as an approximation to the Bayesian bootstrap.
Given the posterior distribution for the weights, we can approximate the posterior distribution of the functional $\mu$ by repeated sampling $w$ from its Dirichlet distribution and computing the dot product with $y$.
We can adopt the framework of estimating equations
$$
\sum_{i=1}^n w_i\, g(y_i,\theta) = \underline 0,
$$
where $g(y_i,\theta)$ is a vector of estimating functions that depends on the unknown parameter (vector) $\theta$ and $\underline 0$ is a vector of zeros. If this system of equations has a unique solution for $\theta$ given $y$ and $w$, then we can compute its posterior distribution by drawing $w$ from its posterior distribution and evaluating that solution. (The framework of estimating equations is used with empirical likelihood and with generalized method of moments (GMM).)
The simplest case is the one we have already dealt with:
$$
\sum_{i=1}^n w_i\,(y_i - \mu) = 0.
$$
For the mean and the variance, $\theta = (\mu,v)$ we have
$$
g(y_i,\theta) = \begin{pmatrix}
y_i - \mu \\
(y_i - \mu)^2 - v
\end{pmatrix}.
$$
The setup is a bit more involved than that for the frequentist bootstrap, which is why a Bayesian might adopt the frequentist bootstrap as a quick approximation.
|
Bootstrapping vs Bayesian Bootstrapping conceptually?
|
The (frequentist) bootstrap takes the data as a reasonable approximation to the unknown population distribution. Therefore, the sampling distribution of a statistic (a function of the data) can be app
|
Bootstrapping vs Bayesian Bootstrapping conceptually?
The (frequentist) bootstrap takes the data as a reasonable approximation to the unknown population distribution. Therefore, the sampling distribution of a statistic (a function of the data) can be approximated by repeatedly resampling the observations with replacement and computing the statistic for each sample.
Let $y = (y_1,\ldots,y_n)$ denote the original data (In the example given, $n=5$). Let $y^b = (y_1^b, \ldots, y_n^b)$ denote a bootstrap sample. Such a sample will likely have some observations repeated one or more times and other observations will be absent. The mean of the bootstrap sample is given by $$m_b = \frac{1}{n} \sum_{i=1}^n y_i^b.$$ It is the distribution of $m_b$ over a number of bootstrap replications that is used to approximate the sampling distribution from the unknown population.
In order to understand the connection between the frequentist bootstrap and the Bayesian bootstrap, it is instructive to see how to compute $m_b$ from a different perspective.
In each bootstrap sample $y^b$, each observation $y_i$ occurs anywhere from 0 to $n$ times. Let $h_i^b$ denote the number of times $y_i$ occurs in $y^b$, and let $h^b = (h_1^b, \ldots, h_n^b)$. Thus $h_i^b \in \{0, 1, \ldots, n-1,n\}$ and $\sum_{i=1}^n h_i^b = n$. Given $h^b$, we can construct a collection of nonnegative weights that sum to one: $w^b = h^b/n$, where $w_i^b = h_i^b/n$. With this notation we can reexpress the mean of the bootstrap sample as
$$
m_b = \sum_{i=1}^n w_i^b\, y_i.
$$
The way in which the observations are chosen for a bootstrap sample determines the joint distribution for $w^b$. In particular, $h^b$ has a multinomial distribution and thus $$(n\,w^b) \sim \textsf{Multinomial}(n,(1/n)_{i=1}^n).$$ Therefore, we can compute $m_b$ by drawing $w^b$ from its distribution and computing the dot product with $y$. From this new perspective, it appears that the observations are fixed while the weights are varying.
In Bayesian inference, the observations are indeed taken as fixed, so this new perspective seems congenial to the Bayesian approach. Indeed, the calculation of the mean according to the Bayesian bootstrap differs only in the distribution of the weights. (Nevertheless, from a conceptual standpoint the Bayesian bootstrap is quite different from the frequentist version.) The data $y$ are fixed and the weights $w$ are the unknown parameters. We may be interested in some functional of the data that depends on the unknown parameters:
$$
\mu = \sum_{i=1}^n w_i\, y_i.
$$
Here is a thumbnail sketch of the model behind the Bayesian bootstrap: The sampling distribution for the observations is multinomial and the prior for the weights is a limiting Dirichlet distribution that puts all its weight on the vertices of the simplex. (Some authors refer to this model as the multinomial likelihood model.)
This model produces the following posterior distribution for the weights:
$$
w \sim \textsf{Dirichlet}(1,\ldots,1).
$$
(This distribution is flat over the simplex.) The two distributions for the weights (frequentist and Bayesian) are quite similar: They have the same means and similar covariances. The Dirichlet distribution is 'smoother' than the multinomial distribution, so the Bayesian bootstrap may be call the smoothed bootstrap. We may interpret the frequentist bootstrap as an approximation to the Bayesian bootstrap.
Given the posterior distribution for the weights, we can approximate the posterior distribution of the functional $\mu$ by repeated sampling $w$ from its Dirichlet distribution and computing the dot product with $y$.
We can adopt the framework of estimating equations
$$
\sum_{i=1}^n w_i\, g(y_i,\theta) = \underline 0,
$$
where $g(y_i,\theta)$ is a vector of estimating functions that depends on the unknown parameter (vector) $\theta$ and $\underline 0$ is a vector of zeros. If this system of equations has a unique solution for $\theta$ given $y$ and $w$, then we can compute its posterior distribution by drawing $w$ from its posterior distribution and evaluating that solution. (The framework of estimating equations is used with empirical likelihood and with generalized method of moments (GMM).)
The simplest case is the one we have already dealt with:
$$
\sum_{i=1}^n w_i\,(y_i - \mu) = 0.
$$
For the mean and the variance, $\theta = (\mu,v)$ we have
$$
g(y_i,\theta) = \begin{pmatrix}
y_i - \mu \\
(y_i - \mu)^2 - v
\end{pmatrix}.
$$
The setup is a bit more involved than that for the frequentist bootstrap, which is why a Bayesian might adopt the frequentist bootstrap as a quick approximation.
|
Bootstrapping vs Bayesian Bootstrapping conceptually?
The (frequentist) bootstrap takes the data as a reasonable approximation to the unknown population distribution. Therefore, the sampling distribution of a statistic (a function of the data) can be app
|
6,429
|
Regression coefficients that flip sign after including other predictors
|
Multicollinearity is the usual suspect as JoFrhwld mentioned. Basically, if your variables are positively correlated, then the coefficients will be negatively correlated, which can lead to a wrong sign on one of the coefficients.
One check would be to perform a principal components regression or ridge regression. This reduces the dimensionality of the regression space, handling the multicollinearity. You end up with biased estimates but a possibly lower MSE and corrected signs. Whether you go with those particular results or not, it's a good diagnostic check. If you still get sign changes, it may be theoretically interesting.
UPDATE
Following from the comment in John Christie's answer, this might be interesting. Reversal in association (magnitude or direction) are examples of Simpson's Paradox, Lord's Paradox and Suppression Effects. The differences essentially relate to the type of variable. It's more useful to understand the underlying phenomenon rather than think in terms of a particular "paradox" or effect. For a causal perspective, the paper below does a good job of explaining why and I'll quote at length their introduction and conclusion to whet your appetite.
The role of causal reasoning in understanding Simpson's paradox, Lord's paradox, and the suppression effect: covariate selection in the analysis of observational studies
Tu et al present an analysis of the equivalence of three paradoxes, concluding that all three simply reiterate the unsurprising change in the association of any two variables when a third variable is statistically controlled for. I call this unsurprising because reversal or change in magnitude is common in conditional analysis. To avoid either, we must avoid conditional analysis altogether. What is it about Simpson's and Lord's paradoxes or the suppression effect, beyond their pointing out the obvious, that attracts the intermittent and sometimes alarmist interests seen in the literature?
[...]
In conclusion, it cannot be overemphasized that although Simpson's and related paradoxes reveal the perils of using statistical criteria to guide causal analysis, they hold neither the explanations of the phenomenon they purport to depict nor the pointers on how to avoid them. The explanations and solutions lie in causal reasoning which relies on background knowledge, not statistical criteria. It is high time we stopped treating misinterpreted signs and symptoms ('paradoxes'), and got on with the business of handling the disease ('causality'). We should rightly turn our attention to the perennial problem of covariate selection for causal analysis using non-experimental data.
|
Regression coefficients that flip sign after including other predictors
|
Multicollinearity is the usual suspect as JoFrhwld mentioned. Basically, if your variables are positively correlated, then the coefficients will be negatively correlated, which can lead to a wrong si
|
Regression coefficients that flip sign after including other predictors
Multicollinearity is the usual suspect as JoFrhwld mentioned. Basically, if your variables are positively correlated, then the coefficients will be negatively correlated, which can lead to a wrong sign on one of the coefficients.
One check would be to perform a principal components regression or ridge regression. This reduces the dimensionality of the regression space, handling the multicollinearity. You end up with biased estimates but a possibly lower MSE and corrected signs. Whether you go with those particular results or not, it's a good diagnostic check. If you still get sign changes, it may be theoretically interesting.
UPDATE
Following from the comment in John Christie's answer, this might be interesting. Reversal in association (magnitude or direction) are examples of Simpson's Paradox, Lord's Paradox and Suppression Effects. The differences essentially relate to the type of variable. It's more useful to understand the underlying phenomenon rather than think in terms of a particular "paradox" or effect. For a causal perspective, the paper below does a good job of explaining why and I'll quote at length their introduction and conclusion to whet your appetite.
The role of causal reasoning in understanding Simpson's paradox, Lord's paradox, and the suppression effect: covariate selection in the analysis of observational studies
Tu et al present an analysis of the equivalence of three paradoxes, concluding that all three simply reiterate the unsurprising change in the association of any two variables when a third variable is statistically controlled for. I call this unsurprising because reversal or change in magnitude is common in conditional analysis. To avoid either, we must avoid conditional analysis altogether. What is it about Simpson's and Lord's paradoxes or the suppression effect, beyond their pointing out the obvious, that attracts the intermittent and sometimes alarmist interests seen in the literature?
[...]
In conclusion, it cannot be overemphasized that although Simpson's and related paradoxes reveal the perils of using statistical criteria to guide causal analysis, they hold neither the explanations of the phenomenon they purport to depict nor the pointers on how to avoid them. The explanations and solutions lie in causal reasoning which relies on background knowledge, not statistical criteria. It is high time we stopped treating misinterpreted signs and symptoms ('paradoxes'), and got on with the business of handling the disease ('causality'). We should rightly turn our attention to the perennial problem of covariate selection for causal analysis using non-experimental data.
|
Regression coefficients that flip sign after including other predictors
Multicollinearity is the usual suspect as JoFrhwld mentioned. Basically, if your variables are positively correlated, then the coefficients will be negatively correlated, which can lead to a wrong si
|
6,430
|
Regression coefficients that flip sign after including other predictors
|
I believe effects like these are frequently caused by collinearity (see this question). I think the book on multilevel modeling by Gelman and Hill talks about it. The problem is that IV1 is correlated with one or more of the other predictors, and when they are all included in the model, their estimation becomes erratic.
If the coefficient flipping is due to collinearity, then it's not really interesting to report, because it's not due to the relationship between your predictors to the outcome, but really due to the relationship between predictors.
What I've seen suggested to resolve this problem is residualization. First, you fit a model for IV2 ~ IV1, then take the residuals of that model as rIV2. If all of your variables are correlated, you should really residualize all of them. You may choose do to so like this
rIV2 <- resid(IV2 ~ IV1)
rIV3 <- resid(IV3 ~ IV1 + rIV2)
rIV4 <- resid(IV4 ~ IV1 + rIV2 + rIV3)
Now, fit the final model with
DV ~ IV1 + rIV2 + rIV3 + rIV4
Now, the coefficient for rIV2 represents the independent effect of IV2 given its correlation with IV1. I've heard you won't get the same result if you residualized in a different order, and that choosing the residualization order is really a judgment call within your research.
|
Regression coefficients that flip sign after including other predictors
|
I believe effects like these are frequently caused by collinearity (see this question). I think the book on multilevel modeling by Gelman and Hill talks about it. The problem is that IV1 is correlated
|
Regression coefficients that flip sign after including other predictors
I believe effects like these are frequently caused by collinearity (see this question). I think the book on multilevel modeling by Gelman and Hill talks about it. The problem is that IV1 is correlated with one or more of the other predictors, and when they are all included in the model, their estimation becomes erratic.
If the coefficient flipping is due to collinearity, then it's not really interesting to report, because it's not due to the relationship between your predictors to the outcome, but really due to the relationship between predictors.
What I've seen suggested to resolve this problem is residualization. First, you fit a model for IV2 ~ IV1, then take the residuals of that model as rIV2. If all of your variables are correlated, you should really residualize all of them. You may choose do to so like this
rIV2 <- resid(IV2 ~ IV1)
rIV3 <- resid(IV3 ~ IV1 + rIV2)
rIV4 <- resid(IV4 ~ IV1 + rIV2 + rIV3)
Now, fit the final model with
DV ~ IV1 + rIV2 + rIV3 + rIV4
Now, the coefficient for rIV2 represents the independent effect of IV2 given its correlation with IV1. I've heard you won't get the same result if you residualized in a different order, and that choosing the residualization order is really a judgment call within your research.
|
Regression coefficients that flip sign after including other predictors
I believe effects like these are frequently caused by collinearity (see this question). I think the book on multilevel modeling by Gelman and Hill talks about it. The problem is that IV1 is correlated
|
6,431
|
Regression coefficients that flip sign after including other predictors
|
See Simpson's Paradox. In short the main effect observed can reverse when an interaction is added to a model. At the linked page most of the examples are categorical but there is a figure at the top of the page one could imagine continuously. For example, if you have a categorical and continuous predictor then the continuous predictor could easily flip sign if the categorical one is added and within each category the sign is different than for the overall score.
|
Regression coefficients that flip sign after including other predictors
|
See Simpson's Paradox. In short the main effect observed can reverse when an interaction is added to a model. At the linked page most of the examples are categorical but there is a figure at the top o
|
Regression coefficients that flip sign after including other predictors
See Simpson's Paradox. In short the main effect observed can reverse when an interaction is added to a model. At the linked page most of the examples are categorical but there is a figure at the top of the page one could imagine continuously. For example, if you have a categorical and continuous predictor then the continuous predictor could easily flip sign if the categorical one is added and within each category the sign is different than for the overall score.
|
Regression coefficients that flip sign after including other predictors
See Simpson's Paradox. In short the main effect observed can reverse when an interaction is added to a model. At the linked page most of the examples are categorical but there is a figure at the top o
|
6,432
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of normality?
|
You can't really even compare the two since the Kolmogorov-Smirnov is for a completely specified distribution (so if you're testing normality, you must specify the mean and variance; they can't be estimated from the data*), while the Shapiro-Wilk is for normality, with unspecified mean and variance.
* you also can't standardize by using estimated parameters and test for standard normal; that's actually the same thing.
One way to compare would be to supplement the Shapiro-Wilk with a test for specified mean and variance in a normal (combining the tests in some manner), or by having the KS tables adjusted for the parameter estimation (but then it's no longer distribution-free).
There is such a test (equivalent to the Kolmogorov-Smirnov with estimated parameters) - the Lilliefors test; the normality-test version could be validly compared to the Shapiro-Wilk (and will generally have lower power). More competitive is the Anderson-Darling test (which must also be adjusted for parameter estimation for a comparison to be valid).
As for what they test - the KS test (and the Lilliefors) looks at the largest difference between the empirical CDF and the specified distribution, while the Shapiro Wilk effectively compares two estimates of variance; the closely related Shapiro-Francia can be regarded as a monotonic function of the squared correlation in a Q-Q plot; if I recall correctly, the Shapiro-Wilk also takes into account covariances between the order statistics.
Edited to add: While the Shapiro-Wilk nearly always beats the Lilliefors test on alternatives of interest, an example where it doesn't is the $t_{30}$ in medium-large samples ($n>60$-ish). There the Lilliefors has higher power.
[It should be kept in mind that there are many more tests for normality that are available than these.]
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of
|
You can't really even compare the two since the Kolmogorov-Smirnov is for a completely specified distribution (so if you're testing normality, you must specify the mean and variance; they can't be est
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of normality?
You can't really even compare the two since the Kolmogorov-Smirnov is for a completely specified distribution (so if you're testing normality, you must specify the mean and variance; they can't be estimated from the data*), while the Shapiro-Wilk is for normality, with unspecified mean and variance.
* you also can't standardize by using estimated parameters and test for standard normal; that's actually the same thing.
One way to compare would be to supplement the Shapiro-Wilk with a test for specified mean and variance in a normal (combining the tests in some manner), or by having the KS tables adjusted for the parameter estimation (but then it's no longer distribution-free).
There is such a test (equivalent to the Kolmogorov-Smirnov with estimated parameters) - the Lilliefors test; the normality-test version could be validly compared to the Shapiro-Wilk (and will generally have lower power). More competitive is the Anderson-Darling test (which must also be adjusted for parameter estimation for a comparison to be valid).
As for what they test - the KS test (and the Lilliefors) looks at the largest difference between the empirical CDF and the specified distribution, while the Shapiro Wilk effectively compares two estimates of variance; the closely related Shapiro-Francia can be regarded as a monotonic function of the squared correlation in a Q-Q plot; if I recall correctly, the Shapiro-Wilk also takes into account covariances between the order statistics.
Edited to add: While the Shapiro-Wilk nearly always beats the Lilliefors test on alternatives of interest, an example where it doesn't is the $t_{30}$ in medium-large samples ($n>60$-ish). There the Lilliefors has higher power.
[It should be kept in mind that there are many more tests for normality that are available than these.]
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of
You can't really even compare the two since the Kolmogorov-Smirnov is for a completely specified distribution (so if you're testing normality, you must specify the mean and variance; they can't be est
|
6,433
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of normality?
|
Briefly stated, the Shapiro-Wilk test is a specific test for normality, whereas the method used by Kolmogorov-Smirnov test is more general, but less powerful (meaning it correctly rejects the null hypothesis of normality less often). Both statistics take normality as the null and establishes a test statistic based on the sample, but how they do so is different from one another in ways that make them more or less sensitive to features of normal distributions.
How exactly W (the test statistic for Shapiro-Wilk) is calculated is a bit involved, but conceptually, it involves arraying the sample values by size and measuring fit against expected means, variances and covariances. These multiple comparisons against normality, as I understand it, give the test more power than the the Kolmogorov-Smirnov test, which is one way in which they may differ.
By contrast, the Kolmogorov-Smirnov test for normality is derived from a general approach for assessing goodness of fit by comparing the expected cumulative distribution against the empirical cumulative distribution, vis:
As such, it is sensitive at the center of the distribution, and not the tails. However, the K-S is test is convergent, in the sense that as n tends to infinity, the test converges to the true answer in probability (I believe that Glivenko-Cantelli Theorem applies here, but someone may correct me). These are two more ways in which these two tests might differ in their evaluation of normality.
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of
|
Briefly stated, the Shapiro-Wilk test is a specific test for normality, whereas the method used by Kolmogorov-Smirnov test is more general, but less powerful (meaning it correctly rejects the null hyp
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of normality?
Briefly stated, the Shapiro-Wilk test is a specific test for normality, whereas the method used by Kolmogorov-Smirnov test is more general, but less powerful (meaning it correctly rejects the null hypothesis of normality less often). Both statistics take normality as the null and establishes a test statistic based on the sample, but how they do so is different from one another in ways that make them more or less sensitive to features of normal distributions.
How exactly W (the test statistic for Shapiro-Wilk) is calculated is a bit involved, but conceptually, it involves arraying the sample values by size and measuring fit against expected means, variances and covariances. These multiple comparisons against normality, as I understand it, give the test more power than the the Kolmogorov-Smirnov test, which is one way in which they may differ.
By contrast, the Kolmogorov-Smirnov test for normality is derived from a general approach for assessing goodness of fit by comparing the expected cumulative distribution against the empirical cumulative distribution, vis:
As such, it is sensitive at the center of the distribution, and not the tails. However, the K-S is test is convergent, in the sense that as n tends to infinity, the test converges to the true answer in probability (I believe that Glivenko-Cantelli Theorem applies here, but someone may correct me). These are two more ways in which these two tests might differ in their evaluation of normality.
|
What is the difference between the Shapiro–Wilk test of normality and the Kolmogorov–Smirnov test of
Briefly stated, the Shapiro-Wilk test is a specific test for normality, whereas the method used by Kolmogorov-Smirnov test is more general, but less powerful (meaning it correctly rejects the null hyp
|
6,434
|
How to draw valid conclusions from "big data"?
|
Your fears are well founded and perceptive. Yahoo and probably several other companies are doing randomized experiments on users and doing it well. But observational data are frought with difficulties. It is a common misperception that problems diminish as the sample size increases. This is true for variance, but bias stays constant as n increases. When the bias is large, a very small truly random sample or randomized study can be more valuable than 100,000,000 observations.
|
How to draw valid conclusions from "big data"?
|
Your fears are well founded and perceptive. Yahoo and probably several other companies are doing randomized experiments on users and doing it well. But observational data are frought with difficulti
|
How to draw valid conclusions from "big data"?
Your fears are well founded and perceptive. Yahoo and probably several other companies are doing randomized experiments on users and doing it well. But observational data are frought with difficulties. It is a common misperception that problems diminish as the sample size increases. This is true for variance, but bias stays constant as n increases. When the bias is large, a very small truly random sample or randomized study can be more valuable than 100,000,000 observations.
|
How to draw valid conclusions from "big data"?
Your fears are well founded and perceptive. Yahoo and probably several other companies are doing randomized experiments on users and doing it well. But observational data are frought with difficulti
|
6,435
|
How to draw valid conclusions from "big data"?
|
There are a number of techniques in experimental design and analysis that can help you reduce your bias, but this again always boils down to the same thing: One has to know what one is doing. Big data analysis has the same problem as any other data analysis; it suffers from a lack of hypotheses.
A clear example is multiple regression with stepwise variable selection. Very nice, one say, but with 100 variables measured statistical laws dictate that some of them will show a significant relation when evaluated by looking whether the respective coefficient differs significantly from zero. So the more variables in your dataset, the more chance of finding two that show some (meaningless) relation. And the bigger your dataset, the more chance for meaningless models due to eg a small confounding effect. If you test many models (and with even only 10 variables that can be a whole lot of models), you're very likely to find at least one significant. Does it mean something? No.
What should one do then? Use your brain:
formulate a hypothesis before collecting the data and test that hypothesis. That's the only way to make sure your statistics actually tell a story.
Use your covariates to stratify your sampling before doing some tests. Stupid example: If you have 1000 males and 100 females in your dataset, randomly select 50 each if you want to talk about an average population. That's actually something where big data comes in handy: You have more than enough to sample from.
Describe the test population thoroughly, so it's clear for which population your conclusions are formulated.
If you use your big dataset for explorative purposes, test the hypotheses you come up with during this exploration on a new and different dataset, not just a subset of what you collected. And test them again using all the necessary precautions.
These things are all obvious and well-known. Heck, already in 1984 Rosenbaum and Rubin illustrated how to use propensity scores to reduce bias in observational studies, and that's what most big datasets are: observational data. In more recent work of Feng et al, the use of the Mahalanobis distance is also advocated. And in fact, one of my statistical heroes, Cochran, wrote a review about that problem already in 1973! Or what about Rubin, who introduced multivariate matched sampling and regression correcting already in 1979. Old publications are seriously underestimated and far too often ignored, certainly in a field like statistics.
All these techniques have pros and cons, and one has to understand that reducing bias is not the same as eliminating bias. But if you are aware of :
what you want to test, and
how you are doing it
Big data is not an excuse to come with bogus results.
Edited after the (correc) remark of @D.W. who pointed out I used the term 'overfitting' in a wrong context.
|
How to draw valid conclusions from "big data"?
|
There are a number of techniques in experimental design and analysis that can help you reduce your bias, but this again always boils down to the same thing: One has to know what one is doing. Big data
|
How to draw valid conclusions from "big data"?
There are a number of techniques in experimental design and analysis that can help you reduce your bias, but this again always boils down to the same thing: One has to know what one is doing. Big data analysis has the same problem as any other data analysis; it suffers from a lack of hypotheses.
A clear example is multiple regression with stepwise variable selection. Very nice, one say, but with 100 variables measured statistical laws dictate that some of them will show a significant relation when evaluated by looking whether the respective coefficient differs significantly from zero. So the more variables in your dataset, the more chance of finding two that show some (meaningless) relation. And the bigger your dataset, the more chance for meaningless models due to eg a small confounding effect. If you test many models (and with even only 10 variables that can be a whole lot of models), you're very likely to find at least one significant. Does it mean something? No.
What should one do then? Use your brain:
formulate a hypothesis before collecting the data and test that hypothesis. That's the only way to make sure your statistics actually tell a story.
Use your covariates to stratify your sampling before doing some tests. Stupid example: If you have 1000 males and 100 females in your dataset, randomly select 50 each if you want to talk about an average population. That's actually something where big data comes in handy: You have more than enough to sample from.
Describe the test population thoroughly, so it's clear for which population your conclusions are formulated.
If you use your big dataset for explorative purposes, test the hypotheses you come up with during this exploration on a new and different dataset, not just a subset of what you collected. And test them again using all the necessary precautions.
These things are all obvious and well-known. Heck, already in 1984 Rosenbaum and Rubin illustrated how to use propensity scores to reduce bias in observational studies, and that's what most big datasets are: observational data. In more recent work of Feng et al, the use of the Mahalanobis distance is also advocated. And in fact, one of my statistical heroes, Cochran, wrote a review about that problem already in 1973! Or what about Rubin, who introduced multivariate matched sampling and regression correcting already in 1979. Old publications are seriously underestimated and far too often ignored, certainly in a field like statistics.
All these techniques have pros and cons, and one has to understand that reducing bias is not the same as eliminating bias. But if you are aware of :
what you want to test, and
how you are doing it
Big data is not an excuse to come with bogus results.
Edited after the (correc) remark of @D.W. who pointed out I used the term 'overfitting' in a wrong context.
|
How to draw valid conclusions from "big data"?
There are a number of techniques in experimental design and analysis that can help you reduce your bias, but this again always boils down to the same thing: One has to know what one is doing. Big data
|
6,436
|
Why is the exponential family so important in statistics?
|
Excellent questions.
Regarding A:
A sufficient statistic is nothing more than a distillation of the information that is contained in the sample with respect to a given model. As you would expect, if you have a sample $x_i \sim N(\mu,\sigma^2)$ for $i \in \{1, \ldots, N\}$ and each independent, it is clear that so long as we calculate the sample mean and sample variance, it doesn't matter what the values of each $x_i$ are. In linear regression (easier to talk about than logistic in this context), the sampling distribution of the unknown coefficient vector (for known variance) is $N(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}, \sigma^2\mathbf{X}^\top\mathbf{X})^{-1})$, so as long as these final quantities are identical, inference based thereupon while be too. This is the idea of sufficiency.
Note that in the $N(\mu,\sigma^2)$ example, the sufficient statistic comprises of just two numbers: $\hat{\mu}=\frac{1}{N}\sum_{i=1}^N x_i$ and $\frac{1}{N}\sum_{i=1}^N (x_i-\hat{\mu})^2$, no matter how big our sample size $N$ is (and assuming $N>2$). Likewise, the vector $(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}$ is of dimension $P$ and $\sigma^2(\mathbf{X}^\top\mathbf{X})^{-1}$ of dimension $P\times P$ (here $P$ is the dimension of the design matrix), which are both independent of $N$ (though, technically, the matrix $\sigma^2(\mathbf{X}^\top\mathbf{X})^{-1}$ is just a constant under our assumptions). So in these examples, the sufficient statistic has a fixed number of values (not fixed values), or as I would put it, fixed dimension.
Let's note three more things. First, that there is no such thing as the sufficient statistic for a distribution, rather, there are many possible statistics which may be sufficient, and which may be of different dimension. Indeed, our second thing to discuss is that the entire sample itself, since it naturally contains all information contained in itself, is always a sufficient statistic. This is a trivial case, but an important one, as in general one cannot always expect to find a sufficient statistic of dimension less than $N$. And the final thing to note is model specificity: that's why I wrote with respect to a given model above. Changing your likelihood will change the sufficient statistics, at least potentially, for a given dataset.
Regarding B: What you're saying is correct, but additionally to allowing analytic posteriors in the univariate case, conjugacy has serious benefits in the context of Bayesian hierarchical models estimated via MCMC. This is because conditional posteriors are also available in closed form. So we can actually accelerate Metropolis-within-Gibbs style MCMC algos with conjugacy.
Regarding C: It's definitely a similar idea, but I do want to make clear that we're talking about two different distributions here: "posterior" versus "posterior predictive". As the name implies, both of these are posterior distributions, which means that they are distributions of an unknown variable conditioned on our known data. A "posterior" plain and simple usually refers to something like $P(\mu, \sigma^2| \{x_1, \ldots, x_N\})$ from our normal example above: a distribution of unkown parameters defined in the data generating distributions. In contrast, a "posterior predictive" gives the distribution of a hypothetical $N+1$'st data point $x_{N+1}$ conditional on the observed data: $P(x_{N+1}| \{x_1, \ldots, x_N\})$. Notice that this is not conditional on the parameters $\mu$ and $\sigma^2$: they had to be integrated out. It is this additional integral that is guaranteed by conjugacy.
Regarding D: In the context of Variational Bayes (VB), you have some posterior distribution $P(\theta|X)$ where $\theta$ is some vector of $P$ parameters and $X$ are some data. Rather than trying to generate a sample from it like MCMC, we are instead going to use an approximate posterior distribution that's easy to work with and pretty close to the true one. That's called a variational distribution and is denoted $Q_\eta(\theta)$. Notice that our variational distribution is indexed by variational parameters $\eta$. Variational parameters are nothing like the parameters we do Bayesian inference on, and are nothing like our data. They don't have a distribution associated with them and they don't have some hypothetical role generating the data. Rather, they are chosen as a result of an iterative optimization algorithm. The whole idea of variational inference is to define some measure of dissimilarity between the variational distribution and the true posterior and then minimize that measure with respect to the parameters $\eta$. We'll denote the result of that optimization process by $\hat{\eta}(X)$. At that point, hopefully $Q_{\hat{\eta}(X)}(\theta)$ is pretty close to $P(\theta|X)$, and if we do inferences using $Q_{\hat{\eta}(X)}(\theta)$ instead we'll get similar answers.
Now where does conjugacy fit in? A popular way to measure dissimilarity is this measure, which is called the reverse KL cost:
$$ \hat{\eta}(X) := \underset{\eta}{\textrm{argmin}}\, \mathbb{E}_{\theta\sim Q_\eta}\bigg[\frac{\log Q_{\eta}(\theta)}{\log P(\theta|X)}\bigg] $$
This integral cannot be solved in terms of simple functions in general. However, it is available in closed form when:
We use a conjugate prior to define $P(\theta|X)$.
We assume that variational distribution is independent, so in other words that $q_\eta(\theta)=\prod_{j=1}^P q_{j,\eta}(\theta_j)$.
We further restrict ourselves to a particular $q_{j,\eta_j}$ for each $j$ (which is determined by the likelihood).
So it's not that the variational posterior is available in closed form. Rather, it's that the cost function which defines the variational posterior is available in closed form. The cost function being closed form makes computing the variational distribution an easier optimization problem, since we can analytically compute function values and gradients.
|
Why is the exponential family so important in statistics?
|
Excellent questions.
Regarding A:
A sufficient statistic is nothing more than a distillation of the information that is contained in the sample with respect to a given model. As you would expect, if y
|
Why is the exponential family so important in statistics?
Excellent questions.
Regarding A:
A sufficient statistic is nothing more than a distillation of the information that is contained in the sample with respect to a given model. As you would expect, if you have a sample $x_i \sim N(\mu,\sigma^2)$ for $i \in \{1, \ldots, N\}$ and each independent, it is clear that so long as we calculate the sample mean and sample variance, it doesn't matter what the values of each $x_i$ are. In linear regression (easier to talk about than logistic in this context), the sampling distribution of the unknown coefficient vector (for known variance) is $N(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}, \sigma^2\mathbf{X}^\top\mathbf{X})^{-1})$, so as long as these final quantities are identical, inference based thereupon while be too. This is the idea of sufficiency.
Note that in the $N(\mu,\sigma^2)$ example, the sufficient statistic comprises of just two numbers: $\hat{\mu}=\frac{1}{N}\sum_{i=1}^N x_i$ and $\frac{1}{N}\sum_{i=1}^N (x_i-\hat{\mu})^2$, no matter how big our sample size $N$ is (and assuming $N>2$). Likewise, the vector $(\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}$ is of dimension $P$ and $\sigma^2(\mathbf{X}^\top\mathbf{X})^{-1}$ of dimension $P\times P$ (here $P$ is the dimension of the design matrix), which are both independent of $N$ (though, technically, the matrix $\sigma^2(\mathbf{X}^\top\mathbf{X})^{-1}$ is just a constant under our assumptions). So in these examples, the sufficient statistic has a fixed number of values (not fixed values), or as I would put it, fixed dimension.
Let's note three more things. First, that there is no such thing as the sufficient statistic for a distribution, rather, there are many possible statistics which may be sufficient, and which may be of different dimension. Indeed, our second thing to discuss is that the entire sample itself, since it naturally contains all information contained in itself, is always a sufficient statistic. This is a trivial case, but an important one, as in general one cannot always expect to find a sufficient statistic of dimension less than $N$. And the final thing to note is model specificity: that's why I wrote with respect to a given model above. Changing your likelihood will change the sufficient statistics, at least potentially, for a given dataset.
Regarding B: What you're saying is correct, but additionally to allowing analytic posteriors in the univariate case, conjugacy has serious benefits in the context of Bayesian hierarchical models estimated via MCMC. This is because conditional posteriors are also available in closed form. So we can actually accelerate Metropolis-within-Gibbs style MCMC algos with conjugacy.
Regarding C: It's definitely a similar idea, but I do want to make clear that we're talking about two different distributions here: "posterior" versus "posterior predictive". As the name implies, both of these are posterior distributions, which means that they are distributions of an unknown variable conditioned on our known data. A "posterior" plain and simple usually refers to something like $P(\mu, \sigma^2| \{x_1, \ldots, x_N\})$ from our normal example above: a distribution of unkown parameters defined in the data generating distributions. In contrast, a "posterior predictive" gives the distribution of a hypothetical $N+1$'st data point $x_{N+1}$ conditional on the observed data: $P(x_{N+1}| \{x_1, \ldots, x_N\})$. Notice that this is not conditional on the parameters $\mu$ and $\sigma^2$: they had to be integrated out. It is this additional integral that is guaranteed by conjugacy.
Regarding D: In the context of Variational Bayes (VB), you have some posterior distribution $P(\theta|X)$ where $\theta$ is some vector of $P$ parameters and $X$ are some data. Rather than trying to generate a sample from it like MCMC, we are instead going to use an approximate posterior distribution that's easy to work with and pretty close to the true one. That's called a variational distribution and is denoted $Q_\eta(\theta)$. Notice that our variational distribution is indexed by variational parameters $\eta$. Variational parameters are nothing like the parameters we do Bayesian inference on, and are nothing like our data. They don't have a distribution associated with them and they don't have some hypothetical role generating the data. Rather, they are chosen as a result of an iterative optimization algorithm. The whole idea of variational inference is to define some measure of dissimilarity between the variational distribution and the true posterior and then minimize that measure with respect to the parameters $\eta$. We'll denote the result of that optimization process by $\hat{\eta}(X)$. At that point, hopefully $Q_{\hat{\eta}(X)}(\theta)$ is pretty close to $P(\theta|X)$, and if we do inferences using $Q_{\hat{\eta}(X)}(\theta)$ instead we'll get similar answers.
Now where does conjugacy fit in? A popular way to measure dissimilarity is this measure, which is called the reverse KL cost:
$$ \hat{\eta}(X) := \underset{\eta}{\textrm{argmin}}\, \mathbb{E}_{\theta\sim Q_\eta}\bigg[\frac{\log Q_{\eta}(\theta)}{\log P(\theta|X)}\bigg] $$
This integral cannot be solved in terms of simple functions in general. However, it is available in closed form when:
We use a conjugate prior to define $P(\theta|X)$.
We assume that variational distribution is independent, so in other words that $q_\eta(\theta)=\prod_{j=1}^P q_{j,\eta}(\theta_j)$.
We further restrict ourselves to a particular $q_{j,\eta_j}$ for each $j$ (which is determined by the likelihood).
So it's not that the variational posterior is available in closed form. Rather, it's that the cost function which defines the variational posterior is available in closed form. The cost function being closed form makes computing the variational distribution an easier optimization problem, since we can analytically compute function values and gradients.
|
Why is the exponential family so important in statistics?
Excellent questions.
Regarding A:
A sufficient statistic is nothing more than a distillation of the information that is contained in the sample with respect to a given model. As you would expect, if y
|
6,437
|
Why is the exponential family so important in statistics?
|
Since I do not see the result mentioned on that thread so far, let me mention an often neglected if significant issue, namely that, concerning question A, exponential families are closely linked with the notion of sufficiency due to the Pitman-Koopman-Darmois lemma:
Suppose $X_n$ , $n = 1 , 2 , 3 , \dots$ are independent identically
distributed random variables whose distribution is known to be in some
family of probability distributions with fixed support. Only if that
family is an exponential family there is a sufficient statistic
(possibly vector-valued) $\displaystyle T(X_{1},\dots ,X_{n})$ whose
number of scalar components does not increase as the sample size $n$
increases. Wikipedia
In short, there is no fixed-support family outside the exponential families that enjoys a fixed dimension sufficient statistic.
And while I am at it, point B is not a compelling argument as closed-form expressions are not a strong argument for defining a prior distribution that reflects one's prior beliefs. Furthermore, there exist exponential families whose conjugates are not manageable, witness the Beta distribution. Conjugates are thus better seen as handy approximations in the spirit of question D.
|
Why is the exponential family so important in statistics?
|
Since I do not see the result mentioned on that thread so far, let me mention an often neglected if significant issue, namely that, concerning question A, exponential families are closely linked with
|
Why is the exponential family so important in statistics?
Since I do not see the result mentioned on that thread so far, let me mention an often neglected if significant issue, namely that, concerning question A, exponential families are closely linked with the notion of sufficiency due to the Pitman-Koopman-Darmois lemma:
Suppose $X_n$ , $n = 1 , 2 , 3 , \dots$ are independent identically
distributed random variables whose distribution is known to be in some
family of probability distributions with fixed support. Only if that
family is an exponential family there is a sufficient statistic
(possibly vector-valued) $\displaystyle T(X_{1},\dots ,X_{n})$ whose
number of scalar components does not increase as the sample size $n$
increases. Wikipedia
In short, there is no fixed-support family outside the exponential families that enjoys a fixed dimension sufficient statistic.
And while I am at it, point B is not a compelling argument as closed-form expressions are not a strong argument for defining a prior distribution that reflects one's prior beliefs. Furthermore, there exist exponential families whose conjugates are not manageable, witness the Beta distribution. Conjugates are thus better seen as handy approximations in the spirit of question D.
|
Why is the exponential family so important in statistics?
Since I do not see the result mentioned on that thread so far, let me mention an often neglected if significant issue, namely that, concerning question A, exponential families are closely linked with
|
6,438
|
Why is the exponential family so important in statistics?
|
Great questions. There are lots of ways to answer these. John Madden does an excellent job, but I'm going to crib a little bit from Ben's answer here regarding sufficient statistics.
The loss function for a Gaussian linear model (as Ben notes) is
$$ \ell_{\mathbf{y}, \mathbf{x}}(\boldsymbol{\beta}, \sigma)=-n \ln \sigma-\frac{1}{2 \sigma^{2}}\|\mathbf{y}-\mathbf{x} \boldsymbol{\beta}\|^{2}$$
In a lot of pedagogical material on fitting models, we would use the data to compute gradients of the loss and perform some sort of optimization routine. Some code to do this might look like
def compute_loss(beta, X, y):
number_rows = len(X)
loss = 0
# Potentially expensive!
for i in range(number_rows):
loss += (y[i] - X[i]@beta)**2
loss/=number_rows
return loss
If we have lots of data, then this loop (and any additional iterations over the data to compute gradients, for example) might be expensive to compute. But, because we can write down sufficient statistics for the exponential family, we can improve our computation drastically.
As Ben writes, the loss can be rewritten as
$$
\begin{aligned}
&=-n \ln \sigma-\frac{1}{2 \sigma^{2}} \mathbf{y}^{\mathrm{T}} \mathbf{y}-\frac{1}{2 \sigma^{2}}\left(2 \boldsymbol{\beta}^{\mathrm{T}} \mathbf{T}_{1}-\boldsymbol{\beta}^{\mathrm{T}} \mathbf{T}_{2} \boldsymbol{\beta}\right) \\
&=h(\mathbf{y}, \sigma)+g_{\beta}\left(\mathbf{T}_{1}, \mathbf{T}_{2}, \sigma\right)
\end{aligned}
$$
Where $\mathbf{T}_{1} \equiv \mathbf{T}_{1}(\mathbf{x}, \mathbf{y}) \equiv \mathbf{x}^{\mathrm{T}} \mathbf{y}$ and $\mathbf{T}_{2} \equiv \mathbf{T}_{2}(\mathbf{x}, \mathbf{y}) \equiv \mathbf{x}^{\mathrm{T}} \mathbf{x}$. We can thus compute these quantities one time and fit our models, as opposed to recomputing them at each update step.
Let's compare on a simulated problem. I will assume $\sigma=1$ and does not require estimation for simplicity. I'll vary the number of observations and the number of covariates in the model and compare the time to optimize the loss assuming when using sufficient stats and when using a naive approach. Shown below is a plot of the expected time to completion plus/minus a standard deviation. We can see that as the data become larger in size, using sufficient statistics is advantageous.
Now, this whole answer is a bit of a straw man. I've not shown you the results when not using sufficient statistics and not using loops (so maybe leveraging some linear algebra). But the point about sufficient statistics remains. That we can represent all the information in a sample with a single number, computed once, is a very valuable property to have.
Code to reproduce experiments:
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from itertools import product
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="darkgrid")
# First, simulate big data!
def make_data(N, p):
X = np.random.normal(size = (N,p))
beta = np.random.normal(2, 2, size = p)
y = X@beta + np.random.normal(size = N)
return X,y
# Next, set up a loss function to optimize using loops
def solve_naive(N, p):
X, y = make_data(N, p)
def loss_and_grad(w):
number_rows, number_columns = X.shape
grads = np.zeros_like(w)
loss=0
for i in range(number_rows):
res= (y[i] - X[i]@w)
loss+= res**2/number_rows
grads+= -2*res*X[i]/number_rows
return loss, grads
r=minimize(loss_and_grad, x0=np.zeros(p), jac=True)
return loss_and_grad
# Next, set up a loss function to opimize which only uses sufficient statistics
def solve_sufficient(N, p):
X, y = make_data(N, p)
T1 = X.T@y
T2 = X.T@X
const = y.T@y
n = len(X)
def loss_and_grad(w):
loss = const - (2*w@T1 - w@T2@w)
grads = -2*T1 + (T2@w + T2.T@w)
return loss/n, grads/n
r=minimize(loss_and_grad, x0=np.zeros(p), jac=True)
return loss_and_grad
# A helper function to time the optimization for various datasets
def time_to_optimize(N, p):
naive_optimization_times = %timeit -o -n 10 solve_naive(N, p)
suff_optimization_times = %timeit -o -n 10 solve_sufficient(N, p)
suff = pd.DataFrame({'times':suff_optimization_times.timings,
'type': 'Sufficient Statistics'})
naive = pd.DataFrame({'times':naive_optimization_times.timings,
'type': 'Naive'})
df = pd.concat((suff, naive))
df['N'] = N
df['p'] = p
return df
if __name__ == '__main__':
Ns = [1_000, 10_000, 100_000]
ps = [10, 100, 250]
prods = product(Ns, ps)
frames = []
for N, p in prods:
frames.append(time_to_optimize(N, p))
df = pd.concat(frames).reset_index(drop=True)
fig, ax = plt.subplots(dpi = 240, figsize = (8, 5))
grid = sns.lineplot(data=df, x='N', y='times', hue='type', style='p')
grid.set(xscale="log", yscale="log", xlabel = 'Number of Observations', ylabel='Execution Time (Seconds)')
grid.legend(loc='best', prop = {'size':6})
|
Why is the exponential family so important in statistics?
|
Great questions. There are lots of ways to answer these. John Madden does an excellent job, but I'm going to crib a little bit from Ben's answer here regarding sufficient statistics.
The loss functio
|
Why is the exponential family so important in statistics?
Great questions. There are lots of ways to answer these. John Madden does an excellent job, but I'm going to crib a little bit from Ben's answer here regarding sufficient statistics.
The loss function for a Gaussian linear model (as Ben notes) is
$$ \ell_{\mathbf{y}, \mathbf{x}}(\boldsymbol{\beta}, \sigma)=-n \ln \sigma-\frac{1}{2 \sigma^{2}}\|\mathbf{y}-\mathbf{x} \boldsymbol{\beta}\|^{2}$$
In a lot of pedagogical material on fitting models, we would use the data to compute gradients of the loss and perform some sort of optimization routine. Some code to do this might look like
def compute_loss(beta, X, y):
number_rows = len(X)
loss = 0
# Potentially expensive!
for i in range(number_rows):
loss += (y[i] - X[i]@beta)**2
loss/=number_rows
return loss
If we have lots of data, then this loop (and any additional iterations over the data to compute gradients, for example) might be expensive to compute. But, because we can write down sufficient statistics for the exponential family, we can improve our computation drastically.
As Ben writes, the loss can be rewritten as
$$
\begin{aligned}
&=-n \ln \sigma-\frac{1}{2 \sigma^{2}} \mathbf{y}^{\mathrm{T}} \mathbf{y}-\frac{1}{2 \sigma^{2}}\left(2 \boldsymbol{\beta}^{\mathrm{T}} \mathbf{T}_{1}-\boldsymbol{\beta}^{\mathrm{T}} \mathbf{T}_{2} \boldsymbol{\beta}\right) \\
&=h(\mathbf{y}, \sigma)+g_{\beta}\left(\mathbf{T}_{1}, \mathbf{T}_{2}, \sigma\right)
\end{aligned}
$$
Where $\mathbf{T}_{1} \equiv \mathbf{T}_{1}(\mathbf{x}, \mathbf{y}) \equiv \mathbf{x}^{\mathrm{T}} \mathbf{y}$ and $\mathbf{T}_{2} \equiv \mathbf{T}_{2}(\mathbf{x}, \mathbf{y}) \equiv \mathbf{x}^{\mathrm{T}} \mathbf{x}$. We can thus compute these quantities one time and fit our models, as opposed to recomputing them at each update step.
Let's compare on a simulated problem. I will assume $\sigma=1$ and does not require estimation for simplicity. I'll vary the number of observations and the number of covariates in the model and compare the time to optimize the loss assuming when using sufficient stats and when using a naive approach. Shown below is a plot of the expected time to completion plus/minus a standard deviation. We can see that as the data become larger in size, using sufficient statistics is advantageous.
Now, this whole answer is a bit of a straw man. I've not shown you the results when not using sufficient statistics and not using loops (so maybe leveraging some linear algebra). But the point about sufficient statistics remains. That we can represent all the information in a sample with a single number, computed once, is a very valuable property to have.
Code to reproduce experiments:
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from itertools import product
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="darkgrid")
# First, simulate big data!
def make_data(N, p):
X = np.random.normal(size = (N,p))
beta = np.random.normal(2, 2, size = p)
y = X@beta + np.random.normal(size = N)
return X,y
# Next, set up a loss function to optimize using loops
def solve_naive(N, p):
X, y = make_data(N, p)
def loss_and_grad(w):
number_rows, number_columns = X.shape
grads = np.zeros_like(w)
loss=0
for i in range(number_rows):
res= (y[i] - X[i]@w)
loss+= res**2/number_rows
grads+= -2*res*X[i]/number_rows
return loss, grads
r=minimize(loss_and_grad, x0=np.zeros(p), jac=True)
return loss_and_grad
# Next, set up a loss function to opimize which only uses sufficient statistics
def solve_sufficient(N, p):
X, y = make_data(N, p)
T1 = X.T@y
T2 = X.T@X
const = y.T@y
n = len(X)
def loss_and_grad(w):
loss = const - (2*w@T1 - w@T2@w)
grads = -2*T1 + (T2@w + T2.T@w)
return loss/n, grads/n
r=minimize(loss_and_grad, x0=np.zeros(p), jac=True)
return loss_and_grad
# A helper function to time the optimization for various datasets
def time_to_optimize(N, p):
naive_optimization_times = %timeit -o -n 10 solve_naive(N, p)
suff_optimization_times = %timeit -o -n 10 solve_sufficient(N, p)
suff = pd.DataFrame({'times':suff_optimization_times.timings,
'type': 'Sufficient Statistics'})
naive = pd.DataFrame({'times':naive_optimization_times.timings,
'type': 'Naive'})
df = pd.concat((suff, naive))
df['N'] = N
df['p'] = p
return df
if __name__ == '__main__':
Ns = [1_000, 10_000, 100_000]
ps = [10, 100, 250]
prods = product(Ns, ps)
frames = []
for N, p in prods:
frames.append(time_to_optimize(N, p))
df = pd.concat(frames).reset_index(drop=True)
fig, ax = plt.subplots(dpi = 240, figsize = (8, 5))
grid = sns.lineplot(data=df, x='N', y='times', hue='type', style='p')
grid.set(xscale="log", yscale="log", xlabel = 'Number of Observations', ylabel='Execution Time (Seconds)')
grid.legend(loc='best', prop = {'size':6})
|
Why is the exponential family so important in statistics?
Great questions. There are lots of ways to answer these. John Madden does an excellent job, but I'm going to crib a little bit from Ben's answer here regarding sufficient statistics.
The loss functio
|
6,439
|
Why is the exponential family so important in statistics?
|
None of the properties that OP mentions were important when the most popular exponential family distributions were discovered or were put in use. That is not to say that the properties are irrelevant or not important. These are all interesting and useful features, but these are not the reasons for popularity of the distributions. Distributions such as Gaussian and Poisson became popular because they are ubiquitous in nature, and also approximate very well processes in engineering and the industry.
Poisson.
Here's one example: Poisson distribution. It and its related distributions, such as exponential distribution, are observed in radioactive decay phenomenon. Not only it is simply convenient to approximate the observed data with them, but they arise from the theory of radioactive decay in their exact form, and the observations are consistent with equations beyond any doubt with arbitrary precision limited only by the precision of our instrumentation. This has been discovered in early 20th century and ever increasing precision of measurements has not produced any deviation from the exact equations. At this point it's simply a fact that Poisson distribution explains the number of decaying nuclei in a given period of time, and that time between two events is from exponential distribution.
Gaussian. Gaussian distribution is observed in numerous natural phenomena, e.g. Brownian motion. I gave an exotic example in my comment to the question: Heisenberg's uncertainty principle (UP) from quantum mechanics (QM).
The first thing to note here is that physicists so far failed to find any deviation from QM finding. The precision with which it's confirmed to work is mind boggling and unprecedented in any field of study in sciences. So, you can safely accept UP as a fact of nature.
In its simple form it states that the uncertainties about the measurement of the moment and coordinate of a particle simultaneously has a lower limit:$$\Delta p\Delta x\ge h/4\pi$$
If you measure the coordinate very precisely, then the moment measurement will be very imprecise etc.
But when does the inequality become equality $\Delta p\Delta x= h/4\pi$? For a Gaussian wave packet!
We don't always have a choice. In the above examples we do not pick Poisson or Gaussian because they have some nice statistical properties. We use them because we must use them. That's how nature works, and if we want to describe the observed phenomena then we don't have choice but to use these distributions regardless of their convenience or elegance.
|
Why is the exponential family so important in statistics?
|
None of the properties that OP mentions were important when the most popular exponential family distributions were discovered or were put in use. That is not to say that the properties are irrelevant
|
Why is the exponential family so important in statistics?
None of the properties that OP mentions were important when the most popular exponential family distributions were discovered or were put in use. That is not to say that the properties are irrelevant or not important. These are all interesting and useful features, but these are not the reasons for popularity of the distributions. Distributions such as Gaussian and Poisson became popular because they are ubiquitous in nature, and also approximate very well processes in engineering and the industry.
Poisson.
Here's one example: Poisson distribution. It and its related distributions, such as exponential distribution, are observed in radioactive decay phenomenon. Not only it is simply convenient to approximate the observed data with them, but they arise from the theory of radioactive decay in their exact form, and the observations are consistent with equations beyond any doubt with arbitrary precision limited only by the precision of our instrumentation. This has been discovered in early 20th century and ever increasing precision of measurements has not produced any deviation from the exact equations. At this point it's simply a fact that Poisson distribution explains the number of decaying nuclei in a given period of time, and that time between two events is from exponential distribution.
Gaussian. Gaussian distribution is observed in numerous natural phenomena, e.g. Brownian motion. I gave an exotic example in my comment to the question: Heisenberg's uncertainty principle (UP) from quantum mechanics (QM).
The first thing to note here is that physicists so far failed to find any deviation from QM finding. The precision with which it's confirmed to work is mind boggling and unprecedented in any field of study in sciences. So, you can safely accept UP as a fact of nature.
In its simple form it states that the uncertainties about the measurement of the moment and coordinate of a particle simultaneously has a lower limit:$$\Delta p\Delta x\ge h/4\pi$$
If you measure the coordinate very precisely, then the moment measurement will be very imprecise etc.
But when does the inequality become equality $\Delta p\Delta x= h/4\pi$? For a Gaussian wave packet!
We don't always have a choice. In the above examples we do not pick Poisson or Gaussian because they have some nice statistical properties. We use them because we must use them. That's how nature works, and if we want to describe the observed phenomena then we don't have choice but to use these distributions regardless of their convenience or elegance.
|
Why is the exponential family so important in statistics?
None of the properties that OP mentions were important when the most popular exponential family distributions were discovered or were put in use. That is not to say that the properties are irrelevant
|
6,440
|
Why is the exponential family so important in statistics?
|
Regarding a point you raise in A: the sufficient statistic for the parameters $\beta$ of a logistic regression - that's a good question. There is no analytical solution to Logistic regression, only numerical. So, calling the final solution a function of the data $T(X,y)$ is a bit of a stretch to the definition of a function. It's true that you use the data in the fitting process - and technically you need only $X$ and $X^Ty$ - but there are other considerations: like the fitting algorithm (do you use Fisher-Scoring? Gradient Ascent? What threshold do you use? What learning step for the gradient?) Maybe others can answer if there is such a thing as a sufficient statistic for the logistic regression model.
Regarding point D: one of the main algorithms for Variational Inference (VI) / Variational Bayes - is called CAVI - Coordinate Ascent VI. It uses the "mean field" approximation (what John Madden called "Independent") $q(z)=\prod_j q_j(z_j)$. The CAVI update rule says that for each coordinate of the parameter, you update the variational distribution to be $q_j(z_j)\propto e^{\mathbb E_{-j}[\log p(z_j|z_{-j},x)]}$. This can be hard and require quite a lot of analytical work to find out what is this distribution, and what are it's parameters (take expectation on all other variational distributions, etc.). If you further assume that each "complete conditional" $p(z_j | x, z_{-j})$ is in the expo. family, the algorithm simplifies: the variational distributions have the same exponential family form as their complete-conditionals counterparts, and the update rule becomes simply updating the natural parameters of that family, $\theta_j$, by setting $\theta_j=\mathbb E_{-j}[\theta_{-j}]$ (where $\theta_{-j}$ will be a function of the conditioning set $x,z_{-j}$). For more information check sections 4.1 and 4.2 in "Variational Inference: A Review for Statisticians" here.
|
Why is the exponential family so important in statistics?
|
Regarding a point you raise in A: the sufficient statistic for the parameters $\beta$ of a logistic regression - that's a good question. There is no analytical solution to Logistic regression, only nu
|
Why is the exponential family so important in statistics?
Regarding a point you raise in A: the sufficient statistic for the parameters $\beta$ of a logistic regression - that's a good question. There is no analytical solution to Logistic regression, only numerical. So, calling the final solution a function of the data $T(X,y)$ is a bit of a stretch to the definition of a function. It's true that you use the data in the fitting process - and technically you need only $X$ and $X^Ty$ - but there are other considerations: like the fitting algorithm (do you use Fisher-Scoring? Gradient Ascent? What threshold do you use? What learning step for the gradient?) Maybe others can answer if there is such a thing as a sufficient statistic for the logistic regression model.
Regarding point D: one of the main algorithms for Variational Inference (VI) / Variational Bayes - is called CAVI - Coordinate Ascent VI. It uses the "mean field" approximation (what John Madden called "Independent") $q(z)=\prod_j q_j(z_j)$. The CAVI update rule says that for each coordinate of the parameter, you update the variational distribution to be $q_j(z_j)\propto e^{\mathbb E_{-j}[\log p(z_j|z_{-j},x)]}$. This can be hard and require quite a lot of analytical work to find out what is this distribution, and what are it's parameters (take expectation on all other variational distributions, etc.). If you further assume that each "complete conditional" $p(z_j | x, z_{-j})$ is in the expo. family, the algorithm simplifies: the variational distributions have the same exponential family form as their complete-conditionals counterparts, and the update rule becomes simply updating the natural parameters of that family, $\theta_j$, by setting $\theta_j=\mathbb E_{-j}[\theta_{-j}]$ (where $\theta_{-j}$ will be a function of the conditioning set $x,z_{-j}$). For more information check sections 4.1 and 4.2 in "Variational Inference: A Review for Statisticians" here.
|
Why is the exponential family so important in statistics?
Regarding a point you raise in A: the sufficient statistic for the parameters $\beta$ of a logistic regression - that's a good question. There is no analytical solution to Logistic regression, only nu
|
6,441
|
Step-by-step example of reverse-mode automatic differentiation
|
Let's say we have expression $z = x_1x_2 + \sin(x_1)$ and want to find derivatives $\frac{dz}{dx_1}$ and $\frac{dz}{dx_2}$. Reverse-mode AD splits this task into 2 parts, namely, forward and reverse passes.
Forward pass
First, we decompose our complex expression into a set of primitive ones, i.e. expressions consisting of at most single function call. Note that I also rename input and output variables for consistency, though it's not necessary:
$$w_1 = x_1$$
$$w_2 = x_2$$
$$w_3 = w_1w_2$$
$$w_4 = \sin(w_1)$$
$$w_5 = w_3 + w_4$$
$$z = w_5$$
The advantage of this representation is that differentiation rules for each separate expression are already known. For example, we know that derivative of $\sin$ is $\cos$, and so $\frac{dw_4}{dw_1} = \cos(w_1)$. We will use this fact in reverse pass below.
Essentially, forward pass consists of evaluating each of these expressions and saving the results. Say, our inputs are: $x_1 = 2$ and $x_2 = 3$. Then we have:
$$w_1 = x_1 = 2$$
$$w_2 = x_2 = 3$$
$$w_3 = w_1w_2 = 6$$
$$w_4 = \sin(w_1) ~= 0.9$$
$$w_5 = w_3 + w_4 = 6.9$$
$$z = w_5 = 6.9$$
Reverse pass
This is were the magic starts, and it starts with the chain rule. In its basic form, chain rule states that if you have variable $t(u(v))$ which depends on $u$ which, in its turn, depends on $v$, then:
$$\frac{dt}{dv} = \frac{dt}{du}\frac{du}{dv}$$
or, if $t$ depends on $v$ via several paths / variables $u_i$, e.g.:
$$u_1 = f(v)$$
$$u_2 = g(v)$$
$$t = h(u_1, u_2)$$
then (see proof here):
$$\frac{dt}{dv} = \sum_i \frac{dt}{du_i}\frac{du_i}{dv}$$
In terms of expression graph, if we have a final node $z$ and input nodes $w_i$, and path from $z$ to $w_i$ goes through intermediate nodes $w_p$ (i.e. $z = g(w_p)$ where $w_p = f(w_i)$), we can find derivative $\frac{dz}{dw_i}$ as
$$\frac{dz}{dw_i} = \sum_{p \in parents(i)} \frac{dz}{dw_p} \frac{dw_p}{dw_i}$$
In other words, to calculate the derivative of output variable $z$ w.r.t. any intermediate or input variable $w_i$, we only need to know the derivatives of its parents and the formula to calculate derivative of primitive expression $w_p = f(w_i)$.
Reverse pass starts at the end (i.e. $\frac{dz}{dz}$) and propagates backward to all dependencies. Here we have (expression for "seed"):
$$\frac{dz}{dz} = 1$$
That may be read as "change in $z$ results in exactly the same change in $z$", which is quite obvious.
Then we know that $z = w_5$ and so:
$$\frac{dz}{dw_5} = 1$$
$w_5$ linearly depends on $w_3$ and $w_4$, so $\frac{dw_5}{dw_3} = 1$ and $\frac{dw_5}{dw_4} = 1$. Using the chain rule we find:
$$\frac{dz}{dw_3} = \frac{dz}{dw_5} \frac{dw_5}{dw_3} = 1 \times 1 = 1$$
$$\frac{dz}{dw_4} = \frac{dz}{dw_5} \frac{dw_5}{dw_4} = 1 \times 1 = 1$$
From definition $w_3 = w_1w_2$ and rules of partial derivatives, we find that $\frac{dw_3}{dw_2} = w_1$. Thus:
$$\frac{dz}{dw_2} = \frac{dz}{dw_3} \frac{dw_3}{dw_2} = 1 \times w_1 = w_1$$
Which, as we already know from forward pass, is:
$$\frac{dz}{dw_2} = w_1 = 2$$
Finally, $w_1$ contributes to $z$ via $w_3$ and $w_4$. Once again, from the rules of partial derivatives we know that $\frac{dw_3}{dw_1} = w_2$ and $\frac{dw_4}{dw_1} = \cos(w_1)$. Thus:
$$\frac{dz}{dw_1} = \frac{dz}{dw_3} \frac{dw_3}{dw_1} + \frac{dz}{dw_4} \frac{dw_4}{dw_1} = w_2 + \cos(w_1)$$
And again, given known inputs, we can calculate it:
$$\frac{dz}{dw_1} = w_2 + \cos(w_1) = 3 + \cos(2) ~= 2.58$$
Since $w_1$ and $w_2$ are just aliases for $x_1$ and $x_2$, we get our answer:
$$\frac{dz}{dx_1} = 2.58$$
$$\frac{dz}{dx_2} = 2$$
And that's it!
This description concerns only scalar inputs, i.e. numbers, but in fact it can also be applied to multidimensional arrays such as vectors and matrices. Two things that one should keep in mind when differentiating expressions with such objects:
Derivatives may have much higher dimensionality than inputs or output, e.g. derivative of vector w.r.t. vector is a matrix and derivative of matrix w.r.t. matrix is a 4-dimensional array (sometimes referred to as a tensor). In many cases such derivatives are very sparse.
Each component in output array is an independent function of 1 or more components of input array(s). E.g. if $y = f(x)$ and both $x$ and $y$ are vectors, $y_i$ never depends on $y_j$, but only on subset of $x_k$. In particular, this means that finding derivative $\frac{dy_i}{dx_j}$ boils down to tracking how $y_i$ depends on $x_j$.
The power of automatic differentiation is that it can deal with complicated structures from programming languages like conditions and loops. However, if all you need is algebraic expressions and you have good enough framework to work with symbolic representations, it's possible to construct fully symbolic expressions. In fact, in this example we could produce expression $\frac{dz}{dw_1} = w_2 + \cos(w_1) = x_2 + \cos(x_1)$ and calculate this derivative for whatever inputs we want.
|
Step-by-step example of reverse-mode automatic differentiation
|
Let's say we have expression $z = x_1x_2 + \sin(x_1)$ and want to find derivatives $\frac{dz}{dx_1}$ and $\frac{dz}{dx_2}$. Reverse-mode AD splits this task into 2 parts, namely, forward and reverse p
|
Step-by-step example of reverse-mode automatic differentiation
Let's say we have expression $z = x_1x_2 + \sin(x_1)$ and want to find derivatives $\frac{dz}{dx_1}$ and $\frac{dz}{dx_2}$. Reverse-mode AD splits this task into 2 parts, namely, forward and reverse passes.
Forward pass
First, we decompose our complex expression into a set of primitive ones, i.e. expressions consisting of at most single function call. Note that I also rename input and output variables for consistency, though it's not necessary:
$$w_1 = x_1$$
$$w_2 = x_2$$
$$w_3 = w_1w_2$$
$$w_4 = \sin(w_1)$$
$$w_5 = w_3 + w_4$$
$$z = w_5$$
The advantage of this representation is that differentiation rules for each separate expression are already known. For example, we know that derivative of $\sin$ is $\cos$, and so $\frac{dw_4}{dw_1} = \cos(w_1)$. We will use this fact in reverse pass below.
Essentially, forward pass consists of evaluating each of these expressions and saving the results. Say, our inputs are: $x_1 = 2$ and $x_2 = 3$. Then we have:
$$w_1 = x_1 = 2$$
$$w_2 = x_2 = 3$$
$$w_3 = w_1w_2 = 6$$
$$w_4 = \sin(w_1) ~= 0.9$$
$$w_5 = w_3 + w_4 = 6.9$$
$$z = w_5 = 6.9$$
Reverse pass
This is were the magic starts, and it starts with the chain rule. In its basic form, chain rule states that if you have variable $t(u(v))$ which depends on $u$ which, in its turn, depends on $v$, then:
$$\frac{dt}{dv} = \frac{dt}{du}\frac{du}{dv}$$
or, if $t$ depends on $v$ via several paths / variables $u_i$, e.g.:
$$u_1 = f(v)$$
$$u_2 = g(v)$$
$$t = h(u_1, u_2)$$
then (see proof here):
$$\frac{dt}{dv} = \sum_i \frac{dt}{du_i}\frac{du_i}{dv}$$
In terms of expression graph, if we have a final node $z$ and input nodes $w_i$, and path from $z$ to $w_i$ goes through intermediate nodes $w_p$ (i.e. $z = g(w_p)$ where $w_p = f(w_i)$), we can find derivative $\frac{dz}{dw_i}$ as
$$\frac{dz}{dw_i} = \sum_{p \in parents(i)} \frac{dz}{dw_p} \frac{dw_p}{dw_i}$$
In other words, to calculate the derivative of output variable $z$ w.r.t. any intermediate or input variable $w_i$, we only need to know the derivatives of its parents and the formula to calculate derivative of primitive expression $w_p = f(w_i)$.
Reverse pass starts at the end (i.e. $\frac{dz}{dz}$) and propagates backward to all dependencies. Here we have (expression for "seed"):
$$\frac{dz}{dz} = 1$$
That may be read as "change in $z$ results in exactly the same change in $z$", which is quite obvious.
Then we know that $z = w_5$ and so:
$$\frac{dz}{dw_5} = 1$$
$w_5$ linearly depends on $w_3$ and $w_4$, so $\frac{dw_5}{dw_3} = 1$ and $\frac{dw_5}{dw_4} = 1$. Using the chain rule we find:
$$\frac{dz}{dw_3} = \frac{dz}{dw_5} \frac{dw_5}{dw_3} = 1 \times 1 = 1$$
$$\frac{dz}{dw_4} = \frac{dz}{dw_5} \frac{dw_5}{dw_4} = 1 \times 1 = 1$$
From definition $w_3 = w_1w_2$ and rules of partial derivatives, we find that $\frac{dw_3}{dw_2} = w_1$. Thus:
$$\frac{dz}{dw_2} = \frac{dz}{dw_3} \frac{dw_3}{dw_2} = 1 \times w_1 = w_1$$
Which, as we already know from forward pass, is:
$$\frac{dz}{dw_2} = w_1 = 2$$
Finally, $w_1$ contributes to $z$ via $w_3$ and $w_4$. Once again, from the rules of partial derivatives we know that $\frac{dw_3}{dw_1} = w_2$ and $\frac{dw_4}{dw_1} = \cos(w_1)$. Thus:
$$\frac{dz}{dw_1} = \frac{dz}{dw_3} \frac{dw_3}{dw_1} + \frac{dz}{dw_4} \frac{dw_4}{dw_1} = w_2 + \cos(w_1)$$
And again, given known inputs, we can calculate it:
$$\frac{dz}{dw_1} = w_2 + \cos(w_1) = 3 + \cos(2) ~= 2.58$$
Since $w_1$ and $w_2$ are just aliases for $x_1$ and $x_2$, we get our answer:
$$\frac{dz}{dx_1} = 2.58$$
$$\frac{dz}{dx_2} = 2$$
And that's it!
This description concerns only scalar inputs, i.e. numbers, but in fact it can also be applied to multidimensional arrays such as vectors and matrices. Two things that one should keep in mind when differentiating expressions with such objects:
Derivatives may have much higher dimensionality than inputs or output, e.g. derivative of vector w.r.t. vector is a matrix and derivative of matrix w.r.t. matrix is a 4-dimensional array (sometimes referred to as a tensor). In many cases such derivatives are very sparse.
Each component in output array is an independent function of 1 or more components of input array(s). E.g. if $y = f(x)$ and both $x$ and $y$ are vectors, $y_i$ never depends on $y_j$, but only on subset of $x_k$. In particular, this means that finding derivative $\frac{dy_i}{dx_j}$ boils down to tracking how $y_i$ depends on $x_j$.
The power of automatic differentiation is that it can deal with complicated structures from programming languages like conditions and loops. However, if all you need is algebraic expressions and you have good enough framework to work with symbolic representations, it's possible to construct fully symbolic expressions. In fact, in this example we could produce expression $\frac{dz}{dw_1} = w_2 + \cos(w_1) = x_2 + \cos(x_1)$ and calculate this derivative for whatever inputs we want.
|
Step-by-step example of reverse-mode automatic differentiation
Let's say we have expression $z = x_1x_2 + \sin(x_1)$ and want to find derivatives $\frac{dz}{dx_1}$ and $\frac{dz}{dx_2}$. Reverse-mode AD splits this task into 2 parts, namely, forward and reverse p
|
6,442
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
|
It's useful to take a step back and forget about the forecasting aspect for a minute. Let's consider just any distribution $F$ and assume we wish to summarize it using a single number.
You learn very early in your statistics classes that using the expectation of $F$ as a single number summary will minimize the expected squared error.
The question now is: why does using the median of $F$ minimize the expected absolute error?
For this, I often recommend "Visualizing the Median as the Minimum-Deviation Location" by Hanley et al. (2001, The American Statistician). They did set up a little applet along with their paper, which unfortunately probably doesn't work with modern browsers any more, but we can follow the logic in the paper.
Suppose you stand in front of a bank of elevators. They may be arranged equally spaced, or some distances between elevator doors may be larger than others (e.g., some elevators may be out of order). In front of which elevator should you stand to have the minimal expected walk when one of the elevators does arrive? Note that this expected walk plays the role of the expected absolute error!
Suppose you have three elevators A, B and C.
If you wait in front of A, you may need to walk from A to B (if B arrives), or from A to C (if C arrives) - passing B!
If you wait in front of B, you need to walk from B to A (if A arrives) or from B to C (if C arrives).
If you wait in front of C, you need to walk from C to A (if A arrives) - passing B - or from C to B (if B arrives).
Note that from the first and last waiting position, there is a distance - AB in the first, BC in the last position - that you need to walk in multiple cases of elevators arriving. Therefore, your best bet is to stand right in front of the middle elevator - regardless of how the three elevators are arranged.
Here is Figure 1 from Hanley et al.:
This generalizes easily to more than three elevators. Or to elevators with different chances of arriving first. Or indeed to countably infinitely many elevators. So we can apply this logic to all discrete distributions and then pass to the limit to arrive at continuous distributions.
To double back to forecasting, you need to consider that underlying your point forecast for a particular future time bucket, there is a (usually implicit) density forecast or predictive distribution, which we summarize using a single number point forecast. The above argument shows why the median of your predictive density $\hat{F}$ is the point forecast that minimizes the expected absolute error or MAE. (To be more precise, any median may do, since it may not be uniquely defined - in the elevator example, this corresponds to having an even number of elevators.)
And of course the median may be quite different than the expectation if $\hat{F}$ is asymmetric. One important example is with low-volume count-data, especially intermittent-time-series. Indeed, if you have a 50% or higher chance of zero sales, e.g., if sales are Poisson distributed with parameter $\lambda\leq \ln 2$, then you will minimize your expected absolute error by forecasting a flat zero - which is rather unintuitive, even for highly intermittent time series. I wrote a little paper on this (Kolassa, 2016, International Journal of Forecasting).
Thus, if you suspect that your predictive distribution is (or should be) asymmetric, as in the two cases above, then if you wish to get unbiased expectation forecasts, use the rmse. If the distribution can be assumed symmetric (typically for high-volume series), then the median and the mean coincide, and using the mae will also guide you to unbiased forecasts - and the MAE is easier to understand.
Similarly, minimizing the mape can lead to biased forecasts, even for symmetric distributions. This earlier answer of mine contains a simulated example with an asymmetrically distributed strictly positive (lognormally distributed) series can meaningfully be point forecasted using three different point forecasts, depending on whether we want to minimize the MSE, the MAE or the MAPE.
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
|
It's useful to take a step back and forget about the forecasting aspect for a minute. Let's consider just any distribution $F$ and assume we wish to summarize it using a single number.
You learn very
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
It's useful to take a step back and forget about the forecasting aspect for a minute. Let's consider just any distribution $F$ and assume we wish to summarize it using a single number.
You learn very early in your statistics classes that using the expectation of $F$ as a single number summary will minimize the expected squared error.
The question now is: why does using the median of $F$ minimize the expected absolute error?
For this, I often recommend "Visualizing the Median as the Minimum-Deviation Location" by Hanley et al. (2001, The American Statistician). They did set up a little applet along with their paper, which unfortunately probably doesn't work with modern browsers any more, but we can follow the logic in the paper.
Suppose you stand in front of a bank of elevators. They may be arranged equally spaced, or some distances between elevator doors may be larger than others (e.g., some elevators may be out of order). In front of which elevator should you stand to have the minimal expected walk when one of the elevators does arrive? Note that this expected walk plays the role of the expected absolute error!
Suppose you have three elevators A, B and C.
If you wait in front of A, you may need to walk from A to B (if B arrives), or from A to C (if C arrives) - passing B!
If you wait in front of B, you need to walk from B to A (if A arrives) or from B to C (if C arrives).
If you wait in front of C, you need to walk from C to A (if A arrives) - passing B - or from C to B (if B arrives).
Note that from the first and last waiting position, there is a distance - AB in the first, BC in the last position - that you need to walk in multiple cases of elevators arriving. Therefore, your best bet is to stand right in front of the middle elevator - regardless of how the three elevators are arranged.
Here is Figure 1 from Hanley et al.:
This generalizes easily to more than three elevators. Or to elevators with different chances of arriving first. Or indeed to countably infinitely many elevators. So we can apply this logic to all discrete distributions and then pass to the limit to arrive at continuous distributions.
To double back to forecasting, you need to consider that underlying your point forecast for a particular future time bucket, there is a (usually implicit) density forecast or predictive distribution, which we summarize using a single number point forecast. The above argument shows why the median of your predictive density $\hat{F}$ is the point forecast that minimizes the expected absolute error or MAE. (To be more precise, any median may do, since it may not be uniquely defined - in the elevator example, this corresponds to having an even number of elevators.)
And of course the median may be quite different than the expectation if $\hat{F}$ is asymmetric. One important example is with low-volume count-data, especially intermittent-time-series. Indeed, if you have a 50% or higher chance of zero sales, e.g., if sales are Poisson distributed with parameter $\lambda\leq \ln 2$, then you will minimize your expected absolute error by forecasting a flat zero - which is rather unintuitive, even for highly intermittent time series. I wrote a little paper on this (Kolassa, 2016, International Journal of Forecasting).
Thus, if you suspect that your predictive distribution is (or should be) asymmetric, as in the two cases above, then if you wish to get unbiased expectation forecasts, use the rmse. If the distribution can be assumed symmetric (typically for high-volume series), then the median and the mean coincide, and using the mae will also guide you to unbiased forecasts - and the MAE is easier to understand.
Similarly, minimizing the mape can lead to biased forecasts, even for symmetric distributions. This earlier answer of mine contains a simulated example with an asymmetrically distributed strictly positive (lognormally distributed) series can meaningfully be point forecasted using three different point forecasts, depending on whether we want to minimize the MSE, the MAE or the MAPE.
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
It's useful to take a step back and forget about the forecasting aspect for a minute. Let's consider just any distribution $F$ and assume we wish to summarize it using a single number.
You learn very
|
6,443
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
|
Stephan answer gives you an intuitive explanation of why the minimizing the absolute average error give you the median. Now to answer which of the MSE, MAE or MAPE to use:
The MAE is robust, meaning it is less sensitive to outliers. Imagine a series with an error a million time greater that what it should. On the MSE, it will pull the forecast a million/N times (where N is the number of points), while the MAE will only be pulled for 1 unit.
Unfortunately, the MAE is not unique, so it may exhibit some kind of schizophrenic behavior.
So my recommendation is to first make a MSE, then uses the MSE parameters to start the MAE regression.
In any case compare both forecast : if they are very different then there is something smelly in your data.
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
|
Stephan answer gives you an intuitive explanation of why the minimizing the absolute average error give you the median. Now to answer which of the MSE, MAE or MAPE to use:
The MAE is robust, meaning i
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
Stephan answer gives you an intuitive explanation of why the minimizing the absolute average error give you the median. Now to answer which of the MSE, MAE or MAPE to use:
The MAE is robust, meaning it is less sensitive to outliers. Imagine a series with an error a million time greater that what it should. On the MSE, it will pull the forecast a million/N times (where N is the number of points), while the MAE will only be pulled for 1 unit.
Unfortunately, the MAE is not unique, so it may exhibit some kind of schizophrenic behavior.
So my recommendation is to first make a MSE, then uses the MSE parameters to start the MAE regression.
In any case compare both forecast : if they are very different then there is something smelly in your data.
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
Stephan answer gives you an intuitive explanation of why the minimizing the absolute average error give you the median. Now to answer which of the MSE, MAE or MAPE to use:
The MAE is robust, meaning i
|
6,444
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
|
All the aforementioned explanations are great, just suggesting a shorter one.
Assuming you would use some value which isn't the median to minimize MAE then there are A examples above the value and B examples below it such that w.l.o.g $A>B$. Then by increasing the value by $\epsilon>0$ the error reduces by $\epsilon$ for all $A$ examples and increases by $\epsilon$ for all $B$ examples, so overall the error was reduced by $(A-B)\epsilon>0$.
This is true for any value where $A \neq B$, I.e. any value but the median.
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
|
All the aforementioned explanations are great, just suggesting a shorter one.
Assuming you would use some value which isn't the median to minimize MAE then there are A examples above the value and B e
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
All the aforementioned explanations are great, just suggesting a shorter one.
Assuming you would use some value which isn't the median to minimize MAE then there are A examples above the value and B examples below it such that w.l.o.g $A>B$. Then by increasing the value by $\epsilon>0$ the error reduces by $\epsilon$ for all $A$ examples and increases by $\epsilon$ for all $B$ examples, so overall the error was reduced by $(A-B)\epsilon>0$.
This is true for any value where $A \neq B$, I.e. any value but the median.
|
Why does minimizing the MAE lead to forecasting the median and not the mean?
All the aforementioned explanations are great, just suggesting a shorter one.
Assuming you would use some value which isn't the median to minimize MAE then there are A examples above the value and B e
|
6,445
|
Dropping one of the columns when using one-hot encoding
|
This depends on the models (and maybe even software) you want to use. With linear regression, or generalized linear models estimated by maximum likelihood (or least squares) (in R this means using functions lm or glm), you need to leave out one column. Otherwise you will get a message about some columns "left out because of singularities"$^\dagger$.
But if you estimate such models with regularization, for example ridge, lasso er the elastic net, then you should not leave out any columns. The regularization takes care of the singularities, and more important, the prediction obtained may depend on which columns you leave out. That will not happen when you do not use regularization$^\ddagger$. See the answer at How to interpret coefficients of a multinomial elastic net (glmnet) regression which supports this view (with a direct quote from one of the authors of glmnet).
With other models, use the same principles. If the predictions obtained depends on which columns you leave out, then do not do it. Otherwise it is fine.
So far, this answer only mentions linear (and some mildly non-linear) models. But what about very non-linear models, like trees and randomforests? The ideas about categorical encoding, like one-hot, stems mainly from linear models and extensions. There is little reason to think that ideas derived from that context should apply without modification for trees and forests! For some ideas see Random Forest Regression with sparse data in Python.
$^\dagger$ But, using factor variables, R will take care of that for you.
$^\ddagger$ Trying to answer extra question in comment: When using regularization, most often iterative methods are used (as with lasso or elasticnet) which do not need matrix inversion, so that the design matrix do not have full rank is not a problem. With ridge regularization, matrix inversion may be used, but in that case the regularization term added to the matrix before inversion makes it invertible. That is a technical reason, a more profound reason is that removing one column changes the optimization problem, it changes the meaning of the parameters, and it will actually lead to different optimal solutions. As a concrete example, say you have a categorical variable with three levels, 1,2 and 3. The corresponding parameters is $\beta_, \beta_2, \beta_3$. Leaving out column 1 leads to $\beta_1=0$, while the other two parameters change meaning to $\beta_2-\beta_1, \beta_3-\beta_1$. So those two differences will be shrunk. If you leave out another column, other contrasts in the original parameters will be shrunk. So this changes the criterion function being optimized, and there is no reason to expect equivalent solutions! If this is not clear enough, I can add a simulated example (but not today).
|
Dropping one of the columns when using one-hot encoding
|
This depends on the models (and maybe even software) you want to use. With linear regression, or generalized linear models estimated by maximum likelihood (or least squares) (in R this means using fun
|
Dropping one of the columns when using one-hot encoding
This depends on the models (and maybe even software) you want to use. With linear regression, or generalized linear models estimated by maximum likelihood (or least squares) (in R this means using functions lm or glm), you need to leave out one column. Otherwise you will get a message about some columns "left out because of singularities"$^\dagger$.
But if you estimate such models with regularization, for example ridge, lasso er the elastic net, then you should not leave out any columns. The regularization takes care of the singularities, and more important, the prediction obtained may depend on which columns you leave out. That will not happen when you do not use regularization$^\ddagger$. See the answer at How to interpret coefficients of a multinomial elastic net (glmnet) regression which supports this view (with a direct quote from one of the authors of glmnet).
With other models, use the same principles. If the predictions obtained depends on which columns you leave out, then do not do it. Otherwise it is fine.
So far, this answer only mentions linear (and some mildly non-linear) models. But what about very non-linear models, like trees and randomforests? The ideas about categorical encoding, like one-hot, stems mainly from linear models and extensions. There is little reason to think that ideas derived from that context should apply without modification for trees and forests! For some ideas see Random Forest Regression with sparse data in Python.
$^\dagger$ But, using factor variables, R will take care of that for you.
$^\ddagger$ Trying to answer extra question in comment: When using regularization, most often iterative methods are used (as with lasso or elasticnet) which do not need matrix inversion, so that the design matrix do not have full rank is not a problem. With ridge regularization, matrix inversion may be used, but in that case the regularization term added to the matrix before inversion makes it invertible. That is a technical reason, a more profound reason is that removing one column changes the optimization problem, it changes the meaning of the parameters, and it will actually lead to different optimal solutions. As a concrete example, say you have a categorical variable with three levels, 1,2 and 3. The corresponding parameters is $\beta_, \beta_2, \beta_3$. Leaving out column 1 leads to $\beta_1=0$, while the other two parameters change meaning to $\beta_2-\beta_1, \beta_3-\beta_1$. So those two differences will be shrunk. If you leave out another column, other contrasts in the original parameters will be shrunk. So this changes the criterion function being optimized, and there is no reason to expect equivalent solutions! If this is not clear enough, I can add a simulated example (but not today).
|
Dropping one of the columns when using one-hot encoding
This depends on the models (and maybe even software) you want to use. With linear regression, or generalized linear models estimated by maximum likelihood (or least squares) (in R this means using fun
|
6,446
|
Dropping one of the columns when using one-hot encoding
|
In chapter 5 of this book Feature engineering for machine learning has an example can illustrate kjetil's answer.
City Rent
0 SF 3999
1 SF 4000
2 SF 4001
3 NYC 3499
4 NYC 3500
5 NYC 3501
6 Seattle 2499
7 Seattle 2500
8 Seattle 2501
One-hot encoding:
San Francisco 1 0 0
New York 0 1 0
Seattle 0 0 1
Dummy encoding (drop one column):
San Francisco 1 0 0
New York 0 1 0
Seattle 0 0 1
Results:
NYC SF SE b
One-hot encoding 166.67 666.67 –833.33 3333.33
Dummy coding 0 500 –1000 3500
|
Dropping one of the columns when using one-hot encoding
|
In chapter 5 of this book Feature engineering for machine learning has an example can illustrate kjetil's answer.
City Rent
0 SF 3999
1 SF 4000
2 SF 4001
3 NYC 3499
4 NYC 3500
5 NYC 3501
6 Seattle 249
|
Dropping one of the columns when using one-hot encoding
In chapter 5 of this book Feature engineering for machine learning has an example can illustrate kjetil's answer.
City Rent
0 SF 3999
1 SF 4000
2 SF 4001
3 NYC 3499
4 NYC 3500
5 NYC 3501
6 Seattle 2499
7 Seattle 2500
8 Seattle 2501
One-hot encoding:
San Francisco 1 0 0
New York 0 1 0
Seattle 0 0 1
Dummy encoding (drop one column):
San Francisco 1 0 0
New York 0 1 0
Seattle 0 0 1
Results:
NYC SF SE b
One-hot encoding 166.67 666.67 –833.33 3333.33
Dummy coding 0 500 –1000 3500
|
Dropping one of the columns when using one-hot encoding
In chapter 5 of this book Feature engineering for machine learning has an example can illustrate kjetil's answer.
City Rent
0 SF 3999
1 SF 4000
2 SF 4001
3 NYC 3499
4 NYC 3500
5 NYC 3501
6 Seattle 249
|
6,447
|
Understanding shape and calculation of confidence bands in linear regression
|
The standard error of the regression line at point $X$ (i.e. $s_{\widehat{Y}_{X}}$) is hand calculated (Yech!) using:
$s_{\widehat{Y}_{X}} = s_{Y|X}\sqrt{\frac{1}{n}+\frac{\left(X-\overline{X}\right)^{2}}{\sum_{i=1}^{n}{\left(X_{i}-\overline{X}\right)^{2}}}}$,
where the standard error of the estimate (i.e. $s_{Y|X}$) is hand calculated (Double yech!) using:
$s_{Y|X} = \sqrt{\frac{\sum_{i=1}^{n}{\left(Y_{i}-\widehat{Y}\right)^{2}}}{n-2}}$.
The confidence band about the regression line is then obtained as $\widehat{Y} \pm t_{\nu=n-2, \alpha/2}s_{\widehat{Y}}$.
Bear in mind that the confidence band about the regression line is not the same beast as the prediction band about the regression line (there is more uncertainty in predicting $Y$ given a value of $X$ than in estimating the regression line). And, as you are struggling to understand, the confidence intervals about the intercept and slope are yet other quantities.
Further, you do not understand confidence intervals: "if in 95% of the cases my estimates are within the confidence interval, these seem like a possible outcome?" Confidence intervals do not 'contain 95% of the estimates,' rather for each separate sample (produced by the same study design), 95% of the (separately calculated for each sample) 95% confidence intervals would contain the 'true population parameter' (i.e. the true slope, the true intercept, etc.) that $\widehat{\beta}$ and $\widehat{\alpha}$ are estimating.
|
Understanding shape and calculation of confidence bands in linear regression
|
The standard error of the regression line at point $X$ (i.e. $s_{\widehat{Y}_{X}}$) is hand calculated (Yech!) using:
$s_{\widehat{Y}_{X}} = s_{Y|X}\sqrt{\frac{1}{n}+\frac{\left(X-\overline{X}\right)^
|
Understanding shape and calculation of confidence bands in linear regression
The standard error of the regression line at point $X$ (i.e. $s_{\widehat{Y}_{X}}$) is hand calculated (Yech!) using:
$s_{\widehat{Y}_{X}} = s_{Y|X}\sqrt{\frac{1}{n}+\frac{\left(X-\overline{X}\right)^{2}}{\sum_{i=1}^{n}{\left(X_{i}-\overline{X}\right)^{2}}}}$,
where the standard error of the estimate (i.e. $s_{Y|X}$) is hand calculated (Double yech!) using:
$s_{Y|X} = \sqrt{\frac{\sum_{i=1}^{n}{\left(Y_{i}-\widehat{Y}\right)^{2}}}{n-2}}$.
The confidence band about the regression line is then obtained as $\widehat{Y} \pm t_{\nu=n-2, \alpha/2}s_{\widehat{Y}}$.
Bear in mind that the confidence band about the regression line is not the same beast as the prediction band about the regression line (there is more uncertainty in predicting $Y$ given a value of $X$ than in estimating the regression line). And, as you are struggling to understand, the confidence intervals about the intercept and slope are yet other quantities.
Further, you do not understand confidence intervals: "if in 95% of the cases my estimates are within the confidence interval, these seem like a possible outcome?" Confidence intervals do not 'contain 95% of the estimates,' rather for each separate sample (produced by the same study design), 95% of the (separately calculated for each sample) 95% confidence intervals would contain the 'true population parameter' (i.e. the true slope, the true intercept, etc.) that $\widehat{\beta}$ and $\widehat{\alpha}$ are estimating.
|
Understanding shape and calculation of confidence bands in linear regression
The standard error of the regression line at point $X$ (i.e. $s_{\widehat{Y}_{X}}$) is hand calculated (Yech!) using:
$s_{\widehat{Y}_{X}} = s_{Y|X}\sqrt{\frac{1}{n}+\frac{\left(X-\overline{X}\right)^
|
6,448
|
Understanding shape and calculation of confidence bands in linear regression
|
Nice question. It's important to understand these concepts and they're not straightforward.
The 95% confidence bands you see around the regression line are generated by the 95% confidence intervals that the true value for $\bar y$ falls within that range for each individual x. So take a vertical slice, say at x = 50. The regression tells us that $\bar y$ at x = 50 is approximately 25. The confidence interval calculation tells us that we're 95% confident that the true value for $\bar y$ at that point is within the gray area of the graph (so approximately 15 and 35 for the graph above).
When we combine all of the confidence intervals, for every possible x, it gives us the gray bands that you see in the output.
What this functionally means is that we're 95% confident that the true regression line lies somewhere in that gray zone.
Because the confidence bands are calculated using the 95% confidence intervals for each individual point, it's very closely related to the 95% CI for the intercept. In fact, at x = 0 the edges of the gray zone will coincide exactly with the 95% CI for the intercept, because that's how we've generated the confidence bands. That's why the lines you've added above hit the edge of the gray band towards the left.
However, the slope is a little different. It does contribute to the limits, as you've seen above, but the slope and intercept are not separable in a linear regression. So, you can't really say "well what if the intercept was at the minimum of the CI range and the slope was also at the minimum?" This line would generate points that are well outside our 95% CI's for a lot of x's. This means that we're 95% confident that is not our true regression line.
To address your second question, out regression calculations are more precise for x values in the middle of our sample. In fact, the narrowest 95% CI will show up at $\bar x$. This is because, as you can see in the formula in Alexis's answer, $s_{{\hat y}_x}$, $(x - \bar x)$ is in the numerator of a fraction. When $x = \bar x$ this value is zero, so the standard error is smaller.
There's a decent powerpoint here that can help you visualize some of these things:
http://www.stat.duke.edu/~tjl13/s101/slides/unit6lec3H.pdf
|
Understanding shape and calculation of confidence bands in linear regression
|
Nice question. It's important to understand these concepts and they're not straightforward.
The 95% confidence bands you see around the regression line are generated by the 95% confidence intervals th
|
Understanding shape and calculation of confidence bands in linear regression
Nice question. It's important to understand these concepts and they're not straightforward.
The 95% confidence bands you see around the regression line are generated by the 95% confidence intervals that the true value for $\bar y$ falls within that range for each individual x. So take a vertical slice, say at x = 50. The regression tells us that $\bar y$ at x = 50 is approximately 25. The confidence interval calculation tells us that we're 95% confident that the true value for $\bar y$ at that point is within the gray area of the graph (so approximately 15 and 35 for the graph above).
When we combine all of the confidence intervals, for every possible x, it gives us the gray bands that you see in the output.
What this functionally means is that we're 95% confident that the true regression line lies somewhere in that gray zone.
Because the confidence bands are calculated using the 95% confidence intervals for each individual point, it's very closely related to the 95% CI for the intercept. In fact, at x = 0 the edges of the gray zone will coincide exactly with the 95% CI for the intercept, because that's how we've generated the confidence bands. That's why the lines you've added above hit the edge of the gray band towards the left.
However, the slope is a little different. It does contribute to the limits, as you've seen above, but the slope and intercept are not separable in a linear regression. So, you can't really say "well what if the intercept was at the minimum of the CI range and the slope was also at the minimum?" This line would generate points that are well outside our 95% CI's for a lot of x's. This means that we're 95% confident that is not our true regression line.
To address your second question, out regression calculations are more precise for x values in the middle of our sample. In fact, the narrowest 95% CI will show up at $\bar x$. This is because, as you can see in the formula in Alexis's answer, $s_{{\hat y}_x}$, $(x - \bar x)$ is in the numerator of a fraction. When $x = \bar x$ this value is zero, so the standard error is smaller.
There's a decent powerpoint here that can help you visualize some of these things:
http://www.stat.duke.edu/~tjl13/s101/slides/unit6lec3H.pdf
|
Understanding shape and calculation of confidence bands in linear regression
Nice question. It's important to understand these concepts and they're not straightforward.
The 95% confidence bands you see around the regression line are generated by the 95% confidence intervals th
|
6,449
|
Classification/evaluation metrics for highly imbalanced data
|
Yes, your assumptions about Kappa seem about right. Kappa as single, scalar metrics is mostly and advantage over other single, scalar metrics like accuracy, which will not reflect prediction performance of smaller classes (shadowed by performance of any much bigger class). Kappa solves this problem more elegantly, as you pointed out.
Using a metric like Kappa to measure your performance will not necessarily increase how your model fits to the data. You could measure the performance of any model using a number of metrics, but how the model fits data is determined using other parameters (e.g. hyperparameters). So you might use e.g. Kappa for selecting a best suited model type and hyperparametrization amongst multiple choices for your very imbalanced problem - but just computing Kappa itself will not change how your model fits your imbalanced data.
For different metrics: besides Kappa and precision/recall, also take a look at true positive and true negative rates TPR/TNR, and ROC curves and the area under curve AUC. Which of those are useful for your problem will mostly depend on the details of your goal. For example, the different information reflected in TPR/TNR and precision/recall: is your goal to have a high share of frauds actually being detected as such, and a high share of legitimate transactions being detected as such, and/or minimizing the share of false alarms (which you will naturally get "en mass" with such problems) in all alarms?
For up-/downsampling: I think there is no canonical answer to "if those are required". They are more one way of adapting your problem. Technically: yes, you could use them, but use them with care, especially upsampling (you might end up creating unrealistic samples without noticing it) - and be aware that changing the frequency of samples of both classes to something not realistic "in the wild" might have negative effects on prediction performance as well. At least the final, held-out test set should reflect the real-life frequency of samples again. Bottom line: I've seen both cases where doing and not doing up-/or downsampling resulted in the better final outcomes, so this is something you might need to try out (but don't manipulate your test set(s)!).
|
Classification/evaluation metrics for highly imbalanced data
|
Yes, your assumptions about Kappa seem about right. Kappa as single, scalar metrics is mostly and advantage over other single, scalar metrics like accuracy, which will not reflect prediction performan
|
Classification/evaluation metrics for highly imbalanced data
Yes, your assumptions about Kappa seem about right. Kappa as single, scalar metrics is mostly and advantage over other single, scalar metrics like accuracy, which will not reflect prediction performance of smaller classes (shadowed by performance of any much bigger class). Kappa solves this problem more elegantly, as you pointed out.
Using a metric like Kappa to measure your performance will not necessarily increase how your model fits to the data. You could measure the performance of any model using a number of metrics, but how the model fits data is determined using other parameters (e.g. hyperparameters). So you might use e.g. Kappa for selecting a best suited model type and hyperparametrization amongst multiple choices for your very imbalanced problem - but just computing Kappa itself will not change how your model fits your imbalanced data.
For different metrics: besides Kappa and precision/recall, also take a look at true positive and true negative rates TPR/TNR, and ROC curves and the area under curve AUC. Which of those are useful for your problem will mostly depend on the details of your goal. For example, the different information reflected in TPR/TNR and precision/recall: is your goal to have a high share of frauds actually being detected as such, and a high share of legitimate transactions being detected as such, and/or minimizing the share of false alarms (which you will naturally get "en mass" with such problems) in all alarms?
For up-/downsampling: I think there is no canonical answer to "if those are required". They are more one way of adapting your problem. Technically: yes, you could use them, but use them with care, especially upsampling (you might end up creating unrealistic samples without noticing it) - and be aware that changing the frequency of samples of both classes to something not realistic "in the wild" might have negative effects on prediction performance as well. At least the final, held-out test set should reflect the real-life frequency of samples again. Bottom line: I've seen both cases where doing and not doing up-/or downsampling resulted in the better final outcomes, so this is something you might need to try out (but don't manipulate your test set(s)!).
|
Classification/evaluation metrics for highly imbalanced data
Yes, your assumptions about Kappa seem about right. Kappa as single, scalar metrics is mostly and advantage over other single, scalar metrics like accuracy, which will not reflect prediction performan
|
6,450
|
Classification/evaluation metrics for highly imbalanced data
|
Besides the AUC and Kohonen's kappa already discussed in the other answers, I'd also like to add a few metrics I've found useful for imbalanced data. They are both related to precision and recall. Because by averaging these you get a metric weighing $TP$s and both types of errors ($FP$ and $FN$):
F1 score, which is the harmonic mean of precision and recall.
G-measure, which is the geometric mean of precision and recall. Compared to F1, I've found it a bit better for imbalanced data.
Jaccard index, which you can think of as the $TP / (TP + FP + FN)$. This is actually the metric that has worked for me the best.
Note: For imbalanced datasets, it is best to have your metrics be macro-averaged.
|
Classification/evaluation metrics for highly imbalanced data
|
Besides the AUC and Kohonen's kappa already discussed in the other answers, I'd also like to add a few metrics I've found useful for imbalanced data. They are both related to precision and recall. Bec
|
Classification/evaluation metrics for highly imbalanced data
Besides the AUC and Kohonen's kappa already discussed in the other answers, I'd also like to add a few metrics I've found useful for imbalanced data. They are both related to precision and recall. Because by averaging these you get a metric weighing $TP$s and both types of errors ($FP$ and $FN$):
F1 score, which is the harmonic mean of precision and recall.
G-measure, which is the geometric mean of precision and recall. Compared to F1, I've found it a bit better for imbalanced data.
Jaccard index, which you can think of as the $TP / (TP + FP + FN)$. This is actually the metric that has worked for me the best.
Note: For imbalanced datasets, it is best to have your metrics be macro-averaged.
|
Classification/evaluation metrics for highly imbalanced data
Besides the AUC and Kohonen's kappa already discussed in the other answers, I'd also like to add a few metrics I've found useful for imbalanced data. They are both related to precision and recall. Bec
|
6,451
|
Classification/evaluation metrics for highly imbalanced data
|
For imbalanced datasets, the Average Precision metric is sometimes a better alternative to the AUROC. The AP score is the area under the precision-recall curve.
Here's a discussion with some code (Python)
Here's a paper.
Also see Peter Flach's Precision-Recall-Gain curves, along with a discussion about the shortcoming of AP curves.
|
Classification/evaluation metrics for highly imbalanced data
|
For imbalanced datasets, the Average Precision metric is sometimes a better alternative to the AUROC. The AP score is the area under the precision-recall curve.
Here's a discussion with some code (Py
|
Classification/evaluation metrics for highly imbalanced data
For imbalanced datasets, the Average Precision metric is sometimes a better alternative to the AUROC. The AP score is the area under the precision-recall curve.
Here's a discussion with some code (Python)
Here's a paper.
Also see Peter Flach's Precision-Recall-Gain curves, along with a discussion about the shortcoming of AP curves.
|
Classification/evaluation metrics for highly imbalanced data
For imbalanced datasets, the Average Precision metric is sometimes a better alternative to the AUROC. The AP score is the area under the precision-recall curve.
Here's a discussion with some code (Py
|
6,452
|
What does the anova() command do with a lmer model object?
|
Use the Source, Luke. We can peek inside the ANOVA function by doing getAnywhere(anova.Mermod). The first part of that function is for comparing two different models. The anova on the fixed effects comes in the big else block in the second half:
dc <- getME(object, "devcomp")
X <- getME(object, "X")
asgn <- attr(X, "assign")
stopifnot(length(asgn) == (p <- dc$dims[["p"]]))
ss <- as.vector(object@pp$RX() %*% object@beta)^2
names(ss) <- colnames(X)
terms <- terms(object)
nmeffects <- attr(terms, "term.labels")[unique(asgn)]
if ("(Intercept)" %in% names(ss))
nmeffects <- c("(Intercept)", nmeffects)
ss <- unlist(lapply(split(ss, asgn), sum))
stopifnot(length(ss) == length(nmeffects))
df <- vapply(split(asgn, asgn), length, 1L)
ms <- ss/df
f <- ms/(sigma(object)^2)
table <- data.frame(df, ss, ms, f)
dimnames(table) <- list(nmeffects, c("Df", "Sum Sq",
"Mean Sq", "F value"))
if ("(Intercept)" %in% nmeffects)
table <- table[-match("(Intercept)", nmeffects),
]
attr(table, "heading") <- "Analysis of Variance Table"
class(table) <- c("anova", "data.frame")
table
object is the lmer output. We start to calculate the sum of squares in line 5: ss <- as.vector ... The code multiplies the fixed parameters (in beta) by an upper triangular matrix; then squares each term. Here is that upper triangular matrix for the irrigation example. Each row corresponds to one of the five fixed effects parameters (intercept, 3 degrees of freedom for irrigation, 1 df for variety).
zapsmall(irrigation.lmer@pp$RX(), digits = 3)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.813 0.203 0.203 0.203 0.407
[2,] 0.000 0.352 -0.117 -0.117 0.000
[3,] 0.000 0.000 0.332 -0.166 0.000
[4,] 0.000 0.000 0.000 0.287 0.000
[5,] 0.000 0.000 0.000 0.000 2.000
The first row gives you the sum of squares for the intercept and the last gives you the SS for the within-fields variety effect. Rows 2-4 only involve the 3 parameters for the irrigation levels, so pre-multiplication gives you three pieces of the SS for irrigation.
These pieces are not interesting in themselves since they come from the default treatment contrast in R, but in line ss <- unlist(lapply(split .... Bates scoops up bits of sums of squares according to the number of levels and which factors they refer to. There's a lot of book-keeping going on here. We get the degrees of freedom as well (which are 3 for irrigation). Then, he gets the mean squares which show up on the printout of anova. Finally, he divides all his means squares by the within-groups residual variance, sigma(object)^2.
So what's going on? The philosophy of lmer has nothing to do with the method of moments approach used by aov. The idea in lmer is to maximize a marginal likelihood obtained by integrating out the unseen random effects. In this case, the random fertility level of each field. Chapter 2 of Pinheiro and Bates describes the ugliness of this process. The RX matrix used to get the sums of squares is their matrix $R_{00}$ from equation 2.17, page 70 of the text. This matrix is obtained from a bunch of QR decompositions upon (amongst other things) the design matrix of the random effects and $\sqrt{\sigma^2/\sigma_f^2}$, where $\sigma_f^2$ is the variance of the field effect. This is that missing factor you were asking about, but it does not enter into the solution in a transparent or simple way.
Asymptotically, the estimates of the fixed effects have distribution:
$$
\hat{\beta} \sim \mathcal{N}(\beta, \sigma^2[R_{00}^{-1}R_{00}^{-T}])
$$
which means that the components of $R_{00}\hat{\beta}$ are independently distributed. If $\beta=0$, the squares of those terms (divided by $\sigma^2$) follow a chi-squared distribution. Dividing through by the estimate of $\sigma^2$ (another chi-squared when divided by $\sigma^2$) gives an F statistic. We don't divide by the mean square error for the between-groups analysis because that has nothing to do with what's going on here. We need to compare the sums of squares obtained through $R_{00}$ by comparing them to an estimate of $\sigma^2$.
Note that you would not have got the same F statistics had the data been unbalanced. Nor would you have obtained the same F statistics if you had used ML instead of REML.
The idea behind aov is that the expected mean squares for irrigation is a function of $\sigma^2$, $\sigma_f^2$ and the irrigation effects. The expected mean square for field residuals is a function of $\sigma^2$ and $\sigma_f^2$. When the irrigation effects are 0, both of these quantities estimate the same thing and their ratio follows an F distribution.
Interestingly, Bates and Pinheiro recommend using the ANOVA over fitting two models and doing a likelihood ratio test. The latter tends to be anti-conservative.
Of course, if the data are unbalanced, it is no longer clear exactly what hypothesis the ANOVA is testing. I removed the first observation from the irrigation data and refit. Here is the $R_{00}$ matrix again:
zapsmall(fit2@pp$RX(), digits = 3)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.816 0.205 0.205 0.205 0.457
[2,] 0.000 0.354 -0.119 -0.119 -0.029
[3,] 0.000 0.000 0.334 -0.168 -0.040
[4,] 0.000 0.000 0.000 0.288 -0.071
[5,] 0.000 0.000 0.000 0.000 1.874
As you can see, the sums of squares for the irrigation parameters now contain some of the variety effect as well.
|
What does the anova() command do with a lmer model object?
|
Use the Source, Luke. We can peek inside the ANOVA function by doing getAnywhere(anova.Mermod). The first part of that function is for comparing two different models. The anova on the fixed effects co
|
What does the anova() command do with a lmer model object?
Use the Source, Luke. We can peek inside the ANOVA function by doing getAnywhere(anova.Mermod). The first part of that function is for comparing two different models. The anova on the fixed effects comes in the big else block in the second half:
dc <- getME(object, "devcomp")
X <- getME(object, "X")
asgn <- attr(X, "assign")
stopifnot(length(asgn) == (p <- dc$dims[["p"]]))
ss <- as.vector(object@pp$RX() %*% object@beta)^2
names(ss) <- colnames(X)
terms <- terms(object)
nmeffects <- attr(terms, "term.labels")[unique(asgn)]
if ("(Intercept)" %in% names(ss))
nmeffects <- c("(Intercept)", nmeffects)
ss <- unlist(lapply(split(ss, asgn), sum))
stopifnot(length(ss) == length(nmeffects))
df <- vapply(split(asgn, asgn), length, 1L)
ms <- ss/df
f <- ms/(sigma(object)^2)
table <- data.frame(df, ss, ms, f)
dimnames(table) <- list(nmeffects, c("Df", "Sum Sq",
"Mean Sq", "F value"))
if ("(Intercept)" %in% nmeffects)
table <- table[-match("(Intercept)", nmeffects),
]
attr(table, "heading") <- "Analysis of Variance Table"
class(table) <- c("anova", "data.frame")
table
object is the lmer output. We start to calculate the sum of squares in line 5: ss <- as.vector ... The code multiplies the fixed parameters (in beta) by an upper triangular matrix; then squares each term. Here is that upper triangular matrix for the irrigation example. Each row corresponds to one of the five fixed effects parameters (intercept, 3 degrees of freedom for irrigation, 1 df for variety).
zapsmall(irrigation.lmer@pp$RX(), digits = 3)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.813 0.203 0.203 0.203 0.407
[2,] 0.000 0.352 -0.117 -0.117 0.000
[3,] 0.000 0.000 0.332 -0.166 0.000
[4,] 0.000 0.000 0.000 0.287 0.000
[5,] 0.000 0.000 0.000 0.000 2.000
The first row gives you the sum of squares for the intercept and the last gives you the SS for the within-fields variety effect. Rows 2-4 only involve the 3 parameters for the irrigation levels, so pre-multiplication gives you three pieces of the SS for irrigation.
These pieces are not interesting in themselves since they come from the default treatment contrast in R, but in line ss <- unlist(lapply(split .... Bates scoops up bits of sums of squares according to the number of levels and which factors they refer to. There's a lot of book-keeping going on here. We get the degrees of freedom as well (which are 3 for irrigation). Then, he gets the mean squares which show up on the printout of anova. Finally, he divides all his means squares by the within-groups residual variance, sigma(object)^2.
So what's going on? The philosophy of lmer has nothing to do with the method of moments approach used by aov. The idea in lmer is to maximize a marginal likelihood obtained by integrating out the unseen random effects. In this case, the random fertility level of each field. Chapter 2 of Pinheiro and Bates describes the ugliness of this process. The RX matrix used to get the sums of squares is their matrix $R_{00}$ from equation 2.17, page 70 of the text. This matrix is obtained from a bunch of QR decompositions upon (amongst other things) the design matrix of the random effects and $\sqrt{\sigma^2/\sigma_f^2}$, where $\sigma_f^2$ is the variance of the field effect. This is that missing factor you were asking about, but it does not enter into the solution in a transparent or simple way.
Asymptotically, the estimates of the fixed effects have distribution:
$$
\hat{\beta} \sim \mathcal{N}(\beta, \sigma^2[R_{00}^{-1}R_{00}^{-T}])
$$
which means that the components of $R_{00}\hat{\beta}$ are independently distributed. If $\beta=0$, the squares of those terms (divided by $\sigma^2$) follow a chi-squared distribution. Dividing through by the estimate of $\sigma^2$ (another chi-squared when divided by $\sigma^2$) gives an F statistic. We don't divide by the mean square error for the between-groups analysis because that has nothing to do with what's going on here. We need to compare the sums of squares obtained through $R_{00}$ by comparing them to an estimate of $\sigma^2$.
Note that you would not have got the same F statistics had the data been unbalanced. Nor would you have obtained the same F statistics if you had used ML instead of REML.
The idea behind aov is that the expected mean squares for irrigation is a function of $\sigma^2$, $\sigma_f^2$ and the irrigation effects. The expected mean square for field residuals is a function of $\sigma^2$ and $\sigma_f^2$. When the irrigation effects are 0, both of these quantities estimate the same thing and their ratio follows an F distribution.
Interestingly, Bates and Pinheiro recommend using the ANOVA over fitting two models and doing a likelihood ratio test. The latter tends to be anti-conservative.
Of course, if the data are unbalanced, it is no longer clear exactly what hypothesis the ANOVA is testing. I removed the first observation from the irrigation data and refit. Here is the $R_{00}$ matrix again:
zapsmall(fit2@pp$RX(), digits = 3)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.816 0.205 0.205 0.205 0.457
[2,] 0.000 0.354 -0.119 -0.119 -0.029
[3,] 0.000 0.000 0.334 -0.168 -0.040
[4,] 0.000 0.000 0.000 0.288 -0.071
[5,] 0.000 0.000 0.000 0.000 1.874
As you can see, the sums of squares for the irrigation parameters now contain some of the variety effect as well.
|
What does the anova() command do with a lmer model object?
Use the Source, Luke. We can peek inside the ANOVA function by doing getAnywhere(anova.Mermod). The first part of that function is for comparing two different models. The anova on the fixed effects co
|
6,453
|
What is compound symmetry in plain english?
|
Compound symmetry is essentially the "exchangeable" correlation structure, except with a specific decomposition for the total variance. For example, if you have mixed model for the subject $i$ in cluster $j$ response, $Y_{ij}$, with only a random intercept by cluster
$$ Y_{ij} = \alpha + \gamma_{j} + \varepsilon_{ij} $$
where $\gamma_{j}$ is the cluster $j$ random effect with variance $\sigma^{2}_{\gamma}$ and $\varepsilon_{ij}$ is the subject $i$ in cluster $j$ "measurement error" with variance $\sigma^{2}_{\varepsilon}$ and $\gamma_{j}, \varepsilon_{ij}$ are independent. This model implicitly specifies the compound symmetry covariance matrix between observations in the same cluster:
$$ {\rm cov}(Y_{ij}, Y_{kj}) = \sigma^{2}_{\gamma} + \sigma^{2}_{\varepsilon} \cdot \mathcal{I}(k = i) $$
Note that the compound symmetry assumption implies that the correlation between distinct members of a cluster is $\sigma^{2}_{\gamma}/(\sigma^{2}_{\gamma} + \sigma^{2}_{\varepsilon})$.
In "plain english" you might say this covariance structure implies that all distinct members of a cluster are equally correlated with each other and the total variation, $\sigma^{2} = \sigma^{2}_{\gamma} + \sigma^{2}_{\varepsilon}$, can be partitioned into the "shared" (within a cluster) component, $\sigma^{2}_{\gamma}$ and the "unshared" component, $\sigma^{2}_{\varepsilon}$.
Edit: To aid understanding in the "plain english" sense, consider an example where individuals are clustered within families so that $Y_{ij}$ denotes the subject $i$ in family $j$ response. In this case the compound symmetry assumption means that the total variation in $Y_{ij}$ can be partitioned into the variation within a family, $\sigma^{2}_{\varepsilon}$, and the variation between families, $\sigma^{2}_{\gamma}$.
|
What is compound symmetry in plain english?
|
Compound symmetry is essentially the "exchangeable" correlation structure, except with a specific decomposition for the total variance. For example, if you have mixed model for the subject $i$ in clus
|
What is compound symmetry in plain english?
Compound symmetry is essentially the "exchangeable" correlation structure, except with a specific decomposition for the total variance. For example, if you have mixed model for the subject $i$ in cluster $j$ response, $Y_{ij}$, with only a random intercept by cluster
$$ Y_{ij} = \alpha + \gamma_{j} + \varepsilon_{ij} $$
where $\gamma_{j}$ is the cluster $j$ random effect with variance $\sigma^{2}_{\gamma}$ and $\varepsilon_{ij}$ is the subject $i$ in cluster $j$ "measurement error" with variance $\sigma^{2}_{\varepsilon}$ and $\gamma_{j}, \varepsilon_{ij}$ are independent. This model implicitly specifies the compound symmetry covariance matrix between observations in the same cluster:
$$ {\rm cov}(Y_{ij}, Y_{kj}) = \sigma^{2}_{\gamma} + \sigma^{2}_{\varepsilon} \cdot \mathcal{I}(k = i) $$
Note that the compound symmetry assumption implies that the correlation between distinct members of a cluster is $\sigma^{2}_{\gamma}/(\sigma^{2}_{\gamma} + \sigma^{2}_{\varepsilon})$.
In "plain english" you might say this covariance structure implies that all distinct members of a cluster are equally correlated with each other and the total variation, $\sigma^{2} = \sigma^{2}_{\gamma} + \sigma^{2}_{\varepsilon}$, can be partitioned into the "shared" (within a cluster) component, $\sigma^{2}_{\gamma}$ and the "unshared" component, $\sigma^{2}_{\varepsilon}$.
Edit: To aid understanding in the "plain english" sense, consider an example where individuals are clustered within families so that $Y_{ij}$ denotes the subject $i$ in family $j$ response. In this case the compound symmetry assumption means that the total variation in $Y_{ij}$ can be partitioned into the variation within a family, $\sigma^{2}_{\varepsilon}$, and the variation between families, $\sigma^{2}_{\gamma}$.
|
What is compound symmetry in plain english?
Compound symmetry is essentially the "exchangeable" correlation structure, except with a specific decomposition for the total variance. For example, if you have mixed model for the subject $i$ in clus
|
6,454
|
What is compound symmetry in plain english?
|
For me, the best answer I've seen about compound symmetry is from David Howell (here):
In other words, the correlation between trial 1 and trial 2 is equal to the correlation between trial 1 and trial 4 or trial 3 and trial 4, etc. But a more direct way to think about compound symmetry is to say that it requires that all subjects in each group change in the same way over trials. In other words the slopes of the lines regressing the dependent variable on time are the same for all subjects. Put that way it is easy to see that compound symmetry can really be an unrealistic assumption. If some of your subjects improve but others don't, you do not have compound symmetry and you make an error if you use a solution that assumes that you do.
|
What is compound symmetry in plain english?
|
For me, the best answer I've seen about compound symmetry is from David Howell (here):
In other words, the correlation between trial 1 and trial 2 is equal to the correlation between trial 1 and tr
|
What is compound symmetry in plain english?
For me, the best answer I've seen about compound symmetry is from David Howell (here):
In other words, the correlation between trial 1 and trial 2 is equal to the correlation between trial 1 and trial 4 or trial 3 and trial 4, etc. But a more direct way to think about compound symmetry is to say that it requires that all subjects in each group change in the same way over trials. In other words the slopes of the lines regressing the dependent variable on time are the same for all subjects. Put that way it is easy to see that compound symmetry can really be an unrealistic assumption. If some of your subjects improve but others don't, you do not have compound symmetry and you make an error if you use a solution that assumes that you do.
|
What is compound symmetry in plain english?
For me, the best answer I've seen about compound symmetry is from David Howell (here):
In other words, the correlation between trial 1 and trial 2 is equal to the correlation between trial 1 and tr
|
6,455
|
What is compound symmetry in plain english?
|
Compound Symmetry just means that all the variances are equal and all the covariances are equal. So the same variance and covariance are used for all subjects. If you think this applies to the factors in your ANOVA model, compound symmetry is a good covariance structure to use because of its simple structure.
|
What is compound symmetry in plain english?
|
Compound Symmetry just means that all the variances are equal and all the covariances are equal. So the same variance and covariance are used for all subjects. If you think this applies to the factors
|
What is compound symmetry in plain english?
Compound Symmetry just means that all the variances are equal and all the covariances are equal. So the same variance and covariance are used for all subjects. If you think this applies to the factors in your ANOVA model, compound symmetry is a good covariance structure to use because of its simple structure.
|
What is compound symmetry in plain english?
Compound Symmetry just means that all the variances are equal and all the covariances are equal. So the same variance and covariance are used for all subjects. If you think this applies to the factors
|
6,456
|
Maximum likelihood estimators for a truncated distribution
|
Consider any location-scale family determined by a "standard" distribution $F$,
$$\Omega_F = \left\{F_{(\mu, \sigma)}: x \to F\left(\frac{x-\mu}{\sigma}\right) \mid \sigma \gt 0\right\}.$$
Assuming $F$ differentiable, basic rules of differentiation show its probability elements are $\frac{1}{\sigma}f\left((x-\mu)/\sigma\right)\mathrm dx$.
Truncating these distributions to restrict their support between $a$ and $b$, $a \lt b$, means that the probability elements are replaced by
$$f_{(\mu, \sigma; a,b)}(x)\mathrm dx = \frac{f\left(\frac{x-\mu}{\sigma}\right)\mathrm dx}{\sigma C(\mu, \sigma, a, b)}, a \le x \le b$$
(and are zero for all other values of $x$) where $C(\mu, \sigma, a, b) = F_{(\mu,\sigma)}(b) - F_{(\mu,\sigma)}(a)$ is the normalizing factor needed to ensure that $f_{(\mu, \sigma; a, b)}$ integrates to unity. (Note that $C$ is identically $1$ in the absence of truncation.) The log likelihood for iid data $x_i$ therefore is
$$\Lambda(\mu, \sigma) = \sum_i \left[\log{f\left(\frac{x_i-\mu}{\sigma}\right)} - \log{\sigma}-\log{C(\mu, \sigma, a, b)}\right].$$
Critical points (including any global minima) are found where either $\sigma=0$ (a special case I will ignore here) or the gradient vanishes. Using subscripts to denote derivatives, we may formally compute the gradient and write the likelihood equations as
$$\eqalign{
0 &= \frac{\partial\Lambda}{\partial\mu} &= \sum_i \left[\frac{-f_\mu\left(\frac{x_i-\mu}{\sigma}\right)}{f\left(\frac{x_i-\mu}{\sigma}\right)} -\frac{C_\mu(\mu,\sigma,a,b)}{C(\mu,\sigma,a,b)}\right] \\
0 &= \frac{\partial\Lambda}{\partial\sigma} &= \sum_i \left[\frac{-f_\sigma\left(\frac{x_i-\mu}{\sigma}\right)}{\sigma^2f\left(\frac{x_i-\mu}{\sigma}\right)} -\frac{1}{\sigma}-\frac{C_\sigma(\mu,\sigma,a,b)}{C(\mu,\sigma,a,b)}\right]
}$$
Because $a$ and $b$ are fixed, drop them from the notation and write $nC_\mu(\mu, \sigma, a, b)/C(\mu, \sigma,a,b)$ as $A(\mu,\sigma)$ and $nC_\sigma(\mu, \sigma, a, b)/C(\mu, \sigma,a,b)$ as $B(\mu, \sigma)$. (With no truncation, both functions would be identically zero.) Separating the terms involving the data from the rest gives
$$\eqalign{
-A(\mu,\sigma) &= \sum_i \frac{f_\mu\left(\frac{x_i-\mu}{\sigma}\right)}{f\left(\frac{x_i-\mu}{\sigma}\right)} \\
-\sigma^2 B(\mu,\sigma) - n\sigma &= \sum_i \frac{f_\sigma\left(\frac{x_i-\mu}{\sigma}\right)}{f\left(\frac{x_i-\mu}{\sigma}\right)}
}$$
By comparing these to the no-truncation situation it is evident that
Any sufficient statistics for the original problem are sufficient for the truncated problem (because the right hand sides have not changed).
Our ability to find closed-form solutions relies on the tractability of $A$ and $B$. If these do not involve $\mu$ and $\sigma$ in simple ways, we cannot hope to obtain closed-form solutions in general.
For the case of a normal family, $C(\mu,\sigma,a,b)$ of course is given by the cumulative normal distribution, which is a difference of error functions: there is no chance that a closed-form solution can be obtained in general. However, there are only two sufficient statistics (the sample mean and variance will do) and the cumulative distribution function is as smooth as can be, so numerical solutions will be relatively easy to obtain.
|
Maximum likelihood estimators for a truncated distribution
|
Consider any location-scale family determined by a "standard" distribution $F$,
$$\Omega_F = \left\{F_{(\mu, \sigma)}: x \to F\left(\frac{x-\mu}{\sigma}\right) \mid \sigma \gt 0\right\}.$$
Assuming $F
|
Maximum likelihood estimators for a truncated distribution
Consider any location-scale family determined by a "standard" distribution $F$,
$$\Omega_F = \left\{F_{(\mu, \sigma)}: x \to F\left(\frac{x-\mu}{\sigma}\right) \mid \sigma \gt 0\right\}.$$
Assuming $F$ differentiable, basic rules of differentiation show its probability elements are $\frac{1}{\sigma}f\left((x-\mu)/\sigma\right)\mathrm dx$.
Truncating these distributions to restrict their support between $a$ and $b$, $a \lt b$, means that the probability elements are replaced by
$$f_{(\mu, \sigma; a,b)}(x)\mathrm dx = \frac{f\left(\frac{x-\mu}{\sigma}\right)\mathrm dx}{\sigma C(\mu, \sigma, a, b)}, a \le x \le b$$
(and are zero for all other values of $x$) where $C(\mu, \sigma, a, b) = F_{(\mu,\sigma)}(b) - F_{(\mu,\sigma)}(a)$ is the normalizing factor needed to ensure that $f_{(\mu, \sigma; a, b)}$ integrates to unity. (Note that $C$ is identically $1$ in the absence of truncation.) The log likelihood for iid data $x_i$ therefore is
$$\Lambda(\mu, \sigma) = \sum_i \left[\log{f\left(\frac{x_i-\mu}{\sigma}\right)} - \log{\sigma}-\log{C(\mu, \sigma, a, b)}\right].$$
Critical points (including any global minima) are found where either $\sigma=0$ (a special case I will ignore here) or the gradient vanishes. Using subscripts to denote derivatives, we may formally compute the gradient and write the likelihood equations as
$$\eqalign{
0 &= \frac{\partial\Lambda}{\partial\mu} &= \sum_i \left[\frac{-f_\mu\left(\frac{x_i-\mu}{\sigma}\right)}{f\left(\frac{x_i-\mu}{\sigma}\right)} -\frac{C_\mu(\mu,\sigma,a,b)}{C(\mu,\sigma,a,b)}\right] \\
0 &= \frac{\partial\Lambda}{\partial\sigma} &= \sum_i \left[\frac{-f_\sigma\left(\frac{x_i-\mu}{\sigma}\right)}{\sigma^2f\left(\frac{x_i-\mu}{\sigma}\right)} -\frac{1}{\sigma}-\frac{C_\sigma(\mu,\sigma,a,b)}{C(\mu,\sigma,a,b)}\right]
}$$
Because $a$ and $b$ are fixed, drop them from the notation and write $nC_\mu(\mu, \sigma, a, b)/C(\mu, \sigma,a,b)$ as $A(\mu,\sigma)$ and $nC_\sigma(\mu, \sigma, a, b)/C(\mu, \sigma,a,b)$ as $B(\mu, \sigma)$. (With no truncation, both functions would be identically zero.) Separating the terms involving the data from the rest gives
$$\eqalign{
-A(\mu,\sigma) &= \sum_i \frac{f_\mu\left(\frac{x_i-\mu}{\sigma}\right)}{f\left(\frac{x_i-\mu}{\sigma}\right)} \\
-\sigma^2 B(\mu,\sigma) - n\sigma &= \sum_i \frac{f_\sigma\left(\frac{x_i-\mu}{\sigma}\right)}{f\left(\frac{x_i-\mu}{\sigma}\right)}
}$$
By comparing these to the no-truncation situation it is evident that
Any sufficient statistics for the original problem are sufficient for the truncated problem (because the right hand sides have not changed).
Our ability to find closed-form solutions relies on the tractability of $A$ and $B$. If these do not involve $\mu$ and $\sigma$ in simple ways, we cannot hope to obtain closed-form solutions in general.
For the case of a normal family, $C(\mu,\sigma,a,b)$ of course is given by the cumulative normal distribution, which is a difference of error functions: there is no chance that a closed-form solution can be obtained in general. However, there are only two sufficient statistics (the sample mean and variance will do) and the cumulative distribution function is as smooth as can be, so numerical solutions will be relatively easy to obtain.
|
Maximum likelihood estimators for a truncated distribution
Consider any location-scale family determined by a "standard" distribution $F$,
$$\Omega_F = \left\{F_{(\mu, \sigma)}: x \to F\left(\frac{x-\mu}{\sigma}\right) \mid \sigma \gt 0\right\}.$$
Assuming $F
|
6,457
|
Clojure versus R: advantages and disadvantages for data analysis
|
Let me start by saying that I love both languages: you can't go wrong with either, and they are certainly better than something like C++ or Java for doing data analysis.
For basic data analysis I would suggest R (especially with plyr). IMO, R is a little easier to learn than Clojure, although this isn't completely obvious since Clojure is based on Lisp and there are numerous fantastic Lisp resources available (such as SICP). There are less keywords in Clojure, but the libraries are much more difficult to install and work with. Also, keep in mind that R (or S) is largely derived from Scheme, so you would benefit from Lisp knowledge when using it.
In general:
The main advantage of R is the community on CRAN (over 2461 packages and counting). Nothing will compare with this in the near future, not even a commercial application like matlab.
Clojure has the big advantage of running on the JVM which means that it can use any Java based library immediately.
I would add that I gave a talk relating Clojure/Incanter to R a while ago, so you may find it of interest. In my experience around creating this, Clojure was generally slower than R for simple operations.
|
Clojure versus R: advantages and disadvantages for data analysis
|
Let me start by saying that I love both languages: you can't go wrong with either, and they are certainly better than something like C++ or Java for doing data analysis.
For basic data analysis I woul
|
Clojure versus R: advantages and disadvantages for data analysis
Let me start by saying that I love both languages: you can't go wrong with either, and they are certainly better than something like C++ or Java for doing data analysis.
For basic data analysis I would suggest R (especially with plyr). IMO, R is a little easier to learn than Clojure, although this isn't completely obvious since Clojure is based on Lisp and there are numerous fantastic Lisp resources available (such as SICP). There are less keywords in Clojure, but the libraries are much more difficult to install and work with. Also, keep in mind that R (or S) is largely derived from Scheme, so you would benefit from Lisp knowledge when using it.
In general:
The main advantage of R is the community on CRAN (over 2461 packages and counting). Nothing will compare with this in the near future, not even a commercial application like matlab.
Clojure has the big advantage of running on the JVM which means that it can use any Java based library immediately.
I would add that I gave a talk relating Clojure/Incanter to R a while ago, so you may find it of interest. In my experience around creating this, Clojure was generally slower than R for simple operations.
|
Clojure versus R: advantages and disadvantages for data analysis
Let me start by saying that I love both languages: you can't go wrong with either, and they are certainly better than something like C++ or Java for doing data analysis.
For basic data analysis I woul
|
6,458
|
Clojure versus R: advantages and disadvantages for data analysis
|
I have been a heavy R user for the past 6-7 years. As a language, it has several design limitations. Yet, for work in econometrics and in data analysis, I still wholeheartedly recommend it. It has a large number of packages that would be relevant to you for econometrics, time series, consumer choice modeling etc. and of course excellent visualization, good algebra and numerical libraries etc. I would not worry too much about data size limitations. Although R was not designed for "big data" (unlike, say, SAS) there are ways around it. The availability of packages is what makes the difference, really.
I've only read Clojure's language specs, and it's beautiful and clean. It addresses in a natural way issues of parallelization and scale. And if you have some basic java or OOP knowledge, you can benefit from the large number of high-quality java libraries.
The issue I have with Clojure is that is a recent one-man (R.Hickey) operation, therefore 1) very risky 2) very immature 3) with niche adoption. Great for enthusiasts, early adopters, CS/ML people who want to try new things. For a user who sees a language as a means to an end and who needs very robust code that can be shared code with others, established languages seem a safer choice. Just know who you are.
|
Clojure versus R: advantages and disadvantages for data analysis
|
I have been a heavy R user for the past 6-7 years. As a language, it has several design limitations. Yet, for work in econometrics and in data analysis, I still wholeheartedly recommend it. It has a l
|
Clojure versus R: advantages and disadvantages for data analysis
I have been a heavy R user for the past 6-7 years. As a language, it has several design limitations. Yet, for work in econometrics and in data analysis, I still wholeheartedly recommend it. It has a large number of packages that would be relevant to you for econometrics, time series, consumer choice modeling etc. and of course excellent visualization, good algebra and numerical libraries etc. I would not worry too much about data size limitations. Although R was not designed for "big data" (unlike, say, SAS) there are ways around it. The availability of packages is what makes the difference, really.
I've only read Clojure's language specs, and it's beautiful and clean. It addresses in a natural way issues of parallelization and scale. And if you have some basic java or OOP knowledge, you can benefit from the large number of high-quality java libraries.
The issue I have with Clojure is that is a recent one-man (R.Hickey) operation, therefore 1) very risky 2) very immature 3) with niche adoption. Great for enthusiasts, early adopters, CS/ML people who want to try new things. For a user who sees a language as a means to an end and who needs very robust code that can be shared code with others, established languages seem a safer choice. Just know who you are.
|
Clojure versus R: advantages and disadvantages for data analysis
I have been a heavy R user for the past 6-7 years. As a language, it has several design limitations. Yet, for work in econometrics and in data analysis, I still wholeheartedly recommend it. It has a l
|
6,459
|
Clojure versus R: advantages and disadvantages for data analysis
|
Update (August 2014): as @gappy comments below, as of R version 3.0.0 the limits are higher and means R is capable of handling larger datasets.
Here's a data point: R has a "big data ceiling", useful to know if you plan on working with huge data sets.
I'm unsure whether the same limitations apply to Clojure/Incanter, whether it outperforms R or is actually worse. I imagine the JVM can probably handle large datasets, especially if you manage to harness the power of Clojure's lazy features.
|
Clojure versus R: advantages and disadvantages for data analysis
|
Update (August 2014): as @gappy comments below, as of R version 3.0.0 the limits are higher and means R is capable of handling larger datasets.
Here's a data point: R has a "big data ceiling", useful
|
Clojure versus R: advantages and disadvantages for data analysis
Update (August 2014): as @gappy comments below, as of R version 3.0.0 the limits are higher and means R is capable of handling larger datasets.
Here's a data point: R has a "big data ceiling", useful to know if you plan on working with huge data sets.
I'm unsure whether the same limitations apply to Clojure/Incanter, whether it outperforms R or is actually worse. I imagine the JVM can probably handle large datasets, especially if you manage to harness the power of Clojure's lazy features.
|
Clojure versus R: advantages and disadvantages for data analysis
Update (August 2014): as @gappy comments below, as of R version 3.0.0 the limits are higher and means R is capable of handling larger datasets.
Here's a data point: R has a "big data ceiling", useful
|
6,460
|
Do null and alternative hypotheses have to be exhaustive or not?
|
On principle, there is no reason for hypotheses to be exhaustive. If the test is about a parameter $\theta$ with $H_0$ being the restriction $\theta\in\Theta_0$, the alternative $H_a$ can be of any form $\theta\in\Theta_a$ as long as $$\Theta_0\cap\Theta_a=\emptyset.$$
An example as to why exhaustivity does not make much sense is when comparing two families of models, $H_0:\ x\sim f_0(x|\theta_0)$ versus $H_a:\ x\sim f_1(x|\theta_1)$. In such a case, exhaustivity is impossible, as the alternative would then have to cover all possible probability models.
|
Do null and alternative hypotheses have to be exhaustive or not?
|
On principle, there is no reason for hypotheses to be exhaustive. If the test is about a parameter $\theta$ with $H_0$ being the restriction $\theta\in\Theta_0$, the alternative $H_a$ can be of any fo
|
Do null and alternative hypotheses have to be exhaustive or not?
On principle, there is no reason for hypotheses to be exhaustive. If the test is about a parameter $\theta$ with $H_0$ being the restriction $\theta\in\Theta_0$, the alternative $H_a$ can be of any form $\theta\in\Theta_a$ as long as $$\Theta_0\cap\Theta_a=\emptyset.$$
An example as to why exhaustivity does not make much sense is when comparing two families of models, $H_0:\ x\sim f_0(x|\theta_0)$ versus $H_a:\ x\sim f_1(x|\theta_1)$. In such a case, exhaustivity is impossible, as the alternative would then have to cover all possible probability models.
|
Do null and alternative hypotheses have to be exhaustive or not?
On principle, there is no reason for hypotheses to be exhaustive. If the test is about a parameter $\theta$ with $H_0$ being the restriction $\theta\in\Theta_0$, the alternative $H_a$ can be of any fo
|
6,461
|
Do null and alternative hypotheses have to be exhaustive or not?
|
The main reason you see the requirement that hypotheses be exhaustive is the problem of what happens if the true parameter value is in the region which is not covered by either the null or alternative hypothesis. Then, testing at the $\alpha %$ level of confidence becomes meaningless, or, perhaps worse, your test will be biased in favor of the null - e.g., a one-sided test of the form $\theta = 0$ vs. $\theta > 0$, when actually $\theta < 0$.
An example: a one-sided test for $\mu = 0$ vs $\mu > 0$ from a Normal distribution with known $\sigma = 1$ and true $\mu = -0.1$. With a sample size of 100, a 95% test would reject if $\bar{x} > 0.1645$, but 0.1645 is actually 2.645 standard deviations above the true mean, leading to an actual test level of about 99.6%.
Also, you rule out the possibility of being surprised, and learning something interesting.
However, one can also look at it as defining the parameter space to be a subset of what might typically be considered the parameter space, e.g., the mean of a Normal distribution is often considered to lie somewhere on the real line, but if we do a one-sided test, we are, in effect, defining the parameter space to be the part of the line covered by the null and alternative.
|
Do null and alternative hypotheses have to be exhaustive or not?
|
The main reason you see the requirement that hypotheses be exhaustive is the problem of what happens if the true parameter value is in the region which is not covered by either the null or alternative
|
Do null and alternative hypotheses have to be exhaustive or not?
The main reason you see the requirement that hypotheses be exhaustive is the problem of what happens if the true parameter value is in the region which is not covered by either the null or alternative hypothesis. Then, testing at the $\alpha %$ level of confidence becomes meaningless, or, perhaps worse, your test will be biased in favor of the null - e.g., a one-sided test of the form $\theta = 0$ vs. $\theta > 0$, when actually $\theta < 0$.
An example: a one-sided test for $\mu = 0$ vs $\mu > 0$ from a Normal distribution with known $\sigma = 1$ and true $\mu = -0.1$. With a sample size of 100, a 95% test would reject if $\bar{x} > 0.1645$, but 0.1645 is actually 2.645 standard deviations above the true mean, leading to an actual test level of about 99.6%.
Also, you rule out the possibility of being surprised, and learning something interesting.
However, one can also look at it as defining the parameter space to be a subset of what might typically be considered the parameter space, e.g., the mean of a Normal distribution is often considered to lie somewhere on the real line, but if we do a one-sided test, we are, in effect, defining the parameter space to be the part of the line covered by the null and alternative.
|
Do null and alternative hypotheses have to be exhaustive or not?
The main reason you see the requirement that hypotheses be exhaustive is the problem of what happens if the true parameter value is in the region which is not covered by either the null or alternative
|
6,462
|
Do null and alternative hypotheses have to be exhaustive or not?
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
The alternative does not need to be exhaustive neither the null hypothesis must necessarily mean something different than what it states. For example, consider three independent observations $X_i\sim N(\mu_i,1)$, $i=1,2,3$, where $(\mu_1,\mu_2,\mu_3)\in\mathbb R^3$ and the problem of testing $H_0:\mu_1=\mu_2=\mu_3$ vs $H_1:\mu_1\leqslant\mu_2\leqslant\mu_3$ with at least one inequality being strict. This is a basic problem of order restricted inference, see e.g. Robertson, Wright and Dykstra (1988, Order Restricted Statistical Inference) or Silvapulle and Sen (2005, Constrained Statistical Inference: Inequality, Order, and Shape Restrictions). In this problem the null hypothesis does not mean anything else than that the three distributions coincide while the two hypotheses are not exhaustive.
|
Do null and alternative hypotheses have to be exhaustive or not?
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
Do null and alternative hypotheses have to be exhaustive or not?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
The alternative does not need to be exhaustive neither the null hypothesis must necessarily mean something different than what it states. For example, consider three independent observations $X_i\sim N(\mu_i,1)$, $i=1,2,3$, where $(\mu_1,\mu_2,\mu_3)\in\mathbb R^3$ and the problem of testing $H_0:\mu_1=\mu_2=\mu_3$ vs $H_1:\mu_1\leqslant\mu_2\leqslant\mu_3$ with at least one inequality being strict. This is a basic problem of order restricted inference, see e.g. Robertson, Wright and Dykstra (1988, Order Restricted Statistical Inference) or Silvapulle and Sen (2005, Constrained Statistical Inference: Inequality, Order, and Shape Restrictions). In this problem the null hypothesis does not mean anything else than that the three distributions coincide while the two hypotheses are not exhaustive.
|
Do null and alternative hypotheses have to be exhaustive or not?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
6,463
|
Good games for learning statistical thinking?
|
How about the game show "Deal or No Deal". Though not emphasized the banker is checking the probability given the number of remaining suitcases what the probability is that the 1,000,000 dollar prize is in your suitcase. Based on the odds he makes an offer that favors him. Whenever I watch this I am hoping the contestant understands expected gain and expected loss so as to not go for the bankers offer unless it is close to fair and a lot of money. As the game progresses an instructor can explain the odds and show the student how to compute what a fair offer would be.
The famous game show "Let's Make a Deal" had that flavor in it for the deal of the day at the end of the show. A slight modification led to the famous Monty Hall problem that baffled even some famous mathematicians.
Other games have aspects of probability in their decision making. With the spinning of the big wheel, there is the decision to hold with the first spin result or gamble to add to a higher total with the risk of going over $1. Even if you don't have a good prior distribution for the price of an item, bidding strategy can be partially based on an idea of a bet that is going to be reasonable and have a better chance of winning than the competitors. The best example is when you bid in the last position and the highest bid so far has a good chance in your mind to be below the actual price. Then bidding 1 dollar over it (the minimum that you can bid over) is a very good strategy. Many people actually use that strategy and very often are successful.
In addition I think Jeopardy with a statistics board of categories might be a fun way to reinforce concepts through competition. I have seen this work well and be fun for medical topics and once played it on categories for nutrition to teach good eating habits.
|
Good games for learning statistical thinking?
|
How about the game show "Deal or No Deal". Though not emphasized the banker is checking the probability given the number of remaining suitcases what the probability is that the 1,000,000 dollar priz
|
Good games for learning statistical thinking?
How about the game show "Deal or No Deal". Though not emphasized the banker is checking the probability given the number of remaining suitcases what the probability is that the 1,000,000 dollar prize is in your suitcase. Based on the odds he makes an offer that favors him. Whenever I watch this I am hoping the contestant understands expected gain and expected loss so as to not go for the bankers offer unless it is close to fair and a lot of money. As the game progresses an instructor can explain the odds and show the student how to compute what a fair offer would be.
The famous game show "Let's Make a Deal" had that flavor in it for the deal of the day at the end of the show. A slight modification led to the famous Monty Hall problem that baffled even some famous mathematicians.
Other games have aspects of probability in their decision making. With the spinning of the big wheel, there is the decision to hold with the first spin result or gamble to add to a higher total with the risk of going over $1. Even if you don't have a good prior distribution for the price of an item, bidding strategy can be partially based on an idea of a bet that is going to be reasonable and have a better chance of winning than the competitors. The best example is when you bid in the last position and the highest bid so far has a good chance in your mind to be below the actual price. Then bidding 1 dollar over it (the minimum that you can bid over) is a very good strategy. Many people actually use that strategy and very often are successful.
In addition I think Jeopardy with a statistics board of categories might be a fun way to reinforce concepts through competition. I have seen this work well and be fun for medical topics and once played it on categories for nutrition to teach good eating habits.
|
Good games for learning statistical thinking?
How about the game show "Deal or No Deal". Though not emphasized the banker is checking the probability given the number of remaining suitcases what the probability is that the 1,000,000 dollar priz
|
6,464
|
Good games for learning statistical thinking?
|
Fantasy sports incentivize players to think with statistical intuition. For example, every week in fantasy football you must choose which players to start based on, e.g.:
that player's career stats,
the trend in the time series of that player's stats,
the team he is going up against,
weather,
injuries,
and many more. According to http://www.fsta.org/, 32 million people in the US and Canada now play some type of fantasy sport! I know that it was one of the major reasons I developed an interest in statistics.
|
Good games for learning statistical thinking?
|
Fantasy sports incentivize players to think with statistical intuition. For example, every week in fantasy football you must choose which players to start based on, e.g.:
that player's career stats,
|
Good games for learning statistical thinking?
Fantasy sports incentivize players to think with statistical intuition. For example, every week in fantasy football you must choose which players to start based on, e.g.:
that player's career stats,
the trend in the time series of that player's stats,
the team he is going up against,
weather,
injuries,
and many more. According to http://www.fsta.org/, 32 million people in the US and Canada now play some type of fantasy sport! I know that it was one of the major reasons I developed an interest in statistics.
|
Good games for learning statistical thinking?
Fantasy sports incentivize players to think with statistical intuition. For example, every week in fantasy football you must choose which players to start based on, e.g.:
that player's career stats,
|
6,465
|
Good games for learning statistical thinking?
|
Poker is a good game for learning probabilistic thinking. The game has been dominated at the highest level in recent years by "math nerds" who have spent a lot of time studying the odds and spend very little time trying to read their opponents. Check out the Time article World Series of Poker: Attack of the Math Brats for some details.
Also, I can't find any specific examples yet, but NPR's "Math Guy" Keith Devlin has spent a lot of time in the past few years promoting video gaming as the future of math education. Some of the links in that article might be a good starting point, or you might want to check out his book on the subject, Mathematics Education for a New Era: Video Games as a Medium for Learning.
|
Good games for learning statistical thinking?
|
Poker is a good game for learning probabilistic thinking. The game has been dominated at the highest level in recent years by "math nerds" who have spent a lot of time studying the odds and spend ver
|
Good games for learning statistical thinking?
Poker is a good game for learning probabilistic thinking. The game has been dominated at the highest level in recent years by "math nerds" who have spent a lot of time studying the odds and spend very little time trying to read their opponents. Check out the Time article World Series of Poker: Attack of the Math Brats for some details.
Also, I can't find any specific examples yet, but NPR's "Math Guy" Keith Devlin has spent a lot of time in the past few years promoting video gaming as the future of math education. Some of the links in that article might be a good starting point, or you might want to check out his book on the subject, Mathematics Education for a New Era: Video Games as a Medium for Learning.
|
Good games for learning statistical thinking?
Poker is a good game for learning probabilistic thinking. The game has been dominated at the highest level in recent years by "math nerds" who have spent a lot of time studying the odds and spend ver
|
6,466
|
Good games for learning statistical thinking?
|
Democracy by Positech is mostly a web model of all the statistical and political interactions that get news coverage. It includes polling and bias as a game mechanic but pretty much nothing else requested in the opening post. However having to conduct those studies to reveal interactions would gel very well with the game as it is now. There exist far better programing games like Hack n Slash, Quadrilateral Cowboy and Cosmic Supremacy. My Get Smarter Games playlist.
|
Good games for learning statistical thinking?
|
Democracy by Positech is mostly a web model of all the statistical and political interactions that get news coverage. It includes polling and bias as a game mechanic but pretty much nothing else reque
|
Good games for learning statistical thinking?
Democracy by Positech is mostly a web model of all the statistical and political interactions that get news coverage. It includes polling and bias as a game mechanic but pretty much nothing else requested in the opening post. However having to conduct those studies to reveal interactions would gel very well with the game as it is now. There exist far better programing games like Hack n Slash, Quadrilateral Cowboy and Cosmic Supremacy. My Get Smarter Games playlist.
|
Good games for learning statistical thinking?
Democracy by Positech is mostly a web model of all the statistical and political interactions that get news coverage. It includes polling and bias as a game mechanic but pretty much nothing else reque
|
6,467
|
Good games for learning statistical thinking?
|
I have made some statistics games for teaching. They deal with confidence intervals, hypothesis tests (Neyman-Pearson) and significance tests (Fisherian).
They are excellent tools for engaging students in lectures/workshops and a subset of the students spend quite a lot of time playing them.
I have been going to make an online high scores leader-board to make the game aspect more competitive but, well, I haven't got around to it ;-)
|
Good games for learning statistical thinking?
|
I have made some statistics games for teaching. They deal with confidence intervals, hypothesis tests (Neyman-Pearson) and significance tests (Fisherian).
They are excellent tools for engaging student
|
Good games for learning statistical thinking?
I have made some statistics games for teaching. They deal with confidence intervals, hypothesis tests (Neyman-Pearson) and significance tests (Fisherian).
They are excellent tools for engaging students in lectures/workshops and a subset of the students spend quite a lot of time playing them.
I have been going to make an online high scores leader-board to make the game aspect more competitive but, well, I haven't got around to it ;-)
|
Good games for learning statistical thinking?
I have made some statistics games for teaching. They deal with confidence intervals, hypothesis tests (Neyman-Pearson) and significance tests (Fisherian).
They are excellent tools for engaging student
|
6,468
|
ANOVA on binomial data
|
No to ANOVA, which assumes a normally distributed outcome variable (among other things). There are "old school" transformations to consider, but I would prefer logistic regression (equivalent to a chi square when there is only one independent variable, as in your case). The advantage of using logistic regression over a chi square test is that you can easily use a linear contrast to compare specific levels of the treatment if you find a significant result to the overall test (type 3). For example A versus B, B versus C etc.
Update Added for clarity:
Taking data at hand (the post doc data set from Allison) and using the variable cits as follows, this was my point:
postdocData$citsBin <- ifelse(postdocData$cits>2, 3, postdocData$cits)
postdocData$citsBin <- as.factor(postdocData$citsBin)
ordered(postdocData$citsBin, levels=c("0", "1", "2", "3"))
contrasts(postdocData$citsBin) <- contr.treatment(4, base=4) # set 4th level as reference
contrasts(postdocData$citsBin)
# 1 2 3
# 0 1 0 0
# 1 0 1 0
# 2 0 0 1
# 3 0 0 0
# fit the univariate logistic regression model
model.1 <- glm(pdoc~citsBin, data=postdocData, family=binomial(link="logit"))
library(car) # John Fox package
car::Anova(model.1, test="LR", type="III") # type 3 analysis (SAS verbiage)
# Response: pdoc
# LR Chisq Df Pr(>Chisq)
# citsBin 1.7977 3 0.6154
chisq.test(table(postdocData$citsBin, postdocData$pdoc))
# X-squared = 1.7957, df = 3, p-value = 0.6159
# then can test differences in levels, such as: contrast cits=0 minus cits=1 = 0
# Ho: Beta_1 - Beta_2 = 0
cVec <- c(0,1,-1,0)
car::linearHypothesis(model.1, cVec, verbose=TRUE)
|
ANOVA on binomial data
|
No to ANOVA, which assumes a normally distributed outcome variable (among other things). There are "old school" transformations to consider, but I would prefer logistic regression (equivalent to a chi
|
ANOVA on binomial data
No to ANOVA, which assumes a normally distributed outcome variable (among other things). There are "old school" transformations to consider, but I would prefer logistic regression (equivalent to a chi square when there is only one independent variable, as in your case). The advantage of using logistic regression over a chi square test is that you can easily use a linear contrast to compare specific levels of the treatment if you find a significant result to the overall test (type 3). For example A versus B, B versus C etc.
Update Added for clarity:
Taking data at hand (the post doc data set from Allison) and using the variable cits as follows, this was my point:
postdocData$citsBin <- ifelse(postdocData$cits>2, 3, postdocData$cits)
postdocData$citsBin <- as.factor(postdocData$citsBin)
ordered(postdocData$citsBin, levels=c("0", "1", "2", "3"))
contrasts(postdocData$citsBin) <- contr.treatment(4, base=4) # set 4th level as reference
contrasts(postdocData$citsBin)
# 1 2 3
# 0 1 0 0
# 1 0 1 0
# 2 0 0 1
# 3 0 0 0
# fit the univariate logistic regression model
model.1 <- glm(pdoc~citsBin, data=postdocData, family=binomial(link="logit"))
library(car) # John Fox package
car::Anova(model.1, test="LR", type="III") # type 3 analysis (SAS verbiage)
# Response: pdoc
# LR Chisq Df Pr(>Chisq)
# citsBin 1.7977 3 0.6154
chisq.test(table(postdocData$citsBin, postdocData$pdoc))
# X-squared = 1.7957, df = 3, p-value = 0.6159
# then can test differences in levels, such as: contrast cits=0 minus cits=1 = 0
# Ho: Beta_1 - Beta_2 = 0
cVec <- c(0,1,-1,0)
car::linearHypothesis(model.1, cVec, verbose=TRUE)
|
ANOVA on binomial data
No to ANOVA, which assumes a normally distributed outcome variable (among other things). There are "old school" transformations to consider, but I would prefer logistic regression (equivalent to a chi
|
6,469
|
ANOVA on binomial data
|
Maybe some consider it old-fashioned, but if you only want to test the null hypothesis of all groups having equal success probability, then you can define
$X_k$ as number of successes in group $k$, $n_k$ as number of trials in group $k$, the estimated probability in group $k$ will be $\hat{p}_k=X_k/n_k$, and then use the variance-stabilizing transformation for the binomial, which is
$$
g(p) = \arcsin \sqrt{p}
$$
Such an approach was (at times) good enough for Fisher, so can be useful also today!
However, some modern authors are quite sceptical of the arcsine transformation, see for example http://www.mun.ca/biology/dschneider/b7932/B7932Final10Dec2010.pdf But this authors are concerned with problems such as prediction, where they show the arcsine can lead to problems. If you are only concerned with hypothesis testing, it should be OK. A more modern approach could use logistic regression.
|
ANOVA on binomial data
|
Maybe some consider it old-fashioned, but if you only want to test the null hypothesis of all groups having equal success probability, then you can define
$X_k$ as number of successes in group $k$, $n
|
ANOVA on binomial data
Maybe some consider it old-fashioned, but if you only want to test the null hypothesis of all groups having equal success probability, then you can define
$X_k$ as number of successes in group $k$, $n_k$ as number of trials in group $k$, the estimated probability in group $k$ will be $\hat{p}_k=X_k/n_k$, and then use the variance-stabilizing transformation for the binomial, which is
$$
g(p) = \arcsin \sqrt{p}
$$
Such an approach was (at times) good enough for Fisher, so can be useful also today!
However, some modern authors are quite sceptical of the arcsine transformation, see for example http://www.mun.ca/biology/dschneider/b7932/B7932Final10Dec2010.pdf But this authors are concerned with problems such as prediction, where they show the arcsine can lead to problems. If you are only concerned with hypothesis testing, it should be OK. A more modern approach could use logistic regression.
|
ANOVA on binomial data
Maybe some consider it old-fashioned, but if you only want to test the null hypothesis of all groups having equal success probability, then you can define
$X_k$ as number of successes in group $k$, $n
|
6,470
|
ANOVA on binomial data
|
I would like to differ from what you think about Chi-Sq test. It is applicable even if the data is not binomial. It's based on the asymptotic normality of mle (in most of the cases).
I would do a logistic regression like this:
$$\log \frac {\hat{\pi}} {1-\hat{\pi}} = \beta_0 + \beta_1 \times D_1 + \beta_2 \times D_2$$
where
$D_1$ and $D_2$ are dummy variables. $D_1 = D_2 = 0 \implies A, D_1 = 1, D_2 = 0 \implies B, D_1 = 1 D_2 = 1 \implies C$
$$H_o : \beta_0 = \beta_1 = \beta_2 = 0$$
Is the ANOVA equivalent if there is a relation or not.
$$H_o : \beta_0 = 0$$
Is the test is A has some effect.
$$H_o : \beta_1 - \beta_0 = 0$$
Is the test is B has some effect.
$$H_o : \beta_2 - (\frac {\beta_0+\beta_1} {2}) = 0$$
Is the test is C has some effect.
Now you can do further contrasts to find our what you are interested in. It is still a chi-sq test, but with different degrees of freedom (3, 1, 1, and 1, respectively)
|
ANOVA on binomial data
|
I would like to differ from what you think about Chi-Sq test. It is applicable even if the data is not binomial. It's based on the asymptotic normality of mle (in most of the cases).
I would do a log
|
ANOVA on binomial data
I would like to differ from what you think about Chi-Sq test. It is applicable even if the data is not binomial. It's based on the asymptotic normality of mle (in most of the cases).
I would do a logistic regression like this:
$$\log \frac {\hat{\pi}} {1-\hat{\pi}} = \beta_0 + \beta_1 \times D_1 + \beta_2 \times D_2$$
where
$D_1$ and $D_2$ are dummy variables. $D_1 = D_2 = 0 \implies A, D_1 = 1, D_2 = 0 \implies B, D_1 = 1 D_2 = 1 \implies C$
$$H_o : \beta_0 = \beta_1 = \beta_2 = 0$$
Is the ANOVA equivalent if there is a relation or not.
$$H_o : \beta_0 = 0$$
Is the test is A has some effect.
$$H_o : \beta_1 - \beta_0 = 0$$
Is the test is B has some effect.
$$H_o : \beta_2 - (\frac {\beta_0+\beta_1} {2}) = 0$$
Is the test is C has some effect.
Now you can do further contrasts to find our what you are interested in. It is still a chi-sq test, but with different degrees of freedom (3, 1, 1, and 1, respectively)
|
ANOVA on binomial data
I would like to differ from what you think about Chi-Sq test. It is applicable even if the data is not binomial. It's based on the asymptotic normality of mle (in most of the cases).
I would do a log
|
6,471
|
ANOVA on binomial data
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I think you are right that ANOVA should not be used to analyze binomial dependent variable. Many people use this to compare means of the binary response variable (0 1) but it should not be used because this seriously violates the Normality and Equal variance assumption. Chi-Square tests or Logistic regression are best for these situations.
|
ANOVA on binomial data
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
ANOVA on binomial data
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I think you are right that ANOVA should not be used to analyze binomial dependent variable. Many people use this to compare means of the binary response variable (0 1) but it should not be used because this seriously violates the Normality and Equal variance assumption. Chi-Square tests or Logistic regression are best for these situations.
|
ANOVA on binomial data
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
6,472
|
How to present results of a Lasso using glmnet?
|
My understanding is that you can't necessarily say much about which variables are "important" or have "real" effects based on whether their coefficients are nonzero. To give an extreme example, if you have two predictors that are perfectly collinear, the lasso will pick one of them essentially at random to get the full weight and the other one will get zero weight.
This paper, which includes one of the authors of glmnet, presents some glmnet-based analyses (see especially: the Introduction, Sections 2.3 and 4.3, and Tables 4 and 5). Glancing through, it looks like they didn't calculate P-valued directly from the glmnet model. They did calculate two different kinds of P-values using other methods, but it doesn't look like they fully trust either of them.
I'm not 100% sure what you're suggesting in terms of plotting methods, but I think it sounds reasonable.
Hope that helps.
|
How to present results of a Lasso using glmnet?
|
My understanding is that you can't necessarily say much about which variables are "important" or have "real" effects based on whether their coefficients are nonzero. To give an extreme example, if yo
|
How to present results of a Lasso using glmnet?
My understanding is that you can't necessarily say much about which variables are "important" or have "real" effects based on whether their coefficients are nonzero. To give an extreme example, if you have two predictors that are perfectly collinear, the lasso will pick one of them essentially at random to get the full weight and the other one will get zero weight.
This paper, which includes one of the authors of glmnet, presents some glmnet-based analyses (see especially: the Introduction, Sections 2.3 and 4.3, and Tables 4 and 5). Glancing through, it looks like they didn't calculate P-valued directly from the glmnet model. They did calculate two different kinds of P-values using other methods, but it doesn't look like they fully trust either of them.
I'm not 100% sure what you're suggesting in terms of plotting methods, but I think it sounds reasonable.
Hope that helps.
|
How to present results of a Lasso using glmnet?
My understanding is that you can't necessarily say much about which variables are "important" or have "real" effects based on whether their coefficients are nonzero. To give an extreme example, if yo
|
6,473
|
How to present results of a Lasso using glmnet?
|
I just wanted to point out that there is recent work trying to develop a test statistic specifically for the LASSO, which takes into account the feature selection being performed:
A significance test for the lasso.
Richard Lockhart, Jonathan Taylor, Ryan J. Tibshirani, Robert Tibshirani.
http://arxiv.org/abs/1301.7161
I haven't seen this used in applied work yet however, whereas bootstrapping certainly is used.
|
How to present results of a Lasso using glmnet?
|
I just wanted to point out that there is recent work trying to develop a test statistic specifically for the LASSO, which takes into account the feature selection being performed:
A significance test
|
How to present results of a Lasso using glmnet?
I just wanted to point out that there is recent work trying to develop a test statistic specifically for the LASSO, which takes into account the feature selection being performed:
A significance test for the lasso.
Richard Lockhart, Jonathan Taylor, Ryan J. Tibshirani, Robert Tibshirani.
http://arxiv.org/abs/1301.7161
I haven't seen this used in applied work yet however, whereas bootstrapping certainly is used.
|
How to present results of a Lasso using glmnet?
I just wanted to point out that there is recent work trying to develop a test statistic specifically for the LASSO, which takes into account the feature selection being performed:
A significance test
|
6,474
|
How to present results of a Lasso using glmnet?
|
Regarding inference for LASSO or elastic net models have a look at CRAN packages selectiveInference and hdi, they do exactly that whilst taking into account the variable selection step!
|
How to present results of a Lasso using glmnet?
|
Regarding inference for LASSO or elastic net models have a look at CRAN packages selectiveInference and hdi, they do exactly that whilst taking into account the variable selection step!
|
How to present results of a Lasso using glmnet?
Regarding inference for LASSO or elastic net models have a look at CRAN packages selectiveInference and hdi, they do exactly that whilst taking into account the variable selection step!
|
How to present results of a Lasso using glmnet?
Regarding inference for LASSO or elastic net models have a look at CRAN packages selectiveInference and hdi, they do exactly that whilst taking into account the variable selection step!
|
6,475
|
When should one use Coordinate descent vs. gradient descent?
|
I think it usually is a matter of how simple/easy it is to work out the gradient of the smooth part of the function and/or the proximal operator of the penalty.
Sometimes, it is a lot more simple to find an exact solution of the problem in the case with one single variable (or a block or variables), than it is to work it out for all variables simultaneously. Othertimes it is just too expensive to compute the gradient compared to the individual derivatives. Also, the convergence of coordinate descent is the same as for ista, $1/k^2$, where $k$ is the number of iterations, but it may sometimes perform better compared to both ISTA and FISTA, see e.g. https://tibshirani.su.domains/comparison.txt.
Such things will influence the choice of coordinate descent vs. ISTA/FISTA, for instance.
|
When should one use Coordinate descent vs. gradient descent?
|
I think it usually is a matter of how simple/easy it is to work out the gradient of the smooth part of the function and/or the proximal operator of the penalty.
Sometimes, it is a lot more simple to f
|
When should one use Coordinate descent vs. gradient descent?
I think it usually is a matter of how simple/easy it is to work out the gradient of the smooth part of the function and/or the proximal operator of the penalty.
Sometimes, it is a lot more simple to find an exact solution of the problem in the case with one single variable (or a block or variables), than it is to work it out for all variables simultaneously. Othertimes it is just too expensive to compute the gradient compared to the individual derivatives. Also, the convergence of coordinate descent is the same as for ista, $1/k^2$, where $k$ is the number of iterations, but it may sometimes perform better compared to both ISTA and FISTA, see e.g. https://tibshirani.su.domains/comparison.txt.
Such things will influence the choice of coordinate descent vs. ISTA/FISTA, for instance.
|
When should one use Coordinate descent vs. gradient descent?
I think it usually is a matter of how simple/easy it is to work out the gradient of the smooth part of the function and/or the proximal operator of the penalty.
Sometimes, it is a lot more simple to f
|
6,476
|
When should one use Coordinate descent vs. gradient descent?
|
Coordinate descent updates one parameter at a time, while gradient descent attempts to update all parameters at once.
It's hard to specify exactly when one algorithm will do better than the other. For example, I was very shocked to learn that coordinate descent was state of the art for LASSO. And I was not the only one; see slide 17.
With that said, there are some features that can make a problem more amendable to coordinate descent:
(1) Fast conditional updates. If, for some reason, the problem allows one to individually optimize parameters very quickly, coordinate descent can make use of this. For example, one may be able to update certain parameters using only a subset of the data, greatly reducing computational cost of these updates. Another case is if there is a closed form solution for an individual parameter, conditional on the values of all the other parameters.
(2) Relatively independent modes for parameters. If the optimal value of one parameter is completely independent of the other parameters values, then one round of coordinate descent will lead to the solution (assuming that each coordinate update finds the current mode). On the other hand, if the mode for a given parameter is very highly dependent on other parameter values, coordinate descent is very likely to inch along, with very small updates at each round.
Unfortunately, for most problems, (2) does not hold, so it is rare that coordinate descent does well compared alternative algorithms. I believe the reason it performs well for LASSO is that there are a lot of tricks one can use to enact condition (1).
For gradient descent, this algorithm will work well if the second derivative is relatively stable, a good $\alpha$ is selected and the off-diagonal of the Hessian is relatively small compared with the diagonal entries. These conditions are rare as well, so it generally performs worse than algorithms such as L-BFGS.
|
When should one use Coordinate descent vs. gradient descent?
|
Coordinate descent updates one parameter at a time, while gradient descent attempts to update all parameters at once.
It's hard to specify exactly when one algorithm will do better than the other. Fo
|
When should one use Coordinate descent vs. gradient descent?
Coordinate descent updates one parameter at a time, while gradient descent attempts to update all parameters at once.
It's hard to specify exactly when one algorithm will do better than the other. For example, I was very shocked to learn that coordinate descent was state of the art for LASSO. And I was not the only one; see slide 17.
With that said, there are some features that can make a problem more amendable to coordinate descent:
(1) Fast conditional updates. If, for some reason, the problem allows one to individually optimize parameters very quickly, coordinate descent can make use of this. For example, one may be able to update certain parameters using only a subset of the data, greatly reducing computational cost of these updates. Another case is if there is a closed form solution for an individual parameter, conditional on the values of all the other parameters.
(2) Relatively independent modes for parameters. If the optimal value of one parameter is completely independent of the other parameters values, then one round of coordinate descent will lead to the solution (assuming that each coordinate update finds the current mode). On the other hand, if the mode for a given parameter is very highly dependent on other parameter values, coordinate descent is very likely to inch along, with very small updates at each round.
Unfortunately, for most problems, (2) does not hold, so it is rare that coordinate descent does well compared alternative algorithms. I believe the reason it performs well for LASSO is that there are a lot of tricks one can use to enact condition (1).
For gradient descent, this algorithm will work well if the second derivative is relatively stable, a good $\alpha$ is selected and the off-diagonal of the Hessian is relatively small compared with the diagonal entries. These conditions are rare as well, so it generally performs worse than algorithms such as L-BFGS.
|
When should one use Coordinate descent vs. gradient descent?
Coordinate descent updates one parameter at a time, while gradient descent attempts to update all parameters at once.
It's hard to specify exactly when one algorithm will do better than the other. Fo
|
6,477
|
When should one use Coordinate descent vs. gradient descent?
|
I realise that this is an old question and has some very good answers. I would like to share some practical personal experience.
When working with generative machine learning techniques, you are usually working with some sort of probabilities. An example may be the mixture probabilities of the $k$ components in a mixture model. They have the following constraints:
All probabilities must be positive.
All elements of the probability set must sum up to one
This is actually asking a lot. With gradient descent one usually deals with constraints via a penalty function. Here it will not work. As soon as a value violates one of these constraints, your code will typically raise a numerical error of sorts. So one has to deal with the constraints by never actually allowing the optimisation algorithm to traverse it.
There are numerous transformations that you can apply to your problem to satisfy the constraints in order to allows gradient descent. However, if you are looking for the easiest and most lazy way to implement this then coordinate descent is the way to go:
For each probability $p_i$:
$p_i^{k+1} = p_i^{k} - \eta \frac{\partial J}{\partial p_i}$
$p_i = \min(\max(p_i,0),1)$
Update all p_i: $\mathbf{P}^{j+1} = \mathbf{P}^j \cdot \frac{1}{\sum_{i=1}^n p_i} $
For someone like me that work in Python, this usually means that I have to use an additional for-loop which impacts performance quite negatively. Gradient descent allows me to use Numpy which is performance optimised. One can get very good speed with it, however, this is not achievable with coordinate descent so I usually use some transform technique.
So the conclusion really is that coordinate descent is the easiest option to deal with very strict constraints such as the rate parameter in the Poisson distribution. If its becomes negative, you code complains etc.
I hope this has added a bit of insight.
|
When should one use Coordinate descent vs. gradient descent?
|
I realise that this is an old question and has some very good answers. I would like to share some practical personal experience.
When working with generative machine learning techniques, you are usual
|
When should one use Coordinate descent vs. gradient descent?
I realise that this is an old question and has some very good answers. I would like to share some practical personal experience.
When working with generative machine learning techniques, you are usually working with some sort of probabilities. An example may be the mixture probabilities of the $k$ components in a mixture model. They have the following constraints:
All probabilities must be positive.
All elements of the probability set must sum up to one
This is actually asking a lot. With gradient descent one usually deals with constraints via a penalty function. Here it will not work. As soon as a value violates one of these constraints, your code will typically raise a numerical error of sorts. So one has to deal with the constraints by never actually allowing the optimisation algorithm to traverse it.
There are numerous transformations that you can apply to your problem to satisfy the constraints in order to allows gradient descent. However, if you are looking for the easiest and most lazy way to implement this then coordinate descent is the way to go:
For each probability $p_i$:
$p_i^{k+1} = p_i^{k} - \eta \frac{\partial J}{\partial p_i}$
$p_i = \min(\max(p_i,0),1)$
Update all p_i: $\mathbf{P}^{j+1} = \mathbf{P}^j \cdot \frac{1}{\sum_{i=1}^n p_i} $
For someone like me that work in Python, this usually means that I have to use an additional for-loop which impacts performance quite negatively. Gradient descent allows me to use Numpy which is performance optimised. One can get very good speed with it, however, this is not achievable with coordinate descent so I usually use some transform technique.
So the conclusion really is that coordinate descent is the easiest option to deal with very strict constraints such as the rate parameter in the Poisson distribution. If its becomes negative, you code complains etc.
I hope this has added a bit of insight.
|
When should one use Coordinate descent vs. gradient descent?
I realise that this is an old question and has some very good answers. I would like to share some practical personal experience.
When working with generative machine learning techniques, you are usual
|
6,478
|
(Why) do overfitted models tend to have large coefficients?
|
In the regularisation context a "large" coefficient means that the estimate's magnitude is larger than it would have been, if a fixed model specification had been used. It's the impact of obtaining not just the estimates, but also the model specification, from the data.
Consider what a procedure like stepwise regression will do for a given variable. If the estimate of its coefficient is small relative to the standard error, it will get dropped from the model. This could be because the true value really is small, or simply because of random error (or a combination of the two). If it's dropped, then we no longer pay it any attention. On the other hand, if the estimate is large relative to its standard error, it will be retained. Notice the imbalance: our final model will reject a variable when the coefficient estimate is small, but we will keep it when the estimate is large. Thus we are likely to overestimate its value.
Put another way, what overfitting means is you're overstating the impact of a given set of predictors on the response. But the only way that you can overstate the impact is if the estimated coefficients are too big (and conversely, the estimates for your excluded predictors are too small).
What you should do is incorporate into your experiment a variable selection procedure, eg stepwise regression via step. Then repeat your experiment multiple times, on different random samples, and save the estimates. You should find that all the estimates of the coefficients $\beta_3$ to $\beta_{10}$ are systematically too large, when compared to not using variable selection. Regularisation procedures aim to fix or mitigate this problem.
Here's an example of what I'm talking about.
repeat.exp <- function(M)
{
x <- seq(-2, 2, len=25)
px <- poly(x, 10)
colnames(px) <- paste0("x", 1:10)
out <- setNames(rep(NA, 11), c("(Intercept)", colnames(px)))
sapply(1:M, function(...) {
y <- x^2 + rnorm(N, s=2)
d <- data.frame(px, y)
b <- coef(step(lm(y ~ x1, data=d), y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10, trace=0))
out[names(b)] <- b
out
})
}
set.seed(53520)
z <- repeat.exp(M=1000)
# some time later...
rowMeans(abs(z), na.rm=TRUE)
(Intercept) x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
1.453553 3.162100 6.533642 3.108974 3.204341 3.131208 3.118276 3.217231 3.293691 3.149520 3.073062
Contrast this to what happens when you don't use variable selection, and just fit everything blindly. While there is still some error in the estimates of $\beta_3$ to $\beta_{10}$, the average deviation is much smaller.
repeat.exp.base <- function(M)
{
x <- seq(-2, 2, len=25)
px <- poly(x, 10)
colnames(px) <- paste0("x", 1:10)
out <- setNames(rep(NA, 11), c("(Intercept)", colnames(px)))
sapply(1:M, function(...) {
y <- x^2 + rnorm(N, s=2)
d <- data.frame(px, y)
b <- coef(lm(y ~ ., data=d))
out[names(b)] <- b
out
})
}
set.seed(53520)
z2 <- repeat.exp.base(M=1000)
rowMeans(abs(z2))
(Intercept) x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
1.453553 1.676066 6.400629 1.589061 1.648441 1.584861 1.611819 1.607720 1.656267 1.583362 1.556168
Also, both L1 and L2 regularisation make the implicit assumption that all your variables, and hence coefficients, are in the same units of measurement, ie a unit change in $\beta_1$ is equivalent to a unit change in $\beta_2$. Hence the usual step of standardising your variables before applying either of these techniques.
|
(Why) do overfitted models tend to have large coefficients?
|
In the regularisation context a "large" coefficient means that the estimate's magnitude is larger than it would have been, if a fixed model specification had been used. It's the impact of obtaining no
|
(Why) do overfitted models tend to have large coefficients?
In the regularisation context a "large" coefficient means that the estimate's magnitude is larger than it would have been, if a fixed model specification had been used. It's the impact of obtaining not just the estimates, but also the model specification, from the data.
Consider what a procedure like stepwise regression will do for a given variable. If the estimate of its coefficient is small relative to the standard error, it will get dropped from the model. This could be because the true value really is small, or simply because of random error (or a combination of the two). If it's dropped, then we no longer pay it any attention. On the other hand, if the estimate is large relative to its standard error, it will be retained. Notice the imbalance: our final model will reject a variable when the coefficient estimate is small, but we will keep it when the estimate is large. Thus we are likely to overestimate its value.
Put another way, what overfitting means is you're overstating the impact of a given set of predictors on the response. But the only way that you can overstate the impact is if the estimated coefficients are too big (and conversely, the estimates for your excluded predictors are too small).
What you should do is incorporate into your experiment a variable selection procedure, eg stepwise regression via step. Then repeat your experiment multiple times, on different random samples, and save the estimates. You should find that all the estimates of the coefficients $\beta_3$ to $\beta_{10}$ are systematically too large, when compared to not using variable selection. Regularisation procedures aim to fix or mitigate this problem.
Here's an example of what I'm talking about.
repeat.exp <- function(M)
{
x <- seq(-2, 2, len=25)
px <- poly(x, 10)
colnames(px) <- paste0("x", 1:10)
out <- setNames(rep(NA, 11), c("(Intercept)", colnames(px)))
sapply(1:M, function(...) {
y <- x^2 + rnorm(N, s=2)
d <- data.frame(px, y)
b <- coef(step(lm(y ~ x1, data=d), y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10, trace=0))
out[names(b)] <- b
out
})
}
set.seed(53520)
z <- repeat.exp(M=1000)
# some time later...
rowMeans(abs(z), na.rm=TRUE)
(Intercept) x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
1.453553 3.162100 6.533642 3.108974 3.204341 3.131208 3.118276 3.217231 3.293691 3.149520 3.073062
Contrast this to what happens when you don't use variable selection, and just fit everything blindly. While there is still some error in the estimates of $\beta_3$ to $\beta_{10}$, the average deviation is much smaller.
repeat.exp.base <- function(M)
{
x <- seq(-2, 2, len=25)
px <- poly(x, 10)
colnames(px) <- paste0("x", 1:10)
out <- setNames(rep(NA, 11), c("(Intercept)", colnames(px)))
sapply(1:M, function(...) {
y <- x^2 + rnorm(N, s=2)
d <- data.frame(px, y)
b <- coef(lm(y ~ ., data=d))
out[names(b)] <- b
out
})
}
set.seed(53520)
z2 <- repeat.exp.base(M=1000)
rowMeans(abs(z2))
(Intercept) x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
1.453553 1.676066 6.400629 1.589061 1.648441 1.584861 1.611819 1.607720 1.656267 1.583362 1.556168
Also, both L1 and L2 regularisation make the implicit assumption that all your variables, and hence coefficients, are in the same units of measurement, ie a unit change in $\beta_1$ is equivalent to a unit change in $\beta_2$. Hence the usual step of standardising your variables before applying either of these techniques.
|
(Why) do overfitted models tend to have large coefficients?
In the regularisation context a "large" coefficient means that the estimate's magnitude is larger than it would have been, if a fixed model specification had been used. It's the impact of obtaining no
|
6,479
|
(Why) do overfitted models tend to have large coefficients?
|
One very simple answer without looking into your details: When you are overfitting, the parameter estimators tend to get large variances, and with large variances large values are just what you should expect!
|
(Why) do overfitted models tend to have large coefficients?
|
One very simple answer without looking into your details: When you are overfitting, the parameter estimators tend to get large variances, and with large variances large values are just what you shoul
|
(Why) do overfitted models tend to have large coefficients?
One very simple answer without looking into your details: When you are overfitting, the parameter estimators tend to get large variances, and with large variances large values are just what you should expect!
|
(Why) do overfitted models tend to have large coefficients?
One very simple answer without looking into your details: When you are overfitting, the parameter estimators tend to get large variances, and with large variances large values are just what you shoul
|
6,480
|
(Why) do overfitted models tend to have large coefficients?
|
David. I think the problem with your example is you haven't normalised your data ( ie X^10>> X.
So david is right that it shrinks larger coefficients more ( so you can end up with lots of small coefficients, whilst L1 regularisation might give you one large and the rest zero)
so basically it is encapsulating that small changes should have small effects (and of course we are back to the issue of how small is small - normalising your data etc).
But the key thing is in higher dimensions, where correlation comes into play:
imagine you have two variables x,y that are highly correlated (both normalised to variance 1) then their difference will be small ="noise" - penalising large weights will therefore prevent you fitting to this noise ( and getting very large almost cancelling coefficients for y and x).
The example still holds for any linear relation (y=mx)
look up ridge regression
|
(Why) do overfitted models tend to have large coefficients?
|
David. I think the problem with your example is you haven't normalised your data ( ie X^10>> X.
So david is right that it shrinks larger coefficients more ( so you can end up with lots of small coeffi
|
(Why) do overfitted models tend to have large coefficients?
David. I think the problem with your example is you haven't normalised your data ( ie X^10>> X.
So david is right that it shrinks larger coefficients more ( so you can end up with lots of small coefficients, whilst L1 regularisation might give you one large and the rest zero)
so basically it is encapsulating that small changes should have small effects (and of course we are back to the issue of how small is small - normalising your data etc).
But the key thing is in higher dimensions, where correlation comes into play:
imagine you have two variables x,y that are highly correlated (both normalised to variance 1) then their difference will be small ="noise" - penalising large weights will therefore prevent you fitting to this noise ( and getting very large almost cancelling coefficients for y and x).
The example still holds for any linear relation (y=mx)
look up ridge regression
|
(Why) do overfitted models tend to have large coefficients?
David. I think the problem with your example is you haven't normalised your data ( ie X^10>> X.
So david is right that it shrinks larger coefficients more ( so you can end up with lots of small coeffi
|
6,481
|
(Why) do overfitted models tend to have large coefficients?
|
This image is from my note of Andrew Ng's DL course, pls let me know if you have question
|
(Why) do overfitted models tend to have large coefficients?
|
This image is from my note of Andrew Ng's DL course, pls let me know if you have question
|
(Why) do overfitted models tend to have large coefficients?
This image is from my note of Andrew Ng's DL course, pls let me know if you have question
|
(Why) do overfitted models tend to have large coefficients?
This image is from my note of Andrew Ng's DL course, pls let me know if you have question
|
6,482
|
How to split dataset for time-series prediction?
|
This link from Rob Hyndman's blog has some info that may be useful: http://robjhyndman.com/hyndsight/crossvalidation/
In my experience, splitting data into chronological sets (year 1, year 2, etc) and checking for parameter stability over time is very useful in building something that's robust. Furthermore, if your data is seasonal, or has another obvious way to split in to groups (e.g. geographic regions) then checking for parameter stability in those sub-groups can also help determine how robust the model will be and if it makes sense to fit separate models for separate categories of data.
I think that statistical tests can be useful but the end result should also pass the "smell test".
|
How to split dataset for time-series prediction?
|
This link from Rob Hyndman's blog has some info that may be useful: http://robjhyndman.com/hyndsight/crossvalidation/
In my experience, splitting data into chronological sets (year 1, year 2, etc) and
|
How to split dataset for time-series prediction?
This link from Rob Hyndman's blog has some info that may be useful: http://robjhyndman.com/hyndsight/crossvalidation/
In my experience, splitting data into chronological sets (year 1, year 2, etc) and checking for parameter stability over time is very useful in building something that's robust. Furthermore, if your data is seasonal, or has another obvious way to split in to groups (e.g. geographic regions) then checking for parameter stability in those sub-groups can also help determine how robust the model will be and if it makes sense to fit separate models for separate categories of data.
I think that statistical tests can be useful but the end result should also pass the "smell test".
|
How to split dataset for time-series prediction?
This link from Rob Hyndman's blog has some info that may be useful: http://robjhyndman.com/hyndsight/crossvalidation/
In my experience, splitting data into chronological sets (year 1, year 2, etc) and
|
6,483
|
How to split dataset for time-series prediction?
|
1) Technically speaking, you don't need to test out of sample if you use AIC and similar criteria because they help avoid overfitting.
3) I don't see how you can do the standard CV because it implies training a time series model with some missing values. Instead, try using a rolling window for training and predict the response at one or more points that follow the window.
|
How to split dataset for time-series prediction?
|
1) Technically speaking, you don't need to test out of sample if you use AIC and similar criteria because they help avoid overfitting.
3) I don't see how you can do the standard CV because it implies
|
How to split dataset for time-series prediction?
1) Technically speaking, you don't need to test out of sample if you use AIC and similar criteria because they help avoid overfitting.
3) I don't see how you can do the standard CV because it implies training a time series model with some missing values. Instead, try using a rolling window for training and predict the response at one or more points that follow the window.
|
How to split dataset for time-series prediction?
1) Technically speaking, you don't need to test out of sample if you use AIC and similar criteria because they help avoid overfitting.
3) I don't see how you can do the standard CV because it implies
|
6,484
|
How to split dataset for time-series prediction?
|
In your case you don't have a lot of options. You only have one bakery, it seems. So, to run an out-of-sample test your only option is the time separation, i.e. the training sample would from the beginning to some recent point in time, and the holdout would from that point to today.
If your model is not time series, then it's a different story. For instance, if your sales $y_t=f(t)+\varepsilon_t$, where $f(t)$ is a function of different exogenous things like seasonal dummies, weather etc. but not $y_{s< t}$, then this is not a dynamic time series model. In this case you can create the holdout sample in any different ways such as random subset of days, a month from any period in the past etc.
|
How to split dataset for time-series prediction?
|
In your case you don't have a lot of options. You only have one bakery, it seems. So, to run an out-of-sample test your only option is the time separation, i.e. the training sample would from the begi
|
How to split dataset for time-series prediction?
In your case you don't have a lot of options. You only have one bakery, it seems. So, to run an out-of-sample test your only option is the time separation, i.e. the training sample would from the beginning to some recent point in time, and the holdout would from that point to today.
If your model is not time series, then it's a different story. For instance, if your sales $y_t=f(t)+\varepsilon_t$, where $f(t)$ is a function of different exogenous things like seasonal dummies, weather etc. but not $y_{s< t}$, then this is not a dynamic time series model. In this case you can create the holdout sample in any different ways such as random subset of days, a month from any period in the past etc.
|
How to split dataset for time-series prediction?
In your case you don't have a lot of options. You only have one bakery, it seems. So, to run an out-of-sample test your only option is the time separation, i.e. the training sample would from the begi
|
6,485
|
How to split dataset for time-series prediction?
|
I often approach problems from a Bayesian perspective. In this case, I'd consider using overimputation as a strategy. This means setting up a likelihood for your data, but omit some of your outcomes. Treat those values as missing, and model those missing outcomes using their corresponding covariates. Then rotate through which data are omitted. You can do this inside of, e.g., a 10-fold CV procedure.
When implemented inside of a sampling program, this means that at each step you draw a candidate value of your omitted data value (alongside your parameters) and assess its likelihood against your proposed model. After achieving stationarity, you have counter-factual sampled values given your model which you can use to assess prediction error: these samples answer the question "what would my model have looked like in the absence of these values?" Note that these predictions will also inherit uncertainty from the uncertainty present in coefficient estimates, so when you collect all of your predicted values for, e.g. March 1, 2010 together, you'll have a distribution of predictions for that date.
The fact that these values are sampled means that you can still use error terms that depend on having a complete data series available (e.g. moving average), since you have a sampled outcome value available at every step.
|
How to split dataset for time-series prediction?
|
I often approach problems from a Bayesian perspective. In this case, I'd consider using overimputation as a strategy. This means setting up a likelihood for your data, but omit some of your outcomes.
|
How to split dataset for time-series prediction?
I often approach problems from a Bayesian perspective. In this case, I'd consider using overimputation as a strategy. This means setting up a likelihood for your data, but omit some of your outcomes. Treat those values as missing, and model those missing outcomes using their corresponding covariates. Then rotate through which data are omitted. You can do this inside of, e.g., a 10-fold CV procedure.
When implemented inside of a sampling program, this means that at each step you draw a candidate value of your omitted data value (alongside your parameters) and assess its likelihood against your proposed model. After achieving stationarity, you have counter-factual sampled values given your model which you can use to assess prediction error: these samples answer the question "what would my model have looked like in the absence of these values?" Note that these predictions will also inherit uncertainty from the uncertainty present in coefficient estimates, so when you collect all of your predicted values for, e.g. March 1, 2010 together, you'll have a distribution of predictions for that date.
The fact that these values are sampled means that you can still use error terms that depend on having a complete data series available (e.g. moving average), since you have a sampled outcome value available at every step.
|
How to split dataset for time-series prediction?
I often approach problems from a Bayesian perspective. In this case, I'd consider using overimputation as a strategy. This means setting up a likelihood for your data, but omit some of your outcomes.
|
6,486
|
How to split dataset for time-series prediction?
|
Disclaimer: The method described here is original research, not based on a thorough reading of the litterature. It is my best attempt at improvising a K-fold CV method for a multivariate timeseries analysis with relatively short input window lengths (assuming no/low dependence over longer time spans), where there was a problem with non-homogeneous presence of data sources over the data collection period.
First, the series of observations is transformed into a series of observation history windows of length h and with step 1 between windows. Then the principle is to split the window dataset in S ordered slices (where S>>K, to approximate random splitting), each with length>>h (to not waste data), and hand out the slices alternately (like playing cards) to separate model instances. To keep the resulting subsets more cleanly separated, a quarantine window of length h at the beginning of each slice is held out of training.
The models are trained on all slices except their own, and their own slices are used for validation. Validation of the collection/ensemble of models is done by summing the validation error over all slices, where each slice is processed by the submodel which has not been trained on that slice. Testing on unseen data can be done using an average (or other suitable combination) of the outputs of all the trained model instances. Or one can first distill the ensemble into a single model, training on reproduction of the validation outputs.
This method is intended to reduce dependence on the stationarity of the data-generating process (including measurement reliability) over the collection period. It is also intended to give every part of the data roughly the same influence on the model.
Note that the slice length should not align too well with periods that (are expected to) appear in the data, such as (typically) daily, weekly and yearly cycles. Otherwise, the subsets will be more biased. Imagine, for example (and it is a silly one), a situation where one fold contains all night hours and one contains all day hours and the task is to predict air temperature from radon gas concentration. I have no idea what to expect from the radon gas, but certainly a best guess with no sensible input is lower at night than at day.
One way to test the performance of the resulting CV ensemble is to hold out every K+1-th slice and test the ensemble on the resulting subset. This can be extended to an outer Cross-Validation where different subsets are held out in each fold, at a cost of a factor K+1 on the amount of computation needed.
|
How to split dataset for time-series prediction?
|
Disclaimer: The method described here is original research, not based on a thorough reading of the litterature. It is my best attempt at improvising a K-fold CV method for a multivariate timeseries an
|
How to split dataset for time-series prediction?
Disclaimer: The method described here is original research, not based on a thorough reading of the litterature. It is my best attempt at improvising a K-fold CV method for a multivariate timeseries analysis with relatively short input window lengths (assuming no/low dependence over longer time spans), where there was a problem with non-homogeneous presence of data sources over the data collection period.
First, the series of observations is transformed into a series of observation history windows of length h and with step 1 between windows. Then the principle is to split the window dataset in S ordered slices (where S>>K, to approximate random splitting), each with length>>h (to not waste data), and hand out the slices alternately (like playing cards) to separate model instances. To keep the resulting subsets more cleanly separated, a quarantine window of length h at the beginning of each slice is held out of training.
The models are trained on all slices except their own, and their own slices are used for validation. Validation of the collection/ensemble of models is done by summing the validation error over all slices, where each slice is processed by the submodel which has not been trained on that slice. Testing on unseen data can be done using an average (or other suitable combination) of the outputs of all the trained model instances. Or one can first distill the ensemble into a single model, training on reproduction of the validation outputs.
This method is intended to reduce dependence on the stationarity of the data-generating process (including measurement reliability) over the collection period. It is also intended to give every part of the data roughly the same influence on the model.
Note that the slice length should not align too well with periods that (are expected to) appear in the data, such as (typically) daily, weekly and yearly cycles. Otherwise, the subsets will be more biased. Imagine, for example (and it is a silly one), a situation where one fold contains all night hours and one contains all day hours and the task is to predict air temperature from radon gas concentration. I have no idea what to expect from the radon gas, but certainly a best guess with no sensible input is lower at night than at day.
One way to test the performance of the resulting CV ensemble is to hold out every K+1-th slice and test the ensemble on the resulting subset. This can be extended to an outer Cross-Validation where different subsets are held out in each fold, at a cost of a factor K+1 on the amount of computation needed.
|
How to split dataset for time-series prediction?
Disclaimer: The method described here is original research, not based on a thorough reading of the litterature. It is my best attempt at improvising a K-fold CV method for a multivariate timeseries an
|
6,487
|
How do bottleneck architectures work in neural networks?
|
The bottleneck architecture is used in very deep networks due to computational considerations.
To answer your questions:
56x56 feature maps are not represented in the above image. This block is taken from a ResNet with input size 224x224. 56x56 is the downsampled version of the input at some intermediate layer.
64-d refers to the number of feature maps(filters). The bottleneck architecture has 256-d, simply because it is meant for much deeper network, which possibly take higher resolution image as input and hence require more feature maps.
Refer this figure for parameters of each bottleneck layer in ResNet 50.
|
How do bottleneck architectures work in neural networks?
|
The bottleneck architecture is used in very deep networks due to computational considerations.
To answer your questions:
56x56 feature maps are not represented in the above image. This block is taken
|
How do bottleneck architectures work in neural networks?
The bottleneck architecture is used in very deep networks due to computational considerations.
To answer your questions:
56x56 feature maps are not represented in the above image. This block is taken from a ResNet with input size 224x224. 56x56 is the downsampled version of the input at some intermediate layer.
64-d refers to the number of feature maps(filters). The bottleneck architecture has 256-d, simply because it is meant for much deeper network, which possibly take higher resolution image as input and hence require more feature maps.
Refer this figure for parameters of each bottleneck layer in ResNet 50.
|
How do bottleneck architectures work in neural networks?
The bottleneck architecture is used in very deep networks due to computational considerations.
To answer your questions:
56x56 feature maps are not represented in the above image. This block is taken
|
6,488
|
How do bottleneck architectures work in neural networks?
|
As far as I understand, illustration on the right shows that input to this block already has 256 features. So we are deep into some ResNet architecture and already created 256 features (we lost some w x h due to conv 3x3 before but gained features instead).
Still, calculating 256 channels (features) can take too much time, and authors proposed using 1x1 conv layer with stride 1 and padding 0 that keeps image's w x h as it was but in the meantime reduces depth, number of output channels to 64.
Thus, but using this bottleneck, at first layer you are shoving w x h x 256 element into conv 1x1 layer that will pass through just w x h x 64
|
How do bottleneck architectures work in neural networks?
|
As far as I understand, illustration on the right shows that input to this block already has 256 features. So we are deep into some ResNet architecture and already created 256 features (we lost some w
|
How do bottleneck architectures work in neural networks?
As far as I understand, illustration on the right shows that input to this block already has 256 features. So we are deep into some ResNet architecture and already created 256 features (we lost some w x h due to conv 3x3 before but gained features instead).
Still, calculating 256 channels (features) can take too much time, and authors proposed using 1x1 conv layer with stride 1 and padding 0 that keeps image's w x h as it was but in the meantime reduces depth, number of output channels to 64.
Thus, but using this bottleneck, at first layer you are shoving w x h x 256 element into conv 1x1 layer that will pass through just w x h x 64
|
How do bottleneck architectures work in neural networks?
As far as I understand, illustration on the right shows that input to this block already has 256 features. So we are deep into some ResNet architecture and already created 256 features (we lost some w
|
6,489
|
How do bottleneck architectures work in neural networks?
|
I just want to answer your questions:
What stride length is used and at what layers?
Stride is not relevant in this discussion/figure. The "layers" are represented as rectangles and are 2d convolutional layers.
How are the 56x56 feature maps represented in the diagram above?
Feature maps are the result of a conv. layer. So they should be positioned right after the rectangles (which are the convolutional layers). The dimension of the feature maps are not provided in the figure but can be calculated.
Do the 64-d refer to the number of filters, why does this differ from the 256-d filters?
Yes, they indicate the number of filters/kernels used in this layer. A lower number means that fewer filters are used which means that the network has less capacity to represent/store information. By this mechanism, a bottleneck is obtained and it is assumed that the network learns to focus on the most relevant things and remove noise.
|
How do bottleneck architectures work in neural networks?
|
I just want to answer your questions:
What stride length is used and at what layers?
Stride is not relevant in this discussion/figure. The "layers" are represented as rectangles and are 2d convolution
|
How do bottleneck architectures work in neural networks?
I just want to answer your questions:
What stride length is used and at what layers?
Stride is not relevant in this discussion/figure. The "layers" are represented as rectangles and are 2d convolutional layers.
How are the 56x56 feature maps represented in the diagram above?
Feature maps are the result of a conv. layer. So they should be positioned right after the rectangles (which are the convolutional layers). The dimension of the feature maps are not provided in the figure but can be calculated.
Do the 64-d refer to the number of filters, why does this differ from the 256-d filters?
Yes, they indicate the number of filters/kernels used in this layer. A lower number means that fewer filters are used which means that the network has less capacity to represent/store information. By this mechanism, a bottleneck is obtained and it is assumed that the network learns to focus on the most relevant things and remove noise.
|
How do bottleneck architectures work in neural networks?
I just want to answer your questions:
What stride length is used and at what layers?
Stride is not relevant in this discussion/figure. The "layers" are represented as rectangles and are 2d convolution
|
6,490
|
When is the bootstrap estimate of bias valid?
|
I think your formula is wrong. The last $t$ should have a star rather than a hat:
\begin{equation}
\mathrm{bias}_t \approx \frac{1}{N}\sum_i \tilde{t}_i- t^*
\end{equation}
You want to use the actual statistic evaluated on the empirical distribution (this is often easy, since the original sample is a finite set), rather than the estimate. In some cases, these may be the same (for example, the empirical mean is the same as the sample mean), but they won't be in general. You gave one case where they are different, but a less pathological example is the usual unbiased estimator for variance, which is not the same as the population variance when applied to a finite distribution.
If the statistic $t$ doesn't make sense on the empirical distribution (for example, if it assumes a continuous distribution), then you shouldn't use vanilla bootstrapping. You can replace the empirical distribution with a kernel density estimate (smooth bootstrap), or if you know that the original distribution lies in some particular family, you can replace the empirical distribution with the maximum likely estimate from that family (parametric bootstrap).
TL/DR: The bootstrap method is not magical. To get an unbiased estimate of the bias, you need to be able to compute the parameter of interest exactly on a finite distribution.
|
When is the bootstrap estimate of bias valid?
|
I think your formula is wrong. The last $t$ should have a star rather than a hat:
\begin{equation}
\mathrm{bias}_t \approx \frac{1}{N}\sum_i \tilde{t}_i- t^*
\end{equation}
You want to use the actual
|
When is the bootstrap estimate of bias valid?
I think your formula is wrong. The last $t$ should have a star rather than a hat:
\begin{equation}
\mathrm{bias}_t \approx \frac{1}{N}\sum_i \tilde{t}_i- t^*
\end{equation}
You want to use the actual statistic evaluated on the empirical distribution (this is often easy, since the original sample is a finite set), rather than the estimate. In some cases, these may be the same (for example, the empirical mean is the same as the sample mean), but they won't be in general. You gave one case where they are different, but a less pathological example is the usual unbiased estimator for variance, which is not the same as the population variance when applied to a finite distribution.
If the statistic $t$ doesn't make sense on the empirical distribution (for example, if it assumes a continuous distribution), then you shouldn't use vanilla bootstrapping. You can replace the empirical distribution with a kernel density estimate (smooth bootstrap), or if you know that the original distribution lies in some particular family, you can replace the empirical distribution with the maximum likely estimate from that family (parametric bootstrap).
TL/DR: The bootstrap method is not magical. To get an unbiased estimate of the bias, you need to be able to compute the parameter of interest exactly on a finite distribution.
|
When is the bootstrap estimate of bias valid?
I think your formula is wrong. The last $t$ should have a star rather than a hat:
\begin{equation}
\mathrm{bias}_t \approx \frac{1}{N}\sum_i \tilde{t}_i- t^*
\end{equation}
You want to use the actual
|
6,491
|
When is the bootstrap estimate of bias valid?
|
The problem you describe is a problem of interpretation, not one of validity. The bootstrap bias estimate for your constant estimator isn't invalid, it is in fact perfect.
The bootstrap estimate of bias is between an estimator $\hat\theta = s(x)$ and a parameter $\theta = t(F),$ where $F$ is some unknown distribution and $x$ a sample from $F$. The function $t(F)$ is something you could in principle calculate if you had the population at hand. Some times we take $s(x) = t(\hat F),$ the plug-in estimate of $t(F)$ using the empirical distribution $\hat F$ in the place of $F$. This is presumably what you describe above. In all cases the bootstrap estimate of bias is
$$
\mathrm{bias}_{\hat F} = E_{\hat F}[s(x^*)] - t(\hat F),
$$
where $x^*$ are bootstrap samples from $x$.
The constant $c$ is a perfect plug-in estimate for that same constant: The population is $\sim F$ and the sample $\sim \hat F$, the empirical distribution, which approximates $F$. If you could evaluate $t(F) = c$, you'd get $c$. When you compute the plug-in estimate $t(\hat F) = c$ you also get $c$. No bias, as you would expect.
A well-known case where there is a bias in the plug-in estimate $t(\hat F)$ is in estimating variance, hence Bessel's correction. Below I demonstrate this. The bootstrap bias estimate isn't too bad:
library(plyr)
n <- 20
data <- rnorm(n, 0, 1)
variance <- sum((data - mean(data))^2)/n
boots <- raply(1000, {
data_b <- sample(data, n, replace=T)
sum((data_b - mean(data_b))^2)/n
})
# estimated bias
mean(boots) - variance
#> [1] -0.06504726
# true bias:
((n-1)/n)*1 -1
#> [1] -0.05
We could instead take $t(F)$ to be the population mean and $s(x) = c$, situation where in most cases there should be a clear bias:
library(plyr)
mu <- 3
a_constant <- 1
n <- 20
data <- rnorm(n, mu, 1)
boots <- raply(1000, {
# not necessary as we will ignore the data, but let's do it on principle
data_b <- sample(data, n, replace=T)
a_constant
})
# estimated bias
mean(boots) - mean(data)
#> [1] -1.964877
# true bias is clearly -2
Again the bootstrap estimate isn't too bad.
|
When is the bootstrap estimate of bias valid?
|
The problem you describe is a problem of interpretation, not one of validity. The bootstrap bias estimate for your constant estimator isn't invalid, it is in fact perfect.
The bootstrap estimate of b
|
When is the bootstrap estimate of bias valid?
The problem you describe is a problem of interpretation, not one of validity. The bootstrap bias estimate for your constant estimator isn't invalid, it is in fact perfect.
The bootstrap estimate of bias is between an estimator $\hat\theta = s(x)$ and a parameter $\theta = t(F),$ where $F$ is some unknown distribution and $x$ a sample from $F$. The function $t(F)$ is something you could in principle calculate if you had the population at hand. Some times we take $s(x) = t(\hat F),$ the plug-in estimate of $t(F)$ using the empirical distribution $\hat F$ in the place of $F$. This is presumably what you describe above. In all cases the bootstrap estimate of bias is
$$
\mathrm{bias}_{\hat F} = E_{\hat F}[s(x^*)] - t(\hat F),
$$
where $x^*$ are bootstrap samples from $x$.
The constant $c$ is a perfect plug-in estimate for that same constant: The population is $\sim F$ and the sample $\sim \hat F$, the empirical distribution, which approximates $F$. If you could evaluate $t(F) = c$, you'd get $c$. When you compute the plug-in estimate $t(\hat F) = c$ you also get $c$. No bias, as you would expect.
A well-known case where there is a bias in the plug-in estimate $t(\hat F)$ is in estimating variance, hence Bessel's correction. Below I demonstrate this. The bootstrap bias estimate isn't too bad:
library(plyr)
n <- 20
data <- rnorm(n, 0, 1)
variance <- sum((data - mean(data))^2)/n
boots <- raply(1000, {
data_b <- sample(data, n, replace=T)
sum((data_b - mean(data_b))^2)/n
})
# estimated bias
mean(boots) - variance
#> [1] -0.06504726
# true bias:
((n-1)/n)*1 -1
#> [1] -0.05
We could instead take $t(F)$ to be the population mean and $s(x) = c$, situation where in most cases there should be a clear bias:
library(plyr)
mu <- 3
a_constant <- 1
n <- 20
data <- rnorm(n, mu, 1)
boots <- raply(1000, {
# not necessary as we will ignore the data, but let's do it on principle
data_b <- sample(data, n, replace=T)
a_constant
})
# estimated bias
mean(boots) - mean(data)
#> [1] -1.964877
# true bias is clearly -2
Again the bootstrap estimate isn't too bad.
|
When is the bootstrap estimate of bias valid?
The problem you describe is a problem of interpretation, not one of validity. The bootstrap bias estimate for your constant estimator isn't invalid, it is in fact perfect.
The bootstrap estimate of b
|
6,492
|
When is the bootstrap estimate of bias valid?
|
You make one mistake and maybe that is the reason it is confusing. You say:
if my estimator simply returns a constant that is independent of the
observations, the above estimate of bias is clearly invalid
Bootstrap is not about how much your method is biased, but how much your results obtained by some function, given your data are biased.
If you choose appropriate statistical method for analyzing your data, and all the assumptions of this method are met, and you did your math correctly, then your statistical method should provide you the "best" possible estimate that can be obtained using your data.
The idea of bootstrap is to sample from your data the same way as you sampled your cases from the population - so it is a kind of replication of your sampling. This lets you to obtain approximate distribution (using Efrons words) of your value and hence to asses bias of your estimate.
However, what I argue is that your example is misleading and so it is not the best example for discussing bootstrap. Since there were misunderstandings on both sides, let me update my answer and write it in more formal way to illustrate my point.
Bias for $\hat{\theta}$ being estimate of true value $\theta$ is defined as:
$$\text{bias}(\hat{\theta}_n) = \mathbb{E}_\theta(\hat{\theta}_n) - \theta$$
where:
$$\hat{\theta}_n = g(x_1,x_2,...,x_n)$$
where $g(\cdot)$ is the estimator.
As Larry Wasserman notes in his book "All the Statistics":
A reasonable requirement for an estimator is that it should converge
to the true parameter value as we collect more and more data. This
requirement is quantified by the following definition:
6.7 Definition. A point estimator $\hat{\theta}_n$ of a parameter $\theta$ is consistent if $\hat{\theta}_n \overset{P}{\rightarrow} \theta$.
Constant estimator, being a constant function of $x$: $g(X) = \lambda$ does not meet this requirement since it is independent of data and growing number of observations would not make it approach the true value $\theta$ (unless by pure luck or having very solid a priori assumptions on $\lambda$ it is that $\lambda = \theta$).
Constant estimator does not meet the basic requirement for being a reasonable estimator and hence, it is impossible to estimate it's bias because $\hat{\theta}_n$ does not approach $\theta$ even with $n \rightarrow \infty$. It's impossible to do it with bootstrap and with any other method, so it's not a problem with bootstrap.
|
When is the bootstrap estimate of bias valid?
|
You make one mistake and maybe that is the reason it is confusing. You say:
if my estimator simply returns a constant that is independent of the
observations, the above estimate of bias is clearly
|
When is the bootstrap estimate of bias valid?
You make one mistake and maybe that is the reason it is confusing. You say:
if my estimator simply returns a constant that is independent of the
observations, the above estimate of bias is clearly invalid
Bootstrap is not about how much your method is biased, but how much your results obtained by some function, given your data are biased.
If you choose appropriate statistical method for analyzing your data, and all the assumptions of this method are met, and you did your math correctly, then your statistical method should provide you the "best" possible estimate that can be obtained using your data.
The idea of bootstrap is to sample from your data the same way as you sampled your cases from the population - so it is a kind of replication of your sampling. This lets you to obtain approximate distribution (using Efrons words) of your value and hence to asses bias of your estimate.
However, what I argue is that your example is misleading and so it is not the best example for discussing bootstrap. Since there were misunderstandings on both sides, let me update my answer and write it in more formal way to illustrate my point.
Bias for $\hat{\theta}$ being estimate of true value $\theta$ is defined as:
$$\text{bias}(\hat{\theta}_n) = \mathbb{E}_\theta(\hat{\theta}_n) - \theta$$
where:
$$\hat{\theta}_n = g(x_1,x_2,...,x_n)$$
where $g(\cdot)$ is the estimator.
As Larry Wasserman notes in his book "All the Statistics":
A reasonable requirement for an estimator is that it should converge
to the true parameter value as we collect more and more data. This
requirement is quantified by the following definition:
6.7 Definition. A point estimator $\hat{\theta}_n$ of a parameter $\theta$ is consistent if $\hat{\theta}_n \overset{P}{\rightarrow} \theta$.
Constant estimator, being a constant function of $x$: $g(X) = \lambda$ does not meet this requirement since it is independent of data and growing number of observations would not make it approach the true value $\theta$ (unless by pure luck or having very solid a priori assumptions on $\lambda$ it is that $\lambda = \theta$).
Constant estimator does not meet the basic requirement for being a reasonable estimator and hence, it is impossible to estimate it's bias because $\hat{\theta}_n$ does not approach $\theta$ even with $n \rightarrow \infty$. It's impossible to do it with bootstrap and with any other method, so it's not a problem with bootstrap.
|
When is the bootstrap estimate of bias valid?
You make one mistake and maybe that is the reason it is confusing. You say:
if my estimator simply returns a constant that is independent of the
observations, the above estimate of bias is clearly
|
6,493
|
When is the bootstrap estimate of bias valid?
|
I find it useful to think about the bootstrap procedures in terms of the functionals of the distributions they operate on -- I gave an example in this answer to a different bootstrap question.
The estimate you gave is what it is -- an estimate. Nobody says it does not suffer from problems that statistical estimates may have. It will give you a non-zero estimate of bias for the sample mean, for instance, which we all know is unbiased to begin with. One problem with this bias estimator is that it suffers from sampling variability when the bootstrap is implemented as Monte Carlo rather than a complete enumeration of all possible subsamples (and nobody that that theoretical bootstrap in practice, anyway).
As such, a Monte Carlo implementation of the bootstrap is unfixable, and you have to use a different bootstrap scheme. Davison et. al. (1986) demonstrated how to create a different bootstrap scheme that restricts the random draws to produce balanced samples: if you create $B$ bootstrap replicates, then each of the original elements needs to be used exactly $B$ times for the first-order balance. (The second order balance that works better for the second moments of the estimands, is further discussed by Graham et. al. (1990).)
|
When is the bootstrap estimate of bias valid?
|
I find it useful to think about the bootstrap procedures in terms of the functionals of the distributions they operate on -- I gave an example in this answer to a different bootstrap question.
The est
|
When is the bootstrap estimate of bias valid?
I find it useful to think about the bootstrap procedures in terms of the functionals of the distributions they operate on -- I gave an example in this answer to a different bootstrap question.
The estimate you gave is what it is -- an estimate. Nobody says it does not suffer from problems that statistical estimates may have. It will give you a non-zero estimate of bias for the sample mean, for instance, which we all know is unbiased to begin with. One problem with this bias estimator is that it suffers from sampling variability when the bootstrap is implemented as Monte Carlo rather than a complete enumeration of all possible subsamples (and nobody that that theoretical bootstrap in practice, anyway).
As such, a Monte Carlo implementation of the bootstrap is unfixable, and you have to use a different bootstrap scheme. Davison et. al. (1986) demonstrated how to create a different bootstrap scheme that restricts the random draws to produce balanced samples: if you create $B$ bootstrap replicates, then each of the original elements needs to be used exactly $B$ times for the first-order balance. (The second order balance that works better for the second moments of the estimands, is further discussed by Graham et. al. (1990).)
|
When is the bootstrap estimate of bias valid?
I find it useful to think about the bootstrap procedures in terms of the functionals of the distributions they operate on -- I gave an example in this answer to a different bootstrap question.
The est
|
6,494
|
Quantile regression: Which standard errors?
|
Did you go through the paper Koenker and Hallock(2000): Quantile Regression: An Introduction (econ.uiuc.edu/~roger/research/intro/rq.pdf)? Bootstrap is preferable because it makes no assumption about the distribution of response (p. 47, Quantile regressions, Hao and Naiman, 2007). Also, note that the "...assumptions for the asymptotic procedure usually do not hold, and even if these assumptions are satisfied, it is complicated to solve for the standard error of the constructed scale and skewness shifts (p. 43)..."
|
Quantile regression: Which standard errors?
|
Did you go through the paper Koenker and Hallock(2000): Quantile Regression: An Introduction (econ.uiuc.edu/~roger/research/intro/rq.pdf)? Bootstrap is preferable because it makes no assumption about
|
Quantile regression: Which standard errors?
Did you go through the paper Koenker and Hallock(2000): Quantile Regression: An Introduction (econ.uiuc.edu/~roger/research/intro/rq.pdf)? Bootstrap is preferable because it makes no assumption about the distribution of response (p. 47, Quantile regressions, Hao and Naiman, 2007). Also, note that the "...assumptions for the asymptotic procedure usually do not hold, and even if these assumptions are satisfied, it is complicated to solve for the standard error of the constructed scale and skewness shifts (p. 43)..."
|
Quantile regression: Which standard errors?
Did you go through the paper Koenker and Hallock(2000): Quantile Regression: An Introduction (econ.uiuc.edu/~roger/research/intro/rq.pdf)? Bootstrap is preferable because it makes no assumption about
|
6,495
|
Are there statistical lessons from the "Bible Code" episode
|
Edit This is one of those questions whose answer may elicit negative reactions irrespective of whether or not the answer is correct. There have been several deleted answers so far, and it is doubtful that any answer will satisfy a majority of readers. Frankly, I do not care, but also any answer has to deal with the conundrum of belief in the bible as well as a belief in statistics, and they mix like oil and water. Nevertheless, it is possible to walk that thin line of truth by due consideration of what is in play, but it is not simple to do so.
There is a lot of wisdom in the bible, but given the preceding text, it is unlikely to be efficiently unpacked using numerology, as there is no unique textural version of the bible to refer to. Thus, my answer to the question Is there something related to statistics that we have learned, (including perhaps some interesting questions to ask) from the Bible Code episode [Sic, ?] is that most of the learning is from the negative side of the argument, i.e., what not to do, and why not. That does not mean that one cannot analyze the bible numerically, just that it is unlikely to yield very much in the way of useful information when too many assumptions are made. For example, if we want to use the bible to help calculate when King David was born, we will likely have better luck than when back-calculating when the Earth was created from an entire series of assumed dates.
There are two types of information. Statistical information differs from religious information in that the former is based upon disbelief and the latter on belief; oil and water. Let us illustrate them in practice. George Box famously said "Essentially, all models are wrong, but some are useful." What that implies is that when we formulate a hypothetical explanation, what we have done does not illustrate any fundamental truth, but rather a "working hypothesis," that has the property of explanatory power that makes it useful. Such is the way of the statistician, condemned to perpetually search for words to express the truth, but words are, at best a convention. So statistics assumes everything is wrong until proven otherwise, and religion assumes the opposite, what then is the truth?
Truth is not in words but rather behind them. In specific, each of us sees only our own personal world view, for example, we need faith to believe that life is worth living. Thus, truth is a first person phenomenon and words are not truth; they are shared values that by their nature have no insight of their own such that no matter how well we choose our words, it takes an individual, each of us, to actually have an insight that implies any feeling of mystery, wonder or appreciation. That is, we live in our own skins and our existence is a first person, subjective, phenomenon. The closest truth comes to being a shared value is for mathematics, but problems ensue as soon as we presume to apply mathematics to a hypothetical situation. Thus we can argue about whether in Exodus God told Moses "I am He who am," or the more literal translation "I am that which am," but the mystery is not in the words but rather in the first person context that inspired them. Kepler said, in effect, that it was unnecessary to postulate angelic intervention to explain the moon's orbit. William of Ockham, an English Franciscan friar, was excommunicated for leaving Avignon without permission. One can suspect that the principle of parsimony that he espoused was not especially popular with establishmentarians.
In statistics, we would generally refer to models with supernumerary postulates as overfit or predictive/extrapolative, and testing for overfitting or extrapolation is not merely a matter of doing controlled experiments as comparison between two models does not address the parsimony or predictive accuracy of either one. As Einstein intimated, one should only postulate the least number of relevant variables that adequately explains the data, and no fewer. Note the implication of deterministic data interpretation. If a predictive model is based upon an assumption, then whichever prediction is being made either has to be related to some hypothesis that is verifiable and deterministic, or we are engaging in what physicists call 'hand-waving'.
Re: Olle Häggström's question "...illustrating the pitfalls of data mining and related techniques." This can happen if one fails entirely to postulate a pre hoc deterministic context. In this case, the numerical analysis invites no deterministic interpretation, and invites us to discount hypothesis testing, and as such the interpretation invokes faith, not science. Such efforts, if done conscientiously, are likely to be futile, and even the declaration of a miraculous event is often based upon faith-based determinism. As if we needed further on this, Newton spent most of his lifetime's intellectual activity looking for numerical structure within the bible, and yet was silent on that topic. It is plausible to ascribe that failure, along with Newton's secret failure to deduce chemistry having only alchemy as a starting point, to problems that he could not solve. Thus, even physicists, including Newton who was arguably the first physicist, can fall victim to their own unverifiable imaginings. Nor has this ever ceased to be problematic. For example, string theorists have faith that eventually something verifiable will eventually result from their current multi-dimensional exercises in pure mathematics, and so far, there is nothing of the sort.
Many modern theologians would argue against a literal interpretation of the mere wording of biblical Divine inspiration, as in the contrary case we would pay undue attention to concepts such as what constitutes a firmament (vault) in the heavens that opened to let the waters come forth upon the Earth (Genesis). It is plausible that the concept of the Earth's being late bombardment epoch supplied by water from ice asteroids formed in the region beyond the solar system's snow line, as it contains words that would have been anachronisms in biblical times, is a reasonable substitute for the rather more terse concept of a firmament. What is perhaps astounding, is that there are modern equivalents to "Let there be light" but I caution that that could refer to several events in modern cosmology, e.g., the ending of the dark universe several hundred million years after the big bang, or the illumination of the sun a mere 4.6 billion years ago. Furthermore, there is no general agreement on these concepts, as some interpretations of the bible are literal and deny the existence of anything older than 6000 years ago, again from counting up numbers as cited in the bible. Keep in mind that scribes hand copied text 2000 years ago, so that minor changes in actual text, as exemplified by the Dead Sea Scrolls, would have been inevitable, which brings up the question of how one can do precise numerology on paraphrased text. All of this is beside the point, which is that the bible has a clear evolution in time of what constituted ethical comportment, and that today, there are multiple versions variously accepted by different sects and religions as dogma, not all of which can have identical numerological significance. One view of orthodoxy for biblical interpretation is that the text was divinely inspired, but written by humans whose ability to express themselves was limited, thus looking for hidden code in the umpteenth translation or paraphrasing of the original text, lost in time, is an exercise in futility.
|
Are there statistical lessons from the "Bible Code" episode
|
Edit This is one of those questions whose answer may elicit negative reactions irrespective of whether or not the answer is correct. There have been several deleted answers so far, and it is doubtful
|
Are there statistical lessons from the "Bible Code" episode
Edit This is one of those questions whose answer may elicit negative reactions irrespective of whether or not the answer is correct. There have been several deleted answers so far, and it is doubtful that any answer will satisfy a majority of readers. Frankly, I do not care, but also any answer has to deal with the conundrum of belief in the bible as well as a belief in statistics, and they mix like oil and water. Nevertheless, it is possible to walk that thin line of truth by due consideration of what is in play, but it is not simple to do so.
There is a lot of wisdom in the bible, but given the preceding text, it is unlikely to be efficiently unpacked using numerology, as there is no unique textural version of the bible to refer to. Thus, my answer to the question Is there something related to statistics that we have learned, (including perhaps some interesting questions to ask) from the Bible Code episode [Sic, ?] is that most of the learning is from the negative side of the argument, i.e., what not to do, and why not. That does not mean that one cannot analyze the bible numerically, just that it is unlikely to yield very much in the way of useful information when too many assumptions are made. For example, if we want to use the bible to help calculate when King David was born, we will likely have better luck than when back-calculating when the Earth was created from an entire series of assumed dates.
There are two types of information. Statistical information differs from religious information in that the former is based upon disbelief and the latter on belief; oil and water. Let us illustrate them in practice. George Box famously said "Essentially, all models are wrong, but some are useful." What that implies is that when we formulate a hypothetical explanation, what we have done does not illustrate any fundamental truth, but rather a "working hypothesis," that has the property of explanatory power that makes it useful. Such is the way of the statistician, condemned to perpetually search for words to express the truth, but words are, at best a convention. So statistics assumes everything is wrong until proven otherwise, and religion assumes the opposite, what then is the truth?
Truth is not in words but rather behind them. In specific, each of us sees only our own personal world view, for example, we need faith to believe that life is worth living. Thus, truth is a first person phenomenon and words are not truth; they are shared values that by their nature have no insight of their own such that no matter how well we choose our words, it takes an individual, each of us, to actually have an insight that implies any feeling of mystery, wonder or appreciation. That is, we live in our own skins and our existence is a first person, subjective, phenomenon. The closest truth comes to being a shared value is for mathematics, but problems ensue as soon as we presume to apply mathematics to a hypothetical situation. Thus we can argue about whether in Exodus God told Moses "I am He who am," or the more literal translation "I am that which am," but the mystery is not in the words but rather in the first person context that inspired them. Kepler said, in effect, that it was unnecessary to postulate angelic intervention to explain the moon's orbit. William of Ockham, an English Franciscan friar, was excommunicated for leaving Avignon without permission. One can suspect that the principle of parsimony that he espoused was not especially popular with establishmentarians.
In statistics, we would generally refer to models with supernumerary postulates as overfit or predictive/extrapolative, and testing for overfitting or extrapolation is not merely a matter of doing controlled experiments as comparison between two models does not address the parsimony or predictive accuracy of either one. As Einstein intimated, one should only postulate the least number of relevant variables that adequately explains the data, and no fewer. Note the implication of deterministic data interpretation. If a predictive model is based upon an assumption, then whichever prediction is being made either has to be related to some hypothesis that is verifiable and deterministic, or we are engaging in what physicists call 'hand-waving'.
Re: Olle Häggström's question "...illustrating the pitfalls of data mining and related techniques." This can happen if one fails entirely to postulate a pre hoc deterministic context. In this case, the numerical analysis invites no deterministic interpretation, and invites us to discount hypothesis testing, and as such the interpretation invokes faith, not science. Such efforts, if done conscientiously, are likely to be futile, and even the declaration of a miraculous event is often based upon faith-based determinism. As if we needed further on this, Newton spent most of his lifetime's intellectual activity looking for numerical structure within the bible, and yet was silent on that topic. It is plausible to ascribe that failure, along with Newton's secret failure to deduce chemistry having only alchemy as a starting point, to problems that he could not solve. Thus, even physicists, including Newton who was arguably the first physicist, can fall victim to their own unverifiable imaginings. Nor has this ever ceased to be problematic. For example, string theorists have faith that eventually something verifiable will eventually result from their current multi-dimensional exercises in pure mathematics, and so far, there is nothing of the sort.
Many modern theologians would argue against a literal interpretation of the mere wording of biblical Divine inspiration, as in the contrary case we would pay undue attention to concepts such as what constitutes a firmament (vault) in the heavens that opened to let the waters come forth upon the Earth (Genesis). It is plausible that the concept of the Earth's being late bombardment epoch supplied by water from ice asteroids formed in the region beyond the solar system's snow line, as it contains words that would have been anachronisms in biblical times, is a reasonable substitute for the rather more terse concept of a firmament. What is perhaps astounding, is that there are modern equivalents to "Let there be light" but I caution that that could refer to several events in modern cosmology, e.g., the ending of the dark universe several hundred million years after the big bang, or the illumination of the sun a mere 4.6 billion years ago. Furthermore, there is no general agreement on these concepts, as some interpretations of the bible are literal and deny the existence of anything older than 6000 years ago, again from counting up numbers as cited in the bible. Keep in mind that scribes hand copied text 2000 years ago, so that minor changes in actual text, as exemplified by the Dead Sea Scrolls, would have been inevitable, which brings up the question of how one can do precise numerology on paraphrased text. All of this is beside the point, which is that the bible has a clear evolution in time of what constituted ethical comportment, and that today, there are multiple versions variously accepted by different sects and religions as dogma, not all of which can have identical numerological significance. One view of orthodoxy for biblical interpretation is that the text was divinely inspired, but written by humans whose ability to express themselves was limited, thus looking for hidden code in the umpteenth translation or paraphrasing of the original text, lost in time, is an exercise in futility.
|
Are there statistical lessons from the "Bible Code" episode
Edit This is one of those questions whose answer may elicit negative reactions irrespective of whether or not the answer is correct. There have been several deleted answers so far, and it is doubtful
|
6,496
|
Maximum Mean Discrepancy (distance distribution)
|
It might help to give slightly more of an overview of MMD.$\DeclareMathOperator{\E}{\mathbb E}\newcommand{\R}{\mathbb R}\newcommand{\X}{\mathcal X}\newcommand{\h}{\mathcal H}\DeclareMathOperator{\MMD}{MMD}$
In general, MMD is defined by the idea of representing distances between distributions as distances between mean embeddings of features. That is, say we have distributions $P$ and $Q$ over a set $\X$. The MMD is defined by a feature map $\varphi : \X \to \h$, where $\mathcal H$ is what's called a reproducing kernel Hilbert space. In general, the MMD is
$$
\MMD(P, Q) = \lVert \E_{X \sim P}[ \varphi(X) ] - \E_{Y \sim Q}[ \varphi(Y) ] \rVert_\h
.$$
As one example, we might have $\X = \h = \R^d$ and $\varphi(x) = x$. In that case:
\begin{align}
\MMD(P, Q)
&= \lVert \E_{X \sim P}[ \varphi(X) ] - \E_{Y \sim Q}[ \varphi(Y) ] \rVert_\h
\\&= \lVert \E_{X \sim P}[ X ] - \E_{Y \sim Q}[ Y ] \rVert_{\R^d}
\\&= \lVert \mu_P - \mu_Q \rVert_{\R^d}
,\end{align}
so this MMD is just the distance between the means of the two distributions. Matching distributions like this will match their means, though they might differ in their variance or in other ways.
Your case is slightly different: we have $\mathcal X = \mathbb R^d$ and $\mathcal H = \mathbb R^p$, with $\varphi(x) = A' x$, where $A$ is a $d \times p$ matrix. So we have
\begin{align}
\MMD(P, Q)
&= \lVert \E_{X \sim P}[ \varphi(X) ] - \E_{Y \sim Q}[ \varphi(Y) ] \rVert_\h
\\&= \lVert \E_{X \sim P}[ A' X ] - \E_{Y \sim Q}[ A' Y ] \rVert_{\R^p}
\\&= \lVert A' \E_{X \sim P}[ X ] - A' \E_{Y \sim Q}[ Y ] \rVert_{\R^p}
\\&= \lVert A'( \mu_P - \mu_Q ) \rVert_{\R^p}
.\end{align}
This MMD is the difference between two different projections of the mean. If $p < d$ or the mapping $A'$ otherwise isn't invertible, then this MMD is weaker than the previous one: it doesn't distinguish between some distributions that the previous one does.
You can also construct stronger distances. For example, if $\X = \R$ and you use $\varphi(x) = (x, x^2)$, then the MMD becomes $\sqrt{(\E X - \E Y)^2 + (\E X^2 - \E Y^2)^2}$, and can distinguish not only distributions with different means but with different variances as well.
And you can get much stronger than that: if $\varphi$ maps to a general reproducing kernel Hilbert space, then you can apply the kernel trick to compute the MMD, and it turns out that many kernels, including the Gaussian kernel, lead to the MMD being zero if and only the distributions are identical.
Specifically, letting $k(x, y) = \langle \varphi(x), \varphi(y) \rangle_\h$, you get
\begin{align}
\MMD^2(P, Q)
&= \lVert \E_{X \sim P} \varphi(X) - \E_{Y \sim Q} \varphi(Y) \rVert_\h^2
\\&= \langle \E_{X \sim P} \varphi(X), \E_{X' \sim P} \varphi(X') \rangle_\h
+ \langle \E_{Y \sim Q} \varphi(Y), \E_{Y' \sim Q} \varphi(Y') \rangle_\h
- 2 \langle \E_{X \sim P} \varphi(X), \E_{Y \sim Q} \varphi(Y) \rangle_\h
\\&= \E_{X, X' \sim P} k(X, X') + \E_{Y, Y' \sim Q} k(Y, Y') - 2 \E_{X \sim P, Y \sim Q} k(X, Y)
\end{align}
which you can straightforwardly estimate with samples.
Update: here's where the "maximum" in the name comes from.
The feature map $\varphi: \X \to \h$ maps into a reproducing kernel Hilbert space. These are spaces of functions, and satisfy a key property (called the reproducing property): $\langle f, \varphi(x) \rangle_\h = f(x)$ for any $f \in \h$.
In the simplest example, $\X = \h = \R^d$ with $\varphi(x) = x$, we view each $f \in \h$ as the function corresponding to some $w \in \R^d$, by $f(x) = w' x$. Then the reproducing property $\langle f, \varphi(x) \rangle_\h = \langle w, x \rangle_{\R^d}$ should make sense.
In more complex settings, like a Gaussian kernel, $f$ is a much more complicated function, but the reproducing property still holds.
Now, we can give an alternative characterization of the MMD:
\begin{align}
\MMD(P, Q)
&= \lVert \E_{X \sim P}[\varphi(X)] - \E_{Y \sim Q}[\varphi(Y)] \rVert_\h
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \langle f, \E_{X \sim P}[\varphi(X)] - \E_{Y \sim Q}[\varphi(Y)] \rangle_\h
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \langle f, \E_{X \sim P}[\varphi(X)] \rangle_\h - \langle f, \E_{Y \sim Q}[\varphi(Y)] \rangle_\h
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \E_{X \sim P}[\langle f, \varphi(X)\rangle_\h] - \E_{Y \sim Q}[\langle f, \varphi(Y) \rangle_\h]
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \E_{X \sim P}[f(X)] - \E_{Y \sim Q}[f(Y)]
.\end{align}
The second line is a general fact about norms in Hilbert spaces: $\sup_{f : \lVert f \rVert \le 1} \langle f, g \rangle_\h = \lVert g \rVert$ is achieved by $f = g / \lVert g \rVert$. The fourth depends on a technical condition known as Bochner integrability but is true e.g. for bounded kernels or distributions with bounded support. Then at the end we use the reproducing property.
This last line is why it's called the "maximum mean discrepancy" – it's the maximum, over test functions $f$ in the unit ball of $\h$, of the mean difference between the two distributions.
|
Maximum Mean Discrepancy (distance distribution)
|
It might help to give slightly more of an overview of MMD.$\DeclareMathOperator{\E}{\mathbb E}\newcommand{\R}{\mathbb R}\newcommand{\X}{\mathcal X}\newcommand{\h}{\mathcal H}\DeclareMathOperator{\MMD}
|
Maximum Mean Discrepancy (distance distribution)
It might help to give slightly more of an overview of MMD.$\DeclareMathOperator{\E}{\mathbb E}\newcommand{\R}{\mathbb R}\newcommand{\X}{\mathcal X}\newcommand{\h}{\mathcal H}\DeclareMathOperator{\MMD}{MMD}$
In general, MMD is defined by the idea of representing distances between distributions as distances between mean embeddings of features. That is, say we have distributions $P$ and $Q$ over a set $\X$. The MMD is defined by a feature map $\varphi : \X \to \h$, where $\mathcal H$ is what's called a reproducing kernel Hilbert space. In general, the MMD is
$$
\MMD(P, Q) = \lVert \E_{X \sim P}[ \varphi(X) ] - \E_{Y \sim Q}[ \varphi(Y) ] \rVert_\h
.$$
As one example, we might have $\X = \h = \R^d$ and $\varphi(x) = x$. In that case:
\begin{align}
\MMD(P, Q)
&= \lVert \E_{X \sim P}[ \varphi(X) ] - \E_{Y \sim Q}[ \varphi(Y) ] \rVert_\h
\\&= \lVert \E_{X \sim P}[ X ] - \E_{Y \sim Q}[ Y ] \rVert_{\R^d}
\\&= \lVert \mu_P - \mu_Q \rVert_{\R^d}
,\end{align}
so this MMD is just the distance between the means of the two distributions. Matching distributions like this will match their means, though they might differ in their variance or in other ways.
Your case is slightly different: we have $\mathcal X = \mathbb R^d$ and $\mathcal H = \mathbb R^p$, with $\varphi(x) = A' x$, where $A$ is a $d \times p$ matrix. So we have
\begin{align}
\MMD(P, Q)
&= \lVert \E_{X \sim P}[ \varphi(X) ] - \E_{Y \sim Q}[ \varphi(Y) ] \rVert_\h
\\&= \lVert \E_{X \sim P}[ A' X ] - \E_{Y \sim Q}[ A' Y ] \rVert_{\R^p}
\\&= \lVert A' \E_{X \sim P}[ X ] - A' \E_{Y \sim Q}[ Y ] \rVert_{\R^p}
\\&= \lVert A'( \mu_P - \mu_Q ) \rVert_{\R^p}
.\end{align}
This MMD is the difference between two different projections of the mean. If $p < d$ or the mapping $A'$ otherwise isn't invertible, then this MMD is weaker than the previous one: it doesn't distinguish between some distributions that the previous one does.
You can also construct stronger distances. For example, if $\X = \R$ and you use $\varphi(x) = (x, x^2)$, then the MMD becomes $\sqrt{(\E X - \E Y)^2 + (\E X^2 - \E Y^2)^2}$, and can distinguish not only distributions with different means but with different variances as well.
And you can get much stronger than that: if $\varphi$ maps to a general reproducing kernel Hilbert space, then you can apply the kernel trick to compute the MMD, and it turns out that many kernels, including the Gaussian kernel, lead to the MMD being zero if and only the distributions are identical.
Specifically, letting $k(x, y) = \langle \varphi(x), \varphi(y) \rangle_\h$, you get
\begin{align}
\MMD^2(P, Q)
&= \lVert \E_{X \sim P} \varphi(X) - \E_{Y \sim Q} \varphi(Y) \rVert_\h^2
\\&= \langle \E_{X \sim P} \varphi(X), \E_{X' \sim P} \varphi(X') \rangle_\h
+ \langle \E_{Y \sim Q} \varphi(Y), \E_{Y' \sim Q} \varphi(Y') \rangle_\h
- 2 \langle \E_{X \sim P} \varphi(X), \E_{Y \sim Q} \varphi(Y) \rangle_\h
\\&= \E_{X, X' \sim P} k(X, X') + \E_{Y, Y' \sim Q} k(Y, Y') - 2 \E_{X \sim P, Y \sim Q} k(X, Y)
\end{align}
which you can straightforwardly estimate with samples.
Update: here's where the "maximum" in the name comes from.
The feature map $\varphi: \X \to \h$ maps into a reproducing kernel Hilbert space. These are spaces of functions, and satisfy a key property (called the reproducing property): $\langle f, \varphi(x) \rangle_\h = f(x)$ for any $f \in \h$.
In the simplest example, $\X = \h = \R^d$ with $\varphi(x) = x$, we view each $f \in \h$ as the function corresponding to some $w \in \R^d$, by $f(x) = w' x$. Then the reproducing property $\langle f, \varphi(x) \rangle_\h = \langle w, x \rangle_{\R^d}$ should make sense.
In more complex settings, like a Gaussian kernel, $f$ is a much more complicated function, but the reproducing property still holds.
Now, we can give an alternative characterization of the MMD:
\begin{align}
\MMD(P, Q)
&= \lVert \E_{X \sim P}[\varphi(X)] - \E_{Y \sim Q}[\varphi(Y)] \rVert_\h
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \langle f, \E_{X \sim P}[\varphi(X)] - \E_{Y \sim Q}[\varphi(Y)] \rangle_\h
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \langle f, \E_{X \sim P}[\varphi(X)] \rangle_\h - \langle f, \E_{Y \sim Q}[\varphi(Y)] \rangle_\h
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \E_{X \sim P}[\langle f, \varphi(X)\rangle_\h] - \E_{Y \sim Q}[\langle f, \varphi(Y) \rangle_\h]
\\&= \sup_{f \in \h : \lVert f \rVert_\h \le 1} \E_{X \sim P}[f(X)] - \E_{Y \sim Q}[f(Y)]
.\end{align}
The second line is a general fact about norms in Hilbert spaces: $\sup_{f : \lVert f \rVert \le 1} \langle f, g \rangle_\h = \lVert g \rVert$ is achieved by $f = g / \lVert g \rVert$. The fourth depends on a technical condition known as Bochner integrability but is true e.g. for bounded kernels or distributions with bounded support. Then at the end we use the reproducing property.
This last line is why it's called the "maximum mean discrepancy" – it's the maximum, over test functions $f$ in the unit ball of $\h$, of the mean difference between the two distributions.
|
Maximum Mean Discrepancy (distance distribution)
It might help to give slightly more of an overview of MMD.$\DeclareMathOperator{\E}{\mathbb E}\newcommand{\R}{\mathbb R}\newcommand{\X}{\mathcal X}\newcommand{\h}{\mathcal H}\DeclareMathOperator{\MMD}
|
6,497
|
Maximum Mean Discrepancy (distance distribution)
|
Here is how I interpretted MMD. Two distributions are similar if their moments are similar. By applying a kernel, I can transform the variable such that all moments (first, second, third etc.) are computed. In the latent space I can compute the difference between the moments and average it. This gives a measure of the similarity/dissimilarity between the datasets.
|
Maximum Mean Discrepancy (distance distribution)
|
Here is how I interpretted MMD. Two distributions are similar if their moments are similar. By applying a kernel, I can transform the variable such that all moments (first, second, third etc.) are com
|
Maximum Mean Discrepancy (distance distribution)
Here is how I interpretted MMD. Two distributions are similar if their moments are similar. By applying a kernel, I can transform the variable such that all moments (first, second, third etc.) are computed. In the latent space I can compute the difference between the moments and average it. This gives a measure of the similarity/dissimilarity between the datasets.
|
Maximum Mean Discrepancy (distance distribution)
Here is how I interpretted MMD. Two distributions are similar if their moments are similar. By applying a kernel, I can transform the variable such that all moments (first, second, third etc.) are com
|
6,498
|
Maximum Mean Discrepancy (distance distribution)
|
What we know today as Maximum Mean Discrepancy is actually derived from the following Integral Probability Metric [A]:
If p and q are two distributions and $\mathcal{F}$ is a class of real
valued bounded bounded measurable functions, then the metric is
defined as, $$D(p, q, \mathcal{F}) = \sup_{f \in \mathcal{F}} \left|\mathbb{E}_p[f(x)] - \mathbb{E}_q[f(x)]\right|$$
If you select the function class $\mathcal{F} = \{f \;\;|\;\; \|f\|_{\mathcal{H}} \leq 1\}$ where $\mathcal{H}$ represents the reproducing kernel Hilbert space with reproducing kernel $k$, it can be shown that the above metric reduces to [D]:
$$D(p, q, \mathcal{F}) = \left|\mathbb{E}_p[k(x, \cdot)] - \mathbb{E}_q[k(x, \cdot)]\right|$$
Thus, it so happens, that computing the differences of the mean in the kernel space gives you the distance between the distribution computed over a certain function class. Several other metrics can actually be derived this way, by selecting certain classes of functions and analyzing the original integral probability metric under that function class e.g. Total Variation Distance, Wasserstein Distance [B].
Now, coming to the description you gave in the original post, I am a little worried about how you are going about computing the MMD. Even for the original MMD measure, the kernel had to satisfy some properties [C]. However, all you seem to be doing is multiplying your features with some matrix and computing distance in that space. Which doesn't really mean anything unless the projection matrices are special. So, it would be good to go through the linked articles and ensure that what you are doing abides by requirements of a kernel mean embedding.
[A] Integral Probability Metrics and their Generating Classes of Functions, Muller, 1997
[B] On Integral Probability Metrics, ϕ-divergences and Binary Classification, Sriperumbudur et. al, 2009
[C] Universality, Characteristic Kernels and RKHS Embedding of Measures, Sriperumbudur et. al, 2012 (PDF)
[D] Kernel Mean Embedding of Distributions: A Review and Beyond, Muandet et. al, 2016
|
Maximum Mean Discrepancy (distance distribution)
|
What we know today as Maximum Mean Discrepancy is actually derived from the following Integral Probability Metric [A]:
If p and q are two distributions and $\mathcal{F}$ is a class of real
valued bou
|
Maximum Mean Discrepancy (distance distribution)
What we know today as Maximum Mean Discrepancy is actually derived from the following Integral Probability Metric [A]:
If p and q are two distributions and $\mathcal{F}$ is a class of real
valued bounded bounded measurable functions, then the metric is
defined as, $$D(p, q, \mathcal{F}) = \sup_{f \in \mathcal{F}} \left|\mathbb{E}_p[f(x)] - \mathbb{E}_q[f(x)]\right|$$
If you select the function class $\mathcal{F} = \{f \;\;|\;\; \|f\|_{\mathcal{H}} \leq 1\}$ where $\mathcal{H}$ represents the reproducing kernel Hilbert space with reproducing kernel $k$, it can be shown that the above metric reduces to [D]:
$$D(p, q, \mathcal{F}) = \left|\mathbb{E}_p[k(x, \cdot)] - \mathbb{E}_q[k(x, \cdot)]\right|$$
Thus, it so happens, that computing the differences of the mean in the kernel space gives you the distance between the distribution computed over a certain function class. Several other metrics can actually be derived this way, by selecting certain classes of functions and analyzing the original integral probability metric under that function class e.g. Total Variation Distance, Wasserstein Distance [B].
Now, coming to the description you gave in the original post, I am a little worried about how you are going about computing the MMD. Even for the original MMD measure, the kernel had to satisfy some properties [C]. However, all you seem to be doing is multiplying your features with some matrix and computing distance in that space. Which doesn't really mean anything unless the projection matrices are special. So, it would be good to go through the linked articles and ensure that what you are doing abides by requirements of a kernel mean embedding.
[A] Integral Probability Metrics and their Generating Classes of Functions, Muller, 1997
[B] On Integral Probability Metrics, ϕ-divergences and Binary Classification, Sriperumbudur et. al, 2009
[C] Universality, Characteristic Kernels and RKHS Embedding of Measures, Sriperumbudur et. al, 2012 (PDF)
[D] Kernel Mean Embedding of Distributions: A Review and Beyond, Muandet et. al, 2016
|
Maximum Mean Discrepancy (distance distribution)
What we know today as Maximum Mean Discrepancy is actually derived from the following Integral Probability Metric [A]:
If p and q are two distributions and $\mathcal{F}$ is a class of real
valued bou
|
6,499
|
Maximum Mean Discrepancy (distance distribution)
|
For the Gaussian kernel $K({\mathbf x}, {\mathbf y})=e^{-||{\mathbf x}-{\mathbf y}||^2/4\sigma^2}$ on ${\mathbb R}^n$, the MMD satisfies:
${\rm MMD}(P,Q) \propto \sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} {\mathbb E}_{X\sim P, \epsilon\sim N(0, \sigma^2I_n)} f(X+\epsilon)-{\mathbb E}_{Y\sim Q, \epsilon'\sim N(0, \sigma^2I_n)} f(Y+\epsilon')$
This representation helps to understand what MMD is about: the critic's function is from the unit ball in $L_2$ and it is applied to random vectors distributed according to ``smoothed'' $P$ and $Q$.
For the translation-invariant kernel, $K({\mathbf x}, {\mathbf y}) = k({\mathbf x} - {\mathbf y})$, one can represent MMD as:
${\rm MMD}(P,Q) \propto \sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} {\mathbb E}_{X\sim P, \epsilon\sim E} f(X+\epsilon)-{\mathbb E}_{Y\sim Q, \epsilon'\sim E} f(Y+\epsilon')$ (1)
where $E({\mathbf x}) = \frac{F({\mathbf x})}{||F||_{L_1}}$ where $F=\mathcal{F}\big\{\sqrt{\mathcal{F}^{-1}[k]}\big\}$ and $\mathcal{F}$ denotes the Fourier transform.
Let us show why the formula (1) holds ($P$ and $Q$ are smooth pdfs, $\ast$ denotes convolution):
$
\begin{align}
{\rm MMD}(P,Q)^2 = {\mathbb E}_{X, X' \sim P} k(X - X') + {\mathbb E}_{Y, Y' \sim Q} k(Y- Y') - 2 {\mathbb E}_{X \sim P, Y \sim Q} k(X- Y) = \\
\langle P, k\ast P\rangle_{L_2}+\langle Q, k\ast Q\rangle_{L_2} - 2 \langle P, k\ast Q\rangle_{L_2} \propto \\
\langle F\ast P, F\ast P\rangle_{L_2}+\langle F\ast Q, F\ast Q\rangle_{L_2} - 2 \langle F\ast P, F\ast Q\rangle_{L_2} = \\
||F\ast P - F\ast Q||^2_{L_2}
\end{align}
$
Therefore,
$
\begin{align}
{\rm MMD}(P,Q) = ||F\ast P - F\ast Q||_{L_2} = \\
\sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} \langle f, F\ast P - F\ast Q\rangle_{L_2} = \sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} \langle f, F\ast P\rangle - \langle f, F\ast Q\rangle_{L_2} = \\
\sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} {\mathbb E}_{X\sim P, \epsilon\sim E} f(X+\epsilon)-{\mathbb E}_{Y\sim Q, \epsilon'\sim E} f(Y+\epsilon')
\end{align}
$
Even for the general kernel similar formulas can be obtained, but then you need some pseudo-differential calculus (see https://arxiv.org/pdf/2106.14277.pdf).
|
Maximum Mean Discrepancy (distance distribution)
|
For the Gaussian kernel $K({\mathbf x}, {\mathbf y})=e^{-||{\mathbf x}-{\mathbf y}||^2/4\sigma^2}$ on ${\mathbb R}^n$, the MMD satisfies:
${\rm MMD}(P,Q) \propto \sup\limits_{f\in L_2({\mathbb R}^n),
|
Maximum Mean Discrepancy (distance distribution)
For the Gaussian kernel $K({\mathbf x}, {\mathbf y})=e^{-||{\mathbf x}-{\mathbf y}||^2/4\sigma^2}$ on ${\mathbb R}^n$, the MMD satisfies:
${\rm MMD}(P,Q) \propto \sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} {\mathbb E}_{X\sim P, \epsilon\sim N(0, \sigma^2I_n)} f(X+\epsilon)-{\mathbb E}_{Y\sim Q, \epsilon'\sim N(0, \sigma^2I_n)} f(Y+\epsilon')$
This representation helps to understand what MMD is about: the critic's function is from the unit ball in $L_2$ and it is applied to random vectors distributed according to ``smoothed'' $P$ and $Q$.
For the translation-invariant kernel, $K({\mathbf x}, {\mathbf y}) = k({\mathbf x} - {\mathbf y})$, one can represent MMD as:
${\rm MMD}(P,Q) \propto \sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} {\mathbb E}_{X\sim P, \epsilon\sim E} f(X+\epsilon)-{\mathbb E}_{Y\sim Q, \epsilon'\sim E} f(Y+\epsilon')$ (1)
where $E({\mathbf x}) = \frac{F({\mathbf x})}{||F||_{L_1}}$ where $F=\mathcal{F}\big\{\sqrt{\mathcal{F}^{-1}[k]}\big\}$ and $\mathcal{F}$ denotes the Fourier transform.
Let us show why the formula (1) holds ($P$ and $Q$ are smooth pdfs, $\ast$ denotes convolution):
$
\begin{align}
{\rm MMD}(P,Q)^2 = {\mathbb E}_{X, X' \sim P} k(X - X') + {\mathbb E}_{Y, Y' \sim Q} k(Y- Y') - 2 {\mathbb E}_{X \sim P, Y \sim Q} k(X- Y) = \\
\langle P, k\ast P\rangle_{L_2}+\langle Q, k\ast Q\rangle_{L_2} - 2 \langle P, k\ast Q\rangle_{L_2} \propto \\
\langle F\ast P, F\ast P\rangle_{L_2}+\langle F\ast Q, F\ast Q\rangle_{L_2} - 2 \langle F\ast P, F\ast Q\rangle_{L_2} = \\
||F\ast P - F\ast Q||^2_{L_2}
\end{align}
$
Therefore,
$
\begin{align}
{\rm MMD}(P,Q) = ||F\ast P - F\ast Q||_{L_2} = \\
\sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} \langle f, F\ast P - F\ast Q\rangle_{L_2} = \sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} \langle f, F\ast P\rangle - \langle f, F\ast Q\rangle_{L_2} = \\
\sup\limits_{f\in L_2({\mathbb R}^n), ||f||_{L_2}\leq 1} {\mathbb E}_{X\sim P, \epsilon\sim E} f(X+\epsilon)-{\mathbb E}_{Y\sim Q, \epsilon'\sim E} f(Y+\epsilon')
\end{align}
$
Even for the general kernel similar formulas can be obtained, but then you need some pseudo-differential calculus (see https://arxiv.org/pdf/2106.14277.pdf).
|
Maximum Mean Discrepancy (distance distribution)
For the Gaussian kernel $K({\mathbf x}, {\mathbf y})=e^{-||{\mathbf x}-{\mathbf y}||^2/4\sigma^2}$ on ${\mathbb R}^n$, the MMD satisfies:
${\rm MMD}(P,Q) \propto \sup\limits_{f\in L_2({\mathbb R}^n),
|
6,500
|
Random walk on the edges of a cube
|
I suggest modeling the problem as a Markov chain where each state represents the distance between the spider and the ant. In this case we have 4 possible states $S_i$ as the distances $i$ can be $\{0,1,2,3\}$.
When the spider is at the opposite corner of the cube, it is at a distance of 3 steps from the ant. It is in state $S_3$.
Building the transition matrix $\mathbf{P}$.
If we draw a cube we see that when we are at state $S_3$, every movement reduces the distance between the spider and the ant to 2 steps. So, when we are at state $S_3$ we move to state $S_2$ with probability 1.
When we are at state $S_2$, we can go back to state $S_3$ using the edge we arrived from there or we can decrease the distance to only one step if we choose two other edges. So, when we are at state $S_2$ we can move to state $S_1$ with probability 2/3 and to state $S_3$ with probability 1/3.
When we are at state $S_1$, we can go to state $S_0$ using one of the three possible edges. If we use the other two, we go back to state $S_2$. So, when we are at state $S_1$ we can move to state $S_0$ with probability 1/3 and to state $S_2$ with probability 2/3.
When we get to state $S_0$, we stay there since it is our goal. $S_0$ is an absorbing state.
\begin{equation}
\mathbf{P} = \left[\begin{array}{cccc}
P_{S_3 \to S_3} & P_{S_3 \to S_2}& P_{S_3 \to S_1} & P_{S_3 \to S_0} \\
P_{S_2 \to S_3} & P_{S_2 \to S_2}& P_{S_2 \to S_1} & P_{S_2 \to S_0} \\
P_{S_1 \to S_3} & P_{S_1 \to S_2}& P_{S_1 \to S_1} & P_{S_1 \to S_0} \\
P_{S_0 \to S_3} & P_{S_0 \to S_2} & P_{S_0 \to S_1}& P_{S_0 \to S_0} \\
\end{array}\right] = \left[\begin{array}{cccc}
0 & 1 & 0 & 0 \\
1/3 & 0 & 2/3 & 0 \\
0 & 2/3 & 0 & 1/3 \\
0 & 0 & 0 & 1 \\
\end{array}\right]
\end{equation}
This is an absorbing Markov chain with three transient states ($S_3$, $S_2$, $S_1$) and one absorbing state ($S_0$).
According to the theory, the transition matrix of a Markov chain with $t$ transient states and $r$ absorbing states can be rewritten as:
\begin{equation}
\mathbf{P} = \left[\begin{array}{cc}
\mathbf{Q}_t &\mathbf{R} \\
\mathbf{0}_{r \times t} & \mathbf{I}_r \\
\end{array}\right]
\end{equation}
where $\mathbf{Q}_t$ is a $t \times t$ matrix that shows the probability of transitioning from some transient state to another transient state, while $\mathbf{R}$ is a $t \times r$ matrix with the probabilities of transitioning from one of the $t$ transient states to one of the $r$ absorbing states. The identity matrix $\mathbf{I}_r$ shows us that when any of the $r$ absorbing state is reached, there is no transition away from that state. The all zeros matrix $\mathbf{0}_{r \times t}$ can be interpreted as that there is no transition from any of the $r$ absorbing states to any of the $t$ transient states.
The $(i,j)$ entry of $\mathbf{Q}_t$ represents probability of transitioning from a state $i$ to a state $j$ in exactly one step. To get the probability for $k$ steps we need the $(i,j)$ entry of $\mathbf{Q}_t^k$. Summing for all $k$, we get a matrix that contains in its $(i,j)$ entry the expected number of visits to transient state $j$ after starting from transient state $i$.
\begin{equation}
\sum_{k=0}^{\infty} \mathbf{Q}_t^k = (\mathbf{I}_t - \mathbf{Q}_t)^{-1}
\end{equation}
To get the number of steps until being absorbed, just sum the values of each row of $(\mathbf{I}_t - \mathbf{Q}_t)^{-1}$. This can be represented by
\begin{equation}
\mathbf{t} = (\mathbf{I}_t - \mathbf{Q}_t)^{-1} \mathbf{1}
\end{equation}
where $\mathbf{1}$ is a column vector with all components equal to 1.
Let us apply this to our case:
As stated above, in our case we have $t$=3 transient states and $r$=1 absorbing state, therefore:
\begin{equation}
\mathbf{Q}_t = \left[\begin{array}{ccc}
0 & 1 & 0 \\
1/3 & 0 & 2/3\\
0 & 2/3 & 0 \\
\end{array}\right] \quad \quad
\mathbf{R} = \left[\begin{array}{c}
0 \\
0\\
1/3 \\
\end{array}\right]
\end{equation}
The matrix with the expected number of visits is
\begin{equation}
(\mathbf{I}_t - \mathbf{Q}_t)^{-1} = \left[\begin{array}{ccc}
2.5 & 4.5 & 3 \\
1.5 & 4.5 & 3\\
1 & 3 & 3 \\
\end{array}\right]
\end{equation}
This matrix can be interpreted as follows. Starting from state $S_3$ and before getting absorbed at $S_0$ we visit, on average, $S_3$ 2.5 times, $S_2$ 4.5 times, and $S_1$ 3 times.
The expected number of steps from state $S_3$ to state $S_0$ is given by the first component of the following vector:
\begin{equation}
\mathbf{t} = \left[\begin{array}{ccc}
2.5 & 4.5 & 3 \\
1.5 & 4.5 & 3\\
1 & 3 & 3 \\
\end{array}\right] \left[\begin{array}{c}
1 \\
1\\
1\\
\end{array}\right] = \left[\begin{array}{c}
10 \\
9\\
7\\
\end{array}\right].
\end{equation}
The second and third components of $\mathbf{t}$ are the expected number of steps to $S_0$ if we start from $S_2$ and $S_1$ respectively.
|
Random walk on the edges of a cube
|
I suggest modeling the problem as a Markov chain where each state represents the distance between the spider and the ant. In this case we have 4 possible states $S_i$ as the distances $i$ can be $\{0,
|
Random walk on the edges of a cube
I suggest modeling the problem as a Markov chain where each state represents the distance between the spider and the ant. In this case we have 4 possible states $S_i$ as the distances $i$ can be $\{0,1,2,3\}$.
When the spider is at the opposite corner of the cube, it is at a distance of 3 steps from the ant. It is in state $S_3$.
Building the transition matrix $\mathbf{P}$.
If we draw a cube we see that when we are at state $S_3$, every movement reduces the distance between the spider and the ant to 2 steps. So, when we are at state $S_3$ we move to state $S_2$ with probability 1.
When we are at state $S_2$, we can go back to state $S_3$ using the edge we arrived from there or we can decrease the distance to only one step if we choose two other edges. So, when we are at state $S_2$ we can move to state $S_1$ with probability 2/3 and to state $S_3$ with probability 1/3.
When we are at state $S_1$, we can go to state $S_0$ using one of the three possible edges. If we use the other two, we go back to state $S_2$. So, when we are at state $S_1$ we can move to state $S_0$ with probability 1/3 and to state $S_2$ with probability 2/3.
When we get to state $S_0$, we stay there since it is our goal. $S_0$ is an absorbing state.
\begin{equation}
\mathbf{P} = \left[\begin{array}{cccc}
P_{S_3 \to S_3} & P_{S_3 \to S_2}& P_{S_3 \to S_1} & P_{S_3 \to S_0} \\
P_{S_2 \to S_3} & P_{S_2 \to S_2}& P_{S_2 \to S_1} & P_{S_2 \to S_0} \\
P_{S_1 \to S_3} & P_{S_1 \to S_2}& P_{S_1 \to S_1} & P_{S_1 \to S_0} \\
P_{S_0 \to S_3} & P_{S_0 \to S_2} & P_{S_0 \to S_1}& P_{S_0 \to S_0} \\
\end{array}\right] = \left[\begin{array}{cccc}
0 & 1 & 0 & 0 \\
1/3 & 0 & 2/3 & 0 \\
0 & 2/3 & 0 & 1/3 \\
0 & 0 & 0 & 1 \\
\end{array}\right]
\end{equation}
This is an absorbing Markov chain with three transient states ($S_3$, $S_2$, $S_1$) and one absorbing state ($S_0$).
According to the theory, the transition matrix of a Markov chain with $t$ transient states and $r$ absorbing states can be rewritten as:
\begin{equation}
\mathbf{P} = \left[\begin{array}{cc}
\mathbf{Q}_t &\mathbf{R} \\
\mathbf{0}_{r \times t} & \mathbf{I}_r \\
\end{array}\right]
\end{equation}
where $\mathbf{Q}_t$ is a $t \times t$ matrix that shows the probability of transitioning from some transient state to another transient state, while $\mathbf{R}$ is a $t \times r$ matrix with the probabilities of transitioning from one of the $t$ transient states to one of the $r$ absorbing states. The identity matrix $\mathbf{I}_r$ shows us that when any of the $r$ absorbing state is reached, there is no transition away from that state. The all zeros matrix $\mathbf{0}_{r \times t}$ can be interpreted as that there is no transition from any of the $r$ absorbing states to any of the $t$ transient states.
The $(i,j)$ entry of $\mathbf{Q}_t$ represents probability of transitioning from a state $i$ to a state $j$ in exactly one step. To get the probability for $k$ steps we need the $(i,j)$ entry of $\mathbf{Q}_t^k$. Summing for all $k$, we get a matrix that contains in its $(i,j)$ entry the expected number of visits to transient state $j$ after starting from transient state $i$.
\begin{equation}
\sum_{k=0}^{\infty} \mathbf{Q}_t^k = (\mathbf{I}_t - \mathbf{Q}_t)^{-1}
\end{equation}
To get the number of steps until being absorbed, just sum the values of each row of $(\mathbf{I}_t - \mathbf{Q}_t)^{-1}$. This can be represented by
\begin{equation}
\mathbf{t} = (\mathbf{I}_t - \mathbf{Q}_t)^{-1} \mathbf{1}
\end{equation}
where $\mathbf{1}$ is a column vector with all components equal to 1.
Let us apply this to our case:
As stated above, in our case we have $t$=3 transient states and $r$=1 absorbing state, therefore:
\begin{equation}
\mathbf{Q}_t = \left[\begin{array}{ccc}
0 & 1 & 0 \\
1/3 & 0 & 2/3\\
0 & 2/3 & 0 \\
\end{array}\right] \quad \quad
\mathbf{R} = \left[\begin{array}{c}
0 \\
0\\
1/3 \\
\end{array}\right]
\end{equation}
The matrix with the expected number of visits is
\begin{equation}
(\mathbf{I}_t - \mathbf{Q}_t)^{-1} = \left[\begin{array}{ccc}
2.5 & 4.5 & 3 \\
1.5 & 4.5 & 3\\
1 & 3 & 3 \\
\end{array}\right]
\end{equation}
This matrix can be interpreted as follows. Starting from state $S_3$ and before getting absorbed at $S_0$ we visit, on average, $S_3$ 2.5 times, $S_2$ 4.5 times, and $S_1$ 3 times.
The expected number of steps from state $S_3$ to state $S_0$ is given by the first component of the following vector:
\begin{equation}
\mathbf{t} = \left[\begin{array}{ccc}
2.5 & 4.5 & 3 \\
1.5 & 4.5 & 3\\
1 & 3 & 3 \\
\end{array}\right] \left[\begin{array}{c}
1 \\
1\\
1\\
\end{array}\right] = \left[\begin{array}{c}
10 \\
9\\
7\\
\end{array}\right].
\end{equation}
The second and third components of $\mathbf{t}$ are the expected number of steps to $S_0$ if we start from $S_2$ and $S_1$ respectively.
|
Random walk on the edges of a cube
I suggest modeling the problem as a Markov chain where each state represents the distance between the spider and the ant. In this case we have 4 possible states $S_i$ as the distances $i$ can be $\{0,
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.