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
15,401
Strategy for editing comma separated value (CSV) files
I like Gnumeric because it does not try to be so much idiot-resistant as others (it doesn't shout about lost functionality) and works with large data... yet I think it is Linux-only.
Strategy for editing comma separated value (CSV) files
I like Gnumeric because it does not try to be so much idiot-resistant as others (it doesn't shout about lost functionality) and works with large data... yet I think it is Linux-only.
Strategy for editing comma separated value (CSV) files I like Gnumeric because it does not try to be so much idiot-resistant as others (it doesn't shout about lost functionality) and works with large data... yet I think it is Linux-only.
Strategy for editing comma separated value (CSV) files I like Gnumeric because it does not try to be so much idiot-resistant as others (it doesn't shout about lost functionality) and works with large data... yet I think it is Linux-only.
15,402
Strategy for editing comma separated value (CSV) files
Just use Ron's Editor. Its just like Excel without the 'help'. From the site: Ron's Editor is a powerful tabular text, or CSV, editor. It can open any format of separated text, including the standard comma and tab separated files (CSV and TSV), and allows total control over their content and structure. Not only can tabular text files be edited, but they can also be easily filtered and summarized in as many extra views as required, adding powerful analysis functionality. License: Free for personal use/evaluation Runs on: Windows 32/64-bit 2000/XP/2003/Vista/
Strategy for editing comma separated value (CSV) files
Just use Ron's Editor. Its just like Excel without the 'help'. From the site: Ron's Editor is a powerful tabular text, or CSV, editor. It can open any format of separated text, including the standa
Strategy for editing comma separated value (CSV) files Just use Ron's Editor. Its just like Excel without the 'help'. From the site: Ron's Editor is a powerful tabular text, or CSV, editor. It can open any format of separated text, including the standard comma and tab separated files (CSV and TSV), and allows total control over their content and structure. Not only can tabular text files be edited, but they can also be easily filtered and summarized in as many extra views as required, adding powerful analysis functionality. License: Free for personal use/evaluation Runs on: Windows 32/64-bit 2000/XP/2003/Vista/
Strategy for editing comma separated value (CSV) files Just use Ron's Editor. Its just like Excel without the 'help'. From the site: Ron's Editor is a powerful tabular text, or CSV, editor. It can open any format of separated text, including the standa
15,403
Strategy for editing comma separated value (CSV) files
I personally like to use the idea of "relational database" to manage CSV files. CSV files are good for exchange data, but contains no business logic. My experience of working with CSV is "there are many iterations with business to refine the analysis". Working with only plain text files (CSV) will pose many challenges. For example, CSV file will not show "what make data unique", i.e., what is the "primary key to each row". This will cause big problems later on, when we have other data source to join. SQLite is a good tool to make CSV into relational database, and similar to CSV, it is easy to exchange, and no server set up are needed. More importantly, it supported very well in R and other statistical software. My strategy is always maintain a "cleaned data" in relational database. And keep it clear on the primary key of each table. Here is an example of what may happen in real word (suppose we are selling books): Day 1, I received a CSV file contain all customer information. Day 2, I received another CSV file contain all product (book) information.For some reason, business said no ISBN available and the combination of book name and author name is the primary key. Day 3, Business found book edition needs to be accounted for, they send another CSV to "overwrite" day2's CSV. Day 4, Business found customer information can be updated (such as address change), they send an updated version of customer information. Now, you can see the advantage of clean data and keep them in relational database. With the say customer ID as primary key, and book name, author and edition as primary key. It is very easy to make data updates and incorporate changes as needed. Also the primary key also gives "constraints" and "sanity check" for new coming data.
Strategy for editing comma separated value (CSV) files
I personally like to use the idea of "relational database" to manage CSV files. CSV files are good for exchange data, but contains no business logic. My experience of working with CSV is "there are ma
Strategy for editing comma separated value (CSV) files I personally like to use the idea of "relational database" to manage CSV files. CSV files are good for exchange data, but contains no business logic. My experience of working with CSV is "there are many iterations with business to refine the analysis". Working with only plain text files (CSV) will pose many challenges. For example, CSV file will not show "what make data unique", i.e., what is the "primary key to each row". This will cause big problems later on, when we have other data source to join. SQLite is a good tool to make CSV into relational database, and similar to CSV, it is easy to exchange, and no server set up are needed. More importantly, it supported very well in R and other statistical software. My strategy is always maintain a "cleaned data" in relational database. And keep it clear on the primary key of each table. Here is an example of what may happen in real word (suppose we are selling books): Day 1, I received a CSV file contain all customer information. Day 2, I received another CSV file contain all product (book) information.For some reason, business said no ISBN available and the combination of book name and author name is the primary key. Day 3, Business found book edition needs to be accounted for, they send another CSV to "overwrite" day2's CSV. Day 4, Business found customer information can be updated (such as address change), they send an updated version of customer information. Now, you can see the advantage of clean data and keep them in relational database. With the say customer ID as primary key, and book name, author and edition as primary key. It is very easy to make data updates and incorporate changes as needed. Also the primary key also gives "constraints" and "sanity check" for new coming data.
Strategy for editing comma separated value (CSV) files I personally like to use the idea of "relational database" to manage CSV files. CSV files are good for exchange data, but contains no business logic. My experience of working with CSV is "there are ma
15,404
Strategy for editing comma separated value (CSV) files
If you use Excel's "Import Data" feature, it will give you option of selecting the data type for each column. You can select all the columns and use the "Text" data type.
Strategy for editing comma separated value (CSV) files
If you use Excel's "Import Data" feature, it will give you option of selecting the data type for each column. You can select all the columns and use the "Text" data type.
Strategy for editing comma separated value (CSV) files If you use Excel's "Import Data" feature, it will give you option of selecting the data type for each column. You can select all the columns and use the "Text" data type.
Strategy for editing comma separated value (CSV) files If you use Excel's "Import Data" feature, it will give you option of selecting the data type for each column. You can select all the columns and use the "Text" data type.
15,405
dropout: forward prop VS back prop in machine learning Neural Network
Yes, the neurons are considered zero during backpropagation as well. Otherwise dropout wouldn't do anything! Remember that forward propagation during training is only used to set up the network for backpropagation, where the network is actually modified (as well as for tracking training error and such). In general, it's important to account for anything that you're doing in the forward step in the backward step as well – otherwise you're computing a gradient of a different function than you're evaluating. The way it's implemented in Caffe, for example, is (as can be verified from the source): In forward propagation, inputs are set to zero with probability $p$, and otherwise scaled up by $\frac{1}{1 - p}$. In backward propagation, gradients for the same dropped units are zeroed out; other gradients are scaled up by the same $\frac{1}{1-p}$.
dropout: forward prop VS back prop in machine learning Neural Network
Yes, the neurons are considered zero during backpropagation as well. Otherwise dropout wouldn't do anything! Remember that forward propagation during training is only used to set up the network for ba
dropout: forward prop VS back prop in machine learning Neural Network Yes, the neurons are considered zero during backpropagation as well. Otherwise dropout wouldn't do anything! Remember that forward propagation during training is only used to set up the network for backpropagation, where the network is actually modified (as well as for tracking training error and such). In general, it's important to account for anything that you're doing in the forward step in the backward step as well – otherwise you're computing a gradient of a different function than you're evaluating. The way it's implemented in Caffe, for example, is (as can be verified from the source): In forward propagation, inputs are set to zero with probability $p$, and otherwise scaled up by $\frac{1}{1 - p}$. In backward propagation, gradients for the same dropped units are zeroed out; other gradients are scaled up by the same $\frac{1}{1-p}$.
dropout: forward prop VS back prop in machine learning Neural Network Yes, the neurons are considered zero during backpropagation as well. Otherwise dropout wouldn't do anything! Remember that forward propagation during training is only used to set up the network for ba
15,406
Generalized Additive Model Python Libraries
I've written a Python implementation of GAMs using penalized B-splines. check it out here: https://github.com/dswah/pyGAM I've included lots of link functions, distributions and features.
Generalized Additive Model Python Libraries
I've written a Python implementation of GAMs using penalized B-splines. check it out here: https://github.com/dswah/pyGAM I've included lots of link functions, distributions and features.
Generalized Additive Model Python Libraries I've written a Python implementation of GAMs using penalized B-splines. check it out here: https://github.com/dswah/pyGAM I've included lots of link functions, distributions and features.
Generalized Additive Model Python Libraries I've written a Python implementation of GAMs using penalized B-splines. check it out here: https://github.com/dswah/pyGAM I've included lots of link functions, distributions and features.
15,407
Generalized Additive Model Python Libraries
Another option for quick experimentation with GAM models is the package https://github.com/malmgrek/gammy. The emphasis is on Bayesian modeling of the GAM coefficients as well as easy extensibility on custom basis functions. Currently e.g. Gaussian processes, B-splines, as well as different trivial constructs.
Generalized Additive Model Python Libraries
Another option for quick experimentation with GAM models is the package https://github.com/malmgrek/gammy. The emphasis is on Bayesian modeling of the GAM coefficients as well as easy extensibility on
Generalized Additive Model Python Libraries Another option for quick experimentation with GAM models is the package https://github.com/malmgrek/gammy. The emphasis is on Bayesian modeling of the GAM coefficients as well as easy extensibility on custom basis functions. Currently e.g. Gaussian processes, B-splines, as well as different trivial constructs.
Generalized Additive Model Python Libraries Another option for quick experimentation with GAM models is the package https://github.com/malmgrek/gammy. The emphasis is on Bayesian modeling of the GAM coefficients as well as easy extensibility on
15,408
Generalized Additive Model Python Libraries
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. Another recent development are neural additive models which apply the GAM approach to a deep learning architecture: https://arxiv.org/abs/2004.13912 https://github.com/nickfrosst/neural_additive_models
Generalized Additive Model Python Libraries
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.
Generalized Additive Model Python Libraries 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. Another recent development are neural additive models which apply the GAM approach to a deep learning architecture: https://arxiv.org/abs/2004.13912 https://github.com/nickfrosst/neural_additive_models
Generalized Additive Model Python Libraries 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.
15,409
How do I interpret this fitted vs residuals plot?
As @IrishStat commented you need to check your observed values against your errors to see if there are issues with variability. I'll come back to this towards the end. Just so you get an idea of what we mean by heteroskedasticity: when you fit a linear model on a variable $y$ you are essentially saying that you make the assumption that your $y \sim N(X\beta,\sigma^2)$ or in layman's terms that your $y$ is expected to equate $ X\beta$ plus some errors that have variance $\sigma^2$. This practically your linear model $y = X\beta + \epsilon$, where the errors $\epsilon \sim N(0,\sigma^2)$. OK, cool so far let's see that in code: set.seed(1); #set the seed for reproducability N = 100; #Sample size x = runif(N) #Independant variable beta = 4; #Regression coefficient epsilon = rnorm(N); #Error with variance 1 and mean 0 y = x * beta + epsilon #Your generative model lin_mod <- lm(y ~x) #Your linear model so right, how do my model behaves: x11(); par(mfrow=c(1,3)); #Make a new 1-by-3 plot plot(residuals(lin_mod)); title("Simple Residual Plot - OK model") acf(residuals(lin_mod), main = ""); title("Residual Autocorrelation Plot - OK model"); plot(fitted(lin_mod), residuals(lin_mod)); title("Residual vs Fit. value - OK model"); which should give you something like this: which means that your residuals do not seem to have an obvious trend based on your arbitrary index (1st plot - least informative really), seem to have no real correlation between them (2nd plot - quite important and probably more important than homoskedasticity) and that fitted values do not have an obvious trend of failure, ie. your fitted values vs your residuals appear quite random. Based on this we would say that we have no problems of heteroskedasticity as our residuals appear to have the same variance everywhere. OK, you want heteroskedasticity though. Given the same assumptions of linearity and additivity let's define another generative model with "obvious" heteroskedasticity problems. Namely after some values our observation will be much more noisy. epsilon_HS = epsilon; epsilon_HS[ x>.55 ] = epsilon_HS[x>.55 ] * 9 #Heteroskedastic errors y2 = x * beta + epsilon_HS #Your generative model lin_mod2 <- lm(y2 ~x) #Your unfortunate LM where the simple diagnostic plots of the model: par(mfrow=c(1,3)); #Make a new 1-by-3 plot plot(residuals(lin_mod2)); title("Simple Residual Plot - Fishy model") acf(residuals(lin_mod2), main = ""); title("Residual Autocorrelation Plot - Fishy model"); plot(fitted(lin_mod2), residuals(lin_mod2)); title("Residual vs Fit. value - Fishy model"); should give something like: Here the first plot seems a bit "odd"; it looks like we have a few residuals that cluster in small magnitudes but that is not always a problem... The second plot is OK, means we have not correlation between your residuals in different lags so we might breathe for a moment. And the third plot spills the beans: it is dead clear that as we got to higher values our residuals explode. We definitely have heteroskedasticity in this model's residuals and we need to do something about (eg. IRLS, Theil–Sen regression, etc.) Here the problem was really obvious but in other cases we might have missed; to reduce our chances of missing it another insightful plot was the one mentioned by IrishStat: Residuals versus Observed values, or in for our toy problem at hand: par(mfrow=c(1,2)) plot(y, residuals(lin_mod) ); title( "Residual vs Obs. value - OK model") plot(y2, residuals(lin_mod2) ); title( "Residual vs Obs. value - Fishy model") which should give something like: here the first plot seems "relatively OK" with only a somewhat hazy upward trend in the residuals of the model (as Scortchi mentioned see here as to why we are not worried). The second plot though exhibits this problem fully. It is crystal clear we have errors that are strongly dependent on the values of our observed values. This manifesting in issues with the coefficient of determination $R^2$ of our models at hand; eg. the "OK" model having an adjusted $R^2$ of $0.5989$ while the "fishy" one of $0.03919$. Thus we have reasons to believe model misspecification might be an issue. (Thanks to Scortchi for pointing out the misleading statement in my original answer.) In fairness of your situation, your residuals vs. fitted values plot seems relative OK. Checking your residuals vs. your observed values would probably be helpful to make sure you are on the safe side. (I did not mention QQ-plots or anything like that as not to perplex things more but you may want to briefly check those too.) I hope this helps with your understanding of heteroskedasticity and what you should look out for.
How do I interpret this fitted vs residuals plot?
As @IrishStat commented you need to check your observed values against your errors to see if there are issues with variability. I'll come back to this towards the end. Just so you get an idea of what
How do I interpret this fitted vs residuals plot? As @IrishStat commented you need to check your observed values against your errors to see if there are issues with variability. I'll come back to this towards the end. Just so you get an idea of what we mean by heteroskedasticity: when you fit a linear model on a variable $y$ you are essentially saying that you make the assumption that your $y \sim N(X\beta,\sigma^2)$ or in layman's terms that your $y$ is expected to equate $ X\beta$ plus some errors that have variance $\sigma^2$. This practically your linear model $y = X\beta + \epsilon$, where the errors $\epsilon \sim N(0,\sigma^2)$. OK, cool so far let's see that in code: set.seed(1); #set the seed for reproducability N = 100; #Sample size x = runif(N) #Independant variable beta = 4; #Regression coefficient epsilon = rnorm(N); #Error with variance 1 and mean 0 y = x * beta + epsilon #Your generative model lin_mod <- lm(y ~x) #Your linear model so right, how do my model behaves: x11(); par(mfrow=c(1,3)); #Make a new 1-by-3 plot plot(residuals(lin_mod)); title("Simple Residual Plot - OK model") acf(residuals(lin_mod), main = ""); title("Residual Autocorrelation Plot - OK model"); plot(fitted(lin_mod), residuals(lin_mod)); title("Residual vs Fit. value - OK model"); which should give you something like this: which means that your residuals do not seem to have an obvious trend based on your arbitrary index (1st plot - least informative really), seem to have no real correlation between them (2nd plot - quite important and probably more important than homoskedasticity) and that fitted values do not have an obvious trend of failure, ie. your fitted values vs your residuals appear quite random. Based on this we would say that we have no problems of heteroskedasticity as our residuals appear to have the same variance everywhere. OK, you want heteroskedasticity though. Given the same assumptions of linearity and additivity let's define another generative model with "obvious" heteroskedasticity problems. Namely after some values our observation will be much more noisy. epsilon_HS = epsilon; epsilon_HS[ x>.55 ] = epsilon_HS[x>.55 ] * 9 #Heteroskedastic errors y2 = x * beta + epsilon_HS #Your generative model lin_mod2 <- lm(y2 ~x) #Your unfortunate LM where the simple diagnostic plots of the model: par(mfrow=c(1,3)); #Make a new 1-by-3 plot plot(residuals(lin_mod2)); title("Simple Residual Plot - Fishy model") acf(residuals(lin_mod2), main = ""); title("Residual Autocorrelation Plot - Fishy model"); plot(fitted(lin_mod2), residuals(lin_mod2)); title("Residual vs Fit. value - Fishy model"); should give something like: Here the first plot seems a bit "odd"; it looks like we have a few residuals that cluster in small magnitudes but that is not always a problem... The second plot is OK, means we have not correlation between your residuals in different lags so we might breathe for a moment. And the third plot spills the beans: it is dead clear that as we got to higher values our residuals explode. We definitely have heteroskedasticity in this model's residuals and we need to do something about (eg. IRLS, Theil–Sen regression, etc.) Here the problem was really obvious but in other cases we might have missed; to reduce our chances of missing it another insightful plot was the one mentioned by IrishStat: Residuals versus Observed values, or in for our toy problem at hand: par(mfrow=c(1,2)) plot(y, residuals(lin_mod) ); title( "Residual vs Obs. value - OK model") plot(y2, residuals(lin_mod2) ); title( "Residual vs Obs. value - Fishy model") which should give something like: here the first plot seems "relatively OK" with only a somewhat hazy upward trend in the residuals of the model (as Scortchi mentioned see here as to why we are not worried). The second plot though exhibits this problem fully. It is crystal clear we have errors that are strongly dependent on the values of our observed values. This manifesting in issues with the coefficient of determination $R^2$ of our models at hand; eg. the "OK" model having an adjusted $R^2$ of $0.5989$ while the "fishy" one of $0.03919$. Thus we have reasons to believe model misspecification might be an issue. (Thanks to Scortchi for pointing out the misleading statement in my original answer.) In fairness of your situation, your residuals vs. fitted values plot seems relative OK. Checking your residuals vs. your observed values would probably be helpful to make sure you are on the safe side. (I did not mention QQ-plots or anything like that as not to perplex things more but you may want to briefly check those too.) I hope this helps with your understanding of heteroskedasticity and what you should look out for.
How do I interpret this fitted vs residuals plot? As @IrishStat commented you need to check your observed values against your errors to see if there are issues with variability. I'll come back to this towards the end. Just so you get an idea of what
15,410
How do I interpret this fitted vs residuals plot?
Your question seems to be about heteroscedasticity (because you mentioned it by name and added the tag), but your explicit question (e.g., in the title and) ending your post is more general, "whether my model is appropriate or not according to this plot". There is more to determining if a model is inappropriate than assessing heteroscedasticity. I scraped your data using this website (ht @Alexis). Note that the data are sorted in ascending order of fitted. Based on the regression and upper left plot, it seems to be sufficiently faithful: mod = lm(residuals~fitted) summary(mod) # ... # Residuals: # Min 1Q Median 3Q Max # -0.78374 -0.13559 0.00928 0.19525 0.48107 # # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 0.06406 0.35123 0.182 0.856 # fitted -0.01178 0.05675 -0.208 0.836 # # Residual standard error: 0.2349 on 53 degrees of freedom # Multiple R-squared: 0.0008118, Adjusted R-squared: -0.01804 # F-statistic: 0.04306 on 1 and 53 DF, p-value: 0.8364 I don't see any evidence of heteroscedasticity here. From the upper right (qq-plot), there doesn't seem to be any problems with the normality assumption either. On the other hand, the "S" curve in the red lowess fit (in the upper left plot), and the acf and pacf plots (at the bottom) do seem problematic. At the far left, most of the residuals are above the gray 0 line. As you move to the right, the bulk of the residuals drop below 0, then above, and then below again. The result of this is that if I told you I were looking at a particular residual and that it had a negative value (but I didn't tell you which one I was looking at), you could guess with good accuracy that the residuals nearby were also negatively valued. In other words, the residuals are not independent—knowing something about one gives you information about others. In addition to plots, this can be tested. A simple approach is to use a runs test: library(randtests) runs.test(residuals) # Runs Test # # data: residuals # statistic = -3.2972, runs = 16, n1 = 27, n2 = 27, n = 54, p-value = 0.0009764 # alternative hypothesis: nonrandomness The implication of this is that your model is misspecified. Because there are two 'bends' in the relationship, you will want to add $X^2$ and $X^3$ terms to your model to account for that. To answer your explicit questions: Your plot shows serial autocorrelations / non-independence of your residuals. It means that your model is not appropriate in its current form.
How do I interpret this fitted vs residuals plot?
Your question seems to be about heteroscedasticity (because you mentioned it by name and added the tag), but your explicit question (e.g., in the title and) ending your post is more general, "whether
How do I interpret this fitted vs residuals plot? Your question seems to be about heteroscedasticity (because you mentioned it by name and added the tag), but your explicit question (e.g., in the title and) ending your post is more general, "whether my model is appropriate or not according to this plot". There is more to determining if a model is inappropriate than assessing heteroscedasticity. I scraped your data using this website (ht @Alexis). Note that the data are sorted in ascending order of fitted. Based on the regression and upper left plot, it seems to be sufficiently faithful: mod = lm(residuals~fitted) summary(mod) # ... # Residuals: # Min 1Q Median 3Q Max # -0.78374 -0.13559 0.00928 0.19525 0.48107 # # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 0.06406 0.35123 0.182 0.856 # fitted -0.01178 0.05675 -0.208 0.836 # # Residual standard error: 0.2349 on 53 degrees of freedom # Multiple R-squared: 0.0008118, Adjusted R-squared: -0.01804 # F-statistic: 0.04306 on 1 and 53 DF, p-value: 0.8364 I don't see any evidence of heteroscedasticity here. From the upper right (qq-plot), there doesn't seem to be any problems with the normality assumption either. On the other hand, the "S" curve in the red lowess fit (in the upper left plot), and the acf and pacf plots (at the bottom) do seem problematic. At the far left, most of the residuals are above the gray 0 line. As you move to the right, the bulk of the residuals drop below 0, then above, and then below again. The result of this is that if I told you I were looking at a particular residual and that it had a negative value (but I didn't tell you which one I was looking at), you could guess with good accuracy that the residuals nearby were also negatively valued. In other words, the residuals are not independent—knowing something about one gives you information about others. In addition to plots, this can be tested. A simple approach is to use a runs test: library(randtests) runs.test(residuals) # Runs Test # # data: residuals # statistic = -3.2972, runs = 16, n1 = 27, n2 = 27, n = 54, p-value = 0.0009764 # alternative hypothesis: nonrandomness The implication of this is that your model is misspecified. Because there are two 'bends' in the relationship, you will want to add $X^2$ and $X^3$ terms to your model to account for that. To answer your explicit questions: Your plot shows serial autocorrelations / non-independence of your residuals. It means that your model is not appropriate in its current form.
How do I interpret this fitted vs residuals plot? Your question seems to be about heteroscedasticity (because you mentioned it by name and added the tag), but your explicit question (e.g., in the title and) ending your post is more general, "whether
15,411
Understanding the confidence band from a polynomial regression
The gray band is a confidence band for the regression line. I'm not familiar enough with ggplot2 to know for sure whether it is a 1 SE confidence band or a 95% confidence band, but I believe it is the former (Edit: evidently it is a 95% CI). A confidence band provides a representation of the uncertainty about your regression line. In a sense, you could think that the true regression line is as high as the top of that band, as low as the bottom, or wiggling differently within the band. (Note that this explanation is intended to be intuitive, and is not technically correct, but the fully correct explanation is hard for most people to follow.) You should use the confidence band to help you understand / think about the regression line. You should not use it to think about the raw data points. Remember that the regression line represents the mean of $Y$ at each point in $X$ (if you need to understand this more fully, it may help you to read my answer here: What is the intuition behind conditional Gaussian distributions?). On the other hand, you certainly do not expect every observed data point to be equal to the conditional mean. In other words, you should not use the confidence band to assess whether a data point is an outlier. (Edit: this note is peripheral to the main question, but seeks to clarify a point for the OP.) A polynomial regression is not a non-linear regression, even though what you get doesn't look like a straight line. The term 'linear' has a very specific meaning in a mathematical context, specifically, that the parameters you are estimating--the betas--are all coefficients. A polynomial regression just means that your covariates are $X$, $X^2$, $X^3$, etc., that is, they have a non-linear relation to each other, but your betas are still coefficients, thus it is still a linear model. If your betas were, say, exponents, then you would have a non-linear model. In sum, whether or not a line looks straight has nothing to do with whether or not a model is linear. When you fit a polynomial model (say with $X$ and $X^2$), the model doesn't 'know' that, e.g., $X_2$ is actually just the square of $X_1$. It 'thinks' these are just two variables (although it may recognize that there is some multicollinearity). Thus, in truth it is fitting a (straight / flat) regression plane in a three dimensional space rather than a (curved) regression line in a two dimensional space. This is not useful for us to think about, and in fact, extremely difficult to see since $X^2$ is a perfect function of $X$. As a result, we don't bother thinking of it in this way and our plots are really two dimensional projections onto the $(X,\ Y)$ plane. Nonetheless, in the appropriate space, the line is actually 'straight' in some sense. From a mathematical perspective, a model is linear if the parameters you are trying to estimate are coefficients. To clarify further, consider the comparison between the standard (OLS) linear regression model, and a simple logistic regression model presented in two different forms: $$ Y = \beta_0 + \beta_1X + \varepsilon $$ $$ \ln\left(\frac{\pi(Y)}{1 - \pi(Y)}\right) = \beta_0 + \beta_1X $$ $$ \pi(Y) = \frac{\exp(\beta_0 + \beta_1X)}{1 + \exp(\beta_0 + \beta_1X)} $$ The top model is OLS regression, and the bottom two are logistic regression, albeit presented in different ways. In all three cases, when you fit the model, you are estimating the $\beta$s. The top two models are linear, because all of the $\beta$s are coefficients, but the bottom model is non-linear (in this form) because the $\beta$s are exponents. (This may seem quite strange, but logistic regression is an instance of the generalized linear model, because it can be rewritten as a linear model. For more information about that, it may help to read my answer here: Difference between logit and probit models.)
Understanding the confidence band from a polynomial regression
The gray band is a confidence band for the regression line. I'm not familiar enough with ggplot2 to know for sure whether it is a 1 SE confidence band or a 95% confidence band, but I believe it is th
Understanding the confidence band from a polynomial regression The gray band is a confidence band for the regression line. I'm not familiar enough with ggplot2 to know for sure whether it is a 1 SE confidence band or a 95% confidence band, but I believe it is the former (Edit: evidently it is a 95% CI). A confidence band provides a representation of the uncertainty about your regression line. In a sense, you could think that the true regression line is as high as the top of that band, as low as the bottom, or wiggling differently within the band. (Note that this explanation is intended to be intuitive, and is not technically correct, but the fully correct explanation is hard for most people to follow.) You should use the confidence band to help you understand / think about the regression line. You should not use it to think about the raw data points. Remember that the regression line represents the mean of $Y$ at each point in $X$ (if you need to understand this more fully, it may help you to read my answer here: What is the intuition behind conditional Gaussian distributions?). On the other hand, you certainly do not expect every observed data point to be equal to the conditional mean. In other words, you should not use the confidence band to assess whether a data point is an outlier. (Edit: this note is peripheral to the main question, but seeks to clarify a point for the OP.) A polynomial regression is not a non-linear regression, even though what you get doesn't look like a straight line. The term 'linear' has a very specific meaning in a mathematical context, specifically, that the parameters you are estimating--the betas--are all coefficients. A polynomial regression just means that your covariates are $X$, $X^2$, $X^3$, etc., that is, they have a non-linear relation to each other, but your betas are still coefficients, thus it is still a linear model. If your betas were, say, exponents, then you would have a non-linear model. In sum, whether or not a line looks straight has nothing to do with whether or not a model is linear. When you fit a polynomial model (say with $X$ and $X^2$), the model doesn't 'know' that, e.g., $X_2$ is actually just the square of $X_1$. It 'thinks' these are just two variables (although it may recognize that there is some multicollinearity). Thus, in truth it is fitting a (straight / flat) regression plane in a three dimensional space rather than a (curved) regression line in a two dimensional space. This is not useful for us to think about, and in fact, extremely difficult to see since $X^2$ is a perfect function of $X$. As a result, we don't bother thinking of it in this way and our plots are really two dimensional projections onto the $(X,\ Y)$ plane. Nonetheless, in the appropriate space, the line is actually 'straight' in some sense. From a mathematical perspective, a model is linear if the parameters you are trying to estimate are coefficients. To clarify further, consider the comparison between the standard (OLS) linear regression model, and a simple logistic regression model presented in two different forms: $$ Y = \beta_0 + \beta_1X + \varepsilon $$ $$ \ln\left(\frac{\pi(Y)}{1 - \pi(Y)}\right) = \beta_0 + \beta_1X $$ $$ \pi(Y) = \frac{\exp(\beta_0 + \beta_1X)}{1 + \exp(\beta_0 + \beta_1X)} $$ The top model is OLS regression, and the bottom two are logistic regression, albeit presented in different ways. In all three cases, when you fit the model, you are estimating the $\beta$s. The top two models are linear, because all of the $\beta$s are coefficients, but the bottom model is non-linear (in this form) because the $\beta$s are exponents. (This may seem quite strange, but logistic regression is an instance of the generalized linear model, because it can be rewritten as a linear model. For more information about that, it may help to read my answer here: Difference between logit and probit models.)
Understanding the confidence band from a polynomial regression The gray band is a confidence band for the regression line. I'm not familiar enough with ggplot2 to know for sure whether it is a 1 SE confidence band or a 95% confidence band, but I believe it is th
15,412
Understanding the confidence band from a polynomial regression
To add to the already existing answers, the band represents a confidence interval of the mean, but from your question you clearly are looking for a prediction interval. Prediction intervals are a range that if you drew one new point that point would theoretically be contained in the range X% of the time (where you can set the level of X). library(ggplot2) set.seed(5) x <- rnorm(100) y <- 0.5*x + rt(100,1) MyD <- data.frame(cbind(x,y)) We can generate the same type of plot you've shown in your initial question with a confidence interval around the mean of the smoothed loess regression line (the default is a 95% confidence interval). ConfiMean <- ggplot(data = MyD, aes(x,y)) + geom_point() + geom_smooth() ConfiMean For a quick and dirty example of prediction intervals, here I generate a prediction interval using linear regression with smoothing splines (so it is not necessarily a straight line). With the sample data it does pretty well, for the 100 points only 4 are outside the range (and I specified a 90% interval on the predict function). #Now getting prediction intervals from lm using smoothing splines library(splines) MyMod <- lm(y ~ ns(x,4), MyD) MyPreds <- data.frame(predict(MyMod, interval="predict", level = 0.90)) PredInt <- ggplot(data = MyD, aes(x,y)) + geom_point() + geom_ribbon(data=MyPreds, aes(x=x,ymin=lwr, ymax=upr), alpha=0.5) PredInt (note: actual confidence intervals are smoother, as there was a code typo in the original answer) Now a few more notes. I agree with Ladislav that you should consider time series forecasting methods since you have a regular series since sometime in 2007 and it is clear from your plot if you look hard there is seasonality (connecting the points would make it much clearer). For this I would suggest checking out the forecast.stl function in the forecast package where you can choose a seasonal window and it provides a robust decomposition of the seasonality and trend using Loess. I mention robust methods because your data have a few noticeable spikes. More generally for non-time series data I would consider other robust methods if you have data with occasional outliers. I do not know how to generate prediction intervals using Loess directly, but you may consider quantile regression (depending on how extreme the prediction intervals need to be). Otherwise if you just want to fit to be potentially non-linear you can consider splines to allow the function to vary over x.
Understanding the confidence band from a polynomial regression
To add to the already existing answers, the band represents a confidence interval of the mean, but from your question you clearly are looking for a prediction interval. Prediction intervals are a rang
Understanding the confidence band from a polynomial regression To add to the already existing answers, the band represents a confidence interval of the mean, but from your question you clearly are looking for a prediction interval. Prediction intervals are a range that if you drew one new point that point would theoretically be contained in the range X% of the time (where you can set the level of X). library(ggplot2) set.seed(5) x <- rnorm(100) y <- 0.5*x + rt(100,1) MyD <- data.frame(cbind(x,y)) We can generate the same type of plot you've shown in your initial question with a confidence interval around the mean of the smoothed loess regression line (the default is a 95% confidence interval). ConfiMean <- ggplot(data = MyD, aes(x,y)) + geom_point() + geom_smooth() ConfiMean For a quick and dirty example of prediction intervals, here I generate a prediction interval using linear regression with smoothing splines (so it is not necessarily a straight line). With the sample data it does pretty well, for the 100 points only 4 are outside the range (and I specified a 90% interval on the predict function). #Now getting prediction intervals from lm using smoothing splines library(splines) MyMod <- lm(y ~ ns(x,4), MyD) MyPreds <- data.frame(predict(MyMod, interval="predict", level = 0.90)) PredInt <- ggplot(data = MyD, aes(x,y)) + geom_point() + geom_ribbon(data=MyPreds, aes(x=x,ymin=lwr, ymax=upr), alpha=0.5) PredInt (note: actual confidence intervals are smoother, as there was a code typo in the original answer) Now a few more notes. I agree with Ladislav that you should consider time series forecasting methods since you have a regular series since sometime in 2007 and it is clear from your plot if you look hard there is seasonality (connecting the points would make it much clearer). For this I would suggest checking out the forecast.stl function in the forecast package where you can choose a seasonal window and it provides a robust decomposition of the seasonality and trend using Loess. I mention robust methods because your data have a few noticeable spikes. More generally for non-time series data I would consider other robust methods if you have data with occasional outliers. I do not know how to generate prediction intervals using Loess directly, but you may consider quantile regression (depending on how extreme the prediction intervals need to be). Otherwise if you just want to fit to be potentially non-linear you can consider splines to allow the function to vary over x.
Understanding the confidence band from a polynomial regression To add to the already existing answers, the band represents a confidence interval of the mean, but from your question you clearly are looking for a prediction interval. Prediction intervals are a rang
15,413
Understanding the confidence band from a polynomial regression
Well, the blue line is a smooth local regression. You may control the wiggliness of the line by the span parameter (from 0 to 1). But your example is a "time-series" so try to look for some more proper methods of analysis than only fit a smooth curve (which should serve only to reveal possible trend). According to documentation to ggplot2(and book in comment below): stat_smooth is a confidence interval of the smooth shown in grey. If you want to turn the confidence interval off, use se = FALSE.
Understanding the confidence band from a polynomial regression
Well, the blue line is a smooth local regression. You may control the wiggliness of the line by the span parameter (from 0 to 1). But your example is a "time-series" so try to look for some more prope
Understanding the confidence band from a polynomial regression Well, the blue line is a smooth local regression. You may control the wiggliness of the line by the span parameter (from 0 to 1). But your example is a "time-series" so try to look for some more proper methods of analysis than only fit a smooth curve (which should serve only to reveal possible trend). According to documentation to ggplot2(and book in comment below): stat_smooth is a confidence interval of the smooth shown in grey. If you want to turn the confidence interval off, use se = FALSE.
Understanding the confidence band from a polynomial regression Well, the blue line is a smooth local regression. You may control the wiggliness of the line by the span parameter (from 0 to 1). But your example is a "time-series" so try to look for some more prope
15,414
What is tied data in the context of a rank correlation coefficient?
It means data that have the same value; for instance if you have 1,2,3,3,4 as the dataset then the two 3's are tied data. If you have 1,2,3,4,5,5,5,6,7,7 as the dataset then the 5's and the 7's are tied data.
What is tied data in the context of a rank correlation coefficient?
It means data that have the same value; for instance if you have 1,2,3,3,4 as the dataset then the two 3's are tied data. If you have 1,2,3,4,5,5,5,6,7,7 as the dataset then the 5's and the 7's are ti
What is tied data in the context of a rank correlation coefficient? It means data that have the same value; for instance if you have 1,2,3,3,4 as the dataset then the two 3's are tied data. If you have 1,2,3,4,5,5,5,6,7,7 as the dataset then the 5's and the 7's are tied data.
What is tied data in the context of a rank correlation coefficient? It means data that have the same value; for instance if you have 1,2,3,3,4 as the dataset then the two 3's are tied data. If you have 1,2,3,4,5,5,5,6,7,7 as the dataset then the 5's and the 7's are ti
15,415
What is tied data in the context of a rank correlation coefficient?
"Tied data" comes up in the context of rank-based non-parametric statistical tests. Non-parametric tests: testing that does not assume a particular probability distribution, eg it does not assume a bell-shaped curve. rank-based: a large class of non-parametric tests start by converting the numbers (eg "3 days", "5 days", and "4 days") into ranks (eg "shortest duration (3rd)", "longest duration (1st)", "second longest duration (2nd)"). A traditional parametric testing method is then applied to these ranks. Tied data is an issue since numbers that are identical now need to be converted into rank. Sometimes ranks are randomly assigned, sometimes an average rank is used. Most importantly, a protocol for breaking tied ranks needs to be described for reproducibility of the result.
What is tied data in the context of a rank correlation coefficient?
"Tied data" comes up in the context of rank-based non-parametric statistical tests. Non-parametric tests: testing that does not assume a particular probability distribution, eg it does not assume a be
What is tied data in the context of a rank correlation coefficient? "Tied data" comes up in the context of rank-based non-parametric statistical tests. Non-parametric tests: testing that does not assume a particular probability distribution, eg it does not assume a bell-shaped curve. rank-based: a large class of non-parametric tests start by converting the numbers (eg "3 days", "5 days", and "4 days") into ranks (eg "shortest duration (3rd)", "longest duration (1st)", "second longest duration (2nd)"). A traditional parametric testing method is then applied to these ranks. Tied data is an issue since numbers that are identical now need to be converted into rank. Sometimes ranks are randomly assigned, sometimes an average rank is used. Most importantly, a protocol for breaking tied ranks needs to be described for reproducibility of the result.
What is tied data in the context of a rank correlation coefficient? "Tied data" comes up in the context of rank-based non-parametric statistical tests. Non-parametric tests: testing that does not assume a particular probability distribution, eg it does not assume a be
15,416
What is tied data in the context of a rank correlation coefficient?
It's simply two identical data values, such as observing 7 twice in the same data set. This comes up in the context of statistical methods that assume data has a continuous and so identical measurements are impossible (or technically, the probability identical values is zero). Practical complications arise when these methods are applied to data that are rounded or clipped so that identical measurements are not only possible but fairly common.
What is tied data in the context of a rank correlation coefficient?
It's simply two identical data values, such as observing 7 twice in the same data set. This comes up in the context of statistical methods that assume data has a continuous and so identical measuremen
What is tied data in the context of a rank correlation coefficient? It's simply two identical data values, such as observing 7 twice in the same data set. This comes up in the context of statistical methods that assume data has a continuous and so identical measurements are impossible (or technically, the probability identical values is zero). Practical complications arise when these methods are applied to data that are rounded or clipped so that identical measurements are not only possible but fairly common.
What is tied data in the context of a rank correlation coefficient? It's simply two identical data values, such as observing 7 twice in the same data set. This comes up in the context of statistical methods that assume data has a continuous and so identical measuremen
15,417
What is tied data in the context of a rank correlation coefficient?
The question is of fundamental importance: What is a tied observation/data/pair ? Altough often mentioned only in nonparametric methods, this notion is independent of nonparametric methods. It is mentioned in nonparametric methods because this situation will cause calculation complication in obtaining the statistics used in nonparametric methods, like Wilcoxon Signed Ranked statistics $T^+$. (So I don't think @Ming-Chih Kao's answer is proper by introducing nonparametric tests first. But since the title is 'What is tied data in the context of a rank correlation coefficient?', I will buy it.) To illustrate, I think the best way is to work with the simplest example of Wilcoxon Signed Ranked Test: Let us have a sample of paired data of size 10: Define the difference random variable $Z_{i}=X_{i}-Y_{i}$ $(X_{i},Y_{i})$: (1,-1) (1,2) (1,2) (1,-1) (2,1) (2,1) (2,3) (2,3) (3,2) (3,0) $Z_{i}$: 2 -1 -1 2 1 1 -1 -1 1 3 Take the absolute value of these $Z_{i}$'s in order to have a rank. $|Z_{i}|$: 2 1 1 2 1 1 1 1 1 3 Now the problem arise, with so many identical 1's and 2's, how can we make a ranking? We give them the term "tied" to show this case. And by the term "tied group"(which is an equivalent relation), we simply group those tied observations into groups by their values. In this example, we have 3 tied groups(Think why):$\{(1,-1) (1,-1)\},\{ (1,2) (1,2) (2,1) (2,1) (2,3) (2,3) (3,2) \},\{(3,0)\}$ Attention that the bracket does not mean a set but just a notation. Let us try the very easy way of doing this, we rank from left to right and give: $R_{i}$: 8 1 2 9 3 4 5 6 7 10 But here again we should ask why so other ranking is not suitable since there is no difference between those identical $|Z_{i}|$'s, like: $R_{i}$: 8 7 6 9 5 4 3 2 1 10 Therefore we may just take the mean of those identical $|Z_{i}|$'s and assign again: $R_{i}$: 8 7 6 9 5 4 3 2 1 10 The bold represents the first tied group consists of those $|Z_{i}|=1$ observations; the italic represents the second tied group consists of those $|Z_{i}|=2$ observations. We assign to each of the observation in the first group the rank$\frac{1+\cdots+7}{7}=4$;we assign to each of the observation in the second group the rank$\frac{8+9}{2}=8.5$. Therefore we have: $R_{i}$: 8.5 4 4 8.5 4 4 4 4 4 10 This modified the rankings and make each of the tied observation has the same influence in calculating the ranked statistics, thus in the rank test. What are the solutions to tied observation/data/pair ? (1)Assign the average rank. This is just what we did above. By assigning the same rank to the tied data in the same group, we make their influence in the ranked test just the same and therefore eliminate the possible inaccuracy caused by tied observations. (2)Assign the random rank. Just assign ranks randomly to each of the tied group element. The only restriction is that $MaxRank_{first group}<MinRank_{second group}$ since if $MaxRank_{first group}>MinRank_{second group}$, that breaks the ranking law; if $MaxRank_{first group}=MinRank_{second group}$, then we have to merge two tied groups into one. (3)Perturbation of data. This requires very careful consideration about the nature of the data. This works only if the data is not categorical(discrete). In the above example, we can just make a This will put different weights manually to each of the elements in the tied group. For a continuous distribution, for example, it makes little difference if you perturb it in $\epsilon$ manner. (@John D. Cook 's answer is a bit misleading in this way. A better way of saying this point is that when the distribution is continuous, $P{X=x}=0$. However, we shall observe ties since our measurement is of limited accuracy, i.e. any sample space in reality is actually finite.) (@quarkdown27 's answer is simple but correct in each word.)
What is tied data in the context of a rank correlation coefficient?
The question is of fundamental importance: What is a tied observation/data/pair ? Altough often mentioned only in nonparametric methods, this notion is independent of nonparametric methods. It is men
What is tied data in the context of a rank correlation coefficient? The question is of fundamental importance: What is a tied observation/data/pair ? Altough often mentioned only in nonparametric methods, this notion is independent of nonparametric methods. It is mentioned in nonparametric methods because this situation will cause calculation complication in obtaining the statistics used in nonparametric methods, like Wilcoxon Signed Ranked statistics $T^+$. (So I don't think @Ming-Chih Kao's answer is proper by introducing nonparametric tests first. But since the title is 'What is tied data in the context of a rank correlation coefficient?', I will buy it.) To illustrate, I think the best way is to work with the simplest example of Wilcoxon Signed Ranked Test: Let us have a sample of paired data of size 10: Define the difference random variable $Z_{i}=X_{i}-Y_{i}$ $(X_{i},Y_{i})$: (1,-1) (1,2) (1,2) (1,-1) (2,1) (2,1) (2,3) (2,3) (3,2) (3,0) $Z_{i}$: 2 -1 -1 2 1 1 -1 -1 1 3 Take the absolute value of these $Z_{i}$'s in order to have a rank. $|Z_{i}|$: 2 1 1 2 1 1 1 1 1 3 Now the problem arise, with so many identical 1's and 2's, how can we make a ranking? We give them the term "tied" to show this case. And by the term "tied group"(which is an equivalent relation), we simply group those tied observations into groups by their values. In this example, we have 3 tied groups(Think why):$\{(1,-1) (1,-1)\},\{ (1,2) (1,2) (2,1) (2,1) (2,3) (2,3) (3,2) \},\{(3,0)\}$ Attention that the bracket does not mean a set but just a notation. Let us try the very easy way of doing this, we rank from left to right and give: $R_{i}$: 8 1 2 9 3 4 5 6 7 10 But here again we should ask why so other ranking is not suitable since there is no difference between those identical $|Z_{i}|$'s, like: $R_{i}$: 8 7 6 9 5 4 3 2 1 10 Therefore we may just take the mean of those identical $|Z_{i}|$'s and assign again: $R_{i}$: 8 7 6 9 5 4 3 2 1 10 The bold represents the first tied group consists of those $|Z_{i}|=1$ observations; the italic represents the second tied group consists of those $|Z_{i}|=2$ observations. We assign to each of the observation in the first group the rank$\frac{1+\cdots+7}{7}=4$;we assign to each of the observation in the second group the rank$\frac{8+9}{2}=8.5$. Therefore we have: $R_{i}$: 8.5 4 4 8.5 4 4 4 4 4 10 This modified the rankings and make each of the tied observation has the same influence in calculating the ranked statistics, thus in the rank test. What are the solutions to tied observation/data/pair ? (1)Assign the average rank. This is just what we did above. By assigning the same rank to the tied data in the same group, we make their influence in the ranked test just the same and therefore eliminate the possible inaccuracy caused by tied observations. (2)Assign the random rank. Just assign ranks randomly to each of the tied group element. The only restriction is that $MaxRank_{first group}<MinRank_{second group}$ since if $MaxRank_{first group}>MinRank_{second group}$, that breaks the ranking law; if $MaxRank_{first group}=MinRank_{second group}$, then we have to merge two tied groups into one. (3)Perturbation of data. This requires very careful consideration about the nature of the data. This works only if the data is not categorical(discrete). In the above example, we can just make a This will put different weights manually to each of the elements in the tied group. For a continuous distribution, for example, it makes little difference if you perturb it in $\epsilon$ manner. (@John D. Cook 's answer is a bit misleading in this way. A better way of saying this point is that when the distribution is continuous, $P{X=x}=0$. However, we shall observe ties since our measurement is of limited accuracy, i.e. any sample space in reality is actually finite.) (@quarkdown27 's answer is simple but correct in each word.)
What is tied data in the context of a rank correlation coefficient? The question is of fundamental importance: What is a tied observation/data/pair ? Altough often mentioned only in nonparametric methods, this notion is independent of nonparametric methods. It is men
15,418
Can the empirical Hessian of an M-estimator be indefinite?
I think you're right. Let's distill your argument to its essence: $\widehat \theta_N$ minimizes the function $Q$ defined as $Q(\theta) = {1 \over N}\sum_{i=1}^N q(w_i,\theta).$ Let $H$ be the Hessian of $Q$, whence $H(\theta) = \frac{\partial^2 Q}{\partial \theta_i \partial \theta_j}$ by definition and this in turn, by linearity of differentiation, equals $\frac{1}{N}\sum_{i=1}^N H(w_i, \theta_n)$. Assuming $\widehat \theta_N$ lies in the interior of the domain of $Q$, then $H(\widehat \theta_N)$ must be positive semi-definite. This is merely a statement about the function $Q$: how it is defined is merely a distraction, except insofar as the assumed second order differentiability of $q$ with respect to its second argument ($\theta$) assures the second order differentiability of $Q$. Finding M-estimators can be tricky. Consider these data provided by @mpiktas: {1.168042, 0.3998378}, {1.807516, 0.5939584}, {1.384942, 3.6700205}, {1.327734, -3.3390724}, {1.602101, 4.1317608}, {1.604394, -1.9045958}, {1.124633, -3.0865249}, {1.294601, -1.8331763},{1.577610, 1.0865977}, { 1.630979, 0.7869717} The R procedure to find the M-estimator with $q((x,y),\theta)=(y-c_1x^{c_2})^4$ produced the solution $(c_1, c_2)$ = $(-114.91316, -32.54386)$. The value of the objective function (the average of the $q$'s) at this point equals 62.3542. Here is a plot of the fit: Here is a plot of the (log) objective function in a neighborhood of this fit: Something is fishy here: the parameters of the fit are extremely far from the parameters used to simulate the data (near $(0.3, 0.2)$) and we do not seem to be at a minimum: we are in an extremely shallow valley that is sloping towards larger values of both parameters: The negative determinant of the Hessian at this point confirms that this is not a local minimum! Nevertheless, when you look at the z-axis labels, you can see that this function is flat to five-digit precision within the entire region, because it equals a constant 4.1329 (the logarithm of 62.354). This probably led the R function minimizer (with its default tolerances) to conclude it was near a minimum. In fact, the solution is far from this point. To be sure of finding it, I employed the computationally expensive but highly effective "Principal Axis" method in Mathematica, using 50-digit precision (base 10) to avoid possible numerical problems. It finds a minimum near $(c_1, c_2) = (0.02506, 7.55973)$ where the objective function has the value 58.292655: about 6% smaller than the "minimum" found by R. This minimum occurs in an extremely flat-looking section, but I can make it look (just barely) like a true minimum, with elliptical contours, by exaggerating the $c_2$ direction in the plot: The contours range from 58.29266 in the middle all the way up to 58.29284 in the corners(!). Here's the 3D view (again of the log objective): Here the Hessian is positive-definite: its eigenvalues are 55062.02 and 0.430978. Thus this point is a local minimum (and likely a global minimum). Here is the fit it corresponds to: I think it's better than the other one. The parameter values are certainly more realistic and it's clear we're not going to be able to do much better with this family of curves. There are useful lessons we can draw from this example: Numerical optimization can be difficult, especially with nonlinear fitting and non-quadratic loss functions. Therefore: Double-check results in as many ways as possible, including: Graph the objective function whenever you can. When numerical results appear to violate mathematical theorems, be extremely suspicious. When statistical results are surprising--such as the surprising parameter values returned by the R code--be extra suspicious.
Can the empirical Hessian of an M-estimator be indefinite?
I think you're right. Let's distill your argument to its essence: $\widehat \theta_N$ minimizes the function $Q$ defined as $Q(\theta) = {1 \over N}\sum_{i=1}^N q(w_i,\theta).$ Let $H$ be the Hessia
Can the empirical Hessian of an M-estimator be indefinite? I think you're right. Let's distill your argument to its essence: $\widehat \theta_N$ minimizes the function $Q$ defined as $Q(\theta) = {1 \over N}\sum_{i=1}^N q(w_i,\theta).$ Let $H$ be the Hessian of $Q$, whence $H(\theta) = \frac{\partial^2 Q}{\partial \theta_i \partial \theta_j}$ by definition and this in turn, by linearity of differentiation, equals $\frac{1}{N}\sum_{i=1}^N H(w_i, \theta_n)$. Assuming $\widehat \theta_N$ lies in the interior of the domain of $Q$, then $H(\widehat \theta_N)$ must be positive semi-definite. This is merely a statement about the function $Q$: how it is defined is merely a distraction, except insofar as the assumed second order differentiability of $q$ with respect to its second argument ($\theta$) assures the second order differentiability of $Q$. Finding M-estimators can be tricky. Consider these data provided by @mpiktas: {1.168042, 0.3998378}, {1.807516, 0.5939584}, {1.384942, 3.6700205}, {1.327734, -3.3390724}, {1.602101, 4.1317608}, {1.604394, -1.9045958}, {1.124633, -3.0865249}, {1.294601, -1.8331763},{1.577610, 1.0865977}, { 1.630979, 0.7869717} The R procedure to find the M-estimator with $q((x,y),\theta)=(y-c_1x^{c_2})^4$ produced the solution $(c_1, c_2)$ = $(-114.91316, -32.54386)$. The value of the objective function (the average of the $q$'s) at this point equals 62.3542. Here is a plot of the fit: Here is a plot of the (log) objective function in a neighborhood of this fit: Something is fishy here: the parameters of the fit are extremely far from the parameters used to simulate the data (near $(0.3, 0.2)$) and we do not seem to be at a minimum: we are in an extremely shallow valley that is sloping towards larger values of both parameters: The negative determinant of the Hessian at this point confirms that this is not a local minimum! Nevertheless, when you look at the z-axis labels, you can see that this function is flat to five-digit precision within the entire region, because it equals a constant 4.1329 (the logarithm of 62.354). This probably led the R function minimizer (with its default tolerances) to conclude it was near a minimum. In fact, the solution is far from this point. To be sure of finding it, I employed the computationally expensive but highly effective "Principal Axis" method in Mathematica, using 50-digit precision (base 10) to avoid possible numerical problems. It finds a minimum near $(c_1, c_2) = (0.02506, 7.55973)$ where the objective function has the value 58.292655: about 6% smaller than the "minimum" found by R. This minimum occurs in an extremely flat-looking section, but I can make it look (just barely) like a true minimum, with elliptical contours, by exaggerating the $c_2$ direction in the plot: The contours range from 58.29266 in the middle all the way up to 58.29284 in the corners(!). Here's the 3D view (again of the log objective): Here the Hessian is positive-definite: its eigenvalues are 55062.02 and 0.430978. Thus this point is a local minimum (and likely a global minimum). Here is the fit it corresponds to: I think it's better than the other one. The parameter values are certainly more realistic and it's clear we're not going to be able to do much better with this family of curves. There are useful lessons we can draw from this example: Numerical optimization can be difficult, especially with nonlinear fitting and non-quadratic loss functions. Therefore: Double-check results in as many ways as possible, including: Graph the objective function whenever you can. When numerical results appear to violate mathematical theorems, be extremely suspicious. When statistical results are surprising--such as the surprising parameter values returned by the R code--be extra suspicious.
Can the empirical Hessian of an M-estimator be indefinite? I think you're right. Let's distill your argument to its essence: $\widehat \theta_N$ minimizes the function $Q$ defined as $Q(\theta) = {1 \over N}\sum_{i=1}^N q(w_i,\theta).$ Let $H$ be the Hessia
15,419
Can the empirical Hessian of an M-estimator be indefinite?
The quotation in full can be found here. The estimate $\hat{\theta}_N$ is the solution of minimization problem (page 344): \begin{align} \min_{\theta\in \Theta}N^{-1}\sum_{i=1}^Nq(w_i,\theta) \end{align} If the solution $\hat{\theta}_N$ is interior point of $\Theta$, objective function is twice differentiable and gradient of the objective function is zero, then Hessian of the objective function (which is $\hat{H}$) is positive semi-definite. Now what Wooldridge is saying that for given sample the empirical Hessian is not guaranteed to be positive definite or even positive semidefinite. This is true, since Wooldridge does not require that objective function $N^{-1}\sum_{i=1}^Nq(w_i,\theta)$ has nice properties, he requires that there exists a unique solution $\theta_0$ for $$\min_{\theta\in\Theta}Eq(w,\theta).$$ So for given sample objective function $N^{-1}\sum_{i=1}^Nq(w_i,\theta)$ may be minimized on the boundary point of $\Theta$ in which Hessian of objective function needs not to be positive definite. Further in his book Wooldridge gives an examples of estimates of Hessian which are guaranteed to be numerically positive definite. In practice non-positive definiteness of Hessian should indicate that solution is either on the boundary point or the algorithm failed to find the solution. Which usually is a further indication that the model fitted may be inappropriate for a given data. Here is the numerical example. I generate non-linear least squares problem: $$y_i=c_1x_i^{c_2}+\varepsilon_i$$ I take $X$ uniformly distributed in interval $[1,2]$ and $\varepsilon$ normal with zero mean and variance $\sigma^2$. I generated a sample of size 10, in R 2.11.1 using set.seed(3). Here is the link to the values of $x_i$ and $y_i$. I chose the objective function square of usual non-linear least squares objective function: $$q(w,\theta)=(y-c_1x_i^{c_2})^4$$ Here is the code in R for optimising function, its gradient and hessian. ##First set-up the epxressions for optimising function, its gradient and hessian. ##I use symbolic derivation of R to guard against human error mt <- expression((y-c1*x^c2)^4) gradmt <- c(D(mt,"c1"),D(mt,"c2")) hessmt <- lapply(gradmt,function(l)c(D(l,"c1"),D(l,"c2"))) ##Evaluate the expressions on data to get the empirical values. ##Note there was a bug in previous version of the answer res should not be squared. optf <- function(p) { res <- eval(mt,list(y=y,x=x,c1=p[1],c2=p[2])) mean(res) } gf <- function(p) { evl <- list(y=y,x=x,c1=p[1],c2=p[2]) res <- sapply(gradmt,function(l)eval(l,evl)) apply(res,2,mean) } hesf <- function(p) { evl <- list(y=y,x=x,c1=p[1],c2=p[2]) res1 <- lapply(hessmt,function(l)sapply(l,function(ll)eval(ll,evl))) res <- sapply(res1,function(l)apply(l,2,mean)) res } First test that gradient and hessian works as advertised. set.seed(3) x <- runif(10,1,2) y <- 0.3*x^0.2 > optf(c(0.3,0.2)) [1] 0 > gf(c(0.3,0.2)) [1] 0 0 > hesf(c(0.3,0.2)) [,1] [,2] [1,] 0 0 [2,] 0 0 > eigen(hesf(c(0.3,0.2)))$values [1] 0 0 The hessian is zero, so it is positive semi-definite. Now for the values of $x$ and $y$ given in the link we get > df <- read.csv("badhessian.csv") > df x y 1 1.168042 0.3998378 2 1.807516 0.5939584 3 1.384942 3.6700205 4 1.327734 -3.3390724 5 1.602101 4.1317608 6 1.604394 -1.9045958 7 1.124633 -3.0865249 8 1.294601 -1.8331763 9 1.577610 1.0865977 10 1.630979 0.7869717 > x <- df$x > y <- df$y > opt <- optim(c(1,1),optf,gr=gf,method="BFGS") > opt$par [1] -114.91316 -32.54386 > gf(opt$par) [1] -0.0005795979 -0.0002399711 > hesf(opt$par) [,1] [,2] [1,] 0.0002514806 -0.003670634 [2,] -0.0036706345 0.050998404 > eigen(hesf(opt$par))$values [1] 5.126253e-02 -1.264959e-05 Gradient is zero, but the hessian is non positive. Note: This is my third attempt to give an answer. I hope I finally managed to give precise mathematical statements, which eluded me in the previous versions.
Can the empirical Hessian of an M-estimator be indefinite?
The quotation in full can be found here. The estimate $\hat{\theta}_N$ is the solution of minimization problem (page 344): \begin{align} \min_{\theta\in \Theta}N^{-1}\sum_{i=1}^Nq(w_i,\theta) \end{ali
Can the empirical Hessian of an M-estimator be indefinite? The quotation in full can be found here. The estimate $\hat{\theta}_N$ is the solution of minimization problem (page 344): \begin{align} \min_{\theta\in \Theta}N^{-1}\sum_{i=1}^Nq(w_i,\theta) \end{align} If the solution $\hat{\theta}_N$ is interior point of $\Theta$, objective function is twice differentiable and gradient of the objective function is zero, then Hessian of the objective function (which is $\hat{H}$) is positive semi-definite. Now what Wooldridge is saying that for given sample the empirical Hessian is not guaranteed to be positive definite or even positive semidefinite. This is true, since Wooldridge does not require that objective function $N^{-1}\sum_{i=1}^Nq(w_i,\theta)$ has nice properties, he requires that there exists a unique solution $\theta_0$ for $$\min_{\theta\in\Theta}Eq(w,\theta).$$ So for given sample objective function $N^{-1}\sum_{i=1}^Nq(w_i,\theta)$ may be minimized on the boundary point of $\Theta$ in which Hessian of objective function needs not to be positive definite. Further in his book Wooldridge gives an examples of estimates of Hessian which are guaranteed to be numerically positive definite. In practice non-positive definiteness of Hessian should indicate that solution is either on the boundary point or the algorithm failed to find the solution. Which usually is a further indication that the model fitted may be inappropriate for a given data. Here is the numerical example. I generate non-linear least squares problem: $$y_i=c_1x_i^{c_2}+\varepsilon_i$$ I take $X$ uniformly distributed in interval $[1,2]$ and $\varepsilon$ normal with zero mean and variance $\sigma^2$. I generated a sample of size 10, in R 2.11.1 using set.seed(3). Here is the link to the values of $x_i$ and $y_i$. I chose the objective function square of usual non-linear least squares objective function: $$q(w,\theta)=(y-c_1x_i^{c_2})^4$$ Here is the code in R for optimising function, its gradient and hessian. ##First set-up the epxressions for optimising function, its gradient and hessian. ##I use symbolic derivation of R to guard against human error mt <- expression((y-c1*x^c2)^4) gradmt <- c(D(mt,"c1"),D(mt,"c2")) hessmt <- lapply(gradmt,function(l)c(D(l,"c1"),D(l,"c2"))) ##Evaluate the expressions on data to get the empirical values. ##Note there was a bug in previous version of the answer res should not be squared. optf <- function(p) { res <- eval(mt,list(y=y,x=x,c1=p[1],c2=p[2])) mean(res) } gf <- function(p) { evl <- list(y=y,x=x,c1=p[1],c2=p[2]) res <- sapply(gradmt,function(l)eval(l,evl)) apply(res,2,mean) } hesf <- function(p) { evl <- list(y=y,x=x,c1=p[1],c2=p[2]) res1 <- lapply(hessmt,function(l)sapply(l,function(ll)eval(ll,evl))) res <- sapply(res1,function(l)apply(l,2,mean)) res } First test that gradient and hessian works as advertised. set.seed(3) x <- runif(10,1,2) y <- 0.3*x^0.2 > optf(c(0.3,0.2)) [1] 0 > gf(c(0.3,0.2)) [1] 0 0 > hesf(c(0.3,0.2)) [,1] [,2] [1,] 0 0 [2,] 0 0 > eigen(hesf(c(0.3,0.2)))$values [1] 0 0 The hessian is zero, so it is positive semi-definite. Now for the values of $x$ and $y$ given in the link we get > df <- read.csv("badhessian.csv") > df x y 1 1.168042 0.3998378 2 1.807516 0.5939584 3 1.384942 3.6700205 4 1.327734 -3.3390724 5 1.602101 4.1317608 6 1.604394 -1.9045958 7 1.124633 -3.0865249 8 1.294601 -1.8331763 9 1.577610 1.0865977 10 1.630979 0.7869717 > x <- df$x > y <- df$y > opt <- optim(c(1,1),optf,gr=gf,method="BFGS") > opt$par [1] -114.91316 -32.54386 > gf(opt$par) [1] -0.0005795979 -0.0002399711 > hesf(opt$par) [,1] [,2] [1,] 0.0002514806 -0.003670634 [2,] -0.0036706345 0.050998404 > eigen(hesf(opt$par))$values [1] 5.126253e-02 -1.264959e-05 Gradient is zero, but the hessian is non positive. Note: This is my third attempt to give an answer. I hope I finally managed to give precise mathematical statements, which eluded me in the previous versions.
Can the empirical Hessian of an M-estimator be indefinite? The quotation in full can be found here. The estimate $\hat{\theta}_N$ is the solution of minimization problem (page 344): \begin{align} \min_{\theta\in \Theta}N^{-1}\sum_{i=1}^Nq(w_i,\theta) \end{ali
15,420
Can the empirical Hessian of an M-estimator be indefinite?
The hessian is indefinite at a saddle point. It’s possible that this may be the only stationary point in the interior of the parameter space. Update: Let me elaborate. First, let’s assume that the empirical Hessian exists everywhere. If $\hat{\theta}_n$ is a local (or even global) minimum of $\sum_i q(w_i, \cdot)$ and in the interior of the parameter space (assumed to be an open set) then necessarily the Hessian $(1/N) \sum_i H(w_i, \hat{\theta}_n)$ is positive semidefinite. If not, then $\hat{\theta}_n$ is not a local minimum. This follows from second order optimality conditions — locally $\sum_i q(w_i, \cdot)$ must not decrease in any directions away from $\hat{\theta}_n$. One source of the confusion might the "working" definition of an M-estimator. Although in principle an M-estimator should be defined as $\arg\min_\theta \sum_i q(w_i, \theta)$, it might also be defined as a solution to the equation $$0 = \sum_i \dot{q}(w_i, \theta)\,,$$ where $\dot{q}$ is the gradient of $q(w, \theta)$ with respect to $\theta$. This is sometimes called the $\Psi$-type. In the latter case a solution of that equation need not be a local minimum. It can be a saddle point and in this case the Hessian would be indefinite. Practically speaking, even a positive definite Hessian that is nearly singular or ill-conditioned would suggest that the estimator is poor and you have more to worry about than estimating its variance.
Can the empirical Hessian of an M-estimator be indefinite?
The hessian is indefinite at a saddle point. It’s possible that this may be the only stationary point in the interior of the parameter space. Update: Let me elaborate. First, let’s assume that the e
Can the empirical Hessian of an M-estimator be indefinite? The hessian is indefinite at a saddle point. It’s possible that this may be the only stationary point in the interior of the parameter space. Update: Let me elaborate. First, let’s assume that the empirical Hessian exists everywhere. If $\hat{\theta}_n$ is a local (or even global) minimum of $\sum_i q(w_i, \cdot)$ and in the interior of the parameter space (assumed to be an open set) then necessarily the Hessian $(1/N) \sum_i H(w_i, \hat{\theta}_n)$ is positive semidefinite. If not, then $\hat{\theta}_n$ is not a local minimum. This follows from second order optimality conditions — locally $\sum_i q(w_i, \cdot)$ must not decrease in any directions away from $\hat{\theta}_n$. One source of the confusion might the "working" definition of an M-estimator. Although in principle an M-estimator should be defined as $\arg\min_\theta \sum_i q(w_i, \theta)$, it might also be defined as a solution to the equation $$0 = \sum_i \dot{q}(w_i, \theta)\,,$$ where $\dot{q}$ is the gradient of $q(w, \theta)$ with respect to $\theta$. This is sometimes called the $\Psi$-type. In the latter case a solution of that equation need not be a local minimum. It can be a saddle point and in this case the Hessian would be indefinite. Practically speaking, even a positive definite Hessian that is nearly singular or ill-conditioned would suggest that the estimator is poor and you have more to worry about than estimating its variance.
Can the empirical Hessian of an M-estimator be indefinite? The hessian is indefinite at a saddle point. It’s possible that this may be the only stationary point in the interior of the parameter space. Update: Let me elaborate. First, let’s assume that the e
15,421
Can the empirical Hessian of an M-estimator be indefinite?
There's been a lot of beating around the bush in this thread regarding whether the Hessian has to be positive (semi)definite at a local minimum. So I will make a clear statement on that. Presuming the objective function and all constraint functions are twice continuously differentiable, then at any local minimum, the Hessian of the Lagrangian projected into the null space of the Jacobian of active constraints must be positive semidefinite. I.e., if $Z$ is a basis for the null space of the Jacobian of active constraints, then $Z^T*(\text{Hessian of Lagrangian})*Z$ must be positive semidefinite. This must be positive definite for a strict local minimum. So the Hessian of the objective function in a constrained problem having active constraint(s) need not be positive semidefinite if there are active constraints. Notes: 1) Active constraints consist of all equality constraints, plus inequality constraints which are satisfied with equality. 2) See the definition of the Lagrangian at https://www.encyclopediaofmath.org/index.php/Karush-Kuhn-Tucker_conditions . 3) If all constraints are linear, then the Hessian of the Lagrangian = Hessian of the objective function because the 2nd derivatives of linear functions are zero. But you still need to do the projection jazz if any of these constraints are active. Note that lower or upper bound constraints are particular cases of linear inequality constraints. If the only constraints which are active are bound constraints, the projection of the Hessian into the null space of the Jacobian of active constraints amounts to eliminating the rows and columns of the Hessian corresponding to those components on their bounds. 4) Because Lagrange multipliers of inactive constraints are zero, if there are no active constraints, the Hessian of the Lagrangian = the Hessian of the objective function, and the Identity matrix is a basis for the null space of the Jacobian of active constraints, which results in the simplification of the criterion being the familiar condition that the Hessian of the objective function be positive semidefinite at a local minimum (positive definite if a strict local minimum).
Can the empirical Hessian of an M-estimator be indefinite?
There's been a lot of beating around the bush in this thread regarding whether the Hessian has to be positive (semi)definite at a local minimum. So I will make a clear statement on that. Presuming th
Can the empirical Hessian of an M-estimator be indefinite? There's been a lot of beating around the bush in this thread regarding whether the Hessian has to be positive (semi)definite at a local minimum. So I will make a clear statement on that. Presuming the objective function and all constraint functions are twice continuously differentiable, then at any local minimum, the Hessian of the Lagrangian projected into the null space of the Jacobian of active constraints must be positive semidefinite. I.e., if $Z$ is a basis for the null space of the Jacobian of active constraints, then $Z^T*(\text{Hessian of Lagrangian})*Z$ must be positive semidefinite. This must be positive definite for a strict local minimum. So the Hessian of the objective function in a constrained problem having active constraint(s) need not be positive semidefinite if there are active constraints. Notes: 1) Active constraints consist of all equality constraints, plus inequality constraints which are satisfied with equality. 2) See the definition of the Lagrangian at https://www.encyclopediaofmath.org/index.php/Karush-Kuhn-Tucker_conditions . 3) If all constraints are linear, then the Hessian of the Lagrangian = Hessian of the objective function because the 2nd derivatives of linear functions are zero. But you still need to do the projection jazz if any of these constraints are active. Note that lower or upper bound constraints are particular cases of linear inequality constraints. If the only constraints which are active are bound constraints, the projection of the Hessian into the null space of the Jacobian of active constraints amounts to eliminating the rows and columns of the Hessian corresponding to those components on their bounds. 4) Because Lagrange multipliers of inactive constraints are zero, if there are no active constraints, the Hessian of the Lagrangian = the Hessian of the objective function, and the Identity matrix is a basis for the null space of the Jacobian of active constraints, which results in the simplification of the criterion being the familiar condition that the Hessian of the objective function be positive semidefinite at a local minimum (positive definite if a strict local minimum).
Can the empirical Hessian of an M-estimator be indefinite? There's been a lot of beating around the bush in this thread regarding whether the Hessian has to be positive (semi)definite at a local minimum. So I will make a clear statement on that. Presuming th
15,422
Can the empirical Hessian of an M-estimator be indefinite?
The positive answers above are true but they leave out the crucial identification assumption - if your model is not identified (or if it is only set identified) you might indeed, as Wooldridge correctly indicated, find yourself with a non-PSD empirical Hessian. Just run some non-toy psychometric / econometric model and see for yourself.
Can the empirical Hessian of an M-estimator be indefinite?
The positive answers above are true but they leave out the crucial identification assumption - if your model is not identified (or if it is only set identified) you might indeed, as Wooldridge correct
Can the empirical Hessian of an M-estimator be indefinite? The positive answers above are true but they leave out the crucial identification assumption - if your model is not identified (or if it is only set identified) you might indeed, as Wooldridge correctly indicated, find yourself with a non-PSD empirical Hessian. Just run some non-toy psychometric / econometric model and see for yourself.
Can the empirical Hessian of an M-estimator be indefinite? The positive answers above are true but they leave out the crucial identification assumption - if your model is not identified (or if it is only set identified) you might indeed, as Wooldridge correct
15,423
Are over-dispersion tests in GLMs actually *useful*?
In principle, I actually agree that 99% of the time, it's better to just use the more flexible model. With that said, here are two and a half arguments for why you might not. (1) Less flexible means more efficient estimates. Given that variance parameters tend to be less stable than mean parameters, your assumption of fixed mean-variance relation may stabilize standard errors more. (2) Model checking. I've worked with physicists who believe that various measurements can be described by Poisson distributions due to theoretical physics. If we reject the hypothesis that mean = variance, we have evidence against the Poisson distribution hypothesis. As pointed out in a comment by @GordonSmyth, if you have reason to believe that a given measurement should follow a Poisson distribution, if you have evidence of over dispersion, you have evidence that you are missing important factors. (2.5) Proper distribution. While the negative binomial regression comes from a valid statistical distribution, it's my understanding that the Quasi-Poisson does not. That means you can't really simulate count data if you believe $Var[y] = \alpha E[y]$ for $\alpha \neq 1$. That might be annoying for some use cases. Likewise, you can't use probabilities to test for outliers, etc.
Are over-dispersion tests in GLMs actually *useful*?
In principle, I actually agree that 99% of the time, it's better to just use the more flexible model. With that said, here are two and a half arguments for why you might not. (1) Less flexible means
Are over-dispersion tests in GLMs actually *useful*? In principle, I actually agree that 99% of the time, it's better to just use the more flexible model. With that said, here are two and a half arguments for why you might not. (1) Less flexible means more efficient estimates. Given that variance parameters tend to be less stable than mean parameters, your assumption of fixed mean-variance relation may stabilize standard errors more. (2) Model checking. I've worked with physicists who believe that various measurements can be described by Poisson distributions due to theoretical physics. If we reject the hypothesis that mean = variance, we have evidence against the Poisson distribution hypothesis. As pointed out in a comment by @GordonSmyth, if you have reason to believe that a given measurement should follow a Poisson distribution, if you have evidence of over dispersion, you have evidence that you are missing important factors. (2.5) Proper distribution. While the negative binomial regression comes from a valid statistical distribution, it's my understanding that the Quasi-Poisson does not. That means you can't really simulate count data if you believe $Var[y] = \alpha E[y]$ for $\alpha \neq 1$. That might be annoying for some use cases. Likewise, you can't use probabilities to test for outliers, etc.
Are over-dispersion tests in GLMs actually *useful*? In principle, I actually agree that 99% of the time, it's better to just use the more flexible model. With that said, here are two and a half arguments for why you might not. (1) Less flexible means
15,424
Are over-dispersion tests in GLMs actually *useful*?
Although this is my own question, I'm also going to post my own two-cents as an answer, so that we add to the number of perspectives on this question. The issue here is whether or not it is sensible to initially fit a one-parameter distribution to data. When you use a one-parameter distribution (such as the Poisson GLM, or a binomial GLM with fixed trial parameter), the variance is not a free parameter, and is instead constrained to be some function of the mean. This means that it is ill-advised to fit a one-parameter distribution to data in any situation where you are not absolutely sure that the variance follows the structure of that distribution. Fitting one-parameter distributions to data is almost always a bad idea: Data is often messier than proposed models indicate, and even when there are theoretical reasons to believe that a particular one-parameter model may obtain, it is often the case that the data actually come from a mixture of that one-parameter distribution, with a range of parameter values. This is often equivalent to a broader model, such as a two-parameter distribution that allows greater freedom for the variance. As discussed below, this is true for the Poisson GLM in the case of count data. As stated in the question, in most applications of statistics, it is standard practice to use distributional forms that at least allow the first two moments to vary freely. This ensures that the fitted model allows the data to dictate the inferred mean and variance, rather than having these artificially constrained by the model. Having this second parameter only loses one degree-of-freedom in the model, which is a tiny loss compared to the benefit of allowing the variance to be estimated from the data. One can of course extend this reasoning and add a third parameter to allow fitting of skewness, a fourth to allow fitting of kurtosis, etc. The reason that these higher-order moments are not usually as important is that asymptotic theorems for estimators usually show that they converge to a normal distribution (regardless of the higher-order moments of the underlying data) and in this case estimates of the mean and variance are sufficient to get good estimates of the asymptotic distribution of the parameter estimators. With some extremely minor exceptions, a Poisson GLM is a bad model: In my experience, fitting a Poisson distribution to count data is almost always a bad idea. For count data it is extremely common for the variance in the data to be 'over-dispersed' relative to the Poisson distribution. Even in situations where theory points to a Poisson distribution, often the best model is a mixture of Poisson distributions, where the variance becomes a free parameter. Indeed, in the case of count data the negative-binomial distribution is a Poisson mixture with a gamma distribution for the rate parameter, so even when there are theoretical reasons to think that the counts arrive according to the process of a Poisson distribution, it is often the case that there is 'over-dispersion' and the negative-binomial distribution fits much better. The practice of fitting a Poisson GLM to count data and then doing a statistical test to check for 'over-dispersion' is an anachronism, and it is hardly ever a good practice. In other forms of statistical analysis, we do not start with a two-parameter distribution, arbitrarily choose a variance restriction, and then test for this restriction to try to eliminate a parameter from the distribution. By doing things this way, we actually create an awkward hybrid procedure, consisting of an initial hypothesis test used for model selection, and then the actual model (either Poisson, or a broader distribution). It has been shown in many contexts that this kind of practice of creating hybrid models from an initial model selection test leads to bad overall models. An analogous situation, where a similar hybrid method has been used, is in T-tests of mean difference. It used to be the case that statistics courses would recommend first using Levene's test (or even just some much crappier "rules of thumb") to check for equality of variances between two populations, and then if the data "passed" this test you would use the Student T-test that assumes equal variance, and if the data "failed" the test then you would instead use Welch's T-test. This is actually a really bad procedure (see e.g., here and here). It is much better just to use the latter test, which makes no assumption on the variance, rather than creating an awkward compound test that jams together a preliminary hypothesis test and then uses this to choose the model. For count data, you will generally get good initial results by fitting a two-parameter model such as a negative-binomial or quasi-Poisson model. (Note that the latter is not a real distribution, but it still gives a reasonable two-parameter model.) If any further generalisation is needed at all, it is usually the addition of zero-inflation, where there are an excessive number of zeroes in the data. Restricting to a Poisson GLM is an artificial and senseless model choice, and this is not made much better by testing for over-dispersion. Okay, now here are the minor exceptions: The only real exceptions to the above are two situations: (1) You have extremely strong a priori theoretical reasons for believing that the assumptions for the one parameter distribution are satisfied, and part of the analysis is to test this theoretical model against the data; or (2) For some other (strange) reason, the purpose of your analysis is to conduct a hypothesis test on the variance of the data, and so you actually want to restrict this variance to this hypothesised restriction, and then test this hypothesis. These situations are very rare. They tend to arise only when there is strong a priori theoretical knowledge about the data-generating mechanism, and the purpose of the analysis is to test this underlying theory. This may be the case in an extremely limited range of applications where data is generated under tightly controlled conditions (e.g., in physics).
Are over-dispersion tests in GLMs actually *useful*?
Although this is my own question, I'm also going to post my own two-cents as an answer, so that we add to the number of perspectives on this question. The issue here is whether or not it is sensible
Are over-dispersion tests in GLMs actually *useful*? Although this is my own question, I'm also going to post my own two-cents as an answer, so that we add to the number of perspectives on this question. The issue here is whether or not it is sensible to initially fit a one-parameter distribution to data. When you use a one-parameter distribution (such as the Poisson GLM, or a binomial GLM with fixed trial parameter), the variance is not a free parameter, and is instead constrained to be some function of the mean. This means that it is ill-advised to fit a one-parameter distribution to data in any situation where you are not absolutely sure that the variance follows the structure of that distribution. Fitting one-parameter distributions to data is almost always a bad idea: Data is often messier than proposed models indicate, and even when there are theoretical reasons to believe that a particular one-parameter model may obtain, it is often the case that the data actually come from a mixture of that one-parameter distribution, with a range of parameter values. This is often equivalent to a broader model, such as a two-parameter distribution that allows greater freedom for the variance. As discussed below, this is true for the Poisson GLM in the case of count data. As stated in the question, in most applications of statistics, it is standard practice to use distributional forms that at least allow the first two moments to vary freely. This ensures that the fitted model allows the data to dictate the inferred mean and variance, rather than having these artificially constrained by the model. Having this second parameter only loses one degree-of-freedom in the model, which is a tiny loss compared to the benefit of allowing the variance to be estimated from the data. One can of course extend this reasoning and add a third parameter to allow fitting of skewness, a fourth to allow fitting of kurtosis, etc. The reason that these higher-order moments are not usually as important is that asymptotic theorems for estimators usually show that they converge to a normal distribution (regardless of the higher-order moments of the underlying data) and in this case estimates of the mean and variance are sufficient to get good estimates of the asymptotic distribution of the parameter estimators. With some extremely minor exceptions, a Poisson GLM is a bad model: In my experience, fitting a Poisson distribution to count data is almost always a bad idea. For count data it is extremely common for the variance in the data to be 'over-dispersed' relative to the Poisson distribution. Even in situations where theory points to a Poisson distribution, often the best model is a mixture of Poisson distributions, where the variance becomes a free parameter. Indeed, in the case of count data the negative-binomial distribution is a Poisson mixture with a gamma distribution for the rate parameter, so even when there are theoretical reasons to think that the counts arrive according to the process of a Poisson distribution, it is often the case that there is 'over-dispersion' and the negative-binomial distribution fits much better. The practice of fitting a Poisson GLM to count data and then doing a statistical test to check for 'over-dispersion' is an anachronism, and it is hardly ever a good practice. In other forms of statistical analysis, we do not start with a two-parameter distribution, arbitrarily choose a variance restriction, and then test for this restriction to try to eliminate a parameter from the distribution. By doing things this way, we actually create an awkward hybrid procedure, consisting of an initial hypothesis test used for model selection, and then the actual model (either Poisson, or a broader distribution). It has been shown in many contexts that this kind of practice of creating hybrid models from an initial model selection test leads to bad overall models. An analogous situation, where a similar hybrid method has been used, is in T-tests of mean difference. It used to be the case that statistics courses would recommend first using Levene's test (or even just some much crappier "rules of thumb") to check for equality of variances between two populations, and then if the data "passed" this test you would use the Student T-test that assumes equal variance, and if the data "failed" the test then you would instead use Welch's T-test. This is actually a really bad procedure (see e.g., here and here). It is much better just to use the latter test, which makes no assumption on the variance, rather than creating an awkward compound test that jams together a preliminary hypothesis test and then uses this to choose the model. For count data, you will generally get good initial results by fitting a two-parameter model such as a negative-binomial or quasi-Poisson model. (Note that the latter is not a real distribution, but it still gives a reasonable two-parameter model.) If any further generalisation is needed at all, it is usually the addition of zero-inflation, where there are an excessive number of zeroes in the data. Restricting to a Poisson GLM is an artificial and senseless model choice, and this is not made much better by testing for over-dispersion. Okay, now here are the minor exceptions: The only real exceptions to the above are two situations: (1) You have extremely strong a priori theoretical reasons for believing that the assumptions for the one parameter distribution are satisfied, and part of the analysis is to test this theoretical model against the data; or (2) For some other (strange) reason, the purpose of your analysis is to conduct a hypothesis test on the variance of the data, and so you actually want to restrict this variance to this hypothesised restriction, and then test this hypothesis. These situations are very rare. They tend to arise only when there is strong a priori theoretical knowledge about the data-generating mechanism, and the purpose of the analysis is to test this underlying theory. This may be the case in an extremely limited range of applications where data is generated under tightly controlled conditions (e.g., in physics).
Are over-dispersion tests in GLMs actually *useful*? Although this is my own question, I'm also going to post my own two-cents as an answer, so that we add to the number of perspectives on this question. The issue here is whether or not it is sensible
15,425
Summary of a GAM fit
The way the output of this approach to fitting GAMs is structured is to group the linear parts of the smoothers in with the other parametric terms. Notice Private has an entry in the first table but it's entry is empty in the second. This is because Private is a strictly parametric term; it is a factor variable and hence is associated with an estimated parameter which represents the effect of Private. The reason the smooth terms are separated into two types of effect is that this output allows you to decide if a smooth term has a nonlinear effect: look at the nonparametric table and assess significance. If significance, leave as a smooth nonlinear effect. If insignificant, consider the linear effect (2. below) a linear effect: look at the parametric table and assess the significance of the linear effect. If significant you can turn the term into a smooth s(x) -> x in the formula describing the model. If insignificant you might consider dropping the term from the model entirely (but do be careful with this --- that amounts to a strong statement that the true effect is == 0). Parametric table Entries here are like what you'd get if you fitted this a linear model and computed the ANOVA table, except no estimates for any associated model coefficients are shown. Instead of estimated coefficients and standard errors, and associated t or Wald tests, the amount of variance explained (in terms of sums of squares) is shown alongside F tests. As with other regression models fitted with multiple covariates (or functions of covariates), the entries in the table are conditional upon the other terms/functions in the model. Nonparametric table The nonparametric effects relate to the nonlinear parts of the smoothers fitted. Non of these nonlinear effects is significant except for the nonlinear effect of Expend. There is some evidence of a nonlinear effect of Room.Board. Each of this is associated with some number of non-parametric degrees of freedom (Npar Df) and they explain an amount of variation in the response, the amount of which is assessed via a F test (by default, see argument test). These tests in the nonparametric section can be interpreted as test of the null hypothesis of a linear relationship instead of a nonlinear relationship. The way you can interpret this is that only Expend warrants being treated as a smooth nonlinear effect. The other smooths could be converted to linear parametric terms. You may want to check that the smooth of Room.Board continues to have an non-significant non-parametric effect once you convert the other smooths to linear, parametric terms; it may be that the effect of Room.Board is slightly nonlinear but this is being affected by the presence of the other smooth terms in the model. However, a lot of this might depend on the fact that many smooths were only allowed to use 2 degrees of freedom; why 2? Automatic smoothness selection Newer approaches to fitting GAMs would choose the degree of smoothness for you via automatic smoothness selection approaches such as the penalised spline approach of Simon Wood as implemented in recommended package mgcv: data(College, package = 'ISLR') library('mgcv') set.seed(1) nr <- nrow(College) train <- with(College, sample(nr, ceiling(nr/2))) College.train <- College[train, ] m <- mgcv::gam(Outstate ~ Private + s(Room.Board) + s(PhD) + s(perc.alumni) + s(Expend) + s(Grad.Rate), data = College.train, method = 'REML') The model summary is more concise and directly considers the smooth function as a whole rather than as a linear (parametric) and nonlinear (nonparametric) contributions: > summary(m) Family: gaussian Link function: identity Formula: Outstate ~ Private + s(Room.Board) + s(PhD) + s(perc.alumni) + s(Expend) + s(Grad.Rate) Parametric coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 8544.1 217.2 39.330 <2e-16 *** PrivateYes 2499.2 274.2 9.115 <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 s(Room.Board) 2.190 2.776 20.233 3.91e-11 *** s(PhD) 2.433 3.116 3.037 0.029249 * s(perc.alumni) 1.656 2.072 15.888 1.84e-07 *** s(Expend) 4.528 5.592 19.614 < 2e-16 *** s(Grad.Rate) 2.125 2.710 6.553 0.000452 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 R-sq.(adj) = 0.794 Deviance explained = 80.2% -REML = 3436.4 Scale est. = 3.3143e+06 n = 389 Now the output gathers the smooth terms and the parametric terms into separate tables, with the latter getting a more familiar output similar to that of a linear model. The smooth terms entire effect is shown in the lower table. These aren't the same tests as for the gam::gam model you show; they are tests against the null hypothesis that the smooth effect is a flat, horizontal line, a null effect or showing zero effect. The alternative is that the true nonlinear effect is different from zero. Notice that the EDFs are all larger than 2 except for s(perc.alumni), suggesting that the gam::gam model may be a little restrictive. The fitted smooths for comparison are given by plot(m, pages = 1, scheme = 1, all.terms = TRUE, seWithMean = TRUE) which produces The automatic smoothness selection can also be co-opted to shrinking terms out of the model entirely: Having done that, we see that the model fit has not really changed > summary(m2) Family: gaussian Link function: identity Formula: Outstate ~ Private + s(Room.Board) + s(PhD) + s(perc.alumni) + s(Expend) + s(Grad.Rate) Parametric coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 8539.4 214.8 39.755 <2e-16 *** PrivateYes 2505.7 270.4 9.266 <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 s(Room.Board) 2.260 9 6.338 3.95e-14 *** s(PhD) 1.809 9 0.913 0.00611 ** s(perc.alumni) 1.544 9 3.542 8.21e-09 *** s(Expend) 4.234 9 13.517 < 2e-16 *** s(Grad.Rate) 2.114 9 2.209 1.01e-05 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 R-sq.(adj) = 0.794 Deviance explained = 80.1% -REML = 3475.3 Scale est. = 3.3145e+06 n = 389 All of the smooths seem to suggest slightly nonlinear effects even after we've shrunk the linear and nonlinear parts of the splines. Personally, I find the output from mgcv easier to interpret, and because it has been shown that the automatic smoothness selection methods will tend to fit a linear effect if that is supported by the data.
Summary of a GAM fit
The way the output of this approach to fitting GAMs is structured is to group the linear parts of the smoothers in with the other parametric terms. Notice Private has an entry in the first table but i
Summary of a GAM fit The way the output of this approach to fitting GAMs is structured is to group the linear parts of the smoothers in with the other parametric terms. Notice Private has an entry in the first table but it's entry is empty in the second. This is because Private is a strictly parametric term; it is a factor variable and hence is associated with an estimated parameter which represents the effect of Private. The reason the smooth terms are separated into two types of effect is that this output allows you to decide if a smooth term has a nonlinear effect: look at the nonparametric table and assess significance. If significance, leave as a smooth nonlinear effect. If insignificant, consider the linear effect (2. below) a linear effect: look at the parametric table and assess the significance of the linear effect. If significant you can turn the term into a smooth s(x) -> x in the formula describing the model. If insignificant you might consider dropping the term from the model entirely (but do be careful with this --- that amounts to a strong statement that the true effect is == 0). Parametric table Entries here are like what you'd get if you fitted this a linear model and computed the ANOVA table, except no estimates for any associated model coefficients are shown. Instead of estimated coefficients and standard errors, and associated t or Wald tests, the amount of variance explained (in terms of sums of squares) is shown alongside F tests. As with other regression models fitted with multiple covariates (or functions of covariates), the entries in the table are conditional upon the other terms/functions in the model. Nonparametric table The nonparametric effects relate to the nonlinear parts of the smoothers fitted. Non of these nonlinear effects is significant except for the nonlinear effect of Expend. There is some evidence of a nonlinear effect of Room.Board. Each of this is associated with some number of non-parametric degrees of freedom (Npar Df) and they explain an amount of variation in the response, the amount of which is assessed via a F test (by default, see argument test). These tests in the nonparametric section can be interpreted as test of the null hypothesis of a linear relationship instead of a nonlinear relationship. The way you can interpret this is that only Expend warrants being treated as a smooth nonlinear effect. The other smooths could be converted to linear parametric terms. You may want to check that the smooth of Room.Board continues to have an non-significant non-parametric effect once you convert the other smooths to linear, parametric terms; it may be that the effect of Room.Board is slightly nonlinear but this is being affected by the presence of the other smooth terms in the model. However, a lot of this might depend on the fact that many smooths were only allowed to use 2 degrees of freedom; why 2? Automatic smoothness selection Newer approaches to fitting GAMs would choose the degree of smoothness for you via automatic smoothness selection approaches such as the penalised spline approach of Simon Wood as implemented in recommended package mgcv: data(College, package = 'ISLR') library('mgcv') set.seed(1) nr <- nrow(College) train <- with(College, sample(nr, ceiling(nr/2))) College.train <- College[train, ] m <- mgcv::gam(Outstate ~ Private + s(Room.Board) + s(PhD) + s(perc.alumni) + s(Expend) + s(Grad.Rate), data = College.train, method = 'REML') The model summary is more concise and directly considers the smooth function as a whole rather than as a linear (parametric) and nonlinear (nonparametric) contributions: > summary(m) Family: gaussian Link function: identity Formula: Outstate ~ Private + s(Room.Board) + s(PhD) + s(perc.alumni) + s(Expend) + s(Grad.Rate) Parametric coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 8544.1 217.2 39.330 <2e-16 *** PrivateYes 2499.2 274.2 9.115 <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 s(Room.Board) 2.190 2.776 20.233 3.91e-11 *** s(PhD) 2.433 3.116 3.037 0.029249 * s(perc.alumni) 1.656 2.072 15.888 1.84e-07 *** s(Expend) 4.528 5.592 19.614 < 2e-16 *** s(Grad.Rate) 2.125 2.710 6.553 0.000452 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 R-sq.(adj) = 0.794 Deviance explained = 80.2% -REML = 3436.4 Scale est. = 3.3143e+06 n = 389 Now the output gathers the smooth terms and the parametric terms into separate tables, with the latter getting a more familiar output similar to that of a linear model. The smooth terms entire effect is shown in the lower table. These aren't the same tests as for the gam::gam model you show; they are tests against the null hypothesis that the smooth effect is a flat, horizontal line, a null effect or showing zero effect. The alternative is that the true nonlinear effect is different from zero. Notice that the EDFs are all larger than 2 except for s(perc.alumni), suggesting that the gam::gam model may be a little restrictive. The fitted smooths for comparison are given by plot(m, pages = 1, scheme = 1, all.terms = TRUE, seWithMean = TRUE) which produces The automatic smoothness selection can also be co-opted to shrinking terms out of the model entirely: Having done that, we see that the model fit has not really changed > summary(m2) Family: gaussian Link function: identity Formula: Outstate ~ Private + s(Room.Board) + s(PhD) + s(perc.alumni) + s(Expend) + s(Grad.Rate) Parametric coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 8539.4 214.8 39.755 <2e-16 *** PrivateYes 2505.7 270.4 9.266 <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 s(Room.Board) 2.260 9 6.338 3.95e-14 *** s(PhD) 1.809 9 0.913 0.00611 ** s(perc.alumni) 1.544 9 3.542 8.21e-09 *** s(Expend) 4.234 9 13.517 < 2e-16 *** s(Grad.Rate) 2.114 9 2.209 1.01e-05 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 R-sq.(adj) = 0.794 Deviance explained = 80.1% -REML = 3475.3 Scale est. = 3.3145e+06 n = 389 All of the smooths seem to suggest slightly nonlinear effects even after we've shrunk the linear and nonlinear parts of the splines. Personally, I find the output from mgcv easier to interpret, and because it has been shown that the automatic smoothness selection methods will tend to fit a linear effect if that is supported by the data.
Summary of a GAM fit The way the output of this approach to fitting GAMs is structured is to group the linear parts of the smoothers in with the other parametric terms. Notice Private has an entry in the first table but i
15,426
How to use XGboost.cv with hyperparameters optimization?
This is how I have trained a xgboost classifier with a 5-fold cross-validation to optimize the F1 score using randomized search for hyperparameter optimization. Note that X and y here should be pandas dataframes. from scipy import stats from xgboost import XGBClassifier from sklearn.model_selection import RandomizedSearchCV, KFold from sklearn.metrics import f1_score clf_xgb = XGBClassifier(objective = 'binary:logistic') param_dist = {'n_estimators': stats.randint(150, 500), 'learning_rate': stats.uniform(0.01, 0.07), 'subsample': stats.uniform(0.3, 0.7), 'max_depth': [3, 4, 5, 6, 7, 8, 9], 'colsample_bytree': stats.uniform(0.5, 0.45), 'min_child_weight': [1, 2, 3] } clf = RandomizedSearchCV(clf_xgb, param_distributions = param_dist, n_iter = 25, scoring = 'f1', error_score = 0, verbose = 3, n_jobs = -1) numFolds = 5 folds = KFold(n_splits = numFolds, shuffle = True) estimators = [] results = np.zeros(len(X)) score = 0.0 for train_index, test_index in folds.split(X): X_train, X_test = X.iloc[train_index,:], X.iloc[test_index,:] y_train, y_test = y.iloc[train_index].values.ravel(), y.iloc[test_index].values.ravel() clf.fit(X_train, y_train) estimators.append(clf.best_estimator_) results[test_index] = clf.predict(X_test) score += f1_score(y_test, results[test_index]) score /= numFolds At the end, you get a list of trained classifiers in estimators, a prediction for the entire dataset in results constructed from out-of-fold predictions, and an estimate for the $F_1$ score in score.
How to use XGboost.cv with hyperparameters optimization?
This is how I have trained a xgboost classifier with a 5-fold cross-validation to optimize the F1 score using randomized search for hyperparameter optimization. Note that X and y here should be pandas
How to use XGboost.cv with hyperparameters optimization? This is how I have trained a xgboost classifier with a 5-fold cross-validation to optimize the F1 score using randomized search for hyperparameter optimization. Note that X and y here should be pandas dataframes. from scipy import stats from xgboost import XGBClassifier from sklearn.model_selection import RandomizedSearchCV, KFold from sklearn.metrics import f1_score clf_xgb = XGBClassifier(objective = 'binary:logistic') param_dist = {'n_estimators': stats.randint(150, 500), 'learning_rate': stats.uniform(0.01, 0.07), 'subsample': stats.uniform(0.3, 0.7), 'max_depth': [3, 4, 5, 6, 7, 8, 9], 'colsample_bytree': stats.uniform(0.5, 0.45), 'min_child_weight': [1, 2, 3] } clf = RandomizedSearchCV(clf_xgb, param_distributions = param_dist, n_iter = 25, scoring = 'f1', error_score = 0, verbose = 3, n_jobs = -1) numFolds = 5 folds = KFold(n_splits = numFolds, shuffle = True) estimators = [] results = np.zeros(len(X)) score = 0.0 for train_index, test_index in folds.split(X): X_train, X_test = X.iloc[train_index,:], X.iloc[test_index,:] y_train, y_test = y.iloc[train_index].values.ravel(), y.iloc[test_index].values.ravel() clf.fit(X_train, y_train) estimators.append(clf.best_estimator_) results[test_index] = clf.predict(X_test) score += f1_score(y_test, results[test_index]) score /= numFolds At the end, you get a list of trained classifiers in estimators, a prediction for the entire dataset in results constructed from out-of-fold predictions, and an estimate for the $F_1$ score in score.
How to use XGboost.cv with hyperparameters optimization? This is how I have trained a xgboost classifier with a 5-fold cross-validation to optimize the F1 score using randomized search for hyperparameter optimization. Note that X and y here should be pandas
15,427
How to use XGboost.cv with hyperparameters optimization?
I don't have enough reputation to make a comment on @darXider's answer. So I add an "answer" to make comments. Why do you need for train_index, test_index in folds: since clf is already doing cross-validation to pick the best set of hyper-parameter values? In your code, it looks like you perform CV for each of the five folds (a "nested" CV) to pick the best model for that particular fold. So in the end, you will have five "best" estimators. Most likely, they don't have the same hyper-parameter values. Correct me if I am wrong.
How to use XGboost.cv with hyperparameters optimization?
I don't have enough reputation to make a comment on @darXider's answer. So I add an "answer" to make comments. Why do you need for train_index, test_index in folds: since clf is already doing cross-va
How to use XGboost.cv with hyperparameters optimization? I don't have enough reputation to make a comment on @darXider's answer. So I add an "answer" to make comments. Why do you need for train_index, test_index in folds: since clf is already doing cross-validation to pick the best set of hyper-parameter values? In your code, it looks like you perform CV for each of the five folds (a "nested" CV) to pick the best model for that particular fold. So in the end, you will have five "best" estimators. Most likely, they don't have the same hyper-parameter values. Correct me if I am wrong.
How to use XGboost.cv with hyperparameters optimization? I don't have enough reputation to make a comment on @darXider's answer. So I add an "answer" to make comments. Why do you need for train_index, test_index in folds: since clf is already doing cross-va
15,428
Supervised dimensionality reduction
The most standard linear method of supervised dimensionality reduction is called linear discriminant analysis (LDA). It is designed to find low-dimensional projection that maximizes class separation. You can find a lot of information about it under our discriminant-analysis tag, and in any machine learning textbook such as e.g. freely available The Elements of Statistical Learning. Here is a picture that I found here with a quick google search; it shows one-dimensional PCA and LDA projections when there are two classes in the dataset (origin added by me): Another approach is called partial least squares (PLS). LDA can be interpreted as looking for projections having highest correlation with the dummy variables encoding group labels (in this sense LDA can be seen as a special case of canonical correlation analysis, CCA). In contrast, PLS looks for projections having highest covariance with group labels. Whereas LDA only yields 1 axis for the case of two groups (like on the picture above), PLS will find many axes ordered by the decreasing covariance. Note that when there are more than two groups present in the dataset, there are different "flavours" of PLS that will produce somewhat different results. Update (2018) I should find time to expand this answer; this thread seems to be popular but my original answer above is very short and not detailed enough. In the meantime, I will mention Neighbourhood Components Analysis -- a linear method that finds the projection maximizing $k$-nearest-neighbours classification accuracy. There is a nonlinear generalization using neural networks, see Learning a Nonlinear Embedding by Preserving Class Neighbourhood Structure. One can also use neural network classifiers with a bottleneck, see Deep Bottleneck Classifiers in Supervised Dimension Reduction.
Supervised dimensionality reduction
The most standard linear method of supervised dimensionality reduction is called linear discriminant analysis (LDA). It is designed to find low-dimensional projection that maximizes class separation.
Supervised dimensionality reduction The most standard linear method of supervised dimensionality reduction is called linear discriminant analysis (LDA). It is designed to find low-dimensional projection that maximizes class separation. You can find a lot of information about it under our discriminant-analysis tag, and in any machine learning textbook such as e.g. freely available The Elements of Statistical Learning. Here is a picture that I found here with a quick google search; it shows one-dimensional PCA and LDA projections when there are two classes in the dataset (origin added by me): Another approach is called partial least squares (PLS). LDA can be interpreted as looking for projections having highest correlation with the dummy variables encoding group labels (in this sense LDA can be seen as a special case of canonical correlation analysis, CCA). In contrast, PLS looks for projections having highest covariance with group labels. Whereas LDA only yields 1 axis for the case of two groups (like on the picture above), PLS will find many axes ordered by the decreasing covariance. Note that when there are more than two groups present in the dataset, there are different "flavours" of PLS that will produce somewhat different results. Update (2018) I should find time to expand this answer; this thread seems to be popular but my original answer above is very short and not detailed enough. In the meantime, I will mention Neighbourhood Components Analysis -- a linear method that finds the projection maximizing $k$-nearest-neighbours classification accuracy. There is a nonlinear generalization using neural networks, see Learning a Nonlinear Embedding by Preserving Class Neighbourhood Structure. One can also use neural network classifiers with a bottleneck, see Deep Bottleneck Classifiers in Supervised Dimension Reduction.
Supervised dimensionality reduction The most standard linear method of supervised dimensionality reduction is called linear discriminant analysis (LDA). It is designed to find low-dimensional projection that maximizes class separation.
15,429
Do descriptive statistics have p-values?
Your are correct. Descriptive statistics characterize the data with which you are working. To generate p-values, assumptions need to be generated. Assumptions are not descriptive.
Do descriptive statistics have p-values?
Your are correct. Descriptive statistics characterize the data with which you are working. To generate p-values, assumptions need to be generated. Assumptions are not descriptive.
Do descriptive statistics have p-values? Your are correct. Descriptive statistics characterize the data with which you are working. To generate p-values, assumptions need to be generated. Assumptions are not descriptive.
Do descriptive statistics have p-values? Your are correct. Descriptive statistics characterize the data with which you are working. To generate p-values, assumptions need to be generated. Assumptions are not descriptive.
15,430
Do descriptive statistics have p-values?
Descriptive statistics do not have p-values. Hypothesis tests, which can test whether or not a descriptive statistic equals a specific value, can have p-values. Whoever asked you to get p-values for descriptive statistics likely meant for you to get a p-value for whether or not that descriptive statistic equals 0. I recommend you follow up and clarify this. What you can do is get a confidence interval for a descriptive statistic which tells you much of the same thing.
Do descriptive statistics have p-values?
Descriptive statistics do not have p-values. Hypothesis tests, which can test whether or not a descriptive statistic equals a specific value, can have p-values. Whoever asked you to get p-values for d
Do descriptive statistics have p-values? Descriptive statistics do not have p-values. Hypothesis tests, which can test whether or not a descriptive statistic equals a specific value, can have p-values. Whoever asked you to get p-values for descriptive statistics likely meant for you to get a p-value for whether or not that descriptive statistic equals 0. I recommend you follow up and clarify this. What you can do is get a confidence interval for a descriptive statistic which tells you much of the same thing.
Do descriptive statistics have p-values? Descriptive statistics do not have p-values. Hypothesis tests, which can test whether or not a descriptive statistic equals a specific value, can have p-values. Whoever asked you to get p-values for d
15,431
Do descriptive statistics have p-values?
Almost all descriptive statistics are used in hypothesis testing too. So, it's not exclusive classification into inferential and descriptive when we talk about the metrics such as the mean and standard deviation. For instance, the sample mean is a descriptive statistic. Yet, you can obtain its p-value if you construct a hypothesis, such as $H_0: E[x]=0$, i.e. that the mean of the population is zero.
Do descriptive statistics have p-values?
Almost all descriptive statistics are used in hypothesis testing too. So, it's not exclusive classification into inferential and descriptive when we talk about the metrics such as the mean and standar
Do descriptive statistics have p-values? Almost all descriptive statistics are used in hypothesis testing too. So, it's not exclusive classification into inferential and descriptive when we talk about the metrics such as the mean and standard deviation. For instance, the sample mean is a descriptive statistic. Yet, you can obtain its p-value if you construct a hypothesis, such as $H_0: E[x]=0$, i.e. that the mean of the population is zero.
Do descriptive statistics have p-values? Almost all descriptive statistics are used in hypothesis testing too. So, it's not exclusive classification into inferential and descriptive when we talk about the metrics such as the mean and standar
15,432
Do descriptive statistics have p-values?
In descriptive tables, the p-value is frequently used to check whether the randomization was successful or, in non-randomized experiments, if covariates are equally distributed among the categories of the main exposure variable. The issue is controversial because (1) you can't test whether between-group differences are due to chance, since you made the randomization, so it doesn't make much sense to test whether they are due to chance; (2) tests without adequately sized/powered samples don't mean much, and if you are considering it, maybe you should fully adjust your analysis to account for said covariates.
Do descriptive statistics have p-values?
In descriptive tables, the p-value is frequently used to check whether the randomization was successful or, in non-randomized experiments, if covariates are equally distributed among the categories of
Do descriptive statistics have p-values? In descriptive tables, the p-value is frequently used to check whether the randomization was successful or, in non-randomized experiments, if covariates are equally distributed among the categories of the main exposure variable. The issue is controversial because (1) you can't test whether between-group differences are due to chance, since you made the randomization, so it doesn't make much sense to test whether they are due to chance; (2) tests without adequately sized/powered samples don't mean much, and if you are considering it, maybe you should fully adjust your analysis to account for said covariates.
Do descriptive statistics have p-values? In descriptive tables, the p-value is frequently used to check whether the randomization was successful or, in non-randomized experiments, if covariates are equally distributed among the categories of
15,433
Questions on PCA: when are PCs independent? why is PCA sensitive to scaling? why are PCs constrained to be orthogonal?
Q1. Principal components are mutually orthogonal (uncorrelated) variables. Orthogonality and statistical independence are not synonyms. There is nothing special about principal components; the same is true of any variables in multivariate data analysis. If the data are multivariate normal (which is not the same as to state that each of the variables is univariately normal) and the variables are uncorrelated, then yes, they are independent. Whether independence of principal components matters or not - depends on how you are going to use them. Quite often, their orthogonality will suffice. Q2. Yes, scaling means shrinking or stretching variance of individual variables. The variables are the dimensions of the space the data lie in. PCA results - the components - are sensitive to the shape of the data cloud, the shape of that "ellipsoid". If you only center the variables, leave the variances as they are, this is often called "PCA based on covariances". If you also standardize the variables to variances = 1, this is often called "PCA based on correlations", and it can be very different from the former (see a thread). Also, relatively seldom people do PCA on non-centered data: raw data or just scaled to unit magnitude; results of such PCA are further different from where you center the data (see a picture). Q3. The "constraint" is how PCA works (see a huge thread). Imagine your data is 3-dimensional cloud (3 variables, $n$ points); the origin is set at the centroid (the mean) of it. PCA draws component1 as such an axis through the origin, the sum of the squared projections (coordinates) on which is maximized; that is, the variance along component1 is maximized. After component1 is defined, it can be removed as a dimension, which means that the data points are projected onto the plane orthogonal to that component. You are left with a 2-dimensional cloud. Then again, you apply the above procedure of finding the axis of maximal variance - now in this remnant, 2D cloud. And that will be component2. You remove the drawn component2 from the plane by projecting data points onto the line orthogonal to it. That line, representing the remnant 1D cloud, is defined as the last component, component 3. You can see that on each of these 3 "steps", the analysis a) found the dimension of the greatest variance in the current $p$-dimensional space, b) reduced the data to the dimensions without that dimension, that is, to the $p-1$-dimensional space orthogonal to the mentioned dimension. That is how it turns out that each principal component is a "maximal variance" and all the components are mutually orthogonal (see also). [P.S. Please note that "orthogonal" means two things: (1) variable axes as physically perpendicular axes; (2) variables as uncorrelated by their data. With PCA and some other multivariate methods, these two things are the same thing. But with some other analyses (e.g. Discriminant analysis), uncorrelated extracted latent variables does not automatically mean that their axes are perpendicular in the original space.]
Questions on PCA: when are PCs independent? why is PCA sensitive to scaling? why are PCs constrained
Q1. Principal components are mutually orthogonal (uncorrelated) variables. Orthogonality and statistical independence are not synonyms. There is nothing special about principal components; the same is
Questions on PCA: when are PCs independent? why is PCA sensitive to scaling? why are PCs constrained to be orthogonal? Q1. Principal components are mutually orthogonal (uncorrelated) variables. Orthogonality and statistical independence are not synonyms. There is nothing special about principal components; the same is true of any variables in multivariate data analysis. If the data are multivariate normal (which is not the same as to state that each of the variables is univariately normal) and the variables are uncorrelated, then yes, they are independent. Whether independence of principal components matters or not - depends on how you are going to use them. Quite often, their orthogonality will suffice. Q2. Yes, scaling means shrinking or stretching variance of individual variables. The variables are the dimensions of the space the data lie in. PCA results - the components - are sensitive to the shape of the data cloud, the shape of that "ellipsoid". If you only center the variables, leave the variances as they are, this is often called "PCA based on covariances". If you also standardize the variables to variances = 1, this is often called "PCA based on correlations", and it can be very different from the former (see a thread). Also, relatively seldom people do PCA on non-centered data: raw data or just scaled to unit magnitude; results of such PCA are further different from where you center the data (see a picture). Q3. The "constraint" is how PCA works (see a huge thread). Imagine your data is 3-dimensional cloud (3 variables, $n$ points); the origin is set at the centroid (the mean) of it. PCA draws component1 as such an axis through the origin, the sum of the squared projections (coordinates) on which is maximized; that is, the variance along component1 is maximized. After component1 is defined, it can be removed as a dimension, which means that the data points are projected onto the plane orthogonal to that component. You are left with a 2-dimensional cloud. Then again, you apply the above procedure of finding the axis of maximal variance - now in this remnant, 2D cloud. And that will be component2. You remove the drawn component2 from the plane by projecting data points onto the line orthogonal to it. That line, representing the remnant 1D cloud, is defined as the last component, component 3. You can see that on each of these 3 "steps", the analysis a) found the dimension of the greatest variance in the current $p$-dimensional space, b) reduced the data to the dimensions without that dimension, that is, to the $p-1$-dimensional space orthogonal to the mentioned dimension. That is how it turns out that each principal component is a "maximal variance" and all the components are mutually orthogonal (see also). [P.S. Please note that "orthogonal" means two things: (1) variable axes as physically perpendicular axes; (2) variables as uncorrelated by their data. With PCA and some other multivariate methods, these two things are the same thing. But with some other analyses (e.g. Discriminant analysis), uncorrelated extracted latent variables does not automatically mean that their axes are perpendicular in the original space.]
Questions on PCA: when are PCs independent? why is PCA sensitive to scaling? why are PCs constrained Q1. Principal components are mutually orthogonal (uncorrelated) variables. Orthogonality and statistical independence are not synonyms. There is nothing special about principal components; the same is
15,434
How we can draw an ROC curve for decision trees?
If your classifier produces only factor outcomes (only labels) without scores, you still can draw a ROC curve. However, this ROC curve is only a point. Considering the ROC space, this point is $(x,y) = (\text{FPR}, \text{TPR})$, where $\text{FPR}$ - false positive rate and $\text{TPR}$ - true positive rate. See more on how this is computed on Wikipedia page. You can extend this point to look like a ROC curve by drawing a line from $(0,0)$ to your point, and from there to $(1,1)$. Thus you have a curve. However, for a decision tree is easy to extend from an label output to a numeric output. Note that when you predict with a decision tree you go down from the root node to a leaf node, where you predict with majority class. If instead of that class you would return the proportion of classes in that leaf node, you would have a score for each class. Suppose that you have two classes $\text{T}$ and $\text{F}$, and in your leaf node you have 10 instances with $\text{T}$ and 5 instances with $\text{F}$, you can return a vector of scores: $(\text{score}_T, \text{score}_F) = ( \frac{\text{count}_T}{\text{count}_T + \text{count}_F}, \frac{\text{count}_F}{\text{count}_T + \text{count}_F}) = (10/15, 5/15) = (0.66, 0.33)$. Take care that this is really not a proper scoring rule (these are not the best estimators for probabilities), but is better than nothing I believe, and this is how usually scores are retrieved for decision trees.
How we can draw an ROC curve for decision trees?
If your classifier produces only factor outcomes (only labels) without scores, you still can draw a ROC curve. However, this ROC curve is only a point. Considering the ROC space, this point is $(x,y)
How we can draw an ROC curve for decision trees? If your classifier produces only factor outcomes (only labels) without scores, you still can draw a ROC curve. However, this ROC curve is only a point. Considering the ROC space, this point is $(x,y) = (\text{FPR}, \text{TPR})$, where $\text{FPR}$ - false positive rate and $\text{TPR}$ - true positive rate. See more on how this is computed on Wikipedia page. You can extend this point to look like a ROC curve by drawing a line from $(0,0)$ to your point, and from there to $(1,1)$. Thus you have a curve. However, for a decision tree is easy to extend from an label output to a numeric output. Note that when you predict with a decision tree you go down from the root node to a leaf node, where you predict with majority class. If instead of that class you would return the proportion of classes in that leaf node, you would have a score for each class. Suppose that you have two classes $\text{T}$ and $\text{F}$, and in your leaf node you have 10 instances with $\text{T}$ and 5 instances with $\text{F}$, you can return a vector of scores: $(\text{score}_T, \text{score}_F) = ( \frac{\text{count}_T}{\text{count}_T + \text{count}_F}, \frac{\text{count}_F}{\text{count}_T + \text{count}_F}) = (10/15, 5/15) = (0.66, 0.33)$. Take care that this is really not a proper scoring rule (these are not the best estimators for probabilities), but is better than nothing I believe, and this is how usually scores are retrieved for decision trees.
How we can draw an ROC curve for decision trees? If your classifier produces only factor outcomes (only labels) without scores, you still can draw a ROC curve. However, this ROC curve is only a point. Considering the ROC space, this point is $(x,y)
15,435
How we can draw an ROC curve for decision trees?
For a Decision Tree, the classes are still predicted with some level of certainty. The answer is already given by @rapaio, but I'll expand on it a bit. Imagine the following decision tree (it's a little bit modified version of this one) At each node there are not only the majority class labels, but also others what ended up at that leaf, so we can assign the degree of certainty to that leaf at which we predict the label. For example, consider the following data We run it, and assign the scores to the output, not the actual labels. With this, we can draw a ROC curve, like suggested here It makes little sense, though, to use it to tune your threshold (since, of course, there's no such thing as threshold in Decision Trees), but it still can be used to calculate the AUC, which, in this case, is 0.92 R code used here: outlook = c('rain', 'overcast', 'rain', 'sunny', 'rain', 'rain', 'sunny', 'overcast', 'overcast', 'overcast', 'sunny', 'sunny', 'rain', 'rain', 'overcast', 'sunny', 'overcast', 'overcast', 'sunny', 'sunny', 'sunny', 'overcast') humidity = c(79, 74, 80, 60, 65, 79, 60, 74, 77, 80, 71, 70, 80, 65, 70, 56, 80, 70, 56, 70, 71, 77) windy = c(T, T, F, T, F, T, T, T, T, F, T, F, F, F, T, T, F, T, T, F, T, T) play = c(F, F, T, F, T, F, F, T, T, T, F, F, T, T, T, T, T, T, F, T, F, T) game = data.frame(outlook, humidity, windy, play) game$score = NA attach(game) game$score[outlook == 'sunny' & humidity <= 70] = 5/8 game$score[outlook == 'sunny' & humidity > 70] = 1 - 3/4 game$score[outlook == 'overcast'] = 4/5 game$score[outlook == 'rain' & windy == T] = 1 - 2/2 game$score[outlook == 'rain' & windy == F] = 3/3 detach(game) game$predict = game$score >= 0.5 game$correct = game$predict == game$play library(ROCR) pred = prediction(game$score, game$play) roc = performance(pred, measure="tpr", x.measure="fpr") plot(roc, col="orange", lwd=2) lines(x=c(0, 1), y=c(0, 1), col="red", lwd=2) auc = performance(pred, 'auc') slot(auc, 'y.values')
How we can draw an ROC curve for decision trees?
For a Decision Tree, the classes are still predicted with some level of certainty. The answer is already given by @rapaio, but I'll expand on it a bit. Imagine the following decision tree (it's a li
How we can draw an ROC curve for decision trees? For a Decision Tree, the classes are still predicted with some level of certainty. The answer is already given by @rapaio, but I'll expand on it a bit. Imagine the following decision tree (it's a little bit modified version of this one) At each node there are not only the majority class labels, but also others what ended up at that leaf, so we can assign the degree of certainty to that leaf at which we predict the label. For example, consider the following data We run it, and assign the scores to the output, not the actual labels. With this, we can draw a ROC curve, like suggested here It makes little sense, though, to use it to tune your threshold (since, of course, there's no such thing as threshold in Decision Trees), but it still can be used to calculate the AUC, which, in this case, is 0.92 R code used here: outlook = c('rain', 'overcast', 'rain', 'sunny', 'rain', 'rain', 'sunny', 'overcast', 'overcast', 'overcast', 'sunny', 'sunny', 'rain', 'rain', 'overcast', 'sunny', 'overcast', 'overcast', 'sunny', 'sunny', 'sunny', 'overcast') humidity = c(79, 74, 80, 60, 65, 79, 60, 74, 77, 80, 71, 70, 80, 65, 70, 56, 80, 70, 56, 70, 71, 77) windy = c(T, T, F, T, F, T, T, T, T, F, T, F, F, F, T, T, F, T, T, F, T, T) play = c(F, F, T, F, T, F, F, T, T, T, F, F, T, T, T, T, T, T, F, T, F, T) game = data.frame(outlook, humidity, windy, play) game$score = NA attach(game) game$score[outlook == 'sunny' & humidity <= 70] = 5/8 game$score[outlook == 'sunny' & humidity > 70] = 1 - 3/4 game$score[outlook == 'overcast'] = 4/5 game$score[outlook == 'rain' & windy == T] = 1 - 2/2 game$score[outlook == 'rain' & windy == F] = 3/3 detach(game) game$predict = game$score >= 0.5 game$correct = game$predict == game$play library(ROCR) pred = prediction(game$score, game$play) roc = performance(pred, measure="tpr", x.measure="fpr") plot(roc, col="orange", lwd=2) lines(x=c(0, 1), y=c(0, 1), col="red", lwd=2) auc = performance(pred, 'auc') slot(auc, 'y.values')
How we can draw an ROC curve for decision trees? For a Decision Tree, the classes are still predicted with some level of certainty. The answer is already given by @rapaio, but I'll expand on it a bit. Imagine the following decision tree (it's a li
15,436
What are the issues with using percentage outcome in linear regression?
I'll address the issues relevant to either discrete or continuous possibility: A problem with the description of the mean You have a bounded response. But the model you're fitting isn't bounded, and so can blast right through the bound; some of your fitted values may be impossible, and predicted values eventually must be. The true relationship must eventually become flatter than it is at the middle as it approaches the bounds, so it would be expected to bend in some fashion. A problem with the description of the variance As the mean approaches the bound, the variance will tend to decrease as well, other things being equal. There's less room between the mean and the bound, so the overall variability tends to reduce (otherwise the mean would tend to be pulled away from the bound by points being on average further away on the side not close to the bound. (Indeed, if all the population values in some neighborhood were exactly at the bound, the variance there would be zero.) A model that deals with such a bound should take such effects into consideration. If the proportion is for a count variable, a common model for the distribution of the proportion is a binomial GLM. There are several options for the form of the relationship of the mean proportion and the predictors, but the most common one would be a logistic GLM (several other choices are in common use). If the proportion is a continuous one (like the percentage of cream in milk), there are a number of options. Beta regression seems to be one fairly common choice. Again, it might use a logistic relationship between the mean and the predictors, or it might use some other functional form. See also Regression for an outcome (ratio or fraction) between 0 and 1.
What are the issues with using percentage outcome in linear regression?
I'll address the issues relevant to either discrete or continuous possibility: A problem with the description of the mean You have a bounded response. But the model you're fitting isn't bounded, and
What are the issues with using percentage outcome in linear regression? I'll address the issues relevant to either discrete or continuous possibility: A problem with the description of the mean You have a bounded response. But the model you're fitting isn't bounded, and so can blast right through the bound; some of your fitted values may be impossible, and predicted values eventually must be. The true relationship must eventually become flatter than it is at the middle as it approaches the bounds, so it would be expected to bend in some fashion. A problem with the description of the variance As the mean approaches the bound, the variance will tend to decrease as well, other things being equal. There's less room between the mean and the bound, so the overall variability tends to reduce (otherwise the mean would tend to be pulled away from the bound by points being on average further away on the side not close to the bound. (Indeed, if all the population values in some neighborhood were exactly at the bound, the variance there would be zero.) A model that deals with such a bound should take such effects into consideration. If the proportion is for a count variable, a common model for the distribution of the proportion is a binomial GLM. There are several options for the form of the relationship of the mean proportion and the predictors, but the most common one would be a logistic GLM (several other choices are in common use). If the proportion is a continuous one (like the percentage of cream in milk), there are a number of options. Beta regression seems to be one fairly common choice. Again, it might use a logistic relationship between the mean and the predictors, or it might use some other functional form. See also Regression for an outcome (ratio or fraction) between 0 and 1.
What are the issues with using percentage outcome in linear regression? I'll address the issues relevant to either discrete or continuous possibility: A problem with the description of the mean You have a bounded response. But the model you're fitting isn't bounded, and
15,437
What are the issues with using percentage outcome in linear regression?
This is exactly the same thing as the case when the outcome is between 0 and 1, and that case is typically handled with a generalized linear model (GLM) like logistic regression. There are lots of excellent primers for logistic regression (and other GLMs) on the internet, and there is also a well-known book by Agresti on the topic. Beta regression is a viable but more complicated alternative. Chances are logistic regression would work fine for your application, and would typically be easier to implement with most statistical software. Why not use ordinary least squares regression? Actually people do, sometimes under the name "linear probability model" (LPM). The most obvious reason why LPMs are "bad" is that there's no easy way to constrain the outcome to lie within a certain range, and you can get predictions above 1 (or 100% or any other finite upper bound) and below 0 (or some other lower bound). For the same reason, predictions near the upper bound tend to be systematically too high, and predictions near the lower bound tend to be too low. The math underlying linear regression explicitly assumes that tendencies like this don't exist. There typically isn't a great reason to fit an LPM over logistic regression. As an aside, it turns out that all OLS regression models, including LPMs, can be defined as a special kind of GLM, and in this context LPMs are related to logistic regression.
What are the issues with using percentage outcome in linear regression?
This is exactly the same thing as the case when the outcome is between 0 and 1, and that case is typically handled with a generalized linear model (GLM) like logistic regression. There are lots of exc
What are the issues with using percentage outcome in linear regression? This is exactly the same thing as the case when the outcome is between 0 and 1, and that case is typically handled with a generalized linear model (GLM) like logistic regression. There are lots of excellent primers for logistic regression (and other GLMs) on the internet, and there is also a well-known book by Agresti on the topic. Beta regression is a viable but more complicated alternative. Chances are logistic regression would work fine for your application, and would typically be easier to implement with most statistical software. Why not use ordinary least squares regression? Actually people do, sometimes under the name "linear probability model" (LPM). The most obvious reason why LPMs are "bad" is that there's no easy way to constrain the outcome to lie within a certain range, and you can get predictions above 1 (or 100% or any other finite upper bound) and below 0 (or some other lower bound). For the same reason, predictions near the upper bound tend to be systematically too high, and predictions near the lower bound tend to be too low. The math underlying linear regression explicitly assumes that tendencies like this don't exist. There typically isn't a great reason to fit an LPM over logistic regression. As an aside, it turns out that all OLS regression models, including LPMs, can be defined as a special kind of GLM, and in this context LPMs are related to logistic regression.
What are the issues with using percentage outcome in linear regression? This is exactly the same thing as the case when the outcome is between 0 and 1, and that case is typically handled with a generalized linear model (GLM) like logistic regression. There are lots of exc
15,438
What are the issues with using percentage outcome in linear regression?
It might be worth investigating beta regression (for which I understand there is an R package), which seems well suited to such problems. http://www.jstatsoft.org/v34/i02/paper
What are the issues with using percentage outcome in linear regression?
It might be worth investigating beta regression (for which I understand there is an R package), which seems well suited to such problems. http://www.jstatsoft.org/v34/i02/paper
What are the issues with using percentage outcome in linear regression? It might be worth investigating beta regression (for which I understand there is an R package), which seems well suited to such problems. http://www.jstatsoft.org/v34/i02/paper
What are the issues with using percentage outcome in linear regression? It might be worth investigating beta regression (for which I understand there is an R package), which seems well suited to such problems. http://www.jstatsoft.org/v34/i02/paper
15,439
How to perform an ANCOVA in R
The basic tool for this is lm; note that aov is a wrapper for lm. In particular, if you have some grouping variable (factor), $g$, and a continuous covariate $x$, the model y ~ x + g would fit a main effects ANCOVA model, while y ~ x * g would fit a model which includes interaction with the covariate. aov will take the same formulas. Pay particular attention to the Note in the help on aov. As for + vs *, russellpierce pretty much covers it, but I'd recommend you look at ?lm and ?formula and most especially section 11.1 of the manual An Introduction to R that comes with R (or you can find it online if you haven't figured out how to find it on your computer; most easily, this involves finding the "Help" pull down menu in either R or RStudio).
How to perform an ANCOVA in R
The basic tool for this is lm; note that aov is a wrapper for lm. In particular, if you have some grouping variable (factor), $g$, and a continuous covariate $x$, the model y ~ x + g would fit a main
How to perform an ANCOVA in R The basic tool for this is lm; note that aov is a wrapper for lm. In particular, if you have some grouping variable (factor), $g$, and a continuous covariate $x$, the model y ~ x + g would fit a main effects ANCOVA model, while y ~ x * g would fit a model which includes interaction with the covariate. aov will take the same formulas. Pay particular attention to the Note in the help on aov. As for + vs *, russellpierce pretty much covers it, but I'd recommend you look at ?lm and ?formula and most especially section 11.1 of the manual An Introduction to R that comes with R (or you can find it online if you haven't figured out how to find it on your computer; most easily, this involves finding the "Help" pull down menu in either R or RStudio).
How to perform an ANCOVA in R The basic tool for this is lm; note that aov is a wrapper for lm. In particular, if you have some grouping variable (factor), $g$, and a continuous covariate $x$, the model y ~ x + g would fit a main
15,440
How to perform an ANCOVA in R
I recommend getting and reading Discovering Statistics using R by Field. He has a nice section on ANCOVA. To run ANCOVA in R load the following packages: car compute.es effects ggplot2 multcomp pastecs WRS If you are using lm or aov (I use aov) make sure that you set the contrasts using the "contrasts" function before doing either aov or lm. R uses non-orthogonal contrasts by default which can mess everything up in an ANCOVA. If you want to set orthogonal contrasts use: contrasts(dataname$factorvariable)=contr.poly(# of levels, i.e. 3) then run your model as model.1=aov(dv~covariate+factorvariable, data=dataname) To view the model use: Anova(model.1, type="III") Make sure you use capital "A" Anova here and not anova. This will give results using type III SS. summary.lm(model.1) will give another summary and includes the R-sq. output. posth=glht(model.1, linfct=mcp(factorvariable="Tukey")) ##gives the post-hoc Tukey analysis summary(posth) ##shows the output in a nice format. If you want to test for homogeneity of regression slopes you can also include an interaction term for the IV and covariate. That would be: model=aov(dv~covariate+IV+covariate:IV, data=dataname) If the interaction term is significant then you do not have homogeneity.
How to perform an ANCOVA in R
I recommend getting and reading Discovering Statistics using R by Field. He has a nice section on ANCOVA. To run ANCOVA in R load the following packages: car compute.es effects ggplot2 multcomp past
How to perform an ANCOVA in R I recommend getting and reading Discovering Statistics using R by Field. He has a nice section on ANCOVA. To run ANCOVA in R load the following packages: car compute.es effects ggplot2 multcomp pastecs WRS If you are using lm or aov (I use aov) make sure that you set the contrasts using the "contrasts" function before doing either aov or lm. R uses non-orthogonal contrasts by default which can mess everything up in an ANCOVA. If you want to set orthogonal contrasts use: contrasts(dataname$factorvariable)=contr.poly(# of levels, i.e. 3) then run your model as model.1=aov(dv~covariate+factorvariable, data=dataname) To view the model use: Anova(model.1, type="III") Make sure you use capital "A" Anova here and not anova. This will give results using type III SS. summary.lm(model.1) will give another summary and includes the R-sq. output. posth=glht(model.1, linfct=mcp(factorvariable="Tukey")) ##gives the post-hoc Tukey analysis summary(posth) ##shows the output in a nice format. If you want to test for homogeneity of regression slopes you can also include an interaction term for the IV and covariate. That would be: model=aov(dv~covariate+IV+covariate:IV, data=dataname) If the interaction term is significant then you do not have homogeneity.
How to perform an ANCOVA in R I recommend getting and reading Discovering Statistics using R by Field. He has a nice section on ANCOVA. To run ANCOVA in R load the following packages: car compute.es effects ggplot2 multcomp past
15,441
How to perform an ANCOVA in R
Here is a complementary documentation http://goo.gl/yxUZ1R of the procedure suggested by @Butorovich. In addition, my observation is that when the covariate is binary, using summary(lm.object) would give same IV estimate as generate by Anova(lm.object, type="III").
How to perform an ANCOVA in R
Here is a complementary documentation http://goo.gl/yxUZ1R of the procedure suggested by @Butorovich. In addition, my observation is that when the covariate is binary, using summary(lm.object) would g
How to perform an ANCOVA in R Here is a complementary documentation http://goo.gl/yxUZ1R of the procedure suggested by @Butorovich. In addition, my observation is that when the covariate is binary, using summary(lm.object) would give same IV estimate as generate by Anova(lm.object, type="III").
How to perform an ANCOVA in R Here is a complementary documentation http://goo.gl/yxUZ1R of the procedure suggested by @Butorovich. In addition, my observation is that when the covariate is binary, using summary(lm.object) would g
15,442
Kullback–Leibler divergence between two gamma distributions
The KL divergence is a difference of integrals of the form $$\begin{aligned} I(a,b,c,d)&=\int_0^{\infty} \log\left(\frac{e^{-x/a}x^{b-1}}{a^b\Gamma(b)}\right) \frac{e^{-x/c}x^{d-1}}{c^d \Gamma(d)}\, \mathrm dx \\ &=-\frac{1}{a}\int_0^\infty \frac{x^d e^{-x/c}}{c^d\Gamma(d)}\, \mathrm dx - \log(a^b\Gamma(b))\int_0^\infty \frac{e^{-x/c}x^{d-1}}{c^d\Gamma(d)}\, \mathrm dx\\ &\quad+ (b-1)\int_0^\infty \log(x) \frac{e^{-x/c}x^{d-1}}{c^d\Gamma(d)}\, \mathrm dx\\ &=-\frac{cd}{a} - \log(a^b\Gamma(b)) + (b-1)\int_0^\infty \log(x) \frac{e^{-x/c}x^{d-1}}{c^d\Gamma(d)}\,\mathrm dx \end{aligned}$$ We just have to deal with the right hand integral, which is obtained by observing $$\eqalign{ \frac{\partial}{\partial d}\Gamma(d) =& \frac{\partial}{\partial d}\int_0^{\infty}e^{-x/c}\frac{x^{d-1}}{c^d}\, \mathrm dx\\ =& \frac{\partial}{\partial d} \int_0^\infty e^{-x/c} \frac{(x/c)^{d-1}}{c}\, \mathrm dx\\ =&\int_0^\infty e^{-x/c}\frac{x^{d-1}}{c^d} \log\frac{x}{c} \, \mathrm dx\\ =&\int_0^{\infty}\log(x)e^{-x/c}\frac{x^{d-1}}{c^d}\, \mathrm dx - \log(c)\Gamma(d). }$$ Whence $$\frac{b-1}{\Gamma(d)}\int_0^{\infty} \log(x)e^{-x/c}(x/c)^{d-1}\, \mathrm dx = (b-1)\frac{\Gamma'(d)}{\Gamma(d)} + (b-1)\log(c).$$ Plugging into the preceding yields $$I(a,b,c,d)=\frac{-cd}{a} -\log(a^b\Gamma(b))+(b-1)\frac{\Gamma'(d)}{\Gamma(d)} + (b-1)\log(c).$$ The KL divergence between $\Gamma(c,d)$ and $\Gamma(a,b)$ equals $I(c,d,c,d) - I(a,b,c,d)$, which is straightforward to assemble. Implementation Details Gamma functions grow rapidly, so to avoid overflow don't compute Gamma and take its logarithm: instead use the log-Gamma function that will be found in any statistical computing platform (including Excel, for that matter). The ratio $\Gamma^\prime(d)/\Gamma(d)$ is the logarithmic derivative of $\Gamma,$ generally called $\psi,$ the digamma function. If it's not available to you, there are relatively simple ways to approximate it, as described in the Wikipedia article. Here, to illustrate, is a direct R implementation of the formula in terms of $I$. This does not exploit an opportunity to simplify the result algebraically, which would make it a little more efficient (by eliminating a redundant calculation of $\psi$). # # `b` and `d` are Gamma shape parameters and # `a` and `c` are scale parameters. # (All, therefore, must be positive.) # KL.gamma <- function(a,b,c,d) { i <- function(a,b,c,d) - c * d / a - b * log(a) - lgamma(b) + (b-1)*(psigamma(d) + log(c)) i(c,d,c,d) - i(a,b,c,d) } print(KL.gamma(1/114186.3, 202, 1/119237.3, 195), digits=12)
Kullback–Leibler divergence between two gamma distributions
The KL divergence is a difference of integrals of the form $$\begin{aligned} I(a,b,c,d)&=\int_0^{\infty} \log\left(\frac{e^{-x/a}x^{b-1}}{a^b\Gamma(b)}\right) \frac{e^{-x/c}x^{d-1}}{c^d \Gamma(d)}\, \
Kullback–Leibler divergence between two gamma distributions The KL divergence is a difference of integrals of the form $$\begin{aligned} I(a,b,c,d)&=\int_0^{\infty} \log\left(\frac{e^{-x/a}x^{b-1}}{a^b\Gamma(b)}\right) \frac{e^{-x/c}x^{d-1}}{c^d \Gamma(d)}\, \mathrm dx \\ &=-\frac{1}{a}\int_0^\infty \frac{x^d e^{-x/c}}{c^d\Gamma(d)}\, \mathrm dx - \log(a^b\Gamma(b))\int_0^\infty \frac{e^{-x/c}x^{d-1}}{c^d\Gamma(d)}\, \mathrm dx\\ &\quad+ (b-1)\int_0^\infty \log(x) \frac{e^{-x/c}x^{d-1}}{c^d\Gamma(d)}\, \mathrm dx\\ &=-\frac{cd}{a} - \log(a^b\Gamma(b)) + (b-1)\int_0^\infty \log(x) \frac{e^{-x/c}x^{d-1}}{c^d\Gamma(d)}\,\mathrm dx \end{aligned}$$ We just have to deal with the right hand integral, which is obtained by observing $$\eqalign{ \frac{\partial}{\partial d}\Gamma(d) =& \frac{\partial}{\partial d}\int_0^{\infty}e^{-x/c}\frac{x^{d-1}}{c^d}\, \mathrm dx\\ =& \frac{\partial}{\partial d} \int_0^\infty e^{-x/c} \frac{(x/c)^{d-1}}{c}\, \mathrm dx\\ =&\int_0^\infty e^{-x/c}\frac{x^{d-1}}{c^d} \log\frac{x}{c} \, \mathrm dx\\ =&\int_0^{\infty}\log(x)e^{-x/c}\frac{x^{d-1}}{c^d}\, \mathrm dx - \log(c)\Gamma(d). }$$ Whence $$\frac{b-1}{\Gamma(d)}\int_0^{\infty} \log(x)e^{-x/c}(x/c)^{d-1}\, \mathrm dx = (b-1)\frac{\Gamma'(d)}{\Gamma(d)} + (b-1)\log(c).$$ Plugging into the preceding yields $$I(a,b,c,d)=\frac{-cd}{a} -\log(a^b\Gamma(b))+(b-1)\frac{\Gamma'(d)}{\Gamma(d)} + (b-1)\log(c).$$ The KL divergence between $\Gamma(c,d)$ and $\Gamma(a,b)$ equals $I(c,d,c,d) - I(a,b,c,d)$, which is straightforward to assemble. Implementation Details Gamma functions grow rapidly, so to avoid overflow don't compute Gamma and take its logarithm: instead use the log-Gamma function that will be found in any statistical computing platform (including Excel, for that matter). The ratio $\Gamma^\prime(d)/\Gamma(d)$ is the logarithmic derivative of $\Gamma,$ generally called $\psi,$ the digamma function. If it's not available to you, there are relatively simple ways to approximate it, as described in the Wikipedia article. Here, to illustrate, is a direct R implementation of the formula in terms of $I$. This does not exploit an opportunity to simplify the result algebraically, which would make it a little more efficient (by eliminating a redundant calculation of $\psi$). # # `b` and `d` are Gamma shape parameters and # `a` and `c` are scale parameters. # (All, therefore, must be positive.) # KL.gamma <- function(a,b,c,d) { i <- function(a,b,c,d) - c * d / a - b * log(a) - lgamma(b) + (b-1)*(psigamma(d) + log(c)) i(c,d,c,d) - i(a,b,c,d) } print(KL.gamma(1/114186.3, 202, 1/119237.3, 195), digits=12)
Kullback–Leibler divergence between two gamma distributions The KL divergence is a difference of integrals of the form $$\begin{aligned} I(a,b,c,d)&=\int_0^{\infty} \log\left(\frac{e^{-x/a}x^{b-1}}{a^b\Gamma(b)}\right) \frac{e^{-x/c}x^{d-1}}{c^d \Gamma(d)}\, \
15,443
Kullback–Leibler divergence between two gamma distributions
The Gamma distribution is in the exponential family because its density can be expressed as: \begin{align} \newcommand{\mbx}{\mathbf{x}} \newcommand{\btheta}{\boldsymbol{\theta}} f(\mbx \mid \btheta) &= \exp\bigl(\eta(\btheta) \cdot T(\mbx) - g(\btheta) + h(\mbx)\bigr) \end{align} Looking at the Gamma density function, its log-normalizer is $$g(\btheta) = \log(\Gamma(c)) + c\log(b)$$ with natural parameters $$\btheta = \left[\begin{matrix}c-1\\-\frac1 b\end{matrix}\right]$$ All distributions in the exponential family have KL divergence: \begin{align} KL(q; p) &= g(\btheta_p) - g(\btheta_q) - (\btheta_p-\btheta_q) \cdot \nabla g(\btheta_q). \end{align} There's a really nice proof of that in: Frank Nielsen, École Polytechnique, and Richard Nock, Entropies and cross-entropies of exponential families.
Kullback–Leibler divergence between two gamma distributions
The Gamma distribution is in the exponential family because its density can be expressed as: \begin{align} \newcommand{\mbx}{\mathbf{x}} \newcommand{\btheta}{\boldsymbol{\theta}} f(\mbx \mid \btheta)
Kullback–Leibler divergence between two gamma distributions The Gamma distribution is in the exponential family because its density can be expressed as: \begin{align} \newcommand{\mbx}{\mathbf{x}} \newcommand{\btheta}{\boldsymbol{\theta}} f(\mbx \mid \btheta) &= \exp\bigl(\eta(\btheta) \cdot T(\mbx) - g(\btheta) + h(\mbx)\bigr) \end{align} Looking at the Gamma density function, its log-normalizer is $$g(\btheta) = \log(\Gamma(c)) + c\log(b)$$ with natural parameters $$\btheta = \left[\begin{matrix}c-1\\-\frac1 b\end{matrix}\right]$$ All distributions in the exponential family have KL divergence: \begin{align} KL(q; p) &= g(\btheta_p) - g(\btheta_q) - (\btheta_p-\btheta_q) \cdot \nabla g(\btheta_q). \end{align} There's a really nice proof of that in: Frank Nielsen, École Polytechnique, and Richard Nock, Entropies and cross-entropies of exponential families.
Kullback–Leibler divergence between two gamma distributions The Gamma distribution is in the exponential family because its density can be expressed as: \begin{align} \newcommand{\mbx}{\mathbf{x}} \newcommand{\btheta}{\boldsymbol{\theta}} f(\mbx \mid \btheta)
15,444
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effects model?
I am not an expert in mixed effect modelling, but the question is much easier to answer if it is rephrased in hierarchical regression modelling context. So our observations have two indexes $P_{ij}$ and $F_{ij}$ with index $i$ representing class and $j$ members of the class. The hierarchical models let us fit linear regression, where coefficients vary across classes: $$Y_{ij}=\beta_{0i}+\beta_{1i}F_{ij}$$ This is our first level regression. The second level regression is done on the first regression coefficients: \begin{align*} \beta_{0i}&=\gamma_{00}+u_{0i}\\\\ \beta_{1i}&=\gamma_{01}+u_{1i} \end{align*} when we substitute this in first level regression we get \begin{align*} Y_{ij}&=(\gamma_{00}+u_{0i})+(\gamma_{01}+u_{1i})F_{ij}\\\\ &=\gamma_{00}+u_{0i}+u_{1i}F_{ij}+\gamma_{01}F_{ij} \end{align*} Here $\gamma$ are fixed effects and $u$ are random effects. Mixed models estimate $\gamma$ and variances of $u$. The model I've written down corresponds to lmer syntax P ~ (1+F|R) + F Now if we put $\beta_{1i}=\gamma_{01}$ without the random term we get \begin{align*} Y_{ij}=\gamma_{00}+u_{0i}+\gamma_{01}F_{ij} \end{align*} which corresponds to lmer syntax P ~ (1|R) + F So the question now becomes when can we exclude error term from the second level regression? The canonical answer is that when we are sure that the regressors (here we do not have any, but we can include them, they naturally are constant within classes) in the second level regression fully explain the variance of coefficients across classes. So in this particular case if coefficient of $F_{ij}$ does not vary, or alternatively the variance of $u_{1i}$ is very small we should entertain idea that we are probably better of with the first model. Note. I've only gave algebraic explanation, but I think having it in mind it is much easier to think of particular applied example.
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effect
I am not an expert in mixed effect modelling, but the question is much easier to answer if it is rephrased in hierarchical regression modelling context. So our observations have two indexes $P_{ij}$ a
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effects model? I am not an expert in mixed effect modelling, but the question is much easier to answer if it is rephrased in hierarchical regression modelling context. So our observations have two indexes $P_{ij}$ and $F_{ij}$ with index $i$ representing class and $j$ members of the class. The hierarchical models let us fit linear regression, where coefficients vary across classes: $$Y_{ij}=\beta_{0i}+\beta_{1i}F_{ij}$$ This is our first level regression. The second level regression is done on the first regression coefficients: \begin{align*} \beta_{0i}&=\gamma_{00}+u_{0i}\\\\ \beta_{1i}&=\gamma_{01}+u_{1i} \end{align*} when we substitute this in first level regression we get \begin{align*} Y_{ij}&=(\gamma_{00}+u_{0i})+(\gamma_{01}+u_{1i})F_{ij}\\\\ &=\gamma_{00}+u_{0i}+u_{1i}F_{ij}+\gamma_{01}F_{ij} \end{align*} Here $\gamma$ are fixed effects and $u$ are random effects. Mixed models estimate $\gamma$ and variances of $u$. The model I've written down corresponds to lmer syntax P ~ (1+F|R) + F Now if we put $\beta_{1i}=\gamma_{01}$ without the random term we get \begin{align*} Y_{ij}=\gamma_{00}+u_{0i}+\gamma_{01}F_{ij} \end{align*} which corresponds to lmer syntax P ~ (1|R) + F So the question now becomes when can we exclude error term from the second level regression? The canonical answer is that when we are sure that the regressors (here we do not have any, but we can include them, they naturally are constant within classes) in the second level regression fully explain the variance of coefficients across classes. So in this particular case if coefficient of $F_{ij}$ does not vary, or alternatively the variance of $u_{1i}$ is very small we should entertain idea that we are probably better of with the first model. Note. I've only gave algebraic explanation, but I think having it in mind it is much easier to think of particular applied example.
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effect I am not an expert in mixed effect modelling, but the question is much easier to answer if it is rephrased in hierarchical regression modelling context. So our observations have two indexes $P_{ij}$ a
15,445
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effects model?
You can think of a "Fixed effect" as a "random effect" with a variance component of zero. So, a simple answer to why you wouldn't let fixed effect to vary, is insufficient evidence for a "large enough" variance component. The evidence should come from both the prior information and the data. This is in line with the basic "occam's razor" principle: don't make your model more complex than it needs to be. I tend to think of linear mixed models in the following way, write out a multiple regression as follows: $$Y=X\beta+Zu+e$$ So $X\beta$ is the "fixed" part of the model, $Zu$ is the "random" part and $e$ is the OLS style residual. We have $u\sim N(0,D(\theta))$, for "random effect" variance parameters $\theta$ and $e\sim N(0,\sigma^{2}I)$. This gives the standard results $(Zu+e)\sim N(0,ZD(\theta)Z^{T}+\sigma^{2}I)$, which means we have: $$Y\sim N(X\beta,ZD(\theta)Z^{T}+\sigma^{2}I)$$ Compare this to the OLS regression (which has $Z=0$) and we get: $$Y\sim N(X\beta,\sigma^{2}I)$$ So the "random" part of the model can be seen as a way of specifying prior information about the correlation structure of the noise or error component in the model. OLS basically assumes that any one error from the fixed part of the model in one case is useless for predicting any other error, even if we knew the fixed part of the model with certainty. Adding a random effect is basically saying that you think some errors are likely to be useful in predicting other errors.
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effect
You can think of a "Fixed effect" as a "random effect" with a variance component of zero. So, a simple answer to why you wouldn't let fixed effect to vary, is insufficient evidence for a "large enough
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effects model? You can think of a "Fixed effect" as a "random effect" with a variance component of zero. So, a simple answer to why you wouldn't let fixed effect to vary, is insufficient evidence for a "large enough" variance component. The evidence should come from both the prior information and the data. This is in line with the basic "occam's razor" principle: don't make your model more complex than it needs to be. I tend to think of linear mixed models in the following way, write out a multiple regression as follows: $$Y=X\beta+Zu+e$$ So $X\beta$ is the "fixed" part of the model, $Zu$ is the "random" part and $e$ is the OLS style residual. We have $u\sim N(0,D(\theta))$, for "random effect" variance parameters $\theta$ and $e\sim N(0,\sigma^{2}I)$. This gives the standard results $(Zu+e)\sim N(0,ZD(\theta)Z^{T}+\sigma^{2}I)$, which means we have: $$Y\sim N(X\beta,ZD(\theta)Z^{T}+\sigma^{2}I)$$ Compare this to the OLS regression (which has $Z=0$) and we get: $$Y\sim N(X\beta,\sigma^{2}I)$$ So the "random" part of the model can be seen as a way of specifying prior information about the correlation structure of the noise or error component in the model. OLS basically assumes that any one error from the fixed part of the model in one case is useless for predicting any other error, even if we knew the fixed part of the model with certainty. Adding a random effect is basically saying that you think some errors are likely to be useful in predicting other errors.
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effect You can think of a "Fixed effect" as a "random effect" with a variance component of zero. So, a simple answer to why you wouldn't let fixed effect to vary, is insufficient evidence for a "large enough
15,446
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effects model?
This is quite an old question with some very good answers, however I think it can benefit from a new answer to address a more pragmatic perspective. When should one not permit a fixed effect to vary across levels of a random effect ? I won't address the issues already described in the other answers, instead I will refer to the now-famous, though I would rather say "infamous" paper by Barr et al. (2013) often just referred to as "Keep it maximal". Barr, D.J., Levy, R., Scheepers, C. and Tily, H.J., 2013. Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68(3):255-278. https://doi.org/10.1016/j.jml.2012.11.001 In this paper the authors argue that all fixed effects should be allowed to vary across levels of the grouping factors (random intercepts). Their argument is quite compelling - basically that by not allowing them to vary, it is imposing constraints on the model. This is well-described in the other answers. However, there are potentially serious problems with this approach, which are described by Bates el al. (2015): Bates, D., Kliegl, R., Vasishth, S. and Baayen, H., 2015. Parsimonious mixed models. arXiv preprint arXiv:1506.04967 It is worth noting here that Bates is the primary author of the lme4 package for fitting mixed models in R, which is probably the most widely used package for such models. Bates et al. note that in many real-world applications, the data simply won't support a maximal random effects structure, often because there are insufficient numbers of observations in each cluster for the relevant variables. This can manifest itself in models that fail to converge, or are singular in the random effects. The large number of questions on this site about such models attests to that. They also note that Barr et al. used a relatively simple simulation, with "well-behaved" random effects, as the basis for their paper. Instead Bates et al. suggest the following approach: We proposed (1) to use PCA to determine the dimensionality of the variance-covariance matrix of the random-effect structure, (2) to initially constrain correlation parameters to zero, especially when an initial attempt to fit a maximal model does not converge, and (3) to drop non-significant variance components and their associated correlation parameters from the model In the same paper, they also note: Importantly, failure to converge is not due to defects of the estimation algorithm, but is a straightforward consequence of attempting to fit a model that is too complex to be properly supported by the data. And: maximal models are not necessary to protect against anti-conservative conclusions. This protection is fully provided by comprehensive models that are guided by realistic expectations about the complexity that the data can support. In statistics, as elsewhere in science, parsimony is a virtue, not a vice. Bates et al (2015) From a more applied perspective, a further consideration that should be made is whether or not, the data generation process, the biological/physical/chemical theory that underlies the data, should guide the analyst towards specifying the random effects structure.
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effect
This is quite an old question with some very good answers, however I think it can benefit from a new answer to address a more pragmatic perspective. When should one not permit a fixed effect to vary
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effects model? This is quite an old question with some very good answers, however I think it can benefit from a new answer to address a more pragmatic perspective. When should one not permit a fixed effect to vary across levels of a random effect ? I won't address the issues already described in the other answers, instead I will refer to the now-famous, though I would rather say "infamous" paper by Barr et al. (2013) often just referred to as "Keep it maximal". Barr, D.J., Levy, R., Scheepers, C. and Tily, H.J., 2013. Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68(3):255-278. https://doi.org/10.1016/j.jml.2012.11.001 In this paper the authors argue that all fixed effects should be allowed to vary across levels of the grouping factors (random intercepts). Their argument is quite compelling - basically that by not allowing them to vary, it is imposing constraints on the model. This is well-described in the other answers. However, there are potentially serious problems with this approach, which are described by Bates el al. (2015): Bates, D., Kliegl, R., Vasishth, S. and Baayen, H., 2015. Parsimonious mixed models. arXiv preprint arXiv:1506.04967 It is worth noting here that Bates is the primary author of the lme4 package for fitting mixed models in R, which is probably the most widely used package for such models. Bates et al. note that in many real-world applications, the data simply won't support a maximal random effects structure, often because there are insufficient numbers of observations in each cluster for the relevant variables. This can manifest itself in models that fail to converge, or are singular in the random effects. The large number of questions on this site about such models attests to that. They also note that Barr et al. used a relatively simple simulation, with "well-behaved" random effects, as the basis for their paper. Instead Bates et al. suggest the following approach: We proposed (1) to use PCA to determine the dimensionality of the variance-covariance matrix of the random-effect structure, (2) to initially constrain correlation parameters to zero, especially when an initial attempt to fit a maximal model does not converge, and (3) to drop non-significant variance components and their associated correlation parameters from the model In the same paper, they also note: Importantly, failure to converge is not due to defects of the estimation algorithm, but is a straightforward consequence of attempting to fit a model that is too complex to be properly supported by the data. And: maximal models are not necessary to protect against anti-conservative conclusions. This protection is fully provided by comprehensive models that are guided by realistic expectations about the complexity that the data can support. In statistics, as elsewhere in science, parsimony is a virtue, not a vice. Bates et al (2015) From a more applied perspective, a further consideration that should be made is whether or not, the data generation process, the biological/physical/chemical theory that underlies the data, should guide the analyst towards specifying the random effects structure.
When should I *not* permit a fixed effect to vary across levels of a random effect in a mixed effect This is quite an old question with some very good answers, however I think it can benefit from a new answer to address a more pragmatic perspective. When should one not permit a fixed effect to vary
15,447
Resources for an R user who must learn SAS
15 months ago, I started my current job as someone who had been using R exclusively for about 3 years; I had used SAS in my first-ever stats class, loathed it, and never touched it again until I started here. Here's what has been helpful for me, and what hasn't: Helpful: Colleagues' code. This is the single most useful source, for me. Some of it was very good code, some of it was very bad code, but all of it showed me how to think in SAS. SUGI. Though they are often almost unbearably corny, there is a vast wealth of these little how-to papers all over the Internet. You don't need to look for them; just Google, and they'll present themselves to you. The O'Reilly SQL Pocket Guide, by Gennick. I dodge a lot of SAS coding by using PROC SQL for data manipulation and summarization. This is cheating, and I don't care. This paper explaining formats and informats (PDF). This is without a doubt the least-intuitive part of SAS for me. UCLA's Academic Technology Services' Statistical Computing site. UCLA has heaps of great introductory material here, and there's a lot of parallel material between its R and SAS sections (like these analysis examples). Not helpful: Anything I've ever read that is intended for people transitioning between R and SAS. I have the "R and SAS" book from Kleinman and Horton, which I've opened twice only to not find the answers I needed. I've read a few other guides here and there. Maybe it's just my learning style, but none of this stuff has ever stuck with me, and I inevitably end up googling for it once I actually need it. You'll be okay, though. Just read your colleagues' code, ask questions here and on StackOverflow, and - whatever you do - don't try to plot anything.
Resources for an R user who must learn SAS
15 months ago, I started my current job as someone who had been using R exclusively for about 3 years; I had used SAS in my first-ever stats class, loathed it, and never touched it again until I start
Resources for an R user who must learn SAS 15 months ago, I started my current job as someone who had been using R exclusively for about 3 years; I had used SAS in my first-ever stats class, loathed it, and never touched it again until I started here. Here's what has been helpful for me, and what hasn't: Helpful: Colleagues' code. This is the single most useful source, for me. Some of it was very good code, some of it was very bad code, but all of it showed me how to think in SAS. SUGI. Though they are often almost unbearably corny, there is a vast wealth of these little how-to papers all over the Internet. You don't need to look for them; just Google, and they'll present themselves to you. The O'Reilly SQL Pocket Guide, by Gennick. I dodge a lot of SAS coding by using PROC SQL for data manipulation and summarization. This is cheating, and I don't care. This paper explaining formats and informats (PDF). This is without a doubt the least-intuitive part of SAS for me. UCLA's Academic Technology Services' Statistical Computing site. UCLA has heaps of great introductory material here, and there's a lot of parallel material between its R and SAS sections (like these analysis examples). Not helpful: Anything I've ever read that is intended for people transitioning between R and SAS. I have the "R and SAS" book from Kleinman and Horton, which I've opened twice only to not find the answers I needed. I've read a few other guides here and there. Maybe it's just my learning style, but none of this stuff has ever stuck with me, and I inevitably end up googling for it once I actually need it. You'll be okay, though. Just read your colleagues' code, ask questions here and on StackOverflow, and - whatever you do - don't try to plot anything.
Resources for an R user who must learn SAS 15 months ago, I started my current job as someone who had been using R exclusively for about 3 years; I had used SAS in my first-ever stats class, loathed it, and never touched it again until I start
15,448
Resources for an R user who must learn SAS
A couple things to add to what @matt said: In addition to SUGI (which is now renamed SAS Global Forum, and will be held this year in Las Vegas) there are numerous local and regional SAS user groups. These are smaller, more intimate, and (usually) a lot cheaper. Some local groups are even free. See here SAS-L. This is a mailing list for SAS questions. It is quite friendly, and some of the participants are among the best SAS programmers there are. The book SAS and R: Data Management, Statistical Analysis and Graphics by Kleinman and Horton. Look up what you want to do in the R index, and you'll find how to do it in SAS as well. Sort of like a inter-language dictionary.
Resources for an R user who must learn SAS
A couple things to add to what @matt said: In addition to SUGI (which is now renamed SAS Global Forum, and will be held this year in Las Vegas) there are numerous local and regional SAS user groups.
Resources for an R user who must learn SAS A couple things to add to what @matt said: In addition to SUGI (which is now renamed SAS Global Forum, and will be held this year in Las Vegas) there are numerous local and regional SAS user groups. These are smaller, more intimate, and (usually) a lot cheaper. Some local groups are even free. See here SAS-L. This is a mailing list for SAS questions. It is quite friendly, and some of the participants are among the best SAS programmers there are. The book SAS and R: Data Management, Statistical Analysis and Graphics by Kleinman and Horton. Look up what you want to do in the R index, and you'll find how to do it in SAS as well. Sort of like a inter-language dictionary.
Resources for an R user who must learn SAS A couple things to add to what @matt said: In addition to SUGI (which is now renamed SAS Global Forum, and will be held this year in Las Vegas) there are numerous local and regional SAS user groups.
15,449
Resources for an R user who must learn SAS
In addition to Matt Parkers excellent advice (particularly about reading colleagues code), the actual SAS documentation can be surprisingly helpful (once you've figured out the name of what you want): http://support.sas.com/documentation/ And the Global Forum/SUGI proceedings are available here: http://support.sas.com/events/sasglobalforum/previous/online.html
Resources for an R user who must learn SAS
In addition to Matt Parkers excellent advice (particularly about reading colleagues code), the actual SAS documentation can be surprisingly helpful (once you've figured out the name of what you want):
Resources for an R user who must learn SAS In addition to Matt Parkers excellent advice (particularly about reading colleagues code), the actual SAS documentation can be surprisingly helpful (once you've figured out the name of what you want): http://support.sas.com/documentation/ And the Global Forum/SUGI proceedings are available here: http://support.sas.com/events/sasglobalforum/previous/online.html
Resources for an R user who must learn SAS In addition to Matt Parkers excellent advice (particularly about reading colleagues code), the actual SAS documentation can be surprisingly helpful (once you've figured out the name of what you want):
15,450
Removing borders in R plots for achieving Tufte's axis
Add bty="n" in both plot commands. For time series, add frame.plot=FALSE for the same effect. For fancier Tufte axes, see http://www.cl.cam.ac.uk/~sjm217/projects/graphics/
Removing borders in R plots for achieving Tufte's axis
Add bty="n" in both plot commands. For time series, add frame.plot=FALSE for the same effect. For fancier Tufte axes, see http://www.cl.cam.ac.uk/~sjm217/projects/graphics/
Removing borders in R plots for achieving Tufte's axis Add bty="n" in both plot commands. For time series, add frame.plot=FALSE for the same effect. For fancier Tufte axes, see http://www.cl.cam.ac.uk/~sjm217/projects/graphics/
Removing borders in R plots for achieving Tufte's axis Add bty="n" in both plot commands. For time series, add frame.plot=FALSE for the same effect. For fancier Tufte axes, see http://www.cl.cam.ac.uk/~sjm217/projects/graphics/
15,451
Removing borders in R plots for achieving Tufte's axis
This is straightforward to do, you just include the argument axes=FALSE. Consider: x <- 1:100 y1 <- rnorm(100) y2 <- rnorm(100) + 100 windows() par(mar=c(5,5,5,5)) plot(x, y1, pch=0, type="b", col="red", yaxt="n", ylim=c(-8,2), ylab="", axes=F) axis(side=2, at=c(-2,0,2)) mtext("red line", side = 2, line=2.5, at=0) par(new=T) plot(x, y2, pch=1, type="b", col="blue", yaxt="n", ylim=c(98,108), ylab="", axes=F) axis(side=4, at=c(98,100,102), labels=c("98%","100%","102%")) mtext("blue line", side=4, line=2.5, at=100) Note that this works equally well for histograms: windows() hist(y1, axes=F)
Removing borders in R plots for achieving Tufte's axis
This is straightforward to do, you just include the argument axes=FALSE. Consider: x <- 1:100 y1 <- rnorm(100) y2 <- rnorm(100) + 100 windows() par(mar=c(5,5,5,5)) plot(x, y1, pch=0, type="b",
Removing borders in R plots for achieving Tufte's axis This is straightforward to do, you just include the argument axes=FALSE. Consider: x <- 1:100 y1 <- rnorm(100) y2 <- rnorm(100) + 100 windows() par(mar=c(5,5,5,5)) plot(x, y1, pch=0, type="b", col="red", yaxt="n", ylim=c(-8,2), ylab="", axes=F) axis(side=2, at=c(-2,0,2)) mtext("red line", side = 2, line=2.5, at=0) par(new=T) plot(x, y2, pch=1, type="b", col="blue", yaxt="n", ylim=c(98,108), ylab="", axes=F) axis(side=4, at=c(98,100,102), labels=c("98%","100%","102%")) mtext("blue line", side=4, line=2.5, at=100) Note that this works equally well for histograms: windows() hist(y1, axes=F)
Removing borders in R plots for achieving Tufte's axis This is straightforward to do, you just include the argument axes=FALSE. Consider: x <- 1:100 y1 <- rnorm(100) y2 <- rnorm(100) + 100 windows() par(mar=c(5,5,5,5)) plot(x, y1, pch=0, type="b",
15,452
Removing borders in R plots for achieving Tufte's axis
If you use par(bty = 'n') Before calling plot that will fix it for zoo. It might also fix it for a variety of situations where it isn't passable to the plotting command. (Check out bty option in the par() help for other kinds of frames for the plot)
Removing borders in R plots for achieving Tufte's axis
If you use par(bty = 'n') Before calling plot that will fix it for zoo. It might also fix it for a variety of situations where it isn't passable to the plotting command. (Check out bty option in th
Removing borders in R plots for achieving Tufte's axis If you use par(bty = 'n') Before calling plot that will fix it for zoo. It might also fix it for a variety of situations where it isn't passable to the plotting command. (Check out bty option in the par() help for other kinds of frames for the plot)
Removing borders in R plots for achieving Tufte's axis If you use par(bty = 'n') Before calling plot that will fix it for zoo. It might also fix it for a variety of situations where it isn't passable to the plotting command. (Check out bty option in th
15,453
Removing borders in R plots for achieving Tufte's axis
I am answering the more general question of removing borders in plots, without reference to Tufte. For a histogram I did not find that btn='n' got rid of the border. A solution that does work for histograms and should work for all types of plots is to set the line type for the border to invisible: lty="blank"
Removing borders in R plots for achieving Tufte's axis
I am answering the more general question of removing borders in plots, without reference to Tufte. For a histogram I did not find that btn='n' got rid of the border. A solution that does work for hist
Removing borders in R plots for achieving Tufte's axis I am answering the more general question of removing borders in plots, without reference to Tufte. For a histogram I did not find that btn='n' got rid of the border. A solution that does work for histograms and should work for all types of plots is to set the line type for the border to invisible: lty="blank"
Removing borders in R plots for achieving Tufte's axis I am answering the more general question of removing borders in plots, without reference to Tufte. For a histogram I did not find that btn='n' got rid of the border. A solution that does work for hist
15,454
Is Fig 3.6 in Elements of Statistical Learning correct?
It shows a decreasing relationship between subset size $k$ and mean squared error (MSE) of the true parameters, $\beta$ and the estimates $\hat{\beta}(k)$. The plot shows the results of alternative subset selection methods. The image caption explains the experimental design: there are 10 elements of $\beta$ which are nonzero. The remaining 21 elements are zero. The ideal subset selection method will correctly report which $\beta$ are nonzero and which $\beta$ are zero; in other words, no features are incorrectly included, and no features are incorrectly excluded. Omitted variable bias occurs when one or more features in the data generating process is omitted. Biased parameter estimates have expected values which do not equal their true values (this is the definition of bias), so the choice to plot $\mathbb{E}\|\beta -\hat{\beta}(k) \|^2$ makes sense. (Note that the definition of bias does not exactly coincide with this experimental setting because $\beta$ is also random.) In other words, the plot shows you how incorrect estimates are for various $k$ for various subset selection methods. When $k$ is too small (in this case, when $k<10$) the parameter estimates are biased, which is why the graph shows large values of $\mathbb{E}\|\beta -\hat{\beta}(k) \|^2$for small $k$. Clearly, this shouldn't be the case - adding more variables to a linear model doesn't imply better estimates of the true parameters. Fortunately, that's not what the plot shows. Instead, the plot shows that employing subset selection methods can produce correct or incorrect results depending on the choice of $k$. However, this plot does show a special case when adding additional features does improve the parameter estimates. If one builds a model that exhibits omitted variable bias, then the model which includes those variables will achieve a lower estimation error of the parameters because omitted variable bias is not present. What adding more variables does imply is a lower training error, i.e. lower residual sum of squares. You're confusing the demonstration in this passage with an alternative which does not employ subset selection. In general, estimating a regression with a larger basis decreases the residual error as measured using the training data; that's not what's happening here. Is the $y$-axis labelled incorrectly? In particular, is it possible that the $y$ axis shows Residual Sum of Squares instead of $\mathbb{E}\|\beta -\hat{\beta}(k) \|^2$? I don't think so; the line of reasoning posited in the original post does not itself establish that the label is incorrect. Sextus' experiments find a similar pattern; it's not identical, but the shape of the curve is similar enough. As an aside, I think that since this plot displays empirical results from an experiment, it would be clearer to write out the estimator used for the expectation, per Cagdas Ozgenc's suggestion. Is Figure 3.6 in ESL correct? The only definitive way to answer this question is to obtain the code used to generate the graph. The code is not publicly available or distributed by the authors. Without access to the code used in the procedure, it's always possible that there was some mistake in labeling the graph, or in the scale/location of the data or coefficients; the fact that Sextus has had problems recreating the graph using the procedure described in the caption provides some circumstantial evidence that the caption might not be completely accurate. One might argue that these reproducibility problems support a hypothesis that the labels themselves or the graphed points may be incorrect. On the other hand, it's possible that the description is incorrect but the label itself is correct nonetheless. A different edition of the book publishes a different image. But the existence of a different image does not imply that either one is correct.
Is Fig 3.6 in Elements of Statistical Learning correct?
It shows a decreasing relationship between subset size $k$ and mean squared error (MSE) of the true parameters, $\beta$ and the estimates $\hat{\beta}(k)$. The plot shows the results of alternative s
Is Fig 3.6 in Elements of Statistical Learning correct? It shows a decreasing relationship between subset size $k$ and mean squared error (MSE) of the true parameters, $\beta$ and the estimates $\hat{\beta}(k)$. The plot shows the results of alternative subset selection methods. The image caption explains the experimental design: there are 10 elements of $\beta$ which are nonzero. The remaining 21 elements are zero. The ideal subset selection method will correctly report which $\beta$ are nonzero and which $\beta$ are zero; in other words, no features are incorrectly included, and no features are incorrectly excluded. Omitted variable bias occurs when one or more features in the data generating process is omitted. Biased parameter estimates have expected values which do not equal their true values (this is the definition of bias), so the choice to plot $\mathbb{E}\|\beta -\hat{\beta}(k) \|^2$ makes sense. (Note that the definition of bias does not exactly coincide with this experimental setting because $\beta$ is also random.) In other words, the plot shows you how incorrect estimates are for various $k$ for various subset selection methods. When $k$ is too small (in this case, when $k<10$) the parameter estimates are biased, which is why the graph shows large values of $\mathbb{E}\|\beta -\hat{\beta}(k) \|^2$for small $k$. Clearly, this shouldn't be the case - adding more variables to a linear model doesn't imply better estimates of the true parameters. Fortunately, that's not what the plot shows. Instead, the plot shows that employing subset selection methods can produce correct or incorrect results depending on the choice of $k$. However, this plot does show a special case when adding additional features does improve the parameter estimates. If one builds a model that exhibits omitted variable bias, then the model which includes those variables will achieve a lower estimation error of the parameters because omitted variable bias is not present. What adding more variables does imply is a lower training error, i.e. lower residual sum of squares. You're confusing the demonstration in this passage with an alternative which does not employ subset selection. In general, estimating a regression with a larger basis decreases the residual error as measured using the training data; that's not what's happening here. Is the $y$-axis labelled incorrectly? In particular, is it possible that the $y$ axis shows Residual Sum of Squares instead of $\mathbb{E}\|\beta -\hat{\beta}(k) \|^2$? I don't think so; the line of reasoning posited in the original post does not itself establish that the label is incorrect. Sextus' experiments find a similar pattern; it's not identical, but the shape of the curve is similar enough. As an aside, I think that since this plot displays empirical results from an experiment, it would be clearer to write out the estimator used for the expectation, per Cagdas Ozgenc's suggestion. Is Figure 3.6 in ESL correct? The only definitive way to answer this question is to obtain the code used to generate the graph. The code is not publicly available or distributed by the authors. Without access to the code used in the procedure, it's always possible that there was some mistake in labeling the graph, or in the scale/location of the data or coefficients; the fact that Sextus has had problems recreating the graph using the procedure described in the caption provides some circumstantial evidence that the caption might not be completely accurate. One might argue that these reproducibility problems support a hypothesis that the labels themselves or the graphed points may be incorrect. On the other hand, it's possible that the description is incorrect but the label itself is correct nonetheless. A different edition of the book publishes a different image. But the existence of a different image does not imply that either one is correct.
Is Fig 3.6 in Elements of Statistical Learning correct? It shows a decreasing relationship between subset size $k$ and mean squared error (MSE) of the true parameters, $\beta$ and the estimates $\hat{\beta}(k)$. The plot shows the results of alternative s
15,455
Is Fig 3.6 in Elements of Statistical Learning correct?
adding more variables to a linear model doesn't imply better estimates of the true parameters This is not just estimating variables, but also variable selection. When you only subselect <10 variables, then you are inevitably gonna make an error. That is why the error decreases when you are choosing a larger size for the subset. Because more coefficients, which are likely coefficients from the true model, are being estimated (instead of left equal to zero). The decrease of the error goes a bit further than $k=10$ because of the high correlation between the variables. The strongest improvement happens before k=10. But with $k=10$ you are not there yet, and you are gonna select occasionally the wrong coefficients from the true model. In addition, the additional variables may have some regularizing effect. Note that after some point, around $k=16$, the error goes up when adding more variables. Reproduction of the graph In the R-code at the end I am trying to reproduce the graph for the forward stepwise case. (this is also the question here: Recreating figure from Elements of Statistical Learning) I can make the figure look similar But, I needed to make some adjustment to the generation, using $\beta \sim N(1,0.4)$ instead of $\beta \sim N(0,0.4)$ (and still I do not get the same as the figure which starts at 0.95 and drops down to 0.65, while the MSE computed with the code here is much lower instead). Still, the shape is qualitatively the same. The error in this graph is not so much due to bias: I wanted to split the mean square error into bias and variance (by computing the coefficient's mean error and variance of the error). However, the bias is very low! This is due to the high correlation between the parameters. When you have a subset with only 1 parameter, then the selected parameter in that subset will compensate for the missing parameters (it can do so because it is highly correlated). The amount that the other parameters are too low will be more or less the amount that the selected parameter will be too high. So on average a parameter will be more or less as much too high as too low. The graph above is made with a correlation 0.15 instead of 0.85. In addition, I used a fixed $X$ and $\beta$ (Otherwise the bias would average to zero, more explained about that further). Distribution of the error of the parameter estimate Below you see how the error in the parameter estimate $\hat\beta_1- \beta_1$ is distributed as a function of the subset size. This makes it easier to see why the change in the mean square error behaves like it does. Note the following features There is a single peak for small subset sizes. This is because the parameter is often not included in the subset and the estimate $\hat\beta$ will be zero making the error $\hat\beta - \beta$ equal to $-\beta$. This peak decreases in size as the subset size increases and the probability for the parameter to be included increases. There is a more or less Gaussian distributed component that increases in size when the single peak decreases in size. This is the error when the parameter is included in the subset. For small subset sizes the error in this component is not centered around zero. The reason is that the parameter needs to compensate for the ommission of the other parameter (to which it is highly correlated). This makes that a computation of the bias is actually very low. It is the variance that is high. The example above is for fixed $\beta$ and $X$. If you would change the $\beta$ for each simulation then the bias would be every time different. If you then compute the bias as $\mathbb{E}(\hat \beta - \beta)$ then you get very close to zero. library(MASS) ### function to do stepforward regression ### adding variables with best increase in RSS stepforward <- function(Y,X, intercept) { kl <- length(X[1,]) ### number of columns inset <- c() outset <- 1:kl best_RSS <- sum(Y^2) ### outer loop increasing subset size for (k in 1:kl) { beststep_RSS <- best_RSS ### RSS to beat beststep_par <- 0 ### inner looping trying all variables that can be added for (par in outset) { ### create a subset to test step_set <- c(inset,par) step_data <- data.frame(Y=Y,X=X[,step_set]) ### perform model with subset if (intercept) { step_mod <- lm(Y ~ . + 1, data = step_data) } else { step_mod <- lm(Y ~ . + 0, data = step_data) } step_RSS <- sum(step_mod$residuals^2) ### compare if it is an improvement if (step_RSS <= beststep_RSS) { beststep_RSS <- step_RSS beststep_par <- par } } bestRSS <- beststep_RSS inset <- c(inset,beststep_par) outset[-which(outset == beststep_par)] } return(inset) } get_error <- function(X = NULL, beta = NULL, intercept = 0) { ### 31 random X variables, standard normal if (is.null(X)) { X <- mvrnorm(300,rep(0,31), M) } ### 10 random beta coefficients 21 zero coefficients if (is.null(beta)) { beta <- c(rnorm(10,1,0.4^0.5),rep(0,21)) } ### Y with added noise Y <- (X %*% beta) + rnorm(300,0,6.25^0.5) ### get step order step_order <- stepforward(Y,X, intercept) ### error computation l <- 10 error <- matrix(rep(0,31*31),31) ### this variable will store error for 31 submodel sizes for (l in 1:31) { ### subdata Z <- X[,step_order[1:l]] sub_data <- data.frame(Y=Y,Z=Z) ### compute model if (intercept) { sub_mod <- lm(Y ~ . + 1, data = sub_data) } else { sub_mod <- lm(Y ~ . + 0, data = sub_data) } ### compute error in coefficients coef <- rep(0,31) if (intercept) { coef[step_order[1:l]] <- sub_mod$coefficients[-1] } else { coef[step_order[1:l]] <- sub_mod$coefficients[] } error[l,] <- (coef - beta) } return(error) } ### correlation matrix for X M <- matrix(rep(0.15,31^2),31) for (i in 1:31) { M[i,i] = 1 } ### perform 50 times the model set.seed(1) X <- mvrnorm(300,rep(0,31), M) beta <- c(rnorm(10,1,0.4^0.5),rep(0,21)) nrep <- 500 me <- replicate(nrep,get_error(X,beta, intercept = 1)) ### this line uses fixed X and beta ###me <- replicate(nrep,get_error(X,beta, intercept = 1)) ### this line uses random X and fixed beta ###me <- replicate(nrep,get_error(X,beta, intercept = 1)) ### random X and beta each replicate ### storage for error statistics per coefficient and per k mean_error <- matrix(rep(0,31^2),31) mean_MSE <- matrix(rep(0,31^2),31) mean_var <- matrix(rep(0,31^2),31) ### compute error statistics ### MSE, and bias + variance for each coefficient seperately ### k relates to the subset size ### i refers to the coefficient ### averaging is done over the multiple simulations for (i in 1:31) { mean_error[i,] <- sapply(1:31, FUN = function(k) mean(me[k,i,])) mean_MSE[i,] <- sapply(1:31, FUN = function(k) mean(me[k,i,]^2)) mean_var[i,] <- mean_MSE[i,] - mean_error[i,]^2 } ### plotting curves ### colMeans averages over the multiple coefficients layout(matrix(1)) plot(1:31,colMeans(mean_MSE[1:31,]), ylim = c(0,0.4), xlim = c(1,31), type = "l", lwd = 2, xlab = "Subset size k", ylab = "mean square error of parameters", xaxs = "i", yaxs = "i") points(1:31,colMeans(mean_MSE[1:31,]), pch = 21 , col = 1, bg = 0, cex = 0.7) lines(1:31,colMeans(mean_var[1:31,]), lty = 2) lines(1:31,colMeans(mean_error[1:31,]^2), lty = 3) legend(31,0.4, c("MSE", "variance component", "bias component"), lty = c(1,2,3), lwd = c(2,1,1), pch = c(21,NA,NA), col = 1, pt.bg = 0, xjust = 1, cex = 0.7) ### plotting histogram layout(matrix(1:5,5)) par(mar = c(4,4,2,1)) xpar = 1 for (col in c(1,4,7,10,13)) { hist(me[col,xpar,], breaks = seq(-7,7,0.05), xlim = c(-1,1), ylim = c(0,500), xlab = "", ylab = "", main=paste0("error in parameter ",xpar," for subset size ",col), ) }
Is Fig 3.6 in Elements of Statistical Learning correct?
adding more variables to a linear model doesn't imply better estimates of the true parameters This is not just estimating variables, but also variable selection. When you only subselect <10 variables
Is Fig 3.6 in Elements of Statistical Learning correct? adding more variables to a linear model doesn't imply better estimates of the true parameters This is not just estimating variables, but also variable selection. When you only subselect <10 variables, then you are inevitably gonna make an error. That is why the error decreases when you are choosing a larger size for the subset. Because more coefficients, which are likely coefficients from the true model, are being estimated (instead of left equal to zero). The decrease of the error goes a bit further than $k=10$ because of the high correlation between the variables. The strongest improvement happens before k=10. But with $k=10$ you are not there yet, and you are gonna select occasionally the wrong coefficients from the true model. In addition, the additional variables may have some regularizing effect. Note that after some point, around $k=16$, the error goes up when adding more variables. Reproduction of the graph In the R-code at the end I am trying to reproduce the graph for the forward stepwise case. (this is also the question here: Recreating figure from Elements of Statistical Learning) I can make the figure look similar But, I needed to make some adjustment to the generation, using $\beta \sim N(1,0.4)$ instead of $\beta \sim N(0,0.4)$ (and still I do not get the same as the figure which starts at 0.95 and drops down to 0.65, while the MSE computed with the code here is much lower instead). Still, the shape is qualitatively the same. The error in this graph is not so much due to bias: I wanted to split the mean square error into bias and variance (by computing the coefficient's mean error and variance of the error). However, the bias is very low! This is due to the high correlation between the parameters. When you have a subset with only 1 parameter, then the selected parameter in that subset will compensate for the missing parameters (it can do so because it is highly correlated). The amount that the other parameters are too low will be more or less the amount that the selected parameter will be too high. So on average a parameter will be more or less as much too high as too low. The graph above is made with a correlation 0.15 instead of 0.85. In addition, I used a fixed $X$ and $\beta$ (Otherwise the bias would average to zero, more explained about that further). Distribution of the error of the parameter estimate Below you see how the error in the parameter estimate $\hat\beta_1- \beta_1$ is distributed as a function of the subset size. This makes it easier to see why the change in the mean square error behaves like it does. Note the following features There is a single peak for small subset sizes. This is because the parameter is often not included in the subset and the estimate $\hat\beta$ will be zero making the error $\hat\beta - \beta$ equal to $-\beta$. This peak decreases in size as the subset size increases and the probability for the parameter to be included increases. There is a more or less Gaussian distributed component that increases in size when the single peak decreases in size. This is the error when the parameter is included in the subset. For small subset sizes the error in this component is not centered around zero. The reason is that the parameter needs to compensate for the ommission of the other parameter (to which it is highly correlated). This makes that a computation of the bias is actually very low. It is the variance that is high. The example above is for fixed $\beta$ and $X$. If you would change the $\beta$ for each simulation then the bias would be every time different. If you then compute the bias as $\mathbb{E}(\hat \beta - \beta)$ then you get very close to zero. library(MASS) ### function to do stepforward regression ### adding variables with best increase in RSS stepforward <- function(Y,X, intercept) { kl <- length(X[1,]) ### number of columns inset <- c() outset <- 1:kl best_RSS <- sum(Y^2) ### outer loop increasing subset size for (k in 1:kl) { beststep_RSS <- best_RSS ### RSS to beat beststep_par <- 0 ### inner looping trying all variables that can be added for (par in outset) { ### create a subset to test step_set <- c(inset,par) step_data <- data.frame(Y=Y,X=X[,step_set]) ### perform model with subset if (intercept) { step_mod <- lm(Y ~ . + 1, data = step_data) } else { step_mod <- lm(Y ~ . + 0, data = step_data) } step_RSS <- sum(step_mod$residuals^2) ### compare if it is an improvement if (step_RSS <= beststep_RSS) { beststep_RSS <- step_RSS beststep_par <- par } } bestRSS <- beststep_RSS inset <- c(inset,beststep_par) outset[-which(outset == beststep_par)] } return(inset) } get_error <- function(X = NULL, beta = NULL, intercept = 0) { ### 31 random X variables, standard normal if (is.null(X)) { X <- mvrnorm(300,rep(0,31), M) } ### 10 random beta coefficients 21 zero coefficients if (is.null(beta)) { beta <- c(rnorm(10,1,0.4^0.5),rep(0,21)) } ### Y with added noise Y <- (X %*% beta) + rnorm(300,0,6.25^0.5) ### get step order step_order <- stepforward(Y,X, intercept) ### error computation l <- 10 error <- matrix(rep(0,31*31),31) ### this variable will store error for 31 submodel sizes for (l in 1:31) { ### subdata Z <- X[,step_order[1:l]] sub_data <- data.frame(Y=Y,Z=Z) ### compute model if (intercept) { sub_mod <- lm(Y ~ . + 1, data = sub_data) } else { sub_mod <- lm(Y ~ . + 0, data = sub_data) } ### compute error in coefficients coef <- rep(0,31) if (intercept) { coef[step_order[1:l]] <- sub_mod$coefficients[-1] } else { coef[step_order[1:l]] <- sub_mod$coefficients[] } error[l,] <- (coef - beta) } return(error) } ### correlation matrix for X M <- matrix(rep(0.15,31^2),31) for (i in 1:31) { M[i,i] = 1 } ### perform 50 times the model set.seed(1) X <- mvrnorm(300,rep(0,31), M) beta <- c(rnorm(10,1,0.4^0.5),rep(0,21)) nrep <- 500 me <- replicate(nrep,get_error(X,beta, intercept = 1)) ### this line uses fixed X and beta ###me <- replicate(nrep,get_error(X,beta, intercept = 1)) ### this line uses random X and fixed beta ###me <- replicate(nrep,get_error(X,beta, intercept = 1)) ### random X and beta each replicate ### storage for error statistics per coefficient and per k mean_error <- matrix(rep(0,31^2),31) mean_MSE <- matrix(rep(0,31^2),31) mean_var <- matrix(rep(0,31^2),31) ### compute error statistics ### MSE, and bias + variance for each coefficient seperately ### k relates to the subset size ### i refers to the coefficient ### averaging is done over the multiple simulations for (i in 1:31) { mean_error[i,] <- sapply(1:31, FUN = function(k) mean(me[k,i,])) mean_MSE[i,] <- sapply(1:31, FUN = function(k) mean(me[k,i,]^2)) mean_var[i,] <- mean_MSE[i,] - mean_error[i,]^2 } ### plotting curves ### colMeans averages over the multiple coefficients layout(matrix(1)) plot(1:31,colMeans(mean_MSE[1:31,]), ylim = c(0,0.4), xlim = c(1,31), type = "l", lwd = 2, xlab = "Subset size k", ylab = "mean square error of parameters", xaxs = "i", yaxs = "i") points(1:31,colMeans(mean_MSE[1:31,]), pch = 21 , col = 1, bg = 0, cex = 0.7) lines(1:31,colMeans(mean_var[1:31,]), lty = 2) lines(1:31,colMeans(mean_error[1:31,]^2), lty = 3) legend(31,0.4, c("MSE", "variance component", "bias component"), lty = c(1,2,3), lwd = c(2,1,1), pch = c(21,NA,NA), col = 1, pt.bg = 0, xjust = 1, cex = 0.7) ### plotting histogram layout(matrix(1:5,5)) par(mar = c(4,4,2,1)) xpar = 1 for (col in c(1,4,7,10,13)) { hist(me[col,xpar,], breaks = seq(-7,7,0.05), xlim = c(-1,1), ylim = c(0,500), xlab = "", ylab = "", main=paste0("error in parameter ",xpar," for subset size ",col), ) }
Is Fig 3.6 in Elements of Statistical Learning correct? adding more variables to a linear model doesn't imply better estimates of the true parameters This is not just estimating variables, but also variable selection. When you only subselect <10 variables
15,456
Is Fig 3.6 in Elements of Statistical Learning correct?
There are good answers here, so I'll try to keep this brief and just add a couple points. The point of this figure is to show how close the estimated slopes are to their true values, not how well the model predicts $y$ out of sample, or to whether inferences are valid. adding more variables to a linear model doesn't imply better estimates of the true parameters Don't think of this as adding more variables. In all cases, you started with a fixed set of variables determined a-priori. The question is whether you should drop some of those variables for building your final model. Dropping variables based on what you see in your data is generally a bad thing to do. If you retain all variables (assuming you have enough data, which in this case you do) your estimates will be unbiased. Put another way, the variables whose slopes are actually $0$ in the data generating process should have slope estimates that are close to $0$ in the fitted model. They should be approximately correct. When you drop variables, that's no longer necessarily true. This case is more complicated, because the variables are all correlated with each other. The correlations mean that the slopes will vary from their true values more widely than they would have if the variables were all mutually orthogonal. As a result, if you pick just the right variables you could reduce the variance somewhat while maintaining the property of unbiasedness. However... My intuition is that MSE should be lowest around the optimal $k$ That's because your intuition is that stepwise procedures will pick the right variables. Unfortunately, that isn't necessarily what's going to happen. It is very unlikely that you will pick exactly the right variables. And, if you don't pick only the right variables, you will continue to get sampling distributions with higher variance and biased estimates. Now, let's consider picking the best, say, 15 or 20 variables. What is the probability that we will have included the 10 that we wanted and only thrown away worthless variables that just added noise? It's much better. That's why the curve is lower there. So a takeaway from this is that if you know how many variables are correct, and you know that they are all included in your dataset, you can focus on retaining some proportion beyond what is needed and you will be likely to only have thrown away garbage. (Of course, I don't find those conditions very realistic, and this discussion only pertains to the slope estimates, not out of sample predictions or statistical inference, so I continue to find stepwise procedures ill-advised.) It may help you to read some of the other threads on the site related to these topics: Algorithms for automatic model selection Why are p-values misleading after performing a stepwise selection? (You might also want to read though some of our threads categorized under the multicollinearity tag.)
Is Fig 3.6 in Elements of Statistical Learning correct?
There are good answers here, so I'll try to keep this brief and just add a couple points. The point of this figure is to show how close the estimated slopes are to their true values, not how well the
Is Fig 3.6 in Elements of Statistical Learning correct? There are good answers here, so I'll try to keep this brief and just add a couple points. The point of this figure is to show how close the estimated slopes are to their true values, not how well the model predicts $y$ out of sample, or to whether inferences are valid. adding more variables to a linear model doesn't imply better estimates of the true parameters Don't think of this as adding more variables. In all cases, you started with a fixed set of variables determined a-priori. The question is whether you should drop some of those variables for building your final model. Dropping variables based on what you see in your data is generally a bad thing to do. If you retain all variables (assuming you have enough data, which in this case you do) your estimates will be unbiased. Put another way, the variables whose slopes are actually $0$ in the data generating process should have slope estimates that are close to $0$ in the fitted model. They should be approximately correct. When you drop variables, that's no longer necessarily true. This case is more complicated, because the variables are all correlated with each other. The correlations mean that the slopes will vary from their true values more widely than they would have if the variables were all mutually orthogonal. As a result, if you pick just the right variables you could reduce the variance somewhat while maintaining the property of unbiasedness. However... My intuition is that MSE should be lowest around the optimal $k$ That's because your intuition is that stepwise procedures will pick the right variables. Unfortunately, that isn't necessarily what's going to happen. It is very unlikely that you will pick exactly the right variables. And, if you don't pick only the right variables, you will continue to get sampling distributions with higher variance and biased estimates. Now, let's consider picking the best, say, 15 or 20 variables. What is the probability that we will have included the 10 that we wanted and only thrown away worthless variables that just added noise? It's much better. That's why the curve is lower there. So a takeaway from this is that if you know how many variables are correct, and you know that they are all included in your dataset, you can focus on retaining some proportion beyond what is needed and you will be likely to only have thrown away garbage. (Of course, I don't find those conditions very realistic, and this discussion only pertains to the slope estimates, not out of sample predictions or statistical inference, so I continue to find stepwise procedures ill-advised.) It may help you to read some of the other threads on the site related to these topics: Algorithms for automatic model selection Why are p-values misleading after performing a stepwise selection? (You might also want to read though some of our threads categorized under the multicollinearity tag.)
Is Fig 3.6 in Elements of Statistical Learning correct? There are good answers here, so I'll try to keep this brief and just add a couple points. The point of this figure is to show how close the estimated slopes are to their true values, not how well the
15,457
Is Fig 3.6 in Elements of Statistical Learning correct?
I try to give an intuitive answer without actually checking and trying to reproduce the code. No idea whether the graph is wrong, but I will explain how it corresponds to my intuition. The question has: "I think It shows a decreasing relationship between subset size k and mean squared error (MSE) of the true parameters, β and the estimates β^(k). Clearly, this shouldn't be the case - adding more variables to a linear model doesn't imply better estimates of the true parameters. (...) My intuition is that MSE should be lowest around the optimal k (somewhere between 5-10 due to correlations)." What I think is going on is this. This is about variable selection. MSE of estimated betas should be smallest if exactly the correct 10 variables are selected. It should be substantially larger if at least one of these variables is missed. Note that correlation makes this problem worse, because if one of the correct nonzero beta variables is missed, its contribution will be attributed to those that are already in the model because of correlation. This will make their estimators worse, on top of the fact that there is an error from the missing $\beta$ itself. It is not true that the effect of correlation is that we can do well with fewer variables than the 10 correct ones, regarding the MSE of the estimators. It may be true for prediction, as the information of a missing variable is compensated for by other correlated variables already in the model. But this is not what the graph is about. The very same effect that may be helpful for prediction will be detrimental for estimation, because the effect of the missing correct nonzero beta variables will be divided among those that are already in the model, affecting their estimation. This means that the minimum should occur at 10 only if always or almost always exactly the 10 correct variables are selected. But this is very unlikely, because correlation actually makes it very hard to find the correct variables. Chances are that if the procedure selects 11, 12, even 15 variables, still it's not too unlikely that one true nonzero beta variable is missed. True zero beta variables on the other hand will probably have fairly low estimated coefficients anyway, so will not harm the estimator MSE as much as a missed correct nonzero beta variable does. This explains in my view that the estimator MSE goes up only from about $k=16$ or even $k=27$ or so for stagewise. This seems all fine by me. What it shows is how many variables in this setup need to be selected in order to find all true nonzeroes with large enough probability. 16 seems realistic to me, and it is also clear that stagewise has a hard time in this problem, as it will need many steps to bring initially overestimated parameters down.
Is Fig 3.6 in Elements of Statistical Learning correct?
I try to give an intuitive answer without actually checking and trying to reproduce the code. No idea whether the graph is wrong, but I will explain how it corresponds to my intuition. The question ha
Is Fig 3.6 in Elements of Statistical Learning correct? I try to give an intuitive answer without actually checking and trying to reproduce the code. No idea whether the graph is wrong, but I will explain how it corresponds to my intuition. The question has: "I think It shows a decreasing relationship between subset size k and mean squared error (MSE) of the true parameters, β and the estimates β^(k). Clearly, this shouldn't be the case - adding more variables to a linear model doesn't imply better estimates of the true parameters. (...) My intuition is that MSE should be lowest around the optimal k (somewhere between 5-10 due to correlations)." What I think is going on is this. This is about variable selection. MSE of estimated betas should be smallest if exactly the correct 10 variables are selected. It should be substantially larger if at least one of these variables is missed. Note that correlation makes this problem worse, because if one of the correct nonzero beta variables is missed, its contribution will be attributed to those that are already in the model because of correlation. This will make their estimators worse, on top of the fact that there is an error from the missing $\beta$ itself. It is not true that the effect of correlation is that we can do well with fewer variables than the 10 correct ones, regarding the MSE of the estimators. It may be true for prediction, as the information of a missing variable is compensated for by other correlated variables already in the model. But this is not what the graph is about. The very same effect that may be helpful for prediction will be detrimental for estimation, because the effect of the missing correct nonzero beta variables will be divided among those that are already in the model, affecting their estimation. This means that the minimum should occur at 10 only if always or almost always exactly the 10 correct variables are selected. But this is very unlikely, because correlation actually makes it very hard to find the correct variables. Chances are that if the procedure selects 11, 12, even 15 variables, still it's not too unlikely that one true nonzero beta variable is missed. True zero beta variables on the other hand will probably have fairly low estimated coefficients anyway, so will not harm the estimator MSE as much as a missed correct nonzero beta variable does. This explains in my view that the estimator MSE goes up only from about $k=16$ or even $k=27$ or so for stagewise. This seems all fine by me. What it shows is how many variables in this setup need to be selected in order to find all true nonzeroes with large enough probability. 16 seems realistic to me, and it is also clear that stagewise has a hard time in this problem, as it will need many steps to bring initially overestimated parameters down.
Is Fig 3.6 in Elements of Statistical Learning correct? I try to give an intuitive answer without actually checking and trying to reproduce the code. No idea whether the graph is wrong, but I will explain how it corresponds to my intuition. The question ha
15,458
How to calculate overlap between empirical probability densities?
The area of overlap of two kernel density estimates may be approximated to any desired degree of accuracy. 1) Since the original KDEs have probably been evaluated over some grid, if the grid is the same for both (or can easily be made the same), the exercise could be as easy as simply taking $\min(K_1(x),K_2(x))$ at each point and then using the trapezoidal rule, or even a midpoint rule. If the two are on different grids and can't easily be recalculated on the same grid, interpolation could be used. 2) You might find the point (or points) of intersection and integrate the lower of the two KDEs in each interval where each one is lower. In your diagram above you'd integrate the blue curve to the left of the intersection and the pink one to the right by whatever means you like/have available. This can be done essentially exactly by considering the area under each kernel component $\frac{1}{h}K(\frac{x-x_i}{h})$ to the left or right of that cut-off point. However, whuber's comments above should be clearly borne in mind -- this is not necessarily a very meaningful thing to do.
How to calculate overlap between empirical probability densities?
The area of overlap of two kernel density estimates may be approximated to any desired degree of accuracy. 1) Since the original KDEs have probably been evaluated over some grid, if the grid is the sa
How to calculate overlap between empirical probability densities? The area of overlap of two kernel density estimates may be approximated to any desired degree of accuracy. 1) Since the original KDEs have probably been evaluated over some grid, if the grid is the same for both (or can easily be made the same), the exercise could be as easy as simply taking $\min(K_1(x),K_2(x))$ at each point and then using the trapezoidal rule, or even a midpoint rule. If the two are on different grids and can't easily be recalculated on the same grid, interpolation could be used. 2) You might find the point (or points) of intersection and integrate the lower of the two KDEs in each interval where each one is lower. In your diagram above you'd integrate the blue curve to the left of the intersection and the pink one to the right by whatever means you like/have available. This can be done essentially exactly by considering the area under each kernel component $\frac{1}{h}K(\frac{x-x_i}{h})$ to the left or right of that cut-off point. However, whuber's comments above should be clearly borne in mind -- this is not necessarily a very meaningful thing to do.
How to calculate overlap between empirical probability densities? The area of overlap of two kernel density estimates may be approximated to any desired degree of accuracy. 1) Since the original KDEs have probably been evaluated over some grid, if the grid is the sa
15,459
How to calculate overlap between empirical probability densities?
For the sake of completeness, here's how I ended up doing this in R: # simulate two samples a <- rnorm(100) b <- rnorm(100, 2) # define limits of a common grid, adding a buffer so that tails aren't cut off lower <- min(c(a, b)) - 1 upper <- max(c(a, b)) + 1 # generate kernel densities da <- density(a, from=lower, to=upper) db <- density(b, from=lower, to=upper) d <- data.frame(x=da$x, a=da$y, b=db$y) # calculate intersection densities d$w <- pmin(d$a, d$b) # integrate areas under curves library(sfsmisc) total <- integrate.xy(d$x, d$a) + integrate.xy(d$x, d$b) intersection <- integrate.xy(d$x, d$w) # compute overlap coefficient overlap <- 2 * intersection / total As noted, there is inherent uncertainty and subjectivity involved in the KDE generation and also in the integration.
How to calculate overlap between empirical probability densities?
For the sake of completeness, here's how I ended up doing this in R: # simulate two samples a <- rnorm(100) b <- rnorm(100, 2) # define limits of a common grid, adding a buffer so that tails aren't c
How to calculate overlap between empirical probability densities? For the sake of completeness, here's how I ended up doing this in R: # simulate two samples a <- rnorm(100) b <- rnorm(100, 2) # define limits of a common grid, adding a buffer so that tails aren't cut off lower <- min(c(a, b)) - 1 upper <- max(c(a, b)) + 1 # generate kernel densities da <- density(a, from=lower, to=upper) db <- density(b, from=lower, to=upper) d <- data.frame(x=da$x, a=da$y, b=db$y) # calculate intersection densities d$w <- pmin(d$a, d$b) # integrate areas under curves library(sfsmisc) total <- integrate.xy(d$x, d$a) + integrate.xy(d$x, d$b) intersection <- integrate.xy(d$x, d$w) # compute overlap coefficient overlap <- 2 * intersection / total As noted, there is inherent uncertainty and subjectivity involved in the KDE generation and also in the integration.
How to calculate overlap between empirical probability densities? For the sake of completeness, here's how I ended up doing this in R: # simulate two samples a <- rnorm(100) b <- rnorm(100, 2) # define limits of a common grid, adding a buffer so that tails aren't c
15,460
How to calculate overlap between empirical probability densities?
First, I might be wrong but I think your solution wouldn't work in case where there is multiples points where the Kernel Density Estimates (KDE) intersect. Second, although the overlap package was created for use with timestamp data, you can still use it to estimate the area of overlap of any two KDEs. You simply have to rescale your data so that it range from 0 to 2π. For exemple : # simulate two sample a <- rnorm(100) b <- rnorm(100, 2) # To use overplapTrue(){overlap} the scale must be in radian (i.e. 0 to 2pi) # To keep the *relative* value of a and b the same, combine a and b in the # same dataframe before rescaling. You'll need to load the ‘scales‘ library. # But first add a "Source" column to be able to distinguish between a and b # after they are combined. a = data.frame( value = a, Source = "a" ) b = data.frame( value = b, Source = "b" ) d = rbind(a, b) library(scales) d$value <- rescale( d$value, to = c(0,2*pi) ) # Now you can created the rescaled a and b vectors a <- d[d$Source == "a", 1] b <- d[d$Source == "b", 1] # You can then calculate the area of overlap as you did previously. # It should give almost exactly the same answers. # Or you can use either the overlapTrue() and overlapEst() function # provided with the overlap packages. # Note that with these function the KDE are fitted using von Mises kernel. library(overlap) # Using overlapTrue(): # define limits of a common grid, adding a buffer so that tails aren't cut off lower <- min(d$value)-1 upper <- max(d$value)+1 # generate kernel densities da <- density(a, from=lower, to=upper, adjust = 1) db <- density(b, from=lower, to=upper, adjust = 1) # Compute overlap coefficient overlapTrue(da$y,db$y) # Using overlapEst(): overlapEst(a, b, kmax = 3, adjust=c(0.8, 1, 4), n.grid = 500) # You can also plot the two KDEs and the region of overlap using overlapPlot() # but sadly I haven't found a way of changing the x scale so that the scale # range correspond to the initial x value and not the rescaled value. # You can only change the maximum value of the scale using the xscale argument # (i.e. it always range from 0 to n, where n is set with xscale = n). # So if some of your data take negative value, you're probably better off with # a different plotting method. You can change the x label with the xlab # argument. overlapPlot(a, b, xscale = 10, xlab= "x metrics", rug=T)
How to calculate overlap between empirical probability densities?
First, I might be wrong but I think your solution wouldn't work in case where there is multiples points where the Kernel Density Estimates (KDE) intersect. Second, although the overlap package was cre
How to calculate overlap between empirical probability densities? First, I might be wrong but I think your solution wouldn't work in case where there is multiples points where the Kernel Density Estimates (KDE) intersect. Second, although the overlap package was created for use with timestamp data, you can still use it to estimate the area of overlap of any two KDEs. You simply have to rescale your data so that it range from 0 to 2π. For exemple : # simulate two sample a <- rnorm(100) b <- rnorm(100, 2) # To use overplapTrue(){overlap} the scale must be in radian (i.e. 0 to 2pi) # To keep the *relative* value of a and b the same, combine a and b in the # same dataframe before rescaling. You'll need to load the ‘scales‘ library. # But first add a "Source" column to be able to distinguish between a and b # after they are combined. a = data.frame( value = a, Source = "a" ) b = data.frame( value = b, Source = "b" ) d = rbind(a, b) library(scales) d$value <- rescale( d$value, to = c(0,2*pi) ) # Now you can created the rescaled a and b vectors a <- d[d$Source == "a", 1] b <- d[d$Source == "b", 1] # You can then calculate the area of overlap as you did previously. # It should give almost exactly the same answers. # Or you can use either the overlapTrue() and overlapEst() function # provided with the overlap packages. # Note that with these function the KDE are fitted using von Mises kernel. library(overlap) # Using overlapTrue(): # define limits of a common grid, adding a buffer so that tails aren't cut off lower <- min(d$value)-1 upper <- max(d$value)+1 # generate kernel densities da <- density(a, from=lower, to=upper, adjust = 1) db <- density(b, from=lower, to=upper, adjust = 1) # Compute overlap coefficient overlapTrue(da$y,db$y) # Using overlapEst(): overlapEst(a, b, kmax = 3, adjust=c(0.8, 1, 4), n.grid = 500) # You can also plot the two KDEs and the region of overlap using overlapPlot() # but sadly I haven't found a way of changing the x scale so that the scale # range correspond to the initial x value and not the rescaled value. # You can only change the maximum value of the scale using the xscale argument # (i.e. it always range from 0 to n, where n is set with xscale = n). # So if some of your data take negative value, you're probably better off with # a different plotting method. You can change the x label with the xlab # argument. overlapPlot(a, b, xscale = 10, xlab= "x metrics", rug=T)
How to calculate overlap between empirical probability densities? First, I might be wrong but I think your solution wouldn't work in case where there is multiples points where the Kernel Density Estimates (KDE) intersect. Second, although the overlap package was cre
15,461
How to calculate overlap between empirical probability densities?
An alternative method for empirical estimation is to use the ROC (Receiver Operating Curve) technology for the estimation. The Youden threshold gives us an empirical estimate for the main point of intersection (see https://journals.lww.com/epidem/Fulltext/2005/01000/Optimal_Cut_point_and_Its_Corresponding_Youden.11.aspx and https://math.stackexchange.com/questions/2404750/intersection-normal-distributions-and-minimal-decision-error/2435957#2435957). The Youden threshold is the threshold where the sum of test sensitivity and specificity is maximized and the sum of the error rates (False positive Rate and False Negative Rate) is minimized. The overlap is equal to this minimal sum of error rates. library(UncertainInterval) simple_roc2 <- function(ref, test){ tab = table(test, ref) # head(tab) data.frame(threshold=paste('>=',rownames(tab)), ref0 = tab[,1], ref1 = tab[,2], FPR = rev(cumsum(rev(tab[,1])/sum(tab[,1]))), # 1-Sp TPR = rev(cumsum(rev(tab[,2])/sum(tab[,2]))), # Se row.names=1:nrow(tab)) } a <- rnorm(10000) b <- rnorm(10000, 2) test=c(a,b) ref=c(rep(0, length(a)), rep(1, length(b))) # table(test, ref) res = simple_roc2(ref, test) res$FNR = 1-res$TPR # 1-Se pos.optimal.threshold = which.min(res$FPR+res$FNR) optimal.threshold=row.names(table(test, ref))[pos.optimal.threshold] # Youden threshold plotMD(ref, test) # library(UncertainInterval) # includes kernel intersection estimate abline(v=optimal.threshold, col='red') overlap1(a, b) (overlap2 = min(res$FPR+res$FNR)) In this case, this non-parametric estimate has a slight tendency of under estimation of the true value. This roc-technique only handles a single (main) point of intersection. It is not dependent on any specific distribution. Make sure that distribution b has the higher values (mean(b) > mean(a)). Repeatedly eyeballing plots produced by plotMD shows that with 2 * 100 cases the sample overlap differs considerably. Most differences are due to sample differences, but, dependent on the distributions, all methods have conditions in which they do not work properly. Using a gaussian kernel density is sensitive to spikes in the data, which can be underestimated. Kernel density methods are dependent on the fine-tuning parameters given to the density function. The roc-method has no parameters, but it assumes a single point of intersection. Consequentially, it may overestimate overlap when an additional point of intersection is present (the critical point is the presence of more than one point of intersection, not variance). This overestimation may be negligible when this secondary point of intersection is at the tails of both distributions. How to make sense of the different methods and suggestions? Devising a test is most simple when we know the true value of two distributions. The true value of the overlap for the two normal distributions is easy to calculate. The point of intersection is simply the mean of the two means of the distributions, as they have equal variance: 1. The true overlap is then 0.3173105: (true.overlap = pnorm(1,2,1)+ 1-pnorm(1,0,1)) See https://stackoverflow.com/questions/16982146/point-of-intersection-2-normal-curves/45184024#45184024 for a general method to calculate the point of intersection for two normal distributions. In the original problem, there is a mix of a normal and a uniform distribution. The true value is in that case: true.value=sum(pmin(diff(pnorm(0:3)),1/3)) Running a simulation can show us which estimation method produces estimates that are closest to the true value: library(sfsmisc) overlap1 <- function(a,b){ lower <- min(c(a, b)) - 1 upper <- max(c(a, b)) + 1 # generate kernel densities da <- density(a, from=lower, to=upper) db <- density(b, from=lower, to=upper) d <- data.frame(x=da$x, a=da$y, b=db$y) # calculate intersection densities d$w <- pmin(d$a, d$b) # integrate areas under curves total <- integrate.xy(d$x, d$a) + integrate.xy(d$x, d$b) intersection <- integrate.xy(d$x, d$w) # compute overlap coefficient 2 * intersection / total } library(overlap) library(scales) # For explanation of the next function see the answer of S. Venne overlapEstimates =function(a, b){ a = data.frame( value = a, Source = "a" ) b = data.frame( value = b, Source = "b" ) d = rbind(a, b) d$value <- scales::rescale( d$value, to = c(0,2*pi) ) a <- d[d$Source == "a", 1] b <- d[d$Source == "b", 1] overlapEst(a, b, kmax = 3, adjust=c(0.8, 1, 4), n.grid = 500) } nsim=1000; nobs=100; m1=4; sd1=1; m2=6; sd2=1; poi=5 (true.overlap= 1-pnorm(poi, m1, sd1)+pnorm(poi,m2,sd2)) out=matrix(NA,nrow=nsim,ncol=4) set.seed(0) for (i in 1:nsim){ x <- rnorm( nobs, m1, sd1 ) y <- rnorm( nobs, m2, sd2 ) out[i,1] = overlap1(x,y) out[i,2] = overlapping::overlap(list( x = x, y = y ))$OV out[i,3] = overlapEstimates(x,y)['Dhat4'] out[i,4] = roc.overlap(x,y) } (true.overlap=pnorm(poi,m2,sd2)+1-pnorm(poi,m1,sd1)) colMeans(out-true.overlap) # estimation errors apply(out, 2, sd) # # sd of the estimation errors apply(out, 2, range)-true.overlap par(mfrow=c(2,2)) br = seq(-.33,+.33,by=0.05) hist(out[,1]-true.overlap, breaks=br, ylim=c(0,500), xlim=c(-.33,.33), main='overlap1'); abline(v=0, col='red') hist(out[,2]-true.overlap, breaks=br, ylim=c(0,500), xlim=c(-.33,.33), main='overlapping::overlap') abline(v=0, col='red') hist(out[,3]-true.overlap, breaks=br, ylim=c(0,600), xlim=c(-.33,.33), main='overlap::overlapEst') abline(v=0, col='red') hist(out[,4]-true.overlap, breaks=br, ylim=c(0,500), xlim=c(-.33,.33), main="ROC estimate"); abline(v=0, col='red') In this case, especially the function overlapping::overlap has a tendency of (slight) under-estimation, while overlap1 shows the least estimation error. Estimates that use the density function in one way or another, can produce better or worse results dependent on the parameters given to the density function. The roc method does not have parameters, which can be an advantage. It is always wise to carefully look at a plot of the overlapping distributions and to devise a relevant testing method whether the technique for overlap estimation works as expected for the kind of data that you have. Especially techniques that systematically produce estimates that are often too low or to high are better not used.
How to calculate overlap between empirical probability densities?
An alternative method for empirical estimation is to use the ROC (Receiver Operating Curve) technology for the estimation. The Youden threshold gives us an empirical estimate for the main point of int
How to calculate overlap between empirical probability densities? An alternative method for empirical estimation is to use the ROC (Receiver Operating Curve) technology for the estimation. The Youden threshold gives us an empirical estimate for the main point of intersection (see https://journals.lww.com/epidem/Fulltext/2005/01000/Optimal_Cut_point_and_Its_Corresponding_Youden.11.aspx and https://math.stackexchange.com/questions/2404750/intersection-normal-distributions-and-minimal-decision-error/2435957#2435957). The Youden threshold is the threshold where the sum of test sensitivity and specificity is maximized and the sum of the error rates (False positive Rate and False Negative Rate) is minimized. The overlap is equal to this minimal sum of error rates. library(UncertainInterval) simple_roc2 <- function(ref, test){ tab = table(test, ref) # head(tab) data.frame(threshold=paste('>=',rownames(tab)), ref0 = tab[,1], ref1 = tab[,2], FPR = rev(cumsum(rev(tab[,1])/sum(tab[,1]))), # 1-Sp TPR = rev(cumsum(rev(tab[,2])/sum(tab[,2]))), # Se row.names=1:nrow(tab)) } a <- rnorm(10000) b <- rnorm(10000, 2) test=c(a,b) ref=c(rep(0, length(a)), rep(1, length(b))) # table(test, ref) res = simple_roc2(ref, test) res$FNR = 1-res$TPR # 1-Se pos.optimal.threshold = which.min(res$FPR+res$FNR) optimal.threshold=row.names(table(test, ref))[pos.optimal.threshold] # Youden threshold plotMD(ref, test) # library(UncertainInterval) # includes kernel intersection estimate abline(v=optimal.threshold, col='red') overlap1(a, b) (overlap2 = min(res$FPR+res$FNR)) In this case, this non-parametric estimate has a slight tendency of under estimation of the true value. This roc-technique only handles a single (main) point of intersection. It is not dependent on any specific distribution. Make sure that distribution b has the higher values (mean(b) > mean(a)). Repeatedly eyeballing plots produced by plotMD shows that with 2 * 100 cases the sample overlap differs considerably. Most differences are due to sample differences, but, dependent on the distributions, all methods have conditions in which they do not work properly. Using a gaussian kernel density is sensitive to spikes in the data, which can be underestimated. Kernel density methods are dependent on the fine-tuning parameters given to the density function. The roc-method has no parameters, but it assumes a single point of intersection. Consequentially, it may overestimate overlap when an additional point of intersection is present (the critical point is the presence of more than one point of intersection, not variance). This overestimation may be negligible when this secondary point of intersection is at the tails of both distributions. How to make sense of the different methods and suggestions? Devising a test is most simple when we know the true value of two distributions. The true value of the overlap for the two normal distributions is easy to calculate. The point of intersection is simply the mean of the two means of the distributions, as they have equal variance: 1. The true overlap is then 0.3173105: (true.overlap = pnorm(1,2,1)+ 1-pnorm(1,0,1)) See https://stackoverflow.com/questions/16982146/point-of-intersection-2-normal-curves/45184024#45184024 for a general method to calculate the point of intersection for two normal distributions. In the original problem, there is a mix of a normal and a uniform distribution. The true value is in that case: true.value=sum(pmin(diff(pnorm(0:3)),1/3)) Running a simulation can show us which estimation method produces estimates that are closest to the true value: library(sfsmisc) overlap1 <- function(a,b){ lower <- min(c(a, b)) - 1 upper <- max(c(a, b)) + 1 # generate kernel densities da <- density(a, from=lower, to=upper) db <- density(b, from=lower, to=upper) d <- data.frame(x=da$x, a=da$y, b=db$y) # calculate intersection densities d$w <- pmin(d$a, d$b) # integrate areas under curves total <- integrate.xy(d$x, d$a) + integrate.xy(d$x, d$b) intersection <- integrate.xy(d$x, d$w) # compute overlap coefficient 2 * intersection / total } library(overlap) library(scales) # For explanation of the next function see the answer of S. Venne overlapEstimates =function(a, b){ a = data.frame( value = a, Source = "a" ) b = data.frame( value = b, Source = "b" ) d = rbind(a, b) d$value <- scales::rescale( d$value, to = c(0,2*pi) ) a <- d[d$Source == "a", 1] b <- d[d$Source == "b", 1] overlapEst(a, b, kmax = 3, adjust=c(0.8, 1, 4), n.grid = 500) } nsim=1000; nobs=100; m1=4; sd1=1; m2=6; sd2=1; poi=5 (true.overlap= 1-pnorm(poi, m1, sd1)+pnorm(poi,m2,sd2)) out=matrix(NA,nrow=nsim,ncol=4) set.seed(0) for (i in 1:nsim){ x <- rnorm( nobs, m1, sd1 ) y <- rnorm( nobs, m2, sd2 ) out[i,1] = overlap1(x,y) out[i,2] = overlapping::overlap(list( x = x, y = y ))$OV out[i,3] = overlapEstimates(x,y)['Dhat4'] out[i,4] = roc.overlap(x,y) } (true.overlap=pnorm(poi,m2,sd2)+1-pnorm(poi,m1,sd1)) colMeans(out-true.overlap) # estimation errors apply(out, 2, sd) # # sd of the estimation errors apply(out, 2, range)-true.overlap par(mfrow=c(2,2)) br = seq(-.33,+.33,by=0.05) hist(out[,1]-true.overlap, breaks=br, ylim=c(0,500), xlim=c(-.33,.33), main='overlap1'); abline(v=0, col='red') hist(out[,2]-true.overlap, breaks=br, ylim=c(0,500), xlim=c(-.33,.33), main='overlapping::overlap') abline(v=0, col='red') hist(out[,3]-true.overlap, breaks=br, ylim=c(0,600), xlim=c(-.33,.33), main='overlap::overlapEst') abline(v=0, col='red') hist(out[,4]-true.overlap, breaks=br, ylim=c(0,500), xlim=c(-.33,.33), main="ROC estimate"); abline(v=0, col='red') In this case, especially the function overlapping::overlap has a tendency of (slight) under-estimation, while overlap1 shows the least estimation error. Estimates that use the density function in one way or another, can produce better or worse results dependent on the parameters given to the density function. The roc method does not have parameters, which can be an advantage. It is always wise to carefully look at a plot of the overlapping distributions and to devise a relevant testing method whether the technique for overlap estimation works as expected for the kind of data that you have. Especially techniques that systematically produce estimates that are often too low or to high are better not used.
How to calculate overlap between empirical probability densities? An alternative method for empirical estimation is to use the ROC (Receiver Operating Curve) technology for the estimation. The Youden threshold gives us an empirical estimate for the main point of int
15,462
Why does Natural Language Processing not fall under Machine Learning domain? [closed]
Because they are different: One does not include the other. Yes modern NLP (Natural Language Processing) does make use of a lot of ML (Machine Learning), but that is just one group of techniques in the arsenal. For example, graph theory and search algorithms are also used a lot. As is simple text processing (Regular Expressions). Note I also said "modern NLP" - the statistical approach to NLP is a relatively recent development over the past few decades. I understand a more formal approach (e.g. based on parsing formal grammars) was the norm back in the 1960s/1970s. Similarly ML does not have to use NLP, and usually it doesn't, although some applications might use NLP techniques (eg. to process text input).
Why does Natural Language Processing not fall under Machine Learning domain? [closed]
Because they are different: One does not include the other. Yes modern NLP (Natural Language Processing) does make use of a lot of ML (Machine Learning), but that is just one group of techniques in th
Why does Natural Language Processing not fall under Machine Learning domain? [closed] Because they are different: One does not include the other. Yes modern NLP (Natural Language Processing) does make use of a lot of ML (Machine Learning), but that is just one group of techniques in the arsenal. For example, graph theory and search algorithms are also used a lot. As is simple text processing (Regular Expressions). Note I also said "modern NLP" - the statistical approach to NLP is a relatively recent development over the past few decades. I understand a more formal approach (e.g. based on parsing formal grammars) was the norm back in the 1960s/1970s. Similarly ML does not have to use NLP, and usually it doesn't, although some applications might use NLP techniques (eg. to process text input).
Why does Natural Language Processing not fall under Machine Learning domain? [closed] Because they are different: One does not include the other. Yes modern NLP (Natural Language Processing) does make use of a lot of ML (Machine Learning), but that is just one group of techniques in th
15,463
Why does Natural Language Processing not fall under Machine Learning domain? [closed]
I think @winwaed's answer sums it up quite well, and I agree. However I would also add that I would say that NLP is part of a specific application area, namely text processing, and hence there is a lot of domain-specific knowledge that is contained within the techniques that are used. For the most part ML techniques are general purpose and can be applied in many different applications, although ML techniques are used in text processing as well, and as winwaed says by NLP practitioners too. I think it's no different to saying "what's the difference between bioinformatics and ML?"
Why does Natural Language Processing not fall under Machine Learning domain? [closed]
I think @winwaed's answer sums it up quite well, and I agree. However I would also add that I would say that NLP is part of a specific application area, namely text processing, and hence there is a lo
Why does Natural Language Processing not fall under Machine Learning domain? [closed] I think @winwaed's answer sums it up quite well, and I agree. However I would also add that I would say that NLP is part of a specific application area, namely text processing, and hence there is a lot of domain-specific knowledge that is contained within the techniques that are used. For the most part ML techniques are general purpose and can be applied in many different applications, although ML techniques are used in text processing as well, and as winwaed says by NLP practitioners too. I think it's no different to saying "what's the difference between bioinformatics and ML?"
Why does Natural Language Processing not fall under Machine Learning domain? [closed] I think @winwaed's answer sums it up quite well, and I agree. However I would also add that I would say that NLP is part of a specific application area, namely text processing, and hence there is a lo
15,464
How to calculate the variance of a partition of variables
The formula is fairly straightforward if all the sub-sample have the same sample size. If you had $g$ sub-samples of size $k$ (for a total of $gk$ samples), then the variance of the combined sample depends on the mean $E_j$ and variance $V_j$ of each sub-sample: $$ Var(X_1,\ldots,X_{gk}) = \frac{k-1}{gk-1}(\sum_{j=1}^g V_j + \frac{k(g-1)}{k-1} Var(E_j)),$$ where by $Var(E_j)$ means the variance of the sample means. A demonstration in R: > x <- rnorm(100) > g <- gl(10,10) > mns <- tapply(x, g, mean) > vs <- tapply(x, g, var) > 9/99*(sum(vs) + 10*var(mns)) [1] 1.033749 > var(x) [1] 1.033749 If the sample sizes are not equal, the formula is not so nice. EDIT: formula for unequal sample sizes If there are $g$ sub-samples, each with $k_j, j=1,\ldots,g$ elements for a total of $n=\sum{k_j}$ values, then $$ Var(X_1,\ldots,X_{n}) = \frac{1}{n-1}\left(\sum_{j=1}^g (k_j-1) V_j + \sum_{j=1}^g k_j (\bar{X}_j - \bar{X})^2\right), $$ where $\bar{X} = (\sum_{j=1}^gk_j\bar{X}_j)/n$ is the weighted average of all the means (and equals to the mean of all values). Again, a demonstration: > k <- rpois(10, lambda=10) > n <- sum(k) > g <- factor(rep(1:10, k)) > x <- rnorm(n) > mns <- tapply(x, g, mean) > vs <- tapply(x, g, var) > 1/(n-1)*(sum((k-1)*vs) + sum(k*(mns-weighted.mean(mns,k))^2)) [1] 1.108966 > var(x) [1] 1.108966 By the way, these formulas are easy to derive by writing the desired variance as the scaled sum of $(X_{ji}-\bar{X})^2$, then introducing $\bar{X}_j$: $[(X_{ji}-\bar{X}_j)-(\bar{X}_j-\bar{X})]^2$, using the square of difference formula, and simplifying.
How to calculate the variance of a partition of variables
The formula is fairly straightforward if all the sub-sample have the same sample size. If you had $g$ sub-samples of size $k$ (for a total of $gk$ samples), then the variance of the combined sample de
How to calculate the variance of a partition of variables The formula is fairly straightforward if all the sub-sample have the same sample size. If you had $g$ sub-samples of size $k$ (for a total of $gk$ samples), then the variance of the combined sample depends on the mean $E_j$ and variance $V_j$ of each sub-sample: $$ Var(X_1,\ldots,X_{gk}) = \frac{k-1}{gk-1}(\sum_{j=1}^g V_j + \frac{k(g-1)}{k-1} Var(E_j)),$$ where by $Var(E_j)$ means the variance of the sample means. A demonstration in R: > x <- rnorm(100) > g <- gl(10,10) > mns <- tapply(x, g, mean) > vs <- tapply(x, g, var) > 9/99*(sum(vs) + 10*var(mns)) [1] 1.033749 > var(x) [1] 1.033749 If the sample sizes are not equal, the formula is not so nice. EDIT: formula for unequal sample sizes If there are $g$ sub-samples, each with $k_j, j=1,\ldots,g$ elements for a total of $n=\sum{k_j}$ values, then $$ Var(X_1,\ldots,X_{n}) = \frac{1}{n-1}\left(\sum_{j=1}^g (k_j-1) V_j + \sum_{j=1}^g k_j (\bar{X}_j - \bar{X})^2\right), $$ where $\bar{X} = (\sum_{j=1}^gk_j\bar{X}_j)/n$ is the weighted average of all the means (and equals to the mean of all values). Again, a demonstration: > k <- rpois(10, lambda=10) > n <- sum(k) > g <- factor(rep(1:10, k)) > x <- rnorm(n) > mns <- tapply(x, g, mean) > vs <- tapply(x, g, var) > 1/(n-1)*(sum((k-1)*vs) + sum(k*(mns-weighted.mean(mns,k))^2)) [1] 1.108966 > var(x) [1] 1.108966 By the way, these formulas are easy to derive by writing the desired variance as the scaled sum of $(X_{ji}-\bar{X})^2$, then introducing $\bar{X}_j$: $[(X_{ji}-\bar{X}_j)-(\bar{X}_j-\bar{X})]^2$, using the square of difference formula, and simplifying.
How to calculate the variance of a partition of variables The formula is fairly straightforward if all the sub-sample have the same sample size. If you had $g$ sub-samples of size $k$ (for a total of $gk$ samples), then the variance of the combined sample de
15,465
How to calculate the variance of a partition of variables
This is simply an add-on to the answer of aniko with a rough sketch of the derivation and some python code, so all credits go to aniko. derivation Let $X_j \in X = \{X_1, X_2, \ldots, X_g\}$ be one of $g$ parts of the data where the number of elements in each part is $k_j = |X_j|$. We define the mean and the variance of each part to be $$\begin{align*} E_j & = \mathrm{E}\left[X_j\right] = \frac{1}{k_j} \sum_{i=1}^{k_j} X_{ji}\\ V_j & = \mathrm{Var}\left[X_j\right] = \frac{1}{k_j-1} \sum_{i=1}^{k_j} (X_{ji} - E_j)^2 \end{align*}$$ respectively. If we set $n = \sum_{j=1}^g k_j$, the variance of the total dataset is given by: $$\begin{align*} \mathrm{Var}\left[X\right] & = \frac{1}{n-1} \sum_{j=1}^{g} \sum_{i=1}^{k_j} (X_{ji} - \mathrm{E}\left[X\right])^2 \\ & = \frac{1}{n-1} \sum_{j=1}^{g} \sum_{i=1}^{k_j} \big((X_{ji} - E_j) - (\mathrm{E}\left[X\right] - E_j)\big)^2 \\ & = \frac{1}{n-1} \sum_{j=1}^{g} \sum_{i=1}^{k_j} (X_{ji} - E_j)^2 - 2(X_{ji} - E_j)(\mathrm{E}\left[X\right] - E_j) + (\mathrm{E}\left[X\right] - E_j)^2 \\ & = \frac{1}{n-1} \sum_{j=1}^{g} (k_j - 1) V_j + k_j (\mathrm{E}\left[X\right] - E_j)^2. \end{align*}$$ If we have the same size $k$ for each part, i.e. $\forall j: k_j = k$, above formula simplifies to $$\begin{align*} \mathrm{Var}\left[X\right] & = \frac{1}{n-1} \sum_{j=1}^g (k-1) V_j + k(g-1) \mathrm{Var}\left[E_j\right] \\ & = \frac{k-1}{n-1} \sum_{j=1}^g V_j + \frac{k(g-1)}{k-1} \mathrm{Var}\left[E_j\right] \end{align*}$$ python code The following python function works for arrays that have been splitted along the first dimension and implements the "more complex" formula for differently sized parts. import numpy as np def combine(averages, variances, counts, size=None): """ Combine averages and variances to one single average and variance. # Arguments averages: List of averages for each part. variances: List of variances for each part. counts: List of number of elements in each part. size: Total number of elements in all of the parts. # Returns average: Average over all parts. variance: Variance over all parts. """ average = np.average(averages, weights=counts) # necessary for correct variance in case of multidimensional arrays if size is not None: counts = counts * size // np.sum(counts, dtype='int') squares = (counts - 1) * variances + counts * (averages - average)**2 return average, np.sum(squares) / (size - 1) It can be used as follows: # sizes k_j and n ks = np.random.poisson(10, 10) n = np.sum(ks) # create data x = np.random.randn(n, 20) parts = np.split(x, np.cumsum(ks[:-1])) # compute statistics on parts ms = [np.mean(p) for p in parts] vs = [np.var(p, ddof=1) for p in parts] # combine and compare combined = combine(ms, vs, ks, x.size) numpied = np.mean(x), np.var(x, ddof=1) distance = np.abs(np.array(combined) - np.array(numpied)) print('combined --- mean:{: .9f} - var:{: .9f}'.format(*combined)) print('numpied --- mean:{: .9f} - var:{: .9f}'.format(*numpied)) print('distance --- mean:{: .5e} - var:{: .5e}'.format(*distance))
How to calculate the variance of a partition of variables
This is simply an add-on to the answer of aniko with a rough sketch of the derivation and some python code, so all credits go to aniko. derivation Let $X_j \in X = \{X_1, X_2, \ldots, X_g\}$ be one of
How to calculate the variance of a partition of variables This is simply an add-on to the answer of aniko with a rough sketch of the derivation and some python code, so all credits go to aniko. derivation Let $X_j \in X = \{X_1, X_2, \ldots, X_g\}$ be one of $g$ parts of the data where the number of elements in each part is $k_j = |X_j|$. We define the mean and the variance of each part to be $$\begin{align*} E_j & = \mathrm{E}\left[X_j\right] = \frac{1}{k_j} \sum_{i=1}^{k_j} X_{ji}\\ V_j & = \mathrm{Var}\left[X_j\right] = \frac{1}{k_j-1} \sum_{i=1}^{k_j} (X_{ji} - E_j)^2 \end{align*}$$ respectively. If we set $n = \sum_{j=1}^g k_j$, the variance of the total dataset is given by: $$\begin{align*} \mathrm{Var}\left[X\right] & = \frac{1}{n-1} \sum_{j=1}^{g} \sum_{i=1}^{k_j} (X_{ji} - \mathrm{E}\left[X\right])^2 \\ & = \frac{1}{n-1} \sum_{j=1}^{g} \sum_{i=1}^{k_j} \big((X_{ji} - E_j) - (\mathrm{E}\left[X\right] - E_j)\big)^2 \\ & = \frac{1}{n-1} \sum_{j=1}^{g} \sum_{i=1}^{k_j} (X_{ji} - E_j)^2 - 2(X_{ji} - E_j)(\mathrm{E}\left[X\right] - E_j) + (\mathrm{E}\left[X\right] - E_j)^2 \\ & = \frac{1}{n-1} \sum_{j=1}^{g} (k_j - 1) V_j + k_j (\mathrm{E}\left[X\right] - E_j)^2. \end{align*}$$ If we have the same size $k$ for each part, i.e. $\forall j: k_j = k$, above formula simplifies to $$\begin{align*} \mathrm{Var}\left[X\right] & = \frac{1}{n-1} \sum_{j=1}^g (k-1) V_j + k(g-1) \mathrm{Var}\left[E_j\right] \\ & = \frac{k-1}{n-1} \sum_{j=1}^g V_j + \frac{k(g-1)}{k-1} \mathrm{Var}\left[E_j\right] \end{align*}$$ python code The following python function works for arrays that have been splitted along the first dimension and implements the "more complex" formula for differently sized parts. import numpy as np def combine(averages, variances, counts, size=None): """ Combine averages and variances to one single average and variance. # Arguments averages: List of averages for each part. variances: List of variances for each part. counts: List of number of elements in each part. size: Total number of elements in all of the parts. # Returns average: Average over all parts. variance: Variance over all parts. """ average = np.average(averages, weights=counts) # necessary for correct variance in case of multidimensional arrays if size is not None: counts = counts * size // np.sum(counts, dtype='int') squares = (counts - 1) * variances + counts * (averages - average)**2 return average, np.sum(squares) / (size - 1) It can be used as follows: # sizes k_j and n ks = np.random.poisson(10, 10) n = np.sum(ks) # create data x = np.random.randn(n, 20) parts = np.split(x, np.cumsum(ks[:-1])) # compute statistics on parts ms = [np.mean(p) for p in parts] vs = [np.var(p, ddof=1) for p in parts] # combine and compare combined = combine(ms, vs, ks, x.size) numpied = np.mean(x), np.var(x, ddof=1) distance = np.abs(np.array(combined) - np.array(numpied)) print('combined --- mean:{: .9f} - var:{: .9f}'.format(*combined)) print('numpied --- mean:{: .9f} - var:{: .9f}'.format(*numpied)) print('distance --- mean:{: .5e} - var:{: .5e}'.format(*distance))
How to calculate the variance of a partition of variables This is simply an add-on to the answer of aniko with a rough sketch of the derivation and some python code, so all credits go to aniko. derivation Let $X_j \in X = \{X_1, X_2, \ldots, X_g\}$ be one of
15,466
80% of missing data in a single variable
Are the data "missing" in the sense of being unknown or does it just mean there is no loan (so the loan amount is zero)? It sounds like the latter, in which case you need an additional binary dummy to indicate whether there is a loan. No transformation of the loan amount is needed (apart, perhaps, from a continuous re-expression, such as a root or started log, which might be indicated by virtue of other considerations). This works well in a regression. A simple example is a conceptual model of the form $$\text{dependent variable (Y) = loan amount (X) + constant.}$$ With the addition of a loan indicator ($I$), the regression model is $$Y = \beta_I I + \beta_X X + \beta_0 + \epsilon$$ with $\epsilon$ representing random errors with zero expectations. The coefficients are interpreted as: $\beta_0$ is the expectation of $Y$ for no-loan situations, because those are characterized by $X = 0$ and $I = 0$. $\beta_X$ is the marginal change in $Y$ with respect to the amount of the loan ($X$). $\beta_I + \beta_0$ is the intercept for the cases with loans.
80% of missing data in a single variable
Are the data "missing" in the sense of being unknown or does it just mean there is no loan (so the loan amount is zero)? It sounds like the latter, in which case you need an additional binary dummy t
80% of missing data in a single variable Are the data "missing" in the sense of being unknown or does it just mean there is no loan (so the loan amount is zero)? It sounds like the latter, in which case you need an additional binary dummy to indicate whether there is a loan. No transformation of the loan amount is needed (apart, perhaps, from a continuous re-expression, such as a root or started log, which might be indicated by virtue of other considerations). This works well in a regression. A simple example is a conceptual model of the form $$\text{dependent variable (Y) = loan amount (X) + constant.}$$ With the addition of a loan indicator ($I$), the regression model is $$Y = \beta_I I + \beta_X X + \beta_0 + \epsilon$$ with $\epsilon$ representing random errors with zero expectations. The coefficients are interpreted as: $\beta_0$ is the expectation of $Y$ for no-loan situations, because those are characterized by $X = 0$ and $I = 0$. $\beta_X$ is the marginal change in $Y$ with respect to the amount of the loan ($X$). $\beta_I + \beta_0$ is the intercept for the cases with loans.
80% of missing data in a single variable Are the data "missing" in the sense of being unknown or does it just mean there is no loan (so the loan amount is zero)? It sounds like the latter, in which case you need an additional binary dummy t
15,467
80% of missing data in a single variable
I think you have misunderstood the suggestion of the article: mainly because the suggestion makes no sense. You would then have two problems: how to recode a variable and its values are still missing. What was probably suggested was to create a missingness indicator. A somewhat relevant approach to handling missing data which loosely matches this description is to adjust for a missingness indicator. This is certainly a simple and easy approach, but in general it is biased. The bias can be unbounded in its badness. What this does effectively is fit two models and average their effects together: the first model is the fully conditional model, the second is a complete factor model. The fully conditional model is the complete case model in which each observation is deleted that has missing values. So it is fit on a 20% subset of the data. The second is a fit on the remaining 80% not adjusting for the missing value at all. This marginal model estimates the same effects as the full model when there is no unmeasured interaction, when the link function is collapsible, and when the data are Missing at Random (MAR). These effects are then combined by a weighted average. Even under ideal conditions, no unmeasured interactions, and missing completely at random (MCAR) data, the missing indicator approach leads to biased effects because the marginal model and conditional model estimate different effects. Even predictions are biased in this case. A much better alternative is to just use multiple imputation. Even when the mostly-missing factor is measured at a very low prevalence, MI does a relatively good job of generating sophisticated realizations of what possible values may have been. The only necessary assumption here is MAR.
80% of missing data in a single variable
I think you have misunderstood the suggestion of the article: mainly because the suggestion makes no sense. You would then have two problems: how to recode a variable and its values are still missing.
80% of missing data in a single variable I think you have misunderstood the suggestion of the article: mainly because the suggestion makes no sense. You would then have two problems: how to recode a variable and its values are still missing. What was probably suggested was to create a missingness indicator. A somewhat relevant approach to handling missing data which loosely matches this description is to adjust for a missingness indicator. This is certainly a simple and easy approach, but in general it is biased. The bias can be unbounded in its badness. What this does effectively is fit two models and average their effects together: the first model is the fully conditional model, the second is a complete factor model. The fully conditional model is the complete case model in which each observation is deleted that has missing values. So it is fit on a 20% subset of the data. The second is a fit on the remaining 80% not adjusting for the missing value at all. This marginal model estimates the same effects as the full model when there is no unmeasured interaction, when the link function is collapsible, and when the data are Missing at Random (MAR). These effects are then combined by a weighted average. Even under ideal conditions, no unmeasured interactions, and missing completely at random (MCAR) data, the missing indicator approach leads to biased effects because the marginal model and conditional model estimate different effects. Even predictions are biased in this case. A much better alternative is to just use multiple imputation. Even when the mostly-missing factor is measured at a very low prevalence, MI does a relatively good job of generating sophisticated realizations of what possible values may have been. The only necessary assumption here is MAR.
80% of missing data in a single variable I think you have misunderstood the suggestion of the article: mainly because the suggestion makes no sense. You would then have two problems: how to recode a variable and its values are still missing.
15,468
Examples of Simpson's Paradox being resolved by choosing the aggregate data
I can think of a topical example. If we look at cities overall, we see more coronavirus infections and deaths in denser cities. So clearly, density yields interactions yields infections yields deaths, yes? Except this does not hold if we look inside cities. Inside cities, often the areas with higher density have fewer infections and deaths per capita. What gives? Easy: Density does increase infections overall, but in many cities the densest areas are wealthy and those areas have fewer people with unaddressed health issues. Here, each effect is causal: density increases infections a la any SIR model, but unaddressed health issues also increase infections and deaths.
Examples of Simpson's Paradox being resolved by choosing the aggregate data
I can think of a topical example. If we look at cities overall, we see more coronavirus infections and deaths in denser cities. So clearly, density yields interactions yields infections yields deaths,
Examples of Simpson's Paradox being resolved by choosing the aggregate data I can think of a topical example. If we look at cities overall, we see more coronavirus infections and deaths in denser cities. So clearly, density yields interactions yields infections yields deaths, yes? Except this does not hold if we look inside cities. Inside cities, often the areas with higher density have fewer infections and deaths per capita. What gives? Easy: Density does increase infections overall, but in many cities the densest areas are wealthy and those areas have fewer people with unaddressed health issues. Here, each effect is causal: density increases infections a la any SIR model, but unaddressed health issues also increase infections and deaths.
Examples of Simpson's Paradox being resolved by choosing the aggregate data I can think of a topical example. If we look at cities overall, we see more coronavirus infections and deaths in denser cities. So clearly, density yields interactions yields infections yields deaths,
15,469
Examples of Simpson's Paradox being resolved by choosing the aggregate data
It's going to be hard to find an example quite like that one, because of the number of groups and the fact that there is almost no unexplained variation. A real, two-group one: Smokers who have higher levels of vitamin A in their diet (or who have higher levels in their blood) have lower risk of developing lung cancer, in a dose-dependent way. Two large randomised trials (CARET and ATBC) showed that giving high-dose vitamin to smokers increased their cancer risk The favorable relationship between vitamin A in the blood and cancer risk was still present within groups in the cancer trials [I don't have a reference; I was told this in class many years ago] So, the aggregate relationship goes in the opposite direction to the within-group relationship, and it's the aggregate relationship that (appears to be) causal.
Examples of Simpson's Paradox being resolved by choosing the aggregate data
It's going to be hard to find an example quite like that one, because of the number of groups and the fact that there is almost no unexplained variation. A real, two-group one: Smokers who have high
Examples of Simpson's Paradox being resolved by choosing the aggregate data It's going to be hard to find an example quite like that one, because of the number of groups and the fact that there is almost no unexplained variation. A real, two-group one: Smokers who have higher levels of vitamin A in their diet (or who have higher levels in their blood) have lower risk of developing lung cancer, in a dose-dependent way. Two large randomised trials (CARET and ATBC) showed that giving high-dose vitamin to smokers increased their cancer risk The favorable relationship between vitamin A in the blood and cancer risk was still present within groups in the cancer trials [I don't have a reference; I was told this in class many years ago] So, the aggregate relationship goes in the opposite direction to the within-group relationship, and it's the aggregate relationship that (appears to be) causal.
Examples of Simpson's Paradox being resolved by choosing the aggregate data It's going to be hard to find an example quite like that one, because of the number of groups and the fact that there is almost no unexplained variation. A real, two-group one: Smokers who have high
15,470
Examples of Simpson's Paradox being resolved by choosing the aggregate data
TL/DR--it's just about covariates Philosophical Introduction "Simpson's paradox" is not really a "paradox" in the sense of the barber's paradox or others. It is more like some of Zeno's paradoxes of motion where the paradox results from either not using all of the available information, or not fully understanding the problem. For instance, by using the concept of a rate, we know that Atalanta will reach her goal because she is walking at a constant rate. She reaches half way there in half the time, 3/4 of the way there in 3/4 of the time, 7/8 of the way in 7/8 of the time, and so on, and eventually gets there. You don't resolve Simpson's paradox. It's not a paradox. It's just the difference between doing the best you can with limited information vs. getting more information and using it appropriately. Simpson's Covariate Confounder Situation There is really no paradox. If you do not know the age of a subject, then actually you can do reasonably well predicting the score because there really is positive linear relationship between the two. At the very least, you can do a better job predicting the score than if you don't have any information, as your prediction in this case would simply be the overall average score. However, you can make better predictions if you include the additional covariate of group membership. You only screw up if you try to use the model made from one group on another group. So the lesson is about paying attention to confounders, specifically effect modifiers, not avoiding paradoxes.
Examples of Simpson's Paradox being resolved by choosing the aggregate data
TL/DR--it's just about covariates Philosophical Introduction "Simpson's paradox" is not really a "paradox" in the sense of the barber's paradox or others. It is more like some of Zeno's paradoxes of m
Examples of Simpson's Paradox being resolved by choosing the aggregate data TL/DR--it's just about covariates Philosophical Introduction "Simpson's paradox" is not really a "paradox" in the sense of the barber's paradox or others. It is more like some of Zeno's paradoxes of motion where the paradox results from either not using all of the available information, or not fully understanding the problem. For instance, by using the concept of a rate, we know that Atalanta will reach her goal because she is walking at a constant rate. She reaches half way there in half the time, 3/4 of the way there in 3/4 of the time, 7/8 of the way in 7/8 of the time, and so on, and eventually gets there. You don't resolve Simpson's paradox. It's not a paradox. It's just the difference between doing the best you can with limited information vs. getting more information and using it appropriately. Simpson's Covariate Confounder Situation There is really no paradox. If you do not know the age of a subject, then actually you can do reasonably well predicting the score because there really is positive linear relationship between the two. At the very least, you can do a better job predicting the score than if you don't have any information, as your prediction in this case would simply be the overall average score. However, you can make better predictions if you include the additional covariate of group membership. You only screw up if you try to use the model made from one group on another group. So the lesson is about paying attention to confounders, specifically effect modifiers, not avoiding paradoxes.
Examples of Simpson's Paradox being resolved by choosing the aggregate data TL/DR--it's just about covariates Philosophical Introduction "Simpson's paradox" is not really a "paradox" in the sense of the barber's paradox or others. It is more like some of Zeno's paradoxes of m
15,471
Examples of Simpson's Paradox being resolved by choosing the aggregate data
I don't know of a real example, but maybe I can provide some helpful thoughts nonetheless. The first thing is that the nature of "Simpson's paradox" has evolved over time. Today, it is widely known as the situation where there is a relationship between two variables (call them $X$ and $Y$) with a given direction, but when including information about a grouping variable ($Z$) that was not previously included, the direction of the relationship between the two variables flips. This is a specific case of a general phenomenon in which relationships can change or even reverse when including more information. It is due to the fact that the two covariates, $X$ and $Z$, are correlated. In general, today it is typically understood that Simpson's paradox refers to a situation with observational data and where the relationship between $X$ and $Y$ controlling for $Z$ is the 'true' one. The paradoxical effect of the sign flipping was not the point of Simpson's (1951) paper, however. That this could occur was known much earlier (Yule, 1903). For example, Simpson wrote, "The dangers of amalgamating 2 x 2 tables are well known..." (p. 240). Instead, Simpson's point was that you can't say a-priori that either the disaggregated or aggregated analysis will provide the 'right' answer. You have to know the question, and depending on that, either could be correct. It may be helpful to quote his examples: An investigator wishes to examine whether in a pack of cards the proportion of court cards (King, Queen, Knave) was associated with colour. It happened that the pack which he examined is one with which Baby had been playing, and some of the cards were dirty. He included the classification "dirty" within his scheme, in case it was relevant, and obtained the following probabilities: Table 2 Dirty Clean Court Plain Court Plain Red . . . 4/52 8/52 2/52 12/52 Black . . . 3/52 5/52 3/52 15/52 It will be observed that Baby preferred red cards to black and court cards to plain, but showed no second order interaction on Bartlett's definition. The investigator induced a positive association between redness and plainness both among the dirty cards and among the clean, yet it is the combined table Table 3 Court Plain Red . . . 6/52 20/52 Black . . . 6/52 20/52 which provides what we would call the sensible answer, namely that there is no such association. Suppose we change the names of the classes in Table 2 thus: Table 4 Male Female Untreated Treated Untreated Treated Alive . . . 4/52 8/52 2/52 12/52 Dead . . . 3/52 5/52 3/52 15/52 The probabilities are exactly the same as in Table 2, and there is again the same degree of positive association in each of the 2 x 2 tables. This time we say there is a positive association between treatment and survival among both males and females; but if we combine the tables we again find there is no association between treatment and survival in the combined population. What is the "sensible" interpretation here? The treatment can hardly be rejected as valueless to the race when it is beneficial when it is applied to both males and females. (pp. 240-1) So the point here is different than what Simpson's paradox has become. It is more subtle, and in my opinion, more interesting. What is the 'right' way to analyze a dataset depends on what you are trying to accomplish. In my opinion, the DAG from Pearl that you quote doesn't match what people typically understand as 'Simpson's paradox'. That is, it isn't a case of observational data that are confounded. Instead, the treatment ($X$) seems to be an exogenous cause. In that case, controlling for blood pressure ($Z$) is conditioning on a (partial) mediator. If you did that, it would weaken the total effect measured, because you would only assess the $X \rightarrow Y$ path, whereas the total effect is the sum of both the $X \rightarrow Y\; \&\; X \rightarrow Z \rightarrow Y$. When you lessen the effect measured, it may even become non-significant, depending on the power of the analysis. I'm not saying that Pearl is wrong or that the example is useless. I'm arguing that we need to be very clear and explicit regarding what we're talking about and what we are supposing the investigator wants to achieve. Simpson's counterexample, quoted above, is observational / descriptive in nature. We can also consider a predictive context. With predictive modeling (cf., Shmueli, 2010) the goal is to be able to use the developed model in the future to predict unknown values. It doesn't matter if you have the 'right' $X$ variables, and the relationship between $X$ and $Y$ is not of interest. What matters is whether a predicted value matches the true value with sufficient accuracy. In the typical examples of Simpson's paradox, the confounding grouping, $Z$, is usually implied to be obscure. Now, imagine a predictive situation in which I can get more accurate predictions by taking $Z$ into account, but the model would perform worse if I didn't have the $Z$ values, and end users are extremely unlikely to have them. In that case, a predictive model built without $Z$ would be unambiguously better. Again, that example (such as it is) reflects a different situation with different goals. If you want something that sounds like Pearl's example, consider this: One of the things the doctors who manage emergency rooms are most interested in, is how to move patients through more quickly. There are a couple things to bear in mind here. First, there are generally three paths that patients follow: 1) discharged to home, 2) admitted to hospital, and in between, 3) held for observation for a period of time and then either discharged or admitted. The lengths of time involved is 2 > 3 > 1, with near perfect separation between the three paths. The second thing is that doctors, especially in the ER, are risk-averse. In ambiguous situations, they defer to more extensive treatment, which in this case means a slower path through the ER. Now, imagine a new protocol (checklists, additional tests, etc.) is developed for patients presenting with a certain condition. Implementing this new protocol, on top of everything else that's done, makes each path take longer. However, it yields more appropriate treatment and, importantly, clarifies much of the ambiguity that would have otherwise existed. That means many patients will move through a shorter path than they would otherwise. In this example, an exogenous intervention / treatment ($X$) makes the time through the ER slower within each path / group ($Z$), but isn't independent of group. Moreover, group membership has a large effect on time ($Y$). But the "sensible" interpretation is the change in the marginal distribution of $Y$. References: Shmueli, G. (2010). "To Explain or To Predict?", Statistical Science, 25, 3, pp. 289-310, 2010. Simpson, E.H. (1951). "The Interpretation of Interaction in Contingency Tables". Journal of the Royal Statistical Society, Series B. 13, pp. 238–241. Yule, G.U. (1903). "Notes on the Theory of Association of Attributes in Statistics". Biometrika, 2, 2, pp. 121–134.
Examples of Simpson's Paradox being resolved by choosing the aggregate data
I don't know of a real example, but maybe I can provide some helpful thoughts nonetheless. The first thing is that the nature of "Simpson's paradox" has evolved over time. Today, it is widely known a
Examples of Simpson's Paradox being resolved by choosing the aggregate data I don't know of a real example, but maybe I can provide some helpful thoughts nonetheless. The first thing is that the nature of "Simpson's paradox" has evolved over time. Today, it is widely known as the situation where there is a relationship between two variables (call them $X$ and $Y$) with a given direction, but when including information about a grouping variable ($Z$) that was not previously included, the direction of the relationship between the two variables flips. This is a specific case of a general phenomenon in which relationships can change or even reverse when including more information. It is due to the fact that the two covariates, $X$ and $Z$, are correlated. In general, today it is typically understood that Simpson's paradox refers to a situation with observational data and where the relationship between $X$ and $Y$ controlling for $Z$ is the 'true' one. The paradoxical effect of the sign flipping was not the point of Simpson's (1951) paper, however. That this could occur was known much earlier (Yule, 1903). For example, Simpson wrote, "The dangers of amalgamating 2 x 2 tables are well known..." (p. 240). Instead, Simpson's point was that you can't say a-priori that either the disaggregated or aggregated analysis will provide the 'right' answer. You have to know the question, and depending on that, either could be correct. It may be helpful to quote his examples: An investigator wishes to examine whether in a pack of cards the proportion of court cards (King, Queen, Knave) was associated with colour. It happened that the pack which he examined is one with which Baby had been playing, and some of the cards were dirty. He included the classification "dirty" within his scheme, in case it was relevant, and obtained the following probabilities: Table 2 Dirty Clean Court Plain Court Plain Red . . . 4/52 8/52 2/52 12/52 Black . . . 3/52 5/52 3/52 15/52 It will be observed that Baby preferred red cards to black and court cards to plain, but showed no second order interaction on Bartlett's definition. The investigator induced a positive association between redness and plainness both among the dirty cards and among the clean, yet it is the combined table Table 3 Court Plain Red . . . 6/52 20/52 Black . . . 6/52 20/52 which provides what we would call the sensible answer, namely that there is no such association. Suppose we change the names of the classes in Table 2 thus: Table 4 Male Female Untreated Treated Untreated Treated Alive . . . 4/52 8/52 2/52 12/52 Dead . . . 3/52 5/52 3/52 15/52 The probabilities are exactly the same as in Table 2, and there is again the same degree of positive association in each of the 2 x 2 tables. This time we say there is a positive association between treatment and survival among both males and females; but if we combine the tables we again find there is no association between treatment and survival in the combined population. What is the "sensible" interpretation here? The treatment can hardly be rejected as valueless to the race when it is beneficial when it is applied to both males and females. (pp. 240-1) So the point here is different than what Simpson's paradox has become. It is more subtle, and in my opinion, more interesting. What is the 'right' way to analyze a dataset depends on what you are trying to accomplish. In my opinion, the DAG from Pearl that you quote doesn't match what people typically understand as 'Simpson's paradox'. That is, it isn't a case of observational data that are confounded. Instead, the treatment ($X$) seems to be an exogenous cause. In that case, controlling for blood pressure ($Z$) is conditioning on a (partial) mediator. If you did that, it would weaken the total effect measured, because you would only assess the $X \rightarrow Y$ path, whereas the total effect is the sum of both the $X \rightarrow Y\; \&\; X \rightarrow Z \rightarrow Y$. When you lessen the effect measured, it may even become non-significant, depending on the power of the analysis. I'm not saying that Pearl is wrong or that the example is useless. I'm arguing that we need to be very clear and explicit regarding what we're talking about and what we are supposing the investigator wants to achieve. Simpson's counterexample, quoted above, is observational / descriptive in nature. We can also consider a predictive context. With predictive modeling (cf., Shmueli, 2010) the goal is to be able to use the developed model in the future to predict unknown values. It doesn't matter if you have the 'right' $X$ variables, and the relationship between $X$ and $Y$ is not of interest. What matters is whether a predicted value matches the true value with sufficient accuracy. In the typical examples of Simpson's paradox, the confounding grouping, $Z$, is usually implied to be obscure. Now, imagine a predictive situation in which I can get more accurate predictions by taking $Z$ into account, but the model would perform worse if I didn't have the $Z$ values, and end users are extremely unlikely to have them. In that case, a predictive model built without $Z$ would be unambiguously better. Again, that example (such as it is) reflects a different situation with different goals. If you want something that sounds like Pearl's example, consider this: One of the things the doctors who manage emergency rooms are most interested in, is how to move patients through more quickly. There are a couple things to bear in mind here. First, there are generally three paths that patients follow: 1) discharged to home, 2) admitted to hospital, and in between, 3) held for observation for a period of time and then either discharged or admitted. The lengths of time involved is 2 > 3 > 1, with near perfect separation between the three paths. The second thing is that doctors, especially in the ER, are risk-averse. In ambiguous situations, they defer to more extensive treatment, which in this case means a slower path through the ER. Now, imagine a new protocol (checklists, additional tests, etc.) is developed for patients presenting with a certain condition. Implementing this new protocol, on top of everything else that's done, makes each path take longer. However, it yields more appropriate treatment and, importantly, clarifies much of the ambiguity that would have otherwise existed. That means many patients will move through a shorter path than they would otherwise. In this example, an exogenous intervention / treatment ($X$) makes the time through the ER slower within each path / group ($Z$), but isn't independent of group. Moreover, group membership has a large effect on time ($Y$). But the "sensible" interpretation is the change in the marginal distribution of $Y$. References: Shmueli, G. (2010). "To Explain or To Predict?", Statistical Science, 25, 3, pp. 289-310, 2010. Simpson, E.H. (1951). "The Interpretation of Interaction in Contingency Tables". Journal of the Royal Statistical Society, Series B. 13, pp. 238–241. Yule, G.U. (1903). "Notes on the Theory of Association of Attributes in Statistics". Biometrika, 2, 2, pp. 121–134.
Examples of Simpson's Paradox being resolved by choosing the aggregate data I don't know of a real example, but maybe I can provide some helpful thoughts nonetheless. The first thing is that the nature of "Simpson's paradox" has evolved over time. Today, it is widely known a
15,472
LASSO and ridge from the Bayesian perspective: what about the tuning parameter?
Penalized regression estimators such as LASSO and ridge are said to correspond to Bayesian estimators with certain priors. Yes, that is correct. Whenever we have an optimisation problem involving maximisation of the log-likelihood function plus a penalty function on the parameters, this is mathematically equivalent to posterior maximisation where the penalty function is taken to be the logarithm of a prior kernel.$^\dagger$ To see this, suppose we have a penalty function $w$ using a tuning parameter $\lambda$. The objective function in these cases can be written as: $$\begin{equation} \begin{aligned} H_\mathbf{x}(\theta|\lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) \\[6pt] &= \ln \Big( L_\mathbf{x}(\theta) \cdot \exp ( -w(\theta|\lambda)) \Big) \\[6pt] &= \ln \Bigg( \frac{L_\mathbf{x}(\theta) \pi (\theta|\lambda)}{\int L_\mathbf{x}(\theta) \pi (\theta|\lambda) d\theta} \Bigg) + \text{const} \\[6pt] &= \ln \pi(\theta|\mathbf{x}, \lambda) + \text{const}, \\[6pt] \end{aligned} \end{equation}$$ where we use the prior $\pi(\theta|\lambda) \propto \exp ( -w(\theta|\lambda))$. Observe here that the tuning parameter in the optimisation is treated as a fixed hyperparameter in the prior distribution. If you are undertaking classical optimisation with a fixed tuning parameter, this is equivalent to undertaking a Bayesian optimisation with a fixed hyper-parameter. For LASSO and Ridge regression the penalty functions and corresponding prior-equivalents are: $$\begin{equation} \begin{aligned} \text{LASSO Regression} & & \pi(\theta|\lambda) &= \prod_{k=1}^m \text{Laplace} \Big( 0, \frac{1}{\lambda} \Big) = \prod_{k=1}^m \frac{\lambda}{2} \cdot \exp ( -\lambda |\theta_k| ), \\[6pt] \text{Ridge Regression} & & \pi(\theta|\lambda) &= \prod_{k=1}^m \text{Normal} \Big( 0, \frac{1}{2\lambda} \Big) = \prod_{k=1}^m \sqrt{\lambda/\pi} \cdot \exp ( -\lambda \theta_k^2 ). \\[6pt] \end{aligned} \end{equation}$$ The former method penalises the regression coefficients according to their absolute magnitude, which is the equivalent of imposing a Laplace prior located at zero. The latter method penalises the regression coefficients according to their squared magnitude, which is the equivalent of imposing a normal prior located at zero. Now a frequentist would optimize the tuning parameter by cross validation. Is there a Bayesian equivalent of doing so, and is it used at all? So long as the frequentist method can be posed as an optimisation problem (rather than say, including a hypothesis test, or something like this) there will be a Bayesian analogy using an equivalent prior. Just as the frequentists may treat the tuning parameter $\lambda$ as unknown and estimate this from the data, the Bayesian may similarly treat the hyperparameter $\lambda$ as unknown. In a full Bayesian analysis this would involve giving the hyperparameter its own prior and finding the posterior maximum under this prior, which would be analogous to maximising the following objective function: $$\begin{equation} \begin{aligned} H_\mathbf{x}(\theta, \lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) - h(\lambda) \\[6pt] &= \ln \Big( L_\mathbf{x}(\theta) \cdot \exp ( -w(\theta|\lambda)) \cdot \exp ( -h(\lambda)) \Big) \\[6pt] &= \ln \Bigg( \frac{L_\mathbf{x}(\theta) \pi (\theta|\lambda) \pi (\lambda)}{\int L_\mathbf{x}(\theta) \pi (\theta|\lambda) \pi (\lambda) d\theta} \Bigg) + \text{const} \\[6pt] &= \ln \pi(\theta, \lambda|\mathbf{x}) + \text{const}. \\[6pt] \end{aligned} \end{equation}$$ This method is indeed used in Bayesian analysis in cases where the analyst is not comfortable choosing a specific hyperparameter for their prior, and seeks to make the prior more diffuse by treating it as unknown and giving it a distribution. (Note that this is just an implicit way of giving a more diffuse prior to the parameter of interest $\theta$.) (Comment from statslearner2 below) I'm looking for numerical equivalent MAP estimates. For instance, for a fixed penalty Ridge there is a gaussian prior that will give me the MAP estimate exactly equal the ridge estimate. Now, for k-fold CV ridge, what is the hyper-prior that would give me the MAP estimate which is similar to the CV-ridge estimate? Before proceeding to look at $K$-fold cross-validation, it is first worth noting that, mathematically, the maximum a posteriori (MAP) method is simply an optimisation of a function of the parameter $\theta$ and the data $\mathbf{x}$. If you are willing to allow improper priors then the scope encapsulates any optimisation problem involving a function of these variables. Thus, any frequentist method that can be framed as a single optimisation problem of this kind has a MAP analogy, and any frequentist method that cannot be framed as a single optimisation of this kind does not have a MAP analogy. In the above form of model, involving a penalty function with a tuning parameter, $K$-fold cross-validation is commonly used to estimate the tuning parameter $\lambda$. For this method you partition the data vector $\mathbb{x}$ into $K$ sub-vectors $\mathbf{x}_1,...,\mathbf{x}_K$. For each of sub-vector $k=1,...,K$ you fit the model with the "training" data $\mathbf{x}_{-k}$ and then measure the fit of the model with the "testing" data $\mathbf{x}_k$. In each fit you get an estimator for the model parameters, which then gives you predictions of the testing data, which can then be compared to the actual testing data to give a measure of "loss": $$\begin{matrix} \text{Estimator} & & \hat{\theta}(\mathbf{x}_{-k}, \lambda), \\[6pt] \text{Predictions} & & \hat{\mathbf{x}}_k(\mathbf{x}_{-k}, \lambda), \\[6pt] \text{Testing loss} & & \mathscr{L}_k(\hat{\mathbf{x}}_k, \mathbf{x}_k| \mathbf{x}_{-k}, \lambda). \\[6pt] \end{matrix}$$ The loss measures for each of the $K$ "folds" can then be aggregated to get an overall loss measure for the cross-validation: $$\mathscr{L}(\mathbf{x}, \lambda) = \sum_k \mathscr{L}_k(\hat{\mathbf{x}}_k, \mathbf{x}_k| \mathbf{x}_{-k}, \lambda)$$ One then estimates the tuning parameter by minimising the overall loss measure: $$\hat{\lambda} \equiv \hat{\lambda}(\mathbf{x}) \equiv \underset{\lambda}{\text{arg min }} \mathscr{L}(\mathbf{x}, \lambda).$$ We can see that this is an optimisation problem, and so we now have two seperate optimisation problems (i.e., the one described in the sections above for $\theta$, and the one described here for $\lambda$). Since the latter optimisation does not involve $\theta$, we can combine these optimisations into a single problem, with some technicalities that I discuss below. To do this, consider the optimisation problem with objective function: $$\begin{equation} \begin{aligned} \mathcal{H}_\mathbf{x}(\theta, \lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) - \delta \mathscr{L}(\mathbf{x}, \lambda), \\[6pt] \end{aligned} \end{equation}$$ where $\delta > 0$ is a weighting value on the tuning-loss. As $\delta \rightarrow \infty$ the weight on optimisation of the tuning-loss becomes infinite and so the optimisation problem yields the estimated tuning parameter from $K$-fold cross-validation (in the limit). The remaining part of the objective function is the standard objective function conditional on this estimated value of the tuning parameter. Now, unfortunately, taking $\delta = \infty$ screws up the optimisation problem, but if we take $\delta$ to be a very large (but still finite) value, we can approximate the combination of the two optimisation problems up to arbitrary accuracy. From the above analysis we can see that it is possible to form a MAP analogy to the model-fitting and $K$-fold cross-validation process. This is not an exact analogy, but it is a close analogy, up to arbitrary accuracy. It is also important to note that the MAP analogy no longer shares the same likelihood function as the original problem, since the loss function depends on the data and is thus absorbed as part of the likelihood rather than the prior. In fact, the full analogy is as follows: $$\begin{equation} \begin{aligned} \mathcal{H}_\mathbf{x}(\theta, \lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) - \delta \mathscr{L}(\mathbf{x}, \lambda) \\[6pt] &= \ln \Bigg( \frac{L_\mathbf{x}^*(\theta, \lambda) \pi (\theta, \lambda)}{\int L_\mathbf{x}^*(\theta, \lambda) \pi (\theta, \lambda) d\theta} \Bigg) + \text{const}, \\[6pt] \end{aligned} \end{equation}$$ where $L_\mathbf{x}^*(\theta, \lambda) \propto \exp( \ell_\mathbf{x}(\theta) - \delta \mathscr{L}(\mathbf{x}, \lambda))$ and $\pi (\theta, \lambda) \propto \exp( -w(\theta|\lambda))$, with a fixed (and very large) hyper-parameter $\delta$. (Note: For a related question looking at logistic ridge regression framed in Bayesian terms see here.) $^\dagger$ This gives an improper prior in cases where the penalty does not correspond to the logarithm of a sigma-finite density.
LASSO and ridge from the Bayesian perspective: what about the tuning parameter?
Penalized regression estimators such as LASSO and ridge are said to correspond to Bayesian estimators with certain priors. Yes, that is correct. Whenever we have an optimisation problem involving ma
LASSO and ridge from the Bayesian perspective: what about the tuning parameter? Penalized regression estimators such as LASSO and ridge are said to correspond to Bayesian estimators with certain priors. Yes, that is correct. Whenever we have an optimisation problem involving maximisation of the log-likelihood function plus a penalty function on the parameters, this is mathematically equivalent to posterior maximisation where the penalty function is taken to be the logarithm of a prior kernel.$^\dagger$ To see this, suppose we have a penalty function $w$ using a tuning parameter $\lambda$. The objective function in these cases can be written as: $$\begin{equation} \begin{aligned} H_\mathbf{x}(\theta|\lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) \\[6pt] &= \ln \Big( L_\mathbf{x}(\theta) \cdot \exp ( -w(\theta|\lambda)) \Big) \\[6pt] &= \ln \Bigg( \frac{L_\mathbf{x}(\theta) \pi (\theta|\lambda)}{\int L_\mathbf{x}(\theta) \pi (\theta|\lambda) d\theta} \Bigg) + \text{const} \\[6pt] &= \ln \pi(\theta|\mathbf{x}, \lambda) + \text{const}, \\[6pt] \end{aligned} \end{equation}$$ where we use the prior $\pi(\theta|\lambda) \propto \exp ( -w(\theta|\lambda))$. Observe here that the tuning parameter in the optimisation is treated as a fixed hyperparameter in the prior distribution. If you are undertaking classical optimisation with a fixed tuning parameter, this is equivalent to undertaking a Bayesian optimisation with a fixed hyper-parameter. For LASSO and Ridge regression the penalty functions and corresponding prior-equivalents are: $$\begin{equation} \begin{aligned} \text{LASSO Regression} & & \pi(\theta|\lambda) &= \prod_{k=1}^m \text{Laplace} \Big( 0, \frac{1}{\lambda} \Big) = \prod_{k=1}^m \frac{\lambda}{2} \cdot \exp ( -\lambda |\theta_k| ), \\[6pt] \text{Ridge Regression} & & \pi(\theta|\lambda) &= \prod_{k=1}^m \text{Normal} \Big( 0, \frac{1}{2\lambda} \Big) = \prod_{k=1}^m \sqrt{\lambda/\pi} \cdot \exp ( -\lambda \theta_k^2 ). \\[6pt] \end{aligned} \end{equation}$$ The former method penalises the regression coefficients according to their absolute magnitude, which is the equivalent of imposing a Laplace prior located at zero. The latter method penalises the regression coefficients according to their squared magnitude, which is the equivalent of imposing a normal prior located at zero. Now a frequentist would optimize the tuning parameter by cross validation. Is there a Bayesian equivalent of doing so, and is it used at all? So long as the frequentist method can be posed as an optimisation problem (rather than say, including a hypothesis test, or something like this) there will be a Bayesian analogy using an equivalent prior. Just as the frequentists may treat the tuning parameter $\lambda$ as unknown and estimate this from the data, the Bayesian may similarly treat the hyperparameter $\lambda$ as unknown. In a full Bayesian analysis this would involve giving the hyperparameter its own prior and finding the posterior maximum under this prior, which would be analogous to maximising the following objective function: $$\begin{equation} \begin{aligned} H_\mathbf{x}(\theta, \lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) - h(\lambda) \\[6pt] &= \ln \Big( L_\mathbf{x}(\theta) \cdot \exp ( -w(\theta|\lambda)) \cdot \exp ( -h(\lambda)) \Big) \\[6pt] &= \ln \Bigg( \frac{L_\mathbf{x}(\theta) \pi (\theta|\lambda) \pi (\lambda)}{\int L_\mathbf{x}(\theta) \pi (\theta|\lambda) \pi (\lambda) d\theta} \Bigg) + \text{const} \\[6pt] &= \ln \pi(\theta, \lambda|\mathbf{x}) + \text{const}. \\[6pt] \end{aligned} \end{equation}$$ This method is indeed used in Bayesian analysis in cases where the analyst is not comfortable choosing a specific hyperparameter for their prior, and seeks to make the prior more diffuse by treating it as unknown and giving it a distribution. (Note that this is just an implicit way of giving a more diffuse prior to the parameter of interest $\theta$.) (Comment from statslearner2 below) I'm looking for numerical equivalent MAP estimates. For instance, for a fixed penalty Ridge there is a gaussian prior that will give me the MAP estimate exactly equal the ridge estimate. Now, for k-fold CV ridge, what is the hyper-prior that would give me the MAP estimate which is similar to the CV-ridge estimate? Before proceeding to look at $K$-fold cross-validation, it is first worth noting that, mathematically, the maximum a posteriori (MAP) method is simply an optimisation of a function of the parameter $\theta$ and the data $\mathbf{x}$. If you are willing to allow improper priors then the scope encapsulates any optimisation problem involving a function of these variables. Thus, any frequentist method that can be framed as a single optimisation problem of this kind has a MAP analogy, and any frequentist method that cannot be framed as a single optimisation of this kind does not have a MAP analogy. In the above form of model, involving a penalty function with a tuning parameter, $K$-fold cross-validation is commonly used to estimate the tuning parameter $\lambda$. For this method you partition the data vector $\mathbb{x}$ into $K$ sub-vectors $\mathbf{x}_1,...,\mathbf{x}_K$. For each of sub-vector $k=1,...,K$ you fit the model with the "training" data $\mathbf{x}_{-k}$ and then measure the fit of the model with the "testing" data $\mathbf{x}_k$. In each fit you get an estimator for the model parameters, which then gives you predictions of the testing data, which can then be compared to the actual testing data to give a measure of "loss": $$\begin{matrix} \text{Estimator} & & \hat{\theta}(\mathbf{x}_{-k}, \lambda), \\[6pt] \text{Predictions} & & \hat{\mathbf{x}}_k(\mathbf{x}_{-k}, \lambda), \\[6pt] \text{Testing loss} & & \mathscr{L}_k(\hat{\mathbf{x}}_k, \mathbf{x}_k| \mathbf{x}_{-k}, \lambda). \\[6pt] \end{matrix}$$ The loss measures for each of the $K$ "folds" can then be aggregated to get an overall loss measure for the cross-validation: $$\mathscr{L}(\mathbf{x}, \lambda) = \sum_k \mathscr{L}_k(\hat{\mathbf{x}}_k, \mathbf{x}_k| \mathbf{x}_{-k}, \lambda)$$ One then estimates the tuning parameter by minimising the overall loss measure: $$\hat{\lambda} \equiv \hat{\lambda}(\mathbf{x}) \equiv \underset{\lambda}{\text{arg min }} \mathscr{L}(\mathbf{x}, \lambda).$$ We can see that this is an optimisation problem, and so we now have two seperate optimisation problems (i.e., the one described in the sections above for $\theta$, and the one described here for $\lambda$). Since the latter optimisation does not involve $\theta$, we can combine these optimisations into a single problem, with some technicalities that I discuss below. To do this, consider the optimisation problem with objective function: $$\begin{equation} \begin{aligned} \mathcal{H}_\mathbf{x}(\theta, \lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) - \delta \mathscr{L}(\mathbf{x}, \lambda), \\[6pt] \end{aligned} \end{equation}$$ where $\delta > 0$ is a weighting value on the tuning-loss. As $\delta \rightarrow \infty$ the weight on optimisation of the tuning-loss becomes infinite and so the optimisation problem yields the estimated tuning parameter from $K$-fold cross-validation (in the limit). The remaining part of the objective function is the standard objective function conditional on this estimated value of the tuning parameter. Now, unfortunately, taking $\delta = \infty$ screws up the optimisation problem, but if we take $\delta$ to be a very large (but still finite) value, we can approximate the combination of the two optimisation problems up to arbitrary accuracy. From the above analysis we can see that it is possible to form a MAP analogy to the model-fitting and $K$-fold cross-validation process. This is not an exact analogy, but it is a close analogy, up to arbitrary accuracy. It is also important to note that the MAP analogy no longer shares the same likelihood function as the original problem, since the loss function depends on the data and is thus absorbed as part of the likelihood rather than the prior. In fact, the full analogy is as follows: $$\begin{equation} \begin{aligned} \mathcal{H}_\mathbf{x}(\theta, \lambda) &= \ell_\mathbf{x}(\theta) - w(\theta|\lambda) - \delta \mathscr{L}(\mathbf{x}, \lambda) \\[6pt] &= \ln \Bigg( \frac{L_\mathbf{x}^*(\theta, \lambda) \pi (\theta, \lambda)}{\int L_\mathbf{x}^*(\theta, \lambda) \pi (\theta, \lambda) d\theta} \Bigg) + \text{const}, \\[6pt] \end{aligned} \end{equation}$$ where $L_\mathbf{x}^*(\theta, \lambda) \propto \exp( \ell_\mathbf{x}(\theta) - \delta \mathscr{L}(\mathbf{x}, \lambda))$ and $\pi (\theta, \lambda) \propto \exp( -w(\theta|\lambda))$, with a fixed (and very large) hyper-parameter $\delta$. (Note: For a related question looking at logistic ridge regression framed in Bayesian terms see here.) $^\dagger$ This gives an improper prior in cases where the penalty does not correspond to the logarithm of a sigma-finite density.
LASSO and ridge from the Bayesian perspective: what about the tuning parameter? Penalized regression estimators such as LASSO and ridge are said to correspond to Bayesian estimators with certain priors. Yes, that is correct. Whenever we have an optimisation problem involving ma
15,473
LASSO and ridge from the Bayesian perspective: what about the tuning parameter?
Indeed most penalized regression methods correspond to placing a particular type of prior to the regression coefficients. For example, you get the LASSO using a Laplace prior, and the ridge using a normal prior. The tuning parameters are the “hyperparameters” under the Bayesian formulation for which you can place an additional prior to estimate them; for example, for in the case of the ridge it is often assumed that the inverse variance of the normal distribution has a $\chi^2$ prior. However, as one would expect, resulting inferences can be sensitive to the choice of the prior distributions for these hyperparameters. For example, for the horseshoe prior there are some theoretical results that you should place such a prior for the hyperparameters that it would reflect the number of non-zero coefficients you expect to have. A nice overview of the links between penalized regression and Bayesian priors is given, for example, by Mallick and Yi.
LASSO and ridge from the Bayesian perspective: what about the tuning parameter?
Indeed most penalized regression methods correspond to placing a particular type of prior to the regression coefficients. For example, you get the LASSO using a Laplace prior, and the ridge using a no
LASSO and ridge from the Bayesian perspective: what about the tuning parameter? Indeed most penalized regression methods correspond to placing a particular type of prior to the regression coefficients. For example, you get the LASSO using a Laplace prior, and the ridge using a normal prior. The tuning parameters are the “hyperparameters” under the Bayesian formulation for which you can place an additional prior to estimate them; for example, for in the case of the ridge it is often assumed that the inverse variance of the normal distribution has a $\chi^2$ prior. However, as one would expect, resulting inferences can be sensitive to the choice of the prior distributions for these hyperparameters. For example, for the horseshoe prior there are some theoretical results that you should place such a prior for the hyperparameters that it would reflect the number of non-zero coefficients you expect to have. A nice overview of the links between penalized regression and Bayesian priors is given, for example, by Mallick and Yi.
LASSO and ridge from the Bayesian perspective: what about the tuning parameter? Indeed most penalized regression methods correspond to placing a particular type of prior to the regression coefficients. For example, you get the LASSO using a Laplace prior, and the ridge using a no
15,474
What's the relation between game theory and reinforcement learning?
In Reinforcement Learning (RL) it is common to imagine an underlying Markov Decision Process (MDP). Then the goal of RL is to learn a good policy for the MDP, which is often only partially specified. MDPs can have different objectives such as total, average, or discounted reward, where discounted reward is the most common assumption for RL. There are well-studied extensions of MDPs to two-player (i.e., game) settings; see, e.g., Filar, Jerzy, and Koos Vrieze. Competitive Markov decision processes. Springer Science & Business Media, 2012. There is an underlying theory shared by MDPs and their extensions to two-player (zero-sum) games, including, e.g., the Banach fixed point theorem, Value Iteration, Bellman Optimality, Policy Iteration/Strategy Improvement etc. However, while there are these close connections between MDPs (and thus RL) and these specific type of games: you can learn about RL (and MDPs) directly, without GT as a prerequisite; anyway, you would not learn about this stuff in the majority of GT courses (which would normally be focused on, e.g., strategic-form, extensive-form, and repeated games, but not the state-based infinite games that generalize MDPs).
What's the relation between game theory and reinforcement learning?
In Reinforcement Learning (RL) it is common to imagine an underlying Markov Decision Process (MDP). Then the goal of RL is to learn a good policy for the MDP, which is often only partially specified.
What's the relation between game theory and reinforcement learning? In Reinforcement Learning (RL) it is common to imagine an underlying Markov Decision Process (MDP). Then the goal of RL is to learn a good policy for the MDP, which is often only partially specified. MDPs can have different objectives such as total, average, or discounted reward, where discounted reward is the most common assumption for RL. There are well-studied extensions of MDPs to two-player (i.e., game) settings; see, e.g., Filar, Jerzy, and Koos Vrieze. Competitive Markov decision processes. Springer Science & Business Media, 2012. There is an underlying theory shared by MDPs and their extensions to two-player (zero-sum) games, including, e.g., the Banach fixed point theorem, Value Iteration, Bellman Optimality, Policy Iteration/Strategy Improvement etc. However, while there are these close connections between MDPs (and thus RL) and these specific type of games: you can learn about RL (and MDPs) directly, without GT as a prerequisite; anyway, you would not learn about this stuff in the majority of GT courses (which would normally be focused on, e.g., strategic-form, extensive-form, and repeated games, but not the state-based infinite games that generalize MDPs).
What's the relation between game theory and reinforcement learning? In Reinforcement Learning (RL) it is common to imagine an underlying Markov Decision Process (MDP). Then the goal of RL is to learn a good policy for the MDP, which is often only partially specified.
15,475
What's the relation between game theory and reinforcement learning?
Game theory is quite involved in the context of Multi-agent Reinforcement learning (MARL). Take a look at stochastic games or read the article An Analysis of Stochastic Game Theory for Multiagent Reinforcement Learning. I would not see GT as a prerequisite for RL. However, it provides a nice extension to the multi-agent case.
What's the relation between game theory and reinforcement learning?
Game theory is quite involved in the context of Multi-agent Reinforcement learning (MARL). Take a look at stochastic games or read the article An Analysis of Stochastic Game Theory for Multiagent Rei
What's the relation between game theory and reinforcement learning? Game theory is quite involved in the context of Multi-agent Reinforcement learning (MARL). Take a look at stochastic games or read the article An Analysis of Stochastic Game Theory for Multiagent Reinforcement Learning. I would not see GT as a prerequisite for RL. However, it provides a nice extension to the multi-agent case.
What's the relation between game theory and reinforcement learning? Game theory is quite involved in the context of Multi-agent Reinforcement learning (MARL). Take a look at stochastic games or read the article An Analysis of Stochastic Game Theory for Multiagent Rei
15,476
What's the relation between game theory and reinforcement learning?
RL: A single agent is trained to solve a Markov decision problem (MDPS). GT: Two agents are trained to solve Games. A multi-agent Reinforcement learning (MARL) can be used to solve for stochastic games. If you are interested in the single-agent application of RL in deep learning, then you do not need to go for any GT course. For two or more agents you may need to know the game-theoretic techniques.
What's the relation between game theory and reinforcement learning?
RL: A single agent is trained to solve a Markov decision problem (MDPS). GT: Two agents are trained to solve Games. A multi-agent Reinforcement learning (MARL) can be used to solve for stochastic game
What's the relation between game theory and reinforcement learning? RL: A single agent is trained to solve a Markov decision problem (MDPS). GT: Two agents are trained to solve Games. A multi-agent Reinforcement learning (MARL) can be used to solve for stochastic games. If you are interested in the single-agent application of RL in deep learning, then you do not need to go for any GT course. For two or more agents you may need to know the game-theoretic techniques.
What's the relation between game theory and reinforcement learning? RL: A single agent is trained to solve a Markov decision problem (MDPS). GT: Two agents are trained to solve Games. A multi-agent Reinforcement learning (MARL) can be used to solve for stochastic game
15,477
What's the relation between game theory and reinforcement learning?
If you already know game theory you may see many parallels with reinforcement learning with multiple agents. Decision theory which is essentially game theory with one player is a second area that similar and perhaps a closer match for single agent settings. Strict Domination and Backwards Induction solution concepts map to the main steps used in the rl policy iteration algorithm which does a value function BI estimation followed by greedification step SD The fields seem to diverge in some respects, game theory tends to makes strong assumptions on strategies being fully specified ahead of time and players being rational even when faced with an infinite decision tree. RL looks to solving these online and with minimal computational resources. In this sense rl offers a more realistic and algorithmic approach to solving essentially the same class of problems. The MDP Markov decision process used to formalise rl makes use of the markov property on the state which means rl decisions are made based on the current state and lack memory of earlier actions [unless explicitly included in the state].
What's the relation between game theory and reinforcement learning?
If you already know game theory you may see many parallels with reinforcement learning with multiple agents. Decision theory which is essentially game theory with one player is a second area that simi
What's the relation between game theory and reinforcement learning? If you already know game theory you may see many parallels with reinforcement learning with multiple agents. Decision theory which is essentially game theory with one player is a second area that similar and perhaps a closer match for single agent settings. Strict Domination and Backwards Induction solution concepts map to the main steps used in the rl policy iteration algorithm which does a value function BI estimation followed by greedification step SD The fields seem to diverge in some respects, game theory tends to makes strong assumptions on strategies being fully specified ahead of time and players being rational even when faced with an infinite decision tree. RL looks to solving these online and with minimal computational resources. In this sense rl offers a more realistic and algorithmic approach to solving essentially the same class of problems. The MDP Markov decision process used to formalise rl makes use of the markov property on the state which means rl decisions are made based on the current state and lack memory of earlier actions [unless explicitly included in the state].
What's the relation between game theory and reinforcement learning? If you already know game theory you may see many parallels with reinforcement learning with multiple agents. Decision theory which is essentially game theory with one player is a second area that simi
15,478
What's the relation between game theory and reinforcement learning?
RL environment can be modelled using MDP(Markov Decision Process), in case you are dealing with one single agent. If the environment consists of multiple agents, in this case it is called MultiAgent RL (MARL), then Game Theory (GT) may help. GT is used with MARL when there exists any sort of competition between the agents. But, if your agents will be fully cooperative (meaning that the agents cooperate together to achieve a common goal), in this case you may need to find some other approaches for coordination. MARL settings are divided into three categories: Competitive in which the agents have conflicting interests; each wants to maximize its own reward (e.g. , minmax algorithm in game theory). Cooperative in which all the agents coordinate and cooperate to maximize a shared reward. Mixed mode, it is hybridized from both.
What's the relation between game theory and reinforcement learning?
RL environment can be modelled using MDP(Markov Decision Process), in case you are dealing with one single agent. If the environment consists of multiple agents, in this case it is called MultiAgent R
What's the relation between game theory and reinforcement learning? RL environment can be modelled using MDP(Markov Decision Process), in case you are dealing with one single agent. If the environment consists of multiple agents, in this case it is called MultiAgent RL (MARL), then Game Theory (GT) may help. GT is used with MARL when there exists any sort of competition between the agents. But, if your agents will be fully cooperative (meaning that the agents cooperate together to achieve a common goal), in this case you may need to find some other approaches for coordination. MARL settings are divided into three categories: Competitive in which the agents have conflicting interests; each wants to maximize its own reward (e.g. , minmax algorithm in game theory). Cooperative in which all the agents coordinate and cooperate to maximize a shared reward. Mixed mode, it is hybridized from both.
What's the relation between game theory and reinforcement learning? RL environment can be modelled using MDP(Markov Decision Process), in case you are dealing with one single agent. If the environment consists of multiple agents, in this case it is called MultiAgent R
15,479
why boosting method is sensitive to outliers
Outliers can be bad for boosting because boosting builds each tree on previous trees' residuals/errors. Outliers will have much larger residuals than non-outliers, so gradient boosting will focus a disproportionate amount of its attention on those points.
why boosting method is sensitive to outliers
Outliers can be bad for boosting because boosting builds each tree on previous trees' residuals/errors. Outliers will have much larger residuals than non-outliers, so gradient boosting will focus a di
why boosting method is sensitive to outliers Outliers can be bad for boosting because boosting builds each tree on previous trees' residuals/errors. Outliers will have much larger residuals than non-outliers, so gradient boosting will focus a disproportionate amount of its attention on those points.
why boosting method is sensitive to outliers Outliers can be bad for boosting because boosting builds each tree on previous trees' residuals/errors. Outliers will have much larger residuals than non-outliers, so gradient boosting will focus a di
15,480
why boosting method is sensitive to outliers
The algorithms you specified are for classification, so I'm assuming you don't mean outliers in the target variable, but input variable outliers. Boosted Tree methods should be fairly robust to outliers in the input features since the base learners are tree splits. For example, if the split is x > 3 then 5 and 5,000,000 are treated the same. This may or may not be a good thing, but that's a different question. If instead you were talking about regression and outliers in the target variable, then sensitivity of boosted tree methods would depend on the cost function used. Of course, squared error is sensitive to outliers because the difference is squared and that will highly influence the next tree since boosting attempts to fit the (gradient of the) loss. However, there are more robust error functions that can be used for boosted tree methods like Huber loss and Absolute Loss.
why boosting method is sensitive to outliers
The algorithms you specified are for classification, so I'm assuming you don't mean outliers in the target variable, but input variable outliers. Boosted Tree methods should be fairly robust to outli
why boosting method is sensitive to outliers The algorithms you specified are for classification, so I'm assuming you don't mean outliers in the target variable, but input variable outliers. Boosted Tree methods should be fairly robust to outliers in the input features since the base learners are tree splits. For example, if the split is x > 3 then 5 and 5,000,000 are treated the same. This may or may not be a good thing, but that's a different question. If instead you were talking about regression and outliers in the target variable, then sensitivity of boosted tree methods would depend on the cost function used. Of course, squared error is sensitive to outliers because the difference is squared and that will highly influence the next tree since boosting attempts to fit the (gradient of the) loss. However, there are more robust error functions that can be used for boosted tree methods like Huber loss and Absolute Loss.
why boosting method is sensitive to outliers The algorithms you specified are for classification, so I'm assuming you don't mean outliers in the target variable, but input variable outliers. Boosted Tree methods should be fairly robust to outli
15,481
why boosting method is sensitive to outliers
A nice literature review of this topic can be found in Alexander Hanbo Li and Jelena Bradic "Boosting in the presence of outliers: adaptive classification with non-convex loss functions" Journal of the American Statistical Association. 2018. Preprint link: https://arxiv.org/abs/1510.01064 Recent advances in technologies for cheaper and faster data acquisition and storage have led to an explosive growth of data complexity in a variety of research areas such as high-throughput genomics, biomedical imaging, high-energy physics, astronomy and economics. As a result, noise accumulation, experimental variation and data inhomogeneity have become substantial. Therefore, developing classification methods that are highly efficient and accurate in such settings, is a problem that is of great practical importance. However, classification in such settings is known to poses many statistical challenges and calls for new methods and theories. For binary classification problems, we assume the presence of separable, noiseless data that belong to two classes and in which an adversary has corrupted a number of observations from both classes independently. There are a number of setups that belong to this general framework. A random flipped label design, in which the labels of the class membership were randomly flipped, is one example that can occur very frequently, as labeling is prone to a number of errors, human or otherwise. Another example is the presence of outliers in the observations, in which a small number of observations from both classes have a variance that is larger than the noise of the rest of the observations. Such situations may naturally occur with the new era of big and heterogeneous data, in which data are corrupted (arbitrarily or maliciously) and subgroups may behave differently; a subgroup might only be one or a few individuals in small studies that would appear to be outliers within class data. Considerable effort has therefore been focused on finding methods that adapt to the relative error in the data. Although this has resulted in algorithms, e.g. Grünwald and Dawid (2004), that achieve provable guarantees (Natarajan et al., 2013; Kanamori et.al, 2007) when contamination model (Scott et al., 2013) is known or when multiple noisy copies of the data are available (Cesa-Bianchi et al., 2011), good generalization errors in the test set are by no means guaranteed. This problem is compounded when the contamination model is unknown, where outliers need to be detected automatically. Despite progress on outlier-removing algorithms, significant practical challenges (due to exceedingly restrictive conditions imposed therein) remain. In this paper, we concentrate on the ensemble algorithms. Among these, AdaBoost (Freund and Schapire, 1997) has proven to be simple and effective in solving classification problems of many different kinds. The aesthetics and simplicity of AdaBoost and other forward greedy algorithms, such as LogitBoost (Friedman, et al., 2000), also facilitated a tacit defense from overfitting, especially when combined with early termination of the algorithm (Zhang and Yu, 2005). Friedman, et al. (2000) developed a powerful statistical perspective, which views AdaBoost as a gradient-based incremental search for a good additive model using the exponential loss. The gradient boosting (Friedman, 2001) and AnyBoost (Mason et al., 1999) have used this approach to generalize the boosting idea to wider families of problems and loss functions. This criterion was motivated by the fact that the exponential loss is a convex surrogate of the hinge or 0 − 1 loss. Nevertheless, in the presence of label noise and/or outliers, the performance of all of them deteriorates rapidly (Dietterich, 2000). Although algorithms like LogitBoost, MadaBoost (Domingo and Watanabe, 2000), Log-lossBoost (Collins, et al., 2002) are able to better tolerate noise than AdaBoost, they are still not insensitive to outliers. Hence, they are efficient when the data is observed with little or no noise. However, Long and Servedio (2010) pointed out that any boosting algorithm with convex loss functions is highly susceptible to a random label noise model. They constructed a simple example, from hereon denoted Long/Servedio problem, that cannot be “learned” by the boosting algorithms above.
why boosting method is sensitive to outliers
A nice literature review of this topic can be found in Alexander Hanbo Li and Jelena Bradic "Boosting in the presence of outliers: adaptive classification with non-convex loss functions" Journal of t
why boosting method is sensitive to outliers A nice literature review of this topic can be found in Alexander Hanbo Li and Jelena Bradic "Boosting in the presence of outliers: adaptive classification with non-convex loss functions" Journal of the American Statistical Association. 2018. Preprint link: https://arxiv.org/abs/1510.01064 Recent advances in technologies for cheaper and faster data acquisition and storage have led to an explosive growth of data complexity in a variety of research areas such as high-throughput genomics, biomedical imaging, high-energy physics, astronomy and economics. As a result, noise accumulation, experimental variation and data inhomogeneity have become substantial. Therefore, developing classification methods that are highly efficient and accurate in such settings, is a problem that is of great practical importance. However, classification in such settings is known to poses many statistical challenges and calls for new methods and theories. For binary classification problems, we assume the presence of separable, noiseless data that belong to two classes and in which an adversary has corrupted a number of observations from both classes independently. There are a number of setups that belong to this general framework. A random flipped label design, in which the labels of the class membership were randomly flipped, is one example that can occur very frequently, as labeling is prone to a number of errors, human or otherwise. Another example is the presence of outliers in the observations, in which a small number of observations from both classes have a variance that is larger than the noise of the rest of the observations. Such situations may naturally occur with the new era of big and heterogeneous data, in which data are corrupted (arbitrarily or maliciously) and subgroups may behave differently; a subgroup might only be one or a few individuals in small studies that would appear to be outliers within class data. Considerable effort has therefore been focused on finding methods that adapt to the relative error in the data. Although this has resulted in algorithms, e.g. Grünwald and Dawid (2004), that achieve provable guarantees (Natarajan et al., 2013; Kanamori et.al, 2007) when contamination model (Scott et al., 2013) is known or when multiple noisy copies of the data are available (Cesa-Bianchi et al., 2011), good generalization errors in the test set are by no means guaranteed. This problem is compounded when the contamination model is unknown, where outliers need to be detected automatically. Despite progress on outlier-removing algorithms, significant practical challenges (due to exceedingly restrictive conditions imposed therein) remain. In this paper, we concentrate on the ensemble algorithms. Among these, AdaBoost (Freund and Schapire, 1997) has proven to be simple and effective in solving classification problems of many different kinds. The aesthetics and simplicity of AdaBoost and other forward greedy algorithms, such as LogitBoost (Friedman, et al., 2000), also facilitated a tacit defense from overfitting, especially when combined with early termination of the algorithm (Zhang and Yu, 2005). Friedman, et al. (2000) developed a powerful statistical perspective, which views AdaBoost as a gradient-based incremental search for a good additive model using the exponential loss. The gradient boosting (Friedman, 2001) and AnyBoost (Mason et al., 1999) have used this approach to generalize the boosting idea to wider families of problems and loss functions. This criterion was motivated by the fact that the exponential loss is a convex surrogate of the hinge or 0 − 1 loss. Nevertheless, in the presence of label noise and/or outliers, the performance of all of them deteriorates rapidly (Dietterich, 2000). Although algorithms like LogitBoost, MadaBoost (Domingo and Watanabe, 2000), Log-lossBoost (Collins, et al., 2002) are able to better tolerate noise than AdaBoost, they are still not insensitive to outliers. Hence, they are efficient when the data is observed with little or no noise. However, Long and Servedio (2010) pointed out that any boosting algorithm with convex loss functions is highly susceptible to a random label noise model. They constructed a simple example, from hereon denoted Long/Servedio problem, that cannot be “learned” by the boosting algorithms above.
why boosting method is sensitive to outliers A nice literature review of this topic can be found in Alexander Hanbo Li and Jelena Bradic "Boosting in the presence of outliers: adaptive classification with non-convex loss functions" Journal of t
15,482
why boosting method is sensitive to outliers
In boosting we try to pick the dataset on which the algorithm results were poor instead of randomly choosing the subset of data. These hard examples are important ones to learn, so if the data set has a lot of outliers and algorithm is not performing good on those ones than to learn those hard examples algorithm will try to pick subsets with those examples.
why boosting method is sensitive to outliers
In boosting we try to pick the dataset on which the algorithm results were poor instead of randomly choosing the subset of data. These hard examples are important ones to learn, so if the data set has
why boosting method is sensitive to outliers In boosting we try to pick the dataset on which the algorithm results were poor instead of randomly choosing the subset of data. These hard examples are important ones to learn, so if the data set has a lot of outliers and algorithm is not performing good on those ones than to learn those hard examples algorithm will try to pick subsets with those examples.
why boosting method is sensitive to outliers In boosting we try to pick the dataset on which the algorithm results were poor instead of randomly choosing the subset of data. These hard examples are important ones to learn, so if the data set has
15,483
Use of nested cross-validation
Nested cross-validation is used to avoid optimistically biased estimates of performance that result from using the same cross-validation to set the values of the hyper-parameters of the model (e.g. the regularisation parameter, $C$, and kernel parameters of an SVM) and performance estimation. I wrote a paper on this topic after being rather alarmed by the magnitude of the bias introduced by a seemingly benign short cut often used in the evaluation of kernel machines. I investigated this topic in order to discover why my results were worse than other research groups using similar methods on the same datasets, the reason turned out to be that I was using nested cross-validation and hence didn't benefit from the optimistic bias. G. C. Cawley and N. L. C. Talbot, Over-fitting in model selection and subsequent selection bias in performance evaluation, Journal of Machine Learning Research, 2010. Research, vol. 11, pp. 2079-2107, July 2010. (http://jmlr.org/papers/volume11/cawley10a/cawley10a.pdf) The reasons for the bias with illustrative examples and experimental evaluation can be found in the paper, but essentially the point is that if the performance evaluation criterion is used in any way to make choices about the model, then those choices are based on (i) genuine improvements in generalisation performance and (ii) the statistical peculiarities of the particular sample of data on which the performance evaluation criterion is evaluated. In other words, the bias arises because it is possible (all too easy) to over-fit the cross-validation error when tuning the hyper-parameters.
Use of nested cross-validation
Nested cross-validation is used to avoid optimistically biased estimates of performance that result from using the same cross-validation to set the values of the hyper-parameters of the model (e.g. th
Use of nested cross-validation Nested cross-validation is used to avoid optimistically biased estimates of performance that result from using the same cross-validation to set the values of the hyper-parameters of the model (e.g. the regularisation parameter, $C$, and kernel parameters of an SVM) and performance estimation. I wrote a paper on this topic after being rather alarmed by the magnitude of the bias introduced by a seemingly benign short cut often used in the evaluation of kernel machines. I investigated this topic in order to discover why my results were worse than other research groups using similar methods on the same datasets, the reason turned out to be that I was using nested cross-validation and hence didn't benefit from the optimistic bias. G. C. Cawley and N. L. C. Talbot, Over-fitting in model selection and subsequent selection bias in performance evaluation, Journal of Machine Learning Research, 2010. Research, vol. 11, pp. 2079-2107, July 2010. (http://jmlr.org/papers/volume11/cawley10a/cawley10a.pdf) The reasons for the bias with illustrative examples and experimental evaluation can be found in the paper, but essentially the point is that if the performance evaluation criterion is used in any way to make choices about the model, then those choices are based on (i) genuine improvements in generalisation performance and (ii) the statistical peculiarities of the particular sample of data on which the performance evaluation criterion is evaluated. In other words, the bias arises because it is possible (all too easy) to over-fit the cross-validation error when tuning the hyper-parameters.
Use of nested cross-validation Nested cross-validation is used to avoid optimistically biased estimates of performance that result from using the same cross-validation to set the values of the hyper-parameters of the model (e.g. th
15,484
Use of nested cross-validation
With a held-out test set clf.fit produces one unbiased estimate while nested cross-validation with cross_val_score produces several unbiased estimates. The advantage of nested cross-validation is a better assessment of the true performance using data that the algorithm hasn't seen yet. Better assessment because you get, e.g., three test scores with nested cv instead of just one. The answer to your second question regarding the best estimates is that it is currently (v0.14) not possible to get the parameters of the fitted models using nested cv cross_val_score. See my answer here with an example.
Use of nested cross-validation
With a held-out test set clf.fit produces one unbiased estimate while nested cross-validation with cross_val_score produces several unbiased estimates. The advantage of nested cross-validation is a be
Use of nested cross-validation With a held-out test set clf.fit produces one unbiased estimate while nested cross-validation with cross_val_score produces several unbiased estimates. The advantage of nested cross-validation is a better assessment of the true performance using data that the algorithm hasn't seen yet. Better assessment because you get, e.g., three test scores with nested cv instead of just one. The answer to your second question regarding the best estimates is that it is currently (v0.14) not possible to get the parameters of the fitted models using nested cv cross_val_score. See my answer here with an example.
Use of nested cross-validation With a held-out test set clf.fit produces one unbiased estimate while nested cross-validation with cross_val_score produces several unbiased estimates. The advantage of nested cross-validation is a be
15,485
When does Naive Bayes perform better than SVM?
There is no single answer about which is the best classification method for a given dataset. Different kinds of classifiers should be always considered for a comparative study over a given dataset. Given the properties of the dataset, you might have some clues that may give preference to some methods. However, it would still be advisable to experiment with all, if possible. Naive Bayes Classifier (NBC) and Support Vector Machine (SVM) have different options including the choice of kernel function for each. They are both sensitive to parameter optimization (i.e. different parameter selection can significantly change their output) . So, if you have a result showing that NBC is performing better than SVM. This is only true for the selected parameters. However, for another parameter selection, you might find SVM is performing better. In general, if the assumption of independence in NBC is satisfied by the variables of your dataset and the degree of class overlapping is small (i.e. potential linear decision boundary), NBC would be expected to achieve good. For some datasets, with optimization using wrapper feature selection, for example, NBC may defeat other classifiers. Even if it achieves a comparable performance, NBC will be more desirable because of its high speed. In summary, we should not prefer any classification method if it outperforms others in one context since it might fail severely in another one. (THIS IS NORMAL IN DATA MINING PROBLEMS).
When does Naive Bayes perform better than SVM?
There is no single answer about which is the best classification method for a given dataset. Different kinds of classifiers should be always considered for a comparative study over a given dataset. Gi
When does Naive Bayes perform better than SVM? There is no single answer about which is the best classification method for a given dataset. Different kinds of classifiers should be always considered for a comparative study over a given dataset. Given the properties of the dataset, you might have some clues that may give preference to some methods. However, it would still be advisable to experiment with all, if possible. Naive Bayes Classifier (NBC) and Support Vector Machine (SVM) have different options including the choice of kernel function for each. They are both sensitive to parameter optimization (i.e. different parameter selection can significantly change their output) . So, if you have a result showing that NBC is performing better than SVM. This is only true for the selected parameters. However, for another parameter selection, you might find SVM is performing better. In general, if the assumption of independence in NBC is satisfied by the variables of your dataset and the degree of class overlapping is small (i.e. potential linear decision boundary), NBC would be expected to achieve good. For some datasets, with optimization using wrapper feature selection, for example, NBC may defeat other classifiers. Even if it achieves a comparable performance, NBC will be more desirable because of its high speed. In summary, we should not prefer any classification method if it outperforms others in one context since it might fail severely in another one. (THIS IS NORMAL IN DATA MINING PROBLEMS).
When does Naive Bayes perform better than SVM? There is no single answer about which is the best classification method for a given dataset. Different kinds of classifiers should be always considered for a comparative study over a given dataset. Gi
15,486
What exactly does it mean to 'pool data'?
Yes, your examples are correct. The Oxford English Dictionary defines pool as: pool, v. (puːl) 1.1 trans. To throw into a common stock or fund to be distributed according to agreement; to combine (capital or interests) for the common benefit; spec. of competing railway companies, etc.: To share or divide (traffic or receipts). Another example would be: you measure blood levels of substance X in males and females. You don't see statistical differences between the two groups so you pool the data together, ignoring the sex of the experimental subject. Whether it is statistically correct to do so depends very much on the specific case.
What exactly does it mean to 'pool data'?
Yes, your examples are correct. The Oxford English Dictionary defines pool as: pool, v. (puːl) 1.1 trans. To throw into a common stock or fund to be distributed according to agreement; to combine (c
What exactly does it mean to 'pool data'? Yes, your examples are correct. The Oxford English Dictionary defines pool as: pool, v. (puːl) 1.1 trans. To throw into a common stock or fund to be distributed according to agreement; to combine (capital or interests) for the common benefit; spec. of competing railway companies, etc.: To share or divide (traffic or receipts). Another example would be: you measure blood levels of substance X in males and females. You don't see statistical differences between the two groups so you pool the data together, ignoring the sex of the experimental subject. Whether it is statistically correct to do so depends very much on the specific case.
What exactly does it mean to 'pool data'? Yes, your examples are correct. The Oxford English Dictionary defines pool as: pool, v. (puːl) 1.1 trans. To throw into a common stock or fund to be distributed according to agreement; to combine (c
15,487
What exactly does it mean to 'pool data'?
Pooling can refer to combining data, but it can also refer to combining information rather than the raw data. One of the most common uses of pooling is in estimating a variance. If we believe that 2 populations have the same variance, but not necesarily the same mean, then we can calculate the 2 estimates of the variance from samples of the 2 groups, then pool them (take a weighted average) to get a single estimate of the common variance. We do not compute a single estimate of the variance from the combined data because if the means are not equal then that will inflate the variance estimate.
What exactly does it mean to 'pool data'?
Pooling can refer to combining data, but it can also refer to combining information rather than the raw data. One of the most common uses of pooling is in estimating a variance. If we believe that 2
What exactly does it mean to 'pool data'? Pooling can refer to combining data, but it can also refer to combining information rather than the raw data. One of the most common uses of pooling is in estimating a variance. If we believe that 2 populations have the same variance, but not necesarily the same mean, then we can calculate the 2 estimates of the variance from samples of the 2 groups, then pool them (take a weighted average) to get a single estimate of the common variance. We do not compute a single estimate of the variance from the combined data because if the means are not equal then that will inflate the variance estimate.
What exactly does it mean to 'pool data'? Pooling can refer to combining data, but it can also refer to combining information rather than the raw data. One of the most common uses of pooling is in estimating a variance. If we believe that 2
15,488
Quality assurance and quality control (QA/QC) guidelines for a database
This response focuses on the second question, but in the process a partial answer to the first question (guidelines for a QA/QC procedure) will emerge. By far the best thing you can do is check data quality at the time entry is attempted. The user checks and reports are labor-intensive and so should be reserved for later in the process, as late as is practicable. Here are some principles, guidelines, and suggestions, derived from extensive experience (with the design and creation of many databases comparable to and much larger than yours). They are not rules; you do not have to follow them to be successful and efficient; but they are all here for excellent reasons and you should think hard about deviating from them. Separate data entry from all intellectually demanding activities. Do not ask data entry operators simultaneously to check anything, count anything, etc. Restrict their work to creating a computer-readable facsimile of the data, nothing more. In particular, this principle implies the data-entry forms should reflect the format in which you originally obtain the data, not the format in which you plan to store the data. It is relatively easy to transform one format to another later, but it's an error-prone process to attempt the transformation on the fly while entering data. Create a data audit trail: whenever anything is done to the data, starting at the data entry stage, document this and record the procedure in a way that makes it easy to go back and check what went wrong (because things will go wrong). Consider filling out fields for time stamps, identifiers of data entry operators, identifiers of sources for the original data (such as reports and their page numbers), etc. Storage is cheap, but the time to track down an error is expensive. Automate everything. Assume any step will have to be redone (at the worst possible time, according to Murphy's Law), and plan accordingly. Don't try to save time now by doing a few "simple steps" by hand. In particular, create support for data entry: make a front end for each table (even a spreadsheet can do nicely) that provides a clear, simple, uniform way to get data in. At the same time the front end should enforce your "business rules:" that is, it should perform as many simple validity checks as it can. (E.g., pH must be between 0 and 14; counts must be positive.) Ideally, use a DBMS to enforce relational integrity checks (e.g., every species associated with a measurement really exists in the database). Constantly count things and check that counts exactly agree. E.g., if a study is supposed to measure attributes of 10 species, make sure (as soon as data entry is complete) that 10 species really are reported. Although checking counts is simple and uninformative, it's great at detecting duplicated and omitted data. If the data are valuable and important, consider independently double-entering the entire dataset. This means that each item will be entered at separate times by two different non-interacting people. This is a great way to catch typos, missing data, and so on. The cross-checking can be completely automated. This is faster, better at catching errors, and more efficient than 100% manual double checking. (The data entry "people" can include devices such as scanners with OCR.) Use a DBMS to store and manage the data. Spreadsheets are great for supporting data entry, but get your data out of the spreadsheets or text files and into a real database as soon as possible. This prevents all kinds of insidious errors while adding lots of support for automatic data integrity checks. If you must, use your statistical software for data storage and management, but seriously consider using a dedicated DBMS: it will do a better job. After all data are entered and automatically checked, draw pictures: make sorted tables, histograms, scatterplots, etc., and look at them all. These are easily automated with any full-fledged statistical package. Do not ask people to do repetitive tasks that the computer can do. The computer is much faster and more reliable at these. Get into the habit of writing (and documenting) little scripts and small programs to do any task that cannot be completed immediately. These will become part of your audit trail and they will enable work to be redone easily. Use whatever platform you're comfortable with and that is suitable to the task. (Over the years, depending on what was available, I have used a wide range of such platforms and all have been effective in their way, ranging from C and Fortran programs through AWK and SED scripts, VBA scripts for Excel and Word, and custom programs written for relational database systems, GIS, and statistical analysis platforms like R and Stata.) If you follow most of these guidelines, approximately 50%-80% of the work in getting data into the database will be database design and writing the supporting scripts. It is not unusual to get 90% through such a project and be less than 50% complete, yet still finish on time: once everything is set up and has been tested, the data entry and checking can be amazingly efficient.
Quality assurance and quality control (QA/QC) guidelines for a database
This response focuses on the second question, but in the process a partial answer to the first question (guidelines for a QA/QC procedure) will emerge. By far the best thing you can do is check data q
Quality assurance and quality control (QA/QC) guidelines for a database This response focuses on the second question, but in the process a partial answer to the first question (guidelines for a QA/QC procedure) will emerge. By far the best thing you can do is check data quality at the time entry is attempted. The user checks and reports are labor-intensive and so should be reserved for later in the process, as late as is practicable. Here are some principles, guidelines, and suggestions, derived from extensive experience (with the design and creation of many databases comparable to and much larger than yours). They are not rules; you do not have to follow them to be successful and efficient; but they are all here for excellent reasons and you should think hard about deviating from them. Separate data entry from all intellectually demanding activities. Do not ask data entry operators simultaneously to check anything, count anything, etc. Restrict their work to creating a computer-readable facsimile of the data, nothing more. In particular, this principle implies the data-entry forms should reflect the format in which you originally obtain the data, not the format in which you plan to store the data. It is relatively easy to transform one format to another later, but it's an error-prone process to attempt the transformation on the fly while entering data. Create a data audit trail: whenever anything is done to the data, starting at the data entry stage, document this and record the procedure in a way that makes it easy to go back and check what went wrong (because things will go wrong). Consider filling out fields for time stamps, identifiers of data entry operators, identifiers of sources for the original data (such as reports and their page numbers), etc. Storage is cheap, but the time to track down an error is expensive. Automate everything. Assume any step will have to be redone (at the worst possible time, according to Murphy's Law), and plan accordingly. Don't try to save time now by doing a few "simple steps" by hand. In particular, create support for data entry: make a front end for each table (even a spreadsheet can do nicely) that provides a clear, simple, uniform way to get data in. At the same time the front end should enforce your "business rules:" that is, it should perform as many simple validity checks as it can. (E.g., pH must be between 0 and 14; counts must be positive.) Ideally, use a DBMS to enforce relational integrity checks (e.g., every species associated with a measurement really exists in the database). Constantly count things and check that counts exactly agree. E.g., if a study is supposed to measure attributes of 10 species, make sure (as soon as data entry is complete) that 10 species really are reported. Although checking counts is simple and uninformative, it's great at detecting duplicated and omitted data. If the data are valuable and important, consider independently double-entering the entire dataset. This means that each item will be entered at separate times by two different non-interacting people. This is a great way to catch typos, missing data, and so on. The cross-checking can be completely automated. This is faster, better at catching errors, and more efficient than 100% manual double checking. (The data entry "people" can include devices such as scanners with OCR.) Use a DBMS to store and manage the data. Spreadsheets are great for supporting data entry, but get your data out of the spreadsheets or text files and into a real database as soon as possible. This prevents all kinds of insidious errors while adding lots of support for automatic data integrity checks. If you must, use your statistical software for data storage and management, but seriously consider using a dedicated DBMS: it will do a better job. After all data are entered and automatically checked, draw pictures: make sorted tables, histograms, scatterplots, etc., and look at them all. These are easily automated with any full-fledged statistical package. Do not ask people to do repetitive tasks that the computer can do. The computer is much faster and more reliable at these. Get into the habit of writing (and documenting) little scripts and small programs to do any task that cannot be completed immediately. These will become part of your audit trail and they will enable work to be redone easily. Use whatever platform you're comfortable with and that is suitable to the task. (Over the years, depending on what was available, I have used a wide range of such platforms and all have been effective in their way, ranging from C and Fortran programs through AWK and SED scripts, VBA scripts for Excel and Word, and custom programs written for relational database systems, GIS, and statistical analysis platforms like R and Stata.) If you follow most of these guidelines, approximately 50%-80% of the work in getting data into the database will be database design and writing the supporting scripts. It is not unusual to get 90% through such a project and be less than 50% complete, yet still finish on time: once everything is set up and has been tested, the data entry and checking can be amazingly efficient.
Quality assurance and quality control (QA/QC) guidelines for a database This response focuses on the second question, but in the process a partial answer to the first question (guidelines for a QA/QC procedure) will emerge. By far the best thing you can do is check data q
15,489
Quality assurance and quality control (QA/QC) guidelines for a database
DataOne provides a helpful set of data management best practices that can be filtered by tag. The best practices tagged with "quality", found at http://www.dataone.org/best-practices/quality, reiterating and expanding on many of the points made by @whuber. Here is a list of the topics covered there (in alphabetical order): Communicate data quality Confirm a match between data and their description in metadata Consider the compatibility of the data you are integrating Develop a quality assurance and quality control plan Double-check the data you enter Ensure basic quality control Ensure integrity and accessibility when making backups of data Identify outliers Identify values that are estimated Provide version information for use and discovery
Quality assurance and quality control (QA/QC) guidelines for a database
DataOne provides a helpful set of data management best practices that can be filtered by tag. The best practices tagged with "quality", found at http://www.dataone.org/best-practices/quality, reiterat
Quality assurance and quality control (QA/QC) guidelines for a database DataOne provides a helpful set of data management best practices that can be filtered by tag. The best practices tagged with "quality", found at http://www.dataone.org/best-practices/quality, reiterating and expanding on many of the points made by @whuber. Here is a list of the topics covered there (in alphabetical order): Communicate data quality Confirm a match between data and their description in metadata Consider the compatibility of the data you are integrating Develop a quality assurance and quality control plan Double-check the data you enter Ensure basic quality control Ensure integrity and accessibility when making backups of data Identify outliers Identify values that are estimated Provide version information for use and discovery
Quality assurance and quality control (QA/QC) guidelines for a database DataOne provides a helpful set of data management best practices that can be filtered by tag. The best practices tagged with "quality", found at http://www.dataone.org/best-practices/quality, reiterat
15,490
Essential papers on matrix decompositions
How do you know that SVD and NMF are by far the most used matrix decompositions rather than LU, Cholesky and QR? My personal favourite 'breakthrough' would have to be the guaranteed rank-revealing QR algorithm, Chan, Tony F. "Rank revealing QR factorizations". Linear Algebra and its Applications Volumes 88-89, April 1987, Pages 67-82. DOI:10.1016/0024-3795(87)90103-0 ... a development of the earlier idea of QR with column-pivoting: Businger, Peter; Golub, Gene H. (1965). Linear least squares solutions by Householder transformations. Numerische Mathematik Volume 7, Number 3, 269-276, DOI:10.1007/BF01436084 A (the?) classic textbook is: Golub, Gene H.; Van Loan, Charles F. (1996). Matrix Computations (3rd ed.), Johns Hopkins, ISBN 978-0-8018-5414-9. (i know you didn't ask for textbooks but i can't resist) Edit: A bit more googling finds a paper whose abstract suggests we could be slightly at cross porpoises. My above text was coming from a 'numerical linear algebra' (NLA) perspective; possibly you're concerned more with an 'applied statistics / psychometrics' (AS/P) perspective? Could you perhaps clarify? Lawrence Hubert, Jacqueline Meulman and Willem Heiser. Two Purposes for Matrix Factorization: A Historical Appraisal. SIAM Review Vol. 42, No. 1 (Mar., 2000), pp. 68-82
Essential papers on matrix decompositions
How do you know that SVD and NMF are by far the most used matrix decompositions rather than LU, Cholesky and QR? My personal favourite 'breakthrough' would have to be the guaranteed rank-revealing QR
Essential papers on matrix decompositions How do you know that SVD and NMF are by far the most used matrix decompositions rather than LU, Cholesky and QR? My personal favourite 'breakthrough' would have to be the guaranteed rank-revealing QR algorithm, Chan, Tony F. "Rank revealing QR factorizations". Linear Algebra and its Applications Volumes 88-89, April 1987, Pages 67-82. DOI:10.1016/0024-3795(87)90103-0 ... a development of the earlier idea of QR with column-pivoting: Businger, Peter; Golub, Gene H. (1965). Linear least squares solutions by Householder transformations. Numerische Mathematik Volume 7, Number 3, 269-276, DOI:10.1007/BF01436084 A (the?) classic textbook is: Golub, Gene H.; Van Loan, Charles F. (1996). Matrix Computations (3rd ed.), Johns Hopkins, ISBN 978-0-8018-5414-9. (i know you didn't ask for textbooks but i can't resist) Edit: A bit more googling finds a paper whose abstract suggests we could be slightly at cross porpoises. My above text was coming from a 'numerical linear algebra' (NLA) perspective; possibly you're concerned more with an 'applied statistics / psychometrics' (AS/P) perspective? Could you perhaps clarify? Lawrence Hubert, Jacqueline Meulman and Willem Heiser. Two Purposes for Matrix Factorization: A Historical Appraisal. SIAM Review Vol. 42, No. 1 (Mar., 2000), pp. 68-82
Essential papers on matrix decompositions How do you know that SVD and NMF are by far the most used matrix decompositions rather than LU, Cholesky and QR? My personal favourite 'breakthrough' would have to be the guaranteed rank-revealing QR
15,491
Essential papers on matrix decompositions
For NNMF, Lee and Seung describe an iterative algorithm which is very simple to implement. Actually they give two similar algorithms, one for minimizing Frobenius norm of residual, the other for minimizing Kullback-Leibler Divergence of the approximation and original matrix. Daniel Lee, H. Sebastian Seung, Algorithms for Non-negative Matrix Factorization, Advances in Neural Information Processing Systems 13: Proceedings of the 2000 Conference. MIT Press. pp. 556–562.
Essential papers on matrix decompositions
For NNMF, Lee and Seung describe an iterative algorithm which is very simple to implement. Actually they give two similar algorithms, one for minimizing Frobenius norm of residual, the other for minim
Essential papers on matrix decompositions For NNMF, Lee and Seung describe an iterative algorithm which is very simple to implement. Actually they give two similar algorithms, one for minimizing Frobenius norm of residual, the other for minimizing Kullback-Leibler Divergence of the approximation and original matrix. Daniel Lee, H. Sebastian Seung, Algorithms for Non-negative Matrix Factorization, Advances in Neural Information Processing Systems 13: Proceedings of the 2000 Conference. MIT Press. pp. 556–562.
Essential papers on matrix decompositions For NNMF, Lee and Seung describe an iterative algorithm which is very simple to implement. Actually they give two similar algorithms, one for minimizing Frobenius norm of residual, the other for minim
15,492
Essential papers on matrix decompositions
Maybe, you can find interesting [Learning with Matrix Factorizations] PhD thesis by Nathan Srebro, [Investigation of Various Matrix Factorization Methods for Large Recommender Systems], Gábor Takács et.al. and almost the same technique described here The last two links show how sparse matrix factorizations are used in Collaborative Filtering. However, I believe that SGD-like factorization algorithms can be useful somewhere else (at least they are extremely easy to code)
Essential papers on matrix decompositions
Maybe, you can find interesting [Learning with Matrix Factorizations] PhD thesis by Nathan Srebro, [Investigation of Various Matrix Factorization Methods for Large Recommender Systems], Gábor Takács
Essential papers on matrix decompositions Maybe, you can find interesting [Learning with Matrix Factorizations] PhD thesis by Nathan Srebro, [Investigation of Various Matrix Factorization Methods for Large Recommender Systems], Gábor Takács et.al. and almost the same technique described here The last two links show how sparse matrix factorizations are used in Collaborative Filtering. However, I believe that SGD-like factorization algorithms can be useful somewhere else (at least they are extremely easy to code)
Essential papers on matrix decompositions Maybe, you can find interesting [Learning with Matrix Factorizations] PhD thesis by Nathan Srebro, [Investigation of Various Matrix Factorization Methods for Large Recommender Systems], Gábor Takács
15,493
Essential papers on matrix decompositions
Witten, Tibshirani - Penalized matrix decomposition http://www.biostat.washington.edu/~dwitten/Papers/pmd.pdf http://cran.r-project.org/web/packages/PMA/index.html Martinsson, Rokhlin, Szlam, Tygert - Randomized SVD http://cims.nyu.edu/~tygert/software.html http://cims.nyu.edu/~tygert/blanczos.pdf
Essential papers on matrix decompositions
Witten, Tibshirani - Penalized matrix decomposition http://www.biostat.washington.edu/~dwitten/Papers/pmd.pdf http://cran.r-project.org/web/packages/PMA/index.html Martinsson, Rokhlin, Szlam, Tygert -
Essential papers on matrix decompositions Witten, Tibshirani - Penalized matrix decomposition http://www.biostat.washington.edu/~dwitten/Papers/pmd.pdf http://cran.r-project.org/web/packages/PMA/index.html Martinsson, Rokhlin, Szlam, Tygert - Randomized SVD http://cims.nyu.edu/~tygert/software.html http://cims.nyu.edu/~tygert/blanczos.pdf
Essential papers on matrix decompositions Witten, Tibshirani - Penalized matrix decomposition http://www.biostat.washington.edu/~dwitten/Papers/pmd.pdf http://cran.r-project.org/web/packages/PMA/index.html Martinsson, Rokhlin, Szlam, Tygert -
15,494
Essential papers on matrix decompositions
At this year's NIPS there was a short paper on distributed, very large-scale SVD that works in a single pass over a streaming input matrix. The paper's more implementation-oriented but puts things into perspective with real wall-clock times and all. The table near the beginning is a good survey too.
Essential papers on matrix decompositions
At this year's NIPS there was a short paper on distributed, very large-scale SVD that works in a single pass over a streaming input matrix. The paper's more implementation-oriented but puts things int
Essential papers on matrix decompositions At this year's NIPS there was a short paper on distributed, very large-scale SVD that works in a single pass over a streaming input matrix. The paper's more implementation-oriented but puts things into perspective with real wall-clock times and all. The table near the beginning is a good survey too.
Essential papers on matrix decompositions At this year's NIPS there was a short paper on distributed, very large-scale SVD that works in a single pass over a streaming input matrix. The paper's more implementation-oriented but puts things int
15,495
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis?
I think I figured out the answer (to my own question). If the assumption of proportional hazards is true, the two methods give similar estimates of the hazard ratio. The discrepancy I found in one particular example, I now think, is due to the fact that that assumption is dubious. If the assumption of proportional hazards is true, then a graph of log(time) vs. log(-log(St)) (where St is the proportional survival at time t) should show two parallel lines. Below is the graph created from the problem data set. It seems far from linear. If the assumption of proportional hazards is not valid, then the concept of a hazard ratio is meaningless, and so it doesn't matter which method is used to compute the hazard ratio. I wonder if the discrepancy between the logrank and Mantel-Haenszel estimates of the hazard ratio can be used as a method to test the assumption of proportional hazards?
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz
I think I figured out the answer (to my own question). If the assumption of proportional hazards is true, the two methods give similar estimates of the hazard ratio. The discrepancy I found in one par
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis? I think I figured out the answer (to my own question). If the assumption of proportional hazards is true, the two methods give similar estimates of the hazard ratio. The discrepancy I found in one particular example, I now think, is due to the fact that that assumption is dubious. If the assumption of proportional hazards is true, then a graph of log(time) vs. log(-log(St)) (where St is the proportional survival at time t) should show two parallel lines. Below is the graph created from the problem data set. It seems far from linear. If the assumption of proportional hazards is not valid, then the concept of a hazard ratio is meaningless, and so it doesn't matter which method is used to compute the hazard ratio. I wonder if the discrepancy between the logrank and Mantel-Haenszel estimates of the hazard ratio can be used as a method to test the assumption of proportional hazards?
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz I think I figured out the answer (to my own question). If the assumption of proportional hazards is true, the two methods give similar estimates of the hazard ratio. The discrepancy I found in one par
15,496
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis?
If I'm not mistaken, the log-rank estimator you reference is also known as the Pike estimator. I believe it's generally recommended for HR < 3 because it exhibits less bias in that range. The following paper may be of interest (note that the paper refers to it as O/E): Estimation of the Proportional Hazard in Two-Treatment-Group Clinical Trials (Bernstein, Anderson, Pike) [...] The O/E method is biased but, within the range of values of the ratio of the hazard rates of interest in clinical trials, it is more efficient in terms of mean square error than either CML or the Mantel-Haenszel method for all but the largest trials. The Mantel-Haenszel method is minimally biased, gives answers very close to those obtained using CML, and may be used to provide satisfactory approximate confidence intervals.
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz
If I'm not mistaken, the log-rank estimator you reference is also known as the Pike estimator. I believe it's generally recommended for HR < 3 because it exhibits less bias in that range. The follow
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis? If I'm not mistaken, the log-rank estimator you reference is also known as the Pike estimator. I believe it's generally recommended for HR < 3 because it exhibits less bias in that range. The following paper may be of interest (note that the paper refers to it as O/E): Estimation of the Proportional Hazard in Two-Treatment-Group Clinical Trials (Bernstein, Anderson, Pike) [...] The O/E method is biased but, within the range of values of the ratio of the hazard rates of interest in clinical trials, it is more efficient in terms of mean square error than either CML or the Mantel-Haenszel method for all but the largest trials. The Mantel-Haenszel method is minimally biased, gives answers very close to those obtained using CML, and may be used to provide satisfactory approximate confidence intervals.
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz If I'm not mistaken, the log-rank estimator you reference is also known as the Pike estimator. I believe it's generally recommended for HR < 3 because it exhibits less bias in that range. The follow
15,497
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis?
There are actually several more methods and the choice often depends on whether you are most interested in looking for early differences, later differences or - as for the log-rank test & the Mantel-Haenszel test - give equal weight to all time points. To the question at hand. The log-rank test is in fact a form of the Mantel-Haenszel test applied to survival data. The Mantel-Haenszel test is usually used to test for independence in stratified contingency tables. If we try to apply the MH test to survival data, we can start by assuming that events at each failure time are independent. We then stratify by failure time. We use the MH methods for by making each failure time a strata. Not surprisingly they often give the same result. The exception occcurs when more than one event occurs simultaneously - multiple deaths at exactly the same time point. I can't remember how the treatment then differs. I think the log-rank test averages over the possible orderings of the tied failure times. So the log-rank test is the MH test for survival data and can deal with ties. I've never used the MH test for survival data.
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz
There are actually several more methods and the choice often depends on whether you are most interested in looking for early differences, later differences or - as for the log-rank test & the Mantel-H
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis? There are actually several more methods and the choice often depends on whether you are most interested in looking for early differences, later differences or - as for the log-rank test & the Mantel-Haenszel test - give equal weight to all time points. To the question at hand. The log-rank test is in fact a form of the Mantel-Haenszel test applied to survival data. The Mantel-Haenszel test is usually used to test for independence in stratified contingency tables. If we try to apply the MH test to survival data, we can start by assuming that events at each failure time are independent. We then stratify by failure time. We use the MH methods for by making each failure time a strata. Not surprisingly they often give the same result. The exception occcurs when more than one event occurs simultaneously - multiple deaths at exactly the same time point. I can't remember how the treatment then differs. I think the log-rank test averages over the possible orderings of the tied failure times. So the log-rank test is the MH test for survival data and can deal with ties. I've never used the MH test for survival data.
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz There are actually several more methods and the choice often depends on whether you are most interested in looking for early differences, later differences or - as for the log-rank test & the Mantel-H
15,498
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis?
I thought I'd stumbled across a web site and reference that deals exactly with this question: http://www.graphpad.com/faq/viewfaq.cfm?faq=1226 Start from "The two methods compared". The site references the Berstein paper ars linked (above): http://www.jstor.org/stable/2530564?seq=1 The site summarises Berstein et al's results nicely, so I'll quote it: The two usually give identical (or nearly identical) results. But the results can differ when several subjects die at the same time or when the hazard ratio is far from 1.0. Bernsetin and colleagues analyzed simulated data with both methods (1). In all their simulations, the assumption of proportional hazards was true. The two methods gave very similar values. The logrank method (which they refer to as the O/E method) reports values that are closer to 1.0 than the true Hazard Ratio, especially when the hazard ratio is large or the sample size is large. When there are ties, both methods are less accurate. The logrank methods tend to report hazard ratios that are even closer to 1.0 (so the reported hazard ratio is too small when the hazard ratio is greater than 1.0, and too large when the hazard ratio is less than 1.0). The Mantel-Haenszel method, in contrast, reports hazard ratios that are further from 1.0 (so the reported hazard ratio is too large when the hazard ratio is greater than 1.0, and too small when the hazard ratio is less than 1.0). They did not test the two methods with data simulated where the assumption of proportional hazards is not true. I have seen one data set where the two estimate of HR were very different (by a factor of three), and the assumption of proportional hazards was dubious for those data. It seems that the Mantel-Haenszel method gives more weight to differences in the hazard at late time points, while the logrank method gives equal weight everywhere (but I have not explored this in detail). If you see very different HR values with the two methods, think about whether the assumption of proportional hazards is reasonable. If that assumption is not reasonable, then of course the entire concept of a single hazard ratio describing the entire curve is not meaningful The site also refer to the dataset in which "the two estimate of HR were very different (by a factor of three)", and suggest that the PH assumption is a key consideration. Then I thought, "Who authored the site?" After a little searching I found it was Harvey Motulsky. So Harvey I've managed to reference you in answering your own question. You've become the authority! Is the "problem dataset" a publicly available dataset?
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz
I thought I'd stumbled across a web site and reference that deals exactly with this question: http://www.graphpad.com/faq/viewfaq.cfm?faq=1226 Start from "The two methods compared". The site reference
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Hazard Ratio in survival analysis? I thought I'd stumbled across a web site and reference that deals exactly with this question: http://www.graphpad.com/faq/viewfaq.cfm?faq=1226 Start from "The two methods compared". The site references the Berstein paper ars linked (above): http://www.jstor.org/stable/2530564?seq=1 The site summarises Berstein et al's results nicely, so I'll quote it: The two usually give identical (or nearly identical) results. But the results can differ when several subjects die at the same time or when the hazard ratio is far from 1.0. Bernsetin and colleagues analyzed simulated data with both methods (1). In all their simulations, the assumption of proportional hazards was true. The two methods gave very similar values. The logrank method (which they refer to as the O/E method) reports values that are closer to 1.0 than the true Hazard Ratio, especially when the hazard ratio is large or the sample size is large. When there are ties, both methods are less accurate. The logrank methods tend to report hazard ratios that are even closer to 1.0 (so the reported hazard ratio is too small when the hazard ratio is greater than 1.0, and too large when the hazard ratio is less than 1.0). The Mantel-Haenszel method, in contrast, reports hazard ratios that are further from 1.0 (so the reported hazard ratio is too large when the hazard ratio is greater than 1.0, and too small when the hazard ratio is less than 1.0). They did not test the two methods with data simulated where the assumption of proportional hazards is not true. I have seen one data set where the two estimate of HR were very different (by a factor of three), and the assumption of proportional hazards was dubious for those data. It seems that the Mantel-Haenszel method gives more weight to differences in the hazard at late time points, while the logrank method gives equal weight everywhere (but I have not explored this in detail). If you see very different HR values with the two methods, think about whether the assumption of proportional hazards is reasonable. If that assumption is not reasonable, then of course the entire concept of a single hazard ratio describing the entire curve is not meaningful The site also refer to the dataset in which "the two estimate of HR were very different (by a factor of three)", and suggest that the PH assumption is a key consideration. Then I thought, "Who authored the site?" After a little searching I found it was Harvey Motulsky. So Harvey I've managed to reference you in answering your own question. You've become the authority! Is the "problem dataset" a publicly available dataset?
What are the pros and cons of using the logrank vs. the Mantel-Haenszel method for computing the Haz I thought I'd stumbled across a web site and reference that deals exactly with this question: http://www.graphpad.com/faq/viewfaq.cfm?faq=1226 Start from "The two methods compared". The site reference
15,499
What is the problem with empirical priors?
Generally, informative priors are typically viewed as your information about parameters (or hypotheses) before seeing the data. So any data-based prior is violating the likelihood principle since evidence from the sample is coming through the likelihood function and the prior.
What is the problem with empirical priors?
Generally, informative priors are typically viewed as your information about parameters (or hypotheses) before seeing the data. So any data-based prior is violating the likelihood principle since evid
What is the problem with empirical priors? Generally, informative priors are typically viewed as your information about parameters (or hypotheses) before seeing the data. So any data-based prior is violating the likelihood principle since evidence from the sample is coming through the likelihood function and the prior.
What is the problem with empirical priors? Generally, informative priors are typically viewed as your information about parameters (or hypotheses) before seeing the data. So any data-based prior is violating the likelihood principle since evid
15,500
What is the problem with empirical priors?
The $p$-values are wrong. Take a simple example. Test whether a population mean $\mu$ is equal to a particular value $\mu_0$ or not. Suppose the sample mean $\bar x$ is greater than $\mu_0$. Then it would be simply wrong to let the data guide you into testing only a one-sided alternative. Your $p$-value will be half of what it should be. And just to be clear: The restriction $\mu \ge \mu_0$ implied by the one-sided alternative is a kind of empirical prior. (It throws away half of the possible values for $\mu$ a priori.)
What is the problem with empirical priors?
The $p$-values are wrong. Take a simple example. Test whether a population mean $\mu$ is equal to a particular value $\mu_0$ or not. Suppose the sample mean $\bar x$ is greater than $\mu_0$. Then it w
What is the problem with empirical priors? The $p$-values are wrong. Take a simple example. Test whether a population mean $\mu$ is equal to a particular value $\mu_0$ or not. Suppose the sample mean $\bar x$ is greater than $\mu_0$. Then it would be simply wrong to let the data guide you into testing only a one-sided alternative. Your $p$-value will be half of what it should be. And just to be clear: The restriction $\mu \ge \mu_0$ implied by the one-sided alternative is a kind of empirical prior. (It throws away half of the possible values for $\mu$ a priori.)
What is the problem with empirical priors? The $p$-values are wrong. Take a simple example. Test whether a population mean $\mu$ is equal to a particular value $\mu_0$ or not. Suppose the sample mean $\bar x$ is greater than $\mu_0$. Then it w