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 |
|---|---|---|---|---|---|---|
20,201 | Lag order for Granger causality test | The trade-off is between bias and power. Too few lags, you have a biased test because of the residual auto-correlation. Too many, you allow for potentially spurious rejections of the null - some random correlation might make it look like $X$ helps predict $Y$. Whether or not that's a practical concern depends on your data, my guess would be to lean higher, but lag length can always be determined as follows:
Granger causality always has to be tested in the context of some model. In the specific case of the granger.test function in R, the model has p past values of each of the two variables in the bivariate test. So the model it uses is:
$$
y_{i,t}=\alpha+\sum_{l=1}^p \beta_ly_{i,t-l} + \gamma_lx_{i,t-l}+\epsilon_{i,t}
$$
A conventional way to choose $p$ for this model would be to try this regression with various values of $p$ and use keep track of the AIC or BIC for each lag length. Then run the test again using the value of $p$ which had the lowest IC in your regressions.
In general the number of lag in the model can be different for $x$ and $y$ and a Granger test will still be appropriate. It's in the specific case of the implementation of granger.test that your constrained to the same number of lags for both. This is a matter of convenience not a theoretical necessity. With different lag lengths for the two variables, you can still use the AIC or BIC to select your model, you'll just have to compare many combinations $n$ lags of $x$ and $m$ lags of $y$. See this.
Just an extra word - because the Granger test is model dependent, omitted variables bias may be a problem for Granger causality. You may want to include all the variables in your model, and then use Granger causality to exclude blocks of them instead of using the granger.test function which only does pair-wise tests. | Lag order for Granger causality test | The trade-off is between bias and power. Too few lags, you have a biased test because of the residual auto-correlation. Too many, you allow for potentially spurious rejections of the null - some rando | Lag order for Granger causality test
The trade-off is between bias and power. Too few lags, you have a biased test because of the residual auto-correlation. Too many, you allow for potentially spurious rejections of the null - some random correlation might make it look like $X$ helps predict $Y$. Whether or not that's a practical concern depends on your data, my guess would be to lean higher, but lag length can always be determined as follows:
Granger causality always has to be tested in the context of some model. In the specific case of the granger.test function in R, the model has p past values of each of the two variables in the bivariate test. So the model it uses is:
$$
y_{i,t}=\alpha+\sum_{l=1}^p \beta_ly_{i,t-l} + \gamma_lx_{i,t-l}+\epsilon_{i,t}
$$
A conventional way to choose $p$ for this model would be to try this regression with various values of $p$ and use keep track of the AIC or BIC for each lag length. Then run the test again using the value of $p$ which had the lowest IC in your regressions.
In general the number of lag in the model can be different for $x$ and $y$ and a Granger test will still be appropriate. It's in the specific case of the implementation of granger.test that your constrained to the same number of lags for both. This is a matter of convenience not a theoretical necessity. With different lag lengths for the two variables, you can still use the AIC or BIC to select your model, you'll just have to compare many combinations $n$ lags of $x$ and $m$ lags of $y$. See this.
Just an extra word - because the Granger test is model dependent, omitted variables bias may be a problem for Granger causality. You may want to include all the variables in your model, and then use Granger causality to exclude blocks of them instead of using the granger.test function which only does pair-wise tests. | Lag order for Granger causality test
The trade-off is between bias and power. Too few lags, you have a biased test because of the residual auto-correlation. Too many, you allow for potentially spurious rejections of the null - some rando |
20,202 | What does it imply if accuracy and recall are the same? | I suspect that you're measuring the micro-averages of precision, recall and accuracy for your two classes.
If you're doing so instead of considering one class "positive" and the other "negative", you'll always get equal values for Recall and Accuracy, because the values of FP and FN will be always the same (you can check with more details here: http://metaoptimize.com/qa/questions/8284/does-precision-equal-to-recall-for-micro-averaging ) | What does it imply if accuracy and recall are the same? | I suspect that you're measuring the micro-averages of precision, recall and accuracy for your two classes.
If you're doing so instead of considering one class "positive" and the other "negative", you | What does it imply if accuracy and recall are the same?
I suspect that you're measuring the micro-averages of precision, recall and accuracy for your two classes.
If you're doing so instead of considering one class "positive" and the other "negative", you'll always get equal values for Recall and Accuracy, because the values of FP and FN will be always the same (you can check with more details here: http://metaoptimize.com/qa/questions/8284/does-precision-equal-to-recall-for-micro-averaging ) | What does it imply if accuracy and recall are the same?
I suspect that you're measuring the micro-averages of precision, recall and accuracy for your two classes.
If you're doing so instead of considering one class "positive" and the other "negative", you |
20,203 | What does it imply if accuracy and recall are the same? | It might be a coincidence.
If we have to say something about it, then it indicates that sensitivity (a.k.a. recall, or TPR) is equal to specificity (a.k.a. selectivity, or TNR), and thus they are also equal to accuracy. TP / P = TN / N = (TP+TN) / (P+N), where P = TP+FN, N = TN+FP.
This means your model is somehow "balanced", that is, its ability to correctly classify positive samples is same as its ability to correctly classify negative samples.
However, the importance of sensitivity and specificity may vary from case to case, so being "balanced" is not necessarily good. | What does it imply if accuracy and recall are the same? | It might be a coincidence.
If we have to say something about it, then it indicates that sensitivity (a.k.a. recall, or TPR) is equal to specificity (a.k.a. selectivity, or TNR), and thus they are also | What does it imply if accuracy and recall are the same?
It might be a coincidence.
If we have to say something about it, then it indicates that sensitivity (a.k.a. recall, or TPR) is equal to specificity (a.k.a. selectivity, or TNR), and thus they are also equal to accuracy. TP / P = TN / N = (TP+TN) / (P+N), where P = TP+FN, N = TN+FP.
This means your model is somehow "balanced", that is, its ability to correctly classify positive samples is same as its ability to correctly classify negative samples.
However, the importance of sensitivity and specificity may vary from case to case, so being "balanced" is not necessarily good. | What does it imply if accuracy and recall are the same?
It might be a coincidence.
If we have to say something about it, then it indicates that sensitivity (a.k.a. recall, or TPR) is equal to specificity (a.k.a. selectivity, or TNR), and thus they are also |
20,204 | What does it imply if accuracy and recall are the same? | As OP has mentioned, this is just a coincidence. It's highly likely that number of instances in each class is balanced. Recall = TP/P and Acc = (TP + TN)/(P+N), so in your case TP/P = TN/N. This can happen, and is more likely to happen when |P| = |N|
Try following: Print upto 7-8 places of decimal and you may see some difference.
Second try to imbalance the problem. Like set positive class as just 20% of total and let rest be 80%, you should definitely see the difference. | What does it imply if accuracy and recall are the same? | As OP has mentioned, this is just a coincidence. It's highly likely that number of instances in each class is balanced. Recall = TP/P and Acc = (TP + TN)/(P+N), so in your case TP/P = TN/N. This can h | What does it imply if accuracy and recall are the same?
As OP has mentioned, this is just a coincidence. It's highly likely that number of instances in each class is balanced. Recall = TP/P and Acc = (TP + TN)/(P+N), so in your case TP/P = TN/N. This can happen, and is more likely to happen when |P| = |N|
Try following: Print upto 7-8 places of decimal and you may see some difference.
Second try to imbalance the problem. Like set positive class as just 20% of total and let rest be 80%, you should definitely see the difference. | What does it imply if accuracy and recall are the same?
As OP has mentioned, this is just a coincidence. It's highly likely that number of instances in each class is balanced. Recall = TP/P and Acc = (TP + TN)/(P+N), so in your case TP/P = TN/N. This can h |
20,205 | What does it imply if accuracy and recall are the same? | It means TN and FP are close to 0.
Therefore, precision is close to TP/TP=1.
The recall formula doesn't change since neither TP nor FN is close to 0.
Accuracy which is (TP+TN)/(TP+TN+FP+FN) is close to TP/(TP+FN) which is recall.
Having TN and FP close to 0 means that you have an imbalanced dataset with an inverted imbalance compared to the standard for positive and negative. You have very few negative while it is standard to have very few positive when using precision and recall.
Typically, people use precision and recall because TN is extremely common (and makes the accuracy very high) and you don't care much about it. In your case, TP is common and TN is rare. | What does it imply if accuracy and recall are the same? | It means TN and FP are close to 0.
Therefore, precision is close to TP/TP=1.
The recall formula doesn't change since neither TP nor FN is close to 0.
Accuracy which is (TP+TN)/(TP+TN+FP+FN) is close t | What does it imply if accuracy and recall are the same?
It means TN and FP are close to 0.
Therefore, precision is close to TP/TP=1.
The recall formula doesn't change since neither TP nor FN is close to 0.
Accuracy which is (TP+TN)/(TP+TN+FP+FN) is close to TP/(TP+FN) which is recall.
Having TN and FP close to 0 means that you have an imbalanced dataset with an inverted imbalance compared to the standard for positive and negative. You have very few negative while it is standard to have very few positive when using precision and recall.
Typically, people use precision and recall because TN is extremely common (and makes the accuracy very high) and you don't care much about it. In your case, TP is common and TN is rare. | What does it imply if accuracy and recall are the same?
It means TN and FP are close to 0.
Therefore, precision is close to TP/TP=1.
The recall formula doesn't change since neither TP nor FN is close to 0.
Accuracy which is (TP+TN)/(TP+TN+FP+FN) is close t |
20,206 | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused? | I think the best example of this may likely be the controversy around hormone replacement therapy and cardiovascular risk - large cohort epidemiological studies seem to suggest a protective effect and health policy and physician recommendations were made on this information.
Follow-up RCTs then seem to show that there's actually an increased risk of myocardial infarction in women placed on HRT.
This goes back and forth for a bit, and has been used as one of the canonical cases to attack epidemiology as a field, but a recent re-analysis by Hernan seems to propose that the two studies actually don't have discordant results if you make sure you ask the same question. | What are the case studies in public health policy research where unreliable/confounded/invalid studi | I think the best example of this may likely be the controversy around hormone replacement therapy and cardiovascular risk - large cohort epidemiological studies seem to suggest a protective effect and | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused?
I think the best example of this may likely be the controversy around hormone replacement therapy and cardiovascular risk - large cohort epidemiological studies seem to suggest a protective effect and health policy and physician recommendations were made on this information.
Follow-up RCTs then seem to show that there's actually an increased risk of myocardial infarction in women placed on HRT.
This goes back and forth for a bit, and has been used as one of the canonical cases to attack epidemiology as a field, but a recent re-analysis by Hernan seems to propose that the two studies actually don't have discordant results if you make sure you ask the same question. | What are the case studies in public health policy research where unreliable/confounded/invalid studi
I think the best example of this may likely be the controversy around hormone replacement therapy and cardiovascular risk - large cohort epidemiological studies seem to suggest a protective effect and |
20,207 | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused? | A really interesting example I personally like is taken from the book Freakonomics by Steven D. Levitt and Stephen J. Dubner. There is a chapter in the book that discusses correlation vs. causality. Correlation between two statistical variables does not necessarily imply that these variables are statistically dependent, but a mistake along these lines was made by experts. Quoting from the book:
"A tricky beast, Polio was extremely difficult for researchers to pin down. They couldn’t figure out how it was passed or when/how it expressed itself. We have a tendency to remember this time as one in which Polio was ‘epidemic’ when, in fact, it was not affecting large swaths of the population (compared with the more common measles, for example). The reason it was seen as epidemic was because it was so frightening.
What researchers DID manage to determine in their studies was that Polio infection rates went UP in the Summer. They also saw that ICE CREAM CONSUMPTION went up in the Summer. And so they concluded that ice cream consumption led to Polio and for a time ice cream was demonized. " | What are the case studies in public health policy research where unreliable/confounded/invalid studi | A really interesting example I personally like is taken from the book Freakonomics by Steven D. Levitt and Stephen J. Dubner. There is a chapter in the book that discusses correlation vs. causality. C | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused?
A really interesting example I personally like is taken from the book Freakonomics by Steven D. Levitt and Stephen J. Dubner. There is a chapter in the book that discusses correlation vs. causality. Correlation between two statistical variables does not necessarily imply that these variables are statistically dependent, but a mistake along these lines was made by experts. Quoting from the book:
"A tricky beast, Polio was extremely difficult for researchers to pin down. They couldn’t figure out how it was passed or when/how it expressed itself. We have a tendency to remember this time as one in which Polio was ‘epidemic’ when, in fact, it was not affecting large swaths of the population (compared with the more common measles, for example). The reason it was seen as epidemic was because it was so frightening.
What researchers DID manage to determine in their studies was that Polio infection rates went UP in the Summer. They also saw that ICE CREAM CONSUMPTION went up in the Summer. And so they concluded that ice cream consumption led to Polio and for a time ice cream was demonized. " | What are the case studies in public health policy research where unreliable/confounded/invalid studi
A really interesting example I personally like is taken from the book Freakonomics by Steven D. Levitt and Stephen J. Dubner. There is a chapter in the book that discusses correlation vs. causality. C |
20,208 | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused? | In his paper, "Statistical Models and Shoe Leather" (1991), David Freedman presents some cautionary tales in epidemiological studies. He offers Snow's analysis of cholera in London as a success, not due to statistical modeling, but rather due to diligent data collection. Here's the abstract:
Regression models have been used in the social sciences at least since 1899, when Yule published a paper on the causes of pauperism. Regression models are now used to make causal arguments in a wide variety of applications, and it is perhaps time to evaluate the results. No definitive answers can be given, but this paper takes a rather negative view. Snow's work on cholera is presented as a success story for scientific reasoning based on nonexperimental data. Failure stories are also discussed, and comparisons may provide some insight. In particular, this paper suggests that statistical technique can seldom be an adequate substitute for good design, relevant data, and testing predictions against reality in a variety of settings.
Sociological Methodology. 21: 291-313. | What are the case studies in public health policy research where unreliable/confounded/invalid studi | In his paper, "Statistical Models and Shoe Leather" (1991), David Freedman presents some cautionary tales in epidemiological studies. He offers Snow's analysis of cholera in London as a success, not d | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused?
In his paper, "Statistical Models and Shoe Leather" (1991), David Freedman presents some cautionary tales in epidemiological studies. He offers Snow's analysis of cholera in London as a success, not due to statistical modeling, but rather due to diligent data collection. Here's the abstract:
Regression models have been used in the social sciences at least since 1899, when Yule published a paper on the causes of pauperism. Regression models are now used to make causal arguments in a wide variety of applications, and it is perhaps time to evaluate the results. No definitive answers can be given, but this paper takes a rather negative view. Snow's work on cholera is presented as a success story for scientific reasoning based on nonexperimental data. Failure stories are also discussed, and comparisons may provide some insight. In particular, this paper suggests that statistical technique can seldom be an adequate substitute for good design, relevant data, and testing predictions against reality in a variety of settings.
Sociological Methodology. 21: 291-313. | What are the case studies in public health policy research where unreliable/confounded/invalid studi
In his paper, "Statistical Models and Shoe Leather" (1991), David Freedman presents some cautionary tales in epidemiological studies. He offers Snow's analysis of cholera in London as a success, not d |
20,209 | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused? | The case of high-dose chemotherapy with bone-marrow-transplant rescue as treatment for advanced breast cancer in the 1990's is one such instance. A series of low-quality studies were used to push through legislation mandating health insurer coverage in some states. When the large randomized trials were completed, there was no measurable benefit.
http://www.gao.gov/products/HEHS-96-83 | What are the case studies in public health policy research where unreliable/confounded/invalid studi | The case of high-dose chemotherapy with bone-marrow-transplant rescue as treatment for advanced breast cancer in the 1990's is one such instance. A series of low-quality studies were used to push thro | What are the case studies in public health policy research where unreliable/confounded/invalid studies or models were misused?
The case of high-dose chemotherapy with bone-marrow-transplant rescue as treatment for advanced breast cancer in the 1990's is one such instance. A series of low-quality studies were used to push through legislation mandating health insurer coverage in some states. When the large randomized trials were completed, there was no measurable benefit.
http://www.gao.gov/products/HEHS-96-83 | What are the case studies in public health policy research where unreliable/confounded/invalid studi
The case of high-dose chemotherapy with bone-marrow-transplant rescue as treatment for advanced breast cancer in the 1990's is one such instance. A series of low-quality studies were used to push thro |
20,210 | What are complete sufficient statistics? | Essentially, it means that no non-trivial function of the statistic has constant mean value.
This may not be very enlighthening in itself.
Perhaps one way of looking at the utility of such notion is in connection with the theorem of Lehmann-Scheffé (Cox-Hinkley, Theoretical Statistics, p. 31): "In general, if a sufficient statistic is boundedly complete it is minimal sufficient. The converse is false."
Intuitively, if a function of $T$ has mean value not dependent on $\theta$, that mean value is not informative about $\theta$ and we could get rid of it to obtain a sufficient statistic "simpler". If it is boundedly complete ans sufficient, no such "simplification" is possible. | What are complete sufficient statistics? | Essentially, it means that no non-trivial function of the statistic has constant mean value.
This may not be very enlighthening in itself.
Perhaps one way of looking at the utility of such notion is i | What are complete sufficient statistics?
Essentially, it means that no non-trivial function of the statistic has constant mean value.
This may not be very enlighthening in itself.
Perhaps one way of looking at the utility of such notion is in connection with the theorem of Lehmann-Scheffé (Cox-Hinkley, Theoretical Statistics, p. 31): "In general, if a sufficient statistic is boundedly complete it is minimal sufficient. The converse is false."
Intuitively, if a function of $T$ has mean value not dependent on $\theta$, that mean value is not informative about $\theta$ and we could get rid of it to obtain a sufficient statistic "simpler". If it is boundedly complete ans sufficient, no such "simplification" is possible. | What are complete sufficient statistics?
Essentially, it means that no non-trivial function of the statistic has constant mean value.
This may not be very enlighthening in itself.
Perhaps one way of looking at the utility of such notion is i |
20,211 | Feature construction and normalization in machine learning | Binary case
If you want your features to be binary, the good representations for categorical (resp. real) values are the one hot (resp. thermometer) encoding. You don't need to normalize them.
For the one hot encoding of a categorical feature, you simply reserve one bit for each class. The length of this encoding is therefore the number of classes of your feature. Lets take your example of country,
00001 for US
00010 for UK
00100 for Asia
01000 for Europe
10000 for other
For the thermometer encoding of a real/integer feature, you have to choose a length and the thresholds. For your example of age, you've chosen to split age according to the thresholds 18,25 and 35. The coding will be
000 for 0-17
001 for 18-25
011 for 25-34
111 for 35-above
Putting both together, you obtain here an encoding of size 5+3=8 bits.
For a 30 year old UK resident we have
$$\overbrace{0 \cdot 0 \cdot 0 \cdot 1 \cdot 0}^{UK}\cdot \overbrace{0 \cdot 1 \cdot 1 }^{30yo}$$
Continuous case
If your regression model allows it, you should prefere to keep a real value for a real/integer feature which contains more information.
Let's reconsider your example. This time we simply let the value for age as an integer. The encoding for a 30 year old UK resident is thus
$$\overbrace{0 \cdot 0 \cdot 0 \cdot 1 \cdot 0 }^{UK}\cdot \overbrace{30 }^{30yo}$$
As BGreene said, you should then normalize this value to keep a mean of 0 and a standard deviation of 1, which insure stability of many regression models. In order to do that, simply subtract the empirical mean and divide by the empirical standard deviation.
Y_normalized = ( Y - mean(Y) ) / std(Y)
If the mean of all the age of all persons in your data base is 25, and its standard deviation is 10, the normalized value for a 30y.o. person will be $(30-25)/10 = 0.5$, leading to the representation
$$\overbrace{0 \cdot 0 \cdot 0 \cdot 1 \cdot 0}^{UK}\cdot \overbrace{0.5 }^{30yo}$$ | Feature construction and normalization in machine learning | Binary case
If you want your features to be binary, the good representations for categorical (resp. real) values are the one hot (resp. thermometer) encoding. You don't need to normalize them.
For the | Feature construction and normalization in machine learning
Binary case
If you want your features to be binary, the good representations for categorical (resp. real) values are the one hot (resp. thermometer) encoding. You don't need to normalize them.
For the one hot encoding of a categorical feature, you simply reserve one bit for each class. The length of this encoding is therefore the number of classes of your feature. Lets take your example of country,
00001 for US
00010 for UK
00100 for Asia
01000 for Europe
10000 for other
For the thermometer encoding of a real/integer feature, you have to choose a length and the thresholds. For your example of age, you've chosen to split age according to the thresholds 18,25 and 35. The coding will be
000 for 0-17
001 for 18-25
011 for 25-34
111 for 35-above
Putting both together, you obtain here an encoding of size 5+3=8 bits.
For a 30 year old UK resident we have
$$\overbrace{0 \cdot 0 \cdot 0 \cdot 1 \cdot 0}^{UK}\cdot \overbrace{0 \cdot 1 \cdot 1 }^{30yo}$$
Continuous case
If your regression model allows it, you should prefere to keep a real value for a real/integer feature which contains more information.
Let's reconsider your example. This time we simply let the value for age as an integer. The encoding for a 30 year old UK resident is thus
$$\overbrace{0 \cdot 0 \cdot 0 \cdot 1 \cdot 0 }^{UK}\cdot \overbrace{30 }^{30yo}$$
As BGreene said, you should then normalize this value to keep a mean of 0 and a standard deviation of 1, which insure stability of many regression models. In order to do that, simply subtract the empirical mean and divide by the empirical standard deviation.
Y_normalized = ( Y - mean(Y) ) / std(Y)
If the mean of all the age of all persons in your data base is 25, and its standard deviation is 10, the normalized value for a 30y.o. person will be $(30-25)/10 = 0.5$, leading to the representation
$$\overbrace{0 \cdot 0 \cdot 0 \cdot 1 \cdot 0}^{UK}\cdot \overbrace{0.5 }^{30yo}$$ | Feature construction and normalization in machine learning
Binary case
If you want your features to be binary, the good representations for categorical (resp. real) values are the one hot (resp. thermometer) encoding. You don't need to normalize them.
For the |
20,212 | Joint model with interaction terms vs. separate regressions for a group comparison | The first model will fully interact gender with all other covariates in the model. Essentially, the effect of each covariate (b2, b3... bn). In the second model, the effect of gender is only interacted with your IV. So, assuming you have more covariates than just the IV and gender, this may drive somewhat different results.
If you just have the two covariates, there are documented occasions where the difference in maximization between the Wald test and the Likelihood ratio test lead to different answers (see more on the wikipedia).
In my own experience, I try to be guided by theory. If there is a dominant theory that suggests gender would interact with only the IV, but not the other covariates, I would go with the partial interaction. | Joint model with interaction terms vs. separate regressions for a group comparison | The first model will fully interact gender with all other covariates in the model. Essentially, the effect of each covariate (b2, b3... bn). In the second model, the effect of gender is only interacte | Joint model with interaction terms vs. separate regressions for a group comparison
The first model will fully interact gender with all other covariates in the model. Essentially, the effect of each covariate (b2, b3... bn). In the second model, the effect of gender is only interacted with your IV. So, assuming you have more covariates than just the IV and gender, this may drive somewhat different results.
If you just have the two covariates, there are documented occasions where the difference in maximization between the Wald test and the Likelihood ratio test lead to different answers (see more on the wikipedia).
In my own experience, I try to be guided by theory. If there is a dominant theory that suggests gender would interact with only the IV, but not the other covariates, I would go with the partial interaction. | Joint model with interaction terms vs. separate regressions for a group comparison
The first model will fully interact gender with all other covariates in the model. Essentially, the effect of each covariate (b2, b3... bn). In the second model, the effect of gender is only interacte |
20,213 | Joint model with interaction terms vs. separate regressions for a group comparison | Anytime two different procedures are used to test a particular hypothesis there will different p-values. To say one is significant and the other is not can be just making a black and white decision at the 0.05 level. If one test gives a p-value of 0.03 and the other say 0.07 I would not call the results contradictory. If you are going to be that strict in thinking about significance it is easy to have either situation (i) or (ii) arise when boardline significance is the case.
As I mentioned in response to the previous question my preference for looking for an interaction is to do one combined regression. | Joint model with interaction terms vs. separate regressions for a group comparison | Anytime two different procedures are used to test a particular hypothesis there will different p-values. To say one is significant and the other is not can be just making a black and white decision a | Joint model with interaction terms vs. separate regressions for a group comparison
Anytime two different procedures are used to test a particular hypothesis there will different p-values. To say one is significant and the other is not can be just making a black and white decision at the 0.05 level. If one test gives a p-value of 0.03 and the other say 0.07 I would not call the results contradictory. If you are going to be that strict in thinking about significance it is easy to have either situation (i) or (ii) arise when boardline significance is the case.
As I mentioned in response to the previous question my preference for looking for an interaction is to do one combined regression. | Joint model with interaction terms vs. separate regressions for a group comparison
Anytime two different procedures are used to test a particular hypothesis there will different p-values. To say one is significant and the other is not can be just making a black and white decision a |
20,214 | Joint model with interaction terms vs. separate regressions for a group comparison | In the second case, standard software would suggest you a t-stat with t-student pvalues whereas for the first case the Wald tests may have two options. Under errors normality assumption Wald statistic follows an exact Fisher statistic (which is equivalent to the t-stat as it assumes error's normality). Whereas under asymptotic normality, Wald statistic follows a Chi2 distribution (which is analague to the a t-stat following a normal distribution asimptotically) What distribution are you assuming ? Depending on this your p-values risk to give you different results.
In Textbooks you will find that for bilateral single tests (one parameter) both, t-student and Fisher statistics are equivalent.
If your sample is not large then comparing comparing chi2 and t-stat pvalues would yield different results for certain. In that case assuming an asymptotic dsitribution would not be reasonable. IF your sample is rather small then assuming normality seems more reasonable, this implies t-stat and Fisher pvalues for case 2 and 1 respectively. | Joint model with interaction terms vs. separate regressions for a group comparison | In the second case, standard software would suggest you a t-stat with t-student pvalues whereas for the first case the Wald tests may have two options. Under errors normality assumption Wald statistic | Joint model with interaction terms vs. separate regressions for a group comparison
In the second case, standard software would suggest you a t-stat with t-student pvalues whereas for the first case the Wald tests may have two options. Under errors normality assumption Wald statistic follows an exact Fisher statistic (which is equivalent to the t-stat as it assumes error's normality). Whereas under asymptotic normality, Wald statistic follows a Chi2 distribution (which is analague to the a t-stat following a normal distribution asimptotically) What distribution are you assuming ? Depending on this your p-values risk to give you different results.
In Textbooks you will find that for bilateral single tests (one parameter) both, t-student and Fisher statistics are equivalent.
If your sample is not large then comparing comparing chi2 and t-stat pvalues would yield different results for certain. In that case assuming an asymptotic dsitribution would not be reasonable. IF your sample is rather small then assuming normality seems more reasonable, this implies t-stat and Fisher pvalues for case 2 and 1 respectively. | Joint model with interaction terms vs. separate regressions for a group comparison
In the second case, standard software would suggest you a t-stat with t-student pvalues whereas for the first case the Wald tests may have two options. Under errors normality assumption Wald statistic |
20,215 | Sparsity by discarding least squares' coefficient | There would be no problem if $X$ were orthonormal. However, the possibility of strong correlation among the explanatory variables should give us pause.
When you consider the geometric interpretation of least-squares regression, counterexamples are easy to come by. Take $X_1$ to have, say, almost normally distributed coefficients and $X_2$ to be almost parallel to it. Let $X_3$ be orthogonal to the plane generated by $X_1$ and $X_2$. We can envision a $Y$ that is principally in the $X_3$ direction, yet is displaced a relatively tiny amount from the origin in the $X_1,X_2$ plane. Because $X_1$ and $X_2$ are nearly parallel, its components in that plane might both have large coefficients, causing us to drop $X_3$, which would be a huge mistake.
The geometry can be recreated with a simulation, such as is carried out by these R calculations:
set.seed(17)
x1 <- rnorm(100) # Some nice values, close to standardized
x2 <- rnorm(100) * 0.01 + x1 # Almost parallel to x1
x3 <- rnorm(100) # Likely almost orthogonal to x1 and x2
e <- rnorm(100) * 0.005 # Some tiny errors, just for fun (and realism)
y <- x1 - x2 + x3 * 0.1 + e
summary(lm(y ~ x1 + x2 + x3)) # The full model
summary(lm(y ~ x1 + x2)) # The reduced ("sparse") model
The variances of the $X_i$ are close enough to $1$ that we can inspect the coefficients of the fits as proxies for the standardized coefficients. In the full model the coefficients are 0.99, -0.99, and 0.1 (all highly significant), with the smallest (by far) associated with $X_3$, by design. The residual standard error is 0.00498. In the reduced ("sparse") model the residual standard error, at 0.09803, is $20$ times greater: a huge increase, reflecting the loss of almost all information about $Y$ from dropping the variable with the smallest standardized coefficient. The $R^2$ has dropped from $0.9975$ almost to zero. Neither coefficient is significant at better than the $0.38$ level.
The scatterplot matrix reveals all:
The strong correlation between $x_3$ and $y$ is clear from the linear alignments of points in the lower right. The poor correlation between $x_1$ and $y$ and $x_2$ and $y$ is equally clear from the circular scatter in the other panels. Nevertheless, the smallest standardized coefficient belongs to $x_3$ rather than to $x_1$ or $x_2$. | Sparsity by discarding least squares' coefficient | There would be no problem if $X$ were orthonormal. However, the possibility of strong correlation among the explanatory variables should give us pause.
When you consider the geometric interpretation | Sparsity by discarding least squares' coefficient
There would be no problem if $X$ were orthonormal. However, the possibility of strong correlation among the explanatory variables should give us pause.
When you consider the geometric interpretation of least-squares regression, counterexamples are easy to come by. Take $X_1$ to have, say, almost normally distributed coefficients and $X_2$ to be almost parallel to it. Let $X_3$ be orthogonal to the plane generated by $X_1$ and $X_2$. We can envision a $Y$ that is principally in the $X_3$ direction, yet is displaced a relatively tiny amount from the origin in the $X_1,X_2$ plane. Because $X_1$ and $X_2$ are nearly parallel, its components in that plane might both have large coefficients, causing us to drop $X_3$, which would be a huge mistake.
The geometry can be recreated with a simulation, such as is carried out by these R calculations:
set.seed(17)
x1 <- rnorm(100) # Some nice values, close to standardized
x2 <- rnorm(100) * 0.01 + x1 # Almost parallel to x1
x3 <- rnorm(100) # Likely almost orthogonal to x1 and x2
e <- rnorm(100) * 0.005 # Some tiny errors, just for fun (and realism)
y <- x1 - x2 + x3 * 0.1 + e
summary(lm(y ~ x1 + x2 + x3)) # The full model
summary(lm(y ~ x1 + x2)) # The reduced ("sparse") model
The variances of the $X_i$ are close enough to $1$ that we can inspect the coefficients of the fits as proxies for the standardized coefficients. In the full model the coefficients are 0.99, -0.99, and 0.1 (all highly significant), with the smallest (by far) associated with $X_3$, by design. The residual standard error is 0.00498. In the reduced ("sparse") model the residual standard error, at 0.09803, is $20$ times greater: a huge increase, reflecting the loss of almost all information about $Y$ from dropping the variable with the smallest standardized coefficient. The $R^2$ has dropped from $0.9975$ almost to zero. Neither coefficient is significant at better than the $0.38$ level.
The scatterplot matrix reveals all:
The strong correlation between $x_3$ and $y$ is clear from the linear alignments of points in the lower right. The poor correlation between $x_1$ and $y$ and $x_2$ and $y$ is equally clear from the circular scatter in the other panels. Nevertheless, the smallest standardized coefficient belongs to $x_3$ rather than to $x_1$ or $x_2$. | Sparsity by discarding least squares' coefficient
There would be no problem if $X$ were orthonormal. However, the possibility of strong correlation among the explanatory variables should give us pause.
When you consider the geometric interpretation |
20,216 | Sparsity by discarding least squares' coefficient | Seems to me that if an estimated coefficient is near 0 and the data is normalized that prediction would not be hurt by discarding the variable. Certainly if the coefficient was not statistically significant there would seem to be no problem. But this must be done carefully.The IVs may be correlated and removing one could change the coefficients of others. This gets more dangerous if you start reoving several variables this way. Subset selection procedures are designed to avoid such problems and use sensible criteria for including and excluding variables. If you ask Frank Harrell he would be against stepwise procedures. You mention LARS and LASSO which are two very modern methods. But there are plenty of others Including information criteria that peanlize the introduction of too many variables.
If you try a subset selection procedure that has been carefully studied with a lot of literature about it you will probably find that it will lead to a solution that reoves variables with small coefficients especially if they fail the test for being statistically significantly different from 0. | Sparsity by discarding least squares' coefficient | Seems to me that if an estimated coefficient is near 0 and the data is normalized that prediction would not be hurt by discarding the variable. Certainly if the coefficient was not statistically sign | Sparsity by discarding least squares' coefficient
Seems to me that if an estimated coefficient is near 0 and the data is normalized that prediction would not be hurt by discarding the variable. Certainly if the coefficient was not statistically significant there would seem to be no problem. But this must be done carefully.The IVs may be correlated and removing one could change the coefficients of others. This gets more dangerous if you start reoving several variables this way. Subset selection procedures are designed to avoid such problems and use sensible criteria for including and excluding variables. If you ask Frank Harrell he would be against stepwise procedures. You mention LARS and LASSO which are two very modern methods. But there are plenty of others Including information criteria that peanlize the introduction of too many variables.
If you try a subset selection procedure that has been carefully studied with a lot of literature about it you will probably find that it will lead to a solution that reoves variables with small coefficients especially if they fail the test for being statistically significantly different from 0. | Sparsity by discarding least squares' coefficient
Seems to me that if an estimated coefficient is near 0 and the data is normalized that prediction would not be hurt by discarding the variable. Certainly if the coefficient was not statistically sign |
20,217 | How to test whether subgroup mean differs from overall group that includes the subgroup? | As Michael notes, when comparing a subgroup to an overall group, researchers typically compare the subgroup to the subset of the overall group that does not include the subgroup.
Think about it this way.
If $p$ is the proportion that died, and $1-p$ is the proportion who did not die, and
$$\bar{X}_. = p\bar{X}_d + (1-p)\bar{X}_a$$
where $\bar{X}_.$ is the overall mean, $\bar{X}_d$ is the mean of those that died, and $\bar{X}_a$ is the mean of those that are still alive. Then
$$\bar{X}_d \neq \bar{X}_a$$
if and only if when
$$\bar{X}_d \neq \bar{X}_.$$
$\Rightarrow $
Suppose $\bar{X_{d}}\neq \bar{X_{a}}$. Hence $\bar{X_{.}}\neq p\bar{X_{d}}+(1-p)\bar{X_{d}}=\bar{X_{d}}$.
$\Leftarrow $
Suppose $\bar{X_{.}}\neq\bar{X_{d}}$. Hence $\bar{X_{d}}\neq p\bar{X_{d}}+(1-p)\bar{X_{a}}$, then $(1-p)\bar{X_{d}}\neq (1-p)\bar{X_{a}}$ and since $(1-p)\neq 0$, then $\bar{X_{d}}\neq \bar{X_{a}}$.
The same one can do for inequalities.
Thus, researchers typically test the difference between the subgroup and the subset of the overall group that does not include the subgroup. This has the effect of showing that the subgroup differs from the overall group. It also allows you use conventional methods like an independent groups t-test. | How to test whether subgroup mean differs from overall group that includes the subgroup? | As Michael notes, when comparing a subgroup to an overall group, researchers typically compare the subgroup to the subset of the overall group that does not include the subgroup.
Think about it this w | How to test whether subgroup mean differs from overall group that includes the subgroup?
As Michael notes, when comparing a subgroup to an overall group, researchers typically compare the subgroup to the subset of the overall group that does not include the subgroup.
Think about it this way.
If $p$ is the proportion that died, and $1-p$ is the proportion who did not die, and
$$\bar{X}_. = p\bar{X}_d + (1-p)\bar{X}_a$$
where $\bar{X}_.$ is the overall mean, $\bar{X}_d$ is the mean of those that died, and $\bar{X}_a$ is the mean of those that are still alive. Then
$$\bar{X}_d \neq \bar{X}_a$$
if and only if when
$$\bar{X}_d \neq \bar{X}_.$$
$\Rightarrow $
Suppose $\bar{X_{d}}\neq \bar{X_{a}}$. Hence $\bar{X_{.}}\neq p\bar{X_{d}}+(1-p)\bar{X_{d}}=\bar{X_{d}}$.
$\Leftarrow $
Suppose $\bar{X_{.}}\neq\bar{X_{d}}$. Hence $\bar{X_{d}}\neq p\bar{X_{d}}+(1-p)\bar{X_{a}}$, then $(1-p)\bar{X_{d}}\neq (1-p)\bar{X_{a}}$ and since $(1-p)\neq 0$, then $\bar{X_{d}}\neq \bar{X_{a}}$.
The same one can do for inequalities.
Thus, researchers typically test the difference between the subgroup and the subset of the overall group that does not include the subgroup. This has the effect of showing that the subgroup differs from the overall group. It also allows you use conventional methods like an independent groups t-test. | How to test whether subgroup mean differs from overall group that includes the subgroup?
As Michael notes, when comparing a subgroup to an overall group, researchers typically compare the subgroup to the subset of the overall group that does not include the subgroup.
Think about it this w |
20,218 | How to test whether subgroup mean differs from overall group that includes the subgroup? | The way to test here is to compare those who had the disease and died to those who had the disease and did not die. You could apply the two sample t test or the Wilcoxon rank sum test if normality cannot be assumed. | How to test whether subgroup mean differs from overall group that includes the subgroup? | The way to test here is to compare those who had the disease and died to those who had the disease and did not die. You could apply the two sample t test or the Wilcoxon rank sum test if normality ca | How to test whether subgroup mean differs from overall group that includes the subgroup?
The way to test here is to compare those who had the disease and died to those who had the disease and did not die. You could apply the two sample t test or the Wilcoxon rank sum test if normality cannot be assumed. | How to test whether subgroup mean differs from overall group that includes the subgroup?
The way to test here is to compare those who had the disease and died to those who had the disease and did not die. You could apply the two sample t test or the Wilcoxon rank sum test if normality ca |
20,219 | How to test whether subgroup mean differs from overall group that includes the subgroup? | What you need to do is to test for Population proportions (large sample size).
Statistics involving population proportion often have sample size that is large (n=>30), therefore the normal approximation distribution and associated statistics is used to determine a test for whether the sample proportion(blood pressure of those who died) = population proportion(everyone who had the disease including those that died).
That is, when the sample size is greater than or equal to 30 we can use the z-score statistics to compare the sample proportion against the population proportion using value of the sample standard deviation p-hat, to estimate the sample standard deviation, p if it is not known.
The sample distribution of P (proportion) is approximately normal with a mean or expected value, E(P) = p-hat and standard error, sigma(r)=sqrt(p*q/n) .
The following are the likely test hypothesis questions one may ask when comparing two proportions:
(Two-tailed test)
H0: p-hat = p vs
H1 : p-hat not equal to p
(Right-tailed test)
H0: p-hat = p vs
H1 : p-hat > p
(Left-tailed test)
H0: p-hat = p vs
H1 : p-hat < p
The statistics used to test for large sample size are;
The test statistics is related to the standard normal distribution:
The z-score statistics for proportions
p-hat-p/sqrt(pq/n)
, where p = proportion estimate, q=1-p and is the population proportion.
Proportion mean is:
np/n= p-hat = x/n
Standard deviation:
= sqrt(npq/n)=sqrt(pq/n)
Decision rules:
Upper-Tailed Test (): (H0: P-hat >=P)
Accept H0 if
Z<=Z(1-alpha)
Reject H0 if
Z>Z(1-alpha)
Lower-Tailed Test (Ha: P-hat<=P):
Accept H0 if
Z>=Z(1-alpha)
Reject H0 if
Z
Two-Tailed Test (Ha:P-hat not equal to P):
Accept H0 if
Z(alpha/2)<= Z <=Z(1-alpha/2)
Reject H0 if
Z < Z(alpha/2) or if Z > Z(1-alpha/2) | How to test whether subgroup mean differs from overall group that includes the subgroup? | What you need to do is to test for Population proportions (large sample size).
Statistics involving population proportion often have sample size that is large (n=>30), therefore the normal approximat | How to test whether subgroup mean differs from overall group that includes the subgroup?
What you need to do is to test for Population proportions (large sample size).
Statistics involving population proportion often have sample size that is large (n=>30), therefore the normal approximation distribution and associated statistics is used to determine a test for whether the sample proportion(blood pressure of those who died) = population proportion(everyone who had the disease including those that died).
That is, when the sample size is greater than or equal to 30 we can use the z-score statistics to compare the sample proportion against the population proportion using value of the sample standard deviation p-hat, to estimate the sample standard deviation, p if it is not known.
The sample distribution of P (proportion) is approximately normal with a mean or expected value, E(P) = p-hat and standard error, sigma(r)=sqrt(p*q/n) .
The following are the likely test hypothesis questions one may ask when comparing two proportions:
(Two-tailed test)
H0: p-hat = p vs
H1 : p-hat not equal to p
(Right-tailed test)
H0: p-hat = p vs
H1 : p-hat > p
(Left-tailed test)
H0: p-hat = p vs
H1 : p-hat < p
The statistics used to test for large sample size are;
The test statistics is related to the standard normal distribution:
The z-score statistics for proportions
p-hat-p/sqrt(pq/n)
, where p = proportion estimate, q=1-p and is the population proportion.
Proportion mean is:
np/n= p-hat = x/n
Standard deviation:
= sqrt(npq/n)=sqrt(pq/n)
Decision rules:
Upper-Tailed Test (): (H0: P-hat >=P)
Accept H0 if
Z<=Z(1-alpha)
Reject H0 if
Z>Z(1-alpha)
Lower-Tailed Test (Ha: P-hat<=P):
Accept H0 if
Z>=Z(1-alpha)
Reject H0 if
Z
Two-Tailed Test (Ha:P-hat not equal to P):
Accept H0 if
Z(alpha/2)<= Z <=Z(1-alpha/2)
Reject H0 if
Z < Z(alpha/2) or if Z > Z(1-alpha/2) | How to test whether subgroup mean differs from overall group that includes the subgroup?
What you need to do is to test for Population proportions (large sample size).
Statistics involving population proportion often have sample size that is large (n=>30), therefore the normal approximat |
20,220 | Distribution of sum of squares error for linear regression? | We can prove this for more general case of $p$ variables by using the "hat matrix" and some of its useful properties. These results are usually much harder to state in non matrix terms because of the use of the spectral decomposition.
Now in matrix version of least squares, the hat matrix is $H=X(X^TX)^{-1}X^T$ where $X$ has $n$ rows and $p+1$ columns (column of ones for $\beta_0$). Assume full column rank for convenience - else you could replace $p+1$ by the column rank of $X$ in the following. We can write the fitted values as $\hat{Y}_i=\sum_{j=1}^nH_{ij}Y_j$ or in matrix notation $\hat{Y}=HY$. Using this, we can write the sum of squares as:
$$\frac{\sum_{i=1}(Y-\hat{Y_i})^2}{\sigma^2}=\frac{(Y-\hat{Y})^T(Y-\hat{Y})}{\sigma^2}=\frac{(Y-HY)^T(Y-HY)}{\sigma^2}$$
$$=\frac{Y^T(I_n-H)Y}{\sigma^2}$$
Where $I_n$ is an identity matrix of order $n$. The last step follows from the fact that $H$ is an idepotent matrix, as $$H^2=[X(X^TX)^{-1}X^T][X(X^TX)^{-1}X^T]=X(X^TX)^{-1}X^T=H=HH^T=H^TH$$
Now a neat property of idepotent matrices is that all of their eigenvalues must be equal to zero or one. Letting $e$ denote a normalised eigenvector of $H$ with eigenvalue $l$, we can prove this as follows:
$$He=le\implies H(He)=H(le)$$
$$LHS=H^2e=He=le\;\;\; RHS=lHe=l^2e$$
$$\implies le=l^2e\implies l=0\text{ or }1$$
(note that $e$ cannot be zero as it must satisfy $e^Te=1$) Now because $H$ is idepotent, $I_n-H$ also is, because
$$(I_n-H)(I_n-H)=I-IH-HI+H^2=I_n-H$$
We also have the property that the sum of the eigenvalues equals the trace of the matrix, and
$$tr(I_n-H)=tr(I_n)-tr(H)=n-tr(X(X^TX)^{-1}X^T)=n-tr((X^TX)^{-1}X^TX)$$
$$=n-tr(I_{p+1})=n-p-1$$
Hence $I-H$ must have $n-p-1$ eigenvalues equal to $1$ and $p+1$ eigenvalues equal to $0$.
Now we can use the spectral decomposition of $I-H=ADA^T$ where $D=\begin{pmatrix}I_{n-p-1} & 0_{[n-p-1]\times[p+1]}\\0_{[p+1]\times [n-p-1]} & 0_{[p+1]\times [p+1]}\end{pmatrix}$ and $A$ is orthogonal (because $I-H$ is symmetric) . A further property which is useful is that $HX=X$. This helps narrow down the $A$ matrix
$$HX=X\implies(I-H)X=0\implies ADA^TX=0\implies DA^TX=0$$
$$\implies (A^TX)_{ij}=0\;\;\;i=1,\dots,n-p-1\;\;\; j=1,\dots,p+1$$
and we get:
$$\frac{\sum_{i=1}(Y-\hat{Y_i})^2}{\sigma^2}=\frac{Y^TADA^TY}{\sigma^2}=\frac{\sum_{i=1}^{n-p-1}(A^TY)_i^2}{\sigma^2}$$
Now, under the model we have $Y\sim N(X\beta,\sigma^2I)$ and using standard normal theory we have $A^TY\sim N(A^TX\beta,\sigma^2A^TA)\sim N(A^TX\beta,\sigma^2I)$ showing that the components of $A^TY$ are independent. Now using the useful result, we have that $(A^TY)_i\sim N(0,\sigma^2)$ for $i=1,\dots,n-p-1$. The chi-square distribution with $n-p-1$ degrees of freedom for the sum of squared errors follows immediately. | Distribution of sum of squares error for linear regression? | We can prove this for more general case of $p$ variables by using the "hat matrix" and some of its useful properties. These results are usually much harder to state in non matrix terms because of the | Distribution of sum of squares error for linear regression?
We can prove this for more general case of $p$ variables by using the "hat matrix" and some of its useful properties. These results are usually much harder to state in non matrix terms because of the use of the spectral decomposition.
Now in matrix version of least squares, the hat matrix is $H=X(X^TX)^{-1}X^T$ where $X$ has $n$ rows and $p+1$ columns (column of ones for $\beta_0$). Assume full column rank for convenience - else you could replace $p+1$ by the column rank of $X$ in the following. We can write the fitted values as $\hat{Y}_i=\sum_{j=1}^nH_{ij}Y_j$ or in matrix notation $\hat{Y}=HY$. Using this, we can write the sum of squares as:
$$\frac{\sum_{i=1}(Y-\hat{Y_i})^2}{\sigma^2}=\frac{(Y-\hat{Y})^T(Y-\hat{Y})}{\sigma^2}=\frac{(Y-HY)^T(Y-HY)}{\sigma^2}$$
$$=\frac{Y^T(I_n-H)Y}{\sigma^2}$$
Where $I_n$ is an identity matrix of order $n$. The last step follows from the fact that $H$ is an idepotent matrix, as $$H^2=[X(X^TX)^{-1}X^T][X(X^TX)^{-1}X^T]=X(X^TX)^{-1}X^T=H=HH^T=H^TH$$
Now a neat property of idepotent matrices is that all of their eigenvalues must be equal to zero or one. Letting $e$ denote a normalised eigenvector of $H$ with eigenvalue $l$, we can prove this as follows:
$$He=le\implies H(He)=H(le)$$
$$LHS=H^2e=He=le\;\;\; RHS=lHe=l^2e$$
$$\implies le=l^2e\implies l=0\text{ or }1$$
(note that $e$ cannot be zero as it must satisfy $e^Te=1$) Now because $H$ is idepotent, $I_n-H$ also is, because
$$(I_n-H)(I_n-H)=I-IH-HI+H^2=I_n-H$$
We also have the property that the sum of the eigenvalues equals the trace of the matrix, and
$$tr(I_n-H)=tr(I_n)-tr(H)=n-tr(X(X^TX)^{-1}X^T)=n-tr((X^TX)^{-1}X^TX)$$
$$=n-tr(I_{p+1})=n-p-1$$
Hence $I-H$ must have $n-p-1$ eigenvalues equal to $1$ and $p+1$ eigenvalues equal to $0$.
Now we can use the spectral decomposition of $I-H=ADA^T$ where $D=\begin{pmatrix}I_{n-p-1} & 0_{[n-p-1]\times[p+1]}\\0_{[p+1]\times [n-p-1]} & 0_{[p+1]\times [p+1]}\end{pmatrix}$ and $A$ is orthogonal (because $I-H$ is symmetric) . A further property which is useful is that $HX=X$. This helps narrow down the $A$ matrix
$$HX=X\implies(I-H)X=0\implies ADA^TX=0\implies DA^TX=0$$
$$\implies (A^TX)_{ij}=0\;\;\;i=1,\dots,n-p-1\;\;\; j=1,\dots,p+1$$
and we get:
$$\frac{\sum_{i=1}(Y-\hat{Y_i})^2}{\sigma^2}=\frac{Y^TADA^TY}{\sigma^2}=\frac{\sum_{i=1}^{n-p-1}(A^TY)_i^2}{\sigma^2}$$
Now, under the model we have $Y\sim N(X\beta,\sigma^2I)$ and using standard normal theory we have $A^TY\sim N(A^TX\beta,\sigma^2A^TA)\sim N(A^TX\beta,\sigma^2I)$ showing that the components of $A^TY$ are independent. Now using the useful result, we have that $(A^TY)_i\sim N(0,\sigma^2)$ for $i=1,\dots,n-p-1$. The chi-square distribution with $n-p-1$ degrees of freedom for the sum of squared errors follows immediately. | Distribution of sum of squares error for linear regression?
We can prove this for more general case of $p$ variables by using the "hat matrix" and some of its useful properties. These results are usually much harder to state in non matrix terms because of the |
20,221 | Separating two populations from the sample | If I understand correctly, then you can just fit a mixture of two Normals to the data. There are lots of R packages that are available to do this. This example uses the mixtools package:
#Taken from the documentation
library(mixtools)
data(faithful)
attach(faithful)
#Fit two Normals
wait1 = normalmixEM(waiting, lambda = 0.5)
plot(wait1, density=TRUE, loglik=FALSE)
This gives:
Mixture of two Normals http://img294.imageshack.us/img294/4213/kernal.jpg
The package also contains more sophisticated methods - check the documentation. | Separating two populations from the sample | If I understand correctly, then you can just fit a mixture of two Normals to the data. There are lots of R packages that are available to do this. This example uses the mixtools package:
#Taken from t | Separating two populations from the sample
If I understand correctly, then you can just fit a mixture of two Normals to the data. There are lots of R packages that are available to do this. This example uses the mixtools package:
#Taken from the documentation
library(mixtools)
data(faithful)
attach(faithful)
#Fit two Normals
wait1 = normalmixEM(waiting, lambda = 0.5)
plot(wait1, density=TRUE, loglik=FALSE)
This gives:
Mixture of two Normals http://img294.imageshack.us/img294/4213/kernal.jpg
The package also contains more sophisticated methods - check the documentation. | Separating two populations from the sample
If I understand correctly, then you can just fit a mixture of two Normals to the data. There are lots of R packages that are available to do this. This example uses the mixtools package:
#Taken from t |
20,222 | Separating two populations from the sample | For data in IQR range you should use
truncated normal distribution (for
example R package gamlss.tr) to
estimate parameters of this
distribution.
Another approach is using mixture models with 2 or 3 components (distributions). You can fit such models using gamlss.mx package (distributions from package gamlss.dist can be specified for
each component of mixture). | Separating two populations from the sample | For data in IQR range you should use
truncated normal distribution (for
example R package gamlss.tr) to
estimate parameters of this
distribution.
Another approach is using mixture models with 2 or 3 | Separating two populations from the sample
For data in IQR range you should use
truncated normal distribution (for
example R package gamlss.tr) to
estimate parameters of this
distribution.
Another approach is using mixture models with 2 or 3 components (distributions). You can fit such models using gamlss.mx package (distributions from package gamlss.dist can be specified for
each component of mixture). | Separating two populations from the sample
For data in IQR range you should use
truncated normal distribution (for
example R package gamlss.tr) to
estimate parameters of this
distribution.
Another approach is using mixture models with 2 or 3 |
20,223 | Separating two populations from the sample | This assumes that you don't even know if the second distribution is normal or not; I basically handle this uncertainty by focusing only on the normal distribution. This may or may not be the best approach.
If you can assume that the two populations are completely separated (i.e., all values from distribution A are less than all values from distribution B), then one approach is to use the optimize() function in R to search for the break-point that yields estimates of the mean and sd of the normal distribution that make the data most likely:
#generate completely separated data
a = rnorm(100)
b = rnorm(100,10)
while(!all(a<b)){
a = rnorm(100)
b = rnorm(100,10)
}
#create a mix
mix = c(a,b)
#"forget" the original distributions
rm(a)
rm(b)
#try to find the break point between the distributions
break_point = optimize(
f = function(x){
data_from_a = mix[mix<x]
likelihood = dnorm(data_from_a,mean(data_from_a),sd(data_from_a))
SLL = sum(log(likelihood))
return(SLL)
}
, interval = c(sort(mix)[2],max(mix))
, maximum = TRUE
)$maximum
#label the data
labelled_mix = data.frame(
x = mix
, source = ifelse(mix<break_point,'A','B')
)
print(labelled_mix)
If you can't assume complete separation, then I think you'll have to assume some distribution for the second distribution and then use mixture modelling. Note that mixture modelling won't actually label the individual data points, but will give you the mixture proportion and estimates of the parameters of each distribution (eg. mean, sd, etc.). | Separating two populations from the sample | This assumes that you don't even know if the second distribution is normal or not; I basically handle this uncertainty by focusing only on the normal distribution. This may or may not be the best appr | Separating two populations from the sample
This assumes that you don't even know if the second distribution is normal or not; I basically handle this uncertainty by focusing only on the normal distribution. This may or may not be the best approach.
If you can assume that the two populations are completely separated (i.e., all values from distribution A are less than all values from distribution B), then one approach is to use the optimize() function in R to search for the break-point that yields estimates of the mean and sd of the normal distribution that make the data most likely:
#generate completely separated data
a = rnorm(100)
b = rnorm(100,10)
while(!all(a<b)){
a = rnorm(100)
b = rnorm(100,10)
}
#create a mix
mix = c(a,b)
#"forget" the original distributions
rm(a)
rm(b)
#try to find the break point between the distributions
break_point = optimize(
f = function(x){
data_from_a = mix[mix<x]
likelihood = dnorm(data_from_a,mean(data_from_a),sd(data_from_a))
SLL = sum(log(likelihood))
return(SLL)
}
, interval = c(sort(mix)[2],max(mix))
, maximum = TRUE
)$maximum
#label the data
labelled_mix = data.frame(
x = mix
, source = ifelse(mix<break_point,'A','B')
)
print(labelled_mix)
If you can't assume complete separation, then I think you'll have to assume some distribution for the second distribution and then use mixture modelling. Note that mixture modelling won't actually label the individual data points, but will give you the mixture proportion and estimates of the parameters of each distribution (eg. mean, sd, etc.). | Separating two populations from the sample
This assumes that you don't even know if the second distribution is normal or not; I basically handle this uncertainty by focusing only on the normal distribution. This may or may not be the best appr |
20,224 | Separating two populations from the sample | I'm surprised nobody suggested the obvious solution:
#generate completely separated data
library(robustbase)
set.seed(123)
x<-rnorm(200)
x[1:40]<-x[1:40]+10
x[41:80]<-x[41:80]-10
Rob<-ltsReg(x~1,nsamp="best")
#all the good guys
which(Rob$raw.weights==1)
Now for the explanation: the ltsReg function
in package robustbase, when called with the option
nsamp="best"
yields the univariate (exact) MCD weights.
(these are a n-vector 0-1 weights stored
in the $raw.weights object. The algorithm
to identify them is the MCD estimator (1)).
In a nutshell, these weights are 1 for the
members of the subset of $h=\lceil(n+2)/2\rceil$ most
concentrated observations.
In dimension one, it starts by sorting all the
observations then computes the measure of all
contiguous subsets of $h$ observations: denoting
$x_{(i)}$ the $i^{th}$ entry of the vector of sorted
observations, it computes the measure of
(e.g. $(x_{(1)},...,x_{(h+1)})$ then $(x_{(2)},...,x_{(h+2)})$
and so forth...) then retains the one with smaller
measure.
This algorithm assumes that your group of interest numbers
a strict majority of the original sample and that it
has a symmetrical distribution (but there no
no hypothesis on the distribution of the remaining
$n-h$ observation).
(1) P.J. Rousseeuw (1984). Least median of squares regression, Journal of
the American Statistical Association. | Separating two populations from the sample | I'm surprised nobody suggested the obvious solution:
#generate completely separated data
library(robustbase)
set.seed(123)
x<-rnorm(200)
x[1:40]<-x[1:40]+10
x[41:80]<-x[41:80]-10
Rob<-ltsReg(x~1, | Separating two populations from the sample
I'm surprised nobody suggested the obvious solution:
#generate completely separated data
library(robustbase)
set.seed(123)
x<-rnorm(200)
x[1:40]<-x[1:40]+10
x[41:80]<-x[41:80]-10
Rob<-ltsReg(x~1,nsamp="best")
#all the good guys
which(Rob$raw.weights==1)
Now for the explanation: the ltsReg function
in package robustbase, when called with the option
nsamp="best"
yields the univariate (exact) MCD weights.
(these are a n-vector 0-1 weights stored
in the $raw.weights object. The algorithm
to identify them is the MCD estimator (1)).
In a nutshell, these weights are 1 for the
members of the subset of $h=\lceil(n+2)/2\rceil$ most
concentrated observations.
In dimension one, it starts by sorting all the
observations then computes the measure of all
contiguous subsets of $h$ observations: denoting
$x_{(i)}$ the $i^{th}$ entry of the vector of sorted
observations, it computes the measure of
(e.g. $(x_{(1)},...,x_{(h+1)})$ then $(x_{(2)},...,x_{(h+2)})$
and so forth...) then retains the one with smaller
measure.
This algorithm assumes that your group of interest numbers
a strict majority of the original sample and that it
has a symmetrical distribution (but there no
no hypothesis on the distribution of the remaining
$n-h$ observation).
(1) P.J. Rousseeuw (1984). Least median of squares regression, Journal of
the American Statistical Association. | Separating two populations from the sample
I'm surprised nobody suggested the obvious solution:
#generate completely separated data
library(robustbase)
set.seed(123)
x<-rnorm(200)
x[1:40]<-x[1:40]+10
x[41:80]<-x[41:80]-10
Rob<-ltsReg(x~1, |
20,225 | There is no decision theory that isn’t Bayesian... or is there? | The An Introduction to Decision Theory book by Martin Peterson (Cambridge, 2009) has chapter 10 titled Bayesian vs Non-Bayesian Decision Theory if this answers your question. Yes, there are non-Bayesian approaches, though I never found them interesting and don't feel competent enough for summarizing them. | There is no decision theory that isn’t Bayesian... or is there? | The An Introduction to Decision Theory book by Martin Peterson (Cambridge, 2009) has chapter 10 titled Bayesian vs Non-Bayesian Decision Theory if this answers your question. Yes, there are non-Bayesi | There is no decision theory that isn’t Bayesian... or is there?
The An Introduction to Decision Theory book by Martin Peterson (Cambridge, 2009) has chapter 10 titled Bayesian vs Non-Bayesian Decision Theory if this answers your question. Yes, there are non-Bayesian approaches, though I never found them interesting and don't feel competent enough for summarizing them. | There is no decision theory that isn’t Bayesian... or is there?
The An Introduction to Decision Theory book by Martin Peterson (Cambridge, 2009) has chapter 10 titled Bayesian vs Non-Bayesian Decision Theory if this answers your question. Yes, there are non-Bayesi |
20,226 | There is no decision theory that isn’t Bayesian... or is there? | Taking only the basic decision theory (theories?) based on maximization of expected utility, the answer depends on
(i) the definition of what is considered Bayesian and
(ii) whether a theory that has both a Bayesian and a nonbayesian interpretation or a nonbayesian theory that can be approximated by a Bayesian one count as counterexamples.
Chapter 10 of Martin Peterson's "An Introduction to Decision Theory" (Cambridge, 2009) from Tim's answer characterizes a Bayesian decision theory as follows:
Subjective degrees of belief can be represented by a probability function
defined in terms of the decision maker's preferences over uncertain
prospects.
Degrees of desire can be represented by a utility function defined in the
same way, that is, in terms of preferences over uncertain prospects.
Rational decision makers act as if they maximise subjective expected
utility.
Regarding (i): The step that seems particularly/genuinely Bayesian* to me is 1. but not necessarily 2. or 3. However, one could say all of them are as Bayesian as it gets because of the persons who developed and advanced such theories (Ramsey, de Finetti, Savage).
Regarding (ii): The framework above might be broad enough to cover theories of maximization of expected utility based on probability distributions arrived at without the use of Bayesian thinking. (I think this is commonly seen in microeconomics textbooks, at least on the introductory level; they often take probability distributions as given, leaving it up to the user to figure out how to come up with them in reality.) E.g. in step 1. one could develop a model of uncertain prospects and use frequentist or fiducial techniques to estimate its parameters without ever invoking Bayesian arguments. One could then proceed with steps 2. and 3. as above. Now, this could most likely be approximated by the framework above, and in that sense this would (almost?) count as a Bayesian decision theory. On the other hand, does that necessarily invalidate this as a counterexample?
(Work in progress)
*The definition and delimitation of the term genuinely Bayesian is certainly debatable and I may be making a mistake here. | There is no decision theory that isn’t Bayesian... or is there? | Taking only the basic decision theory (theories?) based on maximization of expected utility, the answer depends on
(i) the definition of what is considered Bayesian and
(ii) whether a theory that has | There is no decision theory that isn’t Bayesian... or is there?
Taking only the basic decision theory (theories?) based on maximization of expected utility, the answer depends on
(i) the definition of what is considered Bayesian and
(ii) whether a theory that has both a Bayesian and a nonbayesian interpretation or a nonbayesian theory that can be approximated by a Bayesian one count as counterexamples.
Chapter 10 of Martin Peterson's "An Introduction to Decision Theory" (Cambridge, 2009) from Tim's answer characterizes a Bayesian decision theory as follows:
Subjective degrees of belief can be represented by a probability function
defined in terms of the decision maker's preferences over uncertain
prospects.
Degrees of desire can be represented by a utility function defined in the
same way, that is, in terms of preferences over uncertain prospects.
Rational decision makers act as if they maximise subjective expected
utility.
Regarding (i): The step that seems particularly/genuinely Bayesian* to me is 1. but not necessarily 2. or 3. However, one could say all of them are as Bayesian as it gets because of the persons who developed and advanced such theories (Ramsey, de Finetti, Savage).
Regarding (ii): The framework above might be broad enough to cover theories of maximization of expected utility based on probability distributions arrived at without the use of Bayesian thinking. (I think this is commonly seen in microeconomics textbooks, at least on the introductory level; they often take probability distributions as given, leaving it up to the user to figure out how to come up with them in reality.) E.g. in step 1. one could develop a model of uncertain prospects and use frequentist or fiducial techniques to estimate its parameters without ever invoking Bayesian arguments. One could then proceed with steps 2. and 3. as above. Now, this could most likely be approximated by the framework above, and in that sense this would (almost?) count as a Bayesian decision theory. On the other hand, does that necessarily invalidate this as a counterexample?
(Work in progress)
*The definition and delimitation of the term genuinely Bayesian is certainly debatable and I may be making a mistake here. | There is no decision theory that isn’t Bayesian... or is there?
Taking only the basic decision theory (theories?) based on maximization of expected utility, the answer depends on
(i) the definition of what is considered Bayesian and
(ii) whether a theory that has |
20,227 | OLS as approximation for non-linear function | WARNING: The results claimed in this post are of contested validity (by the writer himself. When the fog clears I will report back)
Ok. It's a bit long to include the whole proof here, so I will just sketch:
Apply a first-order Taylor expansion around some, initially arbitrary point, $x_0$,
$$y = m(x_0) + [x-x_0]'\nabla m(x_0,\theta) + R_1 + \epsilon.$$
where $R_1$ is the Taylor remainder. Set
$$b_0 = m(x_0),\; b = \nabla m(x_0,\theta),\;\beta = (b_o, b)' $$
$$\tilde x = x-x_0,\; u = R_1 + \epsilon$$
and revert to matrix notation
$$\mathbf y = \tilde X \beta + \mathbf u.$$
So what the OLS will attempt to estimate is the gradient of the conditional expectation function, evaluated at some point $x_0$, and the constant term will attempt to estimate the CEF evaluated at that point $x_0$.
The OLS will be
$$\hat \beta = \beta + (\tilde X'\tilde X)^{-1}\tilde X'u \implies \hat \beta - \beta = (\tilde X'\tilde X)^{-1}\tilde X'(\epsilon + R_1)$$
Since $\epsilon$ is by construction the conditional expectation function error, at the limit we will be left with
$$\text{plim}(\hat \beta - \beta) =E(\tilde x\tilde x')\cdot E(\tilde x\cdot R_1)$$
Now, $R_1$ will depend on the choice of $x_0$. Since $R_1$ represents the inaccuracy of the linear approximation, a natural thought is "what center of expansion minimizes the expected square Taylor remainder $E(R_1^2)$?" So that the linear approximation is deemed "best" under a criterion that mimics "Mean squared error", which is a well-known and widely used optimality criterion as regards deviations in general?
If one follows this path, one will find that setting $x_0 = E(x)$ minimizes $E(R_1^2)$ if the gradient of the CEF is estimated by OLS. Moreover, one finds that in such a case, $E(\tilde x\cdot R_1) = 0$. QED
Implementing this in practice means centering the regressors on their sample mean, while leaving the dependent variable uncentered. | OLS as approximation for non-linear function | WARNING: The results claimed in this post are of contested validity (by the writer himself. When the fog clears I will report back)
Ok. It's a bit long to include the whole proof here, so I will just | OLS as approximation for non-linear function
WARNING: The results claimed in this post are of contested validity (by the writer himself. When the fog clears I will report back)
Ok. It's a bit long to include the whole proof here, so I will just sketch:
Apply a first-order Taylor expansion around some, initially arbitrary point, $x_0$,
$$y = m(x_0) + [x-x_0]'\nabla m(x_0,\theta) + R_1 + \epsilon.$$
where $R_1$ is the Taylor remainder. Set
$$b_0 = m(x_0),\; b = \nabla m(x_0,\theta),\;\beta = (b_o, b)' $$
$$\tilde x = x-x_0,\; u = R_1 + \epsilon$$
and revert to matrix notation
$$\mathbf y = \tilde X \beta + \mathbf u.$$
So what the OLS will attempt to estimate is the gradient of the conditional expectation function, evaluated at some point $x_0$, and the constant term will attempt to estimate the CEF evaluated at that point $x_0$.
The OLS will be
$$\hat \beta = \beta + (\tilde X'\tilde X)^{-1}\tilde X'u \implies \hat \beta - \beta = (\tilde X'\tilde X)^{-1}\tilde X'(\epsilon + R_1)$$
Since $\epsilon$ is by construction the conditional expectation function error, at the limit we will be left with
$$\text{plim}(\hat \beta - \beta) =E(\tilde x\tilde x')\cdot E(\tilde x\cdot R_1)$$
Now, $R_1$ will depend on the choice of $x_0$. Since $R_1$ represents the inaccuracy of the linear approximation, a natural thought is "what center of expansion minimizes the expected square Taylor remainder $E(R_1^2)$?" So that the linear approximation is deemed "best" under a criterion that mimics "Mean squared error", which is a well-known and widely used optimality criterion as regards deviations in general?
If one follows this path, one will find that setting $x_0 = E(x)$ minimizes $E(R_1^2)$ if the gradient of the CEF is estimated by OLS. Moreover, one finds that in such a case, $E(\tilde x\cdot R_1) = 0$. QED
Implementing this in practice means centering the regressors on their sample mean, while leaving the dependent variable uncentered. | OLS as approximation for non-linear function
WARNING: The results claimed in this post are of contested validity (by the writer himself. When the fog clears I will report back)
Ok. It's a bit long to include the whole proof here, so I will just |
20,228 | OLS as approximation for non-linear function | @alecos papadopoulous
The very last statement of your sketch of proof seems a little bit too optmistic. I really do not understand how you can proove that $E[\tilde{x}R_1]=0$.
A majorization of $E[\tilde{x}R_1]$ can be founded if for instance some upper bound to the modulus of the second derivative of $E[Y|X=x]$ is known (see for instance Bera 1984 criticizing a well known paper by white 1980 in International Economic Review), but I do not understand how a general result oabout asymptotic consistency of the OLS estimator towards the derivative of the conditional expectation at some point can be founded. | OLS as approximation for non-linear function | @alecos papadopoulous
The very last statement of your sketch of proof seems a little bit too optmistic. I really do not understand how you can proove that $E[\tilde{x}R_1]=0$.
A majorization of $E[\ti | OLS as approximation for non-linear function
@alecos papadopoulous
The very last statement of your sketch of proof seems a little bit too optmistic. I really do not understand how you can proove that $E[\tilde{x}R_1]=0$.
A majorization of $E[\tilde{x}R_1]$ can be founded if for instance some upper bound to the modulus of the second derivative of $E[Y|X=x]$ is known (see for instance Bera 1984 criticizing a well known paper by white 1980 in International Economic Review), but I do not understand how a general result oabout asymptotic consistency of the OLS estimator towards the derivative of the conditional expectation at some point can be founded. | OLS as approximation for non-linear function
@alecos papadopoulous
The very last statement of your sketch of proof seems a little bit too optmistic. I really do not understand how you can proove that $E[\tilde{x}R_1]=0$.
A majorization of $E[\ti |
20,229 | Which type of data normalizing should be used with KNN? | For k-NN, I'd suggest normalizing the data between $0$ and $1$.
k-NN uses the Euclidean distance, as its means of comparing examples. To calculate the distance between two points $x_1 = (f_1^1, f_1^2, ..., f_1^M)$ and $x_2 = (f_2^1, f_2^2, ..., f_2^M)$, where $f_1^i$ is the value of the $i$-th feature of $x_1$:
$$
d(x_1, x_2) = \sqrt{(f_1^1 - f_2^1)^2 + (f_1^2 - f_2^2)^2 + ... + (f_1^M - f_2^M)^2}
$$
In order for all of the features to be of equal importance when calculating the distance, the features must have the same range of values. This is only achievable through normalization.
If they were not normalized and for instance feature $f^1$ had a range of values in $[0, 1$), while $f^2$ had a range of values in $[1, 10)$. When calculating the distance, the second term would be $10$ times important than the first, leading k-NN to rely more on the second feature than the first. Normalization ensures that all features are mapped to the same range of values.
Standardization, on the other hand, does have many useful properties, but can't ensure that the features are mapped to the same range. While standardization may be best suited for other classifiers, this is not the case for k-NN or any other distance-based classifier. | Which type of data normalizing should be used with KNN? | For k-NN, I'd suggest normalizing the data between $0$ and $1$.
k-NN uses the Euclidean distance, as its means of comparing examples. To calculate the distance between two points $x_1 = (f_1^1, f_1^2, | Which type of data normalizing should be used with KNN?
For k-NN, I'd suggest normalizing the data between $0$ and $1$.
k-NN uses the Euclidean distance, as its means of comparing examples. To calculate the distance between two points $x_1 = (f_1^1, f_1^2, ..., f_1^M)$ and $x_2 = (f_2^1, f_2^2, ..., f_2^M)$, where $f_1^i$ is the value of the $i$-th feature of $x_1$:
$$
d(x_1, x_2) = \sqrt{(f_1^1 - f_2^1)^2 + (f_1^2 - f_2^2)^2 + ... + (f_1^M - f_2^M)^2}
$$
In order for all of the features to be of equal importance when calculating the distance, the features must have the same range of values. This is only achievable through normalization.
If they were not normalized and for instance feature $f^1$ had a range of values in $[0, 1$), while $f^2$ had a range of values in $[1, 10)$. When calculating the distance, the second term would be $10$ times important than the first, leading k-NN to rely more on the second feature than the first. Normalization ensures that all features are mapped to the same range of values.
Standardization, on the other hand, does have many useful properties, but can't ensure that the features are mapped to the same range. While standardization may be best suited for other classifiers, this is not the case for k-NN or any other distance-based classifier. | Which type of data normalizing should be used with KNN?
For k-NN, I'd suggest normalizing the data between $0$ and $1$.
k-NN uses the Euclidean distance, as its means of comparing examples. To calculate the distance between two points $x_1 = (f_1^1, f_1^2, |
20,230 | epsilon-greedy policy improvement? | Ok! If you remember generalized policy iteration, the idea is a policy $\pi$ is first evaluated $v_\pi(s)$ and then improved, into $\pi'$, by acting greedily with respect to our original policy evaluation: $\pi' \rightarrow greedy(v_\pi(s))$. The theorem basically states that acting $\varepsilon$-greedy $still$ will result in policy improvement i.e. a policy with greater reward $v_{\pi'}(s) \geq v_\pi(s)$. The theorem works this out in reverse.
Line 1 left-side: we evaluate our improved policy, $\pi'$, by an action-value function (instead of a value function) with respect to our original policy: $q_\pi(s,\pi'(s)).$
Line 1 right-side: $\sum_{a \in A}\pi'(a|s)q_\pi(s,a) \approx v_{\pi'}(s)$
Line 2: we expand $\pi'(a|s)$, which is the probability of taking an action in a given state, to conform to our definition of being $\varepsilon$-greedy: we choose the max action with $1-\varepsilon$ probability or a random action (which could include the max action) with $\varepsilon/m$ probability where $m$ is the total number of actions.
Line 3: This is by far the most fun part of the proof. $max_{a \in A}q_\pi(s,a)$ is replaced by $\sum_{a \in A}\frac{\pi(a|s)-\varepsilon/m}{1-\varepsilon}q_\pi(s,a).$ The claim is that the max action under $\pi'$ is greater than or equal to a weighted sum of actions under $\pi$ for any arbitrarily chosen max action. To see this, imagine there's two actions we can choose from $A = \{a_1,a_2\}$ where $a_2$ is arbitrarily selected as the max under $\pi$:
$\sum_{a \in A}\frac{\pi(a|s)-\varepsilon/2}{1-\varepsilon}q_\pi(s,a) = \frac{(\varepsilon/2 -\varepsilon/2)q_\pi(s,a_1) + ((1-\varepsilon) + \varepsilon/2 -\varepsilon/2)q_\pi(s,a_2)}{1-\varepsilon} = \frac{(1-\varepsilon)q_\pi(s,a_2)}{1-\varepsilon} = q_\pi(s,a_2).$
The equality is satisfied when the max action under $\pi'$ is the same as $\pi$, namely $a_2$: $ max_{a \in A}q_\pi(s,a) = q_\pi(s,a_2)$. The inequality is satisfied when the max action under $\pi'$ is not $a_2$ in which case: $max_{a \in A}q_\pi(s,a) > q_\pi(s,a_2)$.
Line 4: cancel terms and simplify.
What is crucial to understand is that generalized policy iteration has multiple iterations of evaluation and improvement. The policy under $\pi$ can be different from $\pi'$(hence the difference in selecting $a_2$ as max) because each were improved under different evaluations. This theorem is essentially saying, "Hey, greedily selecting actions after looking at my last choice of greedily selecting actions will either improve my overall reward or just keep it the same." One subtlety (for understanding line 2) is actually (not approximately) $\sum_{a \in A}\pi'(a|s)q_{\pi'}(s,a) = v_{\pi'}(s).$ | epsilon-greedy policy improvement? | Ok! If you remember generalized policy iteration, the idea is a policy $\pi$ is first evaluated $v_\pi(s)$ and then improved, into $\pi'$, by acting greedily with respect to our original policy evalua | epsilon-greedy policy improvement?
Ok! If you remember generalized policy iteration, the idea is a policy $\pi$ is first evaluated $v_\pi(s)$ and then improved, into $\pi'$, by acting greedily with respect to our original policy evaluation: $\pi' \rightarrow greedy(v_\pi(s))$. The theorem basically states that acting $\varepsilon$-greedy $still$ will result in policy improvement i.e. a policy with greater reward $v_{\pi'}(s) \geq v_\pi(s)$. The theorem works this out in reverse.
Line 1 left-side: we evaluate our improved policy, $\pi'$, by an action-value function (instead of a value function) with respect to our original policy: $q_\pi(s,\pi'(s)).$
Line 1 right-side: $\sum_{a \in A}\pi'(a|s)q_\pi(s,a) \approx v_{\pi'}(s)$
Line 2: we expand $\pi'(a|s)$, which is the probability of taking an action in a given state, to conform to our definition of being $\varepsilon$-greedy: we choose the max action with $1-\varepsilon$ probability or a random action (which could include the max action) with $\varepsilon/m$ probability where $m$ is the total number of actions.
Line 3: This is by far the most fun part of the proof. $max_{a \in A}q_\pi(s,a)$ is replaced by $\sum_{a \in A}\frac{\pi(a|s)-\varepsilon/m}{1-\varepsilon}q_\pi(s,a).$ The claim is that the max action under $\pi'$ is greater than or equal to a weighted sum of actions under $\pi$ for any arbitrarily chosen max action. To see this, imagine there's two actions we can choose from $A = \{a_1,a_2\}$ where $a_2$ is arbitrarily selected as the max under $\pi$:
$\sum_{a \in A}\frac{\pi(a|s)-\varepsilon/2}{1-\varepsilon}q_\pi(s,a) = \frac{(\varepsilon/2 -\varepsilon/2)q_\pi(s,a_1) + ((1-\varepsilon) + \varepsilon/2 -\varepsilon/2)q_\pi(s,a_2)}{1-\varepsilon} = \frac{(1-\varepsilon)q_\pi(s,a_2)}{1-\varepsilon} = q_\pi(s,a_2).$
The equality is satisfied when the max action under $\pi'$ is the same as $\pi$, namely $a_2$: $ max_{a \in A}q_\pi(s,a) = q_\pi(s,a_2)$. The inequality is satisfied when the max action under $\pi'$ is not $a_2$ in which case: $max_{a \in A}q_\pi(s,a) > q_\pi(s,a_2)$.
Line 4: cancel terms and simplify.
What is crucial to understand is that generalized policy iteration has multiple iterations of evaluation and improvement. The policy under $\pi$ can be different from $\pi'$(hence the difference in selecting $a_2$ as max) because each were improved under different evaluations. This theorem is essentially saying, "Hey, greedily selecting actions after looking at my last choice of greedily selecting actions will either improve my overall reward or just keep it the same." One subtlety (for understanding line 2) is actually (not approximately) $\sum_{a \in A}\pi'(a|s)q_{\pi'}(s,a) = v_{\pi'}(s).$ | epsilon-greedy policy improvement?
Ok! If you remember generalized policy iteration, the idea is a policy $\pi$ is first evaluated $v_\pi(s)$ and then improved, into $\pi'$, by acting greedily with respect to our original policy evalua |
20,231 | epsilon-greedy policy improvement? | Reinforcement learning is fairly new to me, but hopefully this is helpful. Firstly, some general remarks.
The theorem states that the new policy will not be worse than the previous policy, not that it has to be better.
There is a slight difference in the formulation of the theorem between the book and the slides. The book specifies the first policy to be $\epsilon$-soft, whereas the slides specify $\epsilon$-greedy.
An $\epsilon$-greedy policy is $\epsilon$-greedy with respect to an action-value function, it's useful to think about which action-value function a policy is greedy/$\epsilon$-greedy with respect to.
The $\epsilon$-Greedy policy improvement theorem is the stochastic extension of the policy improvement theorem discussed earlier in Sutton (section 4.2) and in David Silver's lecture. The motivation for the theorem is that we want to find a way of improving policies while ensuring that we explore the environment. Deterministic policies are no good now as there may be state-action pairs that are never encountered under them. One way to ensure exploration is via so called $\epsilon$-soft policies. A policy is $\epsilon$-soft if all actions $a$ have probability of being taken $p(a) \ge \epsilon/N_{a}$, where $\epsilon > 0$ and $N_{a}$ is the number of possible actions.
In both cases of policy improvement the aim is to find a policy $\pi'$ that satisfies $q(s,\pi'(s)) \ge q(s,\pi(s)) = v^{\pi}(s)$, as this implies that $v^{\pi'}(s) \ge v^{\pi}(s)$ and thus we have a better policy. In the deterministic case it was straightforward to arrive at such a policy by construction so it was not necessary to demonstrate that the condition was satisfied. In the stochastic case it is less obvious, and the solution to constructing such a new
policy needs to be shown to satisfy the required condition.
In the deterministic limit ($\epsilon = 0$) of a full greedy policy, we are just back at the case of deterministic policy improvement. Our new policy $\pi'$ is the greedy policy with respect to the action value function of $\pi$, this is exactly the policy constructed to meet the condition in the deterministic case. You're right to say the theorem doesn't say much in this case, it says exactly as much as we already know from the deterministic case, which didn't require proof. We already know how things work in this case and we want to generalise to non-deterministic policies. Hopefully that resolves your second area of confusion.
How do we find a better stochastic policy?
The theorem (according to the book) tells us that given an $\epsilon$-soft policy, $\pi$, we can find a better policy, $\pi'$, by taking the $\epsilon$-greedy policy with respect to the action-value function of $\pi$. Note that $\pi'$ is $\epsilon$-greedy with respect to the action-value function of the previous policy $\pi$, not (in general) its own action-value function. Any policy that is $\epsilon$-greedy with respect to any action-value function is $\epsilon$-soft, i.e. the new policy is still $\epsilon$-soft. Hence we can find another new policy, $\pi''$, this time taking it to be $\epsilon$-greedy with respect to the action-value function of $\pi'$, and this will be better again. We are aiming at the optimal $\epsilon$-soft policy. When we arrive at a policy that is $\epsilon$-greedy with respect to its own action-value function then we are done.
Clearly if a policy is e-greedy, then it is $\epsilon$-soft, giving the formulation on the slide. I think the discussion of $\epsilon$-soft policies in the book helps to illuminate the theorem. Potentially they have avoided introducing $\epsilon$-soft in the slides to reduce the amount of new terminology being presented.
In the case that $\epsilon$ $\approx$ 1, remember that the original policy is also $\epsilon$-greedy so will be almost random. In this case we're essentially saying that we can find an almost random policy that is (occasionally) greedy in a better way than a previous almost random policy. Specifically, we make it "greedy in a better way" by making it $\epsilon$-greedy with respect to the action-value function of the previous policy. | epsilon-greedy policy improvement? | Reinforcement learning is fairly new to me, but hopefully this is helpful. Firstly, some general remarks.
The theorem states that the new policy will not be worse than the previous policy, not that | epsilon-greedy policy improvement?
Reinforcement learning is fairly new to me, but hopefully this is helpful. Firstly, some general remarks.
The theorem states that the new policy will not be worse than the previous policy, not that it has to be better.
There is a slight difference in the formulation of the theorem between the book and the slides. The book specifies the first policy to be $\epsilon$-soft, whereas the slides specify $\epsilon$-greedy.
An $\epsilon$-greedy policy is $\epsilon$-greedy with respect to an action-value function, it's useful to think about which action-value function a policy is greedy/$\epsilon$-greedy with respect to.
The $\epsilon$-Greedy policy improvement theorem is the stochastic extension of the policy improvement theorem discussed earlier in Sutton (section 4.2) and in David Silver's lecture. The motivation for the theorem is that we want to find a way of improving policies while ensuring that we explore the environment. Deterministic policies are no good now as there may be state-action pairs that are never encountered under them. One way to ensure exploration is via so called $\epsilon$-soft policies. A policy is $\epsilon$-soft if all actions $a$ have probability of being taken $p(a) \ge \epsilon/N_{a}$, where $\epsilon > 0$ and $N_{a}$ is the number of possible actions.
In both cases of policy improvement the aim is to find a policy $\pi'$ that satisfies $q(s,\pi'(s)) \ge q(s,\pi(s)) = v^{\pi}(s)$, as this implies that $v^{\pi'}(s) \ge v^{\pi}(s)$ and thus we have a better policy. In the deterministic case it was straightforward to arrive at such a policy by construction so it was not necessary to demonstrate that the condition was satisfied. In the stochastic case it is less obvious, and the solution to constructing such a new
policy needs to be shown to satisfy the required condition.
In the deterministic limit ($\epsilon = 0$) of a full greedy policy, we are just back at the case of deterministic policy improvement. Our new policy $\pi'$ is the greedy policy with respect to the action value function of $\pi$, this is exactly the policy constructed to meet the condition in the deterministic case. You're right to say the theorem doesn't say much in this case, it says exactly as much as we already know from the deterministic case, which didn't require proof. We already know how things work in this case and we want to generalise to non-deterministic policies. Hopefully that resolves your second area of confusion.
How do we find a better stochastic policy?
The theorem (according to the book) tells us that given an $\epsilon$-soft policy, $\pi$, we can find a better policy, $\pi'$, by taking the $\epsilon$-greedy policy with respect to the action-value function of $\pi$. Note that $\pi'$ is $\epsilon$-greedy with respect to the action-value function of the previous policy $\pi$, not (in general) its own action-value function. Any policy that is $\epsilon$-greedy with respect to any action-value function is $\epsilon$-soft, i.e. the new policy is still $\epsilon$-soft. Hence we can find another new policy, $\pi''$, this time taking it to be $\epsilon$-greedy with respect to the action-value function of $\pi'$, and this will be better again. We are aiming at the optimal $\epsilon$-soft policy. When we arrive at a policy that is $\epsilon$-greedy with respect to its own action-value function then we are done.
Clearly if a policy is e-greedy, then it is $\epsilon$-soft, giving the formulation on the slide. I think the discussion of $\epsilon$-soft policies in the book helps to illuminate the theorem. Potentially they have avoided introducing $\epsilon$-soft in the slides to reduce the amount of new terminology being presented.
In the case that $\epsilon$ $\approx$ 1, remember that the original policy is also $\epsilon$-greedy so will be almost random. In this case we're essentially saying that we can find an almost random policy that is (occasionally) greedy in a better way than a previous almost random policy. Specifically, we make it "greedy in a better way" by making it $\epsilon$-greedy with respect to the action-value function of the previous policy. | epsilon-greedy policy improvement?
Reinforcement learning is fairly new to me, but hopefully this is helpful. Firstly, some general remarks.
The theorem states that the new policy will not be worse than the previous policy, not that |
20,232 | epsilon-greedy policy improvement? | Epsilon is defined as the probability of exploration. Exploration is equivalent to picking a random action in action space. This is so that the agent will try out new actions during training, in case these lead to better (future discounted) rewards. If epsilon = 1, the agent will always explore, and never act greedily with respect to the action-value function. Therefore, epsilon < 1 in practice, so that there is a good balance between exploration and exploitation. | epsilon-greedy policy improvement? | Epsilon is defined as the probability of exploration. Exploration is equivalent to picking a random action in action space. This is so that the agent will try out new actions during training, in case | epsilon-greedy policy improvement?
Epsilon is defined as the probability of exploration. Exploration is equivalent to picking a random action in action space. This is so that the agent will try out new actions during training, in case these lead to better (future discounted) rewards. If epsilon = 1, the agent will always explore, and never act greedily with respect to the action-value function. Therefore, epsilon < 1 in practice, so that there is a good balance between exploration and exploitation. | epsilon-greedy policy improvement?
Epsilon is defined as the probability of exploration. Exploration is equivalent to picking a random action in action space. This is so that the agent will try out new actions during training, in case |
20,233 | epsilon-greedy policy improvement? | Sutton RL book says
"Among epsilon-soft policies, epsilon-greedy policies are in some sense those that are closest to greedy."
The theorem assumes that given policy is epsilon soft policy and shows that epsilon greedy on value function obtained by following an epsilon soft policy is optimal.
The fact that policy is episolon soft ensures that weights are non negative. Note that inequality won't hold if weights can be negative.
David silver slides are bit misleading here as they fail to mention that universe of policies considered here are epsilon soft. | epsilon-greedy policy improvement? | Sutton RL book says
"Among epsilon-soft policies, epsilon-greedy policies are in some sense those that are closest to greedy."
The theorem assumes that given policy is epsilon soft policy and shows th | epsilon-greedy policy improvement?
Sutton RL book says
"Among epsilon-soft policies, epsilon-greedy policies are in some sense those that are closest to greedy."
The theorem assumes that given policy is epsilon soft policy and shows that epsilon greedy on value function obtained by following an epsilon soft policy is optimal.
The fact that policy is episolon soft ensures that weights are non negative. Note that inequality won't hold if weights can be negative.
David silver slides are bit misleading here as they fail to mention that universe of policies considered here are epsilon soft. | epsilon-greedy policy improvement?
Sutton RL book says
"Among epsilon-soft policies, epsilon-greedy policies are in some sense those that are closest to greedy."
The theorem assumes that given policy is epsilon soft policy and shows th |
20,234 | epsilon-greedy policy improvement? | I am going through the lectures and the book as well, and had the same confusion as you.
I realize that David does not highlight that the original policy $\pi$ is $\epsilon$-soft in the lecture, meaning every action has probability at least $\epsilon / |\mathcal{A}|$. This is crucial to the proof. This is emphasized in the book (sec 5.4).
However, the theorem does not make sense to me, because if 𝜖≈1, what the theorem implies is that an (almost) random policy would be better than the current one.
You are right. Note that if $\epsilon \approx 1$, then the constraint that the policy $\pi$ must be $\epsilon$-soft implies that $\pi$ too is almost random. All you are saying here is that your new almost random policy will be better than your original almost random policy.
Further, in determinsitic (e.g., greedy) policies, 𝜋(𝑎|𝑠)=0 for 𝑎≠argmax𝑎𝑞𝜋(𝑠,𝑎). Then the theorem tells little.
You are right again. The theorem does not apply to deterministic policies since they are not $\epsilon$-soft. | epsilon-greedy policy improvement? | I am going through the lectures and the book as well, and had the same confusion as you.
I realize that David does not highlight that the original policy $\pi$ is $\epsilon$-soft in the lecture, meani | epsilon-greedy policy improvement?
I am going through the lectures and the book as well, and had the same confusion as you.
I realize that David does not highlight that the original policy $\pi$ is $\epsilon$-soft in the lecture, meaning every action has probability at least $\epsilon / |\mathcal{A}|$. This is crucial to the proof. This is emphasized in the book (sec 5.4).
However, the theorem does not make sense to me, because if 𝜖≈1, what the theorem implies is that an (almost) random policy would be better than the current one.
You are right. Note that if $\epsilon \approx 1$, then the constraint that the policy $\pi$ must be $\epsilon$-soft implies that $\pi$ too is almost random. All you are saying here is that your new almost random policy will be better than your original almost random policy.
Further, in determinsitic (e.g., greedy) policies, 𝜋(𝑎|𝑠)=0 for 𝑎≠argmax𝑎𝑞𝜋(𝑠,𝑎). Then the theorem tells little.
You are right again. The theorem does not apply to deterministic policies since they are not $\epsilon$-soft. | epsilon-greedy policy improvement?
I am going through the lectures and the book as well, and had the same confusion as you.
I realize that David does not highlight that the original policy $\pi$ is $\epsilon$-soft in the lecture, meani |
20,235 | What is a sample of a random variable? | A sample $(X^1,\ldots,X^N)$ is a measurable function from $\Omega_1$ to $\Omega_2^N$. A realisation of this sample is the value taken by the function at $\omega\in\Omega_1$, $(x^1,\ldots,x^N)=(X^1(\omega),\ldots,X^N(\omega))$.
When stating
assuming that $X^n$ are functions and $X^n=X$
The functions $X^n$ are all different functions, which means that the images $X^1(\omega),\ldots,X^N(\omega)$ may be different for a given $\omega$. When the sample is iid (independent and identically distributed), the functions $X^n$ are different with two further properties
identical distribution, meaning that $\mathbb{P}(X^1\in A)=\cdots=\mathbb{P}(X^N\in A)$ for all measurable sets $A$ in $\mathcal{F}_2$;
independence, meaning that $\mathbb{P}(X^1\in A^1,\ldots,X^N\in A^N)=\mathbb{P}(X^1\in A^1)\cdots\mathbb{P}(X^N\in A^N)$ for all measurable sets $A^1,\ldots,A^N$ in $\mathcal{F}_2$
Your definition
\begin{align} \mathbb E[X] = \int_{\Omega_1} X(\omega_1) \,\mathrm
d\omega_1 \end{align}
is incorrect: it should be
\begin{align} \mathbb E[X] = \int_{\Omega_1} X(\omega_1) \,\mathrm
dP(\omega_1) \end{align} | What is a sample of a random variable? | A sample $(X^1,\ldots,X^N)$ is a measurable function from $\Omega_1$ to $\Omega_2^N$. A realisation of this sample is the value taken by the function at $\omega\in\Omega_1$, $(x^1,\ldots,x^N)=(X^1(\om | What is a sample of a random variable?
A sample $(X^1,\ldots,X^N)$ is a measurable function from $\Omega_1$ to $\Omega_2^N$. A realisation of this sample is the value taken by the function at $\omega\in\Omega_1$, $(x^1,\ldots,x^N)=(X^1(\omega),\ldots,X^N(\omega))$.
When stating
assuming that $X^n$ are functions and $X^n=X$
The functions $X^n$ are all different functions, which means that the images $X^1(\omega),\ldots,X^N(\omega)$ may be different for a given $\omega$. When the sample is iid (independent and identically distributed), the functions $X^n$ are different with two further properties
identical distribution, meaning that $\mathbb{P}(X^1\in A)=\cdots=\mathbb{P}(X^N\in A)$ for all measurable sets $A$ in $\mathcal{F}_2$;
independence, meaning that $\mathbb{P}(X^1\in A^1,\ldots,X^N\in A^N)=\mathbb{P}(X^1\in A^1)\cdots\mathbb{P}(X^N\in A^N)$ for all measurable sets $A^1,\ldots,A^N$ in $\mathcal{F}_2$
Your definition
\begin{align} \mathbb E[X] = \int_{\Omega_1} X(\omega_1) \,\mathrm
d\omega_1 \end{align}
is incorrect: it should be
\begin{align} \mathbb E[X] = \int_{\Omega_1} X(\omega_1) \,\mathrm
dP(\omega_1) \end{align} | What is a sample of a random variable?
A sample $(X^1,\ldots,X^N)$ is a measurable function from $\Omega_1$ to $\Omega_2^N$. A realisation of this sample is the value taken by the function at $\omega\in\Omega_1$, $(x^1,\ldots,x^N)=(X^1(\om |
20,236 | What is a sample of a random variable? | Sample can be drawn from population, not from random variable. "Sample of $n$ random variables" is a simplified way of saying that we have a sample drawn from the population, that we assume to be $n$ identically distributed random variables. So such sample behaves like $n$ random variables. It's ambiguous because it mixes terminology used in probability and statistics. The same with simulation, where samples are drawn from common distribution. In both cases sample is the data you have. Samples are considered as random variables because random processes lead to drawing them. They are identically distributed since they come from common distribution. For dealing with samples we have statistics, while statistics use abstract, mathematical description of the it's problems in terms of probability theory, so the terminology is mixed. Random variables are functions assigning probabilities to events that can be encountered in your samples. | What is a sample of a random variable? | Sample can be drawn from population, not from random variable. "Sample of $n$ random variables" is a simplified way of saying that we have a sample drawn from the population, that we assume to be $n$ | What is a sample of a random variable?
Sample can be drawn from population, not from random variable. "Sample of $n$ random variables" is a simplified way of saying that we have a sample drawn from the population, that we assume to be $n$ identically distributed random variables. So such sample behaves like $n$ random variables. It's ambiguous because it mixes terminology used in probability and statistics. The same with simulation, where samples are drawn from common distribution. In both cases sample is the data you have. Samples are considered as random variables because random processes lead to drawing them. They are identically distributed since they come from common distribution. For dealing with samples we have statistics, while statistics use abstract, mathematical description of the it's problems in terms of probability theory, so the terminology is mixed. Random variables are functions assigning probabilities to events that can be encountered in your samples. | What is a sample of a random variable?
Sample can be drawn from population, not from random variable. "Sample of $n$ random variables" is a simplified way of saying that we have a sample drawn from the population, that we assume to be $n$ |
20,237 | How to formulate the offset of a GLM | I don't know where you heard that a Poisson or negative binomial with an offset is preferable to a binomial model for a number of individuals surviving out of an initial number; I would normally prefer a binomial as it is closer to the actual stochastic process we think is going on. Note that the binomial model would be a binomial GLM,
$$
n_{\textrm{surv}} \sim \textrm{Binomial}(p,N)
$$
— different from computing the proportion n/N and using a linear model (or something like that).
However, given that (the edited version of) the question allows for there to be more individuals at the end than at the beginning of the period, the binomial models (and variants such as quasi- or betabinomial) won't work, as they don't allow for an increase in numbers.
In a typical case (not yours) where individuals can only be lost and not gained, the Poisson or negative binomial models will only give sensible answers if the proportion surviving (or the proportion dying, if you quantify mortality rather than survival) is much smaller than 1. In general the variation in the number surviving becomes small as the survival probability approaches 1; the binomial model capture this phenomenon naturally, the Poisson / NB models don't. (The variance becomes small in both models as the probability approaches 0.)
If you do want to use an offset-count model instead, the method for incorporating the offset doesn't differ between Poisson and NB models, both of which almost always use a log link. That is, the model would be written as:
$$
\begin{split}
n_{\textrm{surv}} & \sim \textrm{Poisson}(\mu) \quad \textrm{or} \quad
\sim \textrm{NegBinom}(\mu,k) \\
\mu & = \exp(\beta + \log(N)) = N \exp(\beta)
\end{split}
$$
the second line could also be written as $\log(\mu) = \beta + \log(N)$ (which looks like the regression formula containing an offset) or $\mu/N = \exp(\beta)$, which shows that you're modeling $\beta$ as the log-proportion of survival. In the case where the numbers can increase, $\beta$ would be positive and would represent the log of the expected proportional increase in numbers.
If you happened to decide on an identity link instead (which I wouldn't usually recommend, as it's easy in that case for the optimization process to try negative values for the Poisson/NB mean, which might break the computation), then you'd use an offset of $N$ (not $\log(N)$) so that $\mu = \beta + N$, so $\beta$ represents the additive change in numbers. While sometimes computationally difficult, this does make conceptual sense ...
One possible advantage of the NB model would be that it accounts for overdispersion (e.g., among-individual variation in survival probability), which the binomial or Poisson models don't. You could handle that in the binomial world by switching to a beta-binomial or to a quasi-binomial model ...
If you were using R, assuming your variables are n (surviving number), N (initial number), ttt (a factor/categorical variable specifying treatment group), you would use
glm(n/N~ttt, family=binomial, weights=N) or
glm(n/N~ttt, family=quasibinomial, weights=N) or
glm(n~ttt+offset(log(N)), family=poisson) or
MASS::glm.nb(n~ttt+offset(log(N)))
I've never seen a model with offset(1|initial_no) in it; what software was using this ... ? | How to formulate the offset of a GLM | I don't know where you heard that a Poisson or negative binomial with an offset is preferable to a binomial model for a number of individuals surviving out of an initial number; I would normally prefe | How to formulate the offset of a GLM
I don't know where you heard that a Poisson or negative binomial with an offset is preferable to a binomial model for a number of individuals surviving out of an initial number; I would normally prefer a binomial as it is closer to the actual stochastic process we think is going on. Note that the binomial model would be a binomial GLM,
$$
n_{\textrm{surv}} \sim \textrm{Binomial}(p,N)
$$
— different from computing the proportion n/N and using a linear model (or something like that).
However, given that (the edited version of) the question allows for there to be more individuals at the end than at the beginning of the period, the binomial models (and variants such as quasi- or betabinomial) won't work, as they don't allow for an increase in numbers.
In a typical case (not yours) where individuals can only be lost and not gained, the Poisson or negative binomial models will only give sensible answers if the proportion surviving (or the proportion dying, if you quantify mortality rather than survival) is much smaller than 1. In general the variation in the number surviving becomes small as the survival probability approaches 1; the binomial model capture this phenomenon naturally, the Poisson / NB models don't. (The variance becomes small in both models as the probability approaches 0.)
If you do want to use an offset-count model instead, the method for incorporating the offset doesn't differ between Poisson and NB models, both of which almost always use a log link. That is, the model would be written as:
$$
\begin{split}
n_{\textrm{surv}} & \sim \textrm{Poisson}(\mu) \quad \textrm{or} \quad
\sim \textrm{NegBinom}(\mu,k) \\
\mu & = \exp(\beta + \log(N)) = N \exp(\beta)
\end{split}
$$
the second line could also be written as $\log(\mu) = \beta + \log(N)$ (which looks like the regression formula containing an offset) or $\mu/N = \exp(\beta)$, which shows that you're modeling $\beta$ as the log-proportion of survival. In the case where the numbers can increase, $\beta$ would be positive and would represent the log of the expected proportional increase in numbers.
If you happened to decide on an identity link instead (which I wouldn't usually recommend, as it's easy in that case for the optimization process to try negative values for the Poisson/NB mean, which might break the computation), then you'd use an offset of $N$ (not $\log(N)$) so that $\mu = \beta + N$, so $\beta$ represents the additive change in numbers. While sometimes computationally difficult, this does make conceptual sense ...
One possible advantage of the NB model would be that it accounts for overdispersion (e.g., among-individual variation in survival probability), which the binomial or Poisson models don't. You could handle that in the binomial world by switching to a beta-binomial or to a quasi-binomial model ...
If you were using R, assuming your variables are n (surviving number), N (initial number), ttt (a factor/categorical variable specifying treatment group), you would use
glm(n/N~ttt, family=binomial, weights=N) or
glm(n/N~ttt, family=quasibinomial, weights=N) or
glm(n~ttt+offset(log(N)), family=poisson) or
MASS::glm.nb(n~ttt+offset(log(N)))
I've never seen a model with offset(1|initial_no) in it; what software was using this ... ? | How to formulate the offset of a GLM
I don't know where you heard that a Poisson or negative binomial with an offset is preferable to a binomial model for a number of individuals surviving out of an initial number; I would normally prefe |
20,238 | Mean of inverse exponential distribution | Given that the inverse exponential distribution has $\alpha = 1$, you have stumbled upon the fact that the mean of the inverse exponential is $\infty$. And therefore, the variance of the inverse exponential is undefined.
If $G$ is inverse exponentially distributed, $E(G^r)$ exists and is finite for $r < 1$, and $= \infty$ for $r = 1$. | Mean of inverse exponential distribution | Given that the inverse exponential distribution has $\alpha = 1$, you have stumbled upon the fact that the mean of the inverse exponential is $\infty$. And therefore, the variance of the inverse expo | Mean of inverse exponential distribution
Given that the inverse exponential distribution has $\alpha = 1$, you have stumbled upon the fact that the mean of the inverse exponential is $\infty$. And therefore, the variance of the inverse exponential is undefined.
If $G$ is inverse exponentially distributed, $E(G^r)$ exists and is finite for $r < 1$, and $= \infty$ for $r = 1$. | Mean of inverse exponential distribution
Given that the inverse exponential distribution has $\alpha = 1$, you have stumbled upon the fact that the mean of the inverse exponential is $\infty$. And therefore, the variance of the inverse expo |
20,239 | Mean of inverse exponential distribution | I'll show the calculation for the mean of an Exponential distribution so it will recall you the approach. Then, I'll go for the inverse Exponential with the same approach.
Given $f_Y(y) = \lambda e^{-\lambda y}$
$E[Y] = \int_0^\infty{yf_Y(y) dy}$
$ = \int_0^\infty{y \lambda e^{-\lambda y} dy}$
$ = \lambda \int_0^\infty{y e^{-\lambda y} dy}$
Integrating by part (ignore the $\lambda$ in front of the integral for the moment),
$u = y, dv=e^{-\lambda y} dy$
$du = dy, v = \frac{-1}{\lambda}e^{-\lambda y}$
$ = y \frac{-1}{\lambda}e^{-\lambda y} - \int_0^\infty{ \frac{-1}{\lambda}e^{-\lambda y} dy}$
$ = y \frac{-1}{\lambda}e^{-\lambda y} + \frac{1}{\lambda} \int_0^\infty{ e^{-\lambda y} dy}$
$ = y \frac{-1}{\lambda}e^{-\lambda y} - \frac{1}{\lambda^2} e^{-\lambda y}$
Multiply by the $\lambda$ in front of the integral,
$ = - y e^{-\lambda y} - \frac{1}{\lambda} e^{-\lambda y}$
Evaluate for $0$ and $\infty$,
$ = (0 - 0) - \frac{1}{\lambda} (0 - 1)$
$ = \lambda^{-1}$
Which is a known results.
For $G = \frac{1}{Y}$, the same logic apply.
$E[G] = E[\frac{1}{Y}]= \int_0^\infty{\frac{1}{y} f_Y(y) dy}$
$ = \int_0^\infty{\frac{1}{y} \lambda e^{-\lambda y} dy}$
$ = \lambda \int_0^\infty{\frac{1}{y} e^{-\lambda y} dy}$
The main difference is that for an integration by parts,
$u = y^{-1}$
and
$du = -1y^{-2}$
so it doesn't help us for $G = \frac{1}{y}$. I think the integral is undefined here. Wolfram alpha tell me it doesn't converge.
http://www.wolframalpha.com/input/?i=integrate+from+0+to+infinity+(1%2Fx)+exp(-x)+dx
So the mean doesn't exist for the inverse Exponential, or, equivalently, for the inverse Gamma with $\alpha=1$. The reason is similar for the variance and $\alpha \gt 2$. | Mean of inverse exponential distribution | I'll show the calculation for the mean of an Exponential distribution so it will recall you the approach. Then, I'll go for the inverse Exponential with the same approach.
Given $f_Y(y) = \lambda e^{- | Mean of inverse exponential distribution
I'll show the calculation for the mean of an Exponential distribution so it will recall you the approach. Then, I'll go for the inverse Exponential with the same approach.
Given $f_Y(y) = \lambda e^{-\lambda y}$
$E[Y] = \int_0^\infty{yf_Y(y) dy}$
$ = \int_0^\infty{y \lambda e^{-\lambda y} dy}$
$ = \lambda \int_0^\infty{y e^{-\lambda y} dy}$
Integrating by part (ignore the $\lambda$ in front of the integral for the moment),
$u = y, dv=e^{-\lambda y} dy$
$du = dy, v = \frac{-1}{\lambda}e^{-\lambda y}$
$ = y \frac{-1}{\lambda}e^{-\lambda y} - \int_0^\infty{ \frac{-1}{\lambda}e^{-\lambda y} dy}$
$ = y \frac{-1}{\lambda}e^{-\lambda y} + \frac{1}{\lambda} \int_0^\infty{ e^{-\lambda y} dy}$
$ = y \frac{-1}{\lambda}e^{-\lambda y} - \frac{1}{\lambda^2} e^{-\lambda y}$
Multiply by the $\lambda$ in front of the integral,
$ = - y e^{-\lambda y} - \frac{1}{\lambda} e^{-\lambda y}$
Evaluate for $0$ and $\infty$,
$ = (0 - 0) - \frac{1}{\lambda} (0 - 1)$
$ = \lambda^{-1}$
Which is a known results.
For $G = \frac{1}{Y}$, the same logic apply.
$E[G] = E[\frac{1}{Y}]= \int_0^\infty{\frac{1}{y} f_Y(y) dy}$
$ = \int_0^\infty{\frac{1}{y} \lambda e^{-\lambda y} dy}$
$ = \lambda \int_0^\infty{\frac{1}{y} e^{-\lambda y} dy}$
The main difference is that for an integration by parts,
$u = y^{-1}$
and
$du = -1y^{-2}$
so it doesn't help us for $G = \frac{1}{y}$. I think the integral is undefined here. Wolfram alpha tell me it doesn't converge.
http://www.wolframalpha.com/input/?i=integrate+from+0+to+infinity+(1%2Fx)+exp(-x)+dx
So the mean doesn't exist for the inverse Exponential, or, equivalently, for the inverse Gamma with $\alpha=1$. The reason is similar for the variance and $\alpha \gt 2$. | Mean of inverse exponential distribution
I'll show the calculation for the mean of an Exponential distribution so it will recall you the approach. Then, I'll go for the inverse Exponential with the same approach.
Given $f_Y(y) = \lambda e^{- |
20,240 | Mean of inverse exponential distribution | After a quick simulation (in R), it seems that the mean does not exist :
n<-1000
rates <- c(1,0.5,2,10)
par(mfrow = c(2,2))
for(rate in rates)
{
plot(cumsum(1/rexp(n, rate))/seq(1,n),type='l',main = paste0("Rate = ",rate),
xlab = "Sample size", ylab = "Empirical Mean")
}
For the sake of comparison, here is what happens with a genuine exponential random variable. | Mean of inverse exponential distribution | After a quick simulation (in R), it seems that the mean does not exist :
n<-1000
rates <- c(1,0.5,2,10)
par(mfrow = c(2,2))
for(rate in rates)
{
plot(cumsum(1/rexp(n, rate))/seq(1,n),type='l',main | Mean of inverse exponential distribution
After a quick simulation (in R), it seems that the mean does not exist :
n<-1000
rates <- c(1,0.5,2,10)
par(mfrow = c(2,2))
for(rate in rates)
{
plot(cumsum(1/rexp(n, rate))/seq(1,n),type='l',main = paste0("Rate = ",rate),
xlab = "Sample size", ylab = "Empirical Mean")
}
For the sake of comparison, here is what happens with a genuine exponential random variable. | Mean of inverse exponential distribution
After a quick simulation (in R), it seems that the mean does not exist :
n<-1000
rates <- c(1,0.5,2,10)
par(mfrow = c(2,2))
for(rate in rates)
{
plot(cumsum(1/rexp(n, rate))/seq(1,n),type='l',main |
20,241 | Mean of inverse exponential distribution | You actually can bypass this expectation by introducing a small number $\varepsilon$, so that
$$
\frac{E[G]}{\lambda} = \int_0^{\infty}{ \frac{1}{t} e^{-\lambda t} dt }
= \lim\limits_{\varepsilon\to 0}
\int_0^{\frac{1}{\varepsilon}}{ \frac{1}{t+\varepsilon} e^{-\lambda t} dt }
= \lim\limits_{\varepsilon\to 0}~\big\{e^{\lambda \varepsilon} \Gamma(0; \lambda \varepsilon) - e^{\lambda \varepsilon} \Gamma(0; \lambda (\varepsilon^{-1}+\varepsilon)) \big\}
$$
where $\Gamma(\cdot,\cdot)$ is the upper incomplete Gamma function.
With the above equation, you can do whatever you want with $\lambda$.
For example, if you choose a $\lambda$ satisfying $\lambda \epsilon \to 1$, thus $\lambda \to \infty$, we obtain that
$$
E[G] \to e \lambda \Gamma(0,1).
$$
In this case, $E[G]$ does exist as $\lambda \to \infty$. | Mean of inverse exponential distribution | You actually can bypass this expectation by introducing a small number $\varepsilon$, so that
$$
\frac{E[G]}{\lambda} = \int_0^{\infty}{ \frac{1}{t} e^{-\lambda t} dt }
= \lim\limits_{\varepsilon\to | Mean of inverse exponential distribution
You actually can bypass this expectation by introducing a small number $\varepsilon$, so that
$$
\frac{E[G]}{\lambda} = \int_0^{\infty}{ \frac{1}{t} e^{-\lambda t} dt }
= \lim\limits_{\varepsilon\to 0}
\int_0^{\frac{1}{\varepsilon}}{ \frac{1}{t+\varepsilon} e^{-\lambda t} dt }
= \lim\limits_{\varepsilon\to 0}~\big\{e^{\lambda \varepsilon} \Gamma(0; \lambda \varepsilon) - e^{\lambda \varepsilon} \Gamma(0; \lambda (\varepsilon^{-1}+\varepsilon)) \big\}
$$
where $\Gamma(\cdot,\cdot)$ is the upper incomplete Gamma function.
With the above equation, you can do whatever you want with $\lambda$.
For example, if you choose a $\lambda$ satisfying $\lambda \epsilon \to 1$, thus $\lambda \to \infty$, we obtain that
$$
E[G] \to e \lambda \Gamma(0,1).
$$
In this case, $E[G]$ does exist as $\lambda \to \infty$. | Mean of inverse exponential distribution
You actually can bypass this expectation by introducing a small number $\varepsilon$, so that
$$
\frac{E[G]}{\lambda} = \int_0^{\infty}{ \frac{1}{t} e^{-\lambda t} dt }
= \lim\limits_{\varepsilon\to |
20,242 | Explain how `eigen` helps inverting a matrix | 1) The eigendecomposition doesn't really help that much. It is certainly more numerically stable than a Cholesky factorization, which is helpful if your matrix is ill-conditioned/nearly singular/has a high condition number. So you can use the eigendecomposition and it will give you A solution to your problem. But there's little guarantee that it will be the RIGHT solution. Honestly, once you explicitly invert $\Sigma$, the damage is already done. Forming $X^T \Sigma^{-1} X$ just makes matters worse. The eigendecomposition will help you win the battle, but the war is most certainly lost.
2) Without knowing the specifics of your problem, this is what I would do. First, perform a Cholesky factorization on $\Sigma$ so that $\Sigma = L L^T$. Then perform a QR factorization on $L^{-1} X$ so that $L^{-1} X = QR$. Please be sure to compute $L^{-1} X$ using forward substitution - DO NOT explicitly invert $L$. So then you get:
$$
\begin{array}{}
X^T \Sigma^{-1} X & = & X^T (L L^T)^{-1} X \\
& = & X^T L^{-T} L^{-1} X \\
& = & (L^{-1} X)^T (L^{-1} X) \\
& = & (Q R)^T Q R \\
& = & R^T Q^T Q T \\
& = & R^T R
\end{array}
$$
From here, you can solve any right hand side you want. But again, please do not explicitly invert $R$ (or $R^T R$). Use forward and backward substitutions as necessary.
BTW, I'm curious about the right hand side of your equation. You wrote that it's $X^T \Sigma Y$. Are you sure it's not $X^T \Sigma^{-1} Y$? Because if it were, you could use a similar trick on the right hand side:
$$
\begin{array}{}
X^T \Sigma^{-1} Y & = & X^T (L L^T)^{-1} Y \\
& = & X^T L^{-T} L^{-1} Y \\
& = & (L^{-1} X)^T L^{-1} Y \\
& = & (Q R)^T L^{-1} Y \\
& = & R^T Q^T L^{-1} Y
\end{array}
$$
And then you can deliver the coup de grâce when you go to solve for $\beta$:
$$
\begin{array}{}
X^T \Sigma^{-1} X \beta & = & X^T \Sigma^{-1} Y \\
R^T R \beta & = & R^T Q^T L^{-1} Y \\
R \beta & = & Q^T L^{-1} Y \\
\beta & = & R^{-1} Q^T L^{-1} Y
\end{array}
$$
Of course, you would never explicitly invert $R$ for the final step, right? That's just a backward substitution. :-) | Explain how `eigen` helps inverting a matrix | 1) The eigendecomposition doesn't really help that much. It is certainly more numerically stable than a Cholesky factorization, which is helpful if your matrix is ill-conditioned/nearly singular/has | Explain how `eigen` helps inverting a matrix
1) The eigendecomposition doesn't really help that much. It is certainly more numerically stable than a Cholesky factorization, which is helpful if your matrix is ill-conditioned/nearly singular/has a high condition number. So you can use the eigendecomposition and it will give you A solution to your problem. But there's little guarantee that it will be the RIGHT solution. Honestly, once you explicitly invert $\Sigma$, the damage is already done. Forming $X^T \Sigma^{-1} X$ just makes matters worse. The eigendecomposition will help you win the battle, but the war is most certainly lost.
2) Without knowing the specifics of your problem, this is what I would do. First, perform a Cholesky factorization on $\Sigma$ so that $\Sigma = L L^T$. Then perform a QR factorization on $L^{-1} X$ so that $L^{-1} X = QR$. Please be sure to compute $L^{-1} X$ using forward substitution - DO NOT explicitly invert $L$. So then you get:
$$
\begin{array}{}
X^T \Sigma^{-1} X & = & X^T (L L^T)^{-1} X \\
& = & X^T L^{-T} L^{-1} X \\
& = & (L^{-1} X)^T (L^{-1} X) \\
& = & (Q R)^T Q R \\
& = & R^T Q^T Q T \\
& = & R^T R
\end{array}
$$
From here, you can solve any right hand side you want. But again, please do not explicitly invert $R$ (or $R^T R$). Use forward and backward substitutions as necessary.
BTW, I'm curious about the right hand side of your equation. You wrote that it's $X^T \Sigma Y$. Are you sure it's not $X^T \Sigma^{-1} Y$? Because if it were, you could use a similar trick on the right hand side:
$$
\begin{array}{}
X^T \Sigma^{-1} Y & = & X^T (L L^T)^{-1} Y \\
& = & X^T L^{-T} L^{-1} Y \\
& = & (L^{-1} X)^T L^{-1} Y \\
& = & (Q R)^T L^{-1} Y \\
& = & R^T Q^T L^{-1} Y
\end{array}
$$
And then you can deliver the coup de grâce when you go to solve for $\beta$:
$$
\begin{array}{}
X^T \Sigma^{-1} X \beta & = & X^T \Sigma^{-1} Y \\
R^T R \beta & = & R^T Q^T L^{-1} Y \\
R \beta & = & Q^T L^{-1} Y \\
\beta & = & R^{-1} Q^T L^{-1} Y
\end{array}
$$
Of course, you would never explicitly invert $R$ for the final step, right? That's just a backward substitution. :-) | Explain how `eigen` helps inverting a matrix
1) The eigendecomposition doesn't really help that much. It is certainly more numerically stable than a Cholesky factorization, which is helpful if your matrix is ill-conditioned/nearly singular/has |
20,243 | Automatic keyword extraction: using cosine similarities as features | I don't know how it's possible to do keyword extraction with supervised learning, but I do know how to do it with unsupervised learning.
There are several methods of doing this, so here they are:
Hierarchical
You can apply any hierarchical clustering method on the term similarity matrix directly (with any similarity function, not just cosine)
In scikit-learn you'd do something like this:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import AgglomerativeClustering
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(data)
C = 1 - cosine_similarity(X.T)
ward = AgglomerativeClustering(n_clusters=k, linkage='ward').fit(C)
label = ward.labels_
Source: [1]
But since it's agglomerative clustering, it's computationally expensive and it'll take a while to compute.
K-Means
Another possibility is to do usual k-means on rows of the term-document matrix, and then find most common terms for each centroid
For example, in scikit learn this is the way of doing it:
from sklearn.cluster import KMeans
km = KMeans(n_clusters=k, init='k-means++', max_iter=100, n_init=1)
km.fit(X)
order_centroids = km.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(k):
print("Cluster %d:" % i, end='')
for ind in order_centroids[i, :10]:
print(' %s' % terms[ind], end='')
Source: [2]
But k-means relies on Euclidean distance, which is bad for sparse high-dimensional data. There are other techniques that work better for texts and use cosine similarity
Cosine K-Means and Scatter/Gather
It's possible to use Cosine with K-means (see e.g. [3]): calculate centroids as a mean over all documents in each cluster, and then use cosine to calculate the distance to the closest centroid.
At the end, you can extract keywords the same way as for usual k-means.
Calculating the average centroid as a mean of all documents in the cluster is not always good. Another approach is suggested in the Scatter/Gather algorithm [4]: the centroid of a cluster is concatenation of all the documents in this cluster.
For this approach you'll just need to take most frequent terms for each centroid cluster.
There's no implementation of these algorithms in scikit learn, but you can easily implement them yourself by extending KMeans.
Note that in both cases the centroids become quite dense: denser than the rest of the documents in each clusters, so you may want to truncate terms in the centroids, i.e. remove "unimportant" ones. (see [8]).
Spectral Clustering
Another way would be to apply spectral clustering. You'll need to supply a similarity matrix, which you already have, and it will find clusters on it.
It's implemented in the SpectralClustering class, see examples in [5]. Note that since you already have a pre-computed matrix, you need to use affinity='precumputed' attribute when initializing.
Spectral clustering is related to Kernel KMeans: there is paper (see [7]) that shows that they are the same thing. I recently came across an implementation of Kernel KMeans that may be useful: https://gist.github.com/mblondel/6230787
Non-Negative Matrix Factorization
Finally, you can cluster you term-document matrix with some decomposition techniques from Linear Algebra, like SVD (this would be so-called "Latent Semantic Analysis") or Non-Negative Matrix Factorization. The latter can be seen as clustering, and it can cluster both rows and columns of the matrix at the same time.
For example, you can extract keywords by doing
from sklearn.decomposition import NMF
nmf = NMF(n_components=k, random_state=1).fit(X)
feature_names = vectorizer.get_feature_names()
for topic_idx, topic in enumerate(nmf.components_):
print("Topic #%d:" % topic_idx)
print(" ".join([feature_names[i]
for i in topic.argsort()[:-10-1:-1]]))
print()
Code source: [6]
Even though here the examples are in python scikit-learn, I think it shouldn't be a big problem to find some examples for R
Sources
[1]: http://scikit-learn.org/stable/auto_examples/cluster/plot_ward_structured_vs_unstructured.html
[2]: http://scikit-learn.org/stable/auto_examples/text/document_clustering.html#example-text-document-clustering-py
[3]: Larsen, Bjornar, and Chinatsu Aone. "Fast and effective text mining using linear-time document clustering." (pdf)
[4]: Cutting, Douglass R., et al. "Scatter/gather: A cluster-based approach to browsing large document collections." (pdf)
[5]: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html
[6]: http://scikit-learn.org/stable/auto_examples/applications/topics_extraction_with_nmf.html
[7]: Dhillon, Inderjit S., Yuqiang Guan, and Brian Kulis. "Kernel k-means: spectral clustering and normalized cuts." (pdf)
[8]: Schütze, Hinrich, and Craig Silverstein. "Projections for efficient document clustering." (acm website) | Automatic keyword extraction: using cosine similarities as features | I don't know how it's possible to do keyword extraction with supervised learning, but I do know how to do it with unsupervised learning.
There are several methods of doing this, so here they are:
Hi | Automatic keyword extraction: using cosine similarities as features
I don't know how it's possible to do keyword extraction with supervised learning, but I do know how to do it with unsupervised learning.
There are several methods of doing this, so here they are:
Hierarchical
You can apply any hierarchical clustering method on the term similarity matrix directly (with any similarity function, not just cosine)
In scikit-learn you'd do something like this:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import AgglomerativeClustering
vectorizer = TfidfVectorizer(stop_words='english')
X = vectorizer.fit_transform(data)
C = 1 - cosine_similarity(X.T)
ward = AgglomerativeClustering(n_clusters=k, linkage='ward').fit(C)
label = ward.labels_
Source: [1]
But since it's agglomerative clustering, it's computationally expensive and it'll take a while to compute.
K-Means
Another possibility is to do usual k-means on rows of the term-document matrix, and then find most common terms for each centroid
For example, in scikit learn this is the way of doing it:
from sklearn.cluster import KMeans
km = KMeans(n_clusters=k, init='k-means++', max_iter=100, n_init=1)
km.fit(X)
order_centroids = km.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(k):
print("Cluster %d:" % i, end='')
for ind in order_centroids[i, :10]:
print(' %s' % terms[ind], end='')
Source: [2]
But k-means relies on Euclidean distance, which is bad for sparse high-dimensional data. There are other techniques that work better for texts and use cosine similarity
Cosine K-Means and Scatter/Gather
It's possible to use Cosine with K-means (see e.g. [3]): calculate centroids as a mean over all documents in each cluster, and then use cosine to calculate the distance to the closest centroid.
At the end, you can extract keywords the same way as for usual k-means.
Calculating the average centroid as a mean of all documents in the cluster is not always good. Another approach is suggested in the Scatter/Gather algorithm [4]: the centroid of a cluster is concatenation of all the documents in this cluster.
For this approach you'll just need to take most frequent terms for each centroid cluster.
There's no implementation of these algorithms in scikit learn, but you can easily implement them yourself by extending KMeans.
Note that in both cases the centroids become quite dense: denser than the rest of the documents in each clusters, so you may want to truncate terms in the centroids, i.e. remove "unimportant" ones. (see [8]).
Spectral Clustering
Another way would be to apply spectral clustering. You'll need to supply a similarity matrix, which you already have, and it will find clusters on it.
It's implemented in the SpectralClustering class, see examples in [5]. Note that since you already have a pre-computed matrix, you need to use affinity='precumputed' attribute when initializing.
Spectral clustering is related to Kernel KMeans: there is paper (see [7]) that shows that they are the same thing. I recently came across an implementation of Kernel KMeans that may be useful: https://gist.github.com/mblondel/6230787
Non-Negative Matrix Factorization
Finally, you can cluster you term-document matrix with some decomposition techniques from Linear Algebra, like SVD (this would be so-called "Latent Semantic Analysis") or Non-Negative Matrix Factorization. The latter can be seen as clustering, and it can cluster both rows and columns of the matrix at the same time.
For example, you can extract keywords by doing
from sklearn.decomposition import NMF
nmf = NMF(n_components=k, random_state=1).fit(X)
feature_names = vectorizer.get_feature_names()
for topic_idx, topic in enumerate(nmf.components_):
print("Topic #%d:" % topic_idx)
print(" ".join([feature_names[i]
for i in topic.argsort()[:-10-1:-1]]))
print()
Code source: [6]
Even though here the examples are in python scikit-learn, I think it shouldn't be a big problem to find some examples for R
Sources
[1]: http://scikit-learn.org/stable/auto_examples/cluster/plot_ward_structured_vs_unstructured.html
[2]: http://scikit-learn.org/stable/auto_examples/text/document_clustering.html#example-text-document-clustering-py
[3]: Larsen, Bjornar, and Chinatsu Aone. "Fast and effective text mining using linear-time document clustering." (pdf)
[4]: Cutting, Douglass R., et al. "Scatter/gather: A cluster-based approach to browsing large document collections." (pdf)
[5]: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html
[6]: http://scikit-learn.org/stable/auto_examples/applications/topics_extraction_with_nmf.html
[7]: Dhillon, Inderjit S., Yuqiang Guan, and Brian Kulis. "Kernel k-means: spectral clustering and normalized cuts." (pdf)
[8]: Schütze, Hinrich, and Craig Silverstein. "Projections for efficient document clustering." (acm website) | Automatic keyword extraction: using cosine similarities as features
I don't know how it's possible to do keyword extraction with supervised learning, but I do know how to do it with unsupervised learning.
There are several methods of doing this, so here they are:
Hi |
20,244 | Understanding Gaussian Basis function parameters to be used in linear regression | As you are confused let me start by stating the problem and taking your questions one by one. You have a sample size of 10,000 and each sample is described by a feature vector $x\in\mathbb{R}^{31}$. If you want to perform regression using Gaussian radial basis functions then are looking for a function of the form $$f(x) = \sum_{j}{w_j * g_j(x; \mu_j,\sigma_j}), j=1..m$$ where the $g_i$ are your basis functions. Specifically, you need to find the $m$ weights $w_j$ so that for given parameters $\mu_j$ and $\sigma_j$ you minimise the error between $y$ and the corresponding prediction $\hat{y}$ = $f(\hat{x})$ - typically you will minimise the least squares error.
What exactly is the Mu subscript j parameter?
You need to find $m$ basis functions $g_j$. (You still need to determine the number $m$) Each basis function will have a $\mu_j$ and a $\sigma_j$ (also unknown). The subscript $j$ ranges from $1$ to $m$.
Is the $\mu_j$ a vector?
Yes, it is a point in $\mathbb{R}^{31}$. In other words, it is point somewhere in your feature space and a $\mu$ must be determined for each of the $m$ basis functions.
I've read that this governs the locations of the basis functions. So is this not the mean of something?
The $j^{th}$ basis function is centered at $\mu_j$. You will need to decide on where these locations are. So no, it is not necessarily the mean of anything (but see further down for ways to determine it)
Now for the sigma that "governs the spatial scale". What exactly is that?
$\sigma$ is easier to understand if we turn to the basis functions themselves.
It helps to think of the Gaussian radial basis functions in lower dimensons, say $\mathbb{R}^{1}$ or $\mathbb{R}^{2}$. In $\mathbb{R}^{1}$ the Gaussian radial basis function is just the well-known bell curve. The bell can of course be narrow or wide. The width is determined by $\sigma$ – the larger $\sigma$is the narrower the bell shape. In other words, $\sigma$ scales the width of the bell shape. So for $\sigma$ = 1 we have no scaling. For large $\sigma$ we have substantial scaling.
You may ask what the purpose of this is. If you think of the bell covering some portion of space (a line in $\mathbb{R}^{1}$) – a narrow bell will only cover a small part of the line*. Points $x$ close to the centre of the bell will have a larger $g_j(x)$ value. Points far from the centre will have a smaller $g_j(x)$ value. Scaling has the effect of pushing points further from the centre – as the bell narrows points will be located further from the centre - reducing the value of $g_j(x)$
Each basis function converts input vector x into a scalar value
Yes, you are evaluating the basis functions at some point $\mathbf{x}\in\mathbb{R}^{31}$.
$$\exp\left({-\frac{\|\mathbf{x}-\mu_j\|_2^2}{2*\sigma_j^2}}\right)$$
You get a scalar as a result. The scalar result depends on the distance of the point $\mathbf{x}$ from the centre $\mu_j$ given by $\|\mathbf{x}-\mu_j\|$ and the scalar $\sigma_j$.
I've seen some implementations that try such values as .1, .5, 2.5 for this parameter. How are these values computed?
This of course is one of the interesting and difficult aspects of using Gaussian radial basis functions. if you search the web you will find many suggestions as to how these parameters are determined. I will outline in very simple terms one possibility based on clustering. You can find this and several other suggestions online.
Start by clustering your 10000 samples (you could first use PCA to reduce the dimensions followed by k-Means clustering). You can let $m$ be the number of clusters you find (typically employing cross validation to determine the best $m$). Now, create a radial basis function $g_j$ for each cluster. For each radial basis function let $\mu_j$ be the center (e.g. mean, centroid, etc) of the cluster. Let $\sigma_j$ reflect the width of the cluster (eg radius...) Now go ahead and perform your regression (this simple description is just an overview- it needs lots of work at each step!)
*Of course, the bell curve is defined from -$\infty$ to $\infty$ so will have a value everywhere on the line. However, the values far from the centre are negligible | Understanding Gaussian Basis function parameters to be used in linear regression | As you are confused let me start by stating the problem and taking your questions one by one. You have a sample size of 10,000 and each sample is described by a feature vector $x\in\mathbb{R}^{31}$. I | Understanding Gaussian Basis function parameters to be used in linear regression
As you are confused let me start by stating the problem and taking your questions one by one. You have a sample size of 10,000 and each sample is described by a feature vector $x\in\mathbb{R}^{31}$. If you want to perform regression using Gaussian radial basis functions then are looking for a function of the form $$f(x) = \sum_{j}{w_j * g_j(x; \mu_j,\sigma_j}), j=1..m$$ where the $g_i$ are your basis functions. Specifically, you need to find the $m$ weights $w_j$ so that for given parameters $\mu_j$ and $\sigma_j$ you minimise the error between $y$ and the corresponding prediction $\hat{y}$ = $f(\hat{x})$ - typically you will minimise the least squares error.
What exactly is the Mu subscript j parameter?
You need to find $m$ basis functions $g_j$. (You still need to determine the number $m$) Each basis function will have a $\mu_j$ and a $\sigma_j$ (also unknown). The subscript $j$ ranges from $1$ to $m$.
Is the $\mu_j$ a vector?
Yes, it is a point in $\mathbb{R}^{31}$. In other words, it is point somewhere in your feature space and a $\mu$ must be determined for each of the $m$ basis functions.
I've read that this governs the locations of the basis functions. So is this not the mean of something?
The $j^{th}$ basis function is centered at $\mu_j$. You will need to decide on where these locations are. So no, it is not necessarily the mean of anything (but see further down for ways to determine it)
Now for the sigma that "governs the spatial scale". What exactly is that?
$\sigma$ is easier to understand if we turn to the basis functions themselves.
It helps to think of the Gaussian radial basis functions in lower dimensons, say $\mathbb{R}^{1}$ or $\mathbb{R}^{2}$. In $\mathbb{R}^{1}$ the Gaussian radial basis function is just the well-known bell curve. The bell can of course be narrow or wide. The width is determined by $\sigma$ – the larger $\sigma$is the narrower the bell shape. In other words, $\sigma$ scales the width of the bell shape. So for $\sigma$ = 1 we have no scaling. For large $\sigma$ we have substantial scaling.
You may ask what the purpose of this is. If you think of the bell covering some portion of space (a line in $\mathbb{R}^{1}$) – a narrow bell will only cover a small part of the line*. Points $x$ close to the centre of the bell will have a larger $g_j(x)$ value. Points far from the centre will have a smaller $g_j(x)$ value. Scaling has the effect of pushing points further from the centre – as the bell narrows points will be located further from the centre - reducing the value of $g_j(x)$
Each basis function converts input vector x into a scalar value
Yes, you are evaluating the basis functions at some point $\mathbf{x}\in\mathbb{R}^{31}$.
$$\exp\left({-\frac{\|\mathbf{x}-\mu_j\|_2^2}{2*\sigma_j^2}}\right)$$
You get a scalar as a result. The scalar result depends on the distance of the point $\mathbf{x}$ from the centre $\mu_j$ given by $\|\mathbf{x}-\mu_j\|$ and the scalar $\sigma_j$.
I've seen some implementations that try such values as .1, .5, 2.5 for this parameter. How are these values computed?
This of course is one of the interesting and difficult aspects of using Gaussian radial basis functions. if you search the web you will find many suggestions as to how these parameters are determined. I will outline in very simple terms one possibility based on clustering. You can find this and several other suggestions online.
Start by clustering your 10000 samples (you could first use PCA to reduce the dimensions followed by k-Means clustering). You can let $m$ be the number of clusters you find (typically employing cross validation to determine the best $m$). Now, create a radial basis function $g_j$ for each cluster. For each radial basis function let $\mu_j$ be the center (e.g. mean, centroid, etc) of the cluster. Let $\sigma_j$ reflect the width of the cluster (eg radius...) Now go ahead and perform your regression (this simple description is just an overview- it needs lots of work at each step!)
*Of course, the bell curve is defined from -$\infty$ to $\infty$ so will have a value everywhere on the line. However, the values far from the centre are negligible | Understanding Gaussian Basis function parameters to be used in linear regression
As you are confused let me start by stating the problem and taking your questions one by one. You have a sample size of 10,000 and each sample is described by a feature vector $x\in\mathbb{R}^{31}$. I |
20,245 | Understanding Gaussian Basis function parameters to be used in linear regression | Let me try to give simple explanation. In such notation $j$ can be row number but can be also feature number.
If we write $y=\beta_0+\sum_{j=1:31}{\beta_j\phi_j(x)}$ then $j$ denotes feature number, $y$ is column-vector, $\beta_j$ is scalar and $\phi_j(x)$ is a column-vector.
If we write $y_j=\beta\phi_j(x)$ then $j$ denotes row number, $y_j$ is scalar, $\beta$ is column-vector and $\phi_j(x)$ is a row-vector.
The notation where $i$ denotes row and $j$ denotes column is more common, so let us use the first variant.
Introducing Gaussian basis function into linear regression, $y_i$ (scalar) now depends not on the numerical values of features $x_i$ (vector), but on the distances between $x_i$ and the center of all other points $\mu_i$. In such way $y_i$ does not depend on whether $j$-th feature value of $i$-th observation is high or small, but depends on whether $j$-th feature value is close or far from the mean for that $j$-feature $\mu_{ij}$. So $\mu_j$ is not a parameter, since it cannot be tuned. It is just a property of a dataset. The parameter $\sigma^2$ is a scalar value, it controls the smoothness and can be tuned. If it is small, the small changes in distance will have large effect (remember steep gaussian: all points located already at small distance from center have tiny $y$ values). If it is large, the small changes in distance will have low effect (remember flat gaussian: the decrease of $y$ with increasing distance from center is slow). The optimal value of $\sigma^2$ should be looked for (it is usually found with cross-validation). | Understanding Gaussian Basis function parameters to be used in linear regression | Let me try to give simple explanation. In such notation $j$ can be row number but can be also feature number.
If we write $y=\beta_0+\sum_{j=1:31}{\beta_j\phi_j(x)}$ then $j$ denotes feature number, | Understanding Gaussian Basis function parameters to be used in linear regression
Let me try to give simple explanation. In such notation $j$ can be row number but can be also feature number.
If we write $y=\beta_0+\sum_{j=1:31}{\beta_j\phi_j(x)}$ then $j$ denotes feature number, $y$ is column-vector, $\beta_j$ is scalar and $\phi_j(x)$ is a column-vector.
If we write $y_j=\beta\phi_j(x)$ then $j$ denotes row number, $y_j$ is scalar, $\beta$ is column-vector and $\phi_j(x)$ is a row-vector.
The notation where $i$ denotes row and $j$ denotes column is more common, so let us use the first variant.
Introducing Gaussian basis function into linear regression, $y_i$ (scalar) now depends not on the numerical values of features $x_i$ (vector), but on the distances between $x_i$ and the center of all other points $\mu_i$. In such way $y_i$ does not depend on whether $j$-th feature value of $i$-th observation is high or small, but depends on whether $j$-th feature value is close or far from the mean for that $j$-feature $\mu_{ij}$. So $\mu_j$ is not a parameter, since it cannot be tuned. It is just a property of a dataset. The parameter $\sigma^2$ is a scalar value, it controls the smoothness and can be tuned. If it is small, the small changes in distance will have large effect (remember steep gaussian: all points located already at small distance from center have tiny $y$ values). If it is large, the small changes in distance will have low effect (remember flat gaussian: the decrease of $y$ with increasing distance from center is slow). The optimal value of $\sigma^2$ should be looked for (it is usually found with cross-validation). | Understanding Gaussian Basis function parameters to be used in linear regression
Let me try to give simple explanation. In such notation $j$ can be row number but can be also feature number.
If we write $y=\beta_0+\sum_{j=1:31}{\beta_j\phi_j(x)}$ then $j$ denotes feature number, |
20,246 | Understanding Gaussian Basis function parameters to be used in linear regression | The Gaussian basis functions in the multivariate settings have multivariate centers. Assuming that your $x\in\mathbb{R}^{31}$, then $\mu_j\in\mathbb{R}^{31}$ as well. The Gaussian has to be multivariate, i.e. $e^{(x-\mu_j)'\Sigma_j^{-1}(x-\mu_j)}$ where $\Sigma_j\in\mathbb{R}^{31\times 31}$ is a covariance matrix. The index $j$ is not a component of a vector, it is just the $j$th vector. Similarly, $\Sigma_j$ is the $j$th matrix. | Understanding Gaussian Basis function parameters to be used in linear regression | The Gaussian basis functions in the multivariate settings have multivariate centers. Assuming that your $x\in\mathbb{R}^{31}$, then $\mu_j\in\mathbb{R}^{31}$ as well. The Gaussian has to be multivaria | Understanding Gaussian Basis function parameters to be used in linear regression
The Gaussian basis functions in the multivariate settings have multivariate centers. Assuming that your $x\in\mathbb{R}^{31}$, then $\mu_j\in\mathbb{R}^{31}$ as well. The Gaussian has to be multivariate, i.e. $e^{(x-\mu_j)'\Sigma_j^{-1}(x-\mu_j)}$ where $\Sigma_j\in\mathbb{R}^{31\times 31}$ is a covariance matrix. The index $j$ is not a component of a vector, it is just the $j$th vector. Similarly, $\Sigma_j$ is the $j$th matrix. | Understanding Gaussian Basis function parameters to be used in linear regression
The Gaussian basis functions in the multivariate settings have multivariate centers. Assuming that your $x\in\mathbb{R}^{31}$, then $\mu_j\in\mathbb{R}^{31}$ as well. The Gaussian has to be multivaria |
20,247 | Comparing between random effects structures in a linear mixed-effects model | I was the one suggesting this to you; as I mentioned to my comments there though: "Apologies for being misleading most of my comment regarded selection (on) $X$ not $Z$". By that I mean that I was referring mostly to the fixed effects rather than the random effects structure.
Yes, you can use LRT if you have the same $X$ while using a model fitted by REML. You should be able to use AIC in these cases with caution. This is because it is not obvious how to define the degrees of freedom associated with a specific random effect. You should not use AIC's "vanilla" version directly. Please look at Greven and Kneib, 2010 regarding this; they present a corrected cAIC. They also provide an R package implementing the corrected cAIC they outline.
AIC and LRT are asymptotic tests but things tend to get hairy when you need to estimate parameters that might be close to the boundary of your sample space (ie. when you are testing for variances being close to $0$. In that case you actually want a mixture of $\chi^2$-distributions. A relevant reference of that is Lindquist et al., 2012. To that extent Morell, 1999 can also help if a theoretical justification regarding the use of ReML.
You inquired for a "robust method" to select your random effects structure; on first instance, bootstrap your sample. Use parametric bootstrap to evaluate the asymptotic behavior of your model. Please see the comments mentioned in glmm.wikidot regarding whether a random effect is significant. As mentioned to you in my earlier comment I would be extremely cautious to start model-selection on $Z$; I prefer to "treat it as given" based on my research question. Otherwise I simply cherry-pick my error structure trying to "squeeze more significance out of the remaining terms" [glmm.wikidot].
To recap: using LRT is not "unsound"; it though prone to the limitations of LRTs regarding their asymptotic behavior. There are a number of references on how to provide a remedy. The easiest thing for you at this point would be to simply use RLRsim at first instance. It is based on another piece of work of Greven, Scheipl et al., 2008. | Comparing between random effects structures in a linear mixed-effects model | I was the one suggesting this to you; as I mentioned to my comments there though: "Apologies for being misleading most of my comment regarded selection (on) $X$ not $Z$". By that I mean that I was ref | Comparing between random effects structures in a linear mixed-effects model
I was the one suggesting this to you; as I mentioned to my comments there though: "Apologies for being misleading most of my comment regarded selection (on) $X$ not $Z$". By that I mean that I was referring mostly to the fixed effects rather than the random effects structure.
Yes, you can use LRT if you have the same $X$ while using a model fitted by REML. You should be able to use AIC in these cases with caution. This is because it is not obvious how to define the degrees of freedom associated with a specific random effect. You should not use AIC's "vanilla" version directly. Please look at Greven and Kneib, 2010 regarding this; they present a corrected cAIC. They also provide an R package implementing the corrected cAIC they outline.
AIC and LRT are asymptotic tests but things tend to get hairy when you need to estimate parameters that might be close to the boundary of your sample space (ie. when you are testing for variances being close to $0$. In that case you actually want a mixture of $\chi^2$-distributions. A relevant reference of that is Lindquist et al., 2012. To that extent Morell, 1999 can also help if a theoretical justification regarding the use of ReML.
You inquired for a "robust method" to select your random effects structure; on first instance, bootstrap your sample. Use parametric bootstrap to evaluate the asymptotic behavior of your model. Please see the comments mentioned in glmm.wikidot regarding whether a random effect is significant. As mentioned to you in my earlier comment I would be extremely cautious to start model-selection on $Z$; I prefer to "treat it as given" based on my research question. Otherwise I simply cherry-pick my error structure trying to "squeeze more significance out of the remaining terms" [glmm.wikidot].
To recap: using LRT is not "unsound"; it though prone to the limitations of LRTs regarding their asymptotic behavior. There are a number of references on how to provide a remedy. The easiest thing for you at this point would be to simply use RLRsim at first instance. It is based on another piece of work of Greven, Scheipl et al., 2008. | Comparing between random effects structures in a linear mixed-effects model
I was the one suggesting this to you; as I mentioned to my comments there though: "Apologies for being misleading most of my comment regarded selection (on) $X$ not $Z$". By that I mean that I was ref |
20,248 | Comparing between random effects structures in a linear mixed-effects model | You certainly can't use AIC, BIC or similar criteria that contain an explicit penalty term computed based on the number of parameters in the model. As I pointed out in this topic, the effective number of parameters associated with random effects is unknown. I wasn't sure I was right when I posted that question, but no one challenged me.
Likewise, to compute a p-value based on the LR statistic, one has to know the difference in the number of parameters between the models. I have an ominous feeling that, just like for AIC, that difference has to be in effective terms as opposed to nominal terms. | Comparing between random effects structures in a linear mixed-effects model | You certainly can't use AIC, BIC or similar criteria that contain an explicit penalty term computed based on the number of parameters in the model. As I pointed out in this topic, the effective number | Comparing between random effects structures in a linear mixed-effects model
You certainly can't use AIC, BIC or similar criteria that contain an explicit penalty term computed based on the number of parameters in the model. As I pointed out in this topic, the effective number of parameters associated with random effects is unknown. I wasn't sure I was right when I posted that question, but no one challenged me.
Likewise, to compute a p-value based on the LR statistic, one has to know the difference in the number of parameters between the models. I have an ominous feeling that, just like for AIC, that difference has to be in effective terms as opposed to nominal terms. | Comparing between random effects structures in a linear mixed-effects model
You certainly can't use AIC, BIC or similar criteria that contain an explicit penalty term computed based on the number of parameters in the model. As I pointed out in this topic, the effective number |
20,249 | Training, testing, validating in a survival analysis problem | With a similar outcome frequency I have found that data splitting can work if $n > 20,000$. And it provides an unbiased estimate of model performance, properly penalizing for model selection (if you really need model selection; penalization is still more likely to result in a better model) if you only use the test sample once. BUT don't use the test sample for any re-estimation of parameters. Data splitting relies on the model built using the training sample to be put into "deep freeze" and applied to the test sample without tweaking. | Training, testing, validating in a survival analysis problem | With a similar outcome frequency I have found that data splitting can work if $n > 20,000$. And it provides an unbiased estimate of model performance, properly penalizing for model selection (if you | Training, testing, validating in a survival analysis problem
With a similar outcome frequency I have found that data splitting can work if $n > 20,000$. And it provides an unbiased estimate of model performance, properly penalizing for model selection (if you really need model selection; penalization is still more likely to result in a better model) if you only use the test sample once. BUT don't use the test sample for any re-estimation of parameters. Data splitting relies on the model built using the training sample to be put into "deep freeze" and applied to the test sample without tweaking. | Training, testing, validating in a survival analysis problem
With a similar outcome frequency I have found that data splitting can work if $n > 20,000$. And it provides an unbiased estimate of model performance, properly penalizing for model selection (if you |
20,250 | Training, testing, validating in a survival analysis problem | I've been looking at this paper myself for the similar task of cross-validating survival prediction. The good bits start at Chapter 2. | Training, testing, validating in a survival analysis problem | I've been looking at this paper myself for the similar task of cross-validating survival prediction. The good bits start at Chapter 2. | Training, testing, validating in a survival analysis problem
I've been looking at this paper myself for the similar task of cross-validating survival prediction. The good bits start at Chapter 2. | Training, testing, validating in a survival analysis problem
I've been looking at this paper myself for the similar task of cross-validating survival prediction. The good bits start at Chapter 2. |
20,251 | Training, testing, validating in a survival analysis problem | I have since found this paper which not only answers my question, but provides a method for figuring out the optimal split for particular data sets. I found this thanks to @FrankHarrell 's use of the term "optimum split configuration" which I then Googled. | Training, testing, validating in a survival analysis problem | I have since found this paper which not only answers my question, but provides a method for figuring out the optimal split for particular data sets. I found this thanks to @FrankHarrell 's use of the | Training, testing, validating in a survival analysis problem
I have since found this paper which not only answers my question, but provides a method for figuring out the optimal split for particular data sets. I found this thanks to @FrankHarrell 's use of the term "optimum split configuration" which I then Googled. | Training, testing, validating in a survival analysis problem
I have since found this paper which not only answers my question, but provides a method for figuring out the optimal split for particular data sets. I found this thanks to @FrankHarrell 's use of the |
20,252 | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)? | The following two papers discuss cut-off values for reliability indices:
Lance, C.E., Butts, M.M., & Michels, L.C. (2006). The sources of four commonly reported cutoff criteria: What did they really say? Organizational Research Methods, 9 (2), 202-220.
Henson, R.K. (2001). Understanding internal consistency reliability estimates: A conceptual primer on coefficient alpha. Measurement and Evaluation in Counseling and Development, 34 (3), 177-189.
Strictly speaking neither of them supports the specific scale you describe – the first one in particular is rather critical of the whole idea of a conventional cut-off values – but they do point to many key publications on this topic so digging up those references might bring you to the original sources.
Kline (in the 1993 edition of the Handbook cited by Gavin in his answer) traces his cut-off value to Guilford and Nunnally. IIRC, Nunnally never provided much justification for his recommendation and actually changed it from one edition to the next of his Psychometric Theory but his writings have been very influential so he might very well be most responsible of the popularity of the notion that .7 is acceptable and .9 excellent.
Incidentally, Cronbach's $\alpha$ is often misinterpreted and has been thoroughly criticized. Even the very idea of aiming for higher internal consistency has been called into question (most notably by Cattell, cf. “bloated specifics”). All that to say that looking for the original source of this or that convention might be of some historical interest but none of this is terribly useful to inform psychological measurement. | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)? | The following two papers discuss cut-off values for reliability indices:
Lance, C.E., Butts, M.M., & Michels, L.C. (2006). The sources of four commonly reported cutoff criteria: What did they really | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)?
The following two papers discuss cut-off values for reliability indices:
Lance, C.E., Butts, M.M., & Michels, L.C. (2006). The sources of four commonly reported cutoff criteria: What did they really say? Organizational Research Methods, 9 (2), 202-220.
Henson, R.K. (2001). Understanding internal consistency reliability estimates: A conceptual primer on coefficient alpha. Measurement and Evaluation in Counseling and Development, 34 (3), 177-189.
Strictly speaking neither of them supports the specific scale you describe – the first one in particular is rather critical of the whole idea of a conventional cut-off values – but they do point to many key publications on this topic so digging up those references might bring you to the original sources.
Kline (in the 1993 edition of the Handbook cited by Gavin in his answer) traces his cut-off value to Guilford and Nunnally. IIRC, Nunnally never provided much justification for his recommendation and actually changed it from one edition to the next of his Psychometric Theory but his writings have been very influential so he might very well be most responsible of the popularity of the notion that .7 is acceptable and .9 excellent.
Incidentally, Cronbach's $\alpha$ is often misinterpreted and has been thoroughly criticized. Even the very idea of aiming for higher internal consistency has been called into question (most notably by Cattell, cf. “bloated specifics”). All that to say that looking for the original source of this or that convention might be of some historical interest but none of this is terribly useful to inform psychological measurement. | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)?
The following two papers discuss cut-off values for reliability indices:
Lance, C.E., Butts, M.M., & Michels, L.C. (2006). The sources of four commonly reported cutoff criteria: What did they really |
20,253 | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)? | Wikipedia cites the sources as
George, D., & Mallery, P. (2003). SPSS for Windows step by step: A simple guide and reference. 11.0 update (4th ed.). Boston: Allyn & Bacon.
Kline, P. (1999). The handbook of psychological testing (2nd ed.). London: Routledge
I would follow up those references to see if they cite additional, primary sources. However, as a rule of thumb, these value descriptions may not have a primary source. | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)? | Wikipedia cites the sources as
George, D., & Mallery, P. (2003). SPSS for Windows step by step: A simple guide and reference. 11.0 update (4th ed.). Boston: Allyn & Bacon.
Kline, P. (1999). The handb | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)?
Wikipedia cites the sources as
George, D., & Mallery, P. (2003). SPSS for Windows step by step: A simple guide and reference. 11.0 update (4th ed.). Boston: Allyn & Bacon.
Kline, P. (1999). The handbook of psychological testing (2nd ed.). London: Routledge
I would follow up those references to see if they cite additional, primary sources. However, as a rule of thumb, these value descriptions may not have a primary source. | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)?
Wikipedia cites the sources as
George, D., & Mallery, P. (2003). SPSS for Windows step by step: A simple guide and reference. 11.0 update (4th ed.). Boston: Allyn & Bacon.
Kline, P. (1999). The handb |
20,254 | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)? | Lance, C. E., Butts, M. M., & Michels, L. C. (2006). The sources of four commonly reported cutoff criteria what did they really say?. Organizational research methods, 9(2), 202-220.
"Comparing this section to citations to it, we note several things. First, we suspect that most authors who cite Nunnally’s .70 reliability criterion would not agree that they are trying to save time and energy in an early stage of research by using measures that have only modest reliabilities. Rather, we suspect that most researchers would claim to be conducting basic (or
perhaps applied) research, for which purpose Nunnally clearly recommended a reliability standard of .80. Carmines and Zeller (1979) made a similar recommendation: “As a general rule, we believe that reliabilities should not be below.80 for widely used scales” (p. 51). Thus, our second point is that .80, and not .70 as has been attributed, appears to be Nunnally’s recommended
reliability standard for the majority of purposes cited in organizational research." | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)? | Lance, C. E., Butts, M. M., & Michels, L. C. (2006). The sources of four commonly reported cutoff criteria what did they really say?. Organizational research methods, 9(2), 202-220.
"Comparing this se | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)?
Lance, C. E., Butts, M. M., & Michels, L. C. (2006). The sources of four commonly reported cutoff criteria what did they really say?. Organizational research methods, 9(2), 202-220.
"Comparing this section to citations to it, we note several things. First, we suspect that most authors who cite Nunnally’s .70 reliability criterion would not agree that they are trying to save time and energy in an early stage of research by using measures that have only modest reliabilities. Rather, we suspect that most researchers would claim to be conducting basic (or
perhaps applied) research, for which purpose Nunnally clearly recommended a reliability standard of .80. Carmines and Zeller (1979) made a similar recommendation: “As a general rule, we believe that reliabilities should not be below.80 for widely used scales” (p. 51). Thus, our second point is that .80, and not .70 as has been attributed, appears to be Nunnally’s recommended
reliability standard for the majority of purposes cited in organizational research." | Where do the descriptors for Cronbach's alpha values come from (e.g., poor, excellent)?
Lance, C. E., Butts, M. M., & Michels, L. C. (2006). The sources of four commonly reported cutoff criteria what did they really say?. Organizational research methods, 9(2), 202-220.
"Comparing this se |
20,255 | Boxplot equivalent for heavy-tailed distributions? | The central problem the OP appears to have is that they have very-heavy tailed data - and I don't think most of the present answers actually deal with that issue at all, so I am promoting my previous comment to an answer.
If you did want to stay with boxplots, some options are listed below. I have created some data in R which shows the basic problem:
set.seed(seed=7513870)
x <- rcauchy(80)
boxplot(x,horizontal=TRUE,boxwex=.7)
The middle half of the data is reduced to a tiny strip a couple of mm wide. The same problem afflicts most of the other suggestions - including QQ plots, strip charts, beehive/beeswarm plots, and violin plots.
Now some potential solutions:
transformation,
If logs, or inverses produce a readable boxplot, they may be a very good idea, and the original scale can still be shown on the axis.
The big problem is there's sometimes no 'intuitive' transformation. There's a smaller problem that while quantiles themselves translate with monotonic transformations well enough, the fences don't; if you just boxplot the transformed data (as I did here), the whiskers will be at different x-values than in the original plot.
Here I used a inverse-hyperbolic-sin (asinh); it's sort of log-like in the tails and similar to linear near zero, but people generally don't find it an intuitive transformation, so in general I wouldn't recommend this option unless a fairly intuitive transformation like log is obvious. Code for that:
xlab <- c(-60,-20,-10,-5,-2,-1,0,1,2,5,10,20,40)
boxplot(asinh(x),horizontal=TRUE,boxwex=.7,axes=FALSE,frame.plot=TRUE)
axis(1,at=asinh(xlab),labels=xlab)
scale breaks - take extreme outliers and compress them into narrow windows at each end with a much more compressed scale than at the center. I highly recommend a complete break across the whole scale if you do this.
opar <- par()
layout(matrix(1:3,nr=1,nc=3),heights=c(1,1,1),widths=c(1,6,1))
par(oma = c(5,4,0,0) + 0.1,mar = c(0,0,1,1) + 0.1)
stripchart(x[x< -4],pch=1,cex=1,xlim=c(-80,-5))
boxplot(x[abs(x)<4],horizontal=TRUE,ylim=c(-4,4),at=0,boxwex=.7,cex=1)
stripchart(x[x> 4],pch=1,cex=1,xlim=c(5,80))
par(opar)
trimming of extreme outliers (which I wouldn't normally advise without indicating this very clearly, but it looks like the next plot, without the "<5" and "2>" at either end), and
what I'll call extreme-outlier "arrows" - similar to trimming, but with the count of values trimmed indicated at each end
xout <- boxplot(x,range=3,horizontal=TRUE)$out
xin <- x[!(x %in% xout)]
noutl <- sum(xout<median(x))
nouth <- sum(xout>median(x))
boxplot(xin,horizontal=TRUE,ylim=c(min(xin)*1.15,max(xin)*1.15))
text(x=max(xin)*1.17,y=1,labels=paste0(as.character(nouth)," >"))
text(x=min(xin)*1.17,y=1,labels=paste0("< ",as.character(noutl))) | Boxplot equivalent for heavy-tailed distributions? | The central problem the OP appears to have is that they have very-heavy tailed data - and I don't think most of the present answers actually deal with that issue at all, so I am promoting my previous | Boxplot equivalent for heavy-tailed distributions?
The central problem the OP appears to have is that they have very-heavy tailed data - and I don't think most of the present answers actually deal with that issue at all, so I am promoting my previous comment to an answer.
If you did want to stay with boxplots, some options are listed below. I have created some data in R which shows the basic problem:
set.seed(seed=7513870)
x <- rcauchy(80)
boxplot(x,horizontal=TRUE,boxwex=.7)
The middle half of the data is reduced to a tiny strip a couple of mm wide. The same problem afflicts most of the other suggestions - including QQ plots, strip charts, beehive/beeswarm plots, and violin plots.
Now some potential solutions:
transformation,
If logs, or inverses produce a readable boxplot, they may be a very good idea, and the original scale can still be shown on the axis.
The big problem is there's sometimes no 'intuitive' transformation. There's a smaller problem that while quantiles themselves translate with monotonic transformations well enough, the fences don't; if you just boxplot the transformed data (as I did here), the whiskers will be at different x-values than in the original plot.
Here I used a inverse-hyperbolic-sin (asinh); it's sort of log-like in the tails and similar to linear near zero, but people generally don't find it an intuitive transformation, so in general I wouldn't recommend this option unless a fairly intuitive transformation like log is obvious. Code for that:
xlab <- c(-60,-20,-10,-5,-2,-1,0,1,2,5,10,20,40)
boxplot(asinh(x),horizontal=TRUE,boxwex=.7,axes=FALSE,frame.plot=TRUE)
axis(1,at=asinh(xlab),labels=xlab)
scale breaks - take extreme outliers and compress them into narrow windows at each end with a much more compressed scale than at the center. I highly recommend a complete break across the whole scale if you do this.
opar <- par()
layout(matrix(1:3,nr=1,nc=3),heights=c(1,1,1),widths=c(1,6,1))
par(oma = c(5,4,0,0) + 0.1,mar = c(0,0,1,1) + 0.1)
stripchart(x[x< -4],pch=1,cex=1,xlim=c(-80,-5))
boxplot(x[abs(x)<4],horizontal=TRUE,ylim=c(-4,4),at=0,boxwex=.7,cex=1)
stripchart(x[x> 4],pch=1,cex=1,xlim=c(5,80))
par(opar)
trimming of extreme outliers (which I wouldn't normally advise without indicating this very clearly, but it looks like the next plot, without the "<5" and "2>" at either end), and
what I'll call extreme-outlier "arrows" - similar to trimming, but with the count of values trimmed indicated at each end
xout <- boxplot(x,range=3,horizontal=TRUE)$out
xin <- x[!(x %in% xout)]
noutl <- sum(xout<median(x))
nouth <- sum(xout>median(x))
boxplot(xin,horizontal=TRUE,ylim=c(min(xin)*1.15,max(xin)*1.15))
text(x=max(xin)*1.17,y=1,labels=paste0(as.character(nouth)," >"))
text(x=min(xin)*1.17,y=1,labels=paste0("< ",as.character(noutl))) | Boxplot equivalent for heavy-tailed distributions?
The central problem the OP appears to have is that they have very-heavy tailed data - and I don't think most of the present answers actually deal with that issue at all, so I am promoting my previous |
20,256 | Boxplot equivalent for heavy-tailed distributions? | Personally I like to use a stripplot with jitter at least to get a feel for the data. The plot below is with lattice in R (sorry not ggplot2). I like these plots because they're very easy to interpret. As you say, one reason for this is that there isn't any transform.
df <- data.frame(y1 = c(rnorm(100),-4:4), y2 = c(rnorm(100),-5:3), y3 = c(rnorm(100),-3:5))
df2 <- stack(df)
library(lattice)
stripplot(df2$values ~ df2$ind, jitter=T)
The beeswarm package offers a great alternative to stripplot (thanks to @January for the suggestion).
beeswarm(df2$values ~ df2$ind)
With your data, as it's approximately normally distributed, another thing to try might be a qqplot, qqnorm in this case.
par(mfrow=c(1,3))
for(i in 1:3) { qqnorm(df[,i]); abline(c(0,0),1,col="red") } | Boxplot equivalent for heavy-tailed distributions? | Personally I like to use a stripplot with jitter at least to get a feel for the data. The plot below is with lattice in R (sorry not ggplot2). I like these plots because they're very easy to interpret | Boxplot equivalent for heavy-tailed distributions?
Personally I like to use a stripplot with jitter at least to get a feel for the data. The plot below is with lattice in R (sorry not ggplot2). I like these plots because they're very easy to interpret. As you say, one reason for this is that there isn't any transform.
df <- data.frame(y1 = c(rnorm(100),-4:4), y2 = c(rnorm(100),-5:3), y3 = c(rnorm(100),-3:5))
df2 <- stack(df)
library(lattice)
stripplot(df2$values ~ df2$ind, jitter=T)
The beeswarm package offers a great alternative to stripplot (thanks to @January for the suggestion).
beeswarm(df2$values ~ df2$ind)
With your data, as it's approximately normally distributed, another thing to try might be a qqplot, qqnorm in this case.
par(mfrow=c(1,3))
for(i in 1:3) { qqnorm(df[,i]); abline(c(0,0),1,col="red") } | Boxplot equivalent for heavy-tailed distributions?
Personally I like to use a stripplot with jitter at least to get a feel for the data. The plot below is with lattice in R (sorry not ggplot2). I like these plots because they're very easy to interpret |
20,257 | Boxplot equivalent for heavy-tailed distributions? | You can stick to boxplots. There are different possibilities for defining whiskers. Depending on tail thickness, number of samples and tolerance to outliers you can choose two more or less extreme quantiles. Given your problem I would avoid whiskers defined through the IQR.
Unless of course you want to transform your data, which in this case makes understanding harder. | Boxplot equivalent for heavy-tailed distributions? | You can stick to boxplots. There are different possibilities for defining whiskers. Depending on tail thickness, number of samples and tolerance to outliers you can choose two more or less extreme qua | Boxplot equivalent for heavy-tailed distributions?
You can stick to boxplots. There are different possibilities for defining whiskers. Depending on tail thickness, number of samples and tolerance to outliers you can choose two more or less extreme quantiles. Given your problem I would avoid whiskers defined through the IQR.
Unless of course you want to transform your data, which in this case makes understanding harder. | Boxplot equivalent for heavy-tailed distributions?
You can stick to boxplots. There are different possibilities for defining whiskers. Depending on tail thickness, number of samples and tolerance to outliers you can choose two more or less extreme qua |
20,258 | Boxplot equivalent for heavy-tailed distributions? | I assume this question is about understanding data (as opposed to otherwise “managing” it )
If the data are heavy tailed and/or multimodal, I find these "layers" of ggplot2 very useful for the purpose: geom_violin and geom_jitter. | Boxplot equivalent for heavy-tailed distributions? | I assume this question is about understanding data (as opposed to otherwise “managing” it )
If the data are heavy tailed and/or multimodal, I find these "layers" of ggplot2 very useful for the purpose | Boxplot equivalent for heavy-tailed distributions?
I assume this question is about understanding data (as opposed to otherwise “managing” it )
If the data are heavy tailed and/or multimodal, I find these "layers" of ggplot2 very useful for the purpose: geom_violin and geom_jitter. | Boxplot equivalent for heavy-tailed distributions?
I assume this question is about understanding data (as opposed to otherwise “managing” it )
If the data are heavy tailed and/or multimodal, I find these "layers" of ggplot2 very useful for the purpose |
20,259 | How would you do Bayesian ANOVA and regression in R? [closed] | If you intend to do a lot of Bayesian statistics you would find it helpful to learn the BUGS/JAGS language, which can be accessed in R via the R2OpenBUGS or R2WinBUGS packages.
However, for the sake of a quick example that doesn't require understanding BUGS syntax, you could use the "bayesm" package which has the runiregGibbs function for sampling from the posterior distribution. Here is an example with data similar to that which you describe.....
library(bayesm)
podwt <- structure(list(wt = c(1.76, 1.45, 1.03, 1.53, 2.34, 1.96, 1.79, 1.21, 0.49, 0.85, 1, 1.54, 1.01, 0.75, 2.11, 0.92), treat = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("I", "U"), class = "factor"), mus = c(4.15, 2.76, 1.77, 3.11, 4.65, 3.46, 3.75, 2.04, 1.25, 2.39, 2.54, 3.41, 1.27, 1.26, 3.87, 1.01)), .Names = c("wt", "treat", "mus"), row.names = c(NA, -16L), class = "data.frame")
# response
y1 <- podwt$wt
# First run a one-way anova
# Create the design matrix - need to insert a column of 1s
x1 <- cbind(matrix(1,nrow(podwt),1),podwt$treat)
# data for the Bayesian analysis
dt1 <- list(y=y1,X=x1)
# runiregGibbs uses a normal prior for the regression coefficients and
# an inverse chi-squared prior for va
# mean of the normal prior. We have 2 estimates - 1 intercept
# and 1 regression coefficient
betabar1 <- c(0,0)
# Pecision matrix for the normal prior. Again we have 2
A1 <- 0.01 * diag(2)
# note this is a very diffuse prior
# degrees of freedom for the inverse chi-square prior
n1 <- 3
# scale parameter for the inverse chi-square prior
ssq1 <- var(y1)
Prior1 <- list(betabar=betabar1, A=A1, nu=n1, ssq=ssq1)
# number of iterations of the Gibbs sampler
iter <- 10000
# thinning/slicing parameter. 1 means we keep all all values
slice <- 1
MCMC <- list(R=iter, keep=slice)
sim1 <- runiregGibbs(dt1, Prior1, MCMC)
plot(sim1$betadraw)
plot(sim1$sigmasqdraw)
summary(sim1$betadraw)
summary(sim1$sigmasqdraw)
# compare with maximum likelihood estimates:
fitpodwt <- lm(wt~treat, data=podwt)
summary(fitpodwt)
anova(fitpodwt)
# now for ordinary linear regression
x2 <- cbind(matrix(1,nrow(podwt),1),podwt$mus)
dt2 <- list(y=y1,X=x2)
sim2 <- runiregGibbs(dt1, Prior1, MCMC)
summary(sim1$betadraw)
summary(sim1$sigmasqdraw)
plot(sim$betadraw)
plot(sim$sigmasqdraw)
# compare with maximum likelihood estimates:
summary(lm(podwt$wt~mus,data=podwt))
# now with both variables
x3 <- cbind(matrix(1,nrow(podwt),1),podwt$treat,podwt$mus)
dt3 <- list(y=y1,X=x3)
# now we have an additional estimate so modify the prior accordingly
betabar1 <- c(0,0,0)
A1 <- 0.01 * diag(3)
Prior1 <- list(betabar=betabar1, A=A1, nu=n1, ssq=ssq1)
sim3 <- runiregGibbs(dt3, Prior1, MCMC)
plot(sim3$betadraw)
plot(sim3$sigmasqdraw)
summary(sim3$betadraw)
summary(sim3$sigmasqdraw)
# compare with maximum likelihood estimates:
summary(lm(podwt$wt~treat+mus,data=podwt))
Extracts from the output are:
Anova:
Bayesian:
Summary of Posterior Marginal Distributions
Moments
mean std dev num se rel eff sam size
1 2.18 0.40 0.0042 0.99 9000
2 -0.55 0.25 0.0025 0.87 9000
Quantiles
2.5% 5% 50% 95% 97.5%
1 1.4 1.51 2.18 2.83 2.976
2 -1.1 -0.97 -0.55 -0.13 -0.041
lm():
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.6338 0.1651 9.895 1.06e-07 ***
treatU -0.5500 0.2335 -2.355 0.0336 *
Simple linear regression:
Bayesian:
Summary of Posterior Marginal Distributions
Moments
mean std dev num se rel eff sam size
1 0.23 0.208 0.00222 1.0 4500
2 0.42 0.072 0.00082 1.2 4500
Quantiles
2.5% 5% 50% 95% 97.5%
1 -0.18 -0.10 0.23 0.56 0.63
2 0.28 0.31 0.42 0.54 0.56
lm():
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.23330 0.14272 1.635 0.124
mus 0.42181 0.04931 8.554 6.23e-07 ***
2 covariate model:
Bayesian:
Summary of Posterior Marginal Distributions
Moments
mean std dev num se rel eff sam size
1 0.48 0.437 0.00520 1.3 4500
2 -0.12 0.184 0.00221 1.3 4500
3 0.40 0.083 0.00094 1.2 4500
Quantiles
2.5% 5% 50% 95% 97.5%
1 -0.41 -0.24 0.48 1.18 1.35
2 -0.48 -0.42 -0.12 0.18 0.25
3 0.23 0.26 0.40 0.53 0.56
lm():
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.36242 0.19794 1.831 0.0901 .
treatU -0.11995 0.12688 -0.945 0.3617
mus 0.39590 0.05658 6.997 9.39e-06 ***
from which we can see that the results are broadly comparable, as expected with these simple models and diffuse priors. Of course it is also worth inspecting the MCMC diagnostic plots - posterior density, trace plot, auto correlation - that I also gave the code for above which (plots not shown). | How would you do Bayesian ANOVA and regression in R? [closed] | If you intend to do a lot of Bayesian statistics you would find it helpful to learn the BUGS/JAGS language, which can be accessed in R via the R2OpenBUGS or R2WinBUGS packages.
However, for the sake o | How would you do Bayesian ANOVA and regression in R? [closed]
If you intend to do a lot of Bayesian statistics you would find it helpful to learn the BUGS/JAGS language, which can be accessed in R via the R2OpenBUGS or R2WinBUGS packages.
However, for the sake of a quick example that doesn't require understanding BUGS syntax, you could use the "bayesm" package which has the runiregGibbs function for sampling from the posterior distribution. Here is an example with data similar to that which you describe.....
library(bayesm)
podwt <- structure(list(wt = c(1.76, 1.45, 1.03, 1.53, 2.34, 1.96, 1.79, 1.21, 0.49, 0.85, 1, 1.54, 1.01, 0.75, 2.11, 0.92), treat = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("I", "U"), class = "factor"), mus = c(4.15, 2.76, 1.77, 3.11, 4.65, 3.46, 3.75, 2.04, 1.25, 2.39, 2.54, 3.41, 1.27, 1.26, 3.87, 1.01)), .Names = c("wt", "treat", "mus"), row.names = c(NA, -16L), class = "data.frame")
# response
y1 <- podwt$wt
# First run a one-way anova
# Create the design matrix - need to insert a column of 1s
x1 <- cbind(matrix(1,nrow(podwt),1),podwt$treat)
# data for the Bayesian analysis
dt1 <- list(y=y1,X=x1)
# runiregGibbs uses a normal prior for the regression coefficients and
# an inverse chi-squared prior for va
# mean of the normal prior. We have 2 estimates - 1 intercept
# and 1 regression coefficient
betabar1 <- c(0,0)
# Pecision matrix for the normal prior. Again we have 2
A1 <- 0.01 * diag(2)
# note this is a very diffuse prior
# degrees of freedom for the inverse chi-square prior
n1 <- 3
# scale parameter for the inverse chi-square prior
ssq1 <- var(y1)
Prior1 <- list(betabar=betabar1, A=A1, nu=n1, ssq=ssq1)
# number of iterations of the Gibbs sampler
iter <- 10000
# thinning/slicing parameter. 1 means we keep all all values
slice <- 1
MCMC <- list(R=iter, keep=slice)
sim1 <- runiregGibbs(dt1, Prior1, MCMC)
plot(sim1$betadraw)
plot(sim1$sigmasqdraw)
summary(sim1$betadraw)
summary(sim1$sigmasqdraw)
# compare with maximum likelihood estimates:
fitpodwt <- lm(wt~treat, data=podwt)
summary(fitpodwt)
anova(fitpodwt)
# now for ordinary linear regression
x2 <- cbind(matrix(1,nrow(podwt),1),podwt$mus)
dt2 <- list(y=y1,X=x2)
sim2 <- runiregGibbs(dt1, Prior1, MCMC)
summary(sim1$betadraw)
summary(sim1$sigmasqdraw)
plot(sim$betadraw)
plot(sim$sigmasqdraw)
# compare with maximum likelihood estimates:
summary(lm(podwt$wt~mus,data=podwt))
# now with both variables
x3 <- cbind(matrix(1,nrow(podwt),1),podwt$treat,podwt$mus)
dt3 <- list(y=y1,X=x3)
# now we have an additional estimate so modify the prior accordingly
betabar1 <- c(0,0,0)
A1 <- 0.01 * diag(3)
Prior1 <- list(betabar=betabar1, A=A1, nu=n1, ssq=ssq1)
sim3 <- runiregGibbs(dt3, Prior1, MCMC)
plot(sim3$betadraw)
plot(sim3$sigmasqdraw)
summary(sim3$betadraw)
summary(sim3$sigmasqdraw)
# compare with maximum likelihood estimates:
summary(lm(podwt$wt~treat+mus,data=podwt))
Extracts from the output are:
Anova:
Bayesian:
Summary of Posterior Marginal Distributions
Moments
mean std dev num se rel eff sam size
1 2.18 0.40 0.0042 0.99 9000
2 -0.55 0.25 0.0025 0.87 9000
Quantiles
2.5% 5% 50% 95% 97.5%
1 1.4 1.51 2.18 2.83 2.976
2 -1.1 -0.97 -0.55 -0.13 -0.041
lm():
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.6338 0.1651 9.895 1.06e-07 ***
treatU -0.5500 0.2335 -2.355 0.0336 *
Simple linear regression:
Bayesian:
Summary of Posterior Marginal Distributions
Moments
mean std dev num se rel eff sam size
1 0.23 0.208 0.00222 1.0 4500
2 0.42 0.072 0.00082 1.2 4500
Quantiles
2.5% 5% 50% 95% 97.5%
1 -0.18 -0.10 0.23 0.56 0.63
2 0.28 0.31 0.42 0.54 0.56
lm():
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.23330 0.14272 1.635 0.124
mus 0.42181 0.04931 8.554 6.23e-07 ***
2 covariate model:
Bayesian:
Summary of Posterior Marginal Distributions
Moments
mean std dev num se rel eff sam size
1 0.48 0.437 0.00520 1.3 4500
2 -0.12 0.184 0.00221 1.3 4500
3 0.40 0.083 0.00094 1.2 4500
Quantiles
2.5% 5% 50% 95% 97.5%
1 -0.41 -0.24 0.48 1.18 1.35
2 -0.48 -0.42 -0.12 0.18 0.25
3 0.23 0.26 0.40 0.53 0.56
lm():
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.36242 0.19794 1.831 0.0901 .
treatU -0.11995 0.12688 -0.945 0.3617
mus 0.39590 0.05658 6.997 9.39e-06 ***
from which we can see that the results are broadly comparable, as expected with these simple models and diffuse priors. Of course it is also worth inspecting the MCMC diagnostic plots - posterior density, trace plot, auto correlation - that I also gave the code for above which (plots not shown). | How would you do Bayesian ANOVA and regression in R? [closed]
If you intend to do a lot of Bayesian statistics you would find it helpful to learn the BUGS/JAGS language, which can be accessed in R via the R2OpenBUGS or R2WinBUGS packages.
However, for the sake o |
20,260 | How would you do Bayesian ANOVA and regression in R? [closed] | The BayesFactor package (demonstrated here: http://bayesfactorpcl.r-forge.r-project.org/ and available on CRAN) allows Bayesian ANOVA and regression. It uses Bayes factors for model comparison and allows posterior sampling for estimation. | How would you do Bayesian ANOVA and regression in R? [closed] | The BayesFactor package (demonstrated here: http://bayesfactorpcl.r-forge.r-project.org/ and available on CRAN) allows Bayesian ANOVA and regression. It uses Bayes factors for model comparison and all | How would you do Bayesian ANOVA and regression in R? [closed]
The BayesFactor package (demonstrated here: http://bayesfactorpcl.r-forge.r-project.org/ and available on CRAN) allows Bayesian ANOVA and regression. It uses Bayes factors for model comparison and allows posterior sampling for estimation. | How would you do Bayesian ANOVA and regression in R? [closed]
The BayesFactor package (demonstrated here: http://bayesfactorpcl.r-forge.r-project.org/ and available on CRAN) allows Bayesian ANOVA and regression. It uses Bayes factors for model comparison and all |
20,261 | How would you do Bayesian ANOVA and regression in R? [closed] | This is quite convenient with the LearnBayes package.
fit <- lm(Sepal.Length ~ Species, data=iris, x=TRUE, y=TRUE)
library(LearnBayes)
posterior_sims <- blinreg(fit$y, fit$x, 50000)
The blinreg function uses a noninformative prior by default, and this yields an inference very close to the frequentist one.
Estimates:
> # frequentist
> fit$coefficients
(Intercept) Speciesversicolor Speciesvirginica
5.006 0.930 1.582
> # Bayesian
> colMeans(posterior_sims$beta)
X(Intercept) XSpeciesversicolor XSpeciesvirginica
5.0066682 0.9291718 1.5807763
Confidence intervals:
> # frequentist
> confint(fit)
2.5 % 97.5 %
(Intercept) 4.8621258 5.149874
Speciesversicolor 0.7265312 1.133469
Speciesvirginica 1.3785312 1.785469
> # Bayesian
> apply(posterior_sims$beta, 2, function(x) quantile(x, c(0.025, 0.975)))
X(Intercept) XSpeciesversicolor XSpeciesvirginica
2.5% 4.862444 0.7249691 1.376319
97.5% 5.149735 1.1343101 1.783060 | How would you do Bayesian ANOVA and regression in R? [closed] | This is quite convenient with the LearnBayes package.
fit <- lm(Sepal.Length ~ Species, data=iris, x=TRUE, y=TRUE)
library(LearnBayes)
posterior_sims <- blinreg(fit$y, fit$x, 50000)
The blinreg func | How would you do Bayesian ANOVA and regression in R? [closed]
This is quite convenient with the LearnBayes package.
fit <- lm(Sepal.Length ~ Species, data=iris, x=TRUE, y=TRUE)
library(LearnBayes)
posterior_sims <- blinreg(fit$y, fit$x, 50000)
The blinreg function uses a noninformative prior by default, and this yields an inference very close to the frequentist one.
Estimates:
> # frequentist
> fit$coefficients
(Intercept) Speciesversicolor Speciesvirginica
5.006 0.930 1.582
> # Bayesian
> colMeans(posterior_sims$beta)
X(Intercept) XSpeciesversicolor XSpeciesvirginica
5.0066682 0.9291718 1.5807763
Confidence intervals:
> # frequentist
> confint(fit)
2.5 % 97.5 %
(Intercept) 4.8621258 5.149874
Speciesversicolor 0.7265312 1.133469
Speciesvirginica 1.3785312 1.785469
> # Bayesian
> apply(posterior_sims$beta, 2, function(x) quantile(x, c(0.025, 0.975)))
X(Intercept) XSpeciesversicolor XSpeciesvirginica
2.5% 4.862444 0.7249691 1.376319
97.5% 5.149735 1.1343101 1.783060 | How would you do Bayesian ANOVA and regression in R? [closed]
This is quite convenient with the LearnBayes package.
fit <- lm(Sepal.Length ~ Species, data=iris, x=TRUE, y=TRUE)
library(LearnBayes)
posterior_sims <- blinreg(fit$y, fit$x, 50000)
The blinreg func |
20,262 | When using glmnet how to report p-value significance to claim significance of predictors? | There is a new paper, A Significance Test for the Lasso, including the inventor of LASSO as an author that reports results on this problem. This is a relatively new area of research, so the references in the paper cover a lot of what is known at this point.
As for your second question, have you tried $\alpha \in (0,1)$? Often there is a value in this middle range that achieves a good compromise. This is called Elastic Net regularization. Since you are using cv.glmnet, you will probably want to cross-validate over a grid of $(\lambda, \alpha)$ values. | When using glmnet how to report p-value significance to claim significance of predictors? | There is a new paper, A Significance Test for the Lasso, including the inventor of LASSO as an author that reports results on this problem. This is a relatively new area of research, so the references | When using glmnet how to report p-value significance to claim significance of predictors?
There is a new paper, A Significance Test for the Lasso, including the inventor of LASSO as an author that reports results on this problem. This is a relatively new area of research, so the references in the paper cover a lot of what is known at this point.
As for your second question, have you tried $\alpha \in (0,1)$? Often there is a value in this middle range that achieves a good compromise. This is called Elastic Net regularization. Since you are using cv.glmnet, you will probably want to cross-validate over a grid of $(\lambda, \alpha)$ values. | When using glmnet how to report p-value significance to claim significance of predictors?
There is a new paper, A Significance Test for the Lasso, including the inventor of LASSO as an author that reports results on this problem. This is a relatively new area of research, so the references |
20,263 | When using glmnet how to report p-value significance to claim significance of predictors? | Post-selection inference is a very active topic of statistical research. In my view, an issue with the method described in A Significance Test for the Lasso is that stringent assumptions are required (reproduced from here):
The linear model is correct.
The variance is constant.
The errors have a Normal distribution.
The parameter vector is sparse.
The design matrix has very weak collinearity. This is usually stated in the form of incoherence, eigenvalue restrictions or incompatibility assumptions.
The approach I've found to be useful - as long as there is sufficient data available - is data splitting. The idea of data splitting goes back to at least Moran (1974) and simply entails dividing the data randomly into two sets, making modeling choices on the first set, and making inference on the second set.
So in this case you would split the data into two, do variable selection on the first half, then (assuming you have $n > p$) use standard regression techniques on the second half to determine the statistical significance of the coefficients. Of course, assumptions are still required at both stage but they may be easier to satisfy for each stage individually.
You mention that the covariates are uni-, bi-, and tri-grams so they are highly collinear. So in this case applying the Lasso in the first stage would also violate assumptions - in particular, #5 from above. So to make such an approach genuinely useful and theoretically sound you would need to do some sort of pre-Lasso collinearity screening. | When using glmnet how to report p-value significance to claim significance of predictors? | Post-selection inference is a very active topic of statistical research. In my view, an issue with the method described in A Significance Test for the Lasso is that stringent assumptions are required | When using glmnet how to report p-value significance to claim significance of predictors?
Post-selection inference is a very active topic of statistical research. In my view, an issue with the method described in A Significance Test for the Lasso is that stringent assumptions are required (reproduced from here):
The linear model is correct.
The variance is constant.
The errors have a Normal distribution.
The parameter vector is sparse.
The design matrix has very weak collinearity. This is usually stated in the form of incoherence, eigenvalue restrictions or incompatibility assumptions.
The approach I've found to be useful - as long as there is sufficient data available - is data splitting. The idea of data splitting goes back to at least Moran (1974) and simply entails dividing the data randomly into two sets, making modeling choices on the first set, and making inference on the second set.
So in this case you would split the data into two, do variable selection on the first half, then (assuming you have $n > p$) use standard regression techniques on the second half to determine the statistical significance of the coefficients. Of course, assumptions are still required at both stage but they may be easier to satisfy for each stage individually.
You mention that the covariates are uni-, bi-, and tri-grams so they are highly collinear. So in this case applying the Lasso in the first stage would also violate assumptions - in particular, #5 from above. So to make such an approach genuinely useful and theoretically sound you would need to do some sort of pre-Lasso collinearity screening. | When using glmnet how to report p-value significance to claim significance of predictors?
Post-selection inference is a very active topic of statistical research. In my view, an issue with the method described in A Significance Test for the Lasso is that stringent assumptions are required |
20,264 | When using glmnet how to report p-value significance to claim significance of predictors? | Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Maybe have a look at CRAN package hdi, that one provides inference for high-dimensional models and should do the trick... The full methods are are a bit tedious to repeat here (there are several, and it's still quite an active area of research), but they are well described in this paper:
http://projecteuclid.org/euclid.ss/1449670857 (If you publicly post some test data, or simulate some data, I can also give you a concrete example) | When using glmnet how to report p-value significance to claim significance of predictors? | Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
| When using glmnet how to report p-value significance to claim significance of predictors?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Maybe have a look at CRAN package hdi, that one provides inference for high-dimensional models and should do the trick... The full methods are are a bit tedious to repeat here (there are several, and it's still quite an active area of research), but they are well described in this paper:
http://projecteuclid.org/euclid.ss/1449670857 (If you publicly post some test data, or simulate some data, I can also give you a concrete example) | When using glmnet how to report p-value significance to claim significance of predictors?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
20,265 | PCA and random forests | When doing predictive modeling, you are trying to explain the variation in the response, not the variation in the features. There is no reason to believe that cramming as much of the feature variation into a single new feature will capture a large amount of the predictive power of the features as a whole.
This is often explained as the difference between Principal Component Regression instead of Partial Least Squares. | PCA and random forests | When doing predictive modeling, you are trying to explain the variation in the response, not the variation in the features. There is no reason to believe that cramming as much of the feature variatio | PCA and random forests
When doing predictive modeling, you are trying to explain the variation in the response, not the variation in the features. There is no reason to believe that cramming as much of the feature variation into a single new feature will capture a large amount of the predictive power of the features as a whole.
This is often explained as the difference between Principal Component Regression instead of Partial Least Squares. | PCA and random forests
When doing predictive modeling, you are trying to explain the variation in the response, not the variation in the features. There is no reason to believe that cramming as much of the feature variatio |
20,266 | PCA and random forests | The first principal component is a linear combination of all your features. The fact that it explains almost all the variability just means that most of the coefficients of the variables in the first principal component are significant.
Now the classification trees you generate are a bit of a different animal too. They do binary splits on continuous variables that best separate the categories you want to classify. That is not exactly the same as finding orthogonal linear combinations of continuous variables that give the direction of greatest variance. In fact we have recently discussed a paper on CV where PCA was used for cluster analysis and the author(s) found that there are situations wher best separation is found not in the 1st few principal components but rather in the last ones. | PCA and random forests | The first principal component is a linear combination of all your features. The fact that it explains almost all the variability just means that most of the coefficients of the variables in the first | PCA and random forests
The first principal component is a linear combination of all your features. The fact that it explains almost all the variability just means that most of the coefficients of the variables in the first principal component are significant.
Now the classification trees you generate are a bit of a different animal too. They do binary splits on continuous variables that best separate the categories you want to classify. That is not exactly the same as finding orthogonal linear combinations of continuous variables that give the direction of greatest variance. In fact we have recently discussed a paper on CV where PCA was used for cluster analysis and the author(s) found that there are situations wher best separation is found not in the 1st few principal components but rather in the last ones. | PCA and random forests
The first principal component is a linear combination of all your features. The fact that it explains almost all the variability just means that most of the coefficients of the variables in the first |
20,267 | RFM & customer lifetime value modeling in R | As for references, Data Mining Using RFM Analysis should help as far as terminology and further references go.
One of the simplest (and popular) ways to model the probability of customer response is to use logistic regression with RFM as explanatory variables (among other available variables).
For modeling monetary value, one could just regress revenue on RFM directly (by using a simple linear model for starters) which usually does surprisingly well. More advanced/non-linear models (such as Random Forest or Gradient Boosting Machine) do better than linear models in my experience.
Another popular approach is to build a slightly more complex model for predicting monetary value based on two sub-models: one for probability of response (e.g. using logistic regression as a function of RFM), and the other for revenue conditional on response (again, it could be as simple as a linear model of RFM). Expected monetary value is the product of the two predictions.
If randomized test/control data are available then uplift/netlift based techniques are quite popular for modeling the incremental benefit of a treatment.
As for customer life cycle value, see Modeling Customer Lifetime Value for a review and further references.
With regards to modeling in R, I am not aware of any "off-the-shelf" packages for that type of modeling. R does provide all necessary building blocks for that though (unless you have enormous amount of data - in that case you may have to rely on more scalable tools) | RFM & customer lifetime value modeling in R | As for references, Data Mining Using RFM Analysis should help as far as terminology and further references go.
One of the simplest (and popular) ways to model the probability of customer response is t | RFM & customer lifetime value modeling in R
As for references, Data Mining Using RFM Analysis should help as far as terminology and further references go.
One of the simplest (and popular) ways to model the probability of customer response is to use logistic regression with RFM as explanatory variables (among other available variables).
For modeling monetary value, one could just regress revenue on RFM directly (by using a simple linear model for starters) which usually does surprisingly well. More advanced/non-linear models (such as Random Forest or Gradient Boosting Machine) do better than linear models in my experience.
Another popular approach is to build a slightly more complex model for predicting monetary value based on two sub-models: one for probability of response (e.g. using logistic regression as a function of RFM), and the other for revenue conditional on response (again, it could be as simple as a linear model of RFM). Expected monetary value is the product of the two predictions.
If randomized test/control data are available then uplift/netlift based techniques are quite popular for modeling the incremental benefit of a treatment.
As for customer life cycle value, see Modeling Customer Lifetime Value for a review and further references.
With regards to modeling in R, I am not aware of any "off-the-shelf" packages for that type of modeling. R does provide all necessary building blocks for that though (unless you have enormous amount of data - in that case you may have to rely on more scalable tools) | RFM & customer lifetime value modeling in R
As for references, Data Mining Using RFM Analysis should help as far as terminology and further references go.
One of the simplest (and popular) ways to model the probability of customer response is t |
20,268 | RFM & customer lifetime value modeling in R | Not sure if you are still working on the RFM modeling. Here (pdf) is an article / the vignette for the BTYD package in R that might be helpful to you. The whole article is based on R and it has 3 different models to look at. On Page 1, 2.1 Data Preparation, you can see the context about RFMs. | RFM & customer lifetime value modeling in R | Not sure if you are still working on the RFM modeling. Here (pdf) is an article / the vignette for the BTYD package in R that might be helpful to you. The whole article is based on R and it has 3 diff | RFM & customer lifetime value modeling in R
Not sure if you are still working on the RFM modeling. Here (pdf) is an article / the vignette for the BTYD package in R that might be helpful to you. The whole article is based on R and it has 3 different models to look at. On Page 1, 2.1 Data Preparation, you can see the context about RFMs. | RFM & customer lifetime value modeling in R
Not sure if you are still working on the RFM modeling. Here (pdf) is an article / the vignette for the BTYD package in R that might be helpful to you. The whole article is based on R and it has 3 diff |
20,269 | RFM & customer lifetime value modeling in R | There is a new R package that implements some of the latest modeling techniques for CLV in non-contractual settings (e.g. retailing):
https://cran.r-project.org/package=CLVTools
Here is a step-by-step walk-through based on data from an apparel retailer:
https://www.clvtools.com/articles/CLVTools.html | RFM & customer lifetime value modeling in R | There is a new R package that implements some of the latest modeling techniques for CLV in non-contractual settings (e.g. retailing):
https://cran.r-project.org/package=CLVTools
Here is a step-by-step | RFM & customer lifetime value modeling in R
There is a new R package that implements some of the latest modeling techniques for CLV in non-contractual settings (e.g. retailing):
https://cran.r-project.org/package=CLVTools
Here is a step-by-step walk-through based on data from an apparel retailer:
https://www.clvtools.com/articles/CLVTools.html | RFM & customer lifetime value modeling in R
There is a new R package that implements some of the latest modeling techniques for CLV in non-contractual settings (e.g. retailing):
https://cran.r-project.org/package=CLVTools
Here is a step-by-step |
20,270 | Where to find raw data about clinical trials? | You can have a look at the Clinical Trials Network, where data are available in CDISC format. You must agree to their terms and conditions, although the following point might be of concern for teaching purpose:
To retain control over the received data, and not to transfer any
portion of the received data, with or without charge, to any other
entity or individual
(Anyway, I think that you can just send an email to the contact support to check that their data can be used for teaching.)
The NIDKK Data Repository is specifically concerned with studies on kidney and liver disease, and diabete; however, you have to submit an application.
Otherwise, perhaps the ADNI project, which aims at characterizing change in cognitive functions and brain structures with age, with a particular emphasis on Alzheimer's disease and neuroimaging, might be interesting. This is not a clinical trial, but available data include: demographics, clinical and cognitive data, neuroimaging (MRI/PET) data. Details about protocols and data can be found under ADNI Scientist's Home, and data are available on ADCS website.
There doesn't seem to be anything related to RCTs on http://www.infochimps.com/. However, I remember having seen some clinical data used with the Weka software, as e.g. on this page: Data mining to predict patient outcome in a clinical trial of a lung cancer treatment. | Where to find raw data about clinical trials? | You can have a look at the Clinical Trials Network, where data are available in CDISC format. You must agree to their terms and conditions, although the following point might be of concern for teachin | Where to find raw data about clinical trials?
You can have a look at the Clinical Trials Network, where data are available in CDISC format. You must agree to their terms and conditions, although the following point might be of concern for teaching purpose:
To retain control over the received data, and not to transfer any
portion of the received data, with or without charge, to any other
entity or individual
(Anyway, I think that you can just send an email to the contact support to check that their data can be used for teaching.)
The NIDKK Data Repository is specifically concerned with studies on kidney and liver disease, and diabete; however, you have to submit an application.
Otherwise, perhaps the ADNI project, which aims at characterizing change in cognitive functions and brain structures with age, with a particular emphasis on Alzheimer's disease and neuroimaging, might be interesting. This is not a clinical trial, but available data include: demographics, clinical and cognitive data, neuroimaging (MRI/PET) data. Details about protocols and data can be found under ADNI Scientist's Home, and data are available on ADCS website.
There doesn't seem to be anything related to RCTs on http://www.infochimps.com/. However, I remember having seen some clinical data used with the Weka software, as e.g. on this page: Data mining to predict patient outcome in a clinical trial of a lung cancer treatment. | Where to find raw data about clinical trials?
You can have a look at the Clinical Trials Network, where data are available in CDISC format. You must agree to their terms and conditions, although the following point might be of concern for teachin |
20,271 | Where to find raw data about clinical trials? | It looks like NIMH has a number of slightly lobotomized data sets available, although I have no idea what the data use agreements entail. This will be a problem for almost every trial you come across I suspect - the need to either prevent their trial results from getting scooped, health information privacy concerns, or both.
Others I've found:
National Heart, Lung and Blood Institute has a "teaching" data set.
I'll edit this answer if the list grows. There's also always simulating a data set so it matches the results of a published trial. | Where to find raw data about clinical trials? | It looks like NIMH has a number of slightly lobotomized data sets available, although I have no idea what the data use agreements entail. This will be a problem for almost every trial you come across | Where to find raw data about clinical trials?
It looks like NIMH has a number of slightly lobotomized data sets available, although I have no idea what the data use agreements entail. This will be a problem for almost every trial you come across I suspect - the need to either prevent their trial results from getting scooped, health information privacy concerns, or both.
Others I've found:
National Heart, Lung and Blood Institute has a "teaching" data set.
I'll edit this answer if the list grows. There's also always simulating a data set so it matches the results of a published trial. | Where to find raw data about clinical trials?
It looks like NIMH has a number of slightly lobotomized data sets available, although I have no idea what the data use agreements entail. This will be a problem for almost every trial you come across |
20,272 | Where to find raw data about clinical trials? | You can find details of a trial downloadable in an XML format from http://clinicaltrials.gov/ | Where to find raw data about clinical trials? | You can find details of a trial downloadable in an XML format from http://clinicaltrials.gov/ | Where to find raw data about clinical trials?
You can find details of a trial downloadable in an XML format from http://clinicaltrials.gov/ | Where to find raw data about clinical trials?
You can find details of a trial downloadable in an XML format from http://clinicaltrials.gov/ |
20,273 | Where to find raw data about clinical trials? | Check out http://yoda.yale.edu/ and https://www.clinicalstudydatarequest.com/ both of which require lengthy applications. | Where to find raw data about clinical trials? | Check out http://yoda.yale.edu/ and https://www.clinicalstudydatarequest.com/ both of which require lengthy applications. | Where to find raw data about clinical trials?
Check out http://yoda.yale.edu/ and https://www.clinicalstudydatarequest.com/ both of which require lengthy applications. | Where to find raw data about clinical trials?
Check out http://yoda.yale.edu/ and https://www.clinicalstudydatarequest.com/ both of which require lengthy applications. |
20,274 | Calculate Newey-West standard errors without an lm object in R | Suppose we have a regression
\begin{align*}
y=X\beta+u
\end{align*}
Then OLS estimate $\hat{\beta}$ is
\begin{align*}
\widehat{\beta}-\beta=(X'X)^{-1}X'u
\end{align*}
and assuming that $\hat{\beta}$ is unbiased estimate we have
\begin{align*}
Var(\widehat{\beta})=E\left[(X'X)^{-1}X'uu'X(X'X)^{-1}\right]
\end{align*}
The usual OLS assumptions are that $E(u|X)=0$ and $E(uu'|X)=\sigma^2I_n$ which gives us
\begin{align*}
Var(\widehat{\beta})=\sigma^2E(X'X)^{-1}
\end{align*}
This covariance matrix is usually reported in statistical packages.
If $u_i$ are heteroscedastic and (or) autocorellated, then $E(uu'|X)\neq\sigma^2I_n$ and the usual output gives misleading results. To get the correct results HAC standard errors are calculated. All the methods for HAC errors calculate
\begin{align*}
diag(E(X'X)^{-1}X'uu'X(X'X)^{-1}).
\end{align*}
They differ on their assumptions what $E(uu'|X)$ looks like.
So it is natural then that function NeweyWest requests linear model. Newey-West method calculates the correct standard errors of linear model estimator. So your solution is perfectly correct if you assume that your stock returns follow the model
\begin{align}
r_t=\mu+u_t
\end{align}
and you want to estimate $Var(\mu)$ guarding against irregularities in $u_t$.
If on the other hand you want to estimate "correct" $Var(r_t)$ (whatever that means), you should check out volatility models, such as GARCH and its variants. They assume that
\begin{align*}
r_t=\sigma_t\varepsilon_t
\end{align*}
where $\varepsilon_t$ are iid normal. The goal is then to correctly estimate $\sigma_t$. Then $Var(r_t)=Var(\sigma_t)$ and you have "correct" estimate of your variance, guarding against usual idiosyncrasies of stock returns such as volatility clustering, skewness and etc. | Calculate Newey-West standard errors without an lm object in R | Suppose we have a regression
\begin{align*}
y=X\beta+u
\end{align*}
Then OLS estimate $\hat{\beta}$ is
\begin{align*}
\widehat{\beta}-\beta=(X'X)^{-1}X'u
\end{align*}
and assuming that $\hat{\beta}$ i | Calculate Newey-West standard errors without an lm object in R
Suppose we have a regression
\begin{align*}
y=X\beta+u
\end{align*}
Then OLS estimate $\hat{\beta}$ is
\begin{align*}
\widehat{\beta}-\beta=(X'X)^{-1}X'u
\end{align*}
and assuming that $\hat{\beta}$ is unbiased estimate we have
\begin{align*}
Var(\widehat{\beta})=E\left[(X'X)^{-1}X'uu'X(X'X)^{-1}\right]
\end{align*}
The usual OLS assumptions are that $E(u|X)=0$ and $E(uu'|X)=\sigma^2I_n$ which gives us
\begin{align*}
Var(\widehat{\beta})=\sigma^2E(X'X)^{-1}
\end{align*}
This covariance matrix is usually reported in statistical packages.
If $u_i$ are heteroscedastic and (or) autocorellated, then $E(uu'|X)\neq\sigma^2I_n$ and the usual output gives misleading results. To get the correct results HAC standard errors are calculated. All the methods for HAC errors calculate
\begin{align*}
diag(E(X'X)^{-1}X'uu'X(X'X)^{-1}).
\end{align*}
They differ on their assumptions what $E(uu'|X)$ looks like.
So it is natural then that function NeweyWest requests linear model. Newey-West method calculates the correct standard errors of linear model estimator. So your solution is perfectly correct if you assume that your stock returns follow the model
\begin{align}
r_t=\mu+u_t
\end{align}
and you want to estimate $Var(\mu)$ guarding against irregularities in $u_t$.
If on the other hand you want to estimate "correct" $Var(r_t)$ (whatever that means), you should check out volatility models, such as GARCH and its variants. They assume that
\begin{align*}
r_t=\sigma_t\varepsilon_t
\end{align*}
where $\varepsilon_t$ are iid normal. The goal is then to correctly estimate $\sigma_t$. Then $Var(r_t)=Var(\sigma_t)$ and you have "correct" estimate of your variance, guarding against usual idiosyncrasies of stock returns such as volatility clustering, skewness and etc. | Calculate Newey-West standard errors without an lm object in R
Suppose we have a regression
\begin{align*}
y=X\beta+u
\end{align*}
Then OLS estimate $\hat{\beta}$ is
\begin{align*}
\widehat{\beta}-\beta=(X'X)^{-1}X'u
\end{align*}
and assuming that $\hat{\beta}$ i |
20,275 | interpretation of betareg coef | Yes, the logit link can be interpreted like that. It's just not a change in "odds" (= ratio of probabilities) but a change in a ratio of proportions. More formally, the model equation for the expectation is the same as in logistic regression:
$$ \mathrm{logit}(\mu_i) = x_i^\top \beta $$
where $\mu_i = \mathrm{E}(y_i)$. For your setup this means:
$$
\begin{eqnarray*}
\mathrm{logit}(\mathrm{E}(\mathtt{Proportion})) & = & -1.31 + 0.004 \cdot \mathtt{Temperature} \\
\frac{\mathrm{E}(\mathtt{Proportion})}{1 - \mathrm{E}(\mathtt{Proportion})} & = & \exp(-1.31 + 0.004 \cdot \mathtt{Temperature}) \end{eqnarray*}
$$
Thus, an absolute 1-unit change in $\mathtt{Temperature}$ leads to a relative change of $\exp(0.004) \approx 0.4\%$ in $\mathrm{E}(\mathtt{Proportion})/(1 - \mathrm{E}(\mathtt{Proportion}))$.
With a bit of practice you can get a reasonable feeling for what this means in the actual expected $\mathtt{Proportion}$. If you don't have that feeling (yet), you can easily compute the effects of the changes in $\mathtt{Temperature}$, e.g.,:
nd <- data.frame(TEMPERATURE = seq(-150, 150, by = 50))
nd$Proportion <- predict(b, newdata = nd)
print(nd)
plot(Proportion ~ TEMPERATURE, data = nd, type = "b")
to check what the absolute changes in Proportion are for certain absolute changes in TEMPERATURE. | interpretation of betareg coef | Yes, the logit link can be interpreted like that. It's just not a change in "odds" (= ratio of probabilities) but a change in a ratio of proportions. More formally, the model equation for the expectat | interpretation of betareg coef
Yes, the logit link can be interpreted like that. It's just not a change in "odds" (= ratio of probabilities) but a change in a ratio of proportions. More formally, the model equation for the expectation is the same as in logistic regression:
$$ \mathrm{logit}(\mu_i) = x_i^\top \beta $$
where $\mu_i = \mathrm{E}(y_i)$. For your setup this means:
$$
\begin{eqnarray*}
\mathrm{logit}(\mathrm{E}(\mathtt{Proportion})) & = & -1.31 + 0.004 \cdot \mathtt{Temperature} \\
\frac{\mathrm{E}(\mathtt{Proportion})}{1 - \mathrm{E}(\mathtt{Proportion})} & = & \exp(-1.31 + 0.004 \cdot \mathtt{Temperature}) \end{eqnarray*}
$$
Thus, an absolute 1-unit change in $\mathtt{Temperature}$ leads to a relative change of $\exp(0.004) \approx 0.4\%$ in $\mathrm{E}(\mathtt{Proportion})/(1 - \mathrm{E}(\mathtt{Proportion}))$.
With a bit of practice you can get a reasonable feeling for what this means in the actual expected $\mathtt{Proportion}$. If you don't have that feeling (yet), you can easily compute the effects of the changes in $\mathtt{Temperature}$, e.g.,:
nd <- data.frame(TEMPERATURE = seq(-150, 150, by = 50))
nd$Proportion <- predict(b, newdata = nd)
print(nd)
plot(Proportion ~ TEMPERATURE, data = nd, type = "b")
to check what the absolute changes in Proportion are for certain absolute changes in TEMPERATURE. | interpretation of betareg coef
Yes, the logit link can be interpreted like that. It's just not a change in "odds" (= ratio of probabilities) but a change in a ratio of proportions. More formally, the model equation for the expectat |
20,276 | Repeated measures analysis: why nest experimental factors within subject factor? | This is a very interesting question. I have been thinking this and related things for a long time.
For me the key to understanding this is to realise that: Random intercepts for a grouping factor are not always sufficient to capture the random variation in the data that is in excess of the residual variation. Because of this, we sometimes see models with random intecepts for interactions between a fixed factor and a grouping variable (and even sometimes random intercepts just for a fixed factor). Generally we advise that a factor can be fixed or random (intercepts) but not both - however there are important exceptions of which your example here is one.
Another hindrence to understanding this is for people like me who come from a multilevel modelling / mixed model background in observational social and medical sciences, we are often caught up in thinking about repeated measures and nesting vs crossed random effects without an understanding that things are a bit different in experimental analysis. More on this a bit later.
Judging by the comments we have both discovered the same thing. In the context of a repeated measures ANOVA, if you want to obtain the same results with lmer then you fit:
y ~ A + B + (1|id) + (1|id:A) + (1|id:B)
where I have discarded factor C without loss of generality.
and the reason why some people specify 1|id/A/B is that they are using nmle:lme and not lme4:lmer. I am not sure why this is needed in lme() but I am fairly sure that to replicate a repeated measures anova - where there is variation for each combination of id and the factors - then you fit the model above in lmer(). Note that (1|id/A/B) seems similar, however it is wrong because it would also fit (1|id:A:B) which is indistinguishable from the residual variance (as noted in your comment also).
It is important to note (and therefore worth repeating) that we only fit this type of model where we have reason to believe that there is variation for each combination of id and the factors. Typically with mixed models we would not do this. We need to understand experimental design. One type of experiment where this is common is the so-called split-plot design where blocking has also been used. This type of experimental design employs randomisation at different "levels" - or rather different combinations of factors, and this is why analysis of such experiemnts often includes random intercept terms that at first glance seem odd. However, the random structure is a property of the experimental design and without knowledge of this, it is virtually impossible to select the correct structure.
So, with regards to the your actual question where the experiment has a repeated factorial design, we can use our friend, simulation, to investigate further.
We will simulate data for the models:
y ~ A + B + (1|id)
and
y ~ A + B + (1|id) + (1|id:A) + (1|id:B)
and look at what happens when we use both models to analyse both datasets.
set.seed(15)
n <- 100 # number of subjects
K <- 4 # number of measurements per subject
# set up covariates
df <- data.frame(id = rep(seq_len(n), each = K),
A = rep(c(0,0,1,1), times = n),
B = rep(c(0,1), times = n * 2)
)
#
df$y <- df$A + 2 * df$B + 3 * df$id + rnorm(n * K)
m0 <- lmer(y ~ A + B + (1|id) , data = df)
m1 <- lmer(y ~ A + B + (1|id) + (1|id:A) + (1|id:B), data = df)
summary(m0)
m0 is the "right" model for these data because we simply created y with fixed effects for id (which we capture with random intercepts) and unit variance. This is a bit of an abuse but it is convenient and does what we want:
Groups Name Variance Std.Dev.
id (Intercept) 842.1869 29.0205
Residual 0.9946 0.9973
Number of obs: 400, groups: id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 50.47508 2.90333 17.39
A 1.01277 0.09973 10.15
B 2.06675 0.09973 20.72
as we can see, we recover unit variance in the residual and good estimates for the fixed effects. However:
> summary(m1)
Random effects:
Groups Name Variance Std.Dev.
id:B (Intercept) 0.000e+00 0.0000
id:A (Intercept) 8.724e-03 0.0934
id (Intercept) 8.422e+02 29.0204
Residual 9.888e-01 0.9944
Number of obs: 400, groups: id:B, 200; id:A, 200; id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 50.47508 2.90334 17.39
A 1.01277 0.10031 10.10
B 2.06675 0.09944 20.78
This is a singular fit - zero estimates for the variance of the id:B term and close to zero for id:A - which we happen to know is correct here because we didn't simulate any variance for those "levels". Also we find:
> anova(m0, m1)
m0: y ~ A + B + (1 | id)
m1: y ~ A + B + (1 | id) + (1 | id:A) + (1 | id:B)
npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
m0 5 1952.8 1972.7 -971.39 1942.8
m1 7 1956.8 1984.7 -971.39 1942.8 0.0052 2 0.9974
meaning that we strongly prefer the (correct) model m0
So now we simulate data with variation at these "levels" too. Since m1 is the model we want to simlulate for, we an use it's design matrix for the random effects:
# design matrix for the random effects
Z <- as.matrix(getME(m1, "Z"))
# design matrix for the fixed effects
X <- model.matrix(~ A + B, data = df)
betas <- c(10, 2, 3) # fixed effects coefficients
D1 <- 1 # SD of random intercepts for id
D2 <- 2 # SD of random intercepts for id:A
D3 <- 3 # SD of random intercepts for id:B
# we simulate random effects
b <- c(rnorm(n*2, sd = D3), rnorm(n*2, sd = D2), rnorm(n, sd = D1))
# the order here is goverened by the order that lme4 creates the Z matrix
# linear predictor
lp <- X %*% betas + Z %*% b
# add residual variance of 1
df$y <- lp + rnorm(n * K)
m2 <- lmer(y ~ A + B + (1|id) + (1|id:A) + (1|id:B), data = df)
m3 <- lmer(y ~ A + B + (1|id), data = df)
summary(m2)
'm2` is the corect model here and we obtain:
Random effects:
Groups Name Variance Std.Dev.
id:B (Intercept) 6.9061 2.6279
id:A (Intercept) 4.4766 2.1158
id (Intercept) 2.9117 1.7064
Residual 0.8704 0.9329
Number of obs: 400, groups: id:B, 200; id:A, 200; id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 10.3870 0.3866 26.867
A 1.8123 0.3134 5.782
B 3.0242 0.3832 7.892
the SD for the id intercept is a little high, but otherwise we have good estimates for the random and fixed effects. On the other hand:
> summary(m3)
Random effects:
Groups Name Variance Std.Dev.
id (Intercept) 6.712 2.591
Residual 8.433 2.904
Number of obs: 400, groups: id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 10.3870 0.3611 28.767
A 1.8123 0.2904 6.241
B 3.0242 0.2904 10.414
although the fixed effects point estimates are OK, their standard errors are larger. The random structure is, of course, completely wrong. And finally:
> anova(m2, m3)
Models:
m3: y ~ A + B + (1 | id)
m2: y ~ A + B + (1 | id) + (1 | id:A) + (1 | id:B)
npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
m3 5 2138.1 2158.1 -1064.07 2128.1
m2 7 1985.7 2013.7 -985.87 1971.7 156.4 2 < 2.2e-16 ***
showing that we strongly prefer m2 | Repeated measures analysis: why nest experimental factors within subject factor? | This is a very interesting question. I have been thinking this and related things for a long time.
For me the key to understanding this is to realise that: Random intercepts for a grouping factor are | Repeated measures analysis: why nest experimental factors within subject factor?
This is a very interesting question. I have been thinking this and related things for a long time.
For me the key to understanding this is to realise that: Random intercepts for a grouping factor are not always sufficient to capture the random variation in the data that is in excess of the residual variation. Because of this, we sometimes see models with random intecepts for interactions between a fixed factor and a grouping variable (and even sometimes random intercepts just for a fixed factor). Generally we advise that a factor can be fixed or random (intercepts) but not both - however there are important exceptions of which your example here is one.
Another hindrence to understanding this is for people like me who come from a multilevel modelling / mixed model background in observational social and medical sciences, we are often caught up in thinking about repeated measures and nesting vs crossed random effects without an understanding that things are a bit different in experimental analysis. More on this a bit later.
Judging by the comments we have both discovered the same thing. In the context of a repeated measures ANOVA, if you want to obtain the same results with lmer then you fit:
y ~ A + B + (1|id) + (1|id:A) + (1|id:B)
where I have discarded factor C without loss of generality.
and the reason why some people specify 1|id/A/B is that they are using nmle:lme and not lme4:lmer. I am not sure why this is needed in lme() but I am fairly sure that to replicate a repeated measures anova - where there is variation for each combination of id and the factors - then you fit the model above in lmer(). Note that (1|id/A/B) seems similar, however it is wrong because it would also fit (1|id:A:B) which is indistinguishable from the residual variance (as noted in your comment also).
It is important to note (and therefore worth repeating) that we only fit this type of model where we have reason to believe that there is variation for each combination of id and the factors. Typically with mixed models we would not do this. We need to understand experimental design. One type of experiment where this is common is the so-called split-plot design where blocking has also been used. This type of experimental design employs randomisation at different "levels" - or rather different combinations of factors, and this is why analysis of such experiemnts often includes random intercept terms that at first glance seem odd. However, the random structure is a property of the experimental design and without knowledge of this, it is virtually impossible to select the correct structure.
So, with regards to the your actual question where the experiment has a repeated factorial design, we can use our friend, simulation, to investigate further.
We will simulate data for the models:
y ~ A + B + (1|id)
and
y ~ A + B + (1|id) + (1|id:A) + (1|id:B)
and look at what happens when we use both models to analyse both datasets.
set.seed(15)
n <- 100 # number of subjects
K <- 4 # number of measurements per subject
# set up covariates
df <- data.frame(id = rep(seq_len(n), each = K),
A = rep(c(0,0,1,1), times = n),
B = rep(c(0,1), times = n * 2)
)
#
df$y <- df$A + 2 * df$B + 3 * df$id + rnorm(n * K)
m0 <- lmer(y ~ A + B + (1|id) , data = df)
m1 <- lmer(y ~ A + B + (1|id) + (1|id:A) + (1|id:B), data = df)
summary(m0)
m0 is the "right" model for these data because we simply created y with fixed effects for id (which we capture with random intercepts) and unit variance. This is a bit of an abuse but it is convenient and does what we want:
Groups Name Variance Std.Dev.
id (Intercept) 842.1869 29.0205
Residual 0.9946 0.9973
Number of obs: 400, groups: id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 50.47508 2.90333 17.39
A 1.01277 0.09973 10.15
B 2.06675 0.09973 20.72
as we can see, we recover unit variance in the residual and good estimates for the fixed effects. However:
> summary(m1)
Random effects:
Groups Name Variance Std.Dev.
id:B (Intercept) 0.000e+00 0.0000
id:A (Intercept) 8.724e-03 0.0934
id (Intercept) 8.422e+02 29.0204
Residual 9.888e-01 0.9944
Number of obs: 400, groups: id:B, 200; id:A, 200; id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 50.47508 2.90334 17.39
A 1.01277 0.10031 10.10
B 2.06675 0.09944 20.78
This is a singular fit - zero estimates for the variance of the id:B term and close to zero for id:A - which we happen to know is correct here because we didn't simulate any variance for those "levels". Also we find:
> anova(m0, m1)
m0: y ~ A + B + (1 | id)
m1: y ~ A + B + (1 | id) + (1 | id:A) + (1 | id:B)
npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
m0 5 1952.8 1972.7 -971.39 1942.8
m1 7 1956.8 1984.7 -971.39 1942.8 0.0052 2 0.9974
meaning that we strongly prefer the (correct) model m0
So now we simulate data with variation at these "levels" too. Since m1 is the model we want to simlulate for, we an use it's design matrix for the random effects:
# design matrix for the random effects
Z <- as.matrix(getME(m1, "Z"))
# design matrix for the fixed effects
X <- model.matrix(~ A + B, data = df)
betas <- c(10, 2, 3) # fixed effects coefficients
D1 <- 1 # SD of random intercepts for id
D2 <- 2 # SD of random intercepts for id:A
D3 <- 3 # SD of random intercepts for id:B
# we simulate random effects
b <- c(rnorm(n*2, sd = D3), rnorm(n*2, sd = D2), rnorm(n, sd = D1))
# the order here is goverened by the order that lme4 creates the Z matrix
# linear predictor
lp <- X %*% betas + Z %*% b
# add residual variance of 1
df$y <- lp + rnorm(n * K)
m2 <- lmer(y ~ A + B + (1|id) + (1|id:A) + (1|id:B), data = df)
m3 <- lmer(y ~ A + B + (1|id), data = df)
summary(m2)
'm2` is the corect model here and we obtain:
Random effects:
Groups Name Variance Std.Dev.
id:B (Intercept) 6.9061 2.6279
id:A (Intercept) 4.4766 2.1158
id (Intercept) 2.9117 1.7064
Residual 0.8704 0.9329
Number of obs: 400, groups: id:B, 200; id:A, 200; id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 10.3870 0.3866 26.867
A 1.8123 0.3134 5.782
B 3.0242 0.3832 7.892
the SD for the id intercept is a little high, but otherwise we have good estimates for the random and fixed effects. On the other hand:
> summary(m3)
Random effects:
Groups Name Variance Std.Dev.
id (Intercept) 6.712 2.591
Residual 8.433 2.904
Number of obs: 400, groups: id, 100
Fixed effects:
Estimate Std. Error t value
(Intercept) 10.3870 0.3611 28.767
A 1.8123 0.2904 6.241
B 3.0242 0.2904 10.414
although the fixed effects point estimates are OK, their standard errors are larger. The random structure is, of course, completely wrong. And finally:
> anova(m2, m3)
Models:
m3: y ~ A + B + (1 | id)
m2: y ~ A + B + (1 | id) + (1 | id:A) + (1 | id:B)
npar AIC BIC logLik deviance Chisq Df Pr(>Chisq)
m3 5 2138.1 2158.1 -1064.07 2128.1
m2 7 1985.7 2013.7 -985.87 1971.7 156.4 2 < 2.2e-16 ***
showing that we strongly prefer m2 | Repeated measures analysis: why nest experimental factors within subject factor?
This is a very interesting question. I have been thinking this and related things for a long time.
For me the key to understanding this is to realise that: Random intercepts for a grouping factor are |
20,277 | Simple Linear Regression in Keras | This is probably because there was no normalization done.
Neural network are very sensitive to non-normalized data.
Some intuition: when we're trying to find our multi-dimensional global minimum (like in the stochastic gradient descent model), in every iteration each feature "pulls" into its dimension (vector direction) with some force (the length of the vector). When the data is not normalized a small step in value for column A can cause a huge change in column B.
Your code coped with that using your very low learning rate, which "normalized" the effect on every column, though caused a delayed learning process, requiring much more epochs to finish.
Add this normalization code:
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x = sc.fit_transform(x)
y = sc.fit_transform(y)
And simply drop the learning rate param (lr) - letting it choose wisely an automatic value for you. I got the same desired chart as you now :) | Simple Linear Regression in Keras | This is probably because there was no normalization done.
Neural network are very sensitive to non-normalized data.
Some intuition: when we're trying to find our multi-dimensional global minimum (like | Simple Linear Regression in Keras
This is probably because there was no normalization done.
Neural network are very sensitive to non-normalized data.
Some intuition: when we're trying to find our multi-dimensional global minimum (like in the stochastic gradient descent model), in every iteration each feature "pulls" into its dimension (vector direction) with some force (the length of the vector). When the data is not normalized a small step in value for column A can cause a huge change in column B.
Your code coped with that using your very low learning rate, which "normalized" the effect on every column, though caused a delayed learning process, requiring much more epochs to finish.
Add this normalization code:
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x = sc.fit_transform(x)
y = sc.fit_transform(y)
And simply drop the learning rate param (lr) - letting it choose wisely an automatic value for you. I got the same desired chart as you now :) | Simple Linear Regression in Keras
This is probably because there was no normalization done.
Neural network are very sensitive to non-normalized data.
Some intuition: when we're trying to find our multi-dimensional global minimum (like |
20,278 | Simple Linear Regression in Keras | Normalization matters more when you have more than one dependent variable. If you look at the scatter plot, you can see outliers. A neural net with no hidden layers is the same as a linear regression model. Thus, it is fitting the best line to minimize the distance of residuals. Remove outliers and it will look more appropriate. | Simple Linear Regression in Keras | Normalization matters more when you have more than one dependent variable. If you look at the scatter plot, you can see outliers. A neural net with no hidden layers is the same as a linear regression | Simple Linear Regression in Keras
Normalization matters more when you have more than one dependent variable. If you look at the scatter plot, you can see outliers. A neural net with no hidden layers is the same as a linear regression model. Thus, it is fitting the best line to minimize the distance of residuals. Remove outliers and it will look more appropriate. | Simple Linear Regression in Keras
Normalization matters more when you have more than one dependent variable. If you look at the scatter plot, you can see outliers. A neural net with no hidden layers is the same as a linear regression |
20,279 | How to calculate confidence intervals for ratios? | First, to clarify, what you're dealing with is not quite a binomial distribution, as your question suggests (you refer to it as a Bernoulli experiment). Binomial distributions are discrete --- the outcome is either success or failure. Your outcome is a ratio each time you run your experiment, not a set of successes and failures that you then calculate one summary ratio on. Because of that, methods for calculating a binomial proportion confidence interval will throw away a lot of your information. And yet you're correct that it's problematic to treat this as though it's normally distributed since you can get a CI that extends past the possible range of your variable.
I recommend thinking about this in terms of logistic regression.
Run a logistic regression model with your ratio variable as the outcome and no predictors. The intercept and its CI will give you what you need in logits, and then you can convert it back to proportions. You can also just do the logistic conversion yourself, calculate the CI and then convert back to the original scale. My python is terrible, but here's how you could do that in R:
set.seed(24601)
data <- rbeta(100, 10, 3)
hist(data)
data_logits <- log(data/(1-data))
hist(data_logits)
# calculate CI for the transformed data
mean_logits <- mean(data_logits)
sd <- sd(data_logits)
n <- length(data_logits)
crit_t99 <- qt(.995, df = n-1) # for a CI99
ci_lo_logits <- mean_logits - crit_t * sd/sqrt(n)
ci_hi_logits <- mean_logits + crit_t * sd/sqrt(n)
# convert back to ratio
mean <- exp(mean_logits)/(1 + exp(mean_logits))
ci_lo <- exp(ci_lo_logits)/(1 + exp(ci_lo_logits))
ci_hi <- exp(ci_hi_logits)/(1 + exp(ci_hi_logits))
Here are the lower and upper bounds on a 99% CI for these data:
> ci_lo
[1] 0.7738327
> ci_hi
[1] 0.8207924 | How to calculate confidence intervals for ratios? | First, to clarify, what you're dealing with is not quite a binomial distribution, as your question suggests (you refer to it as a Bernoulli experiment). Binomial distributions are discrete --- the out | How to calculate confidence intervals for ratios?
First, to clarify, what you're dealing with is not quite a binomial distribution, as your question suggests (you refer to it as a Bernoulli experiment). Binomial distributions are discrete --- the outcome is either success or failure. Your outcome is a ratio each time you run your experiment, not a set of successes and failures that you then calculate one summary ratio on. Because of that, methods for calculating a binomial proportion confidence interval will throw away a lot of your information. And yet you're correct that it's problematic to treat this as though it's normally distributed since you can get a CI that extends past the possible range of your variable.
I recommend thinking about this in terms of logistic regression.
Run a logistic regression model with your ratio variable as the outcome and no predictors. The intercept and its CI will give you what you need in logits, and then you can convert it back to proportions. You can also just do the logistic conversion yourself, calculate the CI and then convert back to the original scale. My python is terrible, but here's how you could do that in R:
set.seed(24601)
data <- rbeta(100, 10, 3)
hist(data)
data_logits <- log(data/(1-data))
hist(data_logits)
# calculate CI for the transformed data
mean_logits <- mean(data_logits)
sd <- sd(data_logits)
n <- length(data_logits)
crit_t99 <- qt(.995, df = n-1) # for a CI99
ci_lo_logits <- mean_logits - crit_t * sd/sqrt(n)
ci_hi_logits <- mean_logits + crit_t * sd/sqrt(n)
# convert back to ratio
mean <- exp(mean_logits)/(1 + exp(mean_logits))
ci_lo <- exp(ci_lo_logits)/(1 + exp(ci_lo_logits))
ci_hi <- exp(ci_hi_logits)/(1 + exp(ci_hi_logits))
Here are the lower and upper bounds on a 99% CI for these data:
> ci_lo
[1] 0.7738327
> ci_hi
[1] 0.8207924 | How to calculate confidence intervals for ratios?
First, to clarify, what you're dealing with is not quite a binomial distribution, as your question suggests (you refer to it as a Bernoulli experiment). Binomial distributions are discrete --- the out |
20,280 | How to calculate confidence intervals for ratios? | You might want to try resampling/bootstrapping. Let's look at the simple case you mentioned.
With 3 data points of 0.99, 0.94, and 0.94, you wouldn't even do the resampling because you can just list out all 27 possible permutations, find the mean in each case, and then sort the means.
If you create the list and take the middle 25 observations, you have a $25/27=$ 92.6% confidence interval of [0.9400, 0.9733]. If you want to increase the confidence to $26/27=$ 96.3%, you have two one-sided choices of intervals. Either [0.9400, 0.9733] or [0.94, 0.99].
I assume your $n$ will be much greater than 3, so you will resample with replacement. Say you do this 1000 times. Then find the mean in each case. From the set of 1000 means, take the middle 950 values. The lowest and highest values of this subset form the 95% confidence interval.
The question here: How do we create a confidence interval for the parameter of a permutation test? gives more detail, including some R code. | How to calculate confidence intervals for ratios? | You might want to try resampling/bootstrapping. Let's look at the simple case you mentioned.
With 3 data points of 0.99, 0.94, and 0.94, you wouldn't even do the resampling because you can just list o | How to calculate confidence intervals for ratios?
You might want to try resampling/bootstrapping. Let's look at the simple case you mentioned.
With 3 data points of 0.99, 0.94, and 0.94, you wouldn't even do the resampling because you can just list out all 27 possible permutations, find the mean in each case, and then sort the means.
If you create the list and take the middle 25 observations, you have a $25/27=$ 92.6% confidence interval of [0.9400, 0.9733]. If you want to increase the confidence to $26/27=$ 96.3%, you have two one-sided choices of intervals. Either [0.9400, 0.9733] or [0.94, 0.99].
I assume your $n$ will be much greater than 3, so you will resample with replacement. Say you do this 1000 times. Then find the mean in each case. From the set of 1000 means, take the middle 950 values. The lowest and highest values of this subset form the 95% confidence interval.
The question here: How do we create a confidence interval for the parameter of a permutation test? gives more detail, including some R code. | How to calculate confidence intervals for ratios?
You might want to try resampling/bootstrapping. Let's look at the simple case you mentioned.
With 3 data points of 0.99, 0.94, and 0.94, you wouldn't even do the resampling because you can just list o |
20,281 | How to calculate confidence intervals for ratios? | Binomial confidence intervals have been the subject of statistician debates for a long time. Your problem considers a less than 100% ratio, but it becomes even more problematic if we use 100%. One insightful way to ask the question is:
Given the sun has risen without fail every day for the past 2,000 years, what is the probability that it will rise tomorrow?
With such a high success rate, we think the chances are pretty high, but we can't be 100% sure (the universe might explode first, or something). So, even if you had a 100% proportion, we can't let the confidence interval collapse at $p=1$.
There are a number of methods to calculate these tails. I'd recommend checking out Wikipedia for the math, or if you just want the answer, search for a binomial interval calculator like this one (which happens to also have some more explanation of the math behind it). | How to calculate confidence intervals for ratios? | Binomial confidence intervals have been the subject of statistician debates for a long time. Your problem considers a less than 100% ratio, but it becomes even more problematic if we use 100%. One i | How to calculate confidence intervals for ratios?
Binomial confidence intervals have been the subject of statistician debates for a long time. Your problem considers a less than 100% ratio, but it becomes even more problematic if we use 100%. One insightful way to ask the question is:
Given the sun has risen without fail every day for the past 2,000 years, what is the probability that it will rise tomorrow?
With such a high success rate, we think the chances are pretty high, but we can't be 100% sure (the universe might explode first, or something). So, even if you had a 100% proportion, we can't let the confidence interval collapse at $p=1$.
There are a number of methods to calculate these tails. I'd recommend checking out Wikipedia for the math, or if you just want the answer, search for a binomial interval calculator like this one (which happens to also have some more explanation of the math behind it). | How to calculate confidence intervals for ratios?
Binomial confidence intervals have been the subject of statistician debates for a long time. Your problem considers a less than 100% ratio, but it becomes even more problematic if we use 100%. One i |
20,282 | How to calculate confidence intervals for ratios? | A Bayesian approach:
Find the unique beta distribution $B$ that is induced by the experiments (and a prior, say, the Jeffreys prior), and then choose the smallest interval for which $B$'s density integrates to your desired "confidence". It's possible for there to be multiple solutions, and depending on your prior, the mean ratio might not be in your interval. | How to calculate confidence intervals for ratios? | A Bayesian approach:
Find the unique beta distribution $B$ that is induced by the experiments (and a prior, say, the Jeffreys prior), and then choose the smallest interval for which $B$'s density inte | How to calculate confidence intervals for ratios?
A Bayesian approach:
Find the unique beta distribution $B$ that is induced by the experiments (and a prior, say, the Jeffreys prior), and then choose the smallest interval for which $B$'s density integrates to your desired "confidence". It's possible for there to be multiple solutions, and depending on your prior, the mean ratio might not be in your interval. | How to calculate confidence intervals for ratios?
A Bayesian approach:
Find the unique beta distribution $B$ that is induced by the experiments (and a prior, say, the Jeffreys prior), and then choose the smallest interval for which $B$'s density inte |
20,283 | How to manually calculate the intercept and coefficient in logistic regression | Unfortunately, unlike linear regression, there's no simple formula for the maximum likelihood estimate of logistic regression. You'll have to perform some kind of optimization algorithm, like gradient descent or iteratively reweighted least squares. | How to manually calculate the intercept and coefficient in logistic regression | Unfortunately, unlike linear regression, there's no simple formula for the maximum likelihood estimate of logistic regression. You'll have to perform some kind of optimization algorithm, like gradient | How to manually calculate the intercept and coefficient in logistic regression
Unfortunately, unlike linear regression, there's no simple formula for the maximum likelihood estimate of logistic regression. You'll have to perform some kind of optimization algorithm, like gradient descent or iteratively reweighted least squares. | How to manually calculate the intercept and coefficient in logistic regression
Unfortunately, unlike linear regression, there's no simple formula for the maximum likelihood estimate of logistic regression. You'll have to perform some kind of optimization algorithm, like gradient |
20,284 | How to manually calculate the intercept and coefficient in logistic regression | I'd like to propose my method and hope it helps.
To calculate the coefficients manually you must have some data, or say constraints. In logistic regression, actually it is how logistic function is defined via the maximum entropy and lagrange multipliers, this constraint must be met with other two: $E_p f_j = E_{\hat p}f_j$. That is, the model's expectation should match the observed expectation, which has been illustrated in this paper. That's why logit-function as a link function in logistic regression is also termed mean function.
Take for example, the crosstab bellow shows how many males/females are in the honor class.
| female
hon | male female | Total
-----------+----------------------+----------
0 | 74 77 | 151
1 | 17 32 | 49
-----------+----------------------+----------
Total | 91 109 | 200
As mentioned above $\sum_i y_i x_{ij} = \sum_i p_i x_{ij}$ holds. The left hand side(LHS) is the expectation of the observations(y's in the sample) and the right hand side(RHS) is the model's expectation.
Assuming the function is $log(\frac{p}{1-p})=\beta_0 + \beta_1x_i$ or equivalently $p=\frac{1}{1+e^{-(\beta_0+\beta_1 * x_i)}}$($x_i$ represents the feature of the observation being a female, it is 1 if the observation is a female and 0 otherwise), obviously we know that the following two equations hold respectively when $X=1$ and when $X=0$ with the data shown above:
$$\frac{32}{109} = \frac{1}{1+e^{-(\beta_0+\beta_1 * 1)}}$$
$$\frac{17}{91} = \frac{1}{1+e^{-(\beta_0 + \beta_1 * 0)}}$$
So the intercept($\beta_0$) is -1.47 and the coefficient($\beta_1$) is 0.593. You can manually get it.
Along the same lines, you can manually calculate coefficients of other logistic regression models(it applies also to softmax regression but it is out the scope of this question) if enough data are given.
I hope I am right, if not please let me know. Thanks. | How to manually calculate the intercept and coefficient in logistic regression | I'd like to propose my method and hope it helps.
To calculate the coefficients manually you must have some data, or say constraints. In logistic regression, actually it is how logistic function is d | How to manually calculate the intercept and coefficient in logistic regression
I'd like to propose my method and hope it helps.
To calculate the coefficients manually you must have some data, or say constraints. In logistic regression, actually it is how logistic function is defined via the maximum entropy and lagrange multipliers, this constraint must be met with other two: $E_p f_j = E_{\hat p}f_j$. That is, the model's expectation should match the observed expectation, which has been illustrated in this paper. That's why logit-function as a link function in logistic regression is also termed mean function.
Take for example, the crosstab bellow shows how many males/females are in the honor class.
| female
hon | male female | Total
-----------+----------------------+----------
0 | 74 77 | 151
1 | 17 32 | 49
-----------+----------------------+----------
Total | 91 109 | 200
As mentioned above $\sum_i y_i x_{ij} = \sum_i p_i x_{ij}$ holds. The left hand side(LHS) is the expectation of the observations(y's in the sample) and the right hand side(RHS) is the model's expectation.
Assuming the function is $log(\frac{p}{1-p})=\beta_0 + \beta_1x_i$ or equivalently $p=\frac{1}{1+e^{-(\beta_0+\beta_1 * x_i)}}$($x_i$ represents the feature of the observation being a female, it is 1 if the observation is a female and 0 otherwise), obviously we know that the following two equations hold respectively when $X=1$ and when $X=0$ with the data shown above:
$$\frac{32}{109} = \frac{1}{1+e^{-(\beta_0+\beta_1 * 1)}}$$
$$\frac{17}{91} = \frac{1}{1+e^{-(\beta_0 + \beta_1 * 0)}}$$
So the intercept($\beta_0$) is -1.47 and the coefficient($\beta_1$) is 0.593. You can manually get it.
Along the same lines, you can manually calculate coefficients of other logistic regression models(it applies also to softmax regression but it is out the scope of this question) if enough data are given.
I hope I am right, if not please let me know. Thanks. | How to manually calculate the intercept and coefficient in logistic regression
I'd like to propose my method and hope it helps.
To calculate the coefficients manually you must have some data, or say constraints. In logistic regression, actually it is how logistic function is d |
20,285 | Non-square images for image classification | There are several ways to solve the problem depending on the classifier. Sliding Windows is the method I'm most familiar with, this is used for the neural network methods. This method involves taking a small sub-image and shifting it up and down with some overlaps. Some issues include finding the optimum shift parameters and multi scale-issues.
The final detection is usually determined by how confident the classifier is that each of the sub-images belong in that class: for example majority vote, total likelihood or total distance from the decision boundary. I have listed some material below, the first one is for the HOG classifier method but the concepts are the same.
Object Detection Sliding Windows
Object Category Detection: Sliding Windows
OverFeat Integrated Recognition, Localization and Detection using
Convolutional Networks | Non-square images for image classification | There are several ways to solve the problem depending on the classifier. Sliding Windows is the method I'm most familiar with, this is used for the neural network methods. This method involves taking | Non-square images for image classification
There are several ways to solve the problem depending on the classifier. Sliding Windows is the method I'm most familiar with, this is used for the neural network methods. This method involves taking a small sub-image and shifting it up and down with some overlaps. Some issues include finding the optimum shift parameters and multi scale-issues.
The final detection is usually determined by how confident the classifier is that each of the sub-images belong in that class: for example majority vote, total likelihood or total distance from the decision boundary. I have listed some material below, the first one is for the HOG classifier method but the concepts are the same.
Object Detection Sliding Windows
Object Category Detection: Sliding Windows
OverFeat Integrated Recognition, Localization and Detection using
Convolutional Networks | Non-square images for image classification
There are several ways to solve the problem depending on the classifier. Sliding Windows is the method I'm most familiar with, this is used for the neural network methods. This method involves taking |
20,286 | Non-square images for image classification | This shouldn't cause any problems at all if you are using a CNN. I made a CNN for recognizing faces, and since faces are usually around 70% as wide as they are tall, I used training images that are 80x100 pixels (a little extra width in case the head was at an angle). Your filters should still be squares though.
All that changes would be that now you have to keep track of a width and a height for your activation/pooled maps instead of just one value that tells you the size. For example -
Input image of 80 x 100
Apply 5 x 5 convolution filter gives a map of activations at 76 x 96
Apply 2 x 2 pooling gives a map of pooled activations at 38 x 48 | Non-square images for image classification | This shouldn't cause any problems at all if you are using a CNN. I made a CNN for recognizing faces, and since faces are usually around 70% as wide as they are tall, I used training images that are 80 | Non-square images for image classification
This shouldn't cause any problems at all if you are using a CNN. I made a CNN for recognizing faces, and since faces are usually around 70% as wide as they are tall, I used training images that are 80x100 pixels (a little extra width in case the head was at an angle). Your filters should still be squares though.
All that changes would be that now you have to keep track of a width and a height for your activation/pooled maps instead of just one value that tells you the size. For example -
Input image of 80 x 100
Apply 5 x 5 convolution filter gives a map of activations at 76 x 96
Apply 2 x 2 pooling gives a map of pooled activations at 38 x 48 | Non-square images for image classification
This shouldn't cause any problems at all if you are using a CNN. I made a CNN for recognizing faces, and since faces are usually around 70% as wide as they are tall, I used training images that are 80 |
20,287 | Non-square images for image classification | Just stick with squares, it's safe & easy
Most CNN training datasets have images that are not square. The standard method is to take a square crop out of it -- often picking a random square for training, and at test time to use multiple squares and aggregate the predictions (center + 4 corners is a classic).
Cropping is preferable to padding because with padding you're wasting a lot of compute on blank image space, and you're creating this artificial edge where the real picture has a hard line against a solid color, which can confuse the classifier. So the easiest thing is to just stick with common practice and crop to square.
This is general advice, which works well for typical camera images that have moderate aspect ratios like 1.5:1. In your case where the aspect ratio is extreme, cropping is obviously going to greatly limit what the network can physically see.
Using different sizes
That said most modern CNN's do allow you to run non-square images through them. This is somewhat advanced / unusual, so better to stick to square images unless you're confident you understand what's going on and the risks involved. Whether or not this is physically possible for a type of CNN is determined by the network layer near the end, that transitions from the convolutional processing to the fully-connected processing for classification or what-have-you.
In early CNN's like AlexNet, this layer just serialized all the channel maps from the reduced-resolution processed image into a simple vector of features - so if your last conv layer outputs an 8x8x32 Tensor (HxWxChannel) this just unrolls it to a 2048 dimensional vector. This strategy encodes each position of the image into a different set of dimensions in the vector, allowing the network to reason about features at different locations of the image (can be good or bad), but also means that the resolution it can work with is fixed, because if you change the resolution, the dimensionality of the feature vector would change, and then the down-stream fully-connected layers just wouldn't work.
Most modern CNN's instead use some kind of pooling layer to average or aggregate the location-based features across the spatial dimensions into a simple feature vector (sometimes accurately described as 1x1 resolution) for the down-stream FC layers. So if that same network that output 8x8x32 features reached this pooling layer, it might average all 64 (=8x8) of those 32-dim vectors into a single 32-dimensional feature vector for downstream processing. (In practice these nets have more than 32 features at the end.)
With these networks, there's nothing physically stopping you from running different sized images through the network. Some good details in e.g. this answer: https://stats.stackexchange.com/a/392854/13947 But always remember that if you ask a network to do anything it wasn't trained to do, it's extremely likely to behave badly! | Non-square images for image classification | Just stick with squares, it's safe & easy
Most CNN training datasets have images that are not square. The standard method is to take a square crop out of it -- often picking a random square for train | Non-square images for image classification
Just stick with squares, it's safe & easy
Most CNN training datasets have images that are not square. The standard method is to take a square crop out of it -- often picking a random square for training, and at test time to use multiple squares and aggregate the predictions (center + 4 corners is a classic).
Cropping is preferable to padding because with padding you're wasting a lot of compute on blank image space, and you're creating this artificial edge where the real picture has a hard line against a solid color, which can confuse the classifier. So the easiest thing is to just stick with common practice and crop to square.
This is general advice, which works well for typical camera images that have moderate aspect ratios like 1.5:1. In your case where the aspect ratio is extreme, cropping is obviously going to greatly limit what the network can physically see.
Using different sizes
That said most modern CNN's do allow you to run non-square images through them. This is somewhat advanced / unusual, so better to stick to square images unless you're confident you understand what's going on and the risks involved. Whether or not this is physically possible for a type of CNN is determined by the network layer near the end, that transitions from the convolutional processing to the fully-connected processing for classification or what-have-you.
In early CNN's like AlexNet, this layer just serialized all the channel maps from the reduced-resolution processed image into a simple vector of features - so if your last conv layer outputs an 8x8x32 Tensor (HxWxChannel) this just unrolls it to a 2048 dimensional vector. This strategy encodes each position of the image into a different set of dimensions in the vector, allowing the network to reason about features at different locations of the image (can be good or bad), but also means that the resolution it can work with is fixed, because if you change the resolution, the dimensionality of the feature vector would change, and then the down-stream fully-connected layers just wouldn't work.
Most modern CNN's instead use some kind of pooling layer to average or aggregate the location-based features across the spatial dimensions into a simple feature vector (sometimes accurately described as 1x1 resolution) for the down-stream FC layers. So if that same network that output 8x8x32 features reached this pooling layer, it might average all 64 (=8x8) of those 32-dim vectors into a single 32-dimensional feature vector for downstream processing. (In practice these nets have more than 32 features at the end.)
With these networks, there's nothing physically stopping you from running different sized images through the network. Some good details in e.g. this answer: https://stats.stackexchange.com/a/392854/13947 But always remember that if you ask a network to do anything it wasn't trained to do, it's extremely likely to behave badly! | Non-square images for image classification
Just stick with squares, it's safe & easy
Most CNN training datasets have images that are not square. The standard method is to take a square crop out of it -- often picking a random square for train |
20,288 | How to know if a learning curve from SVM model suffers from bias or variance? | Part 1: How to read learning curve
Firstly, we should focus on the right side of the plot, where there are sufficient data for evaluation.
If two curves are "close to each other" and both of them but have a low score. The model suffer from an under fitting problem (High Bias)
If training curve has a much better score but testing curve has a lower score, i.e., there are large gaps between two curves. Then the model suffer from an over fitting problem (High Variance)
Part 2: My assessment for the plot you provided
From the plot it is hard to say if the model is good or not. It is possible that you have a really "easy problem", a good model can achieve 90%. On the other hand, it is possible you have a really "hard problem" that the best thing we can do is achieving 70%. (Note that, you may not expect you will have a perfect model, say score is 1. How much you can achieve depends on how much noise in your data. Suppose your data has a lot of data points have EXACT feature but different labels, no matter what you do, you cannot achieve 1 on score.)
Another problem in your example is that 350 examples seems to be too small in a real world application.
Part 3: More suggestions
To get a better understanding, you can do following experiments to experience under fitting an over fitting and observe what will happen in learning curve.
Select a very complicated data say MNIST data, and fit with a simple model, say linear model with one feature.
Select a simple data, say iris data, fit with a complexity model, say, SVM.
Part 4: Other examples
In addition, I will give two examples related to under fitting and over fitting. Note this is not learning curve, but the performance respect to number of iterations in gradient boosting model, where more iterations will have more chance of over fitting. The x axis shows number of iterations, and y axis shows the performance, which is negative Area Under ROC (the lower the better.)
The left subplot does not suffer from over fitting (well also not under fitting since the performance is reasonably good) but right one suffers from over fitting when number of iterations is large. | How to know if a learning curve from SVM model suffers from bias or variance? | Part 1: How to read learning curve
Firstly, we should focus on the right side of the plot, where there are sufficient data for evaluation.
If two curves are "close to each other" and both of them but | How to know if a learning curve from SVM model suffers from bias or variance?
Part 1: How to read learning curve
Firstly, we should focus on the right side of the plot, where there are sufficient data for evaluation.
If two curves are "close to each other" and both of them but have a low score. The model suffer from an under fitting problem (High Bias)
If training curve has a much better score but testing curve has a lower score, i.e., there are large gaps between two curves. Then the model suffer from an over fitting problem (High Variance)
Part 2: My assessment for the plot you provided
From the plot it is hard to say if the model is good or not. It is possible that you have a really "easy problem", a good model can achieve 90%. On the other hand, it is possible you have a really "hard problem" that the best thing we can do is achieving 70%. (Note that, you may not expect you will have a perfect model, say score is 1. How much you can achieve depends on how much noise in your data. Suppose your data has a lot of data points have EXACT feature but different labels, no matter what you do, you cannot achieve 1 on score.)
Another problem in your example is that 350 examples seems to be too small in a real world application.
Part 3: More suggestions
To get a better understanding, you can do following experiments to experience under fitting an over fitting and observe what will happen in learning curve.
Select a very complicated data say MNIST data, and fit with a simple model, say linear model with one feature.
Select a simple data, say iris data, fit with a complexity model, say, SVM.
Part 4: Other examples
In addition, I will give two examples related to under fitting and over fitting. Note this is not learning curve, but the performance respect to number of iterations in gradient boosting model, where more iterations will have more chance of over fitting. The x axis shows number of iterations, and y axis shows the performance, which is negative Area Under ROC (the lower the better.)
The left subplot does not suffer from over fitting (well also not under fitting since the performance is reasonably good) but right one suffers from over fitting when number of iterations is large. | How to know if a learning curve from SVM model suffers from bias or variance?
Part 1: How to read learning curve
Firstly, we should focus on the right side of the plot, where there are sufficient data for evaluation.
If two curves are "close to each other" and both of them but |
20,289 | machine learning techniques for longitudinal data | In the case where there are multiple observations from one subject (e.g., multiple visits from the same patient), then the 'patient id' is a 'grouping' variable. Care must be taken during model evaluation so that visits from the same patient do not appear in both the training and testing data, because these are correlated and will lead to inflation of classifier accuracy.
The cross-validation sklearn documentation has cross-validation iterators for grouped data. See GroupKFold, LeaveOneGroupOut, and LeavePGroupsOut.
Even better, try Recurrent Neural Networks or Hidden Markov Models. | machine learning techniques for longitudinal data | In the case where there are multiple observations from one subject (e.g., multiple visits from the same patient), then the 'patient id' is a 'grouping' variable. Care must be taken during model evalu | machine learning techniques for longitudinal data
In the case where there are multiple observations from one subject (e.g., multiple visits from the same patient), then the 'patient id' is a 'grouping' variable. Care must be taken during model evaluation so that visits from the same patient do not appear in both the training and testing data, because these are correlated and will lead to inflation of classifier accuracy.
The cross-validation sklearn documentation has cross-validation iterators for grouped data. See GroupKFold, LeaveOneGroupOut, and LeavePGroupsOut.
Even better, try Recurrent Neural Networks or Hidden Markov Models. | machine learning techniques for longitudinal data
In the case where there are multiple observations from one subject (e.g., multiple visits from the same patient), then the 'patient id' is a 'grouping' variable. Care must be taken during model evalu |
20,290 | machine learning techniques for longitudinal data | You can model your longitudinal with standard machine learning methods by just adding features, that represent the longitudinality, e.g. by adding a feature that represents the time. Or a feature that indicates the membership to a group, person etc (in the panel data case).
If you are creative with feature creation/extraction you can model anything with ML-algorithms. | machine learning techniques for longitudinal data | You can model your longitudinal with standard machine learning methods by just adding features, that represent the longitudinality, e.g. by adding a feature that represents the time. Or a feature that | machine learning techniques for longitudinal data
You can model your longitudinal with standard machine learning methods by just adding features, that represent the longitudinality, e.g. by adding a feature that represents the time. Or a feature that indicates the membership to a group, person etc (in the panel data case).
If you are creative with feature creation/extraction you can model anything with ML-algorithms. | machine learning techniques for longitudinal data
You can model your longitudinal with standard machine learning methods by just adding features, that represent the longitudinality, e.g. by adding a feature that represents the time. Or a feature that |
20,291 | Model construction: How to build a meaningful gam model? (generalized additive model) | The reason for the first error is that bio.percent_b500 doesn't have k - 1 unique values. If you set k to something lower for this spline then the model will fit. Why the 2-d thin-plate version works I think, IIRC, is because of the way it calculates a default for k when not supplied and it must do this from the data. So for model1, setting k = 9 works:
> model1 <- gam(honey.mean ~ s(week) + s(bio.percent_b500, k = 9), data = df)
In mgcv, a model with s(x1, x2) includes the main effects and the interaction. Note the s() assumes similar scaling in the variables, so I doubt you really want s() - try te() instead for a tensor-product smooth. If you want a decomposition into main effects and interaction then try:
model2 <- gam(honey.mean ~ ti(week) + ti(bio.percent_b500) +
ti(week, bio.percent_b500), data = df)
From the summary() it suggests the interaction is not required:
> summary(model2)
Family: gaussian
Link function: identity
Formula:
honey.mean ~ ti(week) + ti(bio.percent_b500) + ti(week, bio.percent_b500)
Parametric coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 12.2910 0.5263 23.35 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Approximate significance of smooth terms:
edf Ref.df F p-value
ti(week) 3.753 3.963 22.572 <2e-16 ***
ti(bio.percent_b500) 3.833 3.974 2.250 0.0461 *
ti(week,bio.percent_b500) 1.246 1.448 1.299 0.2036
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
R-sq.(adj) = 0.25 Deviance explained = 27.3%
GCV = 84.697 Scale est. = 81.884 n = 296
And you get similar information from the generalised likelihood ratio test"
> model1 <- gam(honey.mean ~ ti(week) + ti(bio.percent_b500, k = 9), data = df)
> anova(model1, model2, test = "LRT")
Analysis of Deviance Table
Model 1: honey.mean ~ ti(week) + ti(bio.percent_b500, k = 9)
Model 2: honey.mean ~ ti(week) + ti(bio.percent_b500) + ti(week, bio.percent_b500)
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 285.65 23363
2 286.17 23433 -0.51811 -69.675 0.1831
Here ti() terms are tensor-product interaction terms in which the main/marginal effects for other terms in the model are removed. You don't strictly need ti() I think in model1, te() or even s() should work, but the examples in mgcv all now use this form, so I'm going with that.
model3 doesn't make much sense to me, especially if you use tensor products; the s(week) term is included in the s(week, bio.percent_b500), but as I mentioned bivariate s() terms assume isotropy so this may have overly constrained the week component thus leaving space for the s(week) to come in and explain something. In general you shouldn't this is you get the bivariate term right. Whether you can get a true bivariate term right with your 500m variable isn't clear to me.
Questions:
Q1
I doubt you want an interaction without main/marginal effects. Your model2 includes both.
Q2
The model may be more complex in terms of the sets of functions you envisage but you need to consider the bases produced for each smooth term, plus mgcv uses splines with penalties which do smoothness selection and hence you could end up with a model that is at first glance more complex, but the smooth terms have been shrunken because of the penalties such that they use fewer degrees of freedom once fitted.
Q3
Technically, only model1 is really correctly specified. I don't think you want to assume isotropy for model2. I think you'll run into fitting problems with model3, model6, and model7 in general; if you set up the bases for the tensor products right, you shouldn't need the separate s(week) terms in those models. | Model construction: How to build a meaningful gam model? (generalized additive model) | The reason for the first error is that bio.percent_b500 doesn't have k - 1 unique values. If you set k to something lower for this spline then the model will fit. Why the 2-d thin-plate version works | Model construction: How to build a meaningful gam model? (generalized additive model)
The reason for the first error is that bio.percent_b500 doesn't have k - 1 unique values. If you set k to something lower for this spline then the model will fit. Why the 2-d thin-plate version works I think, IIRC, is because of the way it calculates a default for k when not supplied and it must do this from the data. So for model1, setting k = 9 works:
> model1 <- gam(honey.mean ~ s(week) + s(bio.percent_b500, k = 9), data = df)
In mgcv, a model with s(x1, x2) includes the main effects and the interaction. Note the s() assumes similar scaling in the variables, so I doubt you really want s() - try te() instead for a tensor-product smooth. If you want a decomposition into main effects and interaction then try:
model2 <- gam(honey.mean ~ ti(week) + ti(bio.percent_b500) +
ti(week, bio.percent_b500), data = df)
From the summary() it suggests the interaction is not required:
> summary(model2)
Family: gaussian
Link function: identity
Formula:
honey.mean ~ ti(week) + ti(bio.percent_b500) + ti(week, bio.percent_b500)
Parametric coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 12.2910 0.5263 23.35 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Approximate significance of smooth terms:
edf Ref.df F p-value
ti(week) 3.753 3.963 22.572 <2e-16 ***
ti(bio.percent_b500) 3.833 3.974 2.250 0.0461 *
ti(week,bio.percent_b500) 1.246 1.448 1.299 0.2036
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
R-sq.(adj) = 0.25 Deviance explained = 27.3%
GCV = 84.697 Scale est. = 81.884 n = 296
And you get similar information from the generalised likelihood ratio test"
> model1 <- gam(honey.mean ~ ti(week) + ti(bio.percent_b500, k = 9), data = df)
> anova(model1, model2, test = "LRT")
Analysis of Deviance Table
Model 1: honey.mean ~ ti(week) + ti(bio.percent_b500, k = 9)
Model 2: honey.mean ~ ti(week) + ti(bio.percent_b500) + ti(week, bio.percent_b500)
Resid. Df Resid. Dev Df Deviance Pr(>Chi)
1 285.65 23363
2 286.17 23433 -0.51811 -69.675 0.1831
Here ti() terms are tensor-product interaction terms in which the main/marginal effects for other terms in the model are removed. You don't strictly need ti() I think in model1, te() or even s() should work, but the examples in mgcv all now use this form, so I'm going with that.
model3 doesn't make much sense to me, especially if you use tensor products; the s(week) term is included in the s(week, bio.percent_b500), but as I mentioned bivariate s() terms assume isotropy so this may have overly constrained the week component thus leaving space for the s(week) to come in and explain something. In general you shouldn't this is you get the bivariate term right. Whether you can get a true bivariate term right with your 500m variable isn't clear to me.
Questions:
Q1
I doubt you want an interaction without main/marginal effects. Your model2 includes both.
Q2
The model may be more complex in terms of the sets of functions you envisage but you need to consider the bases produced for each smooth term, plus mgcv uses splines with penalties which do smoothness selection and hence you could end up with a model that is at first glance more complex, but the smooth terms have been shrunken because of the penalties such that they use fewer degrees of freedom once fitted.
Q3
Technically, only model1 is really correctly specified. I don't think you want to assume isotropy for model2. I think you'll run into fitting problems with model3, model6, and model7 in general; if you set up the bases for the tensor products right, you shouldn't need the separate s(week) terms in those models. | Model construction: How to build a meaningful gam model? (generalized additive model)
The reason for the first error is that bio.percent_b500 doesn't have k - 1 unique values. If you set k to something lower for this spline then the model will fit. Why the 2-d thin-plate version works |
20,292 | What is the most appropriate way to transform proportions when they are an independent variable? | The main question about transforming proportions (I'll use $x$ as symbol, similarly but not identically to your notation) allows some general comments.
In what follows I take it that the main motive for transforming proportions that are covariates (predictors, independent variables) is to improve the approximation to linearity of relationship, or if in exploratory mode to get a clearer idea graphically of the shape or indeed existence of any relationship. As usual whether a covariate is (e.g.) approximately normally distributed is not crucial as such. (Proportions are a not too distant relative of indicator variables with values $0, 1$ which can never be distributed normally, and proportions too are necessarily bounded.)
If the proportions can attain exact zeros or exact ones, it is essential that a transformation be defined for those limits, which clearly rules out $\log x$, as $\log 0$ is indeterminate. Beyond that a particular shape ideally requires some substantive (scientific, practical) justification, but lacking that it follows from some simple analysis that $\log (x + c)$ is highly sensitive to the value of $c$, as you hint.
This is a little easier to see with logarithms to base $10$, so temporarily let's consider $c = 10^k$ so that $\log_{10} (x + 10^k)$ maps $x = 0$ to $k$.
Hence $k = 0, c = 1$ maps $x = 0$ to $0$ and $x = 1$ to about $0.301$, while $k = -3, c = 0.001$ maps $x = 0$ to $-3$ and $x = 1$ to only a smidgen more than $0$.
Similarly, $k = -6, -9,$ whatever means that $0$ is mapped to those same limits, whereas to a increasingly good approximation $x = 1$ is mapped to $ 0$.
So the lower bound is stretched outwards with smaller and smaller added constants $c$, while the upper limit remains about the same. Such transformations thus can stretch the lower part of the range exceedingly and even create outliers from very small values at or near $0$.
Simply, people suggesting this presumably imagine that $\log (x + c)$ (now to any base you like) should behave very similarly to $\log x$ for small $c$, which is clearly true for large $x$, but not at all true for small $x$. Otherwise put, the steeper and steeper slope of $\log x$ as a function of $x$ as $x \downarrow 0$ can bite here very hard.
It seems preferable to focus on transformations that vary more gradually near $x = 0$ and (for other, but related, reasons) also near $x = 1$.
Square roots and cube roots and other powers $x^p$ are perfectly well defined for $x = 0, 1$ and often help when there is a need to stretch values near $0$. But these transformations are well known and I focus here more on another possibility.
The family of folded powers popularised by J.W. Tukey (Exploratory Data Analysis, Reading, MA: Addison-Wesley, 1977) is one possibility, and is
$x^p - (1 - x)^p$. Although there is no compulsion to choose powers that allow simple evocative names, the choices $p = 1/2$ (folded root) and $p = 1/3$ (folded cube root) seem the most useful members of this family.
The family resembles the familiar logit transformation $\text{logit}\ x = \log x - \log (1 - x)$ and indeed the logit is a limiting case as $p$ tends to $0$. A key difference is that folded powers are defined for $x = 0, 1$ and $p \ne 0$.
Folded powers, including now the logit, treat the extreme cases near $0$ and $1$ skew-symmetrically and plot as inverse sigmoid curves (some graphs below) mixing additive and multiplicative behaviour, echoing frequent qualitative (if not physical, biological, economic, whatever) facts for the underlying phenomenon that
the difference from say $0.01$ to $0.02$ can be a "big deal" (sure, $x$ changes by only $0.01$, but it also doubles)
the difference from say $0.98$ to $0.99$ can be a "big deal" too (sure, $x$ changes by only $0.01$, but the "fraction without" $1 - x$ also halves)
the difference from say $0.50$ to $0.51$ can be a "lesser deal" (sure, $x$ changes by $0.01$ too, but the proportional change is much smaller)
This is perhaps easiest to think about when some underlying dynamics is imagined: the increasing fraction of say literate people needs a big push to get going, speeds up and then slows down as it approaches the asymptote of universal literacy. So the curve in time can resemble an increasing or decreasing logistic. The fact that $0$ and $1$ proportions are approached more or more slowly is naturally one of several motivations for logit and similar models for proportional responses; although we are here focusing on proportional covariates, sigmoids can be useful here too.
Folded powers such as the folded root or cube root are not as strongly sigmoid as the logit, but a valuable merit here is their being directly and easily defined without fudges, kludges or nudges for $x = 0, 1$.
Turning to your fake but seemingly realistic dataset (which I imported into my own favourite software, but analysis is simple in anything decent), it turns out that none of these transformations really helps at all. But graphing the data gives a clear warning that even $\log(x + 0.001)$ is a mighty strong transformation, as can be seen also by plotting it directly.
The two main points I wish to make are that
$\log (x + c)$ often suggested, and often seemingly regarded as innocuous, is a dangerous transformation unless understood and often inappropriate whenever it stretches out the distribution mightily for small $x$ (unless this really is the desired behaviour).
For your example data, no transformation I tried seems to help.
At the same time, other possibilities are far from exhausted. (Notably, I didn't try square root or cube root, and stress that in many other problems those could be obvious and serious candidates.)
The first set of graphs simply shows some candidate transformations for proportions that can attain both $0$ and $1$. (I used natural logarithms, but shapes don't depend on the base chosen).
The second set of graphs shows no transformation helping much for the example data. (For comparison, a plain regression on the original data yields $R^2 = 3.7$%, RMSE $= 0.994$.)
Tiny puzzle. Your $y$ is said to be a proportion, but its values are around $6$ to $10$.
EDIT: The original data could be plotted here because the OP briefly posted data, but then later removed them.
Other threads here using folded powers include
Transforming proportion data: when arcsin square root is not enough
Regression: Scatterplot with low R squared and high p-values
Plot a highly skewed dataset | What is the most appropriate way to transform proportions when they are an independent variable? | The main question about transforming proportions (I'll use $x$ as symbol, similarly but not identically to your notation) allows some general comments.
In what follows I take it that the main motive | What is the most appropriate way to transform proportions when they are an independent variable?
The main question about transforming proportions (I'll use $x$ as symbol, similarly but not identically to your notation) allows some general comments.
In what follows I take it that the main motive for transforming proportions that are covariates (predictors, independent variables) is to improve the approximation to linearity of relationship, or if in exploratory mode to get a clearer idea graphically of the shape or indeed existence of any relationship. As usual whether a covariate is (e.g.) approximately normally distributed is not crucial as such. (Proportions are a not too distant relative of indicator variables with values $0, 1$ which can never be distributed normally, and proportions too are necessarily bounded.)
If the proportions can attain exact zeros or exact ones, it is essential that a transformation be defined for those limits, which clearly rules out $\log x$, as $\log 0$ is indeterminate. Beyond that a particular shape ideally requires some substantive (scientific, practical) justification, but lacking that it follows from some simple analysis that $\log (x + c)$ is highly sensitive to the value of $c$, as you hint.
This is a little easier to see with logarithms to base $10$, so temporarily let's consider $c = 10^k$ so that $\log_{10} (x + 10^k)$ maps $x = 0$ to $k$.
Hence $k = 0, c = 1$ maps $x = 0$ to $0$ and $x = 1$ to about $0.301$, while $k = -3, c = 0.001$ maps $x = 0$ to $-3$ and $x = 1$ to only a smidgen more than $0$.
Similarly, $k = -6, -9,$ whatever means that $0$ is mapped to those same limits, whereas to a increasingly good approximation $x = 1$ is mapped to $ 0$.
So the lower bound is stretched outwards with smaller and smaller added constants $c$, while the upper limit remains about the same. Such transformations thus can stretch the lower part of the range exceedingly and even create outliers from very small values at or near $0$.
Simply, people suggesting this presumably imagine that $\log (x + c)$ (now to any base you like) should behave very similarly to $\log x$ for small $c$, which is clearly true for large $x$, but not at all true for small $x$. Otherwise put, the steeper and steeper slope of $\log x$ as a function of $x$ as $x \downarrow 0$ can bite here very hard.
It seems preferable to focus on transformations that vary more gradually near $x = 0$ and (for other, but related, reasons) also near $x = 1$.
Square roots and cube roots and other powers $x^p$ are perfectly well defined for $x = 0, 1$ and often help when there is a need to stretch values near $0$. But these transformations are well known and I focus here more on another possibility.
The family of folded powers popularised by J.W. Tukey (Exploratory Data Analysis, Reading, MA: Addison-Wesley, 1977) is one possibility, and is
$x^p - (1 - x)^p$. Although there is no compulsion to choose powers that allow simple evocative names, the choices $p = 1/2$ (folded root) and $p = 1/3$ (folded cube root) seem the most useful members of this family.
The family resembles the familiar logit transformation $\text{logit}\ x = \log x - \log (1 - x)$ and indeed the logit is a limiting case as $p$ tends to $0$. A key difference is that folded powers are defined for $x = 0, 1$ and $p \ne 0$.
Folded powers, including now the logit, treat the extreme cases near $0$ and $1$ skew-symmetrically and plot as inverse sigmoid curves (some graphs below) mixing additive and multiplicative behaviour, echoing frequent qualitative (if not physical, biological, economic, whatever) facts for the underlying phenomenon that
the difference from say $0.01$ to $0.02$ can be a "big deal" (sure, $x$ changes by only $0.01$, but it also doubles)
the difference from say $0.98$ to $0.99$ can be a "big deal" too (sure, $x$ changes by only $0.01$, but the "fraction without" $1 - x$ also halves)
the difference from say $0.50$ to $0.51$ can be a "lesser deal" (sure, $x$ changes by $0.01$ too, but the proportional change is much smaller)
This is perhaps easiest to think about when some underlying dynamics is imagined: the increasing fraction of say literate people needs a big push to get going, speeds up and then slows down as it approaches the asymptote of universal literacy. So the curve in time can resemble an increasing or decreasing logistic. The fact that $0$ and $1$ proportions are approached more or more slowly is naturally one of several motivations for logit and similar models for proportional responses; although we are here focusing on proportional covariates, sigmoids can be useful here too.
Folded powers such as the folded root or cube root are not as strongly sigmoid as the logit, but a valuable merit here is their being directly and easily defined without fudges, kludges or nudges for $x = 0, 1$.
Turning to your fake but seemingly realistic dataset (which I imported into my own favourite software, but analysis is simple in anything decent), it turns out that none of these transformations really helps at all. But graphing the data gives a clear warning that even $\log(x + 0.001)$ is a mighty strong transformation, as can be seen also by plotting it directly.
The two main points I wish to make are that
$\log (x + c)$ often suggested, and often seemingly regarded as innocuous, is a dangerous transformation unless understood and often inappropriate whenever it stretches out the distribution mightily for small $x$ (unless this really is the desired behaviour).
For your example data, no transformation I tried seems to help.
At the same time, other possibilities are far from exhausted. (Notably, I didn't try square root or cube root, and stress that in many other problems those could be obvious and serious candidates.)
The first set of graphs simply shows some candidate transformations for proportions that can attain both $0$ and $1$. (I used natural logarithms, but shapes don't depend on the base chosen).
The second set of graphs shows no transformation helping much for the example data. (For comparison, a plain regression on the original data yields $R^2 = 3.7$%, RMSE $= 0.994$.)
Tiny puzzle. Your $y$ is said to be a proportion, but its values are around $6$ to $10$.
EDIT: The original data could be plotted here because the OP briefly posted data, but then later removed them.
Other threads here using folded powers include
Transforming proportion data: when arcsin square root is not enough
Regression: Scatterplot with low R squared and high p-values
Plot a highly skewed dataset | What is the most appropriate way to transform proportions when they are an independent variable?
The main question about transforming proportions (I'll use $x$ as symbol, similarly but not identically to your notation) allows some general comments.
In what follows I take it that the main motive |
20,293 | Variable importance in RNN or LSTM | In short, yes, you can get some measure of variable importances for RNN based models. I won't iterate through all of the listed suggestions in the question, but I will walk through an example of sensitivity analysis in depth.
The data
The input data for my RNN will be composed of a time-series with three features, $x_1$, $x_2$, $x_3$. Each feature will be all be drawn from the random uniform distribution. The target variable for my RNN will be a time-series (one prediction for each time-step in my input):
$$
y = \left\{\begin{array}{lr}
0, & \text{if } x_1 x_2 \geq 0.25\\
1, & \text{if } x_1 x_2 < 0.25
\end{array}\right.
$$
As we can see, the target is dependent on only the first two features. Thus, a good variable importance metric should show the first two variables being important, and the third variable being unimportant.
The model
The model is a simple three layer LSTM with a sigmoid activation in the final layer. The model will be trained in 5 epochs with 1000 batches per epoch.
Variable importance
To measure the variable importance, we'll take a large sample (250 time-series) of our data $\hat{x}$ and compute the model's predictions $\hat{y}$. Then, for each variable $x_i$ we'll perturb that variable (and only that variable) by a random normal distribution centered at 0 with scale 0.2 and compute a prediction $\hat{y_i}$. We'll measure the effect this perturbation has by computing the Root Mean Square difference between the original $\hat{y}$ and the perturbed $\hat{y_i}$. A larger Root Mean Square difference means that variable is "more important".
Obviously, the exact mechanism you use to perturb your data, and how you measure the difference between perturbed and unperturbed outputs, will be highly dependent on your particular dataset.
Results
After doing all of the above, we see the following importances:
Variable 1, perturbation effect: 0.1162
Variable 2, perturbation effect: 0.1185
Variable 3, perturbation effect: 0.0077
As we expected, variables 1 and 2 are found to be much more important (about 15x more) than variable 3!
Python code to reproduce
from tensorflow import keras # tensorflow v1.14.0 was used
import numpy as np # numpy v1.17.1 was used
np.random.seed(2019)
def make_model():
inp = keras.layers.Input(shape=(10, 3))
x = keras.layers.LSTM(10, activation='relu', return_sequences=True)(inp)
x = keras.layers.LSTM(5, activation='relu', return_sequences=True)(x)
x = keras.layers.LSTM(1, activation='sigmoid', return_sequences=True)(x)
out = keras.layers.Flatten()(x)
return keras.models.Model(inp, out)
def data_gen():
while True:
x = np.random.rand(5, 10, 3) # batch x time x features
yield x, x[:, :, 0] * x[:, :, 1] < 0.25
def var_importance(model):
g = data_gen()
x = np.concatenate([next(g)[0] for _ in range(50)]) # Get a sample of data
orig_out = model.predict(x)
for i in range(3): # iterate over the three features
new_x = x.copy()
perturbation = np.random.normal(0.0, 0.2, size=new_x.shape[:2])
new_x[:, :, i] = new_x[:, :, i] + perturbation
perturbed_out = model.predict(new_x)
effect = ((orig_out - perturbed_out) ** 2).mean() ** 0.5
print(f'Variable {i+1}, perturbation effect: {effect:.4f}')
def main():
model = make_model()
model.compile('adam', 'binary_crossentropy')
print(model.summary())
model.fit_generator(data_gen(), steps_per_epoch=500, epochs=10)
var_importance(model)
if __name__ == "__main__":
main()
The output of the code:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 10, 3)] 0
_________________________________________________________________
lstm (LSTM) (None, 10, 10) 560
_________________________________________________________________
lstm_1 (LSTM) (None, 10, 5) 320
_________________________________________________________________
lstm_2 (LSTM) (None, 10, 1) 28
_________________________________________________________________
flatten (Flatten) (None, 10) 0
=================================================================
Total params: 908
Trainable params: 908
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
1000/1000 [==============================] - 14s 14ms/step - loss: 0.6261
Epoch 2/5
1000/1000 [==============================] - 12s 12ms/step - loss: 0.4901
Epoch 3/5
1000/1000 [==============================] - 13s 13ms/step - loss: 0.4631
Epoch 4/5
1000/1000 [==============================] - 14s 14ms/step - loss: 0.4480
Epoch 5/5
1000/1000 [==============================] - 14s 14ms/step - loss: 0.4440
Variable 1, perturbation effect: 0.1162
Variable 2, perturbation effect: 0.1185
Variable 3, perturbation effect: 0.0077 | Variable importance in RNN or LSTM | In short, yes, you can get some measure of variable importances for RNN based models. I won't iterate through all of the listed suggestions in the question, but I will walk through an example of sensi | Variable importance in RNN or LSTM
In short, yes, you can get some measure of variable importances for RNN based models. I won't iterate through all of the listed suggestions in the question, but I will walk through an example of sensitivity analysis in depth.
The data
The input data for my RNN will be composed of a time-series with three features, $x_1$, $x_2$, $x_3$. Each feature will be all be drawn from the random uniform distribution. The target variable for my RNN will be a time-series (one prediction for each time-step in my input):
$$
y = \left\{\begin{array}{lr}
0, & \text{if } x_1 x_2 \geq 0.25\\
1, & \text{if } x_1 x_2 < 0.25
\end{array}\right.
$$
As we can see, the target is dependent on only the first two features. Thus, a good variable importance metric should show the first two variables being important, and the third variable being unimportant.
The model
The model is a simple three layer LSTM with a sigmoid activation in the final layer. The model will be trained in 5 epochs with 1000 batches per epoch.
Variable importance
To measure the variable importance, we'll take a large sample (250 time-series) of our data $\hat{x}$ and compute the model's predictions $\hat{y}$. Then, for each variable $x_i$ we'll perturb that variable (and only that variable) by a random normal distribution centered at 0 with scale 0.2 and compute a prediction $\hat{y_i}$. We'll measure the effect this perturbation has by computing the Root Mean Square difference between the original $\hat{y}$ and the perturbed $\hat{y_i}$. A larger Root Mean Square difference means that variable is "more important".
Obviously, the exact mechanism you use to perturb your data, and how you measure the difference between perturbed and unperturbed outputs, will be highly dependent on your particular dataset.
Results
After doing all of the above, we see the following importances:
Variable 1, perturbation effect: 0.1162
Variable 2, perturbation effect: 0.1185
Variable 3, perturbation effect: 0.0077
As we expected, variables 1 and 2 are found to be much more important (about 15x more) than variable 3!
Python code to reproduce
from tensorflow import keras # tensorflow v1.14.0 was used
import numpy as np # numpy v1.17.1 was used
np.random.seed(2019)
def make_model():
inp = keras.layers.Input(shape=(10, 3))
x = keras.layers.LSTM(10, activation='relu', return_sequences=True)(inp)
x = keras.layers.LSTM(5, activation='relu', return_sequences=True)(x)
x = keras.layers.LSTM(1, activation='sigmoid', return_sequences=True)(x)
out = keras.layers.Flatten()(x)
return keras.models.Model(inp, out)
def data_gen():
while True:
x = np.random.rand(5, 10, 3) # batch x time x features
yield x, x[:, :, 0] * x[:, :, 1] < 0.25
def var_importance(model):
g = data_gen()
x = np.concatenate([next(g)[0] for _ in range(50)]) # Get a sample of data
orig_out = model.predict(x)
for i in range(3): # iterate over the three features
new_x = x.copy()
perturbation = np.random.normal(0.0, 0.2, size=new_x.shape[:2])
new_x[:, :, i] = new_x[:, :, i] + perturbation
perturbed_out = model.predict(new_x)
effect = ((orig_out - perturbed_out) ** 2).mean() ** 0.5
print(f'Variable {i+1}, perturbation effect: {effect:.4f}')
def main():
model = make_model()
model.compile('adam', 'binary_crossentropy')
print(model.summary())
model.fit_generator(data_gen(), steps_per_epoch=500, epochs=10)
var_importance(model)
if __name__ == "__main__":
main()
The output of the code:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) [(None, 10, 3)] 0
_________________________________________________________________
lstm (LSTM) (None, 10, 10) 560
_________________________________________________________________
lstm_1 (LSTM) (None, 10, 5) 320
_________________________________________________________________
lstm_2 (LSTM) (None, 10, 1) 28
_________________________________________________________________
flatten (Flatten) (None, 10) 0
=================================================================
Total params: 908
Trainable params: 908
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
1000/1000 [==============================] - 14s 14ms/step - loss: 0.6261
Epoch 2/5
1000/1000 [==============================] - 12s 12ms/step - loss: 0.4901
Epoch 3/5
1000/1000 [==============================] - 13s 13ms/step - loss: 0.4631
Epoch 4/5
1000/1000 [==============================] - 14s 14ms/step - loss: 0.4480
Epoch 5/5
1000/1000 [==============================] - 14s 14ms/step - loss: 0.4440
Variable 1, perturbation effect: 0.1162
Variable 2, perturbation effect: 0.1185
Variable 3, perturbation effect: 0.0077 | Variable importance in RNN or LSTM
In short, yes, you can get some measure of variable importances for RNN based models. I won't iterate through all of the listed suggestions in the question, but I will walk through an example of sensi |
20,294 | Bayes Theorem with multiple conditions | By Bayes' Theorem: \begin{align*}P(I\mid M_1\cap M_2)&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(M_1\cap M_2)}\\&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(I)P(M_1\cap M_2\mid I)+P(I')P(M_1\cap M_2\mid I')}.\end{align*} Now the paper you provided argues that
If $I$ is true,
then $M_1$ and $M_2$ are independent. But assuming guilt, the occurrence of one would increase the probability of the other.
So $$P(M_1\cap M_2\mid I)=P(M_1\mid I)P(M_2\mid I),\label{eq1}\tag{1}$$ and $$ P(M_1\cap M_2\mid I')=P(M_1\mid M_2\cap I')P(M_2\mid I')\geq P(M_1\mid I')P(M_2\mid I').\label{eq2}\tag{2}$$ Hence, \begin{align*}P(I\mid M_1\cap M_2)&=\frac{P(I)P(M_1\mid I)P(M_2\mid I)}{P(I)P(M_1\cap M_2\mid I)+P(I')P(M_1\cap M_2\mid I')}&& \text{(Substitute with \eqref{eq1})}\\&\leq\frac{P(I)P(M_1\mid I)P(M_2\mid I)}{P(I')P(M_1\cap M_2\mid I')}&& \text{(Lesser Denominator)}\\&\leq\frac{P(I)}{P(I')}\cdot\frac{P(M_1\mid I)P(M_2\mid I)}{P(M_1\mid I')P(M_2\mid I')}.&& \text{(Substitute with \eqref{eq2})}
\end{align*}
To derive \eqref{eq2}, note \begin{align*}\frac{P(M_1\cap M_2\mid I')}{P(M_2\mid I')}&=\frac{P(M_1\cap M_2\cap I')/P(I')}{P(M_2\cap I')/P(I')}\\&=\frac{P(M_1\cap M_2\cap I')}{P(M_2\cap I')}\\&=P(M_1\mid M_2\cap I')\end{align*} and since the occurrence of $M_2$ would increase the probability of $M_1$: $$P(M_1\mid M_2\cap I')\geq P(M_1\mid I')$$ | Bayes Theorem with multiple conditions | By Bayes' Theorem: \begin{align*}P(I\mid M_1\cap M_2)&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(M_1\cap M_2)}\\&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(I)P(M_1\cap M_2\mid I)+P(I')P(M_1\cap M_2\mid I')}.\end{alig | Bayes Theorem with multiple conditions
By Bayes' Theorem: \begin{align*}P(I\mid M_1\cap M_2)&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(M_1\cap M_2)}\\&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(I)P(M_1\cap M_2\mid I)+P(I')P(M_1\cap M_2\mid I')}.\end{align*} Now the paper you provided argues that
If $I$ is true,
then $M_1$ and $M_2$ are independent. But assuming guilt, the occurrence of one would increase the probability of the other.
So $$P(M_1\cap M_2\mid I)=P(M_1\mid I)P(M_2\mid I),\label{eq1}\tag{1}$$ and $$ P(M_1\cap M_2\mid I')=P(M_1\mid M_2\cap I')P(M_2\mid I')\geq P(M_1\mid I')P(M_2\mid I').\label{eq2}\tag{2}$$ Hence, \begin{align*}P(I\mid M_1\cap M_2)&=\frac{P(I)P(M_1\mid I)P(M_2\mid I)}{P(I)P(M_1\cap M_2\mid I)+P(I')P(M_1\cap M_2\mid I')}&& \text{(Substitute with \eqref{eq1})}\\&\leq\frac{P(I)P(M_1\mid I)P(M_2\mid I)}{P(I')P(M_1\cap M_2\mid I')}&& \text{(Lesser Denominator)}\\&\leq\frac{P(I)}{P(I')}\cdot\frac{P(M_1\mid I)P(M_2\mid I)}{P(M_1\mid I')P(M_2\mid I')}.&& \text{(Substitute with \eqref{eq2})}
\end{align*}
To derive \eqref{eq2}, note \begin{align*}\frac{P(M_1\cap M_2\mid I')}{P(M_2\mid I')}&=\frac{P(M_1\cap M_2\cap I')/P(I')}{P(M_2\cap I')/P(I')}\\&=\frac{P(M_1\cap M_2\cap I')}{P(M_2\cap I')}\\&=P(M_1\mid M_2\cap I')\end{align*} and since the occurrence of $M_2$ would increase the probability of $M_1$: $$P(M_1\mid M_2\cap I')\geq P(M_1\mid I')$$ | Bayes Theorem with multiple conditions
By Bayes' Theorem: \begin{align*}P(I\mid M_1\cap M_2)&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(M_1\cap M_2)}\\&=\frac{P(I)P(M_1\cap M_2\mid I)}{P(I)P(M_1\cap M_2\mid I)+P(I')P(M_1\cap M_2\mid I')}.\end{alig |
20,295 | Relation between "expectation of ratio" and "ratio of expectation" | It seems that's really just an approximation based on a second-order taylor series expansion that isn't garaunteed to be true under all circumstances, but this paper seems to outline a pretty concise derivation of it: http://www.stat.cmu.edu/~hseltman/files/ratio.pdf
I thought that link was especially helpful because it shows how to reach a first-order taylor series approximation at $E(X/Y) = E(X)/E(Y)$ and then further improve that to reach the formula you mentioned. | Relation between "expectation of ratio" and "ratio of expectation" | It seems that's really just an approximation based on a second-order taylor series expansion that isn't garaunteed to be true under all circumstances, but this paper seems to outline a pretty concise | Relation between "expectation of ratio" and "ratio of expectation"
It seems that's really just an approximation based on a second-order taylor series expansion that isn't garaunteed to be true under all circumstances, but this paper seems to outline a pretty concise derivation of it: http://www.stat.cmu.edu/~hseltman/files/ratio.pdf
I thought that link was especially helpful because it shows how to reach a first-order taylor series approximation at $E(X/Y) = E(X)/E(Y)$ and then further improve that to reach the formula you mentioned. | Relation between "expectation of ratio" and "ratio of expectation"
It seems that's really just an approximation based on a second-order taylor series expansion that isn't garaunteed to be true under all circumstances, but this paper seems to outline a pretty concise |
20,296 | Using Kalman filters to impute Missing Values in Time Series | Preliminaries: Kalman filtering:
Kalman filters operate on state-space models of the form (there are several ways to write it; this is an easy one based on Durbin and Koopman (2012); all of the following is based on that book, which is excellent):
$$
\begin{align}
y_t & = Z \alpha_t + \varepsilon_t \qquad & \varepsilon_t \sim N(0, H) \\
\alpha_{t_1} & = T \alpha_t + \eta_t & \eta_t \sim N(0, Q) \\
\alpha_1 & \sim N(a_1, P_1)
\end{align}
$$
where $y_t$ is the observed series (possibly with missing values) but $\alpha_t$ is fully unobserved. The first equation (the "measurement" equation) says that the observed data is related to the unobserved states in a particular way. The second equation (the "transition" equation) says that the unobserved states evolve over time in a particular way.
The Kalman filter operates to find optimal estimates of $\alpha_t$ ($\alpha_t$ is assumed to be Normal: $\alpha_t \sim N(a_t, P_t)$, so what the Kalman filter actually does is to compute the conditional mean and variance of the distribution for $\alpha_t$ conditional on observations up to time $t$).
In the typical case (when observations are available) the Kalman filter uses the estimate of the current state and the current observation $y_t$ to do the best it can to estimate the next state $\alpha_{t+1}$, as follows:
$$
\begin{align}
a_{t+1} & = T a_t + K_t (y_t - Z \alpha_t) \\
P_{t+1} & = T P_t (T - K_t Z)' + Q
\end{align}
$$
where $K_t$ is the "Kalman gain".
When there is not an observation, the Kalman filter still wants to compute $a_{t+1}$ and $P_{t+1}$ in the best possible way. Since $y_t$ is unavailable, it cannot make use of the measurement equation, but it can still use the transition equation. Thus, when $y_t$ is missing, the Kalman filter instead computes:
$$
\begin{align}
a_{t+1} & = T a_t \\
P_{t+1} & = T P_t T' + Q
\end{align}
$$
Essentially, it says that given $\alpha_t$, my best guess as to $\alpha_{t+1}$ without data is just the evolution specified in the transition equation. This can be performed for any number of time periods with missing data.
If there is data $y_t$, then the first set of filtering equations take the best guess without data, and add a "correction" in, based on how good the previous estimate was.
Imputing data:
Once the Kalman filter has been applied to the entire time range, you have optimal estimates of the states $a_t, P_t$ for $t = 1, 2, \dots, T$. Imputing data is then simple via the measurement equation. In particular, you just calculate:
$$\hat y_t = Z a_t $$
As for a reference, Durbin and Koopman (2012) is excellent; section 4.10 discusses missing observations.
Durbin, J., & Koopman, S. J. (2012). Time series analysis by state
space methods (No. 38). Oxford University Press. | Using Kalman filters to impute Missing Values in Time Series | Preliminaries: Kalman filtering:
Kalman filters operate on state-space models of the form (there are several ways to write it; this is an easy one based on Durbin and Koopman (2012); all of the follow | Using Kalman filters to impute Missing Values in Time Series
Preliminaries: Kalman filtering:
Kalman filters operate on state-space models of the form (there are several ways to write it; this is an easy one based on Durbin and Koopman (2012); all of the following is based on that book, which is excellent):
$$
\begin{align}
y_t & = Z \alpha_t + \varepsilon_t \qquad & \varepsilon_t \sim N(0, H) \\
\alpha_{t_1} & = T \alpha_t + \eta_t & \eta_t \sim N(0, Q) \\
\alpha_1 & \sim N(a_1, P_1)
\end{align}
$$
where $y_t$ is the observed series (possibly with missing values) but $\alpha_t$ is fully unobserved. The first equation (the "measurement" equation) says that the observed data is related to the unobserved states in a particular way. The second equation (the "transition" equation) says that the unobserved states evolve over time in a particular way.
The Kalman filter operates to find optimal estimates of $\alpha_t$ ($\alpha_t$ is assumed to be Normal: $\alpha_t \sim N(a_t, P_t)$, so what the Kalman filter actually does is to compute the conditional mean and variance of the distribution for $\alpha_t$ conditional on observations up to time $t$).
In the typical case (when observations are available) the Kalman filter uses the estimate of the current state and the current observation $y_t$ to do the best it can to estimate the next state $\alpha_{t+1}$, as follows:
$$
\begin{align}
a_{t+1} & = T a_t + K_t (y_t - Z \alpha_t) \\
P_{t+1} & = T P_t (T - K_t Z)' + Q
\end{align}
$$
where $K_t$ is the "Kalman gain".
When there is not an observation, the Kalman filter still wants to compute $a_{t+1}$ and $P_{t+1}$ in the best possible way. Since $y_t$ is unavailable, it cannot make use of the measurement equation, but it can still use the transition equation. Thus, when $y_t$ is missing, the Kalman filter instead computes:
$$
\begin{align}
a_{t+1} & = T a_t \\
P_{t+1} & = T P_t T' + Q
\end{align}
$$
Essentially, it says that given $\alpha_t$, my best guess as to $\alpha_{t+1}$ without data is just the evolution specified in the transition equation. This can be performed for any number of time periods with missing data.
If there is data $y_t$, then the first set of filtering equations take the best guess without data, and add a "correction" in, based on how good the previous estimate was.
Imputing data:
Once the Kalman filter has been applied to the entire time range, you have optimal estimates of the states $a_t, P_t$ for $t = 1, 2, \dots, T$. Imputing data is then simple via the measurement equation. In particular, you just calculate:
$$\hat y_t = Z a_t $$
As for a reference, Durbin and Koopman (2012) is excellent; section 4.10 discusses missing observations.
Durbin, J., & Koopman, S. J. (2012). Time series analysis by state
space methods (No. 38). Oxford University Press. | Using Kalman filters to impute Missing Values in Time Series
Preliminaries: Kalman filtering:
Kalman filters operate on state-space models of the form (there are several ways to write it; this is an easy one based on Durbin and Koopman (2012); all of the follow |
20,297 | Using Kalman filters to impute Missing Values in Time Series | The example in the posting that javlacalle points to in their comment features consecutive missing time points. You might also be interested in intervals around the imputed (in-sample forecasted) values, the calculation of which appears in this State Space paper, in section 2.1.
Another paper that might be interesting is this one. | Using Kalman filters to impute Missing Values in Time Series | The example in the posting that javlacalle points to in their comment features consecutive missing time points. You might also be interested in intervals around the imputed (in-sample forecasted) valu | Using Kalman filters to impute Missing Values in Time Series
The example in the posting that javlacalle points to in their comment features consecutive missing time points. You might also be interested in intervals around the imputed (in-sample forecasted) values, the calculation of which appears in this State Space paper, in section 2.1.
Another paper that might be interesting is this one. | Using Kalman filters to impute Missing Values in Time Series
The example in the posting that javlacalle points to in their comment features consecutive missing time points. You might also be interested in intervals around the imputed (in-sample forecasted) valu |
20,298 | Which converges faster, mean or median? | The mean and median are the same, in this particular case. It is known that the median is 64% efficient as the mean, so the mean is faster to converge. I can write more details but wikipedia deals with your question exactly. | Which converges faster, mean or median? | The mean and median are the same, in this particular case. It is known that the median is 64% efficient as the mean, so the mean is faster to converge. I can write more details but wikipedia deals wit | Which converges faster, mean or median?
The mean and median are the same, in this particular case. It is known that the median is 64% efficient as the mean, so the mean is faster to converge. I can write more details but wikipedia deals with your question exactly. | Which converges faster, mean or median?
The mean and median are the same, in this particular case. It is known that the median is 64% efficient as the mean, so the mean is faster to converge. I can write more details but wikipedia deals wit |
20,299 | Error terms vs Innovations | The innovations are used in the time series the same way as errors in cross-sectional analysis (such as OLS). For instance if you data generating process is $$y_t=0.9y_{t-1}+\varepsilon_t$$, then we estimated it as $$y_t=0.85y_{t-1}+e_t$$, we call $\varepsilon_t$ innovations (or errors), and $e_t$ - residuals.
For instance, take a look at this MATLAB help page on ARIMA class, where they always refer to innovations in the place where you'd expect to see errors in cross-sectional analysis such as in this MATLAB help page for LinearModel class. In cross-sectional context the model could look like $$y_i=0.9x_i+\varepsilon_i$$
In this MATLAB help page for arima.infer() method, which estimates innovations, the estimated errors are called residuals as usual.
So, I conclude that innovations are ok to interchange with errors. It's called innovations because in time series context the errors bring new information to the system. In cross-sectional context it doesn't make a sense to call them new, as the observations come not in time-ordered sequence. So, observation number 10 is not newer or older than observation number 9. In time series, 10 comes after 9, so in this regard the error/innovation can be seen as a new information from the point of view of the observer who hold the information set up to time 9. | Error terms vs Innovations | The innovations are used in the time series the same way as errors in cross-sectional analysis (such as OLS). For instance if you data generating process is $$y_t=0.9y_{t-1}+\varepsilon_t$$, then we e | Error terms vs Innovations
The innovations are used in the time series the same way as errors in cross-sectional analysis (such as OLS). For instance if you data generating process is $$y_t=0.9y_{t-1}+\varepsilon_t$$, then we estimated it as $$y_t=0.85y_{t-1}+e_t$$, we call $\varepsilon_t$ innovations (or errors), and $e_t$ - residuals.
For instance, take a look at this MATLAB help page on ARIMA class, where they always refer to innovations in the place where you'd expect to see errors in cross-sectional analysis such as in this MATLAB help page for LinearModel class. In cross-sectional context the model could look like $$y_i=0.9x_i+\varepsilon_i$$
In this MATLAB help page for arima.infer() method, which estimates innovations, the estimated errors are called residuals as usual.
So, I conclude that innovations are ok to interchange with errors. It's called innovations because in time series context the errors bring new information to the system. In cross-sectional context it doesn't make a sense to call them new, as the observations come not in time-ordered sequence. So, observation number 10 is not newer or older than observation number 9. In time series, 10 comes after 9, so in this regard the error/innovation can be seen as a new information from the point of view of the observer who hold the information set up to time 9. | Error terms vs Innovations
The innovations are used in the time series the same way as errors in cross-sectional analysis (such as OLS). For instance if you data generating process is $$y_t=0.9y_{t-1}+\varepsilon_t$$, then we e |
20,300 | Error terms vs Innovations | See Lawrence Christiano''s "Brief Review of VAR's" notes. He distinguishes between u(t)'s which are new errors that occur at each time in the time series (t,t+1) but do not necessarily mean anything, with underlying economic shocks which MAY persist on an Impulse response graph or show a pattern at some level "C", e.g. ut=C*et.
If there is no impact in the Long run, C=0, and ut=0 means random Gaussian white noise with E[ut]=0 mean. But if for example supply shocks are persistent, they will show some impulse response pattern long run where C has some value or level, like may C=.90% of the error ut will impact demand each time.
At least that's how I read it. But agree sometimes used interchangeably. | Error terms vs Innovations | See Lawrence Christiano''s "Brief Review of VAR's" notes. He distinguishes between u(t)'s which are new errors that occur at each time in the time series (t,t+1) but do not necessarily mean anything, | Error terms vs Innovations
See Lawrence Christiano''s "Brief Review of VAR's" notes. He distinguishes between u(t)'s which are new errors that occur at each time in the time series (t,t+1) but do not necessarily mean anything, with underlying economic shocks which MAY persist on an Impulse response graph or show a pattern at some level "C", e.g. ut=C*et.
If there is no impact in the Long run, C=0, and ut=0 means random Gaussian white noise with E[ut]=0 mean. But if for example supply shocks are persistent, they will show some impulse response pattern long run where C has some value or level, like may C=.90% of the error ut will impact demand each time.
At least that's how I read it. But agree sometimes used interchangeably. | Error terms vs Innovations
See Lawrence Christiano''s "Brief Review of VAR's" notes. He distinguishes between u(t)'s which are new errors that occur at each time in the time series (t,t+1) but do not necessarily mean anything, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.