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
|
|---|---|---|---|---|---|---|
41,101
|
R - moderated mediation using the lavaan package
|
I posted this question in another location and was provided the answer by Terry Jorgenson. Question and answer:
I would like to calculate the conditional indirect effects of X on Y given a set of values for the moderator W. Both X and the moderator are continuous. Could you provide some direction for structuring the model syntax?
Assuming X and W are both observed variables, you can calculate the product term XW in your data.frame and simply add the product term (X-W interaction) to the models for M and Y in Yves' example earlier in this thread (but a single-group version, since your moderator is continuous).
model <- '
Y ~ c*X + cw*XW + b*M
M ~ a*X + aw*XW
## indirect and total effects, conditional on W == 0
ab0 := a*b # + 0*aw*b
total0 := ab0 + c # + 0*cw
## indirect and total effects, conditional on W == 1
ab1 := ab0 + 1*aw*b
total1 := ab1 + c + 1*cw
## indirect and total effects, conditional on W == 2
ab2 := ab0 + 2*aw*b
total2 := ab2 + c + 2*cw
'
This is specifically designed to assess conditional indirect effects using the lavaan package.
|
R - moderated mediation using the lavaan package
|
I posted this question in another location and was provided the answer by Terry Jorgenson. Question and answer:
I would like to calculate the conditional indirect effects of X on Y given a set of val
|
R - moderated mediation using the lavaan package
I posted this question in another location and was provided the answer by Terry Jorgenson. Question and answer:
I would like to calculate the conditional indirect effects of X on Y given a set of values for the moderator W. Both X and the moderator are continuous. Could you provide some direction for structuring the model syntax?
Assuming X and W are both observed variables, you can calculate the product term XW in your data.frame and simply add the product term (X-W interaction) to the models for M and Y in Yves' example earlier in this thread (but a single-group version, since your moderator is continuous).
model <- '
Y ~ c*X + cw*XW + b*M
M ~ a*X + aw*XW
## indirect and total effects, conditional on W == 0
ab0 := a*b # + 0*aw*b
total0 := ab0 + c # + 0*cw
## indirect and total effects, conditional on W == 1
ab1 := ab0 + 1*aw*b
total1 := ab1 + c + 1*cw
## indirect and total effects, conditional on W == 2
ab2 := ab0 + 2*aw*b
total2 := ab2 + c + 2*cw
'
This is specifically designed to assess conditional indirect effects using the lavaan package.
|
R - moderated mediation using the lavaan package
I posted this question in another location and was provided the answer by Terry Jorgenson. Question and answer:
I would like to calculate the conditional indirect effects of X on Y given a set of val
|
41,102
|
Comparing a linear model with a spline model
|
I don't have time to answer all of your questions. To answer two of them: the $P$-value is for the test of all coefficients pertaining to a given predictor. In other words it is the global influence of all terms whether linear or nonlinear or interactions involving them. This is a test of association, where the null hypothesis is no association (flatness). This particular calculation uses the Wald $\chi^2$ test, which is a generalization of the $z$-test.
You'll get better output with ggplot(Predict(...)) instead of plot(). For either you can combine the results from Predict() using the rbind function. Type ?rbind.Predict for help.
|
Comparing a linear model with a spline model
|
I don't have time to answer all of your questions. To answer two of them: the $P$-value is for the test of all coefficients pertaining to a given predictor. In other words it is the global influence
|
Comparing a linear model with a spline model
I don't have time to answer all of your questions. To answer two of them: the $P$-value is for the test of all coefficients pertaining to a given predictor. In other words it is the global influence of all terms whether linear or nonlinear or interactions involving them. This is a test of association, where the null hypothesis is no association (flatness). This particular calculation uses the Wald $\chi^2$ test, which is a generalization of the $z$-test.
You'll get better output with ggplot(Predict(...)) instead of plot(). For either you can combine the results from Predict() using the rbind function. Type ?rbind.Predict for help.
|
Comparing a linear model with a spline model
I don't have time to answer all of your questions. To answer two of them: the $P$-value is for the test of all coefficients pertaining to a given predictor. In other words it is the global influence
|
41,103
|
Comparing a linear model with a spline model
|
The "p-value" could be called an "unlikelihood statistics". It is supposed to be the extent to which the data disagrees with the Null or "alternative model". TYu are actually performing a "likelihood ratio test" when you compare two (nested) models. Although you have chosen to use the pspline function which defaults to a fairly high number of knots, it probably doesn't matter much in this case. In a real data analysis it might make sense to limit the number of knots. I find that more than 4 knots to a spline term seems to add very little in additional meaning. Both the difference in deviance or ( -2*(LL1-LL0) ) contribute to a t-statistic and the associated p-value. The more knots, then higher the hurdle over which the likelihood ratio test must jump to achieve conventional levels of "significance".
I'm having a bit of difficulty with the anova on the pspline model versus the non-spline model. If you only have a difference of (-975.61 - -973.26) I don't know why the chi-square statistic is 4.6983. Seems as though it should be a bit over 2. At any rate the df=11 is going to prevent you from concluding tat the spline model is significantly better since the critical value of chisq for a difference of 10 df is around 20.
Answer to Q in comment.:
The df's of the anova-object from the coxph models is
anova(m1,m2)$Df
The df's of the f2 object can be seen with:
a2[, "d.f."]
(To examine the R objects you can either print them or use str
)
|
Comparing a linear model with a spline model
|
The "p-value" could be called an "unlikelihood statistics". It is supposed to be the extent to which the data disagrees with the Null or "alternative model". TYu are actually performing a "likelihood
|
Comparing a linear model with a spline model
The "p-value" could be called an "unlikelihood statistics". It is supposed to be the extent to which the data disagrees with the Null or "alternative model". TYu are actually performing a "likelihood ratio test" when you compare two (nested) models. Although you have chosen to use the pspline function which defaults to a fairly high number of knots, it probably doesn't matter much in this case. In a real data analysis it might make sense to limit the number of knots. I find that more than 4 knots to a spline term seems to add very little in additional meaning. Both the difference in deviance or ( -2*(LL1-LL0) ) contribute to a t-statistic and the associated p-value. The more knots, then higher the hurdle over which the likelihood ratio test must jump to achieve conventional levels of "significance".
I'm having a bit of difficulty with the anova on the pspline model versus the non-spline model. If you only have a difference of (-975.61 - -973.26) I don't know why the chi-square statistic is 4.6983. Seems as though it should be a bit over 2. At any rate the df=11 is going to prevent you from concluding tat the spline model is significantly better since the critical value of chisq for a difference of 10 df is around 20.
Answer to Q in comment.:
The df's of the anova-object from the coxph models is
anova(m1,m2)$Df
The df's of the f2 object can be seen with:
a2[, "d.f."]
(To examine the R objects you can either print them or use str
)
|
Comparing a linear model with a spline model
The "p-value" could be called an "unlikelihood statistics". It is supposed to be the extent to which the data disagrees with the Null or "alternative model". TYu are actually performing a "likelihood
|
41,104
|
Citation for ML vs. REML
|
Sigh.
Comparing models that are fitted with REML and differ in their fixed effects never makes sense.
Using AIC/BIC/p-values to compare the same model fitted with REML vs ML never makes sense; you need to make the decision which method to use on a priori, theoretical grounds.
Comparing models that are fitted with REML and differ in their random effects is justified.
This is mentioned (but only in passing) in
Bates D, Maechler M, Bolker BM and Walker S (2014). “lme4: Linear
mixed-effects models using Eigen and S4.” ArXiv e-print; in press,
Journal of Statistical Software: http://arxiv.org/abs/1406.5823
For objects of class lmerMod the default
behavior is to refit the models with ML if fitted with REML = TRUE, which is necessary in
order to get sensible answers when comparing models that differ in their fixed effects ...
And more thoroughly, Pinheiro and Bates Mixed-Effects Models in S and S-PLUS 2000 (Springer) p. 87 (scraps from Google Books):
When two nested models differ in the specification of their
fixed-effects terms, a likelihood ratio test can be defined
for maximum likelihood fits only. As described in section 2.2.5
a likelihood ratio test for REML fits is not feasible, because
there is a term in the REML criterion that changes with the
change in the fixed-effects specification.
... they then go on to point out that LRT is asymptotic, and finite-size effects (the dreaded "denominator degrees of freedom" problem) can make such tests anticonservative.
This question gives a quotation from Discovering Statistics Using SPSS 4e that also backs up this statement (i.e. it's not just R-using weirdos).
|
Citation for ML vs. REML
|
Sigh.
Comparing models that are fitted with REML and differ in their fixed effects never makes sense.
Using AIC/BIC/p-values to compare the same model fitted with REML vs ML never makes sense; you n
|
Citation for ML vs. REML
Sigh.
Comparing models that are fitted with REML and differ in their fixed effects never makes sense.
Using AIC/BIC/p-values to compare the same model fitted with REML vs ML never makes sense; you need to make the decision which method to use on a priori, theoretical grounds.
Comparing models that are fitted with REML and differ in their random effects is justified.
This is mentioned (but only in passing) in
Bates D, Maechler M, Bolker BM and Walker S (2014). “lme4: Linear
mixed-effects models using Eigen and S4.” ArXiv e-print; in press,
Journal of Statistical Software: http://arxiv.org/abs/1406.5823
For objects of class lmerMod the default
behavior is to refit the models with ML if fitted with REML = TRUE, which is necessary in
order to get sensible answers when comparing models that differ in their fixed effects ...
And more thoroughly, Pinheiro and Bates Mixed-Effects Models in S and S-PLUS 2000 (Springer) p. 87 (scraps from Google Books):
When two nested models differ in the specification of their
fixed-effects terms, a likelihood ratio test can be defined
for maximum likelihood fits only. As described in section 2.2.5
a likelihood ratio test for REML fits is not feasible, because
there is a term in the REML criterion that changes with the
change in the fixed-effects specification.
... they then go on to point out that LRT is asymptotic, and finite-size effects (the dreaded "denominator degrees of freedom" problem) can make such tests anticonservative.
This question gives a quotation from Discovering Statistics Using SPSS 4e that also backs up this statement (i.e. it's not just R-using weirdos).
|
Citation for ML vs. REML
Sigh.
Comparing models that are fitted with REML and differ in their fixed effects never makes sense.
Using AIC/BIC/p-values to compare the same model fitted with REML vs ML never makes sense; you n
|
41,105
|
Significant p-value but odds ratio confidence interval crosses 1 in logistic regression using restricted cubic splines
|
Nice work Dan. The inclusion of 1.0 in an odds ratio's confidence interval will be entirely consistent with the P-value from anova() if and only if the variable is linear or if it is categorical and the reference cell happened to be consistent with how summary sets up the contrasts. This is why I prefer anova for overall inference, accompanied by partial effect plots from ggplot(Predict(...)).
When a predictor's relationship is non-monotonic, e.g. U-shaped, the two approaches will be most inconsistent.
Note that there is one dissatisfying aspect of fit.mult.impute: the model summary statistics such as $D_{xy}$ are only for the last imputed dataset. We need a better way to compute overall summary statistics, such as computing them on an "average model" or averaging the summary statistics over completed datasets.
I would show ORs and CLs but have a footnote stating the reason they are not necessarily consistent with the general tests of association. And you can add the association test statistics on the partial effect plots.
|
Significant p-value but odds ratio confidence interval crosses 1 in logistic regression using restri
|
Nice work Dan. The inclusion of 1.0 in an odds ratio's confidence interval will be entirely consistent with the P-value from anova() if and only if the variable is linear or if it is categorical and
|
Significant p-value but odds ratio confidence interval crosses 1 in logistic regression using restricted cubic splines
Nice work Dan. The inclusion of 1.0 in an odds ratio's confidence interval will be entirely consistent with the P-value from anova() if and only if the variable is linear or if it is categorical and the reference cell happened to be consistent with how summary sets up the contrasts. This is why I prefer anova for overall inference, accompanied by partial effect plots from ggplot(Predict(...)).
When a predictor's relationship is non-monotonic, e.g. U-shaped, the two approaches will be most inconsistent.
Note that there is one dissatisfying aspect of fit.mult.impute: the model summary statistics such as $D_{xy}$ are only for the last imputed dataset. We need a better way to compute overall summary statistics, such as computing them on an "average model" or averaging the summary statistics over completed datasets.
I would show ORs and CLs but have a footnote stating the reason they are not necessarily consistent with the general tests of association. And you can add the association test statistics on the partial effect plots.
|
Significant p-value but odds ratio confidence interval crosses 1 in logistic regression using restri
Nice work Dan. The inclusion of 1.0 in an odds ratio's confidence interval will be entirely consistent with the P-value from anova() if and only if the variable is linear or if it is categorical and
|
41,106
|
What are some good (and fast) alternatives to dynamic time warping?
|
There are various approximations such as Wavelets and SAX that can be used to get a lower bound.
Wavelets on Wikipedia
Piecewise Aggregate Approximation (PAA)
Symbolic Aggregate approXimation (SAX) homepage
But first make sure that DTW is what you need. It would be a big waste of time if you spent a lot of effort to scale something to a large data set which does not work... so always start with a sample.
For many time series, DTW is not usable. Instead, you may need something like fourier transformation, or extract features from the time series.
|
What are some good (and fast) alternatives to dynamic time warping?
|
There are various approximations such as Wavelets and SAX that can be used to get a lower bound.
Wavelets on Wikipedia
Piecewise Aggregate Approximation (PAA)
Symbolic Aggregate approXimation (SAX) h
|
What are some good (and fast) alternatives to dynamic time warping?
There are various approximations such as Wavelets and SAX that can be used to get a lower bound.
Wavelets on Wikipedia
Piecewise Aggregate Approximation (PAA)
Symbolic Aggregate approXimation (SAX) homepage
But first make sure that DTW is what you need. It would be a big waste of time if you spent a lot of effort to scale something to a large data set which does not work... so always start with a sample.
For many time series, DTW is not usable. Instead, you may need something like fourier transformation, or extract features from the time series.
|
What are some good (and fast) alternatives to dynamic time warping?
There are various approximations such as Wavelets and SAX that can be used to get a lower bound.
Wavelets on Wikipedia
Piecewise Aggregate Approximation (PAA)
Symbolic Aggregate approXimation (SAX) h
|
41,107
|
What are some good (and fast) alternatives to dynamic time warping?
|
Hmm.
Lets say you data is richly sampled. If you downsample it by 1 in 2, the speedup will be a factor of 4.
If you downsample it by 1 in 10, the speedup will be a factor of 100.
So if your data is oversampled, this is the easiest way to get a speed up.
You can also use admissible lower bounding to speed things up [a]
[a] http://www.cs.ucr.edu/~eamonn/Speeded%20Clustering%20Paper%20Camera%20Ready.pdf
|
What are some good (and fast) alternatives to dynamic time warping?
|
Hmm.
Lets say you data is richly sampled. If you downsample it by 1 in 2, the speedup will be a factor of 4.
If you downsample it by 1 in 10, the speedup will be a factor of 100.
So if your data is o
|
What are some good (and fast) alternatives to dynamic time warping?
Hmm.
Lets say you data is richly sampled. If you downsample it by 1 in 2, the speedup will be a factor of 4.
If you downsample it by 1 in 10, the speedup will be a factor of 100.
So if your data is oversampled, this is the easiest way to get a speed up.
You can also use admissible lower bounding to speed things up [a]
[a] http://www.cs.ucr.edu/~eamonn/Speeded%20Clustering%20Paper%20Camera%20Ready.pdf
|
What are some good (and fast) alternatives to dynamic time warping?
Hmm.
Lets say you data is richly sampled. If you downsample it by 1 in 2, the speedup will be a factor of 4.
If you downsample it by 1 in 10, the speedup will be a factor of 100.
So if your data is o
|
41,108
|
Meta-analysis of trials given hazard ratios
|
Assuming that you have the log hazard ratios (collected in the vector yi) and the standard errors of the log hazard ratios (collected in the vector sei), then you can fit a fixed-effects model to these data with:
res <- rma(yi, sei=sei, data=dat, method="FE")
As with several other outcome measures typically used for meta-analyses (e.g., risk ratios, odds ratios, incidence rate ratios), we do not meta-analyze the hazard ratios directly, but first log-transform them. This has two purposes:
The sampling distribution of the raw hazard ratio is typically very skewed. However, standard meta-analytic models assume that the sampling distribution of the outcome measure is (at least approximately) normal and that assumption is much more appropriate for the log-transformed hazard ratio.
Raw hazard ratios are not symmetric around 1. So, if one were to average a hazard ratio of 0.5 and 2.0 (which are exact opposites of each other), then we would get 1.25, which makes no sense. However, the log-transformed values are -0.6931 and +0.6931, whose average is 0. After back-transformation (exponentiation), we get 1, and the appropriate conclusion that, on average, the hazard ratio is 1.
Also note that analyses using the Cox proportional hazards model (which is often the source of hazard ratios obtained for a meta-analysis) are done on the log-scale. So, when the standard error is reported together with the hazard ratio, that standard error in all likelihood refers to the log-transformed hazard ratio, not the raw one (in fact, given the skewness of the distribution of the raw hazard ratio, the usefulness of a standard error for the raw hazard ratio, if it were indeed reported, is rather questionable).
Similarly, if a confidence interval is reported, then in all likelihood it was constructed on the log-scale and the bounds were exponentiated afterwards. We can then easily back-calculate the SE of the log hazard ratio. See also this question, which deals exactly with that issue.
The same goes for hazard ratios that are reported in conjunction with the results from the log-rank test. Not surprisingly, as the name of the test implies, the underlying analysis is also done on the log scale. So, a standard error that is computed based on such results again refers to log hazard ratio, not the raw one.
A few additional comments:
The sampling variance of the log hazard ratio is obtained by simply squaring the standard error. So, you could just use rma(yi, sei^2, data=dat, method="FE") or first create vi <- dat$sei^2 and then rma(yi, vi, data=dat, method="FE"). Do not multiply/divide by the sample size or square-root thereof.
The standard error of the log hazard ratio is not the same as taking the log of the standard error of the raw hazard ratio. One cannot just apply the same transformation to the standard error (or variance). In some cases, one can use the delta method to approximate the standard error (or variance) of some random variable following a transformation.
|
Meta-analysis of trials given hazard ratios
|
Assuming that you have the log hazard ratios (collected in the vector yi) and the standard errors of the log hazard ratios (collected in the vector sei), then you can fit a fixed-effects model to thes
|
Meta-analysis of trials given hazard ratios
Assuming that you have the log hazard ratios (collected in the vector yi) and the standard errors of the log hazard ratios (collected in the vector sei), then you can fit a fixed-effects model to these data with:
res <- rma(yi, sei=sei, data=dat, method="FE")
As with several other outcome measures typically used for meta-analyses (e.g., risk ratios, odds ratios, incidence rate ratios), we do not meta-analyze the hazard ratios directly, but first log-transform them. This has two purposes:
The sampling distribution of the raw hazard ratio is typically very skewed. However, standard meta-analytic models assume that the sampling distribution of the outcome measure is (at least approximately) normal and that assumption is much more appropriate for the log-transformed hazard ratio.
Raw hazard ratios are not symmetric around 1. So, if one were to average a hazard ratio of 0.5 and 2.0 (which are exact opposites of each other), then we would get 1.25, which makes no sense. However, the log-transformed values are -0.6931 and +0.6931, whose average is 0. After back-transformation (exponentiation), we get 1, and the appropriate conclusion that, on average, the hazard ratio is 1.
Also note that analyses using the Cox proportional hazards model (which is often the source of hazard ratios obtained for a meta-analysis) are done on the log-scale. So, when the standard error is reported together with the hazard ratio, that standard error in all likelihood refers to the log-transformed hazard ratio, not the raw one (in fact, given the skewness of the distribution of the raw hazard ratio, the usefulness of a standard error for the raw hazard ratio, if it were indeed reported, is rather questionable).
Similarly, if a confidence interval is reported, then in all likelihood it was constructed on the log-scale and the bounds were exponentiated afterwards. We can then easily back-calculate the SE of the log hazard ratio. See also this question, which deals exactly with that issue.
The same goes for hazard ratios that are reported in conjunction with the results from the log-rank test. Not surprisingly, as the name of the test implies, the underlying analysis is also done on the log scale. So, a standard error that is computed based on such results again refers to log hazard ratio, not the raw one.
A few additional comments:
The sampling variance of the log hazard ratio is obtained by simply squaring the standard error. So, you could just use rma(yi, sei^2, data=dat, method="FE") or first create vi <- dat$sei^2 and then rma(yi, vi, data=dat, method="FE"). Do not multiply/divide by the sample size or square-root thereof.
The standard error of the log hazard ratio is not the same as taking the log of the standard error of the raw hazard ratio. One cannot just apply the same transformation to the standard error (or variance). In some cases, one can use the delta method to approximate the standard error (or variance) of some random variable following a transformation.
|
Meta-analysis of trials given hazard ratios
Assuming that you have the log hazard ratios (collected in the vector yi) and the standard errors of the log hazard ratios (collected in the vector sei), then you can fit a fixed-effects model to thes
|
41,109
|
Confidence Interval of a Lognormal Random Variable
|
Is this correct?
No.
i) This isn't a confidence interval you're calculating (since those are for parameters or functions of them), nor is it really a prediction interval, a tolerance interval, or any of the more common statistical intervals ... since for starters it's based on known population values, not on a sample.
ii) You already calculated the limits of an interval that includes 95% of the probability; it's $(a,b)$, not $(\mu-a,\mu+b)$.
do we mean that 95% of the values lie within the mean of the random variable
No. The mean is a single value. How can 95% of a continuous distribution lie "within" a single value?
But now we don't have that an approximate 95% confidence interval is [mean−2∗SD,mean+2∗SD] since the pdf of Y is not symmetric.
Just because the density isn't symmetric doesn't of itself mean that a symmetric interval can't include 95% of the probability.
It doesn't include 95%, as it happens, though it's often fairly close to 95% for unimodal distributions. However, while it works pretty well for $\pm 2\sigma$, that doesn't always carry over nearly as well to other numbers of sds not close to 2.
So, is the mean±SD property for a confidence interval only valid for normal random variables?
(Again, keeping in mind that it's not a confidence interval)
Well, actually, for normal random variables, 95% of the distribution is within 1.96 sd's of the mean and 95.4% is within 2 sd's of the mean.
Those numbers are calculated from the normal distribution function; $\Phi(1.96)-\Phi(-1.96)=0.9500$ and $\Phi(2)-\Phi(-2)=0.9545$.
|
Confidence Interval of a Lognormal Random Variable
|
Is this correct?
No.
i) This isn't a confidence interval you're calculating (since those are for parameters or functions of them), nor is it really a prediction interval, a tolerance interval, or an
|
Confidence Interval of a Lognormal Random Variable
Is this correct?
No.
i) This isn't a confidence interval you're calculating (since those are for parameters or functions of them), nor is it really a prediction interval, a tolerance interval, or any of the more common statistical intervals ... since for starters it's based on known population values, not on a sample.
ii) You already calculated the limits of an interval that includes 95% of the probability; it's $(a,b)$, not $(\mu-a,\mu+b)$.
do we mean that 95% of the values lie within the mean of the random variable
No. The mean is a single value. How can 95% of a continuous distribution lie "within" a single value?
But now we don't have that an approximate 95% confidence interval is [mean−2∗SD,mean+2∗SD] since the pdf of Y is not symmetric.
Just because the density isn't symmetric doesn't of itself mean that a symmetric interval can't include 95% of the probability.
It doesn't include 95%, as it happens, though it's often fairly close to 95% for unimodal distributions. However, while it works pretty well for $\pm 2\sigma$, that doesn't always carry over nearly as well to other numbers of sds not close to 2.
So, is the mean±SD property for a confidence interval only valid for normal random variables?
(Again, keeping in mind that it's not a confidence interval)
Well, actually, for normal random variables, 95% of the distribution is within 1.96 sd's of the mean and 95.4% is within 2 sd's of the mean.
Those numbers are calculated from the normal distribution function; $\Phi(1.96)-\Phi(-1.96)=0.9500$ and $\Phi(2)-\Phi(-2)=0.9545$.
|
Confidence Interval of a Lognormal Random Variable
Is this correct?
No.
i) This isn't a confidence interval you're calculating (since those are for parameters or functions of them), nor is it really a prediction interval, a tolerance interval, or an
|
41,110
|
Should predictive accuracy or, alternatively, minimizing the MSE, be reconsidered?
|
This is a nice and thoughtful post, and in my working life I have observed the things you outline to be correct - the successful statisticians and scientists at my workplace are those that can step back from raw predictive accuracy and deliver a model or analysis that is holistically appropriate for the problem at hand. Sometimes this is raw predictive power, but often it is not.
I explicitly look for this when interviewing, my favorite initial answer to a modeling question is
Well, it depends...
I'll add some examples to your list.
Implementation Costs
Many businesses run core systems on outdated technology, cobol or fortran codebases running on ancient mainframe architectures. They are often reluctant to replace them because of the high fixed costs for doing so (even though the variable costs of maintaining them are high). This can have drastic consequences for model implementation. It may be possible to get a predictive boost from a random forest or gradient booster, but implementing a model of that complexity in a production environment can be completely infeasible.
Shelf Life
Related to implementation costs, a model, once implemented, may have a very long shelf life, and be expected to deliver reasonable predictions for a long time. A model with maximum supportable complexity fit very hard to the data is less robust to distribution shifts in the population and predictive relativity changes between segments.
Tinkering
Business people have a tendency to tinker with production models, and we as modelers sometimes have to assist with hot fixes in production systems. Complex models are more sensitive to this, it is harder to accurately asses how they will react to a production adjustment (talk to a mechanic about whether its easier to get under the hood of a car manufactured in 1980 vs. 2010).
Robustness to New Information
A categorical predictor may obtain new categories in the future, and is often desirable to have principled way to deal with these without refitting a model and pushing it to production.
Model Componentization
A model may be part of a larger system optimization, which imposes environmental constraints on its form and properties. One common source of this is when a model is a component of a larger mathematical optimization scheme, with some causal predictor in the model being manipulated as a lever to enhance business results. This can impose smoothness or differentiability constraints on the predictors that are very important to consider.
Locality Constraints
Some models have better locality properties than others. For example, if I wish to estimate the price elasticity of a customer for small adjustments, then a highly local model (i.e. a density smoother with small bandwidth, a regularized spline with small parameter, or a gradient tree booster with lots of cuts) will invariably use less of the data to support inferences even on a local scale. This can be undesirable when these inferences are used to make important decisions, and should be supported by as much data as possible.
|
Should predictive accuracy or, alternatively, minimizing the MSE, be reconsidered?
|
This is a nice and thoughtful post, and in my working life I have observed the things you outline to be correct - the successful statisticians and scientists at my workplace are those that can step ba
|
Should predictive accuracy or, alternatively, minimizing the MSE, be reconsidered?
This is a nice and thoughtful post, and in my working life I have observed the things you outline to be correct - the successful statisticians and scientists at my workplace are those that can step back from raw predictive accuracy and deliver a model or analysis that is holistically appropriate for the problem at hand. Sometimes this is raw predictive power, but often it is not.
I explicitly look for this when interviewing, my favorite initial answer to a modeling question is
Well, it depends...
I'll add some examples to your list.
Implementation Costs
Many businesses run core systems on outdated technology, cobol or fortran codebases running on ancient mainframe architectures. They are often reluctant to replace them because of the high fixed costs for doing so (even though the variable costs of maintaining them are high). This can have drastic consequences for model implementation. It may be possible to get a predictive boost from a random forest or gradient booster, but implementing a model of that complexity in a production environment can be completely infeasible.
Shelf Life
Related to implementation costs, a model, once implemented, may have a very long shelf life, and be expected to deliver reasonable predictions for a long time. A model with maximum supportable complexity fit very hard to the data is less robust to distribution shifts in the population and predictive relativity changes between segments.
Tinkering
Business people have a tendency to tinker with production models, and we as modelers sometimes have to assist with hot fixes in production systems. Complex models are more sensitive to this, it is harder to accurately asses how they will react to a production adjustment (talk to a mechanic about whether its easier to get under the hood of a car manufactured in 1980 vs. 2010).
Robustness to New Information
A categorical predictor may obtain new categories in the future, and is often desirable to have principled way to deal with these without refitting a model and pushing it to production.
Model Componentization
A model may be part of a larger system optimization, which imposes environmental constraints on its form and properties. One common source of this is when a model is a component of a larger mathematical optimization scheme, with some causal predictor in the model being manipulated as a lever to enhance business results. This can impose smoothness or differentiability constraints on the predictors that are very important to consider.
Locality Constraints
Some models have better locality properties than others. For example, if I wish to estimate the price elasticity of a customer for small adjustments, then a highly local model (i.e. a density smoother with small bandwidth, a regularized spline with small parameter, or a gradient tree booster with lots of cuts) will invariably use less of the data to support inferences even on a local scale. This can be undesirable when these inferences are used to make important decisions, and should be supported by as much data as possible.
|
Should predictive accuracy or, alternatively, minimizing the MSE, be reconsidered?
This is a nice and thoughtful post, and in my working life I have observed the things you outline to be correct - the successful statisticians and scientists at my workplace are those that can step ba
|
41,111
|
How does R calculate prediction intervals in the forecast package?
|
Unless you are using the forecast function's bootstrap = TRUE option the forecast package's ARIMA intervals are calculated by passing an ARIMA object to predict(). The intervals assume that residuals are normally distributed . If you look at the R documentation for predict.Arima() you will see that it uses KalmanForecast() to produce them.
See the following link for a good description of how to calculate a prediction interval for an ARIMA model manually:
https://onlinecourses.science.psu.edu/stat510/node/66
The code is available on Rob Hyndman's github page here:
https://github.com/robjhyndman/forecast/blob/master/R/arima.R
An exception to the resulting prediction intervals being normal around the point estimate is if you have set lambda (are using a Box-Cox transformation) in which case they will not be normal after the back-transformation.
|
How does R calculate prediction intervals in the forecast package?
|
Unless you are using the forecast function's bootstrap = TRUE option the forecast package's ARIMA intervals are calculated by passing an ARIMA object to predict(). The intervals assume that residuals
|
How does R calculate prediction intervals in the forecast package?
Unless you are using the forecast function's bootstrap = TRUE option the forecast package's ARIMA intervals are calculated by passing an ARIMA object to predict(). The intervals assume that residuals are normally distributed . If you look at the R documentation for predict.Arima() you will see that it uses KalmanForecast() to produce them.
See the following link for a good description of how to calculate a prediction interval for an ARIMA model manually:
https://onlinecourses.science.psu.edu/stat510/node/66
The code is available on Rob Hyndman's github page here:
https://github.com/robjhyndman/forecast/blob/master/R/arima.R
An exception to the resulting prediction intervals being normal around the point estimate is if you have set lambda (are using a Box-Cox transformation) in which case they will not be normal after the back-transformation.
|
How does R calculate prediction intervals in the forecast package?
Unless you are using the forecast function's bootstrap = TRUE option the forecast package's ARIMA intervals are calculated by passing an ARIMA object to predict(). The intervals assume that residuals
|
41,112
|
How does R calculate prediction intervals in the forecast package?
| ERROR: type should be string, got "https://www.otexts.org/fpp/2/7 Goes into some further detail.\n95% prediction interval is $y^t \\pm 1.96 \\sigma$ \nand\n80% prediction interval is $y^t \\pm 1.28 \\sigma$\nWhere $y^t$ is a forecast value and $\\sigma$ \"is an estimate of the standard deviation of the forecast distribution\"."
|
How does R calculate prediction intervals in the forecast package?
| ERROR: type should be string, got "https://www.otexts.org/fpp/2/7 Goes into some further detail.\n95% prediction interval is $y^t \\pm 1.96 \\sigma$ \nand\n80% prediction interval is $y^t \\pm 1.28 \\sigma$\nWhere $y^t$ is a forecast value and"
|
How does R calculate prediction intervals in the forecast package?
https://www.otexts.org/fpp/2/7 Goes into some further detail.
95% prediction interval is $y^t \pm 1.96 \sigma$
and
80% prediction interval is $y^t \pm 1.28 \sigma$
Where $y^t$ is a forecast value and $\sigma$ "is an estimate of the standard deviation of the forecast distribution".
|
How does R calculate prediction intervals in the forecast package?
https://www.otexts.org/fpp/2/7 Goes into some further detail.
95% prediction interval is $y^t \pm 1.96 \sigma$
and
80% prediction interval is $y^t \pm 1.28 \sigma$
Where $y^t$ is a forecast value and
|
41,113
|
Is Theano using back-propagation?
|
Theano creates a symbolic graph. This graph allows it to compute derivatives based on the connected inputs, the Op implemented on the Variables, and the output(created by the Apply Node).
import theano.tensor as T
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
The Apply nodes are blue, Variables are red, Op is green, and Types are purple.
As given in the theano official documentation,
Having the graph structure, computing automatic differentiation is simple. The only thing tensor.grad() has to do is to traverse the graph from the outputs back towards the inputs through all apply nodes (apply nodes are those that define which computations the graph does). For each such apply node, its op defines how to compute the gradient of the node’s outputs with respect to its inputs. Note that if an op does not provide this information, it is assumed that the gradient is not defined. Using the chain rule these gradients can be composed in order to obtain the expression of the gradient of the graph’s output with respect to the graph’s inputs .
Comparing with the Python language, an Apply node is Theano’s version of a function call whereas an Op is Theano’s version of a function definition.
While finding derivatives by hand is simple for feed forward neural networks, it becomes exceedingly complex in the case of Recurrent Neural Networks and Long Short Term Memory Cells, especially if the network is deep.
|
Is Theano using back-propagation?
|
Theano creates a symbolic graph. This graph allows it to compute derivatives based on the connected inputs, the Op implemented on the Variables, and the output(created by the Apply Node).
import thean
|
Is Theano using back-propagation?
Theano creates a symbolic graph. This graph allows it to compute derivatives based on the connected inputs, the Op implemented on the Variables, and the output(created by the Apply Node).
import theano.tensor as T
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
The Apply nodes are blue, Variables are red, Op is green, and Types are purple.
As given in the theano official documentation,
Having the graph structure, computing automatic differentiation is simple. The only thing tensor.grad() has to do is to traverse the graph from the outputs back towards the inputs through all apply nodes (apply nodes are those that define which computations the graph does). For each such apply node, its op defines how to compute the gradient of the node’s outputs with respect to its inputs. Note that if an op does not provide this information, it is assumed that the gradient is not defined. Using the chain rule these gradients can be composed in order to obtain the expression of the gradient of the graph’s output with respect to the graph’s inputs .
Comparing with the Python language, an Apply node is Theano’s version of a function call whereas an Op is Theano’s version of a function definition.
While finding derivatives by hand is simple for feed forward neural networks, it becomes exceedingly complex in the case of Recurrent Neural Networks and Long Short Term Memory Cells, especially if the network is deep.
|
Is Theano using back-propagation?
Theano creates a symbolic graph. This graph allows it to compute derivatives based on the connected inputs, the Op implemented on the Variables, and the output(created by the Apply Node).
import thean
|
41,114
|
Is Theano using back-propagation?
|
I think that when you refer to "backpropagation" here you're really meaning "automatic differentiation". The alternative would be "symbolic differentiation", where you find a formula for the derivative of some loss wrt some parameter and compute gradients according to that formula.
Theano sort of combines both. Each Op defines a function for the forward pass and a function for propagating the gradient back, and theano takes care of passing signals between these functions to implement backpropagation. This alone would just be (reverse mode) automatic differentiation.
The thing is theano also has an optimizer which can simplify expressions to reduce computation (eg $x_1\cdot W+x_2\cdot W \rightarrow (x_1+x_2)\cdot W$) or for numerical stability, which makes it a bit more like symbolic differentiation.
There's more discussion on the topic here.
|
Is Theano using back-propagation?
|
I think that when you refer to "backpropagation" here you're really meaning "automatic differentiation". The alternative would be "symbolic differentiation", where you find a formula for the derivati
|
Is Theano using back-propagation?
I think that when you refer to "backpropagation" here you're really meaning "automatic differentiation". The alternative would be "symbolic differentiation", where you find a formula for the derivative of some loss wrt some parameter and compute gradients according to that formula.
Theano sort of combines both. Each Op defines a function for the forward pass and a function for propagating the gradient back, and theano takes care of passing signals between these functions to implement backpropagation. This alone would just be (reverse mode) automatic differentiation.
The thing is theano also has an optimizer which can simplify expressions to reduce computation (eg $x_1\cdot W+x_2\cdot W \rightarrow (x_1+x_2)\cdot W$) or for numerical stability, which makes it a bit more like symbolic differentiation.
There's more discussion on the topic here.
|
Is Theano using back-propagation?
I think that when you refer to "backpropagation" here you're really meaning "automatic differentiation". The alternative would be "symbolic differentiation", where you find a formula for the derivati
|
41,115
|
projecting survival curves estimates into the future
|
As far as I am aware, there is no way to extrapolate beyond that point with standard R-software.
And with good reason too: the Kaplan Meier curves do not make assumptions about the parametric distribution of the data. Because of this, they are complete indifferent to the assignment of probability mass beyond the last observed event.
I'm glossing over some details here, but suppose in your dataset, only 30% of subjects are observed to have had events. You would be hard pressed to estimate the 90% percentile without making very strong assumptions about the parametric family the data was generated from. So if you really want to make estimations beyond t = 6,000, you will probably need to switch to a parametric estimator (also, you should be very skeptical about those estimates!!)
|
projecting survival curves estimates into the future
|
As far as I am aware, there is no way to extrapolate beyond that point with standard R-software.
And with good reason too: the Kaplan Meier curves do not make assumptions about the parametric distrib
|
projecting survival curves estimates into the future
As far as I am aware, there is no way to extrapolate beyond that point with standard R-software.
And with good reason too: the Kaplan Meier curves do not make assumptions about the parametric distribution of the data. Because of this, they are complete indifferent to the assignment of probability mass beyond the last observed event.
I'm glossing over some details here, but suppose in your dataset, only 30% of subjects are observed to have had events. You would be hard pressed to estimate the 90% percentile without making very strong assumptions about the parametric family the data was generated from. So if you really want to make estimations beyond t = 6,000, you will probably need to switch to a parametric estimator (also, you should be very skeptical about those estimates!!)
|
projecting survival curves estimates into the future
As far as I am aware, there is no way to extrapolate beyond that point with standard R-software.
And with good reason too: the Kaplan Meier curves do not make assumptions about the parametric distrib
|
41,116
|
Suppose $X_1 X_2, ..., X_n$ are $n$ independent variables, is their Covariance matrix, $\Sigma$, diagonal?
|
Independence implies zero correlation (but the converse doesn't hold):
$\:\:E(XY)=\int\int \,x\,y\, f(x,y)\, dy \,dx$
$\qquad\qquad=\int\,\int x\,y \,f(x)\,f(y)\, dy\, dx\quad$ (independence)
$\qquad\qquad=\int\, y\, f(y)\, dy\,\cdot\,\int\, x \,f(x)\, dx$
$\qquad\qquad=E(X)\,E(Y)$
Hence $\text{Cov}(X,Y)=E(XY)-E(X)E(Y)=E(X)E(Y)-E(X)E(Y)=0$
Consequently each off-diagonal term in the covariance matrix should be 0.
|
Suppose $X_1 X_2, ..., X_n$ are $n$ independent variables, is their Covariance matrix, $\Sigma$, dia
|
Independence implies zero correlation (but the converse doesn't hold):
$\:\:E(XY)=\int\int \,x\,y\, f(x,y)\, dy \,dx$
$\qquad\qquad=\int\,\int x\,y \,f(x)\,f(y)\, dy\, dx\quad$ (independence)
$\qquad\
|
Suppose $X_1 X_2, ..., X_n$ are $n$ independent variables, is their Covariance matrix, $\Sigma$, diagonal?
Independence implies zero correlation (but the converse doesn't hold):
$\:\:E(XY)=\int\int \,x\,y\, f(x,y)\, dy \,dx$
$\qquad\qquad=\int\,\int x\,y \,f(x)\,f(y)\, dy\, dx\quad$ (independence)
$\qquad\qquad=\int\, y\, f(y)\, dy\,\cdot\,\int\, x \,f(x)\, dx$
$\qquad\qquad=E(X)\,E(Y)$
Hence $\text{Cov}(X,Y)=E(XY)-E(X)E(Y)=E(X)E(Y)-E(X)E(Y)=0$
Consequently each off-diagonal term in the covariance matrix should be 0.
|
Suppose $X_1 X_2, ..., X_n$ are $n$ independent variables, is their Covariance matrix, $\Sigma$, dia
Independence implies zero correlation (but the converse doesn't hold):
$\:\:E(XY)=\int\int \,x\,y\, f(x,y)\, dy \,dx$
$\qquad\qquad=\int\,\int x\,y \,f(x)\,f(y)\, dy\, dx\quad$ (independence)
$\qquad\
|
41,117
|
Computing Dvoretzky–Kiefer–Wolfowitz bounds in MATLAB
|
It sounds like you want to compute a confidence band: a region that contains the whole CDF with probability $1-\alpha$. Doing this with the Dvoretzky–Kiefer–Wolfowitz inequality involves three steps:
Generate the CDF (i.e., sort and count your values--trivial in matlab)
The inequality itself says that
$$ P\bigg(\sup_x \big|F(x) - \hat{F}(x)\big| \gt \epsilon\bigg) \le 2\exp(-2n\epsilon^2)$$ where
$F(x)$ is the "true" population CDF, $\hat{F}(x)$ is your sample CDF, and $n$ is the number of data points. Setting the right hand side of that inequality to $\alpha$ and rearranging yields:
$$ \epsilon = \sqrt{\frac{1}{2n}\log\bigg(\frac{2}{\alpha}}\bigg)$$
You can now draw the confidence band. The confidence band has an upper edge $U(x)$ and a lower edge $L(x)$:
$$ \begin{align*}
L(x) = max\{\hat{F}(x) &- \epsilon, 0\} \\
U(x) = min\{\hat{F}(x) &+ \epsilon, 1\}
\end{align*}$$
Translating this into matlab is pretty trivial:
function [low_edge, F_hat, hi_edge, x] = dkw_bounds(data, alpha)
[F_hat, x] = ecdf(data);
epsilon = sqrt(ln(2/alpha)/(2*length(data)));
low_edge = max(F_hat - epsilon, 0); %Does the right thing here, use pmax in R
hi_edge = min(F_hat + epsilon, 1);
end
You can then plot the three curves, use them to form a patch, etc.
|
Computing Dvoretzky–Kiefer–Wolfowitz bounds in MATLAB
|
It sounds like you want to compute a confidence band: a region that contains the whole CDF with probability $1-\alpha$. Doing this with the Dvoretzky–Kiefer–Wolfowitz inequality involves three steps:
|
Computing Dvoretzky–Kiefer–Wolfowitz bounds in MATLAB
It sounds like you want to compute a confidence band: a region that contains the whole CDF with probability $1-\alpha$. Doing this with the Dvoretzky–Kiefer–Wolfowitz inequality involves three steps:
Generate the CDF (i.e., sort and count your values--trivial in matlab)
The inequality itself says that
$$ P\bigg(\sup_x \big|F(x) - \hat{F}(x)\big| \gt \epsilon\bigg) \le 2\exp(-2n\epsilon^2)$$ where
$F(x)$ is the "true" population CDF, $\hat{F}(x)$ is your sample CDF, and $n$ is the number of data points. Setting the right hand side of that inequality to $\alpha$ and rearranging yields:
$$ \epsilon = \sqrt{\frac{1}{2n}\log\bigg(\frac{2}{\alpha}}\bigg)$$
You can now draw the confidence band. The confidence band has an upper edge $U(x)$ and a lower edge $L(x)$:
$$ \begin{align*}
L(x) = max\{\hat{F}(x) &- \epsilon, 0\} \\
U(x) = min\{\hat{F}(x) &+ \epsilon, 1\}
\end{align*}$$
Translating this into matlab is pretty trivial:
function [low_edge, F_hat, hi_edge, x] = dkw_bounds(data, alpha)
[F_hat, x] = ecdf(data);
epsilon = sqrt(ln(2/alpha)/(2*length(data)));
low_edge = max(F_hat - epsilon, 0); %Does the right thing here, use pmax in R
hi_edge = min(F_hat + epsilon, 1);
end
You can then plot the three curves, use them to form a patch, etc.
|
Computing Dvoretzky–Kiefer–Wolfowitz bounds in MATLAB
It sounds like you want to compute a confidence band: a region that contains the whole CDF with probability $1-\alpha$. Doing this with the Dvoretzky–Kiefer–Wolfowitz inequality involves three steps:
|
41,118
|
Discrepancy between metafor and weighted lm() standard errors
|
A while ago, I wrote up an extensive comparison between the rma() function from the metafor package and the lm() and lme() functions (the latter from the nlme package) for fitting fixed- and random/mixed-effects models. You can find this on the metafor package website:
http://www.metafor-project.org/doku.php/tips:rma_vs_lm_and_lme
To briefly summarize: When you use the lm() and lme() functions with weights, then this fits models that assume that the weights (i.e., sampling variances) are known only up to a proportionality constant -- which is in fact the error variance that is estimated. Those are not standard meta-analytic models as commonly described in the literature.
|
Discrepancy between metafor and weighted lm() standard errors
|
A while ago, I wrote up an extensive comparison between the rma() function from the metafor package and the lm() and lme() functions (the latter from the nlme package) for fitting fixed- and random/mi
|
Discrepancy between metafor and weighted lm() standard errors
A while ago, I wrote up an extensive comparison between the rma() function from the metafor package and the lm() and lme() functions (the latter from the nlme package) for fitting fixed- and random/mixed-effects models. You can find this on the metafor package website:
http://www.metafor-project.org/doku.php/tips:rma_vs_lm_and_lme
To briefly summarize: When you use the lm() and lme() functions with weights, then this fits models that assume that the weights (i.e., sampling variances) are known only up to a proportionality constant -- which is in fact the error variance that is estimated. Those are not standard meta-analytic models as commonly described in the literature.
|
Discrepancy between metafor and weighted lm() standard errors
A while ago, I wrote up an extensive comparison between the rma() function from the metafor package and the lm() and lme() functions (the latter from the nlme package) for fitting fixed- and random/mi
|
41,119
|
What is a good method to identify outliers in exam data?
|
Have you considered Item Response Theory-based methods? IRT is designed especially for this kind of purposes.
Simple example is Rasch model that lets you compute both the student abilities and question difficulty in a single generalized linear model (or generalized linear mixed model). With binary answer format the Rasch model could be written as
$$P(X_{ij} = 1) = \frac{\exp(\theta_i - \beta_j)}{1+\exp(\theta_i - \beta_j)} $$
where response $1$ by $i$-th student for $j$-th test item is modeled as a function of student's abilities $\theta_i$ and item's difficulty $\beta_j$. There are also models considering more than one item parameter (e.g. item discrimination, guessing), models for items with polytomous answering format, or such models that include other additional explanatory or grouping variables. In measuring student's abilities the model "weights" test items by their difficulty so you don't have to worry about the fact that some items are easier and some are harder. If you are interested in item difficulty you can check their $\beta_j$ values. There are also additional tools for measuring item- and person-fit that may be helpful for identifying item- and person-outliers.
This model is suited for "static" tests with finite number of items, but missing-data design is also possible, where you threat the non-answered questions as missing data and impute their answers using your model. Usually EM algorithm is used for estimation but for more complicated designs Bayesian approach is more suitable.
Those methods are really design-specific so it is hard to give a single answer. There are multiple books available, e.g. a nice introduction Item Response Theory for Psychologists by Susan E. Embretson and Steven P. Reise.
|
What is a good method to identify outliers in exam data?
|
Have you considered Item Response Theory-based methods? IRT is designed especially for this kind of purposes.
Simple example is Rasch model that lets you compute both the student abilities and questio
|
What is a good method to identify outliers in exam data?
Have you considered Item Response Theory-based methods? IRT is designed especially for this kind of purposes.
Simple example is Rasch model that lets you compute both the student abilities and question difficulty in a single generalized linear model (or generalized linear mixed model). With binary answer format the Rasch model could be written as
$$P(X_{ij} = 1) = \frac{\exp(\theta_i - \beta_j)}{1+\exp(\theta_i - \beta_j)} $$
where response $1$ by $i$-th student for $j$-th test item is modeled as a function of student's abilities $\theta_i$ and item's difficulty $\beta_j$. There are also models considering more than one item parameter (e.g. item discrimination, guessing), models for items with polytomous answering format, or such models that include other additional explanatory or grouping variables. In measuring student's abilities the model "weights" test items by their difficulty so you don't have to worry about the fact that some items are easier and some are harder. If you are interested in item difficulty you can check their $\beta_j$ values. There are also additional tools for measuring item- and person-fit that may be helpful for identifying item- and person-outliers.
This model is suited for "static" tests with finite number of items, but missing-data design is also possible, where you threat the non-answered questions as missing data and impute their answers using your model. Usually EM algorithm is used for estimation but for more complicated designs Bayesian approach is more suitable.
Those methods are really design-specific so it is hard to give a single answer. There are multiple books available, e.g. a nice introduction Item Response Theory for Psychologists by Susan E. Embretson and Steven P. Reise.
|
What is a good method to identify outliers in exam data?
Have you considered Item Response Theory-based methods? IRT is designed especially for this kind of purposes.
Simple example is Rasch model that lets you compute both the student abilities and questio
|
41,120
|
What is a good method to identify outliers in exam data?
|
You might try fitting a logistic model. Response is a whether the answer was correct or not. You could add a (random?) effect for the student and a fixed effect for each question. You could develop a ranking based on the coefficients for each question.
|
What is a good method to identify outliers in exam data?
|
You might try fitting a logistic model. Response is a whether the answer was correct or not. You could add a (random?) effect for the student and a fixed effect for each question. You could develop a
|
What is a good method to identify outliers in exam data?
You might try fitting a logistic model. Response is a whether the answer was correct or not. You could add a (random?) effect for the student and a fixed effect for each question. You could develop a ranking based on the coefficients for each question.
|
What is a good method to identify outliers in exam data?
You might try fitting a logistic model. Response is a whether the answer was correct or not. You could add a (random?) effect for the student and a fixed effect for each question. You could develop a
|
41,121
|
How to interpret R VIF function in CAR package?
|
The vif function in the car package works like this:
Run an OLS regression that has for example $X_1$ as a dependent variable on the left hand side and all your other independent variables on the right hand side.
Take the $R^2$ from the regression in 1 and stick it into this equation: ${\rm VIF} = \frac{1}{1-R_i^2}$.
This is done for every independent variable of your regression.
|
How to interpret R VIF function in CAR package?
|
The vif function in the car package works like this:
Run an OLS regression that has for example $X_1$ as a dependent variable on the left hand side and all your other independent variables on the rig
|
How to interpret R VIF function in CAR package?
The vif function in the car package works like this:
Run an OLS regression that has for example $X_1$ as a dependent variable on the left hand side and all your other independent variables on the right hand side.
Take the $R^2$ from the regression in 1 and stick it into this equation: ${\rm VIF} = \frac{1}{1-R_i^2}$.
This is done for every independent variable of your regression.
|
How to interpret R VIF function in CAR package?
The vif function in the car package works like this:
Run an OLS regression that has for example $X_1$ as a dependent variable on the left hand side and all your other independent variables on the rig
|
41,122
|
Intuitive meaning of error-in-variables
|
For the intuition you can imagine the signal from your favorite radio station that you receive in your car. That's the variable. Sometimes the weather isn't good and then the signal is disturbed such that you hear noise during the song and the bigger the disturbance the more noise will interfere with your song until you may not even hear it anymore.
The same can happen with variables if they are misreported as in household surveys, among others. Whenever you have self-reported or non-administrative data this is a worry. Suppose you want to regress
$$Y_i = \alpha + \beta X_i + \epsilon_i$$
but you observe $\tilde{X}_i = X_i + \eta_i$ because you were sleepy when you entered the data in your datasheet and every now and then you made a mistake in entering the data. This adds the "noise" we were talking about before. This is represented by $\eta_i$ here. Let's say that you made this sleepiness error at random so it is uncorrelated with $X_i$ and $\epsilon_i$. If you then regress
$$Y_i = \alpha + \beta \tilde{X}_i + u_i$$
with $u_i = \epsilon_i - \beta \eta_i$, you know that your estimated coefficient is
$$\begin{align}
\widehat{\beta} &= \frac{Cov(Y_i,\tilde{X}_i)}{Var(\tilde{X}_i)} \\
&= \frac{Cov(\alpha + \beta \tilde{X}_i + u_i,\tilde{X}_i)}{Var(\tilde{X}_i)} \\
&= \beta + \frac{Cov(u_i,\tilde{X}_i)}{Var(X_i + \eta_i)} \\
&= \beta + \frac{Cov(\epsilon_i -\beta \eta_i , X_i + \eta_i)}{Var(X_i + \eta_i)} \\
&= \beta \left(1 - \frac{Var(\eta_i)}{{Var(X_i + \eta_i)}} \right)
\end{align}
$$
The second line expands $Y_i$. The third line splits the covariance into the sum of covariances, the fourth line uses the definitions of $u_i$ and $\tilde{X}_i$. Then use the fact that $\eta_i$ is uncorrelated with $X_i$ and $\epsilon_i$. The last line factors. In the bracket of the last line you have one minus the inverse of the signal-to-noise ratio.
The bigger the noise becomes relative to the signal the worse will be the song in your radio. The signal-to-noise ratio lies between 0 and 1, so if there is only noise you will not hear the song anymore. This is the so-called attenuation bias of your estimated $\widehat{\beta}$ due to the measurement error.
With regards to whuber's comment that you need a very strong noise in order to affect the results: in panel data methods the attenuation bias is propagated (see Griliches and Hausman, 1986). For example, if somebody reports a 9 dollars hourly wage in year 1 when in reality she gets 10 dollars then this is just an error of 10% for OLS. Now if she gets 12 dollars in year 2 (suppose now you have a panel data set) and you want to take advantage of the panel structure by first differencing, your first difference is $12 - 9 = 3$ but in reality it should have been $12 - 10 = 2$. So now the measurment error has increased to a half.
|
Intuitive meaning of error-in-variables
|
For the intuition you can imagine the signal from your favorite radio station that you receive in your car. That's the variable. Sometimes the weather isn't good and then the signal is disturbed such
|
Intuitive meaning of error-in-variables
For the intuition you can imagine the signal from your favorite radio station that you receive in your car. That's the variable. Sometimes the weather isn't good and then the signal is disturbed such that you hear noise during the song and the bigger the disturbance the more noise will interfere with your song until you may not even hear it anymore.
The same can happen with variables if they are misreported as in household surveys, among others. Whenever you have self-reported or non-administrative data this is a worry. Suppose you want to regress
$$Y_i = \alpha + \beta X_i + \epsilon_i$$
but you observe $\tilde{X}_i = X_i + \eta_i$ because you were sleepy when you entered the data in your datasheet and every now and then you made a mistake in entering the data. This adds the "noise" we were talking about before. This is represented by $\eta_i$ here. Let's say that you made this sleepiness error at random so it is uncorrelated with $X_i$ and $\epsilon_i$. If you then regress
$$Y_i = \alpha + \beta \tilde{X}_i + u_i$$
with $u_i = \epsilon_i - \beta \eta_i$, you know that your estimated coefficient is
$$\begin{align}
\widehat{\beta} &= \frac{Cov(Y_i,\tilde{X}_i)}{Var(\tilde{X}_i)} \\
&= \frac{Cov(\alpha + \beta \tilde{X}_i + u_i,\tilde{X}_i)}{Var(\tilde{X}_i)} \\
&= \beta + \frac{Cov(u_i,\tilde{X}_i)}{Var(X_i + \eta_i)} \\
&= \beta + \frac{Cov(\epsilon_i -\beta \eta_i , X_i + \eta_i)}{Var(X_i + \eta_i)} \\
&= \beta \left(1 - \frac{Var(\eta_i)}{{Var(X_i + \eta_i)}} \right)
\end{align}
$$
The second line expands $Y_i$. The third line splits the covariance into the sum of covariances, the fourth line uses the definitions of $u_i$ and $\tilde{X}_i$. Then use the fact that $\eta_i$ is uncorrelated with $X_i$ and $\epsilon_i$. The last line factors. In the bracket of the last line you have one minus the inverse of the signal-to-noise ratio.
The bigger the noise becomes relative to the signal the worse will be the song in your radio. The signal-to-noise ratio lies between 0 and 1, so if there is only noise you will not hear the song anymore. This is the so-called attenuation bias of your estimated $\widehat{\beta}$ due to the measurement error.
With regards to whuber's comment that you need a very strong noise in order to affect the results: in panel data methods the attenuation bias is propagated (see Griliches and Hausman, 1986). For example, if somebody reports a 9 dollars hourly wage in year 1 when in reality she gets 10 dollars then this is just an error of 10% for OLS. Now if she gets 12 dollars in year 2 (suppose now you have a panel data set) and you want to take advantage of the panel structure by first differencing, your first difference is $12 - 9 = 3$ but in reality it should have been $12 - 10 = 2$. So now the measurment error has increased to a half.
|
Intuitive meaning of error-in-variables
For the intuition you can imagine the signal from your favorite radio station that you receive in your car. That's the variable. Sometimes the weather isn't good and then the signal is disturbed such
|
41,123
|
Rebuilding a signal using the fast fourier transform [closed]
|
Sine and Cosine are the same wave shifted by $\pi/2$ in phase $$\cos(x)=\sin(x+\pi/2)$$. Fourier transform returns you a complex number for each frequency. This number has the amplitude and the angle (phase). It's basically a set of Sine waves with amplitudes and phases. Equivalently, you can re-write them as a sum of Sine and Cosine waves of different amplitudes.
Example:
phase <- Arg(fou)
sx=ampl[4]*cos(2*pi*freq[4]*stp+phase[4])+ampl[10]*cos(2*pi*freq[10]*stp+phase[10])
plot(sx)
|
Rebuilding a signal using the fast fourier transform [closed]
|
Sine and Cosine are the same wave shifted by $\pi/2$ in phase $$\cos(x)=\sin(x+\pi/2)$$. Fourier transform returns you a complex number for each frequency. This number has the amplitude and the angle
|
Rebuilding a signal using the fast fourier transform [closed]
Sine and Cosine are the same wave shifted by $\pi/2$ in phase $$\cos(x)=\sin(x+\pi/2)$$. Fourier transform returns you a complex number for each frequency. This number has the amplitude and the angle (phase). It's basically a set of Sine waves with amplitudes and phases. Equivalently, you can re-write them as a sum of Sine and Cosine waves of different amplitudes.
Example:
phase <- Arg(fou)
sx=ampl[4]*cos(2*pi*freq[4]*stp+phase[4])+ampl[10]*cos(2*pi*freq[10]*stp+phase[10])
plot(sx)
|
Rebuilding a signal using the fast fourier transform [closed]
Sine and Cosine are the same wave shifted by $\pi/2$ in phase $$\cos(x)=\sin(x+\pi/2)$$. Fourier transform returns you a complex number for each frequency. This number has the amplitude and the angle
|
41,124
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
|
I think these two are actually very similar. In the experimental settings, you are comparing some mean outcome for treated versus control and you are worried that there might be individuals with some observed characteristics who appear only among participants or non-participants (or appear more often) and/or that this is happening with some unobserved characteristics, which is a much harder problem.
In the prototypical survey setting, you are essentially comparing wages for low-education (C) and high-education (T) women, and you are worried that you are not observing women with large negative unobservables in the low education groups because they are not in the labor force. Education might be multivalued rather than binary, but the spirit of this comparative exercise is the same.
In both cases, you are using the average outcome for the control or low-education groups in place of what would have happened to the treated or high-education group in the absence of that treatment or education, which is something you don't see.
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
|
I think these two are actually very similar. In the experimental settings, you are comparing some mean outcome for treated versus control and you are worried that there might be individuals with some
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
I think these two are actually very similar. In the experimental settings, you are comparing some mean outcome for treated versus control and you are worried that there might be individuals with some observed characteristics who appear only among participants or non-participants (or appear more often) and/or that this is happening with some unobserved characteristics, which is a much harder problem.
In the prototypical survey setting, you are essentially comparing wages for low-education (C) and high-education (T) women, and you are worried that you are not observing women with large negative unobservables in the low education groups because they are not in the labor force. Education might be multivalued rather than binary, but the spirit of this comparative exercise is the same.
In both cases, you are using the average outcome for the control or low-education groups in place of what would have happened to the treated or high-education group in the absence of that treatment or education, which is something you don't see.
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
I think these two are actually very similar. In the experimental settings, you are comparing some mean outcome for treated versus control and you are worried that there might be individuals with some
|
41,125
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
|
I like @DimitriyV.Masterov's answer (+1); they are very similar and you could probably use "selection bias" for "differential probability of selection to the programme treatment group". However, I am somewhat uncomfortable with that usage and think it would probably be better to use different phrasing.
You don't really select people into treatment groups, you assign them. If the probability of a person being assigned to a treatment group is not independent of their attributes (e.g., healthier patients are more likely to go into the control group), then I think it is better to say that the assignment is confounded.
On the other hand, if your study is observational in nature, there is no assignment at all. The status of all variables, whether categorical (sick / healthy) or continuous (weight), should be understood as endogenous / correlated with unknown confounders. In the world as we find it (that is, without our acting on the world exogenously by manipulating the levels of a variable and assigning people to those levels), everything is ultimately related to everything somehow. It may well be that in selecting your sample, you were more likely to draw people with certain properties than people with different properties, such that the (say) proportion of people in your sample dieting to lose weight is higher than in the population (and the proportion of people exercising to lose weight is lower that in the population). But this is not assignment. I would call that situation a biased "selection to the study sample", but I wouldn't call it a biased "selection to the programme treatment group".
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
|
I like @DimitriyV.Masterov's answer (+1); they are very similar and you could probably use "selection bias" for "differential probability of selection to the programme treatment group". However, I am
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
I like @DimitriyV.Masterov's answer (+1); they are very similar and you could probably use "selection bias" for "differential probability of selection to the programme treatment group". However, I am somewhat uncomfortable with that usage and think it would probably be better to use different phrasing.
You don't really select people into treatment groups, you assign them. If the probability of a person being assigned to a treatment group is not independent of their attributes (e.g., healthier patients are more likely to go into the control group), then I think it is better to say that the assignment is confounded.
On the other hand, if your study is observational in nature, there is no assignment at all. The status of all variables, whether categorical (sick / healthy) or continuous (weight), should be understood as endogenous / correlated with unknown confounders. In the world as we find it (that is, without our acting on the world exogenously by manipulating the levels of a variable and assigning people to those levels), everything is ultimately related to everything somehow. It may well be that in selecting your sample, you were more likely to draw people with certain properties than people with different properties, such that the (say) proportion of people in your sample dieting to lose weight is higher than in the population (and the proportion of people exercising to lose weight is lower that in the population). But this is not assignment. I would call that situation a biased "selection to the study sample", but I wouldn't call it a biased "selection to the programme treatment group".
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
I like @DimitriyV.Masterov's answer (+1); they are very similar and you could probably use "selection bias" for "differential probability of selection to the programme treatment group". However, I am
|
41,126
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
|
Selection Bias occurs when there is no appropriate randomization achieved while selecting individuals, groups or data to be analysed.
Selection bias implies that the obtained sample does not exactly represent the population that was actually intended to be analyzed.
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
|
Selection Bias occurs when there is no appropriate randomization achieved while selecting individuals, groups or data to be analysed.
Selection bias implies that the obtained sample does not exactly r
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
Selection Bias occurs when there is no appropriate randomization achieved while selecting individuals, groups or data to be analysed.
Selection bias implies that the obtained sample does not exactly represent the population that was actually intended to be analyzed.
|
Can 'selection bias' refer to bias in the intervention as well as in the sampling?
Selection Bias occurs when there is no appropriate randomization achieved while selecting individuals, groups or data to be analysed.
Selection bias implies that the obtained sample does not exactly r
|
41,127
|
Handling outliers in Bayesian linear regression
|
Consider a set of data with no outlying observations, at a suitable value of the parameters. Now consider moving an observation far into the tail (keeping parameter values and the remaining data constant)
If the density has thin tails, an observation far away is very unlikely (has low relative probability given the parameters), so the chance of seeing it ... and hence the likelihood would be higher if the parameters were moved substantially to accommodate it (there's a limit to how far of course, as the more you move the parameters, the less probable the remainder of the data become.
By contrast a distribution with fat tails doesn't see that observation as unusual at all, and may hardly need to change in response to it.
|
Handling outliers in Bayesian linear regression
|
Consider a set of data with no outlying observations, at a suitable value of the parameters. Now consider moving an observation far into the tail (keeping parameter values and the remaining data const
|
Handling outliers in Bayesian linear regression
Consider a set of data with no outlying observations, at a suitable value of the parameters. Now consider moving an observation far into the tail (keeping parameter values and the remaining data constant)
If the density has thin tails, an observation far away is very unlikely (has low relative probability given the parameters), so the chance of seeing it ... and hence the likelihood would be higher if the parameters were moved substantially to accommodate it (there's a limit to how far of course, as the more you move the parameters, the less probable the remainder of the data become.
By contrast a distribution with fat tails doesn't see that observation as unusual at all, and may hardly need to change in response to it.
|
Handling outliers in Bayesian linear regression
Consider a set of data with no outlying observations, at a suitable value of the parameters. Now consider moving an observation far into the tail (keeping parameter values and the remaining data const
|
41,128
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
|
You can use MuMIn package and its r.squaredGLMM() function which will give you 2 approximated r-squared values based on Nakagawa & Schielzeth (2012) and Johnson (2014):
Marginal R^2 is the proportion of variance explained by the fixed effects alone.
Conditional R^2 is the proportion of variance explained by the fixed and random effects jointly.
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
|
You can use MuMIn package and its r.squaredGLMM() function which will give you 2 approximated r-squared values based on Nakagawa & Schielzeth (2012) and Johnson (2014):
Marginal R^2 is the proportion
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
You can use MuMIn package and its r.squaredGLMM() function which will give you 2 approximated r-squared values based on Nakagawa & Schielzeth (2012) and Johnson (2014):
Marginal R^2 is the proportion of variance explained by the fixed effects alone.
Conditional R^2 is the proportion of variance explained by the fixed and random effects jointly.
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
You can use MuMIn package and its r.squaredGLMM() function which will give you 2 approximated r-squared values based on Nakagawa & Schielzeth (2012) and Johnson (2014):
Marginal R^2 is the proportion
|
41,129
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
|
"Variance explained" by the model is described by $R^2$ statistic. For LMM's Nakagawa and Schielzeth (2013) suggested that $R^2$ could be decomposed into variance explained by fixed effects ($R^2_m$) and random effects ($R^2_c$) (see here). In this approach, variance explained by the fixed effects is defined as:
$$R^2_m = \frac{\sigma^2_f}{\sigma^2_f + \sigma^2_\alpha + \sigma^2_\varepsilon}$$
where:
$$\sigma^2_f = var\left( \sum^M_{m=1} \beta_m X_m \right)$$
where $X_1,...,X_m$ are $M$ independent variables, $\sigma^2_\alpha$ is variance of random effect and $\sigma^2_\varepsilon$ is residual variance. So it gives you a part of what you are interested in. However, you have to remember that $R^2$ is not a perfect measure, e.g. this question: Is $R^2$ useful or dangerous?.
You could also find this tutorial on ANOVA and lme4 helpful.
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
|
"Variance explained" by the model is described by $R^2$ statistic. For LMM's Nakagawa and Schielzeth (2013) suggested that $R^2$ could be decomposed into variance explained by fixed effects ($R^2_m$)
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
"Variance explained" by the model is described by $R^2$ statistic. For LMM's Nakagawa and Schielzeth (2013) suggested that $R^2$ could be decomposed into variance explained by fixed effects ($R^2_m$) and random effects ($R^2_c$) (see here). In this approach, variance explained by the fixed effects is defined as:
$$R^2_m = \frac{\sigma^2_f}{\sigma^2_f + \sigma^2_\alpha + \sigma^2_\varepsilon}$$
where:
$$\sigma^2_f = var\left( \sum^M_{m=1} \beta_m X_m \right)$$
where $X_1,...,X_m$ are $M$ independent variables, $\sigma^2_\alpha$ is variance of random effect and $\sigma^2_\varepsilon$ is residual variance. So it gives you a part of what you are interested in. However, you have to remember that $R^2$ is not a perfect measure, e.g. this question: Is $R^2$ useful or dangerous?.
You could also find this tutorial on ANOVA and lme4 helpful.
|
Proportion of variance in dependent variable accounted for by predictors in a mixed effects model
"Variance explained" by the model is described by $R^2$ statistic. For LMM's Nakagawa and Schielzeth (2013) suggested that $R^2$ could be decomposed into variance explained by fixed effects ($R^2_m$)
|
41,130
|
Negative Binomial Regression?
|
Assuming LOS is intended as a DV and not a covariate, "Length of stay" is not really a count (in the required sense), but a (possibly discretized) duration. You wouldn't normally use a count model for that.
I'd be inclined toward using a survival model; that will also enable you to cope with the likely censoring (for people who are still in hospital when you stop taking data, for example -- you can't just leave them out because their duration wasn't finished, otherwise you'll be biasing against people with long LOS).
|
Negative Binomial Regression?
|
Assuming LOS is intended as a DV and not a covariate, "Length of stay" is not really a count (in the required sense), but a (possibly discretized) duration. You wouldn't normally use a count model for
|
Negative Binomial Regression?
Assuming LOS is intended as a DV and not a covariate, "Length of stay" is not really a count (in the required sense), but a (possibly discretized) duration. You wouldn't normally use a count model for that.
I'd be inclined toward using a survival model; that will also enable you to cope with the likely censoring (for people who are still in hospital when you stop taking data, for example -- you can't just leave them out because their duration wasn't finished, otherwise you'll be biasing against people with long LOS).
|
Negative Binomial Regression?
Assuming LOS is intended as a DV and not a covariate, "Length of stay" is not really a count (in the required sense), but a (possibly discretized) duration. You wouldn't normally use a count model for
|
41,131
|
Negative Binomial Regression?
|
The advice you refers (that the count need to refer to the same length time intervals) seems to be irrelevant here. That is meant for a situation where you are counting number of point events within some time interval. But your response variable is a duration, so a completely different situation. So I think you could try with a Poisson (or negative binomial) regression, and then validate it with residual plots and so on.
|
Negative Binomial Regression?
|
The advice you refers (that the count need to refer to the same length time intervals) seems to be irrelevant here. That is meant for a situation where you are counting number of point events within
|
Negative Binomial Regression?
The advice you refers (that the count need to refer to the same length time intervals) seems to be irrelevant here. That is meant for a situation where you are counting number of point events within some time interval. But your response variable is a duration, so a completely different situation. So I think you could try with a Poisson (or negative binomial) regression, and then validate it with residual plots and so on.
|
Negative Binomial Regression?
The advice you refers (that the count need to refer to the same length time intervals) seems to be irrelevant here. That is meant for a situation where you are counting number of point events within
|
41,132
|
Negative Binomial Regression?
|
Negative binomial would still be appropriate. Poisson would be as well, if your data meets the equidispersion assumption. (If it does not, stick with nbreg.)
|
Negative Binomial Regression?
|
Negative binomial would still be appropriate. Poisson would be as well, if your data meets the equidispersion assumption. (If it does not, stick with nbreg.)
|
Negative Binomial Regression?
Negative binomial would still be appropriate. Poisson would be as well, if your data meets the equidispersion assumption. (If it does not, stick with nbreg.)
|
Negative Binomial Regression?
Negative binomial would still be appropriate. Poisson would be as well, if your data meets the equidispersion assumption. (If it does not, stick with nbreg.)
|
41,133
|
Is the mean of equal length subsets always equal to the mean of the set?
|
Would it be accurate to say the mean of equal length subsets is always equal to the mean of the set?
It's always true!
Consider $n=mk$ observations, where you take $k$ mutually-exclusive groups of size $m$.
Label the observations in group $i$ as $x_{ij},\: j=1,2,...,m$.
The individual means are $\bar{x}_i = \frac{1}{m}\sum_{j=1}^m x_{ij}$.
The mean-of-means is
$\overline{\bar{x}_i} = \frac{1}{k}\sum_{i=1}^k \bar{x}_{i}$
$\hspace{.5cm}=\frac{1}{k}\sum_{i=1}^k (\frac{1}{m}\sum_{j=1}^m x_{ij})$
$\hspace{.5cm}=\frac{1}{km}\sum_{i=1}^k \sum_{j=1}^m x_{ij}$
$\hspace{.5cm}=\frac{1}{n}\sum_{i,j} x_{ij}$
which is just the overall mean of the data.
For the unequal-length case, they're also equal (that is, the mean of means equals the overall mean) if you do an appropriately weighted average when taking the mean of means.
|
Is the mean of equal length subsets always equal to the mean of the set?
|
Would it be accurate to say the mean of equal length subsets is always equal to the mean of the set?
It's always true!
Consider $n=mk$ observations, where you take $k$ mutually-exclusive groups of s
|
Is the mean of equal length subsets always equal to the mean of the set?
Would it be accurate to say the mean of equal length subsets is always equal to the mean of the set?
It's always true!
Consider $n=mk$ observations, where you take $k$ mutually-exclusive groups of size $m$.
Label the observations in group $i$ as $x_{ij},\: j=1,2,...,m$.
The individual means are $\bar{x}_i = \frac{1}{m}\sum_{j=1}^m x_{ij}$.
The mean-of-means is
$\overline{\bar{x}_i} = \frac{1}{k}\sum_{i=1}^k \bar{x}_{i}$
$\hspace{.5cm}=\frac{1}{k}\sum_{i=1}^k (\frac{1}{m}\sum_{j=1}^m x_{ij})$
$\hspace{.5cm}=\frac{1}{km}\sum_{i=1}^k \sum_{j=1}^m x_{ij}$
$\hspace{.5cm}=\frac{1}{n}\sum_{i,j} x_{ij}$
which is just the overall mean of the data.
For the unequal-length case, they're also equal (that is, the mean of means equals the overall mean) if you do an appropriately weighted average when taking the mean of means.
|
Is the mean of equal length subsets always equal to the mean of the set?
Would it be accurate to say the mean of equal length subsets is always equal to the mean of the set?
It's always true!
Consider $n=mk$ observations, where you take $k$ mutually-exclusive groups of s
|
41,134
|
Conditional independence iff joint factorizes
|
Since $X$ and $Y$ are independent given $Z$ iff $p(x,y|z)=p(x|z)p(y|z)$, all you need to prove is that, if $p(x,y|z)=g(x,z)h(y,z)$, then $p(x,y|z)=p(x|z)p(y|z)$.
Starting from the equality $p(x,y|z)=g(x,z)h(y,z)$. one can integrate both sides in x: $$
\int_\text{X}p(x,y|z)\text{d}x=\int_\text{X}g(x,z)h(y,z)\text{d}x
$$
This implies
$$
p(y|z)=\int_\text{X}g(x,z)h(y,z)\text{d}x=h(y,z)\int_\text{X}g(x,z)\text{d}x
$$
and tells you that
$$
h(y,z)\propto p(y|z)
$$
[where the proportionality sign is for a function of $y$, meaning that the proportionality constant can depend on $z$, i.e., $h(y,z)=\nu(z) p(y|z)$]. A symmetric argument leads to
$$
g(x,z)\propto p(x|z)
\quad\text{i.e., }
g(x,z)=\eta(z) p(x|z)
$$
Therefore,
$$
g(x,z)h(y,z)=\eta(z) p(x|z)\nu(z) p(y|z)\,,
$$
and since both sides integrate to $1$ (when integrating both in $x$ and $y$), we conclude with
$$
\eta(z) \nu(z)=1
$$
Hence,$$p(x,y|z)=p(x|z)p(y|z)$$
|
Conditional independence iff joint factorizes
|
Since $X$ and $Y$ are independent given $Z$ iff $p(x,y|z)=p(x|z)p(y|z)$, all you need to prove is that, if $p(x,y|z)=g(x,z)h(y,z)$, then $p(x,y|z)=p(x|z)p(y|z)$.
Starting from the equality $p(x,y|z)=g
|
Conditional independence iff joint factorizes
Since $X$ and $Y$ are independent given $Z$ iff $p(x,y|z)=p(x|z)p(y|z)$, all you need to prove is that, if $p(x,y|z)=g(x,z)h(y,z)$, then $p(x,y|z)=p(x|z)p(y|z)$.
Starting from the equality $p(x,y|z)=g(x,z)h(y,z)$. one can integrate both sides in x: $$
\int_\text{X}p(x,y|z)\text{d}x=\int_\text{X}g(x,z)h(y,z)\text{d}x
$$
This implies
$$
p(y|z)=\int_\text{X}g(x,z)h(y,z)\text{d}x=h(y,z)\int_\text{X}g(x,z)\text{d}x
$$
and tells you that
$$
h(y,z)\propto p(y|z)
$$
[where the proportionality sign is for a function of $y$, meaning that the proportionality constant can depend on $z$, i.e., $h(y,z)=\nu(z) p(y|z)$]. A symmetric argument leads to
$$
g(x,z)\propto p(x|z)
\quad\text{i.e., }
g(x,z)=\eta(z) p(x|z)
$$
Therefore,
$$
g(x,z)h(y,z)=\eta(z) p(x|z)\nu(z) p(y|z)\,,
$$
and since both sides integrate to $1$ (when integrating both in $x$ and $y$), we conclude with
$$
\eta(z) \nu(z)=1
$$
Hence,$$p(x,y|z)=p(x|z)p(y|z)$$
|
Conditional independence iff joint factorizes
Since $X$ and $Y$ are independent given $Z$ iff $p(x,y|z)=p(x|z)p(y|z)$, all you need to prove is that, if $p(x,y|z)=g(x,z)h(y,z)$, then $p(x,y|z)=p(x|z)p(y|z)$.
Starting from the equality $p(x,y|z)=g
|
41,135
|
Data transformation using copulas
|
This page by MathWorks has a detailed description of using
copulas for various tasks with a lot of examples within MATLAB: Probability Distributions Used for Multivariate Modeling. This is helpful for just seeing the nuts and bolts of how copulas can be used in some simple cases.
For transformation of a data matrix $X$ to the state of having marginal
standard normal distribution functions, there is essentially a
two-step process.
The first step is to transform the margins of the data to the uniform distribution.
This can be done using a fit to a theoretically known distribution, using the empirical distribution function, or using a smooth estimator of the distribution function.
The second step is to use the quantile function of the normal distribution function to transform the margins of the data to normality.
This is the mathematical theory. I don't know right now what the ramifications are of using mis-specified distributions or estimated distributions in place of the theoretical distributions.
The R package regpro has a built-in function called copula.trans() that transforms your data to have margins that are distributed as standard normals. In other words, it carries out the two steps described. If X is your $n\times d$ data matrix, then copula.trans(X) gives you back a data matrix with marginals transformed to theoretically have standard normal distributions (by default).
How to get back is not included in the package. To back-track the process, you would first need the percentile function for the standard normal, then second your theoretical distribution function, your interpolated empirical distribution function, or your smooth estimator of the distribution function.
It would be nice if having marginal normal distributions would be sufficient to drive at least multivariate normality after this process. However, that is unfortunately not generally true, as some of us know. For a simple counter-example, see: Two normally distributed random variables need not be jointly bivariate normal. (See @Glen_b's comment below for a bit more information.)
Even aside from that, it looks like some further assumption might be needed to assure that the distribution after transformation would follow a relationship like $X_t|X_{t-1} \sim {\cal{N}}(\Gamma X_{t-1}, \Omega)$.
Initially, I was looking at some results on conditional distributions that might provide some assurances such as those found in (Arnold and Pourahmadi, 1988) or (Ashsanullah and Wesolowski, 1994). An example is the exchangeability criterion
$$ (X_1,...,X_{t-1}) \stackrel{d}{=} (X_2, ...,X_t).$$
However, the set-up is a bit different here. (See @Stéphane Lauren's comment below.)
Can I use copulas to transform this dataset into a dataset that is
more normal than the original one?
Maybe using the copula transformation will work fine for what you have in mind, but there seems to be little theoretical underpinning to go the whole distance to the model you want to fit.
M. Ahsanullah and J. Wesolowski (1994) Multivariate normality via conditional normality. Statistics and Probability Letters. 20: 235--238.
B.C. Arnold and M. Pourahmadi (1988) Conditional characterizations of
multivariate distributions. Metrika 35(1):95--108.
|
Data transformation using copulas
|
This page by MathWorks has a detailed description of using
copulas for various tasks with a lot of examples within MATLAB: Probability Distributions Used for Multivariate Modeling. This is helpful fo
|
Data transformation using copulas
This page by MathWorks has a detailed description of using
copulas for various tasks with a lot of examples within MATLAB: Probability Distributions Used for Multivariate Modeling. This is helpful for just seeing the nuts and bolts of how copulas can be used in some simple cases.
For transformation of a data matrix $X$ to the state of having marginal
standard normal distribution functions, there is essentially a
two-step process.
The first step is to transform the margins of the data to the uniform distribution.
This can be done using a fit to a theoretically known distribution, using the empirical distribution function, or using a smooth estimator of the distribution function.
The second step is to use the quantile function of the normal distribution function to transform the margins of the data to normality.
This is the mathematical theory. I don't know right now what the ramifications are of using mis-specified distributions or estimated distributions in place of the theoretical distributions.
The R package regpro has a built-in function called copula.trans() that transforms your data to have margins that are distributed as standard normals. In other words, it carries out the two steps described. If X is your $n\times d$ data matrix, then copula.trans(X) gives you back a data matrix with marginals transformed to theoretically have standard normal distributions (by default).
How to get back is not included in the package. To back-track the process, you would first need the percentile function for the standard normal, then second your theoretical distribution function, your interpolated empirical distribution function, or your smooth estimator of the distribution function.
It would be nice if having marginal normal distributions would be sufficient to drive at least multivariate normality after this process. However, that is unfortunately not generally true, as some of us know. For a simple counter-example, see: Two normally distributed random variables need not be jointly bivariate normal. (See @Glen_b's comment below for a bit more information.)
Even aside from that, it looks like some further assumption might be needed to assure that the distribution after transformation would follow a relationship like $X_t|X_{t-1} \sim {\cal{N}}(\Gamma X_{t-1}, \Omega)$.
Initially, I was looking at some results on conditional distributions that might provide some assurances such as those found in (Arnold and Pourahmadi, 1988) or (Ashsanullah and Wesolowski, 1994). An example is the exchangeability criterion
$$ (X_1,...,X_{t-1}) \stackrel{d}{=} (X_2, ...,X_t).$$
However, the set-up is a bit different here. (See @Stéphane Lauren's comment below.)
Can I use copulas to transform this dataset into a dataset that is
more normal than the original one?
Maybe using the copula transformation will work fine for what you have in mind, but there seems to be little theoretical underpinning to go the whole distance to the model you want to fit.
M. Ahsanullah and J. Wesolowski (1994) Multivariate normality via conditional normality. Statistics and Probability Letters. 20: 235--238.
B.C. Arnold and M. Pourahmadi (1988) Conditional characterizations of
multivariate distributions. Metrika 35(1):95--108.
|
Data transformation using copulas
This page by MathWorks has a detailed description of using
copulas for various tasks with a lot of examples within MATLAB: Probability Distributions Used for Multivariate Modeling. This is helpful fo
|
41,136
|
Data transformation using copulas
|
Copulas used to recover the joint distribution from marginal distributions. This application is based on Sklar's theorem, which states that if you have two marginal distributions then they're linked through a copula to a joint distribution. A copula is simply a function itself. If you have a bi-variate distribution, then a copula is a bi-variate function too. What this theorem doesn't tell you is how to find this copula. It only tells you that it exists.
Coming to your question:
Can I use copulas to transform this dataset into a dataset that is
more normal than the original one?
No. You can't. You stated
I want to fit a model to this dataset that assumes that
$X_t|X_{t−1}\sim \mathcal{N}(ΓX_{t−1},Ω)$ (where $Γ$ is a d×d matrix) but my data does not seem
to adhere to this assumption
That is the main issue: you want to fit the model, which doesn't seem to be an appropriate model for your data. If you really think that your data is not normal, then you should not be fitting a normal model. Period.
Now, you can use copulas to model your data in a different way though. Here's how.
Pick a copula. How? You can start with Gaussian copula. The "nice" thing about this one is that if your marginal were, in fact, Gaussians, then the joint will be multivariate Gaussian. If your marginal are "kind of" normal, then this copula may work well for you.
Build an empirical distribution, e.g. using ecdf in MATLAB. The idea is to feed your data into this function, which will build cumulative distribution without using any assumptions about the functional form of the distribution. Alternatively, you could use nonparametric distributions, such as kernel density estimations. The bottom line is to get the univariate cumulative distributions, i.e. marginals, because it's the input into copula.
Fit the copula to data.
Generate random sample using the fitted copula, it'll produce multivariate random numbers between 0 and 1.
Plug the inverse empirical CDFs, to convert [0,1] ranges into the random variables.
Note, that the main assumption here is the copula. There are many copulas out there, you can try several of them. This is the weakest link in this chain.
Here's an example in MATLAB.
|
Data transformation using copulas
|
Copulas used to recover the joint distribution from marginal distributions. This application is based on Sklar's theorem, which states that if you have two marginal distributions then they're linked t
|
Data transformation using copulas
Copulas used to recover the joint distribution from marginal distributions. This application is based on Sklar's theorem, which states that if you have two marginal distributions then they're linked through a copula to a joint distribution. A copula is simply a function itself. If you have a bi-variate distribution, then a copula is a bi-variate function too. What this theorem doesn't tell you is how to find this copula. It only tells you that it exists.
Coming to your question:
Can I use copulas to transform this dataset into a dataset that is
more normal than the original one?
No. You can't. You stated
I want to fit a model to this dataset that assumes that
$X_t|X_{t−1}\sim \mathcal{N}(ΓX_{t−1},Ω)$ (where $Γ$ is a d×d matrix) but my data does not seem
to adhere to this assumption
That is the main issue: you want to fit the model, which doesn't seem to be an appropriate model for your data. If you really think that your data is not normal, then you should not be fitting a normal model. Period.
Now, you can use copulas to model your data in a different way though. Here's how.
Pick a copula. How? You can start with Gaussian copula. The "nice" thing about this one is that if your marginal were, in fact, Gaussians, then the joint will be multivariate Gaussian. If your marginal are "kind of" normal, then this copula may work well for you.
Build an empirical distribution, e.g. using ecdf in MATLAB. The idea is to feed your data into this function, which will build cumulative distribution without using any assumptions about the functional form of the distribution. Alternatively, you could use nonparametric distributions, such as kernel density estimations. The bottom line is to get the univariate cumulative distributions, i.e. marginals, because it's the input into copula.
Fit the copula to data.
Generate random sample using the fitted copula, it'll produce multivariate random numbers between 0 and 1.
Plug the inverse empirical CDFs, to convert [0,1] ranges into the random variables.
Note, that the main assumption here is the copula. There are many copulas out there, you can try several of them. This is the weakest link in this chain.
Here's an example in MATLAB.
|
Data transformation using copulas
Copulas used to recover the joint distribution from marginal distributions. This application is based on Sklar's theorem, which states that if you have two marginal distributions then they're linked t
|
41,137
|
Fitting parametric CDF to ecdf
|
I wouldn't use MSE simply because $\hat{F}$ doesn't have constant variance. If you used a weighted MSE that should do better ... but then $\hat{F}_i$ and $\hat{F}_j$ aren't independent, either.
One possibility if you're trying to make $\hat F$ as close to $F$ in a MSE-like sense as possible is you might try minimizing the Anderson-Darling statistic (since it's like a precision-weighted MSE).
To be honest, I'd be inclined to use likelihood to estimate the parameters, if at all feasible -- but not on the ECDF; you want to deal with the data and construct the likelihood (i.e. look at data values and $f$, not $F$ and $\hat{F}$) if you difference back to what's essentially a histogram$^\dagger$ you should be able to get good ML estimates* from that.
$\hspace{3cm}\to$ 4 5 5 5 6 6 6 7 7 7 7 8 9 9 9 9 9 9 ...
* (if slightly approximate because of the discretization)
$\dagger$ - In case it's not obvious how one obtains the sample size in the case where you only have an ecdf and not $n$, let me be explicit about it. The situation you seem to be dealing with (i.e. as "at a suitably fine grid" suggests) we have a finely discretized continuous distribution, one we might reasonably still treat as if it were continuous if only we had the observations.
Consider that at each jump point, the ecdf must increase by some multiple of $1/n$.
The chance that it will always increase by a multiple of $k/n$ ($2/n$ or $3/n$ say) at every jump point would be extremely small indeed (some simple hand calculations or simulations make the point well enough). So we can - with probability extremely close to 1 - infer the exact $n$ by finding the largest $1/n$ consistent with every change in ecdf.
[On the other hand, with a very small sample at a very coarse grid, so that only a few different values will occur, you could get the increase at each point being $2/n$ or perhaps $3/n$ and so run into problems, particularly if you want standard errors. So if we only had 4 bins and the counts in those bins were 2,6,12,4, we'd get $n$ wrong (it would look like the jumps were multiples of 1/12 rather than 1/24, so we'd think the $n_i$ were 1,3,6,2), and so the standard errors - and in some cases, even the point estimates - could be a fair way off. Fortunately, this isn't the case for this question.]
|
Fitting parametric CDF to ecdf
|
I wouldn't use MSE simply because $\hat{F}$ doesn't have constant variance. If you used a weighted MSE that should do better ... but then $\hat{F}_i$ and $\hat{F}_j$ aren't independent, either.
One po
|
Fitting parametric CDF to ecdf
I wouldn't use MSE simply because $\hat{F}$ doesn't have constant variance. If you used a weighted MSE that should do better ... but then $\hat{F}_i$ and $\hat{F}_j$ aren't independent, either.
One possibility if you're trying to make $\hat F$ as close to $F$ in a MSE-like sense as possible is you might try minimizing the Anderson-Darling statistic (since it's like a precision-weighted MSE).
To be honest, I'd be inclined to use likelihood to estimate the parameters, if at all feasible -- but not on the ECDF; you want to deal with the data and construct the likelihood (i.e. look at data values and $f$, not $F$ and $\hat{F}$) if you difference back to what's essentially a histogram$^\dagger$ you should be able to get good ML estimates* from that.
$\hspace{3cm}\to$ 4 5 5 5 6 6 6 7 7 7 7 8 9 9 9 9 9 9 ...
* (if slightly approximate because of the discretization)
$\dagger$ - In case it's not obvious how one obtains the sample size in the case where you only have an ecdf and not $n$, let me be explicit about it. The situation you seem to be dealing with (i.e. as "at a suitably fine grid" suggests) we have a finely discretized continuous distribution, one we might reasonably still treat as if it were continuous if only we had the observations.
Consider that at each jump point, the ecdf must increase by some multiple of $1/n$.
The chance that it will always increase by a multiple of $k/n$ ($2/n$ or $3/n$ say) at every jump point would be extremely small indeed (some simple hand calculations or simulations make the point well enough). So we can - with probability extremely close to 1 - infer the exact $n$ by finding the largest $1/n$ consistent with every change in ecdf.
[On the other hand, with a very small sample at a very coarse grid, so that only a few different values will occur, you could get the increase at each point being $2/n$ or perhaps $3/n$ and so run into problems, particularly if you want standard errors. So if we only had 4 bins and the counts in those bins were 2,6,12,4, we'd get $n$ wrong (it would look like the jumps were multiples of 1/12 rather than 1/24, so we'd think the $n_i$ were 1,3,6,2), and so the standard errors - and in some cases, even the point estimates - could be a fair way off. Fortunately, this isn't the case for this question.]
|
Fitting parametric CDF to ecdf
I wouldn't use MSE simply because $\hat{F}$ doesn't have constant variance. If you used a weighted MSE that should do better ... but then $\hat{F}_i$ and $\hat{F}_j$ aren't independent, either.
One po
|
41,138
|
Fitting parametric CDF to ecdf
|
You asked about relevant litterature.
If your model is a power law, log-normal, poisson or binomial you should check the work of Clauset et al. "PowerLaw Distribution in Empirical Data" http://arxiv.org/pdf/0706.1062.pdf They describe how to do so by bootstraping, performing fits on the ecdf of the actual data and generated data. You must be cautious when using such approach and follow the procedure described in details in this paper.
An important thing to remember is that you never prove that your data follow a model, you can only disprove it follow a model. p-values give you the closeness of the data and the model, but you can only carefully make conclusions by performing the same test for other likely models that could explain the data.
The authors of the paper also provide a library to perfom the tests for these models (poweRlaw package in R), and partial implementation in other languages.
|
Fitting parametric CDF to ecdf
|
You asked about relevant litterature.
If your model is a power law, log-normal, poisson or binomial you should check the work of Clauset et al. "PowerLaw Distribution in Empirical Data" http://arxiv.o
|
Fitting parametric CDF to ecdf
You asked about relevant litterature.
If your model is a power law, log-normal, poisson or binomial you should check the work of Clauset et al. "PowerLaw Distribution in Empirical Data" http://arxiv.org/pdf/0706.1062.pdf They describe how to do so by bootstraping, performing fits on the ecdf of the actual data and generated data. You must be cautious when using such approach and follow the procedure described in details in this paper.
An important thing to remember is that you never prove that your data follow a model, you can only disprove it follow a model. p-values give you the closeness of the data and the model, but you can only carefully make conclusions by performing the same test for other likely models that could explain the data.
The authors of the paper also provide a library to perfom the tests for these models (poweRlaw package in R), and partial implementation in other languages.
|
Fitting parametric CDF to ecdf
You asked about relevant litterature.
If your model is a power law, log-normal, poisson or binomial you should check the work of Clauset et al. "PowerLaw Distribution in Empirical Data" http://arxiv.o
|
41,139
|
Is the harmonic mean the maximum likelihood estimator for some common continous distribution's parameter?
|
This will happen for the recirpocal of a random variable following an Exponential distribution.
Let $X$ follow an Exponential distribution with probability density function
$$f_X(x) = \alpha e^{-\alpha x}$$
Consider $$ Y = \frac 1{X} \Rightarrow X = 1/Y \Rightarrow \frac{\partial X}{\partial Y} = -Y^{-2}$$
Then
$$f_Y(y) = \left|\frac{\partial X}{\partial Y}\right|\cdot f_X(1/y)= \alpha y^{-2}e^{-\alpha/y},\;\; y\in (0,\infty)$$
The log-likelihood of a sample of $n$ observations will be
$$\ln L = n\ln\alpha -2\sum_{i=1}^n\ln y_i -\alpha \sum_{i=1}^n(1/y_i)$$
and
$$\frac{\partial \ln L}{\partial \alpha} = \frac n{\alpha}-\sum_{i=1}^n(1/y_i) = 0 \Rightarrow \hat \alpha_{ML} = \frac n{\sum_{i=1}^n(1/y_i)}$$
which is the harmonic mean of the $y$'s.
|
Is the harmonic mean the maximum likelihood estimator for some common continous distribution's param
|
This will happen for the recirpocal of a random variable following an Exponential distribution.
Let $X$ follow an Exponential distribution with probability density function
$$f_X(x) = \alpha e^{-\alp
|
Is the harmonic mean the maximum likelihood estimator for some common continous distribution's parameter?
This will happen for the recirpocal of a random variable following an Exponential distribution.
Let $X$ follow an Exponential distribution with probability density function
$$f_X(x) = \alpha e^{-\alpha x}$$
Consider $$ Y = \frac 1{X} \Rightarrow X = 1/Y \Rightarrow \frac{\partial X}{\partial Y} = -Y^{-2}$$
Then
$$f_Y(y) = \left|\frac{\partial X}{\partial Y}\right|\cdot f_X(1/y)= \alpha y^{-2}e^{-\alpha/y},\;\; y\in (0,\infty)$$
The log-likelihood of a sample of $n$ observations will be
$$\ln L = n\ln\alpha -2\sum_{i=1}^n\ln y_i -\alpha \sum_{i=1}^n(1/y_i)$$
and
$$\frac{\partial \ln L}{\partial \alpha} = \frac n{\alpha}-\sum_{i=1}^n(1/y_i) = 0 \Rightarrow \hat \alpha_{ML} = \frac n{\sum_{i=1}^n(1/y_i)}$$
which is the harmonic mean of the $y$'s.
|
Is the harmonic mean the maximum likelihood estimator for some common continous distribution's param
This will happen for the recirpocal of a random variable following an Exponential distribution.
Let $X$ follow an Exponential distribution with probability density function
$$f_X(x) = \alpha e^{-\alp
|
41,140
|
5 defectives rule of thumb
|
This reference on Lean Six Sigma, p. 159, provides a formula to calculate the minimum sample size, and mentions the "$5$ defectives" rule of thumb, a formula that relates to the normal distribution, and it is perhaps more useful to the OP than my contested (see comments) reasoning. I cannot argue about the reference's level of authority though.
Also this US government websource in section "Transforming Poisson Data" mentions this rule of thumb, relating it to the normal approximation to the Poisson distribution.
But I would like to offer a specific argument which is consistent with this rule of thumb (not necessarily an optimal argument -see comments):
One should clarify what "reasonably accurate" estimate means.Taking the road of Confidence Interval, we would want to have a point estimate whose variance/standard deviation is small enough so that the associated confidence interval won't include the value zero (and hence, negative possible values also, which in our case, would be non-sensical, and would also render the point estimate "statistically insignificant").
Associating each unit produced $i$ with a Bernoulli random variable $X_i$ that takes the value $1$ if the unit is defective and $0$ if it is not, and assuming that all units have the same probability of being defective, and that each random variable is independent from all others, then we can estimate this probability of defect as
$$\hat p =\frac 1n\sum_i^nX_i $$
or, writing $n_1$ to denote the number of defective units,
$$\hat p = \frac {n_1}{n},\;\; \operatorname{\hat Var}(\hat p) = \frac {\hat p(1-\hat p)}{n} = \frac {n_1(n-n_1)}{n^3}$$
Using the normal approximation to the binomial, a $90$% Confidence Interval then will be
$$\frac {n_1}{n} \pm (z_{0.05}+0.5){\sqrt {\frac {n_1(n-n_1)}{n^3}}}= \frac {n_1}{n}\pm 2.15\frac {\sqrt {(n_1/n)(n-n_1)}}{n}$$
where to the critical value from the standard normal distribution, we have added the $0.5$ "continuity correction".
We want the $CI$ to not include negative values, so we require
$$\frac {n_1}{n} -2.15\frac {\sqrt {(n_1/n)(n-n_1)}}{n} >0 \Rightarrow n_1^2 > (2.15)^2\cdot (n_1/n)(n-n_1)$$
Manipulating, we want
$$ n_1n > (2.15)^2\cdot (n-n_1) \Rightarrow n_1 > \frac {(2.15)^2n}{n+(2.15)^2}$$
For large $n$, as will the case be, the right-hand side tends to $(2.15)^2 = 4.62$. Since $n_1$ is an integer, $n_1 > 4.62 \Rightarrow n_1 =5$.
|
5 defectives rule of thumb
|
This reference on Lean Six Sigma, p. 159, provides a formula to calculate the minimum sample size, and mentions the "$5$ defectives" rule of thumb, a formula that relates to the normal distribution, a
|
5 defectives rule of thumb
This reference on Lean Six Sigma, p. 159, provides a formula to calculate the minimum sample size, and mentions the "$5$ defectives" rule of thumb, a formula that relates to the normal distribution, and it is perhaps more useful to the OP than my contested (see comments) reasoning. I cannot argue about the reference's level of authority though.
Also this US government websource in section "Transforming Poisson Data" mentions this rule of thumb, relating it to the normal approximation to the Poisson distribution.
But I would like to offer a specific argument which is consistent with this rule of thumb (not necessarily an optimal argument -see comments):
One should clarify what "reasonably accurate" estimate means.Taking the road of Confidence Interval, we would want to have a point estimate whose variance/standard deviation is small enough so that the associated confidence interval won't include the value zero (and hence, negative possible values also, which in our case, would be non-sensical, and would also render the point estimate "statistically insignificant").
Associating each unit produced $i$ with a Bernoulli random variable $X_i$ that takes the value $1$ if the unit is defective and $0$ if it is not, and assuming that all units have the same probability of being defective, and that each random variable is independent from all others, then we can estimate this probability of defect as
$$\hat p =\frac 1n\sum_i^nX_i $$
or, writing $n_1$ to denote the number of defective units,
$$\hat p = \frac {n_1}{n},\;\; \operatorname{\hat Var}(\hat p) = \frac {\hat p(1-\hat p)}{n} = \frac {n_1(n-n_1)}{n^3}$$
Using the normal approximation to the binomial, a $90$% Confidence Interval then will be
$$\frac {n_1}{n} \pm (z_{0.05}+0.5){\sqrt {\frac {n_1(n-n_1)}{n^3}}}= \frac {n_1}{n}\pm 2.15\frac {\sqrt {(n_1/n)(n-n_1)}}{n}$$
where to the critical value from the standard normal distribution, we have added the $0.5$ "continuity correction".
We want the $CI$ to not include negative values, so we require
$$\frac {n_1}{n} -2.15\frac {\sqrt {(n_1/n)(n-n_1)}}{n} >0 \Rightarrow n_1^2 > (2.15)^2\cdot (n_1/n)(n-n_1)$$
Manipulating, we want
$$ n_1n > (2.15)^2\cdot (n-n_1) \Rightarrow n_1 > \frac {(2.15)^2n}{n+(2.15)^2}$$
For large $n$, as will the case be, the right-hand side tends to $(2.15)^2 = 4.62$. Since $n_1$ is an integer, $n_1 > 4.62 \Rightarrow n_1 =5$.
|
5 defectives rule of thumb
This reference on Lean Six Sigma, p. 159, provides a formula to calculate the minimum sample size, and mentions the "$5$ defectives" rule of thumb, a formula that relates to the normal distribution, a
|
41,141
|
5 defectives rule of thumb
|
I think this comes from the rule of thumb for using the normal approximation for a confidence interval (cf. @AlecosPapadopoulos' answer). In short, it is recommended that [the smaller of] $np$ [or $n(1-p)$] be greater than $5$ for the normal approximation to be used. If this condition holds, it is often considered that the normal approximation can be used, and tests that implicitly rely on it can be used instead of exact tests*.
This does not guarantee that you will see a defect, but seems to work pretty well. We can determine the probability you will see a defect by using the binomial distribution's cumulative distribution function (CDF). Here I use R to do so:
1-pbinom(0, size=5e+01, prob=1e-01) # [1] 0.9948462
1-pbinom(0, size=5e+02, prob=1e-02) # [1] 0.9934295
1-pbinom(0, size=5e+03, prob=1e-03) # [1] 0.9932789
1-pbinom(0, size=5e+04, prob=1e-04) # [1] 0.9932637
1-pbinom(0, size=5e+05, prob=1e-05) # [1] 0.9932622
1-pbinom(0, size=5e+06, prob=1e-06) # [1] 0.9932621
1-pbinom(0, size=5e+07, prob=1e-07) # [1] 0.9932621
1-pbinom(0, size=5e+08, prob=1e-08) # [1] 0.9932621
1-pbinom(0, size=5e+09, prob=1e-09) # [1] 0.9932621
1-pbinom(0, size=5e+10, prob=1e-10) # [1] 0.9932621
Since we want the probability of getting anything but $0$ defects, we calculate the probability of getting exactly $0$ and subtract that from $1$. The analytical solutions are listed to the right. They seem to converge to $\approx 99.33\%$ as the defect probability decreases (and $N$ necessarily goes up).
Some meta commentary: A standard paradigm contrasts accuracy vs. precision. Because common statistical procedures privilege unbiasedness (cf. maximum likelihood vs. shrinkage estimators), the process of determining the appropriate sample size (power analysis) tends to focus on getting an acceptable level of precision. In your case, this seems to be whether an interval estimate (e.g., a 95% CI) will have an accurate level of coverage.
* Technically, since the rule of thumb is $>5$, and not $\ge 5$, this would be based on an analogy to the lower limit of the rule of thumb, but then rules of thumb by their nature shouldn't be taken as so exacting.
|
5 defectives rule of thumb
|
I think this comes from the rule of thumb for using the normal approximation for a confidence interval (cf. @AlecosPapadopoulos' answer). In short, it is recommended that [the smaller of] $np$ [or $n
|
5 defectives rule of thumb
I think this comes from the rule of thumb for using the normal approximation for a confidence interval (cf. @AlecosPapadopoulos' answer). In short, it is recommended that [the smaller of] $np$ [or $n(1-p)$] be greater than $5$ for the normal approximation to be used. If this condition holds, it is often considered that the normal approximation can be used, and tests that implicitly rely on it can be used instead of exact tests*.
This does not guarantee that you will see a defect, but seems to work pretty well. We can determine the probability you will see a defect by using the binomial distribution's cumulative distribution function (CDF). Here I use R to do so:
1-pbinom(0, size=5e+01, prob=1e-01) # [1] 0.9948462
1-pbinom(0, size=5e+02, prob=1e-02) # [1] 0.9934295
1-pbinom(0, size=5e+03, prob=1e-03) # [1] 0.9932789
1-pbinom(0, size=5e+04, prob=1e-04) # [1] 0.9932637
1-pbinom(0, size=5e+05, prob=1e-05) # [1] 0.9932622
1-pbinom(0, size=5e+06, prob=1e-06) # [1] 0.9932621
1-pbinom(0, size=5e+07, prob=1e-07) # [1] 0.9932621
1-pbinom(0, size=5e+08, prob=1e-08) # [1] 0.9932621
1-pbinom(0, size=5e+09, prob=1e-09) # [1] 0.9932621
1-pbinom(0, size=5e+10, prob=1e-10) # [1] 0.9932621
Since we want the probability of getting anything but $0$ defects, we calculate the probability of getting exactly $0$ and subtract that from $1$. The analytical solutions are listed to the right. They seem to converge to $\approx 99.33\%$ as the defect probability decreases (and $N$ necessarily goes up).
Some meta commentary: A standard paradigm contrasts accuracy vs. precision. Because common statistical procedures privilege unbiasedness (cf. maximum likelihood vs. shrinkage estimators), the process of determining the appropriate sample size (power analysis) tends to focus on getting an acceptable level of precision. In your case, this seems to be whether an interval estimate (e.g., a 95% CI) will have an accurate level of coverage.
* Technically, since the rule of thumb is $>5$, and not $\ge 5$, this would be based on an analogy to the lower limit of the rule of thumb, but then rules of thumb by their nature shouldn't be taken as so exacting.
|
5 defectives rule of thumb
I think this comes from the rule of thumb for using the normal approximation for a confidence interval (cf. @AlecosPapadopoulos' answer). In short, it is recommended that [the smaller of] $np$ [or $n
|
41,142
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
You can normalize the vectors in each cluster by their lengths and add them up, then normalize the sum. The result will be a unit vector in the direction of the centroid (a.k.a. prototype) vector. As far as the spherical k-means algorithm is concerned, the length of the centroid vector does not matter and is not used. This is because to calculate the cosine distance between each cluster member and the centroid, both vectors are normalized by their lengths. See the following excerpt from this article:
If you really need a centroid vector with a representative length, you can take the average of the lengths of the cluster members and multiply it by the unit centroid vector. But this would be completely your choice and would have nothing to do with the k-means algorithm (you could use any other type of averaging, arithmetic, geometric, or just the length of the average vector to compute the representative centroid lenght).
The formula posted by Vijay Rajan is effectively the same (except giving a centroid vector of non-unit length), but note that in that formula too the vectors must be normalized to unit length before applying the formula. When calculated properly, the centroid does indeed "bisect" the angle between the vectors. (I don't currently have the forum privilege to make this a comment on their response.)
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
You can normalize the vectors in each cluster by their lengths and add them up, then normalize the sum. The result will be a unit vector in the direction of the centroid (a.k.a. prototype) vector. As
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
You can normalize the vectors in each cluster by their lengths and add them up, then normalize the sum. The result will be a unit vector in the direction of the centroid (a.k.a. prototype) vector. As far as the spherical k-means algorithm is concerned, the length of the centroid vector does not matter and is not used. This is because to calculate the cosine distance between each cluster member and the centroid, both vectors are normalized by their lengths. See the following excerpt from this article:
If you really need a centroid vector with a representative length, you can take the average of the lengths of the cluster members and multiply it by the unit centroid vector. But this would be completely your choice and would have nothing to do with the k-means algorithm (you could use any other type of averaging, arithmetic, geometric, or just the length of the average vector to compute the representative centroid lenght).
The formula posted by Vijay Rajan is effectively the same (except giving a centroid vector of non-unit length), but note that in that formula too the vectors must be normalized to unit length before applying the formula. When calculated properly, the centroid does indeed "bisect" the angle between the vectors. (I don't currently have the forum privilege to make this a comment on their response.)
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
You can normalize the vectors in each cluster by their lengths and add them up, then normalize the sum. The result will be a unit vector in the direction of the centroid (a.k.a. prototype) vector. As
|
41,143
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
It should be safe to use the regular means of computing the mean with cosine - at least if your data is positive and does not include a zero vector.
Spherical k-means (that is the proper search term) IIRC normalizes the mean vectors to unit length.
Beware of corner cases: if your clustering degenerates and a cluster becomes empty, you may end up with a zero vector and get NaN values.
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
It should be safe to use the regular means of computing the mean with cosine - at least if your data is positive and does not include a zero vector.
Spherical k-means (that is the proper search term)
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
It should be safe to use the regular means of computing the mean with cosine - at least if your data is positive and does not include a zero vector.
Spherical k-means (that is the proper search term) IIRC normalizes the mean vectors to unit length.
Beware of corner cases: if your clustering degenerates and a cluster becomes empty, you may end up with a zero vector and get NaN values.
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
It should be safe to use the regular means of computing the mean with cosine - at least if your data is positive and does not include a zero vector.
Spherical k-means (that is the proper search term)
|
41,144
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
There are a few implementations of k-means (one k-means in R) which allows you to just input a distance matrix instead of actual data. There is package called 'proxy' on cran, that you use to find a cosine similarity formula based distance matrix of the data.
You can directly use this distance matrix in k-means.
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
There are a few implementations of k-means (one k-means in R) which allows you to just input a distance matrix instead of actual data. There is package called 'proxy' on cran, that you use to find a c
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
There are a few implementations of k-means (one k-means in R) which allows you to just input a distance matrix instead of actual data. There is package called 'proxy' on cran, that you use to find a cosine similarity formula based distance matrix of the data.
You can directly use this distance matrix in k-means.
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
There are a few implementations of k-means (one k-means in R) which allows you to just input a distance matrix instead of actual data. There is package called 'proxy' on cran, that you use to find a c
|
41,145
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
As per http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.7900&rep=rep1&type=pdf it says that you could add up all the vectors and then divide each vector element by the number of vectors.
See image
I personally don't like this formula. The reason is that this does NOT BISECT the angle between 2 Vectors and origin.
Example
Angle at origin between [1,1] and [1,0] is 45 deg which is SQRT(2). But by the formula quoted in the book, the new vector which will now be the centroid, does not BISECT the angle. So as per formula 1/2 * [1+1, 0+1] which is [1,0.5]. This point does not lie on the bisector.
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
|
As per http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.7900&rep=rep1&type=pdf it says that you could add up all the vectors and then divide each vector element by the number of vectors.
S
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
As per http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.7900&rep=rep1&type=pdf it says that you could add up all the vectors and then divide each vector element by the number of vectors.
See image
I personally don't like this formula. The reason is that this does NOT BISECT the angle between 2 Vectors and origin.
Example
Angle at origin between [1,1] and [1,0] is 45 deg which is SQRT(2). But by the formula quoted in the book, the new vector which will now be the centroid, does not BISECT the angle. So as per formula 1/2 * [1+1, 0+1] which is [1,0.5]. This point does not lie on the bisector.
|
k-means cluster, How to re-calculate centroid when using cosine similarity?
As per http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.7900&rep=rep1&type=pdf it says that you could add up all the vectors and then divide each vector element by the number of vectors.
S
|
41,146
|
How to get coefficients of gradient boosting models?
|
I use R "in industry". GBM's and other tree-based methods don't have "coefficients" so it's pointless to try to extract them.
What you CAN do is encode each tree as a SQL query. It take a little effort, but once you can do it for a single tree, you can loop over all the trees in a model, generate ~500 SQL queries, and use them to score your model on a database of your choosing.
|
How to get coefficients of gradient boosting models?
|
I use R "in industry". GBM's and other tree-based methods don't have "coefficients" so it's pointless to try to extract them.
What you CAN do is encode each tree as a SQL query. It take a little eff
|
How to get coefficients of gradient boosting models?
I use R "in industry". GBM's and other tree-based methods don't have "coefficients" so it's pointless to try to extract them.
What you CAN do is encode each tree as a SQL query. It take a little effort, but once you can do it for a single tree, you can loop over all the trees in a model, generate ~500 SQL queries, and use them to score your model on a database of your choosing.
|
How to get coefficients of gradient boosting models?
I use R "in industry". GBM's and other tree-based methods don't have "coefficients" so it's pointless to try to extract them.
What you CAN do is encode each tree as a SQL query. It take a little eff
|
41,147
|
How to get coefficients of gradient boosting models?
|
Like Zach mentioned earlier, "coefficients" don't really apply for a GBM. I'm not sure how you're implementing it, but in a package like CARET (for R) you can look at variable importance during model building. You can also see something similar in the vignette for the GBM package in R. In the GBM package, I think it is called relative influence; the maths behind it is in the 2001 paper by Friedman.
Both of those approaches would go some way to giving you a ranking of how "useful"/"important" your variables were in classifying the target using a GBM.
|
How to get coefficients of gradient boosting models?
|
Like Zach mentioned earlier, "coefficients" don't really apply for a GBM. I'm not sure how you're implementing it, but in a package like CARET (for R) you can look at variable importance during model
|
How to get coefficients of gradient boosting models?
Like Zach mentioned earlier, "coefficients" don't really apply for a GBM. I'm not sure how you're implementing it, but in a package like CARET (for R) you can look at variable importance during model building. You can also see something similar in the vignette for the GBM package in R. In the GBM package, I think it is called relative influence; the maths behind it is in the 2001 paper by Friedman.
Both of those approaches would go some way to giving you a ranking of how "useful"/"important" your variables were in classifying the target using a GBM.
|
How to get coefficients of gradient boosting models?
Like Zach mentioned earlier, "coefficients" don't really apply for a GBM. I'm not sure how you're implementing it, but in a package like CARET (for R) you can look at variable importance during model
|
41,148
|
How to get coefficients of gradient boosting models?
|
Use PMML to transfer the model to other platforms, assuming your other platform is PMML-compatible.
|
How to get coefficients of gradient boosting models?
|
Use PMML to transfer the model to other platforms, assuming your other platform is PMML-compatible.
|
How to get coefficients of gradient boosting models?
Use PMML to transfer the model to other platforms, assuming your other platform is PMML-compatible.
|
How to get coefficients of gradient boosting models?
Use PMML to transfer the model to other platforms, assuming your other platform is PMML-compatible.
|
41,149
|
How to get coefficients of gradient boosting models?
|
For python, you could use import _pickle as cPickle to save the model to a pickle file and restore the model from the pickle file.
The codes for store the model:
with open("gbmFit.pkl", "wb") as pickle_file:
cPickle.dump(model, pickle_file)
For restore the model, one could use following code:
with open('gbmFit.pkl', 'rb') as pickle_file:
gbmfit = cPickle.load(pickle_file)
y_pred_restore = gbmfit.predict(np.array(x1 + 1).reshape((-1, 1)))
Now you could save the model and save it for later real time use.
|
How to get coefficients of gradient boosting models?
|
For python, you could use import _pickle as cPickle to save the model to a pickle file and restore the model from the pickle file.
The codes for store the model:
with open("gbmFit.pkl", "wb") as pick
|
How to get coefficients of gradient boosting models?
For python, you could use import _pickle as cPickle to save the model to a pickle file and restore the model from the pickle file.
The codes for store the model:
with open("gbmFit.pkl", "wb") as pickle_file:
cPickle.dump(model, pickle_file)
For restore the model, one could use following code:
with open('gbmFit.pkl', 'rb') as pickle_file:
gbmfit = cPickle.load(pickle_file)
y_pred_restore = gbmfit.predict(np.array(x1 + 1).reshape((-1, 1)))
Now you could save the model and save it for later real time use.
|
How to get coefficients of gradient boosting models?
For python, you could use import _pickle as cPickle to save the model to a pickle file and restore the model from the pickle file.
The codes for store the model:
with open("gbmFit.pkl", "wb") as pick
|
41,150
|
Weight Decay in Neural Neural Networks Weight Update and Convergence
|
It is not surprising that weight decay will hurt performance of your neural network at some point. Let the prediction loss of your net be $\mathcal{L}$ and the weight decay loss $\mathcal{R}$. Given a coefficient $\lambda$ that establishes a tradeoff between the two, one optimises
$$
\mathcal{L} + \lambda \mathcal{R}.
$$
At the optimium of this loss, the gradients of both terms will have to sum up to zero:
$$
\triangledown \mathcal{L} = -\lambda \triangledown \mathcal{R}.
$$
This makes clear that we will not be at an optimium of the training loss. Even more so, the higher $\lambda$ the steeper the gradient of $\mathcal{L}$, which in the case of convex loss functions implies a higher distance from the optimum.
|
Weight Decay in Neural Neural Networks Weight Update and Convergence
|
It is not surprising that weight decay will hurt performance of your neural network at some point. Let the prediction loss of your net be $\mathcal{L}$ and the weight decay loss $\mathcal{R}$. Given a
|
Weight Decay in Neural Neural Networks Weight Update and Convergence
It is not surprising that weight decay will hurt performance of your neural network at some point. Let the prediction loss of your net be $\mathcal{L}$ and the weight decay loss $\mathcal{R}$. Given a coefficient $\lambda$ that establishes a tradeoff between the two, one optimises
$$
\mathcal{L} + \lambda \mathcal{R}.
$$
At the optimium of this loss, the gradients of both terms will have to sum up to zero:
$$
\triangledown \mathcal{L} = -\lambda \triangledown \mathcal{R}.
$$
This makes clear that we will not be at an optimium of the training loss. Even more so, the higher $\lambda$ the steeper the gradient of $\mathcal{L}$, which in the case of convex loss functions implies a higher distance from the optimum.
|
Weight Decay in Neural Neural Networks Weight Update and Convergence
It is not surprising that weight decay will hurt performance of your neural network at some point. Let the prediction loss of your net be $\mathcal{L}$ and the weight decay loss $\mathcal{R}$. Given a
|
41,151
|
Avoiding numerical error propagation
|
Let $\mathbf \varepsilon = (\varepsilon_1, \varepsilon_2, \ldots, \varepsilon_n)$, $\mathbf y = (y_1,y_2,\ldots, y_n)$, and $\mathbf{\mu} = (\mu, \mu, \ldots, \mu)$. The relationship among these vectors given in the question is
$$\mathbf y - \mathbf\mu = \mathbf{X}\mathbf \varepsilon$$
The matrix $\mathbf{X} = \mathbf{I} + \theta\mathbf{J}$ where $\mathbf{I}$ is the $n$ by $n$ identify matrix and $\mathbf J$ is the $n$ by $n$ matrix with $1$ on the immediate subdiagonal (that is, where $i = j+1$) and $0$ elsewhere.
The problem is that when $|\theta| \gt 1$, $\mathbf{X}$ can be practically singular. (Since $\mathbf{X}^{-1} = \mathbf{I} + \sum_{i=1}^{n-1} (-1)^i \theta^i \mathbf{J}^i$ and the $i^\text{th}$ powers of $\mathbf J$ are also subdiagonal matrices with $1$s (on the diagonal $i$ steps below the main one), the largest entry in the inverse of $\mathbf X$ is $(-1)^{n-1}\theta^{n-1}$. This can easily overflow floating point representations. It will obliterate all precision once $(n-1)\log_{2}|\theta| \gt 52$, which for $\theta=5$ occurs once $n\ge 24$.)
R will even tell you about this problem:
n <- 30
theta <- 5; mu <- 10; sigma <- 3
set.seed(17); epsilon <- rnorm(n, sd=sigma)
x <- diag(1, n) + matrix(c(0, diag(1, n)[-n^2]), n, n) * theta
solve(x, rep(0, n))
Error in solve.default(x, rep(0, n)) :
system is computationally singular: reciprocal condition number = 7.15828e-22
All statistical software provides a way around this: compute the generalized inverse (aka "least squares fit"). In R this can be done with lm (among other tools):
y <- mu + x %*% epsilon # Compute the series `y`
d <- as.data.frame(cbind(y-mu, x))# Create a data frame for computing the solution
fit <- lm(V1 ~ . - 1, data=d) # Obtain the solution
epsilon.hat <- coef(fit) # Extract it from `fit`
This time there are no complaints. Just for fun, I ran this procedure for $n=3000$. Here is a plot of the recovered values of $\mathbf \varepsilon$ against the original ones, with the diagonal line (of perfect equality) superimposed for reference:
plot(epsilon, epsilon.hat, col="#00000060")
abline(c(0,1), col="#e0000080", lwd=2)
The recovery is not perfect, as evidenced by the single off-diagonal plotting symbol. Experimentation suggests this is unavoidable; it is rare for the recovered errors exactly to equal the original ones. The problems occur at the very end of the sequence, as evidenced by the vertical departures from zero (marked by the horizontal gray line):
res <- epsilon.hat - epsilon # Residuals
plot(n-0:9, head(rev(res), 10), type="b",
xlab="Index (t)", ylab="Residual", main="Last residuals")
abline(h=0, col="Gray", lty=2)
The very last one is NA (because lm recognized problems and dropped a variable, I believe).
Nevertheless, for such an unstable series that's a pretty good showing.
|
Avoiding numerical error propagation
|
Let $\mathbf \varepsilon = (\varepsilon_1, \varepsilon_2, \ldots, \varepsilon_n)$, $\mathbf y = (y_1,y_2,\ldots, y_n)$, and $\mathbf{\mu} = (\mu, \mu, \ldots, \mu)$. The relationship among these vect
|
Avoiding numerical error propagation
Let $\mathbf \varepsilon = (\varepsilon_1, \varepsilon_2, \ldots, \varepsilon_n)$, $\mathbf y = (y_1,y_2,\ldots, y_n)$, and $\mathbf{\mu} = (\mu, \mu, \ldots, \mu)$. The relationship among these vectors given in the question is
$$\mathbf y - \mathbf\mu = \mathbf{X}\mathbf \varepsilon$$
The matrix $\mathbf{X} = \mathbf{I} + \theta\mathbf{J}$ where $\mathbf{I}$ is the $n$ by $n$ identify matrix and $\mathbf J$ is the $n$ by $n$ matrix with $1$ on the immediate subdiagonal (that is, where $i = j+1$) and $0$ elsewhere.
The problem is that when $|\theta| \gt 1$, $\mathbf{X}$ can be practically singular. (Since $\mathbf{X}^{-1} = \mathbf{I} + \sum_{i=1}^{n-1} (-1)^i \theta^i \mathbf{J}^i$ and the $i^\text{th}$ powers of $\mathbf J$ are also subdiagonal matrices with $1$s (on the diagonal $i$ steps below the main one), the largest entry in the inverse of $\mathbf X$ is $(-1)^{n-1}\theta^{n-1}$. This can easily overflow floating point representations. It will obliterate all precision once $(n-1)\log_{2}|\theta| \gt 52$, which for $\theta=5$ occurs once $n\ge 24$.)
R will even tell you about this problem:
n <- 30
theta <- 5; mu <- 10; sigma <- 3
set.seed(17); epsilon <- rnorm(n, sd=sigma)
x <- diag(1, n) + matrix(c(0, diag(1, n)[-n^2]), n, n) * theta
solve(x, rep(0, n))
Error in solve.default(x, rep(0, n)) :
system is computationally singular: reciprocal condition number = 7.15828e-22
All statistical software provides a way around this: compute the generalized inverse (aka "least squares fit"). In R this can be done with lm (among other tools):
y <- mu + x %*% epsilon # Compute the series `y`
d <- as.data.frame(cbind(y-mu, x))# Create a data frame for computing the solution
fit <- lm(V1 ~ . - 1, data=d) # Obtain the solution
epsilon.hat <- coef(fit) # Extract it from `fit`
This time there are no complaints. Just for fun, I ran this procedure for $n=3000$. Here is a plot of the recovered values of $\mathbf \varepsilon$ against the original ones, with the diagonal line (of perfect equality) superimposed for reference:
plot(epsilon, epsilon.hat, col="#00000060")
abline(c(0,1), col="#e0000080", lwd=2)
The recovery is not perfect, as evidenced by the single off-diagonal plotting symbol. Experimentation suggests this is unavoidable; it is rare for the recovered errors exactly to equal the original ones. The problems occur at the very end of the sequence, as evidenced by the vertical departures from zero (marked by the horizontal gray line):
res <- epsilon.hat - epsilon # Residuals
plot(n-0:9, head(rev(res), 10), type="b",
xlab="Index (t)", ylab="Residual", main="Last residuals")
abline(h=0, col="Gray", lty=2)
The very last one is NA (because lm recognized problems and dropped a variable, I believe).
Nevertheless, for such an unstable series that's a pretty good showing.
|
Avoiding numerical error propagation
Let $\mathbf \varepsilon = (\varepsilon_1, \varepsilon_2, \ldots, \varepsilon_n)$, $\mathbf y = (y_1,y_2,\ldots, y_n)$, and $\mathbf{\mu} = (\mu, \mu, \ldots, \mu)$. The relationship among these vect
|
41,152
|
Avoiding numerical error propagation
|
Your linear recurrence relation for $\epsilon_t$ is unstable. If you know $\epsilon_1$ with some absolute error $\delta$, then the subsequent values for $\epsilon_t$ will have absolute error on the order of $\theta^t \delta$.
Note that the error doesn't have to come from the estimation error for the parameters, it could also be the roundoff error coming from finite-precision floating-point arithmetic on your computer (then $\delta=O(10^{-16})$ in double precision). Note that $5^{30}\approx 10^{21}$.
Thus this is what you would expect when $|\theta|>1$. This is a mathematical property of the linear recurrence relation you've written down and the value of $\theta$ that you chose. Moving average processes with $|\theta|>1$ are called non-invertible.
|
Avoiding numerical error propagation
|
Your linear recurrence relation for $\epsilon_t$ is unstable. If you know $\epsilon_1$ with some absolute error $\delta$, then the subsequent values for $\epsilon_t$ will have absolute error on the or
|
Avoiding numerical error propagation
Your linear recurrence relation for $\epsilon_t$ is unstable. If you know $\epsilon_1$ with some absolute error $\delta$, then the subsequent values for $\epsilon_t$ will have absolute error on the order of $\theta^t \delta$.
Note that the error doesn't have to come from the estimation error for the parameters, it could also be the roundoff error coming from finite-precision floating-point arithmetic on your computer (then $\delta=O(10^{-16})$ in double precision). Note that $5^{30}\approx 10^{21}$.
Thus this is what you would expect when $|\theta|>1$. This is a mathematical property of the linear recurrence relation you've written down and the value of $\theta$ that you chose. Moving average processes with $|\theta|>1$ are called non-invertible.
|
Avoiding numerical error propagation
Your linear recurrence relation for $\epsilon_t$ is unstable. If you know $\epsilon_1$ with some absolute error $\delta$, then the subsequent values for $\epsilon_t$ will have absolute error on the or
|
41,153
|
Calculate number of support vectors in SVM
|
Notice that since $y_{i} = \pm 1$, you can rewrite,
$$
\alpha_i = \frac{1}{y_i} \left[ \frac{1}{y_i} - \frac{1}{N} \sum_{n=1}^N \frac{1}{y_n}\right] = y_i \left[y_i - \frac{1}{N} \sum_{n=1}^N y_n\right] = 1 - y_{i}\frac{N^{+}-N^{-}}{N}
$$
where $N^{+}$ and $N^{-}$ are the number of samples in each of the classes. You can check that $\sum_{n}\alpha_{n}y_{n} = 0$. Also $\alpha_{n} > 0$, that is, all vectors are support vectors.
As for the margin,
$$
||\omega|| = \sum_{n}\alpha^{2} = N\left[1-\left(\frac{N^{+}-N^{-}}{N}\right)^{2}\right]
$$
|
Calculate number of support vectors in SVM
|
Notice that since $y_{i} = \pm 1$, you can rewrite,
$$
\alpha_i = \frac{1}{y_i} \left[ \frac{1}{y_i} - \frac{1}{N} \sum_{n=1}^N \frac{1}{y_n}\right] = y_i \left[y_i - \frac{1}{N} \sum_{n=1}^N y_n\righ
|
Calculate number of support vectors in SVM
Notice that since $y_{i} = \pm 1$, you can rewrite,
$$
\alpha_i = \frac{1}{y_i} \left[ \frac{1}{y_i} - \frac{1}{N} \sum_{n=1}^N \frac{1}{y_n}\right] = y_i \left[y_i - \frac{1}{N} \sum_{n=1}^N y_n\right] = 1 - y_{i}\frac{N^{+}-N^{-}}{N}
$$
where $N^{+}$ and $N^{-}$ are the number of samples in each of the classes. You can check that $\sum_{n}\alpha_{n}y_{n} = 0$. Also $\alpha_{n} > 0$, that is, all vectors are support vectors.
As for the margin,
$$
||\omega|| = \sum_{n}\alpha^{2} = N\left[1-\left(\frac{N^{+}-N^{-}}{N}\right)^{2}\right]
$$
|
Calculate number of support vectors in SVM
Notice that since $y_{i} = \pm 1$, you can rewrite,
$$
\alpha_i = \frac{1}{y_i} \left[ \frac{1}{y_i} - \frac{1}{N} \sum_{n=1}^N \frac{1}{y_n}\right] = y_i \left[y_i - \frac{1}{N} \sum_{n=1}^N y_n\righ
|
41,154
|
Calculate number of support vectors in SVM
|
You are correct that for such a kernel, for all non-data points, $z$, you will get $w^T\theta(z) = \sum_i \alpha_i k(x_i, z) = 0$. For intuition, note that your kernel is equivalent to the RBF kernel with width converging to 0. Thus, you have no generalization capability at all; the decision function is based on 0-radius balls.
|
Calculate number of support vectors in SVM
|
You are correct that for such a kernel, for all non-data points, $z$, you will get $w^T\theta(z) = \sum_i \alpha_i k(x_i, z) = 0$. For intuition, note that your kernel is equivalent to the RBF kernel
|
Calculate number of support vectors in SVM
You are correct that for such a kernel, for all non-data points, $z$, you will get $w^T\theta(z) = \sum_i \alpha_i k(x_i, z) = 0$. For intuition, note that your kernel is equivalent to the RBF kernel with width converging to 0. Thus, you have no generalization capability at all; the decision function is based on 0-radius balls.
|
Calculate number of support vectors in SVM
You are correct that for such a kernel, for all non-data points, $z$, you will get $w^T\theta(z) = \sum_i \alpha_i k(x_i, z) = 0$. For intuition, note that your kernel is equivalent to the RBF kernel
|
41,155
|
Combining $\chi^{2}$ tests
|
If the traps were all considered independent then this isn't a variation on a $\chi^2$ test, it just is one. But because they're used in pairs, and therefore not independent, then what you're looking for would be a variation on a McNemar's test. Unfortunately, any modification of that test for more than a 2x2 matrix will still suffer because you have such small numbers of items in the Less column.
Your effect is so strong I'd be tempted to just report the data. What's wrong with that? When the data are very strong and there's little to no noise in the effect then it's hard to see why you wouldn't just report what you found and state it as fact. Statistics aren't as powerful as you think and don't really make this compelling data story any better. I fear they'd just be used to hide the small sample problem.
If you really, really want a probability then resampling is probably your best bet here. You could perform a permutation or randomization test. Calculate the mean difference between your More and Less conditions. Then scramble up the samples randomly, maintaining your pairing, and calculate new mean differences. Do that on a computer thousands of times and figure out where the difference you found falls in the distribution of differences you sampled. The probability of an effect that large or larger will be your p-value to report.
Here's some base R that does it.
dat <- matrix(c(6, 1, 3, 1, 15, 0, 0, 1, 0, 3), ncol = 2)
n <- nrow(dat)
eff <- diff( colSums(dat) )
samps <- rowSums(dat)
nsamp <- 5000
# bootstrap nsamp replications of your experiment
y <- replicate(nsamp, {
# get a random amount for each location and put it in the more trap
more <- sapply(1:n, function(i) {sample(samps[i]+1, 1) - 1})
# of course, the rest is in the less trap
less <- samps - more
# calculate effect (less - more might be backwards of what you want
# but it's what the diff command did above for the original effect so
#we keep calculating in the same direction
sum(less) - sum(more)
})
# two sided p-value
sum(y < eff | y > -eff) / nsamp
That p-value is a probability of data coming out with an effect as large, or larger, than the one you got given the null hypothesis, and an assumption of a representative sample (always implicit). Think about it as considering what would happen if the null was true. The traps would just randomly catch insects. Imagine you caught as many insects as you did, in as many locations, and then see how that distribution appears at random across the traps. If the effect you had was unlikely to occur when the null was true then we conclude the null was not.
Alternatively, one could sample the distribution of effects with replacement. By doing this one can bootstrap a confidence interval of the effect.
# get each separate effect
effs <- dat[,2] - dat[,1]
nsamp <- 1000
# bootstrap nsamp replications of your experiment
y <- replicate(nsamp, {
# randomly sample from the distribution of effects
effSamp <- sample(effs, replace = TRUE)
# get total sample effect
sum(effSamp)
})
# get y into order so we can get the distribution cutoffs
y <- sort(y)
# 95% CI
y[0.025 * nsamp]; y[0.975 * nsamp]
|
Combining $\chi^{2}$ tests
|
If the traps were all considered independent then this isn't a variation on a $\chi^2$ test, it just is one. But because they're used in pairs, and therefore not independent, then what you're looking
|
Combining $\chi^{2}$ tests
If the traps were all considered independent then this isn't a variation on a $\chi^2$ test, it just is one. But because they're used in pairs, and therefore not independent, then what you're looking for would be a variation on a McNemar's test. Unfortunately, any modification of that test for more than a 2x2 matrix will still suffer because you have such small numbers of items in the Less column.
Your effect is so strong I'd be tempted to just report the data. What's wrong with that? When the data are very strong and there's little to no noise in the effect then it's hard to see why you wouldn't just report what you found and state it as fact. Statistics aren't as powerful as you think and don't really make this compelling data story any better. I fear they'd just be used to hide the small sample problem.
If you really, really want a probability then resampling is probably your best bet here. You could perform a permutation or randomization test. Calculate the mean difference between your More and Less conditions. Then scramble up the samples randomly, maintaining your pairing, and calculate new mean differences. Do that on a computer thousands of times and figure out where the difference you found falls in the distribution of differences you sampled. The probability of an effect that large or larger will be your p-value to report.
Here's some base R that does it.
dat <- matrix(c(6, 1, 3, 1, 15, 0, 0, 1, 0, 3), ncol = 2)
n <- nrow(dat)
eff <- diff( colSums(dat) )
samps <- rowSums(dat)
nsamp <- 5000
# bootstrap nsamp replications of your experiment
y <- replicate(nsamp, {
# get a random amount for each location and put it in the more trap
more <- sapply(1:n, function(i) {sample(samps[i]+1, 1) - 1})
# of course, the rest is in the less trap
less <- samps - more
# calculate effect (less - more might be backwards of what you want
# but it's what the diff command did above for the original effect so
#we keep calculating in the same direction
sum(less) - sum(more)
})
# two sided p-value
sum(y < eff | y > -eff) / nsamp
That p-value is a probability of data coming out with an effect as large, or larger, than the one you got given the null hypothesis, and an assumption of a representative sample (always implicit). Think about it as considering what would happen if the null was true. The traps would just randomly catch insects. Imagine you caught as many insects as you did, in as many locations, and then see how that distribution appears at random across the traps. If the effect you had was unlikely to occur when the null was true then we conclude the null was not.
Alternatively, one could sample the distribution of effects with replacement. By doing this one can bootstrap a confidence interval of the effect.
# get each separate effect
effs <- dat[,2] - dat[,1]
nsamp <- 1000
# bootstrap nsamp replications of your experiment
y <- replicate(nsamp, {
# randomly sample from the distribution of effects
effSamp <- sample(effs, replace = TRUE)
# get total sample effect
sum(effSamp)
})
# get y into order so we can get the distribution cutoffs
y <- sort(y)
# 95% CI
y[0.025 * nsamp]; y[0.975 * nsamp]
|
Combining $\chi^{2}$ tests
If the traps were all considered independent then this isn't a variation on a $\chi^2$ test, it just is one. But because they're used in pairs, and therefore not independent, then what you're looking
|
41,156
|
Combining $\chi^{2}$ tests
|
One uber-robust and uber-conservative approach would be non-parametric signed rank or matched pairs sign tests. In the first test, you assume identical distributions of two groups; in the second, you explicitly incorporate coupling of the two distributions.
. signrank trapped0 = trapped1
Wilcoxon signed-rank test
sign | obs sum ranks expected
-------------+---------------------------------
positive | 0 0 7.5
negative | 5 15 7.5
zero | 0 0 0
-------------+---------------------------------
all | 5 15 15
unadjusted variance 13.75
adjustment for ties -0.13
adjustment for zeros 0.00
----------
adjusted variance 13.63
Ho: trapped0 = trapped1
z = -2.032
Prob > |z| = 0.0422
. signtest trapped0 = trapped1
Sign test
sign | observed expected
-------------+------------------------
positive | 0 2.5
negative | 5 2.5
zero | 0 0
-------------+------------------------
all | 5 5
One-sided tests:
Ho: median of trapped0 - trapped1 = 0 vs.
Ha: median of trapped0 - trapped1 > 0
Pr(#positive >= 0) =
Binomial(n = 5, x >= 0, p = 0.5) = 1.0000
Ho: median of trapped0 - trapped1 = 0 vs.
Ha: median of trapped0 - trapped1 < 0
Pr(#negative >= 5) =
Binomial(n = 5, x >= 5, p = 0.5) = 0.0313
Two-sided test:
Ho: median of trapped0 - trapped1 = 0 vs.
Ha: median of trapped0 - trapped1 != 0
Pr(#positive >= 5 or #negative >= 5) =
min(1, 2*Binomial(n = 5, x >= 5, p = 0.5)) = 0.0625
Basically, these tests both say that five differences only happen to fall on the same side (higher counts for the "More" condition with 1:2^5 = 1:32 probability if the null of no differences were true. However, these tests may not have much power with the sample size of 5, and you can get stronger results by making stronger assumptions.
Since you are dealing with counts, an appropriate tool for your problem will be a generalized linear model, namely Poisson model for counts. Denoting the sites as block, and the conditions as treat, I am getting
Poisson regression Number of obs = 10
LR chi2(5) = 47.17
Prob > chi2 = 0.0000
Log likelihood = -11.51985 Pseudo R2 = 0.6718
------------------------------------------------------------------------------
trapped | IRR Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
block |
2 | .1666667 .1800206 -1.66 0.097 .0200653 1.384368
3 | .6666667 .4303315 -0.63 0.530 .1881311 2.362419
4 | .1666667 .1800206 -1.66 0.097 .0200653 1.384368
5 | 3 1.414214 2.33 0.020 1.190861 7.557558
|
1.treat | 6.5 3.49106 3.49 0.000 2.268531 18.62438
_cons | .8 .4953114 -0.36 0.719 .2377266 2.692168
------------------------------------------------------------------------------
That is, the "More" condition attracts, on average, 6.5 more insects than does the "Less" condition, with a confidence interval [2.27x, 18.62x]. The p-value here is much stronger than from a non-parametric test with p = 0.0005.
Stata code:
clear
input trapped block treat
6 1 1
0 1 0
1 2 1
0 2 0
3 3 1
1 3 0
1 4 1
0 4 0
15 5 1
3 5 0
end
poisson trapped i.block i.treat, irr
testparm i.treat
reshape wide trapped, i(block) j(treat)
signrank trapped0 = trapped1
signtest trapped0 = trapped1
|
Combining $\chi^{2}$ tests
|
One uber-robust and uber-conservative approach would be non-parametric signed rank or matched pairs sign tests. In the first test, you assume identical distributions of two groups; in the second, you
|
Combining $\chi^{2}$ tests
One uber-robust and uber-conservative approach would be non-parametric signed rank or matched pairs sign tests. In the first test, you assume identical distributions of two groups; in the second, you explicitly incorporate coupling of the two distributions.
. signrank trapped0 = trapped1
Wilcoxon signed-rank test
sign | obs sum ranks expected
-------------+---------------------------------
positive | 0 0 7.5
negative | 5 15 7.5
zero | 0 0 0
-------------+---------------------------------
all | 5 15 15
unadjusted variance 13.75
adjustment for ties -0.13
adjustment for zeros 0.00
----------
adjusted variance 13.63
Ho: trapped0 = trapped1
z = -2.032
Prob > |z| = 0.0422
. signtest trapped0 = trapped1
Sign test
sign | observed expected
-------------+------------------------
positive | 0 2.5
negative | 5 2.5
zero | 0 0
-------------+------------------------
all | 5 5
One-sided tests:
Ho: median of trapped0 - trapped1 = 0 vs.
Ha: median of trapped0 - trapped1 > 0
Pr(#positive >= 0) =
Binomial(n = 5, x >= 0, p = 0.5) = 1.0000
Ho: median of trapped0 - trapped1 = 0 vs.
Ha: median of trapped0 - trapped1 < 0
Pr(#negative >= 5) =
Binomial(n = 5, x >= 5, p = 0.5) = 0.0313
Two-sided test:
Ho: median of trapped0 - trapped1 = 0 vs.
Ha: median of trapped0 - trapped1 != 0
Pr(#positive >= 5 or #negative >= 5) =
min(1, 2*Binomial(n = 5, x >= 5, p = 0.5)) = 0.0625
Basically, these tests both say that five differences only happen to fall on the same side (higher counts for the "More" condition with 1:2^5 = 1:32 probability if the null of no differences were true. However, these tests may not have much power with the sample size of 5, and you can get stronger results by making stronger assumptions.
Since you are dealing with counts, an appropriate tool for your problem will be a generalized linear model, namely Poisson model for counts. Denoting the sites as block, and the conditions as treat, I am getting
Poisson regression Number of obs = 10
LR chi2(5) = 47.17
Prob > chi2 = 0.0000
Log likelihood = -11.51985 Pseudo R2 = 0.6718
------------------------------------------------------------------------------
trapped | IRR Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
block |
2 | .1666667 .1800206 -1.66 0.097 .0200653 1.384368
3 | .6666667 .4303315 -0.63 0.530 .1881311 2.362419
4 | .1666667 .1800206 -1.66 0.097 .0200653 1.384368
5 | 3 1.414214 2.33 0.020 1.190861 7.557558
|
1.treat | 6.5 3.49106 3.49 0.000 2.268531 18.62438
_cons | .8 .4953114 -0.36 0.719 .2377266 2.692168
------------------------------------------------------------------------------
That is, the "More" condition attracts, on average, 6.5 more insects than does the "Less" condition, with a confidence interval [2.27x, 18.62x]. The p-value here is much stronger than from a non-parametric test with p = 0.0005.
Stata code:
clear
input trapped block treat
6 1 1
0 1 0
1 2 1
0 2 0
3 3 1
1 3 0
1 4 1
0 4 0
15 5 1
3 5 0
end
poisson trapped i.block i.treat, irr
testparm i.treat
reshape wide trapped, i(block) j(treat)
signrank trapped0 = trapped1
signtest trapped0 = trapped1
|
Combining $\chi^{2}$ tests
One uber-robust and uber-conservative approach would be non-parametric signed rank or matched pairs sign tests. In the first test, you assume identical distributions of two groups; in the second, you
|
41,157
|
How to test whether there is a significant difference in mean squared error between two datasets?
|
MSE Significance testing:
You can test for significantly different MSEs if your samples are large enough for the Central Limit Theorem to apply (say, larger than 30).
You want to test whether the means of your two samples are significantly different, where the samples in this case are the squared errors from your healthy and Alzheimer's sets. This becomes a standard case of hypothesis testing. To test if the true difference is zero, assume:
$MSE_1 - MSE_2 \sim N(0, \frac{s_1^2}{N_1} + \frac{s_2^2}{N_2})$
which is the same as the textbook* case:
$\overline X_1 - \overline X_2 \sim N(0, \frac{s_1^2}{N_1} + \frac{s_2^2}{N_2})$
where s1 is the sample standard deviation of your first group of squared errors, N1 is the sample size of the first group, and so forth. From there you can find the one-sided p-value with
$Pvalue = P(Z \le \frac{MSE_1 - MSE_2}{\sqrt{\frac{s_1^2}{N_1} + \frac{s_2^2}{N_2}}})$
Another easy way of doing this is to run a 2 sample t-test of the squared errors, which should provide practically identical results.
*Assuming your textbook is Modern Mathematical Statistics with Applications, Second Edition by Devore and Berk, especially pages 490-491
Alternative option– test regression coefficients for significance:
In your regression, you could add a dummy variable for Alzheimer's, and use the standard error of the estimated coefficient to test if it's significantly different from zero. Or, if you think age and Alzheimer's interact, add an age*Alzheimers interaction variable and test that coefficient for significance.
|
How to test whether there is a significant difference in mean squared error between two datasets?
|
MSE Significance testing:
You can test for significantly different MSEs if your samples are large enough for the Central Limit Theorem to apply (say, larger than 30).
You want to test whether the mean
|
How to test whether there is a significant difference in mean squared error between two datasets?
MSE Significance testing:
You can test for significantly different MSEs if your samples are large enough for the Central Limit Theorem to apply (say, larger than 30).
You want to test whether the means of your two samples are significantly different, where the samples in this case are the squared errors from your healthy and Alzheimer's sets. This becomes a standard case of hypothesis testing. To test if the true difference is zero, assume:
$MSE_1 - MSE_2 \sim N(0, \frac{s_1^2}{N_1} + \frac{s_2^2}{N_2})$
which is the same as the textbook* case:
$\overline X_1 - \overline X_2 \sim N(0, \frac{s_1^2}{N_1} + \frac{s_2^2}{N_2})$
where s1 is the sample standard deviation of your first group of squared errors, N1 is the sample size of the first group, and so forth. From there you can find the one-sided p-value with
$Pvalue = P(Z \le \frac{MSE_1 - MSE_2}{\sqrt{\frac{s_1^2}{N_1} + \frac{s_2^2}{N_2}}})$
Another easy way of doing this is to run a 2 sample t-test of the squared errors, which should provide practically identical results.
*Assuming your textbook is Modern Mathematical Statistics with Applications, Second Edition by Devore and Berk, especially pages 490-491
Alternative option– test regression coefficients for significance:
In your regression, you could add a dummy variable for Alzheimer's, and use the standard error of the estimated coefficient to test if it's significantly different from zero. Or, if you think age and Alzheimer's interact, add an age*Alzheimers interaction variable and test that coefficient for significance.
|
How to test whether there is a significant difference in mean squared error between two datasets?
MSE Significance testing:
You can test for significantly different MSEs if your samples are large enough for the Central Limit Theorem to apply (say, larger than 30).
You want to test whether the mean
|
41,158
|
How to test whether there is a significant difference in mean squared error between two datasets?
|
Sounds like an interesting set-up.
Just to re-state your plan, you're creating two populations -- healthy and Alzheimer's. You ten plan to use a 5-fold cross-validation method on only the healthy group. You then plan to fit a model to the training portion of the fold and finally compare the error when applied to the testing portion of the fold versus the Alzheimer's.
If that's correct, I think the simplest approach would be to train your 5 models, apply them against the respective testing sets as well as the Alzheimer's pool. At least initially I would look at the comparison between populations on a per-fold basis. If the results are consistent, I think you're in fine shape. Otherwise, you might do a comparison of the coefficients of the various models you've trained.
I would only follow-up on the penultimate paragraph if your results are very strange.
|
How to test whether there is a significant difference in mean squared error between two datasets?
|
Sounds like an interesting set-up.
Just to re-state your plan, you're creating two populations -- healthy and Alzheimer's. You ten plan to use a 5-fold cross-validation method on only the healthy grou
|
How to test whether there is a significant difference in mean squared error between two datasets?
Sounds like an interesting set-up.
Just to re-state your plan, you're creating two populations -- healthy and Alzheimer's. You ten plan to use a 5-fold cross-validation method on only the healthy group. You then plan to fit a model to the training portion of the fold and finally compare the error when applied to the testing portion of the fold versus the Alzheimer's.
If that's correct, I think the simplest approach would be to train your 5 models, apply them against the respective testing sets as well as the Alzheimer's pool. At least initially I would look at the comparison between populations on a per-fold basis. If the results are consistent, I think you're in fine shape. Otherwise, you might do a comparison of the coefficients of the various models you've trained.
I would only follow-up on the penultimate paragraph if your results are very strange.
|
How to test whether there is a significant difference in mean squared error between two datasets?
Sounds like an interesting set-up.
Just to re-state your plan, you're creating two populations -- healthy and Alzheimer's. You ten plan to use a 5-fold cross-validation method on only the healthy grou
|
41,159
|
Averaging binomial confidence intervals
|
Two points
First point: You could also perform a weighted average of the proportion of female instructors at the three schools (e.g. if A has ten times as many total instructors as B and C combined, one might argue that it should count more heavily). For example, $(n_{A}\times 0.23 + n_{B}\times 0.56 + n_{C} \times 0.8)/(n_{A} + n_{B} + n_{C})$. If the total number of instructors at each institution is the same size, then the weighted average reduces to the simple arithmetic mean as in your example.
Second point: If you recall that for Bernoulli distribution, the variance is determined by $p$ (the proportion), as in $\sigma^{2}_{p}=p(1-p)$, so that $\sigma_{p}=\sqrt{p(1-p)}$, and $\sigma_{\hat{p}}=\sqrt{p(1-p)/n}$ (where $n = n_{A} + n_{B} + n_{C}$), one could readily generate a CI (say $\hat{p} \pm z_{\alpha/2}\sigma_{\hat{p}}$) under the assumption that A, B, and C are all drawn from the same population.
Bonus point: Agresti and Coull have shown that the nominal coverage of the CI I just indicated performs suboptimally for small $n$. They provide an alternative which gives better nominal CI coverage for $\hat{p}$ thus:
$$\tilde{p} \pm z_{\alpha/2}\sqrt{\tilde{p}(1-\tilde{p})\tilde{n}}$$
where $\tilde{n} = n+2z_{\alpha/2}$, and $\tilde{p} = \frac{\left(\Sigma x\right) +z_{\alpha/2}}{\tilde{n}}$. Understand that the use of $\tilde{p}$ is purely instrumental, and the Agresti-Coull confidence interval is for $\hat{p}$. As sample size gets big, the nominal coverage of the standard Wald-type CI and that of the Agresti-Coull CI converge. More details about these and other binomial proportion confidence intervals on Wikipedia.
**References**
Agresti, A. and Coull, B. A. (1998). Approximate is better than “exact” for interval estimation of binomial proportions. The American Statistician, 52(2):119–126.
|
Averaging binomial confidence intervals
|
Two points
First point: You could also perform a weighted average of the proportion of female instructors at the three schools (e.g. if A has ten times as many total instructors as B and C combined, o
|
Averaging binomial confidence intervals
Two points
First point: You could also perform a weighted average of the proportion of female instructors at the three schools (e.g. if A has ten times as many total instructors as B and C combined, one might argue that it should count more heavily). For example, $(n_{A}\times 0.23 + n_{B}\times 0.56 + n_{C} \times 0.8)/(n_{A} + n_{B} + n_{C})$. If the total number of instructors at each institution is the same size, then the weighted average reduces to the simple arithmetic mean as in your example.
Second point: If you recall that for Bernoulli distribution, the variance is determined by $p$ (the proportion), as in $\sigma^{2}_{p}=p(1-p)$, so that $\sigma_{p}=\sqrt{p(1-p)}$, and $\sigma_{\hat{p}}=\sqrt{p(1-p)/n}$ (where $n = n_{A} + n_{B} + n_{C}$), one could readily generate a CI (say $\hat{p} \pm z_{\alpha/2}\sigma_{\hat{p}}$) under the assumption that A, B, and C are all drawn from the same population.
Bonus point: Agresti and Coull have shown that the nominal coverage of the CI I just indicated performs suboptimally for small $n$. They provide an alternative which gives better nominal CI coverage for $\hat{p}$ thus:
$$\tilde{p} \pm z_{\alpha/2}\sqrt{\tilde{p}(1-\tilde{p})\tilde{n}}$$
where $\tilde{n} = n+2z_{\alpha/2}$, and $\tilde{p} = \frac{\left(\Sigma x\right) +z_{\alpha/2}}{\tilde{n}}$. Understand that the use of $\tilde{p}$ is purely instrumental, and the Agresti-Coull confidence interval is for $\hat{p}$. As sample size gets big, the nominal coverage of the standard Wald-type CI and that of the Agresti-Coull CI converge. More details about these and other binomial proportion confidence intervals on Wikipedia.
**References**
Agresti, A. and Coull, B. A. (1998). Approximate is better than “exact” for interval estimation of binomial proportions. The American Statistician, 52(2):119–126.
|
Averaging binomial confidence intervals
Two points
First point: You could also perform a weighted average of the proportion of female instructors at the three schools (e.g. if A has ten times as many total instructors as B and C combined, o
|
41,160
|
What is the difference between a "learner" and "classifier" in supervised learning?
|
I use to find this kind of difference mostly in the world of programmers interested in machine learning. This difference does not appear in the world of statisticians and researchers.
The idea is that a classifier is a program built by a learner. An illuminating intuition comes from one of the many definitions of machine learning which is programming with data. So, you have data (training set) and from that data using a computer program you build another program (for example a decision tree). The program which builds the decision tree from data is the learner. The decision tree is a classifier, because a classifier is a program which is able to predict, which takes only the input data and for each instance it produces the output data.
An alternative way to understand this is that a learner takes the input $x_1,x_2,..,x_p,y$ and produces a classifier. A classifier takes as input $x'_1,x'_2,..,x'_p$ and produces $y'$.
As I said, in research papers this distinction is hard to find. It seems that the researchers are interested only in how to describe the model. When they come to describe how to build that model, then they talk about a learner, and when they talk about how to predict with that model, then they talk about a classifier. So, a third alternative is a functional one. The function of fitting a model is the function of a learner, while the function of predicting values is a function of a classifier.
Note that a regressor is the same as a classifier, only the nature of the output is different.
|
What is the difference between a "learner" and "classifier" in supervised learning?
|
I use to find this kind of difference mostly in the world of programmers interested in machine learning. This difference does not appear in the world of statisticians and researchers.
The idea is tha
|
What is the difference between a "learner" and "classifier" in supervised learning?
I use to find this kind of difference mostly in the world of programmers interested in machine learning. This difference does not appear in the world of statisticians and researchers.
The idea is that a classifier is a program built by a learner. An illuminating intuition comes from one of the many definitions of machine learning which is programming with data. So, you have data (training set) and from that data using a computer program you build another program (for example a decision tree). The program which builds the decision tree from data is the learner. The decision tree is a classifier, because a classifier is a program which is able to predict, which takes only the input data and for each instance it produces the output data.
An alternative way to understand this is that a learner takes the input $x_1,x_2,..,x_p,y$ and produces a classifier. A classifier takes as input $x'_1,x'_2,..,x'_p$ and produces $y'$.
As I said, in research papers this distinction is hard to find. It seems that the researchers are interested only in how to describe the model. When they come to describe how to build that model, then they talk about a learner, and when they talk about how to predict with that model, then they talk about a classifier. So, a third alternative is a functional one. The function of fitting a model is the function of a learner, while the function of predicting values is a function of a classifier.
Note that a regressor is the same as a classifier, only the nature of the output is different.
|
What is the difference between a "learner" and "classifier" in supervised learning?
I use to find this kind of difference mostly in the world of programmers interested in machine learning. This difference does not appear in the world of statisticians and researchers.
The idea is tha
|
41,161
|
What is the difference between a "learner" and "classifier" in supervised learning?
|
I know this is an old post but I just had the same question as to the OP. Thanks to/based on @rapio's description, this is how I would say the same thing:
Both a learner and a classifier refer to the same thing: a machine learning model. It's just that an ML model has aspects to it while in the training phase which are hidden and taken away when the model is being used for inference.
For example, in the training phase, we have an optimizer that guides the backpropagation algorithm on how to update the model weights. Or the learning rate. These parts of the model are stripped away once the model is done training. In other words, the model that you'll have at inference is not exactly the same concept when you are training it. That's why in some literature, they are referred to by different names.
Basically, when you say "learner" you are putting an emphasis on the aspect of the model that exists only in the training phase. Personally, I wish people would stop nitpicking so much and just call it a model. In my opinion, this level of differentiation is not helping anyone.
|
What is the difference between a "learner" and "classifier" in supervised learning?
|
I know this is an old post but I just had the same question as to the OP. Thanks to/based on @rapio's description, this is how I would say the same thing:
Both a learner and a classifier refer to the
|
What is the difference between a "learner" and "classifier" in supervised learning?
I know this is an old post but I just had the same question as to the OP. Thanks to/based on @rapio's description, this is how I would say the same thing:
Both a learner and a classifier refer to the same thing: a machine learning model. It's just that an ML model has aspects to it while in the training phase which are hidden and taken away when the model is being used for inference.
For example, in the training phase, we have an optimizer that guides the backpropagation algorithm on how to update the model weights. Or the learning rate. These parts of the model are stripped away once the model is done training. In other words, the model that you'll have at inference is not exactly the same concept when you are training it. That's why in some literature, they are referred to by different names.
Basically, when you say "learner" you are putting an emphasis on the aspect of the model that exists only in the training phase. Personally, I wish people would stop nitpicking so much and just call it a model. In my opinion, this level of differentiation is not helping anyone.
|
What is the difference between a "learner" and "classifier" in supervised learning?
I know this is an old post but I just had the same question as to the OP. Thanks to/based on @rapio's description, this is how I would say the same thing:
Both a learner and a classifier refer to the
|
41,162
|
Probability mass function of the sample mean
|
If $Z \sim Bernoulli(\frac12)$, then $X=2Z-1$ has a Rademacher distribution where $X=-1$ or $1$ with equal probability. Let $X_1, ..., X_n$ denote indepedent Rademacher random variables.
Then, the pmf of:
$$ S = \sum_{i=1}^n X_i = (2 \sum_{i=1}^n Z_i) - n = 2 Y -n$$
where $Y \sim Binomial(n,\frac12)$ (since the sum of $n$ Bernoulli's is $Binomial(n,p)$).
That is: $Y \sim Binomial(n,\frac12)$ with pmf:
$$f(y) = 2^{-n} \binom{n}{y} \quad \quad \text{for } y = {0,1,\dots,n}$$
Then, the pmf of $\bar X = \frac{S}{n} = \frac1n(2 Y - n)$ can be obtained directly via the method of transformations, which yields:
$$2^{-n} \binom{n}{\frac{1}{2} n \left(\bar{x}+1\right)}$$
... which is the result you seek. Since $y = {0,1,\dots, n}$, the domain of support of $\bar X = \frac1n(2 Y - n)$ will be:
for odd-valued $ n$: $\quad \bar x= \pm \frac1n,\pm \frac3n,\ldots, \pm 1$
for even-valued $n$: $\quad \bar x= 0, \pm \frac2n,\pm \frac4n,\ldots,\pm 1$
|
Probability mass function of the sample mean
|
If $Z \sim Bernoulli(\frac12)$, then $X=2Z-1$ has a Rademacher distribution where $X=-1$ or $1$ with equal probability. Let $X_1, ..., X_n$ denote indepedent Rademacher random variables.
Then, the pm
|
Probability mass function of the sample mean
If $Z \sim Bernoulli(\frac12)$, then $X=2Z-1$ has a Rademacher distribution where $X=-1$ or $1$ with equal probability. Let $X_1, ..., X_n$ denote indepedent Rademacher random variables.
Then, the pmf of:
$$ S = \sum_{i=1}^n X_i = (2 \sum_{i=1}^n Z_i) - n = 2 Y -n$$
where $Y \sim Binomial(n,\frac12)$ (since the sum of $n$ Bernoulli's is $Binomial(n,p)$).
That is: $Y \sim Binomial(n,\frac12)$ with pmf:
$$f(y) = 2^{-n} \binom{n}{y} \quad \quad \text{for } y = {0,1,\dots,n}$$
Then, the pmf of $\bar X = \frac{S}{n} = \frac1n(2 Y - n)$ can be obtained directly via the method of transformations, which yields:
$$2^{-n} \binom{n}{\frac{1}{2} n \left(\bar{x}+1\right)}$$
... which is the result you seek. Since $y = {0,1,\dots, n}$, the domain of support of $\bar X = \frac1n(2 Y - n)$ will be:
for odd-valued $ n$: $\quad \bar x= \pm \frac1n,\pm \frac3n,\ldots, \pm 1$
for even-valued $n$: $\quad \bar x= 0, \pm \frac2n,\pm \frac4n,\ldots,\pm 1$
|
Probability mass function of the sample mean
If $Z \sim Bernoulli(\frac12)$, then $X=2Z-1$ has a Rademacher distribution where $X=-1$ or $1$ with equal probability. Let $X_1, ..., X_n$ denote indepedent Rademacher random variables.
Then, the pm
|
41,163
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
|
"Just an artefact" sounds like the effect could be entirely due to regression to the mean. That is a very strong statement. In fact, Kruger & Dunning already addressed this in section 4.1.3 in their original paper ("regression effect" here stands for "regression to the mean"):
Despite the inevitability of the regression effect, we believe that
the overestimation we observed was more psychological than
artifactual. For one, if regression alone were to blame for our
results, then the magnitude of miscalibration among the bottom
quartile would be comparable with that of the top quartile.
And that simply is not the case; their Figure 1 shows that the bottom performers overestimate their performance by more than the top performers underestimate theirs.
In addition, Kruger & Dunning explicitly ran additional studies (studies 3 and 4 in their original paper) to address this, and the results from their studies 3 and 4 are consistent with an actual underlying psychological effect.
Of course regression to the mean will have an effect in the basic Dunning-Kruger setup, and one could conceive a permutation test approach to estimate how much of the Dunning-Kruger setup is due to it. Nevertheless, my impression is that there is something more there.
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
|
"Just an artefact" sounds like the effect could be entirely due to regression to the mean. That is a very strong statement. In fact, Kruger & Dunning already addressed this in section 4.1.3 in their o
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
"Just an artefact" sounds like the effect could be entirely due to regression to the mean. That is a very strong statement. In fact, Kruger & Dunning already addressed this in section 4.1.3 in their original paper ("regression effect" here stands for "regression to the mean"):
Despite the inevitability of the regression effect, we believe that
the overestimation we observed was more psychological than
artifactual. For one, if regression alone were to blame for our
results, then the magnitude of miscalibration among the bottom
quartile would be comparable with that of the top quartile.
And that simply is not the case; their Figure 1 shows that the bottom performers overestimate their performance by more than the top performers underestimate theirs.
In addition, Kruger & Dunning explicitly ran additional studies (studies 3 and 4 in their original paper) to address this, and the results from their studies 3 and 4 are consistent with an actual underlying psychological effect.
Of course regression to the mean will have an effect in the basic Dunning-Kruger setup, and one could conceive a permutation test approach to estimate how much of the Dunning-Kruger setup is due to it. Nevertheless, my impression is that there is something more there.
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
"Just an artefact" sounds like the effect could be entirely due to regression to the mean. That is a very strong statement. In fact, Kruger & Dunning already addressed this in section 4.1.3 in their o
|
41,164
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
|
Dunning-Kruger only showed that almost everyone, regardless of actual ability level (with the exception of those with very high ability), believes their own performance is above average. This isn't surprising at all, because people judge their own ability relative to the more typical person - because there are more typical people out there, then exceptionally rare people. DK did not show that low skilled individuals believe they are superior to highly ability individuals, which is a common and convenient misinterpretation of the study. It does suggest the low ability individuals believe they are 'relatively', a lot more able than they actually are.
Of course, one important consideration, is measures of 'ability' themselves. For example, in the test of 'logical ability', one should consider, in the light of recent studies on rationality and intuition, that an apparently high capacity for reasoning, on a test with strict time limits, does not translate into the probability of behaving rationally in real time. In other words, it has been established that how well a person performs on a test, does not translate directly into the probability that they will think rationally (and in this case, 'logically') at any given point of time. It has also been established by Chudhursky, 2012, that when time limits are relaxed on tests of fluid reasoning, that performance loses correlation with performance under strict time limits. In other words, some people perform a lot better when time limits are relaxed. All of this means, that artificially creating ability scales based on performance in a very narrow window of time, is a flawed practice.
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
|
Dunning-Kruger only showed that almost everyone, regardless of actual ability level (with the exception of those with very high ability), believes their own performance is above average. This isn't s
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
Dunning-Kruger only showed that almost everyone, regardless of actual ability level (with the exception of those with very high ability), believes their own performance is above average. This isn't surprising at all, because people judge their own ability relative to the more typical person - because there are more typical people out there, then exceptionally rare people. DK did not show that low skilled individuals believe they are superior to highly ability individuals, which is a common and convenient misinterpretation of the study. It does suggest the low ability individuals believe they are 'relatively', a lot more able than they actually are.
Of course, one important consideration, is measures of 'ability' themselves. For example, in the test of 'logical ability', one should consider, in the light of recent studies on rationality and intuition, that an apparently high capacity for reasoning, on a test with strict time limits, does not translate into the probability of behaving rationally in real time. In other words, it has been established that how well a person performs on a test, does not translate directly into the probability that they will think rationally (and in this case, 'logically') at any given point of time. It has also been established by Chudhursky, 2012, that when time limits are relaxed on tests of fluid reasoning, that performance loses correlation with performance under strict time limits. In other words, some people perform a lot better when time limits are relaxed. All of this means, that artificially creating ability scales based on performance in a very narrow window of time, is a flawed practice.
|
Is the Dunning–Kruger effect mostly caused by regression to the mean?
Dunning-Kruger only showed that almost everyone, regardless of actual ability level (with the exception of those with very high ability), believes their own performance is above average. This isn't s
|
41,165
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivative?
|
As whuber commented, what you're seeing is due to the approximation (via a fast fourier transform) that density uses.
If you calculate the kernel density estimate by brute force and compare it to the estimate that density gives, you'll see this sort of cyclic pattern in the differences.
The 2nd differences in the result from density result in an exaggeration of the effect. The second differences from the brute-force kernel density estimate don't show that pattern, but the calculation is like 3 orders of magnitude slower.
I put some code in this gist. My brute-force kernel density estimate is the following:
mydensity <-
function(dat, x, bw=5) # dat=the data; x=points to calculate density estimate
{
y <- vapply(x, function(a) mean(dnorm(a, dat, bw)), 1)
data.frame(x=x, y=y)
}
Here's a picture of the second differences, blue from density and red from brute-force approach.
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivat
|
As whuber commented, what you're seeing is due to the approximation (via a fast fourier transform) that density uses.
If you calculate the kernel density estimate by brute force and compare it to the
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivative?
As whuber commented, what you're seeing is due to the approximation (via a fast fourier transform) that density uses.
If you calculate the kernel density estimate by brute force and compare it to the estimate that density gives, you'll see this sort of cyclic pattern in the differences.
The 2nd differences in the result from density result in an exaggeration of the effect. The second differences from the brute-force kernel density estimate don't show that pattern, but the calculation is like 3 orders of magnitude slower.
I put some code in this gist. My brute-force kernel density estimate is the following:
mydensity <-
function(dat, x, bw=5) # dat=the data; x=points to calculate density estimate
{
y <- vapply(x, function(a) mean(dnorm(a, dat, bw)), 1)
data.frame(x=x, y=y)
}
Here's a picture of the second differences, blue from density and red from brute-force approach.
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivat
As whuber commented, what you're seeing is due to the approximation (via a fast fourier transform) that density uses.
If you calculate the kernel density estimate by brute force and compare it to the
|
41,166
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivative?
|
In your codes in the gist you used a hard-entered bandwidth (bw=5) which is very different from a optimal one returned for example as:
library(ks)
h <- hpi(x)
which is actually about h=0.85.
It is interesting to execute your codes where bw is set to h. Then the final figure is as below. Here the differences are not so drastic.
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivat
|
In your codes in the gist you used a hard-entered bandwidth (bw=5) which is very different from a optimal one returned for example as:
library(ks)
h <- hpi(x)
which is actually about h=0.85.
It is in
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivative?
In your codes in the gist you used a hard-entered bandwidth (bw=5) which is very different from a optimal one returned for example as:
library(ks)
h <- hpi(x)
which is actually about h=0.85.
It is interesting to execute your codes where bw is set to h. Then the final figure is as below. Here the differences are not so drastic.
|
Why does a kernel density estimate of a normally distributed vector have a non-smooth second derivat
In your codes in the gist you used a hard-entered bandwidth (bw=5) which is very different from a optimal one returned for example as:
library(ks)
h <- hpi(x)
which is actually about h=0.85.
It is in
|
41,167
|
Clear steps to calculate coherence between two time series
|
The following are the issues that I summarize succinctly in sequence, as each of them are an interesting problem in itself and then follow it up with my solutions:
i) How to unlag two time-series so as to lose the least data due to the lagging, and at the same time to maximize the cross-correlation or spectral coherence.
ii) how would this be done when you are dealing with multivariate time-series. As it's greater than the two, its like solving a rubiks cube optimally while lagging various time-series in the dataset so as to preserve a summed up measure of (i).
iii) How to compute a weighted-coherence?
I will skip ii) and answer i) and iii) due to reasons of conflict of interest and research collaboration/confidential agreements on my work on ii). I understand that iii) happens to be the central question to start with followed by i).
My solution for iii)
Pre-Processing Steps: Say you had two time -series t1 and t2. Determine a CCF maximizing lag, say optLag and unlag t1 and t2 as unlaggedTS = lag(t2,optLag) and perform a time-series union of the dataset as unionTS = ts.union(t1,unlaggedTS).
Following that, as the time-series unlagging would produce a few NA's as you lose entries by lagging, you need to set these values to zero in unionTS as required-meaning that nothing was observed at the NA points.
Step 2:
Now, obtain an abinded time-series, with the span parameters as required.
bindTSPair= abind(((spectrum(unionTS,span=c(16,16),plot=F)$spec)[,1]),((spectrum(unionTS,span=c(16,16),plot=F)$spec)[,2]))
Following it, just normalize the data in bindTSPair as say:
normalizedTS=round(data.Normalization(c(bindTSPair),type="n4"),6)
Then obtained the following two halves:
TSHalf1=normalizedTS[1:(length(bindTSPair)/2)]
TSHalf2=normalizedTS[((length(bindTSPair)/2)+1):(length(bindTSPair))]
and then finally obtain 'a weighted' version of spectral coherence as follows:
weightedCoherence=sum((10*(TSHalf1 + TSHalf2)) * (spectrum(unionTS,span=c(10,10),plot=F)$coh))
You may change the weighting as required or using 'prior' info.
My solution for i) to obtain a CCF maximizing lag:
for(i in 2:ncol(myTS))
{
for(j in 2:ncol(myTS))
{
r=ccf(myTS[,i],myTS[,j],lag.max=1000,plot=TRUE)
tp=sort((r$acf),index.return=TRUE)$ix
tn=sort((r$acf),index.return=TRUE,decreasing=T)$ix
cn=r$acf[tn[length(tn)]]
cp=r$acf[tp[length(tp)]]
if(abs(cp) > abs(cn))
{
temp=r$lag[tp[length(tp)]]
tcc=cp
}
if(abs(cn) > abs(cp))
{
temp=r$lag[tn[length(tn)]]
tp=tn
tcc=cn
}
if(abs(cn) > abs(cp))
{
temp=r$lag[tp[length(tp)]]
}
show(i)
if(length(tp) != 0)
{
mlag[i,j]=temp
mcc[i,j]=tcc
}
}
}
mlag=mlag[2:ncol(myTS),2:ncol(myTS)]
mlag=data.frame(mlag)
|
Clear steps to calculate coherence between two time series
|
The following are the issues that I summarize succinctly in sequence, as each of them are an interesting problem in itself and then follow it up with my solutions:
i) How to unlag two time-series so
|
Clear steps to calculate coherence between two time series
The following are the issues that I summarize succinctly in sequence, as each of them are an interesting problem in itself and then follow it up with my solutions:
i) How to unlag two time-series so as to lose the least data due to the lagging, and at the same time to maximize the cross-correlation or spectral coherence.
ii) how would this be done when you are dealing with multivariate time-series. As it's greater than the two, its like solving a rubiks cube optimally while lagging various time-series in the dataset so as to preserve a summed up measure of (i).
iii) How to compute a weighted-coherence?
I will skip ii) and answer i) and iii) due to reasons of conflict of interest and research collaboration/confidential agreements on my work on ii). I understand that iii) happens to be the central question to start with followed by i).
My solution for iii)
Pre-Processing Steps: Say you had two time -series t1 and t2. Determine a CCF maximizing lag, say optLag and unlag t1 and t2 as unlaggedTS = lag(t2,optLag) and perform a time-series union of the dataset as unionTS = ts.union(t1,unlaggedTS).
Following that, as the time-series unlagging would produce a few NA's as you lose entries by lagging, you need to set these values to zero in unionTS as required-meaning that nothing was observed at the NA points.
Step 2:
Now, obtain an abinded time-series, with the span parameters as required.
bindTSPair= abind(((spectrum(unionTS,span=c(16,16),plot=F)$spec)[,1]),((spectrum(unionTS,span=c(16,16),plot=F)$spec)[,2]))
Following it, just normalize the data in bindTSPair as say:
normalizedTS=round(data.Normalization(c(bindTSPair),type="n4"),6)
Then obtained the following two halves:
TSHalf1=normalizedTS[1:(length(bindTSPair)/2)]
TSHalf2=normalizedTS[((length(bindTSPair)/2)+1):(length(bindTSPair))]
and then finally obtain 'a weighted' version of spectral coherence as follows:
weightedCoherence=sum((10*(TSHalf1 + TSHalf2)) * (spectrum(unionTS,span=c(10,10),plot=F)$coh))
You may change the weighting as required or using 'prior' info.
My solution for i) to obtain a CCF maximizing lag:
for(i in 2:ncol(myTS))
{
for(j in 2:ncol(myTS))
{
r=ccf(myTS[,i],myTS[,j],lag.max=1000,plot=TRUE)
tp=sort((r$acf),index.return=TRUE)$ix
tn=sort((r$acf),index.return=TRUE,decreasing=T)$ix
cn=r$acf[tn[length(tn)]]
cp=r$acf[tp[length(tp)]]
if(abs(cp) > abs(cn))
{
temp=r$lag[tp[length(tp)]]
tcc=cp
}
if(abs(cn) > abs(cp))
{
temp=r$lag[tn[length(tn)]]
tp=tn
tcc=cn
}
if(abs(cn) > abs(cp))
{
temp=r$lag[tp[length(tp)]]
}
show(i)
if(length(tp) != 0)
{
mlag[i,j]=temp
mcc[i,j]=tcc
}
}
}
mlag=mlag[2:ncol(myTS),2:ncol(myTS)]
mlag=data.frame(mlag)
|
Clear steps to calculate coherence between two time series
The following are the issues that I summarize succinctly in sequence, as each of them are an interesting problem in itself and then follow it up with my solutions:
i) How to unlag two time-series so
|
41,168
|
Clear steps to calculate coherence between two time series
|
unless your task is to actually implement coherence calculation, I wouldn't do it, because there's got to be a package for that. e.g. I see coh package, haven't used it myself. this function seems to do all that you need for a specific frequency f, so you can loop a call to it over the frequency range.
In matlab there's a function called mscohere, which produces an entire graph like this one, it's squared magnitude of coherence
I apolologise for using Matlab example, but I didn't do any spectral analysis in R myself yet. The concepts are the same though.
|
Clear steps to calculate coherence between two time series
|
unless your task is to actually implement coherence calculation, I wouldn't do it, because there's got to be a package for that. e.g. I see coh package, haven't used it myself. this function seems to
|
Clear steps to calculate coherence between two time series
unless your task is to actually implement coherence calculation, I wouldn't do it, because there's got to be a package for that. e.g. I see coh package, haven't used it myself. this function seems to do all that you need for a specific frequency f, so you can loop a call to it over the frequency range.
In matlab there's a function called mscohere, which produces an entire graph like this one, it's squared magnitude of coherence
I apolologise for using Matlab example, but I didn't do any spectral analysis in R myself yet. The concepts are the same though.
|
Clear steps to calculate coherence between two time series
unless your task is to actually implement coherence calculation, I wouldn't do it, because there's got to be a package for that. e.g. I see coh package, haven't used it myself. this function seems to
|
41,169
|
Clear steps to calculate coherence between two time series
|
Use seewave::coh() to extract the coherence and lag values for the maximum coherence point:
coherence <- coh(ts1, ts2, f=100, plot=TRUE)
lags <- coherence[,1]
vals <- coherence[,2]
val.max <- vals[which.max(vals)]
lag.max <- lags[which.max(vals)]
The coh() function is designed to work with ts objects. This is a simple way of doing the calculation Praneeth describes here.
|
Clear steps to calculate coherence between two time series
|
Use seewave::coh() to extract the coherence and lag values for the maximum coherence point:
coherence <- coh(ts1, ts2, f=100, plot=TRUE)
lags <- coherence[,1]
vals <- coherence[,2]
val.max
|
Clear steps to calculate coherence between two time series
Use seewave::coh() to extract the coherence and lag values for the maximum coherence point:
coherence <- coh(ts1, ts2, f=100, plot=TRUE)
lags <- coherence[,1]
vals <- coherence[,2]
val.max <- vals[which.max(vals)]
lag.max <- lags[which.max(vals)]
The coh() function is designed to work with ts objects. This is a simple way of doing the calculation Praneeth describes here.
|
Clear steps to calculate coherence between two time series
Use seewave::coh() to extract the coherence and lag values for the maximum coherence point:
coherence <- coh(ts1, ts2, f=100, plot=TRUE)
lags <- coherence[,1]
vals <- coherence[,2]
val.max
|
41,170
|
Estimating the covariance matrix in linear discriminant analysis
|
You are right. The equation for the shared variance-covariance matrix comes from Pooled Variance
The shared covariance matrix $\Sigma$ is taken as a weighted average of individual covariance matrices, weigted by $n_i-1$
So $\Sigma = \frac{(n_1-1) * \Sigma_1 + (n_2-1) * \Sigma_2 + .... + (n_k-1) * \Sigma_k}{(n_1-1)+(n_2-1)+...+(n_k-1)}$
|
Estimating the covariance matrix in linear discriminant analysis
|
You are right. The equation for the shared variance-covariance matrix comes from Pooled Variance
The shared covariance matrix $\Sigma$ is taken as a weighted average of individual covariance matrices,
|
Estimating the covariance matrix in linear discriminant analysis
You are right. The equation for the shared variance-covariance matrix comes from Pooled Variance
The shared covariance matrix $\Sigma$ is taken as a weighted average of individual covariance matrices, weigted by $n_i-1$
So $\Sigma = \frac{(n_1-1) * \Sigma_1 + (n_2-1) * \Sigma_2 + .... + (n_k-1) * \Sigma_k}{(n_1-1)+(n_2-1)+...+(n_k-1)}$
|
Estimating the covariance matrix in linear discriminant analysis
You are right. The equation for the shared variance-covariance matrix comes from Pooled Variance
The shared covariance matrix $\Sigma$ is taken as a weighted average of individual covariance matrices,
|
41,171
|
What is the interval that relates to the mean as the equal tailed interval relates to the median and the highest density interval relates to the mode?
|
I don't know if the interval centered on the mean has a special name, but I can think of more than one way that one could define an interval centered on the mean in the sense that the interval will converge to the mean as the width of the inverval goes to zero. The most simple would perhaps be the interval
$$C = (\mu-k, \mu+k),$$
where $\mu$ is the mean and $k$ is the smallest value for which
$P(x\in C)\ge 1-\alpha$ holds.
More general, one could define the mean centered interval as
$$C = (\mu-a, \mu+b),$$
where $a$ and $b$ are positive and chosen by some procedure such that again the interval has the desired credibility.
However, I think there are good reasons for mainly considering the highest density region and the equal tailed interval. To quote Christian Robert (The Bayesian Choice):
To consider only HPD [highest posterior density] regions is motivated by the fact that they minimize the volume among $\alpha$-credible regions and, therefore, can be envisioned as optimal solutions in a decision setting.
Highest density regions are not necessarily connected intervals, which can happen for example when the distribution is multimodal. On this, Robert writes:
When (...) the confidence region is not connected (...), the usual
solution is to replace the HPD $\alpha$-credible region by an interval with equal tails.
|
What is the interval that relates to the mean as the equal tailed interval relates to the median and
|
I don't know if the interval centered on the mean has a special name, but I can think of more than one way that one could define an interval centered on the mean in the sense that the interval will co
|
What is the interval that relates to the mean as the equal tailed interval relates to the median and the highest density interval relates to the mode?
I don't know if the interval centered on the mean has a special name, but I can think of more than one way that one could define an interval centered on the mean in the sense that the interval will converge to the mean as the width of the inverval goes to zero. The most simple would perhaps be the interval
$$C = (\mu-k, \mu+k),$$
where $\mu$ is the mean and $k$ is the smallest value for which
$P(x\in C)\ge 1-\alpha$ holds.
More general, one could define the mean centered interval as
$$C = (\mu-a, \mu+b),$$
where $a$ and $b$ are positive and chosen by some procedure such that again the interval has the desired credibility.
However, I think there are good reasons for mainly considering the highest density region and the equal tailed interval. To quote Christian Robert (The Bayesian Choice):
To consider only HPD [highest posterior density] regions is motivated by the fact that they minimize the volume among $\alpha$-credible regions and, therefore, can be envisioned as optimal solutions in a decision setting.
Highest density regions are not necessarily connected intervals, which can happen for example when the distribution is multimodal. On this, Robert writes:
When (...) the confidence region is not connected (...), the usual
solution is to replace the HPD $\alpha$-credible region by an interval with equal tails.
|
What is the interval that relates to the mean as the equal tailed interval relates to the median and
I don't know if the interval centered on the mean has a special name, but I can think of more than one way that one could define an interval centered on the mean in the sense that the interval will co
|
41,172
|
Standard deviation for values below 1
|
If my standard deviation and variance are above 1, the standard deviation will be smaller than the variance. But if they are below 1, the standard deviation will be bigger than the variance.
Actually, this is not the case, because you're ignoring the units. Standard deviation of a percentage is measured in percent, while the variance is not.
It's like having a standard deviation of 20 cm (variance 400 cm$^2$) and then worrying about if you measure it in meters, that the variance (0.04 m$^2$) is smaller than the standard deviation (0.2 m). While 0.04 is less than 0.2, you're comparing apples and oranges - they're in different units!
So you can't say that the variance is bigger than or smaller than the standard deviation. They're not comparable at all.
Nothing is amiss: you can happily work with values above 1 or below 1; everything remains consistent. There's nothing to account for.
The only source of a problem I perceive there is if some of your values are in whole percent (50) and some are written as a fraction (0.50), without keeping track of the corresponding units. That you would worry about.
|
Standard deviation for values below 1
|
If my standard deviation and variance are above 1, the standard deviation will be smaller than the variance. But if they are below 1, the standard deviation will be bigger than the variance.
Actually
|
Standard deviation for values below 1
If my standard deviation and variance are above 1, the standard deviation will be smaller than the variance. But if they are below 1, the standard deviation will be bigger than the variance.
Actually, this is not the case, because you're ignoring the units. Standard deviation of a percentage is measured in percent, while the variance is not.
It's like having a standard deviation of 20 cm (variance 400 cm$^2$) and then worrying about if you measure it in meters, that the variance (0.04 m$^2$) is smaller than the standard deviation (0.2 m). While 0.04 is less than 0.2, you're comparing apples and oranges - they're in different units!
So you can't say that the variance is bigger than or smaller than the standard deviation. They're not comparable at all.
Nothing is amiss: you can happily work with values above 1 or below 1; everything remains consistent. There's nothing to account for.
The only source of a problem I perceive there is if some of your values are in whole percent (50) and some are written as a fraction (0.50), without keeping track of the corresponding units. That you would worry about.
|
Standard deviation for values below 1
If my standard deviation and variance are above 1, the standard deviation will be smaller than the variance. But if they are below 1, the standard deviation will be bigger than the variance.
Actually
|
41,173
|
Standard deviation for values below 1
|
Variance (which ST is derived from) measures differences from the mean. Given differences from the average d1 and d2, whether D > 0 or D < 0 this always applies: d1 <=> d2 === d1^2 <=> d2^2.
Examples:
d1 = 2
d2 = 3
2 < 3 and 4 < 9
d1 = 0.1
d2 = 0.5
0.1 < 0.5 and 0.01 < 0.25
d1 = 0.5
d2 = 2
0.5 < 2 and 0.25 < 4
I don't know exactly how standard deviation works in practice but it holds true that larger differences give a larger value and small differences give a smaller value even if squaring switches from increasing to decreasing going down passed one.
I think this is valid as once you reach as low as 1, the only way from there toward 0 is down. On a plotter it should produce a continuous curve.
Standard deviation will be compared to standard deviation and variance with variance. As long as you stick to that whether using the standard deviation (square root) or variance (averaged squared differences) they'll remain proportionately comparable.
I believe that SD will effectively be converting it from a geometric (squared curve) to a linear curve.
Please excuse that I am from a programming background. The notation I use is works are <=> means compare (-1 less than, 0 same, 1 more than) and === means exactly equal. Numbers in variables are part of the variable name, multiplication only happens with an explicit *.
|
Standard deviation for values below 1
|
Variance (which ST is derived from) measures differences from the mean. Given differences from the average d1 and d2, whether D > 0 or D < 0 this always applies: d1 <=> d2 === d1^2 <=> d2^2.
Examples
|
Standard deviation for values below 1
Variance (which ST is derived from) measures differences from the mean. Given differences from the average d1 and d2, whether D > 0 or D < 0 this always applies: d1 <=> d2 === d1^2 <=> d2^2.
Examples:
d1 = 2
d2 = 3
2 < 3 and 4 < 9
d1 = 0.1
d2 = 0.5
0.1 < 0.5 and 0.01 < 0.25
d1 = 0.5
d2 = 2
0.5 < 2 and 0.25 < 4
I don't know exactly how standard deviation works in practice but it holds true that larger differences give a larger value and small differences give a smaller value even if squaring switches from increasing to decreasing going down passed one.
I think this is valid as once you reach as low as 1, the only way from there toward 0 is down. On a plotter it should produce a continuous curve.
Standard deviation will be compared to standard deviation and variance with variance. As long as you stick to that whether using the standard deviation (square root) or variance (averaged squared differences) they'll remain proportionately comparable.
I believe that SD will effectively be converting it from a geometric (squared curve) to a linear curve.
Please excuse that I am from a programming background. The notation I use is works are <=> means compare (-1 less than, 0 same, 1 more than) and === means exactly equal. Numbers in variables are part of the variable name, multiplication only happens with an explicit *.
|
Standard deviation for values below 1
Variance (which ST is derived from) measures differences from the mean. Given differences from the average d1 and d2, whether D > 0 or D < 0 this always applies: d1 <=> d2 === d1^2 <=> d2^2.
Examples
|
41,174
|
Coverage Proof of Confidence Intervals
|
Probably because you got the quantiles wrong (I suppose your $q(\cdot )$ are the quantiles of the standard normal), which should be $q_{1-\frac{\alpha}{2}}$. Basically what you want to show is that
$$Pr\left( E(Y) \in \left( \widehat{E(Y)} - q_{1-\frac{\alpha}{2}} \sqrt{\frac{\widehat{Var(Y)}}{n}}, \widehat{E(Y)} + q_{1-\frac{\alpha}{2}} \sqrt{\frac{\widehat{Var(Y)}}{n}} \right) \right) $$
which is equal to showing that
$$Pr\left( \sqrt{n}\left( \frac{\widehat{E(Y)}-E(Y)}{\sqrt{\widehat{Var(Y)}}} \right) \in \left( -q_{1-\frac{\alpha}{2}}, q_{1-\frac{\alpha}{2}} \right) \right) $$
You already know that $\sqrt{n}\left( \frac{\widehat{E(Y)}-E(Y)}{\sqrt{\widehat{Var(Y)}}} \right)$ is distributed as $N(0,1)$ so this should be straight forward. A trick that will help is to know that $-q_{1-\frac{\alpha}{2}}=q_{\frac{\alpha}{2}}$ in order to figure out the probabilities that $N(0,1) \leq q_{1-\frac{\alpha}{2}}$ and $N(0,1) > q_\frac{\alpha}{2}$
|
Coverage Proof of Confidence Intervals
|
Probably because you got the quantiles wrong (I suppose your $q(\cdot )$ are the quantiles of the standard normal), which should be $q_{1-\frac{\alpha}{2}}$. Basically what you want to show is that
$$
|
Coverage Proof of Confidence Intervals
Probably because you got the quantiles wrong (I suppose your $q(\cdot )$ are the quantiles of the standard normal), which should be $q_{1-\frac{\alpha}{2}}$. Basically what you want to show is that
$$Pr\left( E(Y) \in \left( \widehat{E(Y)} - q_{1-\frac{\alpha}{2}} \sqrt{\frac{\widehat{Var(Y)}}{n}}, \widehat{E(Y)} + q_{1-\frac{\alpha}{2}} \sqrt{\frac{\widehat{Var(Y)}}{n}} \right) \right) $$
which is equal to showing that
$$Pr\left( \sqrt{n}\left( \frac{\widehat{E(Y)}-E(Y)}{\sqrt{\widehat{Var(Y)}}} \right) \in \left( -q_{1-\frac{\alpha}{2}}, q_{1-\frac{\alpha}{2}} \right) \right) $$
You already know that $\sqrt{n}\left( \frac{\widehat{E(Y)}-E(Y)}{\sqrt{\widehat{Var(Y)}}} \right)$ is distributed as $N(0,1)$ so this should be straight forward. A trick that will help is to know that $-q_{1-\frac{\alpha}{2}}=q_{\frac{\alpha}{2}}$ in order to figure out the probabilities that $N(0,1) \leq q_{1-\frac{\alpha}{2}}$ and $N(0,1) > q_\frac{\alpha}{2}$
|
Coverage Proof of Confidence Intervals
Probably because you got the quantiles wrong (I suppose your $q(\cdot )$ are the quantiles of the standard normal), which should be $q_{1-\frac{\alpha}{2}}$. Basically what you want to show is that
$$
|
41,175
|
extremely left-skewed response variable - how do I model this dataset?
|
Hurdle models and zero-inflated models could both work on the inverted variable. If you wanted to keep it as is, you might have to do some programming.
In R the pscl package offers both hurdle and zeroinfl functions. There is a vignette here that also covers some other packages that do some of the same things.
This being R, if you do want to play with the program, you can see the code easily enough:
install.packages("pscl")
library("pscl")
zeroinfl
|
extremely left-skewed response variable - how do I model this dataset?
|
Hurdle models and zero-inflated models could both work on the inverted variable. If you wanted to keep it as is, you might have to do some programming.
In R the pscl package offers both hurdle and ze
|
extremely left-skewed response variable - how do I model this dataset?
Hurdle models and zero-inflated models could both work on the inverted variable. If you wanted to keep it as is, you might have to do some programming.
In R the pscl package offers both hurdle and zeroinfl functions. There is a vignette here that also covers some other packages that do some of the same things.
This being R, if you do want to play with the program, you can see the code easily enough:
install.packages("pscl")
library("pscl")
zeroinfl
|
extremely left-skewed response variable - how do I model this dataset?
Hurdle models and zero-inflated models could both work on the inverted variable. If you wanted to keep it as is, you might have to do some programming.
In R the pscl package offers both hurdle and ze
|
41,176
|
extremely left-skewed response variable - how do I model this dataset?
|
@whuber's answer to a related question ("How to model this odd-shaped distribution (almost a reverse-J)") recommends censored regression and provides an example with the censReg package. Your case appears more strictly right censored, but you might have a tiny bit of true zero-inflation too (not worth worrying about according to my intuition, which is not based on direct experience). It should be possible to calculate AIC for these models (cf. Wang, Liu, Lu, Latengbaolide, & Lu, 2011). BTW, partitioning into categories (polychotomization) is generally a bad idea (see my answer here for more).
|
extremely left-skewed response variable - how do I model this dataset?
|
@whuber's answer to a related question ("How to model this odd-shaped distribution (almost a reverse-J)") recommends censored regression and provides an example with the censReg package. Your case app
|
extremely left-skewed response variable - how do I model this dataset?
@whuber's answer to a related question ("How to model this odd-shaped distribution (almost a reverse-J)") recommends censored regression and provides an example with the censReg package. Your case appears more strictly right censored, but you might have a tiny bit of true zero-inflation too (not worth worrying about according to my intuition, which is not based on direct experience). It should be possible to calculate AIC for these models (cf. Wang, Liu, Lu, Latengbaolide, & Lu, 2011). BTW, partitioning into categories (polychotomization) is generally a bad idea (see my answer here for more).
|
extremely left-skewed response variable - how do I model this dataset?
@whuber's answer to a related question ("How to model this odd-shaped distribution (almost a reverse-J)") recommends censored regression and provides an example with the censReg package. Your case app
|
41,177
|
Regression Terminology
|
The "regression of W on Z" means you're predicting W from Z. Using your equations, this corresponds to the first one, namely $W=\alpha+\beta Z+\epsilon$
|
Regression Terminology
|
The "regression of W on Z" means you're predicting W from Z. Using your equations, this corresponds to the first one, namely $W=\alpha+\beta Z+\epsilon$
|
Regression Terminology
The "regression of W on Z" means you're predicting W from Z. Using your equations, this corresponds to the first one, namely $W=\alpha+\beta Z+\epsilon$
|
Regression Terminology
The "regression of W on Z" means you're predicting W from Z. Using your equations, this corresponds to the first one, namely $W=\alpha+\beta Z+\epsilon$
|
41,178
|
Overdispersed Poisson regression
|
The "resulting Poisson" is only the conditional distribution of the response given an (unobserved) realization of the normal error term: the unconditional response (or the response conditional only on the realized values of the predictors, if these are random variables) does not have a Poisson distribution.
Suppose the response $Y$ has a Poisson distribution
$$\newcommand{\E}{\operatorname{E}}\newcommand{\var}{\operatorname{Var}}Y|M \sim \mathrm{Pois}(M)$$
where $M$ is a log-normal variate with log-location given by the sum of products of each predictor $x_i$ with its coefficient $\beta_i$, & with log-scale $\sigma$:
$$M = \exp(\beta_0 + \beta_1 x_1 + \ldots + \sigma Z)$$
Conditionally on the realized value of $M$, $m$, $Y$ indeed has variance equal to the mean
$$\E (Y|M=m) = \var (Y | M=m) = m$$
but unconditionally it doesn't: the unconditional expectation is
$$\E Y = \E \E Y|M = \E M \\
= \exp(\beta_0 + \beta_1 x_1 + \ldots + \tfrac{\sigma^2}{2}) \\
= \exp(\beta_0 + \beta_1 x_1 + \ldots) \exp(\tfrac{\sigma^2}{2})$$
& the unconditional variance is
$$\var Y = \E \var Y|M + \var \E Y|M = \E M + \var M \\
= \exp(\beta_0 + \beta_1 x_1 + \ldots + \tfrac{\sigma^2}{2}) + [\exp(\sigma^2)-1]\exp(2(\beta_0 + \beta_1 x_1 + \ldots + \tfrac{\sigma^2}{2}))\\
= \exp(\beta_0 + \beta_1 x_1 + \ldots) \exp(\tfrac{\sigma^2}{2}) + \exp(\beta_0 + \beta_1 x_1 + \ldots)^2 [\exp(\sigma^2)-1] \exp(\sigma^2)$$
increasingly larger than the mean as $\sigma$ increases.
Over-dispersion is measured by $\sigma$: as it tends to zero the model tends to a Poisson model without over-dispersion. Note that over-dispersion parameters in different model families do not bear precisely the same interpretation. There is more than one way to specify a negative binomial model: typically from
$$\var Y = \E Y + \alpha (\E Y)^p$$
where $p$=1 for the NB1 model, $p=2$ for the NB2 model; note the over-dispersion parameter $\alpha$ relates variance to mean differently for different values of $p$.
|
Overdispersed Poisson regression
|
The "resulting Poisson" is only the conditional distribution of the response given an (unobserved) realization of the normal error term: the unconditional response (or the response conditional only on
|
Overdispersed Poisson regression
The "resulting Poisson" is only the conditional distribution of the response given an (unobserved) realization of the normal error term: the unconditional response (or the response conditional only on the realized values of the predictors, if these are random variables) does not have a Poisson distribution.
Suppose the response $Y$ has a Poisson distribution
$$\newcommand{\E}{\operatorname{E}}\newcommand{\var}{\operatorname{Var}}Y|M \sim \mathrm{Pois}(M)$$
where $M$ is a log-normal variate with log-location given by the sum of products of each predictor $x_i$ with its coefficient $\beta_i$, & with log-scale $\sigma$:
$$M = \exp(\beta_0 + \beta_1 x_1 + \ldots + \sigma Z)$$
Conditionally on the realized value of $M$, $m$, $Y$ indeed has variance equal to the mean
$$\E (Y|M=m) = \var (Y | M=m) = m$$
but unconditionally it doesn't: the unconditional expectation is
$$\E Y = \E \E Y|M = \E M \\
= \exp(\beta_0 + \beta_1 x_1 + \ldots + \tfrac{\sigma^2}{2}) \\
= \exp(\beta_0 + \beta_1 x_1 + \ldots) \exp(\tfrac{\sigma^2}{2})$$
& the unconditional variance is
$$\var Y = \E \var Y|M + \var \E Y|M = \E M + \var M \\
= \exp(\beta_0 + \beta_1 x_1 + \ldots + \tfrac{\sigma^2}{2}) + [\exp(\sigma^2)-1]\exp(2(\beta_0 + \beta_1 x_1 + \ldots + \tfrac{\sigma^2}{2}))\\
= \exp(\beta_0 + \beta_1 x_1 + \ldots) \exp(\tfrac{\sigma^2}{2}) + \exp(\beta_0 + \beta_1 x_1 + \ldots)^2 [\exp(\sigma^2)-1] \exp(\sigma^2)$$
increasingly larger than the mean as $\sigma$ increases.
Over-dispersion is measured by $\sigma$: as it tends to zero the model tends to a Poisson model without over-dispersion. Note that over-dispersion parameters in different model families do not bear precisely the same interpretation. There is more than one way to specify a negative binomial model: typically from
$$\var Y = \E Y + \alpha (\E Y)^p$$
where $p$=1 for the NB1 model, $p=2$ for the NB2 model; note the over-dispersion parameter $\alpha$ relates variance to mean differently for different values of $p$.
|
Overdispersed Poisson regression
The "resulting Poisson" is only the conditional distribution of the response given an (unobserved) realization of the normal error term: the unconditional response (or the response conditional only on
|
41,179
|
CDF of a random vector
|
Let us take the simplest example of Bernoulli random variables with parameter $\frac12$. The value of the (joint) CDF $F_{X_1,X_2}(x,y)$ of $X_1$ and $X_2$
is the
total probability mass in the southwest quadrant with northeast corner $(x,y)$
If $X_1$ and $X_2$ are two independent Bernoulli random variables,
then we have four probability masses of $\frac14$ sitting at
$(0,0), (1,0), (0,1)$, and $(1,1)$. Hence
$$F_{X_1,X_2}\left(\frac12,\frac12\right) = \frac14.$$
If $X_2 = 1-X_1$,
then we have two probability masses of $\frac12$ sitting at
$(1,0)$ and $(1,0)$. Hence
$$F_{X_1,X_2}\left(\frac12,\frac12\right) = 0.$$
If $X_2 = X_1$, then we have two probability masses of $\frac12$ sitting at
$(0,0)$ and $(1,1)$. Hence
$$F_{X_1,X_2}\left(\frac12,\frac12\right) = \frac12.$$
Thus, the joint CDF of $X_1$ and $X_2$ does depend on what
kind of relationship (if any) they have with each other, and just
knowing the common CDF of $X_1$ and $X_2$ (these are marginal CDFs)
tells us nothing about the behavior the joint CDF.
|
CDF of a random vector
|
Let us take the simplest example of Bernoulli random variables with parameter $\frac12$. The value of the (joint) CDF $F_{X_1,X_2}(x,y)$ of $X_1$ and $X_2$
is the
total probability mass in the southw
|
CDF of a random vector
Let us take the simplest example of Bernoulli random variables with parameter $\frac12$. The value of the (joint) CDF $F_{X_1,X_2}(x,y)$ of $X_1$ and $X_2$
is the
total probability mass in the southwest quadrant with northeast corner $(x,y)$
If $X_1$ and $X_2$ are two independent Bernoulli random variables,
then we have four probability masses of $\frac14$ sitting at
$(0,0), (1,0), (0,1)$, and $(1,1)$. Hence
$$F_{X_1,X_2}\left(\frac12,\frac12\right) = \frac14.$$
If $X_2 = 1-X_1$,
then we have two probability masses of $\frac12$ sitting at
$(1,0)$ and $(1,0)$. Hence
$$F_{X_1,X_2}\left(\frac12,\frac12\right) = 0.$$
If $X_2 = X_1$, then we have two probability masses of $\frac12$ sitting at
$(0,0)$ and $(1,1)$. Hence
$$F_{X_1,X_2}\left(\frac12,\frac12\right) = \frac12.$$
Thus, the joint CDF of $X_1$ and $X_2$ does depend on what
kind of relationship (if any) they have with each other, and just
knowing the common CDF of $X_1$ and $X_2$ (these are marginal CDFs)
tells us nothing about the behavior the joint CDF.
|
CDF of a random vector
Let us take the simplest example of Bernoulli random variables with parameter $\frac12$. The value of the (joint) CDF $F_{X_1,X_2}(x,y)$ of $X_1$ and $X_2$
is the
total probability mass in the southw
|
41,180
|
CDF of a random vector
|
Random objects can have the same distribution and be almost surely different. Take a look:
Can two random variables have the same distribution, yet be almost surely different?
|
CDF of a random vector
|
Random objects can have the same distribution and be almost surely different. Take a look:
Can two random variables have the same distribution, yet be almost surely different?
|
CDF of a random vector
Random objects can have the same distribution and be almost surely different. Take a look:
Can two random variables have the same distribution, yet be almost surely different?
|
CDF of a random vector
Random objects can have the same distribution and be almost surely different. Take a look:
Can two random variables have the same distribution, yet be almost surely different?
|
41,181
|
CDF of a random vector
|
The key is the difference between joint and marginal distributions. When the book talks about the cdf of a random vector $X=(X_1,X_2)$ they mean the function $$F_X(x_1,x_2):=\mathbb{P}(X_1\leq x_1,X_2\leq x_2 ).$$ As you probably know, if $X_1$ and $X_2$ are independent, this equals $$F_{X_1}(x_1)F_{X_2}(x_2)=\mathbb{P}(X_1\leq x_1)\mathbb{P}(X_2\leq x_2),$$ but, on the other hand if they are not independent, we cannot separate the joint probability into their product like that per definition of dependence/independence.
Indeed, in your example where $X_1=X_2$, we have that $$F_X(x_1,x_2):=\mathbb{P}(X_1\leq x_1,X_2\leq x_2 )=\mathbb{P}(X_1\leq x_1,X_1\leq x_2 )=\mathbb{P}(X_1\leq \min(x_1, x_2))\neq\mathbb{P}(X_1\leq x_1)\mathbb{P}(X_1\leq x_2).$$
Again, the key is that just because two variables have the same marginal distribution, this does not mean their joint distributions with another variable are the same.
|
CDF of a random vector
|
The key is the difference between joint and marginal distributions. When the book talks about the cdf of a random vector $X=(X_1,X_2)$ they mean the function $$F_X(x_1,x_2):=\mathbb{P}(X_1\leq x_1,X_2
|
CDF of a random vector
The key is the difference between joint and marginal distributions. When the book talks about the cdf of a random vector $X=(X_1,X_2)$ they mean the function $$F_X(x_1,x_2):=\mathbb{P}(X_1\leq x_1,X_2\leq x_2 ).$$ As you probably know, if $X_1$ and $X_2$ are independent, this equals $$F_{X_1}(x_1)F_{X_2}(x_2)=\mathbb{P}(X_1\leq x_1)\mathbb{P}(X_2\leq x_2),$$ but, on the other hand if they are not independent, we cannot separate the joint probability into their product like that per definition of dependence/independence.
Indeed, in your example where $X_1=X_2$, we have that $$F_X(x_1,x_2):=\mathbb{P}(X_1\leq x_1,X_2\leq x_2 )=\mathbb{P}(X_1\leq x_1,X_1\leq x_2 )=\mathbb{P}(X_1\leq \min(x_1, x_2))\neq\mathbb{P}(X_1\leq x_1)\mathbb{P}(X_1\leq x_2).$$
Again, the key is that just because two variables have the same marginal distribution, this does not mean their joint distributions with another variable are the same.
|
CDF of a random vector
The key is the difference between joint and marginal distributions. When the book talks about the cdf of a random vector $X=(X_1,X_2)$ they mean the function $$F_X(x_1,x_2):=\mathbb{P}(X_1\leq x_1,X_2
|
41,182
|
What type of regression to use with 1 to 10 scale dependent variable?
|
Here is R example using package MASS with polr function (ordered factorial response) which can use logistic link or be probit.
library(MASS);
recmodel=polr(recom~trust+solutions+proact+qs+es,data=surveydata,method=c("logistic"));
summary(recmodel);
I think it is important to give R notice that all variables are ordinal which means that it must not use them as interval variables.
Inference can be done as a comparison to some baseline. For example value 1 can be such.
|
What type of regression to use with 1 to 10 scale dependent variable?
|
Here is R example using package MASS with polr function (ordered factorial response) which can use logistic link or be probit.
library(MASS);
recmodel=polr(recom~trust+solutions+proact+qs+es,data=su
|
What type of regression to use with 1 to 10 scale dependent variable?
Here is R example using package MASS with polr function (ordered factorial response) which can use logistic link or be probit.
library(MASS);
recmodel=polr(recom~trust+solutions+proact+qs+es,data=surveydata,method=c("logistic"));
summary(recmodel);
I think it is important to give R notice that all variables are ordinal which means that it must not use them as interval variables.
Inference can be done as a comparison to some baseline. For example value 1 can be such.
|
What type of regression to use with 1 to 10 scale dependent variable?
Here is R example using package MASS with polr function (ordered factorial response) which can use logistic link or be probit.
library(MASS);
recmodel=polr(recom~trust+solutions+proact+qs+es,data=su
|
41,183
|
What type of regression to use with 1 to 10 scale dependent variable?
|
1) Judging by the questions in the survey, the likelihood of multi-collinearity is high. You should definitely check for correlation and VIF between your predictor variables before thinking of running the regression.
2) Apart from regression and at the cost of sounding simplistic, I suggest you do some summary statistics and exploratory analysis. a) What is the distribution of responses for each question? b) Depending on the response on an individual question, how the response variable moves. For e.g.: What % of people who rated beetween 5 & 7 on question 2, also said they were likely (rating above 7) to recommend to others?
The descriptive analysis will visualize and give good direction of where you need to head with the regression analysis.
|
What type of regression to use with 1 to 10 scale dependent variable?
|
1) Judging by the questions in the survey, the likelihood of multi-collinearity is high. You should definitely check for correlation and VIF between your predictor variables before thinking of running
|
What type of regression to use with 1 to 10 scale dependent variable?
1) Judging by the questions in the survey, the likelihood of multi-collinearity is high. You should definitely check for correlation and VIF between your predictor variables before thinking of running the regression.
2) Apart from regression and at the cost of sounding simplistic, I suggest you do some summary statistics and exploratory analysis. a) What is the distribution of responses for each question? b) Depending on the response on an individual question, how the response variable moves. For e.g.: What % of people who rated beetween 5 & 7 on question 2, also said they were likely (rating above 7) to recommend to others?
The descriptive analysis will visualize and give good direction of where you need to head with the regression analysis.
|
What type of regression to use with 1 to 10 scale dependent variable?
1) Judging by the questions in the survey, the likelihood of multi-collinearity is high. You should definitely check for correlation and VIF between your predictor variables before thinking of running
|
41,184
|
What type of regression to use with 1 to 10 scale dependent variable?
|
As pointed out in the comments, the dependent variable can be handled with ordinal logit. For the independent variables, the most flexible approach is to convert each variable to 10 dummy variables (assuming you drop the constant from the model). Interpretation will get a little bit messy, but you are not imposing any functional form assumptions on the independent variables.
|
What type of regression to use with 1 to 10 scale dependent variable?
|
As pointed out in the comments, the dependent variable can be handled with ordinal logit. For the independent variables, the most flexible approach is to convert each variable to 10 dummy variables (a
|
What type of regression to use with 1 to 10 scale dependent variable?
As pointed out in the comments, the dependent variable can be handled with ordinal logit. For the independent variables, the most flexible approach is to convert each variable to 10 dummy variables (assuming you drop the constant from the model). Interpretation will get a little bit messy, but you are not imposing any functional form assumptions on the independent variables.
|
What type of regression to use with 1 to 10 scale dependent variable?
As pointed out in the comments, the dependent variable can be handled with ordinal logit. For the independent variables, the most flexible approach is to convert each variable to 10 dummy variables (a
|
41,185
|
What type of regression to use with 1 to 10 scale dependent variable?
|
You can also try the stereotype logistic regression model (a type of reduced-rank generalized linear regression model) that relaxes the constraint of ordering (without reverting to a multinomial logistic regression model, which with ten outcome levels will present a great deal of parameters that might hinder your ability to interpret the relationships in tee data). The constraint of ordering relies on the proportional odds assumption, which may be violated in some instances when using the ordinal regression model. See ?rrvglm in the VGAM package for examples on fitting the stereotype logistic model.
|
What type of regression to use with 1 to 10 scale dependent variable?
|
You can also try the stereotype logistic regression model (a type of reduced-rank generalized linear regression model) that relaxes the constraint of ordering (without reverting to a multinomial logis
|
What type of regression to use with 1 to 10 scale dependent variable?
You can also try the stereotype logistic regression model (a type of reduced-rank generalized linear regression model) that relaxes the constraint of ordering (without reverting to a multinomial logistic regression model, which with ten outcome levels will present a great deal of parameters that might hinder your ability to interpret the relationships in tee data). The constraint of ordering relies on the proportional odds assumption, which may be violated in some instances when using the ordinal regression model. See ?rrvglm in the VGAM package for examples on fitting the stereotype logistic model.
|
What type of regression to use with 1 to 10 scale dependent variable?
You can also try the stereotype logistic regression model (a type of reduced-rank generalized linear regression model) that relaxes the constraint of ordering (without reverting to a multinomial logis
|
41,186
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
|
From my perspective the Normal distribution is useful as a prior on the the mean of a Normal distribution because:
The Normal is the conjugate prior to the mean of a Normal distribution. Using conjugate priors can really speed up computation in, for example, JAGS
It is pretty easy to make the Normal distribution both informative, the mean and SD are parameters that are easy to set as it is relativley clear how they affect the shape of the distribution, and non-informative, just make the SD extremely large and the prior will approach the uniform distribution.
Here is a silly but "real life" example of how the Normal could be used as a slightly informative distribution. :)
Farmer Jöns and Milk Production.
Farmer Jöns has a huge number of cows. He would like to know how much milk a cow is expected to produce on average and thus measures the number of liters of milk that six cows produce during one month:
milk <- c(651, 374, 601, 401, 767, 709)
He sends this data to his statistician friend who tells him that, "Well it's not that much data to work with, but the estimate might get a bit better if you tell me how much milk in your experience a cow produces per month on average". "I haven't thought that much about it", replies Jöns, "but perhaps around 500-600 liters/month is usual."
The statistician decides to run a Bayesian analysis where milk is assumed to be normally distributed:
$$ \mathrm{milk} \sim \mathrm{Norm}(\mu, \sigma) $$
The statistician encodes the information he got from Jöns in the prior on $\mu$ which is pretty easy to do as he choose to use a Normal distribution for this:
$$ \mu \sim \mathrm{Norm}(550, 100) $$
This Normal prior is centered around 550 and has a standard deviation of 100 basically saying that prior to looking at the data the mean is most likely to be in the range 450-650.
As he forgot to ask about the spread of milk production of different cows he puts a flat prior on $\sigma$:
$$ \sigma \sim \mathrm{Unif}(0, 1000) $$
An implementation of this analysis in R using the rjags package would look like this:
library(rjags)
model_string <- "model {
for(i in 1:length(milk)) {
milk[i] ~ dnorm(mu, 1/(sigma * sigma) )
}
mu ~ dnorm(550, 1 / (100*100))
sigma ~ dunif(0, 1000)\n
}"
# The reason for the 1/ (sigma*sigma) 'thing' is because dnorm in JAGS is
# parameterized by precision (1 / SD^2) instead of SD as in R.
model <- jags.model(textConnection(model_string), data = list(milk = milk))
fit <- coda.samples(model, variable.names = c("mu", "sigma"), n.iter = 30000)
summary(fit)
##
## Iterations = 1001:31000
## Thinning interval = 1
## Number of chains = 1
## Sample size per chain = 30000
##
## 1. Empirical mean and standard deviation for each variable,
## plus standard error of the mean:
##
## Mean SD Naive SE Time-series SE
## mu 570 63.3 0.365 0.368
## sigma 208 89.3 0.516 1.173
##
## 2. Quantiles for each variable:
##
## 2.5% 25% 50% 75% 97.5%
## mu 440 530 571 611 693
## sigma 106 150 187 241 435
Looking at the quantiles for the posterior of $\mu$ the statistician tells Jöns that a good guess for the number of liters of milk a cow is expected to produce on average is 571 liters/month and the average is probably not lower than 440 liters/month or higher than 693 liters/month.
What we gained from using a normal distribution as the prior on $\mu$ was a slightly tighter estimate (and hopefully better too). Compare with the 95 % CI using t.test:
t.test(milk)
##
## One Sample t-test
##
## data: milk
## t = 8.819, df = 5, p-value = 0.0003113
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
## 413.7 754.0
## sample estimates:
## mean of x
## 583.8
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
|
From my perspective the Normal distribution is useful as a prior on the the mean of a Normal distribution because:
The Normal is the conjugate prior to the mean of a Normal distribution. Using conjug
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
From my perspective the Normal distribution is useful as a prior on the the mean of a Normal distribution because:
The Normal is the conjugate prior to the mean of a Normal distribution. Using conjugate priors can really speed up computation in, for example, JAGS
It is pretty easy to make the Normal distribution both informative, the mean and SD are parameters that are easy to set as it is relativley clear how they affect the shape of the distribution, and non-informative, just make the SD extremely large and the prior will approach the uniform distribution.
Here is a silly but "real life" example of how the Normal could be used as a slightly informative distribution. :)
Farmer Jöns and Milk Production.
Farmer Jöns has a huge number of cows. He would like to know how much milk a cow is expected to produce on average and thus measures the number of liters of milk that six cows produce during one month:
milk <- c(651, 374, 601, 401, 767, 709)
He sends this data to his statistician friend who tells him that, "Well it's not that much data to work with, but the estimate might get a bit better if you tell me how much milk in your experience a cow produces per month on average". "I haven't thought that much about it", replies Jöns, "but perhaps around 500-600 liters/month is usual."
The statistician decides to run a Bayesian analysis where milk is assumed to be normally distributed:
$$ \mathrm{milk} \sim \mathrm{Norm}(\mu, \sigma) $$
The statistician encodes the information he got from Jöns in the prior on $\mu$ which is pretty easy to do as he choose to use a Normal distribution for this:
$$ \mu \sim \mathrm{Norm}(550, 100) $$
This Normal prior is centered around 550 and has a standard deviation of 100 basically saying that prior to looking at the data the mean is most likely to be in the range 450-650.
As he forgot to ask about the spread of milk production of different cows he puts a flat prior on $\sigma$:
$$ \sigma \sim \mathrm{Unif}(0, 1000) $$
An implementation of this analysis in R using the rjags package would look like this:
library(rjags)
model_string <- "model {
for(i in 1:length(milk)) {
milk[i] ~ dnorm(mu, 1/(sigma * sigma) )
}
mu ~ dnorm(550, 1 / (100*100))
sigma ~ dunif(0, 1000)\n
}"
# The reason for the 1/ (sigma*sigma) 'thing' is because dnorm in JAGS is
# parameterized by precision (1 / SD^2) instead of SD as in R.
model <- jags.model(textConnection(model_string), data = list(milk = milk))
fit <- coda.samples(model, variable.names = c("mu", "sigma"), n.iter = 30000)
summary(fit)
##
## Iterations = 1001:31000
## Thinning interval = 1
## Number of chains = 1
## Sample size per chain = 30000
##
## 1. Empirical mean and standard deviation for each variable,
## plus standard error of the mean:
##
## Mean SD Naive SE Time-series SE
## mu 570 63.3 0.365 0.368
## sigma 208 89.3 0.516 1.173
##
## 2. Quantiles for each variable:
##
## 2.5% 25% 50% 75% 97.5%
## mu 440 530 571 611 693
## sigma 106 150 187 241 435
Looking at the quantiles for the posterior of $\mu$ the statistician tells Jöns that a good guess for the number of liters of milk a cow is expected to produce on average is 571 liters/month and the average is probably not lower than 440 liters/month or higher than 693 liters/month.
What we gained from using a normal distribution as the prior on $\mu$ was a slightly tighter estimate (and hopefully better too). Compare with the 95 % CI using t.test:
t.test(milk)
##
## One Sample t-test
##
## data: milk
## t = 8.819, df = 5, p-value = 0.0003113
## alternative hypothesis: true mean is not equal to 0
## 95 percent confidence interval:
## 413.7 754.0
## sample estimates:
## mean of x
## 583.8
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
From my perspective the Normal distribution is useful as a prior on the the mean of a Normal distribution because:
The Normal is the conjugate prior to the mean of a Normal distribution. Using conjug
|
41,187
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
|
Before delving directly into an example, I'd like to review some of the math for Normal-Normal Bayesian data models. Consider a random sample of n continuous values denoted by $y_1, ..., y_n$. Here the vector $y = (y_1, ..., y_n)^T$ represents the data gathered. The probability model for Normal data with known variance and independent and identically distributed (i.i.d.) samples is
$$
y_1, ..., y_n | \theta \sim N(\theta, \sigma^2)
$$
Or as more typically written by Bayesian,
$$
y_1, ..., y_n | \theta \sim N(\theta, \tau)
$$
where $\tau = 1 / \sigma^2$; $\tau$ is known as the precision
With this notation, the density for $y_i$ is then
$$
f(y_i | \theta, \tau) = \sqrt(\frac{\tau}{2 \pi}) \times exp\left( -\tau (y_i - \theta)^2 / 2 \right)
$$
Classical statistics (i.e. maximum likelihood) gives us an estimate of $\hat{\theta} = \bar{y}$
In a Bayesian perspective, we append maximum likelihood with prior information. A choice of priors for this Normal data model is another Normal distribution for $\theta$. The Normal distribution is conjugate to the Normal distribution.
$$
\theta \sim N(a,1/b)
$$
The posterior distribution we obtain from this Normal-Normal (after a lot of algebra) data model is another Normal distribution (so many Normals!)
$$
\theta | y \sim N(\frac{b}{b + n\tau} a + \frac{n \tau}{b + n \tau} \bar{y}, \frac{1}{b + n\tau})
$$
The posterior precision is $b + n\tau$ and mean is a weighted mean between $a$ and $\bar{y}$, $\frac{b}{b + n\tau} a + \frac{n \tau}{b + n \tau} \bar{y}$.
To your comment
I would like to find a real-life example of why such a construction would be not only elegant, but also useful.
The usefulness comes from the fact that you obtain a distribution of $\theta | y$ rather than just an estimate since $\theta$ is viewed as a random variable rather than a fixed (unknown) value. In addition, your estimate of $\theta$ in this model is a weighted average between the empirical mean and prior information.
That said, you can now use any Normal-data textbook example to illustrate this. I'll use the data set airquality within R. Consider the problem of estimating average wind speeds (MPH).
> ## New York Air Quality Measurements
>
> help("airquality")
>
> ## Estimating average wind speeds
>
> wind = airquality$Wind
> hist(wind, col = "gray", border = "white", xlab = "Wind Speed (MPH)")
>
> n = length(wind)
> ybar = mean(wind)
> ybar
[1] 9.957516 ## "frequentist" estimate
> tau = 1/sd(wind)
>
>
> ## but based on some research, you felt avgerage wind speeds were closer to 12 mph
> ## but probably no greater than 15,
> ## then a potential prior would be N(12, 2)
>
> a = 12
> b = 2
>
> ## Your posterior would be N((1/))
>
> postmean = 1/(1 + n*tau) * a + n*tau/(1 + n*tau) * ybar
> postsd = 1/(1 + n*tau)
>
> set.seed(123)
> posterior_sample = rnorm(n = 10000, mean = postmean, sd = postsd)
> hist(posterior_sample, col = "gray", border = "white", xlab = "Wind Speed (MPH)")
> abline(v = median(posterior_sample))
> abline(v = ybar, lty = 3)
>
> median(posterior_sample)
[1] 10.00324
> quantile(x = posterior_sample, probs = c(0.025, 0.975)) ## confidence intervals
2.5% 97.5%
9.958984 10.047404
In this analysis, the researcher (you) can say that given data + prior information, your estimate of average wind, using the 50th percentile, speeds should be 10.00324, greater than simply using the average from the data. You also obtain a full distribution, from which you can extract a 95% credible interval using the 2.5 and 97.5 quantiles.
Below I include two references, I highly recommend reading Casella's short paper. It's specifically aimed at empirical Bayes methods, but explains the general Bayesian methodology for Normal models.
References:
Casella, G. (1985). An Introduction to Empirical Bayes Data Analysis. The American Statistician, 39(2), 83-87.
Gelman, A. (2004). Bayesian data analysis (2nd ed., Texts in statistical science). Boca Raton, Fla.: Chapman & Hall/CRC.
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
|
Before delving directly into an example, I'd like to review some of the math for Normal-Normal Bayesian data models. Consider a random sample of n continuous values denoted by $y_1, ..., y_n$. Here th
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
Before delving directly into an example, I'd like to review some of the math for Normal-Normal Bayesian data models. Consider a random sample of n continuous values denoted by $y_1, ..., y_n$. Here the vector $y = (y_1, ..., y_n)^T$ represents the data gathered. The probability model for Normal data with known variance and independent and identically distributed (i.i.d.) samples is
$$
y_1, ..., y_n | \theta \sim N(\theta, \sigma^2)
$$
Or as more typically written by Bayesian,
$$
y_1, ..., y_n | \theta \sim N(\theta, \tau)
$$
where $\tau = 1 / \sigma^2$; $\tau$ is known as the precision
With this notation, the density for $y_i$ is then
$$
f(y_i | \theta, \tau) = \sqrt(\frac{\tau}{2 \pi}) \times exp\left( -\tau (y_i - \theta)^2 / 2 \right)
$$
Classical statistics (i.e. maximum likelihood) gives us an estimate of $\hat{\theta} = \bar{y}$
In a Bayesian perspective, we append maximum likelihood with prior information. A choice of priors for this Normal data model is another Normal distribution for $\theta$. The Normal distribution is conjugate to the Normal distribution.
$$
\theta \sim N(a,1/b)
$$
The posterior distribution we obtain from this Normal-Normal (after a lot of algebra) data model is another Normal distribution (so many Normals!)
$$
\theta | y \sim N(\frac{b}{b + n\tau} a + \frac{n \tau}{b + n \tau} \bar{y}, \frac{1}{b + n\tau})
$$
The posterior precision is $b + n\tau$ and mean is a weighted mean between $a$ and $\bar{y}$, $\frac{b}{b + n\tau} a + \frac{n \tau}{b + n \tau} \bar{y}$.
To your comment
I would like to find a real-life example of why such a construction would be not only elegant, but also useful.
The usefulness comes from the fact that you obtain a distribution of $\theta | y$ rather than just an estimate since $\theta$ is viewed as a random variable rather than a fixed (unknown) value. In addition, your estimate of $\theta$ in this model is a weighted average between the empirical mean and prior information.
That said, you can now use any Normal-data textbook example to illustrate this. I'll use the data set airquality within R. Consider the problem of estimating average wind speeds (MPH).
> ## New York Air Quality Measurements
>
> help("airquality")
>
> ## Estimating average wind speeds
>
> wind = airquality$Wind
> hist(wind, col = "gray", border = "white", xlab = "Wind Speed (MPH)")
>
> n = length(wind)
> ybar = mean(wind)
> ybar
[1] 9.957516 ## "frequentist" estimate
> tau = 1/sd(wind)
>
>
> ## but based on some research, you felt avgerage wind speeds were closer to 12 mph
> ## but probably no greater than 15,
> ## then a potential prior would be N(12, 2)
>
> a = 12
> b = 2
>
> ## Your posterior would be N((1/))
>
> postmean = 1/(1 + n*tau) * a + n*tau/(1 + n*tau) * ybar
> postsd = 1/(1 + n*tau)
>
> set.seed(123)
> posterior_sample = rnorm(n = 10000, mean = postmean, sd = postsd)
> hist(posterior_sample, col = "gray", border = "white", xlab = "Wind Speed (MPH)")
> abline(v = median(posterior_sample))
> abline(v = ybar, lty = 3)
>
> median(posterior_sample)
[1] 10.00324
> quantile(x = posterior_sample, probs = c(0.025, 0.975)) ## confidence intervals
2.5% 97.5%
9.958984 10.047404
In this analysis, the researcher (you) can say that given data + prior information, your estimate of average wind, using the 50th percentile, speeds should be 10.00324, greater than simply using the average from the data. You also obtain a full distribution, from which you can extract a 95% credible interval using the 2.5 and 97.5 quantiles.
Below I include two references, I highly recommend reading Casella's short paper. It's specifically aimed at empirical Bayes methods, but explains the general Bayesian methodology for Normal models.
References:
Casella, G. (1985). An Introduction to Empirical Bayes Data Analysis. The American Statistician, 39(2), 83-87.
Gelman, A. (2004). Bayesian data analysis (2nd ed., Texts in statistical science). Boca Raton, Fla.: Chapman & Hall/CRC.
|
Example of "real life" use of Bayesian inference on $\mu$ from a normal distribution?
Before delving directly into an example, I'd like to review some of the math for Normal-Normal Bayesian data models. Consider a random sample of n continuous values denoted by $y_1, ..., y_n$. Here th
|
41,188
|
Data Sets suitable for k-means
|
I would answer that the only really suitable data set would be 2. K-means pushes towards, kind of, spherical clusters of the same size. I say kind of because the divisions are more like voronoi cells. From here that in the first example you would end up with overlapped clusters. There are clearly three clusters, a big one and two small ones. The two small ones would be understood by k-means but it would eat up a section of the big one when trying to define them. This is a classic example called "mouse". You can look at how k-means handles this data in the Wikipedia k-means entry:
Another thing that should be noted in this image is that K-means can't understand noise, It always assigns all the points to a cluster or other. In fact it is quite sensitive to outliers as the algorithm itself is based on, well, means. So that leaves out example number 3. Example 2 has clusters of strange shapes but they are roughly the same size in the feature space as you can wrap them with circles of approximetely the same size. K-means clustering here would do a good job. Of course this is all quite subjective, unsupervised learning always is. Depending on the task and the obtained results, you can decide if you care a lot about the noise and if you can keep the discovered clusters even though they are not "perfect" and so on. Different clustering algorithms are based on different ideas so they will approach the problem trying to obtain different specific things. Meaning they will treat the data the only way they know how to and you have to decide if this answer is suitable for you. Look at this question which shows a cute diagram where you can see what different algorithms do to the same data sets.
|
Data Sets suitable for k-means
|
I would answer that the only really suitable data set would be 2. K-means pushes towards, kind of, spherical clusters of the same size. I say kind of because the divisions are more like voronoi cells.
|
Data Sets suitable for k-means
I would answer that the only really suitable data set would be 2. K-means pushes towards, kind of, spherical clusters of the same size. I say kind of because the divisions are more like voronoi cells. From here that in the first example you would end up with overlapped clusters. There are clearly three clusters, a big one and two small ones. The two small ones would be understood by k-means but it would eat up a section of the big one when trying to define them. This is a classic example called "mouse". You can look at how k-means handles this data in the Wikipedia k-means entry:
Another thing that should be noted in this image is that K-means can't understand noise, It always assigns all the points to a cluster or other. In fact it is quite sensitive to outliers as the algorithm itself is based on, well, means. So that leaves out example number 3. Example 2 has clusters of strange shapes but they are roughly the same size in the feature space as you can wrap them with circles of approximetely the same size. K-means clustering here would do a good job. Of course this is all quite subjective, unsupervised learning always is. Depending on the task and the obtained results, you can decide if you care a lot about the noise and if you can keep the discovered clusters even though they are not "perfect" and so on. Different clustering algorithms are based on different ideas so they will approach the problem trying to obtain different specific things. Meaning they will treat the data the only way they know how to and you have to decide if this answer is suitable for you. Look at this question which shows a cute diagram where you can see what different algorithms do to the same data sets.
|
Data Sets suitable for k-means
I would answer that the only really suitable data set would be 2. K-means pushes towards, kind of, spherical clusters of the same size. I say kind of because the divisions are more like voronoi cells.
|
41,189
|
Data Sets suitable for k-means
|
In complement to JEquihua's great answer, I would like to add 2 points.
Case 3 is a nice example of a case where it would be useful to have a clustering algorithm that doesn't give only the cluster assignment but also some way to assess the degree of certitude that a point belongs to a cluster (e.g. membership degree in fuzzy clustering), which would subsequently allows us to spot noisy/ambiguous points.
Kaufman, Leonard, and Peter J. Rousseeuw. "Finding groups in data: An introduction to cluster analysis." (2005), Chapter 4 explains this issue into more details. Excerpt:
In a partition, each object of the data set is assigned to one and
only one cluster. Therefore, partitioning methods (such as the
standard k-means algorithm) are sometimes said to produce a hard
clustering, because they make a clear-cut decision for each object. On
the other hand, a fuzzy clustering method allows for some ambiguity in
the data, which often occurs.
Another way to spot noisy/ambiguous points is to use some indices such as the silhouette, which provides a metric to assess how well each point lies within its cluster.
Regarding case 2, to rephrase slightly what JEquihua said, k-means would work not just because of the closeness of the points of each three groups, but also because groups have the same size. So it is somehow a lucky situation.
|
Data Sets suitable for k-means
|
In complement to JEquihua's great answer, I would like to add 2 points.
Case 3 is a nice example of a case where it would be useful to have a clustering algorithm that doesn't give only the cluster as
|
Data Sets suitable for k-means
In complement to JEquihua's great answer, I would like to add 2 points.
Case 3 is a nice example of a case where it would be useful to have a clustering algorithm that doesn't give only the cluster assignment but also some way to assess the degree of certitude that a point belongs to a cluster (e.g. membership degree in fuzzy clustering), which would subsequently allows us to spot noisy/ambiguous points.
Kaufman, Leonard, and Peter J. Rousseeuw. "Finding groups in data: An introduction to cluster analysis." (2005), Chapter 4 explains this issue into more details. Excerpt:
In a partition, each object of the data set is assigned to one and
only one cluster. Therefore, partitioning methods (such as the
standard k-means algorithm) are sometimes said to produce a hard
clustering, because they make a clear-cut decision for each object. On
the other hand, a fuzzy clustering method allows for some ambiguity in
the data, which often occurs.
Another way to spot noisy/ambiguous points is to use some indices such as the silhouette, which provides a metric to assess how well each point lies within its cluster.
Regarding case 2, to rephrase slightly what JEquihua said, k-means would work not just because of the closeness of the points of each three groups, but also because groups have the same size. So it is somehow a lucky situation.
|
Data Sets suitable for k-means
In complement to JEquihua's great answer, I would like to add 2 points.
Case 3 is a nice example of a case where it would be useful to have a clustering algorithm that doesn't give only the cluster as
|
41,190
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribution of MLE by Delta method
|
I will denote $\hat \theta$ the maximum likelihood estimator, while $\theta^{\left(m+1\right)}$ and $\theta^{\left(m\right)}$ are any two vectors. $\theta_0$ will denote the true value of the parameter vector. I am suppressing the appearance of the data.
The (untruncated) 2nd-order Taylor expansion of the log-likelihood viewed as a function of $\theta^{\left(m+1\right)}$, $\ell\left(\theta^{\left(m+1\right)}\right)$, centered at $\theta^{\left(m\right)}$ is (in a bit more compact notation than the one used by the OP)
$$\begin{align} \ell\left(\theta^{\left(m+1\right)}\right) =& \ell\left(\theta^{\left(m\right)}\right)+\frac{\partial\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)\\
+&\frac{1}{2}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)^{\prime}\frac{\partial^{2}\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta\partial\theta^{\prime}}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)\\
+&R_2\left(\theta^{\left(m+1\right)}\right) \\\end{align}$$
The derivative of the log-likelihood is (using the properties of matrix differentiation)
$$\frac{\partial}{\partial \theta^{\left(m+1\right)}}\ell\left(\theta^{\left(m+1\right)}\right) = \frac{\partial\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta}
+\frac{\partial^{2}\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta\partial\theta^{\prime}}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)
+\frac{\partial}{\partial \theta^{\left(m+1\right)}}R_2\left(\theta^{\left(m+1\right)}\right) $$
Assume that we require that
$$\frac{\partial}{\partial \theta^{\left(m+1\right)}}\ell\left(\theta^{\left(m+1\right)}\right)- \frac{\partial}{\partial \theta^{\left(m+1\right)}}R_2\left(\theta^{\left(m+1\right)}\right)=\mathbf 0$$
Then we obtain
$$\theta^{\left(m+1\right)}=\theta^{\left(m\right)}-\left[\mathbb{H}\left(\theta^{\left(m\right)}\right)\right]^{-1}\left[\mathbb{S}\left(\theta^{\left(m\right)}\right)\right]$$
This last formula shows how the value of the candidate $\theta$ vector is updated in each step of the algorithm. And we also see how the updating rule was obtained:$\theta^{\left(m+1\right)}$ must be chosen so as its total marginal effect on the log-likelihood equals its marginal effect on the Taylor remainder. In this way we "contain" how much the derivative of the log-likelihood strays away from the value zero.
If (and when) it so happens that $\theta^{\left(m\right)} = \hat \theta$ we will obtain
$$\theta^{\left(m+1\right)}=\hat \theta-\left[\mathbb{H}\left(\hat \theta\right)\right]^{-1}\left[\mathbb{S}\left(\hat \theta\right)\right]= \hat \theta-\left[\mathbb{H}\left(\hat \theta\right)\right]^{-1}\cdot \mathbf 0 = \hat \theta$$
since by construction $\hat \theta$ makes the gradient of the log-likelihood zero. This tells us that once we "hit" $\hat \theta$, we are not going anyplace else after that, which, in an intuitive way, validates our decision to essentially ignore the remainder, in order to calculate $\theta^{\left(m+1\right)}$. If the conditions for quadratic convergence of the algorithm are met, we have essentially a contraction mapping, and the MLE estimate is the (or a) fixed point of it. Note that if $\theta^{\left(m\right)} = \hat \theta$ then the remainder becomes also zero and then we have
$$\frac{\partial}{\partial \theta^{\left(m+1\right)}}\ell\left(\theta^{\left(m+1\right)}\right)- \frac{\partial}{\partial \theta^{\left(m+1\right)}}R_2\left(\theta^{\left(m+1\right)}\right)=\frac{\partial}{\partial \theta}\ell\left(\hat \theta\right)=\mathbf 0$$
So our method is internally consistent.
DISTRIBUTION OF $\hat \theta$
To obtain the asymptotic distribution of the MLE estimator we apply the Mean Value theorem according to which, if the log-likelihood is continuous and differentiable, then
$$\frac{\partial}{\partial \theta}\ell\left(\hat \theta\right) = \frac{\partial\ell\left(\theta_0\right)}{\partial\theta}
+\frac{\partial^{2}\ell\left(\bar \theta\right)}{\partial\theta\partial\theta^{\prime}}\left(\hat \theta-\theta_0\right) = \mathbf 0$$
where $\bar \theta$ is a mean value between $\hat \theta$ and $\theta_0$. Then
$$\left(\hat \theta-\theta_0\right) = -\left[\mathbb{H}\left(\bar \theta\right)\right]^{-1}\left[\mathbb{S}\left( \theta_0\right)\right]$$
$$\Rightarrow \sqrt n\left(\hat \theta-\theta_0\right) = -\left[\frac 1n\mathbb{H}\left(\bar \theta\right)\right]^{-1}\left[\frac 1{\sqrt n}\mathbb{S}\left( \theta_0\right)\right]$$
Under the appropriate assumptions, the MLE is a consistent estimator. Then so is $\bar \theta$, since it is sandwiched between the MLE and the true value. Under the assumption that our data is stationary, and one more technical condition (a local dominance condition that guarantees that the expected value of the supremum of the Hessian in a neighborhood of the true value is finite) we have
$$\frac 1n\mathbb{H}\left(\bar \theta\right) \rightarrow_p E\left[\mathbb{H}\left(\theta_0\right)\right]$$
Moreover, if interchange of integration and differentiation is valid (which usually will be), then
$$E\left[\mathbb{S}\left( \theta_0\right)\right]=\mathbf 0$$
This, together with the assumption that our data is i.i.d, permits us to use the Lindeberg-Levy CLT and conclude that
$$\left[\frac 1{\sqrt n}\mathbb{S}\left( \theta_0\right)\right] \rightarrow_d N(\mathbf 0, \Sigma),\qquad \Sigma = E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]$$
and then, by applying Slutzky's Theorem, that
$$\Rightarrow \sqrt n\left(\hat \theta-\theta_0\right) \rightarrow_d N\left(\mathbf 0, \operatorname{Avar}\right)$$
with
$$\operatorname{Avar} = \Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big)^{-1}\cdot \Big(E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]\Big)\cdot \Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big)^{-1}$$
But the information matrix equality states that
$$-\Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big) = \Big(E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]\Big)$$
and so
$$\operatorname{Avar} = -\Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big)^{-1} = \Big(E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]\Big)^{-1}$$
Then for large samples the distribution of $\hat \theta$ is approximated by
$$\hat \theta \sim _{approx} N\left(\theta_0, \frac 1n\operatorname {\widehat Avar}\right)$$
for a consistent estimator for $\operatorname {\widehat Avar}$ (the sample analogues of the expected values involved are such consistent estimators).
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribu
|
I will denote $\hat \theta$ the maximum likelihood estimator, while $\theta^{\left(m+1\right)}$ and $\theta^{\left(m\right)}$ are any two vectors. $\theta_0$ will denote the true value of the paramet
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribution of MLE by Delta method
I will denote $\hat \theta$ the maximum likelihood estimator, while $\theta^{\left(m+1\right)}$ and $\theta^{\left(m\right)}$ are any two vectors. $\theta_0$ will denote the true value of the parameter vector. I am suppressing the appearance of the data.
The (untruncated) 2nd-order Taylor expansion of the log-likelihood viewed as a function of $\theta^{\left(m+1\right)}$, $\ell\left(\theta^{\left(m+1\right)}\right)$, centered at $\theta^{\left(m\right)}$ is (in a bit more compact notation than the one used by the OP)
$$\begin{align} \ell\left(\theta^{\left(m+1\right)}\right) =& \ell\left(\theta^{\left(m\right)}\right)+\frac{\partial\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)\\
+&\frac{1}{2}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)^{\prime}\frac{\partial^{2}\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta\partial\theta^{\prime}}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)\\
+&R_2\left(\theta^{\left(m+1\right)}\right) \\\end{align}$$
The derivative of the log-likelihood is (using the properties of matrix differentiation)
$$\frac{\partial}{\partial \theta^{\left(m+1\right)}}\ell\left(\theta^{\left(m+1\right)}\right) = \frac{\partial\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta}
+\frac{\partial^{2}\ell\left(\theta^{\left(m\right)}\right)}{\partial\theta\partial\theta^{\prime}}\left(\theta^{\left(m+1\right)}-\theta^{\left(m\right)}\right)
+\frac{\partial}{\partial \theta^{\left(m+1\right)}}R_2\left(\theta^{\left(m+1\right)}\right) $$
Assume that we require that
$$\frac{\partial}{\partial \theta^{\left(m+1\right)}}\ell\left(\theta^{\left(m+1\right)}\right)- \frac{\partial}{\partial \theta^{\left(m+1\right)}}R_2\left(\theta^{\left(m+1\right)}\right)=\mathbf 0$$
Then we obtain
$$\theta^{\left(m+1\right)}=\theta^{\left(m\right)}-\left[\mathbb{H}\left(\theta^{\left(m\right)}\right)\right]^{-1}\left[\mathbb{S}\left(\theta^{\left(m\right)}\right)\right]$$
This last formula shows how the value of the candidate $\theta$ vector is updated in each step of the algorithm. And we also see how the updating rule was obtained:$\theta^{\left(m+1\right)}$ must be chosen so as its total marginal effect on the log-likelihood equals its marginal effect on the Taylor remainder. In this way we "contain" how much the derivative of the log-likelihood strays away from the value zero.
If (and when) it so happens that $\theta^{\left(m\right)} = \hat \theta$ we will obtain
$$\theta^{\left(m+1\right)}=\hat \theta-\left[\mathbb{H}\left(\hat \theta\right)\right]^{-1}\left[\mathbb{S}\left(\hat \theta\right)\right]= \hat \theta-\left[\mathbb{H}\left(\hat \theta\right)\right]^{-1}\cdot \mathbf 0 = \hat \theta$$
since by construction $\hat \theta$ makes the gradient of the log-likelihood zero. This tells us that once we "hit" $\hat \theta$, we are not going anyplace else after that, which, in an intuitive way, validates our decision to essentially ignore the remainder, in order to calculate $\theta^{\left(m+1\right)}$. If the conditions for quadratic convergence of the algorithm are met, we have essentially a contraction mapping, and the MLE estimate is the (or a) fixed point of it. Note that if $\theta^{\left(m\right)} = \hat \theta$ then the remainder becomes also zero and then we have
$$\frac{\partial}{\partial \theta^{\left(m+1\right)}}\ell\left(\theta^{\left(m+1\right)}\right)- \frac{\partial}{\partial \theta^{\left(m+1\right)}}R_2\left(\theta^{\left(m+1\right)}\right)=\frac{\partial}{\partial \theta}\ell\left(\hat \theta\right)=\mathbf 0$$
So our method is internally consistent.
DISTRIBUTION OF $\hat \theta$
To obtain the asymptotic distribution of the MLE estimator we apply the Mean Value theorem according to which, if the log-likelihood is continuous and differentiable, then
$$\frac{\partial}{\partial \theta}\ell\left(\hat \theta\right) = \frac{\partial\ell\left(\theta_0\right)}{\partial\theta}
+\frac{\partial^{2}\ell\left(\bar \theta\right)}{\partial\theta\partial\theta^{\prime}}\left(\hat \theta-\theta_0\right) = \mathbf 0$$
where $\bar \theta$ is a mean value between $\hat \theta$ and $\theta_0$. Then
$$\left(\hat \theta-\theta_0\right) = -\left[\mathbb{H}\left(\bar \theta\right)\right]^{-1}\left[\mathbb{S}\left( \theta_0\right)\right]$$
$$\Rightarrow \sqrt n\left(\hat \theta-\theta_0\right) = -\left[\frac 1n\mathbb{H}\left(\bar \theta\right)\right]^{-1}\left[\frac 1{\sqrt n}\mathbb{S}\left( \theta_0\right)\right]$$
Under the appropriate assumptions, the MLE is a consistent estimator. Then so is $\bar \theta$, since it is sandwiched between the MLE and the true value. Under the assumption that our data is stationary, and one more technical condition (a local dominance condition that guarantees that the expected value of the supremum of the Hessian in a neighborhood of the true value is finite) we have
$$\frac 1n\mathbb{H}\left(\bar \theta\right) \rightarrow_p E\left[\mathbb{H}\left(\theta_0\right)\right]$$
Moreover, if interchange of integration and differentiation is valid (which usually will be), then
$$E\left[\mathbb{S}\left( \theta_0\right)\right]=\mathbf 0$$
This, together with the assumption that our data is i.i.d, permits us to use the Lindeberg-Levy CLT and conclude that
$$\left[\frac 1{\sqrt n}\mathbb{S}\left( \theta_0\right)\right] \rightarrow_d N(\mathbf 0, \Sigma),\qquad \Sigma = E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]$$
and then, by applying Slutzky's Theorem, that
$$\Rightarrow \sqrt n\left(\hat \theta-\theta_0\right) \rightarrow_d N\left(\mathbf 0, \operatorname{Avar}\right)$$
with
$$\operatorname{Avar} = \Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big)^{-1}\cdot \Big(E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]\Big)\cdot \Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big)^{-1}$$
But the information matrix equality states that
$$-\Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big) = \Big(E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]\Big)$$
and so
$$\operatorname{Avar} = -\Big(E\left[\mathbb{H}\left(\theta_0\right)\right]\Big)^{-1} = \Big(E\left[\mathbb{S}\left( \theta_0\right)\mathbb{S}\left( \theta_0\right)'\right]\Big)^{-1}$$
Then for large samples the distribution of $\hat \theta$ is approximated by
$$\hat \theta \sim _{approx} N\left(\theta_0, \frac 1n\operatorname {\widehat Avar}\right)$$
for a consistent estimator for $\operatorname {\widehat Avar}$ (the sample analogues of the expected values involved are such consistent estimators).
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribu
I will denote $\hat \theta$ the maximum likelihood estimator, while $\theta^{\left(m+1\right)}$ and $\theta^{\left(m\right)}$ are any two vectors. $\theta_0$ will denote the true value of the paramet
|
41,191
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribution of MLE by Delta method
|
Under certain regularity conditions, the maximum likelihood estimates follow asymptotically a normal distribution with mean the true parameter values and covariance matrix the inverse of the Fisher information matrix also evaluated at the true parameter values.
The Delta method is typically used to derive standard errors for a nonlinear function of the MLEs - a better alternative is the Bootstrap.
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribu
|
Under certain regularity conditions, the maximum likelihood estimates follow asymptotically a normal distribution with mean the true parameter values and covariance matrix the inverse of the Fisher in
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribution of MLE by Delta method
Under certain regularity conditions, the maximum likelihood estimates follow asymptotically a normal distribution with mean the true parameter values and covariance matrix the inverse of the Fisher information matrix also evaluated at the true parameter values.
The Delta method is typically used to derive standard errors for a nonlinear function of the MLEs - a better alternative is the Bootstrap.
|
Taylor series expansion of maximum likelihood estimator, Newton-Raphson, Fisher scoring and distribu
Under certain regularity conditions, the maximum likelihood estimates follow asymptotically a normal distribution with mean the true parameter values and covariance matrix the inverse of the Fisher in
|
41,192
|
PCA and PLS: testing variables for significance
|
Inclusion/exclusion of variates (step 3):
I understand that you ask which of the original measurement channels to include into the modeling.
Is such a decision sensible for your data?
E.g. I work mainly with spectroscopic data, for which PLS is frequently and successfully used. Well measured spectra have a high correlation betweeen neighbour variates and the relevant information in spectroscopic data sets tends to be spread out over many variates. PLS is well suited for such data, but deciding on a variate-to-variate basis which variates to use for the model IMHO is usually not appropriate (decisions about inclusion/exclusion of spectral ranges based on spectroscopic knowledge about the application is IMHO a far better approach).
If for your data and application variable selection is a natural choice, is PLS the regularization technique you want?
You may want to read the sections about regularization (3.4 - 3.6) in the Elements of Statistical Learning where PLS as a regularization is compared to other regularization approaches. My point here is that in contrast to e.g. the Lasso, PLS is a regularization technique that does not tend to completely exclude variables from the model. I'd thus say that PLS is probably more suitable for data where this behaviour is sensible, but in that case variable selection is not a natural choice (e.g. spectroscopic data).
Does your data contain enough information for such a data-driven model optimization? Doing a t-test for each input variable is a massive multiple testing situation.
IMHO the main point of PLS (or other regularization techniques) is to avoid the need for such a variable selection.
Remark to Step 2:
If you build a linear regression model in PCA score space, that is usually called principal component regression (PCR) in chemometrics. It is not the same as a PLS model.
How to find out which variates are used by the PCA/PLS model?
There are several ways to approach this question. Obviously, variates where the PCA loadings or PLS weights are 0 do not enter the model. Whether it is sufficient to look at the loadings or whether you need to go a step further depends on your data: if the data set is not standardized you may want to calculate how much each variate "contributes" to the respective PCA/PLS score.
Literature where we did that with LDA (works just the same way): C. Beleites, K. Geiger, M. Kirsch, S. B. Sobottka, G. Schackert and R. Salzer: Raman spectroscopic grading of astrocytoma tissues: using soft reference information, Anal. Bioanal. Chem., 400 (2011), 2801 - 2816. The linked page has both links to the official web page and my manuscript.
You can also derive e.g. bootstrap distributions of the loadings (or the contributions) and have a look at them. For PCR and PLS coefficients that is straightforward, as the Y variable automatically "aligns" the coefficients. PCA and PLS scores need some more care, as e.g. flipping of the directions needs to be taken into account, and you may decide to treat models as equivalent where the scores which are then used for further modeling are just rotated or scaled versions of each other. Thus, you may want to align the scores first e.g. by Procrustes analysis. The paper linked above also discusses this (for LDA, but again, the ideas apply to the other bilinear models as well).
Last but not least, you need to be careful not to overinterprete the models, and you can have situations where important variates have coefficients frequently touching the zero mark in the bootstrap experiments if you have correlation between variates. However, ehat you can or cannot conclude will depend on your type of data, though.
|
PCA and PLS: testing variables for significance
|
Inclusion/exclusion of variates (step 3):
I understand that you ask which of the original measurement channels to include into the modeling.
Is such a decision sensible for your data?
E.g. I work mai
|
PCA and PLS: testing variables for significance
Inclusion/exclusion of variates (step 3):
I understand that you ask which of the original measurement channels to include into the modeling.
Is such a decision sensible for your data?
E.g. I work mainly with spectroscopic data, for which PLS is frequently and successfully used. Well measured spectra have a high correlation betweeen neighbour variates and the relevant information in spectroscopic data sets tends to be spread out over many variates. PLS is well suited for such data, but deciding on a variate-to-variate basis which variates to use for the model IMHO is usually not appropriate (decisions about inclusion/exclusion of spectral ranges based on spectroscopic knowledge about the application is IMHO a far better approach).
If for your data and application variable selection is a natural choice, is PLS the regularization technique you want?
You may want to read the sections about regularization (3.4 - 3.6) in the Elements of Statistical Learning where PLS as a regularization is compared to other regularization approaches. My point here is that in contrast to e.g. the Lasso, PLS is a regularization technique that does not tend to completely exclude variables from the model. I'd thus say that PLS is probably more suitable for data where this behaviour is sensible, but in that case variable selection is not a natural choice (e.g. spectroscopic data).
Does your data contain enough information for such a data-driven model optimization? Doing a t-test for each input variable is a massive multiple testing situation.
IMHO the main point of PLS (or other regularization techniques) is to avoid the need for such a variable selection.
Remark to Step 2:
If you build a linear regression model in PCA score space, that is usually called principal component regression (PCR) in chemometrics. It is not the same as a PLS model.
How to find out which variates are used by the PCA/PLS model?
There are several ways to approach this question. Obviously, variates where the PCA loadings or PLS weights are 0 do not enter the model. Whether it is sufficient to look at the loadings or whether you need to go a step further depends on your data: if the data set is not standardized you may want to calculate how much each variate "contributes" to the respective PCA/PLS score.
Literature where we did that with LDA (works just the same way): C. Beleites, K. Geiger, M. Kirsch, S. B. Sobottka, G. Schackert and R. Salzer: Raman spectroscopic grading of astrocytoma tissues: using soft reference information, Anal. Bioanal. Chem., 400 (2011), 2801 - 2816. The linked page has both links to the official web page and my manuscript.
You can also derive e.g. bootstrap distributions of the loadings (or the contributions) and have a look at them. For PCR and PLS coefficients that is straightforward, as the Y variable automatically "aligns" the coefficients. PCA and PLS scores need some more care, as e.g. flipping of the directions needs to be taken into account, and you may decide to treat models as equivalent where the scores which are then used for further modeling are just rotated or scaled versions of each other. Thus, you may want to align the scores first e.g. by Procrustes analysis. The paper linked above also discusses this (for LDA, but again, the ideas apply to the other bilinear models as well).
Last but not least, you need to be careful not to overinterprete the models, and you can have situations where important variates have coefficients frequently touching the zero mark in the bootstrap experiments if you have correlation between variates. However, ehat you can or cannot conclude will depend on your type of data, though.
|
PCA and PLS: testing variables for significance
Inclusion/exclusion of variates (step 3):
I understand that you ask which of the original measurement channels to include into the modeling.
Is such a decision sensible for your data?
E.g. I work mai
|
41,193
|
Inverse transformation sampling for mixture distribution of two normal distributions
|
The "two uniforms" are not absolutely necessary when generating from a mixture, but they make the simulation easy to understand. The mixture of normal distributions,
$$rf_a(x)+(1-r)f_b(x)$$
has a probability mass of $r$ associated with the first normal and $(1-r)$ with the second normal. This means that the distribution of $X\sim f$ can be decomposed as
$$\mathbb{P}(X\in\mathcal{A})=r\mathbb{P}(X_a\in\mathcal{A})+(1-r)\mathbb{P}(X_b\in\mathcal{A})$$
for any measurable set $\mathcal{A}$, where $X_a$ and $X_b$ are normal random variables with means $a$ and $b$ respectively. This can be reinterpreted as
$$X=\begin{cases} X_a &\text{with probability $r$}\\
X_b &\text{with probability $1-r$}\end{cases}$$
meaning that to generate from the mixture, one can follow the steps
Pick between components $a$ and $b$ by generating a uniform $U\sim\mathcal{U}(0,1)$ and, if $U<r$ take $\mu=a$ and else take $\mu=b$;
Generate $X$ as $X_a$ or $X_b$ depending on the first step result, by generating a uniform $V\sim\mathcal{U}(0,1)$ and take $X=\Phi^{-1}(V)+\mu$
This explains for the use of two uniforms.
|
Inverse transformation sampling for mixture distribution of two normal distributions
|
The "two uniforms" are not absolutely necessary when generating from a mixture, but they make the simulation easy to understand. The mixture of normal distributions,
$$rf_a(x)+(1-r)f_b(x)$$
has a prob
|
Inverse transformation sampling for mixture distribution of two normal distributions
The "two uniforms" are not absolutely necessary when generating from a mixture, but they make the simulation easy to understand. The mixture of normal distributions,
$$rf_a(x)+(1-r)f_b(x)$$
has a probability mass of $r$ associated with the first normal and $(1-r)$ with the second normal. This means that the distribution of $X\sim f$ can be decomposed as
$$\mathbb{P}(X\in\mathcal{A})=r\mathbb{P}(X_a\in\mathcal{A})+(1-r)\mathbb{P}(X_b\in\mathcal{A})$$
for any measurable set $\mathcal{A}$, where $X_a$ and $X_b$ are normal random variables with means $a$ and $b$ respectively. This can be reinterpreted as
$$X=\begin{cases} X_a &\text{with probability $r$}\\
X_b &\text{with probability $1-r$}\end{cases}$$
meaning that to generate from the mixture, one can follow the steps
Pick between components $a$ and $b$ by generating a uniform $U\sim\mathcal{U}(0,1)$ and, if $U<r$ take $\mu=a$ and else take $\mu=b$;
Generate $X$ as $X_a$ or $X_b$ depending on the first step result, by generating a uniform $V\sim\mathcal{U}(0,1)$ and take $X=\Phi^{-1}(V)+\mu$
This explains for the use of two uniforms.
|
Inverse transformation sampling for mixture distribution of two normal distributions
The "two uniforms" are not absolutely necessary when generating from a mixture, but they make the simulation easy to understand. The mixture of normal distributions,
$$rf_a(x)+(1-r)f_b(x)$$
has a prob
|
41,194
|
Inverse transformation sampling for mixture distribution of two normal distributions
|
Is this the problem from the STA511 class?:)
pnorm() won't give you the right result, because it's a CDF. What you are looking is an inverse of the CDF, so you have to use qnorm() to get it.
|
Inverse transformation sampling for mixture distribution of two normal distributions
|
Is this the problem from the STA511 class?:)
pnorm() won't give you the right result, because it's a CDF. What you are looking is an inverse of the CDF, so you have to use qnorm() to get it.
|
Inverse transformation sampling for mixture distribution of two normal distributions
Is this the problem from the STA511 class?:)
pnorm() won't give you the right result, because it's a CDF. What you are looking is an inverse of the CDF, so you have to use qnorm() to get it.
|
Inverse transformation sampling for mixture distribution of two normal distributions
Is this the problem from the STA511 class?:)
pnorm() won't give you the right result, because it's a CDF. What you are looking is an inverse of the CDF, so you have to use qnorm() to get it.
|
41,195
|
"Bayesglm", p-values and degrees of freedom?
|
I'm not sure how you got 5 degrees of freedom with seven independent variables for your glm-based model, but I'll assume that's just a typo somewhere or that I'm missing something minor.
Anyway, counting degrees of freedom with models that are constrained by a prior can be tricky, and there isn't necessarily a "correct" way to do it in many cases. Perhaps the authors of arm used -1 degrees of freedom as a way to keep people from blindly misinterpreting the results.
Although we can't easily calculate the number of degrees of freedom for most regularized models, we can at least put an upper bound on it: the number of degrees of freedom must be less than or equal to the degrees of freedom for the corresponding un-regularized model.
So (assuming the 5 degrees of freedom you reported above is correct), you can plug in 5 and be confident that the true P-value will be no larger than what your Chi-square test predicts. Thus, if it's significant with 5 degrees of freedom, the true value will also be significant.
If you want something more exact, you might want to look into using the lasso or ridge regression for regularization instead: statisticians have invested a lot of effort into counting degrees of freedom for these models, and have even developed some significance tests for them. Andrew Gelman talks about one recent advance on his blog here.
Edited to add: If you do stick with bayesglm but don't trust the null deviance estimates, you can find it yourself by running a model with no predictors except the intercept. The formula syntax for this would be a ~ 1.
|
"Bayesglm", p-values and degrees of freedom?
|
I'm not sure how you got 5 degrees of freedom with seven independent variables for your glm-based model, but I'll assume that's just a typo somewhere or that I'm missing something minor.
Anyway, count
|
"Bayesglm", p-values and degrees of freedom?
I'm not sure how you got 5 degrees of freedom with seven independent variables for your glm-based model, but I'll assume that's just a typo somewhere or that I'm missing something minor.
Anyway, counting degrees of freedom with models that are constrained by a prior can be tricky, and there isn't necessarily a "correct" way to do it in many cases. Perhaps the authors of arm used -1 degrees of freedom as a way to keep people from blindly misinterpreting the results.
Although we can't easily calculate the number of degrees of freedom for most regularized models, we can at least put an upper bound on it: the number of degrees of freedom must be less than or equal to the degrees of freedom for the corresponding un-regularized model.
So (assuming the 5 degrees of freedom you reported above is correct), you can plug in 5 and be confident that the true P-value will be no larger than what your Chi-square test predicts. Thus, if it's significant with 5 degrees of freedom, the true value will also be significant.
If you want something more exact, you might want to look into using the lasso or ridge regression for regularization instead: statisticians have invested a lot of effort into counting degrees of freedom for these models, and have even developed some significance tests for them. Andrew Gelman talks about one recent advance on his blog here.
Edited to add: If you do stick with bayesglm but don't trust the null deviance estimates, you can find it yourself by running a model with no predictors except the intercept. The formula syntax for this would be a ~ 1.
|
"Bayesglm", p-values and degrees of freedom?
I'm not sure how you got 5 degrees of freedom with seven independent variables for your glm-based model, but I'll assume that's just a typo somewhere or that I'm missing something minor.
Anyway, count
|
41,196
|
Measuring the smoothness of time series
|
I think that your problem is simply overfitting - you want to have a linearity measure that isn't inflated at very small N.
Here are two candidates:
Adjusted r-square.
In your case (a single regressor), that would be $R^2-\frac{1-R^2}{N-2}$
Cross-validated $R^2$: leave out one measurement at a time. Estimate the linear model without it. Then, calculate the squared difference between the actual held out measurement and its predicted value. Repeat for all time points, add up and you'll get predicted residual sums of squares (PRESS). Next calculate SST (the variance of the measurements * N). From here you can get a predicted $R^2$:
$predicted \ R^2=1-\frac{PRESS}{SST}$
I think that the former tends to be optimistic whether the latter tends to be pessimistic. Both naturally require at least 3 measurements.
|
Measuring the smoothness of time series
|
I think that your problem is simply overfitting - you want to have a linearity measure that isn't inflated at very small N.
Here are two candidates:
Adjusted r-square.
In your case (a single regresso
|
Measuring the smoothness of time series
I think that your problem is simply overfitting - you want to have a linearity measure that isn't inflated at very small N.
Here are two candidates:
Adjusted r-square.
In your case (a single regressor), that would be $R^2-\frac{1-R^2}{N-2}$
Cross-validated $R^2$: leave out one measurement at a time. Estimate the linear model without it. Then, calculate the squared difference between the actual held out measurement and its predicted value. Repeat for all time points, add up and you'll get predicted residual sums of squares (PRESS). Next calculate SST (the variance of the measurements * N). From here you can get a predicted $R^2$:
$predicted \ R^2=1-\frac{PRESS}{SST}$
I think that the former tends to be optimistic whether the latter tends to be pessimistic. Both naturally require at least 3 measurements.
|
Measuring the smoothness of time series
I think that your problem is simply overfitting - you want to have a linearity measure that isn't inflated at very small N.
Here are two candidates:
Adjusted r-square.
In your case (a single regresso
|
41,197
|
Measuring the smoothness of time series
|
Although it would be better if you had described your problem mathematically, from what I read I understand that
a) You have an estimator function that estimates the evolution of brain volume over time, say, $\hat V_t= f($data$)$ and
b) You want to measure the distance of this estimator function from the simple linear time trend $\bar V_t = a + bt$.
So it appears that you should search the various distance measures available, like for example the Hellinger distance (which although it has been devised to measure the distance between two distributions, it can be used more generally to measure the distance between any two sets of points that can be linked pairwise).
But what I don't understand is this: why are you not satisfied with the, supported by the data as you write, simple linear estimator? Are you essentially trying to achieve a better short-term prediction performance, while maintaining as much "long-term linearity" as possible? Is this the case?
|
Measuring the smoothness of time series
|
Although it would be better if you had described your problem mathematically, from what I read I understand that
a) You have an estimator function that estimates the evolution of brain volume over t
|
Measuring the smoothness of time series
Although it would be better if you had described your problem mathematically, from what I read I understand that
a) You have an estimator function that estimates the evolution of brain volume over time, say, $\hat V_t= f($data$)$ and
b) You want to measure the distance of this estimator function from the simple linear time trend $\bar V_t = a + bt$.
So it appears that you should search the various distance measures available, like for example the Hellinger distance (which although it has been devised to measure the distance between two distributions, it can be used more generally to measure the distance between any two sets of points that can be linked pairwise).
But what I don't understand is this: why are you not satisfied with the, supported by the data as you write, simple linear estimator? Are you essentially trying to achieve a better short-term prediction performance, while maintaining as much "long-term linearity" as possible? Is this the case?
|
Measuring the smoothness of time series
Although it would be better if you had described your problem mathematically, from what I read I understand that
a) You have an estimator function that estimates the evolution of brain volume over t
|
41,198
|
Measuring the smoothness of time series
|
Since you are computing $r^2$ for each patient $i$ and you want the following properties:
So patients with more data points will likely have a worse metric, if nothing is done.
Series with more measurements should be higher weighted
My concern is that those with 3 and those with 6 should be treated in a way that does not favor one way or another
Series with lesser points should also be included judiciously.
A simple heurisic comes to mind to measure linearity across the whole dataset: Let the number of data points for each patient be $n_i$ and the total number of patients be $K$. Since you are already computing $r_i^2$ for each patient $i$, how about getting a weighted average:
$$\frac{\sum_{i=1}^{K}n_i r_i^2}{\sum_{i=1}^{K}n_i}$$
This has the property that it will give more importance to series with higher number of observations.
Instead of $n_i$ as the coefficients in the numerator and denominator above, you can use any other function of $n_i$ to address your concerns I quoted above.
Another thought: To counter the issue of ireegularly sampled observations,do the following. Fit $n_i-1$ dimensional polynomials (link1,link2) to each of the time series observations you have (as an extension of the divided differences idea by @Glen_b). Given $n_i$ algorithm outputs $\{V(t_k)\}$ at $n_i$ times $\{t_k\}$, this is just
$$
V^{\textrm{poly. approx}}(t)=\sum_{k=1}^{n_i}V(t_k)\cdot\prod_{1\leq j\leq n,j\neq k}\frac{t-t_k}{t_k-t_j}.
$$
Then, evaluate each of these polynomials at regular time locations for each patient. And then fit the lines and proceed as above.
|
Measuring the smoothness of time series
|
Since you are computing $r^2$ for each patient $i$ and you want the following properties:
So patients with more data points will likely have a worse metric, if nothing is done.
Series with more mea
|
Measuring the smoothness of time series
Since you are computing $r^2$ for each patient $i$ and you want the following properties:
So patients with more data points will likely have a worse metric, if nothing is done.
Series with more measurements should be higher weighted
My concern is that those with 3 and those with 6 should be treated in a way that does not favor one way or another
Series with lesser points should also be included judiciously.
A simple heurisic comes to mind to measure linearity across the whole dataset: Let the number of data points for each patient be $n_i$ and the total number of patients be $K$. Since you are already computing $r_i^2$ for each patient $i$, how about getting a weighted average:
$$\frac{\sum_{i=1}^{K}n_i r_i^2}{\sum_{i=1}^{K}n_i}$$
This has the property that it will give more importance to series with higher number of observations.
Instead of $n_i$ as the coefficients in the numerator and denominator above, you can use any other function of $n_i$ to address your concerns I quoted above.
Another thought: To counter the issue of ireegularly sampled observations,do the following. Fit $n_i-1$ dimensional polynomials (link1,link2) to each of the time series observations you have (as an extension of the divided differences idea by @Glen_b). Given $n_i$ algorithm outputs $\{V(t_k)\}$ at $n_i$ times $\{t_k\}$, this is just
$$
V^{\textrm{poly. approx}}(t)=\sum_{k=1}^{n_i}V(t_k)\cdot\prod_{1\leq j\leq n,j\neq k}\frac{t-t_k}{t_k-t_j}.
$$
Then, evaluate each of these polynomials at regular time locations for each patient. And then fit the lines and proceed as above.
|
Measuring the smoothness of time series
Since you are computing $r^2$ for each patient $i$ and you want the following properties:
So patients with more data points will likely have a worse metric, if nothing is done.
Series with more mea
|
41,199
|
Measuring the smoothness of time series
|
I suggest two different approaches:
First of all, I have read that you suffered from sampling effects. One recommendation is using Wavelets/Fourier coefficients to obtain linearity. In many cases, there are solutions to avoid sampling effect with this tool.
Secondly, you should try kurtosis and skewness to see the variability of the signal and smoothness.
But, if you want to see trends on your signal, the best option is using Wavelet.
|
Measuring the smoothness of time series
|
I suggest two different approaches:
First of all, I have read that you suffered from sampling effects. One recommendation is using Wavelets/Fourier coefficients to obtain linearity. In many cases, th
|
Measuring the smoothness of time series
I suggest two different approaches:
First of all, I have read that you suffered from sampling effects. One recommendation is using Wavelets/Fourier coefficients to obtain linearity. In many cases, there are solutions to avoid sampling effect with this tool.
Secondly, you should try kurtosis and skewness to see the variability of the signal and smoothness.
But, if you want to see trends on your signal, the best option is using Wavelet.
|
Measuring the smoothness of time series
I suggest two different approaches:
First of all, I have read that you suffered from sampling effects. One recommendation is using Wavelets/Fourier coefficients to obtain linearity. In many cases, th
|
41,200
|
Measuring the smoothness of time series
|
How about doing your linear regression, then take the residual by subtracting your regression line from the data, and look at its standard deviation (SD) or median absolute deviation (MAD)? (The SD part may be basically equivalent to the R^2, I'm not sure of the math.)
The problem is the "one to five or six" part. That's not much data there, but of course the data you have is what you have. (If you had a lot more data, you could consider decomposition methods on the residual to look at the power in higher and lower frequencies.)
I thought of things like the KL-divergence or something like Alecos mentioned, but they're for differences in distributions not differences in time series, so I'm not sure they're applicable.
|
Measuring the smoothness of time series
|
How about doing your linear regression, then take the residual by subtracting your regression line from the data, and look at its standard deviation (SD) or median absolute deviation (MAD)? (The SD pa
|
Measuring the smoothness of time series
How about doing your linear regression, then take the residual by subtracting your regression line from the data, and look at its standard deviation (SD) or median absolute deviation (MAD)? (The SD part may be basically equivalent to the R^2, I'm not sure of the math.)
The problem is the "one to five or six" part. That's not much data there, but of course the data you have is what you have. (If you had a lot more data, you could consider decomposition methods on the residual to look at the power in higher and lower frequencies.)
I thought of things like the KL-divergence or something like Alecos mentioned, but they're for differences in distributions not differences in time series, so I'm not sure they're applicable.
|
Measuring the smoothness of time series
How about doing your linear regression, then take the residual by subtracting your regression line from the data, and look at its standard deviation (SD) or median absolute deviation (MAD)? (The SD pa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.