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
|
|---|---|---|---|---|---|---|
6,001
|
Time series 'clustering' in R
|
In data streaming and mining of time series databases, a common approach is to transform the series to a symbolic representation, then use a similarity metric, such as Euclidean distance, to cluster the series. The most popular representations are SAX (Keogh & Lin) or the newer iSAX (Shieh & Keogh):
Symbolic Aggregate approXimation
iSAX: Indexing and Mining Terabyte Sized Time Series
The pages above also contain references to distance metrics and clustering. Keogh and crew are into reproducible research and pretty receptive to releasing their code. So you could email them and ask. I believe they tend to work in MATLAB/C++ though.
There was a recent effort to produce a Java and R implementation:
jmotif
I don't know how far along it is -- it's geared towards motif finding, but, depending on how far they've gotten, it should have the necessary bits you need to put something together for your needs (iSAX and distance metrics: since this part is common to clustering and motif finding).
|
Time series 'clustering' in R
|
In data streaming and mining of time series databases, a common approach is to transform the series to a symbolic representation, then use a similarity metric, such as Euclidean distance, to cluster t
|
Time series 'clustering' in R
In data streaming and mining of time series databases, a common approach is to transform the series to a symbolic representation, then use a similarity metric, such as Euclidean distance, to cluster the series. The most popular representations are SAX (Keogh & Lin) or the newer iSAX (Shieh & Keogh):
Symbolic Aggregate approXimation
iSAX: Indexing and Mining Terabyte Sized Time Series
The pages above also contain references to distance metrics and clustering. Keogh and crew are into reproducible research and pretty receptive to releasing their code. So you could email them and ask. I believe they tend to work in MATLAB/C++ though.
There was a recent effort to produce a Java and R implementation:
jmotif
I don't know how far along it is -- it's geared towards motif finding, but, depending on how far they've gotten, it should have the necessary bits you need to put something together for your needs (iSAX and distance metrics: since this part is common to clustering and motif finding).
|
Time series 'clustering' in R
In data streaming and mining of time series databases, a common approach is to transform the series to a symbolic representation, then use a similarity metric, such as Euclidean distance, to cluster t
|
6,002
|
Time series 'clustering' in R
|
Another way of saying "tend to move in sympathy" is "cointegrated".
There are two standard ways of calculating cointegration: Engle-Granger method and the Johansen procedure. These are covered in "Analysis of Integrated and Cointegrated Time Series with R" (Pfaff 2008) and the related R urca package. I highly recommend the book if you want to pursue these methods in R.
I also recommend that you look at this question on multivariate time series and, in particular, at Ruey Tsay's course at U. Chicago which includes all the necessary R code.
|
Time series 'clustering' in R
|
Another way of saying "tend to move in sympathy" is "cointegrated".
There are two standard ways of calculating cointegration: Engle-Granger method and the Johansen procedure. These are covered in "
|
Time series 'clustering' in R
Another way of saying "tend to move in sympathy" is "cointegrated".
There are two standard ways of calculating cointegration: Engle-Granger method and the Johansen procedure. These are covered in "Analysis of Integrated and Cointegrated Time Series with R" (Pfaff 2008) and the related R urca package. I highly recommend the book if you want to pursue these methods in R.
I also recommend that you look at this question on multivariate time series and, in particular, at Ruey Tsay's course at U. Chicago which includes all the necessary R code.
|
Time series 'clustering' in R
Another way of saying "tend to move in sympathy" is "cointegrated".
There are two standard ways of calculating cointegration: Engle-Granger method and the Johansen procedure. These are covered in "
|
6,003
|
Time series 'clustering' in R
|
Clustering time series is done fairly commonly by population dynamacists, particularily those that study insects to understand trends in outbreak and collapse. Look for work on Gypsy moth, Spruce budoworm, mountain pine beetle and larch budmoth.
For the actual clustering you can choose whatever distance metric you like, each probably has it's own strengths and weeknesses relative to the kind of data being clustered, Kaufmann and Rousseeuw 1990. Finding groups in data. An introduction to cluster analysis is a good place to start. Remember, the clustering method doesn't 'care' that you're using a time series, it only looks at the values measured at the same point of time. If your two time series are not in enough synch over their lifespan they the won't (and perhaps shouldn't) cluster.
Where you will have problems is determining the number of clusters (families) to use after you've clusterd the time series. There are various ways of selecting a cut-off of informative clusters, but here the literature isn't that good.
|
Time series 'clustering' in R
|
Clustering time series is done fairly commonly by population dynamacists, particularily those that study insects to understand trends in outbreak and collapse. Look for work on Gypsy moth, Spruce budo
|
Time series 'clustering' in R
Clustering time series is done fairly commonly by population dynamacists, particularily those that study insects to understand trends in outbreak and collapse. Look for work on Gypsy moth, Spruce budoworm, mountain pine beetle and larch budmoth.
For the actual clustering you can choose whatever distance metric you like, each probably has it's own strengths and weeknesses relative to the kind of data being clustered, Kaufmann and Rousseeuw 1990. Finding groups in data. An introduction to cluster analysis is a good place to start. Remember, the clustering method doesn't 'care' that you're using a time series, it only looks at the values measured at the same point of time. If your two time series are not in enough synch over their lifespan they the won't (and perhaps shouldn't) cluster.
Where you will have problems is determining the number of clusters (families) to use after you've clusterd the time series. There are various ways of selecting a cut-off of informative clusters, but here the literature isn't that good.
|
Time series 'clustering' in R
Clustering time series is done fairly commonly by population dynamacists, particularily those that study insects to understand trends in outbreak and collapse. Look for work on Gypsy moth, Spruce budo
|
6,004
|
Time series 'clustering' in R
|
See my answer to a similar question here. Long story short, do a fast Fourier transform of the data, discard redundant frequencies if your input data was real valued, separate the real and imaginary parts for each element of the fast Fourier transform, and use the Mclust package in R to do model-based clustering on the real and imaginary parts of each element of each time series. The package automates optimization over number of clusters and their densities.
|
Time series 'clustering' in R
|
See my answer to a similar question here. Long story short, do a fast Fourier transform of the data, discard redundant frequencies if your input data was real valued, separate the real and imaginary p
|
Time series 'clustering' in R
See my answer to a similar question here. Long story short, do a fast Fourier transform of the data, discard redundant frequencies if your input data was real valued, separate the real and imaginary parts for each element of the fast Fourier transform, and use the Mclust package in R to do model-based clustering on the real and imaginary parts of each element of each time series. The package automates optimization over number of clusters and their densities.
|
Time series 'clustering' in R
See my answer to a similar question here. Long story short, do a fast Fourier transform of the data, discard redundant frequencies if your input data was real valued, separate the real and imaginary p
|
6,005
|
Time series 'clustering' in R
|
You could also use the package clustDDist, which performs the leaders method and the hierarchical clustering method with different error measures:
http://r-forge.r-project.org/projects/clustddist/
The squared Euclidean distance favors patterns of distributions that have one steep high peak and therefore measure
$$
d_4(x, y) = \frac{(x-y)^2}{y}
$$
is sometimes preferred.
|
Time series 'clustering' in R
|
You could also use the package clustDDist, which performs the leaders method and the hierarchical clustering method with different error measures:
http://r-forge.r-project.org/projects/clustddist/
The
|
Time series 'clustering' in R
You could also use the package clustDDist, which performs the leaders method and the hierarchical clustering method with different error measures:
http://r-forge.r-project.org/projects/clustddist/
The squared Euclidean distance favors patterns of distributions that have one steep high peak and therefore measure
$$
d_4(x, y) = \frac{(x-y)^2}{y}
$$
is sometimes preferred.
|
Time series 'clustering' in R
You could also use the package clustDDist, which performs the leaders method and the hierarchical clustering method with different error measures:
http://r-forge.r-project.org/projects/clustddist/
The
|
6,006
|
How to interpret glmnet?
|
Here's an unintuitive fact - you're not actually supposed to give glmnet a single value of lambda. From the documentation here:
Do not supply a single value for lambda (for predictions after CV use predict() instead).
Supply instead a decreasing sequence of lambda values. glmnet relies on its
warms starts for speed, and its often faster to fit a whole path than compute a
single fit.
cv.glmnet will help you choose lambda, as you alluded to in your examples. The authors of the glmnet package suggest cv$lambda.1se instead of cv$lambda.min, but in practice I've had success with the latter.
After running cv.glmnet, you don't have to rerun glmnet! Every lambda in the grid (cv$lambda) has already been run. This technique is called "Warm Start" and you can read more about it here. Paraphrasing from the introduction, the Warm Start technique reduces running time of iterative methods by using the solution of a different optimization problem (e.g., glmnet with a larger lambda) as the starting value for a later optimization problem (e.g., glmnet with a smaller lambda).
To extract the desired run from cv.glmnet.fit, try this:
small.lambda.index <- which(cv$lambda == cv$lambda.min)
small.lambda.betas <- cv$glmnet.fit$beta[, small.lambda.index]
Revision (1/28/2017)
No need to hack to the glmnet object like I did above; take @alex23lemm's advice below and pass the s = "lambda.min", s = "lambda.1se" or some other number (e.g., s = .007) to both coef and predict. Note that your coefficients and predictions depend on this value which is set by cross validation. Use a seed for reproducibility! And don't forget that if you don't supply an "s" in coef and predict, you'll be using the default of s = "lambda.1se". I have warmed up to that default after seeing it work better in a small data situation. s = "lambda.1se" also tends to provide more regularization, so if you're working with alpha > 0, it will also tend towards a more parsimonious model. You can also choose a numerical value of s with the help of plot.glmnet to get to somewhere in between (just don't forget to exponentiate the values from the x axis!).
|
How to interpret glmnet?
|
Here's an unintuitive fact - you're not actually supposed to give glmnet a single value of lambda. From the documentation here:
Do not supply a single value for lambda (for predictions after CV use
|
How to interpret glmnet?
Here's an unintuitive fact - you're not actually supposed to give glmnet a single value of lambda. From the documentation here:
Do not supply a single value for lambda (for predictions after CV use predict() instead).
Supply instead a decreasing sequence of lambda values. glmnet relies on its
warms starts for speed, and its often faster to fit a whole path than compute a
single fit.
cv.glmnet will help you choose lambda, as you alluded to in your examples. The authors of the glmnet package suggest cv$lambda.1se instead of cv$lambda.min, but in practice I've had success with the latter.
After running cv.glmnet, you don't have to rerun glmnet! Every lambda in the grid (cv$lambda) has already been run. This technique is called "Warm Start" and you can read more about it here. Paraphrasing from the introduction, the Warm Start technique reduces running time of iterative methods by using the solution of a different optimization problem (e.g., glmnet with a larger lambda) as the starting value for a later optimization problem (e.g., glmnet with a smaller lambda).
To extract the desired run from cv.glmnet.fit, try this:
small.lambda.index <- which(cv$lambda == cv$lambda.min)
small.lambda.betas <- cv$glmnet.fit$beta[, small.lambda.index]
Revision (1/28/2017)
No need to hack to the glmnet object like I did above; take @alex23lemm's advice below and pass the s = "lambda.min", s = "lambda.1se" or some other number (e.g., s = .007) to both coef and predict. Note that your coefficients and predictions depend on this value which is set by cross validation. Use a seed for reproducibility! And don't forget that if you don't supply an "s" in coef and predict, you'll be using the default of s = "lambda.1se". I have warmed up to that default after seeing it work better in a small data situation. s = "lambda.1se" also tends to provide more regularization, so if you're working with alpha > 0, it will also tend towards a more parsimonious model. You can also choose a numerical value of s with the help of plot.glmnet to get to somewhere in between (just don't forget to exponentiate the values from the x axis!).
|
How to interpret glmnet?
Here's an unintuitive fact - you're not actually supposed to give glmnet a single value of lambda. From the documentation here:
Do not supply a single value for lambda (for predictions after CV use
|
6,007
|
How to interpret glmnet?
|
Q1) I am not sure about how to choose lambda.
Q2) Should I use the non (.) variables to fit another model? In my case I would like to keep as much variables as possible.
As per @BenOgorek's great answer, typically you let fitting use an entire lambda sequence, then when extracting the optimal coefficients use the lambda.1se value (unlike what you did).
As long as you follow the three caveats below, then do not fight the regularization or tweak the model: if a variable was omitted, then it was because it gave lower overall penalty. The caveats are:
For the regularized coeffts to be meaningful, make sure you explicitly normalized the variable's mean and stdev beforehand with scale(); don't rely on glmnet(standardize=T). For justification see Is standardisation before Lasso really necessary?; basically a variable with large values might get unfairly punished in regularization.
To be reproducible, run with set.seed with several random-seeds and check the regularized coefficients for stability.
If you want less harsh regularization i.e. more variables included, use alpha < 1 (i.e. proper elastic-net) rather than simple ridge. I suggest you sweep alpha from 0 to 1. If you're going to do that, then to avoid overfitting the hyperparameter alpha and the regression error, you must use crossvalidation, i.e. use cv.glmnet() rather than simple glmnet():
.
for (alpha in c(0,.1,.3,.5,.7,.9,1)) {
fit <- cv.glmnet(..., alpha=alpha, nfolds=...)
# Look at the CVE at lambda.1se to find the minimum for this alpha value...
}
If you want to automate such a gridsearch with CV, you can either code it yourself or use caret package on top of glmnet; caret does this well.
For cv.glmnet nfolds parameter value, pick 3 (minimum) if your dataset is small, or 5 or 10 if it's large.
Q3) How do I know the p-value, i.e. which variables significantly predict the response?
Don't, they're not meaningful. As explained in detail in Why is it inadvisable to get statistical summary information for regression coefficients from glmnet model?
Just let cv.glmnet() do the variable selection automatically. With the caveats above. And of course the distribution of the response variable should be normal (assuming you're using family='gaussian').
|
How to interpret glmnet?
|
Q1) I am not sure about how to choose lambda.
Q2) Should I use the non (.) variables to fit another model? In my case I would like to keep as much variables as possible.
As per @BenOgorek's great answ
|
How to interpret glmnet?
Q1) I am not sure about how to choose lambda.
Q2) Should I use the non (.) variables to fit another model? In my case I would like to keep as much variables as possible.
As per @BenOgorek's great answer, typically you let fitting use an entire lambda sequence, then when extracting the optimal coefficients use the lambda.1se value (unlike what you did).
As long as you follow the three caveats below, then do not fight the regularization or tweak the model: if a variable was omitted, then it was because it gave lower overall penalty. The caveats are:
For the regularized coeffts to be meaningful, make sure you explicitly normalized the variable's mean and stdev beforehand with scale(); don't rely on glmnet(standardize=T). For justification see Is standardisation before Lasso really necessary?; basically a variable with large values might get unfairly punished in regularization.
To be reproducible, run with set.seed with several random-seeds and check the regularized coefficients for stability.
If you want less harsh regularization i.e. more variables included, use alpha < 1 (i.e. proper elastic-net) rather than simple ridge. I suggest you sweep alpha from 0 to 1. If you're going to do that, then to avoid overfitting the hyperparameter alpha and the regression error, you must use crossvalidation, i.e. use cv.glmnet() rather than simple glmnet():
.
for (alpha in c(0,.1,.3,.5,.7,.9,1)) {
fit <- cv.glmnet(..., alpha=alpha, nfolds=...)
# Look at the CVE at lambda.1se to find the minimum for this alpha value...
}
If you want to automate such a gridsearch with CV, you can either code it yourself or use caret package on top of glmnet; caret does this well.
For cv.glmnet nfolds parameter value, pick 3 (minimum) if your dataset is small, or 5 or 10 if it's large.
Q3) How do I know the p-value, i.e. which variables significantly predict the response?
Don't, they're not meaningful. As explained in detail in Why is it inadvisable to get statistical summary information for regression coefficients from glmnet model?
Just let cv.glmnet() do the variable selection automatically. With the caveats above. And of course the distribution of the response variable should be normal (assuming you're using family='gaussian').
|
How to interpret glmnet?
Q1) I am not sure about how to choose lambda.
Q2) Should I use the non (.) variables to fit another model? In my case I would like to keep as much variables as possible.
As per @BenOgorek's great answ
|
6,008
|
How to quasi match two vectors of strings (in R)?
|
I've had similar problems. (seen here: https://stackoverflow.com/questions/2231993/merging-two-data-frames-using-fuzzy-approximate-string-matching-in-r)
Most of the recommendations that I received fell around:
pmatch(), and agrep(), grep(), grepl() are three functions that if you take the time to look through will provide you with some insight into approximate string matching either by approximate string or approximate regex.
Without seeing the strings, it's hard to provide you with hard example of how to match them. If you could provide us with some example data I'm sure we could come to a solution.
Another option that I found works well is to flatten the strings, tolower(), looking at the first letter of each word within the string and then comparing. Sometimes that works without a hitch. Then there are more complicated things like the distances mentioned in other answers. Sometimes these work, sometimes they're horrible - it really depends on the strings.
Can we see them?
Update
It looks like agrep() will do the trick for most of these. Note that agrep() is just R's implementation of Levenshtein distance.
agrep(vec55[1],vec91,value=T)
Some don't compute although, I'm not even sure if Ferroplasm acidaramus is the same as Ferroglobus placidus DSM 10642, for example:
agrep(vec55[7],vec91,value=T)
I think you may be a bit SOL for some of these and perhaps creating an index from scratch is the best bet. ie,. Create a table with id numbers for vec55, and then manually create a reference to the id's in vec55 in vec91. Painful, I know, but a lot of it can be done with agrep().
|
How to quasi match two vectors of strings (in R)?
|
I've had similar problems. (seen here: https://stackoverflow.com/questions/2231993/merging-two-data-frames-using-fuzzy-approximate-string-matching-in-r)
Most of the recommendations that I received fel
|
How to quasi match two vectors of strings (in R)?
I've had similar problems. (seen here: https://stackoverflow.com/questions/2231993/merging-two-data-frames-using-fuzzy-approximate-string-matching-in-r)
Most of the recommendations that I received fell around:
pmatch(), and agrep(), grep(), grepl() are three functions that if you take the time to look through will provide you with some insight into approximate string matching either by approximate string or approximate regex.
Without seeing the strings, it's hard to provide you with hard example of how to match them. If you could provide us with some example data I'm sure we could come to a solution.
Another option that I found works well is to flatten the strings, tolower(), looking at the first letter of each word within the string and then comparing. Sometimes that works without a hitch. Then there are more complicated things like the distances mentioned in other answers. Sometimes these work, sometimes they're horrible - it really depends on the strings.
Can we see them?
Update
It looks like agrep() will do the trick for most of these. Note that agrep() is just R's implementation of Levenshtein distance.
agrep(vec55[1],vec91,value=T)
Some don't compute although, I'm not even sure if Ferroplasm acidaramus is the same as Ferroglobus placidus DSM 10642, for example:
agrep(vec55[7],vec91,value=T)
I think you may be a bit SOL for some of these and perhaps creating an index from scratch is the best bet. ie,. Create a table with id numbers for vec55, and then manually create a reference to the id's in vec55 in vec91. Painful, I know, but a lot of it can be done with agrep().
|
How to quasi match two vectors of strings (in R)?
I've had similar problems. (seen here: https://stackoverflow.com/questions/2231993/merging-two-data-frames-using-fuzzy-approximate-string-matching-in-r)
Most of the recommendations that I received fel
|
6,009
|
How to quasi match two vectors of strings (in R)?
|
There are many ways to measure distances between two strings. Two important (standard) approaches widely implemented in R are the Levenshtein and the Hamming distance. The former is avalaible in package 'MiscPsycho' and the latter in 'e1071'. Using these, i would simply compute a 92 by 55 matrix of pairwise distances, then proceed from there (i.e. the best candidate match for string "1" in list 1 is the string "x" from list 2 with smallest distance to string "1").
Alternatively, there is a function compare() in package RecordLinkage that seems to be designed to do what you want and uses the so called Jaro-Winkler distance which seems more appropriate for the task at hand, but i've had no experience with it.
EDIT: i'm editing my answer to include Brandon's comment as well as Tal's code, to find a match to "Aeropyrum pernix", the first entry of vec55:
agrep(vec55[1],vec91,ignore.case=T,value=T,max.distance = 0.1, useBytes = FALSE)
[1] "Aeropyrum pernix K1"
|
How to quasi match two vectors of strings (in R)?
|
There are many ways to measure distances between two strings. Two important (standard) approaches widely implemented in R are the Levenshtein and the Hamming distance. The former is avalaible in packa
|
How to quasi match two vectors of strings (in R)?
There are many ways to measure distances between two strings. Two important (standard) approaches widely implemented in R are the Levenshtein and the Hamming distance. The former is avalaible in package 'MiscPsycho' and the latter in 'e1071'. Using these, i would simply compute a 92 by 55 matrix of pairwise distances, then proceed from there (i.e. the best candidate match for string "1" in list 1 is the string "x" from list 2 with smallest distance to string "1").
Alternatively, there is a function compare() in package RecordLinkage that seems to be designed to do what you want and uses the so called Jaro-Winkler distance which seems more appropriate for the task at hand, but i've had no experience with it.
EDIT: i'm editing my answer to include Brandon's comment as well as Tal's code, to find a match to "Aeropyrum pernix", the first entry of vec55:
agrep(vec55[1],vec91,ignore.case=T,value=T,max.distance = 0.1, useBytes = FALSE)
[1] "Aeropyrum pernix K1"
|
How to quasi match two vectors of strings (in R)?
There are many ways to measure distances between two strings. Two important (standard) approaches widely implemented in R are the Levenshtein and the Hamming distance. The former is avalaible in packa
|
6,010
|
How to quasi match two vectors of strings (in R)?
|
To supplement Kwak's useful answer, allow me to add some simple principles and ideas. A good way to determine the metric is by considering how the strings might vary from their target. "Edit distance" is useful when the variation is a combination of typographic errors like transposing neighbors or mis-typing a single key.
Another useful approach (with a slightly different philosophy) is to map every string into one representative of a class of related strings. The "Soundex" method does this: the Soundex code for a word is a sequence of four characters encoding the principal consonant and groups of similar-sounding internal consequence. It is used when words are phonetic misspellings or variants of one another. In the example application you would fetch all target words whose Soundex code equals the Soundex code for each probe word. (There could be zero or multiple targets fetched this way.)
|
How to quasi match two vectors of strings (in R)?
|
To supplement Kwak's useful answer, allow me to add some simple principles and ideas. A good way to determine the metric is by considering how the strings might vary from their target. "Edit distanc
|
How to quasi match two vectors of strings (in R)?
To supplement Kwak's useful answer, allow me to add some simple principles and ideas. A good way to determine the metric is by considering how the strings might vary from their target. "Edit distance" is useful when the variation is a combination of typographic errors like transposing neighbors or mis-typing a single key.
Another useful approach (with a slightly different philosophy) is to map every string into one representative of a class of related strings. The "Soundex" method does this: the Soundex code for a word is a sequence of four characters encoding the principal consonant and groups of similar-sounding internal consequence. It is used when words are phonetic misspellings or variants of one another. In the example application you would fetch all target words whose Soundex code equals the Soundex code for each probe word. (There could be zero or multiple targets fetched this way.)
|
How to quasi match two vectors of strings (in R)?
To supplement Kwak's useful answer, allow me to add some simple principles and ideas. A good way to determine the metric is by considering how the strings might vary from their target. "Edit distanc
|
6,011
|
How to quasi match two vectors of strings (in R)?
|
I would also suggest you check out N-grams and the Damerau–Levenshtein distance besides the other suggestions of Kwak.
This paper compares the accuracy of a few different edit distances mentioned here (and is highly cited according to google scholar).
As you can see there are many different ways to approach this, and you can even combine different metrics (the paper I linked to talks about this alittle bit). I think the Levenshtein and related based metrics make the most intuitive sense, especially if errors occur because of human typing. N-grams are also simple and make sense for data that is not names or words per say.
While soundex is an option, the little bit of work I have seen (which is admittedly a very small amount) soundex does not perform as well as Levenshstein or other edit distances for matching names. And the Soundex is limited to phonetic phrases likely inputted by human typers, where as Levenshtein and N-grams have a potentially broader scope (especially N-gram, but I would expect the Levenshtein distance to perform better for non-words as well).
I can't help as far as packages, but the concept of N-grams is pretty simple (I did make an SPSS macro to do N-grams recently, but for such a small project I would just go with the already made packages in R the other posters have suggested). Here is an example of calculating the Levenshtein distance in python.
|
How to quasi match two vectors of strings (in R)?
|
I would also suggest you check out N-grams and the Damerau–Levenshtein distance besides the other suggestions of Kwak.
This paper compares the accuracy of a few different edit distances mentioned her
|
How to quasi match two vectors of strings (in R)?
I would also suggest you check out N-grams and the Damerau–Levenshtein distance besides the other suggestions of Kwak.
This paper compares the accuracy of a few different edit distances mentioned here (and is highly cited according to google scholar).
As you can see there are many different ways to approach this, and you can even combine different metrics (the paper I linked to talks about this alittle bit). I think the Levenshtein and related based metrics make the most intuitive sense, especially if errors occur because of human typing. N-grams are also simple and make sense for data that is not names or words per say.
While soundex is an option, the little bit of work I have seen (which is admittedly a very small amount) soundex does not perform as well as Levenshstein or other edit distances for matching names. And the Soundex is limited to phonetic phrases likely inputted by human typers, where as Levenshtein and N-grams have a potentially broader scope (especially N-gram, but I would expect the Levenshtein distance to perform better for non-words as well).
I can't help as far as packages, but the concept of N-grams is pretty simple (I did make an SPSS macro to do N-grams recently, but for such a small project I would just go with the already made packages in R the other posters have suggested). Here is an example of calculating the Levenshtein distance in python.
|
How to quasi match two vectors of strings (in R)?
I would also suggest you check out N-grams and the Damerau–Levenshtein distance besides the other suggestions of Kwak.
This paper compares the accuracy of a few different edit distances mentioned her
|
6,012
|
How to quasi match two vectors of strings (in R)?
|
I researched some packages and ways how to solve this problem and I think the best candidate is the fuzzywuzzyR package.
The fuzzywuzzyR package is a fuzzy string matching implemenation of the fuzzywuzzy python package. It uses the Levenshtein Distance to calculate the differences between sequences. More details on the functionality of fuzzywuzzyR can be found in the blog-post and in the package Vignette.
I did the simple solution for your problem, but there is a little catch. You have to install python and if you use winodows also have to install some build tools for visual studio. You have to choose these:
Windows 10 sdk 10.0.17763.0 and MSVC v140
VS 2015 C++ build tools (v 14v00)
The solution is simple. The main function ExtractOne returns list of two values. First is one string match and second one is the corresponding score ( in the range 0 - 100 ). The fuzzywuzzyR package provides also other functions which can be useful. Main documentation can found here. I hope this code helps solve the problem.
library(fuzzywuzzyR)
# The Fuzzy initialization
init_proc = FuzzUtils$new()
PROC = init_proc$Full_process # class process-method
PROC1 = tolower # base R function
init_scor = FuzzMatcher$new()
SCOR = init_scor$WRATIO
init <- FuzzExtract$new()
match_strings <- function(vector_to_process, base_vector){
new_vec = c()
for(i in 1:length(vector_to_process)){
new_word <- init$ExtractOne(string = vector_to_process[i], sequence_strings = base_vector, processor = PROC1, scorer = SCOR, score_cutoff = 0L)
new_vec[i] <- new_word[[1]]
}
return(new_vec)
}
# Check if all python modules are available
if (check_availability()){
new_vec <- match_strings(vec55, vec91)
print(new_vec)
}
Output:
[1] "Aeropyrum pernix K1" "Archaeoglobus fulgidus DSM 4304"
[3] "Candidatus Korarchaeum cryptofilum OPF8" "Candidatus Methanoregula boonei 6A8"
[5] "Cenarchaeum symbiosum A" "Desulfurococcus kamchatkensis 1221n"
[7] "Thermoplasma volcanium GSS1" "Haloarcula marismortui ATCC 43049"
[9] "Halobacterium sp. NRC-1" "Halobacterium salinarum R1"
[11] "Haloferax volcanii DS2" "Haloquadratum walsbyi DSM 16790"
[13] "Hyperthermus butylicus DSM 5456" "Ignicoccus hospitalis KIN4/I"
[15] "Metallosphaera sedula DSM 5348" "Methanothermobacter thermautotrophicus str. Delta H"
[17] "Methanobrevibacter smithii ATCC 35061" "Methanococcoides burtonii DSM 6242"
|
How to quasi match two vectors of strings (in R)?
|
I researched some packages and ways how to solve this problem and I think the best candidate is the fuzzywuzzyR package.
The fuzzywuzzyR package is a fuzzy string matching implemenation of the fuzzyw
|
How to quasi match two vectors of strings (in R)?
I researched some packages and ways how to solve this problem and I think the best candidate is the fuzzywuzzyR package.
The fuzzywuzzyR package is a fuzzy string matching implemenation of the fuzzywuzzy python package. It uses the Levenshtein Distance to calculate the differences between sequences. More details on the functionality of fuzzywuzzyR can be found in the blog-post and in the package Vignette.
I did the simple solution for your problem, but there is a little catch. You have to install python and if you use winodows also have to install some build tools for visual studio. You have to choose these:
Windows 10 sdk 10.0.17763.0 and MSVC v140
VS 2015 C++ build tools (v 14v00)
The solution is simple. The main function ExtractOne returns list of two values. First is one string match and second one is the corresponding score ( in the range 0 - 100 ). The fuzzywuzzyR package provides also other functions which can be useful. Main documentation can found here. I hope this code helps solve the problem.
library(fuzzywuzzyR)
# The Fuzzy initialization
init_proc = FuzzUtils$new()
PROC = init_proc$Full_process # class process-method
PROC1 = tolower # base R function
init_scor = FuzzMatcher$new()
SCOR = init_scor$WRATIO
init <- FuzzExtract$new()
match_strings <- function(vector_to_process, base_vector){
new_vec = c()
for(i in 1:length(vector_to_process)){
new_word <- init$ExtractOne(string = vector_to_process[i], sequence_strings = base_vector, processor = PROC1, scorer = SCOR, score_cutoff = 0L)
new_vec[i] <- new_word[[1]]
}
return(new_vec)
}
# Check if all python modules are available
if (check_availability()){
new_vec <- match_strings(vec55, vec91)
print(new_vec)
}
Output:
[1] "Aeropyrum pernix K1" "Archaeoglobus fulgidus DSM 4304"
[3] "Candidatus Korarchaeum cryptofilum OPF8" "Candidatus Methanoregula boonei 6A8"
[5] "Cenarchaeum symbiosum A" "Desulfurococcus kamchatkensis 1221n"
[7] "Thermoplasma volcanium GSS1" "Haloarcula marismortui ATCC 43049"
[9] "Halobacterium sp. NRC-1" "Halobacterium salinarum R1"
[11] "Haloferax volcanii DS2" "Haloquadratum walsbyi DSM 16790"
[13] "Hyperthermus butylicus DSM 5456" "Ignicoccus hospitalis KIN4/I"
[15] "Metallosphaera sedula DSM 5348" "Methanothermobacter thermautotrophicus str. Delta H"
[17] "Methanobrevibacter smithii ATCC 35061" "Methanococcoides burtonii DSM 6242"
|
How to quasi match two vectors of strings (in R)?
I researched some packages and ways how to solve this problem and I think the best candidate is the fuzzywuzzyR package.
The fuzzywuzzyR package is a fuzzy string matching implemenation of the fuzzyw
|
6,013
|
How to quasi match two vectors of strings (in R)?
|
Based on function adist
Compute the approximate string distance between character vectors.
The distance is a generalized Levenshtein (edit) distance, giving
the minimal possibly weighted number of insertions, deletions and
substitutions needed to transform one string into another
Function stringdist from a package of the same name has several methods (see ?stringdist-methods):
method = c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine",
"jaccard", "jw", "soundex")
With this, you can select maximum divergence (threshold):
firstvector<-vec55
secondvector<-vec91
match<-character()
threshold<-14 # max 14 characters of divergence
mindist<-integer()
sortedmatches<-character()
for (i in 1:length(firstvector) ) {
matchdist<-adist(firstvector[i],secondvector)[1,]
# matchdist<-stringdist(firstvector[i],secondvector) # several methods available
matchdist<-ifelse(matchdist>threshold,NA,matchdist)
sortedmatches[i]<-paste(secondvector[order(matchdist, na.last=NA)], collapse = ", ")
mindist[i]<- tryCatch(ifelse(is.integer(which.min(matchdist)),matchdist[which.min(matchdist)],NA), error = function(e){NA})
match[i]<-ifelse(length(secondvector[which.min(matchdist)])==0,NA,
secondvector[which.min(matchdist)] )
}
res<-data.frame(firstvector=firstvector,match=match,divergence=mindist, sortedmatches=sortedmatches, stringsAsFactors = F)
res
This dataframe shows the first vector in column firstvector, the bestmatch of the secondvector in column match, its distance in column divergence, and all significant matches ordered in column sortedmatches as in the OP.
|
How to quasi match two vectors of strings (in R)?
|
Based on function adist
Compute the approximate string distance between character vectors.
The distance is a generalized Levenshtein (edit) distance, giving
the minimal possibly weighted number of in
|
How to quasi match two vectors of strings (in R)?
Based on function adist
Compute the approximate string distance between character vectors.
The distance is a generalized Levenshtein (edit) distance, giving
the minimal possibly weighted number of insertions, deletions and
substitutions needed to transform one string into another
Function stringdist from a package of the same name has several methods (see ?stringdist-methods):
method = c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine",
"jaccard", "jw", "soundex")
With this, you can select maximum divergence (threshold):
firstvector<-vec55
secondvector<-vec91
match<-character()
threshold<-14 # max 14 characters of divergence
mindist<-integer()
sortedmatches<-character()
for (i in 1:length(firstvector) ) {
matchdist<-adist(firstvector[i],secondvector)[1,]
# matchdist<-stringdist(firstvector[i],secondvector) # several methods available
matchdist<-ifelse(matchdist>threshold,NA,matchdist)
sortedmatches[i]<-paste(secondvector[order(matchdist, na.last=NA)], collapse = ", ")
mindist[i]<- tryCatch(ifelse(is.integer(which.min(matchdist)),matchdist[which.min(matchdist)],NA), error = function(e){NA})
match[i]<-ifelse(length(secondvector[which.min(matchdist)])==0,NA,
secondvector[which.min(matchdist)] )
}
res<-data.frame(firstvector=firstvector,match=match,divergence=mindist, sortedmatches=sortedmatches, stringsAsFactors = F)
res
This dataframe shows the first vector in column firstvector, the bestmatch of the secondvector in column match, its distance in column divergence, and all significant matches ordered in column sortedmatches as in the OP.
|
How to quasi match two vectors of strings (in R)?
Based on function adist
Compute the approximate string distance between character vectors.
The distance is a generalized Levenshtein (edit) distance, giving
the minimal possibly weighted number of in
|
6,014
|
Improve classification with many categorical variables
|
Random forests should be able to handle categorical values natively so look for a different implementation so you don't have to encode all of those features and use up all your memory.
The problem with high cardinality categorical features is that it is easy to over fit with them. You may have enough data that this isn't an issue but watch out for it.
I suggest looking into random forest based feature selection using either the method Breiman proposed or artificial contrasts. The artificial contrasts method (ACE) is interesting because it compares the importance of the feature to the importance of a shuffled version of itself which fights some of the high cardinality issues. There is a new paper "Module Guided Random Forests" which might be interesting if you had many more features as it uses a feature selection method that is aware of groups of highly correlated features.
Another sometime used option is to tweak the algorithm so it uses the out of bag cases to do the final feature selection after fitting the splits on the in bag cases which sometimes helps fight overfitting.
There is an almost complete ace implementation here and I have a more memory efficient/fast RF implementation that handles categorical variables natively here...the -evaloob option supports option 4 I'm working on adding support for ACE and a couple of other RF based feature selection methods but it isn't done yet.
|
Improve classification with many categorical variables
|
Random forests should be able to handle categorical values natively so look for a different implementation so you don't have to encode all of those features and use up all your memory.
The problem wi
|
Improve classification with many categorical variables
Random forests should be able to handle categorical values natively so look for a different implementation so you don't have to encode all of those features and use up all your memory.
The problem with high cardinality categorical features is that it is easy to over fit with them. You may have enough data that this isn't an issue but watch out for it.
I suggest looking into random forest based feature selection using either the method Breiman proposed or artificial contrasts. The artificial contrasts method (ACE) is interesting because it compares the importance of the feature to the importance of a shuffled version of itself which fights some of the high cardinality issues. There is a new paper "Module Guided Random Forests" which might be interesting if you had many more features as it uses a feature selection method that is aware of groups of highly correlated features.
Another sometime used option is to tweak the algorithm so it uses the out of bag cases to do the final feature selection after fitting the splits on the in bag cases which sometimes helps fight overfitting.
There is an almost complete ace implementation here and I have a more memory efficient/fast RF implementation that handles categorical variables natively here...the -evaloob option supports option 4 I'm working on adding support for ACE and a couple of other RF based feature selection methods but it isn't done yet.
|
Improve classification with many categorical variables
Random forests should be able to handle categorical values natively so look for a different implementation so you don't have to encode all of those features and use up all your memory.
The problem wi
|
6,015
|
Improve classification with many categorical variables
|
Instead of dummifying your categories, why wouldn't you simply use a single numerical variable for each? In the context of random forests, I've often been wondering about the consequence of doing that (because I agree that it sounds suspcious to introduce ordinality in categorical data with which if often doesn't make sense), but in practice (at least with the scikit-learn implementation of RFs I've been using), I've often observed that it doesn't make a difference on the results (I'm not sure why though).
|
Improve classification with many categorical variables
|
Instead of dummifying your categories, why wouldn't you simply use a single numerical variable for each? In the context of random forests, I've often been wondering about the consequence of doing that
|
Improve classification with many categorical variables
Instead of dummifying your categories, why wouldn't you simply use a single numerical variable for each? In the context of random forests, I've often been wondering about the consequence of doing that (because I agree that it sounds suspcious to introduce ordinality in categorical data with which if often doesn't make sense), but in practice (at least with the scikit-learn implementation of RFs I've been using), I've often observed that it doesn't make a difference on the results (I'm not sure why though).
|
Improve classification with many categorical variables
Instead of dummifying your categories, why wouldn't you simply use a single numerical variable for each? In the context of random forests, I've often been wondering about the consequence of doing that
|
6,016
|
Improve classification with many categorical variables
|
I think you should consider a/more variable reduction technique(s). It gets rid of the not so influent predictors.
I have been reading a lot about data pre-processing and it is a great solution to reduce the n° of your variables.
My suggestions are as follows:
for qualitative variables, replace missing values with category "missing".
It can introduce bias if the data is not missing at random, but at least you'll have all your observations intact and the missingness might reveal a different behaviour.
eliminate zero variance predictors or near-zero variance predictors (be careful not to eliminate dummy variables with high unbalanced categories that can separate your Y efficiently. Make some graphs for the variables you think might be important).
In R, you can use the 'nzv' function from the 'caret' package. This will highly reduce your data dimension.
eliminate correlated predictors. Use Kendall's correlation matrix because it is more fit to construct in the presence of categorical variables. The downside is you have to transform all your nominal vars into categorical ones.
there are feature selection methods that will reduce their number even more (clustering - you choose a single representative of each cluster, the LASSO regression, etc...). I haven't had the chance to test them yet because the other steps reduced my variables to under 100.
Also, I would suggest using the AdaBoost algorithm instead of the RF. Personally, the researches that I've done gave me very similar Gini coefficients for both these methods. The good part about AdaBoost is that in R, it handles missing observations. So you can skip the 1st step of this list
I hope it helped a little. Good luck
|
Improve classification with many categorical variables
|
I think you should consider a/more variable reduction technique(s). It gets rid of the not so influent predictors.
I have been reading a lot about data pre-processing and it is a great solution to red
|
Improve classification with many categorical variables
I think you should consider a/more variable reduction technique(s). It gets rid of the not so influent predictors.
I have been reading a lot about data pre-processing and it is a great solution to reduce the n° of your variables.
My suggestions are as follows:
for qualitative variables, replace missing values with category "missing".
It can introduce bias if the data is not missing at random, but at least you'll have all your observations intact and the missingness might reveal a different behaviour.
eliminate zero variance predictors or near-zero variance predictors (be careful not to eliminate dummy variables with high unbalanced categories that can separate your Y efficiently. Make some graphs for the variables you think might be important).
In R, you can use the 'nzv' function from the 'caret' package. This will highly reduce your data dimension.
eliminate correlated predictors. Use Kendall's correlation matrix because it is more fit to construct in the presence of categorical variables. The downside is you have to transform all your nominal vars into categorical ones.
there are feature selection methods that will reduce their number even more (clustering - you choose a single representative of each cluster, the LASSO regression, etc...). I haven't had the chance to test them yet because the other steps reduced my variables to under 100.
Also, I would suggest using the AdaBoost algorithm instead of the RF. Personally, the researches that I've done gave me very similar Gini coefficients for both these methods. The good part about AdaBoost is that in R, it handles missing observations. So you can skip the 1st step of this list
I hope it helped a little. Good luck
|
Improve classification with many categorical variables
I think you should consider a/more variable reduction technique(s). It gets rid of the not so influent predictors.
I have been reading a lot about data pre-processing and it is a great solution to red
|
6,017
|
Improve classification with many categorical variables
|
You may want to consider mixed-effects models. They are popular in social science due to their performance on high-cardinality categorical data, and I have used them to make great predictive models outperforming popular machine learning approaches like gradient boosted trees, random forests, and elastic-net regularized logistic regression. The most well-known implementation is R's lme4 package; the function you'd use for classification is glmer, which implements mixed-effects logistic regression. You may have issues with scaling to your dataset, but I have done 80k rows with 15 features without too much difficulty.
|
Improve classification with many categorical variables
|
You may want to consider mixed-effects models. They are popular in social science due to their performance on high-cardinality categorical data, and I have used them to make great predictive models ou
|
Improve classification with many categorical variables
You may want to consider mixed-effects models. They are popular in social science due to their performance on high-cardinality categorical data, and I have used them to make great predictive models outperforming popular machine learning approaches like gradient boosted trees, random forests, and elastic-net regularized logistic regression. The most well-known implementation is R's lme4 package; the function you'd use for classification is glmer, which implements mixed-effects logistic regression. You may have issues with scaling to your dataset, but I have done 80k rows with 15 features without too much difficulty.
|
Improve classification with many categorical variables
You may want to consider mixed-effects models. They are popular in social science due to their performance on high-cardinality categorical data, and I have used them to make great predictive models ou
|
6,018
|
Improve classification with many categorical variables
|
When you say "build dummy variable for each categorical one", sounds like you're using Python not R? R randomforest can natively handle categoricals, also consequential memory reduction. Try R.
Next, you don't need to manually prune/merge the categorical levels, that sounds like a major pain. And even if you did, you're not guaranteed that the most populous categories are the most predictive. Control randomforest complexity with parameter nodesize: start with a large nodesize, and progressively reduce it (this is hyperparameter search).
Variable selection will be useful. @lorelai gives good recommendations. Try to eliminate useless (low-importance or highly-correlated) features. Tree construction is quadratic to the number of features, so if you even eliminate a third it'll pay dividends.
|
Improve classification with many categorical variables
|
When you say "build dummy variable for each categorical one", sounds like you're using Python not R? R randomforest can natively handle categoricals, also consequential memory reduction. Try R.
Next,
|
Improve classification with many categorical variables
When you say "build dummy variable for each categorical one", sounds like you're using Python not R? R randomforest can natively handle categoricals, also consequential memory reduction. Try R.
Next, you don't need to manually prune/merge the categorical levels, that sounds like a major pain. And even if you did, you're not guaranteed that the most populous categories are the most predictive. Control randomforest complexity with parameter nodesize: start with a large nodesize, and progressively reduce it (this is hyperparameter search).
Variable selection will be useful. @lorelai gives good recommendations. Try to eliminate useless (low-importance or highly-correlated) features. Tree construction is quadratic to the number of features, so if you even eliminate a third it'll pay dividends.
|
Improve classification with many categorical variables
When you say "build dummy variable for each categorical one", sounds like you're using Python not R? R randomforest can natively handle categoricals, also consequential memory reduction. Try R.
Next,
|
6,019
|
Improve classification with many categorical variables
|
You should look at the H2O.ai package. It handles categorical variables out of the box without having to do any encoding (make sure the variables are factors).
I particularly like their implementation of Gradient Boosted Machine (GBM) because you can then look at the variable importance after building the model. GBM's also have the nice feature of being resistant to overfitting.
If you want to explore other models, they have: GLM, Random Forest, Naive Bayes, Deep Learning, etc.
See:
http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm.html
It's also easy to install (Windows, Linux, Mac) and easy to run with API's using R, Python, Java, and Scala.
It can use multiple cores to speed things up.
In the near future, they will support GPUs.
It's also open source and free (There is Enterprise support).
|
Improve classification with many categorical variables
|
You should look at the H2O.ai package. It handles categorical variables out of the box without having to do any encoding (make sure the variables are factors).
I particularly like their implementatio
|
Improve classification with many categorical variables
You should look at the H2O.ai package. It handles categorical variables out of the box without having to do any encoding (make sure the variables are factors).
I particularly like their implementation of Gradient Boosted Machine (GBM) because you can then look at the variable importance after building the model. GBM's also have the nice feature of being resistant to overfitting.
If you want to explore other models, they have: GLM, Random Forest, Naive Bayes, Deep Learning, etc.
See:
http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm.html
It's also easy to install (Windows, Linux, Mac) and easy to run with API's using R, Python, Java, and Scala.
It can use multiple cores to speed things up.
In the near future, they will support GPUs.
It's also open source and free (There is Enterprise support).
|
Improve classification with many categorical variables
You should look at the H2O.ai package. It handles categorical variables out of the box without having to do any encoding (make sure the variables are factors).
I particularly like their implementatio
|
6,020
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
|
It sounds like you need a decent basic statistics text that covers at least basic location tests, simple regression and multiple regression.
Std. Error,t value and Pr.
Std. Error is the standard deviation of the sampling distribution
of the estimate of the coefficient under the standard regression
assumptions. Such standard deviations are called standard errors
of the corresponding quantity (the coefficient estimate in this
case).
In the case of simple regression, it's usually denoted $s_{\hat
\beta}$, as here. Also see this
For multiple regression, it's a little more complicated, but if you
don't know what these things are it's probably best to understand
them in the context of simple regression first.
t value is the value of the t-statistic for testing whether the
corresponding regression coefficient is different from 0.
The formula for computing it is given at the first link above.
Pr. is the p-value for the
hypothesis test for which the t value is the test statistic. It
tells you the probability of a test statistic at least as unusual as
the one you obtained, if the null hypothesis were true. In this
case, the null hypothesis is that the true coefficient is zero; if
that probability is low, it's suggesting that it would be rare to
get a result as unusual as this if the coefficient were really zero.
Most importantly, which variables should I look at to ascertain on whether a model is giving me good prediction data?
What do you mean by 'good prediction data'? Can you make it clearer what you're asking?
The Residual standard error, which is usually called $s$, represents the standard deviation of the residuals. It's a measure of how close the fit is to the points.
The Multiple R-squared, also called the coefficient of determination is the proportion of the variance in the data that's explained by the model. The more variables you add - even if they don't help - the larger this will be. The Adjusted one reduces that to account for the number of variables in the model.
The $F$ statistic on the last line is telling you whether the regression as a whole is performing 'better than random' - any set of random predictors will have some relationship with the response, so it's seeing whether your model fits better than you'd expect if all your predictors had no relationship with the response (beyond what would be explained by that randomness). This is used for a test of whether the model outperforms 'noise' as a predictor. The p-value in the last row is the p-value for that test, essentially comparing the full model you fitted with an intercept-only model.
Where do the data come from? Is this in some package?
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
|
It sounds like you need a decent basic statistics text that covers at least basic location tests, simple regression and multiple regression.
Std. Error,t value and Pr.
Std. Error is the standard d
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
It sounds like you need a decent basic statistics text that covers at least basic location tests, simple regression and multiple regression.
Std. Error,t value and Pr.
Std. Error is the standard deviation of the sampling distribution
of the estimate of the coefficient under the standard regression
assumptions. Such standard deviations are called standard errors
of the corresponding quantity (the coefficient estimate in this
case).
In the case of simple regression, it's usually denoted $s_{\hat
\beta}$, as here. Also see this
For multiple regression, it's a little more complicated, but if you
don't know what these things are it's probably best to understand
them in the context of simple regression first.
t value is the value of the t-statistic for testing whether the
corresponding regression coefficient is different from 0.
The formula for computing it is given at the first link above.
Pr. is the p-value for the
hypothesis test for which the t value is the test statistic. It
tells you the probability of a test statistic at least as unusual as
the one you obtained, if the null hypothesis were true. In this
case, the null hypothesis is that the true coefficient is zero; if
that probability is low, it's suggesting that it would be rare to
get a result as unusual as this if the coefficient were really zero.
Most importantly, which variables should I look at to ascertain on whether a model is giving me good prediction data?
What do you mean by 'good prediction data'? Can you make it clearer what you're asking?
The Residual standard error, which is usually called $s$, represents the standard deviation of the residuals. It's a measure of how close the fit is to the points.
The Multiple R-squared, also called the coefficient of determination is the proportion of the variance in the data that's explained by the model. The more variables you add - even if they don't help - the larger this will be. The Adjusted one reduces that to account for the number of variables in the model.
The $F$ statistic on the last line is telling you whether the regression as a whole is performing 'better than random' - any set of random predictors will have some relationship with the response, so it's seeing whether your model fits better than you'd expect if all your predictors had no relationship with the response (beyond what would be explained by that randomness). This is used for a test of whether the model outperforms 'noise' as a predictor. The p-value in the last row is the p-value for that test, essentially comparing the full model you fitted with an intercept-only model.
Where do the data come from? Is this in some package?
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
It sounds like you need a decent basic statistics text that covers at least basic location tests, simple regression and multiple regression.
Std. Error,t value and Pr.
Std. Error is the standard d
|
6,021
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
|
The Standard error is an estimate of the variance of the strength of the effect, or the strength of the relationship between each causal variable and the predicted variable. If it's high, then the effect size will have to be stronger for us to be able to be sure that it's a real effect, and not just an artefact of randomness.
The t-statistic is an estimate of how extreme the value you see is, relative to the standard error (assuming a normal distribution, centred on the null hypothesis).
The p-value is an estimate of the probability of seeing a t-value as extreme, or more extreme the one you got, if you assume that the null hypothesis is true (the null hypothesis is usually "no effect", unless something else is specified). So if the p-value is very low, then there is a higher probability that you're seeing data that is counter-indicative of zero effect. In other situations, you can get a p-value based on other statistics and variables.
Unfortunately, if that explanation of the p-value is confusing, that's because the entire concept is confusing. It's important to note that technically a low p-value does not show high probability of an effect, although it may indicate that. Have a read of some of the high-voted p-value questions, to get an idea about what's going on here.
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
|
The Standard error is an estimate of the variance of the strength of the effect, or the strength of the relationship between each causal variable and the predicted variable. If it's high, then the eff
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
The Standard error is an estimate of the variance of the strength of the effect, or the strength of the relationship between each causal variable and the predicted variable. If it's high, then the effect size will have to be stronger for us to be able to be sure that it's a real effect, and not just an artefact of randomness.
The t-statistic is an estimate of how extreme the value you see is, relative to the standard error (assuming a normal distribution, centred on the null hypothesis).
The p-value is an estimate of the probability of seeing a t-value as extreme, or more extreme the one you got, if you assume that the null hypothesis is true (the null hypothesis is usually "no effect", unless something else is specified). So if the p-value is very low, then there is a higher probability that you're seeing data that is counter-indicative of zero effect. In other situations, you can get a p-value based on other statistics and variables.
Unfortunately, if that explanation of the p-value is confusing, that's because the entire concept is confusing. It's important to note that technically a low p-value does not show high probability of an effect, although it may indicate that. Have a read of some of the high-voted p-value questions, to get an idea about what's going on here.
|
How to interpret the output of the summary method for an lm object in R? [duplicate]
The Standard error is an estimate of the variance of the strength of the effect, or the strength of the relationship between each causal variable and the predicted variable. If it's high, then the eff
|
6,022
|
How does R handle missing values in lm?
|
Edit: I misunderstood your question. There are two aspects:
a) na.omit and na.exclude both do casewise deletion with respect to both predictors and criterions. They only differ in that extractor functions like residuals() or fitted() will pad their output with NAs for the omitted cases with na.exclude, thus having an output of the same length as the input variables.
> N <- 20 # generate some data
> y1 <- rnorm(N, 175, 7) # criterion 1
> y2 <- rnorm(N, 30, 8) # criterion 2
> x <- 0.5*y1 - 0.3*y2 + rnorm(N, 0, 3) # predictor
> y1[c(1, 3, 5)] <- NA # some NA values
> y2[c(7, 9, 11)] <- NA # some other NA values
> Y <- cbind(y1, y2) # matrix for multivariate regression
> fitO <- lm(Y ~ x, na.action=na.omit) # fit with na.omit
> dim(residuals(fitO)) # use extractor function
[1] 14 2
> fitE <- lm(Y ~ x, na.action=na.exclude) # fit with na.exclude
> dim(residuals(fitE)) # use extractor function -> = N
[1] 20 2
> dim(fitE$residuals) # access residuals directly
[1] 14 2
b) The real issue is not with this difference between na.omit and na.exclude, you don't seem to want casewise deletion that takes criterion variables into account, which both do.
> X <- model.matrix(fitE) # design matrix
> dim(X) # casewise deletion -> only 14 complete cases
[1] 14 2
The regression results depend on the matrices $X^{+} = (X' X)^{-1} X'$ (pseudoinverse of design matrix $X$, coefficients $\hat{\beta} = X^{+} Y$) and the hat matrix $H = X X^{+}$, fitted values $\hat{Y} = H Y$). If you don't want casewise deletion, you need a different design matrix $X$ for each column of $Y$, so there's no way around fitting separate regressions for each criterion. You can try to avoid the overhead of lm() by doing something along the lines of the following:
> Xf <- model.matrix(~ x) # full design matrix (all cases)
# function: manually calculate coefficients and fitted values for single criterion y
> getFit <- function(y) {
+ idx <- !is.na(y) # throw away NAs
+ Xsvd <- svd(Xf[idx , ]) # SVD decomposition of X
+ # get X+ but note: there might be better ways
+ Xplus <- tcrossprod(Xsvd$v %*% diag(Xsvd$d^(-2)) %*% t(Xsvd$v), Xf[idx, ])
+ list(coefs=(Xplus %*% y[idx]), yhat=(Xf[idx, ] %*% Xplus %*% y[idx]))
+ }
> res <- apply(Y, 2, getFit) # get fits for each column of Y
> res$y1$coefs
[,1]
(Intercept) 113.9398761
x 0.7601234
> res$y2$coefs
[,1]
(Intercept) 91.580505
x -0.805897
> coefficients(lm(y1 ~ x)) # compare with separate results from lm()
(Intercept) x
113.9398761 0.7601234
> coefficients(lm(y2 ~ x))
(Intercept) x
91.580505 -0.805897
Note that there might be numerically better ways to caculate $X^{+}$ and $H$, you could check a $QR$-decomposition instead. The SVD-approach is explained here on SE. I have not timed the above approach with big matrices $Y$ against actually using lm().
|
How does R handle missing values in lm?
|
Edit: I misunderstood your question. There are two aspects:
a) na.omit and na.exclude both do casewise deletion with respect to both predictors and criterions. They only differ in that extractor funct
|
How does R handle missing values in lm?
Edit: I misunderstood your question. There are two aspects:
a) na.omit and na.exclude both do casewise deletion with respect to both predictors and criterions. They only differ in that extractor functions like residuals() or fitted() will pad their output with NAs for the omitted cases with na.exclude, thus having an output of the same length as the input variables.
> N <- 20 # generate some data
> y1 <- rnorm(N, 175, 7) # criterion 1
> y2 <- rnorm(N, 30, 8) # criterion 2
> x <- 0.5*y1 - 0.3*y2 + rnorm(N, 0, 3) # predictor
> y1[c(1, 3, 5)] <- NA # some NA values
> y2[c(7, 9, 11)] <- NA # some other NA values
> Y <- cbind(y1, y2) # matrix for multivariate regression
> fitO <- lm(Y ~ x, na.action=na.omit) # fit with na.omit
> dim(residuals(fitO)) # use extractor function
[1] 14 2
> fitE <- lm(Y ~ x, na.action=na.exclude) # fit with na.exclude
> dim(residuals(fitE)) # use extractor function -> = N
[1] 20 2
> dim(fitE$residuals) # access residuals directly
[1] 14 2
b) The real issue is not with this difference between na.omit and na.exclude, you don't seem to want casewise deletion that takes criterion variables into account, which both do.
> X <- model.matrix(fitE) # design matrix
> dim(X) # casewise deletion -> only 14 complete cases
[1] 14 2
The regression results depend on the matrices $X^{+} = (X' X)^{-1} X'$ (pseudoinverse of design matrix $X$, coefficients $\hat{\beta} = X^{+} Y$) and the hat matrix $H = X X^{+}$, fitted values $\hat{Y} = H Y$). If you don't want casewise deletion, you need a different design matrix $X$ for each column of $Y$, so there's no way around fitting separate regressions for each criterion. You can try to avoid the overhead of lm() by doing something along the lines of the following:
> Xf <- model.matrix(~ x) # full design matrix (all cases)
# function: manually calculate coefficients and fitted values for single criterion y
> getFit <- function(y) {
+ idx <- !is.na(y) # throw away NAs
+ Xsvd <- svd(Xf[idx , ]) # SVD decomposition of X
+ # get X+ but note: there might be better ways
+ Xplus <- tcrossprod(Xsvd$v %*% diag(Xsvd$d^(-2)) %*% t(Xsvd$v), Xf[idx, ])
+ list(coefs=(Xplus %*% y[idx]), yhat=(Xf[idx, ] %*% Xplus %*% y[idx]))
+ }
> res <- apply(Y, 2, getFit) # get fits for each column of Y
> res$y1$coefs
[,1]
(Intercept) 113.9398761
x 0.7601234
> res$y2$coefs
[,1]
(Intercept) 91.580505
x -0.805897
> coefficients(lm(y1 ~ x)) # compare with separate results from lm()
(Intercept) x
113.9398761 0.7601234
> coefficients(lm(y2 ~ x))
(Intercept) x
91.580505 -0.805897
Note that there might be numerically better ways to caculate $X^{+}$ and $H$, you could check a $QR$-decomposition instead. The SVD-approach is explained here on SE. I have not timed the above approach with big matrices $Y$ against actually using lm().
|
How does R handle missing values in lm?
Edit: I misunderstood your question. There are two aspects:
a) na.omit and na.exclude both do casewise deletion with respect to both predictors and criterions. They only differ in that extractor funct
|
6,023
|
How does R handle missing values in lm?
|
I can think of two ways. One is combine the data use the na.exclude and then separate data again:
A = matrix(1:20, nrow=10, ncol=2)
colnames(A) <- paste("A",1:ncol(A),sep="")
B = matrix(1:10, nrow=10, ncol=1)
colnames(B) <- paste("B",1:ncol(B),sep="")
C <- cbind(A,B)
C[1,1] <- NA
C.ex <- na.exclude(C)
A.ex <- C[,colnames(A)]
B.ex <- C[,colnames(B)]
lm(A.ex~B.ex)
Another way is to use the data argument and create a formula.
Cd <- data.frame(C)
fr <- formula(paste("cbind(",paste(colnames(A),collapse=","),")~",paste(colnames(B),collapse="+"),sep=""))
lm(fr,data=Cd)
Cd[1,1] <-NA
lm(fr,data=Cd,na.action=na.exclude)
If you are doing a lot of regression the first way should be faster, since less background magic is performed. Although if you need only coefficients and residuals I suggest using lsfit, which is much faster than lm. The second way is a bit nicer, but on my laptop trying to do summary on the resulting regression throws an error. I will try to see whether this is a bug.
|
How does R handle missing values in lm?
|
I can think of two ways. One is combine the data use the na.exclude and then separate data again:
A = matrix(1:20, nrow=10, ncol=2)
colnames(A) <- paste("A",1:ncol(A),sep="")
B = matrix(1:10, nrow=10
|
How does R handle missing values in lm?
I can think of two ways. One is combine the data use the na.exclude and then separate data again:
A = matrix(1:20, nrow=10, ncol=2)
colnames(A) <- paste("A",1:ncol(A),sep="")
B = matrix(1:10, nrow=10, ncol=1)
colnames(B) <- paste("B",1:ncol(B),sep="")
C <- cbind(A,B)
C[1,1] <- NA
C.ex <- na.exclude(C)
A.ex <- C[,colnames(A)]
B.ex <- C[,colnames(B)]
lm(A.ex~B.ex)
Another way is to use the data argument and create a formula.
Cd <- data.frame(C)
fr <- formula(paste("cbind(",paste(colnames(A),collapse=","),")~",paste(colnames(B),collapse="+"),sep=""))
lm(fr,data=Cd)
Cd[1,1] <-NA
lm(fr,data=Cd,na.action=na.exclude)
If you are doing a lot of regression the first way should be faster, since less background magic is performed. Although if you need only coefficients and residuals I suggest using lsfit, which is much faster than lm. The second way is a bit nicer, but on my laptop trying to do summary on the resulting regression throws an error. I will try to see whether this is a bug.
|
How does R handle missing values in lm?
I can think of two ways. One is combine the data use the na.exclude and then separate data again:
A = matrix(1:20, nrow=10, ncol=2)
colnames(A) <- paste("A",1:ncol(A),sep="")
B = matrix(1:10, nrow=10
|
6,024
|
How does R handle missing values in lm?
|
The following example shows how to make predictions and residuals that conform to the original dataframe (using the "na.action=na.exclude" option in lm() to specify that NA's should be placed in the residual and prediction vectors where the original dataframe had missing values. It also shows how to specify whether predictions should include only observations where both explanatory and dependent variables were complete (i.e., strictly in-sample predictions) or observations where the explanatory variables were complete, and hence Xb prediction is possible, (i.e., including out-of-sample prediction for observations that had complete explanatory variables but were missing the dependent variable).
I use cbind to add the predicted and residual variables to the original dataset.
## Set up data with a linear model
N <- 10
NXmissing <- 2
X <- runif(N, 0, 10)
Y <- 6 + 2*X + rnorm(N, 0, 1)
## Put in missing values (missing X, missing Y, missing both)
X[ sample(1:N , NXmissing) ] <- NA
Y[ sample(which(is.na(X)), 1)] <- NA
Y[ sample(which(!is.na(X)), 1)] <- NA
(my.df <- data.frame(X,Y))
## Run the regression with na.action specified to na.exclude
## This puts NA's in the residual and prediction vectors
my.lm <- lm( Y ~ X, na.action=na.exclude, data=my.df)
## Predict outcome for observations with complete both explanatory and
## outcome variables, i.e. observations included in the regression
my.predict.insample <- predict(my.lm)
## Predict outcome for observations with complete explanatory
## variables. The newdata= option specifies the dataset on which
## to apply the coefficients
my.predict.inandout <- predict(my.lm,newdata=my.df)
## Predict residuals
my.residuals <- residuals(my.lm)
## Make sure that it binds correctly
(my.new.df <- cbind(my.df,my.predict.insample,my.predict.inandout,my.residuals))
## or in one fell swoop
(my.new.df <- cbind(my.df,yhat=predict(my.lm),yhato=predict(my.lm,newdata=my.df),uhat=residuals(my.lm)))
|
How does R handle missing values in lm?
|
The following example shows how to make predictions and residuals that conform to the original dataframe (using the "na.action=na.exclude" option in lm() to specify that NA's should be placed in the r
|
How does R handle missing values in lm?
The following example shows how to make predictions and residuals that conform to the original dataframe (using the "na.action=na.exclude" option in lm() to specify that NA's should be placed in the residual and prediction vectors where the original dataframe had missing values. It also shows how to specify whether predictions should include only observations where both explanatory and dependent variables were complete (i.e., strictly in-sample predictions) or observations where the explanatory variables were complete, and hence Xb prediction is possible, (i.e., including out-of-sample prediction for observations that had complete explanatory variables but were missing the dependent variable).
I use cbind to add the predicted and residual variables to the original dataset.
## Set up data with a linear model
N <- 10
NXmissing <- 2
X <- runif(N, 0, 10)
Y <- 6 + 2*X + rnorm(N, 0, 1)
## Put in missing values (missing X, missing Y, missing both)
X[ sample(1:N , NXmissing) ] <- NA
Y[ sample(which(is.na(X)), 1)] <- NA
Y[ sample(which(!is.na(X)), 1)] <- NA
(my.df <- data.frame(X,Y))
## Run the regression with na.action specified to na.exclude
## This puts NA's in the residual and prediction vectors
my.lm <- lm( Y ~ X, na.action=na.exclude, data=my.df)
## Predict outcome for observations with complete both explanatory and
## outcome variables, i.e. observations included in the regression
my.predict.insample <- predict(my.lm)
## Predict outcome for observations with complete explanatory
## variables. The newdata= option specifies the dataset on which
## to apply the coefficients
my.predict.inandout <- predict(my.lm,newdata=my.df)
## Predict residuals
my.residuals <- residuals(my.lm)
## Make sure that it binds correctly
(my.new.df <- cbind(my.df,my.predict.insample,my.predict.inandout,my.residuals))
## or in one fell swoop
(my.new.df <- cbind(my.df,yhat=predict(my.lm),yhato=predict(my.lm,newdata=my.df),uhat=residuals(my.lm)))
|
How does R handle missing values in lm?
The following example shows how to make predictions and residuals that conform to the original dataframe (using the "na.action=na.exclude" option in lm() to specify that NA's should be placed in the r
|
6,025
|
Training loss goes down and up again. What is happening?
|
Your learning rate could be to big after the 25th epoch. This problem is easy to identify. You just need to set up a smaller value for your learning rate. If the problem related to your learning rate than NN should reach a lower error despite that it will go up again after a while. The main point is that the error rate will be lower in some point in time.
If you observed this behaviour you could use two simple solutions. First one is a simplest one. Set up a very small step and train it. The second one is to decrease your learning rate monotonically. Here is a simple formula:
$$
\alpha(t + 1) = \frac{\alpha(0)}{1 + \frac{t}{m}}
$$
Where $a$ is your learning rate, $t$ is your iteration number and $m$ is a coefficient that identifies learning rate decreasing speed. It means that your step will minimise by a factor of two when $t$ is equal to $m$.
|
Training loss goes down and up again. What is happening?
|
Your learning rate could be to big after the 25th epoch. This problem is easy to identify. You just need to set up a smaller value for your learning rate. If the problem related to your learning rate
|
Training loss goes down and up again. What is happening?
Your learning rate could be to big after the 25th epoch. This problem is easy to identify. You just need to set up a smaller value for your learning rate. If the problem related to your learning rate than NN should reach a lower error despite that it will go up again after a while. The main point is that the error rate will be lower in some point in time.
If you observed this behaviour you could use two simple solutions. First one is a simplest one. Set up a very small step and train it. The second one is to decrease your learning rate monotonically. Here is a simple formula:
$$
\alpha(t + 1) = \frac{\alpha(0)}{1 + \frac{t}{m}}
$$
Where $a$ is your learning rate, $t$ is your iteration number and $m$ is a coefficient that identifies learning rate decreasing speed. It means that your step will minimise by a factor of two when $t$ is equal to $m$.
|
Training loss goes down and up again. What is happening?
Your learning rate could be to big after the 25th epoch. This problem is easy to identify. You just need to set up a smaller value for your learning rate. If the problem related to your learning rate
|
6,026
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
This answer follows up on my answer in Bias and variance in leave-one-out vs K-fold cross validation that discusses why LOOCV does not always lead to higher variance. Following a similar approach, I will attempt to highlight a case where LOOCV does lead to higher variance in the presence of outliers and an "unstable model".
Algorithmic stability (learning theory)
The topic of algorithmic stability is a recent one and several classic, infuential results have been proven in the past 20 years. Here are a few papers which are often cited
Heuristics of instability and stabilization in model selection (1996): Leo Breiman
Algorithmic stability and sanity check bounds for LOOCV (1997): Kearns, Ron
Stability and Generalization(2002): Bousquet, Elisseef
Cross-Validation and Mean-Square Stability(2011) Kale, Kumar, Vassilvitskii
Almost everywhere algorithmic stability and generalization error(2012): Kutin, Niyogi
Some notes on the topic: University of Arizona
The best page to gain an understanding is certainly the wikipedia page which provides a excellent summary written by a presumably very knowledgeable user.
Intuitive definition of stability
Intuitively, a stable algorithm is one for which the prediction does not change much when the training data is modified slightly.
Formally, there are half a dozen versions of stability, linked together by technical conditions and hierarchies, see this graphic from here for example:
The objective however is simple, we want to get tight bounds on the generalization error of a specific learning algorithm, when the algorithm satisfies the stability criterion. As one would expect, the more restrictive the stability criterion, the tighter the corresponding bound will be.
Notation
The following notation is from the wikipedia article, which itself copies the Bousquet and Elisseef paper:
The training set $S = \{ z_1 = (x_1,y_1), ..., z_m = (x_m, y_m)\}$ is drawn i.i.d. from an unknown distribution D
The loss function $V$ of a hypothesis $f$ with respect to an example $z$ is defined as $V(f,z)$
We modify the training set by removing the $i$-th element: $S^{|i} = \{ z_1,...,z_{i-1}, z_{i+1},...,z_m\}$
Or by replacing the the $i$-th element: $S^{i} = \{ z_1,...,z_{i-1}, z_i^{'}, z_{i+1},...,z_m\}$
Formal definitions
Perhaps the strongest notion of stability that an interesting learning algorithm might be expected to obey is that of uniform stability:
Uniform stability
An algorithm has uniform stability $\beta$ wth respect to the loss function $V$ if the following holds:
$$\forall S \in Z^m \ \ \forall i \in \{ 1,...,m\}, \ \ \sup | V(f_s,z) - V(f_{S^{|i},z}) |\ \ \leq \beta$$
Considered as a function of $m$, the term $\beta$ can be written as $\beta_m$. We say the algorithm is stable when $\beta_m$ decreases as $\frac{1}{m}$. A slightly weaker form of stability is:
Hypothesis stability
$$\forall i \in \{ 1,...,m\}, \ \ \mathbb{E}[\ | V(f_s,z) - V(f_{S^{|i},z}) |\ ] \ \leq \beta$$
If one point is removed, the difference in the outcome of the learning algorithm is measured by the averaged absolute difference of the losses ($L_1$ norm). Intuitively: small changes in the sample can only cause the algorithm to move to nearby hypotheses.
The advantage of these forms of stability is that they provide bounds for the bias and variance of stable algorithms. In particular, Bousquet proved these bounds for Uniform and Hypothesis stability in 2002. Since then, much work has been done to try to relax the stability conditions and generalize the bounds, for example in 2011, Kale, Kumar, Vassilvitskii argue that mean square stability provides better variance quantitative variance reduction bounds.
Some examples of stable algorithms
The following algorithms have been shown to be stable and have proven generalization bounds:
Regularized least square regression (with appropriate prior)
KNN classifier with 0-1 loss function
SVM with a bounded kernel and large regularization constant
Soft margin SVM
Minimum relative entropy algorithm for classification
A version of bagging regularizers
An experimental simulation
Repeating the experiment from the previous thread (see here), we now introduce a certain ratio of outliers in the data set. In particular:
97% of the data has $[-.5,.5]$ uniform noise
3% of the data with $[-20,20]$ uniform noise
As the $3$ order polynomial model is not regularized, it will be heavily influenced by the presence of a few outliers for small data sets. For larger datasets, or when there are more outliers, their effect is smaller as they tend to cancel out. See below for two models for 60 and 200 data points.
Performing the simulation as previously and plotting the resulting average MSE and variance of the MSE gives results very similar to Experiment 2 of the Bengio & Grandvalet 2004 paper.
Left Hand Side: no outliers. Right Hand Side: 3% outliers.
(see the linked paper for explanation of the last figure)
Explanations
Quoting Yves Grandvalet's answer on the other thread:
Intuitively, [in the situation of unstable algorithms], leave-one-out CV may be blind to instabilities that exist, but may not be triggered by changing a single point in the training data, which makes it highly variable to the realization of the training set.
In practice it is quite difficult to simulate an increase in variance due to LOOCV. It requires a particular combination of instability, some outliers but not too many, and a large number of iterations. Perhaps this is expected since linear regression has been shown to be quite stable. An interesting experiment would be to repeat this for higher dimensional data and a more unstable algorithm (e.g. decision tree)
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
This answer follows up on my answer in Bias and variance in leave-one-out vs K-fold cross validation that discusses why LOOCV does not always lead to higher variance. Following a similar approach, I w
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
This answer follows up on my answer in Bias and variance in leave-one-out vs K-fold cross validation that discusses why LOOCV does not always lead to higher variance. Following a similar approach, I will attempt to highlight a case where LOOCV does lead to higher variance in the presence of outliers and an "unstable model".
Algorithmic stability (learning theory)
The topic of algorithmic stability is a recent one and several classic, infuential results have been proven in the past 20 years. Here are a few papers which are often cited
Heuristics of instability and stabilization in model selection (1996): Leo Breiman
Algorithmic stability and sanity check bounds for LOOCV (1997): Kearns, Ron
Stability and Generalization(2002): Bousquet, Elisseef
Cross-Validation and Mean-Square Stability(2011) Kale, Kumar, Vassilvitskii
Almost everywhere algorithmic stability and generalization error(2012): Kutin, Niyogi
Some notes on the topic: University of Arizona
The best page to gain an understanding is certainly the wikipedia page which provides a excellent summary written by a presumably very knowledgeable user.
Intuitive definition of stability
Intuitively, a stable algorithm is one for which the prediction does not change much when the training data is modified slightly.
Formally, there are half a dozen versions of stability, linked together by technical conditions and hierarchies, see this graphic from here for example:
The objective however is simple, we want to get tight bounds on the generalization error of a specific learning algorithm, when the algorithm satisfies the stability criterion. As one would expect, the more restrictive the stability criterion, the tighter the corresponding bound will be.
Notation
The following notation is from the wikipedia article, which itself copies the Bousquet and Elisseef paper:
The training set $S = \{ z_1 = (x_1,y_1), ..., z_m = (x_m, y_m)\}$ is drawn i.i.d. from an unknown distribution D
The loss function $V$ of a hypothesis $f$ with respect to an example $z$ is defined as $V(f,z)$
We modify the training set by removing the $i$-th element: $S^{|i} = \{ z_1,...,z_{i-1}, z_{i+1},...,z_m\}$
Or by replacing the the $i$-th element: $S^{i} = \{ z_1,...,z_{i-1}, z_i^{'}, z_{i+1},...,z_m\}$
Formal definitions
Perhaps the strongest notion of stability that an interesting learning algorithm might be expected to obey is that of uniform stability:
Uniform stability
An algorithm has uniform stability $\beta$ wth respect to the loss function $V$ if the following holds:
$$\forall S \in Z^m \ \ \forall i \in \{ 1,...,m\}, \ \ \sup | V(f_s,z) - V(f_{S^{|i},z}) |\ \ \leq \beta$$
Considered as a function of $m$, the term $\beta$ can be written as $\beta_m$. We say the algorithm is stable when $\beta_m$ decreases as $\frac{1}{m}$. A slightly weaker form of stability is:
Hypothesis stability
$$\forall i \in \{ 1,...,m\}, \ \ \mathbb{E}[\ | V(f_s,z) - V(f_{S^{|i},z}) |\ ] \ \leq \beta$$
If one point is removed, the difference in the outcome of the learning algorithm is measured by the averaged absolute difference of the losses ($L_1$ norm). Intuitively: small changes in the sample can only cause the algorithm to move to nearby hypotheses.
The advantage of these forms of stability is that they provide bounds for the bias and variance of stable algorithms. In particular, Bousquet proved these bounds for Uniform and Hypothesis stability in 2002. Since then, much work has been done to try to relax the stability conditions and generalize the bounds, for example in 2011, Kale, Kumar, Vassilvitskii argue that mean square stability provides better variance quantitative variance reduction bounds.
Some examples of stable algorithms
The following algorithms have been shown to be stable and have proven generalization bounds:
Regularized least square regression (with appropriate prior)
KNN classifier with 0-1 loss function
SVM with a bounded kernel and large regularization constant
Soft margin SVM
Minimum relative entropy algorithm for classification
A version of bagging regularizers
An experimental simulation
Repeating the experiment from the previous thread (see here), we now introduce a certain ratio of outliers in the data set. In particular:
97% of the data has $[-.5,.5]$ uniform noise
3% of the data with $[-20,20]$ uniform noise
As the $3$ order polynomial model is not regularized, it will be heavily influenced by the presence of a few outliers for small data sets. For larger datasets, or when there are more outliers, their effect is smaller as they tend to cancel out. See below for two models for 60 and 200 data points.
Performing the simulation as previously and plotting the resulting average MSE and variance of the MSE gives results very similar to Experiment 2 of the Bengio & Grandvalet 2004 paper.
Left Hand Side: no outliers. Right Hand Side: 3% outliers.
(see the linked paper for explanation of the last figure)
Explanations
Quoting Yves Grandvalet's answer on the other thread:
Intuitively, [in the situation of unstable algorithms], leave-one-out CV may be blind to instabilities that exist, but may not be triggered by changing a single point in the training data, which makes it highly variable to the realization of the training set.
In practice it is quite difficult to simulate an increase in variance due to LOOCV. It requires a particular combination of instability, some outliers but not too many, and a large number of iterations. Perhaps this is expected since linear regression has been shown to be quite stable. An interesting experiment would be to repeat this for higher dimensional data and a more unstable algorithm (e.g. decision tree)
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
This answer follows up on my answer in Bias and variance in leave-one-out vs K-fold cross validation that discusses why LOOCV does not always lead to higher variance. Following a similar approach, I w
|
6,027
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
I will give my answer in context of the paragraph you cite:
With K=N, the cross-validation estimator is approximately unbiased for
the true (expected) prediction error, but can have high variance
because the N "training sets" are so similar to one another.
The CV estimator of the true (expected) prediction error is based on a training set example, so here, the expectation is over training set samples, when I understand that correctly.
So, what this paragraph regarding "high variance" then says is that there is a "high" difference between expected error and the error estimated by CV (which is here, the average over folds).
This makes sense because the model is fit to a particular training set and because all training folds are so similar within leave-one-out. However, while the training folds are very similar within a CV round, the estimate probably differs by a lot if we swap training samples for CV. In k-fold CV, since we "diversify" the training folds, we have some averaging affect, and across k-folds, the estimates then vary less.
Or in other words, the leave-one-out CV estimator is basically almost like a holdout method were you don't rotate folds and base your error estimate on one validation set. Again, over training examples, there will be a high variance compared to estimates from k-fold, where you average over folds by already training somewhat diverse models within k-fold round (in other words, if you swap training sets, the estimates of the error via k-fold probably won't vary that much).
EDIT:
When I read some answers here on cross-validated and the internet in general, I think there seems some confusion to which estimator we are referring. I think some people refer to a model having high variance (with is ML talk for the loss having a dominating variance component) vs high variance of the k-fold CV estimator. And, another set of answers refer to variance as the sample variance regarding the folds when someone says "k-fold has high variance". So, I suggest to be specific, because the answers are different in either case.
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
I will give my answer in context of the paragraph you cite:
With K=N, the cross-validation estimator is approximately unbiased for
the true (expected) prediction error, but can have high variance
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
I will give my answer in context of the paragraph you cite:
With K=N, the cross-validation estimator is approximately unbiased for
the true (expected) prediction error, but can have high variance
because the N "training sets" are so similar to one another.
The CV estimator of the true (expected) prediction error is based on a training set example, so here, the expectation is over training set samples, when I understand that correctly.
So, what this paragraph regarding "high variance" then says is that there is a "high" difference between expected error and the error estimated by CV (which is here, the average over folds).
This makes sense because the model is fit to a particular training set and because all training folds are so similar within leave-one-out. However, while the training folds are very similar within a CV round, the estimate probably differs by a lot if we swap training samples for CV. In k-fold CV, since we "diversify" the training folds, we have some averaging affect, and across k-folds, the estimates then vary less.
Or in other words, the leave-one-out CV estimator is basically almost like a holdout method were you don't rotate folds and base your error estimate on one validation set. Again, over training examples, there will be a high variance compared to estimates from k-fold, where you average over folds by already training somewhat diverse models within k-fold round (in other words, if you swap training sets, the estimates of the error via k-fold probably won't vary that much).
EDIT:
When I read some answers here on cross-validated and the internet in general, I think there seems some confusion to which estimator we are referring. I think some people refer to a model having high variance (with is ML talk for the loss having a dominating variance component) vs high variance of the k-fold CV estimator. And, another set of answers refer to variance as the sample variance regarding the folds when someone says "k-fold has high variance". So, I suggest to be specific, because the answers are different in either case.
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
I will give my answer in context of the paragraph you cite:
With K=N, the cross-validation estimator is approximately unbiased for
the true (expected) prediction error, but can have high variance
|
6,028
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
We've been through this before -- you're getting too mathematical about a dead horse. See Ron Kohavi's (Stanford-Univ) classic paper on CV and the bias-variance dilemma here. When you're done reading this, you won't want to perform LOOCV, and will likely be attracted to 10-fold CV and/or bootstrap-bias CV.
You also have to think about large datasets, for which LOOCV is way too computationally expensive. At present, LOOCV is not really an option in most groups' workflows/pipelines.
What precisely is this "stability" condition? Does it apply to
models/algorithms, datasets, or both to some extent?
In the universe of all cost functions and in the universe of all feature sets, I would not assume there is an overall "stability" index, because it would not be inadmissible, and would be too prone to breaking down under an infinitely large set of conditions. Fundamentally, $k=n$ is appropriate when the d.f. and/or # parameters is so large that more training data are needed. Bias will also be greater for $k=n$, since more data are used, and variance would be artificially zero, since the training datasets are too similar to one another. You would also be learning more noise in the data when $k=n$.
LREG as a classifier would work when the data are linearly separable, but on average its bias would be too high, since many datasets are not linearly separable.
Is there an intuitive way to think about this stability?
Not in my view -- since there is no general rule on stability.
What are other examples of stable and unstable models/algorithms or
datasets?
This is open-ended and too broad, since an infinitely large number of responses can be contrived, which would not be helpful.
Is it relatively safe to assume that most models/algorithms or
datasets are "stable" and therefore that $K$ should generally be
chosen as high as is computationally feasible?
No. No. Relying only on $k$ assumes that you believe the data. An example is Random Forests, for which there really is no $k$. While roughly 37% of the data will be used for testing (on average, 37% of objects are not selected when sampling with replacement), there are e.g. 5,000 different datasets (bootstraps) each of which are split into training/testing differently. Your example pulled from papers assumed that each dataset used was a true realization of the data -- which is an erroneous assumption.
Given bootstrapping, the rule of stability surrounding $k$ is admissible, since the data sample used for a straightforward CV approach involving $k$ is not a true realization of the universe of all data from which the sample was obtained.
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
We've been through this before -- you're getting too mathematical about a dead horse. See Ron Kohavi's (Stanford-Univ) classic paper on CV and the bias-variance dilemma here. When you're done readin
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
We've been through this before -- you're getting too mathematical about a dead horse. See Ron Kohavi's (Stanford-Univ) classic paper on CV and the bias-variance dilemma here. When you're done reading this, you won't want to perform LOOCV, and will likely be attracted to 10-fold CV and/or bootstrap-bias CV.
You also have to think about large datasets, for which LOOCV is way too computationally expensive. At present, LOOCV is not really an option in most groups' workflows/pipelines.
What precisely is this "stability" condition? Does it apply to
models/algorithms, datasets, or both to some extent?
In the universe of all cost functions and in the universe of all feature sets, I would not assume there is an overall "stability" index, because it would not be inadmissible, and would be too prone to breaking down under an infinitely large set of conditions. Fundamentally, $k=n$ is appropriate when the d.f. and/or # parameters is so large that more training data are needed. Bias will also be greater for $k=n$, since more data are used, and variance would be artificially zero, since the training datasets are too similar to one another. You would also be learning more noise in the data when $k=n$.
LREG as a classifier would work when the data are linearly separable, but on average its bias would be too high, since many datasets are not linearly separable.
Is there an intuitive way to think about this stability?
Not in my view -- since there is no general rule on stability.
What are other examples of stable and unstable models/algorithms or
datasets?
This is open-ended and too broad, since an infinitely large number of responses can be contrived, which would not be helpful.
Is it relatively safe to assume that most models/algorithms or
datasets are "stable" and therefore that $K$ should generally be
chosen as high as is computationally feasible?
No. No. Relying only on $k$ assumes that you believe the data. An example is Random Forests, for which there really is no $k$. While roughly 37% of the data will be used for testing (on average, 37% of objects are not selected when sampling with replacement), there are e.g. 5,000 different datasets (bootstraps) each of which are split into training/testing differently. Your example pulled from papers assumed that each dataset used was a true realization of the data -- which is an erroneous assumption.
Given bootstrapping, the rule of stability surrounding $k$ is admissible, since the data sample used for a straightforward CV approach involving $k$ is not a true realization of the universe of all data from which the sample was obtained.
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
We've been through this before -- you're getting too mathematical about a dead horse. See Ron Kohavi's (Stanford-Univ) classic paper on CV and the bias-variance dilemma here. When you're done readin
|
6,029
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
This answer focuses not on stability, but on a different related issue that I have not seen addressed in the answers/comments above.
There is "conventional wisdom" about LOOCV having higher variance, e.g. quoted from ESL in the question above. This conventional wisdom makes sense to me only if CV with different fold sizes were estimating the same thing. But if the full dataset size $n$ is fixed, then 5-fold CV is estimating MSE for models trained on $n\times4/5$ cases, while 10-fold CV is estimating MSE for models trained on $n\times9/10$ cases, and so on. These are different targets of estimation, so there's no reason to expect a simple relationship between their estimates' variances.
Instead, what would happen if we think about using CV to estimate MSE for a fixed training set size?
I modified @JakeWestfall's R code (linked in the question) to carry out 2-fold, 5-fold, 10-fold, and LOOCV with a fixed training set size. I chose to use $n_{train}=36$ to allow for integer sample sizes, so that the full dataset sizes were:
$n=72=36\times2/(2-1)$ for 2-fold
$n=45=36\times5/(5-1)$ for 5-fold
$n=40=36\times10/(10-1)$ for 10-fold
$n=37=36\times37/(37-1)$ for LOOCV
In other words, for each rep of the simulation:
Generate a new dataset of size $n=72$
Carry out 2-fold CV on this full dataset
Take just the first 45 cases of the full dataset, and carry out 5-fold CV (so that we have five instances of [training on 36 cases and testing on 9 cases] from among the same 45 cases each time)
Similarly for 10-fold on the first 40 cases of the full dataset
Similarly for LOOCV on the first 37 cases of the full dataset
Results from 10,000 reps:
## k = 2 k = 5 k = 10 k = n
## mean 1.122 1.123 1.123 1.123
## variance 0.052 0.068 0.073 0.077
Unsurprisingly, the means are all the same. These are all unbiased estimators of the MSE for models with $n_{train}=36$.
But now that $n_{train}$ is fixed, the variance of $\hat{MSE}$ increases with k. This, to me, matches the intuition from ESL and others. For each rep of the simulation:
2-fold CV is almost the average of 2 independent estimates of $\hat{MSE}$. (Well, not quite. It's the average of $\hat{MSE}$ over two independent $\hat f(x)$, but there is dependence between training and test sets.)
Meanwhile, LOOCV is almost just a single estimate of $\hat{MSE}$. (It's the average of $\hat{MSE}$ over $n$ estimates of $\hat f(x)$, but these $n$ fitted models are so correlated as to be nearly identical, unless there are major outliers.)
By this intuition, LOOCV should have higher variance than 2-fold CV; and 5- or 10-fold should be somewhere in between... if they are all trying to estimate the same thing. And indeed, the simulation supports this intuition.
Back to the OP's question, and as a contrast to @XavierBourretSicotte's answer: when $n_{train}$ is fixed, "LOOCV has higher variance" does not require instability.
Of course, this does not tell us what value of k to choose in the standard situation where $n$ is fixed and $n_{train}$ varies with k! But I hope it helps to illustrate (1) where the "LOOCV has higher variance" intuition came from, and (2) why that intuition breaks down in the standard situation.
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
|
This answer focuses not on stability, but on a different related issue that I have not seen addressed in the answers/comments above.
There is "conventional wisdom" about LOOCV having higher variance,
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
This answer focuses not on stability, but on a different related issue that I have not seen addressed in the answers/comments above.
There is "conventional wisdom" about LOOCV having higher variance, e.g. quoted from ESL in the question above. This conventional wisdom makes sense to me only if CV with different fold sizes were estimating the same thing. But if the full dataset size $n$ is fixed, then 5-fold CV is estimating MSE for models trained on $n\times4/5$ cases, while 10-fold CV is estimating MSE for models trained on $n\times9/10$ cases, and so on. These are different targets of estimation, so there's no reason to expect a simple relationship between their estimates' variances.
Instead, what would happen if we think about using CV to estimate MSE for a fixed training set size?
I modified @JakeWestfall's R code (linked in the question) to carry out 2-fold, 5-fold, 10-fold, and LOOCV with a fixed training set size. I chose to use $n_{train}=36$ to allow for integer sample sizes, so that the full dataset sizes were:
$n=72=36\times2/(2-1)$ for 2-fold
$n=45=36\times5/(5-1)$ for 5-fold
$n=40=36\times10/(10-1)$ for 10-fold
$n=37=36\times37/(37-1)$ for LOOCV
In other words, for each rep of the simulation:
Generate a new dataset of size $n=72$
Carry out 2-fold CV on this full dataset
Take just the first 45 cases of the full dataset, and carry out 5-fold CV (so that we have five instances of [training on 36 cases and testing on 9 cases] from among the same 45 cases each time)
Similarly for 10-fold on the first 40 cases of the full dataset
Similarly for LOOCV on the first 37 cases of the full dataset
Results from 10,000 reps:
## k = 2 k = 5 k = 10 k = n
## mean 1.122 1.123 1.123 1.123
## variance 0.052 0.068 0.073 0.077
Unsurprisingly, the means are all the same. These are all unbiased estimators of the MSE for models with $n_{train}=36$.
But now that $n_{train}$ is fixed, the variance of $\hat{MSE}$ increases with k. This, to me, matches the intuition from ESL and others. For each rep of the simulation:
2-fold CV is almost the average of 2 independent estimates of $\hat{MSE}$. (Well, not quite. It's the average of $\hat{MSE}$ over two independent $\hat f(x)$, but there is dependence between training and test sets.)
Meanwhile, LOOCV is almost just a single estimate of $\hat{MSE}$. (It's the average of $\hat{MSE}$ over $n$ estimates of $\hat f(x)$, but these $n$ fitted models are so correlated as to be nearly identical, unless there are major outliers.)
By this intuition, LOOCV should have higher variance than 2-fold CV; and 5- or 10-fold should be somewhere in between... if they are all trying to estimate the same thing. And indeed, the simulation supports this intuition.
Back to the OP's question, and as a contrast to @XavierBourretSicotte's answer: when $n_{train}$ is fixed, "LOOCV has higher variance" does not require instability.
Of course, this does not tell us what value of k to choose in the standard situation where $n$ is fixed and $n_{train}$ varies with k! But I hope it helps to illustrate (1) where the "LOOCV has higher variance" intuition came from, and (2) why that intuition breaks down in the standard situation.
|
Variance of $K$-fold cross-validation estimates as $f(K)$: what is the role of "stability"?
This answer focuses not on stability, but on a different related issue that I have not seen addressed in the answers/comments above.
There is "conventional wisdom" about LOOCV having higher variance,
|
6,030
|
When teaching statistics, use "normal" or "Gaussian"?
|
Even though I tend to say 'normal' more often (since that's what I was taught when first learning), I think "Gaussian" is a better choice, as long as students/readers are quite familiar with both terms:
The normal isn't particularly typical, so the name is itself misleading. It certainly plays an important role (not least because of the CLT), but observed data is much less often particularly near Gaussian than is sometimes suggested.
The word (and associated words like "normalize") has several meanings that can be relevant in statistics (consider "orthonormal basis" for example). If someone says "I normalized my sample" I can't tell for sure if they transformed to normality, computed z-scores, scaled the vector to unit length, to length $\sqrt{n}$, or a number of other possibilities. If we tended to call the distribution "Gaussian" at least the first option is eliminated and something more descriptive replaces it.
Gauss at least has a reasonable degree of claim to the distribution.
|
When teaching statistics, use "normal" or "Gaussian"?
|
Even though I tend to say 'normal' more often (since that's what I was taught when first learning), I think "Gaussian" is a better choice, as long as students/readers are quite familiar with both term
|
When teaching statistics, use "normal" or "Gaussian"?
Even though I tend to say 'normal' more often (since that's what I was taught when first learning), I think "Gaussian" is a better choice, as long as students/readers are quite familiar with both terms:
The normal isn't particularly typical, so the name is itself misleading. It certainly plays an important role (not least because of the CLT), but observed data is much less often particularly near Gaussian than is sometimes suggested.
The word (and associated words like "normalize") has several meanings that can be relevant in statistics (consider "orthonormal basis" for example). If someone says "I normalized my sample" I can't tell for sure if they transformed to normality, computed z-scores, scaled the vector to unit length, to length $\sqrt{n}$, or a number of other possibilities. If we tended to call the distribution "Gaussian" at least the first option is eliminated and something more descriptive replaces it.
Gauss at least has a reasonable degree of claim to the distribution.
|
When teaching statistics, use "normal" or "Gaussian"?
Even though I tend to say 'normal' more often (since that's what I was taught when first learning), I think "Gaussian" is a better choice, as long as students/readers are quite familiar with both term
|
6,031
|
When teaching statistics, use "normal" or "Gaussian"?
|
I would use Gaussian.
One problem that faces people learning statistics is that we use everyday English words to mean different things (power, significant, distribution etc). To the extent that we can minimize this, we should. "Normal" already has a bunch of meanings.
|
When teaching statistics, use "normal" or "Gaussian"?
|
I would use Gaussian.
One problem that faces people learning statistics is that we use everyday English words to mean different things (power, significant, distribution etc). To the extent that we can
|
When teaching statistics, use "normal" or "Gaussian"?
I would use Gaussian.
One problem that faces people learning statistics is that we use everyday English words to mean different things (power, significant, distribution etc). To the extent that we can minimize this, we should. "Normal" already has a bunch of meanings.
|
When teaching statistics, use "normal" or "Gaussian"?
I would use Gaussian.
One problem that faces people learning statistics is that we use everyday English words to mean different things (power, significant, distribution etc). To the extent that we can
|
6,032
|
When teaching statistics, use "normal" or "Gaussian"?
|
One argument in favor of normal is the entrenched $N(\mu, \sigma^2)$ notation for the distribution, in which $N$ stands for "normal". I haven't seen anyone propose changing this to $G(\mu, \sigma^2)$.
|
When teaching statistics, use "normal" or "Gaussian"?
|
One argument in favor of normal is the entrenched $N(\mu, \sigma^2)$ notation for the distribution, in which $N$ stands for "normal". I haven't seen anyone propose changing this to $G(\mu, \sigma^2)$
|
When teaching statistics, use "normal" or "Gaussian"?
One argument in favor of normal is the entrenched $N(\mu, \sigma^2)$ notation for the distribution, in which $N$ stands for "normal". I haven't seen anyone propose changing this to $G(\mu, \sigma^2)$.
|
When teaching statistics, use "normal" or "Gaussian"?
One argument in favor of normal is the entrenched $N(\mu, \sigma^2)$ notation for the distribution, in which $N$ stands for "normal". I haven't seen anyone propose changing this to $G(\mu, \sigma^2)$
|
6,033
|
When teaching statistics, use "normal" or "Gaussian"?
|
In German it is often called Gaußsche Normalverteilung so it is nearly impossible to conflict easily.
Would it be appropriate for you to combine gaussian and normal?
|
When teaching statistics, use "normal" or "Gaussian"?
|
In German it is often called Gaußsche Normalverteilung so it is nearly impossible to conflict easily.
Would it be appropriate for you to combine gaussian and normal?
|
When teaching statistics, use "normal" or "Gaussian"?
In German it is often called Gaußsche Normalverteilung so it is nearly impossible to conflict easily.
Would it be appropriate for you to combine gaussian and normal?
|
When teaching statistics, use "normal" or "Gaussian"?
In German it is often called Gaußsche Normalverteilung so it is nearly impossible to conflict easily.
Would it be appropriate for you to combine gaussian and normal?
|
6,034
|
When teaching statistics, use "normal" or "Gaussian"?
|
According to the Wolfram encyclopedia:
While statisticians and mathematicians uniformly use the term "normal distribution" for this
distribution, physicists sometimes call it a Gaussian distribution and, because of its
curved flaring shape, social scientists refer to it as the "bell curve."
I agree that "normal" is easier to confuse - yet I suspect statistics books usually use "normal".
|
When teaching statistics, use "normal" or "Gaussian"?
|
According to the Wolfram encyclopedia:
While statisticians and mathematicians uniformly use the term "normal distribution" for this
distribution, physicists sometimes call it a Gaussian distrib
|
When teaching statistics, use "normal" or "Gaussian"?
According to the Wolfram encyclopedia:
While statisticians and mathematicians uniformly use the term "normal distribution" for this
distribution, physicists sometimes call it a Gaussian distribution and, because of its
curved flaring shape, social scientists refer to it as the "bell curve."
I agree that "normal" is easier to confuse - yet I suspect statistics books usually use "normal".
|
When teaching statistics, use "normal" or "Gaussian"?
According to the Wolfram encyclopedia:
While statisticians and mathematicians uniformly use the term "normal distribution" for this
distribution, physicists sometimes call it a Gaussian distrib
|
6,035
|
When teaching statistics, use "normal" or "Gaussian"?
|
I'd like to point out that S. Stigler uses Normal / Gauss / Laplace-Gauss distribution to prove 'Stigler's law of eponymy' published in Statistics on the Table (some pages are available on books.google).
Particularly interesting and relevant to this questions is that on pg 287-288 there are tables of the historical usage of 'Normal' vs 'Gauss' vs 'Laplace' and it seems that over the years the usage shifted from 2:15 in favor of normal in 1816-1884 to 8:14 (1888-1917) to 5:17 (1919-1939) to 9:10 (1947-1976).
So according to this the usage of 'normal' vs 'Gauss' is getting more equal. Or if you believe that the trend will continue then 'Gauss' will beat 'normal' in 50-100 years.
|
When teaching statistics, use "normal" or "Gaussian"?
|
I'd like to point out that S. Stigler uses Normal / Gauss / Laplace-Gauss distribution to prove 'Stigler's law of eponymy' published in Statistics on the Table (some pages are available on books.googl
|
When teaching statistics, use "normal" or "Gaussian"?
I'd like to point out that S. Stigler uses Normal / Gauss / Laplace-Gauss distribution to prove 'Stigler's law of eponymy' published in Statistics on the Table (some pages are available on books.google).
Particularly interesting and relevant to this questions is that on pg 287-288 there are tables of the historical usage of 'Normal' vs 'Gauss' vs 'Laplace' and it seems that over the years the usage shifted from 2:15 in favor of normal in 1816-1884 to 8:14 (1888-1917) to 5:17 (1919-1939) to 9:10 (1947-1976).
So according to this the usage of 'normal' vs 'Gauss' is getting more equal. Or if you believe that the trend will continue then 'Gauss' will beat 'normal' in 50-100 years.
|
When teaching statistics, use "normal" or "Gaussian"?
I'd like to point out that S. Stigler uses Normal / Gauss / Laplace-Gauss distribution to prove 'Stigler's law of eponymy' published in Statistics on the Table (some pages are available on books.googl
|
6,036
|
When teaching statistics, use "normal" or "Gaussian"?
|
An answer I haven't seen yet among all the good answers:
I mostly use "normal" for reasons of previous familiarity, but I like to capitalize it to emphasize its technical meaning: "... if the data are Normally distributed ..." (I don't know whether I copied this practice from somewhere else or (re-)invented it myself)
|
When teaching statistics, use "normal" or "Gaussian"?
|
An answer I haven't seen yet among all the good answers:
I mostly use "normal" for reasons of previous familiarity, but I like to capitalize it to emphasize its technical meaning: "... if the data are
|
When teaching statistics, use "normal" or "Gaussian"?
An answer I haven't seen yet among all the good answers:
I mostly use "normal" for reasons of previous familiarity, but I like to capitalize it to emphasize its technical meaning: "... if the data are Normally distributed ..." (I don't know whether I copied this practice from somewhere else or (re-)invented it myself)
|
When teaching statistics, use "normal" or "Gaussian"?
An answer I haven't seen yet among all the good answers:
I mostly use "normal" for reasons of previous familiarity, but I like to capitalize it to emphasize its technical meaning: "... if the data are
|
6,037
|
When teaching statistics, use "normal" or "Gaussian"?
|
Which to use depends on the level of statistics being taught. Unfortunately, my teaching experience indicates that the majority of undergraduate students never fully grasp the concept of a probability distribution. However, they all must somehow come to grips with the CLT and ways to think about uncertainty. For an undergraduate class, Normal is preferable because it doesn't add the anxiety of a new unfamiliar word. For graduate students Gaussian is preferred because of all the above mentioned confusion over normalization and the historical context that it provides. I teach a an undergraduate research class requiring two prerequisite statistics classes and all the undergraduate books that I have seen used over the last 30 years have used Normal.
|
When teaching statistics, use "normal" or "Gaussian"?
|
Which to use depends on the level of statistics being taught. Unfortunately, my teaching experience indicates that the majority of undergraduate students never fully grasp the concept of a probability
|
When teaching statistics, use "normal" or "Gaussian"?
Which to use depends on the level of statistics being taught. Unfortunately, my teaching experience indicates that the majority of undergraduate students never fully grasp the concept of a probability distribution. However, they all must somehow come to grips with the CLT and ways to think about uncertainty. For an undergraduate class, Normal is preferable because it doesn't add the anxiety of a new unfamiliar word. For graduate students Gaussian is preferred because of all the above mentioned confusion over normalization and the historical context that it provides. I teach a an undergraduate research class requiring two prerequisite statistics classes and all the undergraduate books that I have seen used over the last 30 years have used Normal.
|
When teaching statistics, use "normal" or "Gaussian"?
Which to use depends on the level of statistics being taught. Unfortunately, my teaching experience indicates that the majority of undergraduate students never fully grasp the concept of a probability
|
6,038
|
When teaching statistics, use "normal" or "Gaussian"?
|
The name normal came from some of the observations that errors behave normally. You will find more details here. If that is the reason to call this distribution a normal distribution, it may create new confusion as normal distribution for counts of accidents is poisson. I believe we should move forward and start calling it a Gaussian instead.
|
When teaching statistics, use "normal" or "Gaussian"?
|
The name normal came from some of the observations that errors behave normally. You will find more details here. If that is the reason to call this distribution a normal distribution, it may create ne
|
When teaching statistics, use "normal" or "Gaussian"?
The name normal came from some of the observations that errors behave normally. You will find more details here. If that is the reason to call this distribution a normal distribution, it may create new confusion as normal distribution for counts of accidents is poisson. I believe we should move forward and start calling it a Gaussian instead.
|
When teaching statistics, use "normal" or "Gaussian"?
The name normal came from some of the observations that errors behave normally. You will find more details here. If that is the reason to call this distribution a normal distribution, it may create ne
|
6,039
|
What is the minimum recommended number of groups for a random effects factor?
|
Short answer: Yes, you can use ID as random effect with 6 levels.
Slightly longer answer: The @BenBolker's GLMM FAQ says (among other things) the following under the headline "Should I treat factor xxx as fixed or random?":
One point of particular relevance to 'modern' mixed model estimation
(rather than 'classical' method-of-moments estimation) is that, for
practical purposes, there must be a reasonable number of
random-effects levels (e.g. blocks) — more than 5 or 6 at a minimum.
So you are at the lower bound, but on the right side of it.
|
What is the minimum recommended number of groups for a random effects factor?
|
Short answer: Yes, you can use ID as random effect with 6 levels.
Slightly longer answer: The @BenBolker's GLMM FAQ says (among other things) the following under the headline "Should I treat factor xx
|
What is the minimum recommended number of groups for a random effects factor?
Short answer: Yes, you can use ID as random effect with 6 levels.
Slightly longer answer: The @BenBolker's GLMM FAQ says (among other things) the following under the headline "Should I treat factor xxx as fixed or random?":
One point of particular relevance to 'modern' mixed model estimation
(rather than 'classical' method-of-moments estimation) is that, for
practical purposes, there must be a reasonable number of
random-effects levels (e.g. blocks) — more than 5 or 6 at a minimum.
So you are at the lower bound, but on the right side of it.
|
What is the minimum recommended number of groups for a random effects factor?
Short answer: Yes, you can use ID as random effect with 6 levels.
Slightly longer answer: The @BenBolker's GLMM FAQ says (among other things) the following under the headline "Should I treat factor xx
|
6,040
|
What is the minimum recommended number of groups for a random effects factor?
|
In an attempt to figure out the minimum number of groups for a multilevel model I looked at the book Data Analysis Using Regression and Mulitilevel/Hierarchical models by Gelman and Hill (2007).
They appear to address this topic in Chapter 11, Section 5 (page 247) where they write that when there are < 5 groups then multilevel models typically add little over classical models. However, they appear to write that there is little risk to applying a multilevel model.
The same authors appear to return to this topic in Chapter 12, Section 9 (pages 275-276). There they write that advice on the minimum number of groups for a multilevel model is misguided. There they again say that multilevel models often add little over classical models when number of groups is small. However, they also write that multilevel models should do no worse than no-pooling regression (where no-pooling appears to mean that group indicators are used in classical regression).
On pages 275-276 the authors have a specific subsection for the case of one or two groups (e.g., male versus female). Here they write that they typically express the model in classical form. However, they state that multilevel modeling can be useful even with only one or two groups. They write that with one or two groups multilevel modeling reduces to classical regression.
My impression from this is that classical regression is one end of a continuum of models, i.e., a special case of a multilevel model.
Based on the above, my impression is that classical regression and multilevel modeling will return almost identical estimates when there are only two groups and that using multilevel models with only one, two, three, four, five or six groups is okay.
I will attempt to modify this answer in the future with R code and a small data set comparing estimates obtained with both approaches when using two groups.
|
What is the minimum recommended number of groups for a random effects factor?
|
In an attempt to figure out the minimum number of groups for a multilevel model I looked at the book Data Analysis Using Regression and Mulitilevel/Hierarchical models by Gelman and Hill (2007).
They
|
What is the minimum recommended number of groups for a random effects factor?
In an attempt to figure out the minimum number of groups for a multilevel model I looked at the book Data Analysis Using Regression and Mulitilevel/Hierarchical models by Gelman and Hill (2007).
They appear to address this topic in Chapter 11, Section 5 (page 247) where they write that when there are < 5 groups then multilevel models typically add little over classical models. However, they appear to write that there is little risk to applying a multilevel model.
The same authors appear to return to this topic in Chapter 12, Section 9 (pages 275-276). There they write that advice on the minimum number of groups for a multilevel model is misguided. There they again say that multilevel models often add little over classical models when number of groups is small. However, they also write that multilevel models should do no worse than no-pooling regression (where no-pooling appears to mean that group indicators are used in classical regression).
On pages 275-276 the authors have a specific subsection for the case of one or two groups (e.g., male versus female). Here they write that they typically express the model in classical form. However, they state that multilevel modeling can be useful even with only one or two groups. They write that with one or two groups multilevel modeling reduces to classical regression.
My impression from this is that classical regression is one end of a continuum of models, i.e., a special case of a multilevel model.
Based on the above, my impression is that classical regression and multilevel modeling will return almost identical estimates when there are only two groups and that using multilevel models with only one, two, three, four, five or six groups is okay.
I will attempt to modify this answer in the future with R code and a small data set comparing estimates obtained with both approaches when using two groups.
|
What is the minimum recommended number of groups for a random effects factor?
In an attempt to figure out the minimum number of groups for a multilevel model I looked at the book Data Analysis Using Regression and Mulitilevel/Hierarchical models by Gelman and Hill (2007).
They
|
6,041
|
What is the minimum recommended number of groups for a random effects factor?
|
For what it's worth, I did a bit of a simulation study to look at the stability of the variance estimate for a relatively simple LMM (using the sleepstudy dataset available through lme4). The first way generates all possible subject combinations for ngroups number of subjects, and refits the model for each possible combination. The second takes several random subsets of subjects.
library(lme4)
library(ggplot2)
library(tidyr)
m0 <- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy,
control = lmerControl(optimizer = "nloptwrap"))
# set the number of factor levels
ngroups <- 3:18
# generate all possible combinations
combos <- lapply(X = ngroups,
FUN = function(x) combn(unique(sleepstudy$Subject), x))
# allocate output (sorry, this code is entirely un-optimized)
out <- list(matrix(NA, ncol(combos[[1]]), 1), matrix(NA, ncol(combos[[2]]), 1),
matrix(NA, ncol(combos[[3]]), 1), matrix(NA, ncol(combos[[4]]), 1),
matrix(NA, ncol(combos[[5]]), 1), matrix(NA, ncol(combos[[6]]), 1),
matrix(NA, ncol(combos[[7]]), 1), matrix(NA, ncol(combos[[8]]), 1),
matrix(NA, ncol(combos[[9]]), 1), matrix(NA, ncol(combos[[10]]), 1),
matrix(NA, ncol(combos[[11]]), 1), matrix(NA, ncol(combos[[12]]), 1),
matrix(NA, ncol(combos[[13]]), 1), matrix(NA, ncol(combos[[14]]), 1),
matrix(NA, ncol(combos[[15]]), 1), matrix(NA, ncol(combos[[16]]), 1))
# took ~ 2.5 hrs on my laptop, commented out for safety
#system.time(for(ii in 1:length(combos)) {
# for(jj in 1:ncol(combos[[ii]])) {
# sls <- sleepstudy[sleepstudy$Subject %in% combos[[ii]][,jj],]
# out[[ii]][jj] <- attr(VarCorr(update(m0, data = sls))$Subject, 'stddev')
# }
# })
# pad with zeros, not all were equal
# from http://stackoverflow.com/questions/11148429/r-convert-asymmetric-list-to-matrix-number-of-elements-in-each-sub-list-diffe
max.len <- max(sapply(out, length))
corrected.list <- lapply(out, function(x) {c(x, rep(NA, max.len - length(x)))})
mat <- do.call(rbind, corrected.list)
mat <- data.frame(t(mat))
names(mat) <- paste0('s',3:18)
mat <- gather(mat, run, value)
ggplot(mat, aes(x = value, fill = run)) +
geom_histogram(bins = 60) +
geom_vline(xintercept = 37.12, linetype = 'longdash',
aes(colour = 'original')) +
facet_wrap(~run, scales = 'free_y') +
scale_x_continuous(breaks = seq(0, 100, by = 20)) +
theme_bw() +
guides(fill = FALSE)
The dotted black line is the original point estimate of the variance, and the facets represent different numbers of subjects (s3 being groups of three subjects, s4 being four, etc.).
And the alternative way:
ngroups <- 3:18
reps <- 500
out2<- matrix(NA, length(ngroups), reps)
for (ii in 1:length(ngroups)) {
for(j in 1:reps) {
sls <- sleepstudy[sleepstudy$Subject %in% sample(unique(sleepstudy$Subject), ngroups[i], replace = FALSE),]
out2[i,j] <- attr(VarCorr(update(m0, data = sls))$Subject, 'stddev')
}
}
out2 <- data.frame(t(out2))
names(out2) <- paste0('s',3:18)
out2 <- gather(out2, run, value)
ggplot(out2, aes(x = value, fill = run)) +
geom_histogram(bins = 60) +
geom_vline(xintercept = 37.12, linetype = 'longdash',
aes(colour = 'original')) +
facet_wrap(~run, scales = 'free_y') +
scale_x_continuous(breaks = seq(0, 100, by = 20)) +
theme_bw() +
guides(fill = FALSE)
It appears (for this example, anyway) that the variance doesn't really stabilize until there are at least 14 subjects, if not later.
|
What is the minimum recommended number of groups for a random effects factor?
|
For what it's worth, I did a bit of a simulation study to look at the stability of the variance estimate for a relatively simple LMM (using the sleepstudy dataset available through lme4). The first wa
|
What is the minimum recommended number of groups for a random effects factor?
For what it's worth, I did a bit of a simulation study to look at the stability of the variance estimate for a relatively simple LMM (using the sleepstudy dataset available through lme4). The first way generates all possible subject combinations for ngroups number of subjects, and refits the model for each possible combination. The second takes several random subsets of subjects.
library(lme4)
library(ggplot2)
library(tidyr)
m0 <- lmer(Reaction ~ Days + (1|Subject), data = sleepstudy,
control = lmerControl(optimizer = "nloptwrap"))
# set the number of factor levels
ngroups <- 3:18
# generate all possible combinations
combos <- lapply(X = ngroups,
FUN = function(x) combn(unique(sleepstudy$Subject), x))
# allocate output (sorry, this code is entirely un-optimized)
out <- list(matrix(NA, ncol(combos[[1]]), 1), matrix(NA, ncol(combos[[2]]), 1),
matrix(NA, ncol(combos[[3]]), 1), matrix(NA, ncol(combos[[4]]), 1),
matrix(NA, ncol(combos[[5]]), 1), matrix(NA, ncol(combos[[6]]), 1),
matrix(NA, ncol(combos[[7]]), 1), matrix(NA, ncol(combos[[8]]), 1),
matrix(NA, ncol(combos[[9]]), 1), matrix(NA, ncol(combos[[10]]), 1),
matrix(NA, ncol(combos[[11]]), 1), matrix(NA, ncol(combos[[12]]), 1),
matrix(NA, ncol(combos[[13]]), 1), matrix(NA, ncol(combos[[14]]), 1),
matrix(NA, ncol(combos[[15]]), 1), matrix(NA, ncol(combos[[16]]), 1))
# took ~ 2.5 hrs on my laptop, commented out for safety
#system.time(for(ii in 1:length(combos)) {
# for(jj in 1:ncol(combos[[ii]])) {
# sls <- sleepstudy[sleepstudy$Subject %in% combos[[ii]][,jj],]
# out[[ii]][jj] <- attr(VarCorr(update(m0, data = sls))$Subject, 'stddev')
# }
# })
# pad with zeros, not all were equal
# from http://stackoverflow.com/questions/11148429/r-convert-asymmetric-list-to-matrix-number-of-elements-in-each-sub-list-diffe
max.len <- max(sapply(out, length))
corrected.list <- lapply(out, function(x) {c(x, rep(NA, max.len - length(x)))})
mat <- do.call(rbind, corrected.list)
mat <- data.frame(t(mat))
names(mat) <- paste0('s',3:18)
mat <- gather(mat, run, value)
ggplot(mat, aes(x = value, fill = run)) +
geom_histogram(bins = 60) +
geom_vline(xintercept = 37.12, linetype = 'longdash',
aes(colour = 'original')) +
facet_wrap(~run, scales = 'free_y') +
scale_x_continuous(breaks = seq(0, 100, by = 20)) +
theme_bw() +
guides(fill = FALSE)
The dotted black line is the original point estimate of the variance, and the facets represent different numbers of subjects (s3 being groups of three subjects, s4 being four, etc.).
And the alternative way:
ngroups <- 3:18
reps <- 500
out2<- matrix(NA, length(ngroups), reps)
for (ii in 1:length(ngroups)) {
for(j in 1:reps) {
sls <- sleepstudy[sleepstudy$Subject %in% sample(unique(sleepstudy$Subject), ngroups[i], replace = FALSE),]
out2[i,j] <- attr(VarCorr(update(m0, data = sls))$Subject, 'stddev')
}
}
out2 <- data.frame(t(out2))
names(out2) <- paste0('s',3:18)
out2 <- gather(out2, run, value)
ggplot(out2, aes(x = value, fill = run)) +
geom_histogram(bins = 60) +
geom_vline(xintercept = 37.12, linetype = 'longdash',
aes(colour = 'original')) +
facet_wrap(~run, scales = 'free_y') +
scale_x_continuous(breaks = seq(0, 100, by = 20)) +
theme_bw() +
guides(fill = FALSE)
It appears (for this example, anyway) that the variance doesn't really stabilize until there are at least 14 subjects, if not later.
|
What is the minimum recommended number of groups for a random effects factor?
For what it's worth, I did a bit of a simulation study to look at the stability of the variance estimate for a relatively simple LMM (using the sleepstudy dataset available through lme4). The first wa
|
6,042
|
What is the minimum recommended number of groups for a random effects factor?
|
You could also use a Bayesian mixed model - in that case the uncertainty in the estimation of the random effects is fully taken care of in the calculation of the 95% prediction credible intervals. The new R package brms and function brm, for example, allow for a very easy transition from an lme4 frequentist mixed model to a Bayesian one, as it has near identical syntax.
|
What is the minimum recommended number of groups for a random effects factor?
|
You could also use a Bayesian mixed model - in that case the uncertainty in the estimation of the random effects is fully taken care of in the calculation of the 95% prediction credible intervals. The
|
What is the minimum recommended number of groups for a random effects factor?
You could also use a Bayesian mixed model - in that case the uncertainty in the estimation of the random effects is fully taken care of in the calculation of the 95% prediction credible intervals. The new R package brms and function brm, for example, allow for a very easy transition from an lme4 frequentist mixed model to a Bayesian one, as it has near identical syntax.
|
What is the minimum recommended number of groups for a random effects factor?
You could also use a Bayesian mixed model - in that case the uncertainty in the estimation of the random effects is fully taken care of in the calculation of the 95% prediction credible intervals. The
|
6,043
|
What is the minimum recommended number of groups for a random effects factor?
|
Angrist and Pischke's "Mostly Harmless Econometrics" has a section titled, "Fewer than 42 clusters", in which they semi-jokingly say,
Therefore, following the... dictum that the answer to life, the universe and everything is 42, we believe the question is: How many clusters are enough for reliable inference using the standard cluster adjustment [akin to the variance estimator in GEE]?
The way my econometrics instructor used to answer questions like yours is, "America is a free country, you can do whatever you like. But if you want to have your paper published, you need to be able to defend what you've done." In other words, you will likely be able to run R or Stata or HLM or Mplus or SAS PROC GLIMMIX code with 6 subjects (and switch to these alternative packages if the one of your choice does not run this), but you will likely have very difficult time defending this approach and justifying asymptotic tests.
I believe that by default, including a variable as a random slope implies including that as a fixed effect, as well, and you need to jump through a lot of syntax hoops if you only want to have this as a random effect with the mean of zero. That's a sensible choice that the software developers have made for you.
|
What is the minimum recommended number of groups for a random effects factor?
|
Angrist and Pischke's "Mostly Harmless Econometrics" has a section titled, "Fewer than 42 clusters", in which they semi-jokingly say,
Therefore, following the... dictum that the answer to life, the un
|
What is the minimum recommended number of groups for a random effects factor?
Angrist and Pischke's "Mostly Harmless Econometrics" has a section titled, "Fewer than 42 clusters", in which they semi-jokingly say,
Therefore, following the... dictum that the answer to life, the universe and everything is 42, we believe the question is: How many clusters are enough for reliable inference using the standard cluster adjustment [akin to the variance estimator in GEE]?
The way my econometrics instructor used to answer questions like yours is, "America is a free country, you can do whatever you like. But if you want to have your paper published, you need to be able to defend what you've done." In other words, you will likely be able to run R or Stata or HLM or Mplus or SAS PROC GLIMMIX code with 6 subjects (and switch to these alternative packages if the one of your choice does not run this), but you will likely have very difficult time defending this approach and justifying asymptotic tests.
I believe that by default, including a variable as a random slope implies including that as a fixed effect, as well, and you need to jump through a lot of syntax hoops if you only want to have this as a random effect with the mean of zero. That's a sensible choice that the software developers have made for you.
|
What is the minimum recommended number of groups for a random effects factor?
Angrist and Pischke's "Mostly Harmless Econometrics" has a section titled, "Fewer than 42 clusters", in which they semi-jokingly say,
Therefore, following the... dictum that the answer to life, the un
|
6,044
|
What is the minimum recommended number of groups for a random effects factor?
|
I would not use a random effects model with only 6 levels. Models using a 6-level random effect can sometime be run using many statistical programs and sometimes give unbiased estimates, but:
I think there is an arbitrary consensus in the statistical community that 10-20 is the minimum number. If you want to have your research published, you'll be advised to look for a journal without statistical review (or be able to justify your decision using fairly sophisticated language).
With so few clusters, the between cluster variance is likely to be poorly estimated. Poor estimation of between cluster variance usually translates into poor estimation of the standard error of the coefficients of interest. (random effects models rely on the number of clusters theoretically going to infinity).
Often the models simply don't converge. Have you tried running your model? I would surprised with only 12-16 measures per subject that the models converge. When I've managed to get this sort of model to converge I've had hundreds of measurements per cluster.
This issue is addressed in most standard textbooks in the field and you've sort of addressed them in your question. I don't think I'm giving you any new information.
|
What is the minimum recommended number of groups for a random effects factor?
|
I would not use a random effects model with only 6 levels. Models using a 6-level random effect can sometime be run using many statistical programs and sometimes give unbiased estimates, but:
I thi
|
What is the minimum recommended number of groups for a random effects factor?
I would not use a random effects model with only 6 levels. Models using a 6-level random effect can sometime be run using many statistical programs and sometimes give unbiased estimates, but:
I think there is an arbitrary consensus in the statistical community that 10-20 is the minimum number. If you want to have your research published, you'll be advised to look for a journal without statistical review (or be able to justify your decision using fairly sophisticated language).
With so few clusters, the between cluster variance is likely to be poorly estimated. Poor estimation of between cluster variance usually translates into poor estimation of the standard error of the coefficients of interest. (random effects models rely on the number of clusters theoretically going to infinity).
Often the models simply don't converge. Have you tried running your model? I would surprised with only 12-16 measures per subject that the models converge. When I've managed to get this sort of model to converge I've had hundreds of measurements per cluster.
This issue is addressed in most standard textbooks in the field and you've sort of addressed them in your question. I don't think I'm giving you any new information.
|
What is the minimum recommended number of groups for a random effects factor?
I would not use a random effects model with only 6 levels. Models using a 6-level random effect can sometime be run using many statistical programs and sometimes give unbiased estimates, but:
I thi
|
6,045
|
What is the minimum recommended number of groups for a random effects factor?
|
It has been a long time since the original question but I thought I might add a few points pertinent to model selection.
1 - As long as the model is identified (i.e. you have degrees of freedom in the parameter space) you should be able to TRY to fit the model. Depending on the optimization method model may or may not converge. In any case I would not try to include more than 1 or 2 random effects and definitely not more than 1 cross level interaction. In the specific case of the problem presented here if we suspect an interaction between lizard specific characteristics (e.g. age, size, etc.) and treatment/measure characteristics group size 6 may not be enough to make precise enough estimates.
2 - As a couple of answers mention, convergence may be an issue. However my experience is that while social science data has huge convergence problem due to measurement issues, life sciences and especially bio-chemical repeated measures have much smaller standard errors. It all depends on the data generating process. In social and economic data we have to work at various levels of abstraction. In biological and chemical and most certainly astronomical data measurement error is a less of a problem.
|
What is the minimum recommended number of groups for a random effects factor?
|
It has been a long time since the original question but I thought I might add a few points pertinent to model selection.
1 - As long as the model is identified (i.e. you have degrees of freedom in the
|
What is the minimum recommended number of groups for a random effects factor?
It has been a long time since the original question but I thought I might add a few points pertinent to model selection.
1 - As long as the model is identified (i.e. you have degrees of freedom in the parameter space) you should be able to TRY to fit the model. Depending on the optimization method model may or may not converge. In any case I would not try to include more than 1 or 2 random effects and definitely not more than 1 cross level interaction. In the specific case of the problem presented here if we suspect an interaction between lizard specific characteristics (e.g. age, size, etc.) and treatment/measure characteristics group size 6 may not be enough to make precise enough estimates.
2 - As a couple of answers mention, convergence may be an issue. However my experience is that while social science data has huge convergence problem due to measurement issues, life sciences and especially bio-chemical repeated measures have much smaller standard errors. It all depends on the data generating process. In social and economic data we have to work at various levels of abstraction. In biological and chemical and most certainly astronomical data measurement error is a less of a problem.
|
What is the minimum recommended number of groups for a random effects factor?
It has been a long time since the original question but I thought I might add a few points pertinent to model selection.
1 - As long as the model is identified (i.e. you have degrees of freedom in the
|
6,046
|
What does negative R-squared mean?
|
$R^2$ can be negative, it just means that:
The model fits your data very badly
You did not set an intercept
To the people saying that $R^2$ is between 0 and 1, this is not the case. While a negative value for something with the word 'squared' in it might sound like it breaks the rules of maths, it can happen in an $R^2$ model without an intercept. To understand why, we need to look at how $R^2$ is calculated.
This is a bit long - If you want the answer without understanding it, then skip to the end. Otherwise, I've tried to write this in simple words.
First, let's define 3 variables: $RSS$, $TSS$ and $ESS$.
Calculating RSS:
For every independent variable $x$, we have the dependent variable $y$. We plot a linear line of best fit, which predicts the value of $y$ for each value of $x$. Let's call the values of $y$ the line predicts $\hat y$. The error between what your line predicts and what the actual $y$ value is can be calculated be subtraction. All these differences are squared and added up, which gives the Residual Sum of Squares $RSS$.
Putting that into an equation, $RSS = \sum (y - \hat y)^2$
Calculating TSS:
We can calculate the average value of $y$, which is called $\bar y$. If we plot $\bar y$, it is just a horizontal line through the data because it is constant. What we can do with it though, is subtract $\bar y$ (the average value of $y$) from every actual value of $y$. The result is squared and added together, which gives the total sum of squares $TSS$.
Putting that into an equation $TSS = \sum (y - \bar y)^2$
Calculating ESS:
The differences between $\hat y$ (the values of $y$ predicted by the line) and the average value $\bar y$ are squared and added. This is the Explained sum of squares, which equals $\sum (\hat y - \bar y)^2$
Remember, $TSS = \sum (y - \bar y)^2$, but we can add a $ + \hat y - \hat y$ into it, because it cancels itself out. Therefore, $TSS = \sum (y - \hat y + \hat y -\bar y)^2$. Expanding these brackets, we get $TSS = \sum (y - \hat y)^2 + 2* \sum (y - \hat y)(\hat y - \bar y) + \sum (\hat y - \bar y)^2$
When, and only when the line is plotted with an intercept, the following is always true: $2* \sum (y - \hat y)(\hat y - \bar y) = 0$. Therefore, $TSS = \sum (y - \hat y)^2 + \sum (\hat y - \bar y)^2$, which you may notice just means that $TSS = RSS + ESS$. If we divide all terms by $TSS$ and rearrange, we get $1 - \frac {RSS}{TSS} = \frac {ESS}{TSS}$.
Here's the important part:
$R^2$ is defined as how much of the variance is explained by your model (how good your model is). In equation form, that's $R^2 = 1 - \frac {RSS}{TSS}$. Look familiar? When the line is plotted with an intercept, we can substitute this as $R^2 = \frac {ESS}{TSS}$. Since both the numerator and demoninator are sums of squares, $R^2$ must be positive.
BUT
When we don't specify an intercept, $2* \sum (y - \hat y)(\hat y - \bar y)$ does not necessarily equal $0$. This means that $TSS = RSS + ESS + 2* \sum (y - \hat y)(\hat y - \bar y)$.
Dividing all terms by $TSS$, we get $1 - \frac{RSS}{TSS} = \frac {ESS + 2* \sum (y - \hat y)(\hat y - \bar y)}{TSS}$.
Finally, we substitute to get $R^2 = \frac {ESS + 2* \sum (y - \hat y)(\hat y - \bar y)}{TSS}$. This time, the numerator has a term in it which is not a sum of squares, so it can be negative. This would make $R^2$ negative. When would this happen? $2* \sum (y - \hat y)(\hat y - \bar y)$ would be negative when $y - \hat y$ is negative and $\hat y - \bar y$ is positive, or vice versa. This occurs when the horizontal line of $\bar y$ actually explains the data better than the line of best fit.
Here's an exaggerated example of when $R^2$ is negative (Source: University of Houston Clear Lake)
Put simply:
When $R^2 < 0$, a horizontal line explains the data better than your model.
You also asked about $R^2 = 0$.
When $R^2 = 0$, a horizontal line explains the data equally as well as your model.
I commend you for making it through that. If you found this helpful, you should also upvote fcop's answer here which I had to refer to, because it's been a while.
|
What does negative R-squared mean?
|
$R^2$ can be negative, it just means that:
The model fits your data very badly
You did not set an intercept
To the people saying that $R^2$ is between 0 and 1, this is not the case. While a negative
|
What does negative R-squared mean?
$R^2$ can be negative, it just means that:
The model fits your data very badly
You did not set an intercept
To the people saying that $R^2$ is between 0 and 1, this is not the case. While a negative value for something with the word 'squared' in it might sound like it breaks the rules of maths, it can happen in an $R^2$ model without an intercept. To understand why, we need to look at how $R^2$ is calculated.
This is a bit long - If you want the answer without understanding it, then skip to the end. Otherwise, I've tried to write this in simple words.
First, let's define 3 variables: $RSS$, $TSS$ and $ESS$.
Calculating RSS:
For every independent variable $x$, we have the dependent variable $y$. We plot a linear line of best fit, which predicts the value of $y$ for each value of $x$. Let's call the values of $y$ the line predicts $\hat y$. The error between what your line predicts and what the actual $y$ value is can be calculated be subtraction. All these differences are squared and added up, which gives the Residual Sum of Squares $RSS$.
Putting that into an equation, $RSS = \sum (y - \hat y)^2$
Calculating TSS:
We can calculate the average value of $y$, which is called $\bar y$. If we plot $\bar y$, it is just a horizontal line through the data because it is constant. What we can do with it though, is subtract $\bar y$ (the average value of $y$) from every actual value of $y$. The result is squared and added together, which gives the total sum of squares $TSS$.
Putting that into an equation $TSS = \sum (y - \bar y)^2$
Calculating ESS:
The differences between $\hat y$ (the values of $y$ predicted by the line) and the average value $\bar y$ are squared and added. This is the Explained sum of squares, which equals $\sum (\hat y - \bar y)^2$
Remember, $TSS = \sum (y - \bar y)^2$, but we can add a $ + \hat y - \hat y$ into it, because it cancels itself out. Therefore, $TSS = \sum (y - \hat y + \hat y -\bar y)^2$. Expanding these brackets, we get $TSS = \sum (y - \hat y)^2 + 2* \sum (y - \hat y)(\hat y - \bar y) + \sum (\hat y - \bar y)^2$
When, and only when the line is plotted with an intercept, the following is always true: $2* \sum (y - \hat y)(\hat y - \bar y) = 0$. Therefore, $TSS = \sum (y - \hat y)^2 + \sum (\hat y - \bar y)^2$, which you may notice just means that $TSS = RSS + ESS$. If we divide all terms by $TSS$ and rearrange, we get $1 - \frac {RSS}{TSS} = \frac {ESS}{TSS}$.
Here's the important part:
$R^2$ is defined as how much of the variance is explained by your model (how good your model is). In equation form, that's $R^2 = 1 - \frac {RSS}{TSS}$. Look familiar? When the line is plotted with an intercept, we can substitute this as $R^2 = \frac {ESS}{TSS}$. Since both the numerator and demoninator are sums of squares, $R^2$ must be positive.
BUT
When we don't specify an intercept, $2* \sum (y - \hat y)(\hat y - \bar y)$ does not necessarily equal $0$. This means that $TSS = RSS + ESS + 2* \sum (y - \hat y)(\hat y - \bar y)$.
Dividing all terms by $TSS$, we get $1 - \frac{RSS}{TSS} = \frac {ESS + 2* \sum (y - \hat y)(\hat y - \bar y)}{TSS}$.
Finally, we substitute to get $R^2 = \frac {ESS + 2* \sum (y - \hat y)(\hat y - \bar y)}{TSS}$. This time, the numerator has a term in it which is not a sum of squares, so it can be negative. This would make $R^2$ negative. When would this happen? $2* \sum (y - \hat y)(\hat y - \bar y)$ would be negative when $y - \hat y$ is negative and $\hat y - \bar y$ is positive, or vice versa. This occurs when the horizontal line of $\bar y$ actually explains the data better than the line of best fit.
Here's an exaggerated example of when $R^2$ is negative (Source: University of Houston Clear Lake)
Put simply:
When $R^2 < 0$, a horizontal line explains the data better than your model.
You also asked about $R^2 = 0$.
When $R^2 = 0$, a horizontal line explains the data equally as well as your model.
I commend you for making it through that. If you found this helpful, you should also upvote fcop's answer here which I had to refer to, because it's been a while.
|
What does negative R-squared mean?
$R^2$ can be negative, it just means that:
The model fits your data very badly
You did not set an intercept
To the people saying that $R^2$ is between 0 and 1, this is not the case. While a negative
|
6,047
|
What does negative R-squared mean?
|
Neither answer so far is entirely correct, so I will try to give my understanding of R-Squared. I have given a more detailed explanation of this on my blog post here "What is R-Squared"
Sum Squared Error
The objective of ordinary least squared regression is to get a line which minimized the sum squared error. The default line with minimum sum squared error is a horizontal line through the mean. Basically, if you can't do better, you can just predict the mean value and that will give you the minimum sum squared error
R-Squared is a way of measuring how much better than the mean line you have done based on summed squared error. The equation for R-Squared is
Now SS Regression and SS Total are both sums of squared terms. Both of those are always positive. This means we are taking 1, and subtracting a positive value. So the maximum R-Squared value is positive 1, but the minimum is negative infinity. Yes, that is correct, the range of R-squared is between -infinity and 1, not -1 and 1 and not 0 and 1
What Is Sum Squared Error
Sum squared error is taking the error at every point, squaring it, and adding all the squares. For total error, it uses the horizontal line through the mean, because that gives the lowest sum squared error if you don't have any other information, i.e. can't do a regression.
As an equation it is this
Now with regression, our objective is to do better than the mean. For instance this regression line will give a lower sum squared error than using the horizontal line.
The equation for regression sum squared error is this
Ideally, you would have zero regression error, i.e. your regression line would perfectly match the data. In that case you would get an R-Squared value of 1
Negative R Squared
All the information above is pretty standard. Now what about negative R-Squared ?
Well it turns out that there is not reason that your regression equation must give lower sum squared error than the mean value. It is generally thought that if you can't make a better prediction than the mean value, you would just use the mean value, but there is nothing forcing that to be the cause. You could for instance predict the median for everything.
In actual practice, with ordinary least squared regression, the most common time to get a negative R-Squared value is when you force a point that the regression line must go through. This is typically done by setting the intercept, but you can force the regression line through any point.
When you do that the regression line goes through that point, and attempts to get the minimum sum squared error while still going through that point.
By default, the regression equations use average x and average y as the point that the regression line goes through. But if you force it through a point that is far away from where the regression line would normally be you can get sum squared error that is higher than using the horizontal line
In the image below, both regression lines were forced to have a y intercept of 0. This caused a negative R-squared for the data that is far offset from the origin.
For the top set of points, the red ones, the regression line is the best possible regression line that also passes through the origin. It just happens that that regression line is worse than using a horizontal line, and hence gives a negative R-Squared.
Undefined R-Squared
There is one special case no one mentioned, where you can get an undefined R-Squared. That is if your data is completely horizontal, then your total sum squared error is zero. As a result you would have a zero divided by zero in the R-squared equation, which is undefined.
|
What does negative R-squared mean?
|
Neither answer so far is entirely correct, so I will try to give my understanding of R-Squared. I have given a more detailed explanation of this on my blog post here "What is R-Squared"
Sum Squared E
|
What does negative R-squared mean?
Neither answer so far is entirely correct, so I will try to give my understanding of R-Squared. I have given a more detailed explanation of this on my blog post here "What is R-Squared"
Sum Squared Error
The objective of ordinary least squared regression is to get a line which minimized the sum squared error. The default line with minimum sum squared error is a horizontal line through the mean. Basically, if you can't do better, you can just predict the mean value and that will give you the minimum sum squared error
R-Squared is a way of measuring how much better than the mean line you have done based on summed squared error. The equation for R-Squared is
Now SS Regression and SS Total are both sums of squared terms. Both of those are always positive. This means we are taking 1, and subtracting a positive value. So the maximum R-Squared value is positive 1, but the minimum is negative infinity. Yes, that is correct, the range of R-squared is between -infinity and 1, not -1 and 1 and not 0 and 1
What Is Sum Squared Error
Sum squared error is taking the error at every point, squaring it, and adding all the squares. For total error, it uses the horizontal line through the mean, because that gives the lowest sum squared error if you don't have any other information, i.e. can't do a regression.
As an equation it is this
Now with regression, our objective is to do better than the mean. For instance this regression line will give a lower sum squared error than using the horizontal line.
The equation for regression sum squared error is this
Ideally, you would have zero regression error, i.e. your regression line would perfectly match the data. In that case you would get an R-Squared value of 1
Negative R Squared
All the information above is pretty standard. Now what about negative R-Squared ?
Well it turns out that there is not reason that your regression equation must give lower sum squared error than the mean value. It is generally thought that if you can't make a better prediction than the mean value, you would just use the mean value, but there is nothing forcing that to be the cause. You could for instance predict the median for everything.
In actual practice, with ordinary least squared regression, the most common time to get a negative R-Squared value is when you force a point that the regression line must go through. This is typically done by setting the intercept, but you can force the regression line through any point.
When you do that the regression line goes through that point, and attempts to get the minimum sum squared error while still going through that point.
By default, the regression equations use average x and average y as the point that the regression line goes through. But if you force it through a point that is far away from where the regression line would normally be you can get sum squared error that is higher than using the horizontal line
In the image below, both regression lines were forced to have a y intercept of 0. This caused a negative R-squared for the data that is far offset from the origin.
For the top set of points, the red ones, the regression line is the best possible regression line that also passes through the origin. It just happens that that regression line is worse than using a horizontal line, and hence gives a negative R-Squared.
Undefined R-Squared
There is one special case no one mentioned, where you can get an undefined R-Squared. That is if your data is completely horizontal, then your total sum squared error is zero. As a result you would have a zero divided by zero in the R-squared equation, which is undefined.
|
What does negative R-squared mean?
Neither answer so far is entirely correct, so I will try to give my understanding of R-Squared. I have given a more detailed explanation of this on my blog post here "What is R-Squared"
Sum Squared E
|
6,048
|
What does negative R-squared mean?
|
The question is asking about "a model (a non-linear regression)". In this case there is no bound of how negative R-squared can be.
R-squared = 1 - SSE / TSS
As long as your SSE term is significantly large, you will get an a negative R-squared. It can be caused by overall bad fit or one extreme bad prediction.
For example:
In [78]: from sklearn import metrics
In [79]: actual = np.array([1,2,3,4,5,6])
In [80]: preds = np.array([1,2,3,4,5,60]) # the model can predict anything
In [81]: metrics.r2_score(actual, preds)
Out[81]: -165.62857142857143
In [82]: sse = np.sum((actual - preds) ** 2)
In [83]: sse
Out[83]: 2916
In [84]: tss = np.sum((actual - np.mean(actual)) ** 2)
In [85]: tss
Out[85]: 17.5
In [86]: r_2 = 1 - sse / tss
In [87]: r_2
Out[87]: -165.62857142857143
|
What does negative R-squared mean?
|
The question is asking about "a model (a non-linear regression)". In this case there is no bound of how negative R-squared can be.
R-squared = 1 - SSE / TSS
As long as your SSE term is significantly
|
What does negative R-squared mean?
The question is asking about "a model (a non-linear regression)". In this case there is no bound of how negative R-squared can be.
R-squared = 1 - SSE / TSS
As long as your SSE term is significantly large, you will get an a negative R-squared. It can be caused by overall bad fit or one extreme bad prediction.
For example:
In [78]: from sklearn import metrics
In [79]: actual = np.array([1,2,3,4,5,6])
In [80]: preds = np.array([1,2,3,4,5,60]) # the model can predict anything
In [81]: metrics.r2_score(actual, preds)
Out[81]: -165.62857142857143
In [82]: sse = np.sum((actual - preds) ** 2)
In [83]: sse
Out[83]: 2916
In [84]: tss = np.sum((actual - np.mean(actual)) ** 2)
In [85]: tss
Out[85]: 17.5
In [86]: r_2 = 1 - sse / tss
In [87]: r_2
Out[87]: -165.62857142857143
|
What does negative R-squared mean?
The question is asking about "a model (a non-linear regression)". In this case there is no bound of how negative R-squared can be.
R-squared = 1 - SSE / TSS
As long as your SSE term is significantly
|
6,049
|
What does negative R-squared mean?
|
Negative $R^2$ may indicate poor relative calibration of the model. This strictly applies to Efron's $R^2$ in the context of logistic regression. I think that this can be extrapolated (at least as an intuition) to standard $R^2$ for linear probability model.
This follows from the equivalence of Efron's $R^2$ and Brier Skill Score (BSS):
$$\text{Efron's } R^2 = 1 - \frac{\sum_{i=1}^N ({y_i} - \hat \pi_i)^2}{\sum_{i=1}^N ({y_i} - \bar y)^2}$$
Whereas:
$$BSS = 1 - \frac{BS}{BS_{\text{ref}}} = 1 - \frac{\frac{1}{N} \sum_{t=1}^N (f_t - o_t)^2}{\frac{1}{N} \sum_{t=1}^N (\bar o - o_t)^2} = 1 - \frac{\sum_{t=1}^N (o_t - f_t)^2}{\sum_{t=1}^N (o_t - \bar o)^2}$$
where
$y_i$ - event, $o_t$ - actual outcome
$\hat \pi_i$ - model predicted probability, $f_t$ - forecast probability
$i$ - observation, $t$ - forecast
Notation taken from UCLA for Efron's $R^2$ and from Wiki for BSS.
Some guidelines recommend that all clinical prediction models should have a BSS>0.
|
What does negative R-squared mean?
|
Negative $R^2$ may indicate poor relative calibration of the model. This strictly applies to Efron's $R^2$ in the context of logistic regression. I think that this can be extrapolated (at least as an
|
What does negative R-squared mean?
Negative $R^2$ may indicate poor relative calibration of the model. This strictly applies to Efron's $R^2$ in the context of logistic regression. I think that this can be extrapolated (at least as an intuition) to standard $R^2$ for linear probability model.
This follows from the equivalence of Efron's $R^2$ and Brier Skill Score (BSS):
$$\text{Efron's } R^2 = 1 - \frac{\sum_{i=1}^N ({y_i} - \hat \pi_i)^2}{\sum_{i=1}^N ({y_i} - \bar y)^2}$$
Whereas:
$$BSS = 1 - \frac{BS}{BS_{\text{ref}}} = 1 - \frac{\frac{1}{N} \sum_{t=1}^N (f_t - o_t)^2}{\frac{1}{N} \sum_{t=1}^N (\bar o - o_t)^2} = 1 - \frac{\sum_{t=1}^N (o_t - f_t)^2}{\sum_{t=1}^N (o_t - \bar o)^2}$$
where
$y_i$ - event, $o_t$ - actual outcome
$\hat \pi_i$ - model predicted probability, $f_t$ - forecast probability
$i$ - observation, $t$ - forecast
Notation taken from UCLA for Efron's $R^2$ and from Wiki for BSS.
Some guidelines recommend that all clinical prediction models should have a BSS>0.
|
What does negative R-squared mean?
Negative $R^2$ may indicate poor relative calibration of the model. This strictly applies to Efron's $R^2$ in the context of logistic regression. I think that this can be extrapolated (at least as an
|
6,050
|
What does negative R-squared mean?
|
Means the model is worse the horizontal line (mean).
See this explanation pag. 31: https://scholarsmine.mst.edu/masters_theses/7913/
|
What does negative R-squared mean?
|
Means the model is worse the horizontal line (mean).
See this explanation pag. 31: https://scholarsmine.mst.edu/masters_theses/7913/
|
What does negative R-squared mean?
Means the model is worse the horizontal line (mean).
See this explanation pag. 31: https://scholarsmine.mst.edu/masters_theses/7913/
|
What does negative R-squared mean?
Means the model is worse the horizontal line (mean).
See this explanation pag. 31: https://scholarsmine.mst.edu/masters_theses/7913/
|
6,051
|
What does negative R-squared mean?
|
As the previous commenter notes, r^2 is between [0,1], not [-1,+1], so it is impossible to be negative. You cannot square a value and get a negative number. Perhaps you are looking at r, the correlation? It can be between [-1,+1], where zero means there is no relationship between the variables, -1 means there is a perfect negative relationship (as one variable increases, the other decreases), and +1 is a perfect positive relationship (both variables go up or down concordantly).
If indeed you are looking at r^2, then, as the previous commenter describes, you are probably seeing the adjusted r^2, not the actual r^2. Consider what the statistic means: I teach behavioral science statistics, and the easiest way that I've learned to teach my students about the meaning of r^2 is " % variance explained." So if you have r^2=0.5, the model explains 50% of the variation of the dependent (outcome) variable. If you have a negative r^2, it would mean that the model explains a negative % of the outcome variable, which is not an intuitively reasonable suggestion. However, adjusted r^2 takes the sample size (n) and number of predictors (p) into consideration. A formula for calculating it is here. If you have a very low r^2, then it is reasonably easy to get negative values. Granted, a negative adjusted r^2 does not have any more intuitive meaning than regular r^2, but as the previous commenter says, it just means your model is very poor, if not just plain useless.
|
What does negative R-squared mean?
|
As the previous commenter notes, r^2 is between [0,1], not [-1,+1], so it is impossible to be negative. You cannot square a value and get a negative number. Perhaps you are looking at r, the correl
|
What does negative R-squared mean?
As the previous commenter notes, r^2 is between [0,1], not [-1,+1], so it is impossible to be negative. You cannot square a value and get a negative number. Perhaps you are looking at r, the correlation? It can be between [-1,+1], where zero means there is no relationship between the variables, -1 means there is a perfect negative relationship (as one variable increases, the other decreases), and +1 is a perfect positive relationship (both variables go up or down concordantly).
If indeed you are looking at r^2, then, as the previous commenter describes, you are probably seeing the adjusted r^2, not the actual r^2. Consider what the statistic means: I teach behavioral science statistics, and the easiest way that I've learned to teach my students about the meaning of r^2 is " % variance explained." So if you have r^2=0.5, the model explains 50% of the variation of the dependent (outcome) variable. If you have a negative r^2, it would mean that the model explains a negative % of the outcome variable, which is not an intuitively reasonable suggestion. However, adjusted r^2 takes the sample size (n) and number of predictors (p) into consideration. A formula for calculating it is here. If you have a very low r^2, then it is reasonably easy to get negative values. Granted, a negative adjusted r^2 does not have any more intuitive meaning than regular r^2, but as the previous commenter says, it just means your model is very poor, if not just plain useless.
|
What does negative R-squared mean?
As the previous commenter notes, r^2 is between [0,1], not [-1,+1], so it is impossible to be negative. You cannot square a value and get a negative number. Perhaps you are looking at r, the correl
|
6,052
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
You can do it backward: every matrix $C \in \mathbb{R}_{++}^p$ (the set of all symmetric $p \times p$ PSD matrices) can be decomposed as
$C=O^{T}DO$ where $O$ is an orthonormal matrix
To get $O$, first generate a random basis $(v_1,...,v_p)$ (where $v_i$ are random vectors, typically in $(-1,1)$). From there, use the Gram-Schmidt orthogonalization process to get $(u_1,....,u_p)=O$
$R$ has a number of packages that can do the G-S orthogonalization of a random basis efficiently, that is even for large dimensions, for example the 'far' package. Although you will find the G-S algorithm on wiki, it's probably better not to re-invent the wheel and go for a matlab implementation (one surely exists, i just can't recommend any).
Finally, $D$ is a diagonal matrices whose elements are all positive (this is, again, easy to generate: generate $p$ random numbers, square them, sort them and place them unto the diagonal of a identity $p$ by $p$ matrix).
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
You can do it backward: every matrix $C \in \mathbb{R}_{++}^p$ (the set of all symmetric $p \times p$ PSD matrices) can be decomposed as
$C=O^{T}DO$ where $O$ is an orthonormal matrix
To get $O$, f
|
How to efficiently generate random positive-semidefinite correlation matrices?
You can do it backward: every matrix $C \in \mathbb{R}_{++}^p$ (the set of all symmetric $p \times p$ PSD matrices) can be decomposed as
$C=O^{T}DO$ where $O$ is an orthonormal matrix
To get $O$, first generate a random basis $(v_1,...,v_p)$ (where $v_i$ are random vectors, typically in $(-1,1)$). From there, use the Gram-Schmidt orthogonalization process to get $(u_1,....,u_p)=O$
$R$ has a number of packages that can do the G-S orthogonalization of a random basis efficiently, that is even for large dimensions, for example the 'far' package. Although you will find the G-S algorithm on wiki, it's probably better not to re-invent the wheel and go for a matlab implementation (one surely exists, i just can't recommend any).
Finally, $D$ is a diagonal matrices whose elements are all positive (this is, again, easy to generate: generate $p$ random numbers, square them, sort them and place them unto the diagonal of a identity $p$ by $p$ matrix).
|
How to efficiently generate random positive-semidefinite correlation matrices?
You can do it backward: every matrix $C \in \mathbb{R}_{++}^p$ (the set of all symmetric $p \times p$ PSD matrices) can be decomposed as
$C=O^{T}DO$ where $O$ is an orthonormal matrix
To get $O$, f
|
6,053
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
A paper Generating random correlation matrices based on vines and extended
onion method by Lewandowski, Kurowicka, and Joe (LKJ), 2009, provides a unified treatment and exposition of the two efficient methods of generating random correlation matrices. Both methods allow to generate matrices from a uniform distribution in a certain precise sense defined below, are simple to implement, fast, and have an added advantage of having amusing names.
A real symmetric matrix of $d \times d$ size with ones on the diagonal has $d(d-1)/2$ unique off-diagonal elements and so can be parametrized as a point in $\mathbb R^{d(d-1)/2}$. Each point in this space corresponds to a symmetric matrix, but not all of them are positive-definite (as correlation matrices have to be). Correlation matrices therefore form a subset of $\mathbb R^{d(d-1)/2}$ (actually a connected convex subset), and both methods can generate points from a uniform distribution over this subset.
I will provide my own MATLAB implementation of each method and illustrate them with $d=100$.
Onion method
The onion method comes from another paper (ref #3 in LKJ) and owns its name to the fact the correlation matrices are generated starting with $1\times 1$ matrix and growing it column by column and row by row. Resulting distribution is uniform. I don't really understand the math behind the method (and prefer the second method anyway), but here is the result:
Here and below the title of each subplot shows the smallest and the largest eigenvalues, and the determinant (product of all eigenvalues). Here is the code:
%// ONION METHOD to generate random correlation matrices distributed randomly
function S = onion(d)
S = 1;
for k = 2:d
y = betarnd((k-1)/2, (d-k)/2); %// sampling from beta distribution
r = sqrt(y);
theta = randn(k-1,1);
theta = theta/norm(theta);
w = r*theta;
[U,E] = eig(S);
R = U*E.^(1/2)*U'; %// R is a square root of S
q = R*w;
S = [S q; q' 1]; %// increasing the matrix size
end
end
Extended onion method
LKJ modify this method slightly, in order to be able to sample correlation matrices $\mathbf C$ from a distribution proportional to $[\mathrm{det}\:\mathbf C]^{\eta-1}$. The larger the $\eta$, the larger will be the determinant, meaning that generated correlation matrices will more and more approach the identity matrix. The value $\eta=1$ corresponds to uniform distribution. On the figure below the matrices are generated with $\eta={1, 10, 100, 1000, 10\:000, 100\:000}$.
For some reason to get the determinant of the same order of magnitude as in the vanilla onion method, I need to put $\eta=0$ and not $\eta=1$ (as claimed by LKJ). Not sure where the mistake is.
%// EXTENDED ONION METHOD to generate random correlation matrices
%// distributed ~ det(S)^eta [or maybe det(S)^(eta-1), not sure]
function S = extendedOnion(d, eta)
beta = eta + (d-2)/2;
u = betarnd(beta, beta);
r12 = 2*u - 1;
S = [1 r12; r12 1];
for k = 3:d
beta = beta - 1/2;
y = betarnd((k-1)/2, beta);
r = sqrt(y);
theta = randn(k-1,1);
theta = theta/norm(theta);
w = r*theta;
[U,E] = eig(S);
R = U*E.^(1/2)*U';
q = R*w;
S = [S q; q' 1];
end
end
Vine method
Vine method was originally suggested by Joe (J in LKJ) and improved by LKJ. I like it more, because it is conceptually easier and also easier to modify. The idea is to generate $d(d-1)/2$ partial correlations (they are independent and can have any values from $[-1, 1]$ without any constraints) and then convert them into raw correlations via a recursive formula. It is convenient to organize the computation in a certain order, and this graph is known as "vine". Importantly, if partial correlations are sampled from particular beta distributions (different for different cells in the matrix), then the resulting matrix will be distributed uniformly. Here again, LKJ introduce an additional parameter $\eta$ to sample from a distribution proportional to $[\mathrm{det}\:\mathbf C]^{\eta-1}$. The result is identical to the extended onion:
%// VINE METHOD to generate random correlation matrices
%// distributed ~ det(S)^eta [or maybe det(S)^(eta-1), not sure]
function S = vine(d, eta)
beta = eta + (d-1)/2;
P = zeros(d); %// storing partial correlations
S = eye(d);
for k = 1:d-1
beta = beta - 1/2;
for i = k+1:d
P(k,i) = betarnd(beta,beta); %// sampling from beta
P(k,i) = (P(k,i)-0.5)*2; %// linearly shifting to [-1, 1]
p = P(k,i);
for l = (k-1):-1:1 %// converting partial correlation to raw correlation
p = p * sqrt((1-P(l,i)^2)*(1-P(l,k)^2)) + P(l,i)*P(l,k);
end
S(k,i) = p;
S(i,k) = p;
end
end
end
Vine method with manual sampling of partial correlations
As one can see above, uniform distribution results in almost-diagonal correlation matrices. But one can easily modify the vine method to have stronger correlations (this is not described in the LKJ paper, but is straightforward): for this one should sample partial correlations from a distribution concentrated around $\pm 1$. Below I sample them from beta distribution (rescaled from $[0,1]$ to $[-1, 1]$) with $\alpha=\beta={50, 20, 10, 5, 2, 1}$. The smaller the parameters of the beta distribution, the more it is concentrated near the edges.
Note that in this case the distribution is not guaranteed to be permutation invariant, so I additionally randomly permute rows and columns after generation.
%// VINE METHOD to generate random correlation matrices
%// with all partial correlations distributed ~ beta(betaparam,betaparam)
%// rescaled to [-1, 1]
function S = vineBeta(d, betaparam)
P = zeros(d); %// storing partial correlations
S = eye(d);
for k = 1:d-1
for i = k+1:d
P(k,i) = betarnd(betaparam,betaparam); %// sampling from beta
P(k,i) = (P(k,i)-0.5)*2; %// linearly shifting to [-1, 1]
p = P(k,i);
for l = (k-1):-1:1 %// converting partial correlation to raw correlation
p = p * sqrt((1-P(l,i)^2)*(1-P(l,k)^2)) + P(l,i)*P(l,k);
end
S(k,i) = p;
S(i,k) = p;
end
end
%// permuting the variables to make the distribution permutation-invariant
permutation = randperm(d);
S = S(permutation, permutation);
end
Here is how the histograms of the off-diagonal elements look for the matrices above (variance of the distribution monotonically increases):
Update: using random factors
One really simple method of generating random correlation matrices with some strong correlations was used in the answer by @shabbychef, and I would like to illustrate it here as well. The idea is to randomly generate several ($k<d$) factor loadings $\mathbf W$ (random matrix of $k \times d$ size), form the covariance matrix $\mathbf W \mathbf W^\top$ (which of course will not be full rank) and add to it a random diagonal matrix $\mathbf D$ with positive elements to make $\mathbf B = \mathbf W \mathbf W^\top + \mathbf D$ full rank. The resulting covariance matrix can be normalized to become a correlation matrix, by letting $\mathbf C = \mathbf E^{-1/2}\mathbf B \mathbf E^{-1/2}$, where $\mathbf E$ is a diagonal matrix with the same diagonal as $\mathbf B$. This is very simple and does the trick. Here are some example correlation matrices for $k={100, 50, 20, 10, 5, 1}$:
And the code:
%// FACTOR method
function S = factor(d,k)
W = randn(d,k);
S = W*W' + diag(rand(1,d));
S = diag(1./sqrt(diag(S))) * S * diag(1./sqrt(diag(S)));
end
Here is the wrapping code used to generate the figures:
d = 100; %// size of the correlation matrix
figure('Position', [100 100 1100 600])
for repetition = 1:6
S = onion(d);
%// etas = [1 10 100 1000 1e+4 1e+5];
%// S = extendedOnion(d, etas(repetition));
%// S = vine(d, etas(repetition));
%// betaparams = [50 20 10 5 2 1];
%// S = vineBeta(d, betaparams(repetition));
subplot(2,3,repetition)
%// use this to plot colormaps of S
imagesc(S, [-1 1])
axis square
title(['Eigs: ' num2str(min(eig(S)),2) '...' num2str(max(eig(S)),2) ', det=' num2str(det(S),2)])
%// use this to plot histograms of the off-diagonal elements
%// offd = S(logical(ones(size(S))-eye(size(S))));
%// hist(offd)
%// xlim([-1 1])
end
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
A paper Generating random correlation matrices based on vines and extended
onion method by Lewandowski, Kurowicka, and Joe (LKJ), 2009, provides a unified treatment and exposition of the two efficien
|
How to efficiently generate random positive-semidefinite correlation matrices?
A paper Generating random correlation matrices based on vines and extended
onion method by Lewandowski, Kurowicka, and Joe (LKJ), 2009, provides a unified treatment and exposition of the two efficient methods of generating random correlation matrices. Both methods allow to generate matrices from a uniform distribution in a certain precise sense defined below, are simple to implement, fast, and have an added advantage of having amusing names.
A real symmetric matrix of $d \times d$ size with ones on the diagonal has $d(d-1)/2$ unique off-diagonal elements and so can be parametrized as a point in $\mathbb R^{d(d-1)/2}$. Each point in this space corresponds to a symmetric matrix, but not all of them are positive-definite (as correlation matrices have to be). Correlation matrices therefore form a subset of $\mathbb R^{d(d-1)/2}$ (actually a connected convex subset), and both methods can generate points from a uniform distribution over this subset.
I will provide my own MATLAB implementation of each method and illustrate them with $d=100$.
Onion method
The onion method comes from another paper (ref #3 in LKJ) and owns its name to the fact the correlation matrices are generated starting with $1\times 1$ matrix and growing it column by column and row by row. Resulting distribution is uniform. I don't really understand the math behind the method (and prefer the second method anyway), but here is the result:
Here and below the title of each subplot shows the smallest and the largest eigenvalues, and the determinant (product of all eigenvalues). Here is the code:
%// ONION METHOD to generate random correlation matrices distributed randomly
function S = onion(d)
S = 1;
for k = 2:d
y = betarnd((k-1)/2, (d-k)/2); %// sampling from beta distribution
r = sqrt(y);
theta = randn(k-1,1);
theta = theta/norm(theta);
w = r*theta;
[U,E] = eig(S);
R = U*E.^(1/2)*U'; %// R is a square root of S
q = R*w;
S = [S q; q' 1]; %// increasing the matrix size
end
end
Extended onion method
LKJ modify this method slightly, in order to be able to sample correlation matrices $\mathbf C$ from a distribution proportional to $[\mathrm{det}\:\mathbf C]^{\eta-1}$. The larger the $\eta$, the larger will be the determinant, meaning that generated correlation matrices will more and more approach the identity matrix. The value $\eta=1$ corresponds to uniform distribution. On the figure below the matrices are generated with $\eta={1, 10, 100, 1000, 10\:000, 100\:000}$.
For some reason to get the determinant of the same order of magnitude as in the vanilla onion method, I need to put $\eta=0$ and not $\eta=1$ (as claimed by LKJ). Not sure where the mistake is.
%// EXTENDED ONION METHOD to generate random correlation matrices
%// distributed ~ det(S)^eta [or maybe det(S)^(eta-1), not sure]
function S = extendedOnion(d, eta)
beta = eta + (d-2)/2;
u = betarnd(beta, beta);
r12 = 2*u - 1;
S = [1 r12; r12 1];
for k = 3:d
beta = beta - 1/2;
y = betarnd((k-1)/2, beta);
r = sqrt(y);
theta = randn(k-1,1);
theta = theta/norm(theta);
w = r*theta;
[U,E] = eig(S);
R = U*E.^(1/2)*U';
q = R*w;
S = [S q; q' 1];
end
end
Vine method
Vine method was originally suggested by Joe (J in LKJ) and improved by LKJ. I like it more, because it is conceptually easier and also easier to modify. The idea is to generate $d(d-1)/2$ partial correlations (they are independent and can have any values from $[-1, 1]$ without any constraints) and then convert them into raw correlations via a recursive formula. It is convenient to organize the computation in a certain order, and this graph is known as "vine". Importantly, if partial correlations are sampled from particular beta distributions (different for different cells in the matrix), then the resulting matrix will be distributed uniformly. Here again, LKJ introduce an additional parameter $\eta$ to sample from a distribution proportional to $[\mathrm{det}\:\mathbf C]^{\eta-1}$. The result is identical to the extended onion:
%// VINE METHOD to generate random correlation matrices
%// distributed ~ det(S)^eta [or maybe det(S)^(eta-1), not sure]
function S = vine(d, eta)
beta = eta + (d-1)/2;
P = zeros(d); %// storing partial correlations
S = eye(d);
for k = 1:d-1
beta = beta - 1/2;
for i = k+1:d
P(k,i) = betarnd(beta,beta); %// sampling from beta
P(k,i) = (P(k,i)-0.5)*2; %// linearly shifting to [-1, 1]
p = P(k,i);
for l = (k-1):-1:1 %// converting partial correlation to raw correlation
p = p * sqrt((1-P(l,i)^2)*(1-P(l,k)^2)) + P(l,i)*P(l,k);
end
S(k,i) = p;
S(i,k) = p;
end
end
end
Vine method with manual sampling of partial correlations
As one can see above, uniform distribution results in almost-diagonal correlation matrices. But one can easily modify the vine method to have stronger correlations (this is not described in the LKJ paper, but is straightforward): for this one should sample partial correlations from a distribution concentrated around $\pm 1$. Below I sample them from beta distribution (rescaled from $[0,1]$ to $[-1, 1]$) with $\alpha=\beta={50, 20, 10, 5, 2, 1}$. The smaller the parameters of the beta distribution, the more it is concentrated near the edges.
Note that in this case the distribution is not guaranteed to be permutation invariant, so I additionally randomly permute rows and columns after generation.
%// VINE METHOD to generate random correlation matrices
%// with all partial correlations distributed ~ beta(betaparam,betaparam)
%// rescaled to [-1, 1]
function S = vineBeta(d, betaparam)
P = zeros(d); %// storing partial correlations
S = eye(d);
for k = 1:d-1
for i = k+1:d
P(k,i) = betarnd(betaparam,betaparam); %// sampling from beta
P(k,i) = (P(k,i)-0.5)*2; %// linearly shifting to [-1, 1]
p = P(k,i);
for l = (k-1):-1:1 %// converting partial correlation to raw correlation
p = p * sqrt((1-P(l,i)^2)*(1-P(l,k)^2)) + P(l,i)*P(l,k);
end
S(k,i) = p;
S(i,k) = p;
end
end
%// permuting the variables to make the distribution permutation-invariant
permutation = randperm(d);
S = S(permutation, permutation);
end
Here is how the histograms of the off-diagonal elements look for the matrices above (variance of the distribution monotonically increases):
Update: using random factors
One really simple method of generating random correlation matrices with some strong correlations was used in the answer by @shabbychef, and I would like to illustrate it here as well. The idea is to randomly generate several ($k<d$) factor loadings $\mathbf W$ (random matrix of $k \times d$ size), form the covariance matrix $\mathbf W \mathbf W^\top$ (which of course will not be full rank) and add to it a random diagonal matrix $\mathbf D$ with positive elements to make $\mathbf B = \mathbf W \mathbf W^\top + \mathbf D$ full rank. The resulting covariance matrix can be normalized to become a correlation matrix, by letting $\mathbf C = \mathbf E^{-1/2}\mathbf B \mathbf E^{-1/2}$, where $\mathbf E$ is a diagonal matrix with the same diagonal as $\mathbf B$. This is very simple and does the trick. Here are some example correlation matrices for $k={100, 50, 20, 10, 5, 1}$:
And the code:
%// FACTOR method
function S = factor(d,k)
W = randn(d,k);
S = W*W' + diag(rand(1,d));
S = diag(1./sqrt(diag(S))) * S * diag(1./sqrt(diag(S)));
end
Here is the wrapping code used to generate the figures:
d = 100; %// size of the correlation matrix
figure('Position', [100 100 1100 600])
for repetition = 1:6
S = onion(d);
%// etas = [1 10 100 1000 1e+4 1e+5];
%// S = extendedOnion(d, etas(repetition));
%// S = vine(d, etas(repetition));
%// betaparams = [50 20 10 5 2 1];
%// S = vineBeta(d, betaparams(repetition));
subplot(2,3,repetition)
%// use this to plot colormaps of S
imagesc(S, [-1 1])
axis square
title(['Eigs: ' num2str(min(eig(S)),2) '...' num2str(max(eig(S)),2) ', det=' num2str(det(S),2)])
%// use this to plot histograms of the off-diagonal elements
%// offd = S(logical(ones(size(S))-eye(size(S))));
%// hist(offd)
%// xlim([-1 1])
end
|
How to efficiently generate random positive-semidefinite correlation matrices?
A paper Generating random correlation matrices based on vines and extended
onion method by Lewandowski, Kurowicka, and Joe (LKJ), 2009, provides a unified treatment and exposition of the two efficien
|
6,054
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
An even simpler characterization is that for real matrix $A$, $A^TA$ is positive semidefinite. To see why this is the case, one only has to prove that $y^T (A^TA) y \ge 0$ for all vectors $y$ (of the right size, of course). This is trivial: $y^T (A^TA) y = (Ay)^T Ay = ||Ay||$ which is nonnegative. So in Matlab, simply try
A = randn(m,n); %here n is the desired size of the final matrix, and m > n
X = A' * A;
Depending on the application, this may not give you the distribution of eigenvalues you want; Kwak's answer is much better in that regard. The eigenvalues of X produced by this code snippet should follow the Marchenko-Pastur distribution.
For simulating the correlation matrices of stocks, say, you may want a slightly different approach:
k = 7; % # of latent dimensions;
n = 100; % # of stocks;
A = 0.01 * randn(k,n); % 'hedgeable risk'
D = diag(0.001 * randn(n,1)); % 'idiosyncratic risk'
X = A'*A + D;
ascii_hist(eig(X)); % this is my own function, you do a hist(eig(X));
-Inf <= x < -0.001 : **************** (17)
-0.001 <= x < 0.001 : ************************************************** (53)
0.001 <= x < 0.002 : ******************** (21)
0.002 <= x < 0.004 : ** (2)
0.004 <= x < 0.005 : (0)
0.005 <= x < 0.007 : * (1)
0.007 <= x < 0.008 : * (1)
0.008 <= x < 0.009 : *** (3)
0.009 <= x < 0.011 : * (1)
0.011 <= x < Inf : * (1)
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
An even simpler characterization is that for real matrix $A$, $A^TA$ is positive semidefinite. To see why this is the case, one only has to prove that $y^T (A^TA) y \ge 0$ for all vectors $y$ (of the
|
How to efficiently generate random positive-semidefinite correlation matrices?
An even simpler characterization is that for real matrix $A$, $A^TA$ is positive semidefinite. To see why this is the case, one only has to prove that $y^T (A^TA) y \ge 0$ for all vectors $y$ (of the right size, of course). This is trivial: $y^T (A^TA) y = (Ay)^T Ay = ||Ay||$ which is nonnegative. So in Matlab, simply try
A = randn(m,n); %here n is the desired size of the final matrix, and m > n
X = A' * A;
Depending on the application, this may not give you the distribution of eigenvalues you want; Kwak's answer is much better in that regard. The eigenvalues of X produced by this code snippet should follow the Marchenko-Pastur distribution.
For simulating the correlation matrices of stocks, say, you may want a slightly different approach:
k = 7; % # of latent dimensions;
n = 100; % # of stocks;
A = 0.01 * randn(k,n); % 'hedgeable risk'
D = diag(0.001 * randn(n,1)); % 'idiosyncratic risk'
X = A'*A + D;
ascii_hist(eig(X)); % this is my own function, you do a hist(eig(X));
-Inf <= x < -0.001 : **************** (17)
-0.001 <= x < 0.001 : ************************************************** (53)
0.001 <= x < 0.002 : ******************** (21)
0.002 <= x < 0.004 : ** (2)
0.004 <= x < 0.005 : (0)
0.005 <= x < 0.007 : * (1)
0.007 <= x < 0.008 : * (1)
0.008 <= x < 0.009 : *** (3)
0.009 <= x < 0.011 : * (1)
0.011 <= x < Inf : * (1)
|
How to efficiently generate random positive-semidefinite correlation matrices?
An even simpler characterization is that for real matrix $A$, $A^TA$ is positive semidefinite. To see why this is the case, one only has to prove that $y^T (A^TA) y \ge 0$ for all vectors $y$ (of the
|
6,055
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
As a variation on kwak's answer: generate a diagonal matrix $\mathbf{D}$ with random nonnegative eigenvalues from a distribution of your choice, and then perform a similarity transformation $\mathbf{A}=\mathbf{Q}\mathbf{D}\mathbf{Q}^T$ with $\mathbf{Q}$ a Haar-distributed pseudorandom orthogonal matrix.
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
As a variation on kwak's answer: generate a diagonal matrix $\mathbf{D}$ with random nonnegative eigenvalues from a distribution of your choice, and then perform a similarity transformation $\mathbf{A
|
How to efficiently generate random positive-semidefinite correlation matrices?
As a variation on kwak's answer: generate a diagonal matrix $\mathbf{D}$ with random nonnegative eigenvalues from a distribution of your choice, and then perform a similarity transformation $\mathbf{A}=\mathbf{Q}\mathbf{D}\mathbf{Q}^T$ with $\mathbf{Q}$ a Haar-distributed pseudorandom orthogonal matrix.
|
How to efficiently generate random positive-semidefinite correlation matrices?
As a variation on kwak's answer: generate a diagonal matrix $\mathbf{D}$ with random nonnegative eigenvalues from a distribution of your choice, and then perform a similarity transformation $\mathbf{A
|
6,056
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
You haven't specified a distribution for the matrices. Two common ones are the Wishart and inverse Wishart distributions. The Bartlett decomposition gives a Cholesky factorisation of a random Wishart matrix (which can also be efficiently solved to obtain a random inverse Wishart matrix).
In fact, the Cholesky space is a convenient way to generate other types of random PSD matrices, as you only have to ensure that the diagonal is non-negative.
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
You haven't specified a distribution for the matrices. Two common ones are the Wishart and inverse Wishart distributions. The Bartlett decomposition gives a Cholesky factorisation of a random Wishart
|
How to efficiently generate random positive-semidefinite correlation matrices?
You haven't specified a distribution for the matrices. Two common ones are the Wishart and inverse Wishart distributions. The Bartlett decomposition gives a Cholesky factorisation of a random Wishart matrix (which can also be efficiently solved to obtain a random inverse Wishart matrix).
In fact, the Cholesky space is a convenient way to generate other types of random PSD matrices, as you only have to ensure that the diagonal is non-negative.
|
How to efficiently generate random positive-semidefinite correlation matrices?
You haven't specified a distribution for the matrices. Two common ones are the Wishart and inverse Wishart distributions. The Bartlett decomposition gives a Cholesky factorisation of a random Wishart
|
6,057
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
The simplest method is the one above, which is a simulation of a random dataset and the computation of the Gramian. A word of caution: The resulting matrix will not be uniformly random, in that its decomposition, say $U^TSU$ will have rotations not distributed according to the Haar Measure. If you want to have "uniformly distributed" PSD matrices then you can use any of the approaches described here.
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
The simplest method is the one above, which is a simulation of a random dataset and the computation of the Gramian. A word of caution: The resulting matrix will not be uniformly random, in that its de
|
How to efficiently generate random positive-semidefinite correlation matrices?
The simplest method is the one above, which is a simulation of a random dataset and the computation of the Gramian. A word of caution: The resulting matrix will not be uniformly random, in that its decomposition, say $U^TSU$ will have rotations not distributed according to the Haar Measure. If you want to have "uniformly distributed" PSD matrices then you can use any of the approaches described here.
|
How to efficiently generate random positive-semidefinite correlation matrices?
The simplest method is the one above, which is a simulation of a random dataset and the computation of the Gramian. A word of caution: The resulting matrix will not be uniformly random, in that its de
|
6,058
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
If you'd like to have more control over your generated symmetric PSD matrix, e.g. generate a synthetic validation dataset, you have a number of parameters available.
A symmetric PSD matrix corresponds to a hyper-ellipse in the N-dimensional space, with all the related degrees of freedom:
Rotations.
Lengths of axes.
So, for a 2-dimensional matrix (i.e. 2d ellipse), you'll have 1 rotation + 2 axes = 3 parameters.
If rotations bring to mind Orthogonal matrices, its a correct train of though, since the construction is again $\Sigma=ODO^T$, with $\Sigma$ being the produced Sym.PSD matrix, $O$ the rotation matrix (which is orthogonal), and $D$ the diagonal matrix, whose diagonal elements will control the length of the axes of the ellipse.
The following Matlab code plots 16 2dimensional Gaussian-distributed datasets based on $\Sigma$, with an increasing angle. The code for random generation of parameters is in comments.
figure;
mu = [0,0];
for i=1:16
subplot(4,4,i)
theta = (i/16)*2*pi; % theta = rand*2*pi;
U=[cos(theta), -sin(theta); sin(theta) cos(theta)];
% The diagonal's elements control the lengths of the axes
D = [10, 0; 0, 1]; % D = diag(rand(2,1));
sigma = U*D*U';
data = mvnrnd(mu,sigma,1000);
plot(data(:,1),data(:,2),'+'); axis([-6 6 -6 6]); hold on;
end
For more dimensions, the Diagonal matrix is straight-forward (as above), and the $U$ should derive from multiplication of the rotation matrices.
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
If you'd like to have more control over your generated symmetric PSD matrix, e.g. generate a synthetic validation dataset, you have a number of parameters available.
A symmetric PSD matrix corresponds
|
How to efficiently generate random positive-semidefinite correlation matrices?
If you'd like to have more control over your generated symmetric PSD matrix, e.g. generate a synthetic validation dataset, you have a number of parameters available.
A symmetric PSD matrix corresponds to a hyper-ellipse in the N-dimensional space, with all the related degrees of freedom:
Rotations.
Lengths of axes.
So, for a 2-dimensional matrix (i.e. 2d ellipse), you'll have 1 rotation + 2 axes = 3 parameters.
If rotations bring to mind Orthogonal matrices, its a correct train of though, since the construction is again $\Sigma=ODO^T$, with $\Sigma$ being the produced Sym.PSD matrix, $O$ the rotation matrix (which is orthogonal), and $D$ the diagonal matrix, whose diagonal elements will control the length of the axes of the ellipse.
The following Matlab code plots 16 2dimensional Gaussian-distributed datasets based on $\Sigma$, with an increasing angle. The code for random generation of parameters is in comments.
figure;
mu = [0,0];
for i=1:16
subplot(4,4,i)
theta = (i/16)*2*pi; % theta = rand*2*pi;
U=[cos(theta), -sin(theta); sin(theta) cos(theta)];
% The diagonal's elements control the lengths of the axes
D = [10, 0; 0, 1]; % D = diag(rand(2,1));
sigma = U*D*U';
data = mvnrnd(mu,sigma,1000);
plot(data(:,1),data(:,2),'+'); axis([-6 6 -6 6]); hold on;
end
For more dimensions, the Diagonal matrix is straight-forward (as above), and the $U$ should derive from multiplication of the rotation matrices.
|
How to efficiently generate random positive-semidefinite correlation matrices?
If you'd like to have more control over your generated symmetric PSD matrix, e.g. generate a synthetic validation dataset, you have a number of parameters available.
A symmetric PSD matrix corresponds
|
6,059
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
If you want to sample random correlation matrices from an empirical distribution, you can try to use generative models from machine learning to do that.
One such example is CorrGAN: Sampling Realistic Financial Correlation Matrices Using Generative Adversarial Networks
The basic idea is to fit generative adversarial networks (or variational autoencoders) to a set of empirical correlation matrices (having certain properties that are hard to capture/generate mathematically).
Then, you can use these models to sample as much random correlation matrices as you want that verify the properties of the empirical ones.
Depending on which networks you use, you may want to project the output (which may be not totally PSD) onto the set of correlation matrices (with the Higham projection for example).
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
If you want to sample random correlation matrices from an empirical distribution, you can try to use generative models from machine learning to do that.
One such example is CorrGAN: Sampling Realistic
|
How to efficiently generate random positive-semidefinite correlation matrices?
If you want to sample random correlation matrices from an empirical distribution, you can try to use generative models from machine learning to do that.
One such example is CorrGAN: Sampling Realistic Financial Correlation Matrices Using Generative Adversarial Networks
The basic idea is to fit generative adversarial networks (or variational autoencoders) to a set of empirical correlation matrices (having certain properties that are hard to capture/generate mathematically).
Then, you can use these models to sample as much random correlation matrices as you want that verify the properties of the empirical ones.
Depending on which networks you use, you may want to project the output (which may be not totally PSD) onto the set of correlation matrices (with the Higham projection for example).
|
How to efficiently generate random positive-semidefinite correlation matrices?
If you want to sample random correlation matrices from an empirical distribution, you can try to use generative models from machine learning to do that.
One such example is CorrGAN: Sampling Realistic
|
6,060
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
you can create an arbitrary covariance matrix from the Wishart distribution using the stats function rWishart (included in base R) and then transform it to a correlation matrix
p <- 4
S <- drop(rWishart(1,p,diag(p)))
S * (diag(S)^(-1/2) %o% diag(S)^(-1/2))
The Wishart distribution takes two parameters: the degrees of freedom $\nu$ and the scale matrix $\Sigma$. To understand how these influence the result, condier $X_i \overset{iid}{\sim} N_p(0,\Sigma)$,then
$$
S = \sum\limits_{i=1}^\nu X_iX_i' \sim W_p(\nu,\Sigma)
$$
That is, S follows a Wishart distribution on $p\times p$ matrices with $\nu$ degrees of freedom and $\Sigma$ as scale matrix. As seen, if $\nu$ is larger than $p$, then $S$ will be positive definite a.s.(P). Furthermore,
$$
E(S) = \nu \Sigma
$$
which means that on average, the random draws S will approach a value proportional to the true population parameters $\Sigma$ in probability. This rate of convergence depends on the value of $\nu$, so if $p$ is very large, try to keep $\nu$ close to $p$, otherwise the random draws would be close to each other.
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
you can create an arbitrary covariance matrix from the Wishart distribution using the stats function rWishart (included in base R) and then transform it to a correlation matrix
p <- 4
S <- drop(rWisha
|
How to efficiently generate random positive-semidefinite correlation matrices?
you can create an arbitrary covariance matrix from the Wishart distribution using the stats function rWishart (included in base R) and then transform it to a correlation matrix
p <- 4
S <- drop(rWishart(1,p,diag(p)))
S * (diag(S)^(-1/2) %o% diag(S)^(-1/2))
The Wishart distribution takes two parameters: the degrees of freedom $\nu$ and the scale matrix $\Sigma$. To understand how these influence the result, condier $X_i \overset{iid}{\sim} N_p(0,\Sigma)$,then
$$
S = \sum\limits_{i=1}^\nu X_iX_i' \sim W_p(\nu,\Sigma)
$$
That is, S follows a Wishart distribution on $p\times p$ matrices with $\nu$ degrees of freedom and $\Sigma$ as scale matrix. As seen, if $\nu$ is larger than $p$, then $S$ will be positive definite a.s.(P). Furthermore,
$$
E(S) = \nu \Sigma
$$
which means that on average, the random draws S will approach a value proportional to the true population parameters $\Sigma$ in probability. This rate of convergence depends on the value of $\nu$, so if $p$ is very large, try to keep $\nu$ close to $p$, otherwise the random draws would be close to each other.
|
How to efficiently generate random positive-semidefinite correlation matrices?
you can create an arbitrary covariance matrix from the Wishart distribution using the stats function rWishart (included in base R) and then transform it to a correlation matrix
p <- 4
S <- drop(rWisha
|
6,061
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
A cheap and cheerful approach I've used for testing is to generate m N(0,1) n-vectors V[k] and then use P = d*I + Sum{ V[k]*V[k]'} as an nxn psd matrix. With m < n this will be singular for d=0, and for small d will have high condition number.
|
How to efficiently generate random positive-semidefinite correlation matrices?
|
A cheap and cheerful approach I've used for testing is to generate m N(0,1) n-vectors V[k] and then use P = d*I + Sum{ V[k]*V[k]'} as an nxn psd matrix. With m < n this will be singular for d=0, and f
|
How to efficiently generate random positive-semidefinite correlation matrices?
A cheap and cheerful approach I've used for testing is to generate m N(0,1) n-vectors V[k] and then use P = d*I + Sum{ V[k]*V[k]'} as an nxn psd matrix. With m < n this will be singular for d=0, and for small d will have high condition number.
|
How to efficiently generate random positive-semidefinite correlation matrices?
A cheap and cheerful approach I've used for testing is to generate m N(0,1) n-vectors V[k] and then use P = d*I + Sum{ V[k]*V[k]'} as an nxn psd matrix. With m < n this will be singular for d=0, and f
|
6,062
|
"Model failed to converge" warning in lmer()
|
"Solving" the issue you experience in the sense of not receiving warnings about failed convergence is rather straightforward: you do not use the default BOBYQA optimiser but instead you opt to use the Nelder-Mead optimisation routine used by default in earlier 1.0.x previous versions. Or you install the package optimx so you can directly an L-BFGS-B routine or nlminb (same as lme4 versions prior to ver. 1). For example:
m1 = lmer(effect~duration+(1+duration|sites)+(1+duration|season),
data = dat1, REML = FALSE,
control = lmerControl(optimizer ="Nelder_Mead")
library(optimx)
m1 = lmer(effect~duration+(1+duration|sites)+(1+duration|season),
data = dat1, REML = FALSE,
control = lmerControl(
optimizer ='optimx', optCtrl=list(method='L-BFGS-B')))
m1 = lmer(effect~duration+(1+duration|sites)+(1+duration|season),
data = dat1, REML = FALSE,
control = lmerControl(
optimizer ='optimx', optCtrl=list(method='nlminb')))
all work fine (no warnings). The interesting questions are:
why you got these warnings to begin with and
why when you used REML = TRUE you got no warnings.
Succinctly, 1. you received those warnings because you defined duration both as a fixed effect as well as random slope for the factor sites as well as season. The model effectively ran-out of the degrees of freedom to estimate the correlations between the slopes and the intercepts you defined. If you used a marginally simpler model like:
m1 = lmer(effect~duration+ (1+duration|sites) + (0+duration|season) + (1|season),
data=dat1, REML = FALSE)
you would experience no convergence issues. This model would effectively estimate uncorrelated random intercepts and random slopes for each season.
In addition, 2. when you defined REML = FALSE you used the Maximum Likelihood estimated instead of the Restricted Maximum Likelihood one. The REML estimates try to "factor out" the influence of the fixed effects $X$ before moving into finding the optimal random-effect variance structure (see the thread "What is "restricted maximum likelihood" and when should it be used?" for more detailed information on the matter). Computationally this procedure is essentially done by multiplying both parts of the original LME model equation $y = X\beta + Z\gamma + \epsilon$ by a matrix $K$ such that $KX = 0$, i.e. you change both the original $y$ to $Ky$ as well as the $Z$ to $KZ$. I strongly suspect that this effected the condition number of the design matrix $Z$ and as such help you out of the numerical hard-place you found yourself in the first place.
A final note is that I am not sure whether it makes sense to use season as a random effect to begin with. After all there are only so many seasons so you might as well treat them as fixed effects.
|
"Model failed to converge" warning in lmer()
|
"Solving" the issue you experience in the sense of not receiving warnings about failed convergence is rather straightforward: you do not use the default BOBYQA optimiser but instead you opt to use the
|
"Model failed to converge" warning in lmer()
"Solving" the issue you experience in the sense of not receiving warnings about failed convergence is rather straightforward: you do not use the default BOBYQA optimiser but instead you opt to use the Nelder-Mead optimisation routine used by default in earlier 1.0.x previous versions. Or you install the package optimx so you can directly an L-BFGS-B routine or nlminb (same as lme4 versions prior to ver. 1). For example:
m1 = lmer(effect~duration+(1+duration|sites)+(1+duration|season),
data = dat1, REML = FALSE,
control = lmerControl(optimizer ="Nelder_Mead")
library(optimx)
m1 = lmer(effect~duration+(1+duration|sites)+(1+duration|season),
data = dat1, REML = FALSE,
control = lmerControl(
optimizer ='optimx', optCtrl=list(method='L-BFGS-B')))
m1 = lmer(effect~duration+(1+duration|sites)+(1+duration|season),
data = dat1, REML = FALSE,
control = lmerControl(
optimizer ='optimx', optCtrl=list(method='nlminb')))
all work fine (no warnings). The interesting questions are:
why you got these warnings to begin with and
why when you used REML = TRUE you got no warnings.
Succinctly, 1. you received those warnings because you defined duration both as a fixed effect as well as random slope for the factor sites as well as season. The model effectively ran-out of the degrees of freedom to estimate the correlations between the slopes and the intercepts you defined. If you used a marginally simpler model like:
m1 = lmer(effect~duration+ (1+duration|sites) + (0+duration|season) + (1|season),
data=dat1, REML = FALSE)
you would experience no convergence issues. This model would effectively estimate uncorrelated random intercepts and random slopes for each season.
In addition, 2. when you defined REML = FALSE you used the Maximum Likelihood estimated instead of the Restricted Maximum Likelihood one. The REML estimates try to "factor out" the influence of the fixed effects $X$ before moving into finding the optimal random-effect variance structure (see the thread "What is "restricted maximum likelihood" and when should it be used?" for more detailed information on the matter). Computationally this procedure is essentially done by multiplying both parts of the original LME model equation $y = X\beta + Z\gamma + \epsilon$ by a matrix $K$ such that $KX = 0$, i.e. you change both the original $y$ to $Ky$ as well as the $Z$ to $KZ$. I strongly suspect that this effected the condition number of the design matrix $Z$ and as such help you out of the numerical hard-place you found yourself in the first place.
A final note is that I am not sure whether it makes sense to use season as a random effect to begin with. After all there are only so many seasons so you might as well treat them as fixed effects.
|
"Model failed to converge" warning in lmer()
"Solving" the issue you experience in the sense of not receiving warnings about failed convergence is rather straightforward: you do not use the default BOBYQA optimiser but instead you opt to use the
|
6,063
|
"Model failed to converge" warning in lmer()
|
The question is statistical rather than technical. Actually, I used a random effect model instead of a fixed effect one.None of the factors, I think, should be treated as the random factor as we need at least 5 or 6 levels or replicates to treat a factor as random effect (see here What is the minimum recommended number of groups for a random effects factor?).
The above dataset contains only triplicate samples/site/season which is insufficient for a random effect model.In the data set the duration, 4-day and 7-day belong to two separate parallel experiments run under the same time.
So spiting the data set by duration (4-day and 7-day) and performing a 2-way anova for each duration with season and sites as the factors would be sufficient to model the effect (response variable) here. The model should be the following:
lm(day_4_effect~sites*season, data=dat1)
lm(day_7_effect~sites*season, data=dat1)
Thanks to Bodo Winter (http://www.bodowinter.com/tutorial/bw_LME_tutorial2.pdf) and @usεr11852 who helped me solve the issue.
|
"Model failed to converge" warning in lmer()
|
The question is statistical rather than technical. Actually, I used a random effect model instead of a fixed effect one.None of the factors, I think, should be treated as the random factor as we need
|
"Model failed to converge" warning in lmer()
The question is statistical rather than technical. Actually, I used a random effect model instead of a fixed effect one.None of the factors, I think, should be treated as the random factor as we need at least 5 or 6 levels or replicates to treat a factor as random effect (see here What is the minimum recommended number of groups for a random effects factor?).
The above dataset contains only triplicate samples/site/season which is insufficient for a random effect model.In the data set the duration, 4-day and 7-day belong to two separate parallel experiments run under the same time.
So spiting the data set by duration (4-day and 7-day) and performing a 2-way anova for each duration with season and sites as the factors would be sufficient to model the effect (response variable) here. The model should be the following:
lm(day_4_effect~sites*season, data=dat1)
lm(day_7_effect~sites*season, data=dat1)
Thanks to Bodo Winter (http://www.bodowinter.com/tutorial/bw_LME_tutorial2.pdf) and @usεr11852 who helped me solve the issue.
|
"Model failed to converge" warning in lmer()
The question is statistical rather than technical. Actually, I used a random effect model instead of a fixed effect one.None of the factors, I think, should be treated as the random factor as we need
|
6,064
|
"Model failed to converge" warning in lmer()
|
I've had success with the change of optimizer suggested here in larger samples, but this fix does not always work in relatively small samples in my experience. Matuschek et al., 2017 (Journal of Memory and Language) note that failed model convergence can also result from over specification of the random effects structure when the data cannot support maximal or near-maximal models. In this case, you will need to simplify your random effects structure, which Matuschek et al., 2017 offer some suggestions on. At least assuming I've interpreted their work correctly, mixed effects models are confusing.
|
"Model failed to converge" warning in lmer()
|
I've had success with the change of optimizer suggested here in larger samples, but this fix does not always work in relatively small samples in my experience. Matuschek et al., 2017 (Journal of Memor
|
"Model failed to converge" warning in lmer()
I've had success with the change of optimizer suggested here in larger samples, but this fix does not always work in relatively small samples in my experience. Matuschek et al., 2017 (Journal of Memory and Language) note that failed model convergence can also result from over specification of the random effects structure when the data cannot support maximal or near-maximal models. In this case, you will need to simplify your random effects structure, which Matuschek et al., 2017 offer some suggestions on. At least assuming I've interpreted their work correctly, mixed effects models are confusing.
|
"Model failed to converge" warning in lmer()
I've had success with the change of optimizer suggested here in larger samples, but this fix does not always work in relatively small samples in my experience. Matuschek et al., 2017 (Journal of Memor
|
6,065
|
L1 regression estimates median whereas L2 regression estimates mean?
|
There is a simple geometric explanation for why the L1 loss function yields the median.
Recall that we are working in one dimension, so imagine a number line spreading horizontally. Plot each of the data points on the number line. Put your finger somewhere on the line; your finger will be your current candidate estimate.
Suppose you move your finger a little bit to the right, say $\delta$ units to the right. What happens to the total loss? Well, if your finger was between two data points, and you move it across a data point, you've increased the total loss by $\delta$ for each data point to the left of your finger, and decreased it by $\delta$ for each data point to the right of your finger. So, if there are more data points to the right of your finger than there are to the left, moving your finger to the right decreases the total loss. In other words, if more than half of the data points are to the right of your finger, you should move your finger to the right.
This leads to you moving your finger towards a spot where half of the data points are to the left of that spot, and half are on the right. That spot is the median.
That's L1 and the median. Unfortunately, I don't have a similar, "all intuition, no algebra" explanation for L2 and the mean.
|
L1 regression estimates median whereas L2 regression estimates mean?
|
There is a simple geometric explanation for why the L1 loss function yields the median.
Recall that we are working in one dimension, so imagine a number line spreading horizontally. Plot each of the
|
L1 regression estimates median whereas L2 regression estimates mean?
There is a simple geometric explanation for why the L1 loss function yields the median.
Recall that we are working in one dimension, so imagine a number line spreading horizontally. Plot each of the data points on the number line. Put your finger somewhere on the line; your finger will be your current candidate estimate.
Suppose you move your finger a little bit to the right, say $\delta$ units to the right. What happens to the total loss? Well, if your finger was between two data points, and you move it across a data point, you've increased the total loss by $\delta$ for each data point to the left of your finger, and decreased it by $\delta$ for each data point to the right of your finger. So, if there are more data points to the right of your finger than there are to the left, moving your finger to the right decreases the total loss. In other words, if more than half of the data points are to the right of your finger, you should move your finger to the right.
This leads to you moving your finger towards a spot where half of the data points are to the left of that spot, and half are on the right. That spot is the median.
That's L1 and the median. Unfortunately, I don't have a similar, "all intuition, no algebra" explanation for L2 and the mean.
|
L1 regression estimates median whereas L2 regression estimates mean?
There is a simple geometric explanation for why the L1 loss function yields the median.
Recall that we are working in one dimension, so imagine a number line spreading horizontally. Plot each of the
|
6,066
|
L1 regression estimates median whereas L2 regression estimates mean?
|
This explanation is a summation of muratoa and Yves's comments on D.W.'s answer. Though it is based on calculus, I found it straightforward and easy to understand.
Assuming we have $y_1, y_2, ... y_k$ and to want get a new estimate $\beta$ based on them. The smallest loss is obtained when we find $\beta$ which makes the derivative of the loss to zero.
L1 loss
$$L1=\frac{1}{k}\sum_{i=1}^k|y_i-\beta|$$
$$\frac{\partial L_1}{\partial\beta}=-\frac{1}{k}\sum_{i=1}^k sgn(y_i-\beta)$$
$sgn(y_i-\beta)$ is 1 when $y_i>\beta$, -1 when $y_i<\beta$. The derivative equals to 0 when there is the same number of positive and negative terms among the $y_i-\beta$, which means $\beta$ should be the median of $y_i$.
L2 loss
$$L2=\frac{1}{k}\sum_{i=1}^k(y_i-\beta)^2$$
$$\frac{\partial L_2}{\partial\beta}=-\frac{2}{k}\sum_{i=1}^k(y_i-\beta)$$
$$\frac{\partial L_2}{\partial\beta}=0\rightarrow\beta=\frac{1}{k}\sum_{i=1}^k y_i$$
So to minimize L2 loss, $\beta$ should be the mean of $y_i$.
|
L1 regression estimates median whereas L2 regression estimates mean?
|
This explanation is a summation of muratoa and Yves's comments on D.W.'s answer. Though it is based on calculus, I found it straightforward and easy to understand.
Assuming we have $y_1, y_2, ... y_k$
|
L1 regression estimates median whereas L2 regression estimates mean?
This explanation is a summation of muratoa and Yves's comments on D.W.'s answer. Though it is based on calculus, I found it straightforward and easy to understand.
Assuming we have $y_1, y_2, ... y_k$ and to want get a new estimate $\beta$ based on them. The smallest loss is obtained when we find $\beta$ which makes the derivative of the loss to zero.
L1 loss
$$L1=\frac{1}{k}\sum_{i=1}^k|y_i-\beta|$$
$$\frac{\partial L_1}{\partial\beta}=-\frac{1}{k}\sum_{i=1}^k sgn(y_i-\beta)$$
$sgn(y_i-\beta)$ is 1 when $y_i>\beta$, -1 when $y_i<\beta$. The derivative equals to 0 when there is the same number of positive and negative terms among the $y_i-\beta$, which means $\beta$ should be the median of $y_i$.
L2 loss
$$L2=\frac{1}{k}\sum_{i=1}^k(y_i-\beta)^2$$
$$\frac{\partial L_2}{\partial\beta}=-\frac{2}{k}\sum_{i=1}^k(y_i-\beta)$$
$$\frac{\partial L_2}{\partial\beta}=0\rightarrow\beta=\frac{1}{k}\sum_{i=1}^k y_i$$
So to minimize L2 loss, $\beta$ should be the mean of $y_i$.
|
L1 regression estimates median whereas L2 regression estimates mean?
This explanation is a summation of muratoa and Yves's comments on D.W.'s answer. Though it is based on calculus, I found it straightforward and easy to understand.
Assuming we have $y_1, y_2, ... y_k$
|
6,067
|
L1 regression estimates median whereas L2 regression estimates mean?
|
In addition to the already-posted answers (which have been very helpful to me!), there is a geometric explanation for the connection between the L2 norm and the mean.
To use the same notation as chefwen, the formula for L2 loss is:
$$ L2 = \frac{1}{k} \sum^{k}_{i=1} (y_i - \beta)^2$$
We wish to find the value of $\beta$ which minimizes $L2$. Notice that this is equivalent to minimizing the following, since multiplying by $k$ and taking the square root both preserve order:
$$ \sqrt { \sum^{k}_{i=1} (y_i - \beta)^2 }$$
If you consider the data vector $y$ as a point in $k$-dimensional space, this formula calculates the Euclidean distance between the point $y$ and the point $\vec{\beta} = (\beta, \beta, ..., \beta)$.
So the problem is to find the value $\beta$ which minimizes the Euclidean distance between the points $y$ and $\vec{\beta}$. Since the possible values of $\vec{\beta}$ all lie on the line $\vec{1} = (1, 1, ..., 1)$ by definition, this is equivalent to finding the vector projection of $y$ onto $\vec{1}$.
It's only really possible to visualize this when $k = 2$, but here is an example where $y = (2, 6)$. As shown, projecting onto $\vec{1}$ yields $(4, 4)$ as we expect.
To show that this projection always yields the mean (including when $k > 2$), we can apply the formula for projection:
$$
\begin{alignat}{2}
\vec{\beta} &= \operatorname{proj}_{\vec{1}}{y} \\
&= \frac{y \cdot \vec{1}}{|\vec{1}|^2}\vec{1} \\
\beta &= \frac{\sum^k_{i=1} y_i}{k}
\end{alignat}
$$
|
L1 regression estimates median whereas L2 regression estimates mean?
|
In addition to the already-posted answers (which have been very helpful to me!), there is a geometric explanation for the connection between the L2 norm and the mean.
To use the same notation as chefw
|
L1 regression estimates median whereas L2 regression estimates mean?
In addition to the already-posted answers (which have been very helpful to me!), there is a geometric explanation for the connection between the L2 norm and the mean.
To use the same notation as chefwen, the formula for L2 loss is:
$$ L2 = \frac{1}{k} \sum^{k}_{i=1} (y_i - \beta)^2$$
We wish to find the value of $\beta$ which minimizes $L2$. Notice that this is equivalent to minimizing the following, since multiplying by $k$ and taking the square root both preserve order:
$$ \sqrt { \sum^{k}_{i=1} (y_i - \beta)^2 }$$
If you consider the data vector $y$ as a point in $k$-dimensional space, this formula calculates the Euclidean distance between the point $y$ and the point $\vec{\beta} = (\beta, \beta, ..., \beta)$.
So the problem is to find the value $\beta$ which minimizes the Euclidean distance between the points $y$ and $\vec{\beta}$. Since the possible values of $\vec{\beta}$ all lie on the line $\vec{1} = (1, 1, ..., 1)$ by definition, this is equivalent to finding the vector projection of $y$ onto $\vec{1}$.
It's only really possible to visualize this when $k = 2$, but here is an example where $y = (2, 6)$. As shown, projecting onto $\vec{1}$ yields $(4, 4)$ as we expect.
To show that this projection always yields the mean (including when $k > 2$), we can apply the formula for projection:
$$
\begin{alignat}{2}
\vec{\beta} &= \operatorname{proj}_{\vec{1}}{y} \\
&= \frac{y \cdot \vec{1}}{|\vec{1}|^2}\vec{1} \\
\beta &= \frac{\sum^k_{i=1} y_i}{k}
\end{alignat}
$$
|
L1 regression estimates median whereas L2 regression estimates mean?
In addition to the already-posted answers (which have been very helpful to me!), there is a geometric explanation for the connection between the L2 norm and the mean.
To use the same notation as chefw
|
6,068
|
L1 regression estimates median whereas L2 regression estimates mean?
|
Adding to D.W.'s answer with an even more practical example (for L2 loss function as well):
Imagine a small village made of 4 houses close to each other (e.g. 10 meters). At 1 kilometer from those, you have another very isolated house. Now, you arrive in that town and want to build your own house somewhere. You want to live close to the other houses and be friend with everybody. Consider those two alternative scenarios:
You decide to be at the location where the average distance to any house is the smallest (i.e. minimizing a L1 loss function).
If you put your house at the center of the village, you will be
around 10 meters away from 4 houses and 1 kilometer away from one
house, which gives you an average distance of about 200 meters
(10+10+10+10+1000 / 5).
If you place your house 500 meters away from
the village, you will be around 500 meters away from 5 houses, which
gives you an average distance of 500 meters.
If you place your house next to the isolated house, you will be 1km away from the village (4 houses) and around 10 meters away from 1 house, which gives you an average distance of about 800 meters.
So the lowest average distance of 100 meters is reached by building your house in the village. More specifically, you will build your house in the middle of these 4 houses to gain a few more meters of average distance. And it turns out that this point is the "median point", that you would have obtained similarly using the median formula.
You decide to take a democratic approach. You ask each of your five future neighbors their preferred location for your new house. They all like you and want you to live close to them. So they all state their preferred location to be the spot just next to their own house. You take the average of all the voted locations of your five neighbors, and the result is "200 meters away from the village" (average of the votes: 0+0+0+0+1000/5 = 200), which is the "mean point" of the 5 houses, that you would have obtained similarly using the mean formula. And this location turns out to be exactly the same that mimimizes the sum of squared distances (i.e. L2 loss function). Let's just do the math to see it:
At this location, the sum of squared distances is: 200^2 + 200^2 + 200^2 + 200^2 + 800^2 = 800 000
If we build the house in the center of the village, our sum of squared distances would be: 0^2 + 0^2 + 0^2 + 0^2 + 1000^2 = 1 000 000
If we build build the house at 100 meters away from the village (like in 1), the sum of squared distances is: 100^2 + 100^2 + 100^2 + 100^2 + 900^2 = 850 000
If we build the house at 100 meters away from the isolated house, the sum of squared distances is: 900^2 + 900^2 + 900^2 + 900^2 + 100^2 = 3 250 000
So yes, it is interesting to notice that, a bit counter-intuitively, when we minimize the sum of the distances, we don't end up being in the "middle" in the sense of the mean, but in the sense of the median. This is part of the reason why OLS, one of the most popular regression models, uses squared errors rather than absolute errors.
|
L1 regression estimates median whereas L2 regression estimates mean?
|
Adding to D.W.'s answer with an even more practical example (for L2 loss function as well):
Imagine a small village made of 4 houses close to each other (e.g. 10 meters). At 1 kilometer from those, yo
|
L1 regression estimates median whereas L2 regression estimates mean?
Adding to D.W.'s answer with an even more practical example (for L2 loss function as well):
Imagine a small village made of 4 houses close to each other (e.g. 10 meters). At 1 kilometer from those, you have another very isolated house. Now, you arrive in that town and want to build your own house somewhere. You want to live close to the other houses and be friend with everybody. Consider those two alternative scenarios:
You decide to be at the location where the average distance to any house is the smallest (i.e. minimizing a L1 loss function).
If you put your house at the center of the village, you will be
around 10 meters away from 4 houses and 1 kilometer away from one
house, which gives you an average distance of about 200 meters
(10+10+10+10+1000 / 5).
If you place your house 500 meters away from
the village, you will be around 500 meters away from 5 houses, which
gives you an average distance of 500 meters.
If you place your house next to the isolated house, you will be 1km away from the village (4 houses) and around 10 meters away from 1 house, which gives you an average distance of about 800 meters.
So the lowest average distance of 100 meters is reached by building your house in the village. More specifically, you will build your house in the middle of these 4 houses to gain a few more meters of average distance. And it turns out that this point is the "median point", that you would have obtained similarly using the median formula.
You decide to take a democratic approach. You ask each of your five future neighbors their preferred location for your new house. They all like you and want you to live close to them. So they all state their preferred location to be the spot just next to their own house. You take the average of all the voted locations of your five neighbors, and the result is "200 meters away from the village" (average of the votes: 0+0+0+0+1000/5 = 200), which is the "mean point" of the 5 houses, that you would have obtained similarly using the mean formula. And this location turns out to be exactly the same that mimimizes the sum of squared distances (i.e. L2 loss function). Let's just do the math to see it:
At this location, the sum of squared distances is: 200^2 + 200^2 + 200^2 + 200^2 + 800^2 = 800 000
If we build the house in the center of the village, our sum of squared distances would be: 0^2 + 0^2 + 0^2 + 0^2 + 1000^2 = 1 000 000
If we build build the house at 100 meters away from the village (like in 1), the sum of squared distances is: 100^2 + 100^2 + 100^2 + 100^2 + 900^2 = 850 000
If we build the house at 100 meters away from the isolated house, the sum of squared distances is: 900^2 + 900^2 + 900^2 + 900^2 + 100^2 = 3 250 000
So yes, it is interesting to notice that, a bit counter-intuitively, when we minimize the sum of the distances, we don't end up being in the "middle" in the sense of the mean, but in the sense of the median. This is part of the reason why OLS, one of the most popular regression models, uses squared errors rather than absolute errors.
|
L1 regression estimates median whereas L2 regression estimates mean?
Adding to D.W.'s answer with an even more practical example (for L2 loss function as well):
Imagine a small village made of 4 houses close to each other (e.g. 10 meters). At 1 kilometer from those, yo
|
6,069
|
Why law of large numbers does not apply in the case of Apple share price?
|
Here is the rub: Apple is so big, it’s running up against the law of
large numbers.
Also known as the golden theorem, with a proof attributed to the
17th-century Swiss mathematician Jacob Bernoulli, the law states that
a variable will revert to a mean over a large sample of results. In
the case of the largest companies, it suggests that high earnings
growth and a rapid rise in share price will slow as those companies
grow ever larger.
This muddled jumble actually refers to three different phenomena!
The (various) Laws of Large Numbers are fundamental in probability theory for characterizing situations where it is reasonable to expect large samples to give increasingly better information about a process or population being sampled. Indeed, Jacob Bernoulli was the first to recognize the need to state and prove such a theorem, which appeared in his posthumous Ars Conjectandi in 1713 (edited by nephew Nicholas Bernoulli).
There is no apparent valid application of such a law to Apple's growth.
Regression toward the mean was first recognized by Francis Galton in the 1880's. It has often been underappreciated among business analysts, however. For example, at the beginning of 1933 (during the depths of a Great Depression), Horace Secrist published his magnum opus, the Triumph of Mediocrity in Business. In it, he copiously examined business time series and found, in every case, evidence of regression toward the mean. But, failing to recognize this as an ineluctable mathematical phenomenon, he maintained that he had uncovered a basic truth of business development! This fallacy of mistaking a purely mathematical pattern for the result of some underlying force or tendency (now often called the "regression fallacy") is reminiscent of the quoted passage.
(It is noteworthy that Secrist was a prominent statistician, author of one of the most popular statistics textbooks published at the time. On JSTOR, you can find a lacerating review of Triumph... by Harold Hotelling published in JASA in late 1933. In a subsequent exchange of letters with Secrist, Hotelling wrote
My review ... was chiefly devoted to warning readers not to conclude that business firms have a tendency to become mediocre ... To "prove" such a mathematical result by a costly and prolonged numerical study ... is analogous to proving the multiplication table by arranging elephants in rows and columns, and then doing the same for numerous other kinds of animals. The performance, though perhaps entertaining, and having a certain pedagogical value, is not an important contribution either to zoology or to mathematics.
[JASA Vol. 29, No. 186 (June 1934), pp 198 and 199].)
The NY Times passage seems to make the same mistake with Apple's business data.
If we read on in the article, however, we soon uncover the author's intended meaning:
If Apple’s share price grew even 20 percent a year for the next decade, which is far below its current blistering pace, its \$500 billion market capitalization would be more than \$3 trillion by 2022.
This, of course, is a statement about extrapolation of exponential growth. As such it contains echoes of Malthusian population predictions. The hazards of extrapolation are not confined to exponential growth, however. Mark Twain (Samuel Clements) pilloried wanton extrapolators in Life on the Mississippi (1883, chapter 17):
Now, if I wanted to be one of those ponderous scientific people, and 'let on' to prove ... what will occur in the far future by what has occurred in late years, what an opportunity is here! ... Please observe:--
In the space of one hundred and seventy-six years the Lower Mississippi has shortened itself two hundred and forty-two miles. That is an average of a trifle over one mile and a third per year. Therefore, any calm person, who is not blind or idiotic, can see that in the “Old Oolitic Silurian Period,” just a million years ago next November, the Lower Mississippi River was upwards of one million three hundred thousand miles long, and stuck out over the Gulf of Mexico like a fishing-rod. And by the same token any person can see that seven hundred and forty-two years from now the Lower Mississippi will be only a mile and threequarters long, and Cairo and New Orleans will have joined their streets together, and be plodding comfortably along under a single mayor and a mutual board of aldermen. There is something fascinating about science. One gets such wholesale returns of conjecture out of such a trifling investment of fact.”
(Emphasis added.) Twain's satire compares favorably to the article's quotation of business analyst Robert Cihra:
If you extrapolate far enough out into the future, to sustain that growth Apple would have to sell an iPhone to every man, woman, child, animal and rock on the planet.
(Unfortunately, it appears Cihra does not heed his own advice: he rates this stock a "buy." He might be right, not on the merits, but by virtue of the greater fool theory.)
If we take the article to mean "beware of extrapolating previous growth into the future," we will get much out of it. Investors who think this company is a good buy because its PE ratio is low (which includes several of the notable money managers quoted in the article) are no better than the "ponderous scientific people" Twain skewered over a century ago.
A better acquaintance with Bernoulli, Hotelling, and Twain would have improved the accuracy and readability of this article, but in the end it seems to have gotten the message right.
|
Why law of large numbers does not apply in the case of Apple share price?
|
Here is the rub: Apple is so big, it’s running up against the law of
large numbers.
Also known as the golden theorem, with a proof attributed to the
17th-century Swiss mathematician Jacob Bernoull
|
Why law of large numbers does not apply in the case of Apple share price?
Here is the rub: Apple is so big, it’s running up against the law of
large numbers.
Also known as the golden theorem, with a proof attributed to the
17th-century Swiss mathematician Jacob Bernoulli, the law states that
a variable will revert to a mean over a large sample of results. In
the case of the largest companies, it suggests that high earnings
growth and a rapid rise in share price will slow as those companies
grow ever larger.
This muddled jumble actually refers to three different phenomena!
The (various) Laws of Large Numbers are fundamental in probability theory for characterizing situations where it is reasonable to expect large samples to give increasingly better information about a process or population being sampled. Indeed, Jacob Bernoulli was the first to recognize the need to state and prove such a theorem, which appeared in his posthumous Ars Conjectandi in 1713 (edited by nephew Nicholas Bernoulli).
There is no apparent valid application of such a law to Apple's growth.
Regression toward the mean was first recognized by Francis Galton in the 1880's. It has often been underappreciated among business analysts, however. For example, at the beginning of 1933 (during the depths of a Great Depression), Horace Secrist published his magnum opus, the Triumph of Mediocrity in Business. In it, he copiously examined business time series and found, in every case, evidence of regression toward the mean. But, failing to recognize this as an ineluctable mathematical phenomenon, he maintained that he had uncovered a basic truth of business development! This fallacy of mistaking a purely mathematical pattern for the result of some underlying force or tendency (now often called the "regression fallacy") is reminiscent of the quoted passage.
(It is noteworthy that Secrist was a prominent statistician, author of one of the most popular statistics textbooks published at the time. On JSTOR, you can find a lacerating review of Triumph... by Harold Hotelling published in JASA in late 1933. In a subsequent exchange of letters with Secrist, Hotelling wrote
My review ... was chiefly devoted to warning readers not to conclude that business firms have a tendency to become mediocre ... To "prove" such a mathematical result by a costly and prolonged numerical study ... is analogous to proving the multiplication table by arranging elephants in rows and columns, and then doing the same for numerous other kinds of animals. The performance, though perhaps entertaining, and having a certain pedagogical value, is not an important contribution either to zoology or to mathematics.
[JASA Vol. 29, No. 186 (June 1934), pp 198 and 199].)
The NY Times passage seems to make the same mistake with Apple's business data.
If we read on in the article, however, we soon uncover the author's intended meaning:
If Apple’s share price grew even 20 percent a year for the next decade, which is far below its current blistering pace, its \$500 billion market capitalization would be more than \$3 trillion by 2022.
This, of course, is a statement about extrapolation of exponential growth. As such it contains echoes of Malthusian population predictions. The hazards of extrapolation are not confined to exponential growth, however. Mark Twain (Samuel Clements) pilloried wanton extrapolators in Life on the Mississippi (1883, chapter 17):
Now, if I wanted to be one of those ponderous scientific people, and 'let on' to prove ... what will occur in the far future by what has occurred in late years, what an opportunity is here! ... Please observe:--
In the space of one hundred and seventy-six years the Lower Mississippi has shortened itself two hundred and forty-two miles. That is an average of a trifle over one mile and a third per year. Therefore, any calm person, who is not blind or idiotic, can see that in the “Old Oolitic Silurian Period,” just a million years ago next November, the Lower Mississippi River was upwards of one million three hundred thousand miles long, and stuck out over the Gulf of Mexico like a fishing-rod. And by the same token any person can see that seven hundred and forty-two years from now the Lower Mississippi will be only a mile and threequarters long, and Cairo and New Orleans will have joined their streets together, and be plodding comfortably along under a single mayor and a mutual board of aldermen. There is something fascinating about science. One gets such wholesale returns of conjecture out of such a trifling investment of fact.”
(Emphasis added.) Twain's satire compares favorably to the article's quotation of business analyst Robert Cihra:
If you extrapolate far enough out into the future, to sustain that growth Apple would have to sell an iPhone to every man, woman, child, animal and rock on the planet.
(Unfortunately, it appears Cihra does not heed his own advice: he rates this stock a "buy." He might be right, not on the merits, but by virtue of the greater fool theory.)
If we take the article to mean "beware of extrapolating previous growth into the future," we will get much out of it. Investors who think this company is a good buy because its PE ratio is low (which includes several of the notable money managers quoted in the article) are no better than the "ponderous scientific people" Twain skewered over a century ago.
A better acquaintance with Bernoulli, Hotelling, and Twain would have improved the accuracy and readability of this article, but in the end it seems to have gotten the message right.
|
Why law of large numbers does not apply in the case of Apple share price?
Here is the rub: Apple is so big, it’s running up against the law of
large numbers.
Also known as the golden theorem, with a proof attributed to the
17th-century Swiss mathematician Jacob Bernoull
|
6,070
|
Why law of large numbers does not apply in the case of Apple share price?
|
Humorously enough, I just wrote a blog post on this very subject:
http://confounding.net/2012/03/12/thats-not-how-the-law-of-large-numbers-works/
Essentially, the Law of Large Numbers is that as the number of trials of a random process increases, the mean of those trials will approach the actual mean (or expectation, for more complex distributions). So while if you flip a coin once and get heads your probability of heads = 1.0, as you flip more and more coins, you'll head closer and closer to 0.50.
The author argues that Apple will have trouble in the future due to something that is not actually at all related to the Law of Large Numbers. Namely, that as Apple grows larger, the same % increase in share price, earnings, etc. get harder to reach in absolute dollar terms. Basically, to stay on course, Apple has to get larger and larger hits.
Linking that to the behavior of a random process converging to a mean requires some serious mental gymnastics. As far as I can tell, the assertion is that "The awesomeness of your products" is a random process, and while Apple has had a streak of "Above Average" awesome, they'll eventually have to converge toward a mean of "Middling". But that's being really charitable to the author.
Just because 500 billion is a large number doesn't mean the "Law of Large Numbers" is what's acting on it.
|
Why law of large numbers does not apply in the case of Apple share price?
|
Humorously enough, I just wrote a blog post on this very subject:
http://confounding.net/2012/03/12/thats-not-how-the-law-of-large-numbers-works/
Essentially, the Law of Large Numbers is that as the n
|
Why law of large numbers does not apply in the case of Apple share price?
Humorously enough, I just wrote a blog post on this very subject:
http://confounding.net/2012/03/12/thats-not-how-the-law-of-large-numbers-works/
Essentially, the Law of Large Numbers is that as the number of trials of a random process increases, the mean of those trials will approach the actual mean (or expectation, for more complex distributions). So while if you flip a coin once and get heads your probability of heads = 1.0, as you flip more and more coins, you'll head closer and closer to 0.50.
The author argues that Apple will have trouble in the future due to something that is not actually at all related to the Law of Large Numbers. Namely, that as Apple grows larger, the same % increase in share price, earnings, etc. get harder to reach in absolute dollar terms. Basically, to stay on course, Apple has to get larger and larger hits.
Linking that to the behavior of a random process converging to a mean requires some serious mental gymnastics. As far as I can tell, the assertion is that "The awesomeness of your products" is a random process, and while Apple has had a streak of "Above Average" awesome, they'll eventually have to converge toward a mean of "Middling". But that's being really charitable to the author.
Just because 500 billion is a large number doesn't mean the "Law of Large Numbers" is what's acting on it.
|
Why law of large numbers does not apply in the case of Apple share price?
Humorously enough, I just wrote a blog post on this very subject:
http://confounding.net/2012/03/12/thats-not-how-the-law-of-large-numbers-works/
Essentially, the Law of Large Numbers is that as the n
|
6,071
|
Why law of large numbers does not apply in the case of Apple share price?
|
There is no reason to think that stock price draws over time for a particular company represent independent, identically distributed random variables.
|
Why law of large numbers does not apply in the case of Apple share price?
|
There is no reason to think that stock price draws over time for a particular company represent independent, identically distributed random variables.
|
Why law of large numbers does not apply in the case of Apple share price?
There is no reason to think that stock price draws over time for a particular company represent independent, identically distributed random variables.
|
Why law of large numbers does not apply in the case of Apple share price?
There is no reason to think that stock price draws over time for a particular company represent independent, identically distributed random variables.
|
6,072
|
When should one include a variable in a regression despite it not being statistically significant?
|
Yes!
That a coefficient is statistically indistinguishable from zero does not imply that the coefficient actually is zero, that the coefficient is irrelevant. That an effect does not pass some arbitrary cutoff for statistical significance does not imply one should not attempt to control for it.
Generally speaking, the problem at hand and your research design should guide what to include as regressors.
Some Quick Examples:
And do not take this as an exhaustive list. It's not hard to come up with tons more...
1. Fixed effects
A situation where this often occurs is a regression with fixed effects.
Let's say you have panel data and want to estimate $b$ in the model:
$$ y_{it} = b x_{it} + u_i + \epsilon_{it}$$
Estimating this model with ordinary least squares where $u_i$ are treated as fixed effects is equivalent to running ordinary least squares with an indicator variable for each individual $i$.
Anyway, the point is that the $u_i$ variables (i.e. the coefficients on the indicator variables) are often poorly estimated. Any individual fixed effect $u_i$ is often statistically insignificant. But you still include all the indicator variables in the regression if you are taking account of fixed effects.
(Further note that most stats packages won't even give you the standard errors for individual fixed effects when you use the built-in methods. You don't really care about significance of individual fixed effects. You probably do care about their collective significance.)
2. Functions that go together...
(a) Polynomial curve fitting (hat tip @NickCox in the comments)
If you're fitting a $k$th degree polynomial to some curve, you almost always include lower order polynomial terms.
E.g. if you were fitting a 2nd order polynomial you would run:
$$ y_i = b_0 + b_1 x_i + b_2 x_i^2 + \epsilon_i$$
Usually it would be quite bizarre to force $b_1 = 0$ and instead run
$$ y_i = b_0 + b_2 x_i^2 + \epsilon_i$$
but students of Newtonian mechanics will be able to imagine exceptions.
(b) AR(p) models:
Let's say you were estimating an AR(p) model you would also include the lower order terms. For example for an AR(2) you would run:
$$ y_t = b_0 + b_1 y_{t-1} + b_2 y_{t-2} + \epsilon_t$$
And it would be bizarre to run:
$$ y_t = b_0 + b_2 y_{t-2} + \epsilon_t$$
(c) Trigonometric functions
As @NickCox mentions, $\cos$ and $\sin$ terms similarly tend to go together. For more on that, see e.g. this paper.
More broadly...
You want to include right-hand side variables when there are good theoretical reasons to do so.
And as other answers here and across StackExchange discuss, step-wise variable selection can create numerous statistical problems.
It's also important to distinguish between:
a coefficient statistically indistinguishable from zero with a small standard error.
a coefficient statistically indistinguishable from zero with a large standard error.
In the latter case, it's problematic to argue the coefficient doesn't matter. It may simply be poorly measured.
|
When should one include a variable in a regression despite it not being statistically significant?
|
Yes!
That a coefficient is statistically indistinguishable from zero does not imply that the coefficient actually is zero, that the coefficient is irrelevant. That an effect does not pass some arbitra
|
When should one include a variable in a regression despite it not being statistically significant?
Yes!
That a coefficient is statistically indistinguishable from zero does not imply that the coefficient actually is zero, that the coefficient is irrelevant. That an effect does not pass some arbitrary cutoff for statistical significance does not imply one should not attempt to control for it.
Generally speaking, the problem at hand and your research design should guide what to include as regressors.
Some Quick Examples:
And do not take this as an exhaustive list. It's not hard to come up with tons more...
1. Fixed effects
A situation where this often occurs is a regression with fixed effects.
Let's say you have panel data and want to estimate $b$ in the model:
$$ y_{it} = b x_{it} + u_i + \epsilon_{it}$$
Estimating this model with ordinary least squares where $u_i$ are treated as fixed effects is equivalent to running ordinary least squares with an indicator variable for each individual $i$.
Anyway, the point is that the $u_i$ variables (i.e. the coefficients on the indicator variables) are often poorly estimated. Any individual fixed effect $u_i$ is often statistically insignificant. But you still include all the indicator variables in the regression if you are taking account of fixed effects.
(Further note that most stats packages won't even give you the standard errors for individual fixed effects when you use the built-in methods. You don't really care about significance of individual fixed effects. You probably do care about their collective significance.)
2. Functions that go together...
(a) Polynomial curve fitting (hat tip @NickCox in the comments)
If you're fitting a $k$th degree polynomial to some curve, you almost always include lower order polynomial terms.
E.g. if you were fitting a 2nd order polynomial you would run:
$$ y_i = b_0 + b_1 x_i + b_2 x_i^2 + \epsilon_i$$
Usually it would be quite bizarre to force $b_1 = 0$ and instead run
$$ y_i = b_0 + b_2 x_i^2 + \epsilon_i$$
but students of Newtonian mechanics will be able to imagine exceptions.
(b) AR(p) models:
Let's say you were estimating an AR(p) model you would also include the lower order terms. For example for an AR(2) you would run:
$$ y_t = b_0 + b_1 y_{t-1} + b_2 y_{t-2} + \epsilon_t$$
And it would be bizarre to run:
$$ y_t = b_0 + b_2 y_{t-2} + \epsilon_t$$
(c) Trigonometric functions
As @NickCox mentions, $\cos$ and $\sin$ terms similarly tend to go together. For more on that, see e.g. this paper.
More broadly...
You want to include right-hand side variables when there are good theoretical reasons to do so.
And as other answers here and across StackExchange discuss, step-wise variable selection can create numerous statistical problems.
It's also important to distinguish between:
a coefficient statistically indistinguishable from zero with a small standard error.
a coefficient statistically indistinguishable from zero with a large standard error.
In the latter case, it's problematic to argue the coefficient doesn't matter. It may simply be poorly measured.
|
When should one include a variable in a regression despite it not being statistically significant?
Yes!
That a coefficient is statistically indistinguishable from zero does not imply that the coefficient actually is zero, that the coefficient is irrelevant. That an effect does not pass some arbitra
|
6,073
|
When should one include a variable in a regression despite it not being statistically significant?
|
Yes, there are. Any variable that could correlate with your response variable in a meaningful way, even at a statistically insignificant level, could confound your regression if it is not included. This is known as underspecification, and leads to parameter estimates that are not as accurate as they could otherwise be.
https://onlinecourses.science.psu.edu/stat501/node/328
From the above:
A regression model is underspecified (outcome 2) if the regression
equation is missing one or more important predictor variables. This
situation is perhaps the worst-case scenario, because an
underspecified model yields biased regression coefficients and biased
predictions of the response. That is, in using the model, we would
consistently underestimate or overestimate the population slopes and
the population means. To make already bad matters even worse, the mean
square error MSE tends to overestimate σ², thereby yielding wider
confidence intervals than it should.
|
When should one include a variable in a regression despite it not being statistically significant?
|
Yes, there are. Any variable that could correlate with your response variable in a meaningful way, even at a statistically insignificant level, could confound your regression if it is not included. Th
|
When should one include a variable in a regression despite it not being statistically significant?
Yes, there are. Any variable that could correlate with your response variable in a meaningful way, even at a statistically insignificant level, could confound your regression if it is not included. This is known as underspecification, and leads to parameter estimates that are not as accurate as they could otherwise be.
https://onlinecourses.science.psu.edu/stat501/node/328
From the above:
A regression model is underspecified (outcome 2) if the regression
equation is missing one or more important predictor variables. This
situation is perhaps the worst-case scenario, because an
underspecified model yields biased regression coefficients and biased
predictions of the response. That is, in using the model, we would
consistently underestimate or overestimate the population slopes and
the population means. To make already bad matters even worse, the mean
square error MSE tends to overestimate σ², thereby yielding wider
confidence intervals than it should.
|
When should one include a variable in a regression despite it not being statistically significant?
Yes, there are. Any variable that could correlate with your response variable in a meaningful way, even at a statistically insignificant level, could confound your regression if it is not included. Th
|
6,074
|
When should one include a variable in a regression despite it not being statistically significant?
|
Usually you do not include or exclude variables for linear regression because of their significance. You include them because you assume that the selected variables are (good) predictors of the regression criteria. In other words, the predictor selection is based on theory.
Statistical insignificance in linear regression can mean two things (of which I know):
The insignificant predictors are not related to the criteria. Exclude them but keep in mind that the insignificance does not prove that they are unrelated. Check your theory.
The predictors are insignificant because they can be expressed as a function of other predictors. The set of predictors is then called multicollinear. This does not make the predictors "bad" in any sense but redundant.
A valid reason to exclude insignificant predictors is that you are looking for the smallest subset of predictors that explain the criteria variance or most of it. If you have found it check your theory.
|
When should one include a variable in a regression despite it not being statistically significant?
|
Usually you do not include or exclude variables for linear regression because of their significance. You include them because you assume that the selected variables are (good) predictors of the regres
|
When should one include a variable in a regression despite it not being statistically significant?
Usually you do not include or exclude variables for linear regression because of their significance. You include them because you assume that the selected variables are (good) predictors of the regression criteria. In other words, the predictor selection is based on theory.
Statistical insignificance in linear regression can mean two things (of which I know):
The insignificant predictors are not related to the criteria. Exclude them but keep in mind that the insignificance does not prove that they are unrelated. Check your theory.
The predictors are insignificant because they can be expressed as a function of other predictors. The set of predictors is then called multicollinear. This does not make the predictors "bad" in any sense but redundant.
A valid reason to exclude insignificant predictors is that you are looking for the smallest subset of predictors that explain the criteria variance or most of it. If you have found it check your theory.
|
When should one include a variable in a regression despite it not being statistically significant?
Usually you do not include or exclude variables for linear regression because of their significance. You include them because you assume that the selected variables are (good) predictors of the regres
|
6,075
|
When should one include a variable in a regression despite it not being statistically significant?
|
In econometrics this happens left and right. For instance, if you are using quarterly seasonality dummies Q2,Q3, and Q4, it happens often that as a group they're significant, but some of them are not significant individually. In this case you usually keep them all.
Another typical case is interactions. Consider a model $y\sim x*z$, where main effect $z$ is not significant but the interaction $x*z$ is. In this case it's customary to keep the main effect. There are many reasons why you should not drop it, and some of them were discussed in the forum.
UPDATE:
Another common example is forecasting. Econometrics is usually taught from inference perspective in economics departments. In inference perspective a lot of attention is on p-values and significance, because you're trying to understand what causes what and so on. In forecasting, there's not much emphasis on this stuff, because all you care is how well the model can forecast the variable of interest.
This is similar to machine learning applications, btw, which are making their way into economics recently. You can have a model with all significant variables that doesn't forecast well. In ML it's often associated with so called "over fitting". There's very little use of such model in forecasting, obviously.
|
When should one include a variable in a regression despite it not being statistically significant?
|
In econometrics this happens left and right. For instance, if you are using quarterly seasonality dummies Q2,Q3, and Q4, it happens often that as a group they're significant, but some of them are not
|
When should one include a variable in a regression despite it not being statistically significant?
In econometrics this happens left and right. For instance, if you are using quarterly seasonality dummies Q2,Q3, and Q4, it happens often that as a group they're significant, but some of them are not significant individually. In this case you usually keep them all.
Another typical case is interactions. Consider a model $y\sim x*z$, where main effect $z$ is not significant but the interaction $x*z$ is. In this case it's customary to keep the main effect. There are many reasons why you should not drop it, and some of them were discussed in the forum.
UPDATE:
Another common example is forecasting. Econometrics is usually taught from inference perspective in economics departments. In inference perspective a lot of attention is on p-values and significance, because you're trying to understand what causes what and so on. In forecasting, there's not much emphasis on this stuff, because all you care is how well the model can forecast the variable of interest.
This is similar to machine learning applications, btw, which are making their way into economics recently. You can have a model with all significant variables that doesn't forecast well. In ML it's often associated with so called "over fitting". There's very little use of such model in forecasting, obviously.
|
When should one include a variable in a regression despite it not being statistically significant?
In econometrics this happens left and right. For instance, if you are using quarterly seasonality dummies Q2,Q3, and Q4, it happens often that as a group they're significant, but some of them are not
|
6,076
|
When should one include a variable in a regression despite it not being statistically significant?
|
You are asking two different questions:
When does statistical significance not matter?
When should we include a variable in a regression in spite of it not being statistically significant?
Edit: this was true about the original post, but might no longer be true after the edits.
Regarding Q1, I think it is on the border of being too broad. There are many possible answers, some already provided. One more example is when building models for forecasting (see the source cited below for an explanation).
Regarding Q2, statistical significance is not a sound criterion for model building. Rob J. Hyndman writes the following in his blog post "Statistical tests for variable selection":
Statistical significance is not usually a good basis for determining whether a variable should be included in a model, despite the fact that many people who should know better use them for exactly this purpose. <...> Statistical tests were designed to test hypotheses, not select variables.
Also note that you can often find some variables that are statistically significant purely by chance (the chance being controlled by your choice of the significance level). The observation that a variable is statistically significant is not enough to conclude that the variable belongs in the model.
|
When should one include a variable in a regression despite it not being statistically significant?
|
You are asking two different questions:
When does statistical significance not matter?
When should we include a variable in a regression in spite of it not being statistically significant?
Edit: thi
|
When should one include a variable in a regression despite it not being statistically significant?
You are asking two different questions:
When does statistical significance not matter?
When should we include a variable in a regression in spite of it not being statistically significant?
Edit: this was true about the original post, but might no longer be true after the edits.
Regarding Q1, I think it is on the border of being too broad. There are many possible answers, some already provided. One more example is when building models for forecasting (see the source cited below for an explanation).
Regarding Q2, statistical significance is not a sound criterion for model building. Rob J. Hyndman writes the following in his blog post "Statistical tests for variable selection":
Statistical significance is not usually a good basis for determining whether a variable should be included in a model, despite the fact that many people who should know better use them for exactly this purpose. <...> Statistical tests were designed to test hypotheses, not select variables.
Also note that you can often find some variables that are statistically significant purely by chance (the chance being controlled by your choice of the significance level). The observation that a variable is statistically significant is not enough to conclude that the variable belongs in the model.
|
When should one include a variable in a regression despite it not being statistically significant?
You are asking two different questions:
When does statistical significance not matter?
When should we include a variable in a regression in spite of it not being statistically significant?
Edit: thi
|
6,077
|
When should one include a variable in a regression despite it not being statistically significant?
|
I'll add another "yes". I've always been taught -- and I've tried to pass it along -- that the primary consideration in covariate choice is domain knowledge, not statistics. In biostatistics, for instance, if I'm modelling some health outcome on individuals, then no matter what the regression says, you'll need some darn good arguments for me not to include age, race, and sex in the model.
It also depends on the purpose of your model. If the purpose is gaining better understanding of what factors are most associated with your outcome, then building a parsimonious model has some virtues. If you care about prediction, and not so much about understanding, then eliminating covariates may be a smaller concern.
(Finally, if you're planning to use statistics for variable selection, check out what Frank Harrell has to say on the subject -- http://www.stata.com/support/faqs/statistics/stepwise-regression-problems/, and his book Regression Modeling Strategies. Briefly, by the time you've used stepwise or similar statistically-based strategies for choosing the best predictors, then any tests of "are these good predictors?" are terribly biased -- of course they're good predictors, you've chosen them on that basis, and so the p values for those predictors are falsely low.)
|
When should one include a variable in a regression despite it not being statistically significant?
|
I'll add another "yes". I've always been taught -- and I've tried to pass it along -- that the primary consideration in covariate choice is domain knowledge, not statistics. In biostatistics, for inst
|
When should one include a variable in a regression despite it not being statistically significant?
I'll add another "yes". I've always been taught -- and I've tried to pass it along -- that the primary consideration in covariate choice is domain knowledge, not statistics. In biostatistics, for instance, if I'm modelling some health outcome on individuals, then no matter what the regression says, you'll need some darn good arguments for me not to include age, race, and sex in the model.
It also depends on the purpose of your model. If the purpose is gaining better understanding of what factors are most associated with your outcome, then building a parsimonious model has some virtues. If you care about prediction, and not so much about understanding, then eliminating covariates may be a smaller concern.
(Finally, if you're planning to use statistics for variable selection, check out what Frank Harrell has to say on the subject -- http://www.stata.com/support/faqs/statistics/stepwise-regression-problems/, and his book Regression Modeling Strategies. Briefly, by the time you've used stepwise or similar statistically-based strategies for choosing the best predictors, then any tests of "are these good predictors?" are terribly biased -- of course they're good predictors, you've chosen them on that basis, and so the p values for those predictors are falsely low.)
|
When should one include a variable in a regression despite it not being statistically significant?
I'll add another "yes". I've always been taught -- and I've tried to pass it along -- that the primary consideration in covariate choice is domain knowledge, not statistics. In biostatistics, for inst
|
6,078
|
When should one include a variable in a regression despite it not being statistically significant?
|
The only thing that the result of "statistical insignificance" truly says is that, at the selected level of Type I error, we cannot even tell whether the effect of the regressor on the dependent variable is positive or negative (see this post).
So, if we keep this regressor, any discussion about its own effect on the dependent variable does not have statistical evidence to back it up.
But this estimation failure does not say that the regressor does not belong to the structural relation, it only says that with the specific data set we were unable to determine with some certainty the sign of its coefficient.
So in principle, if there are theoretical arguments that support its presence, the regressor should be kept.
Other answers here provided specific models/situations for which such regressors are kept in the specification, for example the answer mentioning the fixed-effects panel data model.
|
When should one include a variable in a regression despite it not being statistically significant?
|
The only thing that the result of "statistical insignificance" truly says is that, at the selected level of Type I error, we cannot even tell whether the effect of the regressor on the dependent varia
|
When should one include a variable in a regression despite it not being statistically significant?
The only thing that the result of "statistical insignificance" truly says is that, at the selected level of Type I error, we cannot even tell whether the effect of the regressor on the dependent variable is positive or negative (see this post).
So, if we keep this regressor, any discussion about its own effect on the dependent variable does not have statistical evidence to back it up.
But this estimation failure does not say that the regressor does not belong to the structural relation, it only says that with the specific data set we were unable to determine with some certainty the sign of its coefficient.
So in principle, if there are theoretical arguments that support its presence, the regressor should be kept.
Other answers here provided specific models/situations for which such regressors are kept in the specification, for example the answer mentioning the fixed-effects panel data model.
|
When should one include a variable in a regression despite it not being statistically significant?
The only thing that the result of "statistical insignificance" truly says is that, at the selected level of Type I error, we cannot even tell whether the effect of the regressor on the dependent varia
|
6,079
|
When should one include a variable in a regression despite it not being statistically significant?
|
You may include a variable of particular interest if it is the focus of research, even if not statistically significant. Also, in biostatistics, clinical significance is often different than statistical significance.
|
When should one include a variable in a regression despite it not being statistically significant?
|
You may include a variable of particular interest if it is the focus of research, even if not statistically significant. Also, in biostatistics, clinical significance is often different than statistic
|
When should one include a variable in a regression despite it not being statistically significant?
You may include a variable of particular interest if it is the focus of research, even if not statistically significant. Also, in biostatistics, clinical significance is often different than statistical significance.
|
When should one include a variable in a regression despite it not being statistically significant?
You may include a variable of particular interest if it is the focus of research, even if not statistically significant. Also, in biostatistics, clinical significance is often different than statistic
|
6,080
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
Covariances are variances.
Since by the polarization identity
$$\newcommand{\c}{\text{Cov}}\newcommand{\v}{\text{Var}}
\c(X,Y) = \v\left(\frac{X+Y}{2}\right) - \v\left(\frac{X-Y}{2}\right),$$
the denominators must be the same.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
Covariances are variances.
Since by the polarization identity
$$\newcommand{\c}{\text{Cov}}\newcommand{\v}{\text{Var}}
\c(X,Y) = \v\left(\frac{X+Y}{2}\right) - \v\left(\frac{X-Y}{2}\right),$$
the den
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
Covariances are variances.
Since by the polarization identity
$$\newcommand{\c}{\text{Cov}}\newcommand{\v}{\text{Var}}
\c(X,Y) = \v\left(\frac{X+Y}{2}\right) - \v\left(\frac{X-Y}{2}\right),$$
the denominators must be the same.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
Covariances are variances.
Since by the polarization identity
$$\newcommand{\c}{\text{Cov}}\newcommand{\v}{\text{Var}}
\c(X,Y) = \v\left(\frac{X+Y}{2}\right) - \v\left(\frac{X-Y}{2}\right),$$
the den
|
6,081
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
A special case ought to give you an intuition; think about the following:
$$\hat{\mathbb{Cov}}\left(X, X\right)=
\hat{\mathbb{V}}\left(X\right)$$
You are happy that the latter is $\frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)^{2}}{n-1}$ due to the Bessel correction.
But replacing $Y$ by $X$ in $\hat{\mathbb{Cov}}\left(X, Y\right)$ for the the former gives $\frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)\left(X_{i}-\overline{X}\right)}{\text{mystery denominator}}$, so what do you now think might best fill in the blank?
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
A special case ought to give you an intuition; think about the following:
$$\hat{\mathbb{Cov}}\left(X, X\right)=
\hat{\mathbb{V}}\left(X\right)$$
You are happy that the latter is $\frac{\sum_{i=1}^{n}
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
A special case ought to give you an intuition; think about the following:
$$\hat{\mathbb{Cov}}\left(X, X\right)=
\hat{\mathbb{V}}\left(X\right)$$
You are happy that the latter is $\frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)^{2}}{n-1}$ due to the Bessel correction.
But replacing $Y$ by $X$ in $\hat{\mathbb{Cov}}\left(X, Y\right)$ for the the former gives $\frac{\sum_{i=1}^{n}\left(X_{i}-\overline{X}\right)\left(X_{i}-\overline{X}\right)}{\text{mystery denominator}}$, so what do you now think might best fill in the blank?
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
A special case ought to give you an intuition; think about the following:
$$\hat{\mathbb{Cov}}\left(X, X\right)=
\hat{\mathbb{V}}\left(X\right)$$
You are happy that the latter is $\frac{\sum_{i=1}^{n}
|
6,082
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
A quick and dirty answer... Let’s consider first $\text{var}(X)$; if you had $n$ observations with known expected value $E(X) = 0$ you would use ${1\over n}\sum_{i=1}^n X_i^2$ to estimate the variance.
The expected value being unknown, you can transform your $n$ observations into $n-1$ observations with known expected value by taking $A_i = X_i - X_1$ for $i = 2, \dots,n$. You will get a formula with a $n-1$ in the denominator — however the $A_i$ are not independent and you’d have to take this into account; at the end you’d find the usual formula.
Now for the covariance you can use the same idea: if the expected value of $(X,Y)$ was $(0,0)$, you’d had a ${1\over n}$ in the formula. By subtracting $(X_1,Y_1)$ to all other observed values, you get $n-1$ observations with known expected value... and a ${1\over n-1}$ in the formula — once again, this introduces some dependence to take into account.
P.S. The clean way to do that is to choose an orthonormal basis of $\big\langle (1, \dots, 1)' \big\rangle^{\perp}$, that is $n-1$ vectors $c_1, \dots, c_{n-1} \in \mathbb R^n$ such that
$\sum_j c_{ij}^2 = 1$ for all $i$,
$\sum_j c_{ij} = 0$ for all $i$,
$\sum_j c_{i_1j} c_{i_2j} = 0$ for all $i_1 \ne i_2$.
You can then define $n-1$ variables $A_i = \sum_j c_{ij} X_j$ and $B_i = \sum_j c_{ij} Y_j$. The $(A_i,B_i)$ are independent, have expected value $(0,0)$, and have same variance/covariance than the original variables.
All the point is that if you want to get rid of the unknown expectation, you drop one (and only one) observation. This works the same for both cases.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
A quick and dirty answer... Let’s consider first $\text{var}(X)$; if you had $n$ observations with known expected value $E(X) = 0$ you would use ${1\over n}\sum_{i=1}^n X_i^2$ to estimate the variance
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
A quick and dirty answer... Let’s consider first $\text{var}(X)$; if you had $n$ observations with known expected value $E(X) = 0$ you would use ${1\over n}\sum_{i=1}^n X_i^2$ to estimate the variance.
The expected value being unknown, you can transform your $n$ observations into $n-1$ observations with known expected value by taking $A_i = X_i - X_1$ for $i = 2, \dots,n$. You will get a formula with a $n-1$ in the denominator — however the $A_i$ are not independent and you’d have to take this into account; at the end you’d find the usual formula.
Now for the covariance you can use the same idea: if the expected value of $(X,Y)$ was $(0,0)$, you’d had a ${1\over n}$ in the formula. By subtracting $(X_1,Y_1)$ to all other observed values, you get $n-1$ observations with known expected value... and a ${1\over n-1}$ in the formula — once again, this introduces some dependence to take into account.
P.S. The clean way to do that is to choose an orthonormal basis of $\big\langle (1, \dots, 1)' \big\rangle^{\perp}$, that is $n-1$ vectors $c_1, \dots, c_{n-1} \in \mathbb R^n$ such that
$\sum_j c_{ij}^2 = 1$ for all $i$,
$\sum_j c_{ij} = 0$ for all $i$,
$\sum_j c_{i_1j} c_{i_2j} = 0$ for all $i_1 \ne i_2$.
You can then define $n-1$ variables $A_i = \sum_j c_{ij} X_j$ and $B_i = \sum_j c_{ij} Y_j$. The $(A_i,B_i)$ are independent, have expected value $(0,0)$, and have same variance/covariance than the original variables.
All the point is that if you want to get rid of the unknown expectation, you drop one (and only one) observation. This works the same for both cases.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
A quick and dirty answer... Let’s consider first $\text{var}(X)$; if you had $n$ observations with known expected value $E(X) = 0$ you would use ${1\over n}\sum_{i=1}^n X_i^2$ to estimate the variance
|
6,083
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
Here is a proof that the p-variate sample covariance estimator with denominator $\frac{1}{n-1}$ is an unbiased estimator of the covariance matrix:
$ x' = (x_1,...,x_p) $.
$\Sigma= E((x-\mu)(x-\mu)') $
$S = \frac{1}{n} \sum (x_i - \bar{x})(x_i - \bar{x})'$
To show: $E(S) = \frac{n-1}{n}\Sigma$
Proof: $S= \frac{1}{n}\sum x_ix_i' - \bar{x}\bar{x}'$
Next:
(1) $ E(x_ix_i') = \Sigma + \mu\mu'$
(2) $E(\bar{x}\bar{x}') = \frac{1}{n} \Sigma+ \mu\mu' $
Therefore: $E(S) = \Sigma + \mu\mu' - (\frac{1}{n} \Sigma+ \mu\mu') = \frac{n-1}{n} \Sigma $
And so $S_u = \frac{n}{n-1}S $, with the final denominator $\frac{1}{n-1}$, is unbiased. The off-diagonal elements of $S_u$ are your individual sample covariances.
Additional remarks:
The n draws are independent. This is used in (2) to calculate the covariance of the sample mean.
Step (1) and (2) use the fact that $Cov(x)= E[xx']-\mu\mu'$
Step (2) uses the fact that $Cov(\bar{x})= \frac{1}{n}\Sigma$
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
Here is a proof that the p-variate sample covariance estimator with denominator $\frac{1}{n-1}$ is an unbiased estimator of the covariance matrix:
$ x' = (x_1,...,x_p) $.
$\Sigma= E((x-\mu)(x-\mu)')
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
Here is a proof that the p-variate sample covariance estimator with denominator $\frac{1}{n-1}$ is an unbiased estimator of the covariance matrix:
$ x' = (x_1,...,x_p) $.
$\Sigma= E((x-\mu)(x-\mu)') $
$S = \frac{1}{n} \sum (x_i - \bar{x})(x_i - \bar{x})'$
To show: $E(S) = \frac{n-1}{n}\Sigma$
Proof: $S= \frac{1}{n}\sum x_ix_i' - \bar{x}\bar{x}'$
Next:
(1) $ E(x_ix_i') = \Sigma + \mu\mu'$
(2) $E(\bar{x}\bar{x}') = \frac{1}{n} \Sigma+ \mu\mu' $
Therefore: $E(S) = \Sigma + \mu\mu' - (\frac{1}{n} \Sigma+ \mu\mu') = \frac{n-1}{n} \Sigma $
And so $S_u = \frac{n}{n-1}S $, with the final denominator $\frac{1}{n-1}$, is unbiased. The off-diagonal elements of $S_u$ are your individual sample covariances.
Additional remarks:
The n draws are independent. This is used in (2) to calculate the covariance of the sample mean.
Step (1) and (2) use the fact that $Cov(x)= E[xx']-\mu\mu'$
Step (2) uses the fact that $Cov(\bar{x})= \frac{1}{n}\Sigma$
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
Here is a proof that the p-variate sample covariance estimator with denominator $\frac{1}{n-1}$ is an unbiased estimator of the covariance matrix:
$ x' = (x_1,...,x_p) $.
$\Sigma= E((x-\mu)(x-\mu)')
|
6,084
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
I guess one way to build intuition behind using 'n-1' and not 'n-2' is - that for calculating co-variance we do not need to de-mean both X and Y, but either of the two, i.e.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
I guess one way to build intuition behind using 'n-1' and not 'n-2' is - that for calculating co-variance we do not need to de-mean both X and Y, but either of the two, i.e.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
I guess one way to build intuition behind using 'n-1' and not 'n-2' is - that for calculating co-variance we do not need to de-mean both X and Y, but either of the two, i.e.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
I guess one way to build intuition behind using 'n-1' and not 'n-2' is - that for calculating co-variance we do not need to de-mean both X and Y, but either of the two, i.e.
|
6,085
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
1) Start $df=2n$.
2) Sample covariance is proportional to $\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$. Lose two $df$; one from $\bar{X}$, one from $\bar{Y}$ resulting in $df=2(n-1)$.
3) However, $\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$ only contains $n$ separate terms, one from each product. When two numbers are multiplied together the independent information from each separate number disappears.
As a trite example, consider that
$24=1*24=2*12=3*8=4*6=6*4=8*3=12*2=24*1$,
and that does not include irrationals and fractions, e.g. $24=2\sqrt{6}*2\sqrt{6}$, so that when we multiply two number series together and examine their product, all we see are the $df=n-1$ from one number series, as we have lost half of the original information, that is, what those two numbers were before the pair-wise grouping into one number (i.e., multiplication) was performed.
In other words, without loss of generality we can write
$(X_i-\bar{X})(Y_i-\bar{Y})=z_i-\bar{z}$ for some $z_i$ and $\bar{z}$,
i.e., $z_i=X_iY_i-\bar{X}Y_i-X_i\bar{Y}$, and, $\bar{z}=\bar{X}\bar{Y}$. From the $z$'s, which then clearly have $df=n-1$, the covariance formula becomes
$\Sigma_{i=1}^n\frac{z_i-\bar{z}}{n-1}=$
$\Sigma_{i=1}^n\frac{[(X_i-\bar{X})(Y_i-\bar{Y})]}{n-1}=$
$\frac{1}{n-1}\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$.
Thus, the answer to the question is that the $df$ are halved by grouping.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
1) Start $df=2n$.
2) Sample covariance is proportional to $\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$. Lose two $df$; one from $\bar{X}$, one from $\bar{Y}$ resulting in $df=2(n-1)$.
3) However, $\Si
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
1) Start $df=2n$.
2) Sample covariance is proportional to $\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$. Lose two $df$; one from $\bar{X}$, one from $\bar{Y}$ resulting in $df=2(n-1)$.
3) However, $\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$ only contains $n$ separate terms, one from each product. When two numbers are multiplied together the independent information from each separate number disappears.
As a trite example, consider that
$24=1*24=2*12=3*8=4*6=6*4=8*3=12*2=24*1$,
and that does not include irrationals and fractions, e.g. $24=2\sqrt{6}*2\sqrt{6}$, so that when we multiply two number series together and examine their product, all we see are the $df=n-1$ from one number series, as we have lost half of the original information, that is, what those two numbers were before the pair-wise grouping into one number (i.e., multiplication) was performed.
In other words, without loss of generality we can write
$(X_i-\bar{X})(Y_i-\bar{Y})=z_i-\bar{z}$ for some $z_i$ and $\bar{z}$,
i.e., $z_i=X_iY_i-\bar{X}Y_i-X_i\bar{Y}$, and, $\bar{z}=\bar{X}\bar{Y}$. From the $z$'s, which then clearly have $df=n-1$, the covariance formula becomes
$\Sigma_{i=1}^n\frac{z_i-\bar{z}}{n-1}=$
$\Sigma_{i=1}^n\frac{[(X_i-\bar{X})(Y_i-\bar{Y})]}{n-1}=$
$\frac{1}{n-1}\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$.
Thus, the answer to the question is that the $df$ are halved by grouping.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
1) Start $df=2n$.
2) Sample covariance is proportional to $\Sigma_{i=1}^n(X_i-\bar{X})(Y_i-\bar{Y})$. Lose two $df$; one from $\bar{X}$, one from $\bar{Y}$ resulting in $df=2(n-1)$.
3) However, $\Si
|
6,086
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
My simple way of thinking about the intuition behind the 'n-1' degree of freedom is as follow. An observation is a pair $\{x_i, y_i\}$. Therefore, we can always infer the last observation $\{x_n, y_n\}$ if we know 'n-1' previous observations and the sample mean $\{\overline{x}, \overline{y}\}$. The last observation can be considered redundant.
$df = n-2$ should be wrong if we follow the same logic as above.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
|
My simple way of thinking about the intuition behind the 'n-1' degree of freedom is as follow. An observation is a pair $\{x_i, y_i\}$. Therefore, we can always infer the last observation $\{x_n, y_n\
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
My simple way of thinking about the intuition behind the 'n-1' degree of freedom is as follow. An observation is a pair $\{x_i, y_i\}$. Therefore, we can always infer the last observation $\{x_n, y_n\}$ if we know 'n-1' previous observations and the sample mean $\{\overline{x}, \overline{y}\}$. The last observation can be considered redundant.
$df = n-2$ should be wrong if we follow the same logic as above.
|
Why shouldn't the denominator of the covariance estimator be n-2 rather than n-1?
My simple way of thinking about the intuition behind the 'n-1' degree of freedom is as follow. An observation is a pair $\{x_i, y_i\}$. Therefore, we can always infer the last observation $\{x_n, y_n\
|
6,087
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I'll provide another answer, since I think the ones currently provided miss an important point of the statement the physicist made. The quoted statement is:
"correlation does not imply causation, UNLESS one of the variables is time. So, if there is a strong correlation between some independent variable and time, then this implies causation as well."
The physicist is not saying:
"If X and Y are correlated, and X comes before Y, then the correlation implies causation."
That would be incorrect. What the physicist is saying is:
"If X and time are correlated, then that correlation implies that increasing time causes an increase (or decrease) in X."
An example might be entropy. If we have a strong correlation between time passing and entropy increasing, then we might say that increasing time causes an increase in entropy. Note that this ignores what the physical causes of the increasing entropy might be (particle decay, expanding universe, etc.).
One of the traditional requirements for causation is time progression, namely that X can only cause Y if X comes before Y. But if one of your variables IS time, then time progression is already built into the relationship (if a relationship exists).
EDIT: Based on a variety of comments, I'm going to add the following. I think that the physicist may be using a different idea of the word "causation" here. He seems to be saying that if there is a correlation between an independent variable and time, you can conclude that the independent variable changes predictably as time passes. Some people might say the changes are "caused" by time passing, this isn't really how statisticians use the words "cause" or "causation", so that may be causing some of the confusion.
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I'll provide another answer, since I think the ones currently provided miss an important point of the statement the physicist made. The quoted statement is:
"correlation does not imply causation, UNL
|
Correlation does not imply causation; but what about when one of the variables is time?
I'll provide another answer, since I think the ones currently provided miss an important point of the statement the physicist made. The quoted statement is:
"correlation does not imply causation, UNLESS one of the variables is time. So, if there is a strong correlation between some independent variable and time, then this implies causation as well."
The physicist is not saying:
"If X and Y are correlated, and X comes before Y, then the correlation implies causation."
That would be incorrect. What the physicist is saying is:
"If X and time are correlated, then that correlation implies that increasing time causes an increase (or decrease) in X."
An example might be entropy. If we have a strong correlation between time passing and entropy increasing, then we might say that increasing time causes an increase in entropy. Note that this ignores what the physical causes of the increasing entropy might be (particle decay, expanding universe, etc.).
One of the traditional requirements for causation is time progression, namely that X can only cause Y if X comes before Y. But if one of your variables IS time, then time progression is already built into the relationship (if a relationship exists).
EDIT: Based on a variety of comments, I'm going to add the following. I think that the physicist may be using a different idea of the word "causation" here. He seems to be saying that if there is a correlation between an independent variable and time, you can conclude that the independent variable changes predictably as time passes. Some people might say the changes are "caused" by time passing, this isn't really how statisticians use the words "cause" or "causation", so that may be causing some of the confusion.
|
Correlation does not imply causation; but what about when one of the variables is time?
I'll provide another answer, since I think the ones currently provided miss an important point of the statement the physicist made. The quoted statement is:
"correlation does not imply causation, UNL
|
6,088
|
Correlation does not imply causation; but what about when one of the variables is time?
|
We don't know what the physicist meant. Two different interpretations follow.
The claim that $X$ preceding $Y$ and being correlated with $Y$ implies that $X$ causes $Y$ is wrong. It's not enough for $X$ and $Y$ to be dependent even if $X$ precedes $Y$. For example, $X$ and $Y$ can both be caused by some other variable $W$: $X \leftarrow W \rightarrow Y$. Or, an even more complicated pattern could arise: $X \leftarrow V \rightarrow Z \leftarrow W \rightarrow Y$ where $Z$ is observed. Now $X$ and $Y$ are dependent and have no common cause, but neither causes the other.
However, temporal precedence greatly simplifies the conditions for asserting a causal relationship, which you can find in Pearl's Causality book Chapter 2.7 "Local criteria for causal relations".
A variable $X$ has a causal influence on $Y$ if there is a third
variable $Z$ and a context $S$, both occurring before $X$, such that:
$(Z\; \not\perp\!\!\!\!\perp Y \mid S)$;
$(Z \perp\!\!\perp Y \mid S \cup X)$
Essentially, (1) implies that $Z$ is a potential cause of $Y$ given the temporal precedence, and (2) implies that $X$ is able to break that relationship, which can only happen if $X$ causes $Y$.
This condition is much simpler than Pearl's definition for a genuine cause without temporal information.
Another possibility outlined in some of the other answers is that the physicist meant that if $X$ is the passage of time and it's correlated with $Y$, then $X$ causes $Y$. This statement is correct, but vacuous since the passage of time is the cause of all other variables, by which I mean that the causal graphical structure is this way. A causal graphical structure is a set of claims about independence relationships given observations and interventions.
|
Correlation does not imply causation; but what about when one of the variables is time?
|
We don't know what the physicist meant. Two different interpretations follow.
The claim that $X$ preceding $Y$ and being correlated with $Y$ implies that $X$ causes $Y$ is wrong. It's not enough fo
|
Correlation does not imply causation; but what about when one of the variables is time?
We don't know what the physicist meant. Two different interpretations follow.
The claim that $X$ preceding $Y$ and being correlated with $Y$ implies that $X$ causes $Y$ is wrong. It's not enough for $X$ and $Y$ to be dependent even if $X$ precedes $Y$. For example, $X$ and $Y$ can both be caused by some other variable $W$: $X \leftarrow W \rightarrow Y$. Or, an even more complicated pattern could arise: $X \leftarrow V \rightarrow Z \leftarrow W \rightarrow Y$ where $Z$ is observed. Now $X$ and $Y$ are dependent and have no common cause, but neither causes the other.
However, temporal precedence greatly simplifies the conditions for asserting a causal relationship, which you can find in Pearl's Causality book Chapter 2.7 "Local criteria for causal relations".
A variable $X$ has a causal influence on $Y$ if there is a third
variable $Z$ and a context $S$, both occurring before $X$, such that:
$(Z\; \not\perp\!\!\!\!\perp Y \mid S)$;
$(Z \perp\!\!\perp Y \mid S \cup X)$
Essentially, (1) implies that $Z$ is a potential cause of $Y$ given the temporal precedence, and (2) implies that $X$ is able to break that relationship, which can only happen if $X$ causes $Y$.
This condition is much simpler than Pearl's definition for a genuine cause without temporal information.
Another possibility outlined in some of the other answers is that the physicist meant that if $X$ is the passage of time and it's correlated with $Y$, then $X$ causes $Y$. This statement is correct, but vacuous since the passage of time is the cause of all other variables, by which I mean that the causal graphical structure is this way. A causal graphical structure is a set of claims about independence relationships given observations and interventions.
|
Correlation does not imply causation; but what about when one of the variables is time?
We don't know what the physicist meant. Two different interpretations follow.
The claim that $X$ preceding $Y$ and being correlated with $Y$ implies that $X$ causes $Y$ is wrong. It's not enough fo
|
6,089
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I speculate that your guest lecturer meant that in physics the only correlations that survive replication are the ones where there is an underlying causal relationship. Time variable is an exception because it is the only variable that is not controlled by the physicist. Here's why.
In physics we usually deal with repeatable phenomena and experiments. As a matter of fact it's almost a given that any experiment is repeatable, and can be replicated by you at later time or by other researchers. So, let's say you observe a sample where $y_i,x_{ki}$ are observations of the variable of interest and independent variables $x_k$. As I mentioned above we fully control the variables $x_{k}$, and can set them to any value we wish.
Your physicist guy is saying that in this setup you will not see any correlation $Corr[y,x_{k}]$ unless there's a causal link. Why? Because someone else or even you yourself will repeat the experiment with any combination and sequence of $x_{kj}$, and only the correlations with causal relationships will survive the replications of an experiment. All other (spurious) correlations will disappear once you collect enough data in all possible combinations of an experiment.
This situation is in stark contrast with social sciences and some business application where you can't do experiments. You observe only one sequence of GDP of a country, and can't change the unemployment holding all else equal and observe the correlations.
Now, time is the only variable that a physicist cannot control. There's only one Jan 1 2017. He can't repeat this day. He can repeat any other variable, but not time. That's why when it comes to time (not lapsed time or age), a physicist is in the same boat as everyone else: correlation does not imply causation for him.
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I speculate that your guest lecturer meant that in physics the only correlations that survive replication are the ones where there is an underlying causal relationship. Time variable is an exception b
|
Correlation does not imply causation; but what about when one of the variables is time?
I speculate that your guest lecturer meant that in physics the only correlations that survive replication are the ones where there is an underlying causal relationship. Time variable is an exception because it is the only variable that is not controlled by the physicist. Here's why.
In physics we usually deal with repeatable phenomena and experiments. As a matter of fact it's almost a given that any experiment is repeatable, and can be replicated by you at later time or by other researchers. So, let's say you observe a sample where $y_i,x_{ki}$ are observations of the variable of interest and independent variables $x_k$. As I mentioned above we fully control the variables $x_{k}$, and can set them to any value we wish.
Your physicist guy is saying that in this setup you will not see any correlation $Corr[y,x_{k}]$ unless there's a causal link. Why? Because someone else or even you yourself will repeat the experiment with any combination and sequence of $x_{kj}$, and only the correlations with causal relationships will survive the replications of an experiment. All other (spurious) correlations will disappear once you collect enough data in all possible combinations of an experiment.
This situation is in stark contrast with social sciences and some business application where you can't do experiments. You observe only one sequence of GDP of a country, and can't change the unemployment holding all else equal and observe the correlations.
Now, time is the only variable that a physicist cannot control. There's only one Jan 1 2017. He can't repeat this day. He can repeat any other variable, but not time. That's why when it comes to time (not lapsed time or age), a physicist is in the same boat as everyone else: correlation does not imply causation for him.
|
Correlation does not imply causation; but what about when one of the variables is time?
I speculate that your guest lecturer meant that in physics the only correlations that survive replication are the ones where there is an underlying causal relationship. Time variable is an exception b
|
6,090
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I have not heard this before, and it would not be true according to the conceptions of causality that I am familiar with (though I am not a physicist).
Typically, for $X$ to cause $Y$ it is necessary that $X$ precedes $Y$ in time. So if $Y$ precedes $X$ then it cannot be "caused" by $X$, regardless of any correlation. Moreover, $X$ preceding $Y$ is not a sufficient condition for causation (also regardless of any correlation).
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I have not heard this before, and it would not be true according to the conceptions of causality that I am familiar with (though I am not a physicist).
Typically, for $X$ to cause $Y$ it is necessary
|
Correlation does not imply causation; but what about when one of the variables is time?
I have not heard this before, and it would not be true according to the conceptions of causality that I am familiar with (though I am not a physicist).
Typically, for $X$ to cause $Y$ it is necessary that $X$ precedes $Y$ in time. So if $Y$ precedes $X$ then it cannot be "caused" by $X$, regardless of any correlation. Moreover, $X$ preceding $Y$ is not a sufficient condition for causation (also regardless of any correlation).
|
Correlation does not imply causation; but what about when one of the variables is time?
I have not heard this before, and it would not be true according to the conceptions of causality that I am familiar with (though I am not a physicist).
Typically, for $X$ to cause $Y$ it is necessary
|
6,091
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I don't think time is necessarily unique in this, but it's certainly a good example. The point is that typically if A & B are correlated, you can surmise that there is some common causality, but you don't know whether A causes B or B causes A, or perhaps a third variable C causes both A & B. However, in certain cases, you can rule out that any other variable caused A, and so it must be that A caused B. One such example is a controlled experiment, where you, the experimenter, control A. Then if the change you make in A "correlates" with a change in B, you know it must have been A that caused B to change, not the other way around.
Another type of scenario, which is the one this example with time falls into, is if you simply know that no other variable could have caused A because you know that nothing whatsoever can influence A. Since time just flows by one second at a time regardless of any other variable in the world, then if time correlates with changes in some variable your interested in (say, the number of people on the planet), you know for sure that the passage of time must have caused that variable to change, rather than your variable causing time to pass or otherwise change (i.e. time didn't go forward because more people were born, it has to be the other way around).
What you still don't know, of course, is whether the causality is direct. Presumably the passage of time itself doesn't automatically produce more human beings. Rather, history unfolding causes progress in various aspects of society, and this causes the population to increase in size (and even that is a simplification of many little causative relationships). But regardless of the precise factors at play, you do definitely know that A (ultimately) leads to B and not the other way around.
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I don't think time is necessarily unique in this, but it's certainly a good example. The point is that typically if A & B are correlated, you can surmise that there is some common causality, but you d
|
Correlation does not imply causation; but what about when one of the variables is time?
I don't think time is necessarily unique in this, but it's certainly a good example. The point is that typically if A & B are correlated, you can surmise that there is some common causality, but you don't know whether A causes B or B causes A, or perhaps a third variable C causes both A & B. However, in certain cases, you can rule out that any other variable caused A, and so it must be that A caused B. One such example is a controlled experiment, where you, the experimenter, control A. Then if the change you make in A "correlates" with a change in B, you know it must have been A that caused B to change, not the other way around.
Another type of scenario, which is the one this example with time falls into, is if you simply know that no other variable could have caused A because you know that nothing whatsoever can influence A. Since time just flows by one second at a time regardless of any other variable in the world, then if time correlates with changes in some variable your interested in (say, the number of people on the planet), you know for sure that the passage of time must have caused that variable to change, rather than your variable causing time to pass or otherwise change (i.e. time didn't go forward because more people were born, it has to be the other way around).
What you still don't know, of course, is whether the causality is direct. Presumably the passage of time itself doesn't automatically produce more human beings. Rather, history unfolding causes progress in various aspects of society, and this causes the population to increase in size (and even that is a simplification of many little causative relationships). But regardless of the precise factors at play, you do definitely know that A (ultimately) leads to B and not the other way around.
|
Correlation does not imply causation; but what about when one of the variables is time?
I don't think time is necessarily unique in this, but it's certainly a good example. The point is that typically if A & B are correlated, you can surmise that there is some common causality, but you d
|
6,092
|
Correlation does not imply causation; but what about when one of the variables is time?
|
Actually, correlation does imply a causal relationship.
Perhaps A caused B, or C caused A and B.
However, correlation does not prove causation.
This is self-evident.
|
Correlation does not imply causation; but what about when one of the variables is time?
|
Actually, correlation does imply a causal relationship.
Perhaps A caused B, or C caused A and B.
However, correlation does not prove causation.
This is self-evident.
|
Correlation does not imply causation; but what about when one of the variables is time?
Actually, correlation does imply a causal relationship.
Perhaps A caused B, or C caused A and B.
However, correlation does not prove causation.
This is self-evident.
|
Correlation does not imply causation; but what about when one of the variables is time?
Actually, correlation does imply a causal relationship.
Perhaps A caused B, or C caused A and B.
However, correlation does not prove causation.
This is self-evident.
|
6,093
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I would interpret this as a semantic rather than mathematical/statistical argument. I would also take it as a rather severe generalization.
The Bradford Hill Criteria, often used in epidemiology, provide a good framework for thinking about causation. Nothing can definitively prove causation, whether or not time is a factor, and I suspect that the lecturer was not trying to make such a strong assertion. However, many different factors can be used as reasonable arguments for causation.
For example, the Bradford Hill criteria suggest that strength of association between variables can provide evidence for causation, but is not on its own sufficient. Similarly, an association that is consistent with other known/believed facts may suggest causation more strongly than an association that is inconsistent with prevailing knowledge. Temporality is also one of the criteria -- a cause should precede its effect. An association, and the inferences we make about causation, must make temporal sense. I recommend reviewing the other criteria. Some are specific to epidemiology and aren't as applicable to physics but it's still a useful way of thinking.
The main point is that, while no single piece of evidence is going to definitively prove causation, you can build a good case for it based on a number of different logical checks. I would argue that giving absolute precedence to any one criterion, such as time, is not appropriate, but temporality can be an important factor when making a case that causation is plausible.
This leads to a broader point about statistics: generally speaking, we use statistics to make an argument. We use data and statistical tools to make a certain point. Often, the same data (and even the same tools) can be used to make conflicting points. We can't locate the definitive proof of causation in the math itself, but we can deploy our statistical tools as part of a broader argument. For more on that, I recommend Abelson's Statistics as Principled Argument.
To loop this back to the original situation, let's say you've done an experiment about the effect of a the concentration of a certain chemical in a solution on the temperature of that solution. You suspect that adding more of this chemical will result in a reaction that increases temperature. You add more gradually over time. You can look at temperature against time and see an increase. All this shows is that temperature is increasing with time; it doesn't prove that time itself (or anything else, for that matter) has some causal effect. It does, however, provide some evidence in a broader argument that increased concentration of this chemical results in a reaction that increases temperature.
|
Correlation does not imply causation; but what about when one of the variables is time?
|
I would interpret this as a semantic rather than mathematical/statistical argument. I would also take it as a rather severe generalization.
The Bradford Hill Criteria, often used in epidemiology, prov
|
Correlation does not imply causation; but what about when one of the variables is time?
I would interpret this as a semantic rather than mathematical/statistical argument. I would also take it as a rather severe generalization.
The Bradford Hill Criteria, often used in epidemiology, provide a good framework for thinking about causation. Nothing can definitively prove causation, whether or not time is a factor, and I suspect that the lecturer was not trying to make such a strong assertion. However, many different factors can be used as reasonable arguments for causation.
For example, the Bradford Hill criteria suggest that strength of association between variables can provide evidence for causation, but is not on its own sufficient. Similarly, an association that is consistent with other known/believed facts may suggest causation more strongly than an association that is inconsistent with prevailing knowledge. Temporality is also one of the criteria -- a cause should precede its effect. An association, and the inferences we make about causation, must make temporal sense. I recommend reviewing the other criteria. Some are specific to epidemiology and aren't as applicable to physics but it's still a useful way of thinking.
The main point is that, while no single piece of evidence is going to definitively prove causation, you can build a good case for it based on a number of different logical checks. I would argue that giving absolute precedence to any one criterion, such as time, is not appropriate, but temporality can be an important factor when making a case that causation is plausible.
This leads to a broader point about statistics: generally speaking, we use statistics to make an argument. We use data and statistical tools to make a certain point. Often, the same data (and even the same tools) can be used to make conflicting points. We can't locate the definitive proof of causation in the math itself, but we can deploy our statistical tools as part of a broader argument. For more on that, I recommend Abelson's Statistics as Principled Argument.
To loop this back to the original situation, let's say you've done an experiment about the effect of a the concentration of a certain chemical in a solution on the temperature of that solution. You suspect that adding more of this chemical will result in a reaction that increases temperature. You add more gradually over time. You can look at temperature against time and see an increase. All this shows is that temperature is increasing with time; it doesn't prove that time itself (or anything else, for that matter) has some causal effect. It does, however, provide some evidence in a broader argument that increased concentration of this chemical results in a reaction that increases temperature.
|
Correlation does not imply causation; but what about when one of the variables is time?
I would interpret this as a semantic rather than mathematical/statistical argument. I would also take it as a rather severe generalization.
The Bradford Hill Criteria, often used in epidemiology, prov
|
6,094
|
Correlation does not imply causation; but what about when one of the variables is time?
|
The sentence is quite simple and not worth overthinking (and has nothing to do with precedence).
If there is an established correlation between a variable and time (i.e. we know that an increase in time is accompanied by an increase in the variable, and this is a given), then we know the "causal" direction: i.e. time increasing, causes the variable to increase.
Because the alternative hypothesis of "nah-uh, it could be that time only increased because the variable increased first" simply cannot stand given the way time works.
This might sound like a silly observation, but it has important implications for study design trying to prove a causal direction. An important example in medicine is the difference between doing a cross-sectional and a cohort study.
E.g., a cross-sectional study trying to find a link between smoking and cancer might take a group of people, divide it into smokers vs non-smokers, and see how many in each group have cancer vs no-cancer. However, this is weak evidence because a correlation between smoking and cancer could also be interpreted as "people who have cancer are more likely to enjoy taking up smoking".
However, if you perform a cohort study, i.e. take a group of smokers and a group of non-smokers, and follow them up through time, and measure the variable "cancer in smokers minus cancer in non-smokers", and establish a positive correlation of this variable with time, (under reasonable assumptions, such that smoking amount once started is constant and independent of time etc) then you know that "time" is the cause of the cancer difference, since you cannot claim that increased rates of cancer caused time to pass more in the smoking group. Therefore you can claim a causation between time passing and a positive cancer difference related to higher rates in the smoker group. (or, more simply stated, time spent belonging to the smoking group causes a proportional increase in cancer risk).
Furthermore, the weakness of the cross-sectional study, i.e. the possibility that "people with cancer are more likely to take up smoking" has now gone out the window, since smoking as a variable has been taken out of the "time vs cancer" equation (here assumed to be constant and therefore unaffected by time). In other words, by formulating the study in this way, we have examined a very specific causal direction. If we wanted to examine the extent to which the reverse causal direction applies (i.e. how likely it is that people who will eventually get cancer are to take up smoking as time goes by), then we would necessarily have to design a cohort study split into "future cancer vs no-future cancer" and measure the uptake of smoking over time.
Update responding to comments:
Note that this is a discussion over a causal direction rather than one of finding a direct causal link. The question of confounding is a separate one. (i.e. there is nothing to suggest that there isn't an independent third variable that both makes you more likely to be a smoker and increases your chances of cancer with time). I.e., in terms of counterfactual causality, we have not definitively shown that "had it not been for smoking these people would not have gotten cancer". But we have shown that "the association between smoking group and cancer would not have increased had time not passed". (i.e. the association is not down to a snapshot of cancer sufferers mere preference for being in the smoking group or not, but is stengthened over time).
|
Correlation does not imply causation; but what about when one of the variables is time?
|
The sentence is quite simple and not worth overthinking (and has nothing to do with precedence).
If there is an established correlation between a variable and time (i.e. we know that an increase in t
|
Correlation does not imply causation; but what about when one of the variables is time?
The sentence is quite simple and not worth overthinking (and has nothing to do with precedence).
If there is an established correlation between a variable and time (i.e. we know that an increase in time is accompanied by an increase in the variable, and this is a given), then we know the "causal" direction: i.e. time increasing, causes the variable to increase.
Because the alternative hypothesis of "nah-uh, it could be that time only increased because the variable increased first" simply cannot stand given the way time works.
This might sound like a silly observation, but it has important implications for study design trying to prove a causal direction. An important example in medicine is the difference between doing a cross-sectional and a cohort study.
E.g., a cross-sectional study trying to find a link between smoking and cancer might take a group of people, divide it into smokers vs non-smokers, and see how many in each group have cancer vs no-cancer. However, this is weak evidence because a correlation between smoking and cancer could also be interpreted as "people who have cancer are more likely to enjoy taking up smoking".
However, if you perform a cohort study, i.e. take a group of smokers and a group of non-smokers, and follow them up through time, and measure the variable "cancer in smokers minus cancer in non-smokers", and establish a positive correlation of this variable with time, (under reasonable assumptions, such that smoking amount once started is constant and independent of time etc) then you know that "time" is the cause of the cancer difference, since you cannot claim that increased rates of cancer caused time to pass more in the smoking group. Therefore you can claim a causation between time passing and a positive cancer difference related to higher rates in the smoker group. (or, more simply stated, time spent belonging to the smoking group causes a proportional increase in cancer risk).
Furthermore, the weakness of the cross-sectional study, i.e. the possibility that "people with cancer are more likely to take up smoking" has now gone out the window, since smoking as a variable has been taken out of the "time vs cancer" equation (here assumed to be constant and therefore unaffected by time). In other words, by formulating the study in this way, we have examined a very specific causal direction. If we wanted to examine the extent to which the reverse causal direction applies (i.e. how likely it is that people who will eventually get cancer are to take up smoking as time goes by), then we would necessarily have to design a cohort study split into "future cancer vs no-future cancer" and measure the uptake of smoking over time.
Update responding to comments:
Note that this is a discussion over a causal direction rather than one of finding a direct causal link. The question of confounding is a separate one. (i.e. there is nothing to suggest that there isn't an independent third variable that both makes you more likely to be a smoker and increases your chances of cancer with time). I.e., in terms of counterfactual causality, we have not definitively shown that "had it not been for smoking these people would not have gotten cancer". But we have shown that "the association between smoking group and cancer would not have increased had time not passed". (i.e. the association is not down to a snapshot of cancer sufferers mere preference for being in the smoking group or not, but is stengthened over time).
|
Correlation does not imply causation; but what about when one of the variables is time?
The sentence is quite simple and not worth overthinking (and has nothing to do with precedence).
If there is an established correlation between a variable and time (i.e. we know that an increase in t
|
6,095
|
Correlation does not imply causation; but what about when one of the variables is time?
|
This is really a question of how to establish causality, because events which are related but not causative WILL likely be correlated in time or space. So looking at some correlated data, how can we determine if the relationship is dependent? A wise research adviser once told me, "correlation does not imply causation, it just tells you where to look".
Let's consider the situation where events A and B are found to be temporally or spatially correlated. If we would like to investigate the preposition that A causes B, the traditional line of thinking is to introduce tests of necessity and sufficiency -- which is what causality really means.
If the absence of event A leads to the absence of event B, it can be called necessary.
If only event A alone leads to event B, it can be called sufficient.
If not having milk causes me to go to the store, what we are saying is not that I get into my empty milk and drive. Absolute causality would mean that whenever I still have milk, I can't be bothered to go to the store; and conversely whenever I'm at the store, it's because I don't have any milk. Now it's easy to see the problem with positively establishing causality in the rigorous sense: most things are not absolutely causal. There's lots of other reasons I might go to the store which aren't related to the milk-state.
This is an easy way to tell a great paper from an alright paper. In careful research, you will see sufficiency and necessity tests everywhere. Making the claim that small-molecule drug A may lead to disassembly of protein complex B? You will immediately see the tests:
necessity
----test---- ----result----
everything but B --> [nothing] (check for false positive)
everything but A --> assembled
everything with A-like compound --> assembled (control group)
sufficiency
A + B alone (in vitro) --> disassembled (check for false negative)
A + B + everything --> disassembled (trial group)
This is the traditional way you would build an inductive argument for causality experimentally USING correlation, which is what I am confident your lecturer was eluding to!
|
Correlation does not imply causation; but what about when one of the variables is time?
|
This is really a question of how to establish causality, because events which are related but not causative WILL likely be correlated in time or space. So looking at some correlated data, how can we d
|
Correlation does not imply causation; but what about when one of the variables is time?
This is really a question of how to establish causality, because events which are related but not causative WILL likely be correlated in time or space. So looking at some correlated data, how can we determine if the relationship is dependent? A wise research adviser once told me, "correlation does not imply causation, it just tells you where to look".
Let's consider the situation where events A and B are found to be temporally or spatially correlated. If we would like to investigate the preposition that A causes B, the traditional line of thinking is to introduce tests of necessity and sufficiency -- which is what causality really means.
If the absence of event A leads to the absence of event B, it can be called necessary.
If only event A alone leads to event B, it can be called sufficient.
If not having milk causes me to go to the store, what we are saying is not that I get into my empty milk and drive. Absolute causality would mean that whenever I still have milk, I can't be bothered to go to the store; and conversely whenever I'm at the store, it's because I don't have any milk. Now it's easy to see the problem with positively establishing causality in the rigorous sense: most things are not absolutely causal. There's lots of other reasons I might go to the store which aren't related to the milk-state.
This is an easy way to tell a great paper from an alright paper. In careful research, you will see sufficiency and necessity tests everywhere. Making the claim that small-molecule drug A may lead to disassembly of protein complex B? You will immediately see the tests:
necessity
----test---- ----result----
everything but B --> [nothing] (check for false positive)
everything but A --> assembled
everything with A-like compound --> assembled (control group)
sufficiency
A + B alone (in vitro) --> disassembled (check for false negative)
A + B + everything --> disassembled (trial group)
This is the traditional way you would build an inductive argument for causality experimentally USING correlation, which is what I am confident your lecturer was eluding to!
|
Correlation does not imply causation; but what about when one of the variables is time?
This is really a question of how to establish causality, because events which are related but not causative WILL likely be correlated in time or space. So looking at some correlated data, how can we d
|
6,096
|
Is LSTM (Long Short-Term Memory) dead?
|
Maybe. But RNNs aren't.
Transformers learn "pseudo-temporal" relationships; they lack the true recurrent gradient that RNNs have, and thus extract fundamentally different features. This paper, for example, shows that the standard transformers are difficult to optimize in reinforcement learning settings, especially in memory-intensive environments. They do, however, eventually design a variant surpassing LSTMs.
Where are RNNs still needed?
Long memory tasks. Very long memory. IndRNNs have show ability to remember for 5000 timesteps, where LSTM barely manages 1000. A transformer is quadratic in time-complexity whereas RNNs are linear, meaning good luck processing even a single iteration of 5000 timesteps. If that isn't enough, the recent Legendre Memory Units have demonstrated memory of up to 512,000,000 timesteps; I'm unsure the world's top supercomputer could fit the resultant 1E18 tensor in memory.
Aside reinforcement learning, signal applications are memory-demanding - e.g. speech synthesis, video synthesis, seizure classification. While CNNs have shown much success on these tasks, many utilize RNNs inserted in later layers; CNNs learn spatial features, RNNs temporal/recurrrent. An impressive 2019 paper's network manages to clone a speaker's voice from a only a 5 second sample, and it uses CNNs + LSTMs.
Memory vs. Feature Quality:
One doesn't warrant the other; "quality" refers to information utility for a given task. For sentences with 50 words, for example, model A may classify superior to model B, but fail dramatically with 100 where B would have no trouble. This exact phenomenon is illustrated in the recent Bistable Recurrent Cell paper, where the cell shows better memory for longer sequences, but is outdone by LSTMs on shorter sequences. An intuition is, LSTMs' four-gated networking permits for greater control over information routing, and thus richer feature extraction.
Future of LSTMs?
My likeliest bet is, some form of enhancement - like a Bistable Recurrent Cell, maybe with attention, and recurrent normalization (e.g. LayerNorm or Recurrent BatchNorm). BRC's design is based on control theory, and so are LMUs; such architectures enjoy self-regularization, and there's much room for further innovation. Ultimately, RNNs cannot be "replaced" by non-recurrent architectures, and will thus perform superior on some tasks that demand explicitly recurrent features.
Recurrent Transformers
If we can't do away with recurrence, can't we just incorporate it with transformers somehow? Yes: Universal Transformers. Not only is there recurrence, but variable input sequences are supported, just like in RNNs. Authors go so far as to argue that UTs are Turing complete; whether that's true I haven't verified, but even if it is, it doesn't warrant practical ability to fully harness this capability.
Bonus: It helps to visualize RNNs to better understand and debug them; you can see their weights, gradients, and activations in action with See RNN, a package of mine (pretty pics included).
Update 6/29/2020: new paper redesigns transformers to operate in time dimension with linear, O(N), complexity: Transformers are RNNs. Mind the title though; from section 3.4: "we consider recurrence with respect to time and not depth". So they are a kind of RNN, but still differ from 'traditional' ones. I've yet to read it, seems promising; a nice video explanation here.
|
Is LSTM (Long Short-Term Memory) dead?
|
Maybe. But RNNs aren't.
Transformers learn "pseudo-temporal" relationships; they lack the true recurrent gradient that RNNs have, and thus extract fundamentally different features. This paper, for exa
|
Is LSTM (Long Short-Term Memory) dead?
Maybe. But RNNs aren't.
Transformers learn "pseudo-temporal" relationships; they lack the true recurrent gradient that RNNs have, and thus extract fundamentally different features. This paper, for example, shows that the standard transformers are difficult to optimize in reinforcement learning settings, especially in memory-intensive environments. They do, however, eventually design a variant surpassing LSTMs.
Where are RNNs still needed?
Long memory tasks. Very long memory. IndRNNs have show ability to remember for 5000 timesteps, where LSTM barely manages 1000. A transformer is quadratic in time-complexity whereas RNNs are linear, meaning good luck processing even a single iteration of 5000 timesteps. If that isn't enough, the recent Legendre Memory Units have demonstrated memory of up to 512,000,000 timesteps; I'm unsure the world's top supercomputer could fit the resultant 1E18 tensor in memory.
Aside reinforcement learning, signal applications are memory-demanding - e.g. speech synthesis, video synthesis, seizure classification. While CNNs have shown much success on these tasks, many utilize RNNs inserted in later layers; CNNs learn spatial features, RNNs temporal/recurrrent. An impressive 2019 paper's network manages to clone a speaker's voice from a only a 5 second sample, and it uses CNNs + LSTMs.
Memory vs. Feature Quality:
One doesn't warrant the other; "quality" refers to information utility for a given task. For sentences with 50 words, for example, model A may classify superior to model B, but fail dramatically with 100 where B would have no trouble. This exact phenomenon is illustrated in the recent Bistable Recurrent Cell paper, where the cell shows better memory for longer sequences, but is outdone by LSTMs on shorter sequences. An intuition is, LSTMs' four-gated networking permits for greater control over information routing, and thus richer feature extraction.
Future of LSTMs?
My likeliest bet is, some form of enhancement - like a Bistable Recurrent Cell, maybe with attention, and recurrent normalization (e.g. LayerNorm or Recurrent BatchNorm). BRC's design is based on control theory, and so are LMUs; such architectures enjoy self-regularization, and there's much room for further innovation. Ultimately, RNNs cannot be "replaced" by non-recurrent architectures, and will thus perform superior on some tasks that demand explicitly recurrent features.
Recurrent Transformers
If we can't do away with recurrence, can't we just incorporate it with transformers somehow? Yes: Universal Transformers. Not only is there recurrence, but variable input sequences are supported, just like in RNNs. Authors go so far as to argue that UTs are Turing complete; whether that's true I haven't verified, but even if it is, it doesn't warrant practical ability to fully harness this capability.
Bonus: It helps to visualize RNNs to better understand and debug them; you can see their weights, gradients, and activations in action with See RNN, a package of mine (pretty pics included).
Update 6/29/2020: new paper redesigns transformers to operate in time dimension with linear, O(N), complexity: Transformers are RNNs. Mind the title though; from section 3.4: "we consider recurrence with respect to time and not depth". So they are a kind of RNN, but still differ from 'traditional' ones. I've yet to read it, seems promising; a nice video explanation here.
|
Is LSTM (Long Short-Term Memory) dead?
Maybe. But RNNs aren't.
Transformers learn "pseudo-temporal" relationships; they lack the true recurrent gradient that RNNs have, and thus extract fundamentally different features. This paper, for exa
|
6,097
|
Is LSTM (Long Short-Term Memory) dead?
|
It is funny that you ask now, since just today I came across a paper by Wang, Khabsa, and Ma (2020) To Pretrain or Not to Pretrain who show that if you have large enough training set, the difference in performance between huge, "SOTA" model (RoBERTa), and LSTMs is small for NLP task. There was another recent paper by Merity (2019) Single Headed Attention RNN showing similar results, the abstract is worth quoting in full
The leading approaches in language modeling are all obsessed with TV
shows of my youth - namely Transformers and Sesame Street.
Transformers this, Transformers that, and over here a bonfire worth of
GPU-TPU-neuromorphic wafer scale silicon. We opt for the lazy path of
old and proven techniques with a fancy crypto inspired acronym: the
Single Headed Attention RNN (SHA-RNN). The author's lone goal is to
show that the entire field might have evolved a different direction if
we had instead been obsessed with a slightly different acronym and
slightly different result. We take a previously strong language model
based only on boring LSTMs and get it to within a stone's throw of a
stone's throw of state-of-the-art byte level language model results on
enwik8. This work has undergone no intensive hyperparameter
optimization and lived entirely on a commodity desktop machine that
made the author's small studio apartment far too warm in the midst of
a San Franciscan summer. The final results are achievable in plus or
minus 24 hours on a single GPU as the author is impatient. The
attention mechanism is also readily extended to large contexts with
minimal computation. Take that Sesame Street.
I don't think there's much to add.
Here is another example from very recent paper by Abnar, Dehghani, and Zuidema (2020) Transferring Inductive Biases through Knowledge Distillation
Several studies, however, have shown that LSTMs can perform better
than Transformers on tasks requiring sensitivity to (linguistic)
structure, especially when the data is limited [37, 6]. This is mainly
due to the recurrent inductive biases of LSTMs that helps them better
model the hierarchical structure of the inputs.
hence authors show how distilling information from LSTMs can positively impact Transformer model. This another, of many, examples that LSTMs, and RNNs in general, are used and perform good for a particular class of problems. Sure, they have limitations, but for language they are standard model, that is taught on on every NLP course (like Stanford's CS224n), and mentioned in every modern handbook on this topic. The above examples focus on language data, because in this area this model is very popular, but of course it is successfully applied to other kinds of time-series data as well, as mentioned in other answers.
|
Is LSTM (Long Short-Term Memory) dead?
|
It is funny that you ask now, since just today I came across a paper by Wang, Khabsa, and Ma (2020) To Pretrain or Not to Pretrain who show that if you have large enough training set, the difference i
|
Is LSTM (Long Short-Term Memory) dead?
It is funny that you ask now, since just today I came across a paper by Wang, Khabsa, and Ma (2020) To Pretrain or Not to Pretrain who show that if you have large enough training set, the difference in performance between huge, "SOTA" model (RoBERTa), and LSTMs is small for NLP task. There was another recent paper by Merity (2019) Single Headed Attention RNN showing similar results, the abstract is worth quoting in full
The leading approaches in language modeling are all obsessed with TV
shows of my youth - namely Transformers and Sesame Street.
Transformers this, Transformers that, and over here a bonfire worth of
GPU-TPU-neuromorphic wafer scale silicon. We opt for the lazy path of
old and proven techniques with a fancy crypto inspired acronym: the
Single Headed Attention RNN (SHA-RNN). The author's lone goal is to
show that the entire field might have evolved a different direction if
we had instead been obsessed with a slightly different acronym and
slightly different result. We take a previously strong language model
based only on boring LSTMs and get it to within a stone's throw of a
stone's throw of state-of-the-art byte level language model results on
enwik8. This work has undergone no intensive hyperparameter
optimization and lived entirely on a commodity desktop machine that
made the author's small studio apartment far too warm in the midst of
a San Franciscan summer. The final results are achievable in plus or
minus 24 hours on a single GPU as the author is impatient. The
attention mechanism is also readily extended to large contexts with
minimal computation. Take that Sesame Street.
I don't think there's much to add.
Here is another example from very recent paper by Abnar, Dehghani, and Zuidema (2020) Transferring Inductive Biases through Knowledge Distillation
Several studies, however, have shown that LSTMs can perform better
than Transformers on tasks requiring sensitivity to (linguistic)
structure, especially when the data is limited [37, 6]. This is mainly
due to the recurrent inductive biases of LSTMs that helps them better
model the hierarchical structure of the inputs.
hence authors show how distilling information from LSTMs can positively impact Transformer model. This another, of many, examples that LSTMs, and RNNs in general, are used and perform good for a particular class of problems. Sure, they have limitations, but for language they are standard model, that is taught on on every NLP course (like Stanford's CS224n), and mentioned in every modern handbook on this topic. The above examples focus on language data, because in this area this model is very popular, but of course it is successfully applied to other kinds of time-series data as well, as mentioned in other answers.
|
Is LSTM (Long Short-Term Memory) dead?
It is funny that you ask now, since just today I came across a paper by Wang, Khabsa, and Ma (2020) To Pretrain or Not to Pretrain who show that if you have large enough training set, the difference i
|
6,098
|
Is LSTM (Long Short-Term Memory) dead?
|
Our group recently built an LSTM model in a real world application. At first we had used other approaches, but then we decided to include features that were measurements taken over time, but of variable length - so for one person, we would have 15 measurements (of the same parameter) taken over a 3-month period, for another we would have 20 measurements over a 2-month period, and so on. Other features were present once per person, e.g. gender.
In this situation, standard time series approaches turned out to be unusable, since they expected us to have an equal number of measurements per person, taken at equal intervals. LSTM allowed us to build a model predicting if a certain event will occur for a person, using the variable length measurements combined with the once-per-person measurements.
We also compared our model to a simpler regression model using only one value per time-varying parameter (I forget what it was, probably the average value over time) and to a regression model using three measurements per time-varying feature per person and treating them as measurements of independent variables. The LSTM model had much better accuracy than both of these models, especially for the class of persons for whom the event occurred.
I know that this is just one counterexample, and LSTM is not the only algorithm to deal with that kind of situation - but the way your question is stated lends itself to counterexamples, and statistics/ML would be an impoverished area if we didn't have different tools to choose from.
|
Is LSTM (Long Short-Term Memory) dead?
|
Our group recently built an LSTM model in a real world application. At first we had used other approaches, but then we decided to include features that were measurements taken over time, but of variab
|
Is LSTM (Long Short-Term Memory) dead?
Our group recently built an LSTM model in a real world application. At first we had used other approaches, but then we decided to include features that were measurements taken over time, but of variable length - so for one person, we would have 15 measurements (of the same parameter) taken over a 3-month period, for another we would have 20 measurements over a 2-month period, and so on. Other features were present once per person, e.g. gender.
In this situation, standard time series approaches turned out to be unusable, since they expected us to have an equal number of measurements per person, taken at equal intervals. LSTM allowed us to build a model predicting if a certain event will occur for a person, using the variable length measurements combined with the once-per-person measurements.
We also compared our model to a simpler regression model using only one value per time-varying parameter (I forget what it was, probably the average value over time) and to a regression model using three measurements per time-varying feature per person and treating them as measurements of independent variables. The LSTM model had much better accuracy than both of these models, especially for the class of persons for whom the event occurred.
I know that this is just one counterexample, and LSTM is not the only algorithm to deal with that kind of situation - but the way your question is stated lends itself to counterexamples, and statistics/ML would be an impoverished area if we didn't have different tools to choose from.
|
Is LSTM (Long Short-Term Memory) dead?
Our group recently built an LSTM model in a real world application. At first we had used other approaches, but then we decided to include features that were measurements taken over time, but of variab
|
6,099
|
Is LSTM (Long Short-Term Memory) dead?
|
LSTM is a statistical method. It is not alive so it cannot be dead. It can be useful though. Any statistical method is another tool in a box. If one does not work it is good to have an alternative.
LSTM is good for language recognition tasks where context is important. It is also good for forecasting time series. The M4 competition was won by LSTM.
If it was not useful there would not be a significant body of research dedicated to it. However as far as I know there is no proof that LSTM is inferior to any other method in some meaningful sense, i.e. the class of problems which LSTM is able to solve is smaller than logistic regression, etc.
|
Is LSTM (Long Short-Term Memory) dead?
|
LSTM is a statistical method. It is not alive so it cannot be dead. It can be useful though. Any statistical method is another tool in a box. If one does not work it is good to have an alternative.
LS
|
Is LSTM (Long Short-Term Memory) dead?
LSTM is a statistical method. It is not alive so it cannot be dead. It can be useful though. Any statistical method is another tool in a box. If one does not work it is good to have an alternative.
LSTM is good for language recognition tasks where context is important. It is also good for forecasting time series. The M4 competition was won by LSTM.
If it was not useful there would not be a significant body of research dedicated to it. However as far as I know there is no proof that LSTM is inferior to any other method in some meaningful sense, i.e. the class of problems which LSTM is able to solve is smaller than logistic regression, etc.
|
Is LSTM (Long Short-Term Memory) dead?
LSTM is a statistical method. It is not alive so it cannot be dead. It can be useful though. Any statistical method is another tool in a box. If one does not work it is good to have an alternative.
LS
|
6,100
|
How trustworthy are the confidence intervals for lmer objects through effects package?
|
All of the results are essentially the same (for this particular example). Some theoretical differences are:
as @rvl points out, your reconstruction of CIs without taking account of covariance among parameters is just wrong (sorry)
confidence intervals for parameters can be based on Wald confidence intervals (assuming a quadratic log-likelihood surface): lsmeans, effects, confint(.,method="Wald"); except for lsmeans, these methods ignore finite-size effects ("degrees of freedom"), but in this case it barely makes any difference (df=40 is practically indistinguishable from infinite df)
... or on profile confidence intervals (the default method; ignores finite-size effects but allows for non-quadratic surfaces)
... or on parametric bootstrapping (the gold standard -- assumes the model is correct [responses are Normal, random effects are Normally distributed, data are conditionally independent, etc.], but otherwise makes few assumptions)
I think all of these approaches are reasonable (some are more approximate than others), but in this case it barely makes any difference which one you use. If you're concerned, try out several contrasting methods on your data, or on simulated data that resemble your own, and see what happens ...
(PS: I wouldn't put too much weight on the fact that the confidence intervals of A and E don't overlap. You'd have to do a proper pairwise comparison procedure to make reliable inferences about the differences between this particular pair of estimates ...)
95% CIs:
Comparison code:
library(lme4)
fm2 <- lmer(strength ~ batch - 1 + (1 | cask), Pastes)
c0 <- confint(fm2,method="Wald")
c1 <- confint(fm2)
c2 <- confint(fm2,method="boot")
library(effects)
library(lsmeans)
c3 <- with(effect("batch",fm2),cbind(lower,upper))
c4 <- with(summary(lsmeans(fm2,spec="batch")),cbind(lower.CL,upper.CL))
tmpf <- function(method,val) {
data.frame(method=method,
v=LETTERS[1:10],
setNames(as.data.frame(tail(val,10)),
c("lwr","upr")))
}
library(ggplot2); theme_set(theme_bw())
allCI <- rbind(tmpf("lme4_wald",c0),
tmpf("lme4_prof",c1),
tmpf("lme4_boot",c2),
tmpf("effects",c3),
tmpf("lsmeans",c4))
ggplot(allCI,aes(v,ymin=lwr,ymax=upr,colour=method))+
geom_linerange(position=position_dodge(width=0.8))
ggsave("pastes_confint.png",width=10)
|
How trustworthy are the confidence intervals for lmer objects through effects package?
|
All of the results are essentially the same (for this particular example). Some theoretical differences are:
as @rvl points out, your reconstruction of CIs without taking account of covariance among
|
How trustworthy are the confidence intervals for lmer objects through effects package?
All of the results are essentially the same (for this particular example). Some theoretical differences are:
as @rvl points out, your reconstruction of CIs without taking account of covariance among parameters is just wrong (sorry)
confidence intervals for parameters can be based on Wald confidence intervals (assuming a quadratic log-likelihood surface): lsmeans, effects, confint(.,method="Wald"); except for lsmeans, these methods ignore finite-size effects ("degrees of freedom"), but in this case it barely makes any difference (df=40 is practically indistinguishable from infinite df)
... or on profile confidence intervals (the default method; ignores finite-size effects but allows for non-quadratic surfaces)
... or on parametric bootstrapping (the gold standard -- assumes the model is correct [responses are Normal, random effects are Normally distributed, data are conditionally independent, etc.], but otherwise makes few assumptions)
I think all of these approaches are reasonable (some are more approximate than others), but in this case it barely makes any difference which one you use. If you're concerned, try out several contrasting methods on your data, or on simulated data that resemble your own, and see what happens ...
(PS: I wouldn't put too much weight on the fact that the confidence intervals of A and E don't overlap. You'd have to do a proper pairwise comparison procedure to make reliable inferences about the differences between this particular pair of estimates ...)
95% CIs:
Comparison code:
library(lme4)
fm2 <- lmer(strength ~ batch - 1 + (1 | cask), Pastes)
c0 <- confint(fm2,method="Wald")
c1 <- confint(fm2)
c2 <- confint(fm2,method="boot")
library(effects)
library(lsmeans)
c3 <- with(effect("batch",fm2),cbind(lower,upper))
c4 <- with(summary(lsmeans(fm2,spec="batch")),cbind(lower.CL,upper.CL))
tmpf <- function(method,val) {
data.frame(method=method,
v=LETTERS[1:10],
setNames(as.data.frame(tail(val,10)),
c("lwr","upr")))
}
library(ggplot2); theme_set(theme_bw())
allCI <- rbind(tmpf("lme4_wald",c0),
tmpf("lme4_prof",c1),
tmpf("lme4_boot",c2),
tmpf("effects",c3),
tmpf("lsmeans",c4))
ggplot(allCI,aes(v,ymin=lwr,ymax=upr,colour=method))+
geom_linerange(position=position_dodge(width=0.8))
ggsave("pastes_confint.png",width=10)
|
How trustworthy are the confidence intervals for lmer objects through effects package?
All of the results are essentially the same (for this particular example). Some theoretical differences are:
as @rvl points out, your reconstruction of CIs without taking account of covariance among
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.