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
12,701
Does it make sense to use a date variable in a regression?
Building on earlier comments on Stack Overflow: Yes, it makes sense. Here I address the general question and am happy to let R experts fill in the crucial details. In my view, as this is now on Cross-Validated, we should not focus too narrowly on the poster's favourite software, important though that is for like-minded people. Dates in any software if not numeric can be converted to numeric variables, expressed in years, days, milliseconds or whatever since some time origin. The coefficient associated with each date has denominator units which are whatever the units of the date are. The numerator units depend on those of the response or dependent variable. (Non-identity link functions complicate this, naturally.) However, it usually makes most sense when dates are shifted to an origin that makes sense for the study. Usually, but not necessarily, the origin should be a date within the time period of study or very close to it. Perhaps the simplest case is linear regression on a date variable in years. Here a regression of some response on date expressed as dates like 2000 or 2010 implies an intercept which is the value of response in year 0. Setting aside the calendrical detail that there was no such year, such an intercept is often absurdly large positive or negative, which is logical but a distraction in interpretation and presentation (even to well-informed audiences). In a real example from working with undergraduate students, the number of cyclones per year in a certain area was increasing slightly with the date and a linear trend looked a reasonable first stab. The intercept from regression was a large negative number, which caused much puzzlement until it was realised that this was, as always, an extrapolation to year 0. Shifting the origin to 2000 produced better results. (Actually, a Poisson regression ensuring positive predictions was even better, but that's a different story.) Regressing on date - 2000 or whatever is thus a good idea. The substantive details of a study often indicate a good base date, i.e. a new origin. The use of other models and/or other predictors doesn't undermine this principle; it just obscures it. It is also a good idea to graph results using whatever dates are easiest to think about. These may be the original dates; that's not a contradiction, as it is just the same principle of using whatever is easiest to think about. A little thought shows that the principle is much more general. We are often better off with (age - 20) or some such, to avoid logical but awkward predictions for age 0. EDIT 21 March 2019 (original 29 Jul 2013): These arguments have been discussed in a Stata context in Cox, N.J. 2015. Species of origin. Stata Journal 15: 574-587 see here EDIT 2 also 4 Dec 2015 @whuber in comments raises also the important issue of numerical precision. Often the time units are fine and the resulting dates or date-times can be very large, raising important issues for sums of squares, and so on and so forth. He raises an example from R. To that we can add (e.g.) that date-times in Stata are milliseconds since the start of 1960. This problem is not at all specific to dates, as it can arise generally with numbers that are very big or very small, but it is worth flagging too.
Does it make sense to use a date variable in a regression?
Building on earlier comments on Stack Overflow: Yes, it makes sense. Here I address the general question and am happy to let R experts fill in the crucial details. In my view, as this is now on Cross
Does it make sense to use a date variable in a regression? Building on earlier comments on Stack Overflow: Yes, it makes sense. Here I address the general question and am happy to let R experts fill in the crucial details. In my view, as this is now on Cross-Validated, we should not focus too narrowly on the poster's favourite software, important though that is for like-minded people. Dates in any software if not numeric can be converted to numeric variables, expressed in years, days, milliseconds or whatever since some time origin. The coefficient associated with each date has denominator units which are whatever the units of the date are. The numerator units depend on those of the response or dependent variable. (Non-identity link functions complicate this, naturally.) However, it usually makes most sense when dates are shifted to an origin that makes sense for the study. Usually, but not necessarily, the origin should be a date within the time period of study or very close to it. Perhaps the simplest case is linear regression on a date variable in years. Here a regression of some response on date expressed as dates like 2000 or 2010 implies an intercept which is the value of response in year 0. Setting aside the calendrical detail that there was no such year, such an intercept is often absurdly large positive or negative, which is logical but a distraction in interpretation and presentation (even to well-informed audiences). In a real example from working with undergraduate students, the number of cyclones per year in a certain area was increasing slightly with the date and a linear trend looked a reasonable first stab. The intercept from regression was a large negative number, which caused much puzzlement until it was realised that this was, as always, an extrapolation to year 0. Shifting the origin to 2000 produced better results. (Actually, a Poisson regression ensuring positive predictions was even better, but that's a different story.) Regressing on date - 2000 or whatever is thus a good idea. The substantive details of a study often indicate a good base date, i.e. a new origin. The use of other models and/or other predictors doesn't undermine this principle; it just obscures it. It is also a good idea to graph results using whatever dates are easiest to think about. These may be the original dates; that's not a contradiction, as it is just the same principle of using whatever is easiest to think about. A little thought shows that the principle is much more general. We are often better off with (age - 20) or some such, to avoid logical but awkward predictions for age 0. EDIT 21 March 2019 (original 29 Jul 2013): These arguments have been discussed in a Stata context in Cox, N.J. 2015. Species of origin. Stata Journal 15: 574-587 see here EDIT 2 also 4 Dec 2015 @whuber in comments raises also the important issue of numerical precision. Often the time units are fine and the resulting dates or date-times can be very large, raising important issues for sums of squares, and so on and so forth. He raises an example from R. To that we can add (e.g.) that date-times in Stata are milliseconds since the start of 1960. This problem is not at all specific to dates, as it can arise generally with numbers that are very big or very small, but it is worth flagging too.
Does it make sense to use a date variable in a regression? Building on earlier comments on Stack Overflow: Yes, it makes sense. Here I address the general question and am happy to let R experts fill in the crucial details. In my view, as this is now on Cross
12,702
Does it make sense to use a date variable in a regression?
As been said above, with suitable scaling, dates are great regressors. Time effects are less likely to be linear than even the typical covariates, so I almost always use regression splines in time. Some complex time trends require many knots (e.g., 7 or more) to fit. Restricted cubic splines (natural splines) provide safer linear extrapolation beyond the end of the observed times, although extrapolation is seldom completely safe.
Does it make sense to use a date variable in a regression?
As been said above, with suitable scaling, dates are great regressors. Time effects are less likely to be linear than even the typical covariates, so I almost always use regression splines in time.
Does it make sense to use a date variable in a regression? As been said above, with suitable scaling, dates are great regressors. Time effects are less likely to be linear than even the typical covariates, so I almost always use regression splines in time. Some complex time trends require many knots (e.g., 7 or more) to fit. Restricted cubic splines (natural splines) provide safer linear extrapolation beyond the end of the observed times, although extrapolation is seldom completely safe.
Does it make sense to use a date variable in a regression? As been said above, with suitable scaling, dates are great regressors. Time effects are less likely to be linear than even the typical covariates, so I almost always use regression splines in time.
12,703
Sources for learning (not just running) statistics/math through R
I think R (or perhaps a comparable programming language) can be extremely helpful in learning about statistics. Of course, this will require that students learn some programming as well, which may be a bridge too far, so depending on your audience, you may need to do all the programming yourself and just show students the simulations. An example of this can be found in my answer here, regarding teaching the idea of the sampling distribution (warning the code is ugly and comically inefficient). On the other hand, if you want to try having your students learn some programming along the way as well, there are some introductory statistics books based to varying degrees on that model: Vasishth, The Foundations of Statistics: A simulation-based approach Jones, Maillardet, & Robinson, Introduction to Scientific Programming & Simulation using R Torgo, Data Mining with R: Learning with case studies
Sources for learning (not just running) statistics/math through R
I think R (or perhaps a comparable programming language) can be extremely helpful in learning about statistics. Of course, this will require that students learn some programming as well, which may be
Sources for learning (not just running) statistics/math through R I think R (or perhaps a comparable programming language) can be extremely helpful in learning about statistics. Of course, this will require that students learn some programming as well, which may be a bridge too far, so depending on your audience, you may need to do all the programming yourself and just show students the simulations. An example of this can be found in my answer here, regarding teaching the idea of the sampling distribution (warning the code is ugly and comically inefficient). On the other hand, if you want to try having your students learn some programming along the way as well, there are some introductory statistics books based to varying degrees on that model: Vasishth, The Foundations of Statistics: A simulation-based approach Jones, Maillardet, & Robinson, Introduction to Scientific Programming & Simulation using R Torgo, Data Mining with R: Learning with case studies
Sources for learning (not just running) statistics/math through R I think R (or perhaps a comparable programming language) can be extremely helpful in learning about statistics. Of course, this will require that students learn some programming as well, which may be
12,704
Sources for learning (not just running) statistics/math through R
There is "Introduction to Probability and Statistics Using R" by G. Jay Kerns available at http://ipsur.org/ and as the R package IPSUR. From the title alone, it seems like the type of text you are looking for.
Sources for learning (not just running) statistics/math through R
There is "Introduction to Probability and Statistics Using R" by G. Jay Kerns available at http://ipsur.org/ and as the R package IPSUR. From the title alone, it seems like the type of text you are lo
Sources for learning (not just running) statistics/math through R There is "Introduction to Probability and Statistics Using R" by G. Jay Kerns available at http://ipsur.org/ and as the R package IPSUR. From the title alone, it seems like the type of text you are looking for.
Sources for learning (not just running) statistics/math through R There is "Introduction to Probability and Statistics Using R" by G. Jay Kerns available at http://ipsur.org/ and as the R package IPSUR. From the title alone, it seems like the type of text you are lo
12,705
Sources for learning (not just running) statistics/math through R
I think the benchmark in the field here is "An Introduction to Statistical Learning - with applications in R" http://www-bcf.usc.edu/~gareth/ISL/
Sources for learning (not just running) statistics/math through R
I think the benchmark in the field here is "An Introduction to Statistical Learning - with applications in R" http://www-bcf.usc.edu/~gareth/ISL/
Sources for learning (not just running) statistics/math through R I think the benchmark in the field here is "An Introduction to Statistical Learning - with applications in R" http://www-bcf.usc.edu/~gareth/ISL/
Sources for learning (not just running) statistics/math through R I think the benchmark in the field here is "An Introduction to Statistical Learning - with applications in R" http://www-bcf.usc.edu/~gareth/ISL/
12,706
Sources for learning (not just running) statistics/math through R
I recommend the R package swirl, which sounds exactly like what you're looking for- learning R and statistics, not only using R, but in R itself.
Sources for learning (not just running) statistics/math through R
I recommend the R package swirl, which sounds exactly like what you're looking for- learning R and statistics, not only using R, but in R itself.
Sources for learning (not just running) statistics/math through R I recommend the R package swirl, which sounds exactly like what you're looking for- learning R and statistics, not only using R, but in R itself.
Sources for learning (not just running) statistics/math through R I recommend the R package swirl, which sounds exactly like what you're looking for- learning R and statistics, not only using R, but in R itself.
12,707
Sources for learning (not just running) statistics/math through R
I really like the book "introductory statistics with R" a very practical book. It walks you through the basic statistics and implementations in R.
Sources for learning (not just running) statistics/math through R
I really like the book "introductory statistics with R" a very practical book. It walks you through the basic statistics and implementations in R.
Sources for learning (not just running) statistics/math through R I really like the book "introductory statistics with R" a very practical book. It walks you through the basic statistics and implementations in R.
Sources for learning (not just running) statistics/math through R I really like the book "introductory statistics with R" a very practical book. It walks you through the basic statistics and implementations in R.
12,708
Bootstrap-based confidence interval
The question is related to the fundamental construction of confidence intervals, and when it comes to bootstrapping, the answer depends upon which bootstrapping method that is used. Consider the following setup: $\hat{\theta}$ is an estimator of a real valued parameter $\theta$ with (an estimated) standard deviation $\text{se}$, then a standard 95% confidence interval based on a normal $N(\theta, \text{se}^2)$ approximation is $$\hat{\theta} \pm 1.96 \text{se}.$$ This confidence interval is derived as the set of $\theta$'s that fulfill $$z_{1} \leq \hat{\theta} - \theta \leq z_2$$ where $z_1 = -1.96\text{se}$ is the 2.5% quantile and $z_2 = 1.96\text{se}$ is the 97.5% quantile for the $N(0, \text{se}^2)$-distribution. The interesting observation is that when rearranging the inequalities we get the confidence interval expressed as $$\{\theta \mid \hat{\theta} - z_2 \leq \theta \leq \hat{\theta} - z_1 \} = [\hat{\theta} - z_2, \hat{\theta} - z_1].$$ That is, it is the lower 2.5% quantile that determines the right end point and the upper 97.5% quantile that determines the left end point. If the sampling distribution of $\hat{\theta}$ is right skewed compared to the normal approximation, what is then the appropriate action? If right-skewed means that the 97.5% quantile for the sampling distribution is $z_2 > 1.96\text{se}$, the appropriate action is to move the left end point further to the left. That is, if we stick to the standard construction above. A standard usage of the bootstrap is to estimate the sampling quantiles and then use them instead of $\pm 1.96 \text{se}$ in the construction above. However, another standard construction used in bootstrapping is the percentile interval, which is $$[\hat{\theta} + z_1, \hat{\theta} + z_2].$$ in the terminology above. It is simply the interval from the 2.5% quantile to the 97.5% quantile for the sampling distribution of $\hat{\theta}.$ A right-skewed sampling distribution of $\hat{\theta}$ implies a right-skewed confidence interval. For the reasons mentioned above, this appears to me to be a counter-intuitive behavior of percentile intervals. But they have other virtues, and are, for instance, invariant under monotone parameter transformations. The BCa (bias-corrected and accelerated) bootstrap intervals as introduced by Efron, see e.g. the paper Bootstrap Confidence Intervals, improve upon the properties of percentile intervals. I can only guess (and google) the quote the OP post, but maybe BCa is the appropriate context. Citing Diciccio and Efron from the paper mentioned, page 193, The following argument motivates the BCa definition (2.3), as well as the parameters $a$ and $z_0$. Suppose that there exists a monotone increasing transformation $\phi = m(\theta)$ such that $\hat{\phi} = m(\hat{\theta})$ is normally distributed for every choice of $\theta$, but possibly with a bias and a nonconstant variance, $$\hat{\phi} \sim N(\phi - z_0 \sigma_{\phi}, \sigma_{\phi}^2), \quad \sigma_{\phi} = 1 + a \phi.$$ Then (2.3) gives exactly accurate and correct confidence limits for $\theta$ having observed $\hat{\theta}$. where (2.3) is the definition of the BCa intervals. The quote posted by the OP may refer to the fact that BCa can shift confidence intervals with a right-skewed sampling distribution further to the right. It is difficult to tell if this is the "correct action" in a general sense, but according to Diciccio and Efron it is correct in the setup above in the sense of producing confidence intervals with the correct coverage. The existence of the monotone transformation $m$ is a little tricky, though.
Bootstrap-based confidence interval
The question is related to the fundamental construction of confidence intervals, and when it comes to bootstrapping, the answer depends upon which bootstrapping method that is used. Consider the follo
Bootstrap-based confidence interval The question is related to the fundamental construction of confidence intervals, and when it comes to bootstrapping, the answer depends upon which bootstrapping method that is used. Consider the following setup: $\hat{\theta}$ is an estimator of a real valued parameter $\theta$ with (an estimated) standard deviation $\text{se}$, then a standard 95% confidence interval based on a normal $N(\theta, \text{se}^2)$ approximation is $$\hat{\theta} \pm 1.96 \text{se}.$$ This confidence interval is derived as the set of $\theta$'s that fulfill $$z_{1} \leq \hat{\theta} - \theta \leq z_2$$ where $z_1 = -1.96\text{se}$ is the 2.5% quantile and $z_2 = 1.96\text{se}$ is the 97.5% quantile for the $N(0, \text{se}^2)$-distribution. The interesting observation is that when rearranging the inequalities we get the confidence interval expressed as $$\{\theta \mid \hat{\theta} - z_2 \leq \theta \leq \hat{\theta} - z_1 \} = [\hat{\theta} - z_2, \hat{\theta} - z_1].$$ That is, it is the lower 2.5% quantile that determines the right end point and the upper 97.5% quantile that determines the left end point. If the sampling distribution of $\hat{\theta}$ is right skewed compared to the normal approximation, what is then the appropriate action? If right-skewed means that the 97.5% quantile for the sampling distribution is $z_2 > 1.96\text{se}$, the appropriate action is to move the left end point further to the left. That is, if we stick to the standard construction above. A standard usage of the bootstrap is to estimate the sampling quantiles and then use them instead of $\pm 1.96 \text{se}$ in the construction above. However, another standard construction used in bootstrapping is the percentile interval, which is $$[\hat{\theta} + z_1, \hat{\theta} + z_2].$$ in the terminology above. It is simply the interval from the 2.5% quantile to the 97.5% quantile for the sampling distribution of $\hat{\theta}.$ A right-skewed sampling distribution of $\hat{\theta}$ implies a right-skewed confidence interval. For the reasons mentioned above, this appears to me to be a counter-intuitive behavior of percentile intervals. But they have other virtues, and are, for instance, invariant under monotone parameter transformations. The BCa (bias-corrected and accelerated) bootstrap intervals as introduced by Efron, see e.g. the paper Bootstrap Confidence Intervals, improve upon the properties of percentile intervals. I can only guess (and google) the quote the OP post, but maybe BCa is the appropriate context. Citing Diciccio and Efron from the paper mentioned, page 193, The following argument motivates the BCa definition (2.3), as well as the parameters $a$ and $z_0$. Suppose that there exists a monotone increasing transformation $\phi = m(\theta)$ such that $\hat{\phi} = m(\hat{\theta})$ is normally distributed for every choice of $\theta$, but possibly with a bias and a nonconstant variance, $$\hat{\phi} \sim N(\phi - z_0 \sigma_{\phi}, \sigma_{\phi}^2), \quad \sigma_{\phi} = 1 + a \phi.$$ Then (2.3) gives exactly accurate and correct confidence limits for $\theta$ having observed $\hat{\theta}$. where (2.3) is the definition of the BCa intervals. The quote posted by the OP may refer to the fact that BCa can shift confidence intervals with a right-skewed sampling distribution further to the right. It is difficult to tell if this is the "correct action" in a general sense, but according to Diciccio and Efron it is correct in the setup above in the sense of producing confidence intervals with the correct coverage. The existence of the monotone transformation $m$ is a little tricky, though.
Bootstrap-based confidence interval The question is related to the fundamental construction of confidence intervals, and when it comes to bootstrapping, the answer depends upon which bootstrapping method that is used. Consider the follo
12,709
Balancing Reconstruction vs KL Loss Variational Autoencoder
Little late to the party here and you're probably way past this, but it's well documented you have to "warm up" the KL loss term by starting at zero and training a bit on just reconstruction loss before introducing the KL loss or results will not be good. It's unclear from your post if you did this, but it's a classic example of how touchy training these can be -- sometimes I wonder how appropriate they are on cross validated since it's very strongly trial and error, along with a bit of pixie dust and rainbows.
Balancing Reconstruction vs KL Loss Variational Autoencoder
Little late to the party here and you're probably way past this, but it's well documented you have to "warm up" the KL loss term by starting at zero and training a bit on just reconstruction loss befo
Balancing Reconstruction vs KL Loss Variational Autoencoder Little late to the party here and you're probably way past this, but it's well documented you have to "warm up" the KL loss term by starting at zero and training a bit on just reconstruction loss before introducing the KL loss or results will not be good. It's unclear from your post if you did this, but it's a classic example of how touchy training these can be -- sometimes I wonder how appropriate they are on cross validated since it's very strongly trial and error, along with a bit of pixie dust and rainbows.
Balancing Reconstruction vs KL Loss Variational Autoencoder Little late to the party here and you're probably way past this, but it's well documented you have to "warm up" the KL loss term by starting at zero and training a bit on just reconstruction loss befo
12,710
Balancing Reconstruction vs KL Loss Variational Autoencoder
However, when I decrease the weight of the KLL loss by 0.001, I get reasonable samples: (...) The problem is that the learned latent space is not smooth. Looks like overfitting. Remember that KL loss on the latent space sort of corresponds to regularization. Are there any suggestions on how to balance these two loss terms or any other possible things to try so that my autoencoder learns a smooth, interpolatable latent space, while producing reasonable reconstructions? I recently bumped into this paper: $\beta$-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework (it actually uses your dataset in one example). From the paper ($\beta$ is the parameter you changed): We introduce an adjustable hyperparameter $\beta$ that balances latent channel capacity and independence constraints with reconstruction accuracy (...) $\beta$-VAE is stable to train, makes few assumptions about the data and relies on tuning a single hyperparameter $\beta$, which can be directly optimised through a hyperparameter search using weakly labelled data or through heuristic visual inspection for purely unsupervised data.
Balancing Reconstruction vs KL Loss Variational Autoencoder
However, when I decrease the weight of the KLL loss by 0.001, I get reasonable samples: (...) The problem is that the learned latent space is not smooth. Looks like overfitting. Remember that KL
Balancing Reconstruction vs KL Loss Variational Autoencoder However, when I decrease the weight of the KLL loss by 0.001, I get reasonable samples: (...) The problem is that the learned latent space is not smooth. Looks like overfitting. Remember that KL loss on the latent space sort of corresponds to regularization. Are there any suggestions on how to balance these two loss terms or any other possible things to try so that my autoencoder learns a smooth, interpolatable latent space, while producing reasonable reconstructions? I recently bumped into this paper: $\beta$-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework (it actually uses your dataset in one example). From the paper ($\beta$ is the parameter you changed): We introduce an adjustable hyperparameter $\beta$ that balances latent channel capacity and independence constraints with reconstruction accuracy (...) $\beta$-VAE is stable to train, makes few assumptions about the data and relies on tuning a single hyperparameter $\beta$, which can be directly optimised through a hyperparameter search using weakly labelled data or through heuristic visual inspection for purely unsupervised data.
Balancing Reconstruction vs KL Loss Variational Autoencoder However, when I decrease the weight of the KLL loss by 0.001, I get reasonable samples: (...) The problem is that the learned latent space is not smooth. Looks like overfitting. Remember that KL
12,711
How to sample from Cantor distribution?
Easy: sample from a Uniform$(0,1)$ distribution and recode from binary to ternary, interpreting each "1" as a "2". (This is the inverse probability transform approach: it does indeed invert the CDF!) Here is an R implementation, written in a way that ought to port readily to almost any computing environment. binary.to.ternary <- function(x) { y <- 0 x <- round(2^52 * x) for (i in 1:52) { y <- y + 2*(x %% 2) y <- y/3 x <- floor(x/2) } y } n <- 1000 x <- runif(n) y <- binary.to.ternary(x) plot(ecdf(y), pch=".")
How to sample from Cantor distribution?
Easy: sample from a Uniform$(0,1)$ distribution and recode from binary to ternary, interpreting each "1" as a "2". (This is the inverse probability transform approach: it does indeed invert the CDF!)
How to sample from Cantor distribution? Easy: sample from a Uniform$(0,1)$ distribution and recode from binary to ternary, interpreting each "1" as a "2". (This is the inverse probability transform approach: it does indeed invert the CDF!) Here is an R implementation, written in a way that ought to port readily to almost any computing environment. binary.to.ternary <- function(x) { y <- 0 x <- round(2^52 * x) for (i in 1:52) { y <- y + 2*(x %% 2) y <- y/3 x <- floor(x/2) } y } n <- 1000 x <- runif(n) y <- binary.to.ternary(x) plot(ecdf(y), pch=".")
How to sample from Cantor distribution? Easy: sample from a Uniform$(0,1)$ distribution and recode from binary to ternary, interpreting each "1" as a "2". (This is the inverse probability transform approach: it does indeed invert the CDF!)
12,712
Why exactly is the observed Fisher information used?
You've got four quanties here: the true parameter $\theta_0$, a consistent estimate $\hat \theta$, the expected information $I(\theta)$ at $\theta$ and the observed information $J(\theta)$ at $\theta$. These quantities are only equivalent asymptotically, but that is typically how they are used. The observed information $$ J (\theta_0) = \frac{1}{N} \sum_{i=1}^N \frac{\partial^2}{\partial \theta_0^2} \ln f( y_i|\theta_0) $$ converges in probability to the expected information $$ I(\theta_0) = E_{\theta_0} \left[ \frac{\partial^2}{\partial \theta_0^2} \ln f( y| \theta_0) \right] $$ when $Y$ is an iid sample from $f(\theta_0)$. Here $ E_{\theta_0} (x)$ indicates the expectation w/r/t the distribution indexed by $\theta_0$: $\int x f(x | \theta_0) dx$. This convergence holds because of the law of large numbers, so the assumption that $Y \sim f(\theta_0)$ is crucial here. When you've got an estimate $\hat \theta$ that converges in probability to the true parameter $\theta_0$ (ie, is consistent) then you can substitute it for anywhere you see a $\theta_0$ above, essentially due to the continuous mapping theorem$^*$, and all of the convergences continue to hold. $^*$ Actually, it appears to be a bit subtle. Remark As you surmised, observed information is typically easier to work with because differentiation is easier than integration, and you might have already evaluated it in the course of some numeric optimization. In some circumstances (the Normal distribution) they will be the same. The article "Assessing the Accuracy of the Maximum Likelihood Estimator: Observed Versus Expected Fisher Information" by Efron and Hinkley (1978) makes an argument in favor of the observed information for finite samples.
Why exactly is the observed Fisher information used?
You've got four quanties here: the true parameter $\theta_0$, a consistent estimate $\hat \theta$, the expected information $I(\theta)$ at $\theta$ and the observed information $J(\theta)$ at $\theta$
Why exactly is the observed Fisher information used? You've got four quanties here: the true parameter $\theta_0$, a consistent estimate $\hat \theta$, the expected information $I(\theta)$ at $\theta$ and the observed information $J(\theta)$ at $\theta$. These quantities are only equivalent asymptotically, but that is typically how they are used. The observed information $$ J (\theta_0) = \frac{1}{N} \sum_{i=1}^N \frac{\partial^2}{\partial \theta_0^2} \ln f( y_i|\theta_0) $$ converges in probability to the expected information $$ I(\theta_0) = E_{\theta_0} \left[ \frac{\partial^2}{\partial \theta_0^2} \ln f( y| \theta_0) \right] $$ when $Y$ is an iid sample from $f(\theta_0)$. Here $ E_{\theta_0} (x)$ indicates the expectation w/r/t the distribution indexed by $\theta_0$: $\int x f(x | \theta_0) dx$. This convergence holds because of the law of large numbers, so the assumption that $Y \sim f(\theta_0)$ is crucial here. When you've got an estimate $\hat \theta$ that converges in probability to the true parameter $\theta_0$ (ie, is consistent) then you can substitute it for anywhere you see a $\theta_0$ above, essentially due to the continuous mapping theorem$^*$, and all of the convergences continue to hold. $^*$ Actually, it appears to be a bit subtle. Remark As you surmised, observed information is typically easier to work with because differentiation is easier than integration, and you might have already evaluated it in the course of some numeric optimization. In some circumstances (the Normal distribution) they will be the same. The article "Assessing the Accuracy of the Maximum Likelihood Estimator: Observed Versus Expected Fisher Information" by Efron and Hinkley (1978) makes an argument in favor of the observed information for finite samples.
Why exactly is the observed Fisher information used? You've got four quanties here: the true parameter $\theta_0$, a consistent estimate $\hat \theta$, the expected information $I(\theta)$ at $\theta$ and the observed information $J(\theta)$ at $\theta$
12,713
Why exactly is the observed Fisher information used?
There have been some simulation studies that appear supportive of Efron & Hinkley's theoretical observations (which are mentioned in Andrew's answer), here's one I know of offhand: Maldonado, G. and Greenland, S. (1994). A comparison of the performance of model-based confidence intervals when the correct model form is unknown. Epidemiology, 5, 171-182. I've not seen any studies that conflict. It is interesting then that standard GLM packages I know of use expected information to compute Wald intervals. Of course this is not an issue when (as in GLMs linear in the natural parameter) the observed and expected information matrices are equal.
Why exactly is the observed Fisher information used?
There have been some simulation studies that appear supportive of Efron & Hinkley's theoretical observations (which are mentioned in Andrew's answer), here's one I know of offhand: Maldonado, G. and G
Why exactly is the observed Fisher information used? There have been some simulation studies that appear supportive of Efron & Hinkley's theoretical observations (which are mentioned in Andrew's answer), here's one I know of offhand: Maldonado, G. and Greenland, S. (1994). A comparison of the performance of model-based confidence intervals when the correct model form is unknown. Epidemiology, 5, 171-182. I've not seen any studies that conflict. It is interesting then that standard GLM packages I know of use expected information to compute Wald intervals. Of course this is not an issue when (as in GLMs linear in the natural parameter) the observed and expected information matrices are equal.
Why exactly is the observed Fisher information used? There have been some simulation studies that appear supportive of Efron & Hinkley's theoretical observations (which are mentioned in Andrew's answer), here's one I know of offhand: Maldonado, G. and G
12,714
Detecting outliers in count data
You cannot use the distance of an observation from a classical fit of your data to reliably detect outliers because the fitting procedure you use is itself liable to being pulled towards the outliers (this is called the masking effect). One simple way to reliably detect outliers is to use the general idea you suggested (distance from fit) but replacing the classical estimators by robust ones much less susceptible to be swayed by outliers. Below I present a general illustration of the idea and then discuss the solution for your specific problem. An illustration: consider the following 20 observations drawn from a $\mathcal{N}(0,1)$ (rounded to the second digit): x<-c(-2.21,-1.84,-.95,-.91,-.36,-.19,-.11,-.1,.18, .3,.31,.43,.51,.64,.67,.72,1.22,1.35,8.1,17.6) (the last two really ought to be .81 and 1.76 but have been accidentally misstyped). Using a outlier detection rule based on comparing the statistic $$\frac{|x_i-\text{ave}(x_i)|}{\text{sd}(x_i)}$$ to the quantiles of a normal distribution would never lead you to suspect that 8.1 is an outlier, leading you to estimate the $\text{sd}$ of the 'trimmed' series to be 2 (for comparison the raw, e.g. untrimmed, estimate of $\text{sd}$ is 4.35). Had you used a robust statistic instead: $$\frac{|x_i-\text{med}(x_i)|}{\text{mad}(x_i)}$$ and comparing the resulting robust $z$-scores to the quantiles of a normal, you would have correctly flagged the last two observations as outliers (and correctly estimated the $\text{sd}$ of the trimmed series to be 0.96). (in the interest of completeness I should point out that some people, even in this age and day, prefer to cling the raw --untrimmed-- estimate of 4.35 rather than using the more precise estimate based on trimming but this is unintelligible to me) For other distributions the situation is not that different, merely that you will have to pre-transform your data first. For example, in your case: Suppose $X$ is your original count data. One trick is to use the transformation: $$Y=2\sqrt{X}$$ and to exclude an observation as outlier if $Y>\text{med}(Y)+3$ (this rule is not symmetric and I for one would be very cautions about excluding observations from the left 'tail' of a count variable according to a data based threshold. Negative observations, Obviously, should be pretty safe to remove) This is based on the idea that if $X$ is poisson, then $$Y\approx \mathcal{N}(\text{med}(Y),1)$$ This approximation works reasonably well for poisson distributed data when $\lambda$ (the parameter of the poisson distribution) is larger than 3. When $\lambda$ is smaller than 3 (or when the model governing the distribution of the majority of the data has a mode closer to 0 than a poisson $\lambda=3$, as in i.e. ZINB r.v.'s) the approximation tends to err on the conservative side (reject fewer data as outliers). To see why this is considered 'conservative' consider that at the limit (when the data is binomial with very small $p$) no observation would ever be flagged as outlier by this rule and this is precisely the behaviour we want: to cause masking, outliers have to be able to drive the estimated parameters arbitrarily far away from their true values. When the data is drawn from a distribution with bounded support (such as the binomial), this can simply not happen...
Detecting outliers in count data
You cannot use the distance of an observation from a classical fit of your data to reliably detect outliers because the fitting procedure you use is itself liable to being pulled towards the outliers
Detecting outliers in count data You cannot use the distance of an observation from a classical fit of your data to reliably detect outliers because the fitting procedure you use is itself liable to being pulled towards the outliers (this is called the masking effect). One simple way to reliably detect outliers is to use the general idea you suggested (distance from fit) but replacing the classical estimators by robust ones much less susceptible to be swayed by outliers. Below I present a general illustration of the idea and then discuss the solution for your specific problem. An illustration: consider the following 20 observations drawn from a $\mathcal{N}(0,1)$ (rounded to the second digit): x<-c(-2.21,-1.84,-.95,-.91,-.36,-.19,-.11,-.1,.18, .3,.31,.43,.51,.64,.67,.72,1.22,1.35,8.1,17.6) (the last two really ought to be .81 and 1.76 but have been accidentally misstyped). Using a outlier detection rule based on comparing the statistic $$\frac{|x_i-\text{ave}(x_i)|}{\text{sd}(x_i)}$$ to the quantiles of a normal distribution would never lead you to suspect that 8.1 is an outlier, leading you to estimate the $\text{sd}$ of the 'trimmed' series to be 2 (for comparison the raw, e.g. untrimmed, estimate of $\text{sd}$ is 4.35). Had you used a robust statistic instead: $$\frac{|x_i-\text{med}(x_i)|}{\text{mad}(x_i)}$$ and comparing the resulting robust $z$-scores to the quantiles of a normal, you would have correctly flagged the last two observations as outliers (and correctly estimated the $\text{sd}$ of the trimmed series to be 0.96). (in the interest of completeness I should point out that some people, even in this age and day, prefer to cling the raw --untrimmed-- estimate of 4.35 rather than using the more precise estimate based on trimming but this is unintelligible to me) For other distributions the situation is not that different, merely that you will have to pre-transform your data first. For example, in your case: Suppose $X$ is your original count data. One trick is to use the transformation: $$Y=2\sqrt{X}$$ and to exclude an observation as outlier if $Y>\text{med}(Y)+3$ (this rule is not symmetric and I for one would be very cautions about excluding observations from the left 'tail' of a count variable according to a data based threshold. Negative observations, Obviously, should be pretty safe to remove) This is based on the idea that if $X$ is poisson, then $$Y\approx \mathcal{N}(\text{med}(Y),1)$$ This approximation works reasonably well for poisson distributed data when $\lambda$ (the parameter of the poisson distribution) is larger than 3. When $\lambda$ is smaller than 3 (or when the model governing the distribution of the majority of the data has a mode closer to 0 than a poisson $\lambda=3$, as in i.e. ZINB r.v.'s) the approximation tends to err on the conservative side (reject fewer data as outliers). To see why this is considered 'conservative' consider that at the limit (when the data is binomial with very small $p$) no observation would ever be flagged as outlier by this rule and this is precisely the behaviour we want: to cause masking, outliers have to be able to drive the estimated parameters arbitrarily far away from their true values. When the data is drawn from a distribution with bounded support (such as the binomial), this can simply not happen...
Detecting outliers in count data You cannot use the distance of an observation from a classical fit of your data to reliably detect outliers because the fitting procedure you use is itself liable to being pulled towards the outliers
12,715
Multiple imputation for outcome variables
As you suspected, it is valid to use multiple imputation for the outcome measure. There are cases where this is useful, but it can also be risky. I consider the situation where all covariates are complete, and the outcome is incomplete. If the imputation model is correct, we will obtain valid inferences on the parameter estimates from the imputed data. The inferences obtained from just the complete cases may actually be wrong if the missingness is related to the outcome after conditioning on the predictor, i.e. under MNAR. So imputation is useful if we know (or suspect) that the data are MNAR. Under MAR, there are generally no benefits to impute the outcome, and for a low number of imputations the results may even be somewhat more variable because of simulation error. There is an important exception to this. If we have access to an auxiliary complete variable that is not part of the model and that is highly correlated with the outcome, imputation can be considerably more efficient than complete case analysis, resulting in more precise estimates and shorter confidence intervals. A common scenario where this occurs is if we have a cheap outcome measure for everyone, and an expensive measure for a subset. In many data sets, missing data also occur in the independent variables. In these cases, we need to impute the outcome variable since its imputed version is needed to impute the independent variables.
Multiple imputation for outcome variables
As you suspected, it is valid to use multiple imputation for the outcome measure. There are cases where this is useful, but it can also be risky. I consider the situation where all covariates are comp
Multiple imputation for outcome variables As you suspected, it is valid to use multiple imputation for the outcome measure. There are cases where this is useful, but it can also be risky. I consider the situation where all covariates are complete, and the outcome is incomplete. If the imputation model is correct, we will obtain valid inferences on the parameter estimates from the imputed data. The inferences obtained from just the complete cases may actually be wrong if the missingness is related to the outcome after conditioning on the predictor, i.e. under MNAR. So imputation is useful if we know (or suspect) that the data are MNAR. Under MAR, there are generally no benefits to impute the outcome, and for a low number of imputations the results may even be somewhat more variable because of simulation error. There is an important exception to this. If we have access to an auxiliary complete variable that is not part of the model and that is highly correlated with the outcome, imputation can be considerably more efficient than complete case analysis, resulting in more precise estimates and shorter confidence intervals. A common scenario where this occurs is if we have a cheap outcome measure for everyone, and an expensive measure for a subset. In many data sets, missing data also occur in the independent variables. In these cases, we need to impute the outcome variable since its imputed version is needed to impute the independent variables.
Multiple imputation for outcome variables As you suspected, it is valid to use multiple imputation for the outcome measure. There are cases where this is useful, but it can also be risky. I consider the situation where all covariates are comp
12,716
Multiple imputation for outcome variables
Imputing outcome data is very common and leads to correct inference when accounting for the random error. It sounds like what you're doing is single imputation, by imputing the missing values with a conditional mean under a complete case analysis. What you should be doing is multiple imputation which, for continuous covariates, accounts for the random error you would have observed had you retroactively measured these missing values. The EM algorithm works in a similar way by averaging over a range of possible observed outcomes. Single imputation gives correct estimation of model parameters when there is no mean-variance relationship, but it gives standard error estimates which are biased toward zero, inflating type I error rates. This is because you've been "optimistic" about the extent of error you would have observed had you measured these factors. Multiple imputation is a process of iteratively generating additive error for conditional mean imputation, so that through 7 or 8 simulated imputations, you can combine models and their errors to get correct estimates of model parameters and their standard errors. If you have jointly missing covariates and outcomes, then there is software in SAS, STATA, and R called multiple imputation via chained equations where "completed" datasets (datasets with imputed values which are treated as fixed and non-random) are generated, model parameters estimated from each complete dataset, and their parameter estimates and standard errors combined using a correct mathematical formation (details in the Van Buuren paper). The slight difference between the process in MI and the process you described is that you haven't accounted for the fact that estimating the conditional distribution of the outcome using imputed data will depend on which order you impute certain factors. You should have estimated the conditional distribution of the missing covariates conditioning on the outcome in MI, otherwise you'll get biased parameter estimates.
Multiple imputation for outcome variables
Imputing outcome data is very common and leads to correct inference when accounting for the random error. It sounds like what you're doing is single imputation, by imputing the missing values with a c
Multiple imputation for outcome variables Imputing outcome data is very common and leads to correct inference when accounting for the random error. It sounds like what you're doing is single imputation, by imputing the missing values with a conditional mean under a complete case analysis. What you should be doing is multiple imputation which, for continuous covariates, accounts for the random error you would have observed had you retroactively measured these missing values. The EM algorithm works in a similar way by averaging over a range of possible observed outcomes. Single imputation gives correct estimation of model parameters when there is no mean-variance relationship, but it gives standard error estimates which are biased toward zero, inflating type I error rates. This is because you've been "optimistic" about the extent of error you would have observed had you measured these factors. Multiple imputation is a process of iteratively generating additive error for conditional mean imputation, so that through 7 or 8 simulated imputations, you can combine models and their errors to get correct estimates of model parameters and their standard errors. If you have jointly missing covariates and outcomes, then there is software in SAS, STATA, and R called multiple imputation via chained equations where "completed" datasets (datasets with imputed values which are treated as fixed and non-random) are generated, model parameters estimated from each complete dataset, and their parameter estimates and standard errors combined using a correct mathematical formation (details in the Van Buuren paper). The slight difference between the process in MI and the process you described is that you haven't accounted for the fact that estimating the conditional distribution of the outcome using imputed data will depend on which order you impute certain factors. You should have estimated the conditional distribution of the missing covariates conditioning on the outcome in MI, otherwise you'll get biased parameter estimates.
Multiple imputation for outcome variables Imputing outcome data is very common and leads to correct inference when accounting for the random error. It sounds like what you're doing is single imputation, by imputing the missing values with a c
12,717
Central limit theorem versus law of large numbers
The OP says The central limit theorem states that the mean of i.i.d. variables, as N goes to infinity, becomes normally distributed. I will take this to mean that it is the OP's belief that for i.i.d. random variables $X_i$ with mean $\mu$ and standard deviation $\sigma$, the cumulative distribution function $F_{Z_n}(a)$ of $$Z_n = \frac{1}{n} \sum_{i=1}^n X_i$$ converges to the cumulative distribution function of $\mathcal N(\mu,\sigma)$, a normal random variable with mean $\mu$ and standard deviation $\sigma$. Or, the OP believes minor re-arrangements of this formula, e.g. the distribution of $Z_n - \mu$ converges to the distribution of $\mathcal N(0,\sigma)$, or the distribution of $(Z_n - \mu)/\sigma$ converges to the distribution of $\mathcal N(0,1)$, the standard normal random variable. Note as an example that these statements imply that $$P\{|Z_n - \mu| > \sigma\} = 1 - F_{Z_n}(\mu + \sigma) + F_{Z_n}((\mu + \sigma)^-) \to 1-\Phi(1)+\Phi(-1) \approx 0.32$$ as $n \to \infty$. The OP goes on to say This raises two questions: Can we deduce from this the law of large numbers? If the law of large numbers says that the mean of a sample of a random variable's values equals the true mean μ as N goes to infinity, then it seems even stronger to say that (as the central limit says) that the value becomes N(μ,σ) where σ is the standard deviation. The weak law of large numbers says that for i.i.d. random variables $X_i$ with finite mean $\mu$, given any $\epsilon > 0$, $$P\{|Z_n - \mu| > \epsilon\} \to 0 ~~ \text{as}~ n \to \infty.$$ Note that it is not necessary to assume that the standard deviation is finite. So, to answer the OP's question, The central limit theorem as stated by the OP does not imply the weak law of large numbers. As $n \to \infty$, the OP's version of the central limit theorem says that $P\{|Z_n-\mu| > \sigma\} \to 0.317\cdots$ while the weak law says that $P\{|Z_n-\mu| > \sigma\} \to 0$ From a correct statement of the central limit theorem, one can at best deduce only a restricted form of the weak law of large numbers applying to random variables with finite mean and standard deviation. But the weak law of large numbers also holds for random variables such as Pareto random variables with finite means but infinite standard deviation. I do not understand why saying that the sample mean converges to a normal random variable with nonzero standard deviation is a stronger statement than saying that the sample mean converges to the population mean, which is a constant (or a random variable with zero standard deviation if you like).
Central limit theorem versus law of large numbers
The OP says The central limit theorem states that the mean of i.i.d. variables, as N goes to infinity, becomes normally distributed. I will take this to mean that it is the OP's belief that for i.i.
Central limit theorem versus law of large numbers The OP says The central limit theorem states that the mean of i.i.d. variables, as N goes to infinity, becomes normally distributed. I will take this to mean that it is the OP's belief that for i.i.d. random variables $X_i$ with mean $\mu$ and standard deviation $\sigma$, the cumulative distribution function $F_{Z_n}(a)$ of $$Z_n = \frac{1}{n} \sum_{i=1}^n X_i$$ converges to the cumulative distribution function of $\mathcal N(\mu,\sigma)$, a normal random variable with mean $\mu$ and standard deviation $\sigma$. Or, the OP believes minor re-arrangements of this formula, e.g. the distribution of $Z_n - \mu$ converges to the distribution of $\mathcal N(0,\sigma)$, or the distribution of $(Z_n - \mu)/\sigma$ converges to the distribution of $\mathcal N(0,1)$, the standard normal random variable. Note as an example that these statements imply that $$P\{|Z_n - \mu| > \sigma\} = 1 - F_{Z_n}(\mu + \sigma) + F_{Z_n}((\mu + \sigma)^-) \to 1-\Phi(1)+\Phi(-1) \approx 0.32$$ as $n \to \infty$. The OP goes on to say This raises two questions: Can we deduce from this the law of large numbers? If the law of large numbers says that the mean of a sample of a random variable's values equals the true mean μ as N goes to infinity, then it seems even stronger to say that (as the central limit says) that the value becomes N(μ,σ) where σ is the standard deviation. The weak law of large numbers says that for i.i.d. random variables $X_i$ with finite mean $\mu$, given any $\epsilon > 0$, $$P\{|Z_n - \mu| > \epsilon\} \to 0 ~~ \text{as}~ n \to \infty.$$ Note that it is not necessary to assume that the standard deviation is finite. So, to answer the OP's question, The central limit theorem as stated by the OP does not imply the weak law of large numbers. As $n \to \infty$, the OP's version of the central limit theorem says that $P\{|Z_n-\mu| > \sigma\} \to 0.317\cdots$ while the weak law says that $P\{|Z_n-\mu| > \sigma\} \to 0$ From a correct statement of the central limit theorem, one can at best deduce only a restricted form of the weak law of large numbers applying to random variables with finite mean and standard deviation. But the weak law of large numbers also holds for random variables such as Pareto random variables with finite means but infinite standard deviation. I do not understand why saying that the sample mean converges to a normal random variable with nonzero standard deviation is a stronger statement than saying that the sample mean converges to the population mean, which is a constant (or a random variable with zero standard deviation if you like).
Central limit theorem versus law of large numbers The OP says The central limit theorem states that the mean of i.i.d. variables, as N goes to infinity, becomes normally distributed. I will take this to mean that it is the OP's belief that for i.i.
12,718
Central limit theorem versus law of large numbers
For law of large numbers, you need to have all variables to be defined on the same probability space (as the law of large numbers is a statement about probability of an event determined by $\bar X_n$, for all $n$ simultaneously). For convergence in distribution, you can have different probability spaces, and that simplifies many aspects of the proofs (e.g., increasing nested spaces, very common for various triangular array proofs). But it also means you cannot make any statements concerning the joint distributions of $\bar X_n$ and $\bar X_{n+1}$, say. So no, convergence in distribution does not imply the law of large numbers, unless you have a common probability space for all variables.
Central limit theorem versus law of large numbers
For law of large numbers, you need to have all variables to be defined on the same probability space (as the law of large numbers is a statement about probability of an event determined by $\bar X_n$,
Central limit theorem versus law of large numbers For law of large numbers, you need to have all variables to be defined on the same probability space (as the law of large numbers is a statement about probability of an event determined by $\bar X_n$, for all $n$ simultaneously). For convergence in distribution, you can have different probability spaces, and that simplifies many aspects of the proofs (e.g., increasing nested spaces, very common for various triangular array proofs). But it also means you cannot make any statements concerning the joint distributions of $\bar X_n$ and $\bar X_{n+1}$, say. So no, convergence in distribution does not imply the law of large numbers, unless you have a common probability space for all variables.
Central limit theorem versus law of large numbers For law of large numbers, you need to have all variables to be defined on the same probability space (as the law of large numbers is a statement about probability of an event determined by $\bar X_n$,
12,719
Central limit theorem versus law of large numbers
First, though there are many definitions, one of the standard forms of the central limit theorem says that $\sqrt{n}(\bar{X}_n-EX)$ converges in distribution to $\mathcal N(0, Var(X))$, where $\bar{X}$ is the sample mean of $n$ iid copies of some random variable $X$. Secondly, suppose we have two independent random variables $X$ and $Y$. Then $$\sqrt{n}(\frac{1}{n}\sum_{j=1}^n(aX_j+Y_j) - E(aX+Y)) \to \mathcal N(0, Var(aX+Y))$$ or $$\sqrt{n}a(\bar{X}_n- EX)+\sqrt{n}(\bar{Y}_n -EY) \to \mathcal N(0, a^2Var(X)+Var(Y)).$$ In other words, a linear combination of random variables wont converge to a linear combination of normals under the CLT, just one normal. This makes sense because a linear combination of random variables is just a different random variable that CLT can be applied to directly.
Central limit theorem versus law of large numbers
First, though there are many definitions, one of the standard forms of the central limit theorem says that $\sqrt{n}(\bar{X}_n-EX)$ converges in distribution to $\mathcal N(0, Var(X))$, where $\bar{X}
Central limit theorem versus law of large numbers First, though there are many definitions, one of the standard forms of the central limit theorem says that $\sqrt{n}(\bar{X}_n-EX)$ converges in distribution to $\mathcal N(0, Var(X))$, where $\bar{X}$ is the sample mean of $n$ iid copies of some random variable $X$. Secondly, suppose we have two independent random variables $X$ and $Y$. Then $$\sqrt{n}(\frac{1}{n}\sum_{j=1}^n(aX_j+Y_j) - E(aX+Y)) \to \mathcal N(0, Var(aX+Y))$$ or $$\sqrt{n}a(\bar{X}_n- EX)+\sqrt{n}(\bar{Y}_n -EY) \to \mathcal N(0, a^2Var(X)+Var(Y)).$$ In other words, a linear combination of random variables wont converge to a linear combination of normals under the CLT, just one normal. This makes sense because a linear combination of random variables is just a different random variable that CLT can be applied to directly.
Central limit theorem versus law of large numbers First, though there are many definitions, one of the standard forms of the central limit theorem says that $\sqrt{n}(\bar{X}_n-EX)$ converges in distribution to $\mathcal N(0, Var(X))$, where $\bar{X}
12,720
Convolutional neural network for time series? [closed]
If you want an open source black-box solution try looking at Weka, a java library of ML algorithms. This guy has also used Covolutional Layers in Weka and you could edit his classification code to suit a time series classification task. As for coding your own... I am working on the same problem using the python library, theano (I will edit this post with a link to my code if I crack it sometime soon). Here is a comprehensive list of all the papers I will be using to help me from a good hour of searching the web: Time Series Prediction and Neural Networks Convolutional Networks for Images, Speech and Time Series Deep neural networks for time series prediction with applications in ultra-short-term wind forecasting Convolutional Networks for Stock Trading Statistical Arbitrage Stock Trading using Time Delay Neural Networks Time Series Classification Using Multi-Channels Deep Convolutional Neural Networks Neural Networks for Time Series Prediction Applying Neural Networks for Concept Drift Detection in Financial Markets Encoding Time Series as Images for Visual Inspection and Classification Using Tiled Convolutional Neural Networks Time Series Prediction Using Convolution Sum Discrete Process Neural Network Long-term Recurrent Convolutional Networks for Visual Recognition and Description Exploring Convolutional Neural Network Structures and Optimization Techniques for Speech Recognition As a starting point, you could edit the code found here to classify against a different number of categories, or edit it from classification to regression - I did this by removing the final softmax layer and making just one output node. I trained it on slices of a function like y=sin(x) as a test.
Convolutional neural network for time series? [closed]
If you want an open source black-box solution try looking at Weka, a java library of ML algorithms. This guy has also used Covolutional Layers in Weka and you could edit his classification code to sui
Convolutional neural network for time series? [closed] If you want an open source black-box solution try looking at Weka, a java library of ML algorithms. This guy has also used Covolutional Layers in Weka and you could edit his classification code to suit a time series classification task. As for coding your own... I am working on the same problem using the python library, theano (I will edit this post with a link to my code if I crack it sometime soon). Here is a comprehensive list of all the papers I will be using to help me from a good hour of searching the web: Time Series Prediction and Neural Networks Convolutional Networks for Images, Speech and Time Series Deep neural networks for time series prediction with applications in ultra-short-term wind forecasting Convolutional Networks for Stock Trading Statistical Arbitrage Stock Trading using Time Delay Neural Networks Time Series Classification Using Multi-Channels Deep Convolutional Neural Networks Neural Networks for Time Series Prediction Applying Neural Networks for Concept Drift Detection in Financial Markets Encoding Time Series as Images for Visual Inspection and Classification Using Tiled Convolutional Neural Networks Time Series Prediction Using Convolution Sum Discrete Process Neural Network Long-term Recurrent Convolutional Networks for Visual Recognition and Description Exploring Convolutional Neural Network Structures and Optimization Techniques for Speech Recognition As a starting point, you could edit the code found here to classify against a different number of categories, or edit it from classification to regression - I did this by removing the final softmax layer and making just one output node. I trained it on slices of a function like y=sin(x) as a test.
Convolutional neural network for time series? [closed] If you want an open source black-box solution try looking at Weka, a java library of ML algorithms. This guy has also used Covolutional Layers in Weka and you could edit his classification code to sui
12,721
Convolutional neural network for time series? [closed]
It is entirely possible to use a CNN to make time series predictions be it regression or classification. CNNs are good at finding local patterns and in fact CNNs work with the assumption that local patterns are relevant everywhere. Also convolution is a well-known operation in time series and signal processing. Another advantage over RNNs is that they can be very fast to compute since they can be parallelized as opposed to the RNN sequential nature. In the code below I will demonstrate a case study where it is possible to predict electricity demand in R using keras. Note that this is not a classification problem (I did not have an example handy) but it is not difficult to modify the code to handle a classification problem (use a softmax output instead of a linear output and a cross entropy loss). The dataset is available in fpp2 library: library(fpp2) library(keras) data("elecdemand") elec <- as.data.frame(elecdemand) dm <- as.matrix(elec[, c("WorkDay", "Temperature", "Demand")]) Next we create a data generator. This is used for creating batches of training and validation data to be used during the training process. Note that this code is a simpler version of a data generator found in the book "Deep Learning with R" (and the video version of it "Deep Learning with R in Motion") from manning publications. data_gen <- function(dm, batch_size, ycol, lookback, lookahead) { num_rows <- nrow(dm) - lookback - lookahead num_batches <- ceiling(num_rows/batch_size) last_batch_size <- if (num_rows %% batch_size == 0) batch_size else num_rows %% batch_size i <- 1 start_idx <- 1 return(function(){ running_batch_size <<- if (i == num_batches) last_batch_size else batch_size end_idx <- start_idx + running_batch_size - 1 start_indices <- start_idx:end_idx X_batch <- array(0, dim = c(running_batch_size, lookback, ncol(dm))) y_batch <- array(0, dim = c(running_batch_size, length(ycol))) for (j in 1:running_batch_size){ row_indices <- start_indices[j]:(start_indices[j]+lookback-1) X_batch[j,,] <- dm[row_indices,] y_batch[j,] <- dm[start_indices[j]+lookback-1+lookahead, ycol] } i <<- i+1 start_idx <<- end_idx+1 if (i > num_batches){ i <<- 1 start_idx <<- 1 } list(X_batch, y_batch) }) } Next we specify some parameters to be passed into our data generators (we create two generators one for training and one for validation). lookback <- 72 lookahead <- 1 batch_size <- 168 ycol <- 3 The lookback parameter is how far in the past we want to look and the lookahead how far in the future we want to predict. Next we split our dataset and create two generators: train_dm <- dm[1:15000,] val_dm <- dm[15001:16000,] test_dm <- dm[16001:nrow(dm),] train_gen <- data_gen( train_dm, batch_size = batch_size, ycol = ycol, lookback = lookback, lookahead = lookahead ) val_gen <- data_gen( val_dm, batch_size = batch_size, ycol = ycol, lookback = lookback, lookahead = lookahead ) Next we create a neural network with a convolutional layer and train the model: model <- keras_model_sequential() %>% layer_conv_1d(filters=64, kernel_size=4, activation="relu", input_shape=c(lookback, dim(dm)[[-1]])) %>% layer_max_pooling_1d(pool_size=4) %>% layer_flatten() %>% layer_dense(units=lookback * dim(dm)[[-1]], activation="relu") %>% layer_dropout(rate=0.2) %>% layer_dense(units=1, activation="linear") model %>% compile( optimizer = optimizer_rmsprop(lr=0.001), loss = "mse", metric = "mae" ) val_steps <- 48 history <- model %>% fit_generator( train_gen, steps_per_epoch = 50, epochs = 50, validation_data = val_gen, validation_steps = val_steps ) Finally, we can create some code to predict a sequence of 24 datapoints using a simple procedure, explained in the R comments. ####### How to create predictions #################### #We will create a predict_forecast function that will do the following: #The function will be given a dataset that will contain weather forecast values and Demand values for the lookback duration. The rest of the MW values will be non-available and #will be "filled-in" by the deep network (predicted). We will do this with the test_dm dataset. horizon <- 24 #Store all target values in a vector goal_predictions <- test_dm[1:(lookback+horizon),ycol] #get a copy of the dm_test test_set <- test_dm[1:(lookback+horizon),] #Set all the Demand values, except the lookback values, in the test set to be equal to NA. test_set[(lookback+1):nrow(test_set), ycol] <- NA predict_forecast <- function(model, test_data, ycol, lookback, horizon) { i <-1 for (i in 1:horizon){ start_idx <- i end_idx <- start_idx + lookback - 1 predict_idx <- end_idx + 1 input_batch <- test_data[start_idx:end_idx,] input_batch <- input_batch %>% array_reshape(dim = c(1, dim(input_batch))) prediction <- model %>% predict_on_batch(input_batch) test_data[predict_idx, ycol] <- prediction } test_data[(lookback+1):(lookback+horizon), ycol] } preds <- predict_forecast(model, test_set, ycol, lookback, horizon) targets <- goal_predictions[(lookback+1):(lookback+horizon)] pred_df <- data.frame(x = 1:horizon, y = targets, y_hat = preds) and voila: Not too bad.
Convolutional neural network for time series? [closed]
It is entirely possible to use a CNN to make time series predictions be it regression or classification. CNNs are good at finding local patterns and in fact CNNs work with the assumption that local pa
Convolutional neural network for time series? [closed] It is entirely possible to use a CNN to make time series predictions be it regression or classification. CNNs are good at finding local patterns and in fact CNNs work with the assumption that local patterns are relevant everywhere. Also convolution is a well-known operation in time series and signal processing. Another advantage over RNNs is that they can be very fast to compute since they can be parallelized as opposed to the RNN sequential nature. In the code below I will demonstrate a case study where it is possible to predict electricity demand in R using keras. Note that this is not a classification problem (I did not have an example handy) but it is not difficult to modify the code to handle a classification problem (use a softmax output instead of a linear output and a cross entropy loss). The dataset is available in fpp2 library: library(fpp2) library(keras) data("elecdemand") elec <- as.data.frame(elecdemand) dm <- as.matrix(elec[, c("WorkDay", "Temperature", "Demand")]) Next we create a data generator. This is used for creating batches of training and validation data to be used during the training process. Note that this code is a simpler version of a data generator found in the book "Deep Learning with R" (and the video version of it "Deep Learning with R in Motion") from manning publications. data_gen <- function(dm, batch_size, ycol, lookback, lookahead) { num_rows <- nrow(dm) - lookback - lookahead num_batches <- ceiling(num_rows/batch_size) last_batch_size <- if (num_rows %% batch_size == 0) batch_size else num_rows %% batch_size i <- 1 start_idx <- 1 return(function(){ running_batch_size <<- if (i == num_batches) last_batch_size else batch_size end_idx <- start_idx + running_batch_size - 1 start_indices <- start_idx:end_idx X_batch <- array(0, dim = c(running_batch_size, lookback, ncol(dm))) y_batch <- array(0, dim = c(running_batch_size, length(ycol))) for (j in 1:running_batch_size){ row_indices <- start_indices[j]:(start_indices[j]+lookback-1) X_batch[j,,] <- dm[row_indices,] y_batch[j,] <- dm[start_indices[j]+lookback-1+lookahead, ycol] } i <<- i+1 start_idx <<- end_idx+1 if (i > num_batches){ i <<- 1 start_idx <<- 1 } list(X_batch, y_batch) }) } Next we specify some parameters to be passed into our data generators (we create two generators one for training and one for validation). lookback <- 72 lookahead <- 1 batch_size <- 168 ycol <- 3 The lookback parameter is how far in the past we want to look and the lookahead how far in the future we want to predict. Next we split our dataset and create two generators: train_dm <- dm[1:15000,] val_dm <- dm[15001:16000,] test_dm <- dm[16001:nrow(dm),] train_gen <- data_gen( train_dm, batch_size = batch_size, ycol = ycol, lookback = lookback, lookahead = lookahead ) val_gen <- data_gen( val_dm, batch_size = batch_size, ycol = ycol, lookback = lookback, lookahead = lookahead ) Next we create a neural network with a convolutional layer and train the model: model <- keras_model_sequential() %>% layer_conv_1d(filters=64, kernel_size=4, activation="relu", input_shape=c(lookback, dim(dm)[[-1]])) %>% layer_max_pooling_1d(pool_size=4) %>% layer_flatten() %>% layer_dense(units=lookback * dim(dm)[[-1]], activation="relu") %>% layer_dropout(rate=0.2) %>% layer_dense(units=1, activation="linear") model %>% compile( optimizer = optimizer_rmsprop(lr=0.001), loss = "mse", metric = "mae" ) val_steps <- 48 history <- model %>% fit_generator( train_gen, steps_per_epoch = 50, epochs = 50, validation_data = val_gen, validation_steps = val_steps ) Finally, we can create some code to predict a sequence of 24 datapoints using a simple procedure, explained in the R comments. ####### How to create predictions #################### #We will create a predict_forecast function that will do the following: #The function will be given a dataset that will contain weather forecast values and Demand values for the lookback duration. The rest of the MW values will be non-available and #will be "filled-in" by the deep network (predicted). We will do this with the test_dm dataset. horizon <- 24 #Store all target values in a vector goal_predictions <- test_dm[1:(lookback+horizon),ycol] #get a copy of the dm_test test_set <- test_dm[1:(lookback+horizon),] #Set all the Demand values, except the lookback values, in the test set to be equal to NA. test_set[(lookback+1):nrow(test_set), ycol] <- NA predict_forecast <- function(model, test_data, ycol, lookback, horizon) { i <-1 for (i in 1:horizon){ start_idx <- i end_idx <- start_idx + lookback - 1 predict_idx <- end_idx + 1 input_batch <- test_data[start_idx:end_idx,] input_batch <- input_batch %>% array_reshape(dim = c(1, dim(input_batch))) prediction <- model %>% predict_on_batch(input_batch) test_data[predict_idx, ycol] <- prediction } test_data[(lookback+1):(lookback+horizon), ycol] } preds <- predict_forecast(model, test_set, ycol, lookback, horizon) targets <- goal_predictions[(lookback+1):(lookback+horizon)] pred_df <- data.frame(x = 1:horizon, y = targets, y_hat = preds) and voila: Not too bad.
Convolutional neural network for time series? [closed] It is entirely possible to use a CNN to make time series predictions be it regression or classification. CNNs are good at finding local patterns and in fact CNNs work with the assumption that local pa
12,722
Whether distributions with the same moments are identical
Let me answer in reverse order: 2. Yes. If their MGFs exist, they'll be the same*. see here and here for example Indeed it follows from the result you give in the post this comes from; if the MGF uniquely** determines the distribution, and two distributions have MGFs and they have the same distribution, they must have the same MGF (otherwise you'd have a counterexample to 'MGFs uniquely determine distributions'). * for certain values of 'same', due to that phrase 'almost everywhere' ** 'almost everywhere' No - since counterexamples exist. Kendall and Stuart list a continuous distribution family (possibly originally due to Stieltjes or someone of that vintage, but my recollection is unclear, it's been a few decades) that have identical moment sequences and yet are different. The book by Romano and Siegel (Counterexamples in Probability and Statistics) lists counterexamples in section 3.14 and 3.15 (pages 48-49). (Actually, looking at them, I think both of those were in Kendall and Stuart.) Romano, J. P. and Siegel, A. F. (1986), Counterexamples in Probability and Statistics. Boca Raton: Chapman and Hall/CRC. For 3.15 they credit Feller, 1971, p227 That second example involves the family of densities $$f(x;\alpha) = \frac{1}{24}\exp(-x^{1/4})[1-\alpha \sin(x^{1/4})], \quad x>0;\,0<\alpha<1$$ The densities differ as $\alpha$ changes, but the moment sequences are the same. That the moment sequences are the same involves splitting $f$ into the parts $\frac{1}{24}\exp(-x^{1/4}) -\alpha \frac{1}{24}\exp(-x^{1/4})\sin(x^{1/4})$ and then showing that the second part contributes 0 to each moment, so they are all the same as the moments of the first part. Here's what two of the densities look like. The blue is the case at the left limit ($\alpha=0$), the green is the case with $\alpha=0.5$. The right-side graph is the same but with log-log scales on the axes. Better still, perhaps, to have taken a much bigger range and used a fourth-root scale on the x-axis, making the blue curve straight, and the green one move like a sin curve above and below it, something like so: The wiggles above and below the blue curve - whether of larger or smaller magnitude - turn out to leave all positive integer moments unaltered. Note that this also means we can get a distribution all of whose odd moments are zero, but which is asymmetric, by choosing $X_1,X_2$ with different $\alpha$ and taking a 50-50 mix of $X_1$, and $-X_2$. The result must have all odd moments cancel, but the two halves aren't the same.
Whether distributions with the same moments are identical
Let me answer in reverse order: 2. Yes. If their MGFs exist, they'll be the same*. see here and here for example Indeed it follows from the result you give in the post this comes from; if the MGF uniq
Whether distributions with the same moments are identical Let me answer in reverse order: 2. Yes. If their MGFs exist, they'll be the same*. see here and here for example Indeed it follows from the result you give in the post this comes from; if the MGF uniquely** determines the distribution, and two distributions have MGFs and they have the same distribution, they must have the same MGF (otherwise you'd have a counterexample to 'MGFs uniquely determine distributions'). * for certain values of 'same', due to that phrase 'almost everywhere' ** 'almost everywhere' No - since counterexamples exist. Kendall and Stuart list a continuous distribution family (possibly originally due to Stieltjes or someone of that vintage, but my recollection is unclear, it's been a few decades) that have identical moment sequences and yet are different. The book by Romano and Siegel (Counterexamples in Probability and Statistics) lists counterexamples in section 3.14 and 3.15 (pages 48-49). (Actually, looking at them, I think both of those were in Kendall and Stuart.) Romano, J. P. and Siegel, A. F. (1986), Counterexamples in Probability and Statistics. Boca Raton: Chapman and Hall/CRC. For 3.15 they credit Feller, 1971, p227 That second example involves the family of densities $$f(x;\alpha) = \frac{1}{24}\exp(-x^{1/4})[1-\alpha \sin(x^{1/4})], \quad x>0;\,0<\alpha<1$$ The densities differ as $\alpha$ changes, but the moment sequences are the same. That the moment sequences are the same involves splitting $f$ into the parts $\frac{1}{24}\exp(-x^{1/4}) -\alpha \frac{1}{24}\exp(-x^{1/4})\sin(x^{1/4})$ and then showing that the second part contributes 0 to each moment, so they are all the same as the moments of the first part. Here's what two of the densities look like. The blue is the case at the left limit ($\alpha=0$), the green is the case with $\alpha=0.5$. The right-side graph is the same but with log-log scales on the axes. Better still, perhaps, to have taken a much bigger range and used a fourth-root scale on the x-axis, making the blue curve straight, and the green one move like a sin curve above and below it, something like so: The wiggles above and below the blue curve - whether of larger or smaller magnitude - turn out to leave all positive integer moments unaltered. Note that this also means we can get a distribution all of whose odd moments are zero, but which is asymmetric, by choosing $X_1,X_2$ with different $\alpha$ and taking a 50-50 mix of $X_1$, and $-X_2$. The result must have all odd moments cancel, but the two halves aren't the same.
Whether distributions with the same moments are identical Let me answer in reverse order: 2. Yes. If their MGFs exist, they'll be the same*. see here and here for example Indeed it follows from the result you give in the post this comes from; if the MGF uniq
12,723
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
Short answer since I don't have time for better: this is a challenging problem; binary data almost always requires some kind of binning or smoothing to assess goodness of fit. It was somewhat helpful to use fortify.lmerMod (from lme4, experimental) in conjunction with ggplot2 and particularly geom_smooth() to draw essentially the same residual-vs-fitted plot you have above, but with confidence intervals (I also narrowed the y limits a bit to zoom in on the (-5,5) region). That suggested some systematic variation that could be improved by tweaking the link function. (I also tried plotting residuals against the other predictors, but it wasn't too useful.) I tried fitting the model with all 3-way interactions, but it wasn't much of an improvement either in deviance or in the shape of the smoothed residual curve. Then I used this bit of brute force to try inverse-link functions of the form $(\mbox{logistic}(x))^\lambda$, for $\lambda$ ranging from 0.5 to 2.0: ## uses (fragile) internal C calls for speed; could use plogis(), ## qlogis() for readability and stability instead logitpower <- function(lambda) { L <- list(linkfun=function(mu) .Call(stats:::C_logit_link,mu^(1/lambda),PACKAGE="stats"), linkinv=function(eta) .Call(stats:::C_logit_linkinv,eta,PACKAGE="stats")^lambda, mu.eta=function(eta) { mu <- .Call(stats:::C_logit_linkinv,eta,PACKAGE="stats") mu.eta <- .Call(stats:::C_logit_mu_eta,eta,PACKAGE="stats") lambda*mu^(lambda-1)*mu.eta }, valideta = function(eta) TRUE , name=paste0("logit-power(",lambda,")")) class(L) <- "link-glm" L } I found that a $\lambda$ of 0.75 was slightly better than the original model, although not significantly so -- I may have been overinterpreting the data. See also: http://freakonometrics.hypotheses.org/8210
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
Short answer since I don't have time for better: this is a challenging problem; binary data almost always requires some kind of binning or smoothing to assess goodness of fit. It was somewhat helpful
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? Short answer since I don't have time for better: this is a challenging problem; binary data almost always requires some kind of binning or smoothing to assess goodness of fit. It was somewhat helpful to use fortify.lmerMod (from lme4, experimental) in conjunction with ggplot2 and particularly geom_smooth() to draw essentially the same residual-vs-fitted plot you have above, but with confidence intervals (I also narrowed the y limits a bit to zoom in on the (-5,5) region). That suggested some systematic variation that could be improved by tweaking the link function. (I also tried plotting residuals against the other predictors, but it wasn't too useful.) I tried fitting the model with all 3-way interactions, but it wasn't much of an improvement either in deviance or in the shape of the smoothed residual curve. Then I used this bit of brute force to try inverse-link functions of the form $(\mbox{logistic}(x))^\lambda$, for $\lambda$ ranging from 0.5 to 2.0: ## uses (fragile) internal C calls for speed; could use plogis(), ## qlogis() for readability and stability instead logitpower <- function(lambda) { L <- list(linkfun=function(mu) .Call(stats:::C_logit_link,mu^(1/lambda),PACKAGE="stats"), linkinv=function(eta) .Call(stats:::C_logit_linkinv,eta,PACKAGE="stats")^lambda, mu.eta=function(eta) { mu <- .Call(stats:::C_logit_linkinv,eta,PACKAGE="stats") mu.eta <- .Call(stats:::C_logit_mu_eta,eta,PACKAGE="stats") lambda*mu^(lambda-1)*mu.eta }, valideta = function(eta) TRUE , name=paste0("logit-power(",lambda,")")) class(L) <- "link-glm" L } I found that a $\lambda$ of 0.75 was slightly better than the original model, although not significantly so -- I may have been overinterpreting the data. See also: http://freakonometrics.hypotheses.org/8210
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? Short answer since I don't have time for better: this is a challenging problem; binary data almost always requires some kind of binning or smoothing to assess goodness of fit. It was somewhat helpful
12,724
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
This is very common theme on biostatistics/epidemiology courses, and there are not very good solutions for it, basically due to the nature of the model. Often the solution has been to avoid detailed diagnostics using the residuals. Ben already wrote that diagnostics often require either binning or smoothing. Binning of residuals is (or was) available in the R package arm, see e.g., this thread. In addition, there are some work done that uses predicted probabilities; one possibility is the separation plot that has been discussed earlier in this thread. Those might or might not directly help in your case, but could possible help the interpretation.
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
This is very common theme on biostatistics/epidemiology courses, and there are not very good solutions for it, basically due to the nature of the model. Often the solution has been to avoid detailed d
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? This is very common theme on biostatistics/epidemiology courses, and there are not very good solutions for it, basically due to the nature of the model. Often the solution has been to avoid detailed diagnostics using the residuals. Ben already wrote that diagnostics often require either binning or smoothing. Binning of residuals is (or was) available in the R package arm, see e.g., this thread. In addition, there are some work done that uses predicted probabilities; one possibility is the separation plot that has been discussed earlier in this thread. Those might or might not directly help in your case, but could possible help the interpretation.
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? This is very common theme on biostatistics/epidemiology courses, and there are not very good solutions for it, basically due to the nature of the model. Often the solution has been to avoid detailed d
12,725
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
You can plot the residuals against the predictors using simulation techniques in DHARMa package, it also offers a range of diagnostics such as overdispersion, and outliers, I think its a practical and simple assessment tool for GLMM. Check it out: https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
You can plot the residuals against the predictors using simulation techniques in DHARMa package, it also offers a range of diagnostics such as overdispersion, and outliers, I think its a practical and
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? You can plot the residuals against the predictors using simulation techniques in DHARMa package, it also offers a range of diagnostics such as overdispersion, and outliers, I think its a practical and simple assessment tool for GLMM. Check it out: https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? You can plot the residuals against the predictors using simulation techniques in DHARMa package, it also offers a range of diagnostics such as overdispersion, and outliers, I think its a practical and
12,726
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
You could use AIC instead of residual plots to check fit of model. Command in R: AIC(model1) it will give you a number...so then you need to compare this with another model (with more predictors, for example) -- AIC(model2), which will yield another number. Compare the two outputs, and you'll want the model with the lower AIC value. By the way, things like AIC and log likelihood ratio are already listed when you get the summary of your glmer model, and both will give you useful info on fit of model. You want a large negative number for log likelihood ratio to reject the null hypothesis.
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
You could use AIC instead of residual plots to check fit of model. Command in R: AIC(model1) it will give you a number...so then you need to compare this with another model (with more predictors, for
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? You could use AIC instead of residual plots to check fit of model. Command in R: AIC(model1) it will give you a number...so then you need to compare this with another model (with more predictors, for example) -- AIC(model2), which will yield another number. Compare the two outputs, and you'll want the model with the lower AIC value. By the way, things like AIC and log likelihood ratio are already listed when you get the summary of your glmer model, and both will give you useful info on fit of model. You want a large negative number for log likelihood ratio to reject the null hypothesis.
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? You could use AIC instead of residual plots to check fit of model. Command in R: AIC(model1) it will give you a number...so then you need to compare this with another model (with more predictors, for
12,727
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
Fitted vs residuals plot should not show any (clear) pattern. The plot shows that the model does not work well with the data. See http://www.r-bloggers.com/model-validation-interpreting-residual-plots/
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)?
Fitted vs residuals plot should not show any (clear) pattern. The plot shows that the model does not work well with the data. See http://www.r-bloggers.com/model-validation-interpreting-residual-plots
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? Fitted vs residuals plot should not show any (clear) pattern. The plot shows that the model does not work well with the data. See http://www.r-bloggers.com/model-validation-interpreting-residual-plots/
How to assess the fit of a binomial GLMM fitted with lme4 (> 1.0)? Fitted vs residuals plot should not show any (clear) pattern. The plot shows that the model does not work well with the data. See http://www.r-bloggers.com/model-validation-interpreting-residual-plots
12,728
Comparing AIC of a model and its log-transformed version
You cannot compare the AIC or BIC when fitting to two different data sets i.e. $Y$ and $Z$. You only can compare two models based on AIC or BIC just when fitting to the same data set. Have a look at Model Selection and Multi-model Inference: A Practical Information-theoretic Approach (Burnham and Anderson, 2004). They mentioned my answer on page 81 (section 2.11.3 Transformations of the Response Variable): Investigators should be sure that all hypotheses are modeled using the same response variable (e.g., if the whole set of models were based on log(y), no problem would be created; it is the mixing of response variables that is incorrect). And by the way, for using the AIC or BIC criteria, your models do not need to be necessarily nested (same ref, page 88, section 2.12.4 Nonnested Models), and actually that's one of the advantages of using BIC.
Comparing AIC of a model and its log-transformed version
You cannot compare the AIC or BIC when fitting to two different data sets i.e. $Y$ and $Z$. You only can compare two models based on AIC or BIC just when fitting to the same data set. Have a look at
Comparing AIC of a model and its log-transformed version You cannot compare the AIC or BIC when fitting to two different data sets i.e. $Y$ and $Z$. You only can compare two models based on AIC or BIC just when fitting to the same data set. Have a look at Model Selection and Multi-model Inference: A Practical Information-theoretic Approach (Burnham and Anderson, 2004). They mentioned my answer on page 81 (section 2.11.3 Transformations of the Response Variable): Investigators should be sure that all hypotheses are modeled using the same response variable (e.g., if the whole set of models were based on log(y), no problem would be created; it is the mixing of response variables that is incorrect). And by the way, for using the AIC or BIC criteria, your models do not need to be necessarily nested (same ref, page 88, section 2.12.4 Nonnested Models), and actually that's one of the advantages of using BIC.
Comparing AIC of a model and its log-transformed version You cannot compare the AIC or BIC when fitting to two different data sets i.e. $Y$ and $Z$. You only can compare two models based on AIC or BIC just when fitting to the same data set. Have a look at
12,729
Comparing AIC of a model and its log-transformed version
Akaike (1978, pg. 224) describes how the AIC can be adjusted in the presence of a transformed outcome variable to enable model comparison. He states: “the effect of transforming the variable is represented simply by the multiplication of the likelihood by the corresponding Jacobian to the AIC ... for the case of $\log\{y(n)+1\}$, it is −2 $\cdot \sum \log\{y(n)+1\}$, where the summation extends over $n = 1,2, ..., N$.” Akaike, H. 1978. "On the likelihood of a time series model," Journal of the Royal Statistical Society, Series D (The Statistician), 27(3/4), pp. 217–235.
Comparing AIC of a model and its log-transformed version
Akaike (1978, pg. 224) describes how the AIC can be adjusted in the presence of a transformed outcome variable to enable model comparison. He states: “the effect of transforming the variable is repres
Comparing AIC of a model and its log-transformed version Akaike (1978, pg. 224) describes how the AIC can be adjusted in the presence of a transformed outcome variable to enable model comparison. He states: “the effect of transforming the variable is represented simply by the multiplication of the likelihood by the corresponding Jacobian to the AIC ... for the case of $\log\{y(n)+1\}$, it is −2 $\cdot \sum \log\{y(n)+1\}$, where the summation extends over $n = 1,2, ..., N$.” Akaike, H. 1978. "On the likelihood of a time series model," Journal of the Royal Statistical Society, Series D (The Statistician), 27(3/4), pp. 217–235.
Comparing AIC of a model and its log-transformed version Akaike (1978, pg. 224) describes how the AIC can be adjusted in the presence of a transformed outcome variable to enable model comparison. He states: “the effect of transforming the variable is repres
12,730
Comparing AIC of a model and its log-transformed version
Here is an example that elaborates on Ben Bolker's response: seedrates <- data.frame(rate = c(50, 75, 100, 125, 150), grain = c(21.2, 19.9, 19.2, 18.4, 17.9)) quad.lm <- lm(grain~poly(rate,2), data=seedrates) loglin.lm <- lm(log(grain)~log(rate), data=seedrates) oldopt <- options(digits=2) AIC(quad.lm, loglin.lm) df AIC quad.lm 4 -4.1 loglin.lm 3 -37.2 We need to add sum(2*log(seedrates$grain)) = 29.6 to the AIC for the loglinear model (or, subtract it from the AIC for the quadratic model). > AIC(quad.lm, loglin.lm) + matrix(ncol=2, c(0,0,0, sum(2*log(seedrates$grain)))) df AIC quad.lm 4 -4.1 loglin.lm 3 -7.6 > options(oldopt) This should probably be regarded as a toy example. With so few degrees of freedom to play with, it might just be argued that the loglinear model makes more sense. The quadratic model would imply that, a short distance beyond the upper limit of the rate, grain will start to increase.
Comparing AIC of a model and its log-transformed version
Here is an example that elaborates on Ben Bolker's response: seedrates <- data.frame(rate = c(50, 75, 100, 125, 150), grain = c(21.2, 19.9, 19.2, 18.4, 17.9)) quad.lm <- lm(gr
Comparing AIC of a model and its log-transformed version Here is an example that elaborates on Ben Bolker's response: seedrates <- data.frame(rate = c(50, 75, 100, 125, 150), grain = c(21.2, 19.9, 19.2, 18.4, 17.9)) quad.lm <- lm(grain~poly(rate,2), data=seedrates) loglin.lm <- lm(log(grain)~log(rate), data=seedrates) oldopt <- options(digits=2) AIC(quad.lm, loglin.lm) df AIC quad.lm 4 -4.1 loglin.lm 3 -37.2 We need to add sum(2*log(seedrates$grain)) = 29.6 to the AIC for the loglinear model (or, subtract it from the AIC for the quadratic model). > AIC(quad.lm, loglin.lm) + matrix(ncol=2, c(0,0,0, sum(2*log(seedrates$grain)))) df AIC quad.lm 4 -4.1 loglin.lm 3 -7.6 > options(oldopt) This should probably be regarded as a toy example. With so few degrees of freedom to play with, it might just be argued that the loglinear model makes more sense. The quadratic model would imply that, a short distance beyond the upper limit of the rate, grain will start to increase.
Comparing AIC of a model and its log-transformed version Here is an example that elaborates on Ben Bolker's response: seedrates <- data.frame(rate = c(50, 75, 100, 125, 150), grain = c(21.2, 19.9, 19.2, 18.4, 17.9)) quad.lm <- lm(gr
12,731
Which distributions have closed-form solutions for maximum likelihood estimation?
Without any appreciable loss of generality we may assume that the probability density (or mass) $f(x_i)$ for any observation $x_i$ (out of $n$ observations) is strictly positive, enabling us to write it as an exponential $$ f(x_i) = \exp{(g(x_i,\theta))}$$ for a parameter vector $\theta = (\theta_j)$. Equating the gradient of the log likelihood function to zero (which finds stationary points of the likelihood, among which will be all interior global maxima if one exists) gives a set of equations of the form $$\sum_i\frac{d g(x_i, \theta)}{d\theta_j} = 0,$$ one for each $j$. For any one of these to have a ready solution, we would like to be able to separate the $x_i$ terms from the $\theta$ terms. (Everything flows from this key idea, motivated by the Principle of Mathematical Laziness: do as little work as possible; think ahead before computing; tackle easy versions of hard problems first.) The most general way to do this is for the equations to take the form $$\sum_i \left(\eta_j(\theta) \tau_j(x_i) - \alpha_j(\theta)\right) = \eta_j(\theta)\sum_i \tau_j(x_i) - n \alpha_j(\theta) $$ for known functions $\eta_j$, $\tau_j$, and $\alpha_j$, for then the solution is obtained by solving the simultaneous equations $$\frac{n\alpha_j(\theta)}{\eta_j(\theta)}= \sum_i \tau_j(x_i)$$ for $\theta$. In general these will be difficult to solve, but provided the set of values of $\left(\frac{n\alpha_j(\theta)}{\eta_j(\theta)}\right)$ give full information about $\theta$, we could simply use this vector in place of $\theta$ itself (thereby somewhat generalizing the idea of a "closed form" solution, but in a highly productive way). In such a case, integrating with respect to $\theta_j$ yields $$g(x, \theta) = \tau_j(x)\int^\theta \eta_j(\theta) d\theta_j - \int^\theta \alpha_j(\theta) d\theta_j + B(x, \theta_j')$$ (where $\theta_j'$ stands for all the components of $\theta$ except $\theta_j$). Because the left hand side is functionally independent of $\theta_j$, we must have that $\tau_j(x)=T(x)$ for some fixed function $T$; that $B$ must not depend on $\theta$ at all; and the $\eta_j$ are derivatives of some function $H(\theta)$ and the $\alpha_j$ are derivatives of some other function $A(\theta)$, both of them functionally independent of the data. Whence $$g(x, \theta) = H(\theta)T(x) - A(\theta) + B(x).$$ Densities that can be written in this form make up the well-known Koopman-Pitman-Darmois, or exponential, family. It comprises important parametric families, both continuous and discrete, including Gamma, Normal, Chi-squared, Poisson, Multinomial, and many others.
Which distributions have closed-form solutions for maximum likelihood estimation?
Without any appreciable loss of generality we may assume that the probability density (or mass) $f(x_i)$ for any observation $x_i$ (out of $n$ observations) is strictly positive, enabling us to write
Which distributions have closed-form solutions for maximum likelihood estimation? Without any appreciable loss of generality we may assume that the probability density (or mass) $f(x_i)$ for any observation $x_i$ (out of $n$ observations) is strictly positive, enabling us to write it as an exponential $$ f(x_i) = \exp{(g(x_i,\theta))}$$ for a parameter vector $\theta = (\theta_j)$. Equating the gradient of the log likelihood function to zero (which finds stationary points of the likelihood, among which will be all interior global maxima if one exists) gives a set of equations of the form $$\sum_i\frac{d g(x_i, \theta)}{d\theta_j} = 0,$$ one for each $j$. For any one of these to have a ready solution, we would like to be able to separate the $x_i$ terms from the $\theta$ terms. (Everything flows from this key idea, motivated by the Principle of Mathematical Laziness: do as little work as possible; think ahead before computing; tackle easy versions of hard problems first.) The most general way to do this is for the equations to take the form $$\sum_i \left(\eta_j(\theta) \tau_j(x_i) - \alpha_j(\theta)\right) = \eta_j(\theta)\sum_i \tau_j(x_i) - n \alpha_j(\theta) $$ for known functions $\eta_j$, $\tau_j$, and $\alpha_j$, for then the solution is obtained by solving the simultaneous equations $$\frac{n\alpha_j(\theta)}{\eta_j(\theta)}= \sum_i \tau_j(x_i)$$ for $\theta$. In general these will be difficult to solve, but provided the set of values of $\left(\frac{n\alpha_j(\theta)}{\eta_j(\theta)}\right)$ give full information about $\theta$, we could simply use this vector in place of $\theta$ itself (thereby somewhat generalizing the idea of a "closed form" solution, but in a highly productive way). In such a case, integrating with respect to $\theta_j$ yields $$g(x, \theta) = \tau_j(x)\int^\theta \eta_j(\theta) d\theta_j - \int^\theta \alpha_j(\theta) d\theta_j + B(x, \theta_j')$$ (where $\theta_j'$ stands for all the components of $\theta$ except $\theta_j$). Because the left hand side is functionally independent of $\theta_j$, we must have that $\tau_j(x)=T(x)$ for some fixed function $T$; that $B$ must not depend on $\theta$ at all; and the $\eta_j$ are derivatives of some function $H(\theta)$ and the $\alpha_j$ are derivatives of some other function $A(\theta)$, both of them functionally independent of the data. Whence $$g(x, \theta) = H(\theta)T(x) - A(\theta) + B(x).$$ Densities that can be written in this form make up the well-known Koopman-Pitman-Darmois, or exponential, family. It comprises important parametric families, both continuous and discrete, including Gamma, Normal, Chi-squared, Poisson, Multinomial, and many others.
Which distributions have closed-form solutions for maximum likelihood estimation? Without any appreciable loss of generality we may assume that the probability density (or mass) $f(x_i)$ for any observation $x_i$ (out of $n$ observations) is strictly positive, enabling us to write
12,732
Which distributions have closed-form solutions for maximum likelihood estimation?
I don't know if I could list them all. The exponential, normal and binomial come to mind and they all fall into the class of exponential families. The exponential family has its sufficient statistic in the exponent and the mle is often a nice function of this sufficient statistic.
Which distributions have closed-form solutions for maximum likelihood estimation?
I don't know if I could list them all. The exponential, normal and binomial come to mind and they all fall into the class of exponential families. The exponential family has its sufficient statistic
Which distributions have closed-form solutions for maximum likelihood estimation? I don't know if I could list them all. The exponential, normal and binomial come to mind and they all fall into the class of exponential families. The exponential family has its sufficient statistic in the exponent and the mle is often a nice function of this sufficient statistic.
Which distributions have closed-form solutions for maximum likelihood estimation? I don't know if I could list them all. The exponential, normal and binomial come to mind and they all fall into the class of exponential families. The exponential family has its sufficient statistic
12,733
Variable importance from GLMNET
As far as I know glmnet does not calculate the standard errors of regression coefficients (since it fits model parameters using cyclic coordinate descent). So, if you need standardized regression coefficients, you will need to use some other method (e.g. glm) Having said that, if the explanatory variables are standardized before the fit and glmnet is called with "standardize=FALSE", then the less important coefficients will be smaller than the more important ones - so you could rank them just by their magnitude. This becomes even more pronounced with non-trivial amount shrinkage (i.e. non-zero lambda) Hope this helps..
Variable importance from GLMNET
As far as I know glmnet does not calculate the standard errors of regression coefficients (since it fits model parameters using cyclic coordinate descent). So, if you need standardized regression coef
Variable importance from GLMNET As far as I know glmnet does not calculate the standard errors of regression coefficients (since it fits model parameters using cyclic coordinate descent). So, if you need standardized regression coefficients, you will need to use some other method (e.g. glm) Having said that, if the explanatory variables are standardized before the fit and glmnet is called with "standardize=FALSE", then the less important coefficients will be smaller than the more important ones - so you could rank them just by their magnitude. This becomes even more pronounced with non-trivial amount shrinkage (i.e. non-zero lambda) Hope this helps..
Variable importance from GLMNET As far as I know glmnet does not calculate the standard errors of regression coefficients (since it fits model parameters using cyclic coordinate descent). So, if you need standardized regression coef
12,734
Variable importance from GLMNET
To get the coefficient in a space that lets you directly compare their importance, you have to standardize them. I wrote a note on Thinklab to discuss standardization of logistic regression coefficients. (Very) Long story short, I advise to use the Agresti method: # if X is the input matrix of the glmnet function, # and cv.result is your glmnet object: sds <- apply(X, 2, sd) cs <- as.matrix(coef(cv.result, s = "lambda.min")) std_coefs <- coefs[-1, 1] * sds If you relied on internal standardization by glmnet (default option standardize = TRUE), these standardized coefficients are actually the ones resulting from the fitting step, before retransformation by glmnet in the original space (see another note :-) ).
Variable importance from GLMNET
To get the coefficient in a space that lets you directly compare their importance, you have to standardize them. I wrote a note on Thinklab to discuss standardization of logistic regression coefficien
Variable importance from GLMNET To get the coefficient in a space that lets you directly compare their importance, you have to standardize them. I wrote a note on Thinklab to discuss standardization of logistic regression coefficients. (Very) Long story short, I advise to use the Agresti method: # if X is the input matrix of the glmnet function, # and cv.result is your glmnet object: sds <- apply(X, 2, sd) cs <- as.matrix(coef(cv.result, s = "lambda.min")) std_coefs <- coefs[-1, 1] * sds If you relied on internal standardization by glmnet (default option standardize = TRUE), these standardized coefficients are actually the ones resulting from the fitting step, before retransformation by glmnet in the original space (see another note :-) ).
Variable importance from GLMNET To get the coefficient in a space that lets you directly compare their importance, you have to standardize them. I wrote a note on Thinklab to discuss standardization of logistic regression coefficien
12,735
Is there i.i.d. assumption on logistic regression?
From your previous question you learned that GLM is described in terms of probability distribution, linear predictor $\eta$ and link function $g$ and is described as $$ \begin{align} \eta &= X\beta \\ E(Y|X) &= \mu = g^{-1}(\eta) \end{align} $$ where $g$ is a logit link function and $Y$ is assumed to follow a Bernoulli distribution $$ Y_i \sim \mathcal{B}(\mu_i) $$ each $Y_i$ follows Bernoulli distribution with it's own mean $\mu_i$ that is conditional on $X$. We are not assuming that each $Y_i$ comes from the same distribution, with the same mean (this would be the intercept-only model $Y_i = g^{-1}(\mu)$), but that they all have different means. We assume that $Y_i$'s are independent, i.e. we do not have to worry about things such as autocorrelation between subsequent $Y_i$ values etc. The i.i.d. assumption is related to errors in linear regression (i.e. Gaussian GLM), where the model is $$ y_i = \beta_0 + \beta_1 x_i + \varepsilon_i = \mu_i + \varepsilon_i $$ where $\varepsilon_i \sim \mathcal{N}(0, \sigma^2)$, so we have i.i.d. noise around $\mu_i$. This is why are interested in residuals diagnostics and pay attention to the residuals vs. fitted plot. Now, in case of GLM's like logistic regression it's not that simple since there is no additive noise term like with Gaussian model (see here, here and here). We still want residuals to be "random" around zero and we don't want to see any trends in them because they would suggest that there are some effects that are not accounted for in the model, but we don't assume that they are normal and/or i.i.d.. See also the On the importance of the i.i.d. assumption in statistical learning thread. As a sidenote, notice that we can even drop the assumption that each $Y_i$ comes from the same kind of distribution. There are (non-GLM) models that assume that different $Y_i$'s can have different distributions with different parameters, i.e. that your data comes from a mixture of different distributions. In such case we would also assume that the $Y_i$ values are independent, since dependent values, coming from different distributions with different parameters (i.e. typical real-world data) is something that in most cases would be too complicated to model (often impossible).
Is there i.i.d. assumption on logistic regression?
From your previous question you learned that GLM is described in terms of probability distribution, linear predictor $\eta$ and link function $g$ and is described as $$ \begin{align} \eta &= X\beta \\
Is there i.i.d. assumption on logistic regression? From your previous question you learned that GLM is described in terms of probability distribution, linear predictor $\eta$ and link function $g$ and is described as $$ \begin{align} \eta &= X\beta \\ E(Y|X) &= \mu = g^{-1}(\eta) \end{align} $$ where $g$ is a logit link function and $Y$ is assumed to follow a Bernoulli distribution $$ Y_i \sim \mathcal{B}(\mu_i) $$ each $Y_i$ follows Bernoulli distribution with it's own mean $\mu_i$ that is conditional on $X$. We are not assuming that each $Y_i$ comes from the same distribution, with the same mean (this would be the intercept-only model $Y_i = g^{-1}(\mu)$), but that they all have different means. We assume that $Y_i$'s are independent, i.e. we do not have to worry about things such as autocorrelation between subsequent $Y_i$ values etc. The i.i.d. assumption is related to errors in linear regression (i.e. Gaussian GLM), where the model is $$ y_i = \beta_0 + \beta_1 x_i + \varepsilon_i = \mu_i + \varepsilon_i $$ where $\varepsilon_i \sim \mathcal{N}(0, \sigma^2)$, so we have i.i.d. noise around $\mu_i$. This is why are interested in residuals diagnostics and pay attention to the residuals vs. fitted plot. Now, in case of GLM's like logistic regression it's not that simple since there is no additive noise term like with Gaussian model (see here, here and here). We still want residuals to be "random" around zero and we don't want to see any trends in them because they would suggest that there are some effects that are not accounted for in the model, but we don't assume that they are normal and/or i.i.d.. See also the On the importance of the i.i.d. assumption in statistical learning thread. As a sidenote, notice that we can even drop the assumption that each $Y_i$ comes from the same kind of distribution. There are (non-GLM) models that assume that different $Y_i$'s can have different distributions with different parameters, i.e. that your data comes from a mixture of different distributions. In such case we would also assume that the $Y_i$ values are independent, since dependent values, coming from different distributions with different parameters (i.e. typical real-world data) is something that in most cases would be too complicated to model (often impossible).
Is there i.i.d. assumption on logistic regression? From your previous question you learned that GLM is described in terms of probability distribution, linear predictor $\eta$ and link function $g$ and is described as $$ \begin{align} \eta &= X\beta \\
12,736
Is there i.i.d. assumption on logistic regression?
As has been stated, while we often consider the case of iid errors in linear regression, this does not have a direct equivalent in most generalized linear models (including logistic regression). In logistic regression, we typically employ the assumption of independence of outcomes that all have a very strict relation (i.e. linear effects on the log probabilities). But these result in random variables that are not identical, nor are they decomposable into a constant term plus an iid error as is the case with linear regression. If you really want to show that the responses have some sort of iid relation, then follow me for the next paragraph. Just know that this idea is a little off the beaten path; you may not get full credit for this response on a final if your professor is lacking in patience. You maybe familiar with the inverse-cdf method for generating random variables. If not, here's a refresher: if $X$ has cumulative distribution function $F_X$, then I can produce random draws from $X$ by first taking random draws $q \sim \text{uniform(0,1)}$ then calculating $X = F_X^{-1}(q)$. How does this relate to logistic regression? Well, we could think that the generating process for our responses has two parts; a fixed part relating the covariates to the probabilities of success, and a random part that determines the value of the random variable conditional on the fixed part. The fixed part is defined by the link function of logistic regression, i.e. $p = \text{expit}(\beta_o + \beta_1 x)$. For the random part, let's define $F_Y( y | p)$ to be the cdf for a Bernoulli distribution with probability $p$. Then we can think of the response variable $Y_i$ being generated by the following three steps: 1.) $p_i = \text{expit}(\beta_o + \beta_1 x_i)$ 2.) $q_i \sim\text{uniform(0,1)}$ 3.) $Y_i = F^{-1}(q_i | p_i)$ Then the standard assumption in logistic regression is that $q_i$ is iid.
Is there i.i.d. assumption on logistic regression?
As has been stated, while we often consider the case of iid errors in linear regression, this does not have a direct equivalent in most generalized linear models (including logistic regression). In lo
Is there i.i.d. assumption on logistic regression? As has been stated, while we often consider the case of iid errors in linear regression, this does not have a direct equivalent in most generalized linear models (including logistic regression). In logistic regression, we typically employ the assumption of independence of outcomes that all have a very strict relation (i.e. linear effects on the log probabilities). But these result in random variables that are not identical, nor are they decomposable into a constant term plus an iid error as is the case with linear regression. If you really want to show that the responses have some sort of iid relation, then follow me for the next paragraph. Just know that this idea is a little off the beaten path; you may not get full credit for this response on a final if your professor is lacking in patience. You maybe familiar with the inverse-cdf method for generating random variables. If not, here's a refresher: if $X$ has cumulative distribution function $F_X$, then I can produce random draws from $X$ by first taking random draws $q \sim \text{uniform(0,1)}$ then calculating $X = F_X^{-1}(q)$. How does this relate to logistic regression? Well, we could think that the generating process for our responses has two parts; a fixed part relating the covariates to the probabilities of success, and a random part that determines the value of the random variable conditional on the fixed part. The fixed part is defined by the link function of logistic regression, i.e. $p = \text{expit}(\beta_o + \beta_1 x)$. For the random part, let's define $F_Y( y | p)$ to be the cdf for a Bernoulli distribution with probability $p$. Then we can think of the response variable $Y_i$ being generated by the following three steps: 1.) $p_i = \text{expit}(\beta_o + \beta_1 x_i)$ 2.) $q_i \sim\text{uniform(0,1)}$ 3.) $Y_i = F^{-1}(q_i | p_i)$ Then the standard assumption in logistic regression is that $q_i$ is iid.
Is there i.i.d. assumption on logistic regression? As has been stated, while we often consider the case of iid errors in linear regression, this does not have a direct equivalent in most generalized linear models (including logistic regression). In lo
12,737
Why use group lasso instead of lasso?
Intuitively speaking, the group lasso can be preferred to the lasso since it provides a means for us to incorporate (a certain type of) additional information into our estimate for the true coefficient $\beta^*$. As an extreme scenario, considering the following: With $y \sim \mathcal{N} (X \beta^*, \sigma^2 I )$, put $S = \{j : \beta^*_j \neq 0 \}$ as the support of $\beta^*$. Consider the "oracle" estimator $$\hat{\beta} = \arg\min_{\beta} \|y - X \beta\|_2^2 + \lambda \left( |S|^{1/2} \|\beta_S\|_2 + (p-|S|)^{1/2} \|\beta_{S^C}\|_2 \right),$$ which is the group lasso with two groups--one the true support and one the complement. Let $\lambda_{max}$ be the smallest value of $\lambda$ that makes $\hat{\beta} = 0$. Due to the nature of the group lasso penalty, we know that at $\lambda$ moves from $\lambda_{max}$ to $\lambda_{max} - \epsilon$ (for some small $\epsilon > 0$), exactly one group will enter into support of $\hat{\beta}$, which is popularly considered as an estimate for $S$. Due do our grouping, with high probability, the selected group will be $S$, and we'll have done a perfect job. In practice, we don't select the groups this well. However, the groups, despite being finer than the extreme scenario above, will still help us: the choice would still be made between a group of true covariates and a group of untrue covariates. We're still borrowing strength. This is formalized here. They show, under some conditions, that the an upper bound on the prediction error of the group lasso is lower than a lower bound on the prediction error of the plain lasso. That is, they proved that the grouping makes our estimation do better. For your second question: The (plain) lasso penalty is piecewise linear, and this gives rise to the piecewise linear solution path. Intuitively, in the group lasso case, the penalty is no longer piecewise linear, so we no longer have this property. A great reference on piecewise linearity of solution paths is here. See their proposition 1. Let $L(\beta) = \|y - X \beta\|_2^2$ and $J(\beta) = \sum_{g \in G} |g|^{1/2} \|\beta_g\|_2$. They show that the solution path of the group lasso is linear if and only if $$\left( \nabla^2L(\hat{\beta}) + \lambda \nabla^2 J(\hat{\beta}) \right)^{-1} \nabla J(\hat{\beta})$$ is piecewise constant. Of course, it isn't since our penalty $J$ has global curvature.
Why use group lasso instead of lasso?
Intuitively speaking, the group lasso can be preferred to the lasso since it provides a means for us to incorporate (a certain type of) additional information into our estimate for the true coefficien
Why use group lasso instead of lasso? Intuitively speaking, the group lasso can be preferred to the lasso since it provides a means for us to incorporate (a certain type of) additional information into our estimate for the true coefficient $\beta^*$. As an extreme scenario, considering the following: With $y \sim \mathcal{N} (X \beta^*, \sigma^2 I )$, put $S = \{j : \beta^*_j \neq 0 \}$ as the support of $\beta^*$. Consider the "oracle" estimator $$\hat{\beta} = \arg\min_{\beta} \|y - X \beta\|_2^2 + \lambda \left( |S|^{1/2} \|\beta_S\|_2 + (p-|S|)^{1/2} \|\beta_{S^C}\|_2 \right),$$ which is the group lasso with two groups--one the true support and one the complement. Let $\lambda_{max}$ be the smallest value of $\lambda$ that makes $\hat{\beta} = 0$. Due to the nature of the group lasso penalty, we know that at $\lambda$ moves from $\lambda_{max}$ to $\lambda_{max} - \epsilon$ (for some small $\epsilon > 0$), exactly one group will enter into support of $\hat{\beta}$, which is popularly considered as an estimate for $S$. Due do our grouping, with high probability, the selected group will be $S$, and we'll have done a perfect job. In practice, we don't select the groups this well. However, the groups, despite being finer than the extreme scenario above, will still help us: the choice would still be made between a group of true covariates and a group of untrue covariates. We're still borrowing strength. This is formalized here. They show, under some conditions, that the an upper bound on the prediction error of the group lasso is lower than a lower bound on the prediction error of the plain lasso. That is, they proved that the grouping makes our estimation do better. For your second question: The (plain) lasso penalty is piecewise linear, and this gives rise to the piecewise linear solution path. Intuitively, in the group lasso case, the penalty is no longer piecewise linear, so we no longer have this property. A great reference on piecewise linearity of solution paths is here. See their proposition 1. Let $L(\beta) = \|y - X \beta\|_2^2$ and $J(\beta) = \sum_{g \in G} |g|^{1/2} \|\beta_g\|_2$. They show that the solution path of the group lasso is linear if and only if $$\left( \nabla^2L(\hat{\beta}) + \lambda \nabla^2 J(\hat{\beta}) \right)^{-1} \nabla J(\hat{\beta})$$ is piecewise constant. Of course, it isn't since our penalty $J$ has global curvature.
Why use group lasso instead of lasso? Intuitively speaking, the group lasso can be preferred to the lasso since it provides a means for us to incorporate (a certain type of) additional information into our estimate for the true coefficien
12,738
Why use group lasso instead of lasso?
Ben's answer is the most general result. But the intuitive answer to the OP is motivated by the case of categorical predictors, which are usually encoded as multiple dummy variables: one for each category. It makes sense in many analyses to consider these dummy variables (representing one categorical predictor) together rather than separately. If you have a categorical variable with, say, five levels, a straight lasso might leave two in and three out. How do you handle this in a principled manner? Decide to vote? Literally use the dummy variables instead of the more meaningful categorical? How does your dummy encoding affect your choices? As they say in the introduction of The group lasso for logistic regression, it mentions: Already for the special case in linear regression when not only continuous but also categorical predictors (factors) are present, the lasso solution is not satisfactory as it only selects individ- ual dummy variables instead of whole factors. Moreover, the lasso solution depends on how the dummy variables are encoded. Choosing different contrasts for a categorical predictor will produce different solutions in general. As Ben points out, there are also more subtle links between predictors that might indicate that they should either be in or out together. But categorical variables are the poster child for group lasso.
Why use group lasso instead of lasso?
Ben's answer is the most general result. But the intuitive answer to the OP is motivated by the case of categorical predictors, which are usually encoded as multiple dummy variables: one for each cate
Why use group lasso instead of lasso? Ben's answer is the most general result. But the intuitive answer to the OP is motivated by the case of categorical predictors, which are usually encoded as multiple dummy variables: one for each category. It makes sense in many analyses to consider these dummy variables (representing one categorical predictor) together rather than separately. If you have a categorical variable with, say, five levels, a straight lasso might leave two in and three out. How do you handle this in a principled manner? Decide to vote? Literally use the dummy variables instead of the more meaningful categorical? How does your dummy encoding affect your choices? As they say in the introduction of The group lasso for logistic regression, it mentions: Already for the special case in linear regression when not only continuous but also categorical predictors (factors) are present, the lasso solution is not satisfactory as it only selects individ- ual dummy variables instead of whole factors. Moreover, the lasso solution depends on how the dummy variables are encoded. Choosing different contrasts for a categorical predictor will produce different solutions in general. As Ben points out, there are also more subtle links between predictors that might indicate that they should either be in or out together. But categorical variables are the poster child for group lasso.
Why use group lasso instead of lasso? Ben's answer is the most general result. But the intuitive answer to the OP is motivated by the case of categorical predictors, which are usually encoded as multiple dummy variables: one for each cate
12,739
How to transform negative values to logarithms?
Since logarithm is only defined for positive numbers, you can't take the logarithm of negative values. However, if you are aiming at obtaining a better distribution for your data, you can apply the following transformation. Suppose you have skewed negative data: x <- rlnorm(n = 1e2, meanlog = 0, sdlog = 1) x <- x - 5 plot(density(x)) then you can apply a first transformation to make your data lie in $(-1,1)$: z <- (x - min(x)) / (max(x) - min(x)) * 2 - 1 z <- z[-min(z)] z <- z[-max(z)] min(z); max(z) and finally apply the inverse hyperbolic tangent: t <- atanh(z) plot(density(t)) Now, your data look approximately normally distributed. This is also called Fisher transformation.
How to transform negative values to logarithms?
Since logarithm is only defined for positive numbers, you can't take the logarithm of negative values. However, if you are aiming at obtaining a better distribution for your data, you can apply the fo
How to transform negative values to logarithms? Since logarithm is only defined for positive numbers, you can't take the logarithm of negative values. However, if you are aiming at obtaining a better distribution for your data, you can apply the following transformation. Suppose you have skewed negative data: x <- rlnorm(n = 1e2, meanlog = 0, sdlog = 1) x <- x - 5 plot(density(x)) then you can apply a first transformation to make your data lie in $(-1,1)$: z <- (x - min(x)) / (max(x) - min(x)) * 2 - 1 z <- z[-min(z)] z <- z[-max(z)] min(z); max(z) and finally apply the inverse hyperbolic tangent: t <- atanh(z) plot(density(t)) Now, your data look approximately normally distributed. This is also called Fisher transformation.
How to transform negative values to logarithms? Since logarithm is only defined for positive numbers, you can't take the logarithm of negative values. However, if you are aiming at obtaining a better distribution for your data, you can apply the fo
12,740
How to transform negative values to logarithms?
This has been covered in detail in the comments, but there still isn't an answer stating this. So for the benefit of future readers: Please DON'T fiddle with your negative values (especially differences!) so that you can apply a log transformation. Strategies such as adding constants introduce bias; this can work out alright if done with care but can also lead to completely incorrect and uninterpretable results. See this thread for more detail about this: Interpreting log-log regression with log(1+x) as independent variable. Instead, use a transformation that handles negative values naturally. The cube root transformation is an obvious candidate here, as it is simple, easier to interpret than complex options such as rescaled inverse hyperbolic tangents, and has the advantage that the interesting and special case of 0 is preserved. As Nick Cox mentions, you will need to implement this carefully yourself because just raising your values to the power of 1/3 will not work in R. Instead, you'll need something like sign(x) * (abs(x))^(1/3). More generally, it's best to think carefully about the nature of the data and the goal of the analysis while deciding on a transformation, and not letting canned procedures guide how you handle the data.
How to transform negative values to logarithms?
This has been covered in detail in the comments, but there still isn't an answer stating this. So for the benefit of future readers: Please DON'T fiddle with your negative values (especially differenc
How to transform negative values to logarithms? This has been covered in detail in the comments, but there still isn't an answer stating this. So for the benefit of future readers: Please DON'T fiddle with your negative values (especially differences!) so that you can apply a log transformation. Strategies such as adding constants introduce bias; this can work out alright if done with care but can also lead to completely incorrect and uninterpretable results. See this thread for more detail about this: Interpreting log-log regression with log(1+x) as independent variable. Instead, use a transformation that handles negative values naturally. The cube root transformation is an obvious candidate here, as it is simple, easier to interpret than complex options such as rescaled inverse hyperbolic tangents, and has the advantage that the interesting and special case of 0 is preserved. As Nick Cox mentions, you will need to implement this carefully yourself because just raising your values to the power of 1/3 will not work in R. Instead, you'll need something like sign(x) * (abs(x))^(1/3). More generally, it's best to think carefully about the nature of the data and the goal of the analysis while deciding on a transformation, and not letting canned procedures guide how you handle the data.
How to transform negative values to logarithms? This has been covered in detail in the comments, but there still isn't an answer stating this. So for the benefit of future readers: Please DON'T fiddle with your negative values (especially differenc
12,741
Is R-squared value appropriate for comparing models?
I think the crucial part to consider in answering your question is I'm trying to identify the best model to predict the prices of automobiles because this statement implies something about why you want to use the model. Model choice and evaluation should be based on what you want to achieve with your fitted values. First, lets recap what $R^2$ does: It computes a scaled measure based on the quadratic loss function, which I am sure you are already aware of. To see this, define residual $e_i = y_i - \hat{y}_i$ for your i-th observation $y_i$ and the corresponding fitted value $\hat{y}_i$. Using the convenient notation $SSR := \sum_{i=1}^Ne_i^2$, $SST:=\sum_{i=1}^N(y_i - \bar{y})^2$, $R^2$ is simply defined as $R^2 = 1 - SSR/SST$. Second, let us see what using $R^2$ for model choice/evaluation means. Suppose we choose from a set of predictions $\bar{Y}_M$ that were generated using a model $M:M \in \mathcal{M}$, where $\mathcal{M}$ is the collection of models under consideration (in your example, this collection would contain Neural networks, random forests, elastic nets, ...). Since $SST$ will remain constant amongst all the models, if minimizing $R^2$ you will choose exactly the model that minimizes $SSR$. In other words, you will choose $M \in \mathcal{M}$ that produces the minimal square error loss! Third, let us consider why $R^2$ or equivalently, $SSR$ might be interesting for model choice. Traditionally, the square loss ($L^2$ norm) is used for three reasons: (1) It is easier computable than Least Absolute Deviations (LAD, the $L^1$ norm) because no absolute value appears in the computation, (2) it punishes fitted values that are far off from the actual value much more than LAD (in a squared rather than an absolute sense) and thereby makes sure we have less extreme outliers, (3) it is symmetric: Over- or underestimating the price of a car is considered to be equally bad. Fourth (and last), let us see if this is what you need for your predictions. The point that might be of most interest here is (3) from the last paragraph. Suppose you want to take a neutral stance, and you are neither buyer nor seller of a car. Then, $R^2$ can make sense: You are impartial, and you wish to punish deviations to over- or underpricing exactly identically. The same applies if you just want to model the relation between the quantities without wishing to predict unobserved values. Now suppose you are working for a consumer/buyer on a tight budget: In this situation, you might want to punish overestimation of the price in a quadratic sense, but underestimation in an $L^p$ sense, where $1 \leqslant p <2$. For $p=1$, you would punish in an absolute deviation sense. This can be seen to reflect the goals and intentions of the buyer, and biasing the estimation downward might be of interest for him/her. Conversely, you could flip the thinking if you were to model the price predictions for the seller. Needless to say, any norm $L^p$ could be chosen to reflect the preferences of the modeller/the agent you model for. You can also punish outside of the $L^p$ norm entirely, and use constant, exponential, or log loss on one side and a different loss on the other. In summary, model choice/evaluation cannot be considered independently of the model's aim.
Is R-squared value appropriate for comparing models?
I think the crucial part to consider in answering your question is I'm trying to identify the best model to predict the prices of automobiles because this statement implies something about why you w
Is R-squared value appropriate for comparing models? I think the crucial part to consider in answering your question is I'm trying to identify the best model to predict the prices of automobiles because this statement implies something about why you want to use the model. Model choice and evaluation should be based on what you want to achieve with your fitted values. First, lets recap what $R^2$ does: It computes a scaled measure based on the quadratic loss function, which I am sure you are already aware of. To see this, define residual $e_i = y_i - \hat{y}_i$ for your i-th observation $y_i$ and the corresponding fitted value $\hat{y}_i$. Using the convenient notation $SSR := \sum_{i=1}^Ne_i^2$, $SST:=\sum_{i=1}^N(y_i - \bar{y})^2$, $R^2$ is simply defined as $R^2 = 1 - SSR/SST$. Second, let us see what using $R^2$ for model choice/evaluation means. Suppose we choose from a set of predictions $\bar{Y}_M$ that were generated using a model $M:M \in \mathcal{M}$, where $\mathcal{M}$ is the collection of models under consideration (in your example, this collection would contain Neural networks, random forests, elastic nets, ...). Since $SST$ will remain constant amongst all the models, if minimizing $R^2$ you will choose exactly the model that minimizes $SSR$. In other words, you will choose $M \in \mathcal{M}$ that produces the minimal square error loss! Third, let us consider why $R^2$ or equivalently, $SSR$ might be interesting for model choice. Traditionally, the square loss ($L^2$ norm) is used for three reasons: (1) It is easier computable than Least Absolute Deviations (LAD, the $L^1$ norm) because no absolute value appears in the computation, (2) it punishes fitted values that are far off from the actual value much more than LAD (in a squared rather than an absolute sense) and thereby makes sure we have less extreme outliers, (3) it is symmetric: Over- or underestimating the price of a car is considered to be equally bad. Fourth (and last), let us see if this is what you need for your predictions. The point that might be of most interest here is (3) from the last paragraph. Suppose you want to take a neutral stance, and you are neither buyer nor seller of a car. Then, $R^2$ can make sense: You are impartial, and you wish to punish deviations to over- or underpricing exactly identically. The same applies if you just want to model the relation between the quantities without wishing to predict unobserved values. Now suppose you are working for a consumer/buyer on a tight budget: In this situation, you might want to punish overestimation of the price in a quadratic sense, but underestimation in an $L^p$ sense, where $1 \leqslant p <2$. For $p=1$, you would punish in an absolute deviation sense. This can be seen to reflect the goals and intentions of the buyer, and biasing the estimation downward might be of interest for him/her. Conversely, you could flip the thinking if you were to model the price predictions for the seller. Needless to say, any norm $L^p$ could be chosen to reflect the preferences of the modeller/the agent you model for. You can also punish outside of the $L^p$ norm entirely, and use constant, exponential, or log loss on one side and a different loss on the other. In summary, model choice/evaluation cannot be considered independently of the model's aim.
Is R-squared value appropriate for comparing models? I think the crucial part to consider in answering your question is I'm trying to identify the best model to predict the prices of automobiles because this statement implies something about why you w
12,742
Is there a statistical test to compare two samples of size 1 and 3?
Note gung's question; it matters. I will assume that the treatment was the same for every tank in the treatment group. If you can argue the variance would be equal for the two groups (which you would typically assume for a two sample t-test anyway), you can do a test. You just can't check that assumption, no matter how badly violated it might be. The concerns expressed in this answer to a related question are even more relevant to your situation, but there's less you can do about it. [You ask about it being reasonable to assume the variances are equal. We can't answer that for you, that's something you'd have to convince subject matter experts (i.e. ecologists) was a reasonable assumption. Are there other studies where such levels have been measured under both treatment and control? Others where similar tests (t-tests or anova especially - I bet you can find a better precedent) have been done or similar assumptions made? Some form of general reasoning you can see to apply?] If $\bar{x}$ is the sample mean of the treatment and $\bar{y}$ is the mean of the control, and both are from normal distributions with variance $\sigma^2$, then $\bar{x}-\bar{y}$ will have mean $\mu_x - \mu_y$ and variance $\sigma^2 (1/n_x + 1/n_y)$ irrespective of whether one of the $n$'s is 1. So when $n_y$ is 1, $$ \frac{(\bar{x}-\bar{y})}{s_x\sqrt{1/n_x+1}} $$ (where $s_x$ is the standard deviation computed from the treatments) will be $t$-distributed (with $n_x - 1$ degrees of freedom) under the null. You may notice that with the best available estimate of $\sigma$, $s_x$ used for $s_p$, this is exactly like the ordinary two-sample t-test formula with $n_y$ set to 1. Edit: Here's a simulated power curve for this test. The sample size at the null was 10000, at the other points was 1000. As you see, the rejection rate at the null is 0.05, and the power curve, while it requires a large difference in population means to have decent power, has the right shape. That is, this test does what it is supposed to. (End edit) With sample sizes so small, this will be somewhat sensitive to distributional assumptions, however. If you're prepared to make different assumptions, or want to test equality of some other population quantity, some test may still be possible. So all is not lost... but where possible, it's generally better to have at least some replication in both groups.
Is there a statistical test to compare two samples of size 1 and 3?
Note gung's question; it matters. I will assume that the treatment was the same for every tank in the treatment group. If you can argue the variance would be equal for the two groups (which you would
Is there a statistical test to compare two samples of size 1 and 3? Note gung's question; it matters. I will assume that the treatment was the same for every tank in the treatment group. If you can argue the variance would be equal for the two groups (which you would typically assume for a two sample t-test anyway), you can do a test. You just can't check that assumption, no matter how badly violated it might be. The concerns expressed in this answer to a related question are even more relevant to your situation, but there's less you can do about it. [You ask about it being reasonable to assume the variances are equal. We can't answer that for you, that's something you'd have to convince subject matter experts (i.e. ecologists) was a reasonable assumption. Are there other studies where such levels have been measured under both treatment and control? Others where similar tests (t-tests or anova especially - I bet you can find a better precedent) have been done or similar assumptions made? Some form of general reasoning you can see to apply?] If $\bar{x}$ is the sample mean of the treatment and $\bar{y}$ is the mean of the control, and both are from normal distributions with variance $\sigma^2$, then $\bar{x}-\bar{y}$ will have mean $\mu_x - \mu_y$ and variance $\sigma^2 (1/n_x + 1/n_y)$ irrespective of whether one of the $n$'s is 1. So when $n_y$ is 1, $$ \frac{(\bar{x}-\bar{y})}{s_x\sqrt{1/n_x+1}} $$ (where $s_x$ is the standard deviation computed from the treatments) will be $t$-distributed (with $n_x - 1$ degrees of freedom) under the null. You may notice that with the best available estimate of $\sigma$, $s_x$ used for $s_p$, this is exactly like the ordinary two-sample t-test formula with $n_y$ set to 1. Edit: Here's a simulated power curve for this test. The sample size at the null was 10000, at the other points was 1000. As you see, the rejection rate at the null is 0.05, and the power curve, while it requires a large difference in population means to have decent power, has the right shape. That is, this test does what it is supposed to. (End edit) With sample sizes so small, this will be somewhat sensitive to distributional assumptions, however. If you're prepared to make different assumptions, or want to test equality of some other population quantity, some test may still be possible. So all is not lost... but where possible, it's generally better to have at least some replication in both groups.
Is there a statistical test to compare two samples of size 1 and 3? Note gung's question; it matters. I will assume that the treatment was the same for every tank in the treatment group. If you can argue the variance would be equal for the two groups (which you would
12,743
Comparing clusterings: Rand Index vs Variation of Information
In my opinion, there are huge differences. The Rand index is very much affected by the granularity of the clusterings on which it operates. In what follows I'll use the Mirkin distance, which is an adjusted form of the Rand index (easy to see, but see e.g. Meila). I'll also use the split/join distance, which is also mentioned in some of Meila's papers (disclaimer: split/join distance was proposed by me). Suppose a universe of one hundred elements. I'll use Top to denote the clustering with a single cluster containing all elements, Bottom to denote the clustering where all nodes are in separate singleton sets, Left to denote the clustering {{1,2,..10},{11,12..20},{21,22..30}, ..., {91,92,..100}}, and Right to denote the clustering {{1,11,..91}, {2,12,..92}, {3,13,..93}, ..., {10,20,..100}}. To my mind, Bottom and Top are consistent (nesting) clusters, whereas Left and Right are maximally conflicting clusters. The distances from the mentioned metrics for these two pairwise comparisons are as follows: Top-Bottom Left-Right Mirkin 9900 1800 VI 4.605 4.605 Split/join 99 180 It follows that Mirkin/Rand consider the consistent Top-Bottom pair much further apart than the maximally conflicting Left-Right pair. This is an extreme example to illustrate the point, but Mirkin/Rand are in general very much affected by the granularity of the clusterings on which it operates. The reason underlying this is a quadratic relationship between this metric and cluster sizes, explained by the fact that the counting of pairs of nodes is involved. In effect, the Mirkin distance is a Hamming distance between edge sets of unions of complete graphs induced by clusterings (this is the answer to your question I think). Regarding the diffferences between Variation of Information and Split/Join, the first is more sensitive to certain conflict situations as demonstrated by Meila. That is, Split/Join only considers the best match for each cluster, and disregards the fragmentation that might occur on the remaining part of that cluster, whereas Variation of Information will pick this up. That said, Split/Join is easily interpretable as the number of nodes that need to be moved to obtain one cluster from the other, and in that sense its range is more easily understood; in practice the fragmentation issue may also be not that common. Each of these metrics can be formed as the sum of two distances, namely the distances from each of the two clusterings to their greatest common subclustering. I feel it is often beneficial to work with those separate parts rather than just their sum. The above table then becomes: Top-Bottom Left-Right Mirkin 0,9900 900,900 VI 0,4.605 2.303,2.303 Split/join 0,99 90,90 The subsumption relationship between Top and Bottom becomes immediately clear. It is often quite useful to know whether two clusterings are consistent (i.e. one is (nearly) a subclustering of the other) as a relaxation of the question of whether they are close. A clustering can be quite distant from a gold standard, but still be consistent or nearly consistent. In such a case there may be no reason to consider the clustering bad with respect to that gold standard. Of course, the trivial clusterings Top and Bottom will be consistent with any clustering, so this must be taken into account. Finally, I believe that metrics such as Mirkin, Variation of Information, and Split/Join are the natural tools to compare clusterings. For most applications methods that try to incorporate statistical independence and correct for chance are overly contrived and obfuscate rather than clarify. Second example Consider the following pairs of clusterings: C1 = { { 1, 2, 3, 4, 5, 6, 7, 8}, { 9, 10, 11, 12, 13, 14, 15, 16} } with C2 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {11, 12, 13, 14, 15, 16} } and C3 = { { 1, 2, 3, 4}, {5, 6, 7, 8, 9, 10}, {11, 12, 13, 14, 15, 16} } with { { 1, 2, 3, 4}, {5, 6, 7, 8, 9, 10, 11, 12}, {13, 14, 15, 16} } Here C2 can be formed from C1 by moving nodes 9 and 10 and C3 can be formed from C3 by moving nodes 11 and 12. Both changes are identical ("move two nodes") except for the fact that the sizes of the clusters involved differ. The clustering metrics table for these two examples is this: C1-C2 C3-C4 Mirkin 56 40 VI 0.594 0.520 Split/Join 4 4 It can be seen that Mirkin/Rand and Variation of information are affected by the cluster sizes (and Mirkin to a larger extent; this will be more pronounced as cluster sizes diverge), whereas the Split/Join distance is not (its value is 4 as it "moves" nodes from one clustering to the other always via the largest common subclustering). This may be a desirable trait depending on circumstances. The simple interpretation of Split/Join (number of nodes to move) and its independence of cluster size are worth being aware of. Between Mirkin and Variation of Information I think the latter is very much preferable.
Comparing clusterings: Rand Index vs Variation of Information
In my opinion, there are huge differences. The Rand index is very much affected by the granularity of the clusterings on which it operates. In what follows I'll use the Mirkin distance, which is an ad
Comparing clusterings: Rand Index vs Variation of Information In my opinion, there are huge differences. The Rand index is very much affected by the granularity of the clusterings on which it operates. In what follows I'll use the Mirkin distance, which is an adjusted form of the Rand index (easy to see, but see e.g. Meila). I'll also use the split/join distance, which is also mentioned in some of Meila's papers (disclaimer: split/join distance was proposed by me). Suppose a universe of one hundred elements. I'll use Top to denote the clustering with a single cluster containing all elements, Bottom to denote the clustering where all nodes are in separate singleton sets, Left to denote the clustering {{1,2,..10},{11,12..20},{21,22..30}, ..., {91,92,..100}}, and Right to denote the clustering {{1,11,..91}, {2,12,..92}, {3,13,..93}, ..., {10,20,..100}}. To my mind, Bottom and Top are consistent (nesting) clusters, whereas Left and Right are maximally conflicting clusters. The distances from the mentioned metrics for these two pairwise comparisons are as follows: Top-Bottom Left-Right Mirkin 9900 1800 VI 4.605 4.605 Split/join 99 180 It follows that Mirkin/Rand consider the consistent Top-Bottom pair much further apart than the maximally conflicting Left-Right pair. This is an extreme example to illustrate the point, but Mirkin/Rand are in general very much affected by the granularity of the clusterings on which it operates. The reason underlying this is a quadratic relationship between this metric and cluster sizes, explained by the fact that the counting of pairs of nodes is involved. In effect, the Mirkin distance is a Hamming distance between edge sets of unions of complete graphs induced by clusterings (this is the answer to your question I think). Regarding the diffferences between Variation of Information and Split/Join, the first is more sensitive to certain conflict situations as demonstrated by Meila. That is, Split/Join only considers the best match for each cluster, and disregards the fragmentation that might occur on the remaining part of that cluster, whereas Variation of Information will pick this up. That said, Split/Join is easily interpretable as the number of nodes that need to be moved to obtain one cluster from the other, and in that sense its range is more easily understood; in practice the fragmentation issue may also be not that common. Each of these metrics can be formed as the sum of two distances, namely the distances from each of the two clusterings to their greatest common subclustering. I feel it is often beneficial to work with those separate parts rather than just their sum. The above table then becomes: Top-Bottom Left-Right Mirkin 0,9900 900,900 VI 0,4.605 2.303,2.303 Split/join 0,99 90,90 The subsumption relationship between Top and Bottom becomes immediately clear. It is often quite useful to know whether two clusterings are consistent (i.e. one is (nearly) a subclustering of the other) as a relaxation of the question of whether they are close. A clustering can be quite distant from a gold standard, but still be consistent or nearly consistent. In such a case there may be no reason to consider the clustering bad with respect to that gold standard. Of course, the trivial clusterings Top and Bottom will be consistent with any clustering, so this must be taken into account. Finally, I believe that metrics such as Mirkin, Variation of Information, and Split/Join are the natural tools to compare clusterings. For most applications methods that try to incorporate statistical independence and correct for chance are overly contrived and obfuscate rather than clarify. Second example Consider the following pairs of clusterings: C1 = { { 1, 2, 3, 4, 5, 6, 7, 8}, { 9, 10, 11, 12, 13, 14, 15, 16} } with C2 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {11, 12, 13, 14, 15, 16} } and C3 = { { 1, 2, 3, 4}, {5, 6, 7, 8, 9, 10}, {11, 12, 13, 14, 15, 16} } with { { 1, 2, 3, 4}, {5, 6, 7, 8, 9, 10, 11, 12}, {13, 14, 15, 16} } Here C2 can be formed from C1 by moving nodes 9 and 10 and C3 can be formed from C3 by moving nodes 11 and 12. Both changes are identical ("move two nodes") except for the fact that the sizes of the clusters involved differ. The clustering metrics table for these two examples is this: C1-C2 C3-C4 Mirkin 56 40 VI 0.594 0.520 Split/Join 4 4 It can be seen that Mirkin/Rand and Variation of information are affected by the cluster sizes (and Mirkin to a larger extent; this will be more pronounced as cluster sizes diverge), whereas the Split/Join distance is not (its value is 4 as it "moves" nodes from one clustering to the other always via the largest common subclustering). This may be a desirable trait depending on circumstances. The simple interpretation of Split/Join (number of nodes to move) and its independence of cluster size are worth being aware of. Between Mirkin and Variation of Information I think the latter is very much preferable.
Comparing clusterings: Rand Index vs Variation of Information In my opinion, there are huge differences. The Rand index is very much affected by the granularity of the clusterings on which it operates. In what follows I'll use the Mirkin distance, which is an ad
12,744
Comparing clusterings: Rand Index vs Variation of Information
The difference between the two methods is subtle. The best way to think about it is to consider the lattice defined by the merge-split operation on clusterings. Both these measures can be reconstructed by defining a function $f$ on a clustering, and then defining the distance between two clusterings by the formula: \[ d(C, C') = f(C) + f(C') - 2f(C \wedge C') \] where $C \wedge C'$ is the join of the two clusterings in the lattice. Now let $C = \{ C_1, C_2, \ldots, C_k\}$ and let $n_i = |C_i|$. Setting $f(C) = \sum n_i^2$ yields the rand index, and setting $f(C) = \sum n_i \log n_i$ yields VI.
Comparing clusterings: Rand Index vs Variation of Information
The difference between the two methods is subtle. The best way to think about it is to consider the lattice defined by the merge-split operation on clusterings. Both these measures can be reconstructe
Comparing clusterings: Rand Index vs Variation of Information The difference between the two methods is subtle. The best way to think about it is to consider the lattice defined by the merge-split operation on clusterings. Both these measures can be reconstructed by defining a function $f$ on a clustering, and then defining the distance between two clusterings by the formula: \[ d(C, C') = f(C) + f(C') - 2f(C \wedge C') \] where $C \wedge C'$ is the join of the two clusterings in the lattice. Now let $C = \{ C_1, C_2, \ldots, C_k\}$ and let $n_i = |C_i|$. Setting $f(C) = \sum n_i^2$ yields the rand index, and setting $f(C) = \sum n_i \log n_i$ yields VI.
Comparing clusterings: Rand Index vs Variation of Information The difference between the two methods is subtle. The best way to think about it is to consider the lattice defined by the merge-split operation on clusterings. Both these measures can be reconstructe
12,745
Interpreting distance from hyperplane in SVM
Let me first answer your question in general. The SVM is not a probabilistic model. One reason is that it does not correspond to a normalizable likelihood. For example in regularized least squares you have the loss function $\sum_i \|y_i - \langle w, x_i\rangle - b\|_2^2$ and the regularizer $\|w\|_2^2$. The weight vector is obtained by minimizing the sum of the two. However this is equivalent to maximizing the log-posterior of $w$ given the data $p(w|(y_1,x_1),...,(y_m,x_m)) \propto 1/Z \exp(-\|w\|_2^2)\prod_i \exp(\|y_i - \langle w, x_i\rangle - b\|_2^2)$ which you can see to be product of a Gaussian likelihood and a Gaussian prior on $w$ ($Z$ makes sure that it normalizes). You get to the Gaussian likelihood from the loss function by flipping its sign and exponentiating it. However, if you do that with the loss-function of the SVM, the log-likelihood is not a normalizeable probabilistic model. There are attempts to turn SVM into one. The most notable one, which is-I think-also implemented in libsvm is: John Platt: Probabilistic outputs for Support Vector Machines and Comparison to Regularized Likelihood Methods (NIPS 1999): http://www.cs.colorado.edu/~mozer/Teaching/syllabi/6622/papers/Platt1999.pdf To answer your question more specificly: The idea in SVMs indeed is that the further a test vector is from the hyperplane the more it belongs to a certain class (except when it's on the wrong side of course). In that sense, support vectors do not belong to the class with high probability because they either are the ones closest to or on the wrong side of the hyperplane. The $\alpha$ value that you get from libsvm has nothing to do with the $\alpha$ in the decision function. It is rather the output of the decision function $\sum_{i \in SV}\alpha_i k(x,x_i) + b$ (and should therefore be properly called $y$). Since $y = \sum_{i \in SV}\alpha_i k(x,x_i) + b = \langle w, \phi(x) \rangle_{\mathcal H} + b$ where $w$ lives in the reproducing kernel Hilbert space, $y$ is proportional to the signed distance to the hyperplane. It would be if you divide by the norm of $w$, which in kernel terms is $\|w\|_{H} = \sqrt{\sum_{i,j\in SV} \alpha_i \alpha_j k(x_i,x_j)}$.
Interpreting distance from hyperplane in SVM
Let me first answer your question in general. The SVM is not a probabilistic model. One reason is that it does not correspond to a normalizable likelihood. For example in regularized least squares you
Interpreting distance from hyperplane in SVM Let me first answer your question in general. The SVM is not a probabilistic model. One reason is that it does not correspond to a normalizable likelihood. For example in regularized least squares you have the loss function $\sum_i \|y_i - \langle w, x_i\rangle - b\|_2^2$ and the regularizer $\|w\|_2^2$. The weight vector is obtained by minimizing the sum of the two. However this is equivalent to maximizing the log-posterior of $w$ given the data $p(w|(y_1,x_1),...,(y_m,x_m)) \propto 1/Z \exp(-\|w\|_2^2)\prod_i \exp(\|y_i - \langle w, x_i\rangle - b\|_2^2)$ which you can see to be product of a Gaussian likelihood and a Gaussian prior on $w$ ($Z$ makes sure that it normalizes). You get to the Gaussian likelihood from the loss function by flipping its sign and exponentiating it. However, if you do that with the loss-function of the SVM, the log-likelihood is not a normalizeable probabilistic model. There are attempts to turn SVM into one. The most notable one, which is-I think-also implemented in libsvm is: John Platt: Probabilistic outputs for Support Vector Machines and Comparison to Regularized Likelihood Methods (NIPS 1999): http://www.cs.colorado.edu/~mozer/Teaching/syllabi/6622/papers/Platt1999.pdf To answer your question more specificly: The idea in SVMs indeed is that the further a test vector is from the hyperplane the more it belongs to a certain class (except when it's on the wrong side of course). In that sense, support vectors do not belong to the class with high probability because they either are the ones closest to or on the wrong side of the hyperplane. The $\alpha$ value that you get from libsvm has nothing to do with the $\alpha$ in the decision function. It is rather the output of the decision function $\sum_{i \in SV}\alpha_i k(x,x_i) + b$ (and should therefore be properly called $y$). Since $y = \sum_{i \in SV}\alpha_i k(x,x_i) + b = \langle w, \phi(x) \rangle_{\mathcal H} + b$ where $w$ lives in the reproducing kernel Hilbert space, $y$ is proportional to the signed distance to the hyperplane. It would be if you divide by the norm of $w$, which in kernel terms is $\|w\|_{H} = \sqrt{\sum_{i,j\in SV} \alpha_i \alpha_j k(x_i,x_j)}$.
Interpreting distance from hyperplane in SVM Let me first answer your question in general. The SVM is not a probabilistic model. One reason is that it does not correspond to a normalizable likelihood. For example in regularized least squares you
12,746
Good online resource with tips on graphing association between two numeric variables under various conditions
I can't think of great online resources off the top of my head, but a nice (and easily downloadable) book chapter that narrates how to visually explore a large, multidimensional data set in a thoughtful way is Brendan O'Connor and Lukas Biewald's chapter (warning: link is directly to a PDF) from Beautiful Data. The chapter is particularly useful as a teaching resource because it incorporates R code into the narrative. Also, upon further reflection, I think John Tukey's classic "Some Graphic and Semigraphic Displays" (conveniently posted on Edward Tufte's website) is a really wonderful, albeit somewhat idiosyncratic, introduction to visualization. For some reason, I seem to be thinking of book chapters...
Good online resource with tips on graphing association between two numeric variables under various c
I can't think of great online resources off the top of my head, but a nice (and easily downloadable) book chapter that narrates how to visually explore a large, multidimensional data set in a thoughtf
Good online resource with tips on graphing association between two numeric variables under various conditions I can't think of great online resources off the top of my head, but a nice (and easily downloadable) book chapter that narrates how to visually explore a large, multidimensional data set in a thoughtful way is Brendan O'Connor and Lukas Biewald's chapter (warning: link is directly to a PDF) from Beautiful Data. The chapter is particularly useful as a teaching resource because it incorporates R code into the narrative. Also, upon further reflection, I think John Tukey's classic "Some Graphic and Semigraphic Displays" (conveniently posted on Edward Tufte's website) is a really wonderful, albeit somewhat idiosyncratic, introduction to visualization. For some reason, I seem to be thinking of book chapters...
Good online resource with tips on graphing association between two numeric variables under various c I can't think of great online resources off the top of my head, but a nice (and easily downloadable) book chapter that narrates how to visually explore a large, multidimensional data set in a thoughtf
12,747
Good online resource with tips on graphing association between two numeric variables under various conditions
Recent references: Kelleher and Wagner 2011 "Ten guidelines for effective data visualization in scientific publications" provides a nice set of rules. The rules, with references (but not the full article) are available without subscription, although university students would likely have full access. United Nations 2009 "Making Data Meaningful" provides a nice overview, with rules and examples, including a section on 'emerging technologies'. Older, but relevant resources SIGGGRAPH provides some excellent tutorials, though lacking examples, including: Senay and Ignatius 1999 "Rules and Principles of Scientific Data Visualization" Domik 1999 "Tutorial on Visualization" A good summary of Tufte can be found here: Globus 1994 "Principles of Information Display for Visualization Practitioners"
Good online resource with tips on graphing association between two numeric variables under various c
Recent references: Kelleher and Wagner 2011 "Ten guidelines for effective data visualization in scientific publications" provides a nice set of rules. The rules, with references (but not the full art
Good online resource with tips on graphing association between two numeric variables under various conditions Recent references: Kelleher and Wagner 2011 "Ten guidelines for effective data visualization in scientific publications" provides a nice set of rules. The rules, with references (but not the full article) are available without subscription, although university students would likely have full access. United Nations 2009 "Making Data Meaningful" provides a nice overview, with rules and examples, including a section on 'emerging technologies'. Older, but relevant resources SIGGGRAPH provides some excellent tutorials, though lacking examples, including: Senay and Ignatius 1999 "Rules and Principles of Scientific Data Visualization" Domik 1999 "Tutorial on Visualization" A good summary of Tufte can be found here: Globus 1994 "Principles of Information Display for Visualization Practitioners"
Good online resource with tips on graphing association between two numeric variables under various c Recent references: Kelleher and Wagner 2011 "Ten guidelines for effective data visualization in scientific publications" provides a nice set of rules. The rules, with references (but not the full art
12,748
How to choose between learning algorithms
There is a package for "R" called "caret," which stands for "classification and regression testing." I think it would be a good place for you to start, as it will easily allow you to apply a dozen or so different learning algorithms to your data, and then cross-validate them to estimate how accurate they each are. Here is an example that you can modify with your own data/other methods: install.packages('caret',dependencies = c('Depends','Suggests')) library(caret) set.seed(999) Precursor1 <- runif(25) Precursor2 <- runif(25) Target <- sample(c('T','F'),25,replace=TRUE) MyData <- data.frame(Precursor1,Precursor2,Target) str(MyData) #Try Logistic regression model_Logistic <- train(Target~Precursor1+Precursor2,data=MyData,method='glm') #Try Neural Network model_NN <- train(Target~Precursor1+Precursor2,data=MyData,method='nnet',trace=FALSE) #Try Naive Bayes model_NB <- train(Target~Precursor1+Precursor2,data=MyData,method='nb') #Try Random Forest model_RF <- train(Target~Precursor1+Precursor2,data=MyData,method='rf') #Try Support Vector Machine model_SVM<- train(Target~Precursor1+Precursor2,data=MyData,method='svmLinear') #Try Nearest Neighbors model_KNN<- train(Target~Precursor1+Precursor2,data=MyData,method='knn') #Compare the accuracy of each model cat('Logistic:',max(model_Logistic$results$Accuracy)) cat('Neural:',max(model_NN$results$Accuracy)) cat('Bayes:',max(model_NB$results$Accuracy)) cat('Random Forest:',max(model_RF$results$Accuracy)) cat('Support Vector Machine:',max(model_SVM$results$Accuracy)) cat('Nearest Neighbors:',max(model_KNN$results$Accuracy)) #Look at other available methods ?train Another idea would be to break your data into a training set and a test set, and then compare how each model performs on the test set. If you like, I can show you how to do that.
How to choose between learning algorithms
There is a package for "R" called "caret," which stands for "classification and regression testing." I think it would be a good place for you to start, as it will easily allow you to apply a dozen or
How to choose between learning algorithms There is a package for "R" called "caret," which stands for "classification and regression testing." I think it would be a good place for you to start, as it will easily allow you to apply a dozen or so different learning algorithms to your data, and then cross-validate them to estimate how accurate they each are. Here is an example that you can modify with your own data/other methods: install.packages('caret',dependencies = c('Depends','Suggests')) library(caret) set.seed(999) Precursor1 <- runif(25) Precursor2 <- runif(25) Target <- sample(c('T','F'),25,replace=TRUE) MyData <- data.frame(Precursor1,Precursor2,Target) str(MyData) #Try Logistic regression model_Logistic <- train(Target~Precursor1+Precursor2,data=MyData,method='glm') #Try Neural Network model_NN <- train(Target~Precursor1+Precursor2,data=MyData,method='nnet',trace=FALSE) #Try Naive Bayes model_NB <- train(Target~Precursor1+Precursor2,data=MyData,method='nb') #Try Random Forest model_RF <- train(Target~Precursor1+Precursor2,data=MyData,method='rf') #Try Support Vector Machine model_SVM<- train(Target~Precursor1+Precursor2,data=MyData,method='svmLinear') #Try Nearest Neighbors model_KNN<- train(Target~Precursor1+Precursor2,data=MyData,method='knn') #Compare the accuracy of each model cat('Logistic:',max(model_Logistic$results$Accuracy)) cat('Neural:',max(model_NN$results$Accuracy)) cat('Bayes:',max(model_NB$results$Accuracy)) cat('Random Forest:',max(model_RF$results$Accuracy)) cat('Support Vector Machine:',max(model_SVM$results$Accuracy)) cat('Nearest Neighbors:',max(model_KNN$results$Accuracy)) #Look at other available methods ?train Another idea would be to break your data into a training set and a test set, and then compare how each model performs on the test set. If you like, I can show you how to do that.
How to choose between learning algorithms There is a package for "R" called "caret," which stands for "classification and regression testing." I think it would be a good place for you to start, as it will easily allow you to apply a dozen or
12,749
How to choose between learning algorithms
I would use probability theory to start with, and then pick whichever algorithm best calculates what probability theory tells you to do. So you have training data $T$, and some new precursors $X$, and an object to classify $Y$, as well as your prior information $I$. So you want to know about $Y$. Then probability theory says, just calculate its probability, conditional on all the information you have available to you. $$P(Y|T,X,I)$$ Now we can use any of the rules of probability theory to manipulate this into things that we do know how to calculate. So using Bayes theorem, you get: $$P(Y|T,X,I)=\frac{P(Y|T,I)P(X|Y,T,I)}{P(X|T,I)}$$ Now $P(Y|T,I)$ is usually easy - unless you prior information can tell you something about $Y$ beyond the training data (e.g. correlations), then it is given by the rule of succession - or basically the observed fraction of times $Y$ was true in the training data set. For the second term $P(X|Y,T,I)$ - this is your model, and where most of your work will go, and where different algorithms will do different things. $P(X|T,I)$ is a bit of a vicious beast to calculate, so we do the following trick to avoid having to do this: take the odds of $Y$ against $\overline{Y}$ (i.e. not $Y$). And we get: $$O(Y|T,X,I)=\frac{P(Y|T,X,I)}{P(\overline{Y}|T,X,I)}=\frac{P(Y|T,I)}{P(\overline{Y}|T,I)}\frac{P(X|Y,T,I)}{P(X|\overline{Y},T,I)}$$ Now you basically need a decision rule - when the odds/probability is above a certain threshold, you will classify $Y$ as "true", otherwise you will classify it as "false". Now nobody can really help you with this - it is a decision which depends on the consequences of making right and wrong decisions. This is a subjective exercise, and only the proper context can answer this. Of course the "subjectivity" will only matter if there is high uncertainty (i.e. you have a "crap" model/data which can't distinguish the two very well). The second quantity - the model $P(X|Y,T,I)$ is a "predictive" model. Suppose the prior information indicates a single model which depends on parameter $\theta_{Y}$. Then the quantity is given by: $$P(X|Y,T,I)=\int P(X,\theta_{Y}|Y,T,I) d\theta = \int P(X|\theta_{Y},Y,T,I)P(\theta_{Y}|Y,T,I) d\theta_{Y}$$ Now if your model is of the "iid" variety, then $P(X|\theta_{Y},Y,T,I)=P(X|\theta_{Y},Y,I)$. But if you have a dependent model, such as an autoregressive one, then $T$ may still matter. And $P(\theta_{Y}|Y,T,I)$ is the posterior distribution for the parameters in the model - this is the part that the training data would determine. And this is probably where most of the work will go. But what if the model is not known with certainty? well it just becomes another nuisance parameter to integrate out, just as was done for $\theta_{Y}$. Call the ith model $M_i$ and its set of parameters $\theta^{(i)}_{Y}$, and the equation becomes: $$P(X|Y,T,I)= \sum_{i}P(M_{i}|Y,T,I)\int P(X|\theta_{Y}^{(i)},M_{i},Y,T,I)P(\theta_{Y}^{(i)}|M_{i},Y,T,I) d\theta_{Y}^{(i)}$$ Where $$P(M_{i}|Y,T,I)=P(M_{i}|Y,I)\int P(\theta_{Y}^{(i)}|M_{i},Y,I)P(T|\theta_{Y}^{(i)},M_{i},Y,I) d\theta_{Y}^{(i)}$$ (NOTE: $M_i$ is a proposition of the form "the ith model is the best in the set that is being considered". and no improper priors allowed if you are integrating over models - the infinities do not cancel out in this case, and you will be left with non-sense) Now, up to this point, all results are exact and optimal (this is the option 2 - apply some awesome algorithm to the data). But this a daunting task to undertake. In the real world, the mathematics required may be not feasible to do in practice - so you will have to compromise. you should always "have a go" at doing the exact equations, for any maths that you can simplify will save you time at the PC. However, this first step is important, because this sets "the target", and it makes it clear what is to be done. Otherwise you are left (as you seem to be) with a whole host of potential options with nothing to choose between them. Now at this stage, we are still in "symbolic logic" world, where nothing really makes sense. So you need to link these to your specific problem: $P(M_{i}|Y,I)$ is the prior probability for the ith model - generally will be equal for all i. $P(\theta_{Y}^{(i)}|M_{i},Y,I)$ is the prior for the parameters in the ith model (must be proper!) $P(T|\theta_{Y}^{(i)},M_{i},Y,I)$ is the likelihood function for the training data, given the ith model $P(\theta_{Y}^{(i)}|T,M_{i},Y,I)$ is the posterior for the parameters in the ith model, conditional on the training data. $P(M_{i}|Y,T,I)$ is the posterior for the ith model conditional on the training data There will be another set of equations for $\overline{Y}$ Note that the equations will simplify enormously if a) one model is a clear winner, so that $P(M_{j}|Y,T,I)\approx 1$ and b) within this model, its parameters are very accurate, so the integrand resembles a delta function (and integration is very close to substitution or plug-in estimates). If both these conditions are met you have: $$P(X|Y,T,I)\approx P(X|\theta_{Y}^{(j)},M_{j},Y,T,I)_{\theta_{Y}^{(j)}=\hat{\theta}_{Y}^{(j)}}$$ Which is the "standard" approach to this kind of problem.
How to choose between learning algorithms
I would use probability theory to start with, and then pick whichever algorithm best calculates what probability theory tells you to do. So you have training data $T$, and some new precursors $X$, an
How to choose between learning algorithms I would use probability theory to start with, and then pick whichever algorithm best calculates what probability theory tells you to do. So you have training data $T$, and some new precursors $X$, and an object to classify $Y$, as well as your prior information $I$. So you want to know about $Y$. Then probability theory says, just calculate its probability, conditional on all the information you have available to you. $$P(Y|T,X,I)$$ Now we can use any of the rules of probability theory to manipulate this into things that we do know how to calculate. So using Bayes theorem, you get: $$P(Y|T,X,I)=\frac{P(Y|T,I)P(X|Y,T,I)}{P(X|T,I)}$$ Now $P(Y|T,I)$ is usually easy - unless you prior information can tell you something about $Y$ beyond the training data (e.g. correlations), then it is given by the rule of succession - or basically the observed fraction of times $Y$ was true in the training data set. For the second term $P(X|Y,T,I)$ - this is your model, and where most of your work will go, and where different algorithms will do different things. $P(X|T,I)$ is a bit of a vicious beast to calculate, so we do the following trick to avoid having to do this: take the odds of $Y$ against $\overline{Y}$ (i.e. not $Y$). And we get: $$O(Y|T,X,I)=\frac{P(Y|T,X,I)}{P(\overline{Y}|T,X,I)}=\frac{P(Y|T,I)}{P(\overline{Y}|T,I)}\frac{P(X|Y,T,I)}{P(X|\overline{Y},T,I)}$$ Now you basically need a decision rule - when the odds/probability is above a certain threshold, you will classify $Y$ as "true", otherwise you will classify it as "false". Now nobody can really help you with this - it is a decision which depends on the consequences of making right and wrong decisions. This is a subjective exercise, and only the proper context can answer this. Of course the "subjectivity" will only matter if there is high uncertainty (i.e. you have a "crap" model/data which can't distinguish the two very well). The second quantity - the model $P(X|Y,T,I)$ is a "predictive" model. Suppose the prior information indicates a single model which depends on parameter $\theta_{Y}$. Then the quantity is given by: $$P(X|Y,T,I)=\int P(X,\theta_{Y}|Y,T,I) d\theta = \int P(X|\theta_{Y},Y,T,I)P(\theta_{Y}|Y,T,I) d\theta_{Y}$$ Now if your model is of the "iid" variety, then $P(X|\theta_{Y},Y,T,I)=P(X|\theta_{Y},Y,I)$. But if you have a dependent model, such as an autoregressive one, then $T$ may still matter. And $P(\theta_{Y}|Y,T,I)$ is the posterior distribution for the parameters in the model - this is the part that the training data would determine. And this is probably where most of the work will go. But what if the model is not known with certainty? well it just becomes another nuisance parameter to integrate out, just as was done for $\theta_{Y}$. Call the ith model $M_i$ and its set of parameters $\theta^{(i)}_{Y}$, and the equation becomes: $$P(X|Y,T,I)= \sum_{i}P(M_{i}|Y,T,I)\int P(X|\theta_{Y}^{(i)},M_{i},Y,T,I)P(\theta_{Y}^{(i)}|M_{i},Y,T,I) d\theta_{Y}^{(i)}$$ Where $$P(M_{i}|Y,T,I)=P(M_{i}|Y,I)\int P(\theta_{Y}^{(i)}|M_{i},Y,I)P(T|\theta_{Y}^{(i)},M_{i},Y,I) d\theta_{Y}^{(i)}$$ (NOTE: $M_i$ is a proposition of the form "the ith model is the best in the set that is being considered". and no improper priors allowed if you are integrating over models - the infinities do not cancel out in this case, and you will be left with non-sense) Now, up to this point, all results are exact and optimal (this is the option 2 - apply some awesome algorithm to the data). But this a daunting task to undertake. In the real world, the mathematics required may be not feasible to do in practice - so you will have to compromise. you should always "have a go" at doing the exact equations, for any maths that you can simplify will save you time at the PC. However, this first step is important, because this sets "the target", and it makes it clear what is to be done. Otherwise you are left (as you seem to be) with a whole host of potential options with nothing to choose between them. Now at this stage, we are still in "symbolic logic" world, where nothing really makes sense. So you need to link these to your specific problem: $P(M_{i}|Y,I)$ is the prior probability for the ith model - generally will be equal for all i. $P(\theta_{Y}^{(i)}|M_{i},Y,I)$ is the prior for the parameters in the ith model (must be proper!) $P(T|\theta_{Y}^{(i)},M_{i},Y,I)$ is the likelihood function for the training data, given the ith model $P(\theta_{Y}^{(i)}|T,M_{i},Y,I)$ is the posterior for the parameters in the ith model, conditional on the training data. $P(M_{i}|Y,T,I)$ is the posterior for the ith model conditional on the training data There will be another set of equations for $\overline{Y}$ Note that the equations will simplify enormously if a) one model is a clear winner, so that $P(M_{j}|Y,T,I)\approx 1$ and b) within this model, its parameters are very accurate, so the integrand resembles a delta function (and integration is very close to substitution or plug-in estimates). If both these conditions are met you have: $$P(X|Y,T,I)\approx P(X|\theta_{Y}^{(j)},M_{j},Y,T,I)_{\theta_{Y}^{(j)}=\hat{\theta}_{Y}^{(j)}}$$ Which is the "standard" approach to this kind of problem.
How to choose between learning algorithms I would use probability theory to start with, and then pick whichever algorithm best calculates what probability theory tells you to do. So you have training data $T$, and some new precursors $X$, an
12,750
Textbook on the *theory* of neural nets/ML algorithms?
Foundations of Machine Learning, by Mehryar Mohri, Afshin Rostamizadeh and Ameet Talwalkar, is a 2012 book on machine learning theory. Understanding Machine Learning: From Theory to Algorithms, by Shai Shalev-Shwartz and Shai Ben-David, is a similar 2014 book that's fairly well-known and targeted a little more introductory than Mohri/Rostamizadeh/Talwalkar, but still has lots of theory in it. It's freely available online. Neural Network Learning: Theoretical Foundations, by Martin Anthony and Peter Bartlett, is a 1999 book about ML theory phrased as being about neural networks, but (to my impression not having read it) is mostly about ML theory in general. These three books mostly take the predominant viewpoint of statistical learning theory. There is also an interesting point of view called computational learning theory, inspired more by computer science theory. I think the standard introductory book in this area is An Introduction to Computational Learning Theory, a 1994 book by Michael Kearns and Umesh Vazirani. Another excellent and oft-recommended freely available book is Trevor Hastie, Robert Tibshirani, and Jerome Friedman's 2009 second edition of The Elements of Statistical Learning. It's perhaps a little less theoretical than the others, and more from the statistician's point of view than the machine learner's, but still has plenty of interest. Also, if you care about gradient descent in particular, the standard reference is Convex Optimization by Stephen Boyd and Lieven Vandenberghe. This 2004 book is freely available online. None of these books contain much on the modern theory of deep networks, if that's what you care about. (For example, most of the optimization theory will be about convex cases, which deep networks decidedly are not.) That's because this theory is very new; most of the results have come only in the last few years, and it's still very much being figured out. But, as an overview of the basic understanding of the field so far, any of them will set you up well to understand the papers in which that work is done (except perhaps Kearns/Vazirani, which focuses on different aspects of analysis that I'm not sure have been successfully applied to deep networks – yet).
Textbook on the *theory* of neural nets/ML algorithms?
Foundations of Machine Learning, by Mehryar Mohri, Afshin Rostamizadeh and Ameet Talwalkar, is a 2012 book on machine learning theory. Understanding Machine Learning: From Theory to Algorithms, by Sha
Textbook on the *theory* of neural nets/ML algorithms? Foundations of Machine Learning, by Mehryar Mohri, Afshin Rostamizadeh and Ameet Talwalkar, is a 2012 book on machine learning theory. Understanding Machine Learning: From Theory to Algorithms, by Shai Shalev-Shwartz and Shai Ben-David, is a similar 2014 book that's fairly well-known and targeted a little more introductory than Mohri/Rostamizadeh/Talwalkar, but still has lots of theory in it. It's freely available online. Neural Network Learning: Theoretical Foundations, by Martin Anthony and Peter Bartlett, is a 1999 book about ML theory phrased as being about neural networks, but (to my impression not having read it) is mostly about ML theory in general. These three books mostly take the predominant viewpoint of statistical learning theory. There is also an interesting point of view called computational learning theory, inspired more by computer science theory. I think the standard introductory book in this area is An Introduction to Computational Learning Theory, a 1994 book by Michael Kearns and Umesh Vazirani. Another excellent and oft-recommended freely available book is Trevor Hastie, Robert Tibshirani, and Jerome Friedman's 2009 second edition of The Elements of Statistical Learning. It's perhaps a little less theoretical than the others, and more from the statistician's point of view than the machine learner's, but still has plenty of interest. Also, if you care about gradient descent in particular, the standard reference is Convex Optimization by Stephen Boyd and Lieven Vandenberghe. This 2004 book is freely available online. None of these books contain much on the modern theory of deep networks, if that's what you care about. (For example, most of the optimization theory will be about convex cases, which deep networks decidedly are not.) That's because this theory is very new; most of the results have come only in the last few years, and it's still very much being figured out. But, as an overview of the basic understanding of the field so far, any of them will set you up well to understand the papers in which that work is done (except perhaps Kearns/Vazirani, which focuses on different aspects of analysis that I'm not sure have been successfully applied to deep networks – yet).
Textbook on the *theory* of neural nets/ML algorithms? Foundations of Machine Learning, by Mehryar Mohri, Afshin Rostamizadeh and Ameet Talwalkar, is a 2012 book on machine learning theory. Understanding Machine Learning: From Theory to Algorithms, by Sha
12,751
Textbook on the *theory* of neural nets/ML algorithms?
Machine Learning: a Probabilistic Perspective by Kevin P. Murphy explains a lot of theory from a Bayesian perspective (I've only used it for logistic regression, but I thought it was quite good). The whole book is available online as a PDF by searching on Google.
Textbook on the *theory* of neural nets/ML algorithms?
Machine Learning: a Probabilistic Perspective by Kevin P. Murphy explains a lot of theory from a Bayesian perspective (I've only used it for logistic regression, but I thought it was quite good). The
Textbook on the *theory* of neural nets/ML algorithms? Machine Learning: a Probabilistic Perspective by Kevin P. Murphy explains a lot of theory from a Bayesian perspective (I've only used it for logistic regression, but I thought it was quite good). The whole book is available online as a PDF by searching on Google.
Textbook on the *theory* of neural nets/ML algorithms? Machine Learning: a Probabilistic Perspective by Kevin P. Murphy explains a lot of theory from a Bayesian perspective (I've only used it for logistic regression, but I thought it was quite good). The
12,752
Textbook on the *theory* of neural nets/ML algorithms?
Deep Learning (Adaptive Computation and Machine Learning series). This is written by Ian Goodfellow, Yoshua Bengio, Aaron Courville. As per the agreement of the author with MIT Press, you can read the legally free copy available on the browser in this website. www.deeplearningbook.org This is good for pure mathematics and theory of neural net and its different sub branches. In addition to this, The Elements of Statistical Learning: Data Mining, Inference, and Prediction is also a good book to build theoritical and mathematical foundation in traditional machine learning. This is written by Trevor Hastie, Robert Tibshirani and Jerome Friedman and available for free by the authors at https://web.stanford.edu/~hastie/ElemStatLearn/
Textbook on the *theory* of neural nets/ML algorithms?
Deep Learning (Adaptive Computation and Machine Learning series). This is written by Ian Goodfellow, Yoshua Bengio, Aaron Courville. As per the agreement of the author with MIT Press, you can read th
Textbook on the *theory* of neural nets/ML algorithms? Deep Learning (Adaptive Computation and Machine Learning series). This is written by Ian Goodfellow, Yoshua Bengio, Aaron Courville. As per the agreement of the author with MIT Press, you can read the legally free copy available on the browser in this website. www.deeplearningbook.org This is good for pure mathematics and theory of neural net and its different sub branches. In addition to this, The Elements of Statistical Learning: Data Mining, Inference, and Prediction is also a good book to build theoritical and mathematical foundation in traditional machine learning. This is written by Trevor Hastie, Robert Tibshirani and Jerome Friedman and available for free by the authors at https://web.stanford.edu/~hastie/ElemStatLearn/
Textbook on the *theory* of neural nets/ML algorithms? Deep Learning (Adaptive Computation and Machine Learning series). This is written by Ian Goodfellow, Yoshua Bengio, Aaron Courville. As per the agreement of the author with MIT Press, you can read th
12,753
Textbook on the *theory* of neural nets/ML algorithms?
Neural Network Design (Martin T. Hagan, Howard B. Demuth, Mark Hudson Beale, Orlando De Jesús) has some nice discussion of optimization in the context of neural nets.
Textbook on the *theory* of neural nets/ML algorithms?
Neural Network Design (Martin T. Hagan, Howard B. Demuth, Mark Hudson Beale, Orlando De Jesús) has some nice discussion of optimization in the context of neural nets.
Textbook on the *theory* of neural nets/ML algorithms? Neural Network Design (Martin T. Hagan, Howard B. Demuth, Mark Hudson Beale, Orlando De Jesús) has some nice discussion of optimization in the context of neural nets.
Textbook on the *theory* of neural nets/ML algorithms? Neural Network Design (Martin T. Hagan, Howard B. Demuth, Mark Hudson Beale, Orlando De Jesús) has some nice discussion of optimization in the context of neural nets.
12,754
Updating SVD decomposition after adding one new row to the matrix
Yes, one can update an SVD decomposition after adding one new row to the existing matrix. In general this "add one to" problem formulation is known as rank one updates. The MathOverflow link provided by @amoeba on "efficient rank-two updates of an eigenvalue decomposition" is a great first step if you want to start looking deeper into the matter; the first paper provides an explicit solution to your specific question. Just to clarify what rank-one and rank-two mean so you do not get confused, if your new $A^*$ is such that: \begin{align} A^* = A - uv^T \end{align} Where $u$ and $v$ are vectors then you refer to this as a rank-one update (or perturbation). The basic of this update are dictated by the Sherman-Morrison formula.. If the perturbation is more than one rank ie. \begin{align} A^* = A - UV^T \end{align} the Woodbury formula comes into play. If you see these formulas you will notice that there are lot of inverse involved. You do not solve these directly. As you already solved a great deal of their subsystems already (ie. you have some decomposition already computed) you utilize these to get a faster and/or more stable estimates. (That's why people still research this field.) I have used the book "Computational Statistics" by J.E. Gentle a lot as a reference; I think Chapt. 5 Numerical Linear Algebra will set you up properly. (The uber-classic: "Matrix Algebra From a Statistician's Perspective" by Harville unluckily does not touch on rank updates at all.) Looking to the statistics/application side of things, rank one updates are common in recommender systems because one may have thousands of customer entries and recomputing the SVD (or any given decomposition for that matter) each time a new user registers or a new product is added or removed is quite wasteful (if not unattainable). Usually recommender system matrices are sparse and this makes the algorithms even more efficient. An accessible first paper is the "Fast online SVD revisions for lightweight recommender systems" manuscript by M. Brand. Going to dense matrices I think that looking at the papers from Pattern Recognition and Imaging Processing can get you quite far on getting an actual algorithm to use. For example the papers: Incremental learning of bidirectional principal components for face recognition (2009) by Ren and Dai, On incremental and robust subspace learning (2003) by Li et al. Sequential Karhunen-Loeve basis extraction and its application to images (2000) by Levey and Lindenbaum. Incremental Learning for Robust Visual Tracking (2007) by Ross et al. all seem to be tackling the same problem in their core; new features are coming in and we need to update our representation accordingly fast. Notice that these matrices are not symmetric or even square. Another work of M. Brand can also addresses this problem (see the paper "Fast low-rank modifications of the thin singular value decomposition (2006)" - this also mentioned in the MO link given in the beginning of the post.) There a lot of great papers on the subject but most tend to be heavily mathematical (eg. the Benaych-Georgesa and Nadakuditi paper on "The singular values and vectors of low rank perturbations of large rectangular random matrices (2012)") and I do not think they will help get a solution soon. I would suggest you keep your focus on Image Processing literature. Unfortunately I have not come across any R implementations for rank-one updates routines. The answer on "Updatable SVD implementation in Python, C, or Fortran?" from the Computational Science SE gives a number of MATLAB and C++ implementations that you may want to consider. Usually R, Python, etc. implementation are wrappers around C, C++ or FORTRAN implementations.
Updating SVD decomposition after adding one new row to the matrix
Yes, one can update an SVD decomposition after adding one new row to the existing matrix. In general this "add one to" problem formulation is known as rank one updates. The MathOverflow link provided
Updating SVD decomposition after adding one new row to the matrix Yes, one can update an SVD decomposition after adding one new row to the existing matrix. In general this "add one to" problem formulation is known as rank one updates. The MathOverflow link provided by @amoeba on "efficient rank-two updates of an eigenvalue decomposition" is a great first step if you want to start looking deeper into the matter; the first paper provides an explicit solution to your specific question. Just to clarify what rank-one and rank-two mean so you do not get confused, if your new $A^*$ is such that: \begin{align} A^* = A - uv^T \end{align} Where $u$ and $v$ are vectors then you refer to this as a rank-one update (or perturbation). The basic of this update are dictated by the Sherman-Morrison formula.. If the perturbation is more than one rank ie. \begin{align} A^* = A - UV^T \end{align} the Woodbury formula comes into play. If you see these formulas you will notice that there are lot of inverse involved. You do not solve these directly. As you already solved a great deal of their subsystems already (ie. you have some decomposition already computed) you utilize these to get a faster and/or more stable estimates. (That's why people still research this field.) I have used the book "Computational Statistics" by J.E. Gentle a lot as a reference; I think Chapt. 5 Numerical Linear Algebra will set you up properly. (The uber-classic: "Matrix Algebra From a Statistician's Perspective" by Harville unluckily does not touch on rank updates at all.) Looking to the statistics/application side of things, rank one updates are common in recommender systems because one may have thousands of customer entries and recomputing the SVD (or any given decomposition for that matter) each time a new user registers or a new product is added or removed is quite wasteful (if not unattainable). Usually recommender system matrices are sparse and this makes the algorithms even more efficient. An accessible first paper is the "Fast online SVD revisions for lightweight recommender systems" manuscript by M. Brand. Going to dense matrices I think that looking at the papers from Pattern Recognition and Imaging Processing can get you quite far on getting an actual algorithm to use. For example the papers: Incremental learning of bidirectional principal components for face recognition (2009) by Ren and Dai, On incremental and robust subspace learning (2003) by Li et al. Sequential Karhunen-Loeve basis extraction and its application to images (2000) by Levey and Lindenbaum. Incremental Learning for Robust Visual Tracking (2007) by Ross et al. all seem to be tackling the same problem in their core; new features are coming in and we need to update our representation accordingly fast. Notice that these matrices are not symmetric or even square. Another work of M. Brand can also addresses this problem (see the paper "Fast low-rank modifications of the thin singular value decomposition (2006)" - this also mentioned in the MO link given in the beginning of the post.) There a lot of great papers on the subject but most tend to be heavily mathematical (eg. the Benaych-Georgesa and Nadakuditi paper on "The singular values and vectors of low rank perturbations of large rectangular random matrices (2012)") and I do not think they will help get a solution soon. I would suggest you keep your focus on Image Processing literature. Unfortunately I have not come across any R implementations for rank-one updates routines. The answer on "Updatable SVD implementation in Python, C, or Fortran?" from the Computational Science SE gives a number of MATLAB and C++ implementations that you may want to consider. Usually R, Python, etc. implementation are wrappers around C, C++ or FORTRAN implementations.
Updating SVD decomposition after adding one new row to the matrix Yes, one can update an SVD decomposition after adding one new row to the existing matrix. In general this "add one to" problem formulation is known as rank one updates. The MathOverflow link provided
12,755
Clustering -- Intuition behind Kleinberg's Impossibility Theorem
One way or another, every clustering algorithm relies on some notion of “proximity” of points. It seems intuitively clear that you can either use a relative (scale-invariant) notion or an absolute (consistent) notion of proximity, but not both. I will first try to illustrate this with an example, and then go on to say how this intuition fits with Kleinberg’s Theorem. An illustrative example Suppose we have two sets $S_1$ and $S_2$ of $270$ points each, arranged in the plane like this: $\hskip{6em}$ You might not see $270$ points in either of these pictures, but that’s just because many of the points are very close together. We see more points when we zoom in: $\hskip{3em}$ You’ll probably spontaneoulsy agree that, in both data sets, the points are arranged in three clusters. However, it turns out that if you zoom in on any of the three clusters of $S_2$, you see the following: $\hskip{3em}$ If you believe in an absolute notion of proximity, or in consistency, you’ll still maintain that, irrespective of what you just saw under the microscope, $S_2$ consists of just three clusters. Indeed, the only difference between $S_1$ and $S_2$ is that, within each cluster, some points are now closer together. If, on the other hand, you believe in a relative notion of proximity, or in scale invariance, you’ll feel inclined to argue that $S_2$ consists not of $3$ but of $3×3 = 9$ clusters. Neither of these points of view is wrong, but you do have to make a choice one way or the other. A case for isometry invariance If you compare the above intuition with Kleinberg’s Theorem, you will find that they are slightly at odds. Indeed, Kleinberg’s Theorem appears to say that you can achieve scale invariance and consistency simultaneously as long as you do not care about a third property called richness. However, richness is not the only property you lose if you simultaneously insist on scale invariance and consistency. You also lose another, more fundamental property: isometry-invariance. This is a property that I wouldn’t be willing to sacrifice. As it doesn’t appear in Kleinberg’s paper, I’ll dwell on it for a moment. In short, a clustering algorithm is isometry invariant if its output depends only on the distances between points, and not on some additional information like labels that you attach to your points, or on an ordering that you impose on your points. I hope this sounds like a very mild and very natural condition. All algorithms discussed in Kleinberg’s paper are isometry invariant, except for the single linkage algorithm with the $k$-cluster stopping condition. According to Kleinberg’s description, this algorithm uses a lexicographical ordering of the points, so its output may indeed depend on how you label them. For instance, for a set of three equidistant points, the output of the single linkage algorithm with the $2$-cluster stopping condition will give different answers according to whether you label your three points as “cat”, “dog”, “mouse” (c < d < m) or as “Tom”, “Spike”, “Jerry” (J < S < T): $\hskip{6em}$ This unnatural behaviour can of course easily be repaired by replacing the $k$-cluster stopping condition with a “$(≤ k)$-cluster stopping condition”. The idea is simply not to break ties between equidistant points, and to stop merging clusters as soon as we have reached at most $k$ clusters. This repaired algorithm will still produce $k$ clusters most of the time, and it will be isometry invariant and scale invariant. In agreement with the intuition given above, it will however no longer be consistent. For a precise definition of isometry invariance, recall that Kleinberg defines a clustering algorithm on a finite set $S$ as a map that assigns to each metric on $S$ a partition of $S$: $$ Γ\colon \{\text{metrics on } S\} → \{\text{partitions of } S\}\\ d ↦ Γ(d) $$ An isometry $i$ between two metrics $d$ and $d'$ on $S$ is a permutation $i\colon S → S$ such that $d'(i(x),i(y)) = d(x,y)$ for all points $x$ and $y$ in $S$. Definition: A clustering algorithm $Γ$ is isometry invariant if it satisfies the following condition: for any metrics $d$ and $d'$, and any isometry $i$ between them, the points $i(x)$ and $i(y)$ lie in the same cluster of $Γ(d')$ if and only if the original points $x$ and $y$ lie in the same cluster of $Γ(d)$. When we think about clustering algorithms, we often identify the abstract set $S$ with a concrete set of points in the plane, or in some other ambient space, and imagine varying the metric on $S$ as moving the points of $S$ around. Indeed, this is the point of view we took in the illustrative example above. In this context, isometry invariance means that our clustering algorithm is insensitive to rotations, reflections and translations. $\hskip{6em}$ A variant of Kleinberg’s Theorem The intuition given above is captured by the following variant of Kleinberg’s Theorem. Theorem: There is no non-trivial isometry-invariant clustering algorithm that is simultaneously consistent and scale-invariant. Here, by a trivial clustering algorithm, I mean one of the following two algorithms: the algorithm that assigns to every metric on $S$ the discrete partition, in which every cluster consists of a single point, the algorithm that assigns to every metric on $S$ the lump partition, consisting of a single cluster. The claim is that these silly algorithms are the only two isometry invariant algorithms that are both consistent and scale-invariant. Proof: Let $S$ be the finite set on which our algorithm $Γ$ is supposed to operate. Let $d₁$ be the metric on $S$ in which any pair of distinct points has unit distance (i.e. $d₁(x,y) = 1$ for all $x ≠ y$ in $S$). As $Γ$ is isometry invariant, there are only two possibilities for $Γ(d₁)$: either $Γ(d₁)$ is the discrete partition, or $Γ(d₁)$ is the lump partition. Let’s first look at the case when $Γ(d₁)$ is the discrete partition. Given any metric $d$ on $S$, we can rescale it so that all pairs of points have distance $≥ 1$ under $d$. Then, by consistency, we find that $Γ(d) = Γ(d₁)$. So in this case $Γ$ is the trivial algorithm that assigns the discrete partition to every metric. Second, let’s consider the case that $Γ(d₁)$ is the lump partition. We can rescale any metric $d$ on $S$ so that all pairs of points have distance $≤ 1$, so again consistency implies that $Γ(d)=Γ(d₁)$. So $Γ$ is also trivial in this case. ∎ Of course, this proof is very close in spirit to Margareta Ackerman’s proof of Kleinberg’s original theorem, discussed in Alex Williams’s answer.
Clustering -- Intuition behind Kleinberg's Impossibility Theorem
One way or another, every clustering algorithm relies on some notion of “proximity” of points. It seems intuitively clear that you can either use a relative (scale-invariant) notion or an absolute (c
Clustering -- Intuition behind Kleinberg's Impossibility Theorem One way or another, every clustering algorithm relies on some notion of “proximity” of points. It seems intuitively clear that you can either use a relative (scale-invariant) notion or an absolute (consistent) notion of proximity, but not both. I will first try to illustrate this with an example, and then go on to say how this intuition fits with Kleinberg’s Theorem. An illustrative example Suppose we have two sets $S_1$ and $S_2$ of $270$ points each, arranged in the plane like this: $\hskip{6em}$ You might not see $270$ points in either of these pictures, but that’s just because many of the points are very close together. We see more points when we zoom in: $\hskip{3em}$ You’ll probably spontaneoulsy agree that, in both data sets, the points are arranged in three clusters. However, it turns out that if you zoom in on any of the three clusters of $S_2$, you see the following: $\hskip{3em}$ If you believe in an absolute notion of proximity, or in consistency, you’ll still maintain that, irrespective of what you just saw under the microscope, $S_2$ consists of just three clusters. Indeed, the only difference between $S_1$ and $S_2$ is that, within each cluster, some points are now closer together. If, on the other hand, you believe in a relative notion of proximity, or in scale invariance, you’ll feel inclined to argue that $S_2$ consists not of $3$ but of $3×3 = 9$ clusters. Neither of these points of view is wrong, but you do have to make a choice one way or the other. A case for isometry invariance If you compare the above intuition with Kleinberg’s Theorem, you will find that they are slightly at odds. Indeed, Kleinberg’s Theorem appears to say that you can achieve scale invariance and consistency simultaneously as long as you do not care about a third property called richness. However, richness is not the only property you lose if you simultaneously insist on scale invariance and consistency. You also lose another, more fundamental property: isometry-invariance. This is a property that I wouldn’t be willing to sacrifice. As it doesn’t appear in Kleinberg’s paper, I’ll dwell on it for a moment. In short, a clustering algorithm is isometry invariant if its output depends only on the distances between points, and not on some additional information like labels that you attach to your points, or on an ordering that you impose on your points. I hope this sounds like a very mild and very natural condition. All algorithms discussed in Kleinberg’s paper are isometry invariant, except for the single linkage algorithm with the $k$-cluster stopping condition. According to Kleinberg’s description, this algorithm uses a lexicographical ordering of the points, so its output may indeed depend on how you label them. For instance, for a set of three equidistant points, the output of the single linkage algorithm with the $2$-cluster stopping condition will give different answers according to whether you label your three points as “cat”, “dog”, “mouse” (c < d < m) or as “Tom”, “Spike”, “Jerry” (J < S < T): $\hskip{6em}$ This unnatural behaviour can of course easily be repaired by replacing the $k$-cluster stopping condition with a “$(≤ k)$-cluster stopping condition”. The idea is simply not to break ties between equidistant points, and to stop merging clusters as soon as we have reached at most $k$ clusters. This repaired algorithm will still produce $k$ clusters most of the time, and it will be isometry invariant and scale invariant. In agreement with the intuition given above, it will however no longer be consistent. For a precise definition of isometry invariance, recall that Kleinberg defines a clustering algorithm on a finite set $S$ as a map that assigns to each metric on $S$ a partition of $S$: $$ Γ\colon \{\text{metrics on } S\} → \{\text{partitions of } S\}\\ d ↦ Γ(d) $$ An isometry $i$ between two metrics $d$ and $d'$ on $S$ is a permutation $i\colon S → S$ such that $d'(i(x),i(y)) = d(x,y)$ for all points $x$ and $y$ in $S$. Definition: A clustering algorithm $Γ$ is isometry invariant if it satisfies the following condition: for any metrics $d$ and $d'$, and any isometry $i$ between them, the points $i(x)$ and $i(y)$ lie in the same cluster of $Γ(d')$ if and only if the original points $x$ and $y$ lie in the same cluster of $Γ(d)$. When we think about clustering algorithms, we often identify the abstract set $S$ with a concrete set of points in the plane, or in some other ambient space, and imagine varying the metric on $S$ as moving the points of $S$ around. Indeed, this is the point of view we took in the illustrative example above. In this context, isometry invariance means that our clustering algorithm is insensitive to rotations, reflections and translations. $\hskip{6em}$ A variant of Kleinberg’s Theorem The intuition given above is captured by the following variant of Kleinberg’s Theorem. Theorem: There is no non-trivial isometry-invariant clustering algorithm that is simultaneously consistent and scale-invariant. Here, by a trivial clustering algorithm, I mean one of the following two algorithms: the algorithm that assigns to every metric on $S$ the discrete partition, in which every cluster consists of a single point, the algorithm that assigns to every metric on $S$ the lump partition, consisting of a single cluster. The claim is that these silly algorithms are the only two isometry invariant algorithms that are both consistent and scale-invariant. Proof: Let $S$ be the finite set on which our algorithm $Γ$ is supposed to operate. Let $d₁$ be the metric on $S$ in which any pair of distinct points has unit distance (i.e. $d₁(x,y) = 1$ for all $x ≠ y$ in $S$). As $Γ$ is isometry invariant, there are only two possibilities for $Γ(d₁)$: either $Γ(d₁)$ is the discrete partition, or $Γ(d₁)$ is the lump partition. Let’s first look at the case when $Γ(d₁)$ is the discrete partition. Given any metric $d$ on $S$, we can rescale it so that all pairs of points have distance $≥ 1$ under $d$. Then, by consistency, we find that $Γ(d) = Γ(d₁)$. So in this case $Γ$ is the trivial algorithm that assigns the discrete partition to every metric. Second, let’s consider the case that $Γ(d₁)$ is the lump partition. We can rescale any metric $d$ on $S$ so that all pairs of points have distance $≤ 1$, so again consistency implies that $Γ(d)=Γ(d₁)$. So $Γ$ is also trivial in this case. ∎ Of course, this proof is very close in spirit to Margareta Ackerman’s proof of Kleinberg’s original theorem, discussed in Alex Williams’s answer.
Clustering -- Intuition behind Kleinberg's Impossibility Theorem One way or another, every clustering algorithm relies on some notion of “proximity” of points. It seems intuitively clear that you can either use a relative (scale-invariant) notion or an absolute (c
12,756
Clustering -- Intuition behind Kleinberg's Impossibility Theorem
This is the intuition I came up with (a snippet from my blog post here). A consequence of the richness axiom is that we can define two different distance functions, $d_1$ (top left) and $d_2$ (bottom left), that respectively put all the data points into individual clusters and into some other clustering. Then we can define a third distance function $d_3$ (top and bottom right) that simply scales $d_2$ so that the minimum distance between points in $d_3$ space is larger than the maximum distance in $d_1$ space. Then, we arrive at a contradiction, since by consistency the clustering should be the same for the $d_1 \rightarrow d_3$ transformation, but also the same for the $d_2 \rightarrow d_3$ transformation.
Clustering -- Intuition behind Kleinberg's Impossibility Theorem
This is the intuition I came up with (a snippet from my blog post here). A consequence of the richness axiom is that we can define two different distance functions, $d_1$ (top left) and $d_2$ (bottom
Clustering -- Intuition behind Kleinberg's Impossibility Theorem This is the intuition I came up with (a snippet from my blog post here). A consequence of the richness axiom is that we can define two different distance functions, $d_1$ (top left) and $d_2$ (bottom left), that respectively put all the data points into individual clusters and into some other clustering. Then we can define a third distance function $d_3$ (top and bottom right) that simply scales $d_2$ so that the minimum distance between points in $d_3$ space is larger than the maximum distance in $d_1$ space. Then, we arrive at a contradiction, since by consistency the clustering should be the same for the $d_1 \rightarrow d_3$ transformation, but also the same for the $d_2 \rightarrow d_3$ transformation.
Clustering -- Intuition behind Kleinberg's Impossibility Theorem This is the intuition I came up with (a snippet from my blog post here). A consequence of the richness axiom is that we can define two different distance functions, $d_1$ (top left) and $d_2$ (bottom
12,757
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend?
You need to consider the drift and (parametric/linear) trend in the levels of the time series in order to specify the deterministic terms in the augmented Dickey-Fuller regression which is in terms of the first differences of the time series. The confusion arises exactly from deriving the first-differences equation in the way that you have done. (Augmented) Dickey-Fuller regression model Suppose that the levels of the series include a drift and trend term $$ Y_t = \beta_{0,l} + \beta_{1,l} t + \beta_{2, l}Y_{t-1} + \varepsilon_{t} $$ The null hypothesis of nonstationarity in this case would be $\mathfrak{H}_0{}:{}\beta_{2, l} = 1$. One equation for the first differences implied by this data-generating process [DGP], is the one that you have derived $$ \Delta Y_t = \beta_{1,l} + \beta_{2, l}\Delta Y_{t-1} + \Delta \varepsilon_{t} $$ However, this is not the (augmented) Dickey Fuller regression as used in the test. Instead, the correct version can be had by subtracting $Y_{t-1}$ from both sides of the first equation resulting in $$ \begin{align} \Delta Y_t &= \beta_{0,l} + \beta_{1,l} t + (\beta_{2, l}-1)Y_{t-1} + \varepsilon_{t} \\ &\equiv \beta_{0,d} + \beta_{1,d}t + \beta_{2,d}Y_{t-1} + \varepsilon_{t} \end{align} $$ This is the (augmented) Dickey-Fuller regression, and the equivalent version of the null hypothesis of nonstationarity is the test $\mathfrak{H}_0{}:{}\beta_{2, d}=0$ which is just a t-test using the OLS estimate of $\beta_{2, d}$ in the regression above. Note that the drift and trend come through to this specification unchanged. An additional point to note is that if you are not certain about the presence of the linear trend in the levels of the time series, then you can jointly test for the linear trend and unit root, that is, $\mathfrak{H}_0{}:{}[\beta_{2, d}, \beta_{1,l}]' = [0, 0]'$, which can be tested using an F-test with appropriate critical values. These tests and critical values are produced by the R function ur.df in the urca package. Let us consider some examples in detail. Examples 1. Using the US investment series The first example uses the US investment series which is discussed in Lutkepohl and Kratzig (2005, pg. 9). The plot of the series and its first difference are given below. From the levels of the series, it appears that it has a non-zero mean, but does not appear to have a linear trend. So, we proceed with an augmented Dickey Fuller regression with an intercept, and also three lags of the dependent variable to account for serial correlation, that is: $$ \Delta Y_t = \beta_{0,d} + \beta_{2,d}Y_{t-1} + \sum_{j=1}^3 \gamma_j \Delta Y_{t-j} + \varepsilon_{t} $$ Note the key point that I have looked at the levels to specify the regression equation in differences. The R code to do this is given below: library(urca) library(foreign) library(zoo) tsInv <- as.zoo(ts(as.data.frame(read.table( "http://www.jmulti.de/download/datasets/US_investment.dat", skip=8, header=TRUE)), frequency=4, start=1947+2/4)) png("USinvPlot.png", width=6, height=7, units="in", res=100) par(mfrow=c(2, 1)) plot(tsInv$USinvestment) plot(diff(tsInv$USinvestment)) dev.off() # ADF with intercept adfIntercept <- ur.df(tsInv$USinvestment, lags = 3, type= 'drift') summary(adfIntercept) The results indicate that the the null hypothesis of nonstationarity can be rejected for this series using the t-test based on the estimated coefficient. The joint F-test of the intercept and the slope coefficient ($\mathfrak{H}{}:{}[\beta_{2, d}, \beta_{0,l}]' = [0, 0]'$) also rejects the null hypothesis that there is a unit root in the series. 2. Using German (log) consumption series The second example is using the German quarterly seasonally adjusted time series of (log) consumption. The plot of the series and its differences are given below. From the levels of the series, it is clear that the series has a trend, so we include the trend in the augmented Dickey-Fuller regression together with four lags of the first differences to account for the serial correlation, that is $$ \Delta Y_t = \beta_{0,d} + \beta_{1,d}t + \beta_{2,d}Y_{t-1} + \sum_{j=1}^4 \gamma_j \Delta Y_{t-j} + \varepsilon_{t} $$ The R code to do this is # using the (log) consumption series tsConsump <- zoo(read.dta("http://www.stata-press.com/data/r12/lutkepohl2.dta"), frequency=1) png("logConsPlot.png", width=6, height=7, units="in", res=100) par(mfrow=c(2, 1)) plot(tsConsump$ln_consump) plot(diff(tsConsump$ln_consump)) dev.off() # ADF with trend adfTrend <- ur.df(tsConsump$ln_consump, lags = 4, type = 'trend') summary(adfTrend) The results indicate that the null of nonstationarity cannot be rejected using the t-test based on the estimated coefficient. The joint F-test of the linear trend coefficient and the slope coefficient ($\mathfrak{H}{}:{}[\beta_{2, d}, \beta_{1,l}]' = [0, 0]'$) also indicates that the null of nonstationarity cannot be rejected. 3. Using given temperature data Now we can assess the properties of your data. The usual plots in levels and first differences are given below. These indicate that your data has an intercept and a trend, so we perform the ADF test (with no lagged first difference terms), using the following R code # using the given data tsTemp <- read.table(textConnection("temp 64.19749 65.19011 64.03281 64.99111 65.43837 65.51817 65.22061 65.43191 65.0221 65.44038 64.41756 64.65764 64.7486 65.11544 64.12437 64.49148 64.89215 64.72688 64.97553 64.6361 64.29038 65.31076 64.2114 65.37864 65.49637 65.3289 65.38394 65.39384 65.0984 65.32695 65.28 64.31041 65.20193 65.78063 65.17604 66.16412 65.85091 65.46718 65.75551 65.39994 66.36175 65.37125 65.77763 65.48623 64.62135 65.77237 65.84289 65.80289 66.78865 65.56931 65.29913 64.85516 65.56866 64.75768 65.95956 65.64745 64.77283 65.64165 66.64309 65.84163 66.2946 66.10482 65.72736 65.56701 65.11096 66.0006 66.71783 65.35595 66.44798 65.74924 65.4501 65.97633 65.32825 65.7741 65.76783 65.88689 65.88939 65.16927 64.95984 66.02226 66.79225 66.75573 65.74074 66.14969 66.15687 65.81199 66.13094 66.13194 65.82172 66.14661 65.32756 66.3979 65.84383 65.55329 65.68398 66.42857 65.82402 66.01003 66.25157 65.82142 66.08791 65.78863 66.2764 66.00948 66.26236 65.40246 65.40166 65.37064 65.73147 65.32708 65.84894 65.82043 64.91447 65.81062 66.42228 66.0316 65.35361 66.46407 66.41045 65.81548 65.06059 66.25414 65.69747 65.15275 65.50985 66.66216 66.88095 65.81281 66.15546 66.40939 65.94115 65.98144 66.13243 66.89761 66.95423 65.63435 66.05837 66.71114"), header=T) tsTemp <- as.zoo(ts(tsTemp, frequency=1)) png("tempPlot.png", width=6, height=7, units="in", res=100) par(mfrow=c(2, 1)) plot(tsTemp$temp) plot(diff(tsTemp$temp)) dev.off() # ADF with trend adfTrend <- ur.df(tsTemp$temp, type = 'trend') summary(adfTrend) The results for both the t-test and the F-test indicate that the null of nonstationarity can be rejected for the temperature series. I hope that clarifies matter somewhat.
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend?
You need to consider the drift and (parametric/linear) trend in the levels of the time series in order to specify the deterministic terms in the augmented Dickey-Fuller regression which is in terms of
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend? You need to consider the drift and (parametric/linear) trend in the levels of the time series in order to specify the deterministic terms in the augmented Dickey-Fuller regression which is in terms of the first differences of the time series. The confusion arises exactly from deriving the first-differences equation in the way that you have done. (Augmented) Dickey-Fuller regression model Suppose that the levels of the series include a drift and trend term $$ Y_t = \beta_{0,l} + \beta_{1,l} t + \beta_{2, l}Y_{t-1} + \varepsilon_{t} $$ The null hypothesis of nonstationarity in this case would be $\mathfrak{H}_0{}:{}\beta_{2, l} = 1$. One equation for the first differences implied by this data-generating process [DGP], is the one that you have derived $$ \Delta Y_t = \beta_{1,l} + \beta_{2, l}\Delta Y_{t-1} + \Delta \varepsilon_{t} $$ However, this is not the (augmented) Dickey Fuller regression as used in the test. Instead, the correct version can be had by subtracting $Y_{t-1}$ from both sides of the first equation resulting in $$ \begin{align} \Delta Y_t &= \beta_{0,l} + \beta_{1,l} t + (\beta_{2, l}-1)Y_{t-1} + \varepsilon_{t} \\ &\equiv \beta_{0,d} + \beta_{1,d}t + \beta_{2,d}Y_{t-1} + \varepsilon_{t} \end{align} $$ This is the (augmented) Dickey-Fuller regression, and the equivalent version of the null hypothesis of nonstationarity is the test $\mathfrak{H}_0{}:{}\beta_{2, d}=0$ which is just a t-test using the OLS estimate of $\beta_{2, d}$ in the regression above. Note that the drift and trend come through to this specification unchanged. An additional point to note is that if you are not certain about the presence of the linear trend in the levels of the time series, then you can jointly test for the linear trend and unit root, that is, $\mathfrak{H}_0{}:{}[\beta_{2, d}, \beta_{1,l}]' = [0, 0]'$, which can be tested using an F-test with appropriate critical values. These tests and critical values are produced by the R function ur.df in the urca package. Let us consider some examples in detail. Examples 1. Using the US investment series The first example uses the US investment series which is discussed in Lutkepohl and Kratzig (2005, pg. 9). The plot of the series and its first difference are given below. From the levels of the series, it appears that it has a non-zero mean, but does not appear to have a linear trend. So, we proceed with an augmented Dickey Fuller regression with an intercept, and also three lags of the dependent variable to account for serial correlation, that is: $$ \Delta Y_t = \beta_{0,d} + \beta_{2,d}Y_{t-1} + \sum_{j=1}^3 \gamma_j \Delta Y_{t-j} + \varepsilon_{t} $$ Note the key point that I have looked at the levels to specify the regression equation in differences. The R code to do this is given below: library(urca) library(foreign) library(zoo) tsInv <- as.zoo(ts(as.data.frame(read.table( "http://www.jmulti.de/download/datasets/US_investment.dat", skip=8, header=TRUE)), frequency=4, start=1947+2/4)) png("USinvPlot.png", width=6, height=7, units="in", res=100) par(mfrow=c(2, 1)) plot(tsInv$USinvestment) plot(diff(tsInv$USinvestment)) dev.off() # ADF with intercept adfIntercept <- ur.df(tsInv$USinvestment, lags = 3, type= 'drift') summary(adfIntercept) The results indicate that the the null hypothesis of nonstationarity can be rejected for this series using the t-test based on the estimated coefficient. The joint F-test of the intercept and the slope coefficient ($\mathfrak{H}{}:{}[\beta_{2, d}, \beta_{0,l}]' = [0, 0]'$) also rejects the null hypothesis that there is a unit root in the series. 2. Using German (log) consumption series The second example is using the German quarterly seasonally adjusted time series of (log) consumption. The plot of the series and its differences are given below. From the levels of the series, it is clear that the series has a trend, so we include the trend in the augmented Dickey-Fuller regression together with four lags of the first differences to account for the serial correlation, that is $$ \Delta Y_t = \beta_{0,d} + \beta_{1,d}t + \beta_{2,d}Y_{t-1} + \sum_{j=1}^4 \gamma_j \Delta Y_{t-j} + \varepsilon_{t} $$ The R code to do this is # using the (log) consumption series tsConsump <- zoo(read.dta("http://www.stata-press.com/data/r12/lutkepohl2.dta"), frequency=1) png("logConsPlot.png", width=6, height=7, units="in", res=100) par(mfrow=c(2, 1)) plot(tsConsump$ln_consump) plot(diff(tsConsump$ln_consump)) dev.off() # ADF with trend adfTrend <- ur.df(tsConsump$ln_consump, lags = 4, type = 'trend') summary(adfTrend) The results indicate that the null of nonstationarity cannot be rejected using the t-test based on the estimated coefficient. The joint F-test of the linear trend coefficient and the slope coefficient ($\mathfrak{H}{}:{}[\beta_{2, d}, \beta_{1,l}]' = [0, 0]'$) also indicates that the null of nonstationarity cannot be rejected. 3. Using given temperature data Now we can assess the properties of your data. The usual plots in levels and first differences are given below. These indicate that your data has an intercept and a trend, so we perform the ADF test (with no lagged first difference terms), using the following R code # using the given data tsTemp <- read.table(textConnection("temp 64.19749 65.19011 64.03281 64.99111 65.43837 65.51817 65.22061 65.43191 65.0221 65.44038 64.41756 64.65764 64.7486 65.11544 64.12437 64.49148 64.89215 64.72688 64.97553 64.6361 64.29038 65.31076 64.2114 65.37864 65.49637 65.3289 65.38394 65.39384 65.0984 65.32695 65.28 64.31041 65.20193 65.78063 65.17604 66.16412 65.85091 65.46718 65.75551 65.39994 66.36175 65.37125 65.77763 65.48623 64.62135 65.77237 65.84289 65.80289 66.78865 65.56931 65.29913 64.85516 65.56866 64.75768 65.95956 65.64745 64.77283 65.64165 66.64309 65.84163 66.2946 66.10482 65.72736 65.56701 65.11096 66.0006 66.71783 65.35595 66.44798 65.74924 65.4501 65.97633 65.32825 65.7741 65.76783 65.88689 65.88939 65.16927 64.95984 66.02226 66.79225 66.75573 65.74074 66.14969 66.15687 65.81199 66.13094 66.13194 65.82172 66.14661 65.32756 66.3979 65.84383 65.55329 65.68398 66.42857 65.82402 66.01003 66.25157 65.82142 66.08791 65.78863 66.2764 66.00948 66.26236 65.40246 65.40166 65.37064 65.73147 65.32708 65.84894 65.82043 64.91447 65.81062 66.42228 66.0316 65.35361 66.46407 66.41045 65.81548 65.06059 66.25414 65.69747 65.15275 65.50985 66.66216 66.88095 65.81281 66.15546 66.40939 65.94115 65.98144 66.13243 66.89761 66.95423 65.63435 66.05837 66.71114"), header=T) tsTemp <- as.zoo(ts(tsTemp, frequency=1)) png("tempPlot.png", width=6, height=7, units="in", res=100) par(mfrow=c(2, 1)) plot(tsTemp$temp) plot(diff(tsTemp$temp)) dev.off() # ADF with trend adfTrend <- ur.df(tsTemp$temp, type = 'trend') summary(adfTrend) The results for both the t-test and the F-test indicate that the null of nonstationarity can be rejected for the temperature series. I hope that clarifies matter somewhat.
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend? You need to consider the drift and (parametric/linear) trend in the levels of the time series in order to specify the deterministic terms in the augmented Dickey-Fuller regression which is in terms of
12,758
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend?
The null hypothesis in Dickey-Fuller test is that there is a unit root in a process. So when you reject the null, you get that your process is stationary (with the usual caveats of hypothesis testing). Concerning your math, the expresion $$\nabla y_t=\alpha_0+\alpha_1 t+\delta y_{t-1}+u_t$$ does not mean that $\nabla y_t$ has a trend. To say that process has a trend, its definition must include only that process. In the previous equation you have $\nabla y_t$ on one side, and $y_{t-1}$ on other. When you express $y_{t-1}$ in terms of $\nabla y_{t-1}$ you correctly come to the conclusion that there is no trend in the differenced process, if the initial process is stationary.
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend?
The null hypothesis in Dickey-Fuller test is that there is a unit root in a process. So when you reject the null, you get that your process is stationary (with the usual caveats of hypothesis testing)
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend? The null hypothesis in Dickey-Fuller test is that there is a unit root in a process. So when you reject the null, you get that your process is stationary (with the usual caveats of hypothesis testing). Concerning your math, the expresion $$\nabla y_t=\alpha_0+\alpha_1 t+\delta y_{t-1}+u_t$$ does not mean that $\nabla y_t$ has a trend. To say that process has a trend, its definition must include only that process. In the previous equation you have $\nabla y_t$ on one side, and $y_{t-1}$ on other. When you express $y_{t-1}$ in terms of $\nabla y_{t-1}$ you correctly come to the conclusion that there is no trend in the differenced process, if the initial process is stationary.
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend? The null hypothesis in Dickey-Fuller test is that there is a unit root in a process. So when you reject the null, you get that your process is stationary (with the usual caveats of hypothesis testing)
12,759
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend?
Previous answers were excellent. You usually take the decision on which test to implement based on the plot. In this case, the data appears to have an intercept and trend. If you test for an Unit-Root in levels, you'll use an intercept and trend model. If you run the test in differences, you'll use just an intercept model. I just answered this question because I must recommend you to use seasonal tests on this data. These tests are really complex (working with seasonality isn't easy). However, the nature of the data (temperature) and because in the plot you can observe some seasonal behavior. Then, you should research on HEGY test and implement it if you want your estimations to be robust.
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend?
Previous answers were excellent. You usually take the decision on which test to implement based on the plot. In this case, the data appears to have an intercept and trend. If you test for an Unit-Root
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend? Previous answers were excellent. You usually take the decision on which test to implement based on the plot. In this case, the data appears to have an intercept and trend. If you test for an Unit-Root in levels, you'll use an intercept and trend model. If you run the test in differences, you'll use just an intercept model. I just answered this question because I must recommend you to use seasonal tests on this data. These tests are really complex (working with seasonality isn't easy). However, the nature of the data (temperature) and because in the plot you can observe some seasonal behavior. Then, you should research on HEGY test and implement it if you want your estimations to be robust.
Which Dickey-Fuller test for a time series modelled with an intercept/drift and a linear trend? Previous answers were excellent. You usually take the decision on which test to implement based on the plot. In this case, the data appears to have an intercept and trend. If you test for an Unit-Root
12,760
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's procedure?
Why should it not be possible? The overall test and the pairwise tests ask different questions, so they can get different answers.
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's proce
Why should it not be possible? The overall test and the pairwise tests ask different questions, so they can get different answers.
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's procedure? Why should it not be possible? The overall test and the pairwise tests ask different questions, so they can get different answers.
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's proce Why should it not be possible? The overall test and the pairwise tests ask different questions, so they can get different answers.
12,761
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's procedure?
This is mainly due to the sensitivity of ANOVA (greater than the pairwise test sensitivity). Then, ANOVA detect lower variability around mean when pairwise test hardly distinguishes between the pair's mean. The analysis must focus on the differences, and you can be more flexible on the post-hoc analysis, having in mind that you just encountered that there exists differences on the mean. Remember to check the ANOVA assumptions. On the other hand, there are some topics concerning the use of pairwise test without using ANOVA: Do we need a global test before post hoc tests?
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's proce
This is mainly due to the sensitivity of ANOVA (greater than the pairwise test sensitivity). Then, ANOVA detect lower variability around mean when pairwise test hardly distinguishes between the pair
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's procedure? This is mainly due to the sensitivity of ANOVA (greater than the pairwise test sensitivity). Then, ANOVA detect lower variability around mean when pairwise test hardly distinguishes between the pair's mean. The analysis must focus on the differences, and you can be more flexible on the post-hoc analysis, having in mind that you just encountered that there exists differences on the mean. Remember to check the ANOVA assumptions. On the other hand, there are some topics concerning the use of pairwise test without using ANOVA: Do we need a global test before post hoc tests?
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's proce This is mainly due to the sensitivity of ANOVA (greater than the pairwise test sensitivity). Then, ANOVA detect lower variability around mean when pairwise test hardly distinguishes between the pair
12,762
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's procedure?
Below is a copy from an answer to a duplicate question R Tukey HSD Anova: Anova significant, Tukey not? Since this answer is not visible here, and there is no clear link, I create this copy. The relationship between the p-values for the F-test and Tukey HSD test is not one-to-one. (even though both test, indirectly, equality of means $\mu_1=\mu_2=\mu_3$) This is because, for a given distance between the smallest and the largest mean (defining the smallest p-value in Tukey's HSD test), the between group variance (defining the p-value in ANOVA) still depends on the position of the middle mean. The between groups variance is largest when two groups of the three groups cluster together at one end, rather than when the three groups are equally distributed. For instance: the means 0, 0.5 and 1 have a smaller between groups variance than the means 0, 1 and 1. But the largest distance (between the outside groups) is the same. That means the smallest p-value in Tukey HSD test will not be different for those two cases while the ANOVA p-value does differ. So for the experiments with the 5% largest significant differences, you do not get the 5% largest F-scores (or vice versa). It depends on the distribution of the groups and two small p-values in the Tukey test just above 5% can make a F-test with a p-value below 5%. (this becomes even stronger when you have a larger number of groups) The below image is made from a simulation of 1000 draws for three groups of size 50 from a standard normal distribution. It compares the criteria for the Tukey HSD test (showing the smallest and second smallest p-values on the x- and y-axis with two vertical lines at 0.05 and 0.1) with the criteria for the F-test (the red dots have p-value below 0.05, the green dots have p-value above 0.05 and below 0.1, black dots are above 0.1). The p-value for the F-test does not align with the smallest p-value for the Tukey HSD test. The p-value for the F-test can be both higher or lower than the p-value for the lowest p-value in the Tukey HSD test, depending on the other p-values in the Tukey HSD test (this is analogous with the earlier mentioned difference between clustered distribution of group means and even distribution of group means). Note that both the Tukey HSD test (the lowest p-value) and the F-test reject their associated hypothesis for a different fraction of the 1000 simulated experiments, but the sizes of the fractions are equivalent and both correspond to the same type-I error rate.
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's proce
Below is a copy from an answer to a duplicate question R Tukey HSD Anova: Anova significant, Tukey not? Since this answer is not visible here, and there is no clear link, I create this copy. The rela
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's procedure? Below is a copy from an answer to a duplicate question R Tukey HSD Anova: Anova significant, Tukey not? Since this answer is not visible here, and there is no clear link, I create this copy. The relationship between the p-values for the F-test and Tukey HSD test is not one-to-one. (even though both test, indirectly, equality of means $\mu_1=\mu_2=\mu_3$) This is because, for a given distance between the smallest and the largest mean (defining the smallest p-value in Tukey's HSD test), the between group variance (defining the p-value in ANOVA) still depends on the position of the middle mean. The between groups variance is largest when two groups of the three groups cluster together at one end, rather than when the three groups are equally distributed. For instance: the means 0, 0.5 and 1 have a smaller between groups variance than the means 0, 1 and 1. But the largest distance (between the outside groups) is the same. That means the smallest p-value in Tukey HSD test will not be different for those two cases while the ANOVA p-value does differ. So for the experiments with the 5% largest significant differences, you do not get the 5% largest F-scores (or vice versa). It depends on the distribution of the groups and two small p-values in the Tukey test just above 5% can make a F-test with a p-value below 5%. (this becomes even stronger when you have a larger number of groups) The below image is made from a simulation of 1000 draws for three groups of size 50 from a standard normal distribution. It compares the criteria for the Tukey HSD test (showing the smallest and second smallest p-values on the x- and y-axis with two vertical lines at 0.05 and 0.1) with the criteria for the F-test (the red dots have p-value below 0.05, the green dots have p-value above 0.05 and below 0.1, black dots are above 0.1). The p-value for the F-test does not align with the smallest p-value for the Tukey HSD test. The p-value for the F-test can be both higher or lower than the p-value for the lowest p-value in the Tukey HSD test, depending on the other p-values in the Tukey HSD test (this is analogous with the earlier mentioned difference between clustered distribution of group means and even distribution of group means). Note that both the Tukey HSD test (the lowest p-value) and the F-test reject their associated hypothesis for a different fraction of the 1000 simulated experiments, but the sizes of the fractions are equivalent and both correspond to the same type-I error rate.
How can I get a significant overall ANOVA but no significant pairwise differences with Tukey's proce Below is a copy from an answer to a duplicate question R Tukey HSD Anova: Anova significant, Tukey not? Since this answer is not visible here, and there is no clear link, I create this copy. The rela
12,763
How does Naive Bayes work with continuous variables?
There are many ways to perform naive Bayes classification (NBC). A common technique in NBC is to recode the feature (variable) values into quartiles, such that values less than the 25th percentile are assigned a 1, 25th to 50th a 2, 50th to 75th a 3 and greater than the 75th percentile a 4. Thus a single object will deposit one count in bin Q1, Q2, Q3, or Q4. Calculations are merely done on these categorical bins. Bin counts (probabilities) are then based on the number of samples whose variable values fall within a given bin. For example, if a set of objects have very high values for feature X1, then this will result in a lot of bin counts in the bin for Q4 of X1. On the other hand, if another set of objects has low values for feature X1, then those objects will deposit a lot of counts in the bin for Q1 of feature X1. It's actually not a really clever calculation, it's rather a way of discretizing continuous values to discrete, and exploitation thereafter. The Gini index and information gain can be easily calculated after discretization to determine which features are the most informative, i.e., max(Gini). Be advised, however, that there are many ways to perform NBC, and many are quite different from one another. So you just need to state which one you implemented in a talk or paper.
How does Naive Bayes work with continuous variables?
There are many ways to perform naive Bayes classification (NBC). A common technique in NBC is to recode the feature (variable) values into quartiles, such that values less than the 25th percentile ar
How does Naive Bayes work with continuous variables? There are many ways to perform naive Bayes classification (NBC). A common technique in NBC is to recode the feature (variable) values into quartiles, such that values less than the 25th percentile are assigned a 1, 25th to 50th a 2, 50th to 75th a 3 and greater than the 75th percentile a 4. Thus a single object will deposit one count in bin Q1, Q2, Q3, or Q4. Calculations are merely done on these categorical bins. Bin counts (probabilities) are then based on the number of samples whose variable values fall within a given bin. For example, if a set of objects have very high values for feature X1, then this will result in a lot of bin counts in the bin for Q4 of X1. On the other hand, if another set of objects has low values for feature X1, then those objects will deposit a lot of counts in the bin for Q1 of feature X1. It's actually not a really clever calculation, it's rather a way of discretizing continuous values to discrete, and exploitation thereafter. The Gini index and information gain can be easily calculated after discretization to determine which features are the most informative, i.e., max(Gini). Be advised, however, that there are many ways to perform NBC, and many are quite different from one another. So you just need to state which one you implemented in a talk or paper.
How does Naive Bayes work with continuous variables? There are many ways to perform naive Bayes classification (NBC). A common technique in NBC is to recode the feature (variable) values into quartiles, such that values less than the 25th percentile ar
12,764
How does Naive Bayes work with continuous variables?
The heart of Naive Bayes is the heroic conditional assumption: $$P(x \mid X, C) = P(x \mid C)$$ In no way must $x$ be discrete. For example, Gaussian Naive Bayes assumes each category $C$ has a different mean and variance: density $p(x \mid C = i) = \phi(\mu_i, \sigma^2_i)$. There are different ways to estimate the parameters, but typically one might: Use maximum likelihood with labelled data. (In the case of normal distribution, maximum likelihood estimates of the mean and variance are basically the sample mean and the sample variance.) Something like EM Algorithm with unlabelled data.
How does Naive Bayes work with continuous variables?
The heart of Naive Bayes is the heroic conditional assumption: $$P(x \mid X, C) = P(x \mid C)$$ In no way must $x$ be discrete. For example, Gaussian Naive Bayes assumes each category $C$ has a differ
How does Naive Bayes work with continuous variables? The heart of Naive Bayes is the heroic conditional assumption: $$P(x \mid X, C) = P(x \mid C)$$ In no way must $x$ be discrete. For example, Gaussian Naive Bayes assumes each category $C$ has a different mean and variance: density $p(x \mid C = i) = \phi(\mu_i, \sigma^2_i)$. There are different ways to estimate the parameters, but typically one might: Use maximum likelihood with labelled data. (In the case of normal distribution, maximum likelihood estimates of the mean and variance are basically the sample mean and the sample variance.) Something like EM Algorithm with unlabelled data.
How does Naive Bayes work with continuous variables? The heart of Naive Bayes is the heroic conditional assumption: $$P(x \mid X, C) = P(x \mid C)$$ In no way must $x$ be discrete. For example, Gaussian Naive Bayes assumes each category $C$ has a differ
12,765
Why does Ridge Regression work well in the presence of multicollinearity?
Consider the simple case of 2 predictor variables ($x_1$, $x_2$). If there is no or little colinearity and good spread in both predictors, then we are fitting a plane to the data ($y$ is the 3rd dimension) and there is often a very clear "best" plane. But with colinearity the relationship is really a line through 3 dimensional space with data scattered around it. But the regression routine tries to fit a plane to a line, so there are an infinite number of planes that intersect perfectly with that line, which plane is chosen depends on the influential points in the data, change one of those points just a little and the "best" fitting plane changes quite a bit. What ridge regression does is to pull the chosen plane towards simpler/saner models (bias values towards 0). Think of a rubber band from the origin (0,0,0) to the plane that pulls the plane towards 0 while the data will pull it away for a nice compromise.
Why does Ridge Regression work well in the presence of multicollinearity?
Consider the simple case of 2 predictor variables ($x_1$, $x_2$). If there is no or little colinearity and good spread in both predictors, then we are fitting a plane to the data ($y$ is the 3rd dime
Why does Ridge Regression work well in the presence of multicollinearity? Consider the simple case of 2 predictor variables ($x_1$, $x_2$). If there is no or little colinearity and good spread in both predictors, then we are fitting a plane to the data ($y$ is the 3rd dimension) and there is often a very clear "best" plane. But with colinearity the relationship is really a line through 3 dimensional space with data scattered around it. But the regression routine tries to fit a plane to a line, so there are an infinite number of planes that intersect perfectly with that line, which plane is chosen depends on the influential points in the data, change one of those points just a little and the "best" fitting plane changes quite a bit. What ridge regression does is to pull the chosen plane towards simpler/saner models (bias values towards 0). Think of a rubber band from the origin (0,0,0) to the plane that pulls the plane towards 0 while the data will pull it away for a nice compromise.
Why does Ridge Regression work well in the presence of multicollinearity? Consider the simple case of 2 predictor variables ($x_1$, $x_2$). If there is no or little colinearity and good spread in both predictors, then we are fitting a plane to the data ($y$ is the 3rd dime
12,766
If p > n, the lasso selects at most n variables
As said, this is not a property of an algorithm but of the optimization problem. The KKT conditions basically give that for coefficient $\beta_j$ to be non-zero it has to correspond to a fixed correlation with the residual $|X_j^t(y-X\beta)| = \lambda$ ($\lambda$ is the regularization parameter). After resolving the various complications with absolute value etc, you are left with a linear equation for each non-zero coefficient. Since the rank of the matrix $X$ is at most $n$ when $p>n$, this is the number of equations that can be solved, and therefore there are at most n non-zeros (unless there are redundancies). By the way, this is true for any loss function, not only the standard lasso with $L_2$ loss. So it is in fact a property of the lasso penalty. There are many papers that show this KKT view and the resulting conclusions, I can point to our paper: Rosset and Zhu, Piecewise Linear Regularized Solutions Paths, Annals of Stats 2007 and refs therein.
If p > n, the lasso selects at most n variables
As said, this is not a property of an algorithm but of the optimization problem. The KKT conditions basically give that for coefficient $\beta_j$ to be non-zero it has to correspond to a fixed correla
If p > n, the lasso selects at most n variables As said, this is not a property of an algorithm but of the optimization problem. The KKT conditions basically give that for coefficient $\beta_j$ to be non-zero it has to correspond to a fixed correlation with the residual $|X_j^t(y-X\beta)| = \lambda$ ($\lambda$ is the regularization parameter). After resolving the various complications with absolute value etc, you are left with a linear equation for each non-zero coefficient. Since the rank of the matrix $X$ is at most $n$ when $p>n$, this is the number of equations that can be solved, and therefore there are at most n non-zeros (unless there are redundancies). By the way, this is true for any loss function, not only the standard lasso with $L_2$ loss. So it is in fact a property of the lasso penalty. There are many papers that show this KKT view and the resulting conclusions, I can point to our paper: Rosset and Zhu, Piecewise Linear Regularized Solutions Paths, Annals of Stats 2007 and refs therein.
If p > n, the lasso selects at most n variables As said, this is not a property of an algorithm but of the optimization problem. The KKT conditions basically give that for coefficient $\beta_j$ to be non-zero it has to correspond to a fixed correla
12,767
If p > n, the lasso selects at most n variables
Another explanation is the following: if $n < p$, the rank of the data matrix $X$ is at most $n$, so the dimension of its (right) null space is at least $p - n$. Write any vector in this null space as $z$. Then at any feasible point $\beta$, one can always move in this $p - n$-dimensional null space towards the coordinate axes of the $p$-dimensional ambient space, to arrive at a $\beta+z$, where (at most) $n$ $\beta_j$s are nonzero, and the LASSO objective function $$ \|y-X(\beta+z)\|_2^2 + \lambda \|\beta+z\|_1 = \|y-X\beta\|_2^2 + \lambda \|\beta+z\|_1 < \|y-X\beta\|_2^2 + \lambda \|\beta\|_1 $$ has decreased.
If p > n, the lasso selects at most n variables
Another explanation is the following: if $n < p$, the rank of the data matrix $X$ is at most $n$, so the dimension of its (right) null space is at least $p - n$. Write any vector in this null space a
If p > n, the lasso selects at most n variables Another explanation is the following: if $n < p$, the rank of the data matrix $X$ is at most $n$, so the dimension of its (right) null space is at least $p - n$. Write any vector in this null space as $z$. Then at any feasible point $\beta$, one can always move in this $p - n$-dimensional null space towards the coordinate axes of the $p$-dimensional ambient space, to arrive at a $\beta+z$, where (at most) $n$ $\beta_j$s are nonzero, and the LASSO objective function $$ \|y-X(\beta+z)\|_2^2 + \lambda \|\beta+z\|_1 = \|y-X\beta\|_2^2 + \lambda \|\beta+z\|_1 < \|y-X\beta\|_2^2 + \lambda \|\beta\|_1 $$ has decreased.
If p > n, the lasso selects at most n variables Another explanation is the following: if $n < p$, the rank of the data matrix $X$ is at most $n$, so the dimension of its (right) null space is at least $p - n$. Write any vector in this null space a
12,768
An unbiased estimate of the median
Such an estimator does not exist. The intuition is that the median can stay fixed while we freely shift probability density around on both sides of it, so that any estimator whose average value is the median for one distribution will have a different average for the altered distribution, making it biased. The following exposition gives a little more rigor to this intuition. We focus on distributions $F$ having unique medians $m$, so that by definition $F(m) \ge 1/2$ and $F(x) \lt 1/2$ for all $x \lt m$. Fix a sample size $n \ge 1$ and suppose that $t: [0,1]^n \to [0,1]$ estimates $m$. (It will suffice that $t$ only be bounded, but usually one doesn't seriously consider estimators that produce obviously impossible values.) We make no assumptions about $t$; it does not even have to be continuous anywhere. The meaning of $t$ being unbiased (for this fixed sample size) is that $$E_F[t(X_1, \ldots, X_n)] = m$$ for any iid sample with $X_i \sim F$. An "unbiased estimator" $t$ is one with this property for all such $F$. Suppose an unbiased estimator exists. We will derive a contradiction by applying it to a particularly simple set of distributions. Consider distributions $F = F_{x,y,m, \varepsilon}$ having these properties: $0 \le x \lt y \le 1$; $0 \lt \varepsilon \lt (y-x)/4$; $x + \varepsilon \lt m \lt y - \varepsilon$; $\Pr(X = x) = \Pr(X = y) = (1-\varepsilon)/2$; $\Pr(m-\varepsilon \le X \le m+\varepsilon) = \varepsilon$; and $F$ is uniform on $[m-\varepsilon, m+\varepsilon]$. These distributions place probability $(1-\varepsilon)/2$ at each of $x$ and $y$ and a tiny amount of probability symmetrically placed around $m$ between $x$ and $y$. This makes $m$ the unique median of $F$. (If you are concerned that this is not a continuous distribution, then convolve it with a very narrow Gaussian and truncate the result to $[0,1]$: the argument will not change.) Now, for any putative median estimator $t$, an easy estimate shows that $E[t(X_1, X_2, \ldots, X_n)]$ is strictly within $\varepsilon$ of the average of the $2^n$ values $t(x_1, x_2, \ldots, x_n)$ where the $x_i$ vary over all possible combinations of $x$ and $y$. However, we can vary $m$ between $x + \varepsilon$ and $y - \varepsilon$, a change of at least $\varepsilon$ (by virtue of conditions 2 and 3). Thus there exists an $m$, and whence a corresponding distribution $F_{x,y,m,\varepsilon}$, for which this expectation does not equal the median, QED.
An unbiased estimate of the median
Such an estimator does not exist. The intuition is that the median can stay fixed while we freely shift probability density around on both sides of it, so that any estimator whose average value is the
An unbiased estimate of the median Such an estimator does not exist. The intuition is that the median can stay fixed while we freely shift probability density around on both sides of it, so that any estimator whose average value is the median for one distribution will have a different average for the altered distribution, making it biased. The following exposition gives a little more rigor to this intuition. We focus on distributions $F$ having unique medians $m$, so that by definition $F(m) \ge 1/2$ and $F(x) \lt 1/2$ for all $x \lt m$. Fix a sample size $n \ge 1$ and suppose that $t: [0,1]^n \to [0,1]$ estimates $m$. (It will suffice that $t$ only be bounded, but usually one doesn't seriously consider estimators that produce obviously impossible values.) We make no assumptions about $t$; it does not even have to be continuous anywhere. The meaning of $t$ being unbiased (for this fixed sample size) is that $$E_F[t(X_1, \ldots, X_n)] = m$$ for any iid sample with $X_i \sim F$. An "unbiased estimator" $t$ is one with this property for all such $F$. Suppose an unbiased estimator exists. We will derive a contradiction by applying it to a particularly simple set of distributions. Consider distributions $F = F_{x,y,m, \varepsilon}$ having these properties: $0 \le x \lt y \le 1$; $0 \lt \varepsilon \lt (y-x)/4$; $x + \varepsilon \lt m \lt y - \varepsilon$; $\Pr(X = x) = \Pr(X = y) = (1-\varepsilon)/2$; $\Pr(m-\varepsilon \le X \le m+\varepsilon) = \varepsilon$; and $F$ is uniform on $[m-\varepsilon, m+\varepsilon]$. These distributions place probability $(1-\varepsilon)/2$ at each of $x$ and $y$ and a tiny amount of probability symmetrically placed around $m$ between $x$ and $y$. This makes $m$ the unique median of $F$. (If you are concerned that this is not a continuous distribution, then convolve it with a very narrow Gaussian and truncate the result to $[0,1]$: the argument will not change.) Now, for any putative median estimator $t$, an easy estimate shows that $E[t(X_1, X_2, \ldots, X_n)]$ is strictly within $\varepsilon$ of the average of the $2^n$ values $t(x_1, x_2, \ldots, x_n)$ where the $x_i$ vary over all possible combinations of $x$ and $y$. However, we can vary $m$ between $x + \varepsilon$ and $y - \varepsilon$, a change of at least $\varepsilon$ (by virtue of conditions 2 and 3). Thus there exists an $m$, and whence a corresponding distribution $F_{x,y,m,\varepsilon}$, for which this expectation does not equal the median, QED.
An unbiased estimate of the median Such an estimator does not exist. The intuition is that the median can stay fixed while we freely shift probability density around on both sides of it, so that any estimator whose average value is the
12,769
An unbiased estimate of the median
Finding an unbiased estimator without having a parametric model would be difficult! But you could use bootstrapping, and use that to correct the empirical median to get an approximately unbiased estimator.
An unbiased estimate of the median
Finding an unbiased estimator without having a parametric model would be difficult! But you could use bootstrapping, and use that to correct the empirical median to get an approximately unbiased esti
An unbiased estimate of the median Finding an unbiased estimator without having a parametric model would be difficult! But you could use bootstrapping, and use that to correct the empirical median to get an approximately unbiased estimator.
An unbiased estimate of the median Finding an unbiased estimator without having a parametric model would be difficult! But you could use bootstrapping, and use that to correct the empirical median to get an approximately unbiased esti
12,770
An unbiased estimate of the median
I believe quantile regression will give you a consistent estimator of the median. Given the model $Y = \alpha + u$. And you want to estimate $\text{med}(y) = \text{med}(\alpha + u) = \alpha + \text{med}(u)$ since $\alpha$ is a constant. All you need is the $\text{med}(u) = 0$ which should be true so long as you have independent draws. However, as far as unbiasedness, I don't know. Medians are difficult.
An unbiased estimate of the median
I believe quantile regression will give you a consistent estimator of the median. Given the model $Y = \alpha + u$. And you want to estimate $\text{med}(y) = \text{med}(\alpha + u) = \alpha + \text{
An unbiased estimate of the median I believe quantile regression will give you a consistent estimator of the median. Given the model $Y = \alpha + u$. And you want to estimate $\text{med}(y) = \text{med}(\alpha + u) = \alpha + \text{med}(u)$ since $\alpha$ is a constant. All you need is the $\text{med}(u) = 0$ which should be true so long as you have independent draws. However, as far as unbiasedness, I don't know. Medians are difficult.
An unbiased estimate of the median I believe quantile regression will give you a consistent estimator of the median. Given the model $Y = \alpha + u$. And you want to estimate $\text{med}(y) = \text{med}(\alpha + u) = \alpha + \text{
12,771
An unbiased estimate of the median
The average is not the exclusive statistic that can be used to measure the central tendency of the bias of an estimator, and by restricting yourself to the average the problem ends up being the equivalent of saying that the average does not equal the median. Take n=1 (just sample populations consisting of a single sample) so that the only value an estimator t of the median m of the population distribution X, t(X_1), can have is X_1, thus E(t(X_1))=E(X_1)=E(X)!=m, therefore it seems there can be no unbiased estimator of m. Yet median(t(X_1))=median(X_1)=median(X)=m... therefore an unbiased estimator does exist: the sample median!
An unbiased estimate of the median
The average is not the exclusive statistic that can be used to measure the central tendency of the bias of an estimator, and by restricting yourself to the average the problem ends up being the equiva
An unbiased estimate of the median The average is not the exclusive statistic that can be used to measure the central tendency of the bias of an estimator, and by restricting yourself to the average the problem ends up being the equivalent of saying that the average does not equal the median. Take n=1 (just sample populations consisting of a single sample) so that the only value an estimator t of the median m of the population distribution X, t(X_1), can have is X_1, thus E(t(X_1))=E(X_1)=E(X)!=m, therefore it seems there can be no unbiased estimator of m. Yet median(t(X_1))=median(X_1)=median(X)=m... therefore an unbiased estimator does exist: the sample median!
An unbiased estimate of the median The average is not the exclusive statistic that can be used to measure the central tendency of the bias of an estimator, and by restricting yourself to the average the problem ends up being the equiva
12,772
Paired t-test as a special case of linear mixed-effect modeling
The equivalence of the models can be observed by calculating the correlation between two observations from the same individual, as follows: As in your notation, let $Y_{ij} = \mu + \alpha_i + \beta_j + \epsilon_{ij}$, where $\beta_j \sim N(0, \sigma_p^2)$ and $\epsilon_{ij} \sim N(0, \sigma^2)$. Then $Cov(y_{ik}, y_{jk}) = Cov(\mu + \alpha_i + \beta_k + \epsilon_{ik}, \mu + \alpha_j + \beta_k + \epsilon_{jk}) = Cov(\beta_k, \beta_k) = \sigma_p^2$, because all other terms are independent or fixed, and $Var(y_{ik}) = Var(y_{jk}) = \sigma_p^2 + \sigma^2$, so the correlation is $\sigma_p^2/(\sigma_p^2 + \sigma^2)$. Note that the models however are not quite equivalent as the random effect model forces the correlation to be positive. The CS model and the t-test/anova model do not. EDIT: There are two other differences as well. First, the CS and random effect models assume normality for the random effect, but the t-test/anova model does not. Secondly, the CS and random effect models are fit using maximum likelihood, while the anova is fit using mean squares; when everything is balanced they will agree, but not necessarily in more complex situations. Finally, I'd be wary of using F/df/p values from the various fits as measures of how much the models agree; see Doug Bates's famous screed on df's for more details. (END EDIT) The problem with your R code is that you're not specifying the correlation structure properly. You need to use gls with the corCompSymm correlation structure. Generate data so that there is a subject effect: set.seed(5) x <- rnorm(10) x1<-x+rnorm(10) x2<-x+1 + rnorm(10) myDat <- data.frame(c(x1,x2), c(rep("x1", 10), rep("x2", 10)), rep(paste("S", seq(1,10), sep=""), 2)) names(myDat) <- c("y", "x", "subj") Then here's how you'd fit the random effects and the compound symmetry models. library(nlme) fm1 <- lme(y ~ x, random=~1|subj, data=myDat) fm2 <- gls(y ~ x, correlation=corCompSymm(form=~1|subj), data=myDat) The standard errors from the random effects model are: m1.varp <- 0.5453527^2 m1.vare <- 1.084408^2 And the correlation and residual variance from the CS model is: m2.rho <- 0.2018595 m2.var <- 1.213816^2 And they're equal to what is expected: > m1.varp/(m1.varp+m1.vare) [1] 0.2018594 > sqrt(m1.varp + m1.vare) [1] 1.213816 Other correlation structures are usually not fit with random effects but simply by specifying the desired structure; one common exception is the AR(1) + random effect model, which has a random effect and AR(1) correlation between observations on the same random effect. EDIT2: When I fit the three options, I get exactly the same results except that gls doesn't try to guess the df for the term of interest. > summary(fm1) ... Fixed effects: y ~ x Value Std.Error DF t-value p-value (Intercept) -0.5611156 0.3838423 9 -1.461839 0.1778 xx2 2.0772757 0.4849618 9 4.283380 0.0020 > summary(fm2) ... Value Std.Error t-value p-value (Intercept) -0.5611156 0.3838423 -1.461839 0.1610 xx2 2.0772757 0.4849618 4.283380 0.0004 > m1 <- lm(y~ x + subj, data=myDat) > summary(m1) ... Estimate Std. Error t value Pr(>|t|) (Intercept) -0.3154 0.8042 -0.392 0.70403 xx2 2.0773 0.4850 4.283 0.00204 ** (The intercept is different here because with the default coding, it's not the mean of all subjects but instead the mean of the first subject.) It's also of interest to note that the newer lme4 package gives the same results but doesn't even try to compute a p-value. > mm1 <- lmer(y ~ x + (1|subj), data=myDat) > summary(mm1) ... Estimate Std. Error t value (Intercept) -0.5611 0.3838 -1.462 xx2 2.0773 0.4850 4.283
Paired t-test as a special case of linear mixed-effect modeling
The equivalence of the models can be observed by calculating the correlation between two observations from the same individual, as follows: As in your notation, let $Y_{ij} = \mu + \alpha_i + \beta_j
Paired t-test as a special case of linear mixed-effect modeling The equivalence of the models can be observed by calculating the correlation between two observations from the same individual, as follows: As in your notation, let $Y_{ij} = \mu + \alpha_i + \beta_j + \epsilon_{ij}$, where $\beta_j \sim N(0, \sigma_p^2)$ and $\epsilon_{ij} \sim N(0, \sigma^2)$. Then $Cov(y_{ik}, y_{jk}) = Cov(\mu + \alpha_i + \beta_k + \epsilon_{ik}, \mu + \alpha_j + \beta_k + \epsilon_{jk}) = Cov(\beta_k, \beta_k) = \sigma_p^2$, because all other terms are independent or fixed, and $Var(y_{ik}) = Var(y_{jk}) = \sigma_p^2 + \sigma^2$, so the correlation is $\sigma_p^2/(\sigma_p^2 + \sigma^2)$. Note that the models however are not quite equivalent as the random effect model forces the correlation to be positive. The CS model and the t-test/anova model do not. EDIT: There are two other differences as well. First, the CS and random effect models assume normality for the random effect, but the t-test/anova model does not. Secondly, the CS and random effect models are fit using maximum likelihood, while the anova is fit using mean squares; when everything is balanced they will agree, but not necessarily in more complex situations. Finally, I'd be wary of using F/df/p values from the various fits as measures of how much the models agree; see Doug Bates's famous screed on df's for more details. (END EDIT) The problem with your R code is that you're not specifying the correlation structure properly. You need to use gls with the corCompSymm correlation structure. Generate data so that there is a subject effect: set.seed(5) x <- rnorm(10) x1<-x+rnorm(10) x2<-x+1 + rnorm(10) myDat <- data.frame(c(x1,x2), c(rep("x1", 10), rep("x2", 10)), rep(paste("S", seq(1,10), sep=""), 2)) names(myDat) <- c("y", "x", "subj") Then here's how you'd fit the random effects and the compound symmetry models. library(nlme) fm1 <- lme(y ~ x, random=~1|subj, data=myDat) fm2 <- gls(y ~ x, correlation=corCompSymm(form=~1|subj), data=myDat) The standard errors from the random effects model are: m1.varp <- 0.5453527^2 m1.vare <- 1.084408^2 And the correlation and residual variance from the CS model is: m2.rho <- 0.2018595 m2.var <- 1.213816^2 And they're equal to what is expected: > m1.varp/(m1.varp+m1.vare) [1] 0.2018594 > sqrt(m1.varp + m1.vare) [1] 1.213816 Other correlation structures are usually not fit with random effects but simply by specifying the desired structure; one common exception is the AR(1) + random effect model, which has a random effect and AR(1) correlation between observations on the same random effect. EDIT2: When I fit the three options, I get exactly the same results except that gls doesn't try to guess the df for the term of interest. > summary(fm1) ... Fixed effects: y ~ x Value Std.Error DF t-value p-value (Intercept) -0.5611156 0.3838423 9 -1.461839 0.1778 xx2 2.0772757 0.4849618 9 4.283380 0.0020 > summary(fm2) ... Value Std.Error t-value p-value (Intercept) -0.5611156 0.3838423 -1.461839 0.1610 xx2 2.0772757 0.4849618 4.283380 0.0004 > m1 <- lm(y~ x + subj, data=myDat) > summary(m1) ... Estimate Std. Error t value Pr(>|t|) (Intercept) -0.3154 0.8042 -0.392 0.70403 xx2 2.0773 0.4850 4.283 0.00204 ** (The intercept is different here because with the default coding, it's not the mean of all subjects but instead the mean of the first subject.) It's also of interest to note that the newer lme4 package gives the same results but doesn't even try to compute a p-value. > mm1 <- lmer(y ~ x + (1|subj), data=myDat) > summary(mm1) ... Estimate Std. Error t value (Intercept) -0.5611 0.3838 -1.462 xx2 2.0773 0.4850 4.283
Paired t-test as a special case of linear mixed-effect modeling The equivalence of the models can be observed by calculating the correlation between two observations from the same individual, as follows: As in your notation, let $Y_{ij} = \mu + \alpha_i + \beta_j
12,773
Paired t-test as a special case of linear mixed-effect modeling
You might also consider using function mixed in package afex to return p values with Kenward-Roger df approximation, which returns identical p values as a paired t test: library(afex) mixed(y ~ x + (1|subj), type=3,method="KR",data=myDat) Or library(lmerTest) options(contrasts=c('contr.sum', 'contr.poly')) anova(lmer(y ~ x + (1|subj),data=myDat),ddf="Kenward-Roger")
Paired t-test as a special case of linear mixed-effect modeling
You might also consider using function mixed in package afex to return p values with Kenward-Roger df approximation, which returns identical p values as a paired t test: library(afex) mixed(y ~ x + (1
Paired t-test as a special case of linear mixed-effect modeling You might also consider using function mixed in package afex to return p values with Kenward-Roger df approximation, which returns identical p values as a paired t test: library(afex) mixed(y ~ x + (1|subj), type=3,method="KR",data=myDat) Or library(lmerTest) options(contrasts=c('contr.sum', 'contr.poly')) anova(lmer(y ~ x + (1|subj),data=myDat),ddf="Kenward-Roger")
Paired t-test as a special case of linear mixed-effect modeling You might also consider using function mixed in package afex to return p values with Kenward-Roger df approximation, which returns identical p values as a paired t test: library(afex) mixed(y ~ x + (1
12,774
What is the difference between logistic regression and Fractional response regression?
If your question is: what is the difference between these two codes? A look at ?glm says See family for details of family functions, and a look at ?family reveals the following description: The quasibinomial and quasipoisson families differ from the binomial and poisson families only in that the dispersion parameter is not fixed at one, so they can model over-dispersion. This is also what you see in your output. And that is the difference between both models / codes. If your question is: what is the difference between the logistic regression and the fractional response regression? As you correctly identify, the model is a logistic one if your dependent variables are either 0 or 1. Papke and Wooldridge have shown that you can use a GLM of this form for fractions as well for the estimation of the parameters, but you need to compute robust standard errors. This is not required for the logistic regression, and in fact, some people think you should not compute robust standard errors in probit/logit models. Though this is a different debate. The theoretical basis comes from a famous paper by Gourieroux, Monfort, and Trognon in Econometrica in 1984. They show that (under some regularity conditions etc) maximum likelihood parameters obtained by maximizing a likelihood that belongs to the linear exponential family are consistent estimates for parameters belonging to any other likelihood in the linear exponential family. So, in some sense, we are using the logistic distribution here even though it is not exactly the correct one, but the parameters are still consistent for the parameters that we wish to obtain. So, if your question originates from the observation that we are using the very same likelihood function to estimate both logistic and fractional response models, except that we exchange the nature of the dependent variable, then this is the intuition.
What is the difference between logistic regression and Fractional response regression?
If your question is: what is the difference between these two codes? A look at ?glm says See family for details of family functions, and a look at ?family reveals the following description: The quasi
What is the difference between logistic regression and Fractional response regression? If your question is: what is the difference between these two codes? A look at ?glm says See family for details of family functions, and a look at ?family reveals the following description: The quasibinomial and quasipoisson families differ from the binomial and poisson families only in that the dispersion parameter is not fixed at one, so they can model over-dispersion. This is also what you see in your output. And that is the difference between both models / codes. If your question is: what is the difference between the logistic regression and the fractional response regression? As you correctly identify, the model is a logistic one if your dependent variables are either 0 or 1. Papke and Wooldridge have shown that you can use a GLM of this form for fractions as well for the estimation of the parameters, but you need to compute robust standard errors. This is not required for the logistic regression, and in fact, some people think you should not compute robust standard errors in probit/logit models. Though this is a different debate. The theoretical basis comes from a famous paper by Gourieroux, Monfort, and Trognon in Econometrica in 1984. They show that (under some regularity conditions etc) maximum likelihood parameters obtained by maximizing a likelihood that belongs to the linear exponential family are consistent estimates for parameters belonging to any other likelihood in the linear exponential family. So, in some sense, we are using the logistic distribution here even though it is not exactly the correct one, but the parameters are still consistent for the parameters that we wish to obtain. So, if your question originates from the observation that we are using the very same likelihood function to estimate both logistic and fractional response models, except that we exchange the nature of the dependent variable, then this is the intuition.
What is the difference between logistic regression and Fractional response regression? If your question is: what is the difference between these two codes? A look at ?glm says See family for details of family functions, and a look at ?family reveals the following description: The quasi
12,775
How to summarize credible intervals for a medical audience
Quick thoughts: 1) The key issue is what applied question you are trying to answer for your audience, because that determines what information you want from your statistical analysis. In this case, it seems to me that you want to estimate the magnitude of differences between groups (or perhaps the magnitude of ratios of the groups if that is the measure more familiar to your audience). The magnitude of differences is not directly provided by the analyses you presented in the question. But it is straight forward to get what you want from the Bayesian analysis: you want the posterior distribution of the differences (or ratios). Then, from the posterior distribution of the differences (or ratios), you can make a direct probability statement such as this: "The 95% most credible differences fall between [low 95% HDI limit] and [high 95% HDI limit]" (here I'm using the 95% highest density interval [HDI] as the credible interval, and because those are by definition the highest density parameter values they are glossed as 'most credible') A medical-journal audience would intuitively and correctly understand that statement, because it's what the audience typically thinks is the meaning of a frequentist confidence interval (even though that's not meaning of a frequentist confidence interval). How do you get the differences (or ratios) from Stan or JAGS? Merely by post-processing of the completed MCMC chain. At each step in the chain, compute the relevant differences (or ratios), then examine the posterior distribution of the differences (or ratios). Examples are given in DBDA2E https://sites.google.com/site/doingbayesiandataanalysis/ for MCMC generally in Figure 7.9 (p. 177), for JAGS in Figure 8.6 (p. 211), and for Stan in Section 16.3 (p. 468), etc.! 2) If you are compelled by tradition to make a statement about whether or not a difference of zero is rejected, you have two Bayesian options. 2A) One option is to make probability statements regarding intervals near zero, and their relation to the HDI. For this, you set up a region of practical equivalence (ROPE) around zero, which is merely a decision threshold appropriate for your applied domain --- how big of a difference is trivially small? Setting such boundaries is routinely done in clinical non-inferiority testing, for example. If you have an 'effect size' measure in your field, there might be conventions for 'small' effect size, and the ROPE limits could be, say, half of a small effect. Then you can make direct probability statements such as these: "Only 1.2% of the posterior distribution of differences is practically equivalent to zero" and "The 95% most credible differences are all not practically equivalent to zero (i.e., the 95% HDI and ROPE do not overlap) and therefore we reject zero." (notice the distinction between the probability statement from the posterior distribution, versus the subsequent decision based on that statement) You can also accept a difference of zero, for practical purposes, if the 95% most credible values are all practically equivalent ot zero. 2B) A second Bayesian option is Bayesian null hypothesis testing. (Notice that the method above was not called "hypothesis testing"!) Bayesian null hypothesis testing does a Bayesian model comparison of a prior distribution that assumes the difference can only be zero against an alternative prior distribution that assumes the difference could be some diffuse range of possibilities. The result of such a model comparison (usually) depends very strongly on the particular choice of alternative distribution, and so careful justification must be made for the choice of alternative prior. It is best to use at-least-mildly-informed priors for both the null and alternative so that the model comparison is genuinely meaningful. Note that the model comparison provides different information than estimation of differences between groups because the model comparison is addressing a different question. Thus, even with a model comparison, you will still want to provide the posterior distribution of magnitude of differences between groups because the your audience will want to know the magnitude of difference and its uncertainty (credible interval) regardless of whether or not you decided to reject or accept a difference of zero. There might be ways to do a Bayesian null hypothesis test from the Stan/JAGS/MCMC output, but I do not know in this case. For example, one could try a Savage-Dickey approximation to a Bayes factor, but that would rely on knowing the prior density on the differences, which would require some mathematical analysis or some additional MCMC approximation from the prior. The two methods for deciding about null values are discussed in Ch. 12 of DBDA2E https://sites.google.com/site/doingbayesiandataanalysis/. But I really don't want this discussion to get side-tracked by a debate about the "proper" way to assess null values; they're just different and they provide different information. The main point of my reply is point 1, above: Look at the posterior distribution of the differences between groups.
How to summarize credible intervals for a medical audience
Quick thoughts: 1) The key issue is what applied question you are trying to answer for your audience, because that determines what information you want from your statistical analysis. In this case, i
How to summarize credible intervals for a medical audience Quick thoughts: 1) The key issue is what applied question you are trying to answer for your audience, because that determines what information you want from your statistical analysis. In this case, it seems to me that you want to estimate the magnitude of differences between groups (or perhaps the magnitude of ratios of the groups if that is the measure more familiar to your audience). The magnitude of differences is not directly provided by the analyses you presented in the question. But it is straight forward to get what you want from the Bayesian analysis: you want the posterior distribution of the differences (or ratios). Then, from the posterior distribution of the differences (or ratios), you can make a direct probability statement such as this: "The 95% most credible differences fall between [low 95% HDI limit] and [high 95% HDI limit]" (here I'm using the 95% highest density interval [HDI] as the credible interval, and because those are by definition the highest density parameter values they are glossed as 'most credible') A medical-journal audience would intuitively and correctly understand that statement, because it's what the audience typically thinks is the meaning of a frequentist confidence interval (even though that's not meaning of a frequentist confidence interval). How do you get the differences (or ratios) from Stan or JAGS? Merely by post-processing of the completed MCMC chain. At each step in the chain, compute the relevant differences (or ratios), then examine the posterior distribution of the differences (or ratios). Examples are given in DBDA2E https://sites.google.com/site/doingbayesiandataanalysis/ for MCMC generally in Figure 7.9 (p. 177), for JAGS in Figure 8.6 (p. 211), and for Stan in Section 16.3 (p. 468), etc.! 2) If you are compelled by tradition to make a statement about whether or not a difference of zero is rejected, you have two Bayesian options. 2A) One option is to make probability statements regarding intervals near zero, and their relation to the HDI. For this, you set up a region of practical equivalence (ROPE) around zero, which is merely a decision threshold appropriate for your applied domain --- how big of a difference is trivially small? Setting such boundaries is routinely done in clinical non-inferiority testing, for example. If you have an 'effect size' measure in your field, there might be conventions for 'small' effect size, and the ROPE limits could be, say, half of a small effect. Then you can make direct probability statements such as these: "Only 1.2% of the posterior distribution of differences is practically equivalent to zero" and "The 95% most credible differences are all not practically equivalent to zero (i.e., the 95% HDI and ROPE do not overlap) and therefore we reject zero." (notice the distinction between the probability statement from the posterior distribution, versus the subsequent decision based on that statement) You can also accept a difference of zero, for practical purposes, if the 95% most credible values are all practically equivalent ot zero. 2B) A second Bayesian option is Bayesian null hypothesis testing. (Notice that the method above was not called "hypothesis testing"!) Bayesian null hypothesis testing does a Bayesian model comparison of a prior distribution that assumes the difference can only be zero against an alternative prior distribution that assumes the difference could be some diffuse range of possibilities. The result of such a model comparison (usually) depends very strongly on the particular choice of alternative distribution, and so careful justification must be made for the choice of alternative prior. It is best to use at-least-mildly-informed priors for both the null and alternative so that the model comparison is genuinely meaningful. Note that the model comparison provides different information than estimation of differences between groups because the model comparison is addressing a different question. Thus, even with a model comparison, you will still want to provide the posterior distribution of magnitude of differences between groups because the your audience will want to know the magnitude of difference and its uncertainty (credible interval) regardless of whether or not you decided to reject or accept a difference of zero. There might be ways to do a Bayesian null hypothesis test from the Stan/JAGS/MCMC output, but I do not know in this case. For example, one could try a Savage-Dickey approximation to a Bayes factor, but that would rely on knowing the prior density on the differences, which would require some mathematical analysis or some additional MCMC approximation from the prior. The two methods for deciding about null values are discussed in Ch. 12 of DBDA2E https://sites.google.com/site/doingbayesiandataanalysis/. But I really don't want this discussion to get side-tracked by a debate about the "proper" way to assess null values; they're just different and they provide different information. The main point of my reply is point 1, above: Look at the posterior distribution of the differences between groups.
How to summarize credible intervals for a medical audience Quick thoughts: 1) The key issue is what applied question you are trying to answer for your audience, because that determines what information you want from your statistical analysis. In this case, i
12,776
How to summarize credible intervals for a medical audience
Following SO etiquette, this should have been written as a comment to @John K. Kruschke, but longer comments are difficult to structure. Sorry. @John K. Kruschke writes: Merely by post-processing of the completed MCMC chain... lower_CredI and upper_CredI in the original post were computed as you mentioned from the full MCMC chains and are only slightly reformatted for better comparison with lme output. While you favor HDI, these are simple quantiles; with the symmetrical posterior in this example it does not make a big difference. ROPE and effect size I have seen applications to ethics committees were statistical power was computed without stating the assumption about effect size. Even for the case where there is no way around defining a "clinically relevant effect", it is difficult to explain the concept to medical researchers. It is a bit easier for non-inferiority trials, but these are not as often subject of a study. So I am quite sure that introducing ROPES will not be acceptable - another assumptions, people cannot keep more than one number in mind. Bayes factors might work, because there is only one number to take home like p-values before. Priors I am a surprised that neither @John K. Kruschke nor @Ben Goodrich from the Stan team mention priors; most papers on the subject ask for detailed discussion of prior sensitivity when presenting results. It would be nice if in the next edition of your book - hopefully with Stan - you could add boxes "How to publish this (in a non-statistical paper) with 100 words" for selected examples. When I would take your chapter 23.1 by word, a typical medical research paper would by 100 pages and figures long...
How to summarize credible intervals for a medical audience
Following SO etiquette, this should have been written as a comment to @John K. Kruschke, but longer comments are difficult to structure. Sorry. @John K. Kruschke writes: Merely by post-processing of
How to summarize credible intervals for a medical audience Following SO etiquette, this should have been written as a comment to @John K. Kruschke, but longer comments are difficult to structure. Sorry. @John K. Kruschke writes: Merely by post-processing of the completed MCMC chain... lower_CredI and upper_CredI in the original post were computed as you mentioned from the full MCMC chains and are only slightly reformatted for better comparison with lme output. While you favor HDI, these are simple quantiles; with the symmetrical posterior in this example it does not make a big difference. ROPE and effect size I have seen applications to ethics committees were statistical power was computed without stating the assumption about effect size. Even for the case where there is no way around defining a "clinically relevant effect", it is difficult to explain the concept to medical researchers. It is a bit easier for non-inferiority trials, but these are not as often subject of a study. So I am quite sure that introducing ROPES will not be acceptable - another assumptions, people cannot keep more than one number in mind. Bayes factors might work, because there is only one number to take home like p-values before. Priors I am a surprised that neither @John K. Kruschke nor @Ben Goodrich from the Stan team mention priors; most papers on the subject ask for detailed discussion of prior sensitivity when presenting results. It would be nice if in the next edition of your book - hopefully with Stan - you could add boxes "How to publish this (in a non-statistical paper) with 100 words" for selected examples. When I would take your chapter 23.1 by word, a typical medical research paper would by 100 pages and figures long...
How to summarize credible intervals for a medical audience Following SO etiquette, this should have been written as a comment to @John K. Kruschke, but longer comments are difficult to structure. Sorry. @John K. Kruschke writes: Merely by post-processing of
12,777
How to keep exploratory analyses of large datasets in check?
I think that frequently, the tendency to feel like you've gone down a rabbit hole with exploratory analyses is due to losing sight of the substantive question(s) you're asking. I do it myself, occasionally, and then have to remind myself what my goal(s) are. For example, am I trying to build a specific model, or evaluate the adequacy of an existing one? Am I looking for evidence of problems with the data (i.e., forensic data analysis)? Or, is this in the early stages of analysis, where I am investigating specific questions informally (e.g., is there a relationship between two variables?) before moving on to develop a formal model? In sum, if you catch yourself cranking out plots and tables but can't state clearly what your immediate goal is or why that plot/table is relevant, then you know you're getting pulled along by the activity (instead of being in control of it). I try to approach exploratory data analysis like I do writing, whether that be writing a program or writing an article. In either case, I wouldn't start without making an outline first. That outline can change (and frequently does), of course, but to start writing without one is inefficient, and often yields a poor final product. WRT organization, each analyst has to find a workflow that works for him or her—doing so is IMO more important than trying to follow rigidly someone else's workflow (though it is always helpful to get ideas from what others are doing). If you're working programmatically (i.e., writing code that can be run to generate/regenerate a set of results) and checking your work into git, then you're already miles ahead of many in this regard. I suspect that you may just need to spend some time organizing your code, and for that, I would suggest following your outline. For example, keep your analysis files relatively short and targeted, so that each answers one specific question (e.g., diagnostic plots for a specific regression model). Organize these into subdirectories at one or two levels, depending on the size and complexity of the project. In this way, the project becomes self-documenting; a list view of the directories, subdirectories and files (together with the comment at the top of each file) should, in theory, reproduce your outline. Of course, in a large project, you might also have code that does data cleaning and management, code you've written to estimate a certain type of model, or other utilities you've written, and these won't fit within the substantive outline for your data analysis, so they should be organized in a different part of your project folder. Update: After posting this, I realized that I didn't directly address your question about "dead ends." If you really decide that an entire set of analyses is of no value, then if you're working in git, you can always delete the corresponding file(s) with a commit message like "Abandoned this line of analysis because it wasn't productive." Unlike crumpling up what you've written and throwing it in the trash, you can always go back to what you did later on, if desired. However, I think you'll find that if you proceed from an outline to which you've given some thought, you'll have fewer so-called dead-ends. Instead, if you spend time investigating a worthwhile and relevant question—even if this leads to a null finding or doesn't turn out like you anticipated—you probably still want to keep a record of what you've done and the outcome (at a minimum, so that you don't make the mistake of repeating this later on). Just move these to the bottom of your outline, in a sort of "Appendix."
How to keep exploratory analyses of large datasets in check?
I think that frequently, the tendency to feel like you've gone down a rabbit hole with exploratory analyses is due to losing sight of the substantive question(s) you're asking. I do it myself, occasio
How to keep exploratory analyses of large datasets in check? I think that frequently, the tendency to feel like you've gone down a rabbit hole with exploratory analyses is due to losing sight of the substantive question(s) you're asking. I do it myself, occasionally, and then have to remind myself what my goal(s) are. For example, am I trying to build a specific model, or evaluate the adequacy of an existing one? Am I looking for evidence of problems with the data (i.e., forensic data analysis)? Or, is this in the early stages of analysis, where I am investigating specific questions informally (e.g., is there a relationship between two variables?) before moving on to develop a formal model? In sum, if you catch yourself cranking out plots and tables but can't state clearly what your immediate goal is or why that plot/table is relevant, then you know you're getting pulled along by the activity (instead of being in control of it). I try to approach exploratory data analysis like I do writing, whether that be writing a program or writing an article. In either case, I wouldn't start without making an outline first. That outline can change (and frequently does), of course, but to start writing without one is inefficient, and often yields a poor final product. WRT organization, each analyst has to find a workflow that works for him or her—doing so is IMO more important than trying to follow rigidly someone else's workflow (though it is always helpful to get ideas from what others are doing). If you're working programmatically (i.e., writing code that can be run to generate/regenerate a set of results) and checking your work into git, then you're already miles ahead of many in this regard. I suspect that you may just need to spend some time organizing your code, and for that, I would suggest following your outline. For example, keep your analysis files relatively short and targeted, so that each answers one specific question (e.g., diagnostic plots for a specific regression model). Organize these into subdirectories at one or two levels, depending on the size and complexity of the project. In this way, the project becomes self-documenting; a list view of the directories, subdirectories and files (together with the comment at the top of each file) should, in theory, reproduce your outline. Of course, in a large project, you might also have code that does data cleaning and management, code you've written to estimate a certain type of model, or other utilities you've written, and these won't fit within the substantive outline for your data analysis, so they should be organized in a different part of your project folder. Update: After posting this, I realized that I didn't directly address your question about "dead ends." If you really decide that an entire set of analyses is of no value, then if you're working in git, you can always delete the corresponding file(s) with a commit message like "Abandoned this line of analysis because it wasn't productive." Unlike crumpling up what you've written and throwing it in the trash, you can always go back to what you did later on, if desired. However, I think you'll find that if you proceed from an outline to which you've given some thought, you'll have fewer so-called dead-ends. Instead, if you spend time investigating a worthwhile and relevant question—even if this leads to a null finding or doesn't turn out like you anticipated—you probably still want to keep a record of what you've done and the outcome (at a minimum, so that you don't make the mistake of repeating this later on). Just move these to the bottom of your outline, in a sort of "Appendix."
How to keep exploratory analyses of large datasets in check? I think that frequently, the tendency to feel like you've gone down a rabbit hole with exploratory analyses is due to losing sight of the substantive question(s) you're asking. I do it myself, occasio
12,778
How to keep exploratory analyses of large datasets in check?
I don't know how helpful a general answer will be. You're asking how to do something difficult; good answers will probably depend on the discipline and will probably be long and nuanced. :) As far as organization goes, you're already using git, so next you should start using a makefile to execute the analysis. The makefile lays out how different files depend on each other (i.e., which statistics are derived from which code) and when you call make, everything that needs to be updated will. Now, that doesn't help with the exploratory part. For EDA I use (mostly) R in emacs via ESS. You need need need a REPL for EDA. My workflow is to play with plots, estimates, etc. in ESS (in an exploratory.R type file), decide what I want to keep, then recode it so that it can be batch-executed by make. Re: git, I don't know how you're using it, but I use a single repository for each project (usually a single paper) and rebase the hell out of my codebase to keep a clean history; i.e. I use $ git merge meandering-branch --squash $ git add -p somefile $ git rebase -i master $ git reset HEAD --hard way more than when I started with git, and way more than I'd recommend a beginner. If you're not familiar with all of those commands and options, you may want to learn more git. The biggest thing that's helped me is to be disciplined about making logically distinct commits; i.e. every commit should contain all of the changes that you might want to undo all at once in the future (and no more or less). As far as actually exploring the data, I've found these books helpful and interesting, and they deal specifically with large datasets (at least in parts): The Graphics of Large Datasets, edited by Unwin, Theus, and Hofmann. via springerlink if you have access, otherwise individual chapters are probably available by googling. The handbook of data visualization, edited by Chen, Härdle, and Unwin. also via springerlink Data Analysis by Huber (2011)..
How to keep exploratory analyses of large datasets in check?
I don't know how helpful a general answer will be. You're asking how to do something difficult; good answers will probably depend on the discipline and will probably be long and nuanced. :) As far as
How to keep exploratory analyses of large datasets in check? I don't know how helpful a general answer will be. You're asking how to do something difficult; good answers will probably depend on the discipline and will probably be long and nuanced. :) As far as organization goes, you're already using git, so next you should start using a makefile to execute the analysis. The makefile lays out how different files depend on each other (i.e., which statistics are derived from which code) and when you call make, everything that needs to be updated will. Now, that doesn't help with the exploratory part. For EDA I use (mostly) R in emacs via ESS. You need need need a REPL for EDA. My workflow is to play with plots, estimates, etc. in ESS (in an exploratory.R type file), decide what I want to keep, then recode it so that it can be batch-executed by make. Re: git, I don't know how you're using it, but I use a single repository for each project (usually a single paper) and rebase the hell out of my codebase to keep a clean history; i.e. I use $ git merge meandering-branch --squash $ git add -p somefile $ git rebase -i master $ git reset HEAD --hard way more than when I started with git, and way more than I'd recommend a beginner. If you're not familiar with all of those commands and options, you may want to learn more git. The biggest thing that's helped me is to be disciplined about making logically distinct commits; i.e. every commit should contain all of the changes that you might want to undo all at once in the future (and no more or less). As far as actually exploring the data, I've found these books helpful and interesting, and they deal specifically with large datasets (at least in parts): The Graphics of Large Datasets, edited by Unwin, Theus, and Hofmann. via springerlink if you have access, otherwise individual chapters are probably available by googling. The handbook of data visualization, edited by Chen, Härdle, and Unwin. also via springerlink Data Analysis by Huber (2011)..
How to keep exploratory analyses of large datasets in check? I don't know how helpful a general answer will be. You're asking how to do something difficult; good answers will probably depend on the discipline and will probably be long and nuanced. :) As far as
12,779
How to keep exploratory analyses of large datasets in check?
Two words: concept map. That's the only effective way I have found to divide and conquer large data sets or any concept that's really convoluted. http://en.wikipedia.org/wiki/Concept_maps Personally, I think better on paper than on screen, so I just mind map what I'm dealing with before I even start to do any basic analysis. For a more professional diagram, there are lots of mind mapping software http://en.wikipedia.org/wiki/List_of_concept-_and_mind-mapping_software Mind mapping has several advantages: tells me what I have in terms of "core" variables and derived variables (if any) allows for the organization/formulation of a model based on theory/logic points to what variables I may be missing and/or could add if the relationships between the core variables don't pan out like I think they should Edit: As an example, here is the concept map for factor analysis: http://www.metacademy.org/graphs/concepts/factor_analysis#focus=factor_analysis&mode=explore Now this is purely for learning the concept, not performing analysis, but the idea is the same: to map out ahead of time what it makes sense to do, and then do it. If you're looking for an automated/coded version of this, I don't think one exists. You can't automate the concept of modeling when you're trying to understand a system. (And that's a good thing because it would put plenty of people out of a job.)
How to keep exploratory analyses of large datasets in check?
Two words: concept map. That's the only effective way I have found to divide and conquer large data sets or any concept that's really convoluted. http://en.wikipedia.org/wiki/Concept_maps Personally,
How to keep exploratory analyses of large datasets in check? Two words: concept map. That's the only effective way I have found to divide and conquer large data sets or any concept that's really convoluted. http://en.wikipedia.org/wiki/Concept_maps Personally, I think better on paper than on screen, so I just mind map what I'm dealing with before I even start to do any basic analysis. For a more professional diagram, there are lots of mind mapping software http://en.wikipedia.org/wiki/List_of_concept-_and_mind-mapping_software Mind mapping has several advantages: tells me what I have in terms of "core" variables and derived variables (if any) allows for the organization/formulation of a model based on theory/logic points to what variables I may be missing and/or could add if the relationships between the core variables don't pan out like I think they should Edit: As an example, here is the concept map for factor analysis: http://www.metacademy.org/graphs/concepts/factor_analysis#focus=factor_analysis&mode=explore Now this is purely for learning the concept, not performing analysis, but the idea is the same: to map out ahead of time what it makes sense to do, and then do it. If you're looking for an automated/coded version of this, I don't think one exists. You can't automate the concept of modeling when you're trying to understand a system. (And that's a good thing because it would put plenty of people out of a job.)
How to keep exploratory analyses of large datasets in check? Two words: concept map. That's the only effective way I have found to divide and conquer large data sets or any concept that's really convoluted. http://en.wikipedia.org/wiki/Concept_maps Personally,
12,780
How to keep exploratory analyses of large datasets in check?
You're already using git: why not use version control to organize your exploration? Create a new branch for each new "branch" of your exploration, and fork off branches for different versions of plots as well. This method will make it slightly more difficult to combine your end results, but you could always maintain an untracked directory where you could drop in the "gems" of your analysis. You'd probably want to somehow label your files in this directory to indicate which fork/commit they came from. This method has the added benefit of making it really easy to contrast different analyses via the diff command.
How to keep exploratory analyses of large datasets in check?
You're already using git: why not use version control to organize your exploration? Create a new branch for each new "branch" of your exploration, and fork off branches for different versions of plots
How to keep exploratory analyses of large datasets in check? You're already using git: why not use version control to organize your exploration? Create a new branch for each new "branch" of your exploration, and fork off branches for different versions of plots as well. This method will make it slightly more difficult to combine your end results, but you could always maintain an untracked directory where you could drop in the "gems" of your analysis. You'd probably want to somehow label your files in this directory to indicate which fork/commit they came from. This method has the added benefit of making it really easy to contrast different analyses via the diff command.
How to keep exploratory analyses of large datasets in check? You're already using git: why not use version control to organize your exploration? Create a new branch for each new "branch" of your exploration, and fork off branches for different versions of plots
12,781
How to keep exploratory analyses of large datasets in check?
I would look into Business Intelligence tools... where similar issues arise. In particular (data warehouses, dimensional analysis,) hierarchies and drill downs. The basic idea is that you try to represent your underlying data as aggregatable quantities ( counts, earnings etc rather than eg percentages). Then you design hierarchies to aggregate over the details ( eg months/ weeks/...) . This allows you to have simple overviews of all your data and then zoom in on particular areas. see eg http://cubes.databrewery.org/ (python) or excel power pivot
How to keep exploratory analyses of large datasets in check?
I would look into Business Intelligence tools... where similar issues arise. In particular (data warehouses, dimensional analysis,) hierarchies and drill downs. The basic idea is that you try to repr
How to keep exploratory analyses of large datasets in check? I would look into Business Intelligence tools... where similar issues arise. In particular (data warehouses, dimensional analysis,) hierarchies and drill downs. The basic idea is that you try to represent your underlying data as aggregatable quantities ( counts, earnings etc rather than eg percentages). Then you design hierarchies to aggregate over the details ( eg months/ weeks/...) . This allows you to have simple overviews of all your data and then zoom in on particular areas. see eg http://cubes.databrewery.org/ (python) or excel power pivot
How to keep exploratory analyses of large datasets in check? I would look into Business Intelligence tools... where similar issues arise. In particular (data warehouses, dimensional analysis,) hierarchies and drill downs. The basic idea is that you try to repr
12,782
Model stability when dealing with large $p$, small $n$ problem
"Sparse Algorithms are not Stable: A No-free-lunch Theorem" I guess the title says a lot, as you pointed out. [...] a sparse algorithm can have non-unique optimal solutions, and is therefore ill-posed Check out randomized lasso, and the talk by Peter Buhlmann. Update: I found this paper easier to follow than the paper by Meinshausen and Buhlmann called "Stability Selection". In "Random Lasso", the authors consider the two important drawbacks of the lasso for large $p$, small $n$ problems, that is, In the case where there exist several correlated variables, lasso only picks one or a few, thus leading to the instability that you talk about Lasso cannot select more variables than the sample size $n$ which is a problem for many models The main idea for random lasso, that is able to deal with both drawbacks of lasso is the following If several independent data sets were generated from the same distribution, then we would expect lasso to select nonidentical subsets of those highly correlated important variables from different data sets, and our final collection may be most, or perhaps even all, of those highly correlated important variables by taking a union of selected variables from different data sets. Such a process may yield more than $n$ variables, overcoming the other limitation of lasso. Bootstrap samples are drawn to simulate multiple data sets. The final coefficients are obtained by averaging over the results of each bootstrap sample. It would be great if somebody could elaborate on and explain this algorithm further in the answers.
Model stability when dealing with large $p$, small $n$ problem
"Sparse Algorithms are not Stable: A No-free-lunch Theorem" I guess the title says a lot, as you pointed out. [...] a sparse algorithm can have non-unique optimal solutions, and is therefore ill-p
Model stability when dealing with large $p$, small $n$ problem "Sparse Algorithms are not Stable: A No-free-lunch Theorem" I guess the title says a lot, as you pointed out. [...] a sparse algorithm can have non-unique optimal solutions, and is therefore ill-posed Check out randomized lasso, and the talk by Peter Buhlmann. Update: I found this paper easier to follow than the paper by Meinshausen and Buhlmann called "Stability Selection". In "Random Lasso", the authors consider the two important drawbacks of the lasso for large $p$, small $n$ problems, that is, In the case where there exist several correlated variables, lasso only picks one or a few, thus leading to the instability that you talk about Lasso cannot select more variables than the sample size $n$ which is a problem for many models The main idea for random lasso, that is able to deal with both drawbacks of lasso is the following If several independent data sets were generated from the same distribution, then we would expect lasso to select nonidentical subsets of those highly correlated important variables from different data sets, and our final collection may be most, or perhaps even all, of those highly correlated important variables by taking a union of selected variables from different data sets. Such a process may yield more than $n$ variables, overcoming the other limitation of lasso. Bootstrap samples are drawn to simulate multiple data sets. The final coefficients are obtained by averaging over the results of each bootstrap sample. It would be great if somebody could elaborate on and explain this algorithm further in the answers.
Model stability when dealing with large $p$, small $n$ problem "Sparse Algorithms are not Stable: A No-free-lunch Theorem" I guess the title says a lot, as you pointed out. [...] a sparse algorithm can have non-unique optimal solutions, and is therefore ill-p
12,783
Model stability when dealing with large $p$, small $n$ problem
My current approach is to find best tuning parameters (lambda and alpha) in a grid search on 90% of the dataset with 10-fold cross-validation averaging MSE score. Then I train the model with the best tuning parameters on the whole 90% of dataset. I am able to evaluate my model using R squared on the holdout 10% of the dataset (which account to only 15 samples). How stable are the tuning parameters? Do you see large differences between goodness-of-fit (e.g. MSE of the optimal parameter's cross validation) and the 10% independent test performance? That would be a symptom of overfitting: The problem with the grid search (and many other parameter optimization strategies) is that you basically assume a rather smooth behaviour of $MSE = f (grid parameters)$. But for small test sets the variance due to the small test set size (= 135 samples total in 10 c.v.-folds) can be larger than the actual differences of $MSE = f (grid parameters)$. In that case already the parameters are rather unstable. Can I repeatedly run my procedure to create a number of models, and then average regression coefficients? Or should I use the number of occurrences of a predictor in the models as its importance score? There are several possibilities to build such aggregated models: linear models can be averaged by averaging the coefficients more generally, you can predict a sample by each of the $m$ different models, and average the $m$ predictions (you could also derive an idea of the uncertainty looking at the distribution of the predictions). Search terms would be "aggregated models", "bootstrap aggregating", "bagging". Side thought: some types of data have expected and interpretable collinearity that can cause variable selectio to "jump" between more or less equal solutions.
Model stability when dealing with large $p$, small $n$ problem
My current approach is to find best tuning parameters (lambda and alpha) in a grid search on 90% of the dataset with 10-fold cross-validation averaging MSE score. Then I train the model with the best
Model stability when dealing with large $p$, small $n$ problem My current approach is to find best tuning parameters (lambda and alpha) in a grid search on 90% of the dataset with 10-fold cross-validation averaging MSE score. Then I train the model with the best tuning parameters on the whole 90% of dataset. I am able to evaluate my model using R squared on the holdout 10% of the dataset (which account to only 15 samples). How stable are the tuning parameters? Do you see large differences between goodness-of-fit (e.g. MSE of the optimal parameter's cross validation) and the 10% independent test performance? That would be a symptom of overfitting: The problem with the grid search (and many other parameter optimization strategies) is that you basically assume a rather smooth behaviour of $MSE = f (grid parameters)$. But for small test sets the variance due to the small test set size (= 135 samples total in 10 c.v.-folds) can be larger than the actual differences of $MSE = f (grid parameters)$. In that case already the parameters are rather unstable. Can I repeatedly run my procedure to create a number of models, and then average regression coefficients? Or should I use the number of occurrences of a predictor in the models as its importance score? There are several possibilities to build such aggregated models: linear models can be averaged by averaging the coefficients more generally, you can predict a sample by each of the $m$ different models, and average the $m$ predictions (you could also derive an idea of the uncertainty looking at the distribution of the predictions). Search terms would be "aggregated models", "bootstrap aggregating", "bagging". Side thought: some types of data have expected and interpretable collinearity that can cause variable selectio to "jump" between more or less equal solutions.
Model stability when dealing with large $p$, small $n$ problem My current approach is to find best tuning parameters (lambda and alpha) in a grid search on 90% of the dataset with 10-fold cross-validation averaging MSE score. Then I train the model with the best
12,784
Model stability when dealing with large $p$, small $n$ problem
There's no way out of it. As some said, models are unstable by nature (otherwise statistics would not be needed). But instability itself brings information. So instead of trying to get rid of it I tried to analyze it. I run cross validation simulations many times and then get the coefficients for the best selected parameters in each run and put them together. In the case of the elastic net I run a cross validation test for each alpha (0..1 by 0.1) with the same k folded data (you should compare alphas on the same data set) and select the $\lambda$/$\alpha$ pair associated with less test error... Than I repeat it for n times with different randomly selected k folded data and pick the best pair for each iteration. Then I extract the regression coefficients for each parameters pair and this gives me a distribution of values for each parameter. This way I can use the mean/median value to describe the strength of the predictor and its standard deviation/IQR to describe its variability, that is its stability. A very stabile predictor means you can expect its effect to be similar also with new data; a predictor which is unstable even in your data, would probably be very unstable even with new data.
Model stability when dealing with large $p$, small $n$ problem
There's no way out of it. As some said, models are unstable by nature (otherwise statistics would not be needed). But instability itself brings information. So instead of trying to get rid of it I tr
Model stability when dealing with large $p$, small $n$ problem There's no way out of it. As some said, models are unstable by nature (otherwise statistics would not be needed). But instability itself brings information. So instead of trying to get rid of it I tried to analyze it. I run cross validation simulations many times and then get the coefficients for the best selected parameters in each run and put them together. In the case of the elastic net I run a cross validation test for each alpha (0..1 by 0.1) with the same k folded data (you should compare alphas on the same data set) and select the $\lambda$/$\alpha$ pair associated with less test error... Than I repeat it for n times with different randomly selected k folded data and pick the best pair for each iteration. Then I extract the regression coefficients for each parameters pair and this gives me a distribution of values for each parameter. This way I can use the mean/median value to describe the strength of the predictor and its standard deviation/IQR to describe its variability, that is its stability. A very stabile predictor means you can expect its effect to be similar also with new data; a predictor which is unstable even in your data, would probably be very unstable even with new data.
Model stability when dealing with large $p$, small $n$ problem There's no way out of it. As some said, models are unstable by nature (otherwise statistics would not be needed). But instability itself brings information. So instead of trying to get rid of it I tr
12,785
Relationship between gamma and chi-squared distribution
Some background The $\chi^2_n$ distribution is defined as the distribution that results from summing the squares of $n$ independent random variables $\mathcal{N}(0,1)$, so: $$\text{If }X_1,\ldots,X_n\sim\mathcal{N}(0,1)\text{ and are independent, then }Y_1=\sum_{i=1}^nX_i^2\sim \chi^2_n,$$ where $X\sim Y$ denotes that the random variables $X$ and $Y$ have the same distribution (EDIT: $\chi_n^2$ will denote both a Chi squared distribution with $n$ degrees of freedom and a random variable with such distribution). Now, the pdf of the $\chi^2_n$ distribution is $$ f_{\chi^2}(x;n)=\frac{1}{2^\frac{n}{2}\Gamma\left(\frac{n}{2}\right)}x^{\frac{n}{2}-1}e^{-\frac{x}{2}},\quad \text{for } x\geq0\text{ (and $0$ otherwise).} $$ So, indeed the $\chi^2_n$ distribution is a particular case of the $\Gamma(p,a)$ distribution with pdf $$ f_\Gamma(x;a,p)=\frac{1}{a^p\Gamma(p)}x^{p-1}e^{-\frac{x}{a}},\quad \text{for } x\geq0\text{ (and $0$ otherwise).} $$ Now it is clear that $\chi_n^2\sim\Gamma\left(\frac{n}{2},2\right)$. Your case The difference in your case is that you have normal variables $X_i$ with common variances $\sigma^2\neq1$. But a similar distribution arises in that case: $$Y_2=\sum_{i=1}^nX_i^2=\sigma^2\sum_{i=1}^n\left(\frac{X_i}{\sigma}\right)^2\sim\sigma^2\chi_n^2,$$ so $Y$ follows the distribution resulting from multiplying a $\chi_n^2$ random variable with $\sigma^2$. This is easily obtained with a transformation of random variables ($Y_2=\sigma^2Y_1$): $$ f_{\sigma^2\chi^2}(x;n)=f_{\chi^2}\left(\frac{x}{\sigma^2};n\right)\frac{1}{\sigma^2}. $$ Note that this is the same as saying that $Y_2\sim\Gamma\left(\frac{n}{2},2\sigma^2\right)$ since $\sigma^2$ can be absorbed by the Gamma's $a$ parameter. Note If you want to derive the pdf of the $\chi^2_n$ from scratch (which also applies to the situation with $\sigma^2\neq1$ under minor changes), you can follow the first step here for the $\chi_1^2$ using standard transformation for random variables. Then, you may either follow the next steps or shorten the proof relying in the convolution properties of the Gamma distribution and its relationship with the $\chi^2_n$ described above.
Relationship between gamma and chi-squared distribution
Some background The $\chi^2_n$ distribution is defined as the distribution that results from summing the squares of $n$ independent random variables $\mathcal{N}(0,1)$, so: $$\text{If }X_1,\ldots,X_n\
Relationship between gamma and chi-squared distribution Some background The $\chi^2_n$ distribution is defined as the distribution that results from summing the squares of $n$ independent random variables $\mathcal{N}(0,1)$, so: $$\text{If }X_1,\ldots,X_n\sim\mathcal{N}(0,1)\text{ and are independent, then }Y_1=\sum_{i=1}^nX_i^2\sim \chi^2_n,$$ where $X\sim Y$ denotes that the random variables $X$ and $Y$ have the same distribution (EDIT: $\chi_n^2$ will denote both a Chi squared distribution with $n$ degrees of freedom and a random variable with such distribution). Now, the pdf of the $\chi^2_n$ distribution is $$ f_{\chi^2}(x;n)=\frac{1}{2^\frac{n}{2}\Gamma\left(\frac{n}{2}\right)}x^{\frac{n}{2}-1}e^{-\frac{x}{2}},\quad \text{for } x\geq0\text{ (and $0$ otherwise).} $$ So, indeed the $\chi^2_n$ distribution is a particular case of the $\Gamma(p,a)$ distribution with pdf $$ f_\Gamma(x;a,p)=\frac{1}{a^p\Gamma(p)}x^{p-1}e^{-\frac{x}{a}},\quad \text{for } x\geq0\text{ (and $0$ otherwise).} $$ Now it is clear that $\chi_n^2\sim\Gamma\left(\frac{n}{2},2\right)$. Your case The difference in your case is that you have normal variables $X_i$ with common variances $\sigma^2\neq1$. But a similar distribution arises in that case: $$Y_2=\sum_{i=1}^nX_i^2=\sigma^2\sum_{i=1}^n\left(\frac{X_i}{\sigma}\right)^2\sim\sigma^2\chi_n^2,$$ so $Y$ follows the distribution resulting from multiplying a $\chi_n^2$ random variable with $\sigma^2$. This is easily obtained with a transformation of random variables ($Y_2=\sigma^2Y_1$): $$ f_{\sigma^2\chi^2}(x;n)=f_{\chi^2}\left(\frac{x}{\sigma^2};n\right)\frac{1}{\sigma^2}. $$ Note that this is the same as saying that $Y_2\sim\Gamma\left(\frac{n}{2},2\sigma^2\right)$ since $\sigma^2$ can be absorbed by the Gamma's $a$ parameter. Note If you want to derive the pdf of the $\chi^2_n$ from scratch (which also applies to the situation with $\sigma^2\neq1$ under minor changes), you can follow the first step here for the $\chi_1^2$ using standard transformation for random variables. Then, you may either follow the next steps or shorten the proof relying in the convolution properties of the Gamma distribution and its relationship with the $\chi^2_n$ described above.
Relationship between gamma and chi-squared distribution Some background The $\chi^2_n$ distribution is defined as the distribution that results from summing the squares of $n$ independent random variables $\mathcal{N}(0,1)$, so: $$\text{If }X_1,\ldots,X_n\
12,786
Capturing seasonality in multiple regression for daily data
@Irishstat covered pretty much what I was about to say, but I would respond with my own personal experience in modeling these data with time series regression and OLS regression. If it is a daily data then I would do the following: Create a dummy variable for different seasonality: To capture day of the week seasonality, create 6 dummy variables. To capture day of the month seasonality, create 30 dummy variables To capture month of the year, create 11 dummy variables. Create dummy variable for trend variables: If the time series exhibits linear trend, then add a time trend variable. If the time series exhibits nonlinear trend, add a nonlinear time trend variable such as quadratic/cubic/log Add Independent variables Variables This is a time series data, so care should be taken about lead and lag effects of independent varibales. For instance in your example, you mention price point promotional flag, they might not have immediate effect on your response, i.e., there may be lagging and a decaying/permanent effect. So for instance, if run a promotion today, you might have a increase in sales today but the effect of promotion decays after few days. There is no easy way to model this using multiple regression, you would want to use transfer function modeling which is parsimonoius and can handle any type of lead and lag effects. See this example I posted earlier, where there is an intervention(in your case price point) and there is an abrupt increase, followed by a decaying effect. Having said that if you have a priori knowledge about the lead and lag effect, create additional variables in your case dummy variables before and after price point and (yes/no) promotion change. You would also need to add moving Holidays indicator variables, for example as Irishstat pointed out you would want to add Easter/Thanksgiving (in US) which are moving Holidays. Holidays that are fixed dates will be automatically taken care of if you are using dummy coding scheme for capturing seasonality. In addition, you would need to identify outliers such as additive/pulse (one time event) or level shift (permanent shift) and add them as regressors. Identifying outliers in multiple regression for time series data is nearly impossible; you would need time series outlier detection methods such as Tsay's procedure or Chen and Liu's procedure which has been incorporated in software such as AUTOBOX, SPSS, SAS or the tsoutlier package in R. Potential Problems: Following are the problems you would encounter if you model time series data using OLS multiple regression. Errors might be autocorrelated. See this nice website and this website explaining this issue. One way to avoid this is to use Generalized least squares (GLS) or ARIMAX approach vs. OLS multiple regression, where you can correct for auto correlation. OLS model will not be parsimonoius. You have $6+30+11= 47$ dummy variables for seasonality. By using dummy variables, you are assuming that your seasonality is deterministic i.e. it doesn't change over time. Since you have only 3 years of data I would not worry about it, but still it is worthwhile to plot the series and see if the seasonality doesn't change. And there are many more disadvantages of using multiple regression. If prediction is more important to you then I would hold out at least 6 months of data and test the predictive ability of your multiple regression. If your main goal is to explain the correlation between independent variables, then I would be cautious using multiple regression, and instead I would use a time series approach such as ARIMAX/GLS. If you are interested, you could refer to the excellent text by Pankratz, for transfer function and dynamic regression modeling. For general time series forecasting please refer to Makridakis et al. Also, a good reference text would be by Diebold for regression and time series based forecasting.
Capturing seasonality in multiple regression for daily data
@Irishstat covered pretty much what I was about to say, but I would respond with my own personal experience in modeling these data with time series regression and OLS regression. If it is a daily data
Capturing seasonality in multiple regression for daily data @Irishstat covered pretty much what I was about to say, but I would respond with my own personal experience in modeling these data with time series regression and OLS regression. If it is a daily data then I would do the following: Create a dummy variable for different seasonality: To capture day of the week seasonality, create 6 dummy variables. To capture day of the month seasonality, create 30 dummy variables To capture month of the year, create 11 dummy variables. Create dummy variable for trend variables: If the time series exhibits linear trend, then add a time trend variable. If the time series exhibits nonlinear trend, add a nonlinear time trend variable such as quadratic/cubic/log Add Independent variables Variables This is a time series data, so care should be taken about lead and lag effects of independent varibales. For instance in your example, you mention price point promotional flag, they might not have immediate effect on your response, i.e., there may be lagging and a decaying/permanent effect. So for instance, if run a promotion today, you might have a increase in sales today but the effect of promotion decays after few days. There is no easy way to model this using multiple regression, you would want to use transfer function modeling which is parsimonoius and can handle any type of lead and lag effects. See this example I posted earlier, where there is an intervention(in your case price point) and there is an abrupt increase, followed by a decaying effect. Having said that if you have a priori knowledge about the lead and lag effect, create additional variables in your case dummy variables before and after price point and (yes/no) promotion change. You would also need to add moving Holidays indicator variables, for example as Irishstat pointed out you would want to add Easter/Thanksgiving (in US) which are moving Holidays. Holidays that are fixed dates will be automatically taken care of if you are using dummy coding scheme for capturing seasonality. In addition, you would need to identify outliers such as additive/pulse (one time event) or level shift (permanent shift) and add them as regressors. Identifying outliers in multiple regression for time series data is nearly impossible; you would need time series outlier detection methods such as Tsay's procedure or Chen and Liu's procedure which has been incorporated in software such as AUTOBOX, SPSS, SAS or the tsoutlier package in R. Potential Problems: Following are the problems you would encounter if you model time series data using OLS multiple regression. Errors might be autocorrelated. See this nice website and this website explaining this issue. One way to avoid this is to use Generalized least squares (GLS) or ARIMAX approach vs. OLS multiple regression, where you can correct for auto correlation. OLS model will not be parsimonoius. You have $6+30+11= 47$ dummy variables for seasonality. By using dummy variables, you are assuming that your seasonality is deterministic i.e. it doesn't change over time. Since you have only 3 years of data I would not worry about it, but still it is worthwhile to plot the series and see if the seasonality doesn't change. And there are many more disadvantages of using multiple regression. If prediction is more important to you then I would hold out at least 6 months of data and test the predictive ability of your multiple regression. If your main goal is to explain the correlation between independent variables, then I would be cautious using multiple regression, and instead I would use a time series approach such as ARIMAX/GLS. If you are interested, you could refer to the excellent text by Pankratz, for transfer function and dynamic regression modeling. For general time series forecasting please refer to Makridakis et al. Also, a good reference text would be by Diebold for regression and time series based forecasting.
Capturing seasonality in multiple regression for daily data @Irishstat covered pretty much what I was about to say, but I would respond with my own personal experience in modeling these data with time series regression and OLS regression. If it is a daily data
12,787
Capturing seasonality in multiple regression for daily data
What you need is a model that will incorporate daily effects, weekly effects, monthly effects,week of the month effects, day-of-the-month effects,lead and lag effects of the holidays, unspecified but empirically identifiable level/step shifts , local time trends, changes in seasonal pulses and pulses while incorporating ARIMA structure and possibly dealing with changes in parameters and error variance over time. This is called a Transfer Function and can be easily restated (BUT NOT PARSIMONIOUSLY) as a Multiple Linear Regression. In specific a daily indicator would take 6 predictors. In general one has to carefully orchestrate(identify) what kind of predictors are needed. If you have a lot of time on your hands you can experiment with some of the structures I have mentioned. Alternatively you might need some advanced software/consultancy to get you to solve your problem in your lifetime.
Capturing seasonality in multiple regression for daily data
What you need is a model that will incorporate daily effects, weekly effects, monthly effects,week of the month effects, day-of-the-month effects,lead and lag effects of the holidays, unspecified but
Capturing seasonality in multiple regression for daily data What you need is a model that will incorporate daily effects, weekly effects, monthly effects,week of the month effects, day-of-the-month effects,lead and lag effects of the holidays, unspecified but empirically identifiable level/step shifts , local time trends, changes in seasonal pulses and pulses while incorporating ARIMA structure and possibly dealing with changes in parameters and error variance over time. This is called a Transfer Function and can be easily restated (BUT NOT PARSIMONIOUSLY) as a Multiple Linear Regression. In specific a daily indicator would take 6 predictors. In general one has to carefully orchestrate(identify) what kind of predictors are needed. If you have a lot of time on your hands you can experiment with some of the structures I have mentioned. Alternatively you might need some advanced software/consultancy to get you to solve your problem in your lifetime.
Capturing seasonality in multiple regression for daily data What you need is a model that will incorporate daily effects, weekly effects, monthly effects,week of the month effects, day-of-the-month effects,lead and lag effects of the holidays, unspecified but
12,788
libsvm "reaching max number of iterations" warning and cross-validation
This warning means that the iterative routine used by LIBSVM to solve quadratic optimization problem in order to find the maximum margin hyperplane (i.e., parameters $w$ and $b$) separating your data reached the maximum number of iterations and will have to stop, while the current approximation for $w$ can be further enhanced (i.e., $w$ can be changed to make the value of the objective function more extreme). In short, that means the LIBSVM thinks it failed to find the maximum margin hyperplane, which may or may not be true. There are many reasons why this may happen, I'd suggest you to do the following: Normalize your data. Make sure your classes are more or less balanced (have similar size). If they don't, use parameter -w to assign them different weights. Try different $C$ and $\gamma$. Polynomial kernel in LIBSVM also has parameter 'coef0', as the kernel is $$\gamma \cdot u' \cdot v + \text{coeff}_0^{\text{ degree}}$$ It's a good idea to search optimal $C$ on a logarithmic scale, like you do. I think for normalized data the search range for $C$ that you suggested should be OK. A useful check: the accuracy of the classifier should not be changing much on the borders of that range and between two values of your set. If it does, extend the range or add intermediate values. Note that LIBSVM distributive for Windows should contain a Python script called grid.py, which can do parameter selection for you (based on cross validation and specified search ranges). It can also produce contour plots for the accuracy of SVM. This tool may be quite helpful. The following question on StackOverflow and its related questions might also help: libsvm Shrinking Heuristics
libsvm "reaching max number of iterations" warning and cross-validation
This warning means that the iterative routine used by LIBSVM to solve quadratic optimization problem in order to find the maximum margin hyperplane (i.e., parameters $w$ and $b$) separating your data
libsvm "reaching max number of iterations" warning and cross-validation This warning means that the iterative routine used by LIBSVM to solve quadratic optimization problem in order to find the maximum margin hyperplane (i.e., parameters $w$ and $b$) separating your data reached the maximum number of iterations and will have to stop, while the current approximation for $w$ can be further enhanced (i.e., $w$ can be changed to make the value of the objective function more extreme). In short, that means the LIBSVM thinks it failed to find the maximum margin hyperplane, which may or may not be true. There are many reasons why this may happen, I'd suggest you to do the following: Normalize your data. Make sure your classes are more or less balanced (have similar size). If they don't, use parameter -w to assign them different weights. Try different $C$ and $\gamma$. Polynomial kernel in LIBSVM also has parameter 'coef0', as the kernel is $$\gamma \cdot u' \cdot v + \text{coeff}_0^{\text{ degree}}$$ It's a good idea to search optimal $C$ on a logarithmic scale, like you do. I think for normalized data the search range for $C$ that you suggested should be OK. A useful check: the accuracy of the classifier should not be changing much on the borders of that range and between two values of your set. If it does, extend the range or add intermediate values. Note that LIBSVM distributive for Windows should contain a Python script called grid.py, which can do parameter selection for you (based on cross validation and specified search ranges). It can also produce contour plots for the accuracy of SVM. This tool may be quite helpful. The following question on StackOverflow and its related questions might also help: libsvm Shrinking Heuristics
libsvm "reaching max number of iterations" warning and cross-validation This warning means that the iterative routine used by LIBSVM to solve quadratic optimization problem in order to find the maximum margin hyperplane (i.e., parameters $w$ and $b$) separating your data
12,789
What does (pandas) autocorrelation graph show?
Looking at the estimator for the autocovariance function at lag $ h $ might be useful (note that the autocorrelation function is simply a scaled-down version of the autocovariance function). $$ \hat{\gamma}(h) = \frac{1}{n} \sum_{t=1}^{n-\mid h \mid} (x_{t+h} - \bar{x})(x_t - \bar{x}) $$ The idea is that, for each lag $ h $, we go through the series and check whether the data point $ h $ time steps away covaries positively or negatively (i.e. when $ t $ goes above the mean of the series, does $ t+h $ also go above or below?). Your series is a monotonically increasing series, and has mean $ 183 $. Let's see what happens when $ h = 130 $. First, note that we can only compute the autocovariance function up to time point 234, since when $ t = 234 $, $ t+h=365 $. Furthermore, note that from $ t= 1 $ up until $ t = 53 $, we have that $ t + h $ is also below the mean (since 53 + 130 = 183 which is the mean of the series). And then, from $ t=54 $ to $ t=182 $, the estimated correlation will be negative since they covary negatively. Finally, from $ t = 183 $ to $ t = 234 $, the estimated correlation will be positive once again, since $ t $ and $ t+h $ will both be above the mean. Do you see how this would result in the correlation averaging out due to the approximately equal contributions to the autocovariance function from the positively covarying points and the negatively covarying points? You might notice that there are more points that are negatively covarying than points that are positively covarying. However, intuitively, the positively covarying points are of greater magnitude (since they're further away from the mean) whereas the negatively covarying points contribute smaller magnitude to the autocovariance function since they crop up closer to the mean. Thus, this results in an autocovariance function of approximately zero.
What does (pandas) autocorrelation graph show?
Looking at the estimator for the autocovariance function at lag $ h $ might be useful (note that the autocorrelation function is simply a scaled-down version of the autocovariance function). $$ \hat{\
What does (pandas) autocorrelation graph show? Looking at the estimator for the autocovariance function at lag $ h $ might be useful (note that the autocorrelation function is simply a scaled-down version of the autocovariance function). $$ \hat{\gamma}(h) = \frac{1}{n} \sum_{t=1}^{n-\mid h \mid} (x_{t+h} - \bar{x})(x_t - \bar{x}) $$ The idea is that, for each lag $ h $, we go through the series and check whether the data point $ h $ time steps away covaries positively or negatively (i.e. when $ t $ goes above the mean of the series, does $ t+h $ also go above or below?). Your series is a monotonically increasing series, and has mean $ 183 $. Let's see what happens when $ h = 130 $. First, note that we can only compute the autocovariance function up to time point 234, since when $ t = 234 $, $ t+h=365 $. Furthermore, note that from $ t= 1 $ up until $ t = 53 $, we have that $ t + h $ is also below the mean (since 53 + 130 = 183 which is the mean of the series). And then, from $ t=54 $ to $ t=182 $, the estimated correlation will be negative since they covary negatively. Finally, from $ t = 183 $ to $ t = 234 $, the estimated correlation will be positive once again, since $ t $ and $ t+h $ will both be above the mean. Do you see how this would result in the correlation averaging out due to the approximately equal contributions to the autocovariance function from the positively covarying points and the negatively covarying points? You might notice that there are more points that are negatively covarying than points that are positively covarying. However, intuitively, the positively covarying points are of greater magnitude (since they're further away from the mean) whereas the negatively covarying points contribute smaller magnitude to the autocovariance function since they crop up closer to the mean. Thus, this results in an autocovariance function of approximately zero.
What does (pandas) autocorrelation graph show? Looking at the estimator for the autocovariance function at lag $ h $ might be useful (note that the autocorrelation function is simply a scaled-down version of the autocovariance function). $$ \hat{\
12,790
Is Random Forest suitable for very small data sets?
Random forest is basically bootstrap resampling and training decision trees on the samples, so the answer to your question needs to address those two. Bootstrap resampling is not a cure for small samples. If you have just twenty four observations in your dataset, then each of the samples taken with replacement from this data would consist of not more than the twenty four distinct values. Shuffling the cases and not drawing some of them would not change much about your ability to learn anything new about the underlying distribution. So a small sample is a problem for bootstrap. Decision trees are trained by splitting the data conditionally on the predictor variables, one variable at a time, to find such subsamples that have greatest discriminatory power. If you have only twenty four cases, then say that if you were lucky and all the splits were even in size, then with two splits you would end up with four groups of six cases, with tree splits, with eight groups of three. If you calculated conditional means on the samples (to predict continuous values in regression trees, or conditional probabilities in decision trees), you would base your conclusion only on those few cases! So the sub-samples that you would use to make the decisions would be even smaller than your original data. With small samples it is usually wise to use simple methods. Moreover, you can catch up the small sample by using informative priors in Bayesian setting (if you have any reasonable out-of-data knowledge about the problem), so you could consider using some tailor-made Bayesian model.
Is Random Forest suitable for very small data sets?
Random forest is basically bootstrap resampling and training decision trees on the samples, so the answer to your question needs to address those two. Bootstrap resampling is not a cure for small samp
Is Random Forest suitable for very small data sets? Random forest is basically bootstrap resampling and training decision trees on the samples, so the answer to your question needs to address those two. Bootstrap resampling is not a cure for small samples. If you have just twenty four observations in your dataset, then each of the samples taken with replacement from this data would consist of not more than the twenty four distinct values. Shuffling the cases and not drawing some of them would not change much about your ability to learn anything new about the underlying distribution. So a small sample is a problem for bootstrap. Decision trees are trained by splitting the data conditionally on the predictor variables, one variable at a time, to find such subsamples that have greatest discriminatory power. If you have only twenty four cases, then say that if you were lucky and all the splits were even in size, then with two splits you would end up with four groups of six cases, with tree splits, with eight groups of three. If you calculated conditional means on the samples (to predict continuous values in regression trees, or conditional probabilities in decision trees), you would base your conclusion only on those few cases! So the sub-samples that you would use to make the decisions would be even smaller than your original data. With small samples it is usually wise to use simple methods. Moreover, you can catch up the small sample by using informative priors in Bayesian setting (if you have any reasonable out-of-data knowledge about the problem), so you could consider using some tailor-made Bayesian model.
Is Random Forest suitable for very small data sets? Random forest is basically bootstrap resampling and training decision trees on the samples, so the answer to your question needs to address those two. Bootstrap resampling is not a cure for small samp
12,791
Is Random Forest suitable for very small data sets?
On the one hand, this is a small data set, and random forest is data-hungry. On the other hand, maybe something is better than nothing. There's nothing more to say than "Try it and see." You get to decide whether or not any particular model is "good;" moreover, we can't tell you whether any model is fit for a particular purpose (nor would you want us to -- there's no cost to us if we're wrong!).
Is Random Forest suitable for very small data sets?
On the one hand, this is a small data set, and random forest is data-hungry. On the other hand, maybe something is better than nothing. There's nothing more to say than "Try it and see." You get to d
Is Random Forest suitable for very small data sets? On the one hand, this is a small data set, and random forest is data-hungry. On the other hand, maybe something is better than nothing. There's nothing more to say than "Try it and see." You get to decide whether or not any particular model is "good;" moreover, we can't tell you whether any model is fit for a particular purpose (nor would you want us to -- there's no cost to us if we're wrong!).
Is Random Forest suitable for very small data sets? On the one hand, this is a small data set, and random forest is data-hungry. On the other hand, maybe something is better than nothing. There's nothing more to say than "Try it and see." You get to d
12,792
Ordinal logistic regression in Python
statsmodels now supports Ordinal Regression: from statsmodels.miscmodels.ordinal_model import OrderedModel see their documentation here
Ordinal logistic regression in Python
statsmodels now supports Ordinal Regression: from statsmodels.miscmodels.ordinal_model import OrderedModel see their documentation here
Ordinal logistic regression in Python statsmodels now supports Ordinal Regression: from statsmodels.miscmodels.ordinal_model import OrderedModel see their documentation here
Ordinal logistic regression in Python statsmodels now supports Ordinal Regression: from statsmodels.miscmodels.ordinal_model import OrderedModel see their documentation here
12,793
Ordinal logistic regression in Python
Have you tried Mord? It seems there are very few packages to do the same, and it is one of them; though, as Fabian himself suspects, code may not scale properly. Source: Logistic ordinal regression in Python
Ordinal logistic regression in Python
Have you tried Mord? It seems there are very few packages to do the same, and it is one of them; though, as Fabian himself suspects, code may not scale properly. Source: Logistic ordinal regression in
Ordinal logistic regression in Python Have you tried Mord? It seems there are very few packages to do the same, and it is one of them; though, as Fabian himself suspects, code may not scale properly. Source: Logistic ordinal regression in Python
Ordinal logistic regression in Python Have you tried Mord? It seems there are very few packages to do the same, and it is one of them; though, as Fabian himself suspects, code may not scale properly. Source: Logistic ordinal regression in
12,794
How can recurrent neural networks be used for sequence classification?
One can use RNN to map multiple input to a single input (label), as this give figure (source) illustrates: Each rectangle is a vector and arrows represent functions (e.g. matrix multiply). Input vectors are in red, output vectors are in blue and green vectors hold the RNN's state (more on this soon). From left to right: (1) Vanilla mode of processing without RNN, from fixed-sized input to fixed-sized output (e.g. image classification). (2) Sequence output (e.g. image captioning takes an image and outputs a sentence of words). (3) Sequence input (e.g. sentiment analysis where a given sentence is classified as expressing positive or negative sentiment). (4) Sequence input and sequence output (e.g. Machine Translation: an RNN reads a sentence in English and then outputs a sentence in French). (5) Synced sequence input and output (e.g. video classification where we wish to label each frame of the video). Notice that in every case are no pre-specified constraints on the lengths sequences because the recurrent transformation (green) is fixed and can be applied as many times as we like.
How can recurrent neural networks be used for sequence classification?
One can use RNN to map multiple input to a single input (label), as this give figure (source) illustrates: Each rectangle is a vector and arrows represent functions (e.g. matrix multiply). Input vec
How can recurrent neural networks be used for sequence classification? One can use RNN to map multiple input to a single input (label), as this give figure (source) illustrates: Each rectangle is a vector and arrows represent functions (e.g. matrix multiply). Input vectors are in red, output vectors are in blue and green vectors hold the RNN's state (more on this soon). From left to right: (1) Vanilla mode of processing without RNN, from fixed-sized input to fixed-sized output (e.g. image classification). (2) Sequence output (e.g. image captioning takes an image and outputs a sentence of words). (3) Sequence input (e.g. sentiment analysis where a given sentence is classified as expressing positive or negative sentiment). (4) Sequence input and sequence output (e.g. Machine Translation: an RNN reads a sentence in English and then outputs a sentence in French). (5) Synced sequence input and output (e.g. video classification where we wish to label each frame of the video). Notice that in every case are no pre-specified constraints on the lengths sequences because the recurrent transformation (green) is fixed and can be applied as many times as we like.
How can recurrent neural networks be used for sequence classification? One can use RNN to map multiple input to a single input (label), as this give figure (source) illustrates: Each rectangle is a vector and arrows represent functions (e.g. matrix multiply). Input vec
12,795
How can recurrent neural networks be used for sequence classification?
In case of simple RNN, feed entire sequence to your network and then output class label at the last sequence element (see this paper and references there for early example of this approach). In training phase we can backpropogate error in time from last sequence element to the start of the sequence. In general this is no different from RNN sequence labeling problem, where we need to assign labels only to some elements of the sequence (or all other elements are labeled as OTHER).
How can recurrent neural networks be used for sequence classification?
In case of simple RNN, feed entire sequence to your network and then output class label at the last sequence element (see this paper and references there for early example of this approach). In traini
How can recurrent neural networks be used for sequence classification? In case of simple RNN, feed entire sequence to your network and then output class label at the last sequence element (see this paper and references there for early example of this approach). In training phase we can backpropogate error in time from last sequence element to the start of the sequence. In general this is no different from RNN sequence labeling problem, where we need to assign labels only to some elements of the sequence (or all other elements are labeled as OTHER).
How can recurrent neural networks be used for sequence classification? In case of simple RNN, feed entire sequence to your network and then output class label at the last sequence element (see this paper and references there for early example of this approach). In traini
12,796
EM algorithm manually implemented
You have several problems in the source code: As @Pat pointed out, you should not use log(dnorm()) as this value can easily go to infinity. You should use logmvdnorm When you use sum, be aware to remove infinite or missing values You looping variable k is wrong, you should update loglik[k+1] but you update loglik[k] The initial values for your method and mixtools are different. You are using $\Sigma$ in your method, but using $\sigma$ for mixtools(i.e. standard deviation, from mixtools manual). Your data do not look like a mixture of normal (check histogram I plotted at the end). And one component of the mixture has very small s.d., so I arbitrarily added a line to set $\tau_1$ and $\tau_2$ to be equal for some extreme samples. I add them just to make sure the code can work. I also suggest you put complete codes (e.g. how you initialize loglik[]) in your source code and indent the code to make it easy to read. After all, thanks for introducing mixtools package, and I plan to use them in my future research. I also put my working code for your reference: # EM algorithm manually # dat is the data setwd("~/Downloads/") load("datem.Rdata") x <- dat # initial values pi1<-0.5 pi2<-0.5 mu1<--0.01 mu2<-0.01 sigma1<-sqrt(0.01) sigma2<-sqrt(0.02) loglik<- rep(NA, 1000) loglik[1]<-0 loglik[2]<-mysum(pi1*(log(pi1)+log(dnorm(dat,mu1,sigma1))))+mysum(pi2*(log(pi2)+log(dnorm(dat,mu2,sigma2)))) mysum <- function(x) { sum(x[is.finite(x)]) } logdnorm <- function(x, mu, sigma) { mysum(sapply(x, function(x) {logdmvnorm(x, mu, sigma)})) } tau1<-0 tau2<-0 #k<-1 k<-2 # loop while(abs(loglik[k]-loglik[k-1]) >= 0.00001) { # E step tau1<-pi1*dnorm(dat,mean=mu1,sd=sigma1)/(pi1*dnorm(x,mean=mu1,sd=sigma1)+pi2*dnorm(dat,mean=mu2,sd=sigma2)) tau2<-pi2*dnorm(dat,mean=mu2,sd=sigma2)/(pi1*dnorm(x,mean=mu1,sd=sigma1)+pi2*dnorm(dat,mean=mu2,sd=sigma2)) tau1[is.na(tau1)] <- 0.5 tau2[is.na(tau2)] <- 0.5 # M step pi1<-mysum(tau1)/length(dat) pi2<-mysum(tau2)/length(dat) mu1<-mysum(tau1*x)/mysum(tau1) mu2<-mysum(tau2*x)/mysum(tau2) sigma1<-mysum(tau1*(x-mu1)^2)/mysum(tau1) sigma2<-mysum(tau2*(x-mu2)^2)/mysum(tau2) # loglik[k]<-sum(tau1*(log(pi1)+log(dnorm(x,mu1,sigma1))))+sum(tau2*(log(pi2)+log(dnorm(x,mu2,sigma2)))) loglik[k+1]<-mysum(tau1*(log(pi1)+logdnorm(x,mu1,sigma1)))+mysum(tau2*(log(pi2)+logdnorm(x,mu2,sigma2))) k<-k+1 } # compare library(mixtools) gm<-normalmixEM(x,k=2,lambda=c(0.5,0.5),mu=c(-0.01,0.01),sigma=c(0.01,0.02)) gm$lambda gm$mu gm$sigma gm$loglik Historgram
EM algorithm manually implemented
You have several problems in the source code: As @Pat pointed out, you should not use log(dnorm()) as this value can easily go to infinity. You should use logmvdnorm When you use sum, be aware to rem
EM algorithm manually implemented You have several problems in the source code: As @Pat pointed out, you should not use log(dnorm()) as this value can easily go to infinity. You should use logmvdnorm When you use sum, be aware to remove infinite or missing values You looping variable k is wrong, you should update loglik[k+1] but you update loglik[k] The initial values for your method and mixtools are different. You are using $\Sigma$ in your method, but using $\sigma$ for mixtools(i.e. standard deviation, from mixtools manual). Your data do not look like a mixture of normal (check histogram I plotted at the end). And one component of the mixture has very small s.d., so I arbitrarily added a line to set $\tau_1$ and $\tau_2$ to be equal for some extreme samples. I add them just to make sure the code can work. I also suggest you put complete codes (e.g. how you initialize loglik[]) in your source code and indent the code to make it easy to read. After all, thanks for introducing mixtools package, and I plan to use them in my future research. I also put my working code for your reference: # EM algorithm manually # dat is the data setwd("~/Downloads/") load("datem.Rdata") x <- dat # initial values pi1<-0.5 pi2<-0.5 mu1<--0.01 mu2<-0.01 sigma1<-sqrt(0.01) sigma2<-sqrt(0.02) loglik<- rep(NA, 1000) loglik[1]<-0 loglik[2]<-mysum(pi1*(log(pi1)+log(dnorm(dat,mu1,sigma1))))+mysum(pi2*(log(pi2)+log(dnorm(dat,mu2,sigma2)))) mysum <- function(x) { sum(x[is.finite(x)]) } logdnorm <- function(x, mu, sigma) { mysum(sapply(x, function(x) {logdmvnorm(x, mu, sigma)})) } tau1<-0 tau2<-0 #k<-1 k<-2 # loop while(abs(loglik[k]-loglik[k-1]) >= 0.00001) { # E step tau1<-pi1*dnorm(dat,mean=mu1,sd=sigma1)/(pi1*dnorm(x,mean=mu1,sd=sigma1)+pi2*dnorm(dat,mean=mu2,sd=sigma2)) tau2<-pi2*dnorm(dat,mean=mu2,sd=sigma2)/(pi1*dnorm(x,mean=mu1,sd=sigma1)+pi2*dnorm(dat,mean=mu2,sd=sigma2)) tau1[is.na(tau1)] <- 0.5 tau2[is.na(tau2)] <- 0.5 # M step pi1<-mysum(tau1)/length(dat) pi2<-mysum(tau2)/length(dat) mu1<-mysum(tau1*x)/mysum(tau1) mu2<-mysum(tau2*x)/mysum(tau2) sigma1<-mysum(tau1*(x-mu1)^2)/mysum(tau1) sigma2<-mysum(tau2*(x-mu2)^2)/mysum(tau2) # loglik[k]<-sum(tau1*(log(pi1)+log(dnorm(x,mu1,sigma1))))+sum(tau2*(log(pi2)+log(dnorm(x,mu2,sigma2)))) loglik[k+1]<-mysum(tau1*(log(pi1)+logdnorm(x,mu1,sigma1)))+mysum(tau2*(log(pi2)+logdnorm(x,mu2,sigma2))) k<-k+1 } # compare library(mixtools) gm<-normalmixEM(x,k=2,lambda=c(0.5,0.5),mu=c(-0.01,0.01),sigma=c(0.01,0.02)) gm$lambda gm$mu gm$sigma gm$loglik Historgram
EM algorithm manually implemented You have several problems in the source code: As @Pat pointed out, you should not use log(dnorm()) as this value can easily go to infinity. You should use logmvdnorm When you use sum, be aware to rem
12,797
EM algorithm manually implemented
I keep getting an error when trying to open your .rar file, but that may just be me doing something silly. I cna see no obvious errors in your code. A possible reason you're getting zeros is due to floating point precision. Remember, when you calculate $f(y;\theta)$, you're evaluating $\exp(-0.5(y-\mu)^2/\sigma^2)$. It doesn't take a very large difference between $\mu$ and $y$ for this to get rounded down to 0 when you do it on a computer. This is doubly noticeable in mixture models, as some of your data will not be "assigned" to each mixture component and so can end up very far away from it. In theory these points should also end up with a low value of $\tau$ when you evaluate the log likelihood, counteracting the problem - but thanks to the floating point error, the quantity has already been evaluated as -Inf by this stage, so it all breaks :). If that is the problem, there are some possible solutions: One is to move your $\tau$ inside the logarithm. So instead of evaluating $\tau \log(f(y|\theta)) $ evaluate $\log \left( f(y|\theta)^\tau \right)$. Mathematically the same, but think about what happens when $f(y|\theta)$ and $\tau$ are $\approx 0$. Currently you get: $0 \log (0) = 0 (-Inf) = NaN$ but with tau moved you get $\log \left( 0^0\right) = \log(1) = 0$ assuming R evaluates $0^0 = 1$ (I don't know if it does or not as I tend to use matlab) Another solution is to expand out the stuff inside the logarithm. Assuming you're using natural logarithms: $\tau \log(f(y|\theta)) $ $= \tau \log(\exp(-0.5(y-\mu)^2/\sigma^2)/\sqrt{2\pi\sigma^2})$ $= -0.5\tau \log(2 \pi\sigma^2) - 0.5 \tau \frac{(y-\mu)^2}{\sigma^2}$. Mathematically the same, but should be more resilient to floating point errors as you've avoided calculating a large negative power. This means you can't use the built in norm evaluating function any more, but if that's not a problem this is probably the better answer. For example, let's say we have the situation where $-0.5\frac{(y-\mu)^2}{\sigma^2} = -0.5*40^2 = -800$. Evaluate that as I've jsut suggested, and you get -800. However, in matlab if we exp the take the log, we get $\log(\exp(-800)) = \log(0) = -Inf$.
EM algorithm manually implemented
I keep getting an error when trying to open your .rar file, but that may just be me doing something silly. I cna see no obvious errors in your code. A possible reason you're getting zeros is due to fl
EM algorithm manually implemented I keep getting an error when trying to open your .rar file, but that may just be me doing something silly. I cna see no obvious errors in your code. A possible reason you're getting zeros is due to floating point precision. Remember, when you calculate $f(y;\theta)$, you're evaluating $\exp(-0.5(y-\mu)^2/\sigma^2)$. It doesn't take a very large difference between $\mu$ and $y$ for this to get rounded down to 0 when you do it on a computer. This is doubly noticeable in mixture models, as some of your data will not be "assigned" to each mixture component and so can end up very far away from it. In theory these points should also end up with a low value of $\tau$ when you evaluate the log likelihood, counteracting the problem - but thanks to the floating point error, the quantity has already been evaluated as -Inf by this stage, so it all breaks :). If that is the problem, there are some possible solutions: One is to move your $\tau$ inside the logarithm. So instead of evaluating $\tau \log(f(y|\theta)) $ evaluate $\log \left( f(y|\theta)^\tau \right)$. Mathematically the same, but think about what happens when $f(y|\theta)$ and $\tau$ are $\approx 0$. Currently you get: $0 \log (0) = 0 (-Inf) = NaN$ but with tau moved you get $\log \left( 0^0\right) = \log(1) = 0$ assuming R evaluates $0^0 = 1$ (I don't know if it does or not as I tend to use matlab) Another solution is to expand out the stuff inside the logarithm. Assuming you're using natural logarithms: $\tau \log(f(y|\theta)) $ $= \tau \log(\exp(-0.5(y-\mu)^2/\sigma^2)/\sqrt{2\pi\sigma^2})$ $= -0.5\tau \log(2 \pi\sigma^2) - 0.5 \tau \frac{(y-\mu)^2}{\sigma^2}$. Mathematically the same, but should be more resilient to floating point errors as you've avoided calculating a large negative power. This means you can't use the built in norm evaluating function any more, but if that's not a problem this is probably the better answer. For example, let's say we have the situation where $-0.5\frac{(y-\mu)^2}{\sigma^2} = -0.5*40^2 = -800$. Evaluate that as I've jsut suggested, and you get -800. However, in matlab if we exp the take the log, we get $\log(\exp(-800)) = \log(0) = -Inf$.
EM algorithm manually implemented I keep getting an error when trying to open your .rar file, but that may just be me doing something silly. I cna see no obvious errors in your code. A possible reason you're getting zeros is due to fl
12,798
If the likelihood principle clashes with frequentist probability then do we discard one of them?
The part of the Frequentist approach that clashes with the likelihood principle is the theory of statistical testing (and p-value computation). It is usually highlighted by the following example. Suppose two Frequentist want to study a biased coin, which turns 'heads' with unknown propability $p$. They suspect that it is biased towards 'tail', so they postulate the same null hypothesis $p = 1/2$ and the same alternative hypothesis $p < 1/2$. The first statistician flips the coin until 'heads' turns up, which happens to be 6 times. The second decides to flip the coin 6 times, and obtains only one 'heads' in the last throw. According to the model of the first statistician, the p-value is computed as follows: $$ p(1-p)^5 + p(1-p)^6 + ... = p(1-p)^5 \frac{1}{1-p} = p(1-p)^4. $$ According to the model of the second statistician, the p-value is computed as follows: $$ {6 \choose 1} p(1-p)^5 + {6 \choose 0} (1-p)^6 = (5p + 1)(1-p)^5. $$ Replacing $p$ by $1/2$, the first finds a p-value equal to $1/2^5 = 0.03125$, the second finds a p-value equal to $7/2 \times 1/2^5 = 0.109375$. So, they get different results because they did different things, right? But according to the likelihood principle, they should come to the same conclusion. Briefly, the likelihood principle states that likelihood is all that matters for inference. So the clash here comes from the fact that both observations have the same likelihood, proportional to $p(1-p)^5$ (likelihood is determined up to a proportionality constant). As far as I know, the answer to your second question is more of a debated opinion. I personally try to avoid performing tests and computing p-values for the reason above, and for others explained in this blog post. EDIT: Now that I think about it, estimations of $p$ by confidence intervals would also differ. Actually if the models are different, the CI differ by construction.
If the likelihood principle clashes with frequentist probability then do we discard one of them?
The part of the Frequentist approach that clashes with the likelihood principle is the theory of statistical testing (and p-value computation). It is usually highlighted by the following example. Supp
If the likelihood principle clashes with frequentist probability then do we discard one of them? The part of the Frequentist approach that clashes with the likelihood principle is the theory of statistical testing (and p-value computation). It is usually highlighted by the following example. Suppose two Frequentist want to study a biased coin, which turns 'heads' with unknown propability $p$. They suspect that it is biased towards 'tail', so they postulate the same null hypothesis $p = 1/2$ and the same alternative hypothesis $p < 1/2$. The first statistician flips the coin until 'heads' turns up, which happens to be 6 times. The second decides to flip the coin 6 times, and obtains only one 'heads' in the last throw. According to the model of the first statistician, the p-value is computed as follows: $$ p(1-p)^5 + p(1-p)^6 + ... = p(1-p)^5 \frac{1}{1-p} = p(1-p)^4. $$ According to the model of the second statistician, the p-value is computed as follows: $$ {6 \choose 1} p(1-p)^5 + {6 \choose 0} (1-p)^6 = (5p + 1)(1-p)^5. $$ Replacing $p$ by $1/2$, the first finds a p-value equal to $1/2^5 = 0.03125$, the second finds a p-value equal to $7/2 \times 1/2^5 = 0.109375$. So, they get different results because they did different things, right? But according to the likelihood principle, they should come to the same conclusion. Briefly, the likelihood principle states that likelihood is all that matters for inference. So the clash here comes from the fact that both observations have the same likelihood, proportional to $p(1-p)^5$ (likelihood is determined up to a proportionality constant). As far as I know, the answer to your second question is more of a debated opinion. I personally try to avoid performing tests and computing p-values for the reason above, and for others explained in this blog post. EDIT: Now that I think about it, estimations of $p$ by confidence intervals would also differ. Actually if the models are different, the CI differ by construction.
If the likelihood principle clashes with frequentist probability then do we discard one of them? The part of the Frequentist approach that clashes with the likelihood principle is the theory of statistical testing (and p-value computation). It is usually highlighted by the following example. Supp
12,799
If the likelihood principle clashes with frequentist probability then do we discard one of them?
I like the example by @gui11aume (+1), but it can make an impression that the difference in two $p$-values arises only due to the different stopping rules used by the two experimenters. In fact, I believe it is a much more general phenomenon. Consider the second experimenter in @gui11aume's answer: the one who throws a coin six times and observes heads only in the last throw. The outcomes look like that: $$\mathrm{T \;\;\; T \;\;\;T \;\;\;T \;\;\;T \;\;\;H},$$ what is the $p$-value? The usual approach would be to compute the probability that a fair coin would result in one or less heads. There are $7$ possibilities out of total $64$ with one or less heads, hence the $p=7/64\approx 0.109$. But why not take another test statistic? For example, in this experiment we observed five tails in a row. Let's take the length of the longest sequence of tails as the test statistic. There are $3$ possibilities with five or six tails in a row, hence $p=3/64\approx0.047$. So if in this case the error rate were fixed at $\alpha=0.05$, then the choice of the test statistic can easily render the results either significant or not, and this has nothing to do with the stopping rules per se. Speculative part Now, philosophically, I would say that the frequentist choice of the test statistic is in some vague sense similar to the Bayesian choice of prior. We choose one or another test statistic because we believe that the unfair coin would behave in this or that particular way (and we want to have power to detect this behaviour). Isn't it similar to putting prior on the coin types? If so, then the likelihood principle saying that all the evidence is in the likelihood does not clash with the $p$-values, because the $p$-value is then not only the "amount of evidence". It is "a measure of surprise", but something can only be a measure of surprise if it accounts for what we would be surprised about! The $p$-value attempts to combine in one scalar quantity both the evidence and some sort of prior expectations (as represented in the choice of the test statistic). If so, then it should not be compared to the likelihood itself, but perhaps rather to the posterior? I would be very interested to hear some opinions about this speculative part, here or in chat. Update following discussion with @MichaelLew I am afraid that my example above missed the point of this debate. Choosing a different test statistic leads to a change in likelihood function as well. So two different $p$-values computed above correspond to two different likelihood functions, and hence cannot be an example of a "clash" between the likelihood principle and $p$-values. The beauty of the @gui11aume's example is that the likelihood function stays exactly the same, even though the $p$-values differ. I still have to think what this means for my "speculative" part above.
If the likelihood principle clashes with frequentist probability then do we discard one of them?
I like the example by @gui11aume (+1), but it can make an impression that the difference in two $p$-values arises only due to the different stopping rules used by the two experimenters. In fact, I bel
If the likelihood principle clashes with frequentist probability then do we discard one of them? I like the example by @gui11aume (+1), but it can make an impression that the difference in two $p$-values arises only due to the different stopping rules used by the two experimenters. In fact, I believe it is a much more general phenomenon. Consider the second experimenter in @gui11aume's answer: the one who throws a coin six times and observes heads only in the last throw. The outcomes look like that: $$\mathrm{T \;\;\; T \;\;\;T \;\;\;T \;\;\;T \;\;\;H},$$ what is the $p$-value? The usual approach would be to compute the probability that a fair coin would result in one or less heads. There are $7$ possibilities out of total $64$ with one or less heads, hence the $p=7/64\approx 0.109$. But why not take another test statistic? For example, in this experiment we observed five tails in a row. Let's take the length of the longest sequence of tails as the test statistic. There are $3$ possibilities with five or six tails in a row, hence $p=3/64\approx0.047$. So if in this case the error rate were fixed at $\alpha=0.05$, then the choice of the test statistic can easily render the results either significant or not, and this has nothing to do with the stopping rules per se. Speculative part Now, philosophically, I would say that the frequentist choice of the test statistic is in some vague sense similar to the Bayesian choice of prior. We choose one or another test statistic because we believe that the unfair coin would behave in this or that particular way (and we want to have power to detect this behaviour). Isn't it similar to putting prior on the coin types? If so, then the likelihood principle saying that all the evidence is in the likelihood does not clash with the $p$-values, because the $p$-value is then not only the "amount of evidence". It is "a measure of surprise", but something can only be a measure of surprise if it accounts for what we would be surprised about! The $p$-value attempts to combine in one scalar quantity both the evidence and some sort of prior expectations (as represented in the choice of the test statistic). If so, then it should not be compared to the likelihood itself, but perhaps rather to the posterior? I would be very interested to hear some opinions about this speculative part, here or in chat. Update following discussion with @MichaelLew I am afraid that my example above missed the point of this debate. Choosing a different test statistic leads to a change in likelihood function as well. So two different $p$-values computed above correspond to two different likelihood functions, and hence cannot be an example of a "clash" between the likelihood principle and $p$-values. The beauty of the @gui11aume's example is that the likelihood function stays exactly the same, even though the $p$-values differ. I still have to think what this means for my "speculative" part above.
If the likelihood principle clashes with frequentist probability then do we discard one of them? I like the example by @gui11aume (+1), but it can make an impression that the difference in two $p$-values arises only due to the different stopping rules used by the two experimenters. In fact, I bel
12,800
How does a random kitchen sink work?
Random kitchen sinks (or random Fourier features) and other related methods don't endeavour to perform inference but rather they try to reduce the bottleneck of kernel based inference methods. Kernel methods are great in many settings but they usually rely on the manipulation of matrices, for example solving linear systems of equations and finding matrix determinants. If the matrix is $n \times n$ then naively these computations generally cost $O(n^3)$ which limits the applications they can be applied to problems with only a few thousand observations. The most popular way around this bottleneck tends to be low rank methods (although other approaches exist such as Kronecker based methods, H-matrices and Bayesian committee machines to name but a few). Random Fourier features (Rehimi & Recht 2007) considered creating low rank approximations of shift invariant kernels by sampling only a random subset of the kernels Fourier components. As Fourier space is shift invariant, this property was preserved but now an explicit finite dimensional reproducing kernel Hilbert space was formed by the union of these Fourier components. The once infinite dimensional RKHS is approximated by the degenerate approximate kernel. Notes on code snippet: There are a few details brushed over in the 5 lines. The most important is that the Gaussian function is also a Gaussian function in Fourier space, just the variance is inverted. That is why they are sampling from randn and then multiplying by variance. Then they produce alpha which is only a sub-procedure to find ztest. Essentially the normal kernel prediction looks like, $ z_{test} = K(x_{test}, x)(K(x, x) + \lambda I)^{-1} y. $ $ z_{test} = \Phi(x_{test})^T\Phi(x)(\Phi(x)^T\Phi(x) + \lambda I)^{-1} y. $ Where $\Phi(\cdot)$ is the evaluated random Fourier feature vector. Side comment: Should you use it? The answer isn't a clear yes. It depends completely on what you are modelling. The use of the Fourier space is not necessarily appropriate for non-stationary non-shift invariant kernels. The guys never claimed it would work in this setting but if you are just starting out in that area sometimes the nuances aren't obvious.
How does a random kitchen sink work?
Random kitchen sinks (or random Fourier features) and other related methods don't endeavour to perform inference but rather they try to reduce the bottleneck of kernel based inference methods. Kernel
How does a random kitchen sink work? Random kitchen sinks (or random Fourier features) and other related methods don't endeavour to perform inference but rather they try to reduce the bottleneck of kernel based inference methods. Kernel methods are great in many settings but they usually rely on the manipulation of matrices, for example solving linear systems of equations and finding matrix determinants. If the matrix is $n \times n$ then naively these computations generally cost $O(n^3)$ which limits the applications they can be applied to problems with only a few thousand observations. The most popular way around this bottleneck tends to be low rank methods (although other approaches exist such as Kronecker based methods, H-matrices and Bayesian committee machines to name but a few). Random Fourier features (Rehimi & Recht 2007) considered creating low rank approximations of shift invariant kernels by sampling only a random subset of the kernels Fourier components. As Fourier space is shift invariant, this property was preserved but now an explicit finite dimensional reproducing kernel Hilbert space was formed by the union of these Fourier components. The once infinite dimensional RKHS is approximated by the degenerate approximate kernel. Notes on code snippet: There are a few details brushed over in the 5 lines. The most important is that the Gaussian function is also a Gaussian function in Fourier space, just the variance is inverted. That is why they are sampling from randn and then multiplying by variance. Then they produce alpha which is only a sub-procedure to find ztest. Essentially the normal kernel prediction looks like, $ z_{test} = K(x_{test}, x)(K(x, x) + \lambda I)^{-1} y. $ $ z_{test} = \Phi(x_{test})^T\Phi(x)(\Phi(x)^T\Phi(x) + \lambda I)^{-1} y. $ Where $\Phi(\cdot)$ is the evaluated random Fourier feature vector. Side comment: Should you use it? The answer isn't a clear yes. It depends completely on what you are modelling. The use of the Fourier space is not necessarily appropriate for non-stationary non-shift invariant kernels. The guys never claimed it would work in this setting but if you are just starting out in that area sometimes the nuances aren't obvious.
How does a random kitchen sink work? Random kitchen sinks (or random Fourier features) and other related methods don't endeavour to perform inference but rather they try to reduce the bottleneck of kernel based inference methods. Kernel