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 |
|---|---|---|---|---|---|---|
24,201 | What is the distance between a finite Gaussian mixture and a Gaussian? | Let me follow up on considering the consequences of incorrect distribution specification. Rather than using a generic measure of distance, such as KL Divergence, you can evaluate a customized measure of "difference", germane to the consequences at hand.
As an example, if the distribution is going to be used for risk calculation, for instance to determine that the probability of failure is low enough, then the only things that matter in the fit are the probability calculations in the extreme tail. This may be relevant to decisions on multi-billion dollar programs, and involve matters of life and death.
Where is the Normal assumption likely to be most inaccurate? In many cases, in the extreme tails, the only place which matters for these crucial risk calculations. If for instance, your true distribution is a mixture of Normals having the same mean, but different standard deviations, then the tails of the mixture distribution are fatter than the tails of the Normal distribution having the same mean and standard deviation. This can easily result in orders of magnitude difference (underestimation of risk) for probabilities in the extreme tail.
So, for instance, at a crucial level $U$, the relevant measure of difference might be $P(X_{Mixture} > U) - P(X_{Normal} > U)$. In such case, it doesn't matter how good the agreement is in the rest of the distribution. | What is the distance between a finite Gaussian mixture and a Gaussian? | Let me follow up on considering the consequences of incorrect distribution specification. Rather than using a generic measure of distance, such as KL Divergence, you can evaluate a customized measure | What is the distance between a finite Gaussian mixture and a Gaussian?
Let me follow up on considering the consequences of incorrect distribution specification. Rather than using a generic measure of distance, such as KL Divergence, you can evaluate a customized measure of "difference", germane to the consequences at hand.
As an example, if the distribution is going to be used for risk calculation, for instance to determine that the probability of failure is low enough, then the only things that matter in the fit are the probability calculations in the extreme tail. This may be relevant to decisions on multi-billion dollar programs, and involve matters of life and death.
Where is the Normal assumption likely to be most inaccurate? In many cases, in the extreme tails, the only place which matters for these crucial risk calculations. If for instance, your true distribution is a mixture of Normals having the same mean, but different standard deviations, then the tails of the mixture distribution are fatter than the tails of the Normal distribution having the same mean and standard deviation. This can easily result in orders of magnitude difference (underestimation of risk) for probabilities in the extreme tail.
So, for instance, at a crucial level $U$, the relevant measure of difference might be $P(X_{Mixture} > U) - P(X_{Normal} > U)$. In such case, it doesn't matter how good the agreement is in the rest of the distribution. | What is the distance between a finite Gaussian mixture and a Gaussian?
Let me follow up on considering the consequences of incorrect distribution specification. Rather than using a generic measure of distance, such as KL Divergence, you can evaluate a customized measure |
24,202 | Best way to combine binary and continuous response | The idea of gui11aume of building a two-stage model is the right way to go, however, one needs to consider the special difficulty of your setup which is the very strong negative correlation between the debt amount and the probability of making a payment
The primary issue of building a two-stage model here is, that the second model (for prediction of the debt), when built upon the "non-zeros" only, is built on a most likely non-random sample of the population (i.e. the whole dataset), but the combined model has to be applied on the whole population again. This means that the second model will have to make predictions for parts of the data which it has never seen before, resulting in a loss of accuracy. This is called Sample Selection Bias (for a overview from a ML perspective I recommend A Bayesian Network Framework for Reject Inference by Smith and Elkan).
The KDD-Cup-98 dealt with a similar issue where one should predict whether a donor for a veterans organization is likely to donate again and how much it is likely to donate. In this dataset, the probability of donating again was negatively correlated with the expected amount of money, too. The Sample Selection Bias also appeared.
The solution which impressed me the most can be found in Learning and Making Decisions When Costs and Probabilities are Both Unknown by Bianca Zadrozny and Charles Elkan. They have created a cost sensitive solution based upon the Heckman correction, which is to my knowledge the first systematic approach to correct the (sample) selection bias. | Best way to combine binary and continuous response | The idea of gui11aume of building a two-stage model is the right way to go, however, one needs to consider the special difficulty of your setup which is the very strong negative correlation between th | Best way to combine binary and continuous response
The idea of gui11aume of building a two-stage model is the right way to go, however, one needs to consider the special difficulty of your setup which is the very strong negative correlation between the debt amount and the probability of making a payment
The primary issue of building a two-stage model here is, that the second model (for prediction of the debt), when built upon the "non-zeros" only, is built on a most likely non-random sample of the population (i.e. the whole dataset), but the combined model has to be applied on the whole population again. This means that the second model will have to make predictions for parts of the data which it has never seen before, resulting in a loss of accuracy. This is called Sample Selection Bias (for a overview from a ML perspective I recommend A Bayesian Network Framework for Reject Inference by Smith and Elkan).
The KDD-Cup-98 dealt with a similar issue where one should predict whether a donor for a veterans organization is likely to donate again and how much it is likely to donate. In this dataset, the probability of donating again was negatively correlated with the expected amount of money, too. The Sample Selection Bias also appeared.
The solution which impressed me the most can be found in Learning and Making Decisions When Costs and Probabilities are Both Unknown by Bianca Zadrozny and Charles Elkan. They have created a cost sensitive solution based upon the Heckman correction, which is to my knowledge the first systematic approach to correct the (sample) selection bias. | Best way to combine binary and continuous response
The idea of gui11aume of building a two-stage model is the right way to go, however, one needs to consider the special difficulty of your setup which is the very strong negative correlation between th |
24,203 | Best way to combine binary and continuous response | That's a very nice question (+1).
Why not treat the 0s as if they were NAs?
You could add a dummy response indicating whether any money has been recovered (i.e.equal to 0 when the value is 0, and 1 when the value is positive) and fit a logistic model on this binary response with the same predictors. You would fit 2 models: the binary response using all the data points, and the continuous response using only the non zeron data points (in line with the idea of treating 0 as NA).
You can still test the nullity of parameters in each model and compute expected gain by using both sets of paramters. | Best way to combine binary and continuous response | That's a very nice question (+1).
Why not treat the 0s as if they were NAs?
You could add a dummy response indicating whether any money has been recovered (i.e.equal to 0 when the value is 0, and 1 wh | Best way to combine binary and continuous response
That's a very nice question (+1).
Why not treat the 0s as if they were NAs?
You could add a dummy response indicating whether any money has been recovered (i.e.equal to 0 when the value is 0, and 1 when the value is positive) and fit a logistic model on this binary response with the same predictors. You would fit 2 models: the binary response using all the data points, and the continuous response using only the non zeron data points (in line with the idea of treating 0 as NA).
You can still test the nullity of parameters in each model and compute expected gain by using both sets of paramters. | Best way to combine binary and continuous response
That's a very nice question (+1).
Why not treat the 0s as if they were NAs?
You could add a dummy response indicating whether any money has been recovered (i.e.equal to 0 when the value is 0, and 1 wh |
24,204 | Question about calculating mutual information | The Mutual Information of two discrete random variables $X$ and $Y$ taking values in $R_X$ and $R_Y$ respectively is the difference between the expectation of $\log p(x,y)$ (the logarithm of the joint probability of $(X,Y)$) and the expectation of $\log\left(p(x)p(y)\right)$ (which would be the joint probability for independent variables having marginal probabilities of $p(x)$ and $p(y)$).
When the vectors constitute an iid sample of $(X,Y)$, we can compute the mutual information of their joint empirical density. This is just the observed frequency: if a particular combination of values $(x,y)$ occurs $k(x,y)$ times in the dataset out of $n$ total occurrences, the empirical density $\hat{p}(x,y)$ is just the ratio $k(x,y)/n$.
To compute expectations with respect to the empirical density, let's introduce some notation. Let $R$ ("rows") be the set of distinct observed values of $X$ and $C$ ("columns") the set of distinct observed values of $Y$. For $x\in R$ and $y\in C$, $k(x,*) = \sum_{y\in C}k(x,y)$ is the row sum, counting all elements of the dataset whose first component is $x$. Likewise, $k(*,y) = \sum_{x\in R}k(x,y)$ is the column sum. These determine the marginal densities. Notice that the sum of all the $k(x,y)$, the sum of all the $k(x,*)$, and the sum of all the $k(*,y)$ all count the elements of the dataset, whence they are all equal to $n$. The mutual information equals
$$\eqalign{
&\sum_{x\in R, y\in C} \frac{k(x,y)}{n} \left(\log \frac{k(x,y)}{n} - \log \left(\frac{k(x,*)}{n} \frac{k(*,y)}{n}\right)\right)\\
=&\frac{1}{n}\sum_{x\in R, y\in C}k(x,y)\left(\log k(x,y) - \log(n)\right)\\
&- \frac{1}{n}\sum_{x\in R}k(x,*)\left(\log k(x,*) - \log(n)\right) \\
&- \frac{1}{n}\sum_{y\in C}k(*,y)\left(\log k(*,y) - \log(n)\right) \\
=&\log(n) + \\
& \frac{1}{n} \left( \sum_{x\in R, y\in C}k(x,y)\log k(x,y) - \sum_{x\in R}k(x,*)\log k(x,*) - \sum_{y\in C}k(*,y)\log k(*,y) \right).
}$$
The first equality is just exploiting properties of logarithms while the last equality is due to the sum-to-$n$ properties of the $k(,)$.
In the example, $n=6$, $R=\{-1,-2,-3,1,2,3\}$, $C=\{1,4,9\}$, all the $k(x,*)=1$, all the $k(*,y)=2$, and all the $k(x,y)$ are either $0$ or $1$. The mutual information equals
$$\log(6) + \frac{1}{6}\left(6 \times (1\times \log(1)) - 6\times(1\times \log(1)) - 3\times(2\times \log(2)) \right) = \log(3).$$ | Question about calculating mutual information | The Mutual Information of two discrete random variables $X$ and $Y$ taking values in $R_X$ and $R_Y$ respectively is the difference between the expectation of $\log p(x,y)$ (the logarithm of the joint | Question about calculating mutual information
The Mutual Information of two discrete random variables $X$ and $Y$ taking values in $R_X$ and $R_Y$ respectively is the difference between the expectation of $\log p(x,y)$ (the logarithm of the joint probability of $(X,Y)$) and the expectation of $\log\left(p(x)p(y)\right)$ (which would be the joint probability for independent variables having marginal probabilities of $p(x)$ and $p(y)$).
When the vectors constitute an iid sample of $(X,Y)$, we can compute the mutual information of their joint empirical density. This is just the observed frequency: if a particular combination of values $(x,y)$ occurs $k(x,y)$ times in the dataset out of $n$ total occurrences, the empirical density $\hat{p}(x,y)$ is just the ratio $k(x,y)/n$.
To compute expectations with respect to the empirical density, let's introduce some notation. Let $R$ ("rows") be the set of distinct observed values of $X$ and $C$ ("columns") the set of distinct observed values of $Y$. For $x\in R$ and $y\in C$, $k(x,*) = \sum_{y\in C}k(x,y)$ is the row sum, counting all elements of the dataset whose first component is $x$. Likewise, $k(*,y) = \sum_{x\in R}k(x,y)$ is the column sum. These determine the marginal densities. Notice that the sum of all the $k(x,y)$, the sum of all the $k(x,*)$, and the sum of all the $k(*,y)$ all count the elements of the dataset, whence they are all equal to $n$. The mutual information equals
$$\eqalign{
&\sum_{x\in R, y\in C} \frac{k(x,y)}{n} \left(\log \frac{k(x,y)}{n} - \log \left(\frac{k(x,*)}{n} \frac{k(*,y)}{n}\right)\right)\\
=&\frac{1}{n}\sum_{x\in R, y\in C}k(x,y)\left(\log k(x,y) - \log(n)\right)\\
&- \frac{1}{n}\sum_{x\in R}k(x,*)\left(\log k(x,*) - \log(n)\right) \\
&- \frac{1}{n}\sum_{y\in C}k(*,y)\left(\log k(*,y) - \log(n)\right) \\
=&\log(n) + \\
& \frac{1}{n} \left( \sum_{x\in R, y\in C}k(x,y)\log k(x,y) - \sum_{x\in R}k(x,*)\log k(x,*) - \sum_{y\in C}k(*,y)\log k(*,y) \right).
}$$
The first equality is just exploiting properties of logarithms while the last equality is due to the sum-to-$n$ properties of the $k(,)$.
In the example, $n=6$, $R=\{-1,-2,-3,1,2,3\}$, $C=\{1,4,9\}$, all the $k(x,*)=1$, all the $k(*,y)=2$, and all the $k(x,y)$ are either $0$ or $1$. The mutual information equals
$$\log(6) + \frac{1}{6}\left(6 \times (1\times \log(1)) - 6\times(1\times \log(1)) - 3\times(2\times \log(2)) \right) = \log(3).$$ | Question about calculating mutual information
The Mutual Information of two discrete random variables $X$ and $Y$ taking values in $R_X$ and $R_Y$ respectively is the difference between the expectation of $\log p(x,y)$ (the logarithm of the joint |
24,205 | Is it necessary to detrend and decycle time-series data when using machine learning methods? | With machine learning algorithms it is often beneficial to use feature scaling or normalisation to help the algorithm converge quickly during the training and to avoid one set of features dominating another. Take, for example, the problem of predicting stock prices. If you include high priced stocks such as Apple or Microsoft along with some penny stocks, the high valued features you will necessarily extract from Apple and Microsoft prices will overwhelm those that you extract from the penny stocks, and you won't be training on an apple to apple basis ( no pun intended! ), and the resultant trained model might not generalise very well.
However, imho "attempting to decycle and detrend the data" would be a very good thing to do. Extracting the various cyclic and trend components and normalising them by subtracting their respective means and dividing by their standard deviations would place all the data for all time series into the same approximate range, and then you would be training on like to like data which, when rescaled by reversing the normalisation, would likely generalise much better for predictive purposes.
Furthermore, for any time series it might be the case that trend swamps the cyclic component, so you might end up training on trend only data which almost certainly won't perform well on cyclic time series, and vice versa. By separating out the two components and training on each with separate SVMs or NNs and then recombining the two predictions, you might end up with a more accurate and more readily generalisable algorithm. | Is it necessary to detrend and decycle time-series data when using machine learning methods? | With machine learning algorithms it is often beneficial to use feature scaling or normalisation to help the algorithm converge quickly during the training and to avoid one set of features dominating a | Is it necessary to detrend and decycle time-series data when using machine learning methods?
With machine learning algorithms it is often beneficial to use feature scaling or normalisation to help the algorithm converge quickly during the training and to avoid one set of features dominating another. Take, for example, the problem of predicting stock prices. If you include high priced stocks such as Apple or Microsoft along with some penny stocks, the high valued features you will necessarily extract from Apple and Microsoft prices will overwhelm those that you extract from the penny stocks, and you won't be training on an apple to apple basis ( no pun intended! ), and the resultant trained model might not generalise very well.
However, imho "attempting to decycle and detrend the data" would be a very good thing to do. Extracting the various cyclic and trend components and normalising them by subtracting their respective means and dividing by their standard deviations would place all the data for all time series into the same approximate range, and then you would be training on like to like data which, when rescaled by reversing the normalisation, would likely generalise much better for predictive purposes.
Furthermore, for any time series it might be the case that trend swamps the cyclic component, so you might end up training on trend only data which almost certainly won't perform well on cyclic time series, and vice versa. By separating out the two components and training on each with separate SVMs or NNs and then recombining the two predictions, you might end up with a more accurate and more readily generalisable algorithm. | Is it necessary to detrend and decycle time-series data when using machine learning methods?
With machine learning algorithms it is often beneficial to use feature scaling or normalisation to help the algorithm converge quickly during the training and to avoid one set of features dominating a |
24,206 | Is it necessary to detrend and decycle time-series data when using machine learning methods? | How far ahead are you predicting compared to the timescales that trend or cycles operate on? Zhang, Qi 2005 - 'Neural network forecasting for seasonal and trend time series' find de-seasonalising and de-trending (DSDT) beneficial, but their prediction timescales are similar to their trend/seasonal timescales. In contrast I've been working on data where I make short timescale predictions (e.g. 1 day) and trend/seasonality only act over much longer timescales. DSDT does still improve my predictive accuracy to some degree, but the ML can cope reasonably well on its own without DSDT as trend/seasonality is effectively irrelevant for the last few data points. | Is it necessary to detrend and decycle time-series data when using machine learning methods? | How far ahead are you predicting compared to the timescales that trend or cycles operate on? Zhang, Qi 2005 - 'Neural network forecasting for seasonal and trend time series' find de-seasonalising and | Is it necessary to detrend and decycle time-series data when using machine learning methods?
How far ahead are you predicting compared to the timescales that trend or cycles operate on? Zhang, Qi 2005 - 'Neural network forecasting for seasonal and trend time series' find de-seasonalising and de-trending (DSDT) beneficial, but their prediction timescales are similar to their trend/seasonal timescales. In contrast I've been working on data where I make short timescale predictions (e.g. 1 day) and trend/seasonality only act over much longer timescales. DSDT does still improve my predictive accuracy to some degree, but the ML can cope reasonably well on its own without DSDT as trend/seasonality is effectively irrelevant for the last few data points. | Is it necessary to detrend and decycle time-series data when using machine learning methods?
How far ahead are you predicting compared to the timescales that trend or cycles operate on? Zhang, Qi 2005 - 'Neural network forecasting for seasonal and trend time series' find de-seasonalising and |
24,207 | Is it necessary to detrend and decycle time-series data when using machine learning methods? | I'm pretty sure you are using wrong tools here.
ML methods are created for interpolation (like predicting time series A from time series B and C); for extrapolations we have Markov chains and friends.
The problem with your approach is that it is terribly easy to overfit the model in this conditions and, what's worse, it is hard to spot this (normal cross-validation will fail, so it is very hard to fit parameters the proper way, etc.).
Adding explicit time to predictors is also a bad idea -- I have seen models fitted only on time and decision with 90% accuracy on cross-validation and random guessing on post-training-data tests. If you need time, it is better to include it as a series of cycle descriptors like day of week or seconds past midnight, obviously never exceeding or even going near the length of your training series. | Is it necessary to detrend and decycle time-series data when using machine learning methods? | I'm pretty sure you are using wrong tools here.
ML methods are created for interpolation (like predicting time series A from time series B and C); for extrapolations we have Markov chains and friends. | Is it necessary to detrend and decycle time-series data when using machine learning methods?
I'm pretty sure you are using wrong tools here.
ML methods are created for interpolation (like predicting time series A from time series B and C); for extrapolations we have Markov chains and friends.
The problem with your approach is that it is terribly easy to overfit the model in this conditions and, what's worse, it is hard to spot this (normal cross-validation will fail, so it is very hard to fit parameters the proper way, etc.).
Adding explicit time to predictors is also a bad idea -- I have seen models fitted only on time and decision with 90% accuracy on cross-validation and random guessing on post-training-data tests. If you need time, it is better to include it as a series of cycle descriptors like day of week or seconds past midnight, obviously never exceeding or even going near the length of your training series. | Is it necessary to detrend and decycle time-series data when using machine learning methods?
I'm pretty sure you are using wrong tools here.
ML methods are created for interpolation (like predicting time series A from time series B and C); for extrapolations we have Markov chains and friends. |
24,208 | Priors for log-normal models | When I'm trying to be relatively uninformative, I have tended to use a uniform prior on $\ln \sigma$ and specify an upper bound, which corresponds to $p(\sigma) \propto 1/\sigma$ over a finite range—relatively uninformative, and equal to Jeffreys' prior over the range (not equal to what the Jeffreys prior would be if you knew there was an upper bound on $\sigma$ and what it was.) If the posterior piles up against your upper bound, you can increase it and rerun, unless you have some strong reason for choosing that upper bound. This was suggested by Andrew Gelman in the Prior distributions for variance parameters paper here. (Some of the other articles in this issue of Bayesian Analysis are possibly relevant too, hence the link to the journal page.)
However, recently I've tried the beta-prime prior suggested in the first response to
Weakly informative prior distributions for scale parameters and that worked out well for me also. Importance sampling on the output of the MCMC indicated that the differences between the posteriors of the parameters of interest using the two priors were trivial, which, after all, is what you want when you're trying to be relatively uninformative - and it gets you away from that annoying specification of an upper bound on $\sigma$.
This question and answer may also be relevant:
Random effect on scale parameter | Priors for log-normal models | When I'm trying to be relatively uninformative, I have tended to use a uniform prior on $\ln \sigma$ and specify an upper bound, which corresponds to $p(\sigma) \propto 1/\sigma$ over a finite range—r | Priors for log-normal models
When I'm trying to be relatively uninformative, I have tended to use a uniform prior on $\ln \sigma$ and specify an upper bound, which corresponds to $p(\sigma) \propto 1/\sigma$ over a finite range—relatively uninformative, and equal to Jeffreys' prior over the range (not equal to what the Jeffreys prior would be if you knew there was an upper bound on $\sigma$ and what it was.) If the posterior piles up against your upper bound, you can increase it and rerun, unless you have some strong reason for choosing that upper bound. This was suggested by Andrew Gelman in the Prior distributions for variance parameters paper here. (Some of the other articles in this issue of Bayesian Analysis are possibly relevant too, hence the link to the journal page.)
However, recently I've tried the beta-prime prior suggested in the first response to
Weakly informative prior distributions for scale parameters and that worked out well for me also. Importance sampling on the output of the MCMC indicated that the differences between the posteriors of the parameters of interest using the two priors were trivial, which, after all, is what you want when you're trying to be relatively uninformative - and it gets you away from that annoying specification of an upper bound on $\sigma$.
This question and answer may also be relevant:
Random effect on scale parameter | Priors for log-normal models
When I'm trying to be relatively uninformative, I have tended to use a uniform prior on $\ln \sigma$ and specify an upper bound, which corresponds to $p(\sigma) \propto 1/\sigma$ over a finite range—r |
24,209 | Priors for log-normal models | In the absence of a particular desired form of prior, often people use conjugate priors; the conjugate prior for $\sigma^2$ in the normal would be inverse gamma. You can choose anything from highly uninformative (an improper prior like $1/\sigma^2$ is often used and is a limiting case of the Inverse Gamma), through mildly informative, to a fully informative prior (such as one based on a previous study).
I believe the Jeffreys prior is $1/\sigma^2$. The nice thing about Jeffreys priors is they don't depend on your parameterization (if you transform the parameter, the Jeffreys prior 'follows' it so that everything corresponds).
http://en.wikipedia.org/wiki/Inverse-gamma_distribution | Priors for log-normal models | In the absence of a particular desired form of prior, often people use conjugate priors; the conjugate prior for $\sigma^2$ in the normal would be inverse gamma. You can choose anything from highly un | Priors for log-normal models
In the absence of a particular desired form of prior, often people use conjugate priors; the conjugate prior for $\sigma^2$ in the normal would be inverse gamma. You can choose anything from highly uninformative (an improper prior like $1/\sigma^2$ is often used and is a limiting case of the Inverse Gamma), through mildly informative, to a fully informative prior (such as one based on a previous study).
I believe the Jeffreys prior is $1/\sigma^2$. The nice thing about Jeffreys priors is they don't depend on your parameterization (if you transform the parameter, the Jeffreys prior 'follows' it so that everything corresponds).
http://en.wikipedia.org/wiki/Inverse-gamma_distribution | Priors for log-normal models
In the absence of a particular desired form of prior, often people use conjugate priors; the conjugate prior for $\sigma^2$ in the normal would be inverse gamma. You can choose anything from highly un |
24,210 | Priors for log-normal models | Jeffreys in his book on probability describes what noninformative priors he would use for scale parameters. He uses improper priors (i.e. prior density functions that do not have a finite integral). Here is an amazon link to the book. http://www.amazon.com/Theory-Probability-Classic-Physical-Sciences/dp/0198503687/ref=sr_1_1?s=books&ie=UTF8&qid=1339588187&sr=1-1. | Priors for log-normal models | Jeffreys in his book on probability describes what noninformative priors he would use for scale parameters. He uses improper priors (i.e. prior density functions that do not have a finite integral). | Priors for log-normal models
Jeffreys in his book on probability describes what noninformative priors he would use for scale parameters. He uses improper priors (i.e. prior density functions that do not have a finite integral). Here is an amazon link to the book. http://www.amazon.com/Theory-Probability-Classic-Physical-Sciences/dp/0198503687/ref=sr_1_1?s=books&ie=UTF8&qid=1339588187&sr=1-1. | Priors for log-normal models
Jeffreys in his book on probability describes what noninformative priors he would use for scale parameters. He uses improper priors (i.e. prior density functions that do not have a finite integral). |
24,211 | Hosting options for publicly available data | One simple option is github.
I use it a bit to share data and data analysis code. A few good examples of others sharing code and data on the site are listed on this question.
Benefits of github
Easy to upload once you get familiar with git, and why not use git for your version control needs.
You can use gists for simple single files
It's easy for others to download single or multiple files as an archive
It has a good amount of free storage
source code can be browsed on the internet
and more...
Of course, github isn't perfect for data. I can see the merits of using a more permanent institutional repository or some other dedicated tool for more serious archiving. | Hosting options for publicly available data | One simple option is github.
I use it a bit to share data and data analysis code. A few good examples of others sharing code and data on the site are listed on this question.
Benefits of github
Eas | Hosting options for publicly available data
One simple option is github.
I use it a bit to share data and data analysis code. A few good examples of others sharing code and data on the site are listed on this question.
Benefits of github
Easy to upload once you get familiar with git, and why not use git for your version control needs.
You can use gists for simple single files
It's easy for others to download single or multiple files as an archive
It has a good amount of free storage
source code can be browsed on the internet
and more...
Of course, github isn't perfect for data. I can see the merits of using a more permanent institutional repository or some other dedicated tool for more serious archiving. | Hosting options for publicly available data
One simple option is github.
I use it a bit to share data and data analysis code. A few good examples of others sharing code and data on the site are listed on this question.
Benefits of github
Eas |
24,212 | Hosting options for publicly available data | Another option seems to be Dataverse, which is available as a service and as open source software. I did not try it, though. | Hosting options for publicly available data | Another option seems to be Dataverse, which is available as a service and as open source software. I did not try it, though. | Hosting options for publicly available data
Another option seems to be Dataverse, which is available as a service and as open source software. I did not try it, though. | Hosting options for publicly available data
Another option seems to be Dataverse, which is available as a service and as open source software. I did not try it, though. |
24,213 | Hosting options for publicly available data | One possibility for those in academe is the use of a campus digital repository often hosted by campus libraries (to me a logical locus for datasets that accompany publications).
A popular (free) digital repository is DSpace which, to my understanding, can host data sets. But this is a service that someone in your institution must host. | Hosting options for publicly available data | One possibility for those in academe is the use of a campus digital repository often hosted by campus libraries (to me a logical locus for datasets that accompany publications).
A popular (free) digit | Hosting options for publicly available data
One possibility for those in academe is the use of a campus digital repository often hosted by campus libraries (to me a logical locus for datasets that accompany publications).
A popular (free) digital repository is DSpace which, to my understanding, can host data sets. But this is a service that someone in your institution must host. | Hosting options for publicly available data
One possibility for those in academe is the use of a campus digital repository often hosted by campus libraries (to me a logical locus for datasets that accompany publications).
A popular (free) digit |
24,214 | What does a confidence interval (vs. a credible interval) actually express? [duplicate] | Both Confidence Intervals and Credible Intervals represent our knowledge about an unknown parameter given the data and other assumptions. When using lay interpretations the 2 intervals are pretty similar (though I may have just made frequentists and Bayesians have common ground in being offended by my statement). The tricky part comes when getting into exact definitions.
The Bayesians can talk about the probability of the parameter being in the interval, but they have to use the Bayesian definition of probability which is basically that probability represents our knowledge about an unknown parameter (look familiar?). Note that I am not a Bayesian, so they may want to give a better definition than mine. This does not work if you try to use a frequentist understanding of probability.
The frequentist definition of probability talks about the frequency that an outcome will occure if repeated a bunch of times at random. So once the randomness is over we cannot talk about probability any more, so we use the term confidence to represent the idea of amount of uncertainty after the event has occured (frequentist confidence is similar to Bayesian probability). Before I flip a fair coin I have a probability of 0.5 of getting heads, but after the coin has been flipped and landed or been caught it either shows a heads or a tails so the probability is either 0% or 100%, that is why frequentists don't like saying "probability" after the random piece is over (Bayesians don't have this problem since probability to them represents our knowledge about something, not the proportion of actual outcomes). Before collecting the sample from which you will compute your confidence interval you have a 95% chance of getting a sample that will generate a Confidence Interval that contains the true value. But once we have a Confidence Interval, the true value is either inside of that interval or it is not, and it does not change.
Imagine that you have an urn with 95 white balls and 5 black balls (or a higher total number with the same proportion). Now draw one ball out completely at random and hold it in your hand without looking at it (if you are worried about quantum uncertainty you can have a friend look at it but not tell you what color it is). Now you either have a white ball or a black ball in your hand, you just don't know which. A Bayesian can say that there is a 95% probability of having a white ball because their definition of probability represents the knowledge that you drew a ball at random where 95% were white. The frequentists could say that they are 95% confident that you have a white ball for the same reasoning, but neither would claim that if you open your hand 100 times and look at the ball (without drawing a new ball) that you will see a black ball about 5 times and a white about 95 times (which is what would happen if there was a 95% frequentist probability of having a white ball). Now imagine that the white balls represent samples that would lead to a correct CI and black balls represent samples that would not.
You can see this through simulation, either using a computer to simulate data from a known distribution or using a small finite population where you can compute the true mean. If you take a bunch of sample and compute Confidence Intervals and Credible Intervals for each sample, then compute the true mean (or other parameter) you will see that about 95% of the intervals contain the true value (if you have used reasonable assumptions). But if you concentrate on a single interval from a single sample, it either contains the true value or it does not, and no matter how long you stare at that given interval, the true value is not going to jump in or out. | What does a confidence interval (vs. a credible interval) actually express? [duplicate] | Both Confidence Intervals and Credible Intervals represent our knowledge about an unknown parameter given the data and other assumptions. When using lay interpretations the 2 intervals are pretty sim | What does a confidence interval (vs. a credible interval) actually express? [duplicate]
Both Confidence Intervals and Credible Intervals represent our knowledge about an unknown parameter given the data and other assumptions. When using lay interpretations the 2 intervals are pretty similar (though I may have just made frequentists and Bayesians have common ground in being offended by my statement). The tricky part comes when getting into exact definitions.
The Bayesians can talk about the probability of the parameter being in the interval, but they have to use the Bayesian definition of probability which is basically that probability represents our knowledge about an unknown parameter (look familiar?). Note that I am not a Bayesian, so they may want to give a better definition than mine. This does not work if you try to use a frequentist understanding of probability.
The frequentist definition of probability talks about the frequency that an outcome will occure if repeated a bunch of times at random. So once the randomness is over we cannot talk about probability any more, so we use the term confidence to represent the idea of amount of uncertainty after the event has occured (frequentist confidence is similar to Bayesian probability). Before I flip a fair coin I have a probability of 0.5 of getting heads, but after the coin has been flipped and landed or been caught it either shows a heads or a tails so the probability is either 0% or 100%, that is why frequentists don't like saying "probability" after the random piece is over (Bayesians don't have this problem since probability to them represents our knowledge about something, not the proportion of actual outcomes). Before collecting the sample from which you will compute your confidence interval you have a 95% chance of getting a sample that will generate a Confidence Interval that contains the true value. But once we have a Confidence Interval, the true value is either inside of that interval or it is not, and it does not change.
Imagine that you have an urn with 95 white balls and 5 black balls (or a higher total number with the same proportion). Now draw one ball out completely at random and hold it in your hand without looking at it (if you are worried about quantum uncertainty you can have a friend look at it but not tell you what color it is). Now you either have a white ball or a black ball in your hand, you just don't know which. A Bayesian can say that there is a 95% probability of having a white ball because their definition of probability represents the knowledge that you drew a ball at random where 95% were white. The frequentists could say that they are 95% confident that you have a white ball for the same reasoning, but neither would claim that if you open your hand 100 times and look at the ball (without drawing a new ball) that you will see a black ball about 5 times and a white about 95 times (which is what would happen if there was a 95% frequentist probability of having a white ball). Now imagine that the white balls represent samples that would lead to a correct CI and black balls represent samples that would not.
You can see this through simulation, either using a computer to simulate data from a known distribution or using a small finite population where you can compute the true mean. If you take a bunch of sample and compute Confidence Intervals and Credible Intervals for each sample, then compute the true mean (or other parameter) you will see that about 95% of the intervals contain the true value (if you have used reasonable assumptions). But if you concentrate on a single interval from a single sample, it either contains the true value or it does not, and no matter how long you stare at that given interval, the true value is not going to jump in or out. | What does a confidence interval (vs. a credible interval) actually express? [duplicate]
Both Confidence Intervals and Credible Intervals represent our knowledge about an unknown parameter given the data and other assumptions. When using lay interpretations the 2 intervals are pretty sim |
24,215 | What does a confidence interval (vs. a credible interval) actually express? [duplicate] | I never understood confidence intervals until I read, in the wikipedia article, that frequentist confidence interval bounds are random variables. Yes, one performs some computation on observed data to construct confidence intervals, but since the data are (assumed) random variables, the confidence intervals are also random variables.
So for $l, u$ to be a symmetric 95 % confidence interval on population parameter, $\theta$, say, it should be the case that $l$ is a random variable that is larger than $\theta$ with probability 2.5 %, and similarly $u$ is a random variable that is smaller than $\theta$ with probability 2.5 %. For whatever reason, this formulation is easier for me to grasp: there is some unknown population parameter; I draw a sample from the population; as part of my draw, 2 'degrees of freedom' are spent on flipping biased coins for whether the $l$ and $u$ will actually bound the unknown parameter; I compute $l$ and $u$ from my sample. | What does a confidence interval (vs. a credible interval) actually express? [duplicate] | I never understood confidence intervals until I read, in the wikipedia article, that frequentist confidence interval bounds are random variables. Yes, one performs some computation on observed data to | What does a confidence interval (vs. a credible interval) actually express? [duplicate]
I never understood confidence intervals until I read, in the wikipedia article, that frequentist confidence interval bounds are random variables. Yes, one performs some computation on observed data to construct confidence intervals, but since the data are (assumed) random variables, the confidence intervals are also random variables.
So for $l, u$ to be a symmetric 95 % confidence interval on population parameter, $\theta$, say, it should be the case that $l$ is a random variable that is larger than $\theta$ with probability 2.5 %, and similarly $u$ is a random variable that is smaller than $\theta$ with probability 2.5 %. For whatever reason, this formulation is easier for me to grasp: there is some unknown population parameter; I draw a sample from the population; as part of my draw, 2 'degrees of freedom' are spent on flipping biased coins for whether the $l$ and $u$ will actually bound the unknown parameter; I compute $l$ and $u$ from my sample. | What does a confidence interval (vs. a credible interval) actually express? [duplicate]
I never understood confidence intervals until I read, in the wikipedia article, that frequentist confidence interval bounds are random variables. Yes, one performs some computation on observed data to |
24,216 | What does a confidence interval (vs. a credible interval) actually express? [duplicate] | Fruequentist:
By constructing an 1-alpha confidence interval, 1-alpha confidence intervals generated this way will include the "true" population parameter. Here the population parameter is fixed and the boundaries of the confidence interval are random.
This, however, says nothing about the probability of a certain confidence interval including the population parameter after the fact. After the fact, the confidence interval either includes the population parameter or it does not. There is nothing probabilistic anymore. So one cannot say that the true parameter lies within the confidence interval {-0.34, 0.2} with a probability of 95%, but rather that 95% of the confidence intervals generated by the same procedure (random sampling etc.) will include the fixed population parameter.
A good animation illustrating confidence intervals can be found on Yihui Xie's Website, who is author of the animation package in R:
Animation of confidence intervals: http://animation.yihui.name/mathstat:confidence_interval
Animation Package on CRAN: http://cran.r-project.org/web/packages/animation/index.html
Bayesian
Bayesians on the other hand incorporate uncertainty/information about the population parameter in their statistics (this is the so called "prior"). So a credible interval might be better thought of as a region of highest subjective believe. "Based on the prior information and the data I believe to 1-alpha % that the interval {-0.34, 0.2} includes the parameter". Most of the times this subjective believe is based on ohter data.
Practical Use
Both intervals say something about the accuracy of our estimate. If you want to let the data speak for themselves, you could use confidence intervals or bayesian credible intervals with a uniform prior. If, however, you have strong prior information that you want to not only include in your discussion section but also in your statistics, I would use credible intervals. So to me the problem is more one of what you want and less one of interpretation. | What does a confidence interval (vs. a credible interval) actually express? [duplicate] | Fruequentist:
By constructing an 1-alpha confidence interval, 1-alpha confidence intervals generated this way will include the "true" population parameter. Here the population parameter is fixed and t | What does a confidence interval (vs. a credible interval) actually express? [duplicate]
Fruequentist:
By constructing an 1-alpha confidence interval, 1-alpha confidence intervals generated this way will include the "true" population parameter. Here the population parameter is fixed and the boundaries of the confidence interval are random.
This, however, says nothing about the probability of a certain confidence interval including the population parameter after the fact. After the fact, the confidence interval either includes the population parameter or it does not. There is nothing probabilistic anymore. So one cannot say that the true parameter lies within the confidence interval {-0.34, 0.2} with a probability of 95%, but rather that 95% of the confidence intervals generated by the same procedure (random sampling etc.) will include the fixed population parameter.
A good animation illustrating confidence intervals can be found on Yihui Xie's Website, who is author of the animation package in R:
Animation of confidence intervals: http://animation.yihui.name/mathstat:confidence_interval
Animation Package on CRAN: http://cran.r-project.org/web/packages/animation/index.html
Bayesian
Bayesians on the other hand incorporate uncertainty/information about the population parameter in their statistics (this is the so called "prior"). So a credible interval might be better thought of as a region of highest subjective believe. "Based on the prior information and the data I believe to 1-alpha % that the interval {-0.34, 0.2} includes the parameter". Most of the times this subjective believe is based on ohter data.
Practical Use
Both intervals say something about the accuracy of our estimate. If you want to let the data speak for themselves, you could use confidence intervals or bayesian credible intervals with a uniform prior. If, however, you have strong prior information that you want to not only include in your discussion section but also in your statistics, I would use credible intervals. So to me the problem is more one of what you want and less one of interpretation. | What does a confidence interval (vs. a credible interval) actually express? [duplicate]
Fruequentist:
By constructing an 1-alpha confidence interval, 1-alpha confidence intervals generated this way will include the "true" population parameter. Here the population parameter is fixed and t |
24,217 | Estimating parameters for a spatial process | You can use this module of the pysal python library for the spatial data analysis methods I discuss below.
Your description of how each person's attitude is influenced by the attitudes of the people surrounding her can be represented by a spatial autoregressive model (SAR) (also see my simple SAR explanation from this SE answer 2). The simplest approach is to ignore other factors, and estimate the strength of the influence how surrounding people affect one another's attitudes by using the Moran's I statistic.
If you want to assess the importance of other factors while estimating the strength of the influence of surrounding people, a more complex task, then you can estimate the parameters of a regression: $y = bx + rhoWy + e$. See the docs here.(Methods of estimating this type of regression come from the field of spatial econometrics and can get much more sophisticated than the reference I gave.)
Your challenge will be to build a spatial weights matrix ($W$). I think each element $w_{ij}$ of the matrix should be 1 or 0 based on whether the person $i$ is within some distance you feel that it is required to influence the other person $j$.
To get an intuitive idea of the problem, below I illustrate how a spatial autoregressive data generating process (DGP) will make a pattern of values. For the 2 lattices of simulated values the white blocks represent high values and the dark blocks represent low values.
In the first lattice below the grid values have been generated by a normally distributed random process (or Gaussian), where $rho$ is zero.
In the next lattice below the grid values have been generated by a spatial autoregressive process, where $rho$ has been set to something high, say .8. | Estimating parameters for a spatial process | You can use this module of the pysal python library for the spatial data analysis methods I discuss below.
Your description of how each person's attitude is influenced by the attitudes of the people s | Estimating parameters for a spatial process
You can use this module of the pysal python library for the spatial data analysis methods I discuss below.
Your description of how each person's attitude is influenced by the attitudes of the people surrounding her can be represented by a spatial autoregressive model (SAR) (also see my simple SAR explanation from this SE answer 2). The simplest approach is to ignore other factors, and estimate the strength of the influence how surrounding people affect one another's attitudes by using the Moran's I statistic.
If you want to assess the importance of other factors while estimating the strength of the influence of surrounding people, a more complex task, then you can estimate the parameters of a regression: $y = bx + rhoWy + e$. See the docs here.(Methods of estimating this type of regression come from the field of spatial econometrics and can get much more sophisticated than the reference I gave.)
Your challenge will be to build a spatial weights matrix ($W$). I think each element $w_{ij}$ of the matrix should be 1 or 0 based on whether the person $i$ is within some distance you feel that it is required to influence the other person $j$.
To get an intuitive idea of the problem, below I illustrate how a spatial autoregressive data generating process (DGP) will make a pattern of values. For the 2 lattices of simulated values the white blocks represent high values and the dark blocks represent low values.
In the first lattice below the grid values have been generated by a normally distributed random process (or Gaussian), where $rho$ is zero.
In the next lattice below the grid values have been generated by a spatial autoregressive process, where $rho$ has been set to something high, say .8. | Estimating parameters for a spatial process
You can use this module of the pysal python library for the spatial data analysis methods I discuss below.
Your description of how each person's attitude is influenced by the attitudes of the people s |
24,218 | Estimating parameters for a spatial process | Here is a simple idea which might work. As I've said in the comments if you have a grid with intensities why not fit density of bivariate distribution?
Here is the sample graph to illustrate my point:
Each grid point with is displayed as a square, colored according to intensity. Superimposed on the graph is the contour plot of bivariate normal density plot. As you can see the contour lines expand in the direction of decreasing intensity. The center will be controled by the mean of bivariate normal and the spread of the intensity according to covariance matrix.
To get the estimates of mean and covariance matrix simple numerical optimisation can be used, compare the intensities with values of density function using the mean and the covariance matrix as parameters. Minimize to get the estimates.
This is of course strictly speaking not a statistical estimate, but at least it will give you an idea how to proceed further.
Here is the code for reproducing the graph:
require(mvtnorm)
sigma=cbind(c(0.1,0.7*0.1),c(0.7*0.1,0.1))
x<-seq(0,1,by=0.01)
y<-seq(0,1,by=0.01)
z<-outer(x,y,function(x,y)dmvnorm(cbind(x,y),mean=mean,sigma=sigma))
mz<-melt(z)
mz$X1<-(mz$X1-1)/100
mz$X2<-(mz$X2-1)/100
colnames(mz)<-c("x","y","z")
mz$intensity<-round(mz$z*1000)
ggplot(mz, aes(x,y)) + geom_tile(aes(fill = intensity), colour = "white") + scale_fill_gradient(low = "white", high = "steelblue")+geom_contour(aes(z=z),colour="black") | Estimating parameters for a spatial process | Here is a simple idea which might work. As I've said in the comments if you have a grid with intensities why not fit density of bivariate distribution?
Here is the sample graph to illustrate my point: | Estimating parameters for a spatial process
Here is a simple idea which might work. As I've said in the comments if you have a grid with intensities why not fit density of bivariate distribution?
Here is the sample graph to illustrate my point:
Each grid point with is displayed as a square, colored according to intensity. Superimposed on the graph is the contour plot of bivariate normal density plot. As you can see the contour lines expand in the direction of decreasing intensity. The center will be controled by the mean of bivariate normal and the spread of the intensity according to covariance matrix.
To get the estimates of mean and covariance matrix simple numerical optimisation can be used, compare the intensities with values of density function using the mean and the covariance matrix as parameters. Minimize to get the estimates.
This is of course strictly speaking not a statistical estimate, but at least it will give you an idea how to proceed further.
Here is the code for reproducing the graph:
require(mvtnorm)
sigma=cbind(c(0.1,0.7*0.1),c(0.7*0.1,0.1))
x<-seq(0,1,by=0.01)
y<-seq(0,1,by=0.01)
z<-outer(x,y,function(x,y)dmvnorm(cbind(x,y),mean=mean,sigma=sigma))
mz<-melt(z)
mz$X1<-(mz$X1-1)/100
mz$X2<-(mz$X2-1)/100
colnames(mz)<-c("x","y","z")
mz$intensity<-round(mz$z*1000)
ggplot(mz, aes(x,y)) + geom_tile(aes(fill = intensity), colour = "white") + scale_fill_gradient(low = "white", high = "steelblue")+geom_contour(aes(z=z),colour="black") | Estimating parameters for a spatial process
Here is a simple idea which might work. As I've said in the comments if you have a grid with intensities why not fit density of bivariate distribution?
Here is the sample graph to illustrate my point: |
24,219 | Estimating parameters for a spatial process | Your model is a two-dimensional random field $X[i,j]$, and you are trying to estimate the joint distribution of the integer-values random variables $X[i,j]$. You will want to assume spatial stationarity: that is, the joint distribution of $(X[i_1,j_1],...,X[i_m,j_m])$ is the same as the joint distribution of $(X[i_1+k,j_1+l]...,X[i_m+k,j_m+l])$. In particular, the marginal distribution is the same for every cell. A simple question to ask is the autocorrelation structure of the field. That is, what is $corr(X[i_1,j_1],X[i_2,j_2])$ given the distance $d([i_1,j_1],[i_2,j_2])$? We represent this as a function $\rho(d)$. A simple model for the autocorrelation structure is $\rho(d)=kd^{-1}$, where $k$ is a constant.
A 'gaussian' effect corresponds to a quadratic distance function, but there are many other distance functions you should consider, such as the taxicab norm $d([i_1,j_1],[i_2,j_2]) = |i_1-i_2|+|j_1-j_2|$. Once you have decided on a distance function and the form of your model for autocorrelation it is simple enough to estimate $\rho(d)$ e.g. via maximum likelihood. For more ideas, look for "random field". | Estimating parameters for a spatial process | Your model is a two-dimensional random field $X[i,j]$, and you are trying to estimate the joint distribution of the integer-values random variables $X[i,j]$. You will want to assume spatial stationar | Estimating parameters for a spatial process
Your model is a two-dimensional random field $X[i,j]$, and you are trying to estimate the joint distribution of the integer-values random variables $X[i,j]$. You will want to assume spatial stationarity: that is, the joint distribution of $(X[i_1,j_1],...,X[i_m,j_m])$ is the same as the joint distribution of $(X[i_1+k,j_1+l]...,X[i_m+k,j_m+l])$. In particular, the marginal distribution is the same for every cell. A simple question to ask is the autocorrelation structure of the field. That is, what is $corr(X[i_1,j_1],X[i_2,j_2])$ given the distance $d([i_1,j_1],[i_2,j_2])$? We represent this as a function $\rho(d)$. A simple model for the autocorrelation structure is $\rho(d)=kd^{-1}$, where $k$ is a constant.
A 'gaussian' effect corresponds to a quadratic distance function, but there are many other distance functions you should consider, such as the taxicab norm $d([i_1,j_1],[i_2,j_2]) = |i_1-i_2|+|j_1-j_2|$. Once you have decided on a distance function and the form of your model for autocorrelation it is simple enough to estimate $\rho(d)$ e.g. via maximum likelihood. For more ideas, look for "random field". | Estimating parameters for a spatial process
Your model is a two-dimensional random field $X[i,j]$, and you are trying to estimate the joint distribution of the integer-values random variables $X[i,j]$. You will want to assume spatial stationar |
24,220 | Treatment of outliers produced by kurtosis | The obvious "common sense" way to resolving your problem is to
Get the conclusion using the full data set. i.e. what results will you declare ignoring intermediate calculations?
Get the conclusion using the data set with said "outliers" removed. i.e. what results will you declare ignoring intermediate calculations?
Compare step 2 with step 1
If there is no difference, forget you even had a problem. Outliers are irrelevant to your conclusion. The outliers may influence some other conclusion that may have been drawn using these data, but this is irrelevant to your work. It is somebody else's problem.
If there is a difference, then you have basically a question of "trust". Are these "outliers" real in the sense that they genuinely represent something about your analysis? Or are the "outliers" bad in that they come from some "contaminated source"?
In situation 5 you basically have a case of what-ever "model" you have used to describe the "population" is incomplete - there are details which have been left unspecified, but which matter to the conclusions. There are two ways to resolve this, corresponding to the two "trust" scenarios:
Add some additional structure to your model so that is describes the "outliers". So instead of $P(D|\theta)$, consider $P(D|\theta)=\int P(\lambda|\theta)P(D|\theta,\lambda) d\lambda$.
Create a "model-model", one for the "good" observations, and one for the "bad" observations. So instead of $P(D|\theta)$ you would use $P(D|\theta)=G(D|\theta)u+B(D|\theta)(1-u)$, were u is the probability of obtaining a "good" observation in your sample, and G and B represent the models for the "good" and "bad" data.
Most of the "standard" procedures can be shown to be approximations to these kind of models. The most obvious one is by considering case 1, where the variance has been assumed constant across observations. By relaxing this assumption into a distribution you get a mixture distribution. This is the connection between "normal" and "t" distributions. The normal has fixed variance, whereas the "t" mixes over different variances, the amount of "mixing" depends on the degrees of freedom. High DF means low mixing (outliers are unlikely), low DF means high mixing (outliers are likely). In fact you could take case 2 as a special case of case 1, where the "good" observations are normal, and the "bad" observations are Cauchy (t with 1 DF). | Treatment of outliers produced by kurtosis | The obvious "common sense" way to resolving your problem is to
Get the conclusion using the full data set. i.e. what results will you declare ignoring intermediate calculations?
Get the conclusion u | Treatment of outliers produced by kurtosis
The obvious "common sense" way to resolving your problem is to
Get the conclusion using the full data set. i.e. what results will you declare ignoring intermediate calculations?
Get the conclusion using the data set with said "outliers" removed. i.e. what results will you declare ignoring intermediate calculations?
Compare step 2 with step 1
If there is no difference, forget you even had a problem. Outliers are irrelevant to your conclusion. The outliers may influence some other conclusion that may have been drawn using these data, but this is irrelevant to your work. It is somebody else's problem.
If there is a difference, then you have basically a question of "trust". Are these "outliers" real in the sense that they genuinely represent something about your analysis? Or are the "outliers" bad in that they come from some "contaminated source"?
In situation 5 you basically have a case of what-ever "model" you have used to describe the "population" is incomplete - there are details which have been left unspecified, but which matter to the conclusions. There are two ways to resolve this, corresponding to the two "trust" scenarios:
Add some additional structure to your model so that is describes the "outliers". So instead of $P(D|\theta)$, consider $P(D|\theta)=\int P(\lambda|\theta)P(D|\theta,\lambda) d\lambda$.
Create a "model-model", one for the "good" observations, and one for the "bad" observations. So instead of $P(D|\theta)$ you would use $P(D|\theta)=G(D|\theta)u+B(D|\theta)(1-u)$, were u is the probability of obtaining a "good" observation in your sample, and G and B represent the models for the "good" and "bad" data.
Most of the "standard" procedures can be shown to be approximations to these kind of models. The most obvious one is by considering case 1, where the variance has been assumed constant across observations. By relaxing this assumption into a distribution you get a mixture distribution. This is the connection between "normal" and "t" distributions. The normal has fixed variance, whereas the "t" mixes over different variances, the amount of "mixing" depends on the degrees of freedom. High DF means low mixing (outliers are unlikely), low DF means high mixing (outliers are likely). In fact you could take case 2 as a special case of case 1, where the "good" observations are normal, and the "bad" observations are Cauchy (t with 1 DF). | Treatment of outliers produced by kurtosis
The obvious "common sense" way to resolving your problem is to
Get the conclusion using the full data set. i.e. what results will you declare ignoring intermediate calculations?
Get the conclusion u |
24,221 | Effect size for interaction effect in pre-post treatment-control design | Yes, what you are suggesting is exactly what has been suggested in the literature. See, for example: Morris, S. B. (2008). Estimating effect sizes from pretest-posttest-control group designs. Organizational Research Methods, 11(2), 364-386 (link, but unfortunately, no free access). The article also describes different methods for estimating this effect size measure. You can use the letter "d" to denote the effect size, but you should definitely provide an explanation of what you calculated (otherwise, readers will probably assume that you calculated the standardized mean difference only for the post-test scores). | Effect size for interaction effect in pre-post treatment-control design | Yes, what you are suggesting is exactly what has been suggested in the literature. See, for example: Morris, S. B. (2008). Estimating effect sizes from pretest-posttest-control group designs. Organiza | Effect size for interaction effect in pre-post treatment-control design
Yes, what you are suggesting is exactly what has been suggested in the literature. See, for example: Morris, S. B. (2008). Estimating effect sizes from pretest-posttest-control group designs. Organizational Research Methods, 11(2), 364-386 (link, but unfortunately, no free access). The article also describes different methods for estimating this effect size measure. You can use the letter "d" to denote the effect size, but you should definitely provide an explanation of what you calculated (otherwise, readers will probably assume that you calculated the standardized mean difference only for the post-test scores). | Effect size for interaction effect in pre-post treatment-control design
Yes, what you are suggesting is exactly what has been suggested in the literature. See, for example: Morris, S. B. (2008). Estimating effect sizes from pretest-posttest-control group designs. Organiza |
24,222 | Effect size for interaction effect in pre-post treatment-control design | I believe that generalized eta-square (Olejnik & Algena, 2003; Bakeman, 2005) provides a reasonable solution to the quantification of effect size that generalizes across between-Ss and within-Ss designs. If I read those references correctly, generalized eta-square should also generalize across sample sizes.
Generalized eta-square is automatically computed by the ezANOVA() function in the ez package for R. | Effect size for interaction effect in pre-post treatment-control design | I believe that generalized eta-square (Olejnik & Algena, 2003; Bakeman, 2005) provides a reasonable solution to the quantification of effect size that generalizes across between-Ss and within-Ss desig | Effect size for interaction effect in pre-post treatment-control design
I believe that generalized eta-square (Olejnik & Algena, 2003; Bakeman, 2005) provides a reasonable solution to the quantification of effect size that generalizes across between-Ss and within-Ss designs. If I read those references correctly, generalized eta-square should also generalize across sample sizes.
Generalized eta-square is automatically computed by the ezANOVA() function in the ez package for R. | Effect size for interaction effect in pre-post treatment-control design
I believe that generalized eta-square (Olejnik & Algena, 2003; Bakeman, 2005) provides a reasonable solution to the quantification of effect size that generalizes across between-Ss and within-Ss desig |
24,223 | Statistics based on fractal mathematics | Tutorials in Contemporary Nonlinear Methods for the Behavioral Sciences Web Book
It has several chapters discussing fractals. | Statistics based on fractal mathematics | Tutorials in Contemporary Nonlinear Methods for the Behavioral Sciences Web Book
It has several chapters discussing fractals. | Statistics based on fractal mathematics
Tutorials in Contemporary Nonlinear Methods for the Behavioral Sciences Web Book
It has several chapters discussing fractals. | Statistics based on fractal mathematics
Tutorials in Contemporary Nonlinear Methods for the Behavioral Sciences Web Book
It has several chapters discussing fractals. |
24,224 | What's the rationale for not checking residuals when building a ML model? | The main rationale is the (wrongly) perceived low return on investment.
Lack of time and inappropriate training confound the issue. To a lesser extent, these points are aggravated by laziness and technical difficult respectively.
Especially with more complex models it becomes progressively harder to infer why a model made a particular prediction. Yes, there is a multitude of techniques to explain ML predictions (e.g. LIME, SHAP, Partial Dependency and Accumulated Local Effects plots, etc.) but those are "extra steps". And even then, maybe after the effort to get a SHAP force plot or an ALE plot to explain a particular prediction, we are still left with the question as to how affect the model's prediction. We generated some new questions but usually no immediate answers.
Note that in industrial ML applications "usually" we are concerned with prediction as the primary deliverable of our work. As long as the overall RMSE/MAE/Huber loss is "OK" we ship the model. Questions about the actual model estimation and/or attribution (significance) are often downgraded to "nice-to-have".
Efron recently published an insightful discussion paper titled "Prediction, Estimation, and Attribution" high-lighting these differences further. I think you will find it enlightening on this matter too.
Just to be clear:
You are absolutely correct to say that "the residuals offer some information". Just in many cases, the time to extract, interpreter that information and then to appropriately account for it is not factored in. People should always examine model residuals, perform some model spot-checks, etc. Even the strongest ML methods are far from silver bullets when it comes to prediction. | What's the rationale for not checking residuals when building a ML model? | The main rationale is the (wrongly) perceived low return on investment.
Lack of time and inappropriate training confound the issue. To a lesser extent, these points are aggravated by laziness and tec | What's the rationale for not checking residuals when building a ML model?
The main rationale is the (wrongly) perceived low return on investment.
Lack of time and inappropriate training confound the issue. To a lesser extent, these points are aggravated by laziness and technical difficult respectively.
Especially with more complex models it becomes progressively harder to infer why a model made a particular prediction. Yes, there is a multitude of techniques to explain ML predictions (e.g. LIME, SHAP, Partial Dependency and Accumulated Local Effects plots, etc.) but those are "extra steps". And even then, maybe after the effort to get a SHAP force plot or an ALE plot to explain a particular prediction, we are still left with the question as to how affect the model's prediction. We generated some new questions but usually no immediate answers.
Note that in industrial ML applications "usually" we are concerned with prediction as the primary deliverable of our work. As long as the overall RMSE/MAE/Huber loss is "OK" we ship the model. Questions about the actual model estimation and/or attribution (significance) are often downgraded to "nice-to-have".
Efron recently published an insightful discussion paper titled "Prediction, Estimation, and Attribution" high-lighting these differences further. I think you will find it enlightening on this matter too.
Just to be clear:
You are absolutely correct to say that "the residuals offer some information". Just in many cases, the time to extract, interpreter that information and then to appropriately account for it is not factored in. People should always examine model residuals, perform some model spot-checks, etc. Even the strongest ML methods are far from silver bullets when it comes to prediction. | What's the rationale for not checking residuals when building a ML model?
The main rationale is the (wrongly) perceived low return on investment.
Lack of time and inappropriate training confound the issue. To a lesser extent, these points are aggravated by laziness and tec |
24,225 | What's the rationale for not checking residuals when building a ML model? | I'm tending to disagree with user11852's answer. Here's my thinking:
With traditional statistical models, such as regression, the human specifies a model structure that he/she believes is a (or the most) reasonable approximation of some underlying "data generating" model. IF that single model structure does not in fact conform well to the data ... i.e., it is "mis-specified" ... then that lack of fit is often exposed by some non-random pattern in the residuals. Hence, we look for such patterns, as suggestions that a better model specification may exist.
However, a key aspect of most ML techniques, especially those intended for "pure prediction" as Efron's paper describes, is the the human DOES NOT assume or inject any particular structure for the unknown/unseen data generating process. The algorithm finds and learns patterns in the data, but usually it does not intrinsically create anything understandable by normal humans as an underlying data model. (Ensemble methods may even combine many very disparate models, aka inscrutable-cubed.) Hence the label "black box."
But the idea that there is value in the patterns of the residuals from a ML algorithm relies on an underlying assumption that there could be model mis-specification.
I am far from an academic expert, but I'm not aware of any published papers on ML that have found patterns in residuals, that could be used to inform a better specified model. If there are no such patterns, because of the way the algorithms work, then looking for patterns in the residuals could only lead to illusions of discovery. That would be time spent with a negative ROI.
Effron's 2019 paper mentioned above (TU for that, BTW, hadn't seen it before) does have several examples of "concept drift," as a type of predictive error that would have a pattern. However, my belief is that having one or more variables in the set of x'es, capturing dates or data collection sequence order, would have allowed the ML algorithms to identify and compensate for the drift in their predictions. So I don't find Efron's articulation and examples of concept drift to be a compelling refutation on my argument on ML residuals.
Other viewpoints and pushback cheerfully welcomed !!! We're here to learn. | What's the rationale for not checking residuals when building a ML model? | I'm tending to disagree with user11852's answer. Here's my thinking:
With traditional statistical models, such as regression, the human specifies a model structure that he/she believes is a (or the mo | What's the rationale for not checking residuals when building a ML model?
I'm tending to disagree with user11852's answer. Here's my thinking:
With traditional statistical models, such as regression, the human specifies a model structure that he/she believes is a (or the most) reasonable approximation of some underlying "data generating" model. IF that single model structure does not in fact conform well to the data ... i.e., it is "mis-specified" ... then that lack of fit is often exposed by some non-random pattern in the residuals. Hence, we look for such patterns, as suggestions that a better model specification may exist.
However, a key aspect of most ML techniques, especially those intended for "pure prediction" as Efron's paper describes, is the the human DOES NOT assume or inject any particular structure for the unknown/unseen data generating process. The algorithm finds and learns patterns in the data, but usually it does not intrinsically create anything understandable by normal humans as an underlying data model. (Ensemble methods may even combine many very disparate models, aka inscrutable-cubed.) Hence the label "black box."
But the idea that there is value in the patterns of the residuals from a ML algorithm relies on an underlying assumption that there could be model mis-specification.
I am far from an academic expert, but I'm not aware of any published papers on ML that have found patterns in residuals, that could be used to inform a better specified model. If there are no such patterns, because of the way the algorithms work, then looking for patterns in the residuals could only lead to illusions of discovery. That would be time spent with a negative ROI.
Effron's 2019 paper mentioned above (TU for that, BTW, hadn't seen it before) does have several examples of "concept drift," as a type of predictive error that would have a pattern. However, my belief is that having one or more variables in the set of x'es, capturing dates or data collection sequence order, would have allowed the ML algorithms to identify and compensate for the drift in their predictions. So I don't find Efron's articulation and examples of concept drift to be a compelling refutation on my argument on ML residuals.
Other viewpoints and pushback cheerfully welcomed !!! We're here to learn. | What's the rationale for not checking residuals when building a ML model?
I'm tending to disagree with user11852's answer. Here's my thinking:
With traditional statistical models, such as regression, the human specifies a model structure that he/she believes is a (or the mo |
24,226 | Why does R have a different definition on convolution? | Relation with Fourier transforms
The convolve function in R is using a Fourier transform to compute the convolution (that's a potential source for the difference, although I am not sure, and do not know the details).
$$ x * y = \mathcal{F}^{-1}\{\mathcal{F}\{x\} \cdot \mathcal{F}\{y\}\}$$
But more specifically it is using the complex conjugate, and that is how the operation turns the variable backwards.
x = c(c(1,2,3,4),rep(0,4))
y = c(c(5,6,7,8),rep(0,4))
zx = fft(c(x))
zy = fft(c(y))
round(Re(fft(zx*Conj(zy), inverse = TRUE))/8)
round(Re(fft(zx*zy, inverse = TRUE))/8)
Which returns
[1] 70 56 39 20 0 8 23 44
[1] 5 16 34 60 61 52 32 0
I am not sure why the conjugate is used. This operation with the conjugate relates to convolution according to
$$\mathcal{F}\{x(t) * y^*(-t)\} = \mathcal{F}\{x(t)\}\cdot\left(\mathcal{F}\{y(t)\}\right)^*$$
and if $y$ is real then $y = y^*$. And it also relates a bit to cross-correlation. In which case
$$\mathcal{F}\{x(t) * y(-t)\} = \mathcal{F}\{x(t)\}\cdot \left(\mathcal{F}\{y(t)\}\right)^*$$
Note that R's convolve function is regulating this with a parameter conj which is true by default and setting it to false gives the 'normal' convolution.
convolve(x,y,conj=FALSE)
Indirectly the question could be seen as: "why does R convolve use conj = TRUE as the default option?"
Potential (historic) reason for the difference
Why the standard R function for convolution does it in a reverse way, or how this historically came to be, I do not know. But possibly the origin might stem from the book Time Series: Data Analysis and Theory by David R. Brillinger (1981), which is referenced in the R documentation. In the book the convolution occurs as following:
Suppose the values $X(t)$ and $Y(t)$, $t=0,\dots,T-1$, are available. We will sometimes require the convolution $$\sum_{0\leq {{t}\atop{t+u}} \leq T-1} X(t+u)Y(t) \quad u = 0, \pm 1, \dots \quad (3.6.1)$$
The term convolution is used in a more general sense, and later in the text they refer to a specific case of this type of convolution
One case in which one might require the convolution (3.6.1) is in the estimation of the moment function $m_{12}(u) = E[X_1(t+u)X_2(t)]$...
Also in early descriptions of the use of the fast Fourier transform algorithm (a reference occuring in Brillinger) do they use 'convolution' in a broader sense. In Fast Fourier Transforms: for fun and profit AFIPS '66 (Fall): Proceedings of the November 7-10, 1966, fall joint computer conference, Gentleman and Sande write
... To date, the most important uses of the fast Fourier transform have been in connection with the convolution theorem of Table I. Some uses of numerical convolutions are the following:
Auto- and Cross-Covariances:...
...
...The first major use of the convolution theorem, by Sande, was to compute the auto-covariance...
So it seems that, at least in some circles, convolution has a more general meaning and possibly the writers of the R function found the cross covariance most useful to be the standard (it is mentioned to be a major use).
Differences in conventions also (already) occurs for Fourier transformation
As whuber noted in the comments, Fourier transformation, from which convolution can be derived, is not uniquely defined. There are several conventions for $a$ and $b$ in the below defined Fourier transformation and reverse Fourier transformation formulae:
$$\begin{array}{}
\mathcal{F}(x) = \sqrt{\frac{|b|}{(2\pi)^{1-a}}} \int_{-\infty}^{\infty} f(t) e^{ibxt} \text{d}t \\
f(t) = \sqrt{\frac{|b|}{(2\pi)^{1+a}}} \int_{-\infty}^{\infty} \mathcal{F}(x) e^{-ibxt} \text{d}x
\end{array}$$
and different fields use different parameters $a$ and $b$. The scaling parameter $a$ does not relate much to the 'convolution' operation, but the direction/sign of $b$ may be seen as related.
Personally I am still wondering whether this relationship with Fourier transforms (and its ambiguous conventions) is the reason why the R function is different.
We can use Fourier transforms to compute a convolution, but should that be the reason for the diversity in conventions of convolutions?
(note: In the case of Fourier transforms it may be useful to have different conventions, depending on the field. Because transforms of particular functions, that are more/less relevant depending on the field, might have some simple form or not depending on the convention.) | Why does R have a different definition on convolution? | Relation with Fourier transforms
The convolve function in R is using a Fourier transform to compute the convolution (that's a potential source for the difference, although I am not sure, and do not kn | Why does R have a different definition on convolution?
Relation with Fourier transforms
The convolve function in R is using a Fourier transform to compute the convolution (that's a potential source for the difference, although I am not sure, and do not know the details).
$$ x * y = \mathcal{F}^{-1}\{\mathcal{F}\{x\} \cdot \mathcal{F}\{y\}\}$$
But more specifically it is using the complex conjugate, and that is how the operation turns the variable backwards.
x = c(c(1,2,3,4),rep(0,4))
y = c(c(5,6,7,8),rep(0,4))
zx = fft(c(x))
zy = fft(c(y))
round(Re(fft(zx*Conj(zy), inverse = TRUE))/8)
round(Re(fft(zx*zy, inverse = TRUE))/8)
Which returns
[1] 70 56 39 20 0 8 23 44
[1] 5 16 34 60 61 52 32 0
I am not sure why the conjugate is used. This operation with the conjugate relates to convolution according to
$$\mathcal{F}\{x(t) * y^*(-t)\} = \mathcal{F}\{x(t)\}\cdot\left(\mathcal{F}\{y(t)\}\right)^*$$
and if $y$ is real then $y = y^*$. And it also relates a bit to cross-correlation. In which case
$$\mathcal{F}\{x(t) * y(-t)\} = \mathcal{F}\{x(t)\}\cdot \left(\mathcal{F}\{y(t)\}\right)^*$$
Note that R's convolve function is regulating this with a parameter conj which is true by default and setting it to false gives the 'normal' convolution.
convolve(x,y,conj=FALSE)
Indirectly the question could be seen as: "why does R convolve use conj = TRUE as the default option?"
Potential (historic) reason for the difference
Why the standard R function for convolution does it in a reverse way, or how this historically came to be, I do not know. But possibly the origin might stem from the book Time Series: Data Analysis and Theory by David R. Brillinger (1981), which is referenced in the R documentation. In the book the convolution occurs as following:
Suppose the values $X(t)$ and $Y(t)$, $t=0,\dots,T-1$, are available. We will sometimes require the convolution $$\sum_{0\leq {{t}\atop{t+u}} \leq T-1} X(t+u)Y(t) \quad u = 0, \pm 1, \dots \quad (3.6.1)$$
The term convolution is used in a more general sense, and later in the text they refer to a specific case of this type of convolution
One case in which one might require the convolution (3.6.1) is in the estimation of the moment function $m_{12}(u) = E[X_1(t+u)X_2(t)]$...
Also in early descriptions of the use of the fast Fourier transform algorithm (a reference occuring in Brillinger) do they use 'convolution' in a broader sense. In Fast Fourier Transforms: for fun and profit AFIPS '66 (Fall): Proceedings of the November 7-10, 1966, fall joint computer conference, Gentleman and Sande write
... To date, the most important uses of the fast Fourier transform have been in connection with the convolution theorem of Table I. Some uses of numerical convolutions are the following:
Auto- and Cross-Covariances:...
...
...The first major use of the convolution theorem, by Sande, was to compute the auto-covariance...
So it seems that, at least in some circles, convolution has a more general meaning and possibly the writers of the R function found the cross covariance most useful to be the standard (it is mentioned to be a major use).
Differences in conventions also (already) occurs for Fourier transformation
As whuber noted in the comments, Fourier transformation, from which convolution can be derived, is not uniquely defined. There are several conventions for $a$ and $b$ in the below defined Fourier transformation and reverse Fourier transformation formulae:
$$\begin{array}{}
\mathcal{F}(x) = \sqrt{\frac{|b|}{(2\pi)^{1-a}}} \int_{-\infty}^{\infty} f(t) e^{ibxt} \text{d}t \\
f(t) = \sqrt{\frac{|b|}{(2\pi)^{1+a}}} \int_{-\infty}^{\infty} \mathcal{F}(x) e^{-ibxt} \text{d}x
\end{array}$$
and different fields use different parameters $a$ and $b$. The scaling parameter $a$ does not relate much to the 'convolution' operation, but the direction/sign of $b$ may be seen as related.
Personally I am still wondering whether this relationship with Fourier transforms (and its ambiguous conventions) is the reason why the R function is different.
We can use Fourier transforms to compute a convolution, but should that be the reason for the diversity in conventions of convolutions?
(note: In the case of Fourier transforms it may be useful to have different conventions, depending on the field. Because transforms of particular functions, that are more/less relevant depending on the field, might have some simple form or not depending on the convention.) | Why does R have a different definition on convolution?
Relation with Fourier transforms
The convolve function in R is using a Fourier transform to compute the convolution (that's a potential source for the difference, although I am not sure, and do not kn |
24,227 | Keras: What is the meaning of batch_size for validation? | It means that the validation data will be drawn by batches. There may be cases when you can’t put the whole validation dataset at once in your neural net, you do it in minibatch, similarly as you do for training. | Keras: What is the meaning of batch_size for validation? | It means that the validation data will be drawn by batches. There may be cases when you can’t put the whole validation dataset at once in your neural net, you do it in minibatch, similarly as you do f | Keras: What is the meaning of batch_size for validation?
It means that the validation data will be drawn by batches. There may be cases when you can’t put the whole validation dataset at once in your neural net, you do it in minibatch, similarly as you do for training. | Keras: What is the meaning of batch_size for validation?
It means that the validation data will be drawn by batches. There may be cases when you can’t put the whole validation dataset at once in your neural net, you do it in minibatch, similarly as you do f |
24,228 | Why is Bayesian Statistics becoming a more and more popular research topic? [closed] | Personally, I would venture a few guesses:
(1) Bayesian statistics saw a huge uptick in popularity in the last couple decades. Part of this was due to advancements in MCMC and improvements in computational resources. Bayesian statistics went from being theoretically really nice but only applicable to toy problems to an approach that could be more universally applied. This means that several years ago, saying you worked on Bayesian statistics probably did make you a very competitive hire.
Now, I would say that Bayesian statistics is still a plus, but so is working on interesting problems without using Bayesian methods. A lack of background in Bayesian statistics would certainly be a minus to most hiring committees, but getting a PhD in statistics without sufficient training in Bayesian methods would be pretty surprising.
(2) Bayesian statisticians will mention "Bayesian" on their CV. Frequentists will usually not put "Frequentist" on their CV, but much more typically the the area they work in (i.e., survival analysis, predictive modeling, forecasting, etc.). As an example, a lot of my work is writing optimization algorithms, which I'd guess implies you would say means I do Frequentist work. I've also written a fair chunk of Bayesian algorithms, but it's certainly in the minority of my work. Bayesian statistics is on my CV, Frequentist statistics is not.
(3) To an extent, what you've said in your question also holds truth as well. Efficient general Bayesian computation has more open problems in it than the Frequentist realm. For example, Hamiltonian Monte Carlo has recently become a very exciting algorithm for generically sampling from Bayesian models. There's not a lot of room for improvement of generic optimization these days; Newton Raphson, L-BFGS and EM algorithms cover a lot of bases. If you want to improve on these methods, you generally have to specialize a lot to the problem. As such, you're more like to say "I work on high-dimensional optimization of geo-spatial models" rather than "I work on high-dimensional Maximum Likelihood Estimation". The machine learning world is a bit of an exception to that, as there's a lot of excitement in finding out new stochastic optimization methods (i.e., SGD, Adam, etc.), but that's a slightly different beast for a few reasons.
Similarly, there's work to be done on coming up with good priors for models. Frequentist methods do have an equivalent to this (coming up with good penalties, i.e., LASSO, glmnet) but there's probably more fertile ground for priors over penalties.
(4) Finally, and this is definitely more of a personal opinion, a lot of people associate Frequentist with p-values. Given the general misuse of p-values observed in other fields, lots of statisticians would love to distance themselves as far as possible from current misuses of p-values. | Why is Bayesian Statistics becoming a more and more popular research topic? [closed] | Personally, I would venture a few guesses:
(1) Bayesian statistics saw a huge uptick in popularity in the last couple decades. Part of this was due to advancements in MCMC and improvements in computa | Why is Bayesian Statistics becoming a more and more popular research topic? [closed]
Personally, I would venture a few guesses:
(1) Bayesian statistics saw a huge uptick in popularity in the last couple decades. Part of this was due to advancements in MCMC and improvements in computational resources. Bayesian statistics went from being theoretically really nice but only applicable to toy problems to an approach that could be more universally applied. This means that several years ago, saying you worked on Bayesian statistics probably did make you a very competitive hire.
Now, I would say that Bayesian statistics is still a plus, but so is working on interesting problems without using Bayesian methods. A lack of background in Bayesian statistics would certainly be a minus to most hiring committees, but getting a PhD in statistics without sufficient training in Bayesian methods would be pretty surprising.
(2) Bayesian statisticians will mention "Bayesian" on their CV. Frequentists will usually not put "Frequentist" on their CV, but much more typically the the area they work in (i.e., survival analysis, predictive modeling, forecasting, etc.). As an example, a lot of my work is writing optimization algorithms, which I'd guess implies you would say means I do Frequentist work. I've also written a fair chunk of Bayesian algorithms, but it's certainly in the minority of my work. Bayesian statistics is on my CV, Frequentist statistics is not.
(3) To an extent, what you've said in your question also holds truth as well. Efficient general Bayesian computation has more open problems in it than the Frequentist realm. For example, Hamiltonian Monte Carlo has recently become a very exciting algorithm for generically sampling from Bayesian models. There's not a lot of room for improvement of generic optimization these days; Newton Raphson, L-BFGS and EM algorithms cover a lot of bases. If you want to improve on these methods, you generally have to specialize a lot to the problem. As such, you're more like to say "I work on high-dimensional optimization of geo-spatial models" rather than "I work on high-dimensional Maximum Likelihood Estimation". The machine learning world is a bit of an exception to that, as there's a lot of excitement in finding out new stochastic optimization methods (i.e., SGD, Adam, etc.), but that's a slightly different beast for a few reasons.
Similarly, there's work to be done on coming up with good priors for models. Frequentist methods do have an equivalent to this (coming up with good penalties, i.e., LASSO, glmnet) but there's probably more fertile ground for priors over penalties.
(4) Finally, and this is definitely more of a personal opinion, a lot of people associate Frequentist with p-values. Given the general misuse of p-values observed in other fields, lots of statisticians would love to distance themselves as far as possible from current misuses of p-values. | Why is Bayesian Statistics becoming a more and more popular research topic? [closed]
Personally, I would venture a few guesses:
(1) Bayesian statistics saw a huge uptick in popularity in the last couple decades. Part of this was due to advancements in MCMC and improvements in computa |
24,229 | Can a proper prior and exponentiated likelihood lead to an improper posterior? | For $\alpha \leq 1$, perhaps this is an argument to show that it is impossible to construct such a posterior?
We'd like to find out if it's possible for $\int \tilde \pi(\theta|x)d\theta = \infty$.
On the RHS:
$$ \int \pi(\theta) L^{\alpha}(\theta|x) d\theta = E_{\theta}(L^{\alpha}(\theta|x))$$
If $\alpha \leq 1$, $x^{\alpha}$ is a concave function, so by the Jensen inequality:
$$ E_{\theta}(L^{\alpha}(\theta|x)) \leq E^{\alpha}_{\theta}(L(\theta|x)) = m(x)^\alpha < \infty $$
... where $m(x)$ as Xi'an pointed out, is the normalising constant (the evidence). | Can a proper prior and exponentiated likelihood lead to an improper posterior? | For $\alpha \leq 1$, perhaps this is an argument to show that it is impossible to construct such a posterior?
We'd like to find out if it's possible for $\int \tilde \pi(\theta|x)d\theta = \infty$.
On | Can a proper prior and exponentiated likelihood lead to an improper posterior?
For $\alpha \leq 1$, perhaps this is an argument to show that it is impossible to construct such a posterior?
We'd like to find out if it's possible for $\int \tilde \pi(\theta|x)d\theta = \infty$.
On the RHS:
$$ \int \pi(\theta) L^{\alpha}(\theta|x) d\theta = E_{\theta}(L^{\alpha}(\theta|x))$$
If $\alpha \leq 1$, $x^{\alpha}$ is a concave function, so by the Jensen inequality:
$$ E_{\theta}(L^{\alpha}(\theta|x)) \leq E^{\alpha}_{\theta}(L(\theta|x)) = m(x)^\alpha < \infty $$
... where $m(x)$ as Xi'an pointed out, is the normalising constant (the evidence). | Can a proper prior and exponentiated likelihood lead to an improper posterior?
For $\alpha \leq 1$, perhaps this is an argument to show that it is impossible to construct such a posterior?
We'd like to find out if it's possible for $\int \tilde \pi(\theta|x)d\theta = \infty$.
On |
24,230 | Can a proper prior and exponentiated likelihood lead to an improper posterior? | It's possible to use the result in @InfProbSciX's answer to prove the result in general.
Rewrite $L(\theta\mid x)^\alpha\pi(\theta)$ as $$L(\theta\mid x)^{\alpha-1}L(\theta\mid x)\pi(\theta).$$
If $1 \leq \alpha \leq 2$, we have the Jensen's inequality case above, since we know that $L(x|\theta)\pi(\theta)$ is normalisable.
Similarly, if $2 \leq \alpha \leq 3$, we can write $$ L(x|\theta)^{\alpha-p} L(x|\theta)^p\pi(\theta),$$
with $1 \leq p \leq 2$, again falling into the same case, since we know that $L(x|\theta)^{p}\pi(\theta)$ is normalisable.
Now one can use (strong) induction to show the case in general.
Old comments
Not sure if this is super useful, but since I can't comment I will leave this in an answer. In addition to @InfProbSciX's excellent remark about $\alpha \leq 1$, if one makes the further assumption that $L(\theta \mid x) \in L^p$, then it is impossible to have a proper prior but an improper pseudo-posterior for $ 1 < \alpha \leq p$. For instance, if we know that the second ($p$-th) moment of $L(\theta \mid x)$ exists, we know it is in $L^2$ ($L^p$) and hence the pseudo-posterior will proper for $0 \leq \alpha \leq 2$. Section 1 in these notes goes into a bit more detail, but unfortunately it is not clear how broad the class of, say, $L^{10}$ pdfs is.
I apologise if I'm speaking out of turn here, I really wanted to leave this as a comment. | Can a proper prior and exponentiated likelihood lead to an improper posterior? | It's possible to use the result in @InfProbSciX's answer to prove the result in general.
Rewrite $L(\theta\mid x)^\alpha\pi(\theta)$ as $$L(\theta\mid x)^{\alpha-1}L(\theta\mid x)\pi(\theta).$$
If $1 | Can a proper prior and exponentiated likelihood lead to an improper posterior?
It's possible to use the result in @InfProbSciX's answer to prove the result in general.
Rewrite $L(\theta\mid x)^\alpha\pi(\theta)$ as $$L(\theta\mid x)^{\alpha-1}L(\theta\mid x)\pi(\theta).$$
If $1 \leq \alpha \leq 2$, we have the Jensen's inequality case above, since we know that $L(x|\theta)\pi(\theta)$ is normalisable.
Similarly, if $2 \leq \alpha \leq 3$, we can write $$ L(x|\theta)^{\alpha-p} L(x|\theta)^p\pi(\theta),$$
with $1 \leq p \leq 2$, again falling into the same case, since we know that $L(x|\theta)^{p}\pi(\theta)$ is normalisable.
Now one can use (strong) induction to show the case in general.
Old comments
Not sure if this is super useful, but since I can't comment I will leave this in an answer. In addition to @InfProbSciX's excellent remark about $\alpha \leq 1$, if one makes the further assumption that $L(\theta \mid x) \in L^p$, then it is impossible to have a proper prior but an improper pseudo-posterior for $ 1 < \alpha \leq p$. For instance, if we know that the second ($p$-th) moment of $L(\theta \mid x)$ exists, we know it is in $L^2$ ($L^p$) and hence the pseudo-posterior will proper for $0 \leq \alpha \leq 2$. Section 1 in these notes goes into a bit more detail, but unfortunately it is not clear how broad the class of, say, $L^{10}$ pdfs is.
I apologise if I'm speaking out of turn here, I really wanted to leave this as a comment. | Can a proper prior and exponentiated likelihood lead to an improper posterior?
It's possible to use the result in @InfProbSciX's answer to prove the result in general.
Rewrite $L(\theta\mid x)^\alpha\pi(\theta)$ as $$L(\theta\mid x)^{\alpha-1}L(\theta\mid x)\pi(\theta).$$
If $1 |
24,231 | The basic logic of constructing a confidence interval | Example with 100 Bernoulli trials
The construction of confidence intervals could be placed in a plot of $\theta$ versus $\hat{\theta}$ like here:
Can we reject a null hypothesis with confidence intervals produced via sampling rather than the null hypothesis?
In my answer to that question I use the following graph:
Note that this image is a classic and an adaptation from The Use of Confidence or Fiducial Limits Illustrated in the Case of the Binomial C. J. Clopper and E. S. Pearson Biometrika Vol. 26, No. 4 (Dec., 1934), pp. 404-413
You could define a $\alpha$-% confidence region in two ways:
in vertical direction $L(\theta) < X < U(\theta)$ the probability for the data $X$, conditional on the parameter being truly $\theta$, to fall inside these bounds is $\alpha$ .
in horizontal direction $L(X) < \theta < U(X)$ the probability that an experiment will have the true parameter inside the confidence interval is $\alpha$%.
Correspondence between two directions
So the key-point is that there is a correspondence between the intervals $L(X),U(X)$ and the intervals $L(\theta),U(\theta)$. This is where the two methods come from.
When you want $L(X)$ and $U(X)$ to be as close as possible ("the shortest possible ($1−\alpha$) level confidence interval") then you are trying to make the area of the entire region as small as possible, and this is similar to getting $L(\theta)$ and $U(\theta)$ as close as possible. (more or less, there is no unique way to get the shortest possible interval, e.g. you can make the interval shorter for one type of observation $\hat\theta$ at the cost of another type of observation $\hat\theta$)
Example with $\boldsymbol{\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$
To illustrate the difference between the first and second method we adjust the example a bit such that we have a case where the two methods do differ.
Let the $\sigma$ not be constant but instead have some relation with $\mu= \theta$ $${\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$$
then the probability density function for $\hat \theta$, conditional on $\theta$ is $$f(\hat\theta, \theta ) = \frac{1}{\sqrt{2 \pi (1+\theta^2/3)}} exp \left[ \frac{-(\theta-\hat\theta)^2}{2(1+\theta^2/3)} \right] $$
Imagine this probability density function $f(\hat \theta , \theta)$ plotted as function of $\theta$ and $\hat \theta$.
Legend: The red line is the upper boundary for the confidence interval and the green line is the lower boundary for the confidence interval. The confidence interval is drawn for $\pm 1 \sigma$ (approximately 68.3%). The thick black lines are the pdf (2 times) and likelihood function that cross in the points $(\theta,\hat\theta)=(-3,-1)$ and $(\theta,\hat\theta)=(0,-1)$.
PDF In the direction from left to right (constant $\theta$) we have the pdf for the observation $\hat \theta$ given $\theta$. You see two of these projected (in the plane $\theta = 7$). Note that the $p$-values boundaries ($p<1-\alpha$ chosen to be the highest density region) are on the same height for a single pdf, but not for not at the same height for different pdf's (by height that means the value of $f(\hat\theta,\theta)$)
Likelihood function In the direction from top to bottom (constant $\hat \theta$) we have the likelihood function for $\theta$ given the observation $\hat\theta$. You see one of these projected on the right.
For this particular case, when you select the 68% mass with the highest density for constant $\theta$ then you do not get the same as selecting the 68% mass with the highest likelihood for constant $\hat \theta$.
For other percentages of the confidence interval you will have one or both of the boundaries at $\pm \infty$ and also the interval may consist of two disjoint pieces. So, that is obviously not where the highest density of the likelihood function is (method 2). This is a rather artificial example (although it is simple and nice how it results in these many details) but also for more common cases you get easily that the two methods do not coincide (see the example here where the confidence interval and the credible interval with a flat prior are compared for the rate parameter of a exponential distribution).
When are the two methods the same?
This horizontal vs vertical is giving the same result, when the boundaries $U$ and $L$, that bound the intervals in the plot $\theta$ vs $\hat \theta$ are iso-lines for $f(\hat \theta ; \theta)$. If boundaries are everywhere at the same height than in neither of the two directions you can make an improvement.
(contrasting with this: in the example with $\hat \theta \sim \mathcal{N}(\theta,1+\theta^2/3)$ the confidence interval boundaries will not be at the same value $f(\hat \theta, \theta)$ for different $\theta$, because the probability mass becomes more spread out, thus lower density, for larger $\vert \theta \vert$. This makes that $\theta_{low}$ and $\theta_{high}$ will not be at the same value $f(\hat \theta ; \theta)$, at least for some $\hat \theta$, This contradicts with method 2 that seeks to select the highest densities $f(\hat \theta ; \theta)$ for a given $\hat \theta$. In the image above I have tried to emphasize this by plotting the two pdf functions that relate to the confidence interval boundaries at the value $\hat \theta= -1$; you can see that they have different values of the pdf at these boundaries.)
Actually the second method doesn't seem entirely right (it is more a sort of variant of a likelihood interval or a credible interval than a confidence interval) and when you select $\alpha$% density in the horizontal direction (bounding $\alpha$ % of the mass of the likelihood function) then you may be dependent on the prior probabilities.
In the example with the normal distribution it is not a problem and the two methods align. For an illustration see also this answer of Christoph Hanck. There the boundaries are iso-lines. When you change the $\theta$ the function $f(\hat\theta,\theta)$ only makes a shift and does not change 'shape'.
Fiducial probability
The confidence interval, when the bounds are created in vertical direction, are independent of the prior probabilities. This is not the case with the 2nd method.
This difference between the first and the second method may be a good example of the subtle difference between fiducial/confidence distribution $\frac{d}{d\theta}F(\hat\theta,\theta)$ and the likelihood function $\frac{d}{d\hat\theta}F(\hat\theta,\theta)$ (where $F$ is the cumulative distribution function). | The basic logic of constructing a confidence interval | Example with 100 Bernoulli trials
The construction of confidence intervals could be placed in a plot of $\theta$ versus $\hat{\theta}$ like here:
Can we reject a null hypothesis with confidence interv | The basic logic of constructing a confidence interval
Example with 100 Bernoulli trials
The construction of confidence intervals could be placed in a plot of $\theta$ versus $\hat{\theta}$ like here:
Can we reject a null hypothesis with confidence intervals produced via sampling rather than the null hypothesis?
In my answer to that question I use the following graph:
Note that this image is a classic and an adaptation from The Use of Confidence or Fiducial Limits Illustrated in the Case of the Binomial C. J. Clopper and E. S. Pearson Biometrika Vol. 26, No. 4 (Dec., 1934), pp. 404-413
You could define a $\alpha$-% confidence region in two ways:
in vertical direction $L(\theta) < X < U(\theta)$ the probability for the data $X$, conditional on the parameter being truly $\theta$, to fall inside these bounds is $\alpha$ .
in horizontal direction $L(X) < \theta < U(X)$ the probability that an experiment will have the true parameter inside the confidence interval is $\alpha$%.
Correspondence between two directions
So the key-point is that there is a correspondence between the intervals $L(X),U(X)$ and the intervals $L(\theta),U(\theta)$. This is where the two methods come from.
When you want $L(X)$ and $U(X)$ to be as close as possible ("the shortest possible ($1−\alpha$) level confidence interval") then you are trying to make the area of the entire region as small as possible, and this is similar to getting $L(\theta)$ and $U(\theta)$ as close as possible. (more or less, there is no unique way to get the shortest possible interval, e.g. you can make the interval shorter for one type of observation $\hat\theta$ at the cost of another type of observation $\hat\theta$)
Example with $\boldsymbol{\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$
To illustrate the difference between the first and second method we adjust the example a bit such that we have a case where the two methods do differ.
Let the $\sigma$ not be constant but instead have some relation with $\mu= \theta$ $${\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$$
then the probability density function for $\hat \theta$, conditional on $\theta$ is $$f(\hat\theta, \theta ) = \frac{1}{\sqrt{2 \pi (1+\theta^2/3)}} exp \left[ \frac{-(\theta-\hat\theta)^2}{2(1+\theta^2/3)} \right] $$
Imagine this probability density function $f(\hat \theta , \theta)$ plotted as function of $\theta$ and $\hat \theta$.
Legend: The red line is the upper boundary for the confidence interval and the green line is the lower boundary for the confidence interval. The confidence interval is drawn for $\pm 1 \sigma$ (approximately 68.3%). The thick black lines are the pdf (2 times) and likelihood function that cross in the points $(\theta,\hat\theta)=(-3,-1)$ and $(\theta,\hat\theta)=(0,-1)$.
PDF In the direction from left to right (constant $\theta$) we have the pdf for the observation $\hat \theta$ given $\theta$. You see two of these projected (in the plane $\theta = 7$). Note that the $p$-values boundaries ($p<1-\alpha$ chosen to be the highest density region) are on the same height for a single pdf, but not for not at the same height for different pdf's (by height that means the value of $f(\hat\theta,\theta)$)
Likelihood function In the direction from top to bottom (constant $\hat \theta$) we have the likelihood function for $\theta$ given the observation $\hat\theta$. You see one of these projected on the right.
For this particular case, when you select the 68% mass with the highest density for constant $\theta$ then you do not get the same as selecting the 68% mass with the highest likelihood for constant $\hat \theta$.
For other percentages of the confidence interval you will have one or both of the boundaries at $\pm \infty$ and also the interval may consist of two disjoint pieces. So, that is obviously not where the highest density of the likelihood function is (method 2). This is a rather artificial example (although it is simple and nice how it results in these many details) but also for more common cases you get easily that the two methods do not coincide (see the example here where the confidence interval and the credible interval with a flat prior are compared for the rate parameter of a exponential distribution).
When are the two methods the same?
This horizontal vs vertical is giving the same result, when the boundaries $U$ and $L$, that bound the intervals in the plot $\theta$ vs $\hat \theta$ are iso-lines for $f(\hat \theta ; \theta)$. If boundaries are everywhere at the same height than in neither of the two directions you can make an improvement.
(contrasting with this: in the example with $\hat \theta \sim \mathcal{N}(\theta,1+\theta^2/3)$ the confidence interval boundaries will not be at the same value $f(\hat \theta, \theta)$ for different $\theta$, because the probability mass becomes more spread out, thus lower density, for larger $\vert \theta \vert$. This makes that $\theta_{low}$ and $\theta_{high}$ will not be at the same value $f(\hat \theta ; \theta)$, at least for some $\hat \theta$, This contradicts with method 2 that seeks to select the highest densities $f(\hat \theta ; \theta)$ for a given $\hat \theta$. In the image above I have tried to emphasize this by plotting the two pdf functions that relate to the confidence interval boundaries at the value $\hat \theta= -1$; you can see that they have different values of the pdf at these boundaries.)
Actually the second method doesn't seem entirely right (it is more a sort of variant of a likelihood interval or a credible interval than a confidence interval) and when you select $\alpha$% density in the horizontal direction (bounding $\alpha$ % of the mass of the likelihood function) then you may be dependent on the prior probabilities.
In the example with the normal distribution it is not a problem and the two methods align. For an illustration see also this answer of Christoph Hanck. There the boundaries are iso-lines. When you change the $\theta$ the function $f(\hat\theta,\theta)$ only makes a shift and does not change 'shape'.
Fiducial probability
The confidence interval, when the bounds are created in vertical direction, are independent of the prior probabilities. This is not the case with the 2nd method.
This difference between the first and the second method may be a good example of the subtle difference between fiducial/confidence distribution $\frac{d}{d\theta}F(\hat\theta,\theta)$ and the likelihood function $\frac{d}{d\hat\theta}F(\hat\theta,\theta)$ (where $F$ is the cumulative distribution function). | The basic logic of constructing a confidence interval
Example with 100 Bernoulli trials
The construction of confidence intervals could be placed in a plot of $\theta$ versus $\hat{\theta}$ like here:
Can we reject a null hypothesis with confidence interv |
24,232 | Limiting Sum of i.i.d. Gamma variates | You were correct that Chebyshev's Inequality will work. It provides a somewhat crude but effective bound which applies to many such sequences, revealing that the crucial feature of this sequence is that the variance of the partial sums grows at most linearly with $n$.
Consider, then, the extremely general case of any sequence of uncorrelated variables $X_i$ with means $\mu_i$ and finite variances $\sigma_i^2.$ Let $Y_n$ be the sum of the first $n$ of them,
$$Y_n = \sum_{i=1}^n X_i.$$
Consequently the mean of $Y_n$ is
$$m_n = \sum_{i=1}^n \mu_n$$
and its variance is
$$s_n^2 = \operatorname{Var}(Y_n) = \sum_{i=1}^n \operatorname{Var}(X_i) + 2\sum_{j > i}\operatorname{Cov}(X_i,X_j) = \sum_{i=1}^n \sigma_i^2.$$
Suppose $s_n^2$ grows at most linearly with $n$: that is, there exists a number $\lambda\gt 0$ such that for all sufficiently large $n,$ $s_n^2 \le \lambda^2 n.$ Let $k\gt 0$ (yet to be determined), observe that
$$m - k \sqrt{n} \le m - \frac{k}{\lambda}s_n,$$
and apply Chebyshev's Inequality to $Y_n$ to obtain
$$\eqalign{
\Pr(Y_n \ge m_n - k\sqrt{n}) &\ge \Pr(Y_n \ge m_n - \frac{k}{\lambda}s_n) \\
&\ge \Pr(|Y_n - m_n| \le \frac{k}{\lambda} s_n) \\
&\ge 1 - \frac{\lambda^2}{k^2}.
}$$
The first two inequalities are basic: they follow because each successive event is a subset of the preceding one.
In the case at hand, where $X_i$ are independent (and therefore uncorrelated) with means $\mu_i=3$ and variances $\sigma_i^2=3,$ we have $m_n=3n$ and
$$s_n = \sqrt{3}\sqrt{n},$$
whence we may take $\lambda$ as small as $\sqrt{3}.$ The event in the question $3(n-\sqrt{n}) = \mu_n - 3\sqrt{n}$ corresponds to $k=3,$ where
$$\Pr(Y_n \ge 3n - 3\sqrt{n}) \ge 1 - \frac{\sqrt{3}^{\ 2}}{3^2} = \frac{2}{3}\gt \frac{1}{2},$$
QED. | Limiting Sum of i.i.d. Gamma variates | You were correct that Chebyshev's Inequality will work. It provides a somewhat crude but effective bound which applies to many such sequences, revealing that the crucial feature of this sequence is t | Limiting Sum of i.i.d. Gamma variates
You were correct that Chebyshev's Inequality will work. It provides a somewhat crude but effective bound which applies to many such sequences, revealing that the crucial feature of this sequence is that the variance of the partial sums grows at most linearly with $n$.
Consider, then, the extremely general case of any sequence of uncorrelated variables $X_i$ with means $\mu_i$ and finite variances $\sigma_i^2.$ Let $Y_n$ be the sum of the first $n$ of them,
$$Y_n = \sum_{i=1}^n X_i.$$
Consequently the mean of $Y_n$ is
$$m_n = \sum_{i=1}^n \mu_n$$
and its variance is
$$s_n^2 = \operatorname{Var}(Y_n) = \sum_{i=1}^n \operatorname{Var}(X_i) + 2\sum_{j > i}\operatorname{Cov}(X_i,X_j) = \sum_{i=1}^n \sigma_i^2.$$
Suppose $s_n^2$ grows at most linearly with $n$: that is, there exists a number $\lambda\gt 0$ such that for all sufficiently large $n,$ $s_n^2 \le \lambda^2 n.$ Let $k\gt 0$ (yet to be determined), observe that
$$m - k \sqrt{n} \le m - \frac{k}{\lambda}s_n,$$
and apply Chebyshev's Inequality to $Y_n$ to obtain
$$\eqalign{
\Pr(Y_n \ge m_n - k\sqrt{n}) &\ge \Pr(Y_n \ge m_n - \frac{k}{\lambda}s_n) \\
&\ge \Pr(|Y_n - m_n| \le \frac{k}{\lambda} s_n) \\
&\ge 1 - \frac{\lambda^2}{k^2}.
}$$
The first two inequalities are basic: they follow because each successive event is a subset of the preceding one.
In the case at hand, where $X_i$ are independent (and therefore uncorrelated) with means $\mu_i=3$ and variances $\sigma_i^2=3,$ we have $m_n=3n$ and
$$s_n = \sqrt{3}\sqrt{n},$$
whence we may take $\lambda$ as small as $\sqrt{3}.$ The event in the question $3(n-\sqrt{n}) = \mu_n - 3\sqrt{n}$ corresponds to $k=3,$ where
$$\Pr(Y_n \ge 3n - 3\sqrt{n}) \ge 1 - \frac{\sqrt{3}^{\ 2}}{3^2} = \frac{2}{3}\gt \frac{1}{2},$$
QED. | Limiting Sum of i.i.d. Gamma variates
You were correct that Chebyshev's Inequality will work. It provides a somewhat crude but effective bound which applies to many such sequences, revealing that the crucial feature of this sequence is t |
24,233 | Limiting Sum of i.i.d. Gamma variates | As an alternative to whuber's excellent answer, I will try to derive the exact limit of the probability in question. One of the properties of the gamma distribution is that sums of independent gamma random variables with the same rate/scale parameter are also gamma random variables with shape equal to the sum of the shapes of those variables. (That can be proved using the generating functions of the distribution.) In the present case we have $X_1,...X_n \sim \text{IID Gamma}(3,1)$, so we obtain the sum:
$$S_n \equiv X_1 + \cdots + X_n \sim \text{Gamma}(3n, 1).$$
We can therefore write the exact probability of interest using the CDF of the gamma distribution. Letting $a = 3n$ denote the shape parameter and $x = 3(n-\sqrt{n})$ denote the argument of interest, we have:
$$\begin{equation} \begin{aligned}
H(n)
&\equiv \mathbb{P}(S_n \geq 3(n-\sqrt{n})) \\[12pt]
&= \frac{\Gamma(a, x)}{\Gamma(a)} \\[6pt]
&= \frac{a \Gamma(a)}{a \Gamma(a) + x^a e^{-x}} \cdot \frac{\Gamma(a+1, x)}{\Gamma(a+1)}. \\[6pt]
\end{aligned} \end{equation}$$
To find the limit of this probability, we first note that we can write the second parameter in terms of the first as $x = a + \sqrt{2a} \cdot y$ where $y = -\sqrt{3/2}$. Using a result shown in Temme (1975) (Eqn 1.4, p. 1109) we have the asymptotic equivalence:
$$\begin{aligned}
\frac{\Gamma(a+1, x)}{\Gamma(a+1)}
&\sim \frac{1}{2} + \frac{1}{2} \cdot \text{erf}(-y) + \sqrt{\frac{2}{9a \pi}} (1+y^2) \exp( - y^2).
\end{aligned}$$
Using Stirling's approximation, and the limiting definition of the exponential number, it can also be shown that:
$$\begin{aligned}
\frac{a \Gamma(a)}{a \Gamma(a) + x^a e^{-x}}
&\sim \frac{\sqrt{2 \pi} \cdot a \cdot (a-1)^{a-1/2}}{\sqrt{2 \pi} \cdot a \cdot (a-1)^{a-1/2} + x^a \cdot e^{a-x-1}} \\[6pt]
&= \frac{\sqrt{2 \pi} \cdot a \cdot (1-\tfrac{1}{a})^{a-1/2}}{\sqrt{2 \pi} \cdot a \cdot (1-\tfrac{1}{a})^{a-1/2} + \sqrt{x} \cdot (\tfrac{x}{a})^{a-1/2} \cdot e^{a-x-1}} \\[6pt]
&= \frac{\sqrt{2 \pi} \cdot a \cdot e^{-1}}{\sqrt{2 \pi} \cdot a \cdot e^{-1} + \sqrt{x} \cdot e^{x-a} \cdot e^{a-x-1}} \\[6pt]
&= \frac{\sqrt{2 \pi} \cdot a}{\sqrt{2 \pi} \cdot a + \sqrt{x}} \\[6pt]
&\sim \frac{\sqrt{2 \pi a}}{\sqrt{2 \pi a} + 1}. \\[6pt]
\end{aligned}$$
Substituting the relevant values, we therefore obtain:
$$\begin{equation} \begin{aligned}
H(n)
&= \frac{a \Gamma(a)}{a \Gamma(a) + x^a e^{-x}} \cdot \frac{\Gamma(a+1, x)}{\Gamma(a+1)} \\[6pt]
&\sim \frac{\sqrt{2 \pi a}}{\sqrt{2 \pi a} + 1} \cdot \Bigg[ \frac{1}{2} + \frac{1}{2} \cdot \text{erf} \Big( \sqrt{\frac{3}{2}} \Big) + \sqrt{\frac{2}{9a \pi}} \cdot \frac{5}{2} \cdot \exp \Big( \frac{3}{2} \Big) \Bigg]. \\[6pt]
\end{aligned} \end{equation}$$
This gives us the limit:
$$\lim_{n \rightarrow \infty} H(n) = \frac{1}{2} + \frac{1}{2} \cdot \text{erf} \Big( \sqrt{\frac{3}{2}} \Big) = 0.9583677.$$
This gives us the exact limit of the probability of interest, which is larger than one-half. | Limiting Sum of i.i.d. Gamma variates | As an alternative to whuber's excellent answer, I will try to derive the exact limit of the probability in question. One of the properties of the gamma distribution is that sums of independent gamma | Limiting Sum of i.i.d. Gamma variates
As an alternative to whuber's excellent answer, I will try to derive the exact limit of the probability in question. One of the properties of the gamma distribution is that sums of independent gamma random variables with the same rate/scale parameter are also gamma random variables with shape equal to the sum of the shapes of those variables. (That can be proved using the generating functions of the distribution.) In the present case we have $X_1,...X_n \sim \text{IID Gamma}(3,1)$, so we obtain the sum:
$$S_n \equiv X_1 + \cdots + X_n \sim \text{Gamma}(3n, 1).$$
We can therefore write the exact probability of interest using the CDF of the gamma distribution. Letting $a = 3n$ denote the shape parameter and $x = 3(n-\sqrt{n})$ denote the argument of interest, we have:
$$\begin{equation} \begin{aligned}
H(n)
&\equiv \mathbb{P}(S_n \geq 3(n-\sqrt{n})) \\[12pt]
&= \frac{\Gamma(a, x)}{\Gamma(a)} \\[6pt]
&= \frac{a \Gamma(a)}{a \Gamma(a) + x^a e^{-x}} \cdot \frac{\Gamma(a+1, x)}{\Gamma(a+1)}. \\[6pt]
\end{aligned} \end{equation}$$
To find the limit of this probability, we first note that we can write the second parameter in terms of the first as $x = a + \sqrt{2a} \cdot y$ where $y = -\sqrt{3/2}$. Using a result shown in Temme (1975) (Eqn 1.4, p. 1109) we have the asymptotic equivalence:
$$\begin{aligned}
\frac{\Gamma(a+1, x)}{\Gamma(a+1)}
&\sim \frac{1}{2} + \frac{1}{2} \cdot \text{erf}(-y) + \sqrt{\frac{2}{9a \pi}} (1+y^2) \exp( - y^2).
\end{aligned}$$
Using Stirling's approximation, and the limiting definition of the exponential number, it can also be shown that:
$$\begin{aligned}
\frac{a \Gamma(a)}{a \Gamma(a) + x^a e^{-x}}
&\sim \frac{\sqrt{2 \pi} \cdot a \cdot (a-1)^{a-1/2}}{\sqrt{2 \pi} \cdot a \cdot (a-1)^{a-1/2} + x^a \cdot e^{a-x-1}} \\[6pt]
&= \frac{\sqrt{2 \pi} \cdot a \cdot (1-\tfrac{1}{a})^{a-1/2}}{\sqrt{2 \pi} \cdot a \cdot (1-\tfrac{1}{a})^{a-1/2} + \sqrt{x} \cdot (\tfrac{x}{a})^{a-1/2} \cdot e^{a-x-1}} \\[6pt]
&= \frac{\sqrt{2 \pi} \cdot a \cdot e^{-1}}{\sqrt{2 \pi} \cdot a \cdot e^{-1} + \sqrt{x} \cdot e^{x-a} \cdot e^{a-x-1}} \\[6pt]
&= \frac{\sqrt{2 \pi} \cdot a}{\sqrt{2 \pi} \cdot a + \sqrt{x}} \\[6pt]
&\sim \frac{\sqrt{2 \pi a}}{\sqrt{2 \pi a} + 1}. \\[6pt]
\end{aligned}$$
Substituting the relevant values, we therefore obtain:
$$\begin{equation} \begin{aligned}
H(n)
&= \frac{a \Gamma(a)}{a \Gamma(a) + x^a e^{-x}} \cdot \frac{\Gamma(a+1, x)}{\Gamma(a+1)} \\[6pt]
&\sim \frac{\sqrt{2 \pi a}}{\sqrt{2 \pi a} + 1} \cdot \Bigg[ \frac{1}{2} + \frac{1}{2} \cdot \text{erf} \Big( \sqrt{\frac{3}{2}} \Big) + \sqrt{\frac{2}{9a \pi}} \cdot \frac{5}{2} \cdot \exp \Big( \frac{3}{2} \Big) \Bigg]. \\[6pt]
\end{aligned} \end{equation}$$
This gives us the limit:
$$\lim_{n \rightarrow \infty} H(n) = \frac{1}{2} + \frac{1}{2} \cdot \text{erf} \Big( \sqrt{\frac{3}{2}} \Big) = 0.9583677.$$
This gives us the exact limit of the probability of interest, which is larger than one-half. | Limiting Sum of i.i.d. Gamma variates
As an alternative to whuber's excellent answer, I will try to derive the exact limit of the probability in question. One of the properties of the gamma distribution is that sums of independent gamma |
24,234 | Distribution and Variance of Count of Triangles in Random Graph | Let $Y_{ijk}=1$ iff $\{i, j, k\}$ form a triangle. Then $X=\sum_{i, j, k}Y_{ijk}$ and each $Y_{ijk}\sim Bernoulli(p^3)$. This is what you have used to calculate the expected value.
For the variance, the issue is that the $Y_{ijk}$ are not independent. Indeed, write $$X^2=\sum_{i, j, k}\sum_{i', j', k'}Y_{ijk}Y_{i'j'k'}.$$
We need to compute $E[Y_{ijk}Y_{i'j'k'}]$, which is the probability that both triangles are present. There are several cases:
If $\{i,j,k\}=\{i',j',k'\}$ (same 3 vertices) then $E[Y_{ijk}Y_{i'j'k'}]=p^3$. There will be $\binom{n}{3}$ such terms in the double sum.
If the sets $\{i,j,k\}$ and $\{i',j',k'\}$ have exactly 2 elements in common, then we need 5 edges present to get the two triangles, so that $E[Y_{ijk}Y_{i'j'k'}]=p^5$. there will be $12 \binom{n}{4}$ such terms in the sum.
If the sets $\{i,j,k\}$ and $\{i',j',k'\}$ have 1 element in common, then we need 6 edges present, so that $E[Y_{ijk}Y_{i'j'k'}]=p^6$. There will be $30 \binom{n}{5}$ such terms in the sum.
If the sets $\{i,j,k\}$ and $\{i',j',k'\}$ have 0 element in common, then we need 6 edges present, so that $E[Y_{ijk}Y_{i'j'k'}]=p^6$. There will be $20 \binom{n}{6}$ such terms in the sum.
To verify that we have covered all cases, note that the sum adds up to $\binom{n}{3}^{2}$.
$$\binom{n}{3} + 12 \binom{n}{4} + 30 \binom{n}{5} + 20 \binom{n}{6} = \binom{n}{3}^{2}$$
Remembering to subtract the square of the expected mean, putting this all together gives:
$$E[X^2] - E[X]^2 = \binom{n}{3} p^3 + 12 \binom{n}{4} p^5 + 30 \binom{n}{5} p^6 + 20 \binom{n}{6} p^6 - \binom{n}{3}^2 p^6$$
Using the same numerical values as your example, the following R code calculates the standard deviation, which is reasonably close to the value of 262 from your simulation.
n=50
p=0.6
sqrt(choose(n, 3)*p^3+choose(n, 2)*(n-2)*(n-3)*p^5+(choose(n, 3)*choose(n-3, 3)+n*choose(n-1, 2)*choose(n-3, 2))*p^6-4233.6^2)
298.7945
The following Mathematica code also calculates the standard deviation, which gives the same result.
mySTD[n_,p_]:=Sqrt[Binomial[n,3]p^3+12Binomial[n,4]p^5+30 Binomial[n,5]p^6+20Binomial[n,6]p^6-(Binomial[n,3]p^3)^2]
mySTD[50,0.6] // gives 298.795 | Distribution and Variance of Count of Triangles in Random Graph | Let $Y_{ijk}=1$ iff $\{i, j, k\}$ form a triangle. Then $X=\sum_{i, j, k}Y_{ijk}$ and each $Y_{ijk}\sim Bernoulli(p^3)$. This is what you have used to calculate the expected value.
For the variance, t | Distribution and Variance of Count of Triangles in Random Graph
Let $Y_{ijk}=1$ iff $\{i, j, k\}$ form a triangle. Then $X=\sum_{i, j, k}Y_{ijk}$ and each $Y_{ijk}\sim Bernoulli(p^3)$. This is what you have used to calculate the expected value.
For the variance, the issue is that the $Y_{ijk}$ are not independent. Indeed, write $$X^2=\sum_{i, j, k}\sum_{i', j', k'}Y_{ijk}Y_{i'j'k'}.$$
We need to compute $E[Y_{ijk}Y_{i'j'k'}]$, which is the probability that both triangles are present. There are several cases:
If $\{i,j,k\}=\{i',j',k'\}$ (same 3 vertices) then $E[Y_{ijk}Y_{i'j'k'}]=p^3$. There will be $\binom{n}{3}$ such terms in the double sum.
If the sets $\{i,j,k\}$ and $\{i',j',k'\}$ have exactly 2 elements in common, then we need 5 edges present to get the two triangles, so that $E[Y_{ijk}Y_{i'j'k'}]=p^5$. there will be $12 \binom{n}{4}$ such terms in the sum.
If the sets $\{i,j,k\}$ and $\{i',j',k'\}$ have 1 element in common, then we need 6 edges present, so that $E[Y_{ijk}Y_{i'j'k'}]=p^6$. There will be $30 \binom{n}{5}$ such terms in the sum.
If the sets $\{i,j,k\}$ and $\{i',j',k'\}$ have 0 element in common, then we need 6 edges present, so that $E[Y_{ijk}Y_{i'j'k'}]=p^6$. There will be $20 \binom{n}{6}$ such terms in the sum.
To verify that we have covered all cases, note that the sum adds up to $\binom{n}{3}^{2}$.
$$\binom{n}{3} + 12 \binom{n}{4} + 30 \binom{n}{5} + 20 \binom{n}{6} = \binom{n}{3}^{2}$$
Remembering to subtract the square of the expected mean, putting this all together gives:
$$E[X^2] - E[X]^2 = \binom{n}{3} p^3 + 12 \binom{n}{4} p^5 + 30 \binom{n}{5} p^6 + 20 \binom{n}{6} p^6 - \binom{n}{3}^2 p^6$$
Using the same numerical values as your example, the following R code calculates the standard deviation, which is reasonably close to the value of 262 from your simulation.
n=50
p=0.6
sqrt(choose(n, 3)*p^3+choose(n, 2)*(n-2)*(n-3)*p^5+(choose(n, 3)*choose(n-3, 3)+n*choose(n-1, 2)*choose(n-3, 2))*p^6-4233.6^2)
298.7945
The following Mathematica code also calculates the standard deviation, which gives the same result.
mySTD[n_,p_]:=Sqrt[Binomial[n,3]p^3+12Binomial[n,4]p^5+30 Binomial[n,5]p^6+20Binomial[n,6]p^6-(Binomial[n,3]p^3)^2]
mySTD[50,0.6] // gives 298.795 | Distribution and Variance of Count of Triangles in Random Graph
Let $Y_{ijk}=1$ iff $\{i, j, k\}$ form a triangle. Then $X=\sum_{i, j, k}Y_{ijk}$ and each $Y_{ijk}\sim Bernoulli(p^3)$. This is what you have used to calculate the expected value.
For the variance, t |
24,235 | Distribution and Variance of Count of Triangles in Random Graph | I provide a slightly different approach of deriving $\mathrm{X}^{2}$.
With the same case distinction as Robin Ryder did:
If $\{i, j, k\} = \{i', j', k'\}$ i.e. the 3 vertices are the same, thus we must pick 3 vertices out of n possible $\Rightarrow \binom{n}{3}$. We must have 3 edges present $\Rightarrow \mathrm{p}^{3}$. Combined: $\binom{n}{3}\mathrm{p}^{3}$
If $\{i, j, k\}$ and $\{i', j', k'\}$ have two vertices in common, that means $\exists v \in \{i, j, k\}$ for which $v \notin \{i', j', k'\}$ and vice versa (each triangle has one vertex that is not part of the other triangle). W.l.o.g. imagine $v = k$ and $v' = k'$ are the mentioned disjunct vertices and $i$ = $i'$, $j$ = $j'$. To achieve $i$ = $i'$, $j$ = $j'$, we must pick the same two vertices out of n possible $\Rightarrow \binom{n}{2}$. For $k \neq k'$ we must pick two more out of the vertices that are left. First one: $(n-2)$ and second one: $(n-3)$. Because the edge $\{i, j\}$ and $\{i', j'\}$ is the same, we must have 5 edges present $\Rightarrow \mathrm{p}^{5}$. Combined: $\binom{n}{2}(n-2)(n-3)\mathrm{p}^{5}$
If $\{i, j, k\}$ and $\{i', j', k'\}$ have just one vertex in common, then 4 are disjunct. Imagine, w.l.o.g., that $i$ = $i'$. That means, out of n possible vertices, we must pick 1 $\Rightarrow n$. For the triangle $\{i, j, k\}$ we pick 2 vertices out of the remaining $(n-1) \Rightarrow \binom{n-1}{2}$. For the triangle $\{i', j', k'\}$ we pick 2 out of the remaining $(n-3) \Rightarrow \binom{n-3}{2}$, this is due to the assumption that $j'\notin\{i, j, k\}$ and $k'\notin\{i, j, k\}$. Because we only have one vertex in common, we must have 6 edges present $\Rightarrow \mathrm{p}^{6}$. Combined: $n\binom{n-1}{2}\binom{n-3}{2}\mathrm{p}^{6}$
For the last case: If $\{i, j, k\}$ and $\{i', j', k'\}$ have no vertex in common, then the 2 triangles are disjunct. We pick the first triangle, 3 vertices out of n possible $\Rightarrow \binom{n}{3}$. And the second triangle, 3 vertices out of $(n-3)$ remaining $\Rightarrow \binom{n-3}{3}$. The triangles are disjunct, i.e. they share no edges and vertices, thus 6 edges must be present $\Rightarrow \mathrm{p}^{6}$. Combined: $\binom{n}{3}\binom{n-3}{3}\mathrm{p}^{6}$
As in Robin Ryder's approach, we can also verify that:
$\binom{n}{3} + \binom{n}{2}(n-2)(n-3) + n\binom{n-1}{2}\binom{n-3}{2} + \binom{n}{3}\binom{n-3}{3} = \mathrm{\binom{n}{3}}^{2}$ holds.
This leads to:
$Var[X] = E[\mathrm{X}^{2}] - \mathrm{E[X]}^{2} = \binom{n}{3}\mathrm{p}^{3} + \binom{n}{2}(n-2)(n-3)\mathrm{p}^{5} + n\binom{n-1}{2}\binom{n-3}{2}\mathrm{p}^{6} + \binom{n}{3}\binom{n-3}{3}\mathrm{p}^{6} - \mathrm{\binom{n}{3}}^{2}\mathrm{p}^{6}.$ | Distribution and Variance of Count of Triangles in Random Graph | I provide a slightly different approach of deriving $\mathrm{X}^{2}$.
With the same case distinction as Robin Ryder did:
If $\{i, j, k\} = \{i', j', k'\}$ i.e. the 3 vertices are the same, thus we mu | Distribution and Variance of Count of Triangles in Random Graph
I provide a slightly different approach of deriving $\mathrm{X}^{2}$.
With the same case distinction as Robin Ryder did:
If $\{i, j, k\} = \{i', j', k'\}$ i.e. the 3 vertices are the same, thus we must pick 3 vertices out of n possible $\Rightarrow \binom{n}{3}$. We must have 3 edges present $\Rightarrow \mathrm{p}^{3}$. Combined: $\binom{n}{3}\mathrm{p}^{3}$
If $\{i, j, k\}$ and $\{i', j', k'\}$ have two vertices in common, that means $\exists v \in \{i, j, k\}$ for which $v \notin \{i', j', k'\}$ and vice versa (each triangle has one vertex that is not part of the other triangle). W.l.o.g. imagine $v = k$ and $v' = k'$ are the mentioned disjunct vertices and $i$ = $i'$, $j$ = $j'$. To achieve $i$ = $i'$, $j$ = $j'$, we must pick the same two vertices out of n possible $\Rightarrow \binom{n}{2}$. For $k \neq k'$ we must pick two more out of the vertices that are left. First one: $(n-2)$ and second one: $(n-3)$. Because the edge $\{i, j\}$ and $\{i', j'\}$ is the same, we must have 5 edges present $\Rightarrow \mathrm{p}^{5}$. Combined: $\binom{n}{2}(n-2)(n-3)\mathrm{p}^{5}$
If $\{i, j, k\}$ and $\{i', j', k'\}$ have just one vertex in common, then 4 are disjunct. Imagine, w.l.o.g., that $i$ = $i'$. That means, out of n possible vertices, we must pick 1 $\Rightarrow n$. For the triangle $\{i, j, k\}$ we pick 2 vertices out of the remaining $(n-1) \Rightarrow \binom{n-1}{2}$. For the triangle $\{i', j', k'\}$ we pick 2 out of the remaining $(n-3) \Rightarrow \binom{n-3}{2}$, this is due to the assumption that $j'\notin\{i, j, k\}$ and $k'\notin\{i, j, k\}$. Because we only have one vertex in common, we must have 6 edges present $\Rightarrow \mathrm{p}^{6}$. Combined: $n\binom{n-1}{2}\binom{n-3}{2}\mathrm{p}^{6}$
For the last case: If $\{i, j, k\}$ and $\{i', j', k'\}$ have no vertex in common, then the 2 triangles are disjunct. We pick the first triangle, 3 vertices out of n possible $\Rightarrow \binom{n}{3}$. And the second triangle, 3 vertices out of $(n-3)$ remaining $\Rightarrow \binom{n-3}{3}$. The triangles are disjunct, i.e. they share no edges and vertices, thus 6 edges must be present $\Rightarrow \mathrm{p}^{6}$. Combined: $\binom{n}{3}\binom{n-3}{3}\mathrm{p}^{6}$
As in Robin Ryder's approach, we can also verify that:
$\binom{n}{3} + \binom{n}{2}(n-2)(n-3) + n\binom{n-1}{2}\binom{n-3}{2} + \binom{n}{3}\binom{n-3}{3} = \mathrm{\binom{n}{3}}^{2}$ holds.
This leads to:
$Var[X] = E[\mathrm{X}^{2}] - \mathrm{E[X]}^{2} = \binom{n}{3}\mathrm{p}^{3} + \binom{n}{2}(n-2)(n-3)\mathrm{p}^{5} + n\binom{n-1}{2}\binom{n-3}{2}\mathrm{p}^{6} + \binom{n}{3}\binom{n-3}{3}\mathrm{p}^{6} - \mathrm{\binom{n}{3}}^{2}\mathrm{p}^{6}.$ | Distribution and Variance of Count of Triangles in Random Graph
I provide a slightly different approach of deriving $\mathrm{X}^{2}$.
With the same case distinction as Robin Ryder did:
If $\{i, j, k\} = \{i', j', k'\}$ i.e. the 3 vertices are the same, thus we mu |
24,236 | Variance term in bias-variance decomposition of linear regression | There's always a lurking subtlety in treatments of bias and variance, and it's important to pay careful attention to it when studying. If you re-read the first few words of ESL in a section from that chapter, the authors to pay it some respect.
Discussions of error rate estimation can be confusing, because we have
to make clear which quantities are fixed and which are random
The subtlety is what is fixed, and what is random.
In traditional treatments of linear regression, the data $X$ is treated as fixed and known. If you follow the arguments in ESL, you will find that the authors are also making this assumption. Under these assumptions, your example does not come into play, as the only remaining source of randomness in from the conditional distribution of $y$ given $X$. If it helps, you may want to replace the notation $Err(x_0)$ in your mind with $Err(x_0 \mid X)$.
That is not to say that your concern is invalid, it is certainly true that the selection of training data does indeed introduce randomness in our model algorithm, and a diligent practitioner will attempt to quantify the effect of this randomness on their outcomes. In fact, you can see quite clearly that the common practices of bootstrapping and cross-validation explicitly incorporate these sources of randomness into their inferences.
To derive an explicit mathematical expression for the bias and variance of a linear model in the context of a random training data set, one would need to make some assumptions about the structure of the randomness in the $X$ data. This would involve some suppositions on the distribution of $X$. This can be done, but has not become part of the mainstream expositions of these ideas. | Variance term in bias-variance decomposition of linear regression | There's always a lurking subtlety in treatments of bias and variance, and it's important to pay careful attention to it when studying. If you re-read the first few words of ESL in a section from that | Variance term in bias-variance decomposition of linear regression
There's always a lurking subtlety in treatments of bias and variance, and it's important to pay careful attention to it when studying. If you re-read the first few words of ESL in a section from that chapter, the authors to pay it some respect.
Discussions of error rate estimation can be confusing, because we have
to make clear which quantities are fixed and which are random
The subtlety is what is fixed, and what is random.
In traditional treatments of linear regression, the data $X$ is treated as fixed and known. If you follow the arguments in ESL, you will find that the authors are also making this assumption. Under these assumptions, your example does not come into play, as the only remaining source of randomness in from the conditional distribution of $y$ given $X$. If it helps, you may want to replace the notation $Err(x_0)$ in your mind with $Err(x_0 \mid X)$.
That is not to say that your concern is invalid, it is certainly true that the selection of training data does indeed introduce randomness in our model algorithm, and a diligent practitioner will attempt to quantify the effect of this randomness on their outcomes. In fact, you can see quite clearly that the common practices of bootstrapping and cross-validation explicitly incorporate these sources of randomness into their inferences.
To derive an explicit mathematical expression for the bias and variance of a linear model in the context of a random training data set, one would need to make some assumptions about the structure of the randomness in the $X$ data. This would involve some suppositions on the distribution of $X$. This can be done, but has not become part of the mainstream expositions of these ideas. | Variance term in bias-variance decomposition of linear regression
There's always a lurking subtlety in treatments of bias and variance, and it's important to pay careful attention to it when studying. If you re-read the first few words of ESL in a section from that |
24,237 | Dynamic graphs versus static graphs in deep learning libraries | What is the difference between dynamic graphs and static graphs in
deep learning libraries?
For the static graphs, you should first draw the graph completely and then inject data to run(define-and-run), while using dynamic graphs the graph structure is defined on-the-fly via the actual forward computation. This is a far more natural style of programming(define-by-run).
Which one is faster? and when to use each one of them?
When you can distribute the computations over multiple machines it is better to harness static graphs. Being able to do this with a dynamic computation graph would be far more problematic.
Some other comparisons:
Having a static graph enables a lot of convenient operations: storing a fixed graph data structure, shipping models that are independent of code, performing graph transformations, but it is a little bit more complex than dynamic graphs(for example when implementing something like recursive neural networks). When you're working with new architectures, you want the most flexibility possible, and these frameworks allow for that.
This answer is gathered from the reference at the bottom, and I hope my conclusions are correct and can help.
Reference: https://news.ycombinator.com/item?id=13428098 | Dynamic graphs versus static graphs in deep learning libraries | What is the difference between dynamic graphs and static graphs in
deep learning libraries?
For the static graphs, you should first draw the graph completely and then inject data to run(define-and- | Dynamic graphs versus static graphs in deep learning libraries
What is the difference between dynamic graphs and static graphs in
deep learning libraries?
For the static graphs, you should first draw the graph completely and then inject data to run(define-and-run), while using dynamic graphs the graph structure is defined on-the-fly via the actual forward computation. This is a far more natural style of programming(define-by-run).
Which one is faster? and when to use each one of them?
When you can distribute the computations over multiple machines it is better to harness static graphs. Being able to do this with a dynamic computation graph would be far more problematic.
Some other comparisons:
Having a static graph enables a lot of convenient operations: storing a fixed graph data structure, shipping models that are independent of code, performing graph transformations, but it is a little bit more complex than dynamic graphs(for example when implementing something like recursive neural networks). When you're working with new architectures, you want the most flexibility possible, and these frameworks allow for that.
This answer is gathered from the reference at the bottom, and I hope my conclusions are correct and can help.
Reference: https://news.ycombinator.com/item?id=13428098 | Dynamic graphs versus static graphs in deep learning libraries
What is the difference between dynamic graphs and static graphs in
deep learning libraries?
For the static graphs, you should first draw the graph completely and then inject data to run(define-and- |
24,238 | How to use a Kalman filter? | Here is an example of a 2-dimensional Kalman filter that may be useful to you. It is in Python.
The state vector is consists of four variables: position in the x0-direction, position in the x1-direction, velocity in the x0-direction, and velocity in the x1-direction. See the commented line "x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)".
The state-transition matrix (F), which facilitates prediction of the system/objects next state, combines the present state values of position and velocity to predict position (i.e. x0 + x0_dot and x1 + x1_dot) and the present state values of velocity for velocity (i.e. x0_dot and x1_dot).
The measurement matrix (H) appears to consider only position in both the x0 and x1 positions.
The motion noise matrix (Q) is initialized to a 4-by-4 identity matrix, while the measurement noise is set to 0.0001.
Hopefully this example will allow you to get your code working. | How to use a Kalman filter? | Here is an example of a 2-dimensional Kalman filter that may be useful to you. It is in Python.
The state vector is consists of four variables: position in the x0-direction, position in the x1-direc | How to use a Kalman filter?
Here is an example of a 2-dimensional Kalman filter that may be useful to you. It is in Python.
The state vector is consists of four variables: position in the x0-direction, position in the x1-direction, velocity in the x0-direction, and velocity in the x1-direction. See the commented line "x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot)".
The state-transition matrix (F), which facilitates prediction of the system/objects next state, combines the present state values of position and velocity to predict position (i.e. x0 + x0_dot and x1 + x1_dot) and the present state values of velocity for velocity (i.e. x0_dot and x1_dot).
The measurement matrix (H) appears to consider only position in both the x0 and x1 positions.
The motion noise matrix (Q) is initialized to a 4-by-4 identity matrix, while the measurement noise is set to 0.0001.
Hopefully this example will allow you to get your code working. | How to use a Kalman filter?
Here is an example of a 2-dimensional Kalman filter that may be useful to you. It is in Python.
The state vector is consists of four variables: position in the x0-direction, position in the x1-direc |
24,239 | How to use a Kalman filter? | Kalman filter is a model based predictive filter - as such a correct implementation of the filter will have little or no time delay on the output when fed with regular measurements at the input. I find it always to be more straightforward to implement kalman filter directly as opposed to using libraries because the model is not always static.
The way the filter works is it predicts current value based on previous state using mathematical description of the process and then corrects that estimate based on current sensor measurement. It is thus also capable of estimating hidden state (which is not measured) and other parameters that are used in the model so long as their relationships to measured state are defined in the model.
I would suggest you study the kalman filter in more detail because without understanding the algorithm it is very easy to make mistakes when trying to use the filter. | How to use a Kalman filter? | Kalman filter is a model based predictive filter - as such a correct implementation of the filter will have little or no time delay on the output when fed with regular measurements at the input. I fin | How to use a Kalman filter?
Kalman filter is a model based predictive filter - as such a correct implementation of the filter will have little or no time delay on the output when fed with regular measurements at the input. I find it always to be more straightforward to implement kalman filter directly as opposed to using libraries because the model is not always static.
The way the filter works is it predicts current value based on previous state using mathematical description of the process and then corrects that estimate based on current sensor measurement. It is thus also capable of estimating hidden state (which is not measured) and other parameters that are used in the model so long as their relationships to measured state are defined in the model.
I would suggest you study the kalman filter in more detail because without understanding the algorithm it is very easy to make mistakes when trying to use the filter. | How to use a Kalman filter?
Kalman filter is a model based predictive filter - as such a correct implementation of the filter will have little or no time delay on the output when fed with regular measurements at the input. I fin |
24,240 | How to use a Kalman filter? | measurements in the example are integers.
yes, they are acting as sensors (2D) for 1 (Linear-Gaussian model) process , describing random_walk... inputing your previous state's distribution to the state_next_output calculations according to probabilities of current state & current observable measurements... can consider it to represent some form of State-Space model or code, I suppose
Finally, where can I find my output? Should it be filtered_state_means or
smoothed_state_means
read your link: "Functionally, Kalman Smoother should always be preferred. Unlike the Kalman Filter, the Smoother is able to incorporate “future” measurements as well as past ones at the same computational cost"... but if you need just filter - use filter
provide some transition_matrices and observation_matrices. What values
should I put there? What do these matrices mean?
see "Mathematical Formulation" at your link
+
transition_matrix's good explanation at unofficed.com (incl. the whole issues series in the left-hand side of the link) - it is just the paths of state_change described in table (from your graph representation), "shows the probability of the occurrence", found like e.g. here or more OOP-implementation
observation_matrix is your observations -
observation_matrix = np.array(
[observed_x,
observed_y]
) | How to use a Kalman filter? | measurements in the example are integers.
yes, they are acting as sensors (2D) for 1 (Linear-Gaussian model) process , describing random_walk... inputing your previous state's distribution to the sta | How to use a Kalman filter?
measurements in the example are integers.
yes, they are acting as sensors (2D) for 1 (Linear-Gaussian model) process , describing random_walk... inputing your previous state's distribution to the state_next_output calculations according to probabilities of current state & current observable measurements... can consider it to represent some form of State-Space model or code, I suppose
Finally, where can I find my output? Should it be filtered_state_means or
smoothed_state_means
read your link: "Functionally, Kalman Smoother should always be preferred. Unlike the Kalman Filter, the Smoother is able to incorporate “future” measurements as well as past ones at the same computational cost"... but if you need just filter - use filter
provide some transition_matrices and observation_matrices. What values
should I put there? What do these matrices mean?
see "Mathematical Formulation" at your link
+
transition_matrix's good explanation at unofficed.com (incl. the whole issues series in the left-hand side of the link) - it is just the paths of state_change described in table (from your graph representation), "shows the probability of the occurrence", found like e.g. here or more OOP-implementation
observation_matrix is your observations -
observation_matrix = np.array(
[observed_x,
observed_y]
) | How to use a Kalman filter?
measurements in the example are integers.
yes, they are acting as sensors (2D) for 1 (Linear-Gaussian model) process , describing random_walk... inputing your previous state's distribution to the sta |
24,241 | "Averaging" variances | Expanding the comments that you got, answer for the question in your title is already given in How to 'sum' a standard deviation? thread, and reads as follows: to get average standard deviation, first take average of variances and then take square root of it.
At face value this approach is valid, but it ignores the hierarchical nature of your data. Similar example is discussed in chapter 5 of Bayesian Data Analysis by Andrew Gelman et al (see also here), who show that it is actually wiser to use hierarchical models that rely on pooled estimates. In your case you have $n \times k$ observations, for $n$ subjects in $k$ treatments and I guess it can be assumed that there is some kind of similarity between results obtained by each subject and between each treatment. This already suggests a hierarchical model with crossed upper-level effects for treatments and for subjects. By using such model you would account for both sources of variation.
Notice that modern formulations of ICC in fact define it in terms of mixed-effects models of the kind as described above, so employing such model solves multiple problems for you and it is often the recommended approach to meta-analysis (but notice that ICC can be misleading).
Regarding your edit, if your model is
$$ y_{ij} = a + \alpha_i + \beta_j + \epsilon_{ij} $$
then $\alpha_i \sim \mathcal{N}(\mu_\alpha, \sigma^2_\alpha)$, $\beta_j \sim \mathcal{N}(\mu_\beta, \sigma^2_\beta)$ and $\epsilon_{ij} \sim \mathcal{N}(0, \sigma^2_\epsilon)$, so your ICC is
$$
\mathrm{ICC}_\alpha = \frac{\sigma_\alpha^2}{\sigma_\alpha^2 + \sigma_\beta^2 + \sigma_\epsilon^2}
$$
The mean of errors does not come into the equation at any point. What comes to the equation is variance of each of the random effects $\alpha,\beta$ and global "noise" $\epsilon$. The idea is to estimate the share of variance taken by $\alpha$, i.e. how much of the total variance does it account for. This is how ICC was defined by its creator Ronald A. Fisher (1966) in Statistical Methods for Research Workers:
(...) the intraclass correlation will be merely the fraction of the total
variance due to that cause which observations in the same class have
in common.
So the numerator in the ICC formula is the variance of the effect of interest and the denominator is the total variance. Notice that mean of variances has nothing to do with total variance (sum of variances), so unless I misunderstand something, I can't see why the mean is of your interest in here. | "Averaging" variances | Expanding the comments that you got, answer for the question in your title is already given in How to 'sum' a standard deviation? thread, and reads as follows: to get average standard deviation, first | "Averaging" variances
Expanding the comments that you got, answer for the question in your title is already given in How to 'sum' a standard deviation? thread, and reads as follows: to get average standard deviation, first take average of variances and then take square root of it.
At face value this approach is valid, but it ignores the hierarchical nature of your data. Similar example is discussed in chapter 5 of Bayesian Data Analysis by Andrew Gelman et al (see also here), who show that it is actually wiser to use hierarchical models that rely on pooled estimates. In your case you have $n \times k$ observations, for $n$ subjects in $k$ treatments and I guess it can be assumed that there is some kind of similarity between results obtained by each subject and between each treatment. This already suggests a hierarchical model with crossed upper-level effects for treatments and for subjects. By using such model you would account for both sources of variation.
Notice that modern formulations of ICC in fact define it in terms of mixed-effects models of the kind as described above, so employing such model solves multiple problems for you and it is often the recommended approach to meta-analysis (but notice that ICC can be misleading).
Regarding your edit, if your model is
$$ y_{ij} = a + \alpha_i + \beta_j + \epsilon_{ij} $$
then $\alpha_i \sim \mathcal{N}(\mu_\alpha, \sigma^2_\alpha)$, $\beta_j \sim \mathcal{N}(\mu_\beta, \sigma^2_\beta)$ and $\epsilon_{ij} \sim \mathcal{N}(0, \sigma^2_\epsilon)$, so your ICC is
$$
\mathrm{ICC}_\alpha = \frac{\sigma_\alpha^2}{\sigma_\alpha^2 + \sigma_\beta^2 + \sigma_\epsilon^2}
$$
The mean of errors does not come into the equation at any point. What comes to the equation is variance of each of the random effects $\alpha,\beta$ and global "noise" $\epsilon$. The idea is to estimate the share of variance taken by $\alpha$, i.e. how much of the total variance does it account for. This is how ICC was defined by its creator Ronald A. Fisher (1966) in Statistical Methods for Research Workers:
(...) the intraclass correlation will be merely the fraction of the total
variance due to that cause which observations in the same class have
in common.
So the numerator in the ICC formula is the variance of the effect of interest and the denominator is the total variance. Notice that mean of variances has nothing to do with total variance (sum of variances), so unless I misunderstand something, I can't see why the mean is of your interest in here. | "Averaging" variances
Expanding the comments that you got, answer for the question in your title is already given in How to 'sum' a standard deviation? thread, and reads as follows: to get average standard deviation, first |
24,242 | Techniques to detect overfitting | I believe that when asking about over fitting the interviewer was looking for the "text book answer" while you went few steps after that.
A symptom of over fitting is that the classifier performance on the train set is better that the one on the test set.
I refer to this answer as the "text book answer" since it is the common answer and an reasonable approximation.
Note that this answer has many open ends. For example, how much difference is overfitting?. Also, a difference in performance between the data sets is not necessarily due to overfitting. On the other hand, overfitting, won't necessarily result in a significant difference in the performance on the two datasets.
Cross validation is a technique to evaluate the performance of a learner (e.g., decision tree) on data it didn't see before. However, overfitting refers to a specific model (e.g., if "f1" then and not "f2" predict True). It will show you the tendency of the learner to overfit on this data but won't answer whether your specific model overfitted.
In order to overfitted the model will need complexity and that is were regularization helps. It bounds (or trades off) the complexity of the model. Note that another source of overfitting is the hypothesis set size (can be considered to be the number of possible models). Deciding in advance to use a restricted hypothesis set is another way to avoid overfitting. | Techniques to detect overfitting | I believe that when asking about over fitting the interviewer was looking for the "text book answer" while you went few steps after that.
A symptom of over fitting is that the classifier performance o | Techniques to detect overfitting
I believe that when asking about over fitting the interviewer was looking for the "text book answer" while you went few steps after that.
A symptom of over fitting is that the classifier performance on the train set is better that the one on the test set.
I refer to this answer as the "text book answer" since it is the common answer and an reasonable approximation.
Note that this answer has many open ends. For example, how much difference is overfitting?. Also, a difference in performance between the data sets is not necessarily due to overfitting. On the other hand, overfitting, won't necessarily result in a significant difference in the performance on the two datasets.
Cross validation is a technique to evaluate the performance of a learner (e.g., decision tree) on data it didn't see before. However, overfitting refers to a specific model (e.g., if "f1" then and not "f2" predict True). It will show you the tendency of the learner to overfit on this data but won't answer whether your specific model overfitted.
In order to overfitted the model will need complexity and that is were regularization helps. It bounds (or trades off) the complexity of the model. Note that another source of overfitting is the hypothesis set size (can be considered to be the number of possible models). Deciding in advance to use a restricted hypothesis set is another way to avoid overfitting. | Techniques to detect overfitting
I believe that when asking about over fitting the interviewer was looking for the "text book answer" while you went few steps after that.
A symptom of over fitting is that the classifier performance o |
24,243 | How do you report results from a Beta Regression (R output)? | The beta regression model can have two submodels: (1) a regression model for the mean - similar to a linear regression model or a binary regression model; (2) a regression model for the precision parameter - similar to the inverse of a variance in a linear regression model or the dispersion in a GLM.
So far you have just used regressors in (1) but just a constant in (2). I would encourage you to check whether the model D_Ratio ~ BL | BL with the regressor BL in both parts leads to an improved fit.
If not, then you can probably best report the coefficients from the mean equation as you would for a binary regression model. And then you can add the precision parameter estimate (as you would in a linear regression), the pseudo-R-squared and/or log-likelihood and/or AIC/BIC.
If the regressor plays a role in both parts of the model, then probably report both sets of coefficients.
You can also use the function mtable(betareg_object,...) from the memisc package to generate such a table. Export to LaTeX is also available. Furthermore, you might consider a scatterplot of D_RATIO ~ BL with the fitted mean regression line plus possibly some quantiles (e.g., 5% and 95%). The vignette("betareg", package = "betareg") has some examples like that. | How do you report results from a Beta Regression (R output)? | The beta regression model can have two submodels: (1) a regression model for the mean - similar to a linear regression model or a binary regression model; (2) a regression model for the precision para | How do you report results from a Beta Regression (R output)?
The beta regression model can have two submodels: (1) a regression model for the mean - similar to a linear regression model or a binary regression model; (2) a regression model for the precision parameter - similar to the inverse of a variance in a linear regression model or the dispersion in a GLM.
So far you have just used regressors in (1) but just a constant in (2). I would encourage you to check whether the model D_Ratio ~ BL | BL with the regressor BL in both parts leads to an improved fit.
If not, then you can probably best report the coefficients from the mean equation as you would for a binary regression model. And then you can add the precision parameter estimate (as you would in a linear regression), the pseudo-R-squared and/or log-likelihood and/or AIC/BIC.
If the regressor plays a role in both parts of the model, then probably report both sets of coefficients.
You can also use the function mtable(betareg_object,...) from the memisc package to generate such a table. Export to LaTeX is also available. Furthermore, you might consider a scatterplot of D_RATIO ~ BL with the fitted mean regression line plus possibly some quantiles (e.g., 5% and 95%). The vignette("betareg", package = "betareg") has some examples like that. | How do you report results from a Beta Regression (R output)?
The beta regression model can have two submodels: (1) a regression model for the mean - similar to a linear regression model or a binary regression model; (2) a regression model for the precision para |
24,244 | What does log-likelihood mean in the context of generative models like GANs? | You're absolutely correct. The log likelihood of most GAN models on most datasets or true distributions is $-\infty$, and the probability density under the trained model for any actual image is almost always zero.
This is easy to see. Suppose a GAN has a 200-dimensional latent variable and is generating 200x200 grayscale images. Then the space of all images is 40,000-dimensional, and the GAN can only ever generate images on a 200-dimensional submanifold of this 40,000-dimensional space. Real images will almost always lie off this submanifold, and so have a probability density of zero under the GAN. This argument holds whenever the output space has higher dimension than the latent space, which is typically the case (e.g. Nvidia's recent progressive GANs used a 512-dimensional latent space to generate 1024x1024x3 images).
Whether this is a problem or not depends on what you want the generative model for; GANs certainly generate visually attractive samples in many cases. | What does log-likelihood mean in the context of generative models like GANs? | You're absolutely correct. The log likelihood of most GAN models on most datasets or true distributions is $-\infty$, and the probability density under the trained model for any actual image is almost | What does log-likelihood mean in the context of generative models like GANs?
You're absolutely correct. The log likelihood of most GAN models on most datasets or true distributions is $-\infty$, and the probability density under the trained model for any actual image is almost always zero.
This is easy to see. Suppose a GAN has a 200-dimensional latent variable and is generating 200x200 grayscale images. Then the space of all images is 40,000-dimensional, and the GAN can only ever generate images on a 200-dimensional submanifold of this 40,000-dimensional space. Real images will almost always lie off this submanifold, and so have a probability density of zero under the GAN. This argument holds whenever the output space has higher dimension than the latent space, which is typically the case (e.g. Nvidia's recent progressive GANs used a 512-dimensional latent space to generate 1024x1024x3 images).
Whether this is a problem or not depends on what you want the generative model for; GANs certainly generate visually attractive samples in many cases. | What does log-likelihood mean in the context of generative models like GANs?
You're absolutely correct. The log likelihood of most GAN models on most datasets or true distributions is $-\infty$, and the probability density under the trained model for any actual image is almost |
24,245 | What does log-likelihood mean in the context of generative models like GANs? | The theory of maximum likelihood is generally not tractable for generative models, as seen here. Instead, methods such as VAEs and GANs, the likelihood is approximated by a KL Divergense, on VAEs, and JS Divergense on GANs.
Such functions are a measure of how much two distribution probabilities diverges, also known as relative entropy.
Roughly, although two distribution of the same shape but different means have same entropy, you can think that while such functions adapt the shape learned by the network, the Discriminator (in case of GANs), when optimal, decide where is the mean.
For example, if a GAN is trying to learn a Gaussian distribution of mean -1 and standard deviation 2, the discriminator, which reaches its optimum state over time, is responsible for locate that mean, while the divergence function learn its shape.
Tecnically, it is possible because, according to the proof in the article, the optimal Discriminator should achieve a cost of -log(4). So the Generator indirectly approximates its actual distribution to reach this value in Discriminator's cost, ensuring the convergence to the mean and the shape. | What does log-likelihood mean in the context of generative models like GANs? | The theory of maximum likelihood is generally not tractable for generative models, as seen here. Instead, methods such as VAEs and GANs, the likelihood is approximated by a KL Divergense, on VAEs, and | What does log-likelihood mean in the context of generative models like GANs?
The theory of maximum likelihood is generally not tractable for generative models, as seen here. Instead, methods such as VAEs and GANs, the likelihood is approximated by a KL Divergense, on VAEs, and JS Divergense on GANs.
Such functions are a measure of how much two distribution probabilities diverges, also known as relative entropy.
Roughly, although two distribution of the same shape but different means have same entropy, you can think that while such functions adapt the shape learned by the network, the Discriminator (in case of GANs), when optimal, decide where is the mean.
For example, if a GAN is trying to learn a Gaussian distribution of mean -1 and standard deviation 2, the discriminator, which reaches its optimum state over time, is responsible for locate that mean, while the divergence function learn its shape.
Tecnically, it is possible because, according to the proof in the article, the optimal Discriminator should achieve a cost of -log(4). So the Generator indirectly approximates its actual distribution to reach this value in Discriminator's cost, ensuring the convergence to the mean and the shape. | What does log-likelihood mean in the context of generative models like GANs?
The theory of maximum likelihood is generally not tractable for generative models, as seen here. Instead, methods such as VAEs and GANs, the likelihood is approximated by a KL Divergense, on VAEs, and |
24,246 | Calculate random effect predictions manually for a linear mixed model | Two problems (I confess it took me like 40 minutes to spot the second one):
You must not compute $\sigma^2$ with the square of residuals, it is estimated by REML as 23.51, and there is no guarantee that the BLUPs will have the same variance.
sig <- 23.51
And this is not $\psi$ ! Which is estimated as 39.19
psi <- 39.19
The residuals are not obtained with cake$angle - predict(m, re.form=NA) but with residuals(m).
Putting it together:
> psi/sig * zt %*% residuals(m)
15 x 1 Matrix of class "dgeMatrix"
[,1]
1 14.2388572
2 13.0020985
3 4.6674200
4 1.1184601
5 0.2581062
6 -3.2908537
7 -4.6351567
8 -4.5813846
9 -4.6351567
10 -3.1833095
11 -2.1616392
12 -1.1399689
13 -0.2258429
14 -4.0974355
15 -5.3341942
which is similar to ranef(m).
I really don't get what predict computes.
PS. To answer your last remark, the point is that we use the "residuals" $\hat\epsilon$ as a way to obtain the vector $PY$ where $P = V^{-1} - V^{-1} X \left(X' V^{-1} X\right)^{-1} X' V^{-1}$. This matrix is computed during the REML algorithm. It is related to the BLUPs of random terms by
$$ \hat\epsilon = \sigma^2 PY $$
and
$$ \hat b = \psi Z^t PY. $$
Thus $ \hat b = \psi / \sigma^2 Z^t \hat\epsilon $. | Calculate random effect predictions manually for a linear mixed model | Two problems (I confess it took me like 40 minutes to spot the second one):
You must not compute $\sigma^2$ with the square of residuals, it is estimated by REML as 23.51, and there is no guarantee t | Calculate random effect predictions manually for a linear mixed model
Two problems (I confess it took me like 40 minutes to spot the second one):
You must not compute $\sigma^2$ with the square of residuals, it is estimated by REML as 23.51, and there is no guarantee that the BLUPs will have the same variance.
sig <- 23.51
And this is not $\psi$ ! Which is estimated as 39.19
psi <- 39.19
The residuals are not obtained with cake$angle - predict(m, re.form=NA) but with residuals(m).
Putting it together:
> psi/sig * zt %*% residuals(m)
15 x 1 Matrix of class "dgeMatrix"
[,1]
1 14.2388572
2 13.0020985
3 4.6674200
4 1.1184601
5 0.2581062
6 -3.2908537
7 -4.6351567
8 -4.5813846
9 -4.6351567
10 -3.1833095
11 -2.1616392
12 -1.1399689
13 -0.2258429
14 -4.0974355
15 -5.3341942
which is similar to ranef(m).
I really don't get what predict computes.
PS. To answer your last remark, the point is that we use the "residuals" $\hat\epsilon$ as a way to obtain the vector $PY$ where $P = V^{-1} - V^{-1} X \left(X' V^{-1} X\right)^{-1} X' V^{-1}$. This matrix is computed during the REML algorithm. It is related to the BLUPs of random terms by
$$ \hat\epsilon = \sigma^2 PY $$
and
$$ \hat b = \psi Z^t PY. $$
Thus $ \hat b = \psi / \sigma^2 Z^t \hat\epsilon $. | Calculate random effect predictions manually for a linear mixed model
Two problems (I confess it took me like 40 minutes to spot the second one):
You must not compute $\sigma^2$ with the square of residuals, it is estimated by REML as 23.51, and there is no guarantee t |
24,247 | Is the sum of two variables independent of a third variable, if they are so on their own? | EDIT: As pointed out by other users, this answer is not correct because it makes the assumption that $Y$ is independent of $(X_1,X_2)$
Note that $X_1 + X_2$ is a function of $Z = (X_1,X_2)$ because if you take
$$f(x,y) = x+y$$
you get $X_1 + X_2 = f(Z)$.
It is a well known theorem of probability that if $R_1$ and $R_2$ are independent random variables and $f_1$ and $f_2$ are measurable functions then $f_1(R_1)$ is independent of $f_2(R_2)$ (Theorem 10.4 of "Probability: A Graduate Course" 2nd ed. by Allan Gut).
Since $f$ is measurable and Y is independent of $Z$ we know that $Y$ is also independent of $f(Z) = X_1 + X_2$. Note that we took $f_1$ as the identity function and $f_2 = f$. | Is the sum of two variables independent of a third variable, if they are so on their own? | EDIT: As pointed out by other users, this answer is not correct because it makes the assumption that $Y$ is independent of $(X_1,X_2)$
Note that $X_1 + X_2$ is a function of $Z = (X_1,X_2)$ because if | Is the sum of two variables independent of a third variable, if they are so on their own?
EDIT: As pointed out by other users, this answer is not correct because it makes the assumption that $Y$ is independent of $(X_1,X_2)$
Note that $X_1 + X_2$ is a function of $Z = (X_1,X_2)$ because if you take
$$f(x,y) = x+y$$
you get $X_1 + X_2 = f(Z)$.
It is a well known theorem of probability that if $R_1$ and $R_2$ are independent random variables and $f_1$ and $f_2$ are measurable functions then $f_1(R_1)$ is independent of $f_2(R_2)$ (Theorem 10.4 of "Probability: A Graduate Course" 2nd ed. by Allan Gut).
Since $f$ is measurable and Y is independent of $Z$ we know that $Y$ is also independent of $f(Z) = X_1 + X_2$. Note that we took $f_1$ as the identity function and $f_2 = f$. | Is the sum of two variables independent of a third variable, if they are so on their own?
EDIT: As pointed out by other users, this answer is not correct because it makes the assumption that $Y$ is independent of $(X_1,X_2)$
Note that $X_1 + X_2$ is a function of $Z = (X_1,X_2)$ because if |
24,248 | Is the sum of two variables independent of a third variable, if they are so on their own? | (To complete this thread, I am elevating a comment by user233740 into an answer.)
The statement is not true.
The possibility that $X_1+X_2$ might not be independent of $Y$ is strongly reminiscent of the familiar textbook problem concerning trivariate random variables $(X_1,X_2,Y)$ that are pairwise independent but not independent. With that thought in mind, let's consider the simplest such example, that of selecting one of the rows of this matrix uniformly at random:
$$\pmatrix{0&0&0\\1&1&0\\1&0&1\\0&1&1}.$$
You can see that any two columns determine independent Bernoulli$(1/2)$ variables, but the three are not independent because the third can be determined from the other two.
Let us then pick two of these columns, denoting them $X_1$ and $X_2,$ and let $Y$ be the third. Observe that when $Y=0,$ $X_1+X_2$ is either $0$ or $2$ (with equal probability), but when $Y=1,$ $X_1+X_2=1.$ Thus the conditional probability function $$\Pr(X_1+X_2\mid Y)$$ is not constant, demonstrating $X_1+X_2$ and $Y$ are not independent. | Is the sum of two variables independent of a third variable, if they are so on their own? | (To complete this thread, I am elevating a comment by user233740 into an answer.)
The statement is not true.
The possibility that $X_1+X_2$ might not be independent of $Y$ is strongly reminiscent of t | Is the sum of two variables independent of a third variable, if they are so on their own?
(To complete this thread, I am elevating a comment by user233740 into an answer.)
The statement is not true.
The possibility that $X_1+X_2$ might not be independent of $Y$ is strongly reminiscent of the familiar textbook problem concerning trivariate random variables $(X_1,X_2,Y)$ that are pairwise independent but not independent. With that thought in mind, let's consider the simplest such example, that of selecting one of the rows of this matrix uniformly at random:
$$\pmatrix{0&0&0\\1&1&0\\1&0&1\\0&1&1}.$$
You can see that any two columns determine independent Bernoulli$(1/2)$ variables, but the three are not independent because the third can be determined from the other two.
Let us then pick two of these columns, denoting them $X_1$ and $X_2,$ and let $Y$ be the third. Observe that when $Y=0,$ $X_1+X_2$ is either $0$ or $2$ (with equal probability), but when $Y=1,$ $X_1+X_2=1.$ Thus the conditional probability function $$\Pr(X_1+X_2\mid Y)$$ is not constant, demonstrating $X_1+X_2$ and $Y$ are not independent. | Is the sum of two variables independent of a third variable, if they are so on their own?
(To complete this thread, I am elevating a comment by user233740 into an answer.)
The statement is not true.
The possibility that $X_1+X_2$ might not be independent of $Y$ is strongly reminiscent of t |
24,249 | Intuitive explanation of logloss | Logloss is the logarithm of the product of all probabilities. Suppose Alice predicted:
with probability 0.2, John will kill Jack
with probability 0.001, Mary will marry John
with probability 0.01, Bill is a murderer.
It turned out that Mary did not marry John, Bill is not a murderer, but John killed Jack. The product of the probabilities, according to Alice, is 0.2*0.999*0.99=0.197802
Bob predicted:
with probability 0.5, John will kill Jack
with probability 0.5, Mary will marry John
with probability 0.5, Bill is a murderer.
The product is 0.5*0.5*0.5=0.125.
Alice is better predictor than Bob. | Intuitive explanation of logloss | Logloss is the logarithm of the product of all probabilities. Suppose Alice predicted:
with probability 0.2, John will kill Jack
with probability 0.001, Mary will marry John
with probability 0.01, Bi | Intuitive explanation of logloss
Logloss is the logarithm of the product of all probabilities. Suppose Alice predicted:
with probability 0.2, John will kill Jack
with probability 0.001, Mary will marry John
with probability 0.01, Bill is a murderer.
It turned out that Mary did not marry John, Bill is not a murderer, but John killed Jack. The product of the probabilities, according to Alice, is 0.2*0.999*0.99=0.197802
Bob predicted:
with probability 0.5, John will kill Jack
with probability 0.5, Mary will marry John
with probability 0.5, Bill is a murderer.
The product is 0.5*0.5*0.5=0.125.
Alice is better predictor than Bob. | Intuitive explanation of logloss
Logloss is the logarithm of the product of all probabilities. Suppose Alice predicted:
with probability 0.2, John will kill Jack
with probability 0.001, Mary will marry John
with probability 0.01, Bi |
24,250 | What's the difference between a MIMIC factor and a composite with indicators (SEM)? | They're the same model.
It's useful to be able to define a latent variable as a composite outcome where that variable only has composite indicators.
If you don't have:
f1 =~ y1 + y2 + y3
You can't put:
f1 ~ x1 + x2 + x3
But you can have:
f1 <~ x1 + x2 + x3 | What's the difference between a MIMIC factor and a composite with indicators (SEM)? | They're the same model.
It's useful to be able to define a latent variable as a composite outcome where that variable only has composite indicators.
If you don't have:
f1 =~ y1 + y2 + y3
You can't | What's the difference between a MIMIC factor and a composite with indicators (SEM)?
They're the same model.
It's useful to be able to define a latent variable as a composite outcome where that variable only has composite indicators.
If you don't have:
f1 =~ y1 + y2 + y3
You can't put:
f1 ~ x1 + x2 + x3
But you can have:
f1 <~ x1 + x2 + x3 | What's the difference between a MIMIC factor and a composite with indicators (SEM)?
They're the same model.
It's useful to be able to define a latent variable as a composite outcome where that variable only has composite indicators.
If you don't have:
f1 =~ y1 + y2 + y3
You can't |
24,251 | Does invertible monotone transformation of a confidence interval give you a confidence interval (at the same level) in the transformed space? | Yes it does, because
$$ P(a < X < b) = P \Big( \eta(a) < \eta(X) < \eta(b) \Big) $$
for a random variable $X$ and a monotone strictly increasing function, $\eta$. By a similar argument, if $\eta$ is a monotone strictly decreasing function, then the transformed interval becomes $(\eta(b),\eta(a))$. | Does invertible monotone transformation of a confidence interval give you a confidence interval (at | Yes it does, because
$$ P(a < X < b) = P \Big( \eta(a) < \eta(X) < \eta(b) \Big) $$
for a random variable $X$ and a monotone strictly increasing function, $\eta$. By a similar argument, if $\eta$ i | Does invertible monotone transformation of a confidence interval give you a confidence interval (at the same level) in the transformed space?
Yes it does, because
$$ P(a < X < b) = P \Big( \eta(a) < \eta(X) < \eta(b) \Big) $$
for a random variable $X$ and a monotone strictly increasing function, $\eta$. By a similar argument, if $\eta$ is a monotone strictly decreasing function, then the transformed interval becomes $(\eta(b),\eta(a))$. | Does invertible monotone transformation of a confidence interval give you a confidence interval (at
Yes it does, because
$$ P(a < X < b) = P \Big( \eta(a) < \eta(X) < \eta(b) \Big) $$
for a random variable $X$ and a monotone strictly increasing function, $\eta$. By a similar argument, if $\eta$ i |
24,252 | Why does Stouffer's method work? | The higher overall sample size leads to a higher power and thus to a smaller p value (at least if the working hypothesis is supported by the data).
This is usually the main point of any meta analysis: multiple weak evidences supporting a hypothesis are combined to strong evidence for it. | Why does Stouffer's method work? | The higher overall sample size leads to a higher power and thus to a smaller p value (at least if the working hypothesis is supported by the data).
This is usually the main point of any meta analysis | Why does Stouffer's method work?
The higher overall sample size leads to a higher power and thus to a smaller p value (at least if the working hypothesis is supported by the data).
This is usually the main point of any meta analysis: multiple weak evidences supporting a hypothesis are combined to strong evidence for it. | Why does Stouffer's method work?
The higher overall sample size leads to a higher power and thus to a smaller p value (at least if the working hypothesis is supported by the data).
This is usually the main point of any meta analysis |
24,253 | Why does Stouffer's method work? | For simplicity think in terms of a test on means. Suppose under H0 the treatment effect is zero, so that each z value is a weighted estimate of the treatment effect θi. Stouffer's method gives an unweighted average of these treatment effects so will give a more precise estimate (and hence smaller p-value) than each separate z value. This unweighted estimate of the treatment effect is biased but a weighted Stouffer's method is possible, and if the weights are proportional to 1/standard error(θi) the treatment effect estimate is unbiased. This only makes sense however if the separate z values are measures of the same quantity. An advantage of Stouffer's and Fisher's methods is that they can also be applied to meta-analyses where different response variables have been chosen - so they can't be averaged - but where a consistency of direction of effect can still be discerned. | Why does Stouffer's method work? | For simplicity think in terms of a test on means. Suppose under H0 the treatment effect is zero, so that each z value is a weighted estimate of the treatment effect θi. Stouffer's method gives an un | Why does Stouffer's method work?
For simplicity think in terms of a test on means. Suppose under H0 the treatment effect is zero, so that each z value is a weighted estimate of the treatment effect θi. Stouffer's method gives an unweighted average of these treatment effects so will give a more precise estimate (and hence smaller p-value) than each separate z value. This unweighted estimate of the treatment effect is biased but a weighted Stouffer's method is possible, and if the weights are proportional to 1/standard error(θi) the treatment effect estimate is unbiased. This only makes sense however if the separate z values are measures of the same quantity. An advantage of Stouffer's and Fisher's methods is that they can also be applied to meta-analyses where different response variables have been chosen - so they can't be averaged - but where a consistency of direction of effect can still be discerned. | Why does Stouffer's method work?
For simplicity think in terms of a test on means. Suppose under H0 the treatment effect is zero, so that each z value is a weighted estimate of the treatment effect θi. Stouffer's method gives an un |
24,254 | Why does Stouffer's method work? | Think of it from a meta-analysis point of view: If there was no effect ($H_0$), $p$ values would be equally distributed between 0 and 1. So if you get $p<0.1$ in more than 10% of all single analyses (potentially many of them), this can amount to the conclusion that $H_0$ probably should be rejected.
I do not even see a problem for two-tailed tests: In this case the result should be interpreted as: It is unlikely that the true mean is 0 (in the example of a gaussian around 0), but I cannot tell (from either the previous or the combined $p$ value) if the true mean is above or below it. | Why does Stouffer's method work? | Think of it from a meta-analysis point of view: If there was no effect ($H_0$), $p$ values would be equally distributed between 0 and 1. So if you get $p<0.1$ in more than 10% of all single analyses | Why does Stouffer's method work?
Think of it from a meta-analysis point of view: If there was no effect ($H_0$), $p$ values would be equally distributed between 0 and 1. So if you get $p<0.1$ in more than 10% of all single analyses (potentially many of them), this can amount to the conclusion that $H_0$ probably should be rejected.
I do not even see a problem for two-tailed tests: In this case the result should be interpreted as: It is unlikely that the true mean is 0 (in the example of a gaussian around 0), but I cannot tell (from either the previous or the combined $p$ value) if the true mean is above or below it. | Why does Stouffer's method work?
Think of it from a meta-analysis point of view: If there was no effect ($H_0$), $p$ values would be equally distributed between 0 and 1. So if you get $p<0.1$ in more than 10% of all single analyses |
24,255 | Why does Stouffer's method work? | I think it'd be fine to combine 2-tailed results because that means that the result would amount to zero (if there is evidence that the treatment enhances [right-tail] the disease of a patient but also evidence that it worsens [left-tail], the net result is no evidence towards a particular hypothesis since they cancel out and more observations are needed. | Why does Stouffer's method work? | I think it'd be fine to combine 2-tailed results because that means that the result would amount to zero (if there is evidence that the treatment enhances [right-tail] the disease of a patient but als | Why does Stouffer's method work?
I think it'd be fine to combine 2-tailed results because that means that the result would amount to zero (if there is evidence that the treatment enhances [right-tail] the disease of a patient but also evidence that it worsens [left-tail], the net result is no evidence towards a particular hypothesis since they cancel out and more observations are needed. | Why does Stouffer's method work?
I think it'd be fine to combine 2-tailed results because that means that the result would amount to zero (if there is evidence that the treatment enhances [right-tail] the disease of a patient but als |
24,256 | A continuous function of a sequence of random vectors converges in probability to the function of the limit | This all comes down to the axiomatic and self-evident fact that when $\mathcal{A}$ and $\mathcal{B}$ are events, then $\mathbb{P}(\mathcal{A} \cup \mathcal{B}) \le \mathbb{P}(\mathcal{A}) + \mathbb{P}(\mathcal{B})$. Everything else is just manipulation with sets (which can be visualized with Venn diagrams).
Applying this requires decoding the notation, which in turn means remembering that most of it is shorthand for subsets of some sample space $\Omega$. At the outset, it is convenient to view the ordered pair $\mathrm{Z}_n = (\mathrm{X}_n, \mathrm{X})$ as a single random variable with values in the metric space $M = \mathbb{R}^k\times \mathbb{R}^k$.
I am going to reduce most of this notation to statements about the inverse images of functions from $\Omega$ to $\mathbb{R}$.
First, define
$$g^\prime:M \to \mathbb{R},\ g^\prime((\mathrm{X}, \mathrm{Y})) = g(\mathrm{X}) - g(\mathrm{Y}).$$
The functional composition
$$g^\prime \circ \mathrm{Z}_n:\Omega \to \mathbb{R},\ (g^\prime \circ \mathrm{Z}_n)(\omega) = g^\prime\left(Z_n\left(\omega\right)\right)$$
is a real-valued function on $\Omega$.
Let
$$\mathcal{A}_n = \{|g(\mathrm{X}_n) - g(\mathrm{X})| \gt \varepsilon\} = \{\omega\in\Omega\,:\, |g(\mathrm{X}_n(\omega)) - g(\mathrm{X}(\omega))| \gt \varepsilon\}.$$
This is the inverse image of the complement of the real interval $B(\varepsilon) = [-\varepsilon, \varepsilon]$:
$$\mathcal{A}_n = (g^\prime \circ \mathrm{Z}_n)^{-1}(\mathbb{R} \setminus B(\varepsilon)).$$
It's just a bunch of points in $\Omega$. (In words: $\mathcal{A}_n$ consists of all outcomes where the values of $g$ on $\mathrm{X}$ and $\mathrm{X}_n$ differ too much.)
(To simplify the notation, let's write set complements in $\mathbb{R}$ with overbars, as in
$$\bar B(\varepsilon) = \mathbb{R} \setminus B(\varepsilon)$$
for instance.)
Similarly, let
$$\mathcal{B} = \{\mathrm{X} \le K\} = \{\omega\in\Omega\,:\, \mathrm{X}(\omega) \le K\} = \mathrm{X}^{-1}(B(K))$$
(these are the outcomes where $\mathrm{X}$ is bounded by $K$) and
$$\mathcal{B}_n = \{\mathrm{X}_n \le K\} = \{\omega\in\Omega\,:\, \mathrm{X}_n(\omega) \le K\} = \mathrm{X}_n^{-1}(B(K))$$
(the outcomes where $\mathrm{X}_n$ is bounded by $K$).
Finally, writing
$$d:M\to\mathbb{R},\ d((\mathrm{X}, \mathrm{Y})) = |\mathrm{X}-\mathrm{Y}|,$$
set
$$\mathcal{C}_n = \{|\mathrm{X}_n-\mathrm{X}| \gt \gamma(\varepsilon)\} = \{\omega\in\Omega\,:\,|\mathrm{X}_n(\omega)-\mathrm{X}(\omega)| \gt \gamma(\varepsilon)\} = (d \circ \mathrm{Z}_n)^{-1}(\bar B(\gamma(\varepsilon)))$$
(the outcomes where $\mathrm{X}_n$ differs too much from $\mathrm{X}$).
All four sets are thereby seen to be inverse images of real-valued functions.
Bear in mind the relationship between inverse images of functions and complements. When $f:A\to B$ is any function between sets and $C\subset B$, then
$$ A \setminus f^{-1}(C) \subset f^{-1}(B\setminus C).$$
The proof is simple: on the left hand side are all elements $x\in A$ that do not get sent to $C$ by $f$. Since $f$--being a function--is defined on all elements of $A$, any such $x$ must get sent to the complement of $C$ in $B$, QED.
With those mechanical, set-theoretic preliminaries out of the way we can now interpret the text. In the statement after "since $g$ is uniformly continuous ..." we see
$$\{|g(\mathrm{X}_n - g(\mathrm{X})| \gt \varepsilon,\ \mathrm{X}\le K,\ \mathrm{X}_n \le K\} = \mathcal{A}_n \cap \mathcal{B} \cap \mathcal{B}_n$$
and on its right hand side is $\mathcal{C}_n$ itself. In the first step following "Hence" we see such sets as
$$``\mathrm{X} \gt K" = \mathrm{X}^{-1} (\bar B(K)) \supset \bar{\mathcal{B}}$$
and
$$``\mathrm{X}_n \gt K" = \mathrm{X}_n^{-1} (\bar B(K)) \supset \bar{\mathcal{B}_n}.$$
Their probabilities are summed. This suggests we consider the relationship between
$$\mathcal{A}_n \cap \mathcal{B} \cap \mathcal{B}_n \subseteq \mathcal{C}_n$$
and
$$\mathcal{A}_n \subseteq \mathcal{C}_n \cup \bar{\mathcal{B}} \cup \bar{\mathcal{B}_n}.$$
The clarity of this notation now makes it obvious that the first inclusion implies the second, because any $\omega\in\mathcal{A}_n$ that is not in $\mathcal{B}\cap\mathcal{B}_n$ will certainly lie in
$$\Omega \setminus (\mathcal{B}\cap\mathcal{B}_n) = \bar{\mathcal{B}} \cup \bar{\mathcal{B}_n}.$$
The left of the figure shows a Venn diagram with $\mathcal{A}_n \cap \mathcal{B} \cap \mathcal{B}_n$ in gray while the right of the figure shows $\mathcal{C}_n \cup \bar{\mathcal{B}} \cup \bar{\mathcal{B}_n} = \mathcal{C}_n \cup \left(\Omega \setminus \left(\mathcal{B} \cap \mathcal{B}_n\right)\right)$ in gray. The left gray region clearly is contained in the right gray region.
When we apply probabilities, the first inequality following "Hence" follows immediately because the probability of a union cannot exceed the sum of the probabilities, as noted at the outset.
The next inequality is derived in the same fashion: I leave the drawing of its Venn diagram to the interested reader. | A continuous function of a sequence of random vectors converges in probability to the function of th | This all comes down to the axiomatic and self-evident fact that when $\mathcal{A}$ and $\mathcal{B}$ are events, then $\mathbb{P}(\mathcal{A} \cup \mathcal{B}) \le \mathbb{P}(\mathcal{A}) + \mathbb{P} | A continuous function of a sequence of random vectors converges in probability to the function of the limit
This all comes down to the axiomatic and self-evident fact that when $\mathcal{A}$ and $\mathcal{B}$ are events, then $\mathbb{P}(\mathcal{A} \cup \mathcal{B}) \le \mathbb{P}(\mathcal{A}) + \mathbb{P}(\mathcal{B})$. Everything else is just manipulation with sets (which can be visualized with Venn diagrams).
Applying this requires decoding the notation, which in turn means remembering that most of it is shorthand for subsets of some sample space $\Omega$. At the outset, it is convenient to view the ordered pair $\mathrm{Z}_n = (\mathrm{X}_n, \mathrm{X})$ as a single random variable with values in the metric space $M = \mathbb{R}^k\times \mathbb{R}^k$.
I am going to reduce most of this notation to statements about the inverse images of functions from $\Omega$ to $\mathbb{R}$.
First, define
$$g^\prime:M \to \mathbb{R},\ g^\prime((\mathrm{X}, \mathrm{Y})) = g(\mathrm{X}) - g(\mathrm{Y}).$$
The functional composition
$$g^\prime \circ \mathrm{Z}_n:\Omega \to \mathbb{R},\ (g^\prime \circ \mathrm{Z}_n)(\omega) = g^\prime\left(Z_n\left(\omega\right)\right)$$
is a real-valued function on $\Omega$.
Let
$$\mathcal{A}_n = \{|g(\mathrm{X}_n) - g(\mathrm{X})| \gt \varepsilon\} = \{\omega\in\Omega\,:\, |g(\mathrm{X}_n(\omega)) - g(\mathrm{X}(\omega))| \gt \varepsilon\}.$$
This is the inverse image of the complement of the real interval $B(\varepsilon) = [-\varepsilon, \varepsilon]$:
$$\mathcal{A}_n = (g^\prime \circ \mathrm{Z}_n)^{-1}(\mathbb{R} \setminus B(\varepsilon)).$$
It's just a bunch of points in $\Omega$. (In words: $\mathcal{A}_n$ consists of all outcomes where the values of $g$ on $\mathrm{X}$ and $\mathrm{X}_n$ differ too much.)
(To simplify the notation, let's write set complements in $\mathbb{R}$ with overbars, as in
$$\bar B(\varepsilon) = \mathbb{R} \setminus B(\varepsilon)$$
for instance.)
Similarly, let
$$\mathcal{B} = \{\mathrm{X} \le K\} = \{\omega\in\Omega\,:\, \mathrm{X}(\omega) \le K\} = \mathrm{X}^{-1}(B(K))$$
(these are the outcomes where $\mathrm{X}$ is bounded by $K$) and
$$\mathcal{B}_n = \{\mathrm{X}_n \le K\} = \{\omega\in\Omega\,:\, \mathrm{X}_n(\omega) \le K\} = \mathrm{X}_n^{-1}(B(K))$$
(the outcomes where $\mathrm{X}_n$ is bounded by $K$).
Finally, writing
$$d:M\to\mathbb{R},\ d((\mathrm{X}, \mathrm{Y})) = |\mathrm{X}-\mathrm{Y}|,$$
set
$$\mathcal{C}_n = \{|\mathrm{X}_n-\mathrm{X}| \gt \gamma(\varepsilon)\} = \{\omega\in\Omega\,:\,|\mathrm{X}_n(\omega)-\mathrm{X}(\omega)| \gt \gamma(\varepsilon)\} = (d \circ \mathrm{Z}_n)^{-1}(\bar B(\gamma(\varepsilon)))$$
(the outcomes where $\mathrm{X}_n$ differs too much from $\mathrm{X}$).
All four sets are thereby seen to be inverse images of real-valued functions.
Bear in mind the relationship between inverse images of functions and complements. When $f:A\to B$ is any function between sets and $C\subset B$, then
$$ A \setminus f^{-1}(C) \subset f^{-1}(B\setminus C).$$
The proof is simple: on the left hand side are all elements $x\in A$ that do not get sent to $C$ by $f$. Since $f$--being a function--is defined on all elements of $A$, any such $x$ must get sent to the complement of $C$ in $B$, QED.
With those mechanical, set-theoretic preliminaries out of the way we can now interpret the text. In the statement after "since $g$ is uniformly continuous ..." we see
$$\{|g(\mathrm{X}_n - g(\mathrm{X})| \gt \varepsilon,\ \mathrm{X}\le K,\ \mathrm{X}_n \le K\} = \mathcal{A}_n \cap \mathcal{B} \cap \mathcal{B}_n$$
and on its right hand side is $\mathcal{C}_n$ itself. In the first step following "Hence" we see such sets as
$$``\mathrm{X} \gt K" = \mathrm{X}^{-1} (\bar B(K)) \supset \bar{\mathcal{B}}$$
and
$$``\mathrm{X}_n \gt K" = \mathrm{X}_n^{-1} (\bar B(K)) \supset \bar{\mathcal{B}_n}.$$
Their probabilities are summed. This suggests we consider the relationship between
$$\mathcal{A}_n \cap \mathcal{B} \cap \mathcal{B}_n \subseteq \mathcal{C}_n$$
and
$$\mathcal{A}_n \subseteq \mathcal{C}_n \cup \bar{\mathcal{B}} \cup \bar{\mathcal{B}_n}.$$
The clarity of this notation now makes it obvious that the first inclusion implies the second, because any $\omega\in\mathcal{A}_n$ that is not in $\mathcal{B}\cap\mathcal{B}_n$ will certainly lie in
$$\Omega \setminus (\mathcal{B}\cap\mathcal{B}_n) = \bar{\mathcal{B}} \cup \bar{\mathcal{B}_n}.$$
The left of the figure shows a Venn diagram with $\mathcal{A}_n \cap \mathcal{B} \cap \mathcal{B}_n$ in gray while the right of the figure shows $\mathcal{C}_n \cup \bar{\mathcal{B}} \cup \bar{\mathcal{B}_n} = \mathcal{C}_n \cup \left(\Omega \setminus \left(\mathcal{B} \cap \mathcal{B}_n\right)\right)$ in gray. The left gray region clearly is contained in the right gray region.
When we apply probabilities, the first inequality following "Hence" follows immediately because the probability of a union cannot exceed the sum of the probabilities, as noted at the outset.
The next inequality is derived in the same fashion: I leave the drawing of its Venn diagram to the interested reader. | A continuous function of a sequence of random vectors converges in probability to the function of th
This all comes down to the axiomatic and self-evident fact that when $\mathcal{A}$ and $\mathcal{B}$ are events, then $\mathbb{P}(\mathcal{A} \cup \mathcal{B}) \le \mathbb{P}(\mathcal{A}) + \mathbb{P} |
24,257 | A continuous function of a sequence of random vectors converges in probability to the function of the limit | Proposition. If $\{X_n\}_{n\geq 1}$ is a sequence of $k$-dimensional random vectors such that $X_n\overset{\Pr}\to X$, and $g:\mathbb{R}^k\to\mathbb{R}^m$ is continuous, then $g(X_n)\overset{\Pr}\to g(X)$.
Proof. For every $K>0$, if $\|X_n(\omega)\|>K$, then
$$\|X_n(\omega)-X(\omega)\|+\|X(\omega)\|\geq\|X_n(\omega)-X(\omega)+X(\omega)\|=\|X_n(\omega)\|>K,$$
yielding that either $\|X_n(\omega)-X(\omega)\|>K/2$ or $\|X(\omega)\|>K/2$. Hence,
$$
\left\{\omega:\|X_n(\omega)\|>K \right\} \subset \left\{ \omega : \|X_n(\omega)-X(\omega)\|>K/2 \right\} \cup \left\{ \omega : \|X(\omega)\|>K/2 \right\},
$$
for every $n\geq 1$. Since $g$ is a continuous function, it is uniformly continuous on the compact set $\{v\in\mathbb{R}^k:\|v\|\leq K\}$. Therefore, for every $\epsilon>0$, there exists a $\delta>0$ such that, for $\|X_n(\omega)\|\leq K$ and $\|X(\omega)\|\leq K$, if $\|X_n(\omega)-X(\omega)\|<\delta$, then $\|g(X_n(\omega))-g(X(\omega))\|<\epsilon$. It follows contrapositively that
$$\begin{align}
&\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq\epsilon, \|X_n(\omega)\|\leq K, \|X(\omega)\|\leq K \right\} \\
&\qquad\subset\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta, \|X_n(\omega)\|\leq K, \|X(\omega)\|\leq K \right\} \\
&\qquad\subset\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta\right\}.
\end{align}$$
Moreover, defining $A_n=\{\omega:\|X_n(\omega)\|\leq K\}\cap\{\omega:\|X(\omega)\|\leq K\}$ and using the inclusions above, we have
$$
\begin{align}
\Pr\!\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\} &= \Pr\!\left(\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\}\cap A_n\right) \\
&+ \Pr\!\left(\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\}\cap A_n^c\right) \\
&\leq \Pr\!\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta \right\} + \Pr(A_n^c) \\
&\leq \Pr\!\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta \right\} \\
&+ \Pr\!\left\{\omega:\|X_n(\omega)\|>K \right\} + \Pr\!\left\{\omega:\|X(\omega)\|>K \right\} \\
&\leq \Pr\!\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta \right\} \\
&+ 2\Pr\!\left\{\omega:\|X(\omega)\|>K/2 \right\} \\
&+ \Pr\!\left\{\omega:\|X_n(\omega)-X(\omega)\|>K/2 \right\},
\end{align}
$$
for every $n\geq 1$. Since, by hypothesis, $X_n\overset{\Pr}\to X$, it follows that
$$
\lim_{n\to\infty} \Pr\!\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\} \leq 2\Pr\!\left\{\omega:\|X(\omega)\|>K/2 \right\}, \quad (*)
$$
for every $\epsilon>0$, and every $K>0$ (this is a subtle and crucial logical point!). Because increasing $K$ we can make $2\Pr\!\left\{\omega:\|X(\omega)\|>K/2 \right\}$ arbitrarily small, the inequality $(*)$ holds for every $K>0$ if and only if
$$
\lim_{n\to\infty} \Pr\!\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\}=0,
$$
for every $\epsilon>0$, yielding that $g(X_n)\overset{\Pr}\to g(X)$.$\quad\square$
Note. It's much easier to prove this proposition using the fact that $X_n\overset{\Pr}\to X$ if and only if for any subsequence $\{n_i\}\subset\mathbb{N}$ there is a subsequence $\{n_{i_j}\}\subset\{n_i\}$ such that $X_{n_{i_j}}\to X$ almost surely when $j\to\infty$. | A continuous function of a sequence of random vectors converges in probability to the function of th | Proposition. If $\{X_n\}_{n\geq 1}$ is a sequence of $k$-dimensional random vectors such that $X_n\overset{\Pr}\to X$, and $g:\mathbb{R}^k\to\mathbb{R}^m$ is continuous, then $g(X_n)\overset{\Pr}\to g | A continuous function of a sequence of random vectors converges in probability to the function of the limit
Proposition. If $\{X_n\}_{n\geq 1}$ is a sequence of $k$-dimensional random vectors such that $X_n\overset{\Pr}\to X$, and $g:\mathbb{R}^k\to\mathbb{R}^m$ is continuous, then $g(X_n)\overset{\Pr}\to g(X)$.
Proof. For every $K>0$, if $\|X_n(\omega)\|>K$, then
$$\|X_n(\omega)-X(\omega)\|+\|X(\omega)\|\geq\|X_n(\omega)-X(\omega)+X(\omega)\|=\|X_n(\omega)\|>K,$$
yielding that either $\|X_n(\omega)-X(\omega)\|>K/2$ or $\|X(\omega)\|>K/2$. Hence,
$$
\left\{\omega:\|X_n(\omega)\|>K \right\} \subset \left\{ \omega : \|X_n(\omega)-X(\omega)\|>K/2 \right\} \cup \left\{ \omega : \|X(\omega)\|>K/2 \right\},
$$
for every $n\geq 1$. Since $g$ is a continuous function, it is uniformly continuous on the compact set $\{v\in\mathbb{R}^k:\|v\|\leq K\}$. Therefore, for every $\epsilon>0$, there exists a $\delta>0$ such that, for $\|X_n(\omega)\|\leq K$ and $\|X(\omega)\|\leq K$, if $\|X_n(\omega)-X(\omega)\|<\delta$, then $\|g(X_n(\omega))-g(X(\omega))\|<\epsilon$. It follows contrapositively that
$$\begin{align}
&\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq\epsilon, \|X_n(\omega)\|\leq K, \|X(\omega)\|\leq K \right\} \\
&\qquad\subset\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta, \|X_n(\omega)\|\leq K, \|X(\omega)\|\leq K \right\} \\
&\qquad\subset\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta\right\}.
\end{align}$$
Moreover, defining $A_n=\{\omega:\|X_n(\omega)\|\leq K\}\cap\{\omega:\|X(\omega)\|\leq K\}$ and using the inclusions above, we have
$$
\begin{align}
\Pr\!\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\} &= \Pr\!\left(\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\}\cap A_n\right) \\
&+ \Pr\!\left(\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\}\cap A_n^c\right) \\
&\leq \Pr\!\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta \right\} + \Pr(A_n^c) \\
&\leq \Pr\!\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta \right\} \\
&+ \Pr\!\left\{\omega:\|X_n(\omega)\|>K \right\} + \Pr\!\left\{\omega:\|X(\omega)\|>K \right\} \\
&\leq \Pr\!\left\{\omega: \|X_n(\omega)-X(\omega)\|\geq\delta \right\} \\
&+ 2\Pr\!\left\{\omega:\|X(\omega)\|>K/2 \right\} \\
&+ \Pr\!\left\{\omega:\|X_n(\omega)-X(\omega)\|>K/2 \right\},
\end{align}
$$
for every $n\geq 1$. Since, by hypothesis, $X_n\overset{\Pr}\to X$, it follows that
$$
\lim_{n\to\infty} \Pr\!\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\} \leq 2\Pr\!\left\{\omega:\|X(\omega)\|>K/2 \right\}, \quad (*)
$$
for every $\epsilon>0$, and every $K>0$ (this is a subtle and crucial logical point!). Because increasing $K$ we can make $2\Pr\!\left\{\omega:\|X(\omega)\|>K/2 \right\}$ arbitrarily small, the inequality $(*)$ holds for every $K>0$ if and only if
$$
\lim_{n\to\infty} \Pr\!\left\{\omega: \|g(X_n(\omega))-g(X(\omega))\|\geq \epsilon\right\}=0,
$$
for every $\epsilon>0$, yielding that $g(X_n)\overset{\Pr}\to g(X)$.$\quad\square$
Note. It's much easier to prove this proposition using the fact that $X_n\overset{\Pr}\to X$ if and only if for any subsequence $\{n_i\}\subset\mathbb{N}$ there is a subsequence $\{n_{i_j}\}\subset\{n_i\}$ such that $X_{n_{i_j}}\to X$ almost surely when $j\to\infty$. | A continuous function of a sequence of random vectors converges in probability to the function of th
Proposition. If $\{X_n\}_{n\geq 1}$ is a sequence of $k$-dimensional random vectors such that $X_n\overset{\Pr}\to X$, and $g:\mathbb{R}^k\to\mathbb{R}^m$ is continuous, then $g(X_n)\overset{\Pr}\to g |
24,258 | What is the expected norm $\mathbb E \lVert X \rVert$ for a multivariate normal $X \sim \mathcal N(\mu, \Sigma)$? [duplicate] | I will not write out a full answer, that will take to much time now. The complete answer to the question can be found in Mathai & Provost: "Quadratic forms in Random Variables", see for example my answer to this question on the Mathematics Stack Exchange site.
The answer is long, complicated and involves special functions such as "the Lauricella function". I don't know if there is an R package for that (I couldn't find one). The answer can be found in that book in the section 3.2b.7 (Theorem 3.2b.5): Positive Fractional moments of Quadratic forms, between pages 62--66.
The distribution of quadratic form in normal variables can be computed with the R package CompQuadForm, maybe you could try numerical integration with the help of that package. | What is the expected norm $\mathbb E \lVert X \rVert$ for a multivariate normal $X \sim \mathcal N(\ | I will not write out a full answer, that will take to much time now. The complete answer to the question can be found in Mathai & Provost: "Quadratic forms in Random Variables", see for example my an | What is the expected norm $\mathbb E \lVert X \rVert$ for a multivariate normal $X \sim \mathcal N(\mu, \Sigma)$? [duplicate]
I will not write out a full answer, that will take to much time now. The complete answer to the question can be found in Mathai & Provost: "Quadratic forms in Random Variables", see for example my answer to this question on the Mathematics Stack Exchange site.
The answer is long, complicated and involves special functions such as "the Lauricella function". I don't know if there is an R package for that (I couldn't find one). The answer can be found in that book in the section 3.2b.7 (Theorem 3.2b.5): Positive Fractional moments of Quadratic forms, between pages 62--66.
The distribution of quadratic form in normal variables can be computed with the R package CompQuadForm, maybe you could try numerical integration with the help of that package. | What is the expected norm $\mathbb E \lVert X \rVert$ for a multivariate normal $X \sim \mathcal N(\
I will not write out a full answer, that will take to much time now. The complete answer to the question can be found in Mathai & Provost: "Quadratic forms in Random Variables", see for example my an |
24,259 | Mixed-effect model design with a sampling variable | Your model should be written as
fit <- lmer(y ~ treatment*irrigation + (1|plot/subplot), data=mydata)
as subplots are nested within site. although (1|plot) + (1|subplot) would work if the subplots are uniquely labeled (i.e. 1A,1B,1C,...,2A,2B,2C rather than A,B,C...,A,B,C). My book chapter from Fox et al. Ecological Statistics describes an example of nesting:
On the other hand, in the tick example each chick occurs in only one brood,
and each brood occurs in only one site: the model specification is (1 | SITE/BROOD/INDEX), read as “chick (INDEX) nested within brood nested within site,” or equivalently (1 | SITE) + (1 | SITE:BROOD) + (1 | SITE:BROOD:INDEX). If the broods and chicks are uniquely labeled, so that the software can detect the nesting, (1 | SITE) + (1 | BROOD) + (1 | INDEX) will also work (do not use (1 | SITE) + (1 | SITE/BROOD) + (1 | SITE/BROOD/INDEX); it will lead to redundant terms in the model).
Other thoughts:
more information on nesting and model specifications at http://glmm.wikidot.com/faq
are your irrigation treatments really organized as shown in the schematic above, i.e. non-interspersed? Or is that just for convenience of graphical presentation? If the former, then you have a potentially problematic experimental design ...
Since subplots are nested within sites, it would be just fine inferentially (following Murtaugh 2007 Ecology "Simplicity and complexity in ecological data analysis") to take the plot means and analyze the data at the plot level.
For what it's worth, I think you could go even farther and aggregate to the plot level; then you could skip mixed models entirely and just do lm(y~treatment*irrigation, data=my_aggregated_data) | Mixed-effect model design with a sampling variable | Your model should be written as
fit <- lmer(y ~ treatment*irrigation + (1|plot/subplot), data=mydata)
as subplots are nested within site. although (1|plot) + (1|subplot) would work if the subplots ar | Mixed-effect model design with a sampling variable
Your model should be written as
fit <- lmer(y ~ treatment*irrigation + (1|plot/subplot), data=mydata)
as subplots are nested within site. although (1|plot) + (1|subplot) would work if the subplots are uniquely labeled (i.e. 1A,1B,1C,...,2A,2B,2C rather than A,B,C...,A,B,C). My book chapter from Fox et al. Ecological Statistics describes an example of nesting:
On the other hand, in the tick example each chick occurs in only one brood,
and each brood occurs in only one site: the model specification is (1 | SITE/BROOD/INDEX), read as “chick (INDEX) nested within brood nested within site,” or equivalently (1 | SITE) + (1 | SITE:BROOD) + (1 | SITE:BROOD:INDEX). If the broods and chicks are uniquely labeled, so that the software can detect the nesting, (1 | SITE) + (1 | BROOD) + (1 | INDEX) will also work (do not use (1 | SITE) + (1 | SITE/BROOD) + (1 | SITE/BROOD/INDEX); it will lead to redundant terms in the model).
Other thoughts:
more information on nesting and model specifications at http://glmm.wikidot.com/faq
are your irrigation treatments really organized as shown in the schematic above, i.e. non-interspersed? Or is that just for convenience of graphical presentation? If the former, then you have a potentially problematic experimental design ...
Since subplots are nested within sites, it would be just fine inferentially (following Murtaugh 2007 Ecology "Simplicity and complexity in ecological data analysis") to take the plot means and analyze the data at the plot level.
For what it's worth, I think you could go even farther and aggregate to the plot level; then you could skip mixed models entirely and just do lm(y~treatment*irrigation, data=my_aggregated_data) | Mixed-effect model design with a sampling variable
Your model should be written as
fit <- lmer(y ~ treatment*irrigation + (1|plot/subplot), data=mydata)
as subplots are nested within site. although (1|plot) + (1|subplot) would work if the subplots ar |
24,260 | Displaying Ordinal Data - Means, Medians, and Mean Ranks | This is an excellent question. As you found, quantiles do not work when there are many ties in the data, because they are too discontinuous as estimators. I often find means work best, if you can assume that the spacing between the categories are at least "halfway meaningful." Exceedance probabilities are always valid. In your case these would be estimated by the proportion of observations $\geq 1, \geq 2, =3$. Mean ranks are useful when comparing groups, but I don't see as much use for a single variable.
The correctness of using the mean to summarize ordinal variables can seldom come from the data themselves. It is subjective.
Instead of using mean ranks I would use an appropriate rank correlation measure or the concordance probability (a simple linear translation of the Wilcoxon-Mann-Whitney statistic; it is the mean rank of observations in one of the two groups divided by a constant) between two variables (e.g., a binary grouping and an ordinal scale). Choices for correlation coefficients include Somers' $D_{xy}$ (which is consistent with the concordance probability and penalizes for ties on the ordinal variable) and Goodman-Kruskal $\gamma$ which doesn't penalize for ties on either $x$ or $y$. | Displaying Ordinal Data - Means, Medians, and Mean Ranks | This is an excellent question. As you found, quantiles do not work when there are many ties in the data, because they are too discontinuous as estimators. I often find means work best, if you can as | Displaying Ordinal Data - Means, Medians, and Mean Ranks
This is an excellent question. As you found, quantiles do not work when there are many ties in the data, because they are too discontinuous as estimators. I often find means work best, if you can assume that the spacing between the categories are at least "halfway meaningful." Exceedance probabilities are always valid. In your case these would be estimated by the proportion of observations $\geq 1, \geq 2, =3$. Mean ranks are useful when comparing groups, but I don't see as much use for a single variable.
The correctness of using the mean to summarize ordinal variables can seldom come from the data themselves. It is subjective.
Instead of using mean ranks I would use an appropriate rank correlation measure or the concordance probability (a simple linear translation of the Wilcoxon-Mann-Whitney statistic; it is the mean rank of observations in one of the two groups divided by a constant) between two variables (e.g., a binary grouping and an ordinal scale). Choices for correlation coefficients include Somers' $D_{xy}$ (which is consistent with the concordance probability and penalizes for ties on the ordinal variable) and Goodman-Kruskal $\gamma$ which doesn't penalize for ties on either $x$ or $y$. | Displaying Ordinal Data - Means, Medians, and Mean Ranks
This is an excellent question. As you found, quantiles do not work when there are many ties in the data, because they are too discontinuous as estimators. I often find means work best, if you can as |
24,261 | How do I find a p-value of smooth spline / loess regression? | The splines library has functions bs and ns that will create spline basis to use with the lm function, then you can fit a linear model and a model including splines and use the anova function to do the full and reduced model test to see if the spline model fits significantly better than the linear model.
Here is some example code:
x <- rnorm(1000)
y <- sin(x) + rnorm(1000, 0, 0.5)
library(splines)
fit1 <- lm(y~x)
fit0 <- lm(y~1)
fit2 <- lm(y~bs(x,5))
anova(fit1,fit2)
anova(fit0,fit2)
plot(x,y, pch='.')
abline(fit1, col='red')
xx <- seq(min(x),max(x), length.out=250)
yy <- predict(fit2, data.frame(x=xx))
lines(xx,yy, col='blue')
You can also use the poly function to do a polynomial fit and test the non-linear terms as a test of curvature.
For the loess fit it is a little more complicated. There are some estimates of equivalent degrees of freedom for the loess smoothing parameter that could be used along with the $R^2$ values for the linear and loess models to construct and F test. I think methods based on bootstrapping and permutation tests may be more intuitive.
There are techniques to compute and plot a confidence interval for a loess fit (I think there may be a built-in way in the ggplot2 package), you can plot the confidence band and see if a straight line would fit within the band (this is not a p-value, but still gives a yes/no.
You could fit a linear model and take the residuals and fit a loess model to the residuals as response (and the variable of interest as predictor), if the true model is linear then this fit should be close to a flat line and reordering the points relative to the predictor should not make any difference. You can use this to create a permutation test. Fit the loess, find the predicted value farthest from 0, now randomly permute the points and fit a new loess and find the furthest predicted point from 0, repeat a bunch of times, the p-value is the proportion of permuted values that are further from 0 than the original value.
You may also want to look at cross-validation as a method of choosing the loess bandwidth. This does not give a p-value, but an infinite bandwidth corresponds to a perfect linear model, if the cross-validation suggests a very large bandwidth then that suggests a linear model may be reasonable, if the higher bandwidths are clearly inferior to some of the smaller bandwidths then this suggests definite curvature and linear is not sufficient. | How do I find a p-value of smooth spline / loess regression? | The splines library has functions bs and ns that will create spline basis to use with the lm function, then you can fit a linear model and a model including splines and use the anova function to do th | How do I find a p-value of smooth spline / loess regression?
The splines library has functions bs and ns that will create spline basis to use with the lm function, then you can fit a linear model and a model including splines and use the anova function to do the full and reduced model test to see if the spline model fits significantly better than the linear model.
Here is some example code:
x <- rnorm(1000)
y <- sin(x) + rnorm(1000, 0, 0.5)
library(splines)
fit1 <- lm(y~x)
fit0 <- lm(y~1)
fit2 <- lm(y~bs(x,5))
anova(fit1,fit2)
anova(fit0,fit2)
plot(x,y, pch='.')
abline(fit1, col='red')
xx <- seq(min(x),max(x), length.out=250)
yy <- predict(fit2, data.frame(x=xx))
lines(xx,yy, col='blue')
You can also use the poly function to do a polynomial fit and test the non-linear terms as a test of curvature.
For the loess fit it is a little more complicated. There are some estimates of equivalent degrees of freedom for the loess smoothing parameter that could be used along with the $R^2$ values for the linear and loess models to construct and F test. I think methods based on bootstrapping and permutation tests may be more intuitive.
There are techniques to compute and plot a confidence interval for a loess fit (I think there may be a built-in way in the ggplot2 package), you can plot the confidence band and see if a straight line would fit within the band (this is not a p-value, but still gives a yes/no.
You could fit a linear model and take the residuals and fit a loess model to the residuals as response (and the variable of interest as predictor), if the true model is linear then this fit should be close to a flat line and reordering the points relative to the predictor should not make any difference. You can use this to create a permutation test. Fit the loess, find the predicted value farthest from 0, now randomly permute the points and fit a new loess and find the furthest predicted point from 0, repeat a bunch of times, the p-value is the proportion of permuted values that are further from 0 than the original value.
You may also want to look at cross-validation as a method of choosing the loess bandwidth. This does not give a p-value, but an infinite bandwidth corresponds to a perfect linear model, if the cross-validation suggests a very large bandwidth then that suggests a linear model may be reasonable, if the higher bandwidths are clearly inferior to some of the smaller bandwidths then this suggests definite curvature and linear is not sufficient. | How do I find a p-value of smooth spline / loess regression?
The splines library has functions bs and ns that will create spline basis to use with the lm function, then you can fit a linear model and a model including splines and use the anova function to do th |
24,262 | Check a status of training process in R [closed] | When using caret for training, you can set the option verbose = TRUE within the train function. For further detail, there is also the verboseIter argument within the trainControl call. Max Kuhn has a great website built from the github page that can help you familiarize yourself more with the functions here. | Check a status of training process in R [closed] | When using caret for training, you can set the option verbose = TRUE within the train function. For further detail, there is also the verboseIter argument within the trainControl call. Max Kuhn has | Check a status of training process in R [closed]
When using caret for training, you can set the option verbose = TRUE within the train function. For further detail, there is also the verboseIter argument within the trainControl call. Max Kuhn has a great website built from the github page that can help you familiarize yourself more with the functions here. | Check a status of training process in R [closed]
When using caret for training, you can set the option verbose = TRUE within the train function. For further detail, there is also the verboseIter argument within the trainControl call. Max Kuhn has |
24,263 | Time Series Forecast: Convert differenced forecast back to before difference level | The usual approach to the point forecasts is to cumulatively add the difference-forecasts to the last cumulative observation. If $z$ are the differenced data and $y$ the original, then:
$\hat{y}_{t+1}=y_t+\hat{z}_{t+1}$
$\hat{y}_{t+2}=\hat{y}_{t+1}+\hat{z}_{t+2}=y_t+\hat{z}_{t+1}+\hat{z}_{t+2}$
and so on. The cumulative sums of the $\hat{z}$ values are easy, and adding $y_t$ is also easy. Details of what to do in R would depend on the specific model (e.g. if you fitted an ARMA to the differences, just specify the corresponding ARIMA to the original and predict that).
On your second question, you have more data, so you have to calculate new parameter estimates anyway. Since you have new parameter estimates you'd just recalculate forecasts the same way as before, but with those 7 additional observations. In some circumstances the parameter updates can be computed in terms of the old estimates and the data (e.g. state-space models), but for many models you just recompute everything like you did with the previous forecasts. | Time Series Forecast: Convert differenced forecast back to before difference level | The usual approach to the point forecasts is to cumulatively add the difference-forecasts to the last cumulative observation. If $z$ are the differenced data and $y$ the original, then:
$\hat{y}_{t+1} | Time Series Forecast: Convert differenced forecast back to before difference level
The usual approach to the point forecasts is to cumulatively add the difference-forecasts to the last cumulative observation. If $z$ are the differenced data and $y$ the original, then:
$\hat{y}_{t+1}=y_t+\hat{z}_{t+1}$
$\hat{y}_{t+2}=\hat{y}_{t+1}+\hat{z}_{t+2}=y_t+\hat{z}_{t+1}+\hat{z}_{t+2}$
and so on. The cumulative sums of the $\hat{z}$ values are easy, and adding $y_t$ is also easy. Details of what to do in R would depend on the specific model (e.g. if you fitted an ARMA to the differences, just specify the corresponding ARIMA to the original and predict that).
On your second question, you have more data, so you have to calculate new parameter estimates anyway. Since you have new parameter estimates you'd just recalculate forecasts the same way as before, but with those 7 additional observations. In some circumstances the parameter updates can be computed in terms of the old estimates and the data (e.g. state-space models), but for many models you just recompute everything like you did with the previous forecasts. | Time Series Forecast: Convert differenced forecast back to before difference level
The usual approach to the point forecasts is to cumulatively add the difference-forecasts to the last cumulative observation. If $z$ are the differenced data and $y$ the original, then:
$\hat{y}_{t+1} |
24,264 | Interpret Variable Importance (varImp) for Factor Variables | The random forest variable importance scores are aggregate measures. They only quantify the impact of the predictor, not the specific effect.
You could fix the other predictors to a single value and get a profile of predicted values over a single parameter (see partialPlot in the randomForest package). Otherwise, fit a parametric model where you can estimate specific structural terms.
Your other question is about the effect of CITY and STATE. You may have used the formula interface when creating the model (i.e. function(y ~ ., data = dat)). In this case, the formula interface might be breaking up the factor into dummy variables (as it should). You might try using a non-formula interface where x has the predictors (in factor form), y is the outcome and the call function(x, y). That will avoid dummy variable creation and treat a factor predictor as a cohesive set. | Interpret Variable Importance (varImp) for Factor Variables | The random forest variable importance scores are aggregate measures. They only quantify the impact of the predictor, not the specific effect.
You could fix the other predictors to a single value and | Interpret Variable Importance (varImp) for Factor Variables
The random forest variable importance scores are aggregate measures. They only quantify the impact of the predictor, not the specific effect.
You could fix the other predictors to a single value and get a profile of predicted values over a single parameter (see partialPlot in the randomForest package). Otherwise, fit a parametric model where you can estimate specific structural terms.
Your other question is about the effect of CITY and STATE. You may have used the formula interface when creating the model (i.e. function(y ~ ., data = dat)). In this case, the formula interface might be breaking up the factor into dummy variables (as it should). You might try using a non-formula interface where x has the predictors (in factor form), y is the outcome and the call function(x, y). That will avoid dummy variable creation and treat a factor predictor as a cohesive set. | Interpret Variable Importance (varImp) for Factor Variables
The random forest variable importance scores are aggregate measures. They only quantify the impact of the predictor, not the specific effect.
You could fix the other predictors to a single value and |
24,265 | Clustering inertia formula in scikit learn | I guess I found my answer for kmeans clustering:
By looking at the git source code, I found that for scikit learn, inertia is calculated as the sum of squared distance for each point to it's closest centroid, i.e., its assigned cluster. So $I = \sum_{i}(d(i,cr))$ where $cr$ is the centroid of the assigned cluster and $d$ is the squared distance.
Now the formula of gap statistic involves
$$
W_k = \sum_{r=1}^{k}\frac 1 {(2*n_r) }D_r
$$
where $D_r$ is the sum of the squared distances between all points in cluster $r$.
By introducing $+c$, $-c$ in the squared distance formula ($c$ being the centroid of cluster $r$ coordinates), I have a term that corresponds to Inertia (as in scikit) + a term that disappears if each $c$ is the barycentre of each cluster (which it is supposed to be in kmeans). So I guess $W_k$ is in fact scikit Inertia.
I have still two questions:
Do you think my calculus is correct? (For example, I don't know if it holds for hierarchical clustering.)
If I am correct above, I have coded the gap statistic (as difference of log inertias between estimation and clustering) and it performs badly especially on the iris dataset, has anyone tried it? | Clustering inertia formula in scikit learn | I guess I found my answer for kmeans clustering:
By looking at the git source code, I found that for scikit learn, inertia is calculated as the sum of squared distance for each point to it's closest | Clustering inertia formula in scikit learn
I guess I found my answer for kmeans clustering:
By looking at the git source code, I found that for scikit learn, inertia is calculated as the sum of squared distance for each point to it's closest centroid, i.e., its assigned cluster. So $I = \sum_{i}(d(i,cr))$ where $cr$ is the centroid of the assigned cluster and $d$ is the squared distance.
Now the formula of gap statistic involves
$$
W_k = \sum_{r=1}^{k}\frac 1 {(2*n_r) }D_r
$$
where $D_r$ is the sum of the squared distances between all points in cluster $r$.
By introducing $+c$, $-c$ in the squared distance formula ($c$ being the centroid of cluster $r$ coordinates), I have a term that corresponds to Inertia (as in scikit) + a term that disappears if each $c$ is the barycentre of each cluster (which it is supposed to be in kmeans). So I guess $W_k$ is in fact scikit Inertia.
I have still two questions:
Do you think my calculus is correct? (For example, I don't know if it holds for hierarchical clustering.)
If I am correct above, I have coded the gap statistic (as difference of log inertias between estimation and clustering) and it performs badly especially on the iris dataset, has anyone tried it? | Clustering inertia formula in scikit learn
I guess I found my answer for kmeans clustering:
By looking at the git source code, I found that for scikit learn, inertia is calculated as the sum of squared distance for each point to it's closest |
24,266 | Attainable correlations for exponential random variables | Let $\rho_{\min}$ (resp. $\rho_{\max}$) denote the lower (resp. upper) bound of the attainable correlation between $X_1$ and $X_2$.
The bounds $\rho_{\min}$ and $\rho_{\max}$ are reached when $X_1$ and $X_2$ are respectively countermonotonic and comonotonic (see here).
Lower bound
To determine of the lower bound $\rho_{\min}$ we construct a pair countermonotonic exponential variables and compute their correlation.
The necessary and sufficient condition mentioned here and the probability integral transform provide a convenient way to construct the random variables $X_1$ and $X_2$ such that they are countermonotonic.
Recall that the exponential distribution function is $F(x) = 1 - \exp(-\lambda x)$,
so the quantile function is $F^{-1}(q) = -\lambda^{-1}\log (1-q)$.
Let $U\sim U(0, 1)$ be a uniformly distributed random variables, then $1-U$ is also uniformly distributed and the random variables
$$
X_1 = -\lambda_1^{-1}\log (1-U), \quad \text{and } X_2 = -\lambda_2^{-1}\log (U)
$$
have the exponential distribution with rate $\lambda_1$ and $\lambda_2$ respectively.
In addition, they are countermonotonic since $X_1 = h_1(U)$ and $X_2 = h_2(U)$, and the functions $h_1(x)=-\lambda_1^{-1}\log (1-x)$ and $h_2(x)=-\lambda_1^{-1}\log (x)$ are respectively increasing and deacreasing.
Now, let's compute the correlation of $X_1$ and $X_2$. By the properties of the exponential distribution we have ${\rm E}(X_1) = \lambda_1^{-1}$, ${\rm E}(X_2) = \lambda_2^{-1}$, ${\rm var}(X_1) = \lambda_1^{-2}$, and ${\rm var}(X_2) = \lambda_2^{-2}$. Also, we have
\begin{align}
{\rm E}(X_1 X_2)
&= \lambda_1^{-1} \lambda_2^{-1} {\rm E}\{\log (1-U) \log (U)\}\\
&= \lambda_1^{-1} \lambda_2^{-1} \int_0^1 \log (1-u) \log (u) f_U(u) {\rm d}u \\
&= \lambda_1^{-1} \lambda_2^{-1} \int_0^1 \log (1-u) \log (u) {\rm d}u \\
&= \lambda_1^{-1} \lambda_2^{-1} \left (2 - \frac{\pi^2}{6} \right ),
\end{align}
where $f_U(u) \equiv 1$ is the density function of the standard uniform distribution.
For the last equality I relied on WolframAlpha.
Thus,
\begin{align}
\rho_{\min}
&= {\rm corr}(X_1, X_2)\\
&= \frac{ \lambda_1^{-1} \lambda_2^{-1} (2 - \pi^2/6 ) - \lambda_1^{-1} \lambda_2^{-1}}{ \sqrt{\lambda_1^{-2} \lambda_2^{-2}} } \\
&= 1 - \pi^2/6 \approx −0.645.
\end{align}
Note that the lower bound doesn't depend on the rates $\lambda_1$ and $\lambda_2$, and that the correlation never reaches $-1$, even when both margins are equal (i.e., when $\lambda_1 = \lambda_2$).
Upper bound
To determine of the upper bound $\rho_{\max}$ we follow a similar approach with a pair of comonotonic exponential variables.
Now, let $X_1 = g_1(U)$ and $X_2 = g_2(U)$ where
$g_1(x)=-\lambda_1^{-1}\log (1-x)$ and $g_2(x)=-\lambda_2^{-1}\log (1-x)$,
which are both increasing functions. So, these random variables are comonotonic and both exponentialy distributed with rates $\lambda_1$ and $\lambda_2$.
We have
\begin{align}
{\rm E}(X_1 X_2)
&= \lambda_1^{-1} \lambda_2^{-1} {\rm E}\{\log (1-U) \log (1-U)\}\\
&= \lambda_1^{-1} \lambda_2^{-1} \int_0^1 \left\{\log (1-u) \right\}^2 {\rm d}u \\
&= 2 \lambda_1^{-1} \lambda_2^{-1} ,
\end{align}
and thus,
\begin{align}
\rho_{\max}
&= {\rm corr}(X_1, X_2)\\
&= \frac{ 2\lambda_1^{-1} \lambda_2^{-1} - \lambda_1^{-1} \lambda_2^{-1}}{ \sqrt{\lambda_1^{-2} \lambda_2^{-2}} } \\
&= 1 .
\end{align}
Similarly to the lower bound, the upper bound doesn't depend on the rates $\lambda_1$ and $\lambda_2$. | Attainable correlations for exponential random variables | Let $\rho_{\min}$ (resp. $\rho_{\max}$) denote the lower (resp. upper) bound of the attainable correlation between $X_1$ and $X_2$.
The bounds $\rho_{\min}$ and $\rho_{\max}$ are reached when $X_1$ an | Attainable correlations for exponential random variables
Let $\rho_{\min}$ (resp. $\rho_{\max}$) denote the lower (resp. upper) bound of the attainable correlation between $X_1$ and $X_2$.
The bounds $\rho_{\min}$ and $\rho_{\max}$ are reached when $X_1$ and $X_2$ are respectively countermonotonic and comonotonic (see here).
Lower bound
To determine of the lower bound $\rho_{\min}$ we construct a pair countermonotonic exponential variables and compute their correlation.
The necessary and sufficient condition mentioned here and the probability integral transform provide a convenient way to construct the random variables $X_1$ and $X_2$ such that they are countermonotonic.
Recall that the exponential distribution function is $F(x) = 1 - \exp(-\lambda x)$,
so the quantile function is $F^{-1}(q) = -\lambda^{-1}\log (1-q)$.
Let $U\sim U(0, 1)$ be a uniformly distributed random variables, then $1-U$ is also uniformly distributed and the random variables
$$
X_1 = -\lambda_1^{-1}\log (1-U), \quad \text{and } X_2 = -\lambda_2^{-1}\log (U)
$$
have the exponential distribution with rate $\lambda_1$ and $\lambda_2$ respectively.
In addition, they are countermonotonic since $X_1 = h_1(U)$ and $X_2 = h_2(U)$, and the functions $h_1(x)=-\lambda_1^{-1}\log (1-x)$ and $h_2(x)=-\lambda_1^{-1}\log (x)$ are respectively increasing and deacreasing.
Now, let's compute the correlation of $X_1$ and $X_2$. By the properties of the exponential distribution we have ${\rm E}(X_1) = \lambda_1^{-1}$, ${\rm E}(X_2) = \lambda_2^{-1}$, ${\rm var}(X_1) = \lambda_1^{-2}$, and ${\rm var}(X_2) = \lambda_2^{-2}$. Also, we have
\begin{align}
{\rm E}(X_1 X_2)
&= \lambda_1^{-1} \lambda_2^{-1} {\rm E}\{\log (1-U) \log (U)\}\\
&= \lambda_1^{-1} \lambda_2^{-1} \int_0^1 \log (1-u) \log (u) f_U(u) {\rm d}u \\
&= \lambda_1^{-1} \lambda_2^{-1} \int_0^1 \log (1-u) \log (u) {\rm d}u \\
&= \lambda_1^{-1} \lambda_2^{-1} \left (2 - \frac{\pi^2}{6} \right ),
\end{align}
where $f_U(u) \equiv 1$ is the density function of the standard uniform distribution.
For the last equality I relied on WolframAlpha.
Thus,
\begin{align}
\rho_{\min}
&= {\rm corr}(X_1, X_2)\\
&= \frac{ \lambda_1^{-1} \lambda_2^{-1} (2 - \pi^2/6 ) - \lambda_1^{-1} \lambda_2^{-1}}{ \sqrt{\lambda_1^{-2} \lambda_2^{-2}} } \\
&= 1 - \pi^2/6 \approx −0.645.
\end{align}
Note that the lower bound doesn't depend on the rates $\lambda_1$ and $\lambda_2$, and that the correlation never reaches $-1$, even when both margins are equal (i.e., when $\lambda_1 = \lambda_2$).
Upper bound
To determine of the upper bound $\rho_{\max}$ we follow a similar approach with a pair of comonotonic exponential variables.
Now, let $X_1 = g_1(U)$ and $X_2 = g_2(U)$ where
$g_1(x)=-\lambda_1^{-1}\log (1-x)$ and $g_2(x)=-\lambda_2^{-1}\log (1-x)$,
which are both increasing functions. So, these random variables are comonotonic and both exponentialy distributed with rates $\lambda_1$ and $\lambda_2$.
We have
\begin{align}
{\rm E}(X_1 X_2)
&= \lambda_1^{-1} \lambda_2^{-1} {\rm E}\{\log (1-U) \log (1-U)\}\\
&= \lambda_1^{-1} \lambda_2^{-1} \int_0^1 \left\{\log (1-u) \right\}^2 {\rm d}u \\
&= 2 \lambda_1^{-1} \lambda_2^{-1} ,
\end{align}
and thus,
\begin{align}
\rho_{\max}
&= {\rm corr}(X_1, X_2)\\
&= \frac{ 2\lambda_1^{-1} \lambda_2^{-1} - \lambda_1^{-1} \lambda_2^{-1}}{ \sqrt{\lambda_1^{-2} \lambda_2^{-2}} } \\
&= 1 .
\end{align}
Similarly to the lower bound, the upper bound doesn't depend on the rates $\lambda_1$ and $\lambda_2$. | Attainable correlations for exponential random variables
Let $\rho_{\min}$ (resp. $\rho_{\max}$) denote the lower (resp. upper) bound of the attainable correlation between $X_1$ and $X_2$.
The bounds $\rho_{\min}$ and $\rho_{\max}$ are reached when $X_1$ an |
24,267 | Covariance matrix for Gaussian Process and Wishart distribution | What is mixed up is the covariance specification in terms of the ambient space on which the Gaussian process is defined, and the operation that transforms a finite dimensional Gaussian random variable to yield a Wishart distribution.
If $\mathbf{X} \sim \mathcal{N}(0, \Sigma)$ is a $p$-dimensional Gaussian random variable (a column vector)
with mean 0 and covariance matrix $\Sigma$, the distribution of $\mathbf{W} = \mathbf{X} \mathbf{X}^T$ is a Wishart distribution $W_p(\Sigma, 1)$. Note that $\mathbf{W}$ is a $p \times p$ matrix. This is a general result about how the quadratic form
$$\mathbf{x} \mapsto \mathbf{x} \mathbf{x}^T$$
transforms a Gaussian distribution to a Wishart distribution. It holds for any choice of positive definite covariance matrix $\Sigma$. If you have i.i.d. observations $\mathbf{X}_1, \ldots, \mathbf{X}_n$ then with $\mathbf{W}_i = \mathbf{X}_i \mathbf{X}_i^T$ the distribution of
$$\mathbf{W}_{1} + \ldots + \mathbf{W}_n$$
is a Wishart $W_p(\Sigma, n)$-distribution. Dividing by $n$ we get the empirical covariance matrix $-$ an estimate of $\Sigma$.
For Gaussian processes there is an ambient space, lets say for illustration that it is $\mathbb{R}$, such that the random variables considered are indexed by elements in the ambient space. That is, we consider a process $(X(x))_{x \in \mathbb{R}}$. It is Gaussian (and for simplicity, here with mean 0) if its finite dimensional marginal distributions are Gaussian, that is, if
$$\mathbf{X}(x_1, \ldots, x_p) := (X(x_1), \ldots, X(x_p))^T \sim \mathcal{N}(0, \Sigma(x_1, \ldots, x_p))$$
for all $x_1, \ldots, x_p \in \mathbb{R}$. The choice of covariance function, as mentioned by the OP, determines the covariance matrix, that is,
$$\text{cov}(X(x_i), X(x_j)) = \Sigma(x_1, \ldots, x_p)_{i,j} = K(x_i, x_j).$$
Disregarding the choice of $K$ the distribution of
$$\mathbf{X}(x_1, \ldots, x_p) \mathbf{X}(x_1, \ldots, x_p)^T$$
will be a Wishart $W_p(\Sigma(x_1, \ldots, x_p), 1)$-distribution. | Covariance matrix for Gaussian Process and Wishart distribution | What is mixed up is the covariance specification in terms of the ambient space on which the Gaussian process is defined, and the operation that transforms a finite dimensional Gaussian random variable | Covariance matrix for Gaussian Process and Wishart distribution
What is mixed up is the covariance specification in terms of the ambient space on which the Gaussian process is defined, and the operation that transforms a finite dimensional Gaussian random variable to yield a Wishart distribution.
If $\mathbf{X} \sim \mathcal{N}(0, \Sigma)$ is a $p$-dimensional Gaussian random variable (a column vector)
with mean 0 and covariance matrix $\Sigma$, the distribution of $\mathbf{W} = \mathbf{X} \mathbf{X}^T$ is a Wishart distribution $W_p(\Sigma, 1)$. Note that $\mathbf{W}$ is a $p \times p$ matrix. This is a general result about how the quadratic form
$$\mathbf{x} \mapsto \mathbf{x} \mathbf{x}^T$$
transforms a Gaussian distribution to a Wishart distribution. It holds for any choice of positive definite covariance matrix $\Sigma$. If you have i.i.d. observations $\mathbf{X}_1, \ldots, \mathbf{X}_n$ then with $\mathbf{W}_i = \mathbf{X}_i \mathbf{X}_i^T$ the distribution of
$$\mathbf{W}_{1} + \ldots + \mathbf{W}_n$$
is a Wishart $W_p(\Sigma, n)$-distribution. Dividing by $n$ we get the empirical covariance matrix $-$ an estimate of $\Sigma$.
For Gaussian processes there is an ambient space, lets say for illustration that it is $\mathbb{R}$, such that the random variables considered are indexed by elements in the ambient space. That is, we consider a process $(X(x))_{x \in \mathbb{R}}$. It is Gaussian (and for simplicity, here with mean 0) if its finite dimensional marginal distributions are Gaussian, that is, if
$$\mathbf{X}(x_1, \ldots, x_p) := (X(x_1), \ldots, X(x_p))^T \sim \mathcal{N}(0, \Sigma(x_1, \ldots, x_p))$$
for all $x_1, \ldots, x_p \in \mathbb{R}$. The choice of covariance function, as mentioned by the OP, determines the covariance matrix, that is,
$$\text{cov}(X(x_i), X(x_j)) = \Sigma(x_1, \ldots, x_p)_{i,j} = K(x_i, x_j).$$
Disregarding the choice of $K$ the distribution of
$$\mathbf{X}(x_1, \ldots, x_p) \mathbf{X}(x_1, \ldots, x_p)^T$$
will be a Wishart $W_p(\Sigma(x_1, \ldots, x_p), 1)$-distribution. | Covariance matrix for Gaussian Process and Wishart distribution
What is mixed up is the covariance specification in terms of the ambient space on which the Gaussian process is defined, and the operation that transforms a finite dimensional Gaussian random variable |
24,268 | Specifying the Error() term in repeated measures ANOVA in R | It would be
radpos.aov <- aov(WD ~ Species*Radialposition + Error(Individual/(Radialposition)), data=Radpos)
summary(radpos.aov, type=3)
That accounts for the within subject error of Radialposition. If you have other within-subject factors, throw them in (in an interaction) with Radialposition in the Error denominator, like + Error(Individual/(Radialpostion*wiFactorA)). That's my understanding of it. That matches up with SPSS's repeated measures GLM if you have no missing data. | Specifying the Error() term in repeated measures ANOVA in R | It would be
radpos.aov <- aov(WD ~ Species*Radialposition + Error(Individual/(Radialposition)), data=Radpos)
summary(radpos.aov, type=3)
That accounts for the within subject error of Radialposition | Specifying the Error() term in repeated measures ANOVA in R
It would be
radpos.aov <- aov(WD ~ Species*Radialposition + Error(Individual/(Radialposition)), data=Radpos)
summary(radpos.aov, type=3)
That accounts for the within subject error of Radialposition. If you have other within-subject factors, throw them in (in an interaction) with Radialposition in the Error denominator, like + Error(Individual/(Radialpostion*wiFactorA)). That's my understanding of it. That matches up with SPSS's repeated measures GLM if you have no missing data. | Specifying the Error() term in repeated measures ANOVA in R
It would be
radpos.aov <- aov(WD ~ Species*Radialposition + Error(Individual/(Radialposition)), data=Radpos)
summary(radpos.aov, type=3)
That accounts for the within subject error of Radialposition |
24,269 | Sampling with replacement in R randomForest | This does not answer why, but to get around this, one can duplicate the data for the rare class in the training data, and take a stratified sample of the result.
Two drawbacks to this approach, compared with a "natural" oversampling:
the out of bag estimates are no longer meaningful
more resources are required to store the object and take random samples
but it will allow one to build the forest with the desired class ratios. | Sampling with replacement in R randomForest | This does not answer why, but to get around this, one can duplicate the data for the rare class in the training data, and take a stratified sample of the result.
Two drawbacks to this approach, compar | Sampling with replacement in R randomForest
This does not answer why, but to get around this, one can duplicate the data for the rare class in the training data, and take a stratified sample of the result.
Two drawbacks to this approach, compared with a "natural" oversampling:
the out of bag estimates are no longer meaningful
more resources are required to store the object and take random samples
but it will allow one to build the forest with the desired class ratios. | Sampling with replacement in R randomForest
This does not answer why, but to get around this, one can duplicate the data for the rare class in the training data, and take a stratified sample of the result.
Two drawbacks to this approach, compar |
24,270 | Sampling with replacement in R randomForest | I have the exact same question and found this in the changelog for randomForest:
Changes in 4.1-0:
In randomForest(), if sampsize is given, the sampling is now done
without replacement, in addition to stratified by class. Therefore
sampsize can not be larger than the class frequencies.
Setting replace=TRUE manually also does not seem to override this. | Sampling with replacement in R randomForest | I have the exact same question and found this in the changelog for randomForest:
Changes in 4.1-0:
In randomForest(), if sampsize is given, the sampling is now done
without replacement, in addition t | Sampling with replacement in R randomForest
I have the exact same question and found this in the changelog for randomForest:
Changes in 4.1-0:
In randomForest(), if sampsize is given, the sampling is now done
without replacement, in addition to stratified by class. Therefore
sampsize can not be larger than the class frequencies.
Setting replace=TRUE manually also does not seem to override this. | Sampling with replacement in R randomForest
I have the exact same question and found this in the changelog for randomForest:
Changes in 4.1-0:
In randomForest(), if sampsize is given, the sampling is now done
without replacement, in addition t |
24,271 | What do interactions of spline and non-spline terms mean? | +1 for a good, and clearly-stated question. (If you wanted a little more information about polynomials and splines, you might find this helpful, although you seem to have a strong grasp of the topic.) You may also want to read this recent question regarding the interpretation of terms governing the curvature of the relationship between a covariate and a response variable. You will notice that I argue against giving separate interpretations to the different terms, but that it is best to treat them as gestalts. (However not to take too hard a line, I do recognize that you can calculate the location of the apex of the parabola from the betas of the regression model as you note here.) Consistent with my previous answer, I think it is best to interpret all the terms associated with the same underlying variable together. With respect to this specific case, the interaction simply establishes that the shape of the curves differs between the two levels of factor a. | What do interactions of spline and non-spline terms mean? | +1 for a good, and clearly-stated question. (If you wanted a little more information about polynomials and splines, you might find this helpful, although you seem to have a strong grasp of the topic. | What do interactions of spline and non-spline terms mean?
+1 for a good, and clearly-stated question. (If you wanted a little more information about polynomials and splines, you might find this helpful, although you seem to have a strong grasp of the topic.) You may also want to read this recent question regarding the interpretation of terms governing the curvature of the relationship between a covariate and a response variable. You will notice that I argue against giving separate interpretations to the different terms, but that it is best to treat them as gestalts. (However not to take too hard a line, I do recognize that you can calculate the location of the apex of the parabola from the betas of the regression model as you note here.) Consistent with my previous answer, I think it is best to interpret all the terms associated with the same underlying variable together. With respect to this specific case, the interaction simply establishes that the shape of the curves differs between the two levels of factor a. | What do interactions of spline and non-spline terms mean?
+1 for a good, and clearly-stated question. (If you wanted a little more information about polynomials and splines, you might find this helpful, although you seem to have a strong grasp of the topic. |
24,272 | What is a "Unit Information Prior"? | The unit information prior is a data-dependent prior, (typically multivariate Normal) with mean at the MLE, and precision equal to the information provided by one observation. See e.g. this tech report, or this paper for full details. The idea of the UIP is to give a prior that 'lets the data speak for itself'; in most cases the addition of prior that tells you as much as one observation centered where the other data are 'pointing' will have little impact on the subsequent analysis. One of its main uses is in showing that use of BIC corresponds, in large samples, to use of Bayes factors, with UIPs on their parameters.
It's probably also worth noting that many statsticians (including Bayesians) are uncomfortable with the use of Bayes Factors and/or BIC, for many applied problems. | What is a "Unit Information Prior"? | The unit information prior is a data-dependent prior, (typically multivariate Normal) with mean at the MLE, and precision equal to the information provided by one observation. See e.g. this tech repor | What is a "Unit Information Prior"?
The unit information prior is a data-dependent prior, (typically multivariate Normal) with mean at the MLE, and precision equal to the information provided by one observation. See e.g. this tech report, or this paper for full details. The idea of the UIP is to give a prior that 'lets the data speak for itself'; in most cases the addition of prior that tells you as much as one observation centered where the other data are 'pointing' will have little impact on the subsequent analysis. One of its main uses is in showing that use of BIC corresponds, in large samples, to use of Bayes factors, with UIPs on their parameters.
It's probably also worth noting that many statsticians (including Bayesians) are uncomfortable with the use of Bayes Factors and/or BIC, for many applied problems. | What is a "Unit Information Prior"?
The unit information prior is a data-dependent prior, (typically multivariate Normal) with mean at the MLE, and precision equal to the information provided by one observation. See e.g. this tech repor |
24,273 | What is a "Unit Information Prior"? | The unit information prior is based on the following interpretation of conjugacy:
Set up
Normal data: $X^{n}=(X_{1}, \ldots, X_{n})$ with $X_{i} \sim \mathcal{N}( \mu, \sigma^{2})$ with $\mu$ unknown and $\sigma^2$ known. The data can then be sufficiently summarised by the sample mean, which before any datum is seen is distributed according to $\bar{X} \sim \mathcal{N}(\mu, \tfrac{\sigma^{2}}{n} )$.
Normal prior for $\mu$: With $ \mu \sim \mathcal{N} (a, \sigma^{2})$ with the same variance as in the data.
Normal posterior for $\mu$: With $ \mu \sim \mathcal{N} (M, v)$ where $ M=\tfrac{1}{n+1}(a + n \bar{x})$ and $v= \tfrac{\sigma^2}{n+1}$.
Interpretation
Hence, after observing the data $\bar{X}=\bar{x}$, we have a posterior for $\mu$ that concentrates on a convex combination of the observation $\bar{x}$ and what was postulated before the data were observed, that is, $a$. Furthermore, the variance of posterior is then given by $\tfrac{\sigma^{2}}{n+1}$, hence, as if we have $n+1$ observations rather than $n$ compared the sampling distribution of the sample mean. Note, that a sampling distribution is not the same as a posterior distribution. Nonetheless, the posterior kind of looks like it, allowing the data speak for themselves. Hence, with the unit information prior one gets a posterior that is mostly concentrated on the data, $\bar{x}$, and shrunk towards the prior information $a$ as a one-off penalty.
Kass and Wasserman, furthermore, showed that model selection $M_{0}:\mu=a$ versus $M_{1}: \mu \in \mathbf{R}$ with the prior given above can be well approximated with the Schwartz criterion (basically, BIC/2) when $n$ is large.
Some remarks:
The fact BIC approximates a Bayes factor based on a unit information prior, does not imply that we should use a unit information prior to construct a Bayes factor. Jeffreys's (1961) default choice is to use a Cauchy prior on the effect size instead, see also Ly et al. (in press) for an explanation on Jeffreys's choice.
Kass and Wasserman showed that the BIC divided by a constant (that relates the Cauchy to a normal distribution) can still be used as an approximation of the Bayes factor (this time based on a Cauchy prior instead of a normal one).
References
Jeffreys, H. (1961). Theory of Probability. Oxford University Press, Oxford, UK, 3 edition.
Kass, R. E. and Wasserman, L. (1995). "A Reference Bayesian Test for Nested Hypotheses and Its Relationship to the Schwarz Criterion," Journal of the American Statistical Association, 90, 928-934
Ly, A., Verhagen, A. J., & Wagenmakers, E.-J. (in press). Harold Jeffreys’s default Bayes factor hypothesis tests: Explanation, extension, and application in psychology. Journal of Mathematical Psychology. | What is a "Unit Information Prior"? | The unit information prior is based on the following interpretation of conjugacy:
Set up
Normal data: $X^{n}=(X_{1}, \ldots, X_{n})$ with $X_{i} \sim \mathcal{N}( \mu, \sigma^{2})$ with $\mu$ unknown | What is a "Unit Information Prior"?
The unit information prior is based on the following interpretation of conjugacy:
Set up
Normal data: $X^{n}=(X_{1}, \ldots, X_{n})$ with $X_{i} \sim \mathcal{N}( \mu, \sigma^{2})$ with $\mu$ unknown and $\sigma^2$ known. The data can then be sufficiently summarised by the sample mean, which before any datum is seen is distributed according to $\bar{X} \sim \mathcal{N}(\mu, \tfrac{\sigma^{2}}{n} )$.
Normal prior for $\mu$: With $ \mu \sim \mathcal{N} (a, \sigma^{2})$ with the same variance as in the data.
Normal posterior for $\mu$: With $ \mu \sim \mathcal{N} (M, v)$ where $ M=\tfrac{1}{n+1}(a + n \bar{x})$ and $v= \tfrac{\sigma^2}{n+1}$.
Interpretation
Hence, after observing the data $\bar{X}=\bar{x}$, we have a posterior for $\mu$ that concentrates on a convex combination of the observation $\bar{x}$ and what was postulated before the data were observed, that is, $a$. Furthermore, the variance of posterior is then given by $\tfrac{\sigma^{2}}{n+1}$, hence, as if we have $n+1$ observations rather than $n$ compared the sampling distribution of the sample mean. Note, that a sampling distribution is not the same as a posterior distribution. Nonetheless, the posterior kind of looks like it, allowing the data speak for themselves. Hence, with the unit information prior one gets a posterior that is mostly concentrated on the data, $\bar{x}$, and shrunk towards the prior information $a$ as a one-off penalty.
Kass and Wasserman, furthermore, showed that model selection $M_{0}:\mu=a$ versus $M_{1}: \mu \in \mathbf{R}$ with the prior given above can be well approximated with the Schwartz criterion (basically, BIC/2) when $n$ is large.
Some remarks:
The fact BIC approximates a Bayes factor based on a unit information prior, does not imply that we should use a unit information prior to construct a Bayes factor. Jeffreys's (1961) default choice is to use a Cauchy prior on the effect size instead, see also Ly et al. (in press) for an explanation on Jeffreys's choice.
Kass and Wasserman showed that the BIC divided by a constant (that relates the Cauchy to a normal distribution) can still be used as an approximation of the Bayes factor (this time based on a Cauchy prior instead of a normal one).
References
Jeffreys, H. (1961). Theory of Probability. Oxford University Press, Oxford, UK, 3 edition.
Kass, R. E. and Wasserman, L. (1995). "A Reference Bayesian Test for Nested Hypotheses and Its Relationship to the Schwarz Criterion," Journal of the American Statistical Association, 90, 928-934
Ly, A., Verhagen, A. J., & Wagenmakers, E.-J. (in press). Harold Jeffreys’s default Bayes factor hypothesis tests: Explanation, extension, and application in psychology. Journal of Mathematical Psychology. | What is a "Unit Information Prior"?
The unit information prior is based on the following interpretation of conjugacy:
Set up
Normal data: $X^{n}=(X_{1}, \ldots, X_{n})$ with $X_{i} \sim \mathcal{N}( \mu, \sigma^{2})$ with $\mu$ unknown |
24,274 | Does a sparse training set adversely affect an SVM? | Sparsity and linear dependence are two different things. Linear dependence implies that some of the feature vectors are simple multiples of other feature vectors (or the same applied to examples). In the setup you have described I think linear dependence is unlikely (it implies two terms have the same frequency (or multiples thereof) across all documents). Simply having sparse features does not present any problem for the SVM. One way to see this is that you could do a random rotation of the co-ordinate axes, which would leave the problem unchanged and give the same solution, but would make the data completely non-sparse (this is in part how random projections work).
Also it appears that you are talking about the SVM in the primal. Note that if you use the kernel SVM, just because you have a sparse dataset does not mean that the kernel matrix will be sparse. It may, however, be low rank. In that case you can actually take advantage of this fact for more efficient training (see for example Efficient svm training using low-rank kernel representations). | Does a sparse training set adversely affect an SVM? | Sparsity and linear dependence are two different things. Linear dependence implies that some of the feature vectors are simple multiples of other feature vectors (or the same applied to examples). In | Does a sparse training set adversely affect an SVM?
Sparsity and linear dependence are two different things. Linear dependence implies that some of the feature vectors are simple multiples of other feature vectors (or the same applied to examples). In the setup you have described I think linear dependence is unlikely (it implies two terms have the same frequency (or multiples thereof) across all documents). Simply having sparse features does not present any problem for the SVM. One way to see this is that you could do a random rotation of the co-ordinate axes, which would leave the problem unchanged and give the same solution, but would make the data completely non-sparse (this is in part how random projections work).
Also it appears that you are talking about the SVM in the primal. Note that if you use the kernel SVM, just because you have a sparse dataset does not mean that the kernel matrix will be sparse. It may, however, be low rank. In that case you can actually take advantage of this fact for more efficient training (see for example Efficient svm training using low-rank kernel representations). | Does a sparse training set adversely affect an SVM?
Sparsity and linear dependence are two different things. Linear dependence implies that some of the feature vectors are simple multiples of other feature vectors (or the same applied to examples). In |
24,275 | How do I improve my neural network stability? | In general you would get more stability by increasing the number of hidden nodes and using an appropriate weight decay (aka ridge penalty).
Specifically, I would recommend using the caret package to get a better understanding of your accuracy (and even the uncertainty in your accuracy.) Also in caret is the avNNet that makes an ensemble learner out of multiple neural networks to reduce the effect of the initial seeds. I personally haven't seen huge improvement using avNNet but it could address your original question.
I'd also make sure that your inputs are all properly conditioned. Have you orthogonalized and then re-scaled them? Caret can also do this pre-processing for you via it's pcaNNet function.
Lastly you can consider tossing in some skip layer connections. You need to make sure there are no outliers/leverage points in your data to skew those connections though. | How do I improve my neural network stability? | In general you would get more stability by increasing the number of hidden nodes and using an appropriate weight decay (aka ridge penalty).
Specifically, I would recommend using the caret package to g | How do I improve my neural network stability?
In general you would get more stability by increasing the number of hidden nodes and using an appropriate weight decay (aka ridge penalty).
Specifically, I would recommend using the caret package to get a better understanding of your accuracy (and even the uncertainty in your accuracy.) Also in caret is the avNNet that makes an ensemble learner out of multiple neural networks to reduce the effect of the initial seeds. I personally haven't seen huge improvement using avNNet but it could address your original question.
I'd also make sure that your inputs are all properly conditioned. Have you orthogonalized and then re-scaled them? Caret can also do this pre-processing for you via it's pcaNNet function.
Lastly you can consider tossing in some skip layer connections. You need to make sure there are no outliers/leverage points in your data to skew those connections though. | How do I improve my neural network stability?
In general you would get more stability by increasing the number of hidden nodes and using an appropriate weight decay (aka ridge penalty).
Specifically, I would recommend using the caret package to g |
24,276 | How do I improve my neural network stability? | I haven't worked with R, so I can only give more general tips.
Did you check whether the algorithm converged? One possible explanation might be that the different parameter sets are all somewhere half way to the same optimum.
If the algorithm always converges but to a different local optimum, then there are many heuristics you could try to avoid those. One simple strategy when using stochastic gradient descent (SGD) would be to use smaller batches and larger momentum. The smaller batch sizes effectively introduce some noise into the training which can help escape some local optima. A much more sophisticated strategy would be to initialize the weights using autoencoders. | How do I improve my neural network stability? | I haven't worked with R, so I can only give more general tips.
Did you check whether the algorithm converged? One possible explanation might be that the different parameter sets are all somewhere half | How do I improve my neural network stability?
I haven't worked with R, so I can only give more general tips.
Did you check whether the algorithm converged? One possible explanation might be that the different parameter sets are all somewhere half way to the same optimum.
If the algorithm always converges but to a different local optimum, then there are many heuristics you could try to avoid those. One simple strategy when using stochastic gradient descent (SGD) would be to use smaller batches and larger momentum. The smaller batch sizes effectively introduce some noise into the training which can help escape some local optima. A much more sophisticated strategy would be to initialize the weights using autoencoders. | How do I improve my neural network stability?
I haven't worked with R, so I can only give more general tips.
Did you check whether the algorithm converged? One possible explanation might be that the different parameter sets are all somewhere half |
24,277 | Markov blanket vs normal dependency in a Bayesian network | Your first derivation is correct!
Because we haven't observed "Starts" or "Moves", "Ignition" is independent of "Gas". What you are writing here is just the factorisation of the joint distribution, not how to compute a the probability of a specific node given a set of observations.
What the Markov Blanket says, is that all information about a random variable in a Bayesian network is contained within this set of nodes (parents, children, and parents of children). That is, if we observe ALL OF THESE variables, then our node is independent of all other nodes within the network.
For more information about dependency within a Bayesian network, look up the concept of D-separation. | Markov blanket vs normal dependency in a Bayesian network | Your first derivation is correct!
Because we haven't observed "Starts" or "Moves", "Ignition" is independent of "Gas". What you are writing here is just the factorisation of the joint distribution, no | Markov blanket vs normal dependency in a Bayesian network
Your first derivation is correct!
Because we haven't observed "Starts" or "Moves", "Ignition" is independent of "Gas". What you are writing here is just the factorisation of the joint distribution, not how to compute a the probability of a specific node given a set of observations.
What the Markov Blanket says, is that all information about a random variable in a Bayesian network is contained within this set of nodes (parents, children, and parents of children). That is, if we observe ALL OF THESE variables, then our node is independent of all other nodes within the network.
For more information about dependency within a Bayesian network, look up the concept of D-separation. | Markov blanket vs normal dependency in a Bayesian network
Your first derivation is correct!
Because we haven't observed "Starts" or "Moves", "Ignition" is independent of "Gas". What you are writing here is just the factorisation of the joint distribution, no |
24,278 | Plotting Events on a Timeline in R | The following proposition is surely perfectible:
zucchini <- function(st, en, mingap=1)
{
i <- order(st, en-st);
st <- st[i];
en <- en[i];
last <- r <- 1
while( sum( ok <- (st > (en[last] + mingap)) ) > 0 )
{
last <- which(ok)[1];
r <- append(r, last);
}
if( length(r) == length(st) )
return( list(c = list(st[r], en[r]), n = 1 ));
ne <- zucchini( st[-r], en[-r]);
return(list( c = c(list(st[r], en[r]), ne$c), n = ne$n+1));
}
coliflore <- function(st, en, mingap = 1)
{
zu <- zucchini(st, en, mingap);
plot.new();
plot.window( xlim=c(min(st), max(en)), ylim = c(0, zu$n+1));
box(); axis(1);
for(i in seq(1, 2*zu$n, 2))
{
x1 <- zu$c[[i]];
x2 <- zu$c[[i+1]];
for(j in 1:length(x1))
rect( x1[j], (i+1)/2, x2[j], (i+1)/2+0.5, col="gray", border=NA );
}
}
Application:
> st <- runif(20,0,50)
> en <- st + runif(20, 5,20)
> st
[1] 25.571385 17.074676 4.564936 27.247745 23.832638 11.045469 2.845222
[8] 2.824046 23.319625 19.684993 42.610242 48.185618 47.748637 39.813871
[15] 9.235512 40.299425 13.797027 21.079956 31.638772 24.152991
> en
[1] 35.43667 32.20029 19.37133 44.30378 35.73845 16.63794 11.52551 16.06469
[9] 32.22477 26.05563 49.51284 67.77664 67.27914 49.35472 28.27657 50.49421
[17] 27.29273 37.87611 48.76251 39.89335
> coliflore(st, en)
Happy new year! | Plotting Events on a Timeline in R | The following proposition is surely perfectible:
zucchini <- function(st, en, mingap=1)
{
i <- order(st, en-st);
st <- st[i];
en <- en[i];
last <- r <- 1
while( sum( ok <- (st > (en[last] + | Plotting Events on a Timeline in R
The following proposition is surely perfectible:
zucchini <- function(st, en, mingap=1)
{
i <- order(st, en-st);
st <- st[i];
en <- en[i];
last <- r <- 1
while( sum( ok <- (st > (en[last] + mingap)) ) > 0 )
{
last <- which(ok)[1];
r <- append(r, last);
}
if( length(r) == length(st) )
return( list(c = list(st[r], en[r]), n = 1 ));
ne <- zucchini( st[-r], en[-r]);
return(list( c = c(list(st[r], en[r]), ne$c), n = ne$n+1));
}
coliflore <- function(st, en, mingap = 1)
{
zu <- zucchini(st, en, mingap);
plot.new();
plot.window( xlim=c(min(st), max(en)), ylim = c(0, zu$n+1));
box(); axis(1);
for(i in seq(1, 2*zu$n, 2))
{
x1 <- zu$c[[i]];
x2 <- zu$c[[i+1]];
for(j in 1:length(x1))
rect( x1[j], (i+1)/2, x2[j], (i+1)/2+0.5, col="gray", border=NA );
}
}
Application:
> st <- runif(20,0,50)
> en <- st + runif(20, 5,20)
> st
[1] 25.571385 17.074676 4.564936 27.247745 23.832638 11.045469 2.845222
[8] 2.824046 23.319625 19.684993 42.610242 48.185618 47.748637 39.813871
[15] 9.235512 40.299425 13.797027 21.079956 31.638772 24.152991
> en
[1] 35.43667 32.20029 19.37133 44.30378 35.73845 16.63794 11.52551 16.06469
[9] 32.22477 26.05563 49.51284 67.77664 67.27914 49.35472 28.27657 50.49421
[17] 27.29273 37.87611 48.76251 39.89335
> coliflore(st, en)
Happy new year! | Plotting Events on a Timeline in R
The following proposition is surely perfectible:
zucchini <- function(st, en, mingap=1)
{
i <- order(st, en-st);
st <- st[i];
en <- en[i];
last <- r <- 1
while( sum( ok <- (st > (en[last] + |
24,279 | Which is a better cost function for a random forest tree: Gini index or entropy? | As I found in Introduction to Data Mining by Tan et. al:
Studies have shown that the choice of impurity measure has little effect on the performance of decision tree induction algorithms. This is because many impurity measures are quite consistent with each other [...]. Indeed, the strategy used to prune the tree has a greater impact on the final tree than the choice of impurity measure.
Therefore, you can choose to use Gini index like CART or Entropy like C4.5.
I would use Entropy, more specifically the Gain Ratio of C4.5 because you can easily follow the well-written book by Quinlan: C4.5 Programs for Machine Learning. | Which is a better cost function for a random forest tree: Gini index or entropy? | As I found in Introduction to Data Mining by Tan et. al:
Studies have shown that the choice of impurity measure has little effect on the performance of decision tree induction algorithms. This is bec | Which is a better cost function for a random forest tree: Gini index or entropy?
As I found in Introduction to Data Mining by Tan et. al:
Studies have shown that the choice of impurity measure has little effect on the performance of decision tree induction algorithms. This is because many impurity measures are quite consistent with each other [...]. Indeed, the strategy used to prune the tree has a greater impact on the final tree than the choice of impurity measure.
Therefore, you can choose to use Gini index like CART or Entropy like C4.5.
I would use Entropy, more specifically the Gain Ratio of C4.5 because you can easily follow the well-written book by Quinlan: C4.5 Programs for Machine Learning. | Which is a better cost function for a random forest tree: Gini index or entropy?
As I found in Introduction to Data Mining by Tan et. al:
Studies have shown that the choice of impurity measure has little effect on the performance of decision tree induction algorithms. This is bec |
24,280 | Difference in implementation of binary splits in decision trees | In fact there are two types of factors -- ordered (like Tiny < Small < Medium < Big < Huge) and unordered (Cucumber, Carrot, Fennel, Aubergine).
First class is the same as continuous ones -- there is only easier to check all pivots, there is also no problem with extending levels list.
For the second class, you have to make a set of elements that will be directed in one branch, leaving the rest into the other -- in this case you can either:
throw error
assume that unseen class goes into your favorite branch
treat this as NA and select branch in more-less random way.
Now, direct treating of unordered factors is tricky so many algorithms "cheat" and claim unordered factors as ordered ones, so they don't even touch this problem*. The rest usually use int mask, i.e. optimize an integer number from $1$ to $2^{\text{#categories}-1}-1$ and treat $i$-th bit as a branch selection for a factor level $i$. (Ever wondered why there is frequent limit to 32 levels?) In this setting, it is quite natural that unseen levels go silently into "0" branch. Yet this does not seem too "right", because why really should we do this? And what about the number of levels required to entropy leverage in attribute selection?
I would say the the most sensible idea is to make the user define the full set of factors (for instance R does this organically, preserving levels through subset operations) and use option 1. for not-declared levels and option 2. for declared ones. Option 3. may make sense if you already have some NA handling infrastructure.
*) There is also side strategy to do some non-trivial re-coding of levels into numbers, like for instance Breiman encoding -- yet this generates even more problems. | Difference in implementation of binary splits in decision trees | In fact there are two types of factors -- ordered (like Tiny < Small < Medium < Big < Huge) and unordered (Cucumber, Carrot, Fennel, Aubergine).
First class is the same as continuous ones -- there is | Difference in implementation of binary splits in decision trees
In fact there are two types of factors -- ordered (like Tiny < Small < Medium < Big < Huge) and unordered (Cucumber, Carrot, Fennel, Aubergine).
First class is the same as continuous ones -- there is only easier to check all pivots, there is also no problem with extending levels list.
For the second class, you have to make a set of elements that will be directed in one branch, leaving the rest into the other -- in this case you can either:
throw error
assume that unseen class goes into your favorite branch
treat this as NA and select branch in more-less random way.
Now, direct treating of unordered factors is tricky so many algorithms "cheat" and claim unordered factors as ordered ones, so they don't even touch this problem*. The rest usually use int mask, i.e. optimize an integer number from $1$ to $2^{\text{#categories}-1}-1$ and treat $i$-th bit as a branch selection for a factor level $i$. (Ever wondered why there is frequent limit to 32 levels?) In this setting, it is quite natural that unseen levels go silently into "0" branch. Yet this does not seem too "right", because why really should we do this? And what about the number of levels required to entropy leverage in attribute selection?
I would say the the most sensible idea is to make the user define the full set of factors (for instance R does this organically, preserving levels through subset operations) and use option 1. for not-declared levels and option 2. for declared ones. Option 3. may make sense if you already have some NA handling infrastructure.
*) There is also side strategy to do some non-trivial re-coding of levels into numbers, like for instance Breiman encoding -- yet this generates even more problems. | Difference in implementation of binary splits in decision trees
In fact there are two types of factors -- ordered (like Tiny < Small < Medium < Big < Huge) and unordered (Cucumber, Carrot, Fennel, Aubergine).
First class is the same as continuous ones -- there is |
24,281 | Reducing number of levels of unordered categorical predictor variable | How best to do this is going to vary tremendously depending on the task you're performing, so it's impossible to say what will be best in a task-independent way.
There are two easy things to try if your levels are ordinal:
Bin them. E.g., 0 = (0 250), 1 = (251 500), etc. You may want to select the limits so each bin has an equal number of items.
You can also take a log transform of the levels. This will squish the range down.
If the levels are not ordinal you can cluster the levels based on other features/variables in your dataset and substitute the cluster ids for the previous levels. There are as many ways to do this as there are clustering algorithms, so the field is wide open. As I read it, this is what combine.levels() is doing. You could do similarly using kmeans() or prcomp(). (You could/should subsequently train a classifier to predict the clusters for new datapoints.) | Reducing number of levels of unordered categorical predictor variable | How best to do this is going to vary tremendously depending on the task you're performing, so it's impossible to say what will be best in a task-independent way.
There are two easy things to try if yo | Reducing number of levels of unordered categorical predictor variable
How best to do this is going to vary tremendously depending on the task you're performing, so it's impossible to say what will be best in a task-independent way.
There are two easy things to try if your levels are ordinal:
Bin them. E.g., 0 = (0 250), 1 = (251 500), etc. You may want to select the limits so each bin has an equal number of items.
You can also take a log transform of the levels. This will squish the range down.
If the levels are not ordinal you can cluster the levels based on other features/variables in your dataset and substitute the cluster ids for the previous levels. There are as many ways to do this as there are clustering algorithms, so the field is wide open. As I read it, this is what combine.levels() is doing. You could do similarly using kmeans() or prcomp(). (You could/should subsequently train a classifier to predict the clusters for new datapoints.) | Reducing number of levels of unordered categorical predictor variable
How best to do this is going to vary tremendously depending on the task you're performing, so it's impossible to say what will be best in a task-independent way.
There are two easy things to try if yo |
24,282 | Conditional homoskedasticity vs heteroskedasticity | I will begin by just quoting from Hayashi to help anybody else who would like to comment. I have tried to preserve formatting and original equation numbers.
Begin quote from Hayashi page 126, section 2.6:
Conditional versus Unconditional Homoskedasticity
The conditional homoskedasticity assumption is:
Assumption 2.7 (conditional homoskedasticity):
\begin{align*}
\tag{2.6.1} E(\epsilon_i^2|\mathbf{x}_i)=\sigma^2>0.
\end{align*}
This assumption implies that the unconditional second moment $E(\epsilon_i^2)$ equals $\sigma^2$ by the Law of Total Expectations. To be clear about the distinction between unconditional and conditional homoskedasticity, consider the following example [Example 2.6 (unconditionally homoskedastic but conditionally heteroskedastic errors)...]
End quote.
Some relevant equations from Hayashi pages 11-14 (Section 1.1):
\begin{align*}
\tag{1.1.12} E(\epsilon_i^2|\mathbf{X})=\sigma^2>0 \quad (i=1,2,\ldots,n) \\\
\tag{1.1.17} E(\epsilon_i^2|\mathbf x_i)=\sigma^2>0 \quad (i=1,2,.\ldots,n).
\end{align*}
The subsection "The Classical Regression Model for Random Samples" on page 12 discusses the implications of a sample being iid. Quoting from Hayashi pages 12-13: "The implication of the identical distribution aspect of a random sample is that the joint distribution of $(\epsilon_i,\mathbf x_i)$ does not depend on $i$. So the unconditional second moment $E(\epsilon_i^2)$ is constant across $i$ (this is referred to as unconditional homoskedasticity) and the functional form of the conditional second moment $E(\epsilon_i^2|\mathbf x_i)$ is the same across $i$. However Assumption 1.4---that the value of the conditional second moment is the same across $i$---does not follow. Therefore, Assumption 1.4 remains restrictive for the case of a random sample; without it, the conditional second moment $E(\epsilon_i^2|\mathbf x_i)$ can differ across $i$ through its possible dependence on $\mathbf x_i$. To emphasize the distinction, the restrictions on the conditional second moments, (1.1.12) and (1.1.17), are referred to as conditional homoskedasticity."
[No further quotes from Hayashi, just my understanding after this point.]
I assume the original question was about the above discussion on pages 12-13. In that case, I think the first bullet under "Conditional Homoskedasticity" isn't technically correct (though I understand what you mean): Hayashi says (1.1.17) is "conditional homoskedasticity," and if $E(\epsilon_i^2|\mathbf x_i)=\sigma^2$, then $E(\epsilon_i^2)=E[E(\epsilon_i^2|\mathbf x_i)]=E[\sigma^2]=\sigma^2$, as Hayashi notes on page 126 (that conditional homoskedasticity implies unconditional homoskedasticity by the Law of Total Expectations).
So I think part of the issue may be the interpretation of Hayashi's statements. Conditional homoskedasticity says (1.1.17) even for different $\mathbf x_i$, the variance of $\epsilon_i$ is the same constant $\sigma^2$. Unconditional homoskedasticity is a weaker statement, in that you could have $E(\epsilon_i^2)=\sigma^2$ but $E(\epsilon_i^2|\mathbf x_i)\ne\sigma^2$; Examples 2.6 (page 127) illustrates this. It also perhaps answers the question of the overlap between homo- and heteroskedasticity: it gives an example where there is unconditional homoskedasticity as well as conditional heteroskedasticity.
These are confusing concepts, especially without a lot of experience with conditional expectations/distributions, but hopefully this adds some clarity (and source material for any future discussions). | Conditional homoskedasticity vs heteroskedasticity | I will begin by just quoting from Hayashi to help anybody else who would like to comment. I have tried to preserve formatting and original equation numbers.
Begin quote from Hayashi page 126, section | Conditional homoskedasticity vs heteroskedasticity
I will begin by just quoting from Hayashi to help anybody else who would like to comment. I have tried to preserve formatting and original equation numbers.
Begin quote from Hayashi page 126, section 2.6:
Conditional versus Unconditional Homoskedasticity
The conditional homoskedasticity assumption is:
Assumption 2.7 (conditional homoskedasticity):
\begin{align*}
\tag{2.6.1} E(\epsilon_i^2|\mathbf{x}_i)=\sigma^2>0.
\end{align*}
This assumption implies that the unconditional second moment $E(\epsilon_i^2)$ equals $\sigma^2$ by the Law of Total Expectations. To be clear about the distinction between unconditional and conditional homoskedasticity, consider the following example [Example 2.6 (unconditionally homoskedastic but conditionally heteroskedastic errors)...]
End quote.
Some relevant equations from Hayashi pages 11-14 (Section 1.1):
\begin{align*}
\tag{1.1.12} E(\epsilon_i^2|\mathbf{X})=\sigma^2>0 \quad (i=1,2,\ldots,n) \\\
\tag{1.1.17} E(\epsilon_i^2|\mathbf x_i)=\sigma^2>0 \quad (i=1,2,.\ldots,n).
\end{align*}
The subsection "The Classical Regression Model for Random Samples" on page 12 discusses the implications of a sample being iid. Quoting from Hayashi pages 12-13: "The implication of the identical distribution aspect of a random sample is that the joint distribution of $(\epsilon_i,\mathbf x_i)$ does not depend on $i$. So the unconditional second moment $E(\epsilon_i^2)$ is constant across $i$ (this is referred to as unconditional homoskedasticity) and the functional form of the conditional second moment $E(\epsilon_i^2|\mathbf x_i)$ is the same across $i$. However Assumption 1.4---that the value of the conditional second moment is the same across $i$---does not follow. Therefore, Assumption 1.4 remains restrictive for the case of a random sample; without it, the conditional second moment $E(\epsilon_i^2|\mathbf x_i)$ can differ across $i$ through its possible dependence on $\mathbf x_i$. To emphasize the distinction, the restrictions on the conditional second moments, (1.1.12) and (1.1.17), are referred to as conditional homoskedasticity."
[No further quotes from Hayashi, just my understanding after this point.]
I assume the original question was about the above discussion on pages 12-13. In that case, I think the first bullet under "Conditional Homoskedasticity" isn't technically correct (though I understand what you mean): Hayashi says (1.1.17) is "conditional homoskedasticity," and if $E(\epsilon_i^2|\mathbf x_i)=\sigma^2$, then $E(\epsilon_i^2)=E[E(\epsilon_i^2|\mathbf x_i)]=E[\sigma^2]=\sigma^2$, as Hayashi notes on page 126 (that conditional homoskedasticity implies unconditional homoskedasticity by the Law of Total Expectations).
So I think part of the issue may be the interpretation of Hayashi's statements. Conditional homoskedasticity says (1.1.17) even for different $\mathbf x_i$, the variance of $\epsilon_i$ is the same constant $\sigma^2$. Unconditional homoskedasticity is a weaker statement, in that you could have $E(\epsilon_i^2)=\sigma^2$ but $E(\epsilon_i^2|\mathbf x_i)\ne\sigma^2$; Examples 2.6 (page 127) illustrates this. It also perhaps answers the question of the overlap between homo- and heteroskedasticity: it gives an example where there is unconditional homoskedasticity as well as conditional heteroskedasticity.
These are confusing concepts, especially without a lot of experience with conditional expectations/distributions, but hopefully this adds some clarity (and source material for any future discussions). | Conditional homoskedasticity vs heteroskedasticity
I will begin by just quoting from Hayashi to help anybody else who would like to comment. I have tried to preserve formatting and original equation numbers.
Begin quote from Hayashi page 126, section |
24,283 | Should an SVM grid search show a high-accuracy region with low accuracies around? | The optimal values for the hyper-parameters will be different for different learning taks, you need to tune them separately for every problem.
The reason you don't get a single optimum is becuase both the kernel parameter and the regularisation parameter control the complexity of the model. If C is small you get a smooth model, likewise if the kernel with is broad, you will get a smooth model (as the basis functions are not very local). This means that different combinations of C and the kernel width lead to similarly complex models, with similar performance (which is why you get the diagonal feature in many of the plots you have).
The optimum also depends on the particular sampling of the training set. It is possible to over-fit the cross-validation error, so choosing the hyper-parameters by cross-validation can actually make performance worse if you are unlucky. See Cawley and Talbot for some discussion of this.
The fact that there is a broad plateau of values for the hyper-parameters where you get similarly good values is actually a good feature of support vector machines as it suggests that they are not overly vulnerable to over-fitting in model selection. If you had a sharp peak at the optimal values, that would be a bad thing as the peak would be difficult to find using a finite dataset which would provide an unreliable indication of where that peak actually resides. | Should an SVM grid search show a high-accuracy region with low accuracies around? | The optimal values for the hyper-parameters will be different for different learning taks, you need to tune them separately for every problem.
The reason you don't get a single optimum is becuase both | Should an SVM grid search show a high-accuracy region with low accuracies around?
The optimal values for the hyper-parameters will be different for different learning taks, you need to tune them separately for every problem.
The reason you don't get a single optimum is becuase both the kernel parameter and the regularisation parameter control the complexity of the model. If C is small you get a smooth model, likewise if the kernel with is broad, you will get a smooth model (as the basis functions are not very local). This means that different combinations of C and the kernel width lead to similarly complex models, with similar performance (which is why you get the diagonal feature in many of the plots you have).
The optimum also depends on the particular sampling of the training set. It is possible to over-fit the cross-validation error, so choosing the hyper-parameters by cross-validation can actually make performance worse if you are unlucky. See Cawley and Talbot for some discussion of this.
The fact that there is a broad plateau of values for the hyper-parameters where you get similarly good values is actually a good feature of support vector machines as it suggests that they are not overly vulnerable to over-fitting in model selection. If you had a sharp peak at the optimal values, that would be a bad thing as the peak would be difficult to find using a finite dataset which would provide an unreliable indication of where that peak actually resides. | Should an SVM grid search show a high-accuracy region with low accuracies around?
The optimal values for the hyper-parameters will be different for different learning taks, you need to tune them separately for every problem.
The reason you don't get a single optimum is becuase both |
24,284 | Test which distribution has a "longer tail" | The essential features of this question are:
It does not make strong distributional assumptions, lending it a non-parametric flavor.
It concerns only tail behavior, not the entire distribution.
With some diffidence--because I have not studied my proposal theoretically to fully understand its performance--I will outline an approach that might be practicable. It borrows from the concepts behind the Kolmogorov-Smirnov test, familiar rank-based non-parametric tests, and exploratory data analysis methods.
Let's begin by visualizing the problem. We may plot the empirical distribution functions of the datasets on common axes to compare them:
The black curve shows dataset $A$ (here with $m=50$ values) and the red curve shows dataset $B$ (here with $n=100$ values). The height of a curve at a value $x$ shows the proportion of the dataset with values less than or equal to $x.$
This is a situation where data in the upper half of $A$ consistently exceed the data in the upper half of $B.$ We can see that because, scanning from left to right (low values to high values), the curves last cross around a height of $0.5$ and after that, the curve for $A$ (black) remains to the right of -- that is, at higher values than -- the curve for $B$ (red). That's evidence for a heavier right tail in the distribution from which data $A$ are drawn.
We need a test statistic. It must be a way of somehow quantifying whether and by how much $A$ has a "heavier right tail" than $B.$ My proposal is this:
Combine the two datasets into a dataset of $n+m$ values.
Rank them: this assigns the value $n+m$ to the highest, $n+m-1$ to the next highest, and so on down to the value $1$ for the lowest.
Weight the ranks as follows:
Divide the ranks for $A$ by $m$ and the ranks for $B$ by $n.$
Negate the results for $B.$
Accumulate these values (in a cumulative sum), beginning with the largest rank and moving on down.
Optionally, normalize the cumulative sum by multiplying all its values by some constant.
Using the ranks (rather than constant values of $1,$ which is another option) weights the highest values where we want to focus attention. This algorithm creates a running sum that goes up when a value from $A$ appears and (due to the negation) goes down when a value from $B$ appears. If there's no real difference in their tails, this random walk should bounce up and down around zero. (This is a consequence of the weighting by $1/m$ and $1/n.$) If one of the tails is heavier, the random walk should initially trend upwards for a heavier $A$ tail and otherwise head downwards for a heavier $B$ tail.
This provides a nice diagnostic plot. In the figure I have normalized the cumulative sum by multiplying all values by $1/\sqrt{n+m+1}$ and indexing them by the numbers $q = 0/(m+n), 1/(m+n), \ldots, (m+n-1)/(m+n).$ I call this the "cranksum" (cumulative rank sum). Here is the first half, corresponding to the upper half of all the data:
There is a clear upward trend, consistent with what we saw in the previous figure. But is it significant?
A simulation of the cranksums under the null hypothesis (of equally heavy tails) will settle this question. Such a simulation creates many datasets of the same sizes as the original $A$ and $B$ (or, almost equivalently, creates many arbitrary permutations of the combined dataset) according to the same distribution (which distribution it is doesn't matter, provided it is continuous); computes their cranksums; and plots them. Here are the first thousand out of 40,000 that I made for datasets of size $50$ and $100:$
The faint gray jagged curves in the middle form the assemblage of a thousand cranksum plots. The yellow area, bounded in bold curves (the "envelope"), outlines the upper $99.25$ and lower $0.75$ percentiles of all 40,000 values. Why these percentiles? Because some analysis of these simulated data showed that only 5% of the simulated curves ever, at some point, go past these boundaries. Thus, because the cranksum plot for the actual data does exceed the upper boundary for some of the initial (low) values of $q,$ it constitutes significant evidence at the $\alpha=0.05$ level that (1) the tails differ and (2) the tail of $A$ is heavier than the tail of $B.$
Of course you can see much more in the plot: the cranksum for our data is extremely high for all values of $q$ between $0$ and $0.23,$ approximately, and only then starts dropping, eventually reaching a height of $0$ around $q=0.5.$ Thus it is apparent that at least the upper $23\%$ of the underlying distribution of data set $A$ consistently exceeds the upper $23\%$ of the underlying distribution for dataset $B$ and likely the upper $50\%$ of ... $A$ exceeds the upper $50\%$ of ... $B.$
(Because these are synthetic data, I know their underlying distributions, so I can compute that for this example the CDFs cross at $x=1.2149$ at a height of $0.6515,$ implying the upper $34.85\%$ of the distribution for $A$ exceeds that of $B,$ quite in line with what the cranksum analysis is telling us based on the samples.)
Evidently it takes a little work to compute the cranksum and run the simulation, but it can be done efficiently: this simulation took two seconds, for instance. To get you started, I have appended the R code used to make the figures.
#
# Testing whether one tail is longer than another.
# The return value is the cranksum, a vector of length m+n.
#
cranksum <- function(x, y) {
m <- length(x)
n <- length(y)
i <- order(c(x,y))
scores <- c(rep(1/m, m), rep(-1/n, n)) * rank(c(x,y))
cumsum(scores[rev(i)]) / sqrt(n + m + 1)
}
#
# Create two datasets from two different distributions with the same means.
#
mu <- 0 # Logmean of `x`
sigma <- 1/2 # Log sd of `x`
k <- 20 # Gamma parameter of `y`
set.seed(17)
y <- rgamma(100, k, k/exp(mu + sigma^2/2)) # Gamma data
x <- exp(rnorm(50, mu, sigma)) # Lognormal data.
#
# Plot their ECDFs.
#
plot(ecdf(c(x,y)), cex=0, col="00000000", main="Empirical CDFs")
e.x <- ecdf(x)
curve(e.x(x), add=TRUE, lwd=2, n=1001)
e.y <- ecdf(y)
curve(e.y(x), add=TRUE, col="Red", lwd=2, n=1001)
#
# Simulate the null distribution (assuming no ties).
# Each simulated cranksum is in a column.
#
system.time(sim <- replicate(4e4, cranksum(runif(length(x)), runif(length(y)))))
#
# This alpha was found by trial and error, but that needs to be done only
# once for any given pair of dataset sizes.
#
alpha <- 0.0075
tl <- apply(sim, 1, quantile, probs=c(alpha/2, 1-alpha/2)) # Cranksum envelope
#
# Compute the chances of exceeding the upper envelope or falling beneath the lower.
#
p.upper <- mean(apply(sim > tl[2,], 2, max))
p.lower <- mean(apply(sim < tl[1,], 2, max))
#
# Include the data with the simulation for the purpose of plotting everything together.
#
sim <- cbind(cranksum(x, y), sim)
#
# Plot.
#
q <- seq(0, 1, length.out=dim(sim)[1])
# The plot region:
plot(0:1/2, range(sim), type="n", xlab = "q", ylab = "Value", main="Cranksum Plot")
# The region between the envelopes:
polygon(c(q, rev(q)), c(tl[1,], rev(tl[2,])), border="Black", lwd=2, col="#f8f8e8")
# The cranksum curves themselves:
invisible(apply(sim[, seq.int(min(dim(sim)[2], 1e3))], 2,
function(y) lines(q, y, col="#00000004")))
# The cranksum for the data:
lines(q, sim[,1], col="#e01010", lwd=2)
# A reference axis at y=0:
abline(h=0, col="White") | Test which distribution has a "longer tail" | The essential features of this question are:
It does not make strong distributional assumptions, lending it a non-parametric flavor.
It concerns only tail behavior, not the entire distribution.
With | Test which distribution has a "longer tail"
The essential features of this question are:
It does not make strong distributional assumptions, lending it a non-parametric flavor.
It concerns only tail behavior, not the entire distribution.
With some diffidence--because I have not studied my proposal theoretically to fully understand its performance--I will outline an approach that might be practicable. It borrows from the concepts behind the Kolmogorov-Smirnov test, familiar rank-based non-parametric tests, and exploratory data analysis methods.
Let's begin by visualizing the problem. We may plot the empirical distribution functions of the datasets on common axes to compare them:
The black curve shows dataset $A$ (here with $m=50$ values) and the red curve shows dataset $B$ (here with $n=100$ values). The height of a curve at a value $x$ shows the proportion of the dataset with values less than or equal to $x.$
This is a situation where data in the upper half of $A$ consistently exceed the data in the upper half of $B.$ We can see that because, scanning from left to right (low values to high values), the curves last cross around a height of $0.5$ and after that, the curve for $A$ (black) remains to the right of -- that is, at higher values than -- the curve for $B$ (red). That's evidence for a heavier right tail in the distribution from which data $A$ are drawn.
We need a test statistic. It must be a way of somehow quantifying whether and by how much $A$ has a "heavier right tail" than $B.$ My proposal is this:
Combine the two datasets into a dataset of $n+m$ values.
Rank them: this assigns the value $n+m$ to the highest, $n+m-1$ to the next highest, and so on down to the value $1$ for the lowest.
Weight the ranks as follows:
Divide the ranks for $A$ by $m$ and the ranks for $B$ by $n.$
Negate the results for $B.$
Accumulate these values (in a cumulative sum), beginning with the largest rank and moving on down.
Optionally, normalize the cumulative sum by multiplying all its values by some constant.
Using the ranks (rather than constant values of $1,$ which is another option) weights the highest values where we want to focus attention. This algorithm creates a running sum that goes up when a value from $A$ appears and (due to the negation) goes down when a value from $B$ appears. If there's no real difference in their tails, this random walk should bounce up and down around zero. (This is a consequence of the weighting by $1/m$ and $1/n.$) If one of the tails is heavier, the random walk should initially trend upwards for a heavier $A$ tail and otherwise head downwards for a heavier $B$ tail.
This provides a nice diagnostic plot. In the figure I have normalized the cumulative sum by multiplying all values by $1/\sqrt{n+m+1}$ and indexing them by the numbers $q = 0/(m+n), 1/(m+n), \ldots, (m+n-1)/(m+n).$ I call this the "cranksum" (cumulative rank sum). Here is the first half, corresponding to the upper half of all the data:
There is a clear upward trend, consistent with what we saw in the previous figure. But is it significant?
A simulation of the cranksums under the null hypothesis (of equally heavy tails) will settle this question. Such a simulation creates many datasets of the same sizes as the original $A$ and $B$ (or, almost equivalently, creates many arbitrary permutations of the combined dataset) according to the same distribution (which distribution it is doesn't matter, provided it is continuous); computes their cranksums; and plots them. Here are the first thousand out of 40,000 that I made for datasets of size $50$ and $100:$
The faint gray jagged curves in the middle form the assemblage of a thousand cranksum plots. The yellow area, bounded in bold curves (the "envelope"), outlines the upper $99.25$ and lower $0.75$ percentiles of all 40,000 values. Why these percentiles? Because some analysis of these simulated data showed that only 5% of the simulated curves ever, at some point, go past these boundaries. Thus, because the cranksum plot for the actual data does exceed the upper boundary for some of the initial (low) values of $q,$ it constitutes significant evidence at the $\alpha=0.05$ level that (1) the tails differ and (2) the tail of $A$ is heavier than the tail of $B.$
Of course you can see much more in the plot: the cranksum for our data is extremely high for all values of $q$ between $0$ and $0.23,$ approximately, and only then starts dropping, eventually reaching a height of $0$ around $q=0.5.$ Thus it is apparent that at least the upper $23\%$ of the underlying distribution of data set $A$ consistently exceeds the upper $23\%$ of the underlying distribution for dataset $B$ and likely the upper $50\%$ of ... $A$ exceeds the upper $50\%$ of ... $B.$
(Because these are synthetic data, I know their underlying distributions, so I can compute that for this example the CDFs cross at $x=1.2149$ at a height of $0.6515,$ implying the upper $34.85\%$ of the distribution for $A$ exceeds that of $B,$ quite in line with what the cranksum analysis is telling us based on the samples.)
Evidently it takes a little work to compute the cranksum and run the simulation, but it can be done efficiently: this simulation took two seconds, for instance. To get you started, I have appended the R code used to make the figures.
#
# Testing whether one tail is longer than another.
# The return value is the cranksum, a vector of length m+n.
#
cranksum <- function(x, y) {
m <- length(x)
n <- length(y)
i <- order(c(x,y))
scores <- c(rep(1/m, m), rep(-1/n, n)) * rank(c(x,y))
cumsum(scores[rev(i)]) / sqrt(n + m + 1)
}
#
# Create two datasets from two different distributions with the same means.
#
mu <- 0 # Logmean of `x`
sigma <- 1/2 # Log sd of `x`
k <- 20 # Gamma parameter of `y`
set.seed(17)
y <- rgamma(100, k, k/exp(mu + sigma^2/2)) # Gamma data
x <- exp(rnorm(50, mu, sigma)) # Lognormal data.
#
# Plot their ECDFs.
#
plot(ecdf(c(x,y)), cex=0, col="00000000", main="Empirical CDFs")
e.x <- ecdf(x)
curve(e.x(x), add=TRUE, lwd=2, n=1001)
e.y <- ecdf(y)
curve(e.y(x), add=TRUE, col="Red", lwd=2, n=1001)
#
# Simulate the null distribution (assuming no ties).
# Each simulated cranksum is in a column.
#
system.time(sim <- replicate(4e4, cranksum(runif(length(x)), runif(length(y)))))
#
# This alpha was found by trial and error, but that needs to be done only
# once for any given pair of dataset sizes.
#
alpha <- 0.0075
tl <- apply(sim, 1, quantile, probs=c(alpha/2, 1-alpha/2)) # Cranksum envelope
#
# Compute the chances of exceeding the upper envelope or falling beneath the lower.
#
p.upper <- mean(apply(sim > tl[2,], 2, max))
p.lower <- mean(apply(sim < tl[1,], 2, max))
#
# Include the data with the simulation for the purpose of plotting everything together.
#
sim <- cbind(cranksum(x, y), sim)
#
# Plot.
#
q <- seq(0, 1, length.out=dim(sim)[1])
# The plot region:
plot(0:1/2, range(sim), type="n", xlab = "q", ylab = "Value", main="Cranksum Plot")
# The region between the envelopes:
polygon(c(q, rev(q)), c(tl[1,], rev(tl[2,])), border="Black", lwd=2, col="#f8f8e8")
# The cranksum curves themselves:
invisible(apply(sim[, seq.int(min(dim(sim)[2], 1e3))], 2,
function(y) lines(q, y, col="#00000004")))
# The cranksum for the data:
lines(q, sim[,1], col="#e01010", lwd=2)
# A reference axis at y=0:
abline(h=0, col="White") | Test which distribution has a "longer tail"
The essential features of this question are:
It does not make strong distributional assumptions, lending it a non-parametric flavor.
It concerns only tail behavior, not the entire distribution.
With |
24,285 | Test which distribution has a "longer tail" | I would suggest to fit different distributions on your observations, and to perform model selection to find the distribution that fits your observations the best. Exponential and Pareto distributions seem to be the best candidates given your hypotheses (positivity, monotone decrease). Once you have fitted these candidates distributions, model selection criteria, such as the Akaike Information Criterion (AIC) or the Bayesian Information Criterion (BIC) will give you a quantitative score for each model. The following paper will propose rules on how to interpret the evidences for the different models based on the BIC :
Kass, Robert E., and Adrian E. Raftery. "Bayes factors." Journal of the american statistical association 90.430 (1995): 773-795.
You may also want to have a look at this paper which deals with model inference of long-tailed distributions :
Okada, Makoto, Kenji Yamanishi, and Naoki Masuda. "Long-tailed distributions of inter-event times as mixtures of exponential distributions." arXiv preprint arXiv:1905.00699 (2019). | Test which distribution has a "longer tail" | I would suggest to fit different distributions on your observations, and to perform model selection to find the distribution that fits your observations the best. Exponential and Pareto distributions | Test which distribution has a "longer tail"
I would suggest to fit different distributions on your observations, and to perform model selection to find the distribution that fits your observations the best. Exponential and Pareto distributions seem to be the best candidates given your hypotheses (positivity, monotone decrease). Once you have fitted these candidates distributions, model selection criteria, such as the Akaike Information Criterion (AIC) or the Bayesian Information Criterion (BIC) will give you a quantitative score for each model. The following paper will propose rules on how to interpret the evidences for the different models based on the BIC :
Kass, Robert E., and Adrian E. Raftery. "Bayes factors." Journal of the american statistical association 90.430 (1995): 773-795.
You may also want to have a look at this paper which deals with model inference of long-tailed distributions :
Okada, Makoto, Kenji Yamanishi, and Naoki Masuda. "Long-tailed distributions of inter-event times as mixtures of exponential distributions." arXiv preprint arXiv:1905.00699 (2019). | Test which distribution has a "longer tail"
I would suggest to fit different distributions on your observations, and to perform model selection to find the distribution that fits your observations the best. Exponential and Pareto distributions |
24,286 | Test which distribution has a "longer tail" | The OP wants a metric for "tail length." While that term is not precisely defined, one might assume that "tail heaviness" is desired. Both Pearson-based and quantile-based kurtosis are measures of tail heaviness. (This useful application of kurtosis has long been unused because of the incorrect notion that kurtosis measures "peakedness" rather than "tail heaviness.") See here https://math.stackexchange.com/questions/3521769/graphic-representation-of-kurtosis-and-skewness/3532888#3532888 for a clear explanation of why Pearson kurtosis measures tail heaviness.
Estimate such a tail heaviness by using the data for each sample, and find the sampling distribution of the difference. Use this sampling distribution to assess (or test, as the OP wants) the "true magnitude" of the difference between the heaviness of the tails. You could use the bootstrap here, although some kinds of parametric or smoothed bootstrap analysis may be more reliable. (Tail heaviness is very difficult to estimate because it is only the rare extreme values in the data (or outliers) that provide the relevant information, and there are by definition very few of such data points.) | Test which distribution has a "longer tail" | The OP wants a metric for "tail length." While that term is not precisely defined, one might assume that "tail heaviness" is desired. Both Pearson-based and quantile-based kurtosis are measures of tai | Test which distribution has a "longer tail"
The OP wants a metric for "tail length." While that term is not precisely defined, one might assume that "tail heaviness" is desired. Both Pearson-based and quantile-based kurtosis are measures of tail heaviness. (This useful application of kurtosis has long been unused because of the incorrect notion that kurtosis measures "peakedness" rather than "tail heaviness.") See here https://math.stackexchange.com/questions/3521769/graphic-representation-of-kurtosis-and-skewness/3532888#3532888 for a clear explanation of why Pearson kurtosis measures tail heaviness.
Estimate such a tail heaviness by using the data for each sample, and find the sampling distribution of the difference. Use this sampling distribution to assess (or test, as the OP wants) the "true magnitude" of the difference between the heaviness of the tails. You could use the bootstrap here, although some kinds of parametric or smoothed bootstrap analysis may be more reliable. (Tail heaviness is very difficult to estimate because it is only the rare extreme values in the data (or outliers) that provide the relevant information, and there are by definition very few of such data points.) | Test which distribution has a "longer tail"
The OP wants a metric for "tail length." While that term is not precisely defined, one might assume that "tail heaviness" is desired. Both Pearson-based and quantile-based kurtosis are measures of tai |
24,287 | How do Bayesians verify their methods using Monte Carlo simulation methods? | I think you see the logical problem in your question. In the frequentist paradigm, it is fine to presume a population truth, generate data, and see if the estimates have good coverage, because that is what they are suppose to do. In the Bayesian paradigm, however, there is no ground truth to generate data from! Bayesians ask the probability of such truths given data, so in simulation we need different truths that give rise to data and then condition on the data. In practice, one ends up simulating the law of conditional probability, which, fortunately, holds always by definition. I take up this exact issue in Rouder, 2014, Psychonomic Bulletin and Review. https://dx.doi.org/10.3758/s13423-014-0595-4 | How do Bayesians verify their methods using Monte Carlo simulation methods? | I think you see the logical problem in your question. In the frequentist paradigm, it is fine to presume a population truth, generate data, and see if the estimates have good coverage, because that i | How do Bayesians verify their methods using Monte Carlo simulation methods?
I think you see the logical problem in your question. In the frequentist paradigm, it is fine to presume a population truth, generate data, and see if the estimates have good coverage, because that is what they are suppose to do. In the Bayesian paradigm, however, there is no ground truth to generate data from! Bayesians ask the probability of such truths given data, so in simulation we need different truths that give rise to data and then condition on the data. In practice, one ends up simulating the law of conditional probability, which, fortunately, holds always by definition. I take up this exact issue in Rouder, 2014, Psychonomic Bulletin and Review. https://dx.doi.org/10.3758/s13423-014-0595-4 | How do Bayesians verify their methods using Monte Carlo simulation methods?
I think you see the logical problem in your question. In the frequentist paradigm, it is fine to presume a population truth, generate data, and see if the estimates have good coverage, because that i |
24,288 | How do Bayesians verify their methods using Monte Carlo simulation methods? | How do Bayesians verify that their methods define uncertainty properly (i.e., calculate valid credible intervals and posterior distributions) using Monte Carlo simulation methods, if probability is not defined as rates in the long run?
I believe the confusion here is about the purpose of simulation methods in Bayesian statistics. The only purpose of Markov Chain Monte Carlo methods such as Gibbs Sampling or Hamiltonian Monte Carlo is to calculate the denominator of Bayes rule.
Of course, there are often other methods available which would make MCMC needless. Some models can be expressed using conjugacy, others through applying a fine grid over the parameter space, yet others can be solved with acceptance-rejection testing. Where MCMC comes in handy is when the integral is ill-behaved.
While I would love to avoid math, that really cannot be avoided. In looking at Bayes rule
$$\pi(\theta|x)=\frac{f(X|\theta)\pi(\theta)}{\int_{\theta\in\Theta}f(X|\theta)\pi(\theta)\mathrm{d}\theta},$$ the numerator is made up of $f(X|\theta)$ and $\pi(\theta)$. $f(X|\theta)$ is a likelihood and not a probability, so it doesn’t sum to one except by chance. The denominator assures us that $\pi(\theta|X)$ sums to one. The goal of MCMC is to determine the bottom number. Note that the bottom number is a constant. It is the expectated likelihood.
The accuracy of that number does determine some but not all parameter estimates. If you were using the maximum a posteriori estimator, then MCMC is an unnecessary step. You should build a hill climbing algorithm instead. On the other hand, it is necessary to determine the posterior mean or an interval. That is because the 95% interval has to be 95% of something and the denominator determines what the scale of that something is.
The goal of MCMC in Bayesian methodologies is to get the Markov chains to converge to the posterior density. That is it. It doesn’t test the validity of anything. It is just an attempt to determine a fixed point value. It is a form of numerical integration. As there is no way to know without letting the algorithm to run to infinity whether all dense regions have been covered, there is some human judgment. The algorithm will have a cutoff when it believes it is done, but that does not mean it is actually done.
In Frequentist methodologies, MCMC is often used to test the reasonableness of a model or to numerically approximate a solution when an analytic one is not available. It serves no similar purpose here.
If I were to write a custom model in Stan, how would I know that what I am doing is legit? How could I use simulation methods to verify that what I'm doing in Stan is actually going to tell me what I want to know?
This question is far more difficult. Stan is a fast algorithm, which means it trades speed for an added risk of inaccuracy. Stan, by construction, will more often be correct than incorrect. There are other algorithms that are designed to search the parameter space widely for local maximums which may be more accurate, but which will be very slow.
What you should do, before using a particular algorithm, is read the literature on that algorithm and look at its functional limitations. Unfortunately, that is usually mathematical work as the only real goal of any non-conjugate method is to estimate $$\int_{\theta\in\Theta}f(X|\theta)\pi(\theta)\mathrm{d}\theta.$$
The second thing you can do is to validate it with an alternative algorithm. The numbers will never match, but if you deem them close enough, then you are fine.
Third, most of the prebuilt packages provide warnings that something may be amiss. If a warning comes up, use something else after investigating the source of the problem, so you do not recreate it in another algorithm.
Fourth, look at your prior density. Imagine you had a prior density of $\Pr(\mu)=\mathcal{N}(7,2^2)$ with $\sigma^2$ known just to simplify it and a likelihood of $\mathcal{N}(25,.1^2)$. At the least, you should be going wow, either I was wrong, the sample was bad, or there is something else going on that I should investigate.
Fifth, and you should do this before you start Stan in the first place, graph out your marginal likelihoods in one or two dimensions. Are there surprises anywhere that may interfere with the algorithm?
Since Bayesians don't define probability as what we see in the long run, how can I use simulation methods to verify than stan_glm is accurately capturing uncertainty? That is, how could I trust that these credible intervals are valid, using simulation methods? And right now, I'm not even defining a prior—how does the inclusion of priors come into play here, since that will affect our measures of uncertainty?
If you do not define a prior, then your model is not valid. If you are not defining a reasonable prior density, then why would you use a Bayesian model? Frequentist models minimize the risk of the maximum loss that could happen from gathering a bad sample. They are very pessimistic and it often takes more information to produce the same result a Bayesian method would.
Nonetheless, that is of no use without using a good prior density. The prior density allows the Bayesian method to minimize the average loss from choosing a bad sample. The information in the prior acts as a weighting scheme so that if some extreme sample is chosen by unfortunate chance, the prior weakens the role that the data plays.
EDIT
I realized I didn't provide one specific answer. It was to the question
How could I use simulation methods to verify that what I'm doing in Stan is actually going to tell me what I want to know?
What makes this question challenging is that in the Bayesian paradigm the fixed points are ,$X$, the sample. In Frequentist methods, the parameters are fixed and thousands of unseen samples are created. On the Bayesian side of the coin, it is the sample which is fixed. You need to simulate thousands of parallel universes.
To see what that may be like, imagine all density functions of a coin toss with an unknown probability $p$ of being heads and $1-p$ of being tails. You observe six heads and two tails. Imagine a small parameter space where $p\in\{1/3,1/2,2/3\}$. Your simulation would consider all the cases where six heads could be obtained over the three objective binomial distributions. The posterior would be the weighted average of each parameter being the true value. Your predictive distribution would be the sum of the weighted binomial distributions.
Of importance to you, it is impossible for the Bayesian prediction to ever be the true distribution. One of the three distributions is the true distribution. The Bayesian methods weight their probability based on the observed value and the prior. The posterior can never be the true distribution, nor the predictive density.
It is asking "what is the probability of seeing six heads and two tails over the set of all possible explanations (parameters, models, etc)."
The Frequentist would assert one of the three choices was the true value by making it the null. Six heads and two tails would falsify $H_0:p=1/3,$ but not the others. If, by chance, you chose the correct one of the three distributions, then you are perfectly correct. Otherwise, you will be wrong.
If you would use simulations to hold a sample fixed, you would find that Stan would perform admirably as Bayes theorem is a mathematical theorem. It is ex-post optimal. All you would find is that the algorithm correctly implemented Bayes theorem up to the natural error level in estimating the denominator.
There are three things you can do. First, you can use model scoring methods for out-of-sample data. Second, you can use a Bayesian model selection or model averaging process. Third, you can treat it as a Frequentist problem and construct the sampling distribution of estimators.
For the first, scoring methods are an entire literature unto itself. You should research them. Bayesian model selection and model averaging treat models as parameters. For model selection, the probability of the models being true is calculated. For model averaging the probability each model is true is calculated and that serves as weighting over the model space. Finally, you can treat it as a Frequentist model.
The last one will be a problem in many standard cases because of the prior. For models with three or more dimensions and a normal distribution, the posterior density will not integrate to unity if the prior density isn't a proper density. In other words, you have to bite the bullet and choose a prior for any model with any real complexity.
The presence of a correctly centered proper prior forces the case where the Bayesian method will be superior to the corresponding Frequentist method due to the improved information. The Bayesian method will win under any reasonable standard. That isn't due to a flaw in the Frequentist method, but the Bayesian method assumes exterior information. The Frequentist method, by only considering the information in the sample, will have less information in it if you have a real prior.
Again, if you do not have a real prior, then why are you using a Bayesian method? | How do Bayesians verify their methods using Monte Carlo simulation methods? | How do Bayesians verify that their methods define uncertainty properly (i.e., calculate valid credible intervals and posterior distributions) using Monte Carlo simulation methods, if probability is no | How do Bayesians verify their methods using Monte Carlo simulation methods?
How do Bayesians verify that their methods define uncertainty properly (i.e., calculate valid credible intervals and posterior distributions) using Monte Carlo simulation methods, if probability is not defined as rates in the long run?
I believe the confusion here is about the purpose of simulation methods in Bayesian statistics. The only purpose of Markov Chain Monte Carlo methods such as Gibbs Sampling or Hamiltonian Monte Carlo is to calculate the denominator of Bayes rule.
Of course, there are often other methods available which would make MCMC needless. Some models can be expressed using conjugacy, others through applying a fine grid over the parameter space, yet others can be solved with acceptance-rejection testing. Where MCMC comes in handy is when the integral is ill-behaved.
While I would love to avoid math, that really cannot be avoided. In looking at Bayes rule
$$\pi(\theta|x)=\frac{f(X|\theta)\pi(\theta)}{\int_{\theta\in\Theta}f(X|\theta)\pi(\theta)\mathrm{d}\theta},$$ the numerator is made up of $f(X|\theta)$ and $\pi(\theta)$. $f(X|\theta)$ is a likelihood and not a probability, so it doesn’t sum to one except by chance. The denominator assures us that $\pi(\theta|X)$ sums to one. The goal of MCMC is to determine the bottom number. Note that the bottom number is a constant. It is the expectated likelihood.
The accuracy of that number does determine some but not all parameter estimates. If you were using the maximum a posteriori estimator, then MCMC is an unnecessary step. You should build a hill climbing algorithm instead. On the other hand, it is necessary to determine the posterior mean or an interval. That is because the 95% interval has to be 95% of something and the denominator determines what the scale of that something is.
The goal of MCMC in Bayesian methodologies is to get the Markov chains to converge to the posterior density. That is it. It doesn’t test the validity of anything. It is just an attempt to determine a fixed point value. It is a form of numerical integration. As there is no way to know without letting the algorithm to run to infinity whether all dense regions have been covered, there is some human judgment. The algorithm will have a cutoff when it believes it is done, but that does not mean it is actually done.
In Frequentist methodologies, MCMC is often used to test the reasonableness of a model or to numerically approximate a solution when an analytic one is not available. It serves no similar purpose here.
If I were to write a custom model in Stan, how would I know that what I am doing is legit? How could I use simulation methods to verify that what I'm doing in Stan is actually going to tell me what I want to know?
This question is far more difficult. Stan is a fast algorithm, which means it trades speed for an added risk of inaccuracy. Stan, by construction, will more often be correct than incorrect. There are other algorithms that are designed to search the parameter space widely for local maximums which may be more accurate, but which will be very slow.
What you should do, before using a particular algorithm, is read the literature on that algorithm and look at its functional limitations. Unfortunately, that is usually mathematical work as the only real goal of any non-conjugate method is to estimate $$\int_{\theta\in\Theta}f(X|\theta)\pi(\theta)\mathrm{d}\theta.$$
The second thing you can do is to validate it with an alternative algorithm. The numbers will never match, but if you deem them close enough, then you are fine.
Third, most of the prebuilt packages provide warnings that something may be amiss. If a warning comes up, use something else after investigating the source of the problem, so you do not recreate it in another algorithm.
Fourth, look at your prior density. Imagine you had a prior density of $\Pr(\mu)=\mathcal{N}(7,2^2)$ with $\sigma^2$ known just to simplify it and a likelihood of $\mathcal{N}(25,.1^2)$. At the least, you should be going wow, either I was wrong, the sample was bad, or there is something else going on that I should investigate.
Fifth, and you should do this before you start Stan in the first place, graph out your marginal likelihoods in one or two dimensions. Are there surprises anywhere that may interfere with the algorithm?
Since Bayesians don't define probability as what we see in the long run, how can I use simulation methods to verify than stan_glm is accurately capturing uncertainty? That is, how could I trust that these credible intervals are valid, using simulation methods? And right now, I'm not even defining a prior—how does the inclusion of priors come into play here, since that will affect our measures of uncertainty?
If you do not define a prior, then your model is not valid. If you are not defining a reasonable prior density, then why would you use a Bayesian model? Frequentist models minimize the risk of the maximum loss that could happen from gathering a bad sample. They are very pessimistic and it often takes more information to produce the same result a Bayesian method would.
Nonetheless, that is of no use without using a good prior density. The prior density allows the Bayesian method to minimize the average loss from choosing a bad sample. The information in the prior acts as a weighting scheme so that if some extreme sample is chosen by unfortunate chance, the prior weakens the role that the data plays.
EDIT
I realized I didn't provide one specific answer. It was to the question
How could I use simulation methods to verify that what I'm doing in Stan is actually going to tell me what I want to know?
What makes this question challenging is that in the Bayesian paradigm the fixed points are ,$X$, the sample. In Frequentist methods, the parameters are fixed and thousands of unseen samples are created. On the Bayesian side of the coin, it is the sample which is fixed. You need to simulate thousands of parallel universes.
To see what that may be like, imagine all density functions of a coin toss with an unknown probability $p$ of being heads and $1-p$ of being tails. You observe six heads and two tails. Imagine a small parameter space where $p\in\{1/3,1/2,2/3\}$. Your simulation would consider all the cases where six heads could be obtained over the three objective binomial distributions. The posterior would be the weighted average of each parameter being the true value. Your predictive distribution would be the sum of the weighted binomial distributions.
Of importance to you, it is impossible for the Bayesian prediction to ever be the true distribution. One of the three distributions is the true distribution. The Bayesian methods weight their probability based on the observed value and the prior. The posterior can never be the true distribution, nor the predictive density.
It is asking "what is the probability of seeing six heads and two tails over the set of all possible explanations (parameters, models, etc)."
The Frequentist would assert one of the three choices was the true value by making it the null. Six heads and two tails would falsify $H_0:p=1/3,$ but not the others. If, by chance, you chose the correct one of the three distributions, then you are perfectly correct. Otherwise, you will be wrong.
If you would use simulations to hold a sample fixed, you would find that Stan would perform admirably as Bayes theorem is a mathematical theorem. It is ex-post optimal. All you would find is that the algorithm correctly implemented Bayes theorem up to the natural error level in estimating the denominator.
There are three things you can do. First, you can use model scoring methods for out-of-sample data. Second, you can use a Bayesian model selection or model averaging process. Third, you can treat it as a Frequentist problem and construct the sampling distribution of estimators.
For the first, scoring methods are an entire literature unto itself. You should research them. Bayesian model selection and model averaging treat models as parameters. For model selection, the probability of the models being true is calculated. For model averaging the probability each model is true is calculated and that serves as weighting over the model space. Finally, you can treat it as a Frequentist model.
The last one will be a problem in many standard cases because of the prior. For models with three or more dimensions and a normal distribution, the posterior density will not integrate to unity if the prior density isn't a proper density. In other words, you have to bite the bullet and choose a prior for any model with any real complexity.
The presence of a correctly centered proper prior forces the case where the Bayesian method will be superior to the corresponding Frequentist method due to the improved information. The Bayesian method will win under any reasonable standard. That isn't due to a flaw in the Frequentist method, but the Bayesian method assumes exterior information. The Frequentist method, by only considering the information in the sample, will have less information in it if you have a real prior.
Again, if you do not have a real prior, then why are you using a Bayesian method? | How do Bayesians verify their methods using Monte Carlo simulation methods?
How do Bayesians verify that their methods define uncertainty properly (i.e., calculate valid credible intervals and posterior distributions) using Monte Carlo simulation methods, if probability is no |
24,289 | Is the optimization of the Gaussian VAE well-posed? | I co-wrote a paper on this exact problem:
https://papers.nips.cc/paper/7642-leveraging-the-exact-likelihood-of-deep-latent-variable-models
We show that, as you thought, maximum-likelihood is ill-posed for Gaussian output VAEs. Things go pretty much like for GMMs. A solution is to constrain the eigenvalues of the covariance network to be bigger than some threshold.
An interesting remark is that, for discrete data, the problem is well-posed. This possibly explains why VAEs are usually benchmarked on discrete data sets (like binary MNIST).
We show all these results in Section 2.1 of our paper.
Similar investigations were also conducted in this paper:
http://www.jmlr.org/papers/volume19/17-704/17-704.pdf
they show (Theorem 5) that the VAE objective is unbounded. This means that, in general, even having the KL term does not make the objective well-posed. | Is the optimization of the Gaussian VAE well-posed? | I co-wrote a paper on this exact problem:
https://papers.nips.cc/paper/7642-leveraging-the-exact-likelihood-of-deep-latent-variable-models
We show that, as you thought, maximum-likelihood is ill-posed | Is the optimization of the Gaussian VAE well-posed?
I co-wrote a paper on this exact problem:
https://papers.nips.cc/paper/7642-leveraging-the-exact-likelihood-of-deep-latent-variable-models
We show that, as you thought, maximum-likelihood is ill-posed for Gaussian output VAEs. Things go pretty much like for GMMs. A solution is to constrain the eigenvalues of the covariance network to be bigger than some threshold.
An interesting remark is that, for discrete data, the problem is well-posed. This possibly explains why VAEs are usually benchmarked on discrete data sets (like binary MNIST).
We show all these results in Section 2.1 of our paper.
Similar investigations were also conducted in this paper:
http://www.jmlr.org/papers/volume19/17-704/17-704.pdf
they show (Theorem 5) that the VAE objective is unbounded. This means that, in general, even having the KL term does not make the objective well-posed. | Is the optimization of the Gaussian VAE well-posed?
I co-wrote a paper on this exact problem:
https://papers.nips.cc/paper/7642-leveraging-the-exact-likelihood-of-deep-latent-variable-models
We show that, as you thought, maximum-likelihood is ill-posed |
24,290 | Is the optimization of the Gaussian VAE well-posed? | I think the KL divergence term keeps the problem well-defined. Intuitively, you can think of it as a "coding cost", where specifying a very narrow posterior distribution is expensive.
Consider the case where you have a single datapoint $x = 0$, and your latent space is 1D with the standard VAE prior $\mathcal{N}(0,1)$. One possible variational posterior would then have $\mu(x) = 0$ and $\sigma(x) = \sigma^*$ for some unknown optimal value of $\sigma^*$. Then the decoder would simply be the identity function.
The loss would be $$
\begin{align*}
E_{z \sim \mathcal{N}(0, \sigma^*)} [\log P(0\mid z)] - \mathcal{D}_{KL}(Q(z\mid X)\parallel P(z))
&= \lambda (\sigma^*)^2 - \left( \log \frac{1}{\sigma^*} + \frac{(\sigma^*)^2}{2} - \frac{1}{2} \right) +c\\
&= \lambda'(\sigma^*)^2 - \log \sigma^* + c' \\
2\lambda' \sigma^*-\frac{1}{\sigma^*} &= 0 \\
\sigma^* &= (2\lambda')^{-\frac{1}{2}}
\end{align*}
$$
where $\lambda$ is proportional to the precision of $P(X|z)$ and $\lambda' = \lambda - \frac{1}{2}$. As long as $\lambda > \frac{1}{2}$, then the KL term prevents the posterior from collapsing. | Is the optimization of the Gaussian VAE well-posed? | I think the KL divergence term keeps the problem well-defined. Intuitively, you can think of it as a "coding cost", where specifying a very narrow posterior distribution is expensive.
Consider the cas | Is the optimization of the Gaussian VAE well-posed?
I think the KL divergence term keeps the problem well-defined. Intuitively, you can think of it as a "coding cost", where specifying a very narrow posterior distribution is expensive.
Consider the case where you have a single datapoint $x = 0$, and your latent space is 1D with the standard VAE prior $\mathcal{N}(0,1)$. One possible variational posterior would then have $\mu(x) = 0$ and $\sigma(x) = \sigma^*$ for some unknown optimal value of $\sigma^*$. Then the decoder would simply be the identity function.
The loss would be $$
\begin{align*}
E_{z \sim \mathcal{N}(0, \sigma^*)} [\log P(0\mid z)] - \mathcal{D}_{KL}(Q(z\mid X)\parallel P(z))
&= \lambda (\sigma^*)^2 - \left( \log \frac{1}{\sigma^*} + \frac{(\sigma^*)^2}{2} - \frac{1}{2} \right) +c\\
&= \lambda'(\sigma^*)^2 - \log \sigma^* + c' \\
2\lambda' \sigma^*-\frac{1}{\sigma^*} &= 0 \\
\sigma^* &= (2\lambda')^{-\frac{1}{2}}
\end{align*}
$$
where $\lambda$ is proportional to the precision of $P(X|z)$ and $\lambda' = \lambda - \frac{1}{2}$. As long as $\lambda > \frac{1}{2}$, then the KL term prevents the posterior from collapsing. | Is the optimization of the Gaussian VAE well-posed?
I think the KL divergence term keeps the problem well-defined. Intuitively, you can think of it as a "coding cost", where specifying a very narrow posterior distribution is expensive.
Consider the cas |
24,291 | Is the optimization of the Gaussian VAE well-posed? | I think the original poster is right, and the problem is not well-posed. When variance goes to 0, the likelihood term explodes to infinity. KL term cannot control the regularize. As a result there is a variance shrinkage problem.
https://arxiv.org/abs/2010.09042 | Is the optimization of the Gaussian VAE well-posed? | I think the original poster is right, and the problem is not well-posed. When variance goes to 0, the likelihood term explodes to infinity. KL term cannot control the regularize. As a result there is | Is the optimization of the Gaussian VAE well-posed?
I think the original poster is right, and the problem is not well-posed. When variance goes to 0, the likelihood term explodes to infinity. KL term cannot control the regularize. As a result there is a variance shrinkage problem.
https://arxiv.org/abs/2010.09042 | Is the optimization of the Gaussian VAE well-posed?
I think the original poster is right, and the problem is not well-posed. When variance goes to 0, the likelihood term explodes to infinity. KL term cannot control the regularize. As a result there is |
24,292 | Regressing Logistic Regression Residuals on other Regressors | In standard multiple linear regression, the ability to fit ordinary-least-squares (OLS) estimates in two-steps comes from the Frisch–Waugh–Lovell theorem. This theorem shows that the estimate of a coefficient for a particular predictor in a multiple linear model is equal to the estimate obtained by regressing the response residuals (residuals from a regression of the response variable against the other explanatory variables) against the predictor residuals (residuals from a regression of the predictor variable against the other explanatory variables). Evidently, you are seeking an analogy to this theorem that can be used in a logistic regression model.
For this question, it is helpful to recall the latent-variable characterisation of logistic regression:
$$Y_i = \mathbb{I}(Y_i^* > 0) \quad \quad \quad Y_i^* = \beta_0 + \beta_X x_i + \beta_Z z_i + \varepsilon_i \quad \quad \quad \varepsilon_i \sim \text{IID Logistic}(0,1).$$
In this characterisation of the model, the latent response variable $Y_i^*$ is unobservable, and instead we observe the indicator $Y_i$ which tells us whether or not the latent response is positive. This form of the model looks similar to multiple linear regression, except that we use a slightly different error distribution (the logistic distribution instead of the normal distribution), and more importantly, we only observe an indicator showing whether or not the latent response is positive.
This creates an issue for any attempt to create a two-step fit of the model. This Frisch-Waugh-Lovell theorem hinges on the ability to obtain intermediate residuals for the response and predictor of interest, taken against the other explanatory variables. In the present case, we can only obtain residuals from a "categorised" response variable. Creating a two-step fitting process for logistic regression would require you to use response residuals from this categorised response variable, without access to the underlying latent response. This seems to me like a major hurdle, and while it does not prove impossibility, it seems unlikely to be possible to fit the model in two steps.
Below I will give you an account of what would be required to find a two-step process to fit a logistic regression. I am not sure if there is a solution to this problem, or if there is a proof of impossibility, but the material here should get you some way towards understanding what is required.
What would a two-step logistic regression fit look like? Suppose we want to construct a two-step fit for a logistic regression model where the parameters are estimated via maximum-likelihood estimation at each step. We want the process to involve an intermediate step that fits the following two models:
$$\begin{matrix}
Y_i = \mathbb{I}(Y_i^{**} > 0) & & & Y_i^{**} = \alpha_0 + \alpha_X x_i + \tau_i & & & \tau_i \sim \text{IID Logistic}(0,1), \\[6pt]
& & & \text{ } \text{ } Z_i = \gamma_0 + \gamma_X x_i + \delta_i & & & \delta_i \sim \text{IID } g. \quad \quad \quad \quad \quad \\
\end{matrix}$$
We estimate the coefficients of these models (via MLEs) and this yields intermediate fitted values $\hat{\alpha}_0, \hat{\alpha}_X, \hat{\gamma}_0, \hat{\gamma}_X$. Then in the second step we fit the model:
$$Y_i = \text{logistic}(\hat{\alpha}_0 + \hat{\alpha}_1 x_i) + \beta_Z (z_i - \hat{\gamma}_0 - \hat{\gamma}_X x_i) + \epsilon_i \quad \quad \quad \epsilon_i \sim \text{IID } f.$$
As specified, the procedure has a lot of fixed elements, but the density functions $g$ and $f$ in these steps are left unspecified (though they should be zero-mean distributions that do not depend on the data). To obtain a two-step fitting method under these constraints we need to choose $g$ and $f$ to ensure that the MLE for $\beta_Z$ in this two-step model-fit algorithm is the same as the MLE obtained from the one-step logistic regression model above.
To see if this is possible, we first write all the estimated parameters from the first step:
$$\begin{equation} \begin{aligned}
\ell_{\mathbf{y}| \mathbf{x}} (\hat{\alpha}_0, \hat{\alpha}_X) &= \underset{\alpha_0, \alpha_X}{\max} \sum_{i=1}^n \ln \text{Bern}(y_i | \text{logistic}(\alpha_0 + \alpha_X x_i)), \\[10pt]
\ell_{\mathbf{z}| \mathbf{x}} (\hat{\gamma}_0, \hat{\gamma}_X) &= \underset{\gamma_0, \gamma_X}{\max} \sum_{i=1}^n \ln g( z_i - \gamma_0 - \gamma_X x_i ).
\end{aligned} \end{equation}$$
Let $\epsilon_i = y_i - \text{logistic}(\hat{\alpha}_0 - \hat{\alpha}_1 x_i) + \beta_Z (z_i - \hat{\gamma}_0 - \hat{\gamma}_X x_i)$ so that the log-likelihood function for the second step is:
$$\ell_{\mathbf{y}|\mathbf{z}|\mathbf{x}}(\beta_Z) = \sum_{i=1}^n \ln f(y_i - \text{logistic}(\hat{\alpha}_0 - \hat{\alpha}_1 x_i) + \beta_Z (z_i - \hat{\gamma}_0 - \hat{\gamma}_X x_i)).$$
We require that the maximising value of this function is the MLE of the multiple logistic regression model. In other words, we require:
$$\underset{\beta_X}{\text{arg max }} \ell_{\mathbf{y}|\mathbf{z}|\mathbf{x}}(\beta_Z) = \underset{\beta_X}{\text{arg max }} \underset{\beta_0, \beta_Z}{\max} \sum_{i=1}^n \ln \text{Bern}(y_i | \text{logistic}(\beta_0 + \beta_X x_i + \beta_Z z_i)).$$
I leave it to others to determine if there is a solution to this problem, or a proof of no solution. I suspect that the "categorisation" of the latent response variable in a logistic regression will make it impossible to find a two-step process. | Regressing Logistic Regression Residuals on other Regressors | In standard multiple linear regression, the ability to fit ordinary-least-squares (OLS) estimates in two-steps comes from the Frisch–Waugh–Lovell theorem. This theorem shows that the estimate of a co | Regressing Logistic Regression Residuals on other Regressors
In standard multiple linear regression, the ability to fit ordinary-least-squares (OLS) estimates in two-steps comes from the Frisch–Waugh–Lovell theorem. This theorem shows that the estimate of a coefficient for a particular predictor in a multiple linear model is equal to the estimate obtained by regressing the response residuals (residuals from a regression of the response variable against the other explanatory variables) against the predictor residuals (residuals from a regression of the predictor variable against the other explanatory variables). Evidently, you are seeking an analogy to this theorem that can be used in a logistic regression model.
For this question, it is helpful to recall the latent-variable characterisation of logistic regression:
$$Y_i = \mathbb{I}(Y_i^* > 0) \quad \quad \quad Y_i^* = \beta_0 + \beta_X x_i + \beta_Z z_i + \varepsilon_i \quad \quad \quad \varepsilon_i \sim \text{IID Logistic}(0,1).$$
In this characterisation of the model, the latent response variable $Y_i^*$ is unobservable, and instead we observe the indicator $Y_i$ which tells us whether or not the latent response is positive. This form of the model looks similar to multiple linear regression, except that we use a slightly different error distribution (the logistic distribution instead of the normal distribution), and more importantly, we only observe an indicator showing whether or not the latent response is positive.
This creates an issue for any attempt to create a two-step fit of the model. This Frisch-Waugh-Lovell theorem hinges on the ability to obtain intermediate residuals for the response and predictor of interest, taken against the other explanatory variables. In the present case, we can only obtain residuals from a "categorised" response variable. Creating a two-step fitting process for logistic regression would require you to use response residuals from this categorised response variable, without access to the underlying latent response. This seems to me like a major hurdle, and while it does not prove impossibility, it seems unlikely to be possible to fit the model in two steps.
Below I will give you an account of what would be required to find a two-step process to fit a logistic regression. I am not sure if there is a solution to this problem, or if there is a proof of impossibility, but the material here should get you some way towards understanding what is required.
What would a two-step logistic regression fit look like? Suppose we want to construct a two-step fit for a logistic regression model where the parameters are estimated via maximum-likelihood estimation at each step. We want the process to involve an intermediate step that fits the following two models:
$$\begin{matrix}
Y_i = \mathbb{I}(Y_i^{**} > 0) & & & Y_i^{**} = \alpha_0 + \alpha_X x_i + \tau_i & & & \tau_i \sim \text{IID Logistic}(0,1), \\[6pt]
& & & \text{ } \text{ } Z_i = \gamma_0 + \gamma_X x_i + \delta_i & & & \delta_i \sim \text{IID } g. \quad \quad \quad \quad \quad \\
\end{matrix}$$
We estimate the coefficients of these models (via MLEs) and this yields intermediate fitted values $\hat{\alpha}_0, \hat{\alpha}_X, \hat{\gamma}_0, \hat{\gamma}_X$. Then in the second step we fit the model:
$$Y_i = \text{logistic}(\hat{\alpha}_0 + \hat{\alpha}_1 x_i) + \beta_Z (z_i - \hat{\gamma}_0 - \hat{\gamma}_X x_i) + \epsilon_i \quad \quad \quad \epsilon_i \sim \text{IID } f.$$
As specified, the procedure has a lot of fixed elements, but the density functions $g$ and $f$ in these steps are left unspecified (though they should be zero-mean distributions that do not depend on the data). To obtain a two-step fitting method under these constraints we need to choose $g$ and $f$ to ensure that the MLE for $\beta_Z$ in this two-step model-fit algorithm is the same as the MLE obtained from the one-step logistic regression model above.
To see if this is possible, we first write all the estimated parameters from the first step:
$$\begin{equation} \begin{aligned}
\ell_{\mathbf{y}| \mathbf{x}} (\hat{\alpha}_0, \hat{\alpha}_X) &= \underset{\alpha_0, \alpha_X}{\max} \sum_{i=1}^n \ln \text{Bern}(y_i | \text{logistic}(\alpha_0 + \alpha_X x_i)), \\[10pt]
\ell_{\mathbf{z}| \mathbf{x}} (\hat{\gamma}_0, \hat{\gamma}_X) &= \underset{\gamma_0, \gamma_X}{\max} \sum_{i=1}^n \ln g( z_i - \gamma_0 - \gamma_X x_i ).
\end{aligned} \end{equation}$$
Let $\epsilon_i = y_i - \text{logistic}(\hat{\alpha}_0 - \hat{\alpha}_1 x_i) + \beta_Z (z_i - \hat{\gamma}_0 - \hat{\gamma}_X x_i)$ so that the log-likelihood function for the second step is:
$$\ell_{\mathbf{y}|\mathbf{z}|\mathbf{x}}(\beta_Z) = \sum_{i=1}^n \ln f(y_i - \text{logistic}(\hat{\alpha}_0 - \hat{\alpha}_1 x_i) + \beta_Z (z_i - \hat{\gamma}_0 - \hat{\gamma}_X x_i)).$$
We require that the maximising value of this function is the MLE of the multiple logistic regression model. In other words, we require:
$$\underset{\beta_X}{\text{arg max }} \ell_{\mathbf{y}|\mathbf{z}|\mathbf{x}}(\beta_Z) = \underset{\beta_X}{\text{arg max }} \underset{\beta_0, \beta_Z}{\max} \sum_{i=1}^n \ln \text{Bern}(y_i | \text{logistic}(\beta_0 + \beta_X x_i + \beta_Z z_i)).$$
I leave it to others to determine if there is a solution to this problem, or a proof of no solution. I suspect that the "categorisation" of the latent response variable in a logistic regression will make it impossible to find a two-step process. | Regressing Logistic Regression Residuals on other Regressors
In standard multiple linear regression, the ability to fit ordinary-least-squares (OLS) estimates in two-steps comes from the Frisch–Waugh–Lovell theorem. This theorem shows that the estimate of a co |
24,293 | Regressing Logistic Regression Residuals on other Regressors | I may be misinterpreting the question. I doubt you can build up the linear regression equation by regression on residuals in the way OP specified. OP's method would only work if the predictors are independent of each other.
To make it work, assume $y$ is the outcome vector, $X$ is the model matrix for the predictors already in the model and you want to include $x_1$. You need to regress the residual of the regression of $y$ on $X$ against the residual of the regression of $x_1$ on $X$ to obtain the OLS coefficient for $x_1$.
Here's a simple example:
set.seed(12345)
n <- 5000
x1 <- rnorm(n)
x2 <- .5 * x1 + rnorm(n) # Correlated predictors
y <- x1 + x2 + rnorm(n)
Fit model with OLS:
coef(lm(y ~ x1 + x2))
(Intercept) x1 x2
0.001653707 1.037426007 0.996259446
Regression on residuals:
coef(lm(residuals(lm(y ~ x1)) ~ x2))
(Intercept) x2
0.001219232 0.818774874
This is wrong, you need to fit:
coef(lm(residuals(lm(y ~ x1)) ~ residuals(lm(x2 ~ x1))))
(Intercept) residuals(lm(x2 ~ x1))
-6.707350e-17 9.962594e-01
Which returns the right coefficient for x2, this aligns with expected differences in y given differences in x2, holding x1 constant (taking it out of both y and x1).
That aside, in logistic regression, it would even be more problematic because logistic regression coefficients suffer from omitted variable bias even in the absence of confounded relations, see here and here, so unless all predictors of the outcome are in the model, one cannot obtain unbiased estimates of the true population parameters. Moreover, I do not know of any residuals from the model that would be amenable to a second logistic regression with all values lying between 0 and 1.
Some references on regression on residuals:
Maxwell, S. E., Delaney, H. D., & Manheimer, J. M. (1985). Anova of Residuals and Ancova: Correcting an Illusion by Using Model Comparisons and Graphs. Journal of Educational Statistics, 10(3), 197–209. Retrieved from http://journals.sagepub.com/doi/pdf/10.3102/10769986010003197
Freckleton, R. P. (2002), On the misuse of residuals in ecology: regression of residuals vs. multiple regression. Journal of Animal Ecology, 71, 542-545. doi:10.1046/j.1365-2656.2002.00618.x | Regressing Logistic Regression Residuals on other Regressors | I may be misinterpreting the question. I doubt you can build up the linear regression equation by regression on residuals in the way OP specified. OP's method would only work if the predictors are ind | Regressing Logistic Regression Residuals on other Regressors
I may be misinterpreting the question. I doubt you can build up the linear regression equation by regression on residuals in the way OP specified. OP's method would only work if the predictors are independent of each other.
To make it work, assume $y$ is the outcome vector, $X$ is the model matrix for the predictors already in the model and you want to include $x_1$. You need to regress the residual of the regression of $y$ on $X$ against the residual of the regression of $x_1$ on $X$ to obtain the OLS coefficient for $x_1$.
Here's a simple example:
set.seed(12345)
n <- 5000
x1 <- rnorm(n)
x2 <- .5 * x1 + rnorm(n) # Correlated predictors
y <- x1 + x2 + rnorm(n)
Fit model with OLS:
coef(lm(y ~ x1 + x2))
(Intercept) x1 x2
0.001653707 1.037426007 0.996259446
Regression on residuals:
coef(lm(residuals(lm(y ~ x1)) ~ x2))
(Intercept) x2
0.001219232 0.818774874
This is wrong, you need to fit:
coef(lm(residuals(lm(y ~ x1)) ~ residuals(lm(x2 ~ x1))))
(Intercept) residuals(lm(x2 ~ x1))
-6.707350e-17 9.962594e-01
Which returns the right coefficient for x2, this aligns with expected differences in y given differences in x2, holding x1 constant (taking it out of both y and x1).
That aside, in logistic regression, it would even be more problematic because logistic regression coefficients suffer from omitted variable bias even in the absence of confounded relations, see here and here, so unless all predictors of the outcome are in the model, one cannot obtain unbiased estimates of the true population parameters. Moreover, I do not know of any residuals from the model that would be amenable to a second logistic regression with all values lying between 0 and 1.
Some references on regression on residuals:
Maxwell, S. E., Delaney, H. D., & Manheimer, J. M. (1985). Anova of Residuals and Ancova: Correcting an Illusion by Using Model Comparisons and Graphs. Journal of Educational Statistics, 10(3), 197–209. Retrieved from http://journals.sagepub.com/doi/pdf/10.3102/10769986010003197
Freckleton, R. P. (2002), On the misuse of residuals in ecology: regression of residuals vs. multiple regression. Journal of Animal Ecology, 71, 542-545. doi:10.1046/j.1365-2656.2002.00618.x | Regressing Logistic Regression Residuals on other Regressors
I may be misinterpreting the question. I doubt you can build up the linear regression equation by regression on residuals in the way OP specified. OP's method would only work if the predictors are ind |
24,294 | Regressing Logistic Regression Residuals on other Regressors | I hope I am not misinterpreting your question, as my answer is going to change somewhat the wording of how you phrased your subject.
I think what you are trying to do is build your regression model by adding one independent variable at a time. And, you do that by observing which prospective variable has the highest correlation with the residual of your first regression between Y and X1. So, the variable with the highest correlation with this first residual will be X2. So, now you have a model with two independent variables X1 & X2. And, you continue this exact process to select X3, X4, etc. This is a stepwise forward process.
You can do the exact same thing with Logistic Regression for the simple reason that Logistic Regression is pretty much an OLS Regression where the dependent variable is the log of the odd (or logit). But, whether Y is a logit or not does not affect the stepwise forward process mentioned above.
OLS minimizes the sum of the square errors to fit the actual data. Logit regression uses a maximum likelihood process that generates a fit that is not all that different than OLS. And, that too (the fitting mechanism) should not affect the stepwise forward process that allows you to build your multiple regression model, whether the latter is an OLS Regression or a Logit Regression. | Regressing Logistic Regression Residuals on other Regressors | I hope I am not misinterpreting your question, as my answer is going to change somewhat the wording of how you phrased your subject.
I think what you are trying to do is build your regression model | Regressing Logistic Regression Residuals on other Regressors
I hope I am not misinterpreting your question, as my answer is going to change somewhat the wording of how you phrased your subject.
I think what you are trying to do is build your regression model by adding one independent variable at a time. And, you do that by observing which prospective variable has the highest correlation with the residual of your first regression between Y and X1. So, the variable with the highest correlation with this first residual will be X2. So, now you have a model with two independent variables X1 & X2. And, you continue this exact process to select X3, X4, etc. This is a stepwise forward process.
You can do the exact same thing with Logistic Regression for the simple reason that Logistic Regression is pretty much an OLS Regression where the dependent variable is the log of the odd (or logit). But, whether Y is a logit or not does not affect the stepwise forward process mentioned above.
OLS minimizes the sum of the square errors to fit the actual data. Logit regression uses a maximum likelihood process that generates a fit that is not all that different than OLS. And, that too (the fitting mechanism) should not affect the stepwise forward process that allows you to build your multiple regression model, whether the latter is an OLS Regression or a Logit Regression. | Regressing Logistic Regression Residuals on other Regressors
I hope I am not misinterpreting your question, as my answer is going to change somewhat the wording of how you phrased your subject.
I think what you are trying to do is build your regression model |
24,295 | Creating an Imbalanced Dataset | Try SMOTE, its an algorithm used for over-sampling. It creates synthetic samples from the class you want over-sampled.
You can use this to create any number of samples you need. | Creating an Imbalanced Dataset | Try SMOTE, its an algorithm used for over-sampling. It creates synthetic samples from the class you want over-sampled.
You can use this to create any number of samples you need. | Creating an Imbalanced Dataset
Try SMOTE, its an algorithm used for over-sampling. It creates synthetic samples from the class you want over-sampled.
You can use this to create any number of samples you need. | Creating an Imbalanced Dataset
Try SMOTE, its an algorithm used for over-sampling. It creates synthetic samples from the class you want over-sampled.
You can use this to create any number of samples you need. |
24,296 | Does k-means have any advantages over HDBSCAN expect for runtime? | Randomization can be valuable. You can run k-means several times to get different possible clusters, as not all may be good. With HDBSCAN, you will always get the same result again.
Classifier: k-means yields an obvious and fast nearest-center classifier to predict the label for new objects. Correctly labeling new objects in HDBSCAN isn't obvious
No noise. Many users don't (want to) know how to handle noise in their data. K-means gives a very simple and easy to understand result: every object belongs to exactly one cluster. With HDBSCAN, objects can belong to 0 clusters, and clusters are actually a tree and not flat.
Performance and approximation. If you have a huge dataset, you can just take a random sample for k-means, and statistics says you'll get almost the same result. For HDBSCAN, it's not clear how to use it only with a subset of the data.
But don't get me wrong. IMHO k-means is very limited, hard to use, and often badly used on inappropriate problems and data. I do admire the HDBSCAN algorithm (and the original DBSCAN and OPTICS). On Geo data, these just work a thousand times better than k-means. K-means is totally overused (because too many classes do not teach anything except k-means), and mini-batch k-means is the worst version of k-means, it does not make sense to use it when your data fits into memory (hence it should be removed from sklearn IMHO). | Does k-means have any advantages over HDBSCAN expect for runtime? | Randomization can be valuable. You can run k-means several times to get different possible clusters, as not all may be good. With HDBSCAN, you will always get the same result again.
Classifier: k-mean | Does k-means have any advantages over HDBSCAN expect for runtime?
Randomization can be valuable. You can run k-means several times to get different possible clusters, as not all may be good. With HDBSCAN, you will always get the same result again.
Classifier: k-means yields an obvious and fast nearest-center classifier to predict the label for new objects. Correctly labeling new objects in HDBSCAN isn't obvious
No noise. Many users don't (want to) know how to handle noise in their data. K-means gives a very simple and easy to understand result: every object belongs to exactly one cluster. With HDBSCAN, objects can belong to 0 clusters, and clusters are actually a tree and not flat.
Performance and approximation. If you have a huge dataset, you can just take a random sample for k-means, and statistics says you'll get almost the same result. For HDBSCAN, it's not clear how to use it only with a subset of the data.
But don't get me wrong. IMHO k-means is very limited, hard to use, and often badly used on inappropriate problems and data. I do admire the HDBSCAN algorithm (and the original DBSCAN and OPTICS). On Geo data, these just work a thousand times better than k-means. K-means is totally overused (because too many classes do not teach anything except k-means), and mini-batch k-means is the worst version of k-means, it does not make sense to use it when your data fits into memory (hence it should be removed from sklearn IMHO). | Does k-means have any advantages over HDBSCAN expect for runtime?
Randomization can be valuable. You can run k-means several times to get different possible clusters, as not all may be good. With HDBSCAN, you will always get the same result again.
Classifier: k-mean |
24,297 | Does k-means have any advantages over HDBSCAN expect for runtime? | Yes, there is an example: The iris dataset is nearly perfectly clustered by k-means regarding its three classes, while hdbscan is most likely not going to be able to recover those three classes. Of course you need to know that there are three classes.
However, I would argue that this task is not what clustering is about - it would be some sort of "unsupervised classification" task which is basically nonsense. However, an unfortunate amount of researcher are evaluating their papers like that (as in "trying if the clustering can recover labels"). The reason is simple: It is inherently difficult to evaluate unsupervised learning - I know, because I am a researcher of clustering myself. So this is an inherently invalid, but simple to understand "evaluation approach". If anyone is interested in more information on that, I can deliver, but I am not sure whether anyone care at this point.
Scientifically speaking there is no "good" or "bad" clustering technique. There are only different techniques following different definitions of what a "cluster" is in the first place. However, the definition that k-means follows is usually not the definition that you want - that is why k-means is usually not the method you want and thus k-means use is limited. The definition is very opinionated. In fact, it looks such that I am not even sure if I would call k-means a clustering method or rather a vector quantization method - as many others have called it as well.
And here we see a very useful application of k-means (and frankly the one I would use k-means for): To tessellate a space. Since k-means is also so very fast, it is very useful for some sort of "multidimensional histogram" or "pre-clustering" for speedups and these sort of things. Unfortunately this often means you want a large "k" and then k-means becomes slow (quadratic runtime), which kind of defeats the purpose. Fortunately, this is where dual trees come into play - they are able to make k-means fast even for large "k". | Does k-means have any advantages over HDBSCAN expect for runtime? | Yes, there is an example: The iris dataset is nearly perfectly clustered by k-means regarding its three classes, while hdbscan is most likely not going to be able to recover those three classes. Of co | Does k-means have any advantages over HDBSCAN expect for runtime?
Yes, there is an example: The iris dataset is nearly perfectly clustered by k-means regarding its three classes, while hdbscan is most likely not going to be able to recover those three classes. Of course you need to know that there are three classes.
However, I would argue that this task is not what clustering is about - it would be some sort of "unsupervised classification" task which is basically nonsense. However, an unfortunate amount of researcher are evaluating their papers like that (as in "trying if the clustering can recover labels"). The reason is simple: It is inherently difficult to evaluate unsupervised learning - I know, because I am a researcher of clustering myself. So this is an inherently invalid, but simple to understand "evaluation approach". If anyone is interested in more information on that, I can deliver, but I am not sure whether anyone care at this point.
Scientifically speaking there is no "good" or "bad" clustering technique. There are only different techniques following different definitions of what a "cluster" is in the first place. However, the definition that k-means follows is usually not the definition that you want - that is why k-means is usually not the method you want and thus k-means use is limited. The definition is very opinionated. In fact, it looks such that I am not even sure if I would call k-means a clustering method or rather a vector quantization method - as many others have called it as well.
And here we see a very useful application of k-means (and frankly the one I would use k-means for): To tessellate a space. Since k-means is also so very fast, it is very useful for some sort of "multidimensional histogram" or "pre-clustering" for speedups and these sort of things. Unfortunately this often means you want a large "k" and then k-means becomes slow (quadratic runtime), which kind of defeats the purpose. Fortunately, this is where dual trees come into play - they are able to make k-means fast even for large "k". | Does k-means have any advantages over HDBSCAN expect for runtime?
Yes, there is an example: The iris dataset is nearly perfectly clustered by k-means regarding its three classes, while hdbscan is most likely not going to be able to recover those three classes. Of co |
24,298 | What is a probability distribution? [duplicate] | "A probability distribution is a specification of the stochastic structure of a random variable." (Gentle, Matrix Algebra, Chapt. 9)
That said, yes, you are correct to assume that in terms of distances in probability theory, the measure $P$ on $A$ is what is called probability measure, or probability distribution law, or probability distribution. (Here $A$ is the set of all measurable subsets of $\Omega$ where $\Omega$ itself is the sample space.) (See, Deza & Deza, Encyclopedia of Distances, Chapt. 14)
Therefore I think the answer to the question "what is a probability distribution" depends on the context of that the phrase is used. For most applied purposes, e.g. "drawing a random variable" from a probability distribution that we associate with our data, using the concept of the variable having a particular PMF/PDF is perfectly adequate; nobody explicitly defines a probability space but just alludes indirectly to it by assuming a particular probability distribution. This is actually what is done computationally too; during random number generation in most cases, either through the inverse CDF of a distribution or through some composite scheme (e.g. rejection sampling) we enforce a particular PMF/PDF in our sample.
Mathematically though, yes, we do need the concept of a measure $P$ on a given space to define a random variable.
There is an excellent thread on why do we need σ
-algebras to define probability spaces? which questions more the mechanism around a probability space. To that extent, Math.SE also has some very relevant topics on the difference between density and distribution [in formal mathematical terms] and the difference between “probability density function” and “probability distribution function”. | What is a probability distribution? [duplicate] | "A probability distribution is a specification of the stochastic structure of a random variable." (Gentle, Matrix Algebra, Chapt. 9)
That said, yes, you are correct to assume that in terms of distance | What is a probability distribution? [duplicate]
"A probability distribution is a specification of the stochastic structure of a random variable." (Gentle, Matrix Algebra, Chapt. 9)
That said, yes, you are correct to assume that in terms of distances in probability theory, the measure $P$ on $A$ is what is called probability measure, or probability distribution law, or probability distribution. (Here $A$ is the set of all measurable subsets of $\Omega$ where $\Omega$ itself is the sample space.) (See, Deza & Deza, Encyclopedia of Distances, Chapt. 14)
Therefore I think the answer to the question "what is a probability distribution" depends on the context of that the phrase is used. For most applied purposes, e.g. "drawing a random variable" from a probability distribution that we associate with our data, using the concept of the variable having a particular PMF/PDF is perfectly adequate; nobody explicitly defines a probability space but just alludes indirectly to it by assuming a particular probability distribution. This is actually what is done computationally too; during random number generation in most cases, either through the inverse CDF of a distribution or through some composite scheme (e.g. rejection sampling) we enforce a particular PMF/PDF in our sample.
Mathematically though, yes, we do need the concept of a measure $P$ on a given space to define a random variable.
There is an excellent thread on why do we need σ
-algebras to define probability spaces? which questions more the mechanism around a probability space. To that extent, Math.SE also has some very relevant topics on the difference between density and distribution [in formal mathematical terms] and the difference between “probability density function” and “probability distribution function”. | What is a probability distribution? [duplicate]
"A probability distribution is a specification of the stochastic structure of a random variable." (Gentle, Matrix Algebra, Chapt. 9)
That said, yes, you are correct to assume that in terms of distance |
24,299 | What is a probability distribution? [duplicate] | A probability distribution $\mathbb{P}$ is defined as a positive measure on a measurable space ${\cal X}$ with $\sigma$-algebra ${\cal A}$ and total mass one, $\mathbb{P}({\cal X})=1$. It is naturally associated with a random variable in that each random variable has a probability distribution and, given a probability distribution, one can always construct a random variable with this probability distribution. To quote Terry Tao's
254A, Notes 0: A review of probability theory, a random variable is a measurable transform from a sample space $\Omega$ endowed with a probability distribution $(\Omega,{\cal B},\mu)$ with $\mu(\Omega)=1$, onto a set ${\cal X}$:
Definition 3 (Random variable) Let $R = (R,{\mathcal R})$ be a measurable space (i.e. a set $R$, equipped with a $\sigma$-algebra of
subsets of ${\mathcal R}$). A random variable taking values in $R$ (or
an $R$-valued random variable) is a measurable map $X$ from the sample
space to $R$, i.e. a function$$X: \Omega \rightarrow R$$such that
$X^{-1}(S)$ is an event for every $S \in {\mathcal R}$.
(although I do not deem the measurability of $R$ necessary to the definition, since ${\mathcal R}=X(\mathcal B)$ is automatically defined as the transformed $\sigma$-algebra). And
Lemma 4 (Creating a random variable with a specified distribution) Let $\mu$ be a probability measure on a measurable space $R =
> (R,{\mathcal R})$. Then (after extending the sample space {\Omega} if
necessary) there exists an $R$-valued random variable $X$ with
distribution $\mu$. | What is a probability distribution? [duplicate] | A probability distribution $\mathbb{P}$ is defined as a positive measure on a measurable space ${\cal X}$ with $\sigma$-algebra ${\cal A}$ and total mass one, $\mathbb{P}({\cal X})=1$. It is naturally | What is a probability distribution? [duplicate]
A probability distribution $\mathbb{P}$ is defined as a positive measure on a measurable space ${\cal X}$ with $\sigma$-algebra ${\cal A}$ and total mass one, $\mathbb{P}({\cal X})=1$. It is naturally associated with a random variable in that each random variable has a probability distribution and, given a probability distribution, one can always construct a random variable with this probability distribution. To quote Terry Tao's
254A, Notes 0: A review of probability theory, a random variable is a measurable transform from a sample space $\Omega$ endowed with a probability distribution $(\Omega,{\cal B},\mu)$ with $\mu(\Omega)=1$, onto a set ${\cal X}$:
Definition 3 (Random variable) Let $R = (R,{\mathcal R})$ be a measurable space (i.e. a set $R$, equipped with a $\sigma$-algebra of
subsets of ${\mathcal R}$). A random variable taking values in $R$ (or
an $R$-valued random variable) is a measurable map $X$ from the sample
space to $R$, i.e. a function$$X: \Omega \rightarrow R$$such that
$X^{-1}(S)$ is an event for every $S \in {\mathcal R}$.
(although I do not deem the measurability of $R$ necessary to the definition, since ${\mathcal R}=X(\mathcal B)$ is automatically defined as the transformed $\sigma$-algebra). And
Lemma 4 (Creating a random variable with a specified distribution) Let $\mu$ be a probability measure on a measurable space $R =
> (R,{\mathcal R})$. Then (after extending the sample space {\Omega} if
necessary) there exists an $R$-valued random variable $X$ with
distribution $\mu$. | What is a probability distribution? [duplicate]
A probability distribution $\mathbb{P}$ is defined as a positive measure on a measurable space ${\cal X}$ with $\sigma$-algebra ${\cal A}$ and total mass one, $\mathbb{P}({\cal X})=1$. It is naturally |
24,300 | How to train an LSTM when the sequence has imbalanced classes | Inversely proportional contributions to cost function
Another way of dealing with imbalanced data is to weight each label's contribution to the cost function inversely proportional to the frequency of the label. In your above example, I count the following frequencies of the classes:
1: 10
2: 7
3: 20
4: 2
So you could multiply the cost on a sample-by-sample basis by $\frac{1}{10}$ when the true label is 1, by $\frac{1}{7}$ for the label 2, $\frac{1}{20}$ for the label 3, and $\frac{1}{2}$ for the label 4. So you'll see 5 times as many 1 labels as 4 labels, but they'll each contribute $\frac{1}{5}^{th}$ as much to your overall cost function. In other words, you can expect each label to have roughly the same impact on your cost function on average.
In practice, I would use the frequencies of the labels across my whole training set, and set the numerator so that the sum of my multipliers is 1. E.g. in the above example, I'd use the fractions $\frac{1.26}{10}$, $\frac{1.26}{7}$, $\frac{1.26}{20}$, $\frac{1.26}{2}$ which add up to ~1. You don't need to scale in this way, but if you don't you are in effect modifying your learning rate.
A danger of using this approach (as with resampling) is the increased chance of overfitting to the rare labels. You'll likely want to regularize your model somehow if you use this kind of approach.
On a practical note, I believe most deep learning libraries offer this functionality. For example, in the python library keras, the keras.models.Model.fit() method has a sample_weight parameter:
sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile().
Lastly, I'll encourage you to make sure you have a good performance metric you trust. Using an approach like this may result in your model estimating your rare labels more often than is actually desirable. As Tim said in a comment:
If something is more common, it is reasonable that it gets predicted more commonly. | How to train an LSTM when the sequence has imbalanced classes | Inversely proportional contributions to cost function
Another way of dealing with imbalanced data is to weight each label's contribution to the cost function inversely proportional to the frequency of | How to train an LSTM when the sequence has imbalanced classes
Inversely proportional contributions to cost function
Another way of dealing with imbalanced data is to weight each label's contribution to the cost function inversely proportional to the frequency of the label. In your above example, I count the following frequencies of the classes:
1: 10
2: 7
3: 20
4: 2
So you could multiply the cost on a sample-by-sample basis by $\frac{1}{10}$ when the true label is 1, by $\frac{1}{7}$ for the label 2, $\frac{1}{20}$ for the label 3, and $\frac{1}{2}$ for the label 4. So you'll see 5 times as many 1 labels as 4 labels, but they'll each contribute $\frac{1}{5}^{th}$ as much to your overall cost function. In other words, you can expect each label to have roughly the same impact on your cost function on average.
In practice, I would use the frequencies of the labels across my whole training set, and set the numerator so that the sum of my multipliers is 1. E.g. in the above example, I'd use the fractions $\frac{1.26}{10}$, $\frac{1.26}{7}$, $\frac{1.26}{20}$, $\frac{1.26}{2}$ which add up to ~1. You don't need to scale in this way, but if you don't you are in effect modifying your learning rate.
A danger of using this approach (as with resampling) is the increased chance of overfitting to the rare labels. You'll likely want to regularize your model somehow if you use this kind of approach.
On a practical note, I believe most deep learning libraries offer this functionality. For example, in the python library keras, the keras.models.Model.fit() method has a sample_weight parameter:
sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile().
Lastly, I'll encourage you to make sure you have a good performance metric you trust. Using an approach like this may result in your model estimating your rare labels more often than is actually desirable. As Tim said in a comment:
If something is more common, it is reasonable that it gets predicted more commonly. | How to train an LSTM when the sequence has imbalanced classes
Inversely proportional contributions to cost function
Another way of dealing with imbalanced data is to weight each label's contribution to the cost function inversely proportional to the frequency of |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.