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
27,301
Could we explain the disadvantage of imbalanced data mathematically?
In general statisticians are not worried about bias in imbalanced data (not a problem per se), since they use probabilistic classifiers like logistic regression the bias (in small samples) of logistic regression is orders of magnitude smaller than the variance. So it's my personal belief that ML researchers have been 'fooled by randomness'. In addition SVMs and random forests are not (or not good) probabilistic classifiers, and there rebalancing might have been beneficial. gradient boosted models are well calibrated probability classifiers so this is no longer an issue. There is a relatively recent freely accessible paper (https://gking.harvard.edu/files/0s.pdf) that covers your particular question for logistic regression, and reports the estimated bias which has been known since the 60s? Although the paper seems to argue for the importance of bias correction, their results show that it's pretty immaterial for probability estimation ( until you go to 3 standard deviations from the mean of their normally distributed input data). see figure 6. Infact the debiased model gives worse results than both standard logistic regression and their proposed bayesian regression. I interpret these results as consistent with the argument that the variance is the big problem with imbalanced data and standard regularisation approaches (like bayesian regression) have the most to offer to fix the problem. @lambda, So I tried to find the theory paper (from the same author) that the paper you mentioned references. Class Imbalance, Redux. I have only access to a summary wallace imbalance. It seems like the authors took the heuristic explanation given by King et al. (" To see this intuitively, and only heuristically...") and promoted it to a theory. The suggestion seems to be that the maximum is biased low (as function of sample size). So in the perfect separation case, a decision boundary set between the extrema of majority and minority class will be biased (towards the minority class). Undersampling the majority class will help this (oversampling the minority will not help). Adjusting costs will not help this because you are already correctly classifying all the negative class correctly. This assumes that the maximum is actually used in the ML algorithm. As alluded to by @dikran-marsupial, this seems to depend on perfectly separating the data, it's not a general property (eg most clearly linear discriminant analysis only uses means and covariances of the class). Another proviso is this assumes numeric and not categorical data. I do think this is an interesting argument and it might explain why this is something that ML people training trees etc to perfect classification hit this problem, whilst focussing on probability calibration avoids this.
Could we explain the disadvantage of imbalanced data mathematically?
In general statisticians are not worried about bias in imbalanced data (not a problem per se), since they use probabilistic classifiers like logistic regression the bias (in small samples) of logisti
Could we explain the disadvantage of imbalanced data mathematically? In general statisticians are not worried about bias in imbalanced data (not a problem per se), since they use probabilistic classifiers like logistic regression the bias (in small samples) of logistic regression is orders of magnitude smaller than the variance. So it's my personal belief that ML researchers have been 'fooled by randomness'. In addition SVMs and random forests are not (or not good) probabilistic classifiers, and there rebalancing might have been beneficial. gradient boosted models are well calibrated probability classifiers so this is no longer an issue. There is a relatively recent freely accessible paper (https://gking.harvard.edu/files/0s.pdf) that covers your particular question for logistic regression, and reports the estimated bias which has been known since the 60s? Although the paper seems to argue for the importance of bias correction, their results show that it's pretty immaterial for probability estimation ( until you go to 3 standard deviations from the mean of their normally distributed input data). see figure 6. Infact the debiased model gives worse results than both standard logistic regression and their proposed bayesian regression. I interpret these results as consistent with the argument that the variance is the big problem with imbalanced data and standard regularisation approaches (like bayesian regression) have the most to offer to fix the problem. @lambda, So I tried to find the theory paper (from the same author) that the paper you mentioned references. Class Imbalance, Redux. I have only access to a summary wallace imbalance. It seems like the authors took the heuristic explanation given by King et al. (" To see this intuitively, and only heuristically...") and promoted it to a theory. The suggestion seems to be that the maximum is biased low (as function of sample size). So in the perfect separation case, a decision boundary set between the extrema of majority and minority class will be biased (towards the minority class). Undersampling the majority class will help this (oversampling the minority will not help). Adjusting costs will not help this because you are already correctly classifying all the negative class correctly. This assumes that the maximum is actually used in the ML algorithm. As alluded to by @dikran-marsupial, this seems to depend on perfectly separating the data, it's not a general property (eg most clearly linear discriminant analysis only uses means and covariances of the class). Another proviso is this assumes numeric and not categorical data. I do think this is an interesting argument and it might explain why this is something that ML people training trees etc to perfect classification hit this problem, whilst focussing on probability calibration avoids this.
Could we explain the disadvantage of imbalanced data mathematically? In general statisticians are not worried about bias in imbalanced data (not a problem per se), since they use probabilistic classifiers like logistic regression the bias (in small samples) of logisti
27,302
Could we explain the disadvantage of imbalanced data mathematically?
There is indeed a bias with logistic regression and maximum likelihood estimation when the classes are not equal. Below is a demonstration by coding a simulation (example in literature here) set.seed(1) sim = function(n1 = 500, n2 = 20) { ### data x1 = rnorm(n1,-1,1) x2 = rnorm(n2,1,1) x = c(x1,x2) y = c(rep(0,n1),rep(1,n2)) ### model plus correct for undersampling mod = glm(y ~ x, family = binomial()) coefficients(mod) + c(log(n1/n2),0) } sims = replicate(10000,sim()) layout(matrix(1:2)) hist(sims[1,], main = "intercept estimate should be 0") hist(sims[2,], main ="slope estimate should be 2") rowMeans(sims) Possibly you could proof this mathematically. Intuitively it is not unsurprising when a maximum likelihood, which is not designed to be zero bias, to be biased. If the penalties for false positives and false negatives are different then it might be good to add some bias. In the case of a contingency table we will also get a bias $$\begin{array}{} & x=0 & x= 1 \\ y = 0 & 1-p_0 & 1-p_1 \\ y = 1 & p_0 & p_1 \end{array}$$ The bias does not occur in the estimates of $p_0$ and $p_1$, which is like estimating parameters of independent Bernoulli distributions, which should be unbiased. However, the slope parameter of the curve that we draw through the points will be biased. $$\hat{\beta}_{slope} = \log\left(\frac{\hat{p}_1}{1-\hat{p}_1}\right) - \log\left(\frac{\hat{p}_0}{1-\hat{p}_0}\right)$$ Also, it could be a form of regression attenuation, the bias of a regression curve being closer towards zero, when the x-values have measurement error. When one of the categories is rare (away from odds equal to 1), then this attenuation will be stronger. I imagine more strong bias to occur when you have complex patterns and a model is better able to learn one class and not the other class. Another type of bias that relates to this training difference is here: Was Amazon's AI tool, more than human recruiters, biased against women? Some recruiter tool might select based on some criteria the best men and women. But due to underrepresentation of women they might be underrepresented in the high level criteria. Then you could have a situation as in the image below. Even when on average women might be more often in the class of a good candidate, it is mostly men that could end up with a higher class probability probability because the model trained on men and got very good and seperating them.
Could we explain the disadvantage of imbalanced data mathematically?
There is indeed a bias with logistic regression and maximum likelihood estimation when the classes are not equal. Below is a demonstration by coding a simulation (example in literature here) set.seed(
Could we explain the disadvantage of imbalanced data mathematically? There is indeed a bias with logistic regression and maximum likelihood estimation when the classes are not equal. Below is a demonstration by coding a simulation (example in literature here) set.seed(1) sim = function(n1 = 500, n2 = 20) { ### data x1 = rnorm(n1,-1,1) x2 = rnorm(n2,1,1) x = c(x1,x2) y = c(rep(0,n1),rep(1,n2)) ### model plus correct for undersampling mod = glm(y ~ x, family = binomial()) coefficients(mod) + c(log(n1/n2),0) } sims = replicate(10000,sim()) layout(matrix(1:2)) hist(sims[1,], main = "intercept estimate should be 0") hist(sims[2,], main ="slope estimate should be 2") rowMeans(sims) Possibly you could proof this mathematically. Intuitively it is not unsurprising when a maximum likelihood, which is not designed to be zero bias, to be biased. If the penalties for false positives and false negatives are different then it might be good to add some bias. In the case of a contingency table we will also get a bias $$\begin{array}{} & x=0 & x= 1 \\ y = 0 & 1-p_0 & 1-p_1 \\ y = 1 & p_0 & p_1 \end{array}$$ The bias does not occur in the estimates of $p_0$ and $p_1$, which is like estimating parameters of independent Bernoulli distributions, which should be unbiased. However, the slope parameter of the curve that we draw through the points will be biased. $$\hat{\beta}_{slope} = \log\left(\frac{\hat{p}_1}{1-\hat{p}_1}\right) - \log\left(\frac{\hat{p}_0}{1-\hat{p}_0}\right)$$ Also, it could be a form of regression attenuation, the bias of a regression curve being closer towards zero, when the x-values have measurement error. When one of the categories is rare (away from odds equal to 1), then this attenuation will be stronger. I imagine more strong bias to occur when you have complex patterns and a model is better able to learn one class and not the other class. Another type of bias that relates to this training difference is here: Was Amazon's AI tool, more than human recruiters, biased against women? Some recruiter tool might select based on some criteria the best men and women. But due to underrepresentation of women they might be underrepresented in the high level criteria. Then you could have a situation as in the image below. Even when on average women might be more often in the class of a good candidate, it is mostly men that could end up with a higher class probability probability because the model trained on men and got very good and seperating them.
Could we explain the disadvantage of imbalanced data mathematically? There is indeed a bias with logistic regression and maximum likelihood estimation when the classes are not equal. Below is a demonstration by coding a simulation (example in literature here) set.seed(
27,303
Could we explain the disadvantage of imbalanced data mathematically?
Not all strongly unbalanced data would result in logistic regression underestimating the probability of the minority in a relevant way. If the data is perfectly separated (and logistic regression is using proper regularization), there will be perfect accuracy. But, of course, lots of unbalanced data sets will lead to relevantly underestimating the probability of the minority class. And the mathematical proof for each of those data sets would be to simply apply your choice of logistic regression to this data set and check the resulting accuracy. Here is a link to the paper you mentioned, maybe you can access this one. In there, see Figure 3, they give an intuitive example that shows why we often observe underestimation.
Could we explain the disadvantage of imbalanced data mathematically?
Not all strongly unbalanced data would result in logistic regression underestimating the probability of the minority in a relevant way. If the data is perfectly separated (and logistic regression is
Could we explain the disadvantage of imbalanced data mathematically? Not all strongly unbalanced data would result in logistic regression underestimating the probability of the minority in a relevant way. If the data is perfectly separated (and logistic regression is using proper regularization), there will be perfect accuracy. But, of course, lots of unbalanced data sets will lead to relevantly underestimating the probability of the minority class. And the mathematical proof for each of those data sets would be to simply apply your choice of logistic regression to this data set and check the resulting accuracy. Here is a link to the paper you mentioned, maybe you can access this one. In there, see Figure 3, they give an intuitive example that shows why we often observe underestimation.
Could we explain the disadvantage of imbalanced data mathematically? Not all strongly unbalanced data would result in logistic regression underestimating the probability of the minority in a relevant way. If the data is perfectly separated (and logistic regression is
27,304
Could we explain the disadvantage of imbalanced data mathematically?
Not an explanation but an example illustrating that strong imbalance forces dismissal of the underrepresented class. Let $y = y_1, ..., y_N$ be a sample where $y_k = 0$ except for $y_1 = 1$. Also, assume that you have observations $x_k$ such that the true probability $p(y_k = 1 \mid x_k) = 0.5$ for all $k$. If $m(x)$ is your model output, the MSE is given by $$ \frac{1}{N}\sum_{k=1}^N (y_k - m(x_k))^2 = \frac{1}{N}(1 - m(x_1))^2 + \frac{1}{N}\sum_{k=2}^N m(x_k)^2 $$ As $N$ tends to infinity, the first term disappears and the optimal model becomes indistinguishable from $m(x) = 0$. What is worse, the true model ($m(x) = 0.5$) gives a very large error.
Could we explain the disadvantage of imbalanced data mathematically?
Not an explanation but an example illustrating that strong imbalance forces dismissal of the underrepresented class. Let $y = y_1, ..., y_N$ be a sample where $y_k = 0$ except for $y_1 = 1$. Also, ass
Could we explain the disadvantage of imbalanced data mathematically? Not an explanation but an example illustrating that strong imbalance forces dismissal of the underrepresented class. Let $y = y_1, ..., y_N$ be a sample where $y_k = 0$ except for $y_1 = 1$. Also, assume that you have observations $x_k$ such that the true probability $p(y_k = 1 \mid x_k) = 0.5$ for all $k$. If $m(x)$ is your model output, the MSE is given by $$ \frac{1}{N}\sum_{k=1}^N (y_k - m(x_k))^2 = \frac{1}{N}(1 - m(x_1))^2 + \frac{1}{N}\sum_{k=2}^N m(x_k)^2 $$ As $N$ tends to infinity, the first term disappears and the optimal model becomes indistinguishable from $m(x) = 0$. What is worse, the true model ($m(x) = 0.5$) gives a very large error.
Could we explain the disadvantage of imbalanced data mathematically? Not an explanation but an example illustrating that strong imbalance forces dismissal of the underrepresented class. Let $y = y_1, ..., y_N$ be a sample where $y_k = 0$ except for $y_1 = 1$. Also, ass
27,305
Why is ANOVA not p-hacking?
It is not p-hacking. Multiple groups are compared but only a single hypothesis is tested. ANOVA computes a ratio of variances and a p-value can be computed for that ratio based on a single hypothesis. Possibly the idea of 'anova = p-hacking' arises due to the confusing aspect that a hypothesis test is often not used to test a null hypothesis, but instead to give prove/justification for the alternative hypothesis (which can be many at once). Note that ANOVA has the following properties ANOVA doesn't tell which of the many groups are different, but only that they are not the same. ANOVA is less powerfull than seperate t-test for all sort of combinations of groups. If I split the dataset into many (100+) groups, where group one might split vegetarians/meat eaters, group two might split coffee drinkers and tea drinkers, group 3 might split female coffee drinkers and male tea drinkers etc. If then use ANOVA to compare all groups to see if there's a statistically significant difference, is this not effectively p-hacking? It is not clear how you are gonna do this splitting and ANOVA. With ANOVA you can have multiple groups, but these should not be overlapping. You might do something like a linear model with all those variables, but then each additional group/variable is gonna decrease the degrees of freedom and make the ANOVA test less sensitive/powerful.
Why is ANOVA not p-hacking?
It is not p-hacking. Multiple groups are compared but only a single hypothesis is tested. ANOVA computes a ratio of variances and a p-value can be computed for that ratio based on a single hypothesis.
Why is ANOVA not p-hacking? It is not p-hacking. Multiple groups are compared but only a single hypothesis is tested. ANOVA computes a ratio of variances and a p-value can be computed for that ratio based on a single hypothesis. Possibly the idea of 'anova = p-hacking' arises due to the confusing aspect that a hypothesis test is often not used to test a null hypothesis, but instead to give prove/justification for the alternative hypothesis (which can be many at once). Note that ANOVA has the following properties ANOVA doesn't tell which of the many groups are different, but only that they are not the same. ANOVA is less powerfull than seperate t-test for all sort of combinations of groups. If I split the dataset into many (100+) groups, where group one might split vegetarians/meat eaters, group two might split coffee drinkers and tea drinkers, group 3 might split female coffee drinkers and male tea drinkers etc. If then use ANOVA to compare all groups to see if there's a statistically significant difference, is this not effectively p-hacking? It is not clear how you are gonna do this splitting and ANOVA. With ANOVA you can have multiple groups, but these should not be overlapping. You might do something like a linear model with all those variables, but then each additional group/variable is gonna decrease the degrees of freedom and make the ANOVA test less sensitive/powerful.
Why is ANOVA not p-hacking? It is not p-hacking. Multiple groups are compared but only a single hypothesis is tested. ANOVA computes a ratio of variances and a p-value can be computed for that ratio based on a single hypothesis.
27,306
Why is ANOVA not p-hacking?
You appear to perhaps be confusing p hacking with application of statistical methods involving more than a single binary explanatory variable (also see below, where I address post hoc tests following ANOVA). This reminds me of the accusation "Anyone can lie with statistics!" which, while true, does not reveal some special truth about statistics: when describing human communication you can just expostulate "Anyone can lie" full stop. Regardless of statistical method (e.g., ANOVA, or something else), the term p hacking connotes a researcher (or research group) who has prioritized reporting "statistically significant findings" over reporting "scientifically substantive findings" (whether positive or negative)… if not outright abandoning the reporting of findings of scientific substance. So p hacking is less about a specific statistical method (ANOVA or otherwise), than it is an orientation towards what one does with the method (and the study design, measurement, selection of participants, level of inference, etc.). A good cue, if you are unsure whether you are p hacking, is whether your research is lead by a well-formed theory-driven question in your particular domain of research, one that it would be valuable to answer, (with choice of research methods, including statistical methods following the lead of that question), or whether you start with a specific statistical method and go looking for "questions" to answer. Finally, ANOVA (and other omnibus hypothesis tests) do just what they say on the package: identify whether there is enough deviation from similarity among all the groups collectively for a given type I error rate (i.e. $\alpha$). Of course, p hacking really comes into play with the post hoc pairwise tests—if there are $k$ groups, then there are as many as $\frac{k^2 - k}{2}$ of these, which gives a good chance (specifically an $\alpha$ chance) of false positives to be reported as "statistically significant". Non-p hacking researchers can account for this by using muliple comparisons adjustment strategies (e.g., false discovery rate, family-wise error rate, etc.). Randall Munroe's "Significant" is always worth a chuckle, and is germane, so I am including yet again here. :)
Why is ANOVA not p-hacking?
You appear to perhaps be confusing p hacking with application of statistical methods involving more than a single binary explanatory variable (also see below, where I address post hoc tests following
Why is ANOVA not p-hacking? You appear to perhaps be confusing p hacking with application of statistical methods involving more than a single binary explanatory variable (also see below, where I address post hoc tests following ANOVA). This reminds me of the accusation "Anyone can lie with statistics!" which, while true, does not reveal some special truth about statistics: when describing human communication you can just expostulate "Anyone can lie" full stop. Regardless of statistical method (e.g., ANOVA, or something else), the term p hacking connotes a researcher (or research group) who has prioritized reporting "statistically significant findings" over reporting "scientifically substantive findings" (whether positive or negative)… if not outright abandoning the reporting of findings of scientific substance. So p hacking is less about a specific statistical method (ANOVA or otherwise), than it is an orientation towards what one does with the method (and the study design, measurement, selection of participants, level of inference, etc.). A good cue, if you are unsure whether you are p hacking, is whether your research is lead by a well-formed theory-driven question in your particular domain of research, one that it would be valuable to answer, (with choice of research methods, including statistical methods following the lead of that question), or whether you start with a specific statistical method and go looking for "questions" to answer. Finally, ANOVA (and other omnibus hypothesis tests) do just what they say on the package: identify whether there is enough deviation from similarity among all the groups collectively for a given type I error rate (i.e. $\alpha$). Of course, p hacking really comes into play with the post hoc pairwise tests—if there are $k$ groups, then there are as many as $\frac{k^2 - k}{2}$ of these, which gives a good chance (specifically an $\alpha$ chance) of false positives to be reported as "statistically significant". Non-p hacking researchers can account for this by using muliple comparisons adjustment strategies (e.g., false discovery rate, family-wise error rate, etc.). Randall Munroe's "Significant" is always worth a chuckle, and is germane, so I am including yet again here. :)
Why is ANOVA not p-hacking? You appear to perhaps be confusing p hacking with application of statistical methods involving more than a single binary explanatory variable (also see below, where I address post hoc tests following
27,307
Why is ANOVA not p-hacking?
There is no doubt that ANOVA--and any many other statistical tests--can be used for P-hacking, if used repeatedly on many random datasets, as you describe. At the 5% level, about 1 in 20 of the tests will have a P-value below 0.05. Under $H_0$ for an exact test based on a continuous test statistic, the distribution of the P-value is standard uniform, and thus has probability 0.05, below 0.05. Shown below are simulations for (a) t.tests with normal data, (b) exact binomial tests with binomial counts, and (c) one-sample Wilcoxon tests with normal data. When $H_0$ is true: Only the t.test shows a standard uniform distribution for the P-value. The binomial test has P-values as close to 5% as possible (without exceeding 5%), so there is no (nonrandomized) binomial test at exactly the 5% level. The Wilcoxon test is based on ranks; hence the test statistic is not continuous. But a test near the 5% level is available. R code for figure: set.seed(1234) pv.t = replicate(10^5, t.test(rnorm(25, 100, 15), mu = 100)$p.val) mean(pv.t <= 0.05) [1] 0.05017 # 5% within margin of sim error set.seed(1235) pv.b = replicate(10^5, binom.test(rbinom(1, 10, .5), 10)$p.val) mean(pv.b <= 0.05) [1] 0.02173 # No test at exactly 5% available # This test rejects for x=0,1,9, or 10 set.seed(1236) pv.w = replicate(10^5, wilcox.test(rnorm(25, 100, 15), mu = 100)$p.val) mean(pv.w <= 0.05) [1] 0.04905 # test very nearly at 5% par(mfrow=c(1,3)) hist(pv.t, prob=T, col="skyblue2", main="T Test") curve(dunif(x), add=T, col="brown", lwd=2) abline(v=.05, col="red", lty="dotted", lwd=2) hist(pv.b, prob=T, col="skyblue2", main="Exact Binomial Test") curve(dunif(x), add=T, col="brown", lwd=2) abline(v=.05, col="red", lty="dotted", lwd=2) hist(pv.w, prob=T, col="skyblue2", main="Wilcoxon Test") curve(dunif(x), add=T, col="brown", lwd=2) abline(v=.05, col="red", lty="dotted", lwd=2) par(mfrow=c(1,1))
Why is ANOVA not p-hacking?
There is no doubt that ANOVA--and any many other statistical tests--can be used for P-hacking, if used repeatedly on many random datasets, as you describe. At the 5% level, about 1 in 20 of the tests
Why is ANOVA not p-hacking? There is no doubt that ANOVA--and any many other statistical tests--can be used for P-hacking, if used repeatedly on many random datasets, as you describe. At the 5% level, about 1 in 20 of the tests will have a P-value below 0.05. Under $H_0$ for an exact test based on a continuous test statistic, the distribution of the P-value is standard uniform, and thus has probability 0.05, below 0.05. Shown below are simulations for (a) t.tests with normal data, (b) exact binomial tests with binomial counts, and (c) one-sample Wilcoxon tests with normal data. When $H_0$ is true: Only the t.test shows a standard uniform distribution for the P-value. The binomial test has P-values as close to 5% as possible (without exceeding 5%), so there is no (nonrandomized) binomial test at exactly the 5% level. The Wilcoxon test is based on ranks; hence the test statistic is not continuous. But a test near the 5% level is available. R code for figure: set.seed(1234) pv.t = replicate(10^5, t.test(rnorm(25, 100, 15), mu = 100)$p.val) mean(pv.t <= 0.05) [1] 0.05017 # 5% within margin of sim error set.seed(1235) pv.b = replicate(10^5, binom.test(rbinom(1, 10, .5), 10)$p.val) mean(pv.b <= 0.05) [1] 0.02173 # No test at exactly 5% available # This test rejects for x=0,1,9, or 10 set.seed(1236) pv.w = replicate(10^5, wilcox.test(rnorm(25, 100, 15), mu = 100)$p.val) mean(pv.w <= 0.05) [1] 0.04905 # test very nearly at 5% par(mfrow=c(1,3)) hist(pv.t, prob=T, col="skyblue2", main="T Test") curve(dunif(x), add=T, col="brown", lwd=2) abline(v=.05, col="red", lty="dotted", lwd=2) hist(pv.b, prob=T, col="skyblue2", main="Exact Binomial Test") curve(dunif(x), add=T, col="brown", lwd=2) abline(v=.05, col="red", lty="dotted", lwd=2) hist(pv.w, prob=T, col="skyblue2", main="Wilcoxon Test") curve(dunif(x), add=T, col="brown", lwd=2) abline(v=.05, col="red", lty="dotted", lwd=2) par(mfrow=c(1,1))
Why is ANOVA not p-hacking? There is no doubt that ANOVA--and any many other statistical tests--can be used for P-hacking, if used repeatedly on many random datasets, as you describe. At the 5% level, about 1 in 20 of the tests
27,308
How to calculate number of sets in Sigma Algebra
It is the number of subsets of a given set. While constructing a subset, we have two choices for each element in the set, i.e. take it or leave it. For $n$ elements, we have $2\times2...2=2^n$ choices, so there are $2^n$ different subsets of a given set.
How to calculate number of sets in Sigma Algebra
It is the number of subsets of a given set. While constructing a subset, we have two choices for each element in the set, i.e. take it or leave it. For $n$ elements, we have $2\times2...2=2^n$ choices
How to calculate number of sets in Sigma Algebra It is the number of subsets of a given set. While constructing a subset, we have two choices for each element in the set, i.e. take it or leave it. For $n$ elements, we have $2\times2...2=2^n$ choices, so there are $2^n$ different subsets of a given set.
How to calculate number of sets in Sigma Algebra It is the number of subsets of a given set. While constructing a subset, we have two choices for each element in the set, i.e. take it or leave it. For $n$ elements, we have $2\times2...2=2^n$ choices
27,309
How to calculate number of sets in Sigma Algebra
Although I am personally a fan of the answer laid out by @gunes (+1) for its simplicity, it is worth mentioning an alternative method of proof. The number of subsets of $S$ consisting of exactly $k$ elements is "n choose k", i.e. $$\binom{n}{k} = \frac{n!}{k!(n-k)!}.$$ Thus the total number of subsets is given by $$\begin{align*} |\mathcal B| &= \sum_{k=0}^n\binom{n}{k} \\[1.2ex] &= \sum_{k=0}^n\binom{n}{k}\times 1^k \times 1^{n-k} \\[1.2ex] &= (1+1)^n \\[1.2ex] &= 2^n \end{align*}$$ where the second to last equality is due to the binomial theorem.
How to calculate number of sets in Sigma Algebra
Although I am personally a fan of the answer laid out by @gunes (+1) for its simplicity, it is worth mentioning an alternative method of proof. The number of subsets of $S$ consisting of exactly $k$ e
How to calculate number of sets in Sigma Algebra Although I am personally a fan of the answer laid out by @gunes (+1) for its simplicity, it is worth mentioning an alternative method of proof. The number of subsets of $S$ consisting of exactly $k$ elements is "n choose k", i.e. $$\binom{n}{k} = \frac{n!}{k!(n-k)!}.$$ Thus the total number of subsets is given by $$\begin{align*} |\mathcal B| &= \sum_{k=0}^n\binom{n}{k} \\[1.2ex] &= \sum_{k=0}^n\binom{n}{k}\times 1^k \times 1^{n-k} \\[1.2ex] &= (1+1)^n \\[1.2ex] &= 2^n \end{align*}$$ where the second to last equality is due to the binomial theorem.
How to calculate number of sets in Sigma Algebra Although I am personally a fan of the answer laid out by @gunes (+1) for its simplicity, it is worth mentioning an alternative method of proof. The number of subsets of $S$ consisting of exactly $k$ e
27,310
How to calculate number of sets in Sigma Algebra
This is called power set. The other answers have information contained in the linked wikipedia page, though none of them surprisingly contain the term 'power set'. I think this answers a question that didn't ask but needs to know the answer to: 'What's the $\mathcal B$ called?' If Nemo knew what it was called, then Nemo wouldn't even be asking this question since Nemo would instead search google or wikipedia for 'number of elements in power set'.
How to calculate number of sets in Sigma Algebra
This is called power set. The other answers have information contained in the linked wikipedia page, though none of them surprisingly contain the term 'power set'. I think this answers a question that
How to calculate number of sets in Sigma Algebra This is called power set. The other answers have information contained in the linked wikipedia page, though none of them surprisingly contain the term 'power set'. I think this answers a question that didn't ask but needs to know the answer to: 'What's the $\mathcal B$ called?' If Nemo knew what it was called, then Nemo wouldn't even be asking this question since Nemo would instead search google or wikipedia for 'number of elements in power set'.
How to calculate number of sets in Sigma Algebra This is called power set. The other answers have information contained in the linked wikipedia page, though none of them surprisingly contain the term 'power set'. I think this answers a question that
27,311
Finding minimum/maximum peaks in a n-modal distribution
A very long time ago I learned an effective technique in the geological literature. (I apologize for not remembering the source.) It consists of studying the modes of a kernel density estimator (KDE) as the bandwidth is varied. What happens is that with a very large bandwidth, the data look like a big lump with a single mode. This one uses a bandwidth of 60 and its mode is near 110: As the bandwidth shrinks, the KDE outlines what the eye sees more closely and more modes appear. This one uses a bandwidth of 10 and has three obvious modes with a fourth just beginning to show near 60: When the bandwidth shrinks too far, the KDE is too detailed. This one with a bandwidth of 1 has 36 modes: You can explore this behavior with a "mode trace." For each bandwidth within the full range (from no detail to too detailed) it plots the modes. I have tracked the evolution of each mode and colored them accordingly. For instance, the single mode in the first figure corresponds to the central red line (shaped almost like a question mark); the four modes in the second figure correspond to the four traces rising to a height (bandwidth) of 10; the 36 modes in the third figure correspond to all 36 traces: It's probably a good idea to use a logarithmic scale for the bandwidth, as shown here. A glance at the mode trace will indicate how many modes to identify. I have chosen four. To determine their locations, I have found the points where the traces are the most vertical among all bandwidths smaller than the one at which all four modes first appear: at these locations the locations are stable even when the bandwidth changes. It is comforting (but not really essential) that all four locations are found using comparable bandwidths. (One really should take a bit more care in case multiple stable points appear along a trace: I would opt for the one with the largest bandwidth less than the bandwidth at which all the modes appear.) Having located the modes, we may plot them on the original histogram: It's then a simple matter to select the extreme modes. The mode trace will tell you how sensitive their locations are to both the number of modes you identify and to the bandwidth you use. In this example it suggests a tendency for the highest mode to grow even greater with smaller bandwidths before it splits into multiple modes, but the other three modes remain relatively stable (their traces remain nearly vertical at low bandwidths). It doesn't much matter what shape kernel you pick. The original paper suggested using a Gaussian kernel, which I have done here. The use of a Gaussian is not tantamount to any assumption that the peaks will even approximately have Gaussian shapes. Because Gaussians are (infinitely) smooth, so is the KDE, which means you can analyze it with Calculus techniques to your heart's content. To be perfectly clear, here is a mathematical account of the mode trace. Let the Kernel function $K$ have unit area and unique mode at $0$ and let the data be $x_1, \ldots, x_n.$ The KDE of the data with bandwidth $h\ge 0$ is the convolution $$f(x,h) = \frac{1}{nh}\sum_{i=1}^n K\left(\frac{x-x_i}{h}\right).$$ For each $h\ge 0,$ let $M(h)$ be the set of modes of the distribution function $x\to f(x,h).$ The "mode trace" of the data is the union of $M(h)$ as $h$ ranges over an interval $(0, A)$ where $A$ has been chosen so large that $M(h)$ contains a unique element for all $h\ge A.$ The mode trace has additional structure: it can be decomposed (not necessarily uniquely) into the disjoint union of graphs of continuous partial functions of $h$ defined on intervals. This decomposition is maximal in the sense that the only points any two distinct such functions can possibly have in common are at the endpoints of their domains. I have used colors to designate these partial functions. Apart from selecting the number of modes to use--which depends very much on your concept of the correct resolution at which to analyze your data--everything can be automated. Here is the R code I used to generate sample data, analyze them, and make the figures. Its results will be contained in a dataframe X recording the mode trace and an array modes containing information about the selected modes. BTW, if you code your own, note that the KDE is obtained most efficiently using the Fast Fourier Transform (FFT). The most efficient method transforms the data once and then multiplies that by a sequence of transformed kernels, inverting each product to produce the KDE. To determine the range of bandwidths to search, make the largest approximately one-quarter the range of the data and the smallest perhaps 3% or 1% of that. # # Generate random values from a mixture distribution. # rmix <- function(n, mu, sigma, p) { matrix(rnorm(length(mu)*n, mu, sigma), ncol=n)[ cbind(sample.int(length(mu), n, replace=TRUE, prob=p), 1:n)] } mu <- c(25, 60, 130, 190) # Means sigma <- c(8, 13, 15, 19) # SDs p <- c(.18, .2, .24, .28) # Relative proportions (needn't sum to 1) n <- 1e4 # Sample size x <- rmix(n, mu, sigma, p) # # Find the modes of a KDE. # (Quick and dirty: it assumes no mode spans more than one x value.) # findmodes <- function(kde) { kde$x[which(c(kde$y[-1],NA) < kde$y & kde$y > c(NA,kde$y[-length(kde$y)]))] } # # Compute the mode trace by varying the bandwidth within a factor of 10 of # the default bandwidth. Track the modes as the bandwidth is decreased from # its largest to its smallest value. # This calculation is fast, so we can afford a detailed search. # m <- mean(x) id <- 1 bw <- density(x)$bw * 10^seq(1,-1, length.out=101) modes.lst <- lapply(bw, function(h) { m.new <- sort(findmodes(density(x, bw=h))) # -- Associate each previous mode with a nearest new mode. if (length(m.new)==1) delta <- Inf else delta <- min(diff(m.new))/2 d <- outer(m.new, m, function(x,y) abs(x-y)) i <- apply(d, 2, which.min) g <- rep(NA_integer_, length(m.new)) g[i] <- id[1:ncol(d)] #-- Create new ids for new modes that appear. k <- is.na(g) g[k] <- (sum(!k)+1):length(g) id <<- g m <<- m.new data.frame(bw=h, Mode=m.new, id=g) }) X <- do.call(rbind, args=modes.lst) X$id <- factor(X$id) # # Locate the modes at the most vertical portions of their traces. # minslope <- function(x, y) { f <- splinefun(x, y) e <- diff(range(x)) * 1e-4 df2 <- function(x) ((f(x+e)-f(x-e)) / (2*e))^2 # Numerical derivative, squared v <- optimize(df2, c(min(x),max(x))) c(bw=v$minimum, slope=v$objective, Mode=f(v$minimum)) } # # Retain the desired modes. # n.modes <- 4 # USER SELECTED: Not automatic bw.max <- max(subset(X, id==n.modes)$bw) modes <- sapply(1:n.modes, function(i) { Y <- subset(X, id==i & bw <= bw.max) minslope(Y$bw, Y$Mode) }) # # Plot the results. # library(ggplot2) ggplot(X, aes(bw, Mode)) + geom_line(aes(col=id), size=1.2, show.legend=FALSE) + geom_point(aes(bw, Mode), data=as.data.frame(t(modes)), size=3, col="Black", alpha=1/2) + scale_x_log10() + coord_flip() + ggtitle("Mode Trace") ggplot(data.frame(x), aes(x, ..density..)) + geom_histogram(bins=500, fill="#2E75B2") + geom_vline(data=as.data.frame(t(modes)), mapping=aes(xintercept=Mode), col="#D18A4e", size=1) + ggtitle("Histogram With Modes")
Finding minimum/maximum peaks in a n-modal distribution
A very long time ago I learned an effective technique in the geological literature. (I apologize for not remembering the source.) It consists of studying the modes of a kernel density estimator (KDE
Finding minimum/maximum peaks in a n-modal distribution A very long time ago I learned an effective technique in the geological literature. (I apologize for not remembering the source.) It consists of studying the modes of a kernel density estimator (KDE) as the bandwidth is varied. What happens is that with a very large bandwidth, the data look like a big lump with a single mode. This one uses a bandwidth of 60 and its mode is near 110: As the bandwidth shrinks, the KDE outlines what the eye sees more closely and more modes appear. This one uses a bandwidth of 10 and has three obvious modes with a fourth just beginning to show near 60: When the bandwidth shrinks too far, the KDE is too detailed. This one with a bandwidth of 1 has 36 modes: You can explore this behavior with a "mode trace." For each bandwidth within the full range (from no detail to too detailed) it plots the modes. I have tracked the evolution of each mode and colored them accordingly. For instance, the single mode in the first figure corresponds to the central red line (shaped almost like a question mark); the four modes in the second figure correspond to the four traces rising to a height (bandwidth) of 10; the 36 modes in the third figure correspond to all 36 traces: It's probably a good idea to use a logarithmic scale for the bandwidth, as shown here. A glance at the mode trace will indicate how many modes to identify. I have chosen four. To determine their locations, I have found the points where the traces are the most vertical among all bandwidths smaller than the one at which all four modes first appear: at these locations the locations are stable even when the bandwidth changes. It is comforting (but not really essential) that all four locations are found using comparable bandwidths. (One really should take a bit more care in case multiple stable points appear along a trace: I would opt for the one with the largest bandwidth less than the bandwidth at which all the modes appear.) Having located the modes, we may plot them on the original histogram: It's then a simple matter to select the extreme modes. The mode trace will tell you how sensitive their locations are to both the number of modes you identify and to the bandwidth you use. In this example it suggests a tendency for the highest mode to grow even greater with smaller bandwidths before it splits into multiple modes, but the other three modes remain relatively stable (their traces remain nearly vertical at low bandwidths). It doesn't much matter what shape kernel you pick. The original paper suggested using a Gaussian kernel, which I have done here. The use of a Gaussian is not tantamount to any assumption that the peaks will even approximately have Gaussian shapes. Because Gaussians are (infinitely) smooth, so is the KDE, which means you can analyze it with Calculus techniques to your heart's content. To be perfectly clear, here is a mathematical account of the mode trace. Let the Kernel function $K$ have unit area and unique mode at $0$ and let the data be $x_1, \ldots, x_n.$ The KDE of the data with bandwidth $h\ge 0$ is the convolution $$f(x,h) = \frac{1}{nh}\sum_{i=1}^n K\left(\frac{x-x_i}{h}\right).$$ For each $h\ge 0,$ let $M(h)$ be the set of modes of the distribution function $x\to f(x,h).$ The "mode trace" of the data is the union of $M(h)$ as $h$ ranges over an interval $(0, A)$ where $A$ has been chosen so large that $M(h)$ contains a unique element for all $h\ge A.$ The mode trace has additional structure: it can be decomposed (not necessarily uniquely) into the disjoint union of graphs of continuous partial functions of $h$ defined on intervals. This decomposition is maximal in the sense that the only points any two distinct such functions can possibly have in common are at the endpoints of their domains. I have used colors to designate these partial functions. Apart from selecting the number of modes to use--which depends very much on your concept of the correct resolution at which to analyze your data--everything can be automated. Here is the R code I used to generate sample data, analyze them, and make the figures. Its results will be contained in a dataframe X recording the mode trace and an array modes containing information about the selected modes. BTW, if you code your own, note that the KDE is obtained most efficiently using the Fast Fourier Transform (FFT). The most efficient method transforms the data once and then multiplies that by a sequence of transformed kernels, inverting each product to produce the KDE. To determine the range of bandwidths to search, make the largest approximately one-quarter the range of the data and the smallest perhaps 3% or 1% of that. # # Generate random values from a mixture distribution. # rmix <- function(n, mu, sigma, p) { matrix(rnorm(length(mu)*n, mu, sigma), ncol=n)[ cbind(sample.int(length(mu), n, replace=TRUE, prob=p), 1:n)] } mu <- c(25, 60, 130, 190) # Means sigma <- c(8, 13, 15, 19) # SDs p <- c(.18, .2, .24, .28) # Relative proportions (needn't sum to 1) n <- 1e4 # Sample size x <- rmix(n, mu, sigma, p) # # Find the modes of a KDE. # (Quick and dirty: it assumes no mode spans more than one x value.) # findmodes <- function(kde) { kde$x[which(c(kde$y[-1],NA) < kde$y & kde$y > c(NA,kde$y[-length(kde$y)]))] } # # Compute the mode trace by varying the bandwidth within a factor of 10 of # the default bandwidth. Track the modes as the bandwidth is decreased from # its largest to its smallest value. # This calculation is fast, so we can afford a detailed search. # m <- mean(x) id <- 1 bw <- density(x)$bw * 10^seq(1,-1, length.out=101) modes.lst <- lapply(bw, function(h) { m.new <- sort(findmodes(density(x, bw=h))) # -- Associate each previous mode with a nearest new mode. if (length(m.new)==1) delta <- Inf else delta <- min(diff(m.new))/2 d <- outer(m.new, m, function(x,y) abs(x-y)) i <- apply(d, 2, which.min) g <- rep(NA_integer_, length(m.new)) g[i] <- id[1:ncol(d)] #-- Create new ids for new modes that appear. k <- is.na(g) g[k] <- (sum(!k)+1):length(g) id <<- g m <<- m.new data.frame(bw=h, Mode=m.new, id=g) }) X <- do.call(rbind, args=modes.lst) X$id <- factor(X$id) # # Locate the modes at the most vertical portions of their traces. # minslope <- function(x, y) { f <- splinefun(x, y) e <- diff(range(x)) * 1e-4 df2 <- function(x) ((f(x+e)-f(x-e)) / (2*e))^2 # Numerical derivative, squared v <- optimize(df2, c(min(x),max(x))) c(bw=v$minimum, slope=v$objective, Mode=f(v$minimum)) } # # Retain the desired modes. # n.modes <- 4 # USER SELECTED: Not automatic bw.max <- max(subset(X, id==n.modes)$bw) modes <- sapply(1:n.modes, function(i) { Y <- subset(X, id==i & bw <= bw.max) minslope(Y$bw, Y$Mode) }) # # Plot the results. # library(ggplot2) ggplot(X, aes(bw, Mode)) + geom_line(aes(col=id), size=1.2, show.legend=FALSE) + geom_point(aes(bw, Mode), data=as.data.frame(t(modes)), size=3, col="Black", alpha=1/2) + scale_x_log10() + coord_flip() + ggtitle("Mode Trace") ggplot(data.frame(x), aes(x, ..density..)) + geom_histogram(bins=500, fill="#2E75B2") + geom_vline(data=as.data.frame(t(modes)), mapping=aes(xintercept=Mode), col="#D18A4e", size=1) + ggtitle("Histogram With Modes")
Finding minimum/maximum peaks in a n-modal distribution A very long time ago I learned an effective technique in the geological literature. (I apologize for not remembering the source.) It consists of studying the modes of a kernel density estimator (KDE
27,312
Finding minimum/maximum peaks in a n-modal distribution
Here is some fake simulated data that are multimodal. The figure shows three kinds of plots (made with R): (1) histogram [blue], (2) tick marks below the axis, and (3) a kernel density estimator (KDE) of the data [red]. hist(x, prob=T, br=40, col="skyblue2"); rug(x) lines(density(x), col="red") I think the main difficulty with your plot is that it confuses local ties with overall modes. My histogram bars are also of irregular heights because I (purposely) used too many bars (by using parameter br=40). However, even with the best choice of numbers of bars, histograms are not the best kind of device for finding modes. The 'bandwidth' of the KDE can be adjusted for finding modes. Above, I used the default bandwidth. Maybe a slightly narrower bandwidth would have worked a little better. (I used parameter adj=.5 below. You can read the R documentation of density to see how to change bandwidth and types of kernels.) hist(x, prob=T, ylim=c(0, .01), col="skyblue2"); rug(x) lines(density(x, adj=.5), col="red") If you like, you can get a printout of around 500 heights of the KDE, then scan the numerical list left to right for increases and decreases in order to locate modes. (If scanning has to be automated, you can take differences in successive heights and see where they change sign to locate modes.) Here is some output from density, including the first 100 heights, rounded to three places here. DEN = density(x, adj=.5) DEN Call: density.default(x = x, adjust = 0.5) Data: x (950 obs.); Bandwidth 'bw' = 6.928 x y Min. :-13.61 Min. :1.154e-06 1st Qu.: 54.26 1st Qu.:1.829e-03 Median :122.13 Median :3.131e-03 Mean :122.13 Mean :3.680e-03 3rd Qu.:190.00 3rd Qu.:5.655e-03 Max. :257.87 Max. :1.010e-02 round(DEN$y[1:100],3) [1] 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 [11] 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 [21] 0.000 0.000 0.000 0.000 0.000 0.000 0.001 0.001 0.001 0.001 [31] 0.001 0.001 0.001 0.001 0.002 0.002 0.002 0.002 0.002 0.003 [41] 0.003 0.003 0.004 0.004 0.004 0.005 0.005 0.006 0.006 0.006 [51] 0.007 0.007 0.007 0.008 0.008 0.009 0.009 0.009 0.009 0.010 [61] 0.010 0.010 0.010 0.010 0.010 0.010 0.010 0.010 0.010 0.010 [71] 0.009 0.009 0.009 0.009 0.008 0.008 0.008 0.007 0.007 0.007 [81] 0.006 0.006 0.006 0.005 0.005 0.005 0.004 0.004 0.004 0.004 [91] 0.003 0.003 0.003 0.003 0.003 0.002 0.002 0.002 0.002 0.002
Finding minimum/maximum peaks in a n-modal distribution
Here is some fake simulated data that are multimodal. The figure shows three kinds of plots (made with R): (1) histogram [blue], (2) tick marks below the axis, and (3) a kernel density estimator (KDE)
Finding minimum/maximum peaks in a n-modal distribution Here is some fake simulated data that are multimodal. The figure shows three kinds of plots (made with R): (1) histogram [blue], (2) tick marks below the axis, and (3) a kernel density estimator (KDE) of the data [red]. hist(x, prob=T, br=40, col="skyblue2"); rug(x) lines(density(x), col="red") I think the main difficulty with your plot is that it confuses local ties with overall modes. My histogram bars are also of irregular heights because I (purposely) used too many bars (by using parameter br=40). However, even with the best choice of numbers of bars, histograms are not the best kind of device for finding modes. The 'bandwidth' of the KDE can be adjusted for finding modes. Above, I used the default bandwidth. Maybe a slightly narrower bandwidth would have worked a little better. (I used parameter adj=.5 below. You can read the R documentation of density to see how to change bandwidth and types of kernels.) hist(x, prob=T, ylim=c(0, .01), col="skyblue2"); rug(x) lines(density(x, adj=.5), col="red") If you like, you can get a printout of around 500 heights of the KDE, then scan the numerical list left to right for increases and decreases in order to locate modes. (If scanning has to be automated, you can take differences in successive heights and see where they change sign to locate modes.) Here is some output from density, including the first 100 heights, rounded to three places here. DEN = density(x, adj=.5) DEN Call: density.default(x = x, adjust = 0.5) Data: x (950 obs.); Bandwidth 'bw' = 6.928 x y Min. :-13.61 Min. :1.154e-06 1st Qu.: 54.26 1st Qu.:1.829e-03 Median :122.13 Median :3.131e-03 Mean :122.13 Mean :3.680e-03 3rd Qu.:190.00 3rd Qu.:5.655e-03 Max. :257.87 Max. :1.010e-02 round(DEN$y[1:100],3) [1] 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 [11] 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 [21] 0.000 0.000 0.000 0.000 0.000 0.000 0.001 0.001 0.001 0.001 [31] 0.001 0.001 0.001 0.001 0.002 0.002 0.002 0.002 0.002 0.003 [41] 0.003 0.003 0.004 0.004 0.004 0.005 0.005 0.006 0.006 0.006 [51] 0.007 0.007 0.007 0.008 0.008 0.009 0.009 0.009 0.009 0.010 [61] 0.010 0.010 0.010 0.010 0.010 0.010 0.010 0.010 0.010 0.010 [71] 0.009 0.009 0.009 0.009 0.008 0.008 0.008 0.007 0.007 0.007 [81] 0.006 0.006 0.006 0.005 0.005 0.005 0.004 0.004 0.004 0.004 [91] 0.003 0.003 0.003 0.003 0.003 0.002 0.002 0.002 0.002 0.002
Finding minimum/maximum peaks in a n-modal distribution Here is some fake simulated data that are multimodal. The figure shows three kinds of plots (made with R): (1) histogram [blue], (2) tick marks below the axis, and (3) a kernel density estimator (KDE)
27,313
Finding minimum/maximum peaks in a n-modal distribution
Not sure what kind of answer you're looking for, but thought I might give it a try. If you have a few of these, might be easiest to do it by hand. Cut off the sample at the trough of the left-most "bump" and find sample mode. Since you're asking this, I'm assuming you have a bunch of these and couldn't do it by hand. Here's a pseudocode of the algorithm: Set i = 0 Start with a window from 0 to i, find the mode of the data within that window. If the mode increases, continue increasing i and repeat the previous step. If the mode stop increasing, you've found your "minimum" mode. For "maximum" mode, just do the same from the right.
Finding minimum/maximum peaks in a n-modal distribution
Not sure what kind of answer you're looking for, but thought I might give it a try. If you have a few of these, might be easiest to do it by hand. Cut off the sample at the trough of the left-most "bu
Finding minimum/maximum peaks in a n-modal distribution Not sure what kind of answer you're looking for, but thought I might give it a try. If you have a few of these, might be easiest to do it by hand. Cut off the sample at the trough of the left-most "bump" and find sample mode. Since you're asking this, I'm assuming you have a bunch of these and couldn't do it by hand. Here's a pseudocode of the algorithm: Set i = 0 Start with a window from 0 to i, find the mode of the data within that window. If the mode increases, continue increasing i and repeat the previous step. If the mode stop increasing, you've found your "minimum" mode. For "maximum" mode, just do the same from the right.
Finding minimum/maximum peaks in a n-modal distribution Not sure what kind of answer you're looking for, but thought I might give it a try. If you have a few of these, might be easiest to do it by hand. Cut off the sample at the trough of the left-most "bu
27,314
Why are my steps getting smaller when using fixed step size in gradient descent?
Let $f(x) = \frac 12 x^T A x$ where $A$ is symmetric and positive definite (I think this assumption is safe based on your example). Then $\nabla f(x) = Ax$ and we can diagonalize $A$ as $A = Q\Lambda Q^T$. Use the change of basis $y =Q^T x$. Then we have $$ f(y) = \frac 12 y^T \Lambda y \implies \nabla f(y) = \Lambda y. $$ $\Lambda$ is diagonal so we get our updates as $$ y^{(n+1)} = y^{(n)} - \alpha \Lambda y^{(n)} = (I - \alpha \Lambda)y^{(n)} = (I - \alpha \Lambda)^{n+1}y^{(0)}. $$ This means that $1 - \alpha \lambda_i$ govern the convergence, and we only get convergence if $|1 - \alpha \lambda_i| < 1$. In your case we have $$ \Lambda \approx \left(\begin{array}{cc} 10.5 & 0 \\ 0 & 2.5\end{array}\right) $$ so $$ I - \alpha \Lambda \approx \left(\begin{array}{cc} 0.89 & 0 \\ 0 & 0.98\end{array}\right). $$ We get convergence relatively quickly in the direction corresponding to the eigenvector with eigenvalue $\lambda \approx 10.5$ as seen by how the iterates descend the steeper part of the paraboloid pretty quickly, but convergence is slow in the direction of the eigenvector with the smaller eigenvalue because $0.98$ is so close to $1$. So even though the learning rate $\alpha$ is fixed, the actual magnitudes of the steps in this direction decay according to approximately $(0.98)^n$ which becomes slower and slower. That is the cause of that exponential-looking slowdown in the progress in this direction (it happens in both directions but the other direction gets close enough soon enough that we don't notice or care). In this case convergence would be much faster if $\alpha$ was increased. For a much better and more thorough discussion of this, I strongly recommend https://distill.pub/2017/momentum/.
Why are my steps getting smaller when using fixed step size in gradient descent?
Let $f(x) = \frac 12 x^T A x$ where $A$ is symmetric and positive definite (I think this assumption is safe based on your example). Then $\nabla f(x) = Ax$ and we can diagonalize $A$ as $A = Q\Lambda
Why are my steps getting smaller when using fixed step size in gradient descent? Let $f(x) = \frac 12 x^T A x$ where $A$ is symmetric and positive definite (I think this assumption is safe based on your example). Then $\nabla f(x) = Ax$ and we can diagonalize $A$ as $A = Q\Lambda Q^T$. Use the change of basis $y =Q^T x$. Then we have $$ f(y) = \frac 12 y^T \Lambda y \implies \nabla f(y) = \Lambda y. $$ $\Lambda$ is diagonal so we get our updates as $$ y^{(n+1)} = y^{(n)} - \alpha \Lambda y^{(n)} = (I - \alpha \Lambda)y^{(n)} = (I - \alpha \Lambda)^{n+1}y^{(0)}. $$ This means that $1 - \alpha \lambda_i$ govern the convergence, and we only get convergence if $|1 - \alpha \lambda_i| < 1$. In your case we have $$ \Lambda \approx \left(\begin{array}{cc} 10.5 & 0 \\ 0 & 2.5\end{array}\right) $$ so $$ I - \alpha \Lambda \approx \left(\begin{array}{cc} 0.89 & 0 \\ 0 & 0.98\end{array}\right). $$ We get convergence relatively quickly in the direction corresponding to the eigenvector with eigenvalue $\lambda \approx 10.5$ as seen by how the iterates descend the steeper part of the paraboloid pretty quickly, but convergence is slow in the direction of the eigenvector with the smaller eigenvalue because $0.98$ is so close to $1$. So even though the learning rate $\alpha$ is fixed, the actual magnitudes of the steps in this direction decay according to approximately $(0.98)^n$ which becomes slower and slower. That is the cause of that exponential-looking slowdown in the progress in this direction (it happens in both directions but the other direction gets close enough soon enough that we don't notice or care). In this case convergence would be much faster if $\alpha$ was increased. For a much better and more thorough discussion of this, I strongly recommend https://distill.pub/2017/momentum/.
Why are my steps getting smaller when using fixed step size in gradient descent? Let $f(x) = \frac 12 x^T A x$ where $A$ is symmetric and positive definite (I think this assumption is safe based on your example). Then $\nabla f(x) = Ax$ and we can diagonalize $A$ as $A = Q\Lambda
27,315
Why are my steps getting smaller when using fixed step size in gradient descent?
For a smooth function, $\nabla f=0$ at the local minima. Because your update scheme is $\alpha \nabla f$, the magnitude $|\nabla f|$ controls the step size. In the case of your quadratic $|\Delta f|\rightarrow 0$ as well (just compute the hessian of the quadratic in your case). Note that this doesn't always have to be true. For example try the same scheme on $f(x)=x$. Then your step size is always $\alpha$ hence will never decrease. Or more interestingly, $f(x,y)=x+y^2$, where the gradient goes to 0 in the y coordinate, but not the $x$ coordinate. See Chaconne's answer for methodology for quadratics.
Why are my steps getting smaller when using fixed step size in gradient descent?
For a smooth function, $\nabla f=0$ at the local minima. Because your update scheme is $\alpha \nabla f$, the magnitude $|\nabla f|$ controls the step size. In the case of your quadratic $|\Delta f|\r
Why are my steps getting smaller when using fixed step size in gradient descent? For a smooth function, $\nabla f=0$ at the local minima. Because your update scheme is $\alpha \nabla f$, the magnitude $|\nabla f|$ controls the step size. In the case of your quadratic $|\Delta f|\rightarrow 0$ as well (just compute the hessian of the quadratic in your case). Note that this doesn't always have to be true. For example try the same scheme on $f(x)=x$. Then your step size is always $\alpha$ hence will never decrease. Or more interestingly, $f(x,y)=x+y^2$, where the gradient goes to 0 in the y coordinate, but not the $x$ coordinate. See Chaconne's answer for methodology for quadratics.
Why are my steps getting smaller when using fixed step size in gradient descent? For a smooth function, $\nabla f=0$ at the local minima. Because your update scheme is $\alpha \nabla f$, the magnitude $|\nabla f|$ controls the step size. In the case of your quadratic $|\Delta f|\r
27,316
if 2 random variables have exactly same mean and variance [duplicate]
In short: No. There are several properties of a probability distribution that need not affect its mean and variance, but do determine its shape. Skew & Kurtosis For example, a Poisson distribution with $\lambda = 1$ has expected value $\lambda = 1$ and variance $\lambda = 1$. So does a normal distribution with $\mu = 1$ and $\sigma^2 = 1$. An example with two continuous distributions: Take an exponential distribution with $\lambda = 1$, such that its variance is also $\lambda^{-2} = \frac{1}{1^2} = 1$ and compare it to a normal distribution with $\mu = 1$ and $\sigma^2 = 1$. These have the same expected value and the same variance, but look nothing alike and will produce very different numbers: As to what is different from these distributions with equal mean and variance: Consider the skew and excess kurtosis of the distributions. These are both $0$ for the normal distribution, but not for the exponential distribution. Multimodality As @Glen_b pointed out, skew and kurtosis are not the only things to take into consideration. Another example is multimodality: A continuous distribution with multiple modes can have the same mean and variance as a distribution with a single mode, while clearly they are not identically distributed. For example, consider a mixture of two normal distributions, each with $\sigma^2 = 1$, but their means are $2$ and $-2$, respectively. The resulting mixture will have a mean of $\mu=0$ and a variance of $\sigma^2 = 5$, which is the same expectation and variance as a single normal distribution $\mathcal{N}(0, 5)$: If you want to try for yourself, this is fairly easy to demonstrate in R: n <- 10e6 # some arbitrarily large sample size y1 <- rnorm(n, -2, 1) # mixture component 1 y2 <- rnorm(n, 2, 1) # mixture component 2 y.mixture <- c(y1, y2) mean(y.mixture) var(y.mixture) Versus: y.single <- rnorm(10e6, 0, sqrt(5)) # R parameterizes with sd instead of var mean(y.single) var(y.single)
if 2 random variables have exactly same mean and variance [duplicate]
In short: No. There are several properties of a probability distribution that need not affect its mean and variance, but do determine its shape. Skew & Kurtosis For example, a Poisson distribution wit
if 2 random variables have exactly same mean and variance [duplicate] In short: No. There are several properties of a probability distribution that need not affect its mean and variance, but do determine its shape. Skew & Kurtosis For example, a Poisson distribution with $\lambda = 1$ has expected value $\lambda = 1$ and variance $\lambda = 1$. So does a normal distribution with $\mu = 1$ and $\sigma^2 = 1$. An example with two continuous distributions: Take an exponential distribution with $\lambda = 1$, such that its variance is also $\lambda^{-2} = \frac{1}{1^2} = 1$ and compare it to a normal distribution with $\mu = 1$ and $\sigma^2 = 1$. These have the same expected value and the same variance, but look nothing alike and will produce very different numbers: As to what is different from these distributions with equal mean and variance: Consider the skew and excess kurtosis of the distributions. These are both $0$ for the normal distribution, but not for the exponential distribution. Multimodality As @Glen_b pointed out, skew and kurtosis are not the only things to take into consideration. Another example is multimodality: A continuous distribution with multiple modes can have the same mean and variance as a distribution with a single mode, while clearly they are not identically distributed. For example, consider a mixture of two normal distributions, each with $\sigma^2 = 1$, but their means are $2$ and $-2$, respectively. The resulting mixture will have a mean of $\mu=0$ and a variance of $\sigma^2 = 5$, which is the same expectation and variance as a single normal distribution $\mathcal{N}(0, 5)$: If you want to try for yourself, this is fairly easy to demonstrate in R: n <- 10e6 # some arbitrarily large sample size y1 <- rnorm(n, -2, 1) # mixture component 1 y2 <- rnorm(n, 2, 1) # mixture component 2 y.mixture <- c(y1, y2) mean(y.mixture) var(y.mixture) Versus: y.single <- rnorm(10e6, 0, sqrt(5)) # R parameterizes with sd instead of var mean(y.single) var(y.single)
if 2 random variables have exactly same mean and variance [duplicate] In short: No. There are several properties of a probability distribution that need not affect its mean and variance, but do determine its shape. Skew & Kurtosis For example, a Poisson distribution wit
27,317
Size of bootstrap samples
Bootstrap is conducted by sampling with replacement. It seems that the term "with replacement" is unclear for you. As noted by whuber, illustration of sampling with replacement is given on p. 3 of the paper you refer to (reproduced below). (source: http://web.stanford.edu/class/psych252/tutorials/doBootstrapPrimer.pdf) The general idea of sampling with replacement is that any case can be sampled multiple times (green marble on the first image above; blue and violet marbles on the last picture). If you want to imagine yourself this process, think of a bowl filled with colorful marbles. Say that you want to draw some number of marbles from this bowl. If you sampled without replacement, then you would be simply taking the marbles out of the bowl and putting the sampled ones aside. If you sampled with replacement, then you would be sampling the marbles one-by-one, by taking single marble out of the bowl, signing down it's color in your notebook and then returning it back to the bowl. So when sampling with replacement the same marble can be sampled multiple times. So when sampling without replacement, you can sample only $n$ marbles out of the bowl containing $n$ marbles, while in case of sampling with replacement you can sample any number of marbles (even greater then $n$) from the finite population. If you sampled $n$ out of $n$ marbles without replacement you would end up with exactly the same sample but in shuffled order. If you sampled $n$ out of $n$ marbles with replacement, each time you can possibly sample a different combination of marbles. There is $n \choose k$ ways of sampling without replacement $k$ cases out of population of size $ n$ and $n+k-1 \choose k$ ways of sampling with replacement. If you want to read more about the math behind it, you can check the 2.1. Combinatorics chapter of Introduction to Probability online handbook by Hossein Pishro-Nik. There is also a handy cheatsheet on WolframMathWorld page.
Size of bootstrap samples
Bootstrap is conducted by sampling with replacement. It seems that the term "with replacement" is unclear for you. As noted by whuber, illustration of sampling with replacement is given on p. 3 of the
Size of bootstrap samples Bootstrap is conducted by sampling with replacement. It seems that the term "with replacement" is unclear for you. As noted by whuber, illustration of sampling with replacement is given on p. 3 of the paper you refer to (reproduced below). (source: http://web.stanford.edu/class/psych252/tutorials/doBootstrapPrimer.pdf) The general idea of sampling with replacement is that any case can be sampled multiple times (green marble on the first image above; blue and violet marbles on the last picture). If you want to imagine yourself this process, think of a bowl filled with colorful marbles. Say that you want to draw some number of marbles from this bowl. If you sampled without replacement, then you would be simply taking the marbles out of the bowl and putting the sampled ones aside. If you sampled with replacement, then you would be sampling the marbles one-by-one, by taking single marble out of the bowl, signing down it's color in your notebook and then returning it back to the bowl. So when sampling with replacement the same marble can be sampled multiple times. So when sampling without replacement, you can sample only $n$ marbles out of the bowl containing $n$ marbles, while in case of sampling with replacement you can sample any number of marbles (even greater then $n$) from the finite population. If you sampled $n$ out of $n$ marbles without replacement you would end up with exactly the same sample but in shuffled order. If you sampled $n$ out of $n$ marbles with replacement, each time you can possibly sample a different combination of marbles. There is $n \choose k$ ways of sampling without replacement $k$ cases out of population of size $ n$ and $n+k-1 \choose k$ ways of sampling with replacement. If you want to read more about the math behind it, you can check the 2.1. Combinatorics chapter of Introduction to Probability online handbook by Hossein Pishro-Nik. There is also a handy cheatsheet on WolframMathWorld page.
Size of bootstrap samples Bootstrap is conducted by sampling with replacement. It seems that the term "with replacement" is unclear for you. As noted by whuber, illustration of sampling with replacement is given on p. 3 of the
27,318
Size of bootstrap samples
How many observations should we re-sample? A good suggestion is the original sample size. When the original sample size is too large and you don't want/cannot train a model on the full dataset, the "good suggestion" is not so good. PS: I wanted to add this as a comment to the question but I am not allowed to add any comment...
Size of bootstrap samples
How many observations should we re-sample? A good suggestion is the original sample size. When the original sample size is too large and you don't want/cannot train a model on the full dataset, the
Size of bootstrap samples How many observations should we re-sample? A good suggestion is the original sample size. When the original sample size is too large and you don't want/cannot train a model on the full dataset, the "good suggestion" is not so good. PS: I wanted to add this as a comment to the question but I am not allowed to add any comment...
Size of bootstrap samples How many observations should we re-sample? A good suggestion is the original sample size. When the original sample size is too large and you don't want/cannot train a model on the full dataset, the
27,319
Is it allowed to use averages on a dataset to improve correlation?
Let's have a look at two vectors, the first being 2 6 2 6 2 6 2 6 2 6 2 6 and the second vector being 6 2 6 2 6 2 6 2 6 2 6 2 Calculating the Pearson correlation you'll get cor(a,b) [1] -1 However if you take the average of successive pairs for values both vectors are identical. Identical vectors have correlation 1. 4 4 4 4 4 4 This simple example illustrates a downside of your method. Edit: To explain it more generally: The correlation coefficient is computed in the following way. $\frac{E[(X-\mu_X)(Y-\mu_Y)]}{\sigma_X\ \sigma_Y}$ Averaging some $X$s and some $Y$s changes the differences between $X$ and $\mu_X$ as well as the difference between $Y$ and $\mu_Y$.
Is it allowed to use averages on a dataset to improve correlation?
Let's have a look at two vectors, the first being 2 6 2 6 2 6 2 6 2 6 2 6 and the second vector being 6 2 6 2 6 2 6 2 6 2 6 2 Calculating the Pearson correlation you'll get cor(a,b) [1] -1
Is it allowed to use averages on a dataset to improve correlation? Let's have a look at two vectors, the first being 2 6 2 6 2 6 2 6 2 6 2 6 and the second vector being 6 2 6 2 6 2 6 2 6 2 6 2 Calculating the Pearson correlation you'll get cor(a,b) [1] -1 However if you take the average of successive pairs for values both vectors are identical. Identical vectors have correlation 1. 4 4 4 4 4 4 This simple example illustrates a downside of your method. Edit: To explain it more generally: The correlation coefficient is computed in the following way. $\frac{E[(X-\mu_X)(Y-\mu_Y)]}{\sigma_X\ \sigma_Y}$ Averaging some $X$s and some $Y$s changes the differences between $X$ and $\mu_X$ as well as the difference between $Y$ and $\mu_Y$.
Is it allowed to use averages on a dataset to improve correlation? Let's have a look at two vectors, the first being 2 6 2 6 2 6 2 6 2 6 2 6 and the second vector being 6 2 6 2 6 2 6 2 6 2 6 2 Calculating the Pearson correlation you'll get cor(a,b) [1] -1
27,320
Is it allowed to use averages on a dataset to improve correlation?
Averaging can be attractive or convenient. It can also be a source of deception, at worst deceit, so tread carefully even when there is a clear rationale for averaging. Here is a situation it which it is not a good idea. Consider that by careful definition of groups you (usually) could reduce your data to two summary points each distinct on the two variables; and then you would achieve a perfect correlation with magnitude $1$. Congratulations, or not! The improvement here is bogus without a good independent reason for the procedure. You don't need to approach this extreme case to approach the danger. There are some situations in which averaging can make sense. For example, if seasonal variations are of little or no interest, then averaging into yearly values creates a reduced dataset in which you can focus on those yearly values. In various fields, researchers could be interested in correlations at quite different scales, e.g. between unemployment and crime for individuals, counties, states, countries (substitute whatever terms make most sense). The interest, and often also a major source of inference troubles, is in interpreting what is going on at different scales or levels. For example, a high correlation between unemployment rate and crime rate for areas doesn't necessarily mean that the unemployed have a higher tendency to be criminals; you need data on individuals to be clear on that. Data provision can be maximally awkward in data being available only on the least interesting scale, perhaps as a matter of economy or confidentiality. I note also that that many measurements are in the first place often averages over small time intervals and/or small space intervals, so the data often arrive averaged in any case.
Is it allowed to use averages on a dataset to improve correlation?
Averaging can be attractive or convenient. It can also be a source of deception, at worst deceit, so tread carefully even when there is a clear rationale for averaging. Here is a situation it which i
Is it allowed to use averages on a dataset to improve correlation? Averaging can be attractive or convenient. It can also be a source of deception, at worst deceit, so tread carefully even when there is a clear rationale for averaging. Here is a situation it which it is not a good idea. Consider that by careful definition of groups you (usually) could reduce your data to two summary points each distinct on the two variables; and then you would achieve a perfect correlation with magnitude $1$. Congratulations, or not! The improvement here is bogus without a good independent reason for the procedure. You don't need to approach this extreme case to approach the danger. There are some situations in which averaging can make sense. For example, if seasonal variations are of little or no interest, then averaging into yearly values creates a reduced dataset in which you can focus on those yearly values. In various fields, researchers could be interested in correlations at quite different scales, e.g. between unemployment and crime for individuals, counties, states, countries (substitute whatever terms make most sense). The interest, and often also a major source of inference troubles, is in interpreting what is going on at different scales or levels. For example, a high correlation between unemployment rate and crime rate for areas doesn't necessarily mean that the unemployed have a higher tendency to be criminals; you need data on individuals to be clear on that. Data provision can be maximally awkward in data being available only on the least interesting scale, perhaps as a matter of economy or confidentiality. I note also that that many measurements are in the first place often averages over small time intervals and/or small space intervals, so the data often arrive averaged in any case.
Is it allowed to use averages on a dataset to improve correlation? Averaging can be attractive or convenient. It can also be a source of deception, at worst deceit, so tread carefully even when there is a clear rationale for averaging. Here is a situation it which i
27,321
Is it allowed to use averages on a dataset to improve correlation?
In the case of correlation of averages, it is necessary to be aware of Simpson's paradox.
Is it allowed to use averages on a dataset to improve correlation?
In the case of correlation of averages, it is necessary to be aware of Simpson's paradox.
Is it allowed to use averages on a dataset to improve correlation? In the case of correlation of averages, it is necessary to be aware of Simpson's paradox.
Is it allowed to use averages on a dataset to improve correlation? In the case of correlation of averages, it is necessary to be aware of Simpson's paradox.
27,322
Is there a formula for computing median?
If you define $O_1, O_2, \ldots, O_N$ to be the sorted version of your original data $X_1, X_2, \ldots, X_N$, then the median is defined as: $$ \mathrm{Median}(\{O_1, O_2, \ldots, O_N\}) = \left\{\begin{array}{ll} O_{(N+1)/2} & \mathrm{if}~N~\mathrm{is~odd} \\ (O_{N/2}+O_{N/2+1})/2 & \mathrm{otherwise}\end{array}\right. $$ Without ordering your data, you can use the definition of the geometric median to define the median in one dimension: $$ \mathrm{Median}(\{X_1, X_2, \ldots, X_N\}) = \arg\min_{y} \sum_{i=1}^N \big|X_i-y\big| $$ Note that this does not necessarily define a unique median when there are an even number of points; for instance any number $y\in[3, 4]$ optimizes the objective with $X = \{2, 3, 4, 5\}$.
Is there a formula for computing median?
If you define $O_1, O_2, \ldots, O_N$ to be the sorted version of your original data $X_1, X_2, \ldots, X_N$, then the median is defined as: $$ \mathrm{Median}(\{O_1, O_2, \ldots, O_N\}) = \left\{\beg
Is there a formula for computing median? If you define $O_1, O_2, \ldots, O_N$ to be the sorted version of your original data $X_1, X_2, \ldots, X_N$, then the median is defined as: $$ \mathrm{Median}(\{O_1, O_2, \ldots, O_N\}) = \left\{\begin{array}{ll} O_{(N+1)/2} & \mathrm{if}~N~\mathrm{is~odd} \\ (O_{N/2}+O_{N/2+1})/2 & \mathrm{otherwise}\end{array}\right. $$ Without ordering your data, you can use the definition of the geometric median to define the median in one dimension: $$ \mathrm{Median}(\{X_1, X_2, \ldots, X_N\}) = \arg\min_{y} \sum_{i=1}^N \big|X_i-y\big| $$ Note that this does not necessarily define a unique median when there are an even number of points; for instance any number $y\in[3, 4]$ optimizes the objective with $X = \{2, 3, 4, 5\}$.
Is there a formula for computing median? If you define $O_1, O_2, \ldots, O_N$ to be the sorted version of your original data $X_1, X_2, \ldots, X_N$, then the median is defined as: $$ \mathrm{Median}(\{O_1, O_2, \ldots, O_N\}) = \left\{\beg
27,323
Is there a formula for computing median?
One alternative way to express the mean is the "least squares" estimate: $$\sum_{i=1}^N (X_i - m)^2$$ Choosing $m $ to be the mean gives the smallest value of the sum of squared errors. Now the median can be expressed as the "least absolute deviations" estimate: $$\sum_{i=1}^N |X_i - m|$$ Choosing $m $ to be the median gives the smallest value of the sum of absolute errors.
Is there a formula for computing median?
One alternative way to express the mean is the "least squares" estimate: $$\sum_{i=1}^N (X_i - m)^2$$ Choosing $m $ to be the mean gives the smallest value of the sum of squared errors. Now the median
Is there a formula for computing median? One alternative way to express the mean is the "least squares" estimate: $$\sum_{i=1}^N (X_i - m)^2$$ Choosing $m $ to be the mean gives the smallest value of the sum of squared errors. Now the median can be expressed as the "least absolute deviations" estimate: $$\sum_{i=1}^N |X_i - m|$$ Choosing $m $ to be the median gives the smallest value of the sum of absolute errors.
Is there a formula for computing median? One alternative way to express the mean is the "least squares" estimate: $$\sum_{i=1}^N (X_i - m)^2$$ Choosing $m $ to be the mean gives the smallest value of the sum of squared errors. Now the median
27,324
Is there a formula for computing median?
The median is the value corresponding to the half quantile, that is half of the values are higher, half are lower (pardon me for ignoring cases with equality or when the set is even...). Such that given that the pdf $p_X$ of the data set $X_1 \cdot X_n$ is known, then the cumulative distribution is easily evaluated. Noting $P_X$ this function, then $$ median = P_X^{-1}(\frac 1 2) $$ Take for instance the case for angles in this method used in this review paper for histogram equalization. The lower left panel shows the pdf $p(\theta)$ of angles in a set of natural images. $P(\theta)$ is the cumulative distribution and the median is the value of $\theta$ corresponding to the value $1/2$, that is approximately $0$ in that case.
Is there a formula for computing median?
The median is the value corresponding to the half quantile, that is half of the values are higher, half are lower (pardon me for ignoring cases with equality or when the set is even...). Such that giv
Is there a formula for computing median? The median is the value corresponding to the half quantile, that is half of the values are higher, half are lower (pardon me for ignoring cases with equality or when the set is even...). Such that given that the pdf $p_X$ of the data set $X_1 \cdot X_n$ is known, then the cumulative distribution is easily evaluated. Noting $P_X$ this function, then $$ median = P_X^{-1}(\frac 1 2) $$ Take for instance the case for angles in this method used in this review paper for histogram equalization. The lower left panel shows the pdf $p(\theta)$ of angles in a set of natural images. $P(\theta)$ is the cumulative distribution and the median is the value of $\theta$ corresponding to the value $1/2$, that is approximately $0$ in that case.
Is there a formula for computing median? The median is the value corresponding to the half quantile, that is half of the values are higher, half are lower (pardon me for ignoring cases with equality or when the set is even...). Such that giv
27,325
Confidence interval for the median
To directly deal with error on the median you can use the exact nonparametric confidence interval for the median, which uses order statistics. If you want something different, i.e., a measure of dispersion, consider Gini's mean difference. Code is here for the median's confidence interval.
Confidence interval for the median
To directly deal with error on the median you can use the exact nonparametric confidence interval for the median, which uses order statistics. If you want something different, i.e., a measure of disp
Confidence interval for the median To directly deal with error on the median you can use the exact nonparametric confidence interval for the median, which uses order statistics. If you want something different, i.e., a measure of dispersion, consider Gini's mean difference. Code is here for the median's confidence interval.
Confidence interval for the median To directly deal with error on the median you can use the exact nonparametric confidence interval for the median, which uses order statistics. If you want something different, i.e., a measure of disp
27,326
Confidence interval for the median
As pointed out in the other answer, there is a non-parametric CI for the median using the order statistics. That CI is better in many aspects than what you found on the net. Now, if you must know where the $1.2533\frac{\sigma}{\sqrt{N}}$ factor comes from, the answer is from the asymptotic distribution of the median. If we denote the sample median by $\tilde{\theta}$ and the population median by $\theta$ then it can be shown that $$\sqrt{n} \left( \tilde{\theta} - \theta \right) \xrightarrow{L} \mathcal{N} \left(0, \frac{1}{4 \left[f \left( \theta \right) \right]^2} \right)$$ where $f$ is the distribution of your sample. The result is not as universal as the CLT because the asymptptic distribution still depends on the underlying distribution of your sample (through the term $\left[f \left( \theta \right) \right]^2$). You can, however, make the drastic simplication that your sample comes from a normal distribution with mean -and median- $\theta$ and variance $\sigma^2$. Evaluating $f$ at its point of symmetry then yields $$\left[f \left( \theta \right) \right]^2 = \frac{1}{2\pi \sigma^2}$$ and so the asymptotic variance becomes $$\frac{2\pi}{4} \sigma^2$$. Divide by $N$ and take the square root of that to arrive at your standard error $1.2533\frac{\sigma}{\sqrt{N}}$.
Confidence interval for the median
As pointed out in the other answer, there is a non-parametric CI for the median using the order statistics. That CI is better in many aspects than what you found on the net. Now, if you must know wh
Confidence interval for the median As pointed out in the other answer, there is a non-parametric CI for the median using the order statistics. That CI is better in many aspects than what you found on the net. Now, if you must know where the $1.2533\frac{\sigma}{\sqrt{N}}$ factor comes from, the answer is from the asymptotic distribution of the median. If we denote the sample median by $\tilde{\theta}$ and the population median by $\theta$ then it can be shown that $$\sqrt{n} \left( \tilde{\theta} - \theta \right) \xrightarrow{L} \mathcal{N} \left(0, \frac{1}{4 \left[f \left( \theta \right) \right]^2} \right)$$ where $f$ is the distribution of your sample. The result is not as universal as the CLT because the asymptptic distribution still depends on the underlying distribution of your sample (through the term $\left[f \left( \theta \right) \right]^2$). You can, however, make the drastic simplication that your sample comes from a normal distribution with mean -and median- $\theta$ and variance $\sigma^2$. Evaluating $f$ at its point of symmetry then yields $$\left[f \left( \theta \right) \right]^2 = \frac{1}{2\pi \sigma^2}$$ and so the asymptotic variance becomes $$\frac{2\pi}{4} \sigma^2$$. Divide by $N$ and take the square root of that to arrive at your standard error $1.2533\frac{\sigma}{\sqrt{N}}$.
Confidence interval for the median As pointed out in the other answer, there is a non-parametric CI for the median using the order statistics. That CI is better in many aspects than what you found on the net. Now, if you must know wh
27,327
Logistic regression is predicting all 1, and no 0
Well, it does make sense that your model predicts always 1. Have a look at your data set: it is severly imbalanced in favor of your positive class. The negative class makes up only ~7% of your data. Try re-balancing your training set or use a cost-sensitive algorithm.
Logistic regression is predicting all 1, and no 0
Well, it does make sense that your model predicts always 1. Have a look at your data set: it is severly imbalanced in favor of your positive class. The negative class makes up only ~7% of your data. T
Logistic regression is predicting all 1, and no 0 Well, it does make sense that your model predicts always 1. Have a look at your data set: it is severly imbalanced in favor of your positive class. The negative class makes up only ~7% of your data. Try re-balancing your training set or use a cost-sensitive algorithm.
Logistic regression is predicting all 1, and no 0 Well, it does make sense that your model predicts always 1. Have a look at your data set: it is severly imbalanced in favor of your positive class. The negative class makes up only ~7% of your data. T
27,328
Logistic regression is predicting all 1, and no 0
The short answer is that logistic regression is for estimating probabilities, nothing more or less. You can estimate probabilities no matter how imbalanced $Y$ is. ROC curves and some of the other measures given in the discussion don't help. If you need to make a decision or take an action you apply the loss/utility/cost function to the predicted risk and choose the action that optimizes the expected utility. It seems that a lot of machine learning users are not really understanding risks and optimum decisions.
Logistic regression is predicting all 1, and no 0
The short answer is that logistic regression is for estimating probabilities, nothing more or less. You can estimate probabilities no matter how imbalanced $Y$ is. ROC curves and some of the other m
Logistic regression is predicting all 1, and no 0 The short answer is that logistic regression is for estimating probabilities, nothing more or less. You can estimate probabilities no matter how imbalanced $Y$ is. ROC curves and some of the other measures given in the discussion don't help. If you need to make a decision or take an action you apply the loss/utility/cost function to the predicted risk and choose the action that optimizes the expected utility. It seems that a lot of machine learning users are not really understanding risks and optimum decisions.
Logistic regression is predicting all 1, and no 0 The short answer is that logistic regression is for estimating probabilities, nothing more or less. You can estimate probabilities no matter how imbalanced $Y$ is. ROC curves and some of the other m
27,329
Logistic regression is predicting all 1, and no 0
If the problem is indeed the imbalance between the classes, I would simply start by balancing the class weights: log_reg = LogisticRegression(class_weight = 'balanced') This parameter setting means that the penalties for false predictions in the loss function will be weighted with inverse proportions to the frequencies of the classes. This can solve the problem you describe.
Logistic regression is predicting all 1, and no 0
If the problem is indeed the imbalance between the classes, I would simply start by balancing the class weights: log_reg = LogisticRegression(class_weight = 'balanced') This parameter setting means
Logistic regression is predicting all 1, and no 0 If the problem is indeed the imbalance between the classes, I would simply start by balancing the class weights: log_reg = LogisticRegression(class_weight = 'balanced') This parameter setting means that the penalties for false predictions in the loss function will be weighted with inverse proportions to the frequencies of the classes. This can solve the problem you describe.
Logistic regression is predicting all 1, and no 0 If the problem is indeed the imbalance between the classes, I would simply start by balancing the class weights: log_reg = LogisticRegression(class_weight = 'balanced') This parameter setting means
27,330
Logistic regression is predicting all 1, and no 0
When you classify using logit, this is what happens. The logit predicts the probability of default (PD) of a loan, which is a number between 0 and 1. Next, you set a threshold D, such that you mark a loan to default if PD>D, and mark it as non-default if PD Naturally, in a typical loan population PD<<1. So, in your case 7% is rather high probability of it's one year data (PDs are normally reported on annual basis). If this is multi year data, then we're talking about so called cumulative PD, in this case cumPD=7% is not a high number for 10 years of data, for instance. Hence, by any standards, I wouldn't say that your data set is problematic. I'd describe it at least typical for loan default data, if not great (in the sense that you have relative large number of defaults). Now, suppose that your model predicting the following three levels of PD: 0.1 (563,426) 0.5 (20,000) 0.9 (31,932) Suppose also that the actual defaults for these groups were: 0 10,000 31,932 Now you can set D to different values and see how the matrix changes. Let's use D = 0.4 first: Actual default, predict non-default: 0 Actual default, predict default: 41,932 Actual non-default, predict non-default: 563,426 Actual non-default, predict default: 10,000 If you set D = 0.6: Actual default, predict non-default: 31,932 Actual default, predict default: 10,000 Actual non-default, predict non-default: 573,426 Actual non-default, predict default: 0 If you set D = 0.99: Actual default, predict non-default: 41,932 Actual default, predict default: 0 Actual non-default, predict non-default: 573,426 Actual non-default, predict default: 0 The last case is what you see in your model results. In this case I'm emphasizing the threshold D for a classifier. A simple in change in D may improve certain characteristics of your forecast. Note, that in all three cases the predicted PD remained the same, only the threshold D has changed. It is also possible that your logit regression itself is crappy, of course. So, in this case you have at least two variables: the logit spec and the threshold. Both impact your forecast power.
Logistic regression is predicting all 1, and no 0
When you classify using logit, this is what happens. The logit predicts the probability of default (PD) of a loan, which is a number between 0 and 1. Next, you set a threshold D, such that you mark a
Logistic regression is predicting all 1, and no 0 When you classify using logit, this is what happens. The logit predicts the probability of default (PD) of a loan, which is a number between 0 and 1. Next, you set a threshold D, such that you mark a loan to default if PD>D, and mark it as non-default if PD Naturally, in a typical loan population PD<<1. So, in your case 7% is rather high probability of it's one year data (PDs are normally reported on annual basis). If this is multi year data, then we're talking about so called cumulative PD, in this case cumPD=7% is not a high number for 10 years of data, for instance. Hence, by any standards, I wouldn't say that your data set is problematic. I'd describe it at least typical for loan default data, if not great (in the sense that you have relative large number of defaults). Now, suppose that your model predicting the following three levels of PD: 0.1 (563,426) 0.5 (20,000) 0.9 (31,932) Suppose also that the actual defaults for these groups were: 0 10,000 31,932 Now you can set D to different values and see how the matrix changes. Let's use D = 0.4 first: Actual default, predict non-default: 0 Actual default, predict default: 41,932 Actual non-default, predict non-default: 563,426 Actual non-default, predict default: 10,000 If you set D = 0.6: Actual default, predict non-default: 31,932 Actual default, predict default: 10,000 Actual non-default, predict non-default: 573,426 Actual non-default, predict default: 0 If you set D = 0.99: Actual default, predict non-default: 41,932 Actual default, predict default: 0 Actual non-default, predict non-default: 573,426 Actual non-default, predict default: 0 The last case is what you see in your model results. In this case I'm emphasizing the threshold D for a classifier. A simple in change in D may improve certain characteristics of your forecast. Note, that in all three cases the predicted PD remained the same, only the threshold D has changed. It is also possible that your logit regression itself is crappy, of course. So, in this case you have at least two variables: the logit spec and the threshold. Both impact your forecast power.
Logistic regression is predicting all 1, and no 0 When you classify using logit, this is what happens. The logit predicts the probability of default (PD) of a loan, which is a number between 0 and 1. Next, you set a threshold D, such that you mark a
27,331
Logistic regression is predicting all 1, and no 0
Well, without more information its hard to say, but by the definition of logistic regression you are saturating based on the fitted data. So in the equation the e^-t term is going to 0. So the first place to look would be to see what the actual coefficients are. This could also be due to poorly scaled variables. There might be an issue where one of the columns is huge in numerical value compared to others that is causing it mess up.
Logistic regression is predicting all 1, and no 0
Well, without more information its hard to say, but by the definition of logistic regression you are saturating based on the fitted data. So in the equation the e^-t term is going to 0. So the first p
Logistic regression is predicting all 1, and no 0 Well, without more information its hard to say, but by the definition of logistic regression you are saturating based on the fitted data. So in the equation the e^-t term is going to 0. So the first place to look would be to see what the actual coefficients are. This could also be due to poorly scaled variables. There might be an issue where one of the columns is huge in numerical value compared to others that is causing it mess up.
Logistic regression is predicting all 1, and no 0 Well, without more information its hard to say, but by the definition of logistic regression you are saturating based on the fitted data. So in the equation the e^-t term is going to 0. So the first p
27,332
Logistic regression is predicting all 1, and no 0
You may use SMOTE to balance the unbalanced dataset. A good paper for reference is: Lifeng Zhou, Hong Wang, Loan Default Prediction on Large Imbalanced Data Using Random Forests, TELKOMNIKA Indonesian Journal of Electrical Engineering, Vol.10, No.6, October 2012, pp. 1519~1525, link.
Logistic regression is predicting all 1, and no 0
You may use SMOTE to balance the unbalanced dataset. A good paper for reference is: Lifeng Zhou, Hong Wang, Loan Default Prediction on Large Imbalanced Data Using Random Forests, TELKOMNIKA Indonesian
Logistic regression is predicting all 1, and no 0 You may use SMOTE to balance the unbalanced dataset. A good paper for reference is: Lifeng Zhou, Hong Wang, Loan Default Prediction on Large Imbalanced Data Using Random Forests, TELKOMNIKA Indonesian Journal of Electrical Engineering, Vol.10, No.6, October 2012, pp. 1519~1525, link.
Logistic regression is predicting all 1, and no 0 You may use SMOTE to balance the unbalanced dataset. A good paper for reference is: Lifeng Zhou, Hong Wang, Loan Default Prediction on Large Imbalanced Data Using Random Forests, TELKOMNIKA Indonesian
27,333
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
Possibility one: The drug has a very small effect. Perhaps it cures .0001% of people taking it. The test you outlined only implies there is not enough evidence for the dramatic alternative you have proposed. Possibility two: The drug has a very strong negative effect. (credit to @ssdecontrol) Perhaps the drug has no effect and all of those patients would have gotten better on their own, but due to the drug none of the patients recovered. Without any prior knowledge, the data would be consistent with these possibilities as well as with the possibility that the null is true. So, failing to reject the null does not imply that the null is any more true than these other possibilities.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
Possibility one: The drug has a very small effect. Perhaps it cures .0001% of people taking it. The test you outlined only implies there is not enough evidence for the dramatic alternative you have pr
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? Possibility one: The drug has a very small effect. Perhaps it cures .0001% of people taking it. The test you outlined only implies there is not enough evidence for the dramatic alternative you have proposed. Possibility two: The drug has a very strong negative effect. (credit to @ssdecontrol) Perhaps the drug has no effect and all of those patients would have gotten better on their own, but due to the drug none of the patients recovered. Without any prior knowledge, the data would be consistent with these possibilities as well as with the possibility that the null is true. So, failing to reject the null does not imply that the null is any more true than these other possibilities.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis Possibility one: The drug has a very small effect. Perhaps it cures .0001% of people taking it. The test you outlined only implies there is not enough evidence for the dramatic alternative you have pr
27,334
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
There are some good answers here, but what I think is the key issue is not explicitly stated anywhere. In short, your formulation of the null and alternative hypotheses is invalid. The null and alternative hypotheses must be mutually exclusive (that is, they cannot both be true). Your formulation meets that criterion. However, they must also be collectively exhaustive (that is, one of them has to be true). Your formulation does not meet this criterion. You cannot have a null hypothesis that the drug has a $0\%$ chance of curing diabetes and an alternative hypothesis that the drug has a $100\%$ chance of curing diabetes. Imagine that the true probability the drug will cure diabetes is $50\%$, then both your null and your alternative hypotheses are false. That is your problem. The prototypical null hypothesis is a point value (e.g., $0$ on the real number line, or most often $50\%$ when referring to probabilities, but those are just conventions). In addition, if you are working with a bounded parameter space (as you are here—probabilities must range within $[0,\ 1]$), it is generally problematic to try to test values that are at the limits (i.e., $0$ or $1$). Having chosen a point value as your null (the value you want to reject), you can get evidence against it, but cannot get evidence for it from your data (cf. @John's insightful answer). To understand this further, it may help you to read my answer here: Why do statisticians say a non-significant result means “you can't reject the null” as opposed to accepting the null hypothesis? To apply those ideas to your situation more concretely, even if your null were $0\%$ (and hence your alternative hypothesis was $\pi\ne 0$), and you had tried the drug on $100,\!000$ patients without a single one being cured, you could not accept your null hypothesis: The data would still be consistent with the possibility that the probability was $0.00003$ (see: How to tell the probability of failure if there were no failures?). On the other hand, you don't have to have a point null. One-tailed (i.e., $< \theta_0$) null hypotheses are not points, for instance. They are sets of infinite points. Likewise, you could also have a range / interval hypothesis (e.g., that the parameter is within $[a,\ b]$). In that case, you can accept your null on the basis of the evidence—that is what equivalence testing is all about. (You can still be making a type I error, of course.)
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
There are some good answers here, but what I think is the key issue is not explicitly stated anywhere. In short, your formulation of the null and alternative hypotheses is invalid. The null and alte
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? There are some good answers here, but what I think is the key issue is not explicitly stated anywhere. In short, your formulation of the null and alternative hypotheses is invalid. The null and alternative hypotheses must be mutually exclusive (that is, they cannot both be true). Your formulation meets that criterion. However, they must also be collectively exhaustive (that is, one of them has to be true). Your formulation does not meet this criterion. You cannot have a null hypothesis that the drug has a $0\%$ chance of curing diabetes and an alternative hypothesis that the drug has a $100\%$ chance of curing diabetes. Imagine that the true probability the drug will cure diabetes is $50\%$, then both your null and your alternative hypotheses are false. That is your problem. The prototypical null hypothesis is a point value (e.g., $0$ on the real number line, or most often $50\%$ when referring to probabilities, but those are just conventions). In addition, if you are working with a bounded parameter space (as you are here—probabilities must range within $[0,\ 1]$), it is generally problematic to try to test values that are at the limits (i.e., $0$ or $1$). Having chosen a point value as your null (the value you want to reject), you can get evidence against it, but cannot get evidence for it from your data (cf. @John's insightful answer). To understand this further, it may help you to read my answer here: Why do statisticians say a non-significant result means “you can't reject the null” as opposed to accepting the null hypothesis? To apply those ideas to your situation more concretely, even if your null were $0\%$ (and hence your alternative hypothesis was $\pi\ne 0$), and you had tried the drug on $100,\!000$ patients without a single one being cured, you could not accept your null hypothesis: The data would still be consistent with the possibility that the probability was $0.00003$ (see: How to tell the probability of failure if there were no failures?). On the other hand, you don't have to have a point null. One-tailed (i.e., $< \theta_0$) null hypotheses are not points, for instance. They are sets of infinite points. Likewise, you could also have a range / interval hypothesis (e.g., that the parameter is within $[a,\ b]$). In that case, you can accept your null on the basis of the evidence—that is what equivalence testing is all about. (You can still be making a type I error, of course.)
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis There are some good answers here, but what I think is the key issue is not explicitly stated anywhere. In short, your formulation of the null and alternative hypotheses is invalid. The null and alte
27,335
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
As the other users have commented, the issue with accepting the null hypothesis is that we don't have enough evidence (nor will we ever) to conclude that the effect is exactly 0. Mathematically, hypothesis testing is generally not capable of answering such questions. However, that does not mean that the intent of your question is not a valid one! In fact, this is typically the intent in clinical trials for drug generics: the goal is not to show that you've produced a more effective drug, but rather that your drug is essentially about as effective as the name brand (and you can produce it at a much lower cost). Equivalency is typically thought of as the null hypothesis. To address this question using hypothesis testing, the question is reformed in such as a way that it can be answered. The reformatted question looks something like this: $H_o: \beta_g \leq \beta_{nb}\times 0.75$ $H_a: \beta_g > \beta_{nb} \times 0.75$ where $\beta_g$ is the effect of generic and $\beta_{nb}$ is the effect of the name brand drug. So now if we reject the null hypothesis, we can conclude the generic is at least 75% as effective as the namebrand. Clearly, this is not the same as saying exactly equivalent, but it gets at the question you're interested in (and in a way that I believe is a mathematically more reasonable question). We can approach your question in a similar manner. Rather than try to say "do we have enough evidence to conclude 0 effect?", we can ask "given our evidence, what is the maximum effect for which our results were not too unusual?". With $n = 1000$ and 0 successes, can claim we have enough evidence to conclude that the probability of success is less than 0.3% (based on Fisher's exact test, $\alpha = 0.05$). From this result, surely you can still conclude that this is not a drug you will have faith in.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
As the other users have commented, the issue with accepting the null hypothesis is that we don't have enough evidence (nor will we ever) to conclude that the effect is exactly 0. Mathematically, hypot
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? As the other users have commented, the issue with accepting the null hypothesis is that we don't have enough evidence (nor will we ever) to conclude that the effect is exactly 0. Mathematically, hypothesis testing is generally not capable of answering such questions. However, that does not mean that the intent of your question is not a valid one! In fact, this is typically the intent in clinical trials for drug generics: the goal is not to show that you've produced a more effective drug, but rather that your drug is essentially about as effective as the name brand (and you can produce it at a much lower cost). Equivalency is typically thought of as the null hypothesis. To address this question using hypothesis testing, the question is reformed in such as a way that it can be answered. The reformatted question looks something like this: $H_o: \beta_g \leq \beta_{nb}\times 0.75$ $H_a: \beta_g > \beta_{nb} \times 0.75$ where $\beta_g$ is the effect of generic and $\beta_{nb}$ is the effect of the name brand drug. So now if we reject the null hypothesis, we can conclude the generic is at least 75% as effective as the namebrand. Clearly, this is not the same as saying exactly equivalent, but it gets at the question you're interested in (and in a way that I believe is a mathematically more reasonable question). We can approach your question in a similar manner. Rather than try to say "do we have enough evidence to conclude 0 effect?", we can ask "given our evidence, what is the maximum effect for which our results were not too unusual?". With $n = 1000$ and 0 successes, can claim we have enough evidence to conclude that the probability of success is less than 0.3% (based on Fisher's exact test, $\alpha = 0.05$). From this result, surely you can still conclude that this is not a drug you will have faith in.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis As the other users have commented, the issue with accepting the null hypothesis is that we don't have enough evidence (nor will we ever) to conclude that the effect is exactly 0. Mathematically, hypot
27,336
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
Suppose that the drug works, but only on .00001% of the population. The drug works, period. What are the odds of detecting, statistically, that it works it a sample of 10000 people? 100,000 people? 1,000,000 people?
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
Suppose that the drug works, but only on .00001% of the population. The drug works, period. What are the odds of detecting, statistically, that it works it a sample of 10000 people? 100,000 people? 1,
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? Suppose that the drug works, but only on .00001% of the population. The drug works, period. What are the odds of detecting, statistically, that it works it a sample of 10000 people? 100,000 people? 1,000,000 people?
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis Suppose that the drug works, but only on .00001% of the population. The drug works, period. What are the odds of detecting, statistically, that it works it a sample of 10000 people? 100,000 people? 1,
27,337
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
It is incorrect to say that you cannot ever accept the null hypothesis. You're taking the textbook information out of context. What you can't do is use a null hypothesis test to accept it. The test is for rejecting the hypothesis. Note that your own argument for accepting has little to do with a test outcome. It's about the data. It would be rather inane to run a test at all in your example. You can use your data to argue that you accept the null hypothesis. There's nothing wrong with that. You just can't use the results of the test to do so. The reason that you can't use a hypothesis test all by itself is because it's not designed to do that. If you're not understanding that from the textbooks it's understandable. It's actually an interesting paradox that the p-value only actually means something if the null is true but can't be used to demonstrate the null is true. To make it easier perhaps just consider power sensitivity. You could always just collect far too few samples and fail to reject the null. Since you can do that it's clear the test alone isn't a valid reason to accept the null. But again, that doesn't mean you can never say the null is true. It only means the test is no foundation for arguing the null is true. NOTE: There is an Occam's razor argument that you should accept the null when you don't reject; but the test isn't telling you to accept the null. What you're doing is accepting the null as the default and if you don't reject with the test then you're maintain the default state. So even in this case the null is not accepted because of the test.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
It is incorrect to say that you cannot ever accept the null hypothesis. You're taking the textbook information out of context. What you can't do is use a null hypothesis test to accept it. The test is
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? It is incorrect to say that you cannot ever accept the null hypothesis. You're taking the textbook information out of context. What you can't do is use a null hypothesis test to accept it. The test is for rejecting the hypothesis. Note that your own argument for accepting has little to do with a test outcome. It's about the data. It would be rather inane to run a test at all in your example. You can use your data to argue that you accept the null hypothesis. There's nothing wrong with that. You just can't use the results of the test to do so. The reason that you can't use a hypothesis test all by itself is because it's not designed to do that. If you're not understanding that from the textbooks it's understandable. It's actually an interesting paradox that the p-value only actually means something if the null is true but can't be used to demonstrate the null is true. To make it easier perhaps just consider power sensitivity. You could always just collect far too few samples and fail to reject the null. Since you can do that it's clear the test alone isn't a valid reason to accept the null. But again, that doesn't mean you can never say the null is true. It only means the test is no foundation for arguing the null is true. NOTE: There is an Occam's razor argument that you should accept the null when you don't reject; but the test isn't telling you to accept the null. What you're doing is accepting the null as the default and if you don't reject with the test then you're maintain the default state. So even in this case the null is not accepted because of the test.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis It is incorrect to say that you cannot ever accept the null hypothesis. You're taking the textbook information out of context. What you can't do is use a null hypothesis test to accept it. The test is
27,338
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
Looking through your comments, I think that you are very interested in this question: why can we accumulate enough evidence to reject the null, but not the alternative, i.e. what makes hypothesis testing a ones-sided street? The very important thing to think about is what values constitutes the null hypothesis? In your example, it is only a single value, $i.e.$, $p = 0$. The alternative, conversely, is $p > 0$. We accept either hypothesis if all "reasonable values" (i.e. values inside our confidence interval) fall completely into the range given by that hypothesis. So if all our reasonable values are greater than 0, we would accept the alternative. On the other hand, the null hypothesis is only a single point, 0! So to accept the null, we would have to be have confidence interval of length 0. Since (generally speaking) the length confidence interval approaches 0 as $n \rightarrow \infty$, but doesn't achieve length 0 for finite $n$, we would need to collect an infinite amount of data to conclude that we have no margin of error in our estimate. But note that if we define the null hypothesis to be more than just a single point, i.e. a one sided hypothesis test such as $H_o: p \leq 0.5$ $H_a: p > 0.5$ we actually can accept the null hypothesis. Suppose our confidence interval were to be (0.35, 0.45). All these values less than or equal to 0.5, which is in the region of the null hypothesis. So in that case, we could accept the null. Small, technical, abuse of statistics note: if one is really willing to abuse asymptotic theory, one actually could (but shouldn't...) accept the null in your example: the asymptotic standard error is $\sqrt{(\hat p (1 - \hat p) /n)} = 0$. So your asymptotic confidence interval will be (0,0), all of which belongs to the null hypothesis. But this just abusing asymptotic results; note that you get the same conclusion even if $n$ = 1.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
Looking through your comments, I think that you are very interested in this question: why can we accumulate enough evidence to reject the null, but not the alternative, i.e. what makes hypothesis test
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? Looking through your comments, I think that you are very interested in this question: why can we accumulate enough evidence to reject the null, but not the alternative, i.e. what makes hypothesis testing a ones-sided street? The very important thing to think about is what values constitutes the null hypothesis? In your example, it is only a single value, $i.e.$, $p = 0$. The alternative, conversely, is $p > 0$. We accept either hypothesis if all "reasonable values" (i.e. values inside our confidence interval) fall completely into the range given by that hypothesis. So if all our reasonable values are greater than 0, we would accept the alternative. On the other hand, the null hypothesis is only a single point, 0! So to accept the null, we would have to be have confidence interval of length 0. Since (generally speaking) the length confidence interval approaches 0 as $n \rightarrow \infty$, but doesn't achieve length 0 for finite $n$, we would need to collect an infinite amount of data to conclude that we have no margin of error in our estimate. But note that if we define the null hypothesis to be more than just a single point, i.e. a one sided hypothesis test such as $H_o: p \leq 0.5$ $H_a: p > 0.5$ we actually can accept the null hypothesis. Suppose our confidence interval were to be (0.35, 0.45). All these values less than or equal to 0.5, which is in the region of the null hypothesis. So in that case, we could accept the null. Small, technical, abuse of statistics note: if one is really willing to abuse asymptotic theory, one actually could (but shouldn't...) accept the null in your example: the asymptotic standard error is $\sqrt{(\hat p (1 - \hat p) /n)} = 0$. So your asymptotic confidence interval will be (0,0), all of which belongs to the null hypothesis. But this just abusing asymptotic results; note that you get the same conclusion even if $n$ = 1.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis Looking through your comments, I think that you are very interested in this question: why can we accumulate enough evidence to reject the null, but not the alternative, i.e. what makes hypothesis test
27,339
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis?
I know you are dealing with null hypothesis, but the real problem is the example given or as stated the Simple Example. 1,000 people are given a drug and it doesn't work. What other maladies did these people have, what were their ages and stages of desease. To declare a null hypothesis more information; probably detailed ; must be given to make this work in a scientific setting.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis
I know you are dealing with null hypothesis, but the real problem is the example given or as stated the Simple Example. 1,000 people are given a drug and it doesn't work. What other maladies did these
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis? I know you are dealing with null hypothesis, but the real problem is the example given or as stated the Simple Example. 1,000 people are given a drug and it doesn't work. What other maladies did these people have, what were their ages and stages of desease. To declare a null hypothesis more information; probably detailed ; must be given to make this work in a scientific setting.
If all 1000 test patients are not cured by the drug, can't we say that we accept the null hypothesis I know you are dealing with null hypothesis, but the real problem is the example given or as stated the Simple Example. 1,000 people are given a drug and it doesn't work. What other maladies did these
27,340
Does k-NN with k=1 always implies overfitting?
The short answer to your title question is "No". Consider an example with a binary target variable which is perfectly separated by some value of the single explanatory variable to a large degree: Clearly, 1-NN classification will work very well here and won't overfit. (The fact that there are other methods which will work equally well and may be simpler is irrelevant to the central point.) TF-IDF values are outside my areas of expertise, but in general, writing loosely, the greater the separation between values of the target value in the space spanned by the explanatory values, the more effective 1-NN classification will be, regardless of the application area.
Does k-NN with k=1 always implies overfitting?
The short answer to your title question is "No". Consider an example with a binary target variable which is perfectly separated by some value of the single explanatory variable to a large degree: Cl
Does k-NN with k=1 always implies overfitting? The short answer to your title question is "No". Consider an example with a binary target variable which is perfectly separated by some value of the single explanatory variable to a large degree: Clearly, 1-NN classification will work very well here and won't overfit. (The fact that there are other methods which will work equally well and may be simpler is irrelevant to the central point.) TF-IDF values are outside my areas of expertise, but in general, writing loosely, the greater the separation between values of the target value in the space spanned by the explanatory values, the more effective 1-NN classification will be, regardless of the application area.
Does k-NN with k=1 always implies overfitting? The short answer to your title question is "No". Consider an example with a binary target variable which is perfectly separated by some value of the single explanatory variable to a large degree: Cl
27,341
Does k-NN with k=1 always implies overfitting?
The nice answer of @jbowman is absolutely true, but I miss one point though. It would be more accurate to say that kNN with k=1 in general implies over-fitting, or in most cases leads to over-fitting. To see why let me refer to this other answer where it is explained WHY kNN gives you an estimate of the conditional probability. When k=1 you estimate your probability based on a single sample: your closest neighbor. This is very sensitive to all sort of distortions like noise, outliers, mislabelling of data, and so on. By using a higher value for k, you tend to be more robust against those distortions.
Does k-NN with k=1 always implies overfitting?
The nice answer of @jbowman is absolutely true, but I miss one point though. It would be more accurate to say that kNN with k=1 in general implies over-fitting, or in most cases leads to over-fitting.
Does k-NN with k=1 always implies overfitting? The nice answer of @jbowman is absolutely true, but I miss one point though. It would be more accurate to say that kNN with k=1 in general implies over-fitting, or in most cases leads to over-fitting. To see why let me refer to this other answer where it is explained WHY kNN gives you an estimate of the conditional probability. When k=1 you estimate your probability based on a single sample: your closest neighbor. This is very sensitive to all sort of distortions like noise, outliers, mislabelling of data, and so on. By using a higher value for k, you tend to be more robust against those distortions.
Does k-NN with k=1 always implies overfitting? The nice answer of @jbowman is absolutely true, but I miss one point though. It would be more accurate to say that kNN with k=1 in general implies over-fitting, or in most cases leads to over-fitting.
27,342
Does k-NN with k=1 always implies overfitting?
At the risk of stating something obvious to many readers, the one thing you need to be particularly careful about is estimating the classification accuracy of a 1-NN classifier. For any estimation of classifier accuracy, you need to split the data used to train the classifier (training set) and that used to measure accuracy for the classifier (test set). This is generally done using resampling techniques like cross-validation, bootstrap, etc. If you fail to do so, you will overestimate accuracy. 1-NN is the most extreme example of the problem: If you build a 1-NN classifier and test it on same data set you will get 100% accuracy since (barring ties) the "nearest neighbor" will be the point itself. Even if you split training and test, this could be an issue if the data you are using are not truly independent (say texts from the same author that end up in both training and test sets) so that the nearest neighbor is closer than it would be if you were sampling properly.
Does k-NN with k=1 always implies overfitting?
At the risk of stating something obvious to many readers, the one thing you need to be particularly careful about is estimating the classification accuracy of a 1-NN classifier. For any estimation of
Does k-NN with k=1 always implies overfitting? At the risk of stating something obvious to many readers, the one thing you need to be particularly careful about is estimating the classification accuracy of a 1-NN classifier. For any estimation of classifier accuracy, you need to split the data used to train the classifier (training set) and that used to measure accuracy for the classifier (test set). This is generally done using resampling techniques like cross-validation, bootstrap, etc. If you fail to do so, you will overestimate accuracy. 1-NN is the most extreme example of the problem: If you build a 1-NN classifier and test it on same data set you will get 100% accuracy since (barring ties) the "nearest neighbor" will be the point itself. Even if you split training and test, this could be an issue if the data you are using are not truly independent (say texts from the same author that end up in both training and test sets) so that the nearest neighbor is closer than it would be if you were sampling properly.
Does k-NN with k=1 always implies overfitting? At the risk of stating something obvious to many readers, the one thing you need to be particularly careful about is estimating the classification accuracy of a 1-NN classifier. For any estimation of
27,343
History: the role of statistics in astronomy
The main source is Stephen M. Stigler, The History of Statistics, Part One, "The Development of Mathematical Statistics in Astronomy and Geodesy before 1827". Another useful source is John Aldrich, Figures from the History of Probability and Statistics. You could also look at Searle, Casella and McCulloch, Variance Components, chap. 2: p. 23: The method of least squares was independently discovered by Legendre and Gauss. The story is told by R.L. Plackett, "Studies in the History of Probability and Statistics. XXIX: The Discovery of the Method of Least Squares", Biometrika, 59, 239-251. p. 24: According to R.D. Anderson, "astronomers understood the concept of degrees of freedom (but without using the term) as early as the year 1852". He refers to B. J. Peirce, "Criterion for the rejection of doubtful observations", The Astronomical Journal, 2, 161-163 (see here), who specified "the sum of squares of all errors' as being $(N-m)\varepsilon^2$, where $N$ is the total number of observations, $m$ is the number of unknown quantities contained in the observations and $\varepsilon^2$ is the mean error (sample variance)." pages 23-24: The first formulation of a random effects model is that of George Biddell Airy, in a monograph published in 1861. See also Marc Nerlove, "The History of Panel Data Econometrics, 1861-1997", in Essays in Panel Data Econometrics: "what Airy calls a Constant error, we would call a random day effect". It is the error that remains even when every known instrumental correction has been applied. pages 24-25: The second use of a random effects model appears in W. Chauvenet, A Manual of Spherical and Practical Astronomy, 2: Theory and Use of Astronomical Instruments, 1863. He derived the variance of $\bar{y}_{..}=\sum_{i=1}^a\sum_{j=1}^n y_{ij}/an$ as $$\text{var}(\bar{y}_{..})=\frac{\sigma^2_a+\sigma^2_e/n}{a}$$
History: the role of statistics in astronomy
The main source is Stephen M. Stigler, The History of Statistics, Part One, "The Development of Mathematical Statistics in Astronomy and Geodesy before 1827". Another useful source is John Aldrich, Fi
History: the role of statistics in astronomy The main source is Stephen M. Stigler, The History of Statistics, Part One, "The Development of Mathematical Statistics in Astronomy and Geodesy before 1827". Another useful source is John Aldrich, Figures from the History of Probability and Statistics. You could also look at Searle, Casella and McCulloch, Variance Components, chap. 2: p. 23: The method of least squares was independently discovered by Legendre and Gauss. The story is told by R.L. Plackett, "Studies in the History of Probability and Statistics. XXIX: The Discovery of the Method of Least Squares", Biometrika, 59, 239-251. p. 24: According to R.D. Anderson, "astronomers understood the concept of degrees of freedom (but without using the term) as early as the year 1852". He refers to B. J. Peirce, "Criterion for the rejection of doubtful observations", The Astronomical Journal, 2, 161-163 (see here), who specified "the sum of squares of all errors' as being $(N-m)\varepsilon^2$, where $N$ is the total number of observations, $m$ is the number of unknown quantities contained in the observations and $\varepsilon^2$ is the mean error (sample variance)." pages 23-24: The first formulation of a random effects model is that of George Biddell Airy, in a monograph published in 1861. See also Marc Nerlove, "The History of Panel Data Econometrics, 1861-1997", in Essays in Panel Data Econometrics: "what Airy calls a Constant error, we would call a random day effect". It is the error that remains even when every known instrumental correction has been applied. pages 24-25: The second use of a random effects model appears in W. Chauvenet, A Manual of Spherical and Practical Astronomy, 2: Theory and Use of Astronomical Instruments, 1863. He derived the variance of $\bar{y}_{..}=\sum_{i=1}^a\sum_{j=1}^n y_{ij}/an$ as $$\text{var}(\bar{y}_{..})=\frac{\sigma^2_a+\sigma^2_e/n}{a}$$
History: the role of statistics in astronomy The main source is Stephen M. Stigler, The History of Statistics, Part One, "The Development of Mathematical Statistics in Astronomy and Geodesy before 1827". Another useful source is John Aldrich, Fi
27,344
History: the role of statistics in astronomy
Probably the best-known example of a statistical method "developed" from an astronomy problem was Gauss' use of least squares to generate an orbit for Ceres on the basis of Piazzi's observations. Piazzi did not have nearly enough observations for conventional methods of determining orbits when Ceres was lost in the glare of the sun. Gauss took the data, applied least squares and told the astronomers where to point their telescopes to find it again. See Forbes, 1971 "Gauss and the discovery of Ceres", J of the History of Astronomy.
History: the role of statistics in astronomy
Probably the best-known example of a statistical method "developed" from an astronomy problem was Gauss' use of least squares to generate an orbit for Ceres on the basis of Piazzi's observations. Pia
History: the role of statistics in astronomy Probably the best-known example of a statistical method "developed" from an astronomy problem was Gauss' use of least squares to generate an orbit for Ceres on the basis of Piazzi's observations. Piazzi did not have nearly enough observations for conventional methods of determining orbits when Ceres was lost in the glare of the sun. Gauss took the data, applied least squares and told the astronomers where to point their telescopes to find it again. See Forbes, 1971 "Gauss and the discovery of Ceres", J of the History of Astronomy.
History: the role of statistics in astronomy Probably the best-known example of a statistical method "developed" from an astronomy problem was Gauss' use of least squares to generate an orbit for Ceres on the basis of Piazzi's observations. Pia
27,345
Why set weights to 1 in confirmatory factor analysis?
Because it then allows you to use the relationship between the latent variable and the observed variable to determine the variance of the latent variable. For example, consider the regression of Y on X. If I am allowed to change the variance of X, say, by multiplying it by a constant, then I can change the regression coefficient arbitrarily. If instead I fix the value of the regression coefficient, then this determines the variance of X. By convention, and to make it easier to compare the coefficients to each other. In that case, the latent variable simply becomes reversed. For example, suppose our latent variable is math ability, our observed variable is the number of errors on a test, and we fix the regression coefficient to 1. Then our latent variable will become "difficulty with math" instead of math ability, and the coefficients for any other observed variables will change accordingly. If the observed variable and the latent variable are both standardized (i.e., standard deviation equal to 1), then the regression coefficient is equal to the covariance. It is fixing spatial -> visperc to 1 that permits estimation of the variance of spatial (see answer to (1) above). Likewise, fixing verbal -> paragrap permits estimation of the variance of verbal. A model with only one of these constraints would not be identifiable. Because the differences between the unstandardized and standardized coefficients depend not only on the variance of verbal, but also on the variances of paragrap, sentence and wordmean. For example, the standardized coefficient for wordmean equals the unstandardized coefficient multiplied by $\frac{SD_{verbal}}{SD_{wordmean}}$, or $2.234 \times \frac{\sqrt{9.682}}{\sqrt{(2.234^2 \times 9.682) + 19.925}} = 0.841$. Finally, note that err_v is analogous to the error term in a regression model, e.g., $$visperc = \beta_0 + \beta_1 spatial + err\_v$$ We fix the coefficient on err_v (i.e., on the error term) to 1 so that we can estimate the error variance (i.e., the variance of err_v).
Why set weights to 1 in confirmatory factor analysis?
Because it then allows you to use the relationship between the latent variable and the observed variable to determine the variance of the latent variable. For example, consider the regression of Y on
Why set weights to 1 in confirmatory factor analysis? Because it then allows you to use the relationship between the latent variable and the observed variable to determine the variance of the latent variable. For example, consider the regression of Y on X. If I am allowed to change the variance of X, say, by multiplying it by a constant, then I can change the regression coefficient arbitrarily. If instead I fix the value of the regression coefficient, then this determines the variance of X. By convention, and to make it easier to compare the coefficients to each other. In that case, the latent variable simply becomes reversed. For example, suppose our latent variable is math ability, our observed variable is the number of errors on a test, and we fix the regression coefficient to 1. Then our latent variable will become "difficulty with math" instead of math ability, and the coefficients for any other observed variables will change accordingly. If the observed variable and the latent variable are both standardized (i.e., standard deviation equal to 1), then the regression coefficient is equal to the covariance. It is fixing spatial -> visperc to 1 that permits estimation of the variance of spatial (see answer to (1) above). Likewise, fixing verbal -> paragrap permits estimation of the variance of verbal. A model with only one of these constraints would not be identifiable. Because the differences between the unstandardized and standardized coefficients depend not only on the variance of verbal, but also on the variances of paragrap, sentence and wordmean. For example, the standardized coefficient for wordmean equals the unstandardized coefficient multiplied by $\frac{SD_{verbal}}{SD_{wordmean}}$, or $2.234 \times \frac{\sqrt{9.682}}{\sqrt{(2.234^2 \times 9.682) + 19.925}} = 0.841$. Finally, note that err_v is analogous to the error term in a regression model, e.g., $$visperc = \beta_0 + \beta_1 spatial + err\_v$$ We fix the coefficient on err_v (i.e., on the error term) to 1 so that we can estimate the error variance (i.e., the variance of err_v).
Why set weights to 1 in confirmatory factor analysis? Because it then allows you to use the relationship between the latent variable and the observed variable to determine the variance of the latent variable. For example, consider the regression of Y on
27,346
Why set weights to 1 in confirmatory factor analysis?
I may be misunderstanding the phrase "indeterminancy of scale", but I believe it is set to one for identifiability. (That is, the number of unknowns in this system of equations should not exceed the number of equations.) Without setting one of the links to one, there are too many unknowns. Is that the same thing as indeterminancy of scale? In most SEM applications, you are working with covariance matrices, not the raw data. There is an alternative algorithm that uses the original data, called PLS (Partial Least Squares), which might shed some additional light on things for you.
Why set weights to 1 in confirmatory factor analysis?
I may be misunderstanding the phrase "indeterminancy of scale", but I believe it is set to one for identifiability. (That is, the number of unknowns in this system of equations should not exceed the n
Why set weights to 1 in confirmatory factor analysis? I may be misunderstanding the phrase "indeterminancy of scale", but I believe it is set to one for identifiability. (That is, the number of unknowns in this system of equations should not exceed the number of equations.) Without setting one of the links to one, there are too many unknowns. Is that the same thing as indeterminancy of scale? In most SEM applications, you are working with covariance matrices, not the raw data. There is an alternative algorithm that uses the original data, called PLS (Partial Least Squares), which might shed some additional light on things for you.
Why set weights to 1 in confirmatory factor analysis? I may be misunderstanding the phrase "indeterminancy of scale", but I believe it is set to one for identifiability. (That is, the number of unknowns in this system of equations should not exceed the n
27,347
Why set weights to 1 in confirmatory factor analysis?
Think about the interpretation as if it were just a simple regression. The coefficient reflects the unit difference in the dependent variable associated with a 1 unit difference in the independent variable. Thus if a 1 unit change in in the IV is associated with a 1 unit change in the DV, then the units are funcationally equivalent. You need a unit for the latent variable because you want to estimate its variance, which is not unitless. The identification problem is related, in that for a simple CFA with 1 latent variable and 3 indicators, the model is not identified unless the constraint is made. You can set it to any number, and the overall nature of the results will be the same (easily checked by looking at model fit, which will be identical). It just easier to interpret the model if you set it to 1. Regardless of how you fix any of the factor loadings, you can get positively and negativey loaded items for the same latent variable. You can test this by multiplying one of your indicators by -1 and estimating your model again. They are functionally the same thing if the regression coefficient is unadjusted (i.e. the dependent variable only has 1 arrow pointing to it). If this is the case, one can be calcuated from the other. Try it! Each latent variable needs a scale, for the reasons already stated. This is a scale issue and exactly the reason for using standarized coefficients. I can make any regression coefficient arbitrarily large by dividing the DV by larger and larger numbers. Thus a 1 unit change in the IV will produce larger and larger changes in the units of the DV. By normalizing, and comparing like for like, we avoid this problem. Fixing the error factor loading to 1 just makes interpretation easier. It makes the respective regression equation in the SEM take the familiar form of Y = BX + e (or Y = BX + 1*e).
Why set weights to 1 in confirmatory factor analysis?
Think about the interpretation as if it were just a simple regression. The coefficient reflects the unit difference in the dependent variable associated with a 1 unit difference in the independent var
Why set weights to 1 in confirmatory factor analysis? Think about the interpretation as if it were just a simple regression. The coefficient reflects the unit difference in the dependent variable associated with a 1 unit difference in the independent variable. Thus if a 1 unit change in in the IV is associated with a 1 unit change in the DV, then the units are funcationally equivalent. You need a unit for the latent variable because you want to estimate its variance, which is not unitless. The identification problem is related, in that for a simple CFA with 1 latent variable and 3 indicators, the model is not identified unless the constraint is made. You can set it to any number, and the overall nature of the results will be the same (easily checked by looking at model fit, which will be identical). It just easier to interpret the model if you set it to 1. Regardless of how you fix any of the factor loadings, you can get positively and negativey loaded items for the same latent variable. You can test this by multiplying one of your indicators by -1 and estimating your model again. They are functionally the same thing if the regression coefficient is unadjusted (i.e. the dependent variable only has 1 arrow pointing to it). If this is the case, one can be calcuated from the other. Try it! Each latent variable needs a scale, for the reasons already stated. This is a scale issue and exactly the reason for using standarized coefficients. I can make any regression coefficient arbitrarily large by dividing the DV by larger and larger numbers. Thus a 1 unit change in the IV will produce larger and larger changes in the units of the DV. By normalizing, and comparing like for like, we avoid this problem. Fixing the error factor loading to 1 just makes interpretation easier. It makes the respective regression equation in the SEM take the familiar form of Y = BX + e (or Y = BX + 1*e).
Why set weights to 1 in confirmatory factor analysis? Think about the interpretation as if it were just a simple regression. The coefficient reflects the unit difference in the dependent variable associated with a 1 unit difference in the independent var
27,348
Why set weights to 1 in confirmatory factor analysis?
Stata has a very nice documentation on SEM here, look up "Identification 2" section, it has answers to all your questions. the absence of scale comes because your latent variable is not observable. you may come up with numeric answers in the survey of happiness, but happiness itself is not directly measured. now you have to somehow link the answers such as 1 to 10 to happiness. so you designate one of the questions as an anchor and set its loading to 1. it doesn't have to be 1, it could be any value, but 1 is convenient. both spatial and verbal are not observable, so you need to set the scale to both of them, thus you have anchors for each.
Why set weights to 1 in confirmatory factor analysis?
Stata has a very nice documentation on SEM here, look up "Identification 2" section, it has answers to all your questions. the absence of scale comes because your latent variable is not observable. yo
Why set weights to 1 in confirmatory factor analysis? Stata has a very nice documentation on SEM here, look up "Identification 2" section, it has answers to all your questions. the absence of scale comes because your latent variable is not observable. you may come up with numeric answers in the survey of happiness, but happiness itself is not directly measured. now you have to somehow link the answers such as 1 to 10 to happiness. so you designate one of the questions as an anchor and set its loading to 1. it doesn't have to be 1, it could be any value, but 1 is convenient. both spatial and verbal are not observable, so you need to set the scale to both of them, thus you have anchors for each.
Why set weights to 1 in confirmatory factor analysis? Stata has a very nice documentation on SEM here, look up "Identification 2" section, it has answers to all your questions. the absence of scale comes because your latent variable is not observable. yo
27,349
Using a regression model to make prediction: When to stop?
The term you're searching for is 'extrapolation'. The problem is that no matter how much data you have, and how many intermediate levels you have between your endpoints on disk size (i.e., between 5 and 30), it is always possible that there is some degree of curvature in the true underlying function, that you simply don't have the power to detect. As a result, when you extrapolate far out from the endpoint, what was a small degree of curvature becomes magnified, in that the true function moves further and further away from your fit line. Another possibility is that the true function really is perfectly straight within the range examined, but that there is perhaps a change-point at some distance from the end point in your study. These sorts of things are impossible to rule out; the question is, how likely are they and how inaccurate would your prediction be if they turn out to be real? I don't know how to provide an analytical answer to those questions. My hunch is that 500 is an awfully long way off when the range under study was [5, 30], but there is no real reason to think my hunches are more worthwhile than yours. Standard formulas for computing prediction intervals will show you an expanding interval as you move away from $\bar{x}$, seeing what that interval looks like might be helpful. Nonetheless, you need to bear in mind that you are making a theoretical assumption that the line really is perfectly straight, and remains such all the way out to the $x$-value you will use for the prediction. The legitimacy of that prediction is contingent on both the data & fit, and that assumption.
Using a regression model to make prediction: When to stop?
The term you're searching for is 'extrapolation'. The problem is that no matter how much data you have, and how many intermediate levels you have between your endpoints on disk size (i.e., between 5
Using a regression model to make prediction: When to stop? The term you're searching for is 'extrapolation'. The problem is that no matter how much data you have, and how many intermediate levels you have between your endpoints on disk size (i.e., between 5 and 30), it is always possible that there is some degree of curvature in the true underlying function, that you simply don't have the power to detect. As a result, when you extrapolate far out from the endpoint, what was a small degree of curvature becomes magnified, in that the true function moves further and further away from your fit line. Another possibility is that the true function really is perfectly straight within the range examined, but that there is perhaps a change-point at some distance from the end point in your study. These sorts of things are impossible to rule out; the question is, how likely are they and how inaccurate would your prediction be if they turn out to be real? I don't know how to provide an analytical answer to those questions. My hunch is that 500 is an awfully long way off when the range under study was [5, 30], but there is no real reason to think my hunches are more worthwhile than yours. Standard formulas for computing prediction intervals will show you an expanding interval as you move away from $\bar{x}$, seeing what that interval looks like might be helpful. Nonetheless, you need to bear in mind that you are making a theoretical assumption that the line really is perfectly straight, and remains such all the way out to the $x$-value you will use for the prediction. The legitimacy of that prediction is contingent on both the data & fit, and that assumption.
Using a regression model to make prediction: When to stop? The term you're searching for is 'extrapolation'. The problem is that no matter how much data you have, and how many intermediate levels you have between your endpoints on disk size (i.e., between 5
27,350
Using a regression model to make prediction: When to stop?
Let me add a few points to @gung's excellent answer: Depending on your field, there may be relevant norms (as in DIN/EN or ISO). This is probably not an issue with predicting hard disk reading speed, but e.g. in analytical chemistry the rule is no extrapolation. Period. If you want to go as far as 500 GB, then go and do some measurements up to including 500 GB. The usual way of setting up a linear model has two important assumptions Obviously, that the function is linear. In practice it is usually not a very good assumption that linearity extends to infinity. E.g. can you expect still to find linearity if you read larger amounts than the hard disk volume? Usually, also homoskedasticity is assumed. This means that the absolute amount of error/noise does not depend on the dependent ($x$) variable, here: the amount of data to be read. I'm not sure about hard disk readings, but I experience (chemistry/chemometrics) usually something between constant absolute and constant relative noise (or more complicated behaviour due to different sources of noise). Any deviation from the constant absolute amount of noise regime will mean that the prediction intervals for the extrapolation are grossly wrong -- usually they will be far too narrow. Even if these assumptions are met, consider how big the prediction interval actually is for that kind of extrapolation: (I took some real calibration data of a very nice measurement I had and adapted it to your problem). Note that the prediction interval at $x$ = 500 is already twice as large as the total difference in $t$ your calibration data spans! If you don't have such an exceedingly nice linear data set, the prediction interval will just "explode".
Using a regression model to make prediction: When to stop?
Let me add a few points to @gung's excellent answer: Depending on your field, there may be relevant norms (as in DIN/EN or ISO). This is probably not an issue with predicting hard disk reading speed,
Using a regression model to make prediction: When to stop? Let me add a few points to @gung's excellent answer: Depending on your field, there may be relevant norms (as in DIN/EN or ISO). This is probably not an issue with predicting hard disk reading speed, but e.g. in analytical chemistry the rule is no extrapolation. Period. If you want to go as far as 500 GB, then go and do some measurements up to including 500 GB. The usual way of setting up a linear model has two important assumptions Obviously, that the function is linear. In practice it is usually not a very good assumption that linearity extends to infinity. E.g. can you expect still to find linearity if you read larger amounts than the hard disk volume? Usually, also homoskedasticity is assumed. This means that the absolute amount of error/noise does not depend on the dependent ($x$) variable, here: the amount of data to be read. I'm not sure about hard disk readings, but I experience (chemistry/chemometrics) usually something between constant absolute and constant relative noise (or more complicated behaviour due to different sources of noise). Any deviation from the constant absolute amount of noise regime will mean that the prediction intervals for the extrapolation are grossly wrong -- usually they will be far too narrow. Even if these assumptions are met, consider how big the prediction interval actually is for that kind of extrapolation: (I took some real calibration data of a very nice measurement I had and adapted it to your problem). Note that the prediction interval at $x$ = 500 is already twice as large as the total difference in $t$ your calibration data spans! If you don't have such an exceedingly nice linear data set, the prediction interval will just "explode".
Using a regression model to make prediction: When to stop? Let me add a few points to @gung's excellent answer: Depending on your field, there may be relevant norms (as in DIN/EN or ISO). This is probably not an issue with predicting hard disk reading speed,
27,351
First quick glance at a dataset
@Ondrej and @Michelle have provided some good information here. I wonder if I can contribute by addressing some points not mentioned elsewhere. I wouldn't beat yourself up about not being able to glean much from the data in tabular form, tables are generally not a very good way to present information (cf., Gelman et al., Turning Tables into Graphs). On the other hand, asking for a tool that will automatically generate all of the right graphs to help you explore a new data set is almost like asking for a tool that will do your thinking for you. (Don't take that the wrong way, I recognize your question makes clear that you aren't going that far; I just mean that there will never really be such a tool.) A nice discussion that is related to this can be found here. These things having been said, I wanted to talk a little about the kinds of plots that you might want to use to explore your data. The plots listed in the question would be a good start, but we might be able to optimize that a little. To start with, making "a large number of plots" correlating pairs of variables might not be ideal. A scatterplot only displays the marginal relationship between two variables. Important relationships can often be hidden in some combination of multiple variables. So the first way to beef up this approach is to make a scatterplot matrix that displays all pairwise scatterplots simultaneously. Scatterplot matrices can be enhanced in various ways: E.g., they can be combined with univariate kernel density plots of each variable's distribution, different markers / colors can be used to plot different groups, and possible nonlinear relationships can be assessed by overlaying a loess fit. The scatterplot.matrix function in the car package in R can do all of these things nicely (an example can be seen halfway down the page linked above). However, while scatterplot matrices are a good start, they are still only displaying the marginal projections. There are a few ways to try to move beyond this. One is to explore 3-dimensional plots using the rgl package in R. Another approach is to use conditional plots; coplots can help with relationships amongst 3 or 4 variables simultaneously. An especially useful approach is to use a scatterplot matrix interactively (albeit, this will require more effort to learn), e.g. by 'brushing'. Brushing allows you to highlight a point or points in one frame of a matrix and those points will simultaneously be highlighted in all of the other frames. By moving the brush around, you can see how all of the variables change together. UPDATE: Another possibility that I had forgotten to mention is to use a parallel coordinates plot. This has a disadvantage in not making your response variable distinct, but could be useful, for example, in examining inter-correlations amongst your X variables. I also want to commend you for examining your data sorted by date collected. Although data are always gathered over time, people don't always do this. Plotting a line graph is nice, but I would suggest you supplement that with graphs of autocorrelations and partial autocorrelations. In R, the functions for these are acf and pacf respectively. I recognize that all of this doesn't quite answer your question in the sense of giving you a tool that will make all the plots for you automatically, but one implication is that you wouldn't actually have to make as many plots as you fear, e.g., a scatterplot matrix is just one line of code. In addition, in R, it should be possible to write a function / some reusable code for yourself that would partly automate some of this (e.g., I can imagine a function that takes in a list of variables and a date-ordering, sorts them, pops up a new window for each with line, acf, and pacf plots).
First quick glance at a dataset
@Ondrej and @Michelle have provided some good information here. I wonder if I can contribute by addressing some points not mentioned elsewhere. I wouldn't beat yourself up about not being able to gl
First quick glance at a dataset @Ondrej and @Michelle have provided some good information here. I wonder if I can contribute by addressing some points not mentioned elsewhere. I wouldn't beat yourself up about not being able to glean much from the data in tabular form, tables are generally not a very good way to present information (cf., Gelman et al., Turning Tables into Graphs). On the other hand, asking for a tool that will automatically generate all of the right graphs to help you explore a new data set is almost like asking for a tool that will do your thinking for you. (Don't take that the wrong way, I recognize your question makes clear that you aren't going that far; I just mean that there will never really be such a tool.) A nice discussion that is related to this can be found here. These things having been said, I wanted to talk a little about the kinds of plots that you might want to use to explore your data. The plots listed in the question would be a good start, but we might be able to optimize that a little. To start with, making "a large number of plots" correlating pairs of variables might not be ideal. A scatterplot only displays the marginal relationship between two variables. Important relationships can often be hidden in some combination of multiple variables. So the first way to beef up this approach is to make a scatterplot matrix that displays all pairwise scatterplots simultaneously. Scatterplot matrices can be enhanced in various ways: E.g., they can be combined with univariate kernel density plots of each variable's distribution, different markers / colors can be used to plot different groups, and possible nonlinear relationships can be assessed by overlaying a loess fit. The scatterplot.matrix function in the car package in R can do all of these things nicely (an example can be seen halfway down the page linked above). However, while scatterplot matrices are a good start, they are still only displaying the marginal projections. There are a few ways to try to move beyond this. One is to explore 3-dimensional plots using the rgl package in R. Another approach is to use conditional plots; coplots can help with relationships amongst 3 or 4 variables simultaneously. An especially useful approach is to use a scatterplot matrix interactively (albeit, this will require more effort to learn), e.g. by 'brushing'. Brushing allows you to highlight a point or points in one frame of a matrix and those points will simultaneously be highlighted in all of the other frames. By moving the brush around, you can see how all of the variables change together. UPDATE: Another possibility that I had forgotten to mention is to use a parallel coordinates plot. This has a disadvantage in not making your response variable distinct, but could be useful, for example, in examining inter-correlations amongst your X variables. I also want to commend you for examining your data sorted by date collected. Although data are always gathered over time, people don't always do this. Plotting a line graph is nice, but I would suggest you supplement that with graphs of autocorrelations and partial autocorrelations. In R, the functions for these are acf and pacf respectively. I recognize that all of this doesn't quite answer your question in the sense of giving you a tool that will make all the plots for you automatically, but one implication is that you wouldn't actually have to make as many plots as you fear, e.g., a scatterplot matrix is just one line of code. In addition, in R, it should be possible to write a function / some reusable code for yourself that would partly automate some of this (e.g., I can imagine a function that takes in a list of variables and a date-ordering, sorts them, pops up a new window for each with line, acf, and pacf plots).
First quick glance at a dataset @Ondrej and @Michelle have provided some good information here. I wonder if I can contribute by addressing some points not mentioned elsewhere. I wouldn't beat yourself up about not being able to gl
27,352
First quick glance at a dataset
Correlations between each pair of numerical columns can be shown in a correlation matrix. It need not be purely numerical, it can be color coded, to allow for a quick-glance evaluation. Check out corrplot package for R. For further analysis, Rattle is quite a useful GUI tool. If you search Stack Exchange using the keywords "corrplot" or rather "Rattle", you will find several topics where these tools and their alternatives are covered. Like this one. Good luck!
First quick glance at a dataset
Correlations between each pair of numerical columns can be shown in a correlation matrix. It need not be purely numerical, it can be color coded, to allow for a quick-glance evaluation. Check out corr
First quick glance at a dataset Correlations between each pair of numerical columns can be shown in a correlation matrix. It need not be purely numerical, it can be color coded, to allow for a quick-glance evaluation. Check out corrplot package for R. For further analysis, Rattle is quite a useful GUI tool. If you search Stack Exchange using the keywords "corrplot" or rather "Rattle", you will find several topics where these tools and their alternatives are covered. Like this one. Good luck!
First quick glance at a dataset Correlations between each pair of numerical columns can be shown in a correlation matrix. It need not be purely numerical, it can be color coded, to allow for a quick-glance evaluation. Check out corr
27,353
First quick glance at a dataset
@Ondrej has given some good advice, so I will focus on your question around how software treats imported data. With character data, "Category 1" and "Category 2", the software automatically treats these as groups or factors because mathematical operations cannot be conducted on these pieces of data. This means that you will be prevented from entering anything from those categories (alternatively, you'll get an error if you try if you're using syntax or a command line instead of a menu-driven system) into an analysis that requires numbers. For data like your "Number 1" and "Number 2", the software reads these as numeric. If you have any groups/factors that contain purely numeric data, you will need to instruct your software that these are groups/factors. Sometimes dates can be imported badly into statistical software. Once you import your data, you should see that the data type in your statistical software is showing some form of "date" type for "Date". If you see the data type as anything other than date, you have an issue. Even if it is showing as date, check the import of some rows where you have dates like days like the 13th or 25th of the month - depending on how the software is set up, sometimes the American/British date formatting causes screwy data from import, because of the reversal of the day/month.
First quick glance at a dataset
@Ondrej has given some good advice, so I will focus on your question around how software treats imported data. With character data, "Category 1" and "Category 2", the software automatically treats the
First quick glance at a dataset @Ondrej has given some good advice, so I will focus on your question around how software treats imported data. With character data, "Category 1" and "Category 2", the software automatically treats these as groups or factors because mathematical operations cannot be conducted on these pieces of data. This means that you will be prevented from entering anything from those categories (alternatively, you'll get an error if you try if you're using syntax or a command line instead of a menu-driven system) into an analysis that requires numbers. For data like your "Number 1" and "Number 2", the software reads these as numeric. If you have any groups/factors that contain purely numeric data, you will need to instruct your software that these are groups/factors. Sometimes dates can be imported badly into statistical software. Once you import your data, you should see that the data type in your statistical software is showing some form of "date" type for "Date". If you see the data type as anything other than date, you have an issue. Even if it is showing as date, check the import of some rows where you have dates like days like the 13th or 25th of the month - depending on how the software is set up, sometimes the American/British date formatting causes screwy data from import, because of the reversal of the day/month.
First quick glance at a dataset @Ondrej has given some good advice, so I will focus on your question around how software treats imported data. With character data, "Category 1" and "Category 2", the software automatically treats the
27,354
Understanding ridge regression results
You might be better off with the penalized package or the glmnet package; both implement lasso or elastic net so combines properties of the lasso (feature selection) and ridge regression (handling collinear variables). penalized also does ridge. These two packages are far more fully featured than lm.ridge() in the MASS package for such things. Anyway, $\lambda = 0$ implies zero penalty, hence the least squares estimates are optimal in the sense that they had the lowest GCV (generalised cross validation) score. However, you may not have allowed sufficiently large a penalty; in other words, the least squares estimates were optimal of the small set of of $\lambda$ values you looked at. Plot the ridge path (values of the coefficients as a function of $\lambda$ and see if the traces have stabilised or not. If not, increase the range of $\lambda$ values evaluated.
Understanding ridge regression results
You might be better off with the penalized package or the glmnet package; both implement lasso or elastic net so combines properties of the lasso (feature selection) and ridge regression (handling col
Understanding ridge regression results You might be better off with the penalized package or the glmnet package; both implement lasso or elastic net so combines properties of the lasso (feature selection) and ridge regression (handling collinear variables). penalized also does ridge. These two packages are far more fully featured than lm.ridge() in the MASS package for such things. Anyway, $\lambda = 0$ implies zero penalty, hence the least squares estimates are optimal in the sense that they had the lowest GCV (generalised cross validation) score. However, you may not have allowed sufficiently large a penalty; in other words, the least squares estimates were optimal of the small set of of $\lambda$ values you looked at. Plot the ridge path (values of the coefficients as a function of $\lambda$ and see if the traces have stabilised or not. If not, increase the range of $\lambda$ values evaluated.
Understanding ridge regression results You might be better off with the penalized package or the glmnet package; both implement lasso or elastic net so combines properties of the lasso (feature selection) and ridge regression (handling col
27,355
Understanding ridge regression results
The reason you are getting a 0 GCV is because you used: myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb , temp, lamda = seq(0,0.1,0.001)) instead of myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb , temp, lambda = seq(0,0.1,0.001))
Understanding ridge regression results
The reason you are getting a 0 GCV is because you used: myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb , temp, lamda = seq(0,0.1,0.001)) instead of myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb
Understanding ridge regression results The reason you are getting a 0 GCV is because you used: myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb , temp, lamda = seq(0,0.1,0.001)) instead of myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb , temp, lambda = seq(0,0.1,0.001))
Understanding ridge regression results The reason you are getting a 0 GCV is because you used: myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb , temp, lamda = seq(0,0.1,0.001)) instead of myridge = lm.ridge(y ~ ma + sa + lka + cb + ltb
27,356
How to calculate the truncated or trimmed mean?
Trimmed mean involves trimming $P$ percent observations from both ends. E.g.: If you are asked to compute a 10% trimmed mean, $P = 10$. Given a bunch of observations, $X_i$: First find $n$ = number of observations. Reorder them as "order statistics" $X_i$ from the smallest to the largest. Find lower case $p = P/100$ = proportion trimmed. Compute $n p$. If $n p$ is an integer use $k = n p$ and trim $k$ observations at both ends. $R$ = remaining observations = $n - 2k$. Trimmed mean = $(1/R) \left( X_{k+1} + X_{k+2} + \ldots + X_{n-k} \right).$ Example: Find 10% trimmed mean of 2, 4, 6, 7, 11, 21, 81, 90, 105, 121 Here, $n = 10, p = 0.10, k = n p = 1$ which is an integer so trim exactly one observation at each end, since $k = 1$. Thus trim off 2 and 121. We are left with $R = n - 2k = 10 - 2 = 8$ observations. 10% trimmed mean= (1/8) * (4 + 6 + 7 + 11 + 21 + 81 + 90 + 105) = 40.625 If $ n p$ has a fractional part present, trimmed mean is a bit more complicated. In the above example, if we wanted 15% trimmed mean, $P = 15, p = 0.15, n = 10, k = n p = 1.5$. This has integer part 1 and fractional part 0.5 is present. $R = n - 2k = 10 - 2 * 1.5 = 10 - 3 = 7$. Thus $R = 7$ observations are retained. Addendum upon @whuber's comment: To remain unbiased (after removing 2 and 121), it seems we must remove half of the 4 and half of the 105 for a trimmed mean of $(4/2 + 6 + 7 + 11 + 21 + 81 + 90 + 105/2)/7 = 38.64$ Source: Class notes on P percent trimmed mean
How to calculate the truncated or trimmed mean?
Trimmed mean involves trimming $P$ percent observations from both ends. E.g.: If you are asked to compute a 10% trimmed mean, $P = 10$. Given a bunch of observations, $X_i$: First find $n$ = number o
How to calculate the truncated or trimmed mean? Trimmed mean involves trimming $P$ percent observations from both ends. E.g.: If you are asked to compute a 10% trimmed mean, $P = 10$. Given a bunch of observations, $X_i$: First find $n$ = number of observations. Reorder them as "order statistics" $X_i$ from the smallest to the largest. Find lower case $p = P/100$ = proportion trimmed. Compute $n p$. If $n p$ is an integer use $k = n p$ and trim $k$ observations at both ends. $R$ = remaining observations = $n - 2k$. Trimmed mean = $(1/R) \left( X_{k+1} + X_{k+2} + \ldots + X_{n-k} \right).$ Example: Find 10% trimmed mean of 2, 4, 6, 7, 11, 21, 81, 90, 105, 121 Here, $n = 10, p = 0.10, k = n p = 1$ which is an integer so trim exactly one observation at each end, since $k = 1$. Thus trim off 2 and 121. We are left with $R = n - 2k = 10 - 2 = 8$ observations. 10% trimmed mean= (1/8) * (4 + 6 + 7 + 11 + 21 + 81 + 90 + 105) = 40.625 If $ n p$ has a fractional part present, trimmed mean is a bit more complicated. In the above example, if we wanted 15% trimmed mean, $P = 15, p = 0.15, n = 10, k = n p = 1.5$. This has integer part 1 and fractional part 0.5 is present. $R = n - 2k = 10 - 2 * 1.5 = 10 - 3 = 7$. Thus $R = 7$ observations are retained. Addendum upon @whuber's comment: To remain unbiased (after removing 2 and 121), it seems we must remove half of the 4 and half of the 105 for a trimmed mean of $(4/2 + 6 + 7 + 11 + 21 + 81 + 90 + 105/2)/7 = 38.64$ Source: Class notes on P percent trimmed mean
How to calculate the truncated or trimmed mean? Trimmed mean involves trimming $P$ percent observations from both ends. E.g.: If you are asked to compute a 10% trimmed mean, $P = 10$. Given a bunch of observations, $X_i$: First find $n$ = number o
27,357
How to calculate the truncated or trimmed mean?
In addition to the above answer, if there are many entries (say n), then first sorting them takes time O(n log n). However, there is a linear-time solution. Compute the P-quantile L and (1-P)-quantile U. There is a simple (quicksort-like) algorithm for this that runs in expected linear time. There is also a more complicated algorithm that runs in worst case linear time. Both can be found, for example, in: Cormen, Leiserson, Rivest, Stein: Introduction to Algortithms. Scan through all values and add those between L and U. This obviously takes linear time. If there are ties and the computed quantiles exist several times among the values, we might have added too many or too few values and may need to correct for this appropriately. Since we know how many numbers we added in step 2, and also how many times we have seen L and U, this can be done in constant time. Divide the total sum by the number of summands. Note that the above recipe is only worthwhile if n is really large and sorting all of them would be a performance hit, perhaps a few millions.
How to calculate the truncated or trimmed mean?
In addition to the above answer, if there are many entries (say n), then first sorting them takes time O(n log n). However, there is a linear-time solution. Compute the P-quantile L and (1-P)-quantil
How to calculate the truncated or trimmed mean? In addition to the above answer, if there are many entries (say n), then first sorting them takes time O(n log n). However, there is a linear-time solution. Compute the P-quantile L and (1-P)-quantile U. There is a simple (quicksort-like) algorithm for this that runs in expected linear time. There is also a more complicated algorithm that runs in worst case linear time. Both can be found, for example, in: Cormen, Leiserson, Rivest, Stein: Introduction to Algortithms. Scan through all values and add those between L and U. This obviously takes linear time. If there are ties and the computed quantiles exist several times among the values, we might have added too many or too few values and may need to correct for this appropriately. Since we know how many numbers we added in step 2, and also how many times we have seen L and U, this can be done in constant time. Divide the total sum by the number of summands. Note that the above recipe is only worthwhile if n is really large and sorting all of them would be a performance hit, perhaps a few millions.
How to calculate the truncated or trimmed mean? In addition to the above answer, if there are many entries (say n), then first sorting them takes time O(n log n). However, there is a linear-time solution. Compute the P-quantile L and (1-P)-quantil
27,358
ADF test suggesting incorrectly that series is stationary
The ADF test correctly concluded that the series does not have a unit root. The test does not say anything about stationarity beyond the mean of the series. Your series is nonstationary due to variance, not mean, so no wonder the ADF test did not react to that.
ADF test suggesting incorrectly that series is stationary
The ADF test correctly concluded that the series does not have a unit root. The test does not say anything about stationarity beyond the mean of the series. Your series is nonstationary due to varianc
ADF test suggesting incorrectly that series is stationary The ADF test correctly concluded that the series does not have a unit root. The test does not say anything about stationarity beyond the mean of the series. Your series is nonstationary due to variance, not mean, so no wonder the ADF test did not react to that.
ADF test suggesting incorrectly that series is stationary The ADF test correctly concluded that the series does not have a unit root. The test does not say anything about stationarity beyond the mean of the series. Your series is nonstationary due to varianc
27,359
ADF test suggesting incorrectly that series is stationary
The augmented Dickey-Fuller (ADF) test does not have an alternate hypothesis that the data "are stationary." Rather, the ADF tests for evidence that the coefficient $\beta$ in the below equation is not equal to 0 (equivalent to testing whether $\rho=1$ in the un-augmented Dickey Fuller test): $$\Delta y_{t} = \alpha + \beta y_{t-1} + \delta t + \zeta_1 \Delta y_{t-1} + \dots + \zeta_{k}\Delta y_{t-k} + \varepsilon_{t}\text{where }\varepsilon \sim \mathcal{N}(0,\sigma^{2})$$ While it is true that a $\rho = 1$ (or $\rho = -1$) imply nonstationarity of a time series' data, but note that it is possible for $\beta=0$, and yet for $\sigma^{2} = f(t)$, so the ADF's usefulness in providing evidence that data are stationary is not robust to this issue.
ADF test suggesting incorrectly that series is stationary
The augmented Dickey-Fuller (ADF) test does not have an alternate hypothesis that the data "are stationary." Rather, the ADF tests for evidence that the coefficient $\beta$ in the below equation is no
ADF test suggesting incorrectly that series is stationary The augmented Dickey-Fuller (ADF) test does not have an alternate hypothesis that the data "are stationary." Rather, the ADF tests for evidence that the coefficient $\beta$ in the below equation is not equal to 0 (equivalent to testing whether $\rho=1$ in the un-augmented Dickey Fuller test): $$\Delta y_{t} = \alpha + \beta y_{t-1} + \delta t + \zeta_1 \Delta y_{t-1} + \dots + \zeta_{k}\Delta y_{t-k} + \varepsilon_{t}\text{where }\varepsilon \sim \mathcal{N}(0,\sigma^{2})$$ While it is true that a $\rho = 1$ (or $\rho = -1$) imply nonstationarity of a time series' data, but note that it is possible for $\beta=0$, and yet for $\sigma^{2} = f(t)$, so the ADF's usefulness in providing evidence that data are stationary is not robust to this issue.
ADF test suggesting incorrectly that series is stationary The augmented Dickey-Fuller (ADF) test does not have an alternate hypothesis that the data "are stationary." Rather, the ADF tests for evidence that the coefficient $\beta$ in the below equation is no
27,360
Why regularization parameter called as lambda in theory and alpha in python?
No difference. It's just a symbol. Sometimes mathematics uses symbols by convention, but there's no rule or requirement that you must use a certain symbol for a concept. In this particular case, the word lambda is reserved by the Python language, so alpha avoids overlapping with that word. As an aside, one sharp corner in sklearn is that sklearn.linear_model.LogisticRegression uses the inverse of regularization strength as the regularization parameter, so $C=\lambda^{-1}$. In a different package, you might set $\lambda=10$, but for this class, you would get an equivalent result with $C=0.1$.
Why regularization parameter called as lambda in theory and alpha in python?
No difference. It's just a symbol. Sometimes mathematics uses symbols by convention, but there's no rule or requirement that you must use a certain symbol for a concept. In this particular case, the w
Why regularization parameter called as lambda in theory and alpha in python? No difference. It's just a symbol. Sometimes mathematics uses symbols by convention, but there's no rule or requirement that you must use a certain symbol for a concept. In this particular case, the word lambda is reserved by the Python language, so alpha avoids overlapping with that word. As an aside, one sharp corner in sklearn is that sklearn.linear_model.LogisticRegression uses the inverse of regularization strength as the regularization parameter, so $C=\lambda^{-1}$. In a different package, you might set $\lambda=10$, but for this class, you would get an equivalent result with $C=0.1$.
Why regularization parameter called as lambda in theory and alpha in python? No difference. It's just a symbol. Sometimes mathematics uses symbols by convention, but there's no rule or requirement that you must use a certain symbol for a concept. In this particular case, the w
27,361
Derivative of Softmax with respect to weights
The last hidden layer produces output values forming a vector $\vec x = \mathbf x$. The output neuronal layer is meant to classify among $K=1,\dots,k$ categories with a SoftMax activation function assigning conditional probabilities (given $\mathbf x$) to each one the $K$ categories. In each node in the final (or ouput) layer the pre-activated values (logit values) will consist of the scalar products $\mathbf{w}_j^\top\mathbf{x}$, where $\mathbf w_j\in\{\mathbf{w}_1, \mathbf{w}_2,\dots,\mathbf{w}_k\}$. In other words, each category, $k$ will have a different vector of weights pointing at it, determining the contribution of each element in the output of the previous layer (including a bias), encapsulated in $\mathbf x$. However, the activation of this final layer will not take place element-wise (as for example with a sigmoid function in each neuron), but rather through the application of a SoftMax function, which will map a vector in $\mathbb R^k$ to a vector of $K$ elements in [0,1]. Here is a made-up NN to classify colors: Defining the softmax as $$ \sigma(j)=\frac{\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)}=\frac{\exp(z_j)}{\sum_{k=1}^K \exp(z_k)}$$ We want to get the partial derivative with respect to a vector of weights $(\mathbf w_i)$, but we can first get the derivative of $\sigma(j)$ with respect to the logit, i.e. $z_i = \mathbf w_i^\top \cdot \mathbf x$: $$\begin{align} \small{\frac{\partial}{\partial( \mathbf{w}_i^\top \mathbf x)}}\sigma(j) &= \small{\frac{\partial}{\partial \left(\mathbf{w}_i^\top \mathbf x\right)}}\;\frac{\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)} \\[2ex] &\underset{*}{=} \frac{\frac{\partial}{\partial (\mathbf{w_i\top \mathbf x)}}\,\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)}\,-\,\frac{\exp(\mathbf w_j^\top \mathbf x)}{\left(\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x) \right)^2}\quad\small{{\frac{\partial}{\partial \left(\mathbf w_i^\top\mathbf x\right)}}}\,\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)\\[2ex] &= \frac{\delta_{ij}\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)}\,-\,\frac{\exp(\mathbf w_j^\top \mathbf x)}{ \sum_{k=1}^K \exp\left(\mathbf{w}_k^\top\mathbf x \right)} \frac{\exp(\mathbf{w}_i^\top\mathbf x)}{\sum_{k=1}^K \exp\left(\mathbf{w}_k^\top\mathbf x \right)} \\[3ex] &=\sigma(j)\left(\delta_{ij}-\sigma(i)\right) \end{align}$$ $* \text{- quotient rule}$ Thanks and (+1) to Yuntai Kyong for pointing out that there was a forgotten index in the prior version of the post, and the changes in the denominator of the softmax had been left out of the following chain rule... By the chain rule, $$\begin{align}\frac{\partial}{\partial \mathbf{w}_i}\sigma(j)&= \sum_{k = 1}^K \frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\sigma(j)\quad \frac{\partial}{\partial\mathbf{w}_i}\mathbf{w}_k^\top \mathbf{x}\\[2ex] &=\sum_{k = 1}^K \frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\;\sigma(j)\quad \delta_{ik} \mathbf{x}\\[2ex] &=\sum_{k = 1}^K\sigma(j)\left(\delta_{kj}-\sigma(k)\right)\quad \delta_{ik} \mathbf{x} \end{align}$$ Combining this result with the previous equation: $$\bbox[8px, border: 2px solid lime]{\frac{\partial}{\partial \mathbf{w}_i}\sigma(j)=\sigma(j)\left(\delta_{ij}-\sigma(i)\right)\mathbf x}$$
Derivative of Softmax with respect to weights
The last hidden layer produces output values forming a vector $\vec x = \mathbf x$. The output neuronal layer is meant to classify among $K=1,\dots,k$ categories with a SoftMax activation function ass
Derivative of Softmax with respect to weights The last hidden layer produces output values forming a vector $\vec x = \mathbf x$. The output neuronal layer is meant to classify among $K=1,\dots,k$ categories with a SoftMax activation function assigning conditional probabilities (given $\mathbf x$) to each one the $K$ categories. In each node in the final (or ouput) layer the pre-activated values (logit values) will consist of the scalar products $\mathbf{w}_j^\top\mathbf{x}$, where $\mathbf w_j\in\{\mathbf{w}_1, \mathbf{w}_2,\dots,\mathbf{w}_k\}$. In other words, each category, $k$ will have a different vector of weights pointing at it, determining the contribution of each element in the output of the previous layer (including a bias), encapsulated in $\mathbf x$. However, the activation of this final layer will not take place element-wise (as for example with a sigmoid function in each neuron), but rather through the application of a SoftMax function, which will map a vector in $\mathbb R^k$ to a vector of $K$ elements in [0,1]. Here is a made-up NN to classify colors: Defining the softmax as $$ \sigma(j)=\frac{\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)}=\frac{\exp(z_j)}{\sum_{k=1}^K \exp(z_k)}$$ We want to get the partial derivative with respect to a vector of weights $(\mathbf w_i)$, but we can first get the derivative of $\sigma(j)$ with respect to the logit, i.e. $z_i = \mathbf w_i^\top \cdot \mathbf x$: $$\begin{align} \small{\frac{\partial}{\partial( \mathbf{w}_i^\top \mathbf x)}}\sigma(j) &= \small{\frac{\partial}{\partial \left(\mathbf{w}_i^\top \mathbf x\right)}}\;\frac{\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)} \\[2ex] &\underset{*}{=} \frac{\frac{\partial}{\partial (\mathbf{w_i\top \mathbf x)}}\,\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)}\,-\,\frac{\exp(\mathbf w_j^\top \mathbf x)}{\left(\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x) \right)^2}\quad\small{{\frac{\partial}{\partial \left(\mathbf w_i^\top\mathbf x\right)}}}\,\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)\\[2ex] &= \frac{\delta_{ij}\exp(\mathbf{w}_j^\top \mathbf x)}{\sum_{k=1}^K \exp(\mathbf{w}_k^\top\mathbf x)}\,-\,\frac{\exp(\mathbf w_j^\top \mathbf x)}{ \sum_{k=1}^K \exp\left(\mathbf{w}_k^\top\mathbf x \right)} \frac{\exp(\mathbf{w}_i^\top\mathbf x)}{\sum_{k=1}^K \exp\left(\mathbf{w}_k^\top\mathbf x \right)} \\[3ex] &=\sigma(j)\left(\delta_{ij}-\sigma(i)\right) \end{align}$$ $* \text{- quotient rule}$ Thanks and (+1) to Yuntai Kyong for pointing out that there was a forgotten index in the prior version of the post, and the changes in the denominator of the softmax had been left out of the following chain rule... By the chain rule, $$\begin{align}\frac{\partial}{\partial \mathbf{w}_i}\sigma(j)&= \sum_{k = 1}^K \frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\sigma(j)\quad \frac{\partial}{\partial\mathbf{w}_i}\mathbf{w}_k^\top \mathbf{x}\\[2ex] &=\sum_{k = 1}^K \frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\;\sigma(j)\quad \delta_{ik} \mathbf{x}\\[2ex] &=\sum_{k = 1}^K\sigma(j)\left(\delta_{kj}-\sigma(k)\right)\quad \delta_{ik} \mathbf{x} \end{align}$$ Combining this result with the previous equation: $$\bbox[8px, border: 2px solid lime]{\frac{\partial}{\partial \mathbf{w}_i}\sigma(j)=\sigma(j)\left(\delta_{ij}-\sigma(i)\right)\mathbf x}$$
Derivative of Softmax with respect to weights The last hidden layer produces output values forming a vector $\vec x = \mathbf x$. The output neuronal layer is meant to classify among $K=1,\dots,k$ categories with a SoftMax activation function ass
27,362
Derivative of Softmax with respect to weights
I got a different result. Also $\sigma(j)$ depends on $\mathbf{w}_i$ inside the denominator of the softmax, so not sure Antoni's result is correct. $$\begin{align}\frac{\partial}{\partial \mathbf{w}_i}\sigma(j)&= \sum_k\frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\;\sigma(j)\; \frac{\partial}{\partial\mathbf{w}_i}\mathbf{w}_k^\top \mathbf{x}\\[2ex] &= \sum_k \frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\;\sigma(j)\; \delta_{ik} \mathbf{x}\\[2ex] &= \sum_k \sigma(j)\left(\delta_{jk}-\sigma(k)\right)\delta_{ik} \mathbf{x}\\[2ex] &= \sigma(j)\left(\delta_{ij}-\sigma(i)\right) \mathbf{x} \end{align}$$
Derivative of Softmax with respect to weights
I got a different result. Also $\sigma(j)$ depends on $\mathbf{w}_i$ inside the denominator of the softmax, so not sure Antoni's result is correct. $$\begin{align}\frac{\partial}{\partial \mathbf{w}_i
Derivative of Softmax with respect to weights I got a different result. Also $\sigma(j)$ depends on $\mathbf{w}_i$ inside the denominator of the softmax, so not sure Antoni's result is correct. $$\begin{align}\frac{\partial}{\partial \mathbf{w}_i}\sigma(j)&= \sum_k\frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\;\sigma(j)\; \frac{\partial}{\partial\mathbf{w}_i}\mathbf{w}_k^\top \mathbf{x}\\[2ex] &= \sum_k \frac{\partial}{\partial (\mathbf{w}_k^\top \mathbf x)}\;\sigma(j)\; \delta_{ik} \mathbf{x}\\[2ex] &= \sum_k \sigma(j)\left(\delta_{jk}-\sigma(k)\right)\delta_{ik} \mathbf{x}\\[2ex] &= \sigma(j)\left(\delta_{ij}-\sigma(i)\right) \mathbf{x} \end{align}$$
Derivative of Softmax with respect to weights I got a different result. Also $\sigma(j)$ depends on $\mathbf{w}_i$ inside the denominator of the softmax, so not sure Antoni's result is correct. $$\begin{align}\frac{\partial}{\partial \mathbf{w}_i
27,363
Why are numerical solutions preferred to analytical solutions?
Your question is interesting, because it is a starting point into optimization in general. It is maybe better to start with a concrete example on the existence of analytical solution. If you look at your standard polynomial of 2nd degree, $f(x)=ax^2+bx+c$. You have a formula for the zeroes of the function, which is an analytical solution. If you have a polynomial of order 5 or higher, no such formula exists. This is of course not an optimization problem as in minimizing or maximizing a function, but when you find where the derivative is zero, you are essentially looking for a zero of a function, namely the derivative. So it seems that you cannot always solve a problem with pen and paper. This is also dependent on the scale of the problem. Sometimes you need to estimate billions of parameters, and it is just not feasible for a human to work out an analytical solution or even find out if it exists. In the case of ordinary least squares, or fitting a linear model, an analytical solution exists. But it is very easy to change the model slightly, such that no such solution exists, (at least not one we know of). An example of this is the lasso. So the use of numerical methods is completely justified, both by the fact that an analytical solution may not exist, or it is not feasible to work out such a solution.
Why are numerical solutions preferred to analytical solutions?
Your question is interesting, because it is a starting point into optimization in general. It is maybe better to start with a concrete example on the existence of analytical solution. If you look at y
Why are numerical solutions preferred to analytical solutions? Your question is interesting, because it is a starting point into optimization in general. It is maybe better to start with a concrete example on the existence of analytical solution. If you look at your standard polynomial of 2nd degree, $f(x)=ax^2+bx+c$. You have a formula for the zeroes of the function, which is an analytical solution. If you have a polynomial of order 5 or higher, no such formula exists. This is of course not an optimization problem as in minimizing or maximizing a function, but when you find where the derivative is zero, you are essentially looking for a zero of a function, namely the derivative. So it seems that you cannot always solve a problem with pen and paper. This is also dependent on the scale of the problem. Sometimes you need to estimate billions of parameters, and it is just not feasible for a human to work out an analytical solution or even find out if it exists. In the case of ordinary least squares, or fitting a linear model, an analytical solution exists. But it is very easy to change the model slightly, such that no such solution exists, (at least not one we know of). An example of this is the lasso. So the use of numerical methods is completely justified, both by the fact that an analytical solution may not exist, or it is not feasible to work out such a solution.
Why are numerical solutions preferred to analytical solutions? Your question is interesting, because it is a starting point into optimization in general. It is maybe better to start with a concrete example on the existence of analytical solution. If you look at y
27,364
Why are numerical solutions preferred to analytical solutions?
There are many reasons which usually dance around one main consideration: convenience. Often, it's much easier, as you mentioned, to plug the numerical solution than analytical. Say, you have a function $f(x_1,x_2,\dots,x_n)$. If it's a complicated expression, then getting $\bigtriangledown{f}$ and coding it may be cumbersome and error-prone. I mean the typos, not the numerical errors. It's more of an issue in multivariate case, imagine coding all the Hessians! I think that probability of introducing a bug in analytical Hessians is quite high. Hence, the benefit of using analytical expression could be very marginal, especially in multivariate analysis. So, you go through all this trouble to basically get the same result as numerical approximation in many cases. In fact, I code analytical expressions for derivatives only when it's absolutely necessary. This is usually the case only when numerical derivatives are far worse in terms of accuracy. Speed is usually not the factor. It's rare that numerical derivative is slower than analytic one. I focused only on the numerical derivatives, because they always exist analytically as long as $f(.)$ exists. In other problems such as solving equations, integration, optimization - the problem with analytical solutions is that they don't always exist or are very difficult to find, i.e. feasibility.
Why are numerical solutions preferred to analytical solutions?
There are many reasons which usually dance around one main consideration: convenience. Often, it's much easier, as you mentioned, to plug the numerical solution than analytical. Say, you have a functi
Why are numerical solutions preferred to analytical solutions? There are many reasons which usually dance around one main consideration: convenience. Often, it's much easier, as you mentioned, to plug the numerical solution than analytical. Say, you have a function $f(x_1,x_2,\dots,x_n)$. If it's a complicated expression, then getting $\bigtriangledown{f}$ and coding it may be cumbersome and error-prone. I mean the typos, not the numerical errors. It's more of an issue in multivariate case, imagine coding all the Hessians! I think that probability of introducing a bug in analytical Hessians is quite high. Hence, the benefit of using analytical expression could be very marginal, especially in multivariate analysis. So, you go through all this trouble to basically get the same result as numerical approximation in many cases. In fact, I code analytical expressions for derivatives only when it's absolutely necessary. This is usually the case only when numerical derivatives are far worse in terms of accuracy. Speed is usually not the factor. It's rare that numerical derivative is slower than analytic one. I focused only on the numerical derivatives, because they always exist analytically as long as $f(.)$ exists. In other problems such as solving equations, integration, optimization - the problem with analytical solutions is that they don't always exist or are very difficult to find, i.e. feasibility.
Why are numerical solutions preferred to analytical solutions? There are many reasons which usually dance around one main consideration: convenience. Often, it's much easier, as you mentioned, to plug the numerical solution than analytical. Say, you have a functi
27,365
Why are numerical solutions preferred to analytical solutions?
I will add another perspective here, which considers the second order Hessian based methods. Often times, to speed up the convergence, gradient based solvers resort to line-search techniques such as Armijo, L-BFGS etc. These are usually preferred over the naive gradient descent (if we are not training deep networks nowadays). L-BFGS family approaches opt to come up with a positive definite approximation to the inverse Hessian (see BFGS recursion). Of course, whenever possible, we like to provide an analytically computed Hessian, whose inverse has to be positive definite. However, for a large body of problems this quantity is indefinite and thus off the shelf optimizers cannot handle the situation. There are methods such as the Moré and Sorensen trust region step, but a widely accepted solution is far from being existent. This is the reason, for instance, mature optimizers such as Ceres Solver do not allow analytical Hessians, but prefer numerically approximated ones.
Why are numerical solutions preferred to analytical solutions?
I will add another perspective here, which considers the second order Hessian based methods. Often times, to speed up the convergence, gradient based solvers resort to line-search techniques such as A
Why are numerical solutions preferred to analytical solutions? I will add another perspective here, which considers the second order Hessian based methods. Often times, to speed up the convergence, gradient based solvers resort to line-search techniques such as Armijo, L-BFGS etc. These are usually preferred over the naive gradient descent (if we are not training deep networks nowadays). L-BFGS family approaches opt to come up with a positive definite approximation to the inverse Hessian (see BFGS recursion). Of course, whenever possible, we like to provide an analytically computed Hessian, whose inverse has to be positive definite. However, for a large body of problems this quantity is indefinite and thus off the shelf optimizers cannot handle the situation. There are methods such as the Moré and Sorensen trust region step, but a widely accepted solution is far from being existent. This is the reason, for instance, mature optimizers such as Ceres Solver do not allow analytical Hessians, but prefer numerically approximated ones.
Why are numerical solutions preferred to analytical solutions? I will add another perspective here, which considers the second order Hessian based methods. Often times, to speed up the convergence, gradient based solvers resort to line-search techniques such as A
27,366
How should strongly correlated covariates for logistic regression be treated?
There are at least three regularization strategies to address this multi-collinearity/separation problem. 1) Build a Bayesian regression model that establishes a prior distribution over the regression coefficients that shrinks estimates toward zero, but supplies enough prior probability for the posterior distribution to move toward a signal in the data if it is strong enough. There are several types of priors for this, including but not limited to the Laplace, spike-and-slab, and horseshoe priors. Gelman et al. have a nice paper describing a default prior distribution on coefficients in logistic regression, which pairs well with the bayesglm function they developed in the arm package in R, which allows you to easily build and summarize logistic and other generalized linear models. You can read their paper on the subject here. 2) Penalized regression with L1 norm (LASSO regression), L2 norm (ridge regression), or some combination thereof (the elastic net model). Tibshirani, Hastie, and colleagues have developed a package in R called glmnet, which implements elastic net regression (thus L1 and L2 regression, since they are special cases of the elastic net). This package includes the logit model. There is an excellent vignette of the package, at the end of which you can find useful references on regularization in general as well as for the ridge/LASSO/elastic-net framework. If you want to watch a video version of the vignette, and learn a lot of other stuff, too, I recommend taking their Stanford online course, as well. 3) Another way to deal with multi-collinearity problems in logistic and other generalized linear models is through boosted regression. In boosted regression models, you iteratively aggregate the inferences from many simple models called "base learners". By aggregating the estimates of many simple models, you avoid the curse of dimensionality, and you can also compute variable-importance measures. If you set up your base learners properly, multi-collinearity is no longer an issue. There's a great package in R called mboost, which implements boosted generalized linear models and multilevel generalized linear models. Another reason mboost is great is the variety of base learners available, including non-parametric smoothing splines and random fields. Amazing stuff. Even better is a related package called gamboostLSS, which allows you to build boosted regression models over each of the parameters of our likelihood, not just the mean or some other location parameter. In your situation, I'd say the best among these methods is either the Gelman et al. recipe or the elastic net option. Of these, I'd prefer the Gelman et al. recipe, because it will yield you not only point estimates, but posterior distributions of the coefficients, as well. Side note: The beauty of the elastic net and boosting methods, and for some priors the fully Bayesian inference method, is that by regularizing your model, you can also build models with lots of features - even models more features than observations. The regularization procedure in some sense selects those features that are most important while avoiding or at least mitigating the curse of dimensionality.
How should strongly correlated covariates for logistic regression be treated?
There are at least three regularization strategies to address this multi-collinearity/separation problem. 1) Build a Bayesian regression model that establishes a prior distribution over the regression
How should strongly correlated covariates for logistic regression be treated? There are at least three regularization strategies to address this multi-collinearity/separation problem. 1) Build a Bayesian regression model that establishes a prior distribution over the regression coefficients that shrinks estimates toward zero, but supplies enough prior probability for the posterior distribution to move toward a signal in the data if it is strong enough. There are several types of priors for this, including but not limited to the Laplace, spike-and-slab, and horseshoe priors. Gelman et al. have a nice paper describing a default prior distribution on coefficients in logistic regression, which pairs well with the bayesglm function they developed in the arm package in R, which allows you to easily build and summarize logistic and other generalized linear models. You can read their paper on the subject here. 2) Penalized regression with L1 norm (LASSO regression), L2 norm (ridge regression), or some combination thereof (the elastic net model). Tibshirani, Hastie, and colleagues have developed a package in R called glmnet, which implements elastic net regression (thus L1 and L2 regression, since they are special cases of the elastic net). This package includes the logit model. There is an excellent vignette of the package, at the end of which you can find useful references on regularization in general as well as for the ridge/LASSO/elastic-net framework. If you want to watch a video version of the vignette, and learn a lot of other stuff, too, I recommend taking their Stanford online course, as well. 3) Another way to deal with multi-collinearity problems in logistic and other generalized linear models is through boosted regression. In boosted regression models, you iteratively aggregate the inferences from many simple models called "base learners". By aggregating the estimates of many simple models, you avoid the curse of dimensionality, and you can also compute variable-importance measures. If you set up your base learners properly, multi-collinearity is no longer an issue. There's a great package in R called mboost, which implements boosted generalized linear models and multilevel generalized linear models. Another reason mboost is great is the variety of base learners available, including non-parametric smoothing splines and random fields. Amazing stuff. Even better is a related package called gamboostLSS, which allows you to build boosted regression models over each of the parameters of our likelihood, not just the mean or some other location parameter. In your situation, I'd say the best among these methods is either the Gelman et al. recipe or the elastic net option. Of these, I'd prefer the Gelman et al. recipe, because it will yield you not only point estimates, but posterior distributions of the coefficients, as well. Side note: The beauty of the elastic net and boosting methods, and for some priors the fully Bayesian inference method, is that by regularizing your model, you can also build models with lots of features - even models more features than observations. The regularization procedure in some sense selects those features that are most important while avoiding or at least mitigating the curse of dimensionality.
How should strongly correlated covariates for logistic regression be treated? There are at least three regularization strategies to address this multi-collinearity/separation problem. 1) Build a Bayesian regression model that establishes a prior distribution over the regression
27,367
How should strongly correlated covariates for logistic regression be treated?
You can include weakly correlated variables in your model, but any covariate pairs with r > 0.7 should be reduced to the most relevant predictor. Covariates with near-zero variance you can exclude from your analysis, since they don't contribute to your model accuracy but increase the degrees-of-freedom.
How should strongly correlated covariates for logistic regression be treated?
You can include weakly correlated variables in your model, but any covariate pairs with r > 0.7 should be reduced to the most relevant predictor. Covariates with near-zero variance you can exclude fro
How should strongly correlated covariates for logistic regression be treated? You can include weakly correlated variables in your model, but any covariate pairs with r > 0.7 should be reduced to the most relevant predictor. Covariates with near-zero variance you can exclude from your analysis, since they don't contribute to your model accuracy but increase the degrees-of-freedom.
How should strongly correlated covariates for logistic regression be treated? You can include weakly correlated variables in your model, but any covariate pairs with r > 0.7 should be reduced to the most relevant predictor. Covariates with near-zero variance you can exclude fro
27,368
Why are 0.05 < p < 0.95 results called false positives?
Your question is based on a false premise: isn't the null hypothesis still more likely than not to be wrong when p < 0.50 A p-value is not a probability that the null hypothesis is true. For example, if you took a thousand cases where the null hypothesis is true, half of them will have p < .5. Those half will all be null. Indeed, the idea that p > .95 means that the null hypothesis is "probably true" is equally misleading. If the null hypothesis is true, the probability that p > .95 is exactly the same as the probability that p < .05. ETA: Your edit makes it clearer what the issue is: you still do have the issue above (that you're treating a p-value as a posterior probability, when it is not). It's important to note that this is not a subtle philosophical distinction (as I think you're implying with your discussion of the lottery tickets): it has enormous practical implications for any interpretation of p-values. But there is a transformation you can perform on p-values that will get you to what you're looking for, and it's called the local false discovery rate. (As described by this nice paper, it's the frequentist equivalent of the "posterior error probability", so think of it that way if you like). Let's work with a concrete example. Let's say you are performing a t-test to determine whether a sample of 10 numbers (from a normal distribution) has a mean of 0 (a one-sample, two-sided t-test). First, let's see what the p-value distribution looks like when the mean actually is zero, with a short R simulation: null.pvals = replicate(10000, t.test(rnorm(10, mean=0, sd=1))$p.value) hist(null.pvals) As we can see, null p-values have a uniform distribution (equally likely at all points between 0 and 1). This is a necessary condition of p-values: indeed, it's precisely what p-values mean! (Given the null is true, there is a 5% chance it is less than .05, a 10% chance it is less than .1...) Now let's consider the alternative hypothesis- cases where the null is false. Now, this is a bit more complicated: when the null is false, "how false" is it? The mean of the sample isn't 0, but is it .5? 1? 10? Does it randomly vary, sometimes small and sometimes large? For simplicity's sake, let's say it is always equal to .5 (but remember that complication, it'll be important later): alt.pvals = replicate(10000, t.test(rnorm(10, mean=.5, sd=1))$p.value) hist(alt.pvals) Notice that the distribution is now not uniform: it is shifted towards 0! In your comment you mention an "asymmetry" that gives information: this is that asymmetry. So imagine you knew both of those distributions, but you're working with a new experiment, and you also have a prior that there's a 50% chance it's null and 50% that it's alternative. You get a p-value of .7. How can you get from that and the p-value to a probability? What you should do is compare densities: lines(density(alt.pvals, bw=.02)) plot(density(null.pvals, bw=.02)) And look at your p-value: abline(v=.7, col="red", lty=2) That ratio between the null density and the alternative density can be used to calculate the local false discovery rate: the higher the null is relative to the alternative, the higher the local FDR. That's the probability that the hypothesis is null (technically it has a stricter frequentist interpretation, but we'll keep it simple here). If that value is very high, then you can make the interpretation "the null hypothesis is almost certainly true." Indeed, you can make a .05 and .95 threshold of the local FDR: this would have the properties you're looking for. (And since local FDR increases monotonically with p-value, at least if you're doing it right, these will translate to some thresholds A and B where you can say "between A and B we are unsure"). Now, I can already hear you asking "then why don't we use that instead of p-values?" Two reasons: You need to decide on a prior probability that the test is null You need to know the density under the alternative. This is very difficult to guess at, because you need to determine how large your effect sizes and variances can be, and how often they are so! You do not need either of those for a p-value test, and a p-value test still lets you avoid false positives (which is its primary purpose). Now, it is possible to estimate both of those values in multiple hypothesis tests, when you have thousands of p-values (such as one test for each of thousands of genes: see this paper or this paperfor instance), but not when you're doing a single test. Finally, you might say "Isn't the paper still wrong to say a replication that leads to a p-value above .05 is necessarily a false positive?" Well, while it's true that getting one p-value of .04 and another p-value of .06 doesn't really mean the original result was wrong, in practice it's a reasonable metric to pick. But in any case, you might be glad to know others have their doubts about it! The paper you refer to is somewhat controversial in statistics: this paper uses a different method and comes to a very different conclusion about the p-values from medical research, and then that study was criticized by some prominent Bayesians (and round and round it goes...). So while your question is based on some faulty presumptions about p-values, I think it does examine an interesting assumption on the part of the paper you cite.
Why are 0.05 < p < 0.95 results called false positives?
Your question is based on a false premise: isn't the null hypothesis still more likely than not to be wrong when p < 0.50 A p-value is not a probability that the null hypothesis is true. For examp
Why are 0.05 < p < 0.95 results called false positives? Your question is based on a false premise: isn't the null hypothesis still more likely than not to be wrong when p < 0.50 A p-value is not a probability that the null hypothesis is true. For example, if you took a thousand cases where the null hypothesis is true, half of them will have p < .5. Those half will all be null. Indeed, the idea that p > .95 means that the null hypothesis is "probably true" is equally misleading. If the null hypothesis is true, the probability that p > .95 is exactly the same as the probability that p < .05. ETA: Your edit makes it clearer what the issue is: you still do have the issue above (that you're treating a p-value as a posterior probability, when it is not). It's important to note that this is not a subtle philosophical distinction (as I think you're implying with your discussion of the lottery tickets): it has enormous practical implications for any interpretation of p-values. But there is a transformation you can perform on p-values that will get you to what you're looking for, and it's called the local false discovery rate. (As described by this nice paper, it's the frequentist equivalent of the "posterior error probability", so think of it that way if you like). Let's work with a concrete example. Let's say you are performing a t-test to determine whether a sample of 10 numbers (from a normal distribution) has a mean of 0 (a one-sample, two-sided t-test). First, let's see what the p-value distribution looks like when the mean actually is zero, with a short R simulation: null.pvals = replicate(10000, t.test(rnorm(10, mean=0, sd=1))$p.value) hist(null.pvals) As we can see, null p-values have a uniform distribution (equally likely at all points between 0 and 1). This is a necessary condition of p-values: indeed, it's precisely what p-values mean! (Given the null is true, there is a 5% chance it is less than .05, a 10% chance it is less than .1...) Now let's consider the alternative hypothesis- cases where the null is false. Now, this is a bit more complicated: when the null is false, "how false" is it? The mean of the sample isn't 0, but is it .5? 1? 10? Does it randomly vary, sometimes small and sometimes large? For simplicity's sake, let's say it is always equal to .5 (but remember that complication, it'll be important later): alt.pvals = replicate(10000, t.test(rnorm(10, mean=.5, sd=1))$p.value) hist(alt.pvals) Notice that the distribution is now not uniform: it is shifted towards 0! In your comment you mention an "asymmetry" that gives information: this is that asymmetry. So imagine you knew both of those distributions, but you're working with a new experiment, and you also have a prior that there's a 50% chance it's null and 50% that it's alternative. You get a p-value of .7. How can you get from that and the p-value to a probability? What you should do is compare densities: lines(density(alt.pvals, bw=.02)) plot(density(null.pvals, bw=.02)) And look at your p-value: abline(v=.7, col="red", lty=2) That ratio between the null density and the alternative density can be used to calculate the local false discovery rate: the higher the null is relative to the alternative, the higher the local FDR. That's the probability that the hypothesis is null (technically it has a stricter frequentist interpretation, but we'll keep it simple here). If that value is very high, then you can make the interpretation "the null hypothesis is almost certainly true." Indeed, you can make a .05 and .95 threshold of the local FDR: this would have the properties you're looking for. (And since local FDR increases monotonically with p-value, at least if you're doing it right, these will translate to some thresholds A and B where you can say "between A and B we are unsure"). Now, I can already hear you asking "then why don't we use that instead of p-values?" Two reasons: You need to decide on a prior probability that the test is null You need to know the density under the alternative. This is very difficult to guess at, because you need to determine how large your effect sizes and variances can be, and how often they are so! You do not need either of those for a p-value test, and a p-value test still lets you avoid false positives (which is its primary purpose). Now, it is possible to estimate both of those values in multiple hypothesis tests, when you have thousands of p-values (such as one test for each of thousands of genes: see this paper or this paperfor instance), but not when you're doing a single test. Finally, you might say "Isn't the paper still wrong to say a replication that leads to a p-value above .05 is necessarily a false positive?" Well, while it's true that getting one p-value of .04 and another p-value of .06 doesn't really mean the original result was wrong, in practice it's a reasonable metric to pick. But in any case, you might be glad to know others have their doubts about it! The paper you refer to is somewhat controversial in statistics: this paper uses a different method and comes to a very different conclusion about the p-values from medical research, and then that study was criticized by some prominent Bayesians (and round and round it goes...). So while your question is based on some faulty presumptions about p-values, I think it does examine an interesting assumption on the part of the paper you cite.
Why are 0.05 < p < 0.95 results called false positives? Your question is based on a false premise: isn't the null hypothesis still more likely than not to be wrong when p < 0.50 A p-value is not a probability that the null hypothesis is true. For examp
27,369
Why are 0.05 < p < 0.95 results called false positives?
Hover your mouse over any tag ($\leftarrow$ is a fake tag) appearing below to see a brief excerpt of its wiki. Please forgive the disruption of line spacing. I find it worthwhile because tag excerpts may help readers to check understanding of jargon while reading through. Some of these excerpts may deserve editing as well, so they also deserve a publicist, IMHO. $p>.05$ ordinarily implies one should not reject the null-hypothesis. Conversely, type-i-errors or false positives occur when one does reject the null due to sampling error or some other unusual incident that produces a sample that was otherwise unlikely (usually with $p<.05$) to have been sampled randomly from a population in which the null is true. A result with $p>.05$ that is called a false positive seems to reflect a misunderstanding of null hypothesis significance-testing (NHST). Misunderstandings are not uncommon in published research literature, as NHST is notoriously counter-intuitive. This is one of the rallying cries of the bayesian invasion (which I support, but do not follow...yet). I have worked with mistaken impressions such as these myself until recently, so I sympathize most heartily. @DavidRobinson is correct in observing that $p$ is not the probability of the null being false in frequentist NHST. This is (at least) one of Goodman's (2008) "Dirty Dozen" misconceptions about $p$ values (see also Hurlbert & Lombardi, 2009). In NHST, $p$ is the probability that one would draw any future random samples by the same means that would exhibit a relationship or difference (or whatever effect-size is being tested against the null, if other varieties of effect size exist...?) at least as different from the null hypothesis as the sample(s) from the same population(s) one has tested to arrive at a given $p$ value, if the null is true. That is, $p$ is the probability of obtaining a sample like yours given the null; it does not reflect the probability of the null – at least, not directly. Conversely, Bayesian methods pride themselves on their formulation of statistical analyses as focused on estimating the evidence for or against a prior theory of an effect given the data, which they argue is a more intuitively appealing approach (Wagenmakers, 2007), among other advantages, and setting aside debatable disadvantages. (To be fair, see "What are the cons of Bayesian analysis?" You have also commented to cite articles that might offer some nice answers there: Moyé, 2008; Hurlbert & Lombardi, 2009.) Arguably, the null hypothesis as literally stated is often more likely than not to be wrong, because null hypotheses are most commonly, literally hypotheses of zero effect. (For some handy counter-examples, see answers to: "Are large data sets inappropriate for hypothesis testing?") Philosophical issues such as the butterfly effect threaten the literal validity of any such hypothesis; hence the null is useful most generally as a basis of comparison for an alternative hypothesis of some nonzero effect. Such an alternative hypothesis may remain more plausible than the null after data have been collected that would've been improbable if the null were true. Hence researchers typically infer support for an alternative hypothesis from evidence against the null, but that is not what p-values quantify directly (Wagenmakers, 2007). As you suspect, statistical-significance is a function of sample-size, as well as effect size and consistency. (See @gung's answer to the recent question, "How can a t-test be statistically significant if the mean difference is almost 0?") The questions we often intend to ask of our data are, "What is the effect of x on y?" For various reasons (including, IMO, misconceived and otherwise deficient educational programs in statistics, especially as taught by non-statisticians), we often find ourselves instead asking literally the loosely related question, "What is the probability of sampling data such as mine randomly from a population in which x does not affect y?" This is the essential difference between effect size estimation and significance testing, respectively. A $p$ value answers only the latter question directly, but several professionals (@rpierce could probably give you a better list than I; forgive me for dragging you into this!) have argued that researchers misread $p$ as an answer to the former question of effect size all too often; I'm afraid I must agree. To respond more directly regarding the meaning of $.05<p<.95$, it is that the probability of sampling data randomly from a population of which the null is true, but that exhibits a relationship or difference that differs from that which the null describes literally by at least as wide and consistent a margin as your data does...< inhale>...is between 5–95%. One may certainly argue this is a consequence of sample size, because increasing sample size improves one's ability to detect small and inconsistent effect sizes and differentiate them from a null of, say, zero effect with confidence exceeding 5%. However, small and inconsistent effect sizes may or may not be significant pragmatically ( $\ne$ significant statistically – another of Goodman's (2008) dirty dozen); this depends far more on the meaning of the data, with which statistical significance only concerns itself to a limited extent. See my answer to the above. Shouldn't it be correct to call a result definitely false (rather than simply unsupported) if...p > 0.95? Since data should usually represent empirically factual observations, they should not be false; only inferences about them should face this risk, ideally. (Measurement error occurs too of course, but that issue is outside this answer's scope somewhat, so aside from mentioning it here, I'll leave it alone otherwise.) Some risk always exists of making a false positive inference about the null being less useful than the alternative hypothesis, at least unless the inferrer knows the null is true. Only in the rather hard-to-conceive circumstance of knowledge that the null is literally true would an inference favoring an alternative hypothesis be definitely false...at least, as far as I can imagine at the moment. Clearly, widespread usage or convention is not the best authority on epistemic or inferential validity. Even published resources are fallible; see for instance Fallacy in p-value definition. Your reference (Hurlbert & Lombardi, 2009) offers some interesting exposition of this principle too (page 322): StatSoft (2007) boasts on their website that their online manual “is the only internet resource on statistics recommended by Encyclopedia Brittanica.” Never has it been so important to ‘Distrust Authority,’ as the bumper sticker says. [Comically broken URL converted to hyperlinked text.] Another case in point: this phrase in a very recent Nature News article (Nuzzo, 2014): "P value, a common index for the strength of evidence..." See Wagenmakers' (2007, page 787) "Problem 3: $p$ Values Do Not Quantify Statistical Evidence"...However, @MichaelLew (Lew, 2013) disagrees in a way you might find useful: he uses $p$ values to index likelihood functions. Yet in as much as these published sources contradict one another, at least one must be wrong! (On some level, I think...) Of course, this is not as bad as "untrustworthy" per se. I hope I can coax Michael into chiming in here by tagging him as I have (but I'm not sure user tags send notifications when edited in – I don't think yours in the OP did). He may be the only one who can save Nuzzo – even Nature itself! Help us Obi-Wan! (And forgive me if my answer here demonstrates that I've still failed to comprehend the implications of your work, which I'm sure I have in any case...) BTW, Nuzzo also offers some intriguing self-defense and refutation of Wagenmaakers' "Problem 3": see Nuzzo's "Probable cause" figure and supporting citations (Goodman, 2001, 1992; Gorroochurn, Hodge, Heiman, Durner, & Greenberg, 2007). These just might contain the answer you're really looking for, but I doubt I could tell. Re: your multiple choice question, I select d. You may have misinterpreted some concepts here, but you're certainly not alone if so, and I'll leave the judgment to you, as only you know what you really believe. Misinterpretation implies some amount of certainty, whereas asking a question implies the opposite, and that impulse to question when uncertain is quite laudable and far from ubiquitous, unfortunately. This matter of human nature makes the incorrectness of our conventions sadly short of harmless, and deserving of complaints such as those referenced here. (Thanks in part to you!) However, your proposal is not completely correct either. Some interesting discussion of problems related to $p$ values in which I've participated appears in this question: Accommodating entrenched views of p-values. My answer lists a few references you may find useful for reading further into the interpretive problems and alternatives to $p$ values. Be forewarned: I still haven't hit the bottom of this particular rabbit hole myself, but I can at least tell you that it's very deep. I'm still learning about it myself (else I suspect I'd be writing from a more Bayesian perspective [edit]: or maybe the NFSA perspective! Hurlbert & Lombardi, 2009), I am a weak authority at best, and I welcome any corrections or elaborations others may offer to what I've said here. All I can opine in conclusion is that there probably is a mathematically correct answer, and it may well be that most people get it wrong. The right answer certainly doesn't come easily, as the following references demonstrate... P.S. As requested (sort of...I admit I'm really just tacking this on instead of working it in), this question is a better reference for the sometimes uniform distribution of $p$ given the null: "Why are p-values uniformly distributed under the null hypothesis?" Of particular interest are @whuber's comments, which raise a class of exceptions. As is somewhat true with the discussion as a whole, I don't follow the arguments 100%, let alone their implications, so I'm not sure those problems with $p$ distribution uniformity are actually exceptional. Further cause for deep-seated statistical confusion, I'm afraid... References - Goodman, S. N. (1992). A comment on replication, P‐values and evidence. Statistics in Medicine, 11(7), 875–879. - Goodman, S. N. (2001). Of P-values and Bayes: A modest proposal. Epidemiology, 12(3), 295–297. Retrieved from http://swfsc.noaa.gov/uploadedFiles/Divisions/PRD/Programs/ETP_Cetacean_Assessment/Of_P_Values_and_Bayes__A_Modest_Proposal.6.pdf. - Goodman, S. (2008). A dirty dozen: Twelve P-value misconceptions. Seminars in Hematology, 45(3), 135–140. Retrieved from http://xa.yimg.com/kq/groups/18751725/636586767/name/twelve+P+value+misconceptions.pdf. - Gorroochurn, P., Hodge, S. E., Heiman, G. A., Durner, M., & Greenberg, D. A. (2007). Non-replication of association studies: “pseudo-failures” to replicate? Genetics in Medicine, 9(6), 325–331. Retrieved from http://www.nature.com/gim/journal/v9/n6/full/gim200755a.html. - Hurlbert, S. H., & Lombardi, C. M. (2009). Final collapse of the Neyman–Pearson decision theoretic framework and rise of the neoFisherian. Annales Zoologici Fennici, 46(5), 311–349. Retrieved from http://xa.yimg.com/kq/groups/1542294/508917937/name/HurlbertLombardi2009AZF.pdf. - Lew, M. J. (2013). To P or not to P: On the evidential nature of P-values and their place in scientific inference. arXiv:1311.0081 [stat.ME]. Retrieved from http://arxiv.org/abs/1311.0081. - Moyé, L. A. (2008). Bayesians in clinical trials: Asleep at the switch. Statistics in Medicine, 27(4), 469–482. - Nuzzo, R. (2014, February 12). Scientific method: Statistical errors. Nature News, 506(7487). Retrieved from http://www.nature.com/news/scientific-method-statistical-errors-1.14700. - Wagenmakers, E. J. (2007). A practical solution to the pervasive problems of p values. Psychonomic Bulletin & Review, 14(5), 779–804. Retrieved from http://www.brainlife.org/reprint/2007/Wagenmakers_EJ071000.pdf.
Why are 0.05 < p < 0.95 results called false positives?
Hover your mouse over any tag ($\leftarrow$ is a fake tag) appearing below to see a brief excerpt of its wiki. Please forgive the disruption of line spacing. I find it worthwhile because tag excerpts
Why are 0.05 < p < 0.95 results called false positives? Hover your mouse over any tag ($\leftarrow$ is a fake tag) appearing below to see a brief excerpt of its wiki. Please forgive the disruption of line spacing. I find it worthwhile because tag excerpts may help readers to check understanding of jargon while reading through. Some of these excerpts may deserve editing as well, so they also deserve a publicist, IMHO. $p>.05$ ordinarily implies one should not reject the null-hypothesis. Conversely, type-i-errors or false positives occur when one does reject the null due to sampling error or some other unusual incident that produces a sample that was otherwise unlikely (usually with $p<.05$) to have been sampled randomly from a population in which the null is true. A result with $p>.05$ that is called a false positive seems to reflect a misunderstanding of null hypothesis significance-testing (NHST). Misunderstandings are not uncommon in published research literature, as NHST is notoriously counter-intuitive. This is one of the rallying cries of the bayesian invasion (which I support, but do not follow...yet). I have worked with mistaken impressions such as these myself until recently, so I sympathize most heartily. @DavidRobinson is correct in observing that $p$ is not the probability of the null being false in frequentist NHST. This is (at least) one of Goodman's (2008) "Dirty Dozen" misconceptions about $p$ values (see also Hurlbert & Lombardi, 2009). In NHST, $p$ is the probability that one would draw any future random samples by the same means that would exhibit a relationship or difference (or whatever effect-size is being tested against the null, if other varieties of effect size exist...?) at least as different from the null hypothesis as the sample(s) from the same population(s) one has tested to arrive at a given $p$ value, if the null is true. That is, $p$ is the probability of obtaining a sample like yours given the null; it does not reflect the probability of the null – at least, not directly. Conversely, Bayesian methods pride themselves on their formulation of statistical analyses as focused on estimating the evidence for or against a prior theory of an effect given the data, which they argue is a more intuitively appealing approach (Wagenmakers, 2007), among other advantages, and setting aside debatable disadvantages. (To be fair, see "What are the cons of Bayesian analysis?" You have also commented to cite articles that might offer some nice answers there: Moyé, 2008; Hurlbert & Lombardi, 2009.) Arguably, the null hypothesis as literally stated is often more likely than not to be wrong, because null hypotheses are most commonly, literally hypotheses of zero effect. (For some handy counter-examples, see answers to: "Are large data sets inappropriate for hypothesis testing?") Philosophical issues such as the butterfly effect threaten the literal validity of any such hypothesis; hence the null is useful most generally as a basis of comparison for an alternative hypothesis of some nonzero effect. Such an alternative hypothesis may remain more plausible than the null after data have been collected that would've been improbable if the null were true. Hence researchers typically infer support for an alternative hypothesis from evidence against the null, but that is not what p-values quantify directly (Wagenmakers, 2007). As you suspect, statistical-significance is a function of sample-size, as well as effect size and consistency. (See @gung's answer to the recent question, "How can a t-test be statistically significant if the mean difference is almost 0?") The questions we often intend to ask of our data are, "What is the effect of x on y?" For various reasons (including, IMO, misconceived and otherwise deficient educational programs in statistics, especially as taught by non-statisticians), we often find ourselves instead asking literally the loosely related question, "What is the probability of sampling data such as mine randomly from a population in which x does not affect y?" This is the essential difference between effect size estimation and significance testing, respectively. A $p$ value answers only the latter question directly, but several professionals (@rpierce could probably give you a better list than I; forgive me for dragging you into this!) have argued that researchers misread $p$ as an answer to the former question of effect size all too often; I'm afraid I must agree. To respond more directly regarding the meaning of $.05<p<.95$, it is that the probability of sampling data randomly from a population of which the null is true, but that exhibits a relationship or difference that differs from that which the null describes literally by at least as wide and consistent a margin as your data does...< inhale>...is between 5–95%. One may certainly argue this is a consequence of sample size, because increasing sample size improves one's ability to detect small and inconsistent effect sizes and differentiate them from a null of, say, zero effect with confidence exceeding 5%. However, small and inconsistent effect sizes may or may not be significant pragmatically ( $\ne$ significant statistically – another of Goodman's (2008) dirty dozen); this depends far more on the meaning of the data, with which statistical significance only concerns itself to a limited extent. See my answer to the above. Shouldn't it be correct to call a result definitely false (rather than simply unsupported) if...p > 0.95? Since data should usually represent empirically factual observations, they should not be false; only inferences about them should face this risk, ideally. (Measurement error occurs too of course, but that issue is outside this answer's scope somewhat, so aside from mentioning it here, I'll leave it alone otherwise.) Some risk always exists of making a false positive inference about the null being less useful than the alternative hypothesis, at least unless the inferrer knows the null is true. Only in the rather hard-to-conceive circumstance of knowledge that the null is literally true would an inference favoring an alternative hypothesis be definitely false...at least, as far as I can imagine at the moment. Clearly, widespread usage or convention is not the best authority on epistemic or inferential validity. Even published resources are fallible; see for instance Fallacy in p-value definition. Your reference (Hurlbert & Lombardi, 2009) offers some interesting exposition of this principle too (page 322): StatSoft (2007) boasts on their website that their online manual “is the only internet resource on statistics recommended by Encyclopedia Brittanica.” Never has it been so important to ‘Distrust Authority,’ as the bumper sticker says. [Comically broken URL converted to hyperlinked text.] Another case in point: this phrase in a very recent Nature News article (Nuzzo, 2014): "P value, a common index for the strength of evidence..." See Wagenmakers' (2007, page 787) "Problem 3: $p$ Values Do Not Quantify Statistical Evidence"...However, @MichaelLew (Lew, 2013) disagrees in a way you might find useful: he uses $p$ values to index likelihood functions. Yet in as much as these published sources contradict one another, at least one must be wrong! (On some level, I think...) Of course, this is not as bad as "untrustworthy" per se. I hope I can coax Michael into chiming in here by tagging him as I have (but I'm not sure user tags send notifications when edited in – I don't think yours in the OP did). He may be the only one who can save Nuzzo – even Nature itself! Help us Obi-Wan! (And forgive me if my answer here demonstrates that I've still failed to comprehend the implications of your work, which I'm sure I have in any case...) BTW, Nuzzo also offers some intriguing self-defense and refutation of Wagenmaakers' "Problem 3": see Nuzzo's "Probable cause" figure and supporting citations (Goodman, 2001, 1992; Gorroochurn, Hodge, Heiman, Durner, & Greenberg, 2007). These just might contain the answer you're really looking for, but I doubt I could tell. Re: your multiple choice question, I select d. You may have misinterpreted some concepts here, but you're certainly not alone if so, and I'll leave the judgment to you, as only you know what you really believe. Misinterpretation implies some amount of certainty, whereas asking a question implies the opposite, and that impulse to question when uncertain is quite laudable and far from ubiquitous, unfortunately. This matter of human nature makes the incorrectness of our conventions sadly short of harmless, and deserving of complaints such as those referenced here. (Thanks in part to you!) However, your proposal is not completely correct either. Some interesting discussion of problems related to $p$ values in which I've participated appears in this question: Accommodating entrenched views of p-values. My answer lists a few references you may find useful for reading further into the interpretive problems and alternatives to $p$ values. Be forewarned: I still haven't hit the bottom of this particular rabbit hole myself, but I can at least tell you that it's very deep. I'm still learning about it myself (else I suspect I'd be writing from a more Bayesian perspective [edit]: or maybe the NFSA perspective! Hurlbert & Lombardi, 2009), I am a weak authority at best, and I welcome any corrections or elaborations others may offer to what I've said here. All I can opine in conclusion is that there probably is a mathematically correct answer, and it may well be that most people get it wrong. The right answer certainly doesn't come easily, as the following references demonstrate... P.S. As requested (sort of...I admit I'm really just tacking this on instead of working it in), this question is a better reference for the sometimes uniform distribution of $p$ given the null: "Why are p-values uniformly distributed under the null hypothesis?" Of particular interest are @whuber's comments, which raise a class of exceptions. As is somewhat true with the discussion as a whole, I don't follow the arguments 100%, let alone their implications, so I'm not sure those problems with $p$ distribution uniformity are actually exceptional. Further cause for deep-seated statistical confusion, I'm afraid... References - Goodman, S. N. (1992). A comment on replication, P‐values and evidence. Statistics in Medicine, 11(7), 875–879. - Goodman, S. N. (2001). Of P-values and Bayes: A modest proposal. Epidemiology, 12(3), 295–297. Retrieved from http://swfsc.noaa.gov/uploadedFiles/Divisions/PRD/Programs/ETP_Cetacean_Assessment/Of_P_Values_and_Bayes__A_Modest_Proposal.6.pdf. - Goodman, S. (2008). A dirty dozen: Twelve P-value misconceptions. Seminars in Hematology, 45(3), 135–140. Retrieved from http://xa.yimg.com/kq/groups/18751725/636586767/name/twelve+P+value+misconceptions.pdf. - Gorroochurn, P., Hodge, S. E., Heiman, G. A., Durner, M., & Greenberg, D. A. (2007). Non-replication of association studies: “pseudo-failures” to replicate? Genetics in Medicine, 9(6), 325–331. Retrieved from http://www.nature.com/gim/journal/v9/n6/full/gim200755a.html. - Hurlbert, S. H., & Lombardi, C. M. (2009). Final collapse of the Neyman–Pearson decision theoretic framework and rise of the neoFisherian. Annales Zoologici Fennici, 46(5), 311–349. Retrieved from http://xa.yimg.com/kq/groups/1542294/508917937/name/HurlbertLombardi2009AZF.pdf. - Lew, M. J. (2013). To P or not to P: On the evidential nature of P-values and their place in scientific inference. arXiv:1311.0081 [stat.ME]. Retrieved from http://arxiv.org/abs/1311.0081. - Moyé, L. A. (2008). Bayesians in clinical trials: Asleep at the switch. Statistics in Medicine, 27(4), 469–482. - Nuzzo, R. (2014, February 12). Scientific method: Statistical errors. Nature News, 506(7487). Retrieved from http://www.nature.com/news/scientific-method-statistical-errors-1.14700. - Wagenmakers, E. J. (2007). A practical solution to the pervasive problems of p values. Psychonomic Bulletin & Review, 14(5), 779–804. Retrieved from http://www.brainlife.org/reprint/2007/Wagenmakers_EJ071000.pdf.
Why are 0.05 < p < 0.95 results called false positives? Hover your mouse over any tag ($\leftarrow$ is a fake tag) appearing below to see a brief excerpt of its wiki. Please forgive the disruption of line spacing. I find it worthwhile because tag excerpts
27,370
Problem understanding the logistic regression link function
We can rationalize this as follows: Underlying logistic regression is a latent (unobservable) linear regression model: $$y^* = X\beta + u$$ where $y^*$ is a continuous unobservable variable (and $X$ is the regressor matrix). The error term is assumed, conditional on the regressors, to follow the logistic distribution, $u\mid X\sim \Lambda(0, \frac {\pi^2}{3})$. We assume that what we observe, i.e. the binary variable $y$, is an Indicator function of the unobservable $y^*$: $$ y = 1 \;\;\text{if} \;\;y^*>0,\qquad y = 0 \;\;\text{if}\;\; y^*\le 0$$ Then we ask "what is the probability that $y$ will take the value $1$ given the regressors (i.e. we are looking at a conditional probability). This is $$P(y =1\mid X ) = P(y^*>0\mid X) = P(X\beta + u>0\mid X) = P(u> - X\beta\mid X) \\= 1- \Lambda (-Χ\beta) = \Lambda (X\beta) $$ the last equality due to the symmetry property of the logistic cumulative distribution function. So we have obtained the basic logistic regression model $$p=P(y =1 \mid X) = \Lambda (X\beta) = \frac 1 {1+e^{-X\beta}}$$ After that, the other answers give you how we manipulate this expression algebraically to arrive at $$\log \frac {p}{1 - p} = X\beta $$ It is therefore the initial linear assumption/specification related to the Latent variable $y^*$, that leads to this last relation to hold. Note that $\log \frac {p}{1 - p}$ is not equal to the latent variable $y^*$ but rather $y^* = \log \frac {p}{1 - p} + u$
Problem understanding the logistic regression link function
We can rationalize this as follows: Underlying logistic regression is a latent (unobservable) linear regression model: $$y^* = X\beta + u$$ where $y^*$ is a continuous unobservable variable (and $X$ i
Problem understanding the logistic regression link function We can rationalize this as follows: Underlying logistic regression is a latent (unobservable) linear regression model: $$y^* = X\beta + u$$ where $y^*$ is a continuous unobservable variable (and $X$ is the regressor matrix). The error term is assumed, conditional on the regressors, to follow the logistic distribution, $u\mid X\sim \Lambda(0, \frac {\pi^2}{3})$. We assume that what we observe, i.e. the binary variable $y$, is an Indicator function of the unobservable $y^*$: $$ y = 1 \;\;\text{if} \;\;y^*>0,\qquad y = 0 \;\;\text{if}\;\; y^*\le 0$$ Then we ask "what is the probability that $y$ will take the value $1$ given the regressors (i.e. we are looking at a conditional probability). This is $$P(y =1\mid X ) = P(y^*>0\mid X) = P(X\beta + u>0\mid X) = P(u> - X\beta\mid X) \\= 1- \Lambda (-Χ\beta) = \Lambda (X\beta) $$ the last equality due to the symmetry property of the logistic cumulative distribution function. So we have obtained the basic logistic regression model $$p=P(y =1 \mid X) = \Lambda (X\beta) = \frac 1 {1+e^{-X\beta}}$$ After that, the other answers give you how we manipulate this expression algebraically to arrive at $$\log \frac {p}{1 - p} = X\beta $$ It is therefore the initial linear assumption/specification related to the Latent variable $y^*$, that leads to this last relation to hold. Note that $\log \frac {p}{1 - p}$ is not equal to the latent variable $y^*$ but rather $y^* = \log \frac {p}{1 - p} + u$
Problem understanding the logistic regression link function We can rationalize this as follows: Underlying logistic regression is a latent (unobservable) linear regression model: $$y^* = X\beta + u$$ where $y^*$ is a continuous unobservable variable (and $X$ i
27,371
Problem understanding the logistic regression link function
First of all let me re-write your logit model as $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta X,$$ just to emphasize that those $p(x)$ depends on your explanatory random variables, $X$. When we say that $g(x)$ is "linear" it means that this relation is linear with respect to the parameters $\beta$'s and not in those $X$'s. For example let's say you have two explanatory random variables, $X_1$ and $X_2$. Then not only $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_1X_1+\beta_2X_2,$$ but also $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_1X_1^2+\beta_2X_2^3,$$ and $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_1\sin{(X_1)}+\beta_2\sin{(X_2)},$$ are all linear with respect to $\beta_i$'s for $i=0,1,2$. However, the model $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_0\beta_1X,$$ is not linear in $\beta_i$'s because of that product $\beta_0\beta_1$.
Problem understanding the logistic regression link function
First of all let me re-write your logit model as $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta X,$$ just to emphasize that those $p(x)$ depends on your explanatory random variables, $X$. When we say that $g(x)
Problem understanding the logistic regression link function First of all let me re-write your logit model as $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta X,$$ just to emphasize that those $p(x)$ depends on your explanatory random variables, $X$. When we say that $g(x)$ is "linear" it means that this relation is linear with respect to the parameters $\beta$'s and not in those $X$'s. For example let's say you have two explanatory random variables, $X_1$ and $X_2$. Then not only $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_1X_1+\beta_2X_2,$$ but also $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_1X_1^2+\beta_2X_2^3,$$ and $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_1\sin{(X_1)}+\beta_2\sin{(X_2)},$$ are all linear with respect to $\beta_i$'s for $i=0,1,2$. However, the model $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta_0+\beta_0\beta_1X,$$ is not linear in $\beta_i$'s because of that product $\beta_0\beta_1$.
Problem understanding the logistic regression link function First of all let me re-write your logit model as $$g(x)=\ln \frac{p(x)}{1-p(x)}=\beta X,$$ just to emphasize that those $p(x)$ depends on your explanatory random variables, $X$. When we say that $g(x)
27,372
Problem understanding the logistic regression link function
For logistic Regression, our hypothesis is: $$ h_\theta (X) = p = \frac{1}{1 - \exp(-\beta.X)} $$ now simplifying it: $$ 1 - \exp(-\beta.X) = \frac{1}{p} $$ $$ 1 - \frac{1}{p} = \exp(-\beta.X)$$ taking log on both sides, and simplifying it, $$ \ln{\frac{p}{1-p}} = \beta.X $$ now, if we look at this final equation, the LHS of it is logit fuction of $p$, and RHS is the dot product of two vectors, its expansion will look like: $$ \beta.X = \beta_0 + \beta_1.X_1 + \beta_2.X_2 + ... $$ parameters $ \beta_{n * 1} $ and input features $ X_{1 * n} $. Since, the parameters $ \beta $ are learned due to our learning algorithms and are constant, and there is involvement of input features in first degree only (power 1) e.g. terms like $X_1^2, X_1.X_2^2$ do not appear, and no mixed features terms like $X_1.X_2$, the logit of our hypothesis/or probability is linear function/interpretation of input features $ X$.
Problem understanding the logistic regression link function
For logistic Regression, our hypothesis is: $$ h_\theta (X) = p = \frac{1}{1 - \exp(-\beta.X)} $$ now simplifying it: $$ 1 - \exp(-\beta.X) = \frac{1}{p} $$ $$ 1 - \frac{1}{p} = \exp(-\beta.X)$$ tak
Problem understanding the logistic regression link function For logistic Regression, our hypothesis is: $$ h_\theta (X) = p = \frac{1}{1 - \exp(-\beta.X)} $$ now simplifying it: $$ 1 - \exp(-\beta.X) = \frac{1}{p} $$ $$ 1 - \frac{1}{p} = \exp(-\beta.X)$$ taking log on both sides, and simplifying it, $$ \ln{\frac{p}{1-p}} = \beta.X $$ now, if we look at this final equation, the LHS of it is logit fuction of $p$, and RHS is the dot product of two vectors, its expansion will look like: $$ \beta.X = \beta_0 + \beta_1.X_1 + \beta_2.X_2 + ... $$ parameters $ \beta_{n * 1} $ and input features $ X_{1 * n} $. Since, the parameters $ \beta $ are learned due to our learning algorithms and are constant, and there is involvement of input features in first degree only (power 1) e.g. terms like $X_1^2, X_1.X_2^2$ do not appear, and no mixed features terms like $X_1.X_2$, the logit of our hypothesis/or probability is linear function/interpretation of input features $ X$.
Problem understanding the logistic regression link function For logistic Regression, our hypothesis is: $$ h_\theta (X) = p = \frac{1}{1 - \exp(-\beta.X)} $$ now simplifying it: $$ 1 - \exp(-\beta.X) = \frac{1}{p} $$ $$ 1 - \frac{1}{p} = \exp(-\beta.X)$$ tak
27,373
Variance of sample median
The variance of the sample median depends on the distribution you are sampling from. If you know the sampling distribution you can use the distribution of order statistics to find the distribution of the median and thence its variance. If you don't know and don't want to make assumptions about the distribution, then you can do something like bootstrapping to estimate the variance.
Variance of sample median
The variance of the sample median depends on the distribution you are sampling from. If you know the sampling distribution you can use the distribution of order statistics to find the distribution of
Variance of sample median The variance of the sample median depends on the distribution you are sampling from. If you know the sampling distribution you can use the distribution of order statistics to find the distribution of the median and thence its variance. If you don't know and don't want to make assumptions about the distribution, then you can do something like bootstrapping to estimate the variance.
Variance of sample median The variance of the sample median depends on the distribution you are sampling from. If you know the sampling distribution you can use the distribution of order statistics to find the distribution of
27,374
Variance of sample median
To add to Jonathan's answer and your follow-up question. Everything depends on the actual population distribution. You know it, but what is it? In the example below (using R) I know the population distribution but it is somewhat unusual - the product of a gamma distribution multiplied by a normal distribution. The sampling distribution of the median could be calculated but is unlikely to be worth the effort. Bootstrapping is a good practical alternative. My object results contains 1000 sample medians for samples of size 10 drawn from that population and is a nice way to illustrate its sampling distribution. > population <- rgamma(1000,1,1)*rnorm(1000,2,1) > plot(density(population), main="Distribution of population") > n <-10 > samp <- sample(population, n) > c(median(population), median(samp)) [1] 1.136544 1.738544 > > reps <- 1000 > results <- numeric(reps) > for (i in 1:1000){ + samp <- sample(population, n) + results[i] <- median(samp) + } > > plot(density(results), main="Distribution of sample median") > summary(results) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.1134 0.8320 1.1670 1.2530 1.6090 5.8890 > quantile(results, c(0.025,0.975)) 2.5% 97.5% 0.373812 2.573625
Variance of sample median
To add to Jonathan's answer and your follow-up question. Everything depends on the actual population distribution. You know it, but what is it? In the example below (using R) I know the population d
Variance of sample median To add to Jonathan's answer and your follow-up question. Everything depends on the actual population distribution. You know it, but what is it? In the example below (using R) I know the population distribution but it is somewhat unusual - the product of a gamma distribution multiplied by a normal distribution. The sampling distribution of the median could be calculated but is unlikely to be worth the effort. Bootstrapping is a good practical alternative. My object results contains 1000 sample medians for samples of size 10 drawn from that population and is a nice way to illustrate its sampling distribution. > population <- rgamma(1000,1,1)*rnorm(1000,2,1) > plot(density(population), main="Distribution of population") > n <-10 > samp <- sample(population, n) > c(median(population), median(samp)) [1] 1.136544 1.738544 > > reps <- 1000 > results <- numeric(reps) > for (i in 1:1000){ + samp <- sample(population, n) + results[i] <- median(samp) + } > > plot(density(results), main="Distribution of sample median") > summary(results) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.1134 0.8320 1.1670 1.2530 1.6090 5.8890 > quantile(results, c(0.025,0.975)) 2.5% 97.5% 0.373812 2.573625
Variance of sample median To add to Jonathan's answer and your follow-up question. Everything depends on the actual population distribution. You know it, but what is it? In the example below (using R) I know the population d
27,375
Variance of sample median
Depending on how serious you are about the finite population nature of your problem, you might want to look at papers like Woodruff (1952) and Francisco and Fuller (1991). Technically, the variance of the median in the case of an SRS/i.i.d. sample depends on the density at the population median; however, the concept of density is not defined for finite populations, so Woodruff was approximating the median with a primitive kernel-type estimator.
Variance of sample median
Depending on how serious you are about the finite population nature of your problem, you might want to look at papers like Woodruff (1952) and Francisco and Fuller (1991). Technically, the variance of
Variance of sample median Depending on how serious you are about the finite population nature of your problem, you might want to look at papers like Woodruff (1952) and Francisco and Fuller (1991). Technically, the variance of the median in the case of an SRS/i.i.d. sample depends on the density at the population median; however, the concept of density is not defined for finite populations, so Woodruff was approximating the median with a primitive kernel-type estimator.
Variance of sample median Depending on how serious you are about the finite population nature of your problem, you might want to look at papers like Woodruff (1952) and Francisco and Fuller (1991). Technically, the variance of
27,376
Variance of sample median
My opinion is that an efficient and simple solution in practice is perhaps possible for small sample sizes. First to quote Wikipedia on the topic of Median: "For univariate distributions that are symmetric about one median, the Hodges–Lehmann estimator is a robust and highly efficient estimator of the population median.[21]" The HL median estimate is especially simple for small samples of size n, just compute all possible two point (including repeats) averages. From these n(n+1)/2 new constructs, compute the HL Median Estimator as the usual sample median. Now, per the same Wikipedia article on the median, the cited variance of the median 1/(4*n*f(median)*f(median)). However, for a discrete sample of size n, I would argue that a conservative estimate to assume for the value of the density function at the median point is 1/n, as we are dividing by this term. As a consequence, the variance of the median is expected to be n/4 or lower. For large n, this would be poor, so yes a more complex (and some would suggest subjective) exercise involving re-sampling could be employed to construct bins of the optimal width so as provide a greater probability mass for f(median). Now if the purpose of the variance estimate is to gain a precision estimate on the median, may I suggest employing the following bounds due to Mallow assuming the Median is greater than Mean, namely: Median - Mean is less than or equal to Sigma (or, -Sigma when the Median is less than the Mean). Equivalently, the Median lies between the Mean plus Sigma and the Mean minus Sigma. So, inserting population estimators for the mean and sigma, possibly robust, one can establish a bound for the median that would be consisent with the provided mean and sigma estimates based on the sample population.
Variance of sample median
My opinion is that an efficient and simple solution in practice is perhaps possible for small sample sizes. First to quote Wikipedia on the topic of Median: "For univariate distributions that are symm
Variance of sample median My opinion is that an efficient and simple solution in practice is perhaps possible for small sample sizes. First to quote Wikipedia on the topic of Median: "For univariate distributions that are symmetric about one median, the Hodges–Lehmann estimator is a robust and highly efficient estimator of the population median.[21]" The HL median estimate is especially simple for small samples of size n, just compute all possible two point (including repeats) averages. From these n(n+1)/2 new constructs, compute the HL Median Estimator as the usual sample median. Now, per the same Wikipedia article on the median, the cited variance of the median 1/(4*n*f(median)*f(median)). However, for a discrete sample of size n, I would argue that a conservative estimate to assume for the value of the density function at the median point is 1/n, as we are dividing by this term. As a consequence, the variance of the median is expected to be n/4 or lower. For large n, this would be poor, so yes a more complex (and some would suggest subjective) exercise involving re-sampling could be employed to construct bins of the optimal width so as provide a greater probability mass for f(median). Now if the purpose of the variance estimate is to gain a precision estimate on the median, may I suggest employing the following bounds due to Mallow assuming the Median is greater than Mean, namely: Median - Mean is less than or equal to Sigma (or, -Sigma when the Median is less than the Mean). Equivalently, the Median lies between the Mean plus Sigma and the Mean minus Sigma. So, inserting population estimators for the mean and sigma, possibly robust, one can establish a bound for the median that would be consisent with the provided mean and sigma estimates based on the sample population.
Variance of sample median My opinion is that an efficient and simple solution in practice is perhaps possible for small sample sizes. First to quote Wikipedia on the topic of Median: "For univariate distributions that are symm
27,377
Variance of sample median
Building on the aswer by StasK and assuming that we don't know the distribution: Sort the values ($x_0,..,x_i,..,x_{N-1}$). Then Woodruff (1952) suggests to take the difference between the values at half the square root of the sample size above and below the sample median $\tilde{\mu}_s$: \begin{align} \sigma_{\tilde{\mu}_s} \approx \dfrac{x_{\lceil \frac{1}{2}\left(N+\sqrt{N}\right) \rceil} - x_{\lfloor \frac{1}{2}\left(N-\sqrt{N}\right) \rfloor}}{2} \end{align} This can intuitively be understood, because the median value deviates from the middle position in a sorted list of random samples by $\frac{\sqrt{N}}{2}$ on average. Expanding this idea, you can also calculate: \begin{align} \sigma^2_{\tilde{\mu}_s} \approx \sum_{i=0}^{N-1} {N-1 \choose i} \left(\frac{1}{2}\right)^{1-N} \left(x_i - \tilde{\mu}_s\right)^2  \end{align} Analogously to the variance of the sample mean, and weighting the quadratic difference of each sample value by its probability of being the closest value to the true median. The first estimator is easier, faster and more robust, the second may be a little more accurate.
Variance of sample median
Building on the aswer by StasK and assuming that we don't know the distribution: Sort the values ($x_0,..,x_i,..,x_{N-1}$). Then Woodruff (1952) suggests to take the difference between the values at h
Variance of sample median Building on the aswer by StasK and assuming that we don't know the distribution: Sort the values ($x_0,..,x_i,..,x_{N-1}$). Then Woodruff (1952) suggests to take the difference between the values at half the square root of the sample size above and below the sample median $\tilde{\mu}_s$: \begin{align} \sigma_{\tilde{\mu}_s} \approx \dfrac{x_{\lceil \frac{1}{2}\left(N+\sqrt{N}\right) \rceil} - x_{\lfloor \frac{1}{2}\left(N-\sqrt{N}\right) \rfloor}}{2} \end{align} This can intuitively be understood, because the median value deviates from the middle position in a sorted list of random samples by $\frac{\sqrt{N}}{2}$ on average. Expanding this idea, you can also calculate: \begin{align} \sigma^2_{\tilde{\mu}_s} \approx \sum_{i=0}^{N-1} {N-1 \choose i} \left(\frac{1}{2}\right)^{1-N} \left(x_i - \tilde{\mu}_s\right)^2  \end{align} Analogously to the variance of the sample mean, and weighting the quadratic difference of each sample value by its probability of being the closest value to the true median. The first estimator is easier, faster and more robust, the second may be a little more accurate.
Variance of sample median Building on the aswer by StasK and assuming that we don't know the distribution: Sort the values ($x_0,..,x_i,..,x_{N-1}$). Then Woodruff (1952) suggests to take the difference between the values at h
27,378
Choosing c such that log(x + c) would remove skew from the population
Because the intention is to do OLS, the choice of $c$ should be made in this context. In general, we ought to fit $c$ simultaneously with the rest of the regression. A quick and dirty way to do this recognizes that the regression $R^2$ is proportional to the log likelihood, so we could seek a value of $c$ that maximizes $R^2$. This is a special example of the problem of choosing among a parameterized family of transformations $y \to f(y; \theta)$ to achieve the best possible fit of $y$ to explanatory values $x$. This can be solved in R rather simply and directly: xform <- function(f, theta, x, y, ...) { g <- function(theta) -summary(lm(f(y, theta) ~ x))$r.squared nlm(g, theta, ...) } (I am glossing over a somewhat delicate matter of choosing good starting values for the parameter: it is possible to obtain bad solutions with nlm otherwise. Standard methods of exploratory data analysis will produce decent starting values, but that's a subject for another day.) As an example of the use of xform, let's generate some highly skewed data for $y$ for which the "started logarithm" $\log(y+c)$ will produce an unskewed distribution: set.seed(17) y <- sort(exp(rnorm(32, 4, 1))) + 100 Evidently $\log(y-100)$ is drawn iid from a Normal distribution. I will apply xform to three choices of $x$: Values from which $y$ differs by additive, homoscedastic residuals. In this case it would be a mistake to take the logarithm of $y$: it is a grossly incorrect model of the relationship between $x$ and $y$. Values from which $y$ differs by multiplicative lognormal residuals (more or less). In this case, taking the logarithm of $y$ is a good idea because it leads to a model for which OLS regression is appropriate. Constant values of $x$, so that in effect we are looking at $y$ outside of the regression context altogether. In cases (1) and (2) I will plot the histogram of $y$ (to show it is highly skewed), the scatterplot of $y$ against $x$ (to exhibit the data), and the scatterplot of the transformed $y$ against $x$ with the OLS line superimposed, to see the result of the transformation. In the third case those scatterplots are meaningless, so I only report the value of $c$ found by xform. set.seed(17) par(mfrow=c(2,3)) y <- sort(exp(rnorm(32, 4, 1))) + 100 x <- y - rnorm(length(y), 0, 50) hist(y) plot(x,y) const <- xform(function(y,c) log(y+c), 1-min(y), x, y)$estimate plot(x, log(y + const), ylab=sprintf("log(y + %0.1f)", const)) abline(coef(fit1<-lm(log(y+const)~x)), col="Gray") x <- log((1:length(y) + rnorm(length(y), 10, 3))) hist(y) plot(x,y) const <- xform(function(y,c) log(y+c), 1-min(y), x, y)$estimate plot(x, log(y + const), ylab=sprintf("log(y + %0.1f)", const)) abline(coef(fit2<-lm(log(y+const)~x)), col="Gray") x <- rep(1, length(y)) const <- xform(function(y,c) log(y+c), 1-min(y), x, y)$estimate The top row is the first case and the second row of plots are for the second case. Please observe: The $y$ values are identical in all three instances. The $y$ values are constructed from a model in which $c=-100$. The fitted value of $c$ in the first case, $1408392.5$, is essentially infinite. This indicates it's bad to be taking the logarithm at all for these $x$ values. (Adding this huge value of $c$ to $y$ before taking the logarithm basically does not change the shape of the data: that's why the two scatterplots in the top row look the same.) The fitted value of $c$ in the second case, $-104.0$, is close to the value of $-100$ used to generate the data. (Repeated simulations indicate that the fitted value in the second case will be biased slightly low, averaging around $-105$.) The fitted value of $c$ in the third case is $-115.8$, still close to the value used to generate the data. If we were to use the "universal" value of $c$ found in the third case (essentially by ignoring the $x$ values), here is what the scatterplot would look like in conjunction with the $x$ values from case 1: For these particular $x$ values, the OLS line fit to the transformed $y$ values is a terrible description of the relationship between $y$ and $x$. Notice how it underestimates most values of $y$ but grossly overestimates a few of them for $x$ between $140$ and $200$. In summary, if you want to transform the response variable for a regression (to achieve symmetry or linearity), you must account for the regression itself. This is because the regression only "cares" about the residuals, not the raw values of $y$. As the extraordinarily bad value of $c$ in the first case shows, ignoring this advice could produce awful results.
Choosing c such that log(x + c) would remove skew from the population
Because the intention is to do OLS, the choice of $c$ should be made in this context. In general, we ought to fit $c$ simultaneously with the rest of the regression. A quick and dirty way to do this
Choosing c such that log(x + c) would remove skew from the population Because the intention is to do OLS, the choice of $c$ should be made in this context. In general, we ought to fit $c$ simultaneously with the rest of the regression. A quick and dirty way to do this recognizes that the regression $R^2$ is proportional to the log likelihood, so we could seek a value of $c$ that maximizes $R^2$. This is a special example of the problem of choosing among a parameterized family of transformations $y \to f(y; \theta)$ to achieve the best possible fit of $y$ to explanatory values $x$. This can be solved in R rather simply and directly: xform <- function(f, theta, x, y, ...) { g <- function(theta) -summary(lm(f(y, theta) ~ x))$r.squared nlm(g, theta, ...) } (I am glossing over a somewhat delicate matter of choosing good starting values for the parameter: it is possible to obtain bad solutions with nlm otherwise. Standard methods of exploratory data analysis will produce decent starting values, but that's a subject for another day.) As an example of the use of xform, let's generate some highly skewed data for $y$ for which the "started logarithm" $\log(y+c)$ will produce an unskewed distribution: set.seed(17) y <- sort(exp(rnorm(32, 4, 1))) + 100 Evidently $\log(y-100)$ is drawn iid from a Normal distribution. I will apply xform to three choices of $x$: Values from which $y$ differs by additive, homoscedastic residuals. In this case it would be a mistake to take the logarithm of $y$: it is a grossly incorrect model of the relationship between $x$ and $y$. Values from which $y$ differs by multiplicative lognormal residuals (more or less). In this case, taking the logarithm of $y$ is a good idea because it leads to a model for which OLS regression is appropriate. Constant values of $x$, so that in effect we are looking at $y$ outside of the regression context altogether. In cases (1) and (2) I will plot the histogram of $y$ (to show it is highly skewed), the scatterplot of $y$ against $x$ (to exhibit the data), and the scatterplot of the transformed $y$ against $x$ with the OLS line superimposed, to see the result of the transformation. In the third case those scatterplots are meaningless, so I only report the value of $c$ found by xform. set.seed(17) par(mfrow=c(2,3)) y <- sort(exp(rnorm(32, 4, 1))) + 100 x <- y - rnorm(length(y), 0, 50) hist(y) plot(x,y) const <- xform(function(y,c) log(y+c), 1-min(y), x, y)$estimate plot(x, log(y + const), ylab=sprintf("log(y + %0.1f)", const)) abline(coef(fit1<-lm(log(y+const)~x)), col="Gray") x <- log((1:length(y) + rnorm(length(y), 10, 3))) hist(y) plot(x,y) const <- xform(function(y,c) log(y+c), 1-min(y), x, y)$estimate plot(x, log(y + const), ylab=sprintf("log(y + %0.1f)", const)) abline(coef(fit2<-lm(log(y+const)~x)), col="Gray") x <- rep(1, length(y)) const <- xform(function(y,c) log(y+c), 1-min(y), x, y)$estimate The top row is the first case and the second row of plots are for the second case. Please observe: The $y$ values are identical in all three instances. The $y$ values are constructed from a model in which $c=-100$. The fitted value of $c$ in the first case, $1408392.5$, is essentially infinite. This indicates it's bad to be taking the logarithm at all for these $x$ values. (Adding this huge value of $c$ to $y$ before taking the logarithm basically does not change the shape of the data: that's why the two scatterplots in the top row look the same.) The fitted value of $c$ in the second case, $-104.0$, is close to the value of $-100$ used to generate the data. (Repeated simulations indicate that the fitted value in the second case will be biased slightly low, averaging around $-105$.) The fitted value of $c$ in the third case is $-115.8$, still close to the value used to generate the data. If we were to use the "universal" value of $c$ found in the third case (essentially by ignoring the $x$ values), here is what the scatterplot would look like in conjunction with the $x$ values from case 1: For these particular $x$ values, the OLS line fit to the transformed $y$ values is a terrible description of the relationship between $y$ and $x$. Notice how it underestimates most values of $y$ but grossly overestimates a few of them for $x$ between $140$ and $200$. In summary, if you want to transform the response variable for a regression (to achieve symmetry or linearity), you must account for the regression itself. This is because the regression only "cares" about the residuals, not the raw values of $y$. As the extraordinarily bad value of $c$ in the first case shows, ignoring this advice could produce awful results.
Choosing c such that log(x + c) would remove skew from the population Because the intention is to do OLS, the choice of $c$ should be made in this context. In general, we ought to fit $c$ simultaneously with the rest of the regression. A quick and dirty way to do this
27,379
Choosing c such that log(x + c) would remove skew from the population
In a comment, I asserted there is a formula for a constant $c$ which eliminates the "skewness" of a dataset $(y_i)$ upon applying the "started logarithm" $y \to \log(y+c)$. There are many formulas. This answer describes a family of formulas that are extremely simple, fast to compute, robust, and flexible. (Note, though, that another answer I posted explains why you might not want to apply such a formula to the dependent variable in a regression context and gives an alternative for such cases.) Motivation In practice the term "skewness" in the questions usually refers qualitatively to the shape of dataset, not to the sample skewness. The sample skewness (a standardized central third moment) is highly sensitive to even moderate outliers. Procedures that are sensitive to outliers are good procedures only for--letting outliers ruin your analysis. Thus, sample skewness is usually a poor choice to use for exploring or characterizing data. (Yes, there do exist some statistic tests based on skewness, but they tend to be inferior to more robust tests or of limited application.) Instead, pick some low percent $\alpha$--typically between $.05$ and $0.25$--and examine the $\alpha$ and $1-\alpha$ percentiles of the dataset $(y_i)$. Let's call these $q_{-}$ and $q_{+}$, respectively. Let the median of the dataset be $m$. A good measure of symmetry of the data is the difference between the upper spread $q_{+}-m$ and the lower spread $m - q_{-}$: in a perfectly symmetric data set, these two spreads around the median are equal no matter what the value of $\alpha$. Accommodating the reality that almost no dataset is, or can readily be made, symmetric, we anticipate that achieving symmetry of the spreads at the $\alpha$ and $1-\alpha$ percentiles will likely do a good job of symmetrizing the whole dataset, except possibly for some outlying values beyond those percentiles. The formula Here is the signal beauty of this approach: because we seek a monotonic re-expression of the data, say $y_i \to f(y_i,c)$ for a given function $f$ (the logarithm) and parameter $c$ yet to be found, the $\alpha$ percentile of the re-expressed data $(f(y_i,c))$ is (up to a tiny difference related to the discreteness of the data) equal to $f$ applied to the $\alpha$ percentile of $(y_i)$. Therefore, it will suffice to find $c$ so that $$\log(q_{+} + c) - \log(m + c) = \log(m + c) - \log(q_{-} + c).$$ By means of elementary properties of logarithms, this equation implies $$(q_{+} + c)(q_{-} + c) = (m + c)^2.$$ Provided the data are not already symmetric (that is, there actually is a difference in the original spreads), this has at most one solution $$c = \frac{m^2 - q_{+}q_{-}}{q_{+} + q_{-} - 2m}.$$ Because a fixed quantile of $n$ data can be found with $O(n)$ computation, this is a fast procedure. For large datasets, applying this algorithm to a small random sample (as small as a few dozen values) will work fine, leading to an extremely fast constant time algorithm. Implementation There are some messy practical details to deal with if one wants a general-purpose software solution. In order to apply logarithms, we will need all of the $(y_i+c)$ to be positive. Thus, when the solution $c$ is less than or equal to $-\min(\{y_i\})$, some alternative must be found. One reasonable approach includes two things: Return a code to indicate the original solution will not be applicable to all data values and Adjust $c$ to be slightly greater than $-\min(\{y_i\})$. The adjustment should be relative to the range of values in $(y_i)$. That is, we should select some other percent $\beta$ and extrapolate from the $\beta$ percentile of the $(y_i)$ down below $\min(\{y_i\}$ by a tiny proportion $\gamma \gt 0$. That is the solution adopted by the following R function. log.start <- function(y, alpha=0.25, beta=1, gamma=0.01) { # # Find a constant `const` for which log(y+c) is as symmetric # as possible at the `alpha` and 1-alpha percentiles. # Returns a list containing the solution and a code: # Code=0: Constant is good. # Code=1: Data are already symmetric. # Code=2: The best solution is not large enough and has been adjusted. # In this case, the constant is obtained by extrapolating to the # left from the `beta` percentile beyond the minimum value of `y`; # the extrapolation is by a (small, positive) amount `gamma`. # stats <- quantile(y, c(alpha, 1/2, 1-alpha)) code <- 0 if (diff(diff(stats)==0)) { const <- Inf code <- 1 } else { const <- (stats[2]^2 - stats[1]*stats[3]) / (stats[1] + stats[3] - 2*stats[2]) y.min <- min(y) if (const < -y.min) { const <- gamma * quantile(y, beta) - (1+gamma) * y.min code <- 2 } } list(offset=as.numeric(const), code=code) } Example As an example of its use, let's generate data $(y_i)$ for which $\log(y_i+100)$ are iid Normal: set.seed(17) y <- exp(rnorm(32, 4, 1)) + 100 Apply the formula. Here I chose $\alpha=0.10$, in an effort to symmetrize the middle $1-2\alpha$ = $80$% of the data, allowing for as much as $10$% in the upper or lower tails (or both) to exhibit outlying behavior: const <- log.start(y, .10)$offset Display the distributions of the data (in the left column) and the transformed data (in the right column): par(mfrow=c(2,2)) hist(y); hist(log(y + const)) qqnorm(y); qqnorm(log(y + const)) The almost symmetric histogram and nearly linear q-q plot in the right column of graphs show this choice of $c$ (which was $-97.7$, quite close to canceling the value of $100$ used to generate the data) works very well in this instance.
Choosing c such that log(x + c) would remove skew from the population
In a comment, I asserted there is a formula for a constant $c$ which eliminates the "skewness" of a dataset $(y_i)$ upon applying the "started logarithm" $y \to \log(y+c)$. There are many formulas.
Choosing c such that log(x + c) would remove skew from the population In a comment, I asserted there is a formula for a constant $c$ which eliminates the "skewness" of a dataset $(y_i)$ upon applying the "started logarithm" $y \to \log(y+c)$. There are many formulas. This answer describes a family of formulas that are extremely simple, fast to compute, robust, and flexible. (Note, though, that another answer I posted explains why you might not want to apply such a formula to the dependent variable in a regression context and gives an alternative for such cases.) Motivation In practice the term "skewness" in the questions usually refers qualitatively to the shape of dataset, not to the sample skewness. The sample skewness (a standardized central third moment) is highly sensitive to even moderate outliers. Procedures that are sensitive to outliers are good procedures only for--letting outliers ruin your analysis. Thus, sample skewness is usually a poor choice to use for exploring or characterizing data. (Yes, there do exist some statistic tests based on skewness, but they tend to be inferior to more robust tests or of limited application.) Instead, pick some low percent $\alpha$--typically between $.05$ and $0.25$--and examine the $\alpha$ and $1-\alpha$ percentiles of the dataset $(y_i)$. Let's call these $q_{-}$ and $q_{+}$, respectively. Let the median of the dataset be $m$. A good measure of symmetry of the data is the difference between the upper spread $q_{+}-m$ and the lower spread $m - q_{-}$: in a perfectly symmetric data set, these two spreads around the median are equal no matter what the value of $\alpha$. Accommodating the reality that almost no dataset is, or can readily be made, symmetric, we anticipate that achieving symmetry of the spreads at the $\alpha$ and $1-\alpha$ percentiles will likely do a good job of symmetrizing the whole dataset, except possibly for some outlying values beyond those percentiles. The formula Here is the signal beauty of this approach: because we seek a monotonic re-expression of the data, say $y_i \to f(y_i,c)$ for a given function $f$ (the logarithm) and parameter $c$ yet to be found, the $\alpha$ percentile of the re-expressed data $(f(y_i,c))$ is (up to a tiny difference related to the discreteness of the data) equal to $f$ applied to the $\alpha$ percentile of $(y_i)$. Therefore, it will suffice to find $c$ so that $$\log(q_{+} + c) - \log(m + c) = \log(m + c) - \log(q_{-} + c).$$ By means of elementary properties of logarithms, this equation implies $$(q_{+} + c)(q_{-} + c) = (m + c)^2.$$ Provided the data are not already symmetric (that is, there actually is a difference in the original spreads), this has at most one solution $$c = \frac{m^2 - q_{+}q_{-}}{q_{+} + q_{-} - 2m}.$$ Because a fixed quantile of $n$ data can be found with $O(n)$ computation, this is a fast procedure. For large datasets, applying this algorithm to a small random sample (as small as a few dozen values) will work fine, leading to an extremely fast constant time algorithm. Implementation There are some messy practical details to deal with if one wants a general-purpose software solution. In order to apply logarithms, we will need all of the $(y_i+c)$ to be positive. Thus, when the solution $c$ is less than or equal to $-\min(\{y_i\})$, some alternative must be found. One reasonable approach includes two things: Return a code to indicate the original solution will not be applicable to all data values and Adjust $c$ to be slightly greater than $-\min(\{y_i\})$. The adjustment should be relative to the range of values in $(y_i)$. That is, we should select some other percent $\beta$ and extrapolate from the $\beta$ percentile of the $(y_i)$ down below $\min(\{y_i\}$ by a tiny proportion $\gamma \gt 0$. That is the solution adopted by the following R function. log.start <- function(y, alpha=0.25, beta=1, gamma=0.01) { # # Find a constant `const` for which log(y+c) is as symmetric # as possible at the `alpha` and 1-alpha percentiles. # Returns a list containing the solution and a code: # Code=0: Constant is good. # Code=1: Data are already symmetric. # Code=2: The best solution is not large enough and has been adjusted. # In this case, the constant is obtained by extrapolating to the # left from the `beta` percentile beyond the minimum value of `y`; # the extrapolation is by a (small, positive) amount `gamma`. # stats <- quantile(y, c(alpha, 1/2, 1-alpha)) code <- 0 if (diff(diff(stats)==0)) { const <- Inf code <- 1 } else { const <- (stats[2]^2 - stats[1]*stats[3]) / (stats[1] + stats[3] - 2*stats[2]) y.min <- min(y) if (const < -y.min) { const <- gamma * quantile(y, beta) - (1+gamma) * y.min code <- 2 } } list(offset=as.numeric(const), code=code) } Example As an example of its use, let's generate data $(y_i)$ for which $\log(y_i+100)$ are iid Normal: set.seed(17) y <- exp(rnorm(32, 4, 1)) + 100 Apply the formula. Here I chose $\alpha=0.10$, in an effort to symmetrize the middle $1-2\alpha$ = $80$% of the data, allowing for as much as $10$% in the upper or lower tails (or both) to exhibit outlying behavior: const <- log.start(y, .10)$offset Display the distributions of the data (in the left column) and the transformed data (in the right column): par(mfrow=c(2,2)) hist(y); hist(log(y + const)) qqnorm(y); qqnorm(log(y + const)) The almost symmetric histogram and nearly linear q-q plot in the right column of graphs show this choice of $c$ (which was $-97.7$, quite close to canceling the value of $100$ used to generate the data) works very well in this instance.
Choosing c such that log(x + c) would remove skew from the population In a comment, I asserted there is a formula for a constant $c$ which eliminates the "skewness" of a dataset $(y_i)$ upon applying the "started logarithm" $y \to \log(y+c)$. There are many formulas.
27,380
Choosing c such that log(x + c) would remove skew from the population
You could try to minimize the square of the sample skewness with respect to the constant $c$. Here is a quick R program to get the job done, though I'm not sure if this is the best way to go about solving your problem. log.skewness computes the skewness of the transformed data and f returns the square of the skewness of the transformed data. log.skewness <- function(c, x) { y <- log(x+c) mean((y-mean(y))^3)/(mean((y-mean(y))^2))^(3/2) } f <- function(c, x) { log.skewness(c, x)^2 } Here I generate some data, minimize the squared skewness of the transformed data with respect to $c$, and plot the histograms of the original data and the transformed data. set.seed(seed = 1) data <- rexp(100) opt <- optimize(f = f, interval = c(min(data), 1E8), x = data) par(mfrow=c(1,2)) hist(x = data, main = 'Original Data', xlab = '') hist(x = log(data + opt$minimum), main = 'Transformed data', xlab = '') par(mfrow=c(1,1))
Choosing c such that log(x + c) would remove skew from the population
You could try to minimize the square of the sample skewness with respect to the constant $c$. Here is a quick R program to get the job done, though I'm not sure if this is the best way to go about sol
Choosing c such that log(x + c) would remove skew from the population You could try to minimize the square of the sample skewness with respect to the constant $c$. Here is a quick R program to get the job done, though I'm not sure if this is the best way to go about solving your problem. log.skewness computes the skewness of the transformed data and f returns the square of the skewness of the transformed data. log.skewness <- function(c, x) { y <- log(x+c) mean((y-mean(y))^3)/(mean((y-mean(y))^2))^(3/2) } f <- function(c, x) { log.skewness(c, x)^2 } Here I generate some data, minimize the squared skewness of the transformed data with respect to $c$, and plot the histograms of the original data and the transformed data. set.seed(seed = 1) data <- rexp(100) opt <- optimize(f = f, interval = c(min(data), 1E8), x = data) par(mfrow=c(1,2)) hist(x = data, main = 'Original Data', xlab = '') hist(x = log(data + opt$minimum), main = 'Transformed data', xlab = '') par(mfrow=c(1,1))
Choosing c such that log(x + c) would remove skew from the population You could try to minimize the square of the sample skewness with respect to the constant $c$. Here is a quick R program to get the job done, though I'm not sure if this is the best way to go about sol
27,381
What is the point of singular value decomposition?
Singular value decomposition (SVD) is not the same as reducing the dimensionality of the data. It is a method of decomposing a matrix into other matrices that has lots of wonderful properties which I won't go into here. For more on SVD, see the Wikipedia page. Reducing the dimensionality of your data is sometimes very useful. It may be that you have a lot more variables than observations; this is not uncommon in genomic work. It may be that we have several variables that are very highly correlated, e.g., when they are heavily influenced by a small number of underlying factors, and we wish to recover some approximation to the underlying factors. Dimensionality-reducing techniques such as principal component analysis, multidimensional scaling, and canonical variate analysis give us insights into the relationships between observations and/or variables that we might not be able to get any other way. A concrete example: some years ago I was analyzing an employee satisfaction survey that had over 100 questions on it. Well, no manager is ever going to be able to look at 100+ questions worth of answers, even summarized, and do more than guess at what it all means, because who can tell how the answers are related and what is driving them, really? I performed a factor analysis on the data, for which I had over 10,000 observations, and came up with five very clear and readily interpretable factors which could be used to develop manager-specific scores (one for each factor) that would summarize the entirety of the 100+ question survey. A much better solution than the Excel spreadsheet dump that had been the prior method of reporting results!
What is the point of singular value decomposition?
Singular value decomposition (SVD) is not the same as reducing the dimensionality of the data. It is a method of decomposing a matrix into other matrices that has lots of wonderful properties which
What is the point of singular value decomposition? Singular value decomposition (SVD) is not the same as reducing the dimensionality of the data. It is a method of decomposing a matrix into other matrices that has lots of wonderful properties which I won't go into here. For more on SVD, see the Wikipedia page. Reducing the dimensionality of your data is sometimes very useful. It may be that you have a lot more variables than observations; this is not uncommon in genomic work. It may be that we have several variables that are very highly correlated, e.g., when they are heavily influenced by a small number of underlying factors, and we wish to recover some approximation to the underlying factors. Dimensionality-reducing techniques such as principal component analysis, multidimensional scaling, and canonical variate analysis give us insights into the relationships between observations and/or variables that we might not be able to get any other way. A concrete example: some years ago I was analyzing an employee satisfaction survey that had over 100 questions on it. Well, no manager is ever going to be able to look at 100+ questions worth of answers, even summarized, and do more than guess at what it all means, because who can tell how the answers are related and what is driving them, really? I performed a factor analysis on the data, for which I had over 10,000 observations, and came up with five very clear and readily interpretable factors which could be used to develop manager-specific scores (one for each factor) that would summarize the entirety of the 100+ question survey. A much better solution than the Excel spreadsheet dump that had been the prior method of reporting results!
What is the point of singular value decomposition? Singular value decomposition (SVD) is not the same as reducing the dimensionality of the data. It is a method of decomposing a matrix into other matrices that has lots of wonderful properties which
27,382
What is the point of singular value decomposition?
Regarding your secont point of the question, benefits of dimensionality reduction for a data set may be: reduce the storage space needed speed up computation (for example in machine learning algorithms), less dimensions mean les computing, also less dimensions can allow usage of algorithms unfit for a large number of dimensions remove redundant features, for example no point in storing a terrain's size in both sq meters and sq miles (maybe data gathering was flawed) reducing a data's dimension to 2D or 3D may allow us to plot and visualize it, maybe observe patterns, give us insights Other than that, beyond PCA, SVD's has many applications in Signals Processing, NLP and many more
What is the point of singular value decomposition?
Regarding your secont point of the question, benefits of dimensionality reduction for a data set may be: reduce the storage space needed speed up computation (for example in machine learning algorith
What is the point of singular value decomposition? Regarding your secont point of the question, benefits of dimensionality reduction for a data set may be: reduce the storage space needed speed up computation (for example in machine learning algorithms), less dimensions mean les computing, also less dimensions can allow usage of algorithms unfit for a large number of dimensions remove redundant features, for example no point in storing a terrain's size in both sq meters and sq miles (maybe data gathering was flawed) reducing a data's dimension to 2D or 3D may allow us to plot and visualize it, maybe observe patterns, give us insights Other than that, beyond PCA, SVD's has many applications in Signals Processing, NLP and many more
What is the point of singular value decomposition? Regarding your secont point of the question, benefits of dimensionality reduction for a data set may be: reduce the storage space needed speed up computation (for example in machine learning algorith
27,383
What is the point of singular value decomposition?
Take a look at this answer of mine. The singular value decomposition is a key component of principal components analysis, which is a very useful and very powerful data analysis technique. It is often used in facial recognition algorithms, and I make frequent use of it in my day job as a hedge fund analyst.
What is the point of singular value decomposition?
Take a look at this answer of mine. The singular value decomposition is a key component of principal components analysis, which is a very useful and very powerful data analysis technique. It is often
What is the point of singular value decomposition? Take a look at this answer of mine. The singular value decomposition is a key component of principal components analysis, which is a very useful and very powerful data analysis technique. It is often used in facial recognition algorithms, and I make frequent use of it in my day job as a hedge fund analyst.
What is the point of singular value decomposition? Take a look at this answer of mine. The singular value decomposition is a key component of principal components analysis, which is a very useful and very powerful data analysis technique. It is often
27,384
What is "reject inferencing" and how can it be used to increase the accuracy of a model?
In credit model building, reject inferencing is the process of inferring the performance of credit accounts that were rejected in the application process. When building an application credit risk model, we want to build a model that has "through-the-door" applicability, i.e., we input all of the application data into the credit risk model, and the model outputs a risk rating or a probability of default. The problem when using regression to build a model from past data is that we know the performance of the account only for past accepted applications. However, we don't know the performance of the rejects, because after applying we sent them back out the door. This can result in selection bias in our model, because if we only use past "accepts" in our model, the model might not perform well on the "through-the-door" population. There are many ways to deal with reject inferencing, all of them controversial. I'll mention two simple ones here. "Define past rejects as bad" Parceling "Define past rejects as bad" is simply taking all of the rejected application data, and instead of discarding it when building the model, assign all of them as bad. This method heavily biases the model towards the past accept/reject policy. "Parceling" is a little bit more sophisticated. It consists of Build the regression model with the past "accepts" Apply the model to the past rejects to assign risk ratings to them Using the expected probability of default for each risk rating, assign the rejected applications to being either good or bad. E.g., if the risk rating has a probability of default of 10%, and there are 100 rejected applications that fall into this risk rating, assign 10 of the rejects to "bad" and 90 of the rejects to "good". Rebuild the regression model using the accepted applications and now the inferred performance of the rejected applications There are different ways to do the assignments to good or bad in step 3, and this process can also be applied iteratively. As stated earlier, the use of reject inferencing is controversial, and it's difficult to give a straightforward answer on how it can be used to increase accuracy of models. I'll simply quote some others on this matter. Jonathan Crook and John Banasik, Does Reject Inference Really Improve the Performance of Application Scoring Models? First, even where a very large proportion of applicants are rejected, the scope for improving on a model parameterised only on those accepted appears modest. Where the rejection rate is not so large, that scope appears to be very small indeed. David Hand, "Direct Inference in Credit Operations", appearing in Handbook of Credit Scoring, 2001 Several methods have been proposed and are used and, while some of them are clearly poor and should never be recommended, there is no unique best method of universal applicability unless extra information is obtained. That is, the best solution is to obtain more information (perhaps by granting loans to some potential rejects) about those applicants who fall in the reject region.
What is "reject inferencing" and how can it be used to increase the accuracy of a model?
In credit model building, reject inferencing is the process of inferring the performance of credit accounts that were rejected in the application process. When building an application credit risk mode
What is "reject inferencing" and how can it be used to increase the accuracy of a model? In credit model building, reject inferencing is the process of inferring the performance of credit accounts that were rejected in the application process. When building an application credit risk model, we want to build a model that has "through-the-door" applicability, i.e., we input all of the application data into the credit risk model, and the model outputs a risk rating or a probability of default. The problem when using regression to build a model from past data is that we know the performance of the account only for past accepted applications. However, we don't know the performance of the rejects, because after applying we sent them back out the door. This can result in selection bias in our model, because if we only use past "accepts" in our model, the model might not perform well on the "through-the-door" population. There are many ways to deal with reject inferencing, all of them controversial. I'll mention two simple ones here. "Define past rejects as bad" Parceling "Define past rejects as bad" is simply taking all of the rejected application data, and instead of discarding it when building the model, assign all of them as bad. This method heavily biases the model towards the past accept/reject policy. "Parceling" is a little bit more sophisticated. It consists of Build the regression model with the past "accepts" Apply the model to the past rejects to assign risk ratings to them Using the expected probability of default for each risk rating, assign the rejected applications to being either good or bad. E.g., if the risk rating has a probability of default of 10%, and there are 100 rejected applications that fall into this risk rating, assign 10 of the rejects to "bad" and 90 of the rejects to "good". Rebuild the regression model using the accepted applications and now the inferred performance of the rejected applications There are different ways to do the assignments to good or bad in step 3, and this process can also be applied iteratively. As stated earlier, the use of reject inferencing is controversial, and it's difficult to give a straightforward answer on how it can be used to increase accuracy of models. I'll simply quote some others on this matter. Jonathan Crook and John Banasik, Does Reject Inference Really Improve the Performance of Application Scoring Models? First, even where a very large proportion of applicants are rejected, the scope for improving on a model parameterised only on those accepted appears modest. Where the rejection rate is not so large, that scope appears to be very small indeed. David Hand, "Direct Inference in Credit Operations", appearing in Handbook of Credit Scoring, 2001 Several methods have been proposed and are used and, while some of them are clearly poor and should never be recommended, there is no unique best method of universal applicability unless extra information is obtained. That is, the best solution is to obtain more information (perhaps by granting loans to some potential rejects) about those applicants who fall in the reject region.
What is "reject inferencing" and how can it be used to increase the accuracy of a model? In credit model building, reject inferencing is the process of inferring the performance of credit accounts that were rejected in the application process. When building an application credit risk mode
27,385
What is "reject inferencing" and how can it be used to increase the accuracy of a model?
@GabyLP in previous comments. Based on my experience you can split such clients in two parts and assign weights for both of the splits according to probability. For example if a rejected client has 10% PD you can make two clients out of this one. First having target variable 1 and weight 0.1 and second having target variable 0 and weight 0.9. The whole accepted sample of clients will have weights == 1. While this works with logistic regression, it does not work with tree based models.
What is "reject inferencing" and how can it be used to increase the accuracy of a model?
@GabyLP in previous comments. Based on my experience you can split such clients in two parts and assign weights for both of the splits according to probability. For example if a rejected client has 10
What is "reject inferencing" and how can it be used to increase the accuracy of a model? @GabyLP in previous comments. Based on my experience you can split such clients in two parts and assign weights for both of the splits according to probability. For example if a rejected client has 10% PD you can make two clients out of this one. First having target variable 1 and weight 0.1 and second having target variable 0 and weight 0.9. The whole accepted sample of clients will have weights == 1. While this works with logistic regression, it does not work with tree based models.
What is "reject inferencing" and how can it be used to increase the accuracy of a model? @GabyLP in previous comments. Based on my experience you can split such clients in two parts and assign weights for both of the splits according to probability. For example if a rejected client has 10
27,386
Why is the Tukey's IQR not used in the R program?
Appropriate methods for computing quantiles are a deep rabbit hole. quantile() provides 9 separate methods for computing the quantile; of these 9, 4/9 give the result of 33 that you're expecting: sapply(1:9, \(t) quantile(x, 0.25, type = t)) |> setNames(1:9) 1 2 3 4 5 6 7 8 33.00000 33.00000 33.00000 27.25000 37.25000 33.00000 41.50000 35.83333 9 36.18750 The type argument can also be passed to IQR(): sapply(1:9, \(t) IQR(x, type = t)) [1] 1973.000 1973.000 954.000 1214.500 1714.000 1973.000 1455.000 1800.333 [9] 1778.750 Only 3/9 (types 1, 2, 6) give your result. (Type 7 is R's default.) ?quantile (and especially Hyndman and Fan 1996, referenced therein) give much more detail about the different definitions. PS I don't think Normality has anything to do with it ... While I'm at it, I would be interested if anyone could clarify (in a separate answer or in comments) what "Tukey's recommendations" are in the help for ?IQR: Exploratory Data Analysis is available for checkout at the Internet Archive, but I haven't yet located the precise advice that the R documentation is referring to ...
Why is the Tukey's IQR not used in the R program?
Appropriate methods for computing quantiles are a deep rabbit hole. quantile() provides 9 separate methods for computing the quantile; of these 9, 4/9 give the result of 33 that you're expecting: sapp
Why is the Tukey's IQR not used in the R program? Appropriate methods for computing quantiles are a deep rabbit hole. quantile() provides 9 separate methods for computing the quantile; of these 9, 4/9 give the result of 33 that you're expecting: sapply(1:9, \(t) quantile(x, 0.25, type = t)) |> setNames(1:9) 1 2 3 4 5 6 7 8 33.00000 33.00000 33.00000 27.25000 37.25000 33.00000 41.50000 35.83333 9 36.18750 The type argument can also be passed to IQR(): sapply(1:9, \(t) IQR(x, type = t)) [1] 1973.000 1973.000 954.000 1214.500 1714.000 1973.000 1455.000 1800.333 [9] 1778.750 Only 3/9 (types 1, 2, 6) give your result. (Type 7 is R's default.) ?quantile (and especially Hyndman and Fan 1996, referenced therein) give much more detail about the different definitions. PS I don't think Normality has anything to do with it ... While I'm at it, I would be interested if anyone could clarify (in a separate answer or in comments) what "Tukey's recommendations" are in the help for ?IQR: Exploratory Data Analysis is available for checkout at the Internet Archive, but I haven't yet located the precise advice that the R documentation is referring to ...
Why is the Tukey's IQR not used in the R program? Appropriate methods for computing quantiles are a deep rabbit hole. quantile() provides 9 separate methods for computing the quantile; of these 9, 4/9 give the result of 33 that you're expecting: sapp
27,387
Why is the Tukey's IQR not used in the R program?
Ben Bolker's answer explains why the quantile() function, and thus the IQR, may not return the values you expect. However, I think you've misunderstood the documentation about normality. Only the "Type 9" method for quantile and IQR is intended for normally-distributed data, where it provides a median-unbiased estimate (docs here). The default is Type 7. Instead, the IQR documentation is hinting at a method for robustly estimating the standard deviation of samples from a normal distribution. You might be tempted to do so by plugging the values directly into the (Bessel-corrected) definition: $$ s = \sqrt{\frac{1}{n-1} \sum_{i=0}^{N} \left(x_i - \bar{x}\right)^2} $$ However, this can go badly wrong with noisy data. The mean $\bar{x}$ is extremely sensitive to outliers. In fact, even in a single outlier is enough to make $\bar{x}$ take on any value. Robust methods can provide more sensible estimates of the SD. One popular way to do so for normally distributed data is to calculate the IQR and divide it by 1.349. This trick exploits the fact that, for a standard normal distribution, the 1st and 3rd quartiles occur at $\approx \pm 0.67449$). Thus, if you know the data is normal(ish) and the IQR that it spans, you can divide that IQR by 0.67449 * 2, or 1.349, and approximate the SD. There are other robust methods based around the median absolute deviation or pairwise differences. These are useful because the order statistics are much more resilient: changing one value has almost no effect on the median. For example, you'd need to change >50% of them instead to set it to an arbitrary value.
Why is the Tukey's IQR not used in the R program?
Ben Bolker's answer explains why the quantile() function, and thus the IQR, may not return the values you expect. However, I think you've misunderstood the documentation about normality. Only the "Typ
Why is the Tukey's IQR not used in the R program? Ben Bolker's answer explains why the quantile() function, and thus the IQR, may not return the values you expect. However, I think you've misunderstood the documentation about normality. Only the "Type 9" method for quantile and IQR is intended for normally-distributed data, where it provides a median-unbiased estimate (docs here). The default is Type 7. Instead, the IQR documentation is hinting at a method for robustly estimating the standard deviation of samples from a normal distribution. You might be tempted to do so by plugging the values directly into the (Bessel-corrected) definition: $$ s = \sqrt{\frac{1}{n-1} \sum_{i=0}^{N} \left(x_i - \bar{x}\right)^2} $$ However, this can go badly wrong with noisy data. The mean $\bar{x}$ is extremely sensitive to outliers. In fact, even in a single outlier is enough to make $\bar{x}$ take on any value. Robust methods can provide more sensible estimates of the SD. One popular way to do so for normally distributed data is to calculate the IQR and divide it by 1.349. This trick exploits the fact that, for a standard normal distribution, the 1st and 3rd quartiles occur at $\approx \pm 0.67449$). Thus, if you know the data is normal(ish) and the IQR that it spans, you can divide that IQR by 0.67449 * 2, or 1.349, and approximate the SD. There are other robust methods based around the median absolute deviation or pairwise differences. These are useful because the order statistics are much more resilient: changing one value has almost no effect on the median. For example, you'd need to change >50% of them instead to set it to an arbitrary value.
Why is the Tukey's IQR not used in the R program? Ben Bolker's answer explains why the quantile() function, and thus the IQR, may not return the values you expect. However, I think you've misunderstood the documentation about normality. Only the "Typ
27,388
The probability of y < x * z, if x,y, z independent and normally distributed
Conditional on $Z=z$, $$ P(X<YZ|Z=z) =P(X-Yz<0|Z=z) =1/2 $$ since $X-Yz$ is normally distributed with mean zero. Hence, using the law of total probability, $$ P(X<YZ)=E(P(X<YZ|Z))=E(1/2) = 1/2. $$
The probability of y < x * z, if x,y, z independent and normally distributed
Conditional on $Z=z$, $$ P(X<YZ|Z=z) =P(X-Yz<0|Z=z) =1/2 $$ since $X-Yz$ is normally distributed with mean zero. Hence, using the law of total probability, $$ P(X<YZ)=E(P(X<YZ|Z))=E(1/2) = 1/2. $$
The probability of y < x * z, if x,y, z independent and normally distributed Conditional on $Z=z$, $$ P(X<YZ|Z=z) =P(X-Yz<0|Z=z) =1/2 $$ since $X-Yz$ is normally distributed with mean zero. Hence, using the law of total probability, $$ P(X<YZ)=E(P(X<YZ|Z))=E(1/2) = 1/2. $$
The probability of y < x * z, if x,y, z independent and normally distributed Conditional on $Z=z$, $$ P(X<YZ|Z=z) =P(X-Yz<0|Z=z) =1/2 $$ since $X-Yz$ is normally distributed with mean zero. Hence, using the law of total probability, $$ P(X<YZ)=E(P(X<YZ|Z))=E(1/2) = 1/2. $$
27,389
Is least squares means (lsmeans) statistical nonsense?
The short answer is that LS means (or more modernly, estimated marginal means) are incredibly useful with experimental data. With observational data, not so much. A long-winded explanation follows. The underlying ideas are very old (and predate SAS by at least 50 years). Look at a standard experimental design textbook -- pretty much any of them. Such a book has initial chapters on one-way CRDs, focusing especially on balanced designs. Then they move on to factorial designs, and it is a 2-way factorial I will discuss the most. For that, we randomize experimental units to combinations of the levels of two factors $A$ and $B$, and consider analyzing a model of the form $$ Y_{ijk} = \mu_{ij} + E_{ijk}, \quad i=1,2,...,a;\quad j=1,2,...,b;\quad k=1,2,...,n_{ij} $$ where $Y_{ijk}$ is the $k$th observation at the $i$th level of $A$, $j$th level of $B$, the $\mu_{ij}$ are the cell means, and $E_{ijk}$ are random errors, typically assumed to be iid normal. Emphasis is usually placed on balanced experiments, where the $n_{ij}$ are all equal. We proceed to talk about partitioning the total sum of squares into components attributable to marginal effects of $A$, marginal effects of $B$, perhaps interaction effects, and residual error. If the interactions are not strong, we are attracted to an additive model whereby $\mu_{ij} = \mu + \alpha_i + \beta_j$; in that case, interpretation is simpler because the effects of $A$ and $B$ can be considered independently. Evaluating these effects can be expressed in terms of the marginal means for $A$, $\mu_{i.}=\mu+\alpha_i$, and for $B$, $\mu_{.j}=\mu+\beta_j$; and perhaps pairwise comparisons thereof. In a balanced design, these marginal means may be estimated as the marginal means of the data: $\bar Y_{i..}$ and $\bar Y_{.j.}$. Balanced experiments lie in very foundational places in statistics, including the writings of Fisher, Youden, Snedecor, Cochran, Cox, Box, and Tukey. But what if it isn't a balanced experiment? For example, a few observations were lost (completely at random). In very old design texts, what was suggested in some cases was the "method of unweighted means", whereby we use the values of $\bar Y_{ij.}$ and construct an analysis of those cell means as if they were data from a balanced experiment with $\tilde n$ observations per cell (where, typically, $\tilde n$ is the harmonic mean of the cell sample sizes). This is far preferable to just computing marginal means of the data, because some cells receive more weight than others, which can produce Simpson's-paradox-like effects. "Least-square means" are essentially a model-based version of unweighted means. They were developed by Walter Harvey in a technical report in 1960 and finally published as Walter R. Harvey (1982), "Least-Squares Analysis of Discrete Data," Journal of Animal Science, 54(5), 1067–1071, https://doi.org/10.2527/jas1982.5451067x. They were indeed implemented in SAS in an add-on procedure called PROC HARVEY, not long after the first (1972) edition of SAS was released, and then later implemented as part of the new PROC GLM released in SAS75. You may also want to take a look at a 2014 retrospective by Weijie Cai. Again, LS means are essentially the same idea as unweighted means, which is a very, very old idea. In LS means, we fit a model to the data and use it (in the two-way factorial case) to predict the $\mu_{ij}$; then our marginal means are estimated as equally-weighted marginal averages of these predictions, just as in unweighted-means analysis. But these LS means are linear functions of the model predictions, and hence of the regression coefficients; so they can be estimated from the model with no need for ad hoc quantities like $\tilde n$. The idea extends to other experimental designs, such as Latin squares, split-plots, etc., and even to covariance models (where typically we make predictions at the mean of each covariate). You can also generalize these ideas to experimental data analyzed with other types of models, including generalized linear models, ordinal models and multinomial models, zero-inflated models, etc. And the ideas can be applied to Bayesian models fitted via MCMC methods, simply by computing the relevant quantities from the posterior predictions. Is this useful? Definitely yes, when the model is additive and/or the interaction effects are small. They mimic the types of analyses proposed for balanced experiments by the giants among our forebears. If, on the other hand, we do have sizeable interaction effects, then (as our forebears recommend) we simply should not even consider estimating marginal means. (In a multi-factor experiment, it may still be reasonable to construct some marginal means where we are averaging only over negligible interaction effects). In the situation where you have data sampled from a population, then LS means or EMMs may very well be entirely inappropriate. They certainly don't estimate the marginal means of your population because the equal weighting is not appropriate. The emmeans package provides various alternative weighting schemes, and some may be suited for a particular purpose; or not. What about type III sums of squares? What I would say is that you need to consider whether they are appropriate for an individual situation. SAS defines these in terms of estimable functions, and a given set of estimable functions corresponds to a family of contrasts that can usually be expressed as contrasts among LS means. If that family of contrasts is of interest, then the associated type III test is fine; and if not, it's not fine. And again, this has to do with the appropriateness of the LS means being considered. I personally shy away from type III tests, but that is because I don't use omnibus tests for anything but model selection. An additional reference is Searle, Speed, and Milliken (1980), "Population marginal means in the linear model: An alternative to least squares means", The American Statistician 34(4), 216-221, doi:10.1080/00031305.1980.10483031, where they critique Harvey's method and propose the term "estimated marginal means." They also discuss instances where there are empty cells. In that part, I personally think they do it all wrong, but it depends of course on what you are trying to accomplish (if the cells are empty because those factor combinations actually cannot happen, then what they do is more defensible). In general, empty cells can be terribly problematic, and the emmeans package deals with them in terms of assessing estimability of the specified quantities. I would also say that there is a definite anti-SAS attitude among some members of the R community (and S and S-Plus before R). This is unfortunate, because SAS is carefully developed under the direction of many top professional statisticians. It is well documented and its code is solid and reliable for what it does. There are definite reasons I prefer R to SAS myself, not the least of which is that SAS cannot quite escape some very old ruts. But I would like to encourage users to adopt a less tribal attitude about statistical software.
Is least squares means (lsmeans) statistical nonsense?
The short answer is that LS means (or more modernly, estimated marginal means) are incredibly useful with experimental data. With observational data, not so much. A long-winded explanation follows. Th
Is least squares means (lsmeans) statistical nonsense? The short answer is that LS means (or more modernly, estimated marginal means) are incredibly useful with experimental data. With observational data, not so much. A long-winded explanation follows. The underlying ideas are very old (and predate SAS by at least 50 years). Look at a standard experimental design textbook -- pretty much any of them. Such a book has initial chapters on one-way CRDs, focusing especially on balanced designs. Then they move on to factorial designs, and it is a 2-way factorial I will discuss the most. For that, we randomize experimental units to combinations of the levels of two factors $A$ and $B$, and consider analyzing a model of the form $$ Y_{ijk} = \mu_{ij} + E_{ijk}, \quad i=1,2,...,a;\quad j=1,2,...,b;\quad k=1,2,...,n_{ij} $$ where $Y_{ijk}$ is the $k$th observation at the $i$th level of $A$, $j$th level of $B$, the $\mu_{ij}$ are the cell means, and $E_{ijk}$ are random errors, typically assumed to be iid normal. Emphasis is usually placed on balanced experiments, where the $n_{ij}$ are all equal. We proceed to talk about partitioning the total sum of squares into components attributable to marginal effects of $A$, marginal effects of $B$, perhaps interaction effects, and residual error. If the interactions are not strong, we are attracted to an additive model whereby $\mu_{ij} = \mu + \alpha_i + \beta_j$; in that case, interpretation is simpler because the effects of $A$ and $B$ can be considered independently. Evaluating these effects can be expressed in terms of the marginal means for $A$, $\mu_{i.}=\mu+\alpha_i$, and for $B$, $\mu_{.j}=\mu+\beta_j$; and perhaps pairwise comparisons thereof. In a balanced design, these marginal means may be estimated as the marginal means of the data: $\bar Y_{i..}$ and $\bar Y_{.j.}$. Balanced experiments lie in very foundational places in statistics, including the writings of Fisher, Youden, Snedecor, Cochran, Cox, Box, and Tukey. But what if it isn't a balanced experiment? For example, a few observations were lost (completely at random). In very old design texts, what was suggested in some cases was the "method of unweighted means", whereby we use the values of $\bar Y_{ij.}$ and construct an analysis of those cell means as if they were data from a balanced experiment with $\tilde n$ observations per cell (where, typically, $\tilde n$ is the harmonic mean of the cell sample sizes). This is far preferable to just computing marginal means of the data, because some cells receive more weight than others, which can produce Simpson's-paradox-like effects. "Least-square means" are essentially a model-based version of unweighted means. They were developed by Walter Harvey in a technical report in 1960 and finally published as Walter R. Harvey (1982), "Least-Squares Analysis of Discrete Data," Journal of Animal Science, 54(5), 1067–1071, https://doi.org/10.2527/jas1982.5451067x. They were indeed implemented in SAS in an add-on procedure called PROC HARVEY, not long after the first (1972) edition of SAS was released, and then later implemented as part of the new PROC GLM released in SAS75. You may also want to take a look at a 2014 retrospective by Weijie Cai. Again, LS means are essentially the same idea as unweighted means, which is a very, very old idea. In LS means, we fit a model to the data and use it (in the two-way factorial case) to predict the $\mu_{ij}$; then our marginal means are estimated as equally-weighted marginal averages of these predictions, just as in unweighted-means analysis. But these LS means are linear functions of the model predictions, and hence of the regression coefficients; so they can be estimated from the model with no need for ad hoc quantities like $\tilde n$. The idea extends to other experimental designs, such as Latin squares, split-plots, etc., and even to covariance models (where typically we make predictions at the mean of each covariate). You can also generalize these ideas to experimental data analyzed with other types of models, including generalized linear models, ordinal models and multinomial models, zero-inflated models, etc. And the ideas can be applied to Bayesian models fitted via MCMC methods, simply by computing the relevant quantities from the posterior predictions. Is this useful? Definitely yes, when the model is additive and/or the interaction effects are small. They mimic the types of analyses proposed for balanced experiments by the giants among our forebears. If, on the other hand, we do have sizeable interaction effects, then (as our forebears recommend) we simply should not even consider estimating marginal means. (In a multi-factor experiment, it may still be reasonable to construct some marginal means where we are averaging only over negligible interaction effects). In the situation where you have data sampled from a population, then LS means or EMMs may very well be entirely inappropriate. They certainly don't estimate the marginal means of your population because the equal weighting is not appropriate. The emmeans package provides various alternative weighting schemes, and some may be suited for a particular purpose; or not. What about type III sums of squares? What I would say is that you need to consider whether they are appropriate for an individual situation. SAS defines these in terms of estimable functions, and a given set of estimable functions corresponds to a family of contrasts that can usually be expressed as contrasts among LS means. If that family of contrasts is of interest, then the associated type III test is fine; and if not, it's not fine. And again, this has to do with the appropriateness of the LS means being considered. I personally shy away from type III tests, but that is because I don't use omnibus tests for anything but model selection. An additional reference is Searle, Speed, and Milliken (1980), "Population marginal means in the linear model: An alternative to least squares means", The American Statistician 34(4), 216-221, doi:10.1080/00031305.1980.10483031, where they critique Harvey's method and propose the term "estimated marginal means." They also discuss instances where there are empty cells. In that part, I personally think they do it all wrong, but it depends of course on what you are trying to accomplish (if the cells are empty because those factor combinations actually cannot happen, then what they do is more defensible). In general, empty cells can be terribly problematic, and the emmeans package deals with them in terms of assessing estimability of the specified quantities. I would also say that there is a definite anti-SAS attitude among some members of the R community (and S and S-Plus before R). This is unfortunate, because SAS is carefully developed under the direction of many top professional statisticians. It is well documented and its code is solid and reliable for what it does. There are definite reasons I prefer R to SAS myself, not the least of which is that SAS cannot quite escape some very old ruts. But I would like to encourage users to adopt a less tribal attitude about statistical software.
Is least squares means (lsmeans) statistical nonsense? The short answer is that LS means (or more modernly, estimated marginal means) are incredibly useful with experimental data. With observational data, not so much. A long-winded explanation follows. Th
27,390
Meaning of standard error of the coefficients in a regression model?
The standard error is the square root of an estimate of the sampling variability of $\hat\beta_j$ as an estimator of $\beta_j$, or $\sqrt{\widehat{Var}(\hat\beta_j)}$. As this is many things in one sentence, step-by-step: "Square-root": should be self-explanatory, to turn a variance into a standard deviation (that turns out to be what we need in, for example, t-statistics and confidence intervals). "$\hat\beta_j$ as an estimator of $\beta_j$": we use the LS estimator to estimate the unknown parameter $\beta_j$. To do so, we make use of a sample from the underlying population. Had we drawn another sample (or were to draw a fresh one tomorrow, etc.) we would get another estimate $\hat\beta_j$. This is the source of sampling variability. We may summarize that variability through the variance, $Var(\hat\beta_j)$. An expression for this variance may be found, e.g., here. "An estimate of the sampling variability": $Var(\hat\beta_j)$ depends on unknown quantities (like the variance of the Gaussian noise that you generated), which must therefore be estimated, as captured by the formula $\widehat{Var}(\hat\beta_j)$. A formula for this estimator is, for example, given here, or, more introductory, here.
Meaning of standard error of the coefficients in a regression model?
The standard error is the square root of an estimate of the sampling variability of $\hat\beta_j$ as an estimator of $\beta_j$, or $\sqrt{\widehat{Var}(\hat\beta_j)}$. As this is many things in one se
Meaning of standard error of the coefficients in a regression model? The standard error is the square root of an estimate of the sampling variability of $\hat\beta_j$ as an estimator of $\beta_j$, or $\sqrt{\widehat{Var}(\hat\beta_j)}$. As this is many things in one sentence, step-by-step: "Square-root": should be self-explanatory, to turn a variance into a standard deviation (that turns out to be what we need in, for example, t-statistics and confidence intervals). "$\hat\beta_j$ as an estimator of $\beta_j$": we use the LS estimator to estimate the unknown parameter $\beta_j$. To do so, we make use of a sample from the underlying population. Had we drawn another sample (or were to draw a fresh one tomorrow, etc.) we would get another estimate $\hat\beta_j$. This is the source of sampling variability. We may summarize that variability through the variance, $Var(\hat\beta_j)$. An expression for this variance may be found, e.g., here. "An estimate of the sampling variability": $Var(\hat\beta_j)$ depends on unknown quantities (like the variance of the Gaussian noise that you generated), which must therefore be estimated, as captured by the formula $\widehat{Var}(\hat\beta_j)$. A formula for this estimator is, for example, given here, or, more introductory, here.
Meaning of standard error of the coefficients in a regression model? The standard error is the square root of an estimate of the sampling variability of $\hat\beta_j$ as an estimator of $\beta_j$, or $\sqrt{\widehat{Var}(\hat\beta_j)}$. As this is many things in one se
27,391
Meaning of standard error of the coefficients in a regression model?
It’s the usual definition of the standard error: the (estimated) standard deviation of the sampling distribution of $\hat{\beta}_0$. If you were to replicate the work many times with new observations, you would get a distribution of values. Sometimes it would be higher than you observed this time, sometimes lower. We use the standard error in parameter inference. Being loose, if the p-value on the parameter is less than $0.05$, corresponding to a point estimate about $2$ standard errors above or below $0$, then we might say that the population parameter is not zero, so that variable has a measurable impact on the outcome. (There are all sorts of caveats about p-values, and discussing them really warrants a separate question (or a master’s degree in statistics).)
Meaning of standard error of the coefficients in a regression model?
It’s the usual definition of the standard error: the (estimated) standard deviation of the sampling distribution of $\hat{\beta}_0$. If you were to replicate the work many times with new observations,
Meaning of standard error of the coefficients in a regression model? It’s the usual definition of the standard error: the (estimated) standard deviation of the sampling distribution of $\hat{\beta}_0$. If you were to replicate the work many times with new observations, you would get a distribution of values. Sometimes it would be higher than you observed this time, sometimes lower. We use the standard error in parameter inference. Being loose, if the p-value on the parameter is less than $0.05$, corresponding to a point estimate about $2$ standard errors above or below $0$, then we might say that the population parameter is not zero, so that variable has a measurable impact on the outcome. (There are all sorts of caveats about p-values, and discussing them really warrants a separate question (or a master’s degree in statistics).)
Meaning of standard error of the coefficients in a regression model? It’s the usual definition of the standard error: the (estimated) standard deviation of the sampling distribution of $\hat{\beta}_0$. If you were to replicate the work many times with new observations,
27,392
Meaning of standard error of the coefficients in a regression model?
If \begin{align} \hat \beta_0 & = 1.21054 \quad \text{with Std. Error} = 0.11508, \\ \hat \beta_1 & = 1.87723 \quad \text{with Std. Error} = 0.09844. \end{align} it means that the range of values for the coefficient estimates are $$\hat \beta_0 = 1.21054 \pm 0.11508$$ and $$\hat \beta_1 = 1.87723 \pm 0.09844$$ In other words, you can be confident that $\beta_0$ can take on values between $1.09546$ and $1.32562$. As for your repeated question of But for a single sample in isolation: what does it tell me when the coefficient is 1.21054 with a standard error of 0.11508 it is not relevant because the $\beta$s (and therefore the $\sigma(\beta)$s) are computed based on the entire sample set, not from one specific observation. A $\beta$ relates the entire $y$ sample set with the entire sample set being input for (one of) the corresponding $x$ vector. I think what you mean to ask is, what does $\hat \beta_0 = 1.21054 \pm 0.11508$ mean for the output $\hat{y}$ of my fitted model if a new sample $x_i=0.2$ is observed. Well, since $y = \beta_0 x + \beta_0 x + \epsilon$, then the predicted output given that new input is $$\hat{y}_i = (1.21054 \pm 0.11508) \times 0.2 + (\beta_1 \pm \sigma(\beta_1))\times 0.2 + \epsilon$$
Meaning of standard error of the coefficients in a regression model?
If \begin{align} \hat \beta_0 & = 1.21054 \quad \text{with Std. Error} = 0.11508, \\ \hat \beta_1 & = 1.87723 \quad \text{with Std. Error} = 0.09844. \end{align} it means that the range of values for
Meaning of standard error of the coefficients in a regression model? If \begin{align} \hat \beta_0 & = 1.21054 \quad \text{with Std. Error} = 0.11508, \\ \hat \beta_1 & = 1.87723 \quad \text{with Std. Error} = 0.09844. \end{align} it means that the range of values for the coefficient estimates are $$\hat \beta_0 = 1.21054 \pm 0.11508$$ and $$\hat \beta_1 = 1.87723 \pm 0.09844$$ In other words, you can be confident that $\beta_0$ can take on values between $1.09546$ and $1.32562$. As for your repeated question of But for a single sample in isolation: what does it tell me when the coefficient is 1.21054 with a standard error of 0.11508 it is not relevant because the $\beta$s (and therefore the $\sigma(\beta)$s) are computed based on the entire sample set, not from one specific observation. A $\beta$ relates the entire $y$ sample set with the entire sample set being input for (one of) the corresponding $x$ vector. I think what you mean to ask is, what does $\hat \beta_0 = 1.21054 \pm 0.11508$ mean for the output $\hat{y}$ of my fitted model if a new sample $x_i=0.2$ is observed. Well, since $y = \beta_0 x + \beta_0 x + \epsilon$, then the predicted output given that new input is $$\hat{y}_i = (1.21054 \pm 0.11508) \times 0.2 + (\beta_1 \pm \sigma(\beta_1))\times 0.2 + \epsilon$$
Meaning of standard error of the coefficients in a regression model? If \begin{align} \hat \beta_0 & = 1.21054 \quad \text{with Std. Error} = 0.11508, \\ \hat \beta_1 & = 1.87723 \quad \text{with Std. Error} = 0.09844. \end{align} it means that the range of values for
27,393
Meaning of standard error of the coefficients in a regression model?
What you created here is a model, that tries to reflect reality. But of course, unless we are exceptionally lucky, the model will never reflect reality perfectly. And the standard deviations reflect how confident the model is about itself. In your question, you stated you generated data with $\beta_0 = 1$ and $\beta_1=2$. Those numbers are the reality your model tries to reflect. Now suppose you didn't tell us those values, just your model. What can we say about your input? The model tells us the most likely values are $\beta_0 = 1.21042$ and $\beta_1=1.87223$. But could it be that you that the actual values you put in (the reality) were $1.2$ and $1.9$? Well, therefore we have to look at the standard deviation. With the given standard deviations, the model tells you it's $68 \%$ sure the true value of $\beta_0$ is in the range $1.09546 - 1.32562$ (minus 1 sd and plus 1 sd). And it's $95 \%$ sure the true value is in the range $0.98038 - 1.4407$ (2 sd away). For $\beta_1$, we can do a similar calculation. That means the numbers $1.2$ and $1.9$ are very reasonable guesses, but that $1$ and $2$ are also not too outlandish. Now in reality, we often don't have access to the true values of $\beta_0$ and $\beta_1$. We can just take measurements, and make the best model we have. Or sometimes, theorists will come up with a theory that has to be tested on reality, to check whether the model is right or wrong. As an experimental physicist, you'll run some experiments and maybe get the same values you got. You'll make a model, and can publish this to show that a theory that predicts $\beta_0 = 0$ and $\beta_1=5$ is most definitely wrong (if you can prove your experimental setup is correct). The values you got of $1.21$ and $1.87$ are basically your best guesses as to what the true values could be. But a theory that predicts $\beta_0=1$ and $\beta_1=2$ may well be correct. Until you come up with an experiment that's more sensitive. Suppose you do the same, and get a model that shows: \begin{align} \hat \beta_0 & = 1.19554 \quad \text{with Std. Error} = 0.01279, \\ \hat \beta_1 & = 1.88341 \quad \text{with Std. Error} = 0.02369. \end{align} These values allign quite well with your earlier result (showing there was likely no systemic error in your first experiment). But they have much narrower standard deviations, and now also show the theory with $\beta_0=1$ and $\beta_1=2$ is also wrong. But the guesses of $1.2$ and $1.9$ are still holding.
Meaning of standard error of the coefficients in a regression model?
What you created here is a model, that tries to reflect reality. But of course, unless we are exceptionally lucky, the model will never reflect reality perfectly. And the standard deviations reflect h
Meaning of standard error of the coefficients in a regression model? What you created here is a model, that tries to reflect reality. But of course, unless we are exceptionally lucky, the model will never reflect reality perfectly. And the standard deviations reflect how confident the model is about itself. In your question, you stated you generated data with $\beta_0 = 1$ and $\beta_1=2$. Those numbers are the reality your model tries to reflect. Now suppose you didn't tell us those values, just your model. What can we say about your input? The model tells us the most likely values are $\beta_0 = 1.21042$ and $\beta_1=1.87223$. But could it be that you that the actual values you put in (the reality) were $1.2$ and $1.9$? Well, therefore we have to look at the standard deviation. With the given standard deviations, the model tells you it's $68 \%$ sure the true value of $\beta_0$ is in the range $1.09546 - 1.32562$ (minus 1 sd and plus 1 sd). And it's $95 \%$ sure the true value is in the range $0.98038 - 1.4407$ (2 sd away). For $\beta_1$, we can do a similar calculation. That means the numbers $1.2$ and $1.9$ are very reasonable guesses, but that $1$ and $2$ are also not too outlandish. Now in reality, we often don't have access to the true values of $\beta_0$ and $\beta_1$. We can just take measurements, and make the best model we have. Or sometimes, theorists will come up with a theory that has to be tested on reality, to check whether the model is right or wrong. As an experimental physicist, you'll run some experiments and maybe get the same values you got. You'll make a model, and can publish this to show that a theory that predicts $\beta_0 = 0$ and $\beta_1=5$ is most definitely wrong (if you can prove your experimental setup is correct). The values you got of $1.21$ and $1.87$ are basically your best guesses as to what the true values could be. But a theory that predicts $\beta_0=1$ and $\beta_1=2$ may well be correct. Until you come up with an experiment that's more sensitive. Suppose you do the same, and get a model that shows: \begin{align} \hat \beta_0 & = 1.19554 \quad \text{with Std. Error} = 0.01279, \\ \hat \beta_1 & = 1.88341 \quad \text{with Std. Error} = 0.02369. \end{align} These values allign quite well with your earlier result (showing there was likely no systemic error in your first experiment). But they have much narrower standard deviations, and now also show the theory with $\beta_0=1$ and $\beta_1=2$ is also wrong. But the guesses of $1.2$ and $1.9$ are still holding.
Meaning of standard error of the coefficients in a regression model? What you created here is a model, that tries to reflect reality. But of course, unless we are exceptionally lucky, the model will never reflect reality perfectly. And the standard deviations reflect h
27,394
Unbiased, positive estimator for the square of the mean
Note that the sample mean $\bar{X}$ is also normally distributed, with mean $\mu$ and variance $\sigma^2/n$. This means that $$\operatorname E(\bar{X}^2) = \operatorname E(\bar{X})^2 + \operatorname{Var}(\bar{X}) = \mu^2 + \frac{\sigma^2}n$$ If all you care about is an unbiased estimate, you can use the fact that the sample variance is unbiased for $\sigma^2$. This implies that the estimator $$\widehat{\mu^2} = \bar{X}^2 - \frac{S^2}n$$ is unbiased for $\mu^2$.
Unbiased, positive estimator for the square of the mean
Note that the sample mean $\bar{X}$ is also normally distributed, with mean $\mu$ and variance $\sigma^2/n$. This means that $$\operatorname E(\bar{X}^2) = \operatorname E(\bar{X})^2 + \operatorname{V
Unbiased, positive estimator for the square of the mean Note that the sample mean $\bar{X}$ is also normally distributed, with mean $\mu$ and variance $\sigma^2/n$. This means that $$\operatorname E(\bar{X}^2) = \operatorname E(\bar{X})^2 + \operatorname{Var}(\bar{X}) = \mu^2 + \frac{\sigma^2}n$$ If all you care about is an unbiased estimate, you can use the fact that the sample variance is unbiased for $\sigma^2$. This implies that the estimator $$\widehat{\mu^2} = \bar{X}^2 - \frac{S^2}n$$ is unbiased for $\mu^2$.
Unbiased, positive estimator for the square of the mean Note that the sample mean $\bar{X}$ is also normally distributed, with mean $\mu$ and variance $\sigma^2/n$. This means that $$\operatorname E(\bar{X}^2) = \operatorname E(\bar{X})^2 + \operatorname{V
27,395
Unbiased, positive estimator for the square of the mean
It should not be possible produce an estimator that is both unbiased and always positive for $\mu^2$. If the true mean is 0, the estimator must in expectation return 0 but is not allowed to output negative numbers, therefore it is also not allowed to output positive numbers either as it would be biased. An unbiased, always positive estimator of this quantity must therefore always return the correct answer when the mean is 0, regardless of the samples, which seems impossible. knrumsey's answer shows how to correct the bias of the sample-mean-squarred estimator to obtain an unbiased estimate of $\mu^2$.
Unbiased, positive estimator for the square of the mean
It should not be possible produce an estimator that is both unbiased and always positive for $\mu^2$. If the true mean is 0, the estimator must in expectation return 0 but is not allowed to output neg
Unbiased, positive estimator for the square of the mean It should not be possible produce an estimator that is both unbiased and always positive for $\mu^2$. If the true mean is 0, the estimator must in expectation return 0 but is not allowed to output negative numbers, therefore it is also not allowed to output positive numbers either as it would be biased. An unbiased, always positive estimator of this quantity must therefore always return the correct answer when the mean is 0, regardless of the samples, which seems impossible. knrumsey's answer shows how to correct the bias of the sample-mean-squarred estimator to obtain an unbiased estimate of $\mu^2$.
Unbiased, positive estimator for the square of the mean It should not be possible produce an estimator that is both unbiased and always positive for $\mu^2$. If the true mean is 0, the estimator must in expectation return 0 but is not allowed to output neg
27,396
Why feature scaling only to training set?
Not quite. You learn the means and standard deviation of the training set, and then: Standardize the training set using the training set means and standard deviations. Standardize any test set using the training set means and standard deviations. This is just following the general principle: any thing you learn, must be learned from the model's training data.
Why feature scaling only to training set?
Not quite. You learn the means and standard deviation of the training set, and then: Standardize the training set using the training set means and standard deviations. Standardize any test set using
Why feature scaling only to training set? Not quite. You learn the means and standard deviation of the training set, and then: Standardize the training set using the training set means and standard deviations. Standardize any test set using the training set means and standard deviations. This is just following the general principle: any thing you learn, must be learned from the model's training data.
Why feature scaling only to training set? Not quite. You learn the means and standard deviation of the training set, and then: Standardize the training set using the training set means and standard deviations. Standardize any test set using
27,397
Why feature scaling only to training set?
To follow up on a comment made to the answer - If you scale the data before train/test split you will get data leakage. Calculating mean/sd of the entire dataset before splitting will result in leakage as the data from each dataset will contain information about the other set of data (through the mean/sd values) and could influence prediction accuracy and overfit.
Why feature scaling only to training set?
To follow up on a comment made to the answer - If you scale the data before train/test split you will get data leakage. Calculating mean/sd of the entire dataset before splitting will result in leakag
Why feature scaling only to training set? To follow up on a comment made to the answer - If you scale the data before train/test split you will get data leakage. Calculating mean/sd of the entire dataset before splitting will result in leakage as the data from each dataset will contain information about the other set of data (through the mean/sd values) and could influence prediction accuracy and overfit.
Why feature scaling only to training set? To follow up on a comment made to the answer - If you scale the data before train/test split you will get data leakage. Calculating mean/sd of the entire dataset before splitting will result in leakag
27,398
Why feature scaling only to training set?
Data might already be naturally scaled by the experiments and or conventions used (eg predicting percentages). Secondly, you'll have a system with two variables. So, you cannot readily compare to "unscaled" learning with scaled learning.
Why feature scaling only to training set?
Data might already be naturally scaled by the experiments and or conventions used (eg predicting percentages). Secondly, you'll have a system with two variables. So, you cannot readily compare to "uns
Why feature scaling only to training set? Data might already be naturally scaled by the experiments and or conventions used (eg predicting percentages). Secondly, you'll have a system with two variables. So, you cannot readily compare to "unscaled" learning with scaled learning.
Why feature scaling only to training set? Data might already be naturally scaled by the experiments and or conventions used (eg predicting percentages). Secondly, you'll have a system with two variables. So, you cannot readily compare to "uns
27,399
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective?
As Xi'an says, the question is moot, but I think that many people are nevertheless led to consider the maximum-likelihood estimate from a Bayesian perspective because of a statement that appears in some literature and on the internet: "the maximum-likelihood estimate is a particular case of the Bayesian maximum a posteriori estimate, when the prior distribution is uniform". I'd say that from a Bayesian perspective the maximum-likelihood estimator and its invariance property can make sense, but the role and meaning of estimators in Bayesian theory is very different from frequentist theory. And this particular estimator is usually not very sensible from a Bayesian perspective. Here's why. For simplicity let me consider a one-dimensional parameter and one-one transformations. First of all two remarks: It can be useful to consider a parameter as a quantity living on a generic manifold, on which we can choose different coordinate systems or measurement units. From this point of view a reparameterization is just a change of coordinates. For example, the temperature of the triple point of water is the same whether we express it as $T=273.16$ (K), $t=0.01$ (°C), $\theta=32.01$ (°F), or $\eta=5.61$ (a logarithmic scale). Our inferences and decisions should be invariant with respect to coordinate changes. Some coordinate systems may be more natural than others, though, of course. Probabilities for continuous quantities always refer to intervals (more precisely, sets) of values of such quantities, never to particular values; although in singular cases we can consider sets containing one value only, for example. The probability-density notation $\mathrm{p}(x)\,\mathrm{d}x$, in Riemann-integral style, is telling us that (a) we have chosen a coordinate system $x$ on the parameter manifold, (b) this coordinate system allows us to speak of intervals of equal width, (c) the probability that the value lies in a small interval $\Delta x$ is approximately $\mathrm{p}(x)\,\Delta x$, where $x$ is a point within the interval. (Alternatively we can speak of a base Lebesgue measure $\mathrm{d}x$ and intervals of equal measure, but the essence is the same.) Therefore, a statement like "$\mathrm{p}(x_1) > \mathrm{p}(x_2)$" does not mean that the probability for $x_1$ is larger than that for $x_2$, but that the probability that $x$ lies in a small interval around $x_1$ is larger than the probability that it lies in an interval of equal width around $x_2$. Such statement is coordinate-dependent. Let's see the (frequentist) maximum-likelihood point of view From this point of view, speaking about the probability for a parameter value $x$ is simply meaningless. Full stop. We'd like to know what the true parameter value is, and the value $\tilde{x}$ that gives highest probability to the data $D$ should intuitively be not too far off the mark: $$\tilde{x} := \arg\max_x \mathrm{p}(D \mid x)\tag{1}\label{ML}.$$ This is the maximum-likelihood estimator. This estimator selects a point on the parameter manifold and therefore doesn't depend on any coordinate system. Stated otherwise: Each point on the parameter manifold is associated with a number: the probability for the data $D$; we're choosing the point that has the highest associated number. This choice does not require a coordinate system or base measure. It is for this reason that this estimator is parameterization invariant, and this property tells us that it is not a probability – as desired. This invariance remains if we consider more complex parameter transformations, and the profile likelihood mentioned by Xi'an makes complete sense from this perspective. Let's see the Bayesian point of view From this point of view it always makes sense to speak of the probability for a continuous parameter, if we are uncertain about it, conditional on data and other evidence $D$. We write this as $$\mathrm{p}(x \mid D)\,\mathrm{d}x \propto \mathrm{p}(D \mid x)\, \mathrm{p}(x)\,\mathrm{d}x.\tag{2}\label{PD}$$ As remarked at the beginning, this probability refers to intervals on the parameter manifold, not to single points. Ideally we should report our uncertainty by specifying the full probability distribution $\mathrm{p}(x \mid D)\,\mathrm{d}x$ for the parameter. So the notion of estimator is secondary from a Bayesian perspective. This notion appears when we must choose one point on the parameter manifold for some particular purpose or reason, even though the true point is unknown. This choice is the realm of decision theory [1], and the value chosen is the proper definition of "estimator" in Bayesian theory. Decision theory says that we must first introduce a utility function $(P_0,P)\mapsto G(P_0; P)$ which tells us how much we gain by choosing the point $P_0$ on the parameter manifold, when the true point is $P$ (alternatively, we can pessimistically speak of a loss function). This function will have a different expression in each coordinate system, e.g. $(x_0,x)\mapsto G_x(x_0; x)$, and $(y_0,y)\mapsto G_y(y_0; y)$; if the coordinate transformation is $y=f(x)$, the two expressions are related by $G_x(x_0;x) = G_y[f(x_0); f(x)]$ [2]. Let me stress at once that when we speak, say, of a quadratic utility function, we have implicitly chosen a particular coordinate system, usually a natural one for the parameter. In another coordinate system the expression for the utility function will generally not be quadratic, but it's still the same utility function on the parameter manifold. The estimator $\hat{P}$ associated with a utility function $G$ is the point that maximizes the expected utility given our data $D$. In a coordinate system $x$, its coordinate is $$\hat{x} := \arg\max_{x_0} \int G_x(x_0; x)\, \mathrm{p}(x \mid D)\,\mathrm{d}x.\tag{3}\label{UF}$$ This definition is independent of coordinate changes: in new coordinates $y=f(x)$ the coordinate of the estimator is $\hat{y}=f(\hat{x})$. This follows from the coordinate-independence of $G$ and of the integral. You see that this kind of invariance is a built-in property of Bayesian estimators. Now we can ask: is there a utility function that leads to an estimator equal to the maximum-likelihood one? Since the maximum-likelihood estimator is invariant, such a function might exist. From this point of view, maximum-likelihood would be nonsensical from a Bayesian point of view if it were not invariant! A utility function that in a particular coordinate system $x$ is equal to a Dirac delta, $G_x(x_0; x) = \delta(x_0-x)$, seems to do the job [3]. Equation $\eqref{UF}$ yields $\hat{x} = \arg\max_{x} \mathrm{p}(x \mid D)$, and if the prior in $\eqref{PD}$ is uniform in the coordinate $x$, we obtain the maximum-likelihood estimate $\eqref{ML}$. Alternatively we can consider a sequence of utility functions with increasingly smaller support, e.g. $G_x(x_0; x) = 1$ if $\lvert x_0-x \rvert<\epsilon$ and $G_x(x_0; x) = 0$ elsewhere, for $\epsilon\to 0$ [4]. So, yes, the maximum-likelihood estimator and its invariance can make sense from a Bayesian perspective, if we are mathematically generous and accept generalized functions. But the very meaning, role, and use of an estimator in a Bayesian perspective are completely different from those in a frequentist perspective. Let me also add that there seem to be reservations in the literature about whether the utility function defined above makes mathematical sense [5]. In any case, the usefulness of such a utility function is rather limited: as Jaynes [3] points out, it means that "we care only about the chance of being exactly right; and, if we are wrong, we don't care how wrong we are". Now consider the statement "maximum-likelihood is a special case of maximum-a-posteriori with a uniform prior". It's important to note what happens under a general change of coordinates $y=f(x)$: the utility function above assumes a different expression: $G_y(y_0;y) = \delta[f^{-1}(y_0)-f^{-1}(y)] \equiv \delta(y_0-y)\,\lvert f'[f^{-1}(y_0)]\rvert$ the prior density in the coordinate $y$ is not uniform, owing to the Jacobian determinant; the estimator is not the maximum of the posterior density in the $y$ coordinate, because the Dirac delta has acquired an extra multiplicative factor; the estimator is still given by the maximum of the likelihood in the new, $y$ coordinates. These changes combine so that the estimator point is still the same on the parameter manifold. Thus, the statement above is implicitly assuming a special coordinate system. A tentative, more explicit statement would could be this: "the maximum-likelihood estimator is numerically equal to the Bayesian estimator that in some coordinate system has a delta utility function and a uniform prior". Final comments The discussion above is informal, but can be made precise using measure theory and Stieltjes integration. In the Bayesian literature we can find also a more informal notion of estimator: it's a number that somehow "summarizes" a probability distribution, especially when it's inconvenient or impossible to specify its full density $\mathrm{p}(x \mid D)\,\mathrm{d}x$; see e.g. Murphy [6] or MacKay [7]. This notion is usually detached from decision theory, and therefore may be coordinate-dependent or tacitly assumes a particular coordinate system. But in the decision-theoretic definition of estimator, something which is not invariant cannot be an estimator. [1] For example, H. Raiffa, R. Schlaifer: Applied Statistical Decision Theory (Wiley 2000). [2] Y. Choquet-Bruhat, C. DeWitt-Morette, M. Dillard-Bleick: Analysis, Manifolds and Physics. Part I: Basics (Elsevier 1996), or any other good book on differential geometry. [3] E. T. Jaynes: Probability Theory: The Logic of Science (Cambridge University Press 2003), §13.10. [4] J.-M. Bernardo, A. F. Smith: Bayesian Theory (Wiley 2000), §5.1.5. [5] I. H. Jermyn: Invariant Bayesian estimation on manifolds https://doi.org/10.1214/009053604000001273; R. Bassett, J. Deride: Maximum a posteriori estimators as a limit of Bayes estimators https://doi.org/10.1007/s10107-018-1241-0. [6] K. P. Murphy: Machine Learning: A Probabilistic Perspective (MIT Press 2012), especially chap. 5. [7] D. J. C. MacKay: Information Theory, Inference, and Learning Algorithms (Cambridge University Press 2003), http://www.inference.phy.cam.ac.uk/mackay/itila/.
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective?
As Xi'an says, the question is moot, but I think that many people are nevertheless led to consider the maximum-likelihood estimate from a Bayesian perspective because of a statement that appears in so
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective? As Xi'an says, the question is moot, but I think that many people are nevertheless led to consider the maximum-likelihood estimate from a Bayesian perspective because of a statement that appears in some literature and on the internet: "the maximum-likelihood estimate is a particular case of the Bayesian maximum a posteriori estimate, when the prior distribution is uniform". I'd say that from a Bayesian perspective the maximum-likelihood estimator and its invariance property can make sense, but the role and meaning of estimators in Bayesian theory is very different from frequentist theory. And this particular estimator is usually not very sensible from a Bayesian perspective. Here's why. For simplicity let me consider a one-dimensional parameter and one-one transformations. First of all two remarks: It can be useful to consider a parameter as a quantity living on a generic manifold, on which we can choose different coordinate systems or measurement units. From this point of view a reparameterization is just a change of coordinates. For example, the temperature of the triple point of water is the same whether we express it as $T=273.16$ (K), $t=0.01$ (°C), $\theta=32.01$ (°F), or $\eta=5.61$ (a logarithmic scale). Our inferences and decisions should be invariant with respect to coordinate changes. Some coordinate systems may be more natural than others, though, of course. Probabilities for continuous quantities always refer to intervals (more precisely, sets) of values of such quantities, never to particular values; although in singular cases we can consider sets containing one value only, for example. The probability-density notation $\mathrm{p}(x)\,\mathrm{d}x$, in Riemann-integral style, is telling us that (a) we have chosen a coordinate system $x$ on the parameter manifold, (b) this coordinate system allows us to speak of intervals of equal width, (c) the probability that the value lies in a small interval $\Delta x$ is approximately $\mathrm{p}(x)\,\Delta x$, where $x$ is a point within the interval. (Alternatively we can speak of a base Lebesgue measure $\mathrm{d}x$ and intervals of equal measure, but the essence is the same.) Therefore, a statement like "$\mathrm{p}(x_1) > \mathrm{p}(x_2)$" does not mean that the probability for $x_1$ is larger than that for $x_2$, but that the probability that $x$ lies in a small interval around $x_1$ is larger than the probability that it lies in an interval of equal width around $x_2$. Such statement is coordinate-dependent. Let's see the (frequentist) maximum-likelihood point of view From this point of view, speaking about the probability for a parameter value $x$ is simply meaningless. Full stop. We'd like to know what the true parameter value is, and the value $\tilde{x}$ that gives highest probability to the data $D$ should intuitively be not too far off the mark: $$\tilde{x} := \arg\max_x \mathrm{p}(D \mid x)\tag{1}\label{ML}.$$ This is the maximum-likelihood estimator. This estimator selects a point on the parameter manifold and therefore doesn't depend on any coordinate system. Stated otherwise: Each point on the parameter manifold is associated with a number: the probability for the data $D$; we're choosing the point that has the highest associated number. This choice does not require a coordinate system or base measure. It is for this reason that this estimator is parameterization invariant, and this property tells us that it is not a probability – as desired. This invariance remains if we consider more complex parameter transformations, and the profile likelihood mentioned by Xi'an makes complete sense from this perspective. Let's see the Bayesian point of view From this point of view it always makes sense to speak of the probability for a continuous parameter, if we are uncertain about it, conditional on data and other evidence $D$. We write this as $$\mathrm{p}(x \mid D)\,\mathrm{d}x \propto \mathrm{p}(D \mid x)\, \mathrm{p}(x)\,\mathrm{d}x.\tag{2}\label{PD}$$ As remarked at the beginning, this probability refers to intervals on the parameter manifold, not to single points. Ideally we should report our uncertainty by specifying the full probability distribution $\mathrm{p}(x \mid D)\,\mathrm{d}x$ for the parameter. So the notion of estimator is secondary from a Bayesian perspective. This notion appears when we must choose one point on the parameter manifold for some particular purpose or reason, even though the true point is unknown. This choice is the realm of decision theory [1], and the value chosen is the proper definition of "estimator" in Bayesian theory. Decision theory says that we must first introduce a utility function $(P_0,P)\mapsto G(P_0; P)$ which tells us how much we gain by choosing the point $P_0$ on the parameter manifold, when the true point is $P$ (alternatively, we can pessimistically speak of a loss function). This function will have a different expression in each coordinate system, e.g. $(x_0,x)\mapsto G_x(x_0; x)$, and $(y_0,y)\mapsto G_y(y_0; y)$; if the coordinate transformation is $y=f(x)$, the two expressions are related by $G_x(x_0;x) = G_y[f(x_0); f(x)]$ [2]. Let me stress at once that when we speak, say, of a quadratic utility function, we have implicitly chosen a particular coordinate system, usually a natural one for the parameter. In another coordinate system the expression for the utility function will generally not be quadratic, but it's still the same utility function on the parameter manifold. The estimator $\hat{P}$ associated with a utility function $G$ is the point that maximizes the expected utility given our data $D$. In a coordinate system $x$, its coordinate is $$\hat{x} := \arg\max_{x_0} \int G_x(x_0; x)\, \mathrm{p}(x \mid D)\,\mathrm{d}x.\tag{3}\label{UF}$$ This definition is independent of coordinate changes: in new coordinates $y=f(x)$ the coordinate of the estimator is $\hat{y}=f(\hat{x})$. This follows from the coordinate-independence of $G$ and of the integral. You see that this kind of invariance is a built-in property of Bayesian estimators. Now we can ask: is there a utility function that leads to an estimator equal to the maximum-likelihood one? Since the maximum-likelihood estimator is invariant, such a function might exist. From this point of view, maximum-likelihood would be nonsensical from a Bayesian point of view if it were not invariant! A utility function that in a particular coordinate system $x$ is equal to a Dirac delta, $G_x(x_0; x) = \delta(x_0-x)$, seems to do the job [3]. Equation $\eqref{UF}$ yields $\hat{x} = \arg\max_{x} \mathrm{p}(x \mid D)$, and if the prior in $\eqref{PD}$ is uniform in the coordinate $x$, we obtain the maximum-likelihood estimate $\eqref{ML}$. Alternatively we can consider a sequence of utility functions with increasingly smaller support, e.g. $G_x(x_0; x) = 1$ if $\lvert x_0-x \rvert<\epsilon$ and $G_x(x_0; x) = 0$ elsewhere, for $\epsilon\to 0$ [4]. So, yes, the maximum-likelihood estimator and its invariance can make sense from a Bayesian perspective, if we are mathematically generous and accept generalized functions. But the very meaning, role, and use of an estimator in a Bayesian perspective are completely different from those in a frequentist perspective. Let me also add that there seem to be reservations in the literature about whether the utility function defined above makes mathematical sense [5]. In any case, the usefulness of such a utility function is rather limited: as Jaynes [3] points out, it means that "we care only about the chance of being exactly right; and, if we are wrong, we don't care how wrong we are". Now consider the statement "maximum-likelihood is a special case of maximum-a-posteriori with a uniform prior". It's important to note what happens under a general change of coordinates $y=f(x)$: the utility function above assumes a different expression: $G_y(y_0;y) = \delta[f^{-1}(y_0)-f^{-1}(y)] \equiv \delta(y_0-y)\,\lvert f'[f^{-1}(y_0)]\rvert$ the prior density in the coordinate $y$ is not uniform, owing to the Jacobian determinant; the estimator is not the maximum of the posterior density in the $y$ coordinate, because the Dirac delta has acquired an extra multiplicative factor; the estimator is still given by the maximum of the likelihood in the new, $y$ coordinates. These changes combine so that the estimator point is still the same on the parameter manifold. Thus, the statement above is implicitly assuming a special coordinate system. A tentative, more explicit statement would could be this: "the maximum-likelihood estimator is numerically equal to the Bayesian estimator that in some coordinate system has a delta utility function and a uniform prior". Final comments The discussion above is informal, but can be made precise using measure theory and Stieltjes integration. In the Bayesian literature we can find also a more informal notion of estimator: it's a number that somehow "summarizes" a probability distribution, especially when it's inconvenient or impossible to specify its full density $\mathrm{p}(x \mid D)\,\mathrm{d}x$; see e.g. Murphy [6] or MacKay [7]. This notion is usually detached from decision theory, and therefore may be coordinate-dependent or tacitly assumes a particular coordinate system. But in the decision-theoretic definition of estimator, something which is not invariant cannot be an estimator. [1] For example, H. Raiffa, R. Schlaifer: Applied Statistical Decision Theory (Wiley 2000). [2] Y. Choquet-Bruhat, C. DeWitt-Morette, M. Dillard-Bleick: Analysis, Manifolds and Physics. Part I: Basics (Elsevier 1996), or any other good book on differential geometry. [3] E. T. Jaynes: Probability Theory: The Logic of Science (Cambridge University Press 2003), §13.10. [4] J.-M. Bernardo, A. F. Smith: Bayesian Theory (Wiley 2000), §5.1.5. [5] I. H. Jermyn: Invariant Bayesian estimation on manifolds https://doi.org/10.1214/009053604000001273; R. Bassett, J. Deride: Maximum a posteriori estimators as a limit of Bayes estimators https://doi.org/10.1007/s10107-018-1241-0. [6] K. P. Murphy: Machine Learning: A Probabilistic Perspective (MIT Press 2012), especially chap. 5. [7] D. J. C. MacKay: Information Theory, Inference, and Learning Algorithms (Cambridge University Press 2003), http://www.inference.phy.cam.ac.uk/mackay/itila/.
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective? As Xi'an says, the question is moot, but I think that many people are nevertheless led to consider the maximum-likelihood estimate from a Bayesian perspective because of a statement that appears in so
27,400
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective?
From a non-Bayesian view point, there is no definition of quantities like $$p(x|\theta = -\sqrt \eta \lor \theta = \sqrt \eta)$$ because $\theta$ is then a fixed parameter and the conditioning notation does not make sense. The alternative you propose relies on a prior distribution, which is precisely what an approach such as the one proposed by Casella and Berger wants to avoid. You can check the keyword profile likelihood for more entries. (And there is no meaning of right or wrong there.)
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective?
From a non-Bayesian view point, there is no definition of quantities like $$p(x|\theta = -\sqrt \eta \lor \theta = \sqrt \eta)$$ because $\theta$ is then a fixed parameter and the conditioning notatio
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective? From a non-Bayesian view point, there is no definition of quantities like $$p(x|\theta = -\sqrt \eta \lor \theta = \sqrt \eta)$$ because $\theta$ is then a fixed parameter and the conditioning notation does not make sense. The alternative you propose relies on a prior distribution, which is precisely what an approach such as the one proposed by Casella and Berger wants to avoid. You can check the keyword profile likelihood for more entries. (And there is no meaning of right or wrong there.)
Is the invariance property of the ML estimator nonsensical from a Bayesian perspective? From a non-Bayesian view point, there is no definition of quantities like $$p(x|\theta = -\sqrt \eta \lor \theta = \sqrt \eta)$$ because $\theta$ is then a fixed parameter and the conditioning notatio