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
8,201
Imputation before or after splitting into train and test?
You should split before pre-processing or imputing. The division between training and test set is an attempt to replicate the situation where you have past information and are building a model which you will test on future as-yet unknown information: the training set takes the place of the past and the test set takes the place of the future, so you only get to test your trained model once. Keeping the past/future analogy in mind, this means anything you do to pre-process or process your data, such as imputing missing values, you should do on the training set alone. You can then remember what you did to your training set if your test set also needs pre-processing or imputing, so that you do it the same way on both sets. Added from comments: if you use the test data to affect the training data, then the test data is being used to build your model, so it ceases to be test data and will not provide a fair test of your model. You risk overfitting, and it was to discourage this that you separated out the test data in the first place
Imputation before or after splitting into train and test?
You should split before pre-processing or imputing. The division between training and test set is an attempt to replicate the situation where you have past information and are building a model which y
Imputation before or after splitting into train and test? You should split before pre-processing or imputing. The division between training and test set is an attempt to replicate the situation where you have past information and are building a model which you will test on future as-yet unknown information: the training set takes the place of the past and the test set takes the place of the future, so you only get to test your trained model once. Keeping the past/future analogy in mind, this means anything you do to pre-process or process your data, such as imputing missing values, you should do on the training set alone. You can then remember what you did to your training set if your test set also needs pre-processing or imputing, so that you do it the same way on both sets. Added from comments: if you use the test data to affect the training data, then the test data is being used to build your model, so it ceases to be test data and will not provide a fair test of your model. You risk overfitting, and it was to discourage this that you separated out the test data in the first place
Imputation before or after splitting into train and test? You should split before pre-processing or imputing. The division between training and test set is an attempt to replicate the situation where you have past information and are building a model which y
8,202
Imputation before or after splitting into train and test?
I think you'd better split before you do imputation. For instances, you may want to impute missing values with column mean. In this case, if you impute first with train+valid data set and split next, then you have used validation data set before you built your model, which is how a data leakage problem comes into picture. But you might ask, if I impute after splitting, it may be too tedious when I need to do cross validation. My suggest for that is to use sklearn pipeline. It really simplifies your code, and reducex the chance of making a mistake. See Pipeline
Imputation before or after splitting into train and test?
I think you'd better split before you do imputation. For instances, you may want to impute missing values with column mean. In this case, if you impute first with train+valid data set and split next,
Imputation before or after splitting into train and test? I think you'd better split before you do imputation. For instances, you may want to impute missing values with column mean. In this case, if you impute first with train+valid data set and split next, then you have used validation data set before you built your model, which is how a data leakage problem comes into picture. But you might ask, if I impute after splitting, it may be too tedious when I need to do cross validation. My suggest for that is to use sklearn pipeline. It really simplifies your code, and reducex the chance of making a mistake. See Pipeline
Imputation before or after splitting into train and test? I think you'd better split before you do imputation. For instances, you may want to impute missing values with column mean. In this case, if you impute first with train+valid data set and split next,
8,203
Imputation before or after splitting into train and test?
Just to add on the above I would also favour spliting before imputing or any type of pre-processing. Nothing you do with the training data should be informed by the test data (the analogy is that the future should not affect the past). You can then remember what you did to your training set if your test set also needs pre-processing or imputing, so that you do it the same way on both sets (the analogy is that you can use the past to help predict the future). If you use the test data to affect the training data in any way, then the test data is being used to build your model, so it ceases to be test data and will not provide a fair test of your model. You risk over fitting, and it was to discourage this that you separated out the test data in the first place! I think the caret package in r is very useful in that setting. I found in specific that post to be extremely helpful https://topepo.github.io/caret/model-training-and-tuning.html
Imputation before or after splitting into train and test?
Just to add on the above I would also favour spliting before imputing or any type of pre-processing. Nothing you do with the training data should be informed by the test data (the analogy is that the
Imputation before or after splitting into train and test? Just to add on the above I would also favour spliting before imputing or any type of pre-processing. Nothing you do with the training data should be informed by the test data (the analogy is that the future should not affect the past). You can then remember what you did to your training set if your test set also needs pre-processing or imputing, so that you do it the same way on both sets (the analogy is that you can use the past to help predict the future). If you use the test data to affect the training data in any way, then the test data is being used to build your model, so it ceases to be test data and will not provide a fair test of your model. You risk over fitting, and it was to discourage this that you separated out the test data in the first place! I think the caret package in r is very useful in that setting. I found in specific that post to be extremely helpful https://topepo.github.io/caret/model-training-and-tuning.html
Imputation before or after splitting into train and test? Just to add on the above I would also favour spliting before imputing or any type of pre-processing. Nothing you do with the training data should be informed by the test data (the analogy is that the
8,204
How to change data between wide and long formats in R? [closed]
There are several resources on Hadley Wickham's website for the package (now called reshape2), including a link to a paper on the package in the Journal of Statistical Software. Here is a brief example from the paper: > require(reshape2) Loading required package: reshape2 > data(smiths) > smiths subject time age weight height 1 John Smith 1 33 90 1.87 2 Mary Smith 1 NA NA 1.54 We note that the data are in the wide form. To go to the long form, we make the smiths data frame molten: > melt(smiths) Using subject as id variables subject variable value 1 John Smith time 1.00 2 Mary Smith time 1.00 3 John Smith age 33.00 4 Mary Smith age NA 5 John Smith weight 90.00 6 Mary Smith weight NA 7 John Smith height 1.87 8 Mary Smith height 1.54 Notice how melt() chose one of the variables as the id, but we can state explicitly which to use via argument 'id': > melt(smiths, id = "subject") subject variable value 1 John Smith time 1.00 2 Mary Smith time 1.00 3 John Smith age 33.00 4 Mary Smith age NA 5 John Smith weight 90.00 6 Mary Smith weight NA 7 John Smith height 1.87 8 Mary Smith height 1.54 Here is another example from ?cast: #Air quality example names(airquality) <- tolower(names(airquality)) aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE) If we store the molten data frame, we can cast into other forms. In the new version of reshape (called reshape2) there are functions acast() and dcast() returning an array-like (array, matrix, vector) result or a data frame respectively. These functions also take an aggregating function (eg mean()) to provide summaries of data in molten form. For example, following on from the Air Quality example above, we can generate, in wide form, monthly mean values for the variables in the data set: > dcast(aqm, month ~ variable, mean) month ozone solar.r wind temp 1 5 23.61538 181.2963 11.622581 65.54839 2 6 29.44444 190.1667 10.266667 79.10000 3 7 59.11538 216.4839 8.941935 83.90323 4 8 59.96154 171.8571 8.793548 83.96774 5 9 31.44828 167.4333 10.180000 76.90000 There are really only two main functions in reshape2: melt() and the acast() and dcast() pairing. Look at the examples in the help pages for these two functions, see Hadley's website (link above) and look at the paper I mentioned. That should get you started. You might also look into Hadley's plyr package which does similar things to reshape2 but is designed to do a whole lot more besides.
How to change data between wide and long formats in R? [closed]
There are several resources on Hadley Wickham's website for the package (now called reshape2), including a link to a paper on the package in the Journal of Statistical Software. Here is a brief exampl
How to change data between wide and long formats in R? [closed] There are several resources on Hadley Wickham's website for the package (now called reshape2), including a link to a paper on the package in the Journal of Statistical Software. Here is a brief example from the paper: > require(reshape2) Loading required package: reshape2 > data(smiths) > smiths subject time age weight height 1 John Smith 1 33 90 1.87 2 Mary Smith 1 NA NA 1.54 We note that the data are in the wide form. To go to the long form, we make the smiths data frame molten: > melt(smiths) Using subject as id variables subject variable value 1 John Smith time 1.00 2 Mary Smith time 1.00 3 John Smith age 33.00 4 Mary Smith age NA 5 John Smith weight 90.00 6 Mary Smith weight NA 7 John Smith height 1.87 8 Mary Smith height 1.54 Notice how melt() chose one of the variables as the id, but we can state explicitly which to use via argument 'id': > melt(smiths, id = "subject") subject variable value 1 John Smith time 1.00 2 Mary Smith time 1.00 3 John Smith age 33.00 4 Mary Smith age NA 5 John Smith weight 90.00 6 Mary Smith weight NA 7 John Smith height 1.87 8 Mary Smith height 1.54 Here is another example from ?cast: #Air quality example names(airquality) <- tolower(names(airquality)) aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE) If we store the molten data frame, we can cast into other forms. In the new version of reshape (called reshape2) there are functions acast() and dcast() returning an array-like (array, matrix, vector) result or a data frame respectively. These functions also take an aggregating function (eg mean()) to provide summaries of data in molten form. For example, following on from the Air Quality example above, we can generate, in wide form, monthly mean values for the variables in the data set: > dcast(aqm, month ~ variable, mean) month ozone solar.r wind temp 1 5 23.61538 181.2963 11.622581 65.54839 2 6 29.44444 190.1667 10.266667 79.10000 3 7 59.11538 216.4839 8.941935 83.90323 4 8 59.96154 171.8571 8.793548 83.96774 5 9 31.44828 167.4333 10.180000 76.90000 There are really only two main functions in reshape2: melt() and the acast() and dcast() pairing. Look at the examples in the help pages for these two functions, see Hadley's website (link above) and look at the paper I mentioned. That should get you started. You might also look into Hadley's plyr package which does similar things to reshape2 but is designed to do a whole lot more besides.
How to change data between wide and long formats in R? [closed] There are several resources on Hadley Wickham's website for the package (now called reshape2), including a link to a paper on the package in the Journal of Statistical Software. Here is a brief exampl
8,205
How to change data between wide and long formats in R? [closed]
Quick-R has simple example of using reshape package See also ?reshape (LINK) for the Base R way of moving between wide and long format.
How to change data between wide and long formats in R? [closed]
Quick-R has simple example of using reshape package See also ?reshape (LINK) for the Base R way of moving between wide and long format.
How to change data between wide and long formats in R? [closed] Quick-R has simple example of using reshape package See also ?reshape (LINK) for the Base R way of moving between wide and long format.
How to change data between wide and long formats in R? [closed] Quick-R has simple example of using reshape package See also ?reshape (LINK) for the Base R way of moving between wide and long format.
8,206
How to change data between wide and long formats in R? [closed]
You don't have to use melt and cast. Reshaping data can be done lots of ways. In your particular example on your cite using recast with aggregate was redundant because aggregate does the task fine all on it's own. aggregate(cbind(LPMVTUZ, LPMVTVC, LPMVTXC) ~ year, dtm, sum) # or even briefer by first removing the columns you don't want to use aggregate(. ~ year, dtm[,-2], sum) I do like how, in your blog post, you explain what melt is doing. Very few people understand that and once you see it then it gets easier to see how cast works and how you might write your own functions if you want.
How to change data between wide and long formats in R? [closed]
You don't have to use melt and cast. Reshaping data can be done lots of ways. In your particular example on your cite using recast with aggregate was redundant because aggregate does the task fine
How to change data between wide and long formats in R? [closed] You don't have to use melt and cast. Reshaping data can be done lots of ways. In your particular example on your cite using recast with aggregate was redundant because aggregate does the task fine all on it's own. aggregate(cbind(LPMVTUZ, LPMVTVC, LPMVTXC) ~ year, dtm, sum) # or even briefer by first removing the columns you don't want to use aggregate(. ~ year, dtm[,-2], sum) I do like how, in your blog post, you explain what melt is doing. Very few people understand that and once you see it then it gets easier to see how cast works and how you might write your own functions if you want.
How to change data between wide and long formats in R? [closed] You don't have to use melt and cast. Reshaping data can be done lots of ways. In your particular example on your cite using recast with aggregate was redundant because aggregate does the task fine
8,207
How to change data between wide and long formats in R? [closed]
See the reshape2 wiki. It surely provides more examples as you could expect.
How to change data between wide and long formats in R? [closed]
See the reshape2 wiki. It surely provides more examples as you could expect.
How to change data between wide and long formats in R? [closed] See the reshape2 wiki. It surely provides more examples as you could expect.
How to change data between wide and long formats in R? [closed] See the reshape2 wiki. It surely provides more examples as you could expect.
8,208
How to change data between wide and long formats in R? [closed]
Just noticing there's no reference to the more efficient and extensive reshaping methods in data.table here, so I am posting without further comment the excellent answer by Zach/Arun on StackOverflow for a similar question: https://stackoverflow.com/questions/6902087/proper-fastest-way-to-reshape-a-data-table/6913151#6913151 And in particular there's the wonderful vignette on the data.table GitHub page: https://github.com/Rdatatable/data.table/wiki/Getting-started
How to change data between wide and long formats in R? [closed]
Just noticing there's no reference to the more efficient and extensive reshaping methods in data.table here, so I am posting without further comment the excellent answer by Zach/Arun on StackOverflow
How to change data between wide and long formats in R? [closed] Just noticing there's no reference to the more efficient and extensive reshaping methods in data.table here, so I am posting without further comment the excellent answer by Zach/Arun on StackOverflow for a similar question: https://stackoverflow.com/questions/6902087/proper-fastest-way-to-reshape-a-data-table/6913151#6913151 And in particular there's the wonderful vignette on the data.table GitHub page: https://github.com/Rdatatable/data.table/wiki/Getting-started
How to change data between wide and long formats in R? [closed] Just noticing there's no reference to the more efficient and extensive reshaping methods in data.table here, so I am posting without further comment the excellent answer by Zach/Arun on StackOverflow
8,209
What is "baseline" in precision recall curve
The "baseline curve" in a PR curve plot is a horizontal line with height equal to the number of positive examples $P$ over the total number of training data $N$, ie. the proportion of positive examples in our data ($\frac{P}{N}$). OK, why is this the case though? Let's assume we have a "junk classifier" $C_J$. $C_J$ returns a random probability $p_i$ to the $i$-th sample instance $y_i$ to be in class $A$. For convenience, say $p_i \sim U[0,1]$. The direct implication of this random class assignment is that $C_J$ will have (expected) precision equal to the proportion of positive examples in our data. It is only natural; any totally random sub-sample of our data will have $E\{\frac{P}{N}\}$ correctly classified examples. This will be true for any probability threshold $q$ we might use as a decision boundary for the probabilities of class membership returned by $C_J$. ($q$ denotes a value in $[0,1]$ where probability values greater or equal to $q$ are classified in class $A$.) On the other hand the recall performance of $C_J$ is (in expectation) equal to $q$ if $p_i \sim U[0,1]$. At any given threshold $q$ we will pick (approximately) $(100(1-q))\%$ of our total data which subsequently will contain (approximately) $(100(1-q))\%$ of the total number of instances of class $A$ in the sample. Hence the horizontal line we mentioned at the beginning! For every recall value ($x$ values in PR graph) the corresponding precision value ($y$ values in the PR graph) is equal to $\frac{P}{N}$. A quick side-note: The threshold $q$ is not generally equal to 1 minus the expected recall. This happens in the case of a $C_J$ mentioned above only because of the random uniform distribution of $C_J$'s results; for a different distribution (eg. $ p_i \sim B(2,5)$) this approximate identity relation between $q$ and recall does not hold; $U[0,1]$ was used because it is the easiest to understand and mentally visualise. For a different random distribution in $[0,1]$ the PR profile of $C_J$ will not change though. Just the placement of P-R values for given $q$ values will change. Now regarding a perfect classifier $C_P$, one would mean a classifier that returns probability $1$ to sample instance $y_i$ being of class $A$ if $y_i$ is indeed in class $A$ and additionally $C_P$ returns probability $0$ if $y_i$ is not a member of class $A$. This implies that for any threshold $q$ we will have $100\%$ precision (ie. in graph-terms we get a line starting at precision $100\%$). The only point we do not get $100\%$ precision is at $q = 0$. For $q=0$, the precision falls to the proportion of positive examples in our data ($\frac{P}{N}$) as (insanely?) we classify even points with $0$ probability of being of class $A$ as being in class $A$. The PR graph of $C_P$ has just two possible values for its precision, $1$ and $\frac{P}{N}$. OK and some R code to see this first handed with an example where the positive values correspond to $40\%$ of our sample. Notice that we do a "soft-assignment" of class category in the sense that the probability value associated with each point quantifies to our confidence that this point is of class $A$. rm(list= ls()) library(PRROC) N = 40000 set.seed(444) propOfPos = 0.40 trueLabels = rbinom(N,1,propOfPos) randomProbsB = rbeta(n = N, 2, 5) randomProbsU = runif(n = N) # Junk classifier with beta distribution random results pr1B <- pr.curve(scores.class0 = randomProbsB[trueLabels == 1], scores.class1 = randomProbsB[trueLabels == 0], curve = TRUE) # Junk classifier with uniformly distribution random results pr1U <- pr.curve(scores.class0 = randomProbsU[trueLabels == 1], scores.class1 = randomProbsU[trueLabels == 0], curve = TRUE) # Perfect classifier with prob. 1 for positives and prob. 0 for negatives. pr2 <- pr.curve(scores.class0 = rep(1, times= N*propOfPos), scores.class1 = rep(0, times = N*(1-propOfPos)), curve = TRUE) par(mfrow=c(1,3)) plot(pr1U, main ='"Junk" classifier (Unif(0,1))', auc.main= FALSE, legend=FALSE, col='red', panel.first= grid(), cex.main = 1.5); pcord = pr1U$curve[ which.min( abs(pr1U$curve[,3]- 0.50)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 1) pcord = pr1U$curve[ which.min( abs(pr1U$curve[,3]- 0.20)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 17) plot(pr1B, main ='"Junk" classifier (Beta(2,5))', auc.main= FALSE, legend=FALSE, col='red', panel.first= grid(), cex.main = 1.5); pcord = pr1B$curve[ which.min( abs(pr1B$curve[,3]- 0.50)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 1) pcord = pr1B$curve[ which.min( abs(pr1B$curve[,3]- 0.20)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 17) plot(pr2, main = '"Perfect" classifier', auc.main= FALSE, legend=FALSE, col='red', panel.first= grid(), cex.main = 1.5); where the black circles and triangles denote $q =0.50$ and $q=0.20$ respectively in the first two plots. We immediately see that the "junk" classifiers quickly go to precision equal to $\frac{P}{N}$; similarly the perfect classifier has precision $1$ across all recall variables. Unsurprisingly, the AUCPR for the "junk" classifier is equal to the proportion of positive example in our sample ($\approx 0.40$) and the AUCPR for the "perfect classifier" is approximately equal to $1$. Realistically the PR graph of a perfect classifier is a bit useless because one cannot have $0$ recall ever (we never predict only the negative class); we just start plotting the line from the upper left corner as a matter of convention. Strictly speaking it should just show two points but this would make a horrible curve. :D For the record, there are already have been some very good answer in CV regarding the utility of PR curves: here, here and here. Just reading through them carefully should offer a good general understand about PR curves.
What is "baseline" in precision recall curve
The "baseline curve" in a PR curve plot is a horizontal line with height equal to the number of positive examples $P$ over the total number of training data $N$, ie. the proportion of positive exampl
What is "baseline" in precision recall curve The "baseline curve" in a PR curve plot is a horizontal line with height equal to the number of positive examples $P$ over the total number of training data $N$, ie. the proportion of positive examples in our data ($\frac{P}{N}$). OK, why is this the case though? Let's assume we have a "junk classifier" $C_J$. $C_J$ returns a random probability $p_i$ to the $i$-th sample instance $y_i$ to be in class $A$. For convenience, say $p_i \sim U[0,1]$. The direct implication of this random class assignment is that $C_J$ will have (expected) precision equal to the proportion of positive examples in our data. It is only natural; any totally random sub-sample of our data will have $E\{\frac{P}{N}\}$ correctly classified examples. This will be true for any probability threshold $q$ we might use as a decision boundary for the probabilities of class membership returned by $C_J$. ($q$ denotes a value in $[0,1]$ where probability values greater or equal to $q$ are classified in class $A$.) On the other hand the recall performance of $C_J$ is (in expectation) equal to $q$ if $p_i \sim U[0,1]$. At any given threshold $q$ we will pick (approximately) $(100(1-q))\%$ of our total data which subsequently will contain (approximately) $(100(1-q))\%$ of the total number of instances of class $A$ in the sample. Hence the horizontal line we mentioned at the beginning! For every recall value ($x$ values in PR graph) the corresponding precision value ($y$ values in the PR graph) is equal to $\frac{P}{N}$. A quick side-note: The threshold $q$ is not generally equal to 1 minus the expected recall. This happens in the case of a $C_J$ mentioned above only because of the random uniform distribution of $C_J$'s results; for a different distribution (eg. $ p_i \sim B(2,5)$) this approximate identity relation between $q$ and recall does not hold; $U[0,1]$ was used because it is the easiest to understand and mentally visualise. For a different random distribution in $[0,1]$ the PR profile of $C_J$ will not change though. Just the placement of P-R values for given $q$ values will change. Now regarding a perfect classifier $C_P$, one would mean a classifier that returns probability $1$ to sample instance $y_i$ being of class $A$ if $y_i$ is indeed in class $A$ and additionally $C_P$ returns probability $0$ if $y_i$ is not a member of class $A$. This implies that for any threshold $q$ we will have $100\%$ precision (ie. in graph-terms we get a line starting at precision $100\%$). The only point we do not get $100\%$ precision is at $q = 0$. For $q=0$, the precision falls to the proportion of positive examples in our data ($\frac{P}{N}$) as (insanely?) we classify even points with $0$ probability of being of class $A$ as being in class $A$. The PR graph of $C_P$ has just two possible values for its precision, $1$ and $\frac{P}{N}$. OK and some R code to see this first handed with an example where the positive values correspond to $40\%$ of our sample. Notice that we do a "soft-assignment" of class category in the sense that the probability value associated with each point quantifies to our confidence that this point is of class $A$. rm(list= ls()) library(PRROC) N = 40000 set.seed(444) propOfPos = 0.40 trueLabels = rbinom(N,1,propOfPos) randomProbsB = rbeta(n = N, 2, 5) randomProbsU = runif(n = N) # Junk classifier with beta distribution random results pr1B <- pr.curve(scores.class0 = randomProbsB[trueLabels == 1], scores.class1 = randomProbsB[trueLabels == 0], curve = TRUE) # Junk classifier with uniformly distribution random results pr1U <- pr.curve(scores.class0 = randomProbsU[trueLabels == 1], scores.class1 = randomProbsU[trueLabels == 0], curve = TRUE) # Perfect classifier with prob. 1 for positives and prob. 0 for negatives. pr2 <- pr.curve(scores.class0 = rep(1, times= N*propOfPos), scores.class1 = rep(0, times = N*(1-propOfPos)), curve = TRUE) par(mfrow=c(1,3)) plot(pr1U, main ='"Junk" classifier (Unif(0,1))', auc.main= FALSE, legend=FALSE, col='red', panel.first= grid(), cex.main = 1.5); pcord = pr1U$curve[ which.min( abs(pr1U$curve[,3]- 0.50)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 1) pcord = pr1U$curve[ which.min( abs(pr1U$curve[,3]- 0.20)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 17) plot(pr1B, main ='"Junk" classifier (Beta(2,5))', auc.main= FALSE, legend=FALSE, col='red', panel.first= grid(), cex.main = 1.5); pcord = pr1B$curve[ which.min( abs(pr1B$curve[,3]- 0.50)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 1) pcord = pr1B$curve[ which.min( abs(pr1B$curve[,3]- 0.20)),c(1,2)]; points( pcord[1], pcord[2], col='black', cex= 2, pch = 17) plot(pr2, main = '"Perfect" classifier', auc.main= FALSE, legend=FALSE, col='red', panel.first= grid(), cex.main = 1.5); where the black circles and triangles denote $q =0.50$ and $q=0.20$ respectively in the first two plots. We immediately see that the "junk" classifiers quickly go to precision equal to $\frac{P}{N}$; similarly the perfect classifier has precision $1$ across all recall variables. Unsurprisingly, the AUCPR for the "junk" classifier is equal to the proportion of positive example in our sample ($\approx 0.40$) and the AUCPR for the "perfect classifier" is approximately equal to $1$. Realistically the PR graph of a perfect classifier is a bit useless because one cannot have $0$ recall ever (we never predict only the negative class); we just start plotting the line from the upper left corner as a matter of convention. Strictly speaking it should just show two points but this would make a horrible curve. :D For the record, there are already have been some very good answer in CV regarding the utility of PR curves: here, here and here. Just reading through them carefully should offer a good general understand about PR curves.
What is "baseline" in precision recall curve The "baseline curve" in a PR curve plot is a horizontal line with height equal to the number of positive examples $P$ over the total number of training data $N$, ie. the proportion of positive exampl
8,210
What is "baseline" in precision recall curve
Great answer above. Here is my intuitive way of thinking about it. Imagine you have a bunch of balls red = positive and yellow = negative, and you throw them randomly into a bucket = positive fraction. Then if you have the same number of red and yellow balls, when you calculate PREC=tp/tp+fp=100/100+100 from your bucket red (positive) = yellow (negative), therefore, PREC=0.5. However, if I had 1000 red balls and 100 yellow balls, then in the bucket I would randomly expect PREC=tp/tp+fp=1000/1000+100=0.91 because that is the chance baseline in the positive fraction which is also RP/RP+RN, where RP = real positive and RN = real negative.
What is "baseline" in precision recall curve
Great answer above. Here is my intuitive way of thinking about it. Imagine you have a bunch of balls red = positive and yellow = negative, and you throw them randomly into a bucket = positive fraction
What is "baseline" in precision recall curve Great answer above. Here is my intuitive way of thinking about it. Imagine you have a bunch of balls red = positive and yellow = negative, and you throw them randomly into a bucket = positive fraction. Then if you have the same number of red and yellow balls, when you calculate PREC=tp/tp+fp=100/100+100 from your bucket red (positive) = yellow (negative), therefore, PREC=0.5. However, if I had 1000 red balls and 100 yellow balls, then in the bucket I would randomly expect PREC=tp/tp+fp=1000/1000+100=0.91 because that is the chance baseline in the positive fraction which is also RP/RP+RN, where RP = real positive and RN = real negative.
What is "baseline" in precision recall curve Great answer above. Here is my intuitive way of thinking about it. Imagine you have a bunch of balls red = positive and yellow = negative, and you throw them randomly into a bucket = positive fraction
8,211
What is the difference between Maximum Likelihood Estimation & Gradient Descent?
Maximum likelihood estimation is a general approach to estimating parameters in statistical models by maximizing the likelihood function defined as $$ L(\theta|X) = f(X|\theta) $$ that is, the probability of obtaining data $X$ given some value of parameter $\theta$. Knowing the likelihood function for a given problem you can look for such $\theta$ that maximizes the probability of obtaining the data you have. Sometimes we have known estimators, e.g. arithmetic mean is an MLE estimator for $\mu$ parameter for normal distribution, but in other cases you can use different methods that include using optimization algorithms. ML approach does not tell you how to find the optimal value of $\theta$ -- you can simply take guesses and use the likelihood to compare which guess was better -- it just tells you how you can compare if one value of $\theta$ is "more likely" than the other. Gradient descent is an optimization algorithm. You can use this algorithm to find minimum (or maximum, then it is called gradient ascent) of many different functions. The algorithm does not really care what is the function that it minimizes, it just does what it was asked for. So with using optimization algorithm you have to know somehow how could you tell if one value of the parameter of interest is "better" than the other. You have to provide your algorithm some function to minimize and the algorithm will deal with finding its minimum. You can obtain maximum likelihood estimates using different methods and using an optimization algorithm is one of them. On another hand, gradient descent can be also used to maximize functions other than likelihood function.
What is the difference between Maximum Likelihood Estimation & Gradient Descent?
Maximum likelihood estimation is a general approach to estimating parameters in statistical models by maximizing the likelihood function defined as $$ L(\theta|X) = f(X|\theta) $$ that is, the probabi
What is the difference between Maximum Likelihood Estimation & Gradient Descent? Maximum likelihood estimation is a general approach to estimating parameters in statistical models by maximizing the likelihood function defined as $$ L(\theta|X) = f(X|\theta) $$ that is, the probability of obtaining data $X$ given some value of parameter $\theta$. Knowing the likelihood function for a given problem you can look for such $\theta$ that maximizes the probability of obtaining the data you have. Sometimes we have known estimators, e.g. arithmetic mean is an MLE estimator for $\mu$ parameter for normal distribution, but in other cases you can use different methods that include using optimization algorithms. ML approach does not tell you how to find the optimal value of $\theta$ -- you can simply take guesses and use the likelihood to compare which guess was better -- it just tells you how you can compare if one value of $\theta$ is "more likely" than the other. Gradient descent is an optimization algorithm. You can use this algorithm to find minimum (or maximum, then it is called gradient ascent) of many different functions. The algorithm does not really care what is the function that it minimizes, it just does what it was asked for. So with using optimization algorithm you have to know somehow how could you tell if one value of the parameter of interest is "better" than the other. You have to provide your algorithm some function to minimize and the algorithm will deal with finding its minimum. You can obtain maximum likelihood estimates using different methods and using an optimization algorithm is one of them. On another hand, gradient descent can be also used to maximize functions other than likelihood function.
What is the difference between Maximum Likelihood Estimation & Gradient Descent? Maximum likelihood estimation is a general approach to estimating parameters in statistical models by maximizing the likelihood function defined as $$ L(\theta|X) = f(X|\theta) $$ that is, the probabi
8,212
What is the difference between Maximum Likelihood Estimation & Gradient Descent?
Usually, when we get likelihood function $$f = l(\theta)$$, then we solve equation $$\frac{ df }{ d\theta } = 0$$. we can get the value of $$\theta$$ that can give max or min value of f, done! But logistic regression's likelihood function no closed-form solution by this way. So we have to use other method, such as gradient descent.
What is the difference between Maximum Likelihood Estimation & Gradient Descent?
Usually, when we get likelihood function $$f = l(\theta)$$, then we solve equation $$\frac{ df }{ d\theta } = 0$$. we can get the value of $$\theta$$ that can give max or min value of f, done! But log
What is the difference between Maximum Likelihood Estimation & Gradient Descent? Usually, when we get likelihood function $$f = l(\theta)$$, then we solve equation $$\frac{ df }{ d\theta } = 0$$. we can get the value of $$\theta$$ that can give max or min value of f, done! But logistic regression's likelihood function no closed-form solution by this way. So we have to use other method, such as gradient descent.
What is the difference between Maximum Likelihood Estimation & Gradient Descent? Usually, when we get likelihood function $$f = l(\theta)$$, then we solve equation $$\frac{ df }{ d\theta } = 0$$. we can get the value of $$\theta$$ that can give max or min value of f, done! But log
8,213
Statistical classification of text
I recommend these books - they are highly rated on Amazon too: "Text Mining" by Weiss "Text Mining Application Programming", by Konchady For software, I recommend RapidMiner (with the text plugin), free and open-source. This is my "text mining process": collect the documents (usually a web crawl) [sample if too large] timestamp strip out markup tokenize: break into characters, words, n-grams, or sliding windows stemming (aka lemmatization) [include synonyms] see porter or snowflake algorithm pronouns and articles are usually bad predictors remove stopwords feature vectorization binary (appears or doesn’t) word count relative frequency: tf-idf information gain, chi square [have a minimum value for inclusion] weighting weight words at top of document higher? Then you can start the work of classifying them. kNN, SVM, or Naive Bayes as appropriate. You can see my series of text mining videos here
Statistical classification of text
I recommend these books - they are highly rated on Amazon too: "Text Mining" by Weiss "Text Mining Application Programming", by Konchady For software, I recommend RapidMiner (with the text plugin), fr
Statistical classification of text I recommend these books - they are highly rated on Amazon too: "Text Mining" by Weiss "Text Mining Application Programming", by Konchady For software, I recommend RapidMiner (with the text plugin), free and open-source. This is my "text mining process": collect the documents (usually a web crawl) [sample if too large] timestamp strip out markup tokenize: break into characters, words, n-grams, or sliding windows stemming (aka lemmatization) [include synonyms] see porter or snowflake algorithm pronouns and articles are usually bad predictors remove stopwords feature vectorization binary (appears or doesn’t) word count relative frequency: tf-idf information gain, chi square [have a minimum value for inclusion] weighting weight words at top of document higher? Then you can start the work of classifying them. kNN, SVM, or Naive Bayes as appropriate. You can see my series of text mining videos here
Statistical classification of text I recommend these books - they are highly rated on Amazon too: "Text Mining" by Weiss "Text Mining Application Programming", by Konchady For software, I recommend RapidMiner (with the text plugin), fr
8,214
Statistical classification of text
A great introductory text covering the topics you mentioned is Introduction to Information Retrieval, which is available online in full text for free.
Statistical classification of text
A great introductory text covering the topics you mentioned is Introduction to Information Retrieval, which is available online in full text for free.
Statistical classification of text A great introductory text covering the topics you mentioned is Introduction to Information Retrieval, which is available online in full text for free.
Statistical classification of text A great introductory text covering the topics you mentioned is Introduction to Information Retrieval, which is available online in full text for free.
8,215
Statistical classification of text
Neural network may be to slow for a large number of documents (also this is now pretty much obsolete). And you may also check Random Forest among classifiers; it is quite fast, scales nice and does not need complex tuning.
Statistical classification of text
Neural network may be to slow for a large number of documents (also this is now pretty much obsolete). And you may also check Random Forest among classifiers; it is quite fast, scales nice and does no
Statistical classification of text Neural network may be to slow for a large number of documents (also this is now pretty much obsolete). And you may also check Random Forest among classifiers; it is quite fast, scales nice and does not need complex tuning.
Statistical classification of text Neural network may be to slow for a large number of documents (also this is now pretty much obsolete). And you may also check Random Forest among classifiers; it is quite fast, scales nice and does no
8,216
Statistical classification of text
Firstly I can recommend you the book Foundations of statistical natural language processing by Manning and Schütze. The methods I would use are word-frequency distributions and ngram language models. The first works very well when you want to classify on topic and your topics are specific and expert (having keywords). Ngram modelling is the best way when you want to classify writing styles etc.
Statistical classification of text
Firstly I can recommend you the book Foundations of statistical natural language processing by Manning and Schütze. The methods I would use are word-frequency distributions and ngram language models.
Statistical classification of text Firstly I can recommend you the book Foundations of statistical natural language processing by Manning and Schütze. The methods I would use are word-frequency distributions and ngram language models. The first works very well when you want to classify on topic and your topics are specific and expert (having keywords). Ngram modelling is the best way when you want to classify writing styles etc.
Statistical classification of text Firstly I can recommend you the book Foundations of statistical natural language processing by Manning and Schütze. The methods I would use are word-frequency distributions and ngram language models.
8,217
Statistical classification of text
If you're coming from the programming side, one option is to use the Natural Language Toolkit (NLTK) for Python. There's an O'Reilly book, available freely, which might be a less dense and more practical introduction to building classifiers for documents among other things. If you're interested in beefing up on the statistical side, Roger Levy's book in progress, Probabilistic Models in Study of Language, might not be bad to peruse. It's written for cogsci/compsci grad students starting out with statistical NLP techniques.
Statistical classification of text
If you're coming from the programming side, one option is to use the Natural Language Toolkit (NLTK) for Python. There's an O'Reilly book, available freely, which might be a less dense and more pract
Statistical classification of text If you're coming from the programming side, one option is to use the Natural Language Toolkit (NLTK) for Python. There's an O'Reilly book, available freely, which might be a less dense and more practical introduction to building classifiers for documents among other things. If you're interested in beefing up on the statistical side, Roger Levy's book in progress, Probabilistic Models in Study of Language, might not be bad to peruse. It's written for cogsci/compsci grad students starting out with statistical NLP techniques.
Statistical classification of text If you're coming from the programming side, one option is to use the Natural Language Toolkit (NLTK) for Python. There's an O'Reilly book, available freely, which might be a less dense and more pract
8,218
Statistical classification of text
Naive Bayes is usually the starting point for text classification, here's an article from Dr. Dobbs on how to implement one. It's also often the ending point for text classification because it's so efficient and parallelizes well, SpamAssassin and POPFile use it.
Statistical classification of text
Naive Bayes is usually the starting point for text classification, here's an article from Dr. Dobbs on how to implement one. It's also often the ending point for text classification because it's so ef
Statistical classification of text Naive Bayes is usually the starting point for text classification, here's an article from Dr. Dobbs on how to implement one. It's also often the ending point for text classification because it's so efficient and parallelizes well, SpamAssassin and POPFile use it.
Statistical classification of text Naive Bayes is usually the starting point for text classification, here's an article from Dr. Dobbs on how to implement one. It's also often the ending point for text classification because it's so ef
8,219
If I generate a random symmetric matrix, what's the chance it is positive definite?
If your matrices are drawn from standard-normal iid entries, the probability of being positive-definite is approximately $p_N\approx 3^{-N^2/4}$, so for example if $N=5$, the chance is 1/1000, and goes down quite fast after that. You can find an extended discussion of this question here. You can somewhat intuit this answer by accepting that the eigenvalue distribution of your matrix will be approximately Wigner semicircle, which is symmetric about zero. If the eigenvalues were all independent, you'd have a $(1/2)^N$ chance of positive-definiteness by this logic. In reality you get $N^2$ behavior, both due to correlations between eigenvalues and the laws governing large deviations of eigenvalues, specifically the smallest and largest. Specifically, random eigenvalues are very much akin to charged particles, and do not like to be close to each other, hence they repel each-other (strangely enough with the same potential field as charged particles, $\propto 1/r$, where $r$ is the distance between adjacent eigenvalues). Asking them to all be positive would therefore be a very tall request. Also, because of universality laws in random matrix theory, I strongly suspect the above probability $p_N$ will likely be the same for essentially any "reasonable" random matrix, with iid entries that have finite mean and standard deviation.
If I generate a random symmetric matrix, what's the chance it is positive definite?
If your matrices are drawn from standard-normal iid entries, the probability of being positive-definite is approximately $p_N\approx 3^{-N^2/4}$, so for example if $N=5$, the chance is 1/1000, and goe
If I generate a random symmetric matrix, what's the chance it is positive definite? If your matrices are drawn from standard-normal iid entries, the probability of being positive-definite is approximately $p_N\approx 3^{-N^2/4}$, so for example if $N=5$, the chance is 1/1000, and goes down quite fast after that. You can find an extended discussion of this question here. You can somewhat intuit this answer by accepting that the eigenvalue distribution of your matrix will be approximately Wigner semicircle, which is symmetric about zero. If the eigenvalues were all independent, you'd have a $(1/2)^N$ chance of positive-definiteness by this logic. In reality you get $N^2$ behavior, both due to correlations between eigenvalues and the laws governing large deviations of eigenvalues, specifically the smallest and largest. Specifically, random eigenvalues are very much akin to charged particles, and do not like to be close to each other, hence they repel each-other (strangely enough with the same potential field as charged particles, $\propto 1/r$, where $r$ is the distance between adjacent eigenvalues). Asking them to all be positive would therefore be a very tall request. Also, because of universality laws in random matrix theory, I strongly suspect the above probability $p_N$ will likely be the same for essentially any "reasonable" random matrix, with iid entries that have finite mean and standard deviation.
If I generate a random symmetric matrix, what's the chance it is positive definite? If your matrices are drawn from standard-normal iid entries, the probability of being positive-definite is approximately $p_N\approx 3^{-N^2/4}$, so for example if $N=5$, the chance is 1/1000, and goe
8,220
What are "residual connections" in RNNs?
Residual connections are the same thing as 'skip connections'. They are used to allow gradients to flow through a network directly, without passing through non-linear activation functions. Non-linear activation functions, by nature of being non-linear, cause the gradients to explode or vanish (depending on the weights). Skip connections form conceptually a 'bus' which flows right the way through the network, and in reverse, the gradients can flow backwards along it too. Each 'block' of network layers, such as conv layers, poolings, etc, taps the values at a point along the bus, and then adds/subtracts values onto the bus. This means that the blocks do affect the gradients, and conversely, affect the forward output values too. However, there is a direct connection through the network. Actually, resnets ('residual networks') are not entirely well understood yet. They clearly work empirically. Some papers show they are like an ensemble of shallower networks. There are various theories :) Which are not necessarily self-contradictory. But either way, an explanation of exactly why they work is outside the scope of a Cross Validated question, being an open research question :) I made a diagram of how I see resnets in my head, in an earlier answer, at Gradient backpropagation through ResNet skip connections . Here is the diagram I made, reproduced: I understood the main concept, but how are these residual connections usually implemented? They remind me of how an LSTM unit works. So, imagine a network where at each layer you have two conv blocks, in parallel: - the input goes into each block - the outputs are summed Now, replace one of those blocks with a direct connection. An identity block if you like, or no block at all. That's a residual/skip connection. In practice, the remaining conv unit would probably be two units in series, with an activation layer in between.
What are "residual connections" in RNNs?
Residual connections are the same thing as 'skip connections'. They are used to allow gradients to flow through a network directly, without passing through non-linear activation functions. Non-linear
What are "residual connections" in RNNs? Residual connections are the same thing as 'skip connections'. They are used to allow gradients to flow through a network directly, without passing through non-linear activation functions. Non-linear activation functions, by nature of being non-linear, cause the gradients to explode or vanish (depending on the weights). Skip connections form conceptually a 'bus' which flows right the way through the network, and in reverse, the gradients can flow backwards along it too. Each 'block' of network layers, such as conv layers, poolings, etc, taps the values at a point along the bus, and then adds/subtracts values onto the bus. This means that the blocks do affect the gradients, and conversely, affect the forward output values too. However, there is a direct connection through the network. Actually, resnets ('residual networks') are not entirely well understood yet. They clearly work empirically. Some papers show they are like an ensemble of shallower networks. There are various theories :) Which are not necessarily self-contradictory. But either way, an explanation of exactly why they work is outside the scope of a Cross Validated question, being an open research question :) I made a diagram of how I see resnets in my head, in an earlier answer, at Gradient backpropagation through ResNet skip connections . Here is the diagram I made, reproduced: I understood the main concept, but how are these residual connections usually implemented? They remind me of how an LSTM unit works. So, imagine a network where at each layer you have two conv blocks, in parallel: - the input goes into each block - the outputs are summed Now, replace one of those blocks with a direct connection. An identity block if you like, or no block at all. That's a residual/skip connection. In practice, the remaining conv unit would probably be two units in series, with an activation layer in between.
What are "residual connections" in RNNs? Residual connections are the same thing as 'skip connections'. They are used to allow gradients to flow through a network directly, without passing through non-linear activation functions. Non-linear
8,221
What are "residual connections" in RNNs?
With respect to Deep Residual Learning for Image Recognition, I think it's correct to say that a ResNet contains both residual connections and skip connections, and that they are not the same thing. Here's a quotation from the paper: We hypothesize that it is easier to optimize the residual mapping than to optimize the original, unreferenced mapping. To the extreme, if an identity mapping were optimal, it would be easier to push the residual to zero than to fit an identity mapping by a stack of nonlinear layers. The concept of pushing the residual to zero indicates that the residual connection corresponds to layers that are learned rather than to the skip connection. I think it's best to understand a "ResNet" as a network that learns residuals. In the following image (figure 2 from the paper), the path going through the weight layers and relu activation is the residual connection while the identity path is the skip connection. The authors of Squeeze-and-Excitation Networks seem to have this understanding as well based on figure 3 from their paper. References https://arxiv.org/pdf/1512.03385.pdf https://arxiv.org/pdf/1709.01507.pdf https://tim.cogan.dev/residual-connections
What are "residual connections" in RNNs?
With respect to Deep Residual Learning for Image Recognition, I think it's correct to say that a ResNet contains both residual connections and skip connections, and that they are not the same thing. H
What are "residual connections" in RNNs? With respect to Deep Residual Learning for Image Recognition, I think it's correct to say that a ResNet contains both residual connections and skip connections, and that they are not the same thing. Here's a quotation from the paper: We hypothesize that it is easier to optimize the residual mapping than to optimize the original, unreferenced mapping. To the extreme, if an identity mapping were optimal, it would be easier to push the residual to zero than to fit an identity mapping by a stack of nonlinear layers. The concept of pushing the residual to zero indicates that the residual connection corresponds to layers that are learned rather than to the skip connection. I think it's best to understand a "ResNet" as a network that learns residuals. In the following image (figure 2 from the paper), the path going through the weight layers and relu activation is the residual connection while the identity path is the skip connection. The authors of Squeeze-and-Excitation Networks seem to have this understanding as well based on figure 3 from their paper. References https://arxiv.org/pdf/1512.03385.pdf https://arxiv.org/pdf/1709.01507.pdf https://tim.cogan.dev/residual-connections
What are "residual connections" in RNNs? With respect to Deep Residual Learning for Image Recognition, I think it's correct to say that a ResNet contains both residual connections and skip connections, and that they are not the same thing. H
8,222
What are "residual connections" in RNNs?
For better and deeper understanding of the Residual Connection concept, you may want to also read this paper: Deep Residual Learning for Image Recognition. This is the same paper that is also referenced by "Attention Is All You Need" paper when explaining encoder element in the Transformers architecture.
What are "residual connections" in RNNs?
For better and deeper understanding of the Residual Connection concept, you may want to also read this paper: Deep Residual Learning for Image Recognition. This is the same paper that is also referenc
What are "residual connections" in RNNs? For better and deeper understanding of the Residual Connection concept, you may want to also read this paper: Deep Residual Learning for Image Recognition. This is the same paper that is also referenced by "Attention Is All You Need" paper when explaining encoder element in the Transformers architecture.
What are "residual connections" in RNNs? For better and deeper understanding of the Residual Connection concept, you may want to also read this paper: Deep Residual Learning for Image Recognition. This is the same paper that is also referenc
8,223
What are "residual connections" in RNNs?
in super-resolution there are many network architectures with residual connections. If you have a low-resolution picture x and you want to reconstruct a high resolution picture y, a network has to learn to not only predict the missing pixels from y, it also has to learn the representation of x. Because x and y have a high correlation -> y is a higher resolution representation of x, you can add a skip connection from your input to the output of your last layer. That would mean, all the stuff happening in the network will only focus of learning y-x. Because at the end, x is added to the output.
What are "residual connections" in RNNs?
in super-resolution there are many network architectures with residual connections. If you have a low-resolution picture x and you want to reconstruct a high resolution picture y, a network has to le
What are "residual connections" in RNNs? in super-resolution there are many network architectures with residual connections. If you have a low-resolution picture x and you want to reconstruct a high resolution picture y, a network has to learn to not only predict the missing pixels from y, it also has to learn the representation of x. Because x and y have a high correlation -> y is a higher resolution representation of x, you can add a skip connection from your input to the output of your last layer. That would mean, all the stuff happening in the network will only focus of learning y-x. Because at the end, x is added to the output.
What are "residual connections" in RNNs? in super-resolution there are many network architectures with residual connections. If you have a low-resolution picture x and you want to reconstruct a high resolution picture y, a network has to le
8,224
What are "residual connections" in RNNs?
Adding up to the answers above, Residual connection implies a mechanism which carries gradients from the initial layers to the later layers in a deep network, preventing its gradient from vanishing. It does not resolve the vanishing gradient problems but avoids them with shallow networks. You can imagine this as a bunch of deep ensembles which also has many shallow members. Surprisingly, experiments show that in a 100 layers deep network, a significant amount of the gradients is coming from those residual skip connections. For more: Shattered Gradient Problem Revisiting ResNet Revisiting ResNet
What are "residual connections" in RNNs?
Adding up to the answers above, Residual connection implies a mechanism which carries gradients from the initial layers to the later layers in a deep network, preventing its gradient from vanishing. I
What are "residual connections" in RNNs? Adding up to the answers above, Residual connection implies a mechanism which carries gradients from the initial layers to the later layers in a deep network, preventing its gradient from vanishing. It does not resolve the vanishing gradient problems but avoids them with shallow networks. You can imagine this as a bunch of deep ensembles which also has many shallow members. Surprisingly, experiments show that in a 100 layers deep network, a significant amount of the gradients is coming from those residual skip connections. For more: Shattered Gradient Problem Revisiting ResNet Revisiting ResNet
What are "residual connections" in RNNs? Adding up to the answers above, Residual connection implies a mechanism which carries gradients from the initial layers to the later layers in a deep network, preventing its gradient from vanishing. I
8,225
When are confidence intervals useful?
I like to think of CIs as some way to escape the Hypothesis Testing (HT) framework, at least the binary decision framework following Neyman's approach, and keep in line with theory of measurement in some way. More precisely, I view them as more close to the reliability of an estimation (a difference of means, for instance), and conversely HT are more close to hypothetico-deductive reasoning, with its pitfalls (we cannot accept the null, the alternative is often stochastic, etc.). Still, with both interval estimation and HT we have to rely on distribution assumptions most of the time (e.g. a sampling distribution under $H_0$), which allows to make inference from our sample to the general population or a representative one (at least in the frequentist approach). In many context, CIs are complementary to usual HT, and I view them as in the following picture (it is under $H_0$): that is, under the HT framework (left), you look at how far your statistic is from the null, while with CIs (right) you are looking at the null effect "from your statistic", in a certain sense. Also, note that for certain kind of statistic, like odds-ratio, HT are often meaningless and it is better to look at its associated CI which is assymmetrical and provide more relevant information as to the direction and precision of the association, if any.
When are confidence intervals useful?
I like to think of CIs as some way to escape the Hypothesis Testing (HT) framework, at least the binary decision framework following Neyman's approach, and keep in line with theory of measurement in s
When are confidence intervals useful? I like to think of CIs as some way to escape the Hypothesis Testing (HT) framework, at least the binary decision framework following Neyman's approach, and keep in line with theory of measurement in some way. More precisely, I view them as more close to the reliability of an estimation (a difference of means, for instance), and conversely HT are more close to hypothetico-deductive reasoning, with its pitfalls (we cannot accept the null, the alternative is often stochastic, etc.). Still, with both interval estimation and HT we have to rely on distribution assumptions most of the time (e.g. a sampling distribution under $H_0$), which allows to make inference from our sample to the general population or a representative one (at least in the frequentist approach). In many context, CIs are complementary to usual HT, and I view them as in the following picture (it is under $H_0$): that is, under the HT framework (left), you look at how far your statistic is from the null, while with CIs (right) you are looking at the null effect "from your statistic", in a certain sense. Also, note that for certain kind of statistic, like odds-ratio, HT are often meaningless and it is better to look at its associated CI which is assymmetrical and provide more relevant information as to the direction and precision of the association, if any.
When are confidence intervals useful? I like to think of CIs as some way to escape the Hypothesis Testing (HT) framework, at least the binary decision framework following Neyman's approach, and keep in line with theory of measurement in s
8,226
When are confidence intervals useful?
An alternative approach relevant to your 2nd Q, "Are there ways of looking at confidence intervals, at least in some circumstances, which would be meaningful to users of statistics?": You should take a look at Bayesian inference and the resulting credible intervals. A 95% credible interval can be interpreted as an interval which you believe has 95% probability of including the true parameter value. The price you pay is that you need to put a prior probability distribution on the values you believe the true parameter is likely to take before collecting the data. And your prior may differ from someone else's prior, so your resulting credible intervals may also differ even when you use the same data. This is only my quick and crude attempt to summarise! A good recent textbook with a practical focus is: Andrew Gelman, John B. Carlin, Hal S. Stern and Donald B. Rubin. "Bayesian Data Analysis" (2nd edition). Chapman & Hall/CRC, 2003. ISBN 978-1584883883
When are confidence intervals useful?
An alternative approach relevant to your 2nd Q, "Are there ways of looking at confidence intervals, at least in some circumstances, which would be meaningful to users of statistics?": You should take
When are confidence intervals useful? An alternative approach relevant to your 2nd Q, "Are there ways of looking at confidence intervals, at least in some circumstances, which would be meaningful to users of statistics?": You should take a look at Bayesian inference and the resulting credible intervals. A 95% credible interval can be interpreted as an interval which you believe has 95% probability of including the true parameter value. The price you pay is that you need to put a prior probability distribution on the values you believe the true parameter is likely to take before collecting the data. And your prior may differ from someone else's prior, so your resulting credible intervals may also differ even when you use the same data. This is only my quick and crude attempt to summarise! A good recent textbook with a practical focus is: Andrew Gelman, John B. Carlin, Hal S. Stern and Donald B. Rubin. "Bayesian Data Analysis" (2nd edition). Chapman & Hall/CRC, 2003. ISBN 978-1584883883
When are confidence intervals useful? An alternative approach relevant to your 2nd Q, "Are there ways of looking at confidence intervals, at least in some circumstances, which would be meaningful to users of statistics?": You should take
8,227
When are confidence intervals useful?
You are correct in saying that the 95% confidence intervals are things that result from using a method that works in 95% of cases, rather than any individual interval having a 95% likelihood of containing the expected value. "The logical basis and interpretation of confidence limits are, even now, a matter of controversy." {David Colquhoun, 1971, Lectures on Biostatistics} That quotation is taken from a statistics textbook published in 1971, but I would contend that it is still true in 2010. The controversy is probably most extreme in the case of confidence intervals for binomial proportions. There are many competing methods for calculating those confidence intervals, but they are all inaccurate in one or more senses and even the worst performing method has proponents among textbook authors. Even so called ‘exact’ intervals fail to yield the properties expected of confidence intervals. In a paper written for surgeons (widely known for their interest in statistics!), John Ludbrook and I argued for the routine use of confidence intervals calculated using a uniform Bayesian prior because such intervals have frequentist properties as good as any other method (on average exactly 95% coverage over all true proportions) but, importantly, much better coverage over all observed proportions (exactly 95% coverage). The paper, because of its target audience, is not terribly detailed and so it may not convince all statistician, but I am working on a follow-up paper with the full set of results and justifications. This is a case where the Bayesian approach has frequentist properties as good as the frequentist approach, something that happens fairly often. The assumption of a uniform prior is not problematical because a uniform distribution of population proportions is built into every calculation of frequentist coverage that I've come across. You ask: "Are there ways of looking at confidence intervals, at least in some circumstances, which would be meaningful to users of statistics?" My answer, then, is that for binomial confidence intervals one can get intervals that contain the population proportion exactly 95% of the time for all observed proportions. That is a yes. However, the conventional use of confidence intervals expects coverage for all population proportions and for that the answer is "No!" The length of the answers to your question, and the various responses to them suggests that confidence intervals are widely misunderstood. If we change our objective from coverage for all true parameter values to coverage of the true parameter value for all sample values, it might get easier because the intervals will then be shaped to be directly relevant to the observed values rather than for the performance of the method per se.
When are confidence intervals useful?
You are correct in saying that the 95% confidence intervals are things that result from using a method that works in 95% of cases, rather than any individual interval having a 95% likelihood of contai
When are confidence intervals useful? You are correct in saying that the 95% confidence intervals are things that result from using a method that works in 95% of cases, rather than any individual interval having a 95% likelihood of containing the expected value. "The logical basis and interpretation of confidence limits are, even now, a matter of controversy." {David Colquhoun, 1971, Lectures on Biostatistics} That quotation is taken from a statistics textbook published in 1971, but I would contend that it is still true in 2010. The controversy is probably most extreme in the case of confidence intervals for binomial proportions. There are many competing methods for calculating those confidence intervals, but they are all inaccurate in one or more senses and even the worst performing method has proponents among textbook authors. Even so called ‘exact’ intervals fail to yield the properties expected of confidence intervals. In a paper written for surgeons (widely known for their interest in statistics!), John Ludbrook and I argued for the routine use of confidence intervals calculated using a uniform Bayesian prior because such intervals have frequentist properties as good as any other method (on average exactly 95% coverage over all true proportions) but, importantly, much better coverage over all observed proportions (exactly 95% coverage). The paper, because of its target audience, is not terribly detailed and so it may not convince all statistician, but I am working on a follow-up paper with the full set of results and justifications. This is a case where the Bayesian approach has frequentist properties as good as the frequentist approach, something that happens fairly often. The assumption of a uniform prior is not problematical because a uniform distribution of population proportions is built into every calculation of frequentist coverage that I've come across. You ask: "Are there ways of looking at confidence intervals, at least in some circumstances, which would be meaningful to users of statistics?" My answer, then, is that for binomial confidence intervals one can get intervals that contain the population proportion exactly 95% of the time for all observed proportions. That is a yes. However, the conventional use of confidence intervals expects coverage for all population proportions and for that the answer is "No!" The length of the answers to your question, and the various responses to them suggests that confidence intervals are widely misunderstood. If we change our objective from coverage for all true parameter values to coverage of the true parameter value for all sample values, it might get easier because the intervals will then be shaped to be directly relevant to the observed values rather than for the performance of the method per se.
When are confidence intervals useful? You are correct in saying that the 95% confidence intervals are things that result from using a method that works in 95% of cases, rather than any individual interval having a 95% likelihood of contai
8,228
When are confidence intervals useful?
I think the premise of this question is flawed because it denies the distinction between the uncertain and the known. Describing a coin flip provides a good analogy. Before the coin is flipped, the outcome is uncertain; afterwards, it is no longer "hypothetical." Confusing this fait accompli with the actual situation we wish to understand (the behavior of the coin, or decisions that are to be made as a result of its outcome) essentially denies a role for probability in understanding the world. This contrast is thrown in sharp relief within an experimental or regulatory arena. In such cases the scientist or the regulator know they will be faced with situations whose outcomes, at any time beforehand, are unknown, yet they must make important determinations such as how to design the experiment or establish the criteria to use in determining compliance with regulations (for drug testing, workplace safety, environmental standards, and so on). These people and the institutions for which they work need methods and knowledge of the probabilistic characteristics of those methods in order to develop optimal and defensible strategies, such as good experimental designs and fair decision procedures that err as little as possible. Confidence intervals, despite their classically poor justification, fit into this decision-theoretic framework. When a method of constructing a random interval has a combination of good properties, such as assuring a minimal expected coverage of the interval and minimizing the expected length of the interval--both of them a priori properties, not a posteriori ones--then over a long career of using that method we can minimize the costs associated with the actions that are indicated by that method.
When are confidence intervals useful?
I think the premise of this question is flawed because it denies the distinction between the uncertain and the known. Describing a coin flip provides a good analogy. Before the coin is flipped, the o
When are confidence intervals useful? I think the premise of this question is flawed because it denies the distinction between the uncertain and the known. Describing a coin flip provides a good analogy. Before the coin is flipped, the outcome is uncertain; afterwards, it is no longer "hypothetical." Confusing this fait accompli with the actual situation we wish to understand (the behavior of the coin, or decisions that are to be made as a result of its outcome) essentially denies a role for probability in understanding the world. This contrast is thrown in sharp relief within an experimental or regulatory arena. In such cases the scientist or the regulator know they will be faced with situations whose outcomes, at any time beforehand, are unknown, yet they must make important determinations such as how to design the experiment or establish the criteria to use in determining compliance with regulations (for drug testing, workplace safety, environmental standards, and so on). These people and the institutions for which they work need methods and knowledge of the probabilistic characteristics of those methods in order to develop optimal and defensible strategies, such as good experimental designs and fair decision procedures that err as little as possible. Confidence intervals, despite their classically poor justification, fit into this decision-theoretic framework. When a method of constructing a random interval has a combination of good properties, such as assuring a minimal expected coverage of the interval and minimizing the expected length of the interval--both of them a priori properties, not a posteriori ones--then over a long career of using that method we can minimize the costs associated with the actions that are indicated by that method.
When are confidence intervals useful? I think the premise of this question is flawed because it denies the distinction between the uncertain and the known. Describing a coin flip provides a good analogy. Before the coin is flipped, the o
8,229
When are confidence intervals useful?
This is a great discussion. I feel that Bayesian credible intervals and likelihood support intervals are the way to go, as well as Bayesian posterior probabilities of events of interest (e.g., a drug is efficacious). But supplanting P-values with confidence intervals is a major gain. Virtually every issue of the finest medical journals such as NEJM and JAMA has a paper with the "absence of evidence is not evidence of absence" problem in their abstracts. The use of confidence intervals will largely prevent such blunders. A great little text is http://www.amazon.com/Statistics-Confidence-Intervals-Statistical-Guidelines/dp/0727913751
When are confidence intervals useful?
This is a great discussion. I feel that Bayesian credible intervals and likelihood support intervals are the way to go, as well as Bayesian posterior probabilities of events of interest (e.g., a drug
When are confidence intervals useful? This is a great discussion. I feel that Bayesian credible intervals and likelihood support intervals are the way to go, as well as Bayesian posterior probabilities of events of interest (e.g., a drug is efficacious). But supplanting P-values with confidence intervals is a major gain. Virtually every issue of the finest medical journals such as NEJM and JAMA has a paper with the "absence of evidence is not evidence of absence" problem in their abstracts. The use of confidence intervals will largely prevent such blunders. A great little text is http://www.amazon.com/Statistics-Confidence-Intervals-Statistical-Guidelines/dp/0727913751
When are confidence intervals useful? This is a great discussion. I feel that Bayesian credible intervals and likelihood support intervals are the way to go, as well as Bayesian posterior probabilities of events of interest (e.g., a drug
8,230
When are confidence intervals useful?
To address your question directly: Suppose that you are contemplating the use of a machine to fill a cereal box with a certain amount of cereal. Obviously, you do not want to overfill/underfill the box. You want to assess the reliability of the machine. You perform a series of tests like so: (a) Use the machine to fill the box and (b) Measure the amount of cereal that is filled in the box. Using the data collected you construct a confidence interval for the amount of cereal that the machine is likely to fill in the box. This confidence interval tells us that the interval we obtained has a 95% probability that it will contain the the true amount of cereal the machine will put in the box. As you say, the interpretation of the confidence interval relies on hypothetical, unseen samples generated by the method under consideration. But, this is precisely what we want in our context. In the above context, we will use the machine repeatedly to fill the box and thus we care about hypothetical, unseen realizations of the amount of cereal the machine fills in the box. To abstract away from the above context: a confidence interval gives us a guarantee that if we were to use the method under investigation (in the above example method = machine) repeatedly there is a 95% probability that the confidence interval will have the true parameter.
When are confidence intervals useful?
To address your question directly: Suppose that you are contemplating the use of a machine to fill a cereal box with a certain amount of cereal. Obviously, you do not want to overfill/underfill the bo
When are confidence intervals useful? To address your question directly: Suppose that you are contemplating the use of a machine to fill a cereal box with a certain amount of cereal. Obviously, you do not want to overfill/underfill the box. You want to assess the reliability of the machine. You perform a series of tests like so: (a) Use the machine to fill the box and (b) Measure the amount of cereal that is filled in the box. Using the data collected you construct a confidence interval for the amount of cereal that the machine is likely to fill in the box. This confidence interval tells us that the interval we obtained has a 95% probability that it will contain the the true amount of cereal the machine will put in the box. As you say, the interpretation of the confidence interval relies on hypothetical, unseen samples generated by the method under consideration. But, this is precisely what we want in our context. In the above context, we will use the machine repeatedly to fill the box and thus we care about hypothetical, unseen realizations of the amount of cereal the machine fills in the box. To abstract away from the above context: a confidence interval gives us a guarantee that if we were to use the method under investigation (in the above example method = machine) repeatedly there is a 95% probability that the confidence interval will have the true parameter.
When are confidence intervals useful? To address your question directly: Suppose that you are contemplating the use of a machine to fill a cereal box with a certain amount of cereal. Obviously, you do not want to overfill/underfill the bo
8,231
Is hour of day a categorical variable?
Depending on what you want to model, hours (and many other attributes like seasons) are actually ordinal cyclic variables. In case of seasons you can consider them to be more or less categorical, and in case of hours you can model them as continuous as well. However, using hours in your model in a form that does not take care of cyclicity for you will not be fruitful. Instead try to come up with some kind of transformation. Using hours you could use a trigonometric approach by xhr = sin(2*pi*hr/24) yhr = cos(2*pi*hr/24) Thus you would instead use xhr and yhr for modelling. See this post for example: Use of circular predictors in linear regression.
Is hour of day a categorical variable?
Depending on what you want to model, hours (and many other attributes like seasons) are actually ordinal cyclic variables. In case of seasons you can consider them to be more or less categorical, and
Is hour of day a categorical variable? Depending on what you want to model, hours (and many other attributes like seasons) are actually ordinal cyclic variables. In case of seasons you can consider them to be more or less categorical, and in case of hours you can model them as continuous as well. However, using hours in your model in a form that does not take care of cyclicity for you will not be fruitful. Instead try to come up with some kind of transformation. Using hours you could use a trigonometric approach by xhr = sin(2*pi*hr/24) yhr = cos(2*pi*hr/24) Thus you would instead use xhr and yhr for modelling. See this post for example: Use of circular predictors in linear regression.
Is hour of day a categorical variable? Depending on what you want to model, hours (and many other attributes like seasons) are actually ordinal cyclic variables. In case of seasons you can consider them to be more or less categorical, and
8,232
Is hour of day a categorical variable?
Hour of the day isn't best represented as a categorical variable, because there is a natural ordering of the values. Hair color, for example, is categorical, because the ordering of the categories has no meaning - {red, brown, blonde} is as valid as {blonde, brown, red}. Hour of the day, on the other hand, has a natural ordering - 9am is closer to 10am or 8am than it is to 6pm. It is best thought of as a discrete ordinal variable. It has an added characteristic of being cyclic, since 12am follows 11pm and precedes 1am.
Is hour of day a categorical variable?
Hour of the day isn't best represented as a categorical variable, because there is a natural ordering of the values. Hair color, for example, is categorical, because the ordering of the categories has
Is hour of day a categorical variable? Hour of the day isn't best represented as a categorical variable, because there is a natural ordering of the values. Hair color, for example, is categorical, because the ordering of the categories has no meaning - {red, brown, blonde} is as valid as {blonde, brown, red}. Hour of the day, on the other hand, has a natural ordering - 9am is closer to 10am or 8am than it is to 6pm. It is best thought of as a discrete ordinal variable. It has an added characteristic of being cyclic, since 12am follows 11pm and precedes 1am.
Is hour of day a categorical variable? Hour of the day isn't best represented as a categorical variable, because there is a natural ordering of the values. Hair color, for example, is categorical, because the ordering of the categories has
8,233
Is hour of day a categorical variable?
Theoretically, it depends on how you format the variable i.e. it can be "continuous" (modeled with a single coefficient) or categorical (a coefficient per "hour" of day). You could also do a mix of both e.g. piece-wise functions. Practically, because 0 and 23 is essentially the same "hour" of day, I would consider grouping periods of the day into larger, more homogenous and credible groupings. For example, in 8 hour increments - 8am-4pm, 4pm-12am, and 12-8am.
Is hour of day a categorical variable?
Theoretically, it depends on how you format the variable i.e. it can be "continuous" (modeled with a single coefficient) or categorical (a coefficient per "hour" of day). You could also do a mix of bo
Is hour of day a categorical variable? Theoretically, it depends on how you format the variable i.e. it can be "continuous" (modeled with a single coefficient) or categorical (a coefficient per "hour" of day). You could also do a mix of both e.g. piece-wise functions. Practically, because 0 and 23 is essentially the same "hour" of day, I would consider grouping periods of the day into larger, more homogenous and credible groupings. For example, in 8 hour increments - 8am-4pm, 4pm-12am, and 12-8am.
Is hour of day a categorical variable? Theoretically, it depends on how you format the variable i.e. it can be "continuous" (modeled with a single coefficient) or categorical (a coefficient per "hour" of day). You could also do a mix of bo
8,234
How to judge if a supervised machine learning model is overfitting or not?
In short: by validating your model. The main reason of validation is to assert no overfit occurs and to estimate generalized model performance. Overfit First let us look at what overfitting actually is. Models are normally trained to fit a dataset by minimizing some loss function on a training set. There is however a limit where minimizing this training error will no longer benefit the models true performance, but only minimize the error on the specific set of data. This essentially means that the model has been too tightly fitted to the specific data points in the training set, trying to model patterns in the data originating from noise. This concept is called overfit. An example of overfit is displayed below where you see the training set in black and a larger set from the actual population in the background. In this figure you can see that the blue model is too tightly fitted to the training set, modeling the underlying noise. In order to judge if a model is overfitted or not, we need to estimate the generalized error (or performance) that the model will have on future data and compare it to our performance on the training set. Estimating this error can be done in several different ways. Dataset split The most straightforward approach to estimating the generalized performance is to partition the dataset into three parts, a training set, a validation set and a test set. The training set is used for training the model to fit the data, the validation set is used to measure differences in performance between models in order to select the best one and the test set to assert that the model selection process does not overfit to the first two sets. To estimate the amount of overfit simply evaluate your metrics of interest on the test set as a last step and compare it to your performance on the training set. You mention ROC but in my opinion you should also look at other metrics such as for example brier score or a calibration plot to ensure model performance. This is of course depending on your problem. There are a lot of metrics but this is besides the point here. This method is very common and respected but it puts a big demand on availability of data. If your dataset is too small you will most probably lose a lot of performance and your results will be biased on the split. Cross-validation One way to get around wasting a large part of the data to validation and test is to use cross-validation (CV) which estimates the generalized performance using the same data as is used to train the model. The idea behind cross-validation is to split the dataset up into a certain number of subsets, and then use each of these subsets as held out test sets in turn while using the rest of the data to train the model. Averaging the metric over all the folds will give you an estimate of the model performance. The final model is then generally trained using all data. However, the CV estimate is not unbiased. But the more folds you use the smaller the bias but then you get larger variance instead. As in the dataset split we get an estimate of the model performance and to estimate the overfit you simply compare the metrics from your CV with the ones acquired from evaluating the metrics on your training set. Bootstrap The idea behind bootstrap is similar to CV but instead of splitting the dataset into parts we introduce randomness in the training by drawing training sets from the whole dataset repeatedly with replacement and performing the full training phase on each of these bootstrap samples. The simplest form of bootstrap validation simply evaluates the metrics on the samples not found in the training set (i.e. the ones left out) and average over all repeats. This method will give you an estimate of model performance which in most cases are less biased than CV. Again, comparing it with your training set performance and you get the overfit. There are ways to improve the bootstrap validation. The .632+ method is known to give better, more robust estimates of the generalized model performance, taking overfit into account. (If you're interested the original article is a good read: Improvements on Cross-Validation: The 632+ Bootstrap Method) I hope this answers your question. If you are interested in model validation I recommend reading the part on validation in the book The elements of statistical learning: data mining, inference and prediction which is freely available online.
How to judge if a supervised machine learning model is overfitting or not?
In short: by validating your model. The main reason of validation is to assert no overfit occurs and to estimate generalized model performance. Overfit First let us look at what overfitting actually
How to judge if a supervised machine learning model is overfitting or not? In short: by validating your model. The main reason of validation is to assert no overfit occurs and to estimate generalized model performance. Overfit First let us look at what overfitting actually is. Models are normally trained to fit a dataset by minimizing some loss function on a training set. There is however a limit where minimizing this training error will no longer benefit the models true performance, but only minimize the error on the specific set of data. This essentially means that the model has been too tightly fitted to the specific data points in the training set, trying to model patterns in the data originating from noise. This concept is called overfit. An example of overfit is displayed below where you see the training set in black and a larger set from the actual population in the background. In this figure you can see that the blue model is too tightly fitted to the training set, modeling the underlying noise. In order to judge if a model is overfitted or not, we need to estimate the generalized error (or performance) that the model will have on future data and compare it to our performance on the training set. Estimating this error can be done in several different ways. Dataset split The most straightforward approach to estimating the generalized performance is to partition the dataset into three parts, a training set, a validation set and a test set. The training set is used for training the model to fit the data, the validation set is used to measure differences in performance between models in order to select the best one and the test set to assert that the model selection process does not overfit to the first two sets. To estimate the amount of overfit simply evaluate your metrics of interest on the test set as a last step and compare it to your performance on the training set. You mention ROC but in my opinion you should also look at other metrics such as for example brier score or a calibration plot to ensure model performance. This is of course depending on your problem. There are a lot of metrics but this is besides the point here. This method is very common and respected but it puts a big demand on availability of data. If your dataset is too small you will most probably lose a lot of performance and your results will be biased on the split. Cross-validation One way to get around wasting a large part of the data to validation and test is to use cross-validation (CV) which estimates the generalized performance using the same data as is used to train the model. The idea behind cross-validation is to split the dataset up into a certain number of subsets, and then use each of these subsets as held out test sets in turn while using the rest of the data to train the model. Averaging the metric over all the folds will give you an estimate of the model performance. The final model is then generally trained using all data. However, the CV estimate is not unbiased. But the more folds you use the smaller the bias but then you get larger variance instead. As in the dataset split we get an estimate of the model performance and to estimate the overfit you simply compare the metrics from your CV with the ones acquired from evaluating the metrics on your training set. Bootstrap The idea behind bootstrap is similar to CV but instead of splitting the dataset into parts we introduce randomness in the training by drawing training sets from the whole dataset repeatedly with replacement and performing the full training phase on each of these bootstrap samples. The simplest form of bootstrap validation simply evaluates the metrics on the samples not found in the training set (i.e. the ones left out) and average over all repeats. This method will give you an estimate of model performance which in most cases are less biased than CV. Again, comparing it with your training set performance and you get the overfit. There are ways to improve the bootstrap validation. The .632+ method is known to give better, more robust estimates of the generalized model performance, taking overfit into account. (If you're interested the original article is a good read: Improvements on Cross-Validation: The 632+ Bootstrap Method) I hope this answers your question. If you are interested in model validation I recommend reading the part on validation in the book The elements of statistical learning: data mining, inference and prediction which is freely available online.
How to judge if a supervised machine learning model is overfitting or not? In short: by validating your model. The main reason of validation is to assert no overfit occurs and to estimate generalized model performance. Overfit First let us look at what overfitting actually
8,235
How to judge if a supervised machine learning model is overfitting or not?
Here's how you can estimate the extent of overfitting: Get an internal error estimate. Either resubstitutio (= predict training data), or if you do an inner cross "validation" to optimize hyperparameters, also that measure would be of interest. Get an independent test set error estimate. Usually, resampling (iterated cross validation or out-of-bootstrap* is recommended. But you need to be careful that no data leaks occur. I.e. the resampling loop must recalculate all steps that have calculations spanning more than one case. That includes pre-processing steps such as centering, scaling, etc. Also, make sure you split at the highest level if you have a "hierarchical" (also known as "clustered) data structure such as repeated measurements of e.g. the same patient (=> resample patients). Then compare how much better the "inner" error estimate looks than the independent one. Here's an example: Trefferrate = hit rate (% correct classified), Variablenzahl = number of variables (= model complexity) Symbols: . resubstitution, + internal leave-one-out estimate of hyperparameter optimizer, o outer cross validation independent at patient level This works with ROC, or performance measures such as Brier's score, sensitivity, specificity, ... * I don't recommend .632 or .632+ bootstrap here: they already mix in resubstitution error: you can anyways calculate them later from your resubstitution and out-of-bootstap estimates.
How to judge if a supervised machine learning model is overfitting or not?
Here's how you can estimate the extent of overfitting: Get an internal error estimate. Either resubstitutio (= predict training data), or if you do an inner cross "validation" to optimize hyperparame
How to judge if a supervised machine learning model is overfitting or not? Here's how you can estimate the extent of overfitting: Get an internal error estimate. Either resubstitutio (= predict training data), or if you do an inner cross "validation" to optimize hyperparameters, also that measure would be of interest. Get an independent test set error estimate. Usually, resampling (iterated cross validation or out-of-bootstrap* is recommended. But you need to be careful that no data leaks occur. I.e. the resampling loop must recalculate all steps that have calculations spanning more than one case. That includes pre-processing steps such as centering, scaling, etc. Also, make sure you split at the highest level if you have a "hierarchical" (also known as "clustered) data structure such as repeated measurements of e.g. the same patient (=> resample patients). Then compare how much better the "inner" error estimate looks than the independent one. Here's an example: Trefferrate = hit rate (% correct classified), Variablenzahl = number of variables (= model complexity) Symbols: . resubstitution, + internal leave-one-out estimate of hyperparameter optimizer, o outer cross validation independent at patient level This works with ROC, or performance measures such as Brier's score, sensitivity, specificity, ... * I don't recommend .632 or .632+ bootstrap here: they already mix in resubstitution error: you can anyways calculate them later from your resubstitution and out-of-bootstap estimates.
How to judge if a supervised machine learning model is overfitting or not? Here's how you can estimate the extent of overfitting: Get an internal error estimate. Either resubstitutio (= predict training data), or if you do an inner cross "validation" to optimize hyperparame
8,236
How to judge if a supervised machine learning model is overfitting or not?
The overfitting is simply the direct consequence of considering the statistical parameters, and therefore the results obtained, as a useful information without checking that them was not obtained in a random way. Therefore, in order to estimate the presence of overfitting we have to use the algorithm on a database equivalent to the real one but with randomly generated values, repeating this operation many times we can estimate the probability of obtaining equal or better results in a random way. If this probability is high, we are most likely in an overfitting situation. For example, the probability that a fourth-degree polynomial has a correlation of 1 with 5 random points on a plane is 100%, so this correlation is useless and we are in an overfitting situation.
How to judge if a supervised machine learning model is overfitting or not?
The overfitting is simply the direct consequence of considering the statistical parameters, and therefore the results obtained, as a useful information without checking that them was not obtained in a
How to judge if a supervised machine learning model is overfitting or not? The overfitting is simply the direct consequence of considering the statistical parameters, and therefore the results obtained, as a useful information without checking that them was not obtained in a random way. Therefore, in order to estimate the presence of overfitting we have to use the algorithm on a database equivalent to the real one but with randomly generated values, repeating this operation many times we can estimate the probability of obtaining equal or better results in a random way. If this probability is high, we are most likely in an overfitting situation. For example, the probability that a fourth-degree polynomial has a correlation of 1 with 5 random points on a plane is 100%, so this correlation is useless and we are in an overfitting situation.
How to judge if a supervised machine learning model is overfitting or not? The overfitting is simply the direct consequence of considering the statistical parameters, and therefore the results obtained, as a useful information without checking that them was not obtained in a
8,237
Intuitive explanation of how UMAP works, compared to t-SNE
You said that your understanding of t-SNE is based on https://www.youtube.com/watch?v=NEaUSP4YerM and you are looking for an explanation of UMAP on a similar level. I watched this video and it is pretty accurate in what it says (I have some minor nitpicks, but overall it is fine). Funny enough, it almost applies to UMAP just as it is. Here are things that do not apply: Similarities are computed from distances using a different kernel; it is not Gaussian, but it also decays exponentially and it also has adaptive width, as in t-SNE. Similarities are not normalized to sum to 1, but still end up being normalized to sum a constant value. Similarities are symmetrized, but not just by averaging. The similarity kernel in the embedding space is not exactly t-distribution kernel, but a very very similar kernel. I think all of these differences are not very important and not very consequential. The actually important part is the part where in the video the narrator says (10m40s): We want to make this row look like this row [...] The video does not explain how t-SNE quantifies whether they are similar or not and how it goes on achieving that they look similar. Both parts are different in UMAP. But the quoted statement can apply to UMAP too. The way the UMAP paper is written, the computational similarities to t-SNE are not very apparent. Scroll down to Appendix C in https://arxiv.org/pdf/1802.03426.pdf and/or look here https://jlmelville.github.io/uwot/umap-for-tsne.html, if you want to see a side-by-side comparison of the computations that I list above and the loss functions of t-SNE and UMAP.
Intuitive explanation of how UMAP works, compared to t-SNE
You said that your understanding of t-SNE is based on https://www.youtube.com/watch?v=NEaUSP4YerM and you are looking for an explanation of UMAP on a similar level. I watched this video and it is pret
Intuitive explanation of how UMAP works, compared to t-SNE You said that your understanding of t-SNE is based on https://www.youtube.com/watch?v=NEaUSP4YerM and you are looking for an explanation of UMAP on a similar level. I watched this video and it is pretty accurate in what it says (I have some minor nitpicks, but overall it is fine). Funny enough, it almost applies to UMAP just as it is. Here are things that do not apply: Similarities are computed from distances using a different kernel; it is not Gaussian, but it also decays exponentially and it also has adaptive width, as in t-SNE. Similarities are not normalized to sum to 1, but still end up being normalized to sum a constant value. Similarities are symmetrized, but not just by averaging. The similarity kernel in the embedding space is not exactly t-distribution kernel, but a very very similar kernel. I think all of these differences are not very important and not very consequential. The actually important part is the part where in the video the narrator says (10m40s): We want to make this row look like this row [...] The video does not explain how t-SNE quantifies whether they are similar or not and how it goes on achieving that they look similar. Both parts are different in UMAP. But the quoted statement can apply to UMAP too. The way the UMAP paper is written, the computational similarities to t-SNE are not very apparent. Scroll down to Appendix C in https://arxiv.org/pdf/1802.03426.pdf and/or look here https://jlmelville.github.io/uwot/umap-for-tsne.html, if you want to see a side-by-side comparison of the computations that I list above and the loss functions of t-SNE and UMAP.
Intuitive explanation of how UMAP works, compared to t-SNE You said that your understanding of t-SNE is based on https://www.youtube.com/watch?v=NEaUSP4YerM and you are looking for an explanation of UMAP on a similar level. I watched this video and it is pret
8,238
Intuitive explanation of how UMAP works, compared to t-SNE
The main difference between t-SNE and UMAP is the interpretation of the distance between objects or "clusters". I use the quotation marks since both algorithms are not meant for clustering - they are meant for visualization mostly. t-SNE preserves local structure in the data. UMAP claims to preserve both local and most of the global structure in the data. This means with t-SNE you cannot interpret the distance between clusters A and B at different ends of your plot. You cannot infer that these clusters are more dissimilar than A and C, where C is closer to A in the plot. But within cluster A, you can say that points close to each other are more similar objects than points at different ends of the cluster image. With UMAP, you should be able to interpret both the distances between / positions of points and clusters. Both algorithms are highly stochastic and very much dependent on choice of hyperparameters (t-SNE even more than UMAP) and can yield very different results in different runs, so your plot might obfuscate an information in the data that a subsequent run might reveal. Good old PCA on the other hand is deterministic and easily understandable with basic knowledge of linear algebra (matrix multiplication and eigenproblems), but is just a linear reduction in contrast to the non-linear reductions of t-SNE and UMAP.
Intuitive explanation of how UMAP works, compared to t-SNE
The main difference between t-SNE and UMAP is the interpretation of the distance between objects or "clusters". I use the quotation marks since both algorithms are not meant for clustering - they are
Intuitive explanation of how UMAP works, compared to t-SNE The main difference between t-SNE and UMAP is the interpretation of the distance between objects or "clusters". I use the quotation marks since both algorithms are not meant for clustering - they are meant for visualization mostly. t-SNE preserves local structure in the data. UMAP claims to preserve both local and most of the global structure in the data. This means with t-SNE you cannot interpret the distance between clusters A and B at different ends of your plot. You cannot infer that these clusters are more dissimilar than A and C, where C is closer to A in the plot. But within cluster A, you can say that points close to each other are more similar objects than points at different ends of the cluster image. With UMAP, you should be able to interpret both the distances between / positions of points and clusters. Both algorithms are highly stochastic and very much dependent on choice of hyperparameters (t-SNE even more than UMAP) and can yield very different results in different runs, so your plot might obfuscate an information in the data that a subsequent run might reveal. Good old PCA on the other hand is deterministic and easily understandable with basic knowledge of linear algebra (matrix multiplication and eigenproblems), but is just a linear reduction in contrast to the non-linear reductions of t-SNE and UMAP.
Intuitive explanation of how UMAP works, compared to t-SNE The main difference between t-SNE and UMAP is the interpretation of the distance between objects or "clusters". I use the quotation marks since both algorithms are not meant for clustering - they are
8,239
Drawing from Dirichlet distribution
First, draw $K$ independent random samples $y_1, \ldots, y_K$ from Gamma distributions each with density $$ \textrm{Gamma}(\alpha_i, 1) = \frac{y_i^{\alpha_i-1} \; e^{-y_i}}{\Gamma (\alpha_i)},$$ and then set $$x_i = \frac{y_i}{\sum_{j=1}^K y_j}. $$ Now, $x_1,...,x_K$ will follow a Dirichlet distribution The Wikipedia page on the Dirichlet distribution tells you exactly how to sample from the Dirichlet distribution. Also, in the R library MCMCpack there is a function for sampling random variables from the Dirichlet distribution.
Drawing from Dirichlet distribution
First, draw $K$ independent random samples $y_1, \ldots, y_K$ from Gamma distributions each with density $$ \textrm{Gamma}(\alpha_i, 1) = \frac{y_i^{\alpha_i-1} \; e^{-y_i}}{\Gamma (\alpha_i)},$$ and
Drawing from Dirichlet distribution First, draw $K$ independent random samples $y_1, \ldots, y_K$ from Gamma distributions each with density $$ \textrm{Gamma}(\alpha_i, 1) = \frac{y_i^{\alpha_i-1} \; e^{-y_i}}{\Gamma (\alpha_i)},$$ and then set $$x_i = \frac{y_i}{\sum_{j=1}^K y_j}. $$ Now, $x_1,...,x_K$ will follow a Dirichlet distribution The Wikipedia page on the Dirichlet distribution tells you exactly how to sample from the Dirichlet distribution. Also, in the R library MCMCpack there is a function for sampling random variables from the Dirichlet distribution.
Drawing from Dirichlet distribution First, draw $K$ independent random samples $y_1, \ldots, y_K$ from Gamma distributions each with density $$ \textrm{Gamma}(\alpha_i, 1) = \frac{y_i^{\alpha_i-1} \; e^{-y_i}}{\Gamma (\alpha_i)},$$ and
8,240
Drawing from Dirichlet distribution
A simple method (while not exact) consists in using the fact that drawing a Dirichlet distribution is equivalent to the Polya's urn experiment. (Drawing from a set of colored balls and each time you draw a ball, you put it back in the urn with a second ball of the same color) Consider your Dirichlet parameters $\alpha_i$ as an unormalized distribution over i. Then : repeat N times --> draw an i using the $\alpha_i$ multinomial distribution --> add 1 to $\alpha_i$ end repeat Normalize $\alpha$ to get your distribution If I am not wrong, that method is asymptotically exact. But since N is finite, you will NEVER draw some distributions with very small prior probabilities (while you should draw them with a very small frequency). I guess it might be satisfying in most cases with N = K.10.
Drawing from Dirichlet distribution
A simple method (while not exact) consists in using the fact that drawing a Dirichlet distribution is equivalent to the Polya's urn experiment. (Drawing from a set of colored balls and each time you d
Drawing from Dirichlet distribution A simple method (while not exact) consists in using the fact that drawing a Dirichlet distribution is equivalent to the Polya's urn experiment. (Drawing from a set of colored balls and each time you draw a ball, you put it back in the urn with a second ball of the same color) Consider your Dirichlet parameters $\alpha_i$ as an unormalized distribution over i. Then : repeat N times --> draw an i using the $\alpha_i$ multinomial distribution --> add 1 to $\alpha_i$ end repeat Normalize $\alpha$ to get your distribution If I am not wrong, that method is asymptotically exact. But since N is finite, you will NEVER draw some distributions with very small prior probabilities (while you should draw them with a very small frequency). I guess it might be satisfying in most cases with N = K.10.
Drawing from Dirichlet distribution A simple method (while not exact) consists in using the fact that drawing a Dirichlet distribution is equivalent to the Polya's urn experiment. (Drawing from a set of colored balls and each time you d
8,241
Why are rectified linear units considered non-linear?
RELUs are nonlinearities. To help your intuition, consider a very simple network with 1 input unit $x$, 2 hidden units $y_i$, and 1 output unit $z$. With this simple network we could implement an absolute value function, $$z = \max(0, x) + \max(0, -x),$$ or something that looks similar to the commonly used sigmoid function, $$z = \max(0, x + 1) - \max(0, x - 1).$$ By combining these into larger networks/using more hidden units, we can approximate arbitrary functions. $\hskip2in$
Why are rectified linear units considered non-linear?
RELUs are nonlinearities. To help your intuition, consider a very simple network with 1 input unit $x$, 2 hidden units $y_i$, and 1 output unit $z$. With this simple network we could implement an abso
Why are rectified linear units considered non-linear? RELUs are nonlinearities. To help your intuition, consider a very simple network with 1 input unit $x$, 2 hidden units $y_i$, and 1 output unit $z$. With this simple network we could implement an absolute value function, $$z = \max(0, x) + \max(0, -x),$$ or something that looks similar to the commonly used sigmoid function, $$z = \max(0, x + 1) - \max(0, x - 1).$$ By combining these into larger networks/using more hidden units, we can approximate arbitrary functions. $\hskip2in$
Why are rectified linear units considered non-linear? RELUs are nonlinearities. To help your intuition, consider a very simple network with 1 input unit $x$, 2 hidden units $y_i$, and 1 output unit $z$. With this simple network we could implement an abso
8,242
explain meaning and purpose of L2 normalization
we scale the values so that if they were all squared and summed, the value would be 1 That's correct. I'm not totally sure how that would be helpful for the model, though Consider a simpler case, where we just count the number of times each word appears in each document. In this case, two documents might appear different simply because they have different lengths (the longer document contains more words). But, we're more interested in the meaning of the document, and the length doesn't contribute to this. Normalizing lets us consider the frequency of words relative to each other, while removing the effect of total word count. Does L2 normalization have anything to do with L2 regularization? L2 regularization operates on the parameters of a model, whereas L2 normalization (in the context you're asking about) operates on the representation of the data. They're not related in any meaningful sense, beyond the superficial fact that both require computing L2 norms (summing squared terms, as you say). But, note that L2 normalization is a generic operation, and can apply in contexts beyond the one you're asking about. There do exist situations where one could draw a connection between the two concepts, but I think that's beyond the scope of this question.
explain meaning and purpose of L2 normalization
we scale the values so that if they were all squared and summed, the value would be 1 That's correct. I'm not totally sure how that would be helpful for the model, though Consider a simpler case, w
explain meaning and purpose of L2 normalization we scale the values so that if they were all squared and summed, the value would be 1 That's correct. I'm not totally sure how that would be helpful for the model, though Consider a simpler case, where we just count the number of times each word appears in each document. In this case, two documents might appear different simply because they have different lengths (the longer document contains more words). But, we're more interested in the meaning of the document, and the length doesn't contribute to this. Normalizing lets us consider the frequency of words relative to each other, while removing the effect of total word count. Does L2 normalization have anything to do with L2 regularization? L2 regularization operates on the parameters of a model, whereas L2 normalization (in the context you're asking about) operates on the representation of the data. They're not related in any meaningful sense, beyond the superficial fact that both require computing L2 norms (summing squared terms, as you say). But, note that L2 normalization is a generic operation, and can apply in contexts beyond the one you're asking about. There do exist situations where one could draw a connection between the two concepts, but I think that's beyond the scope of this question.
explain meaning and purpose of L2 normalization we scale the values so that if they were all squared and summed, the value would be 1 That's correct. I'm not totally sure how that would be helpful for the model, though Consider a simpler case, w
8,243
k-NN computational complexity
Assuming $k$ is fixed (as both of the linked lectures do), then your algorithmic choices will determine whether your computation takes $O(nd+kn)$ runtime or $O(ndk)$ runtime. First, let's consider a $O(nd+kn)$ runtime algorithm: Initialize $selected_i = 0$ for all observations $i$ in the training set For each training set observation $i$, compute $dist_i$, the distance from the new observation to training set observation $i$ For $j=1$ to $k$: Loop through all training set observations, selecting the index $i$ with the smallest $dist_i$ value and for which $selected_i=0$. Select this observation by setting $selected_i=1$. Return the $k$ selected indices Each distance computation requires $O(d)$ runtime, so the second step requires $O(nd)$ runtime. For each iterate in the third step, we perform $O(n)$ work by looping through the training set observations, so the step overall requires $O(nk)$ work. The first and fourth steps only require $O(n)$ work, so we get a $O(nd+kn)$ runtime. Now, let's consider a $O(ndk)$ runtime algorithm: Initialize $selected_i = 0$ for all observations $i$ in the training set For $j=1$ to $k$: Loop through all training set observations and compute the distance $d$ between the selected training set observation and the new observation. Select the index $i$ with the smallest $d$ value for which $selected_i=0$. Select this observation by setting $selected_i=1$. Return the $k$ selected indices For each iterate in the second step, we compute the distance between the new observation and each training set observation, requiring $O(nd)$ work for an iteration and therefore $O(ndk)$ work overall. The difference between the two algorithms is that the first precomputes and stores the distances (requiring $O(n)$ extra memory), while the second does not. However, given that we already store the entire training set, requiring $O(nd)$ memory, as well as the $selected$ vector, requiring $O(n)$ storage, the storage of the two algorithms is asymptotically the same. As a result, the better asymptotic runtime for $k > 1$ makes the first algorithm more attractive. It's worth noting that it is possible to obtain an $O(nd)$ runtime using an algorithmic improvement: For each training set observation $i$, compute $dist_i$, the distance from the new observation to training set observation $i$ Run the quickselect algorithm to compute the $k^{th}$ smallest distance in $O(n)$ runtime Return all indices no larger than the computed $k^{th}$ smallest distance This approach takes advantage of the fact that efficient approaches exist to find the $k^{th}$ smallest value in an unsorted array.
k-NN computational complexity
Assuming $k$ is fixed (as both of the linked lectures do), then your algorithmic choices will determine whether your computation takes $O(nd+kn)$ runtime or $O(ndk)$ runtime. First, let's consider a $
k-NN computational complexity Assuming $k$ is fixed (as both of the linked lectures do), then your algorithmic choices will determine whether your computation takes $O(nd+kn)$ runtime or $O(ndk)$ runtime. First, let's consider a $O(nd+kn)$ runtime algorithm: Initialize $selected_i = 0$ for all observations $i$ in the training set For each training set observation $i$, compute $dist_i$, the distance from the new observation to training set observation $i$ For $j=1$ to $k$: Loop through all training set observations, selecting the index $i$ with the smallest $dist_i$ value and for which $selected_i=0$. Select this observation by setting $selected_i=1$. Return the $k$ selected indices Each distance computation requires $O(d)$ runtime, so the second step requires $O(nd)$ runtime. For each iterate in the third step, we perform $O(n)$ work by looping through the training set observations, so the step overall requires $O(nk)$ work. The first and fourth steps only require $O(n)$ work, so we get a $O(nd+kn)$ runtime. Now, let's consider a $O(ndk)$ runtime algorithm: Initialize $selected_i = 0$ for all observations $i$ in the training set For $j=1$ to $k$: Loop through all training set observations and compute the distance $d$ between the selected training set observation and the new observation. Select the index $i$ with the smallest $d$ value for which $selected_i=0$. Select this observation by setting $selected_i=1$. Return the $k$ selected indices For each iterate in the second step, we compute the distance between the new observation and each training set observation, requiring $O(nd)$ work for an iteration and therefore $O(ndk)$ work overall. The difference between the two algorithms is that the first precomputes and stores the distances (requiring $O(n)$ extra memory), while the second does not. However, given that we already store the entire training set, requiring $O(nd)$ memory, as well as the $selected$ vector, requiring $O(n)$ storage, the storage of the two algorithms is asymptotically the same. As a result, the better asymptotic runtime for $k > 1$ makes the first algorithm more attractive. It's worth noting that it is possible to obtain an $O(nd)$ runtime using an algorithmic improvement: For each training set observation $i$, compute $dist_i$, the distance from the new observation to training set observation $i$ Run the quickselect algorithm to compute the $k^{th}$ smallest distance in $O(n)$ runtime Return all indices no larger than the computed $k^{th}$ smallest distance This approach takes advantage of the fact that efficient approaches exist to find the $k^{th}$ smallest value in an unsorted array.
k-NN computational complexity Assuming $k$ is fixed (as both of the linked lectures do), then your algorithmic choices will determine whether your computation takes $O(nd+kn)$ runtime or $O(ndk)$ runtime. First, let's consider a $
8,244
Clustering a correlation matrix
Looks like a job for block modeling. Google for "block modeling" and the first few hits are helpful. Say we have a covariance matrix where N=100 and there are actually 5 clusters: What block modelling is trying to do is find an ordering of the rows, so that the clusters become apparent as 'blocks': Below is a code example that performs a basic greedy search to accomplish this. It's probably too slow for your 250-300 variables, but it's a start. See if you can follow along with the comments: import numpy as np from matplotlib import pyplot as plt # This generates 100 variables that could possibly be assigned to 5 clusters n_variables = 100 n_clusters = 5 n_samples = 1000 # To keep this example simple, each cluster will have a fixed size cluster_size = n_variables // n_clusters # Assign each variable to a cluster belongs_to_cluster = np.repeat(range(n_clusters), cluster_size) np.random.shuffle(belongs_to_cluster) # This latent data is used to make variables that belong # to the same cluster correlated. latent = np.random.randn(n_clusters, n_samples) variables = [] for i in range(n_variables): variables.append( np.random.randn(n_samples) + latent[belongs_to_cluster[i], :] ) variables = np.array(variables) C = np.cov(variables) def score(C): ''' Function to assign a score to an ordered covariance matrix. High correlations within a cluster improve the score. High correlations between clusters decease the score. ''' score = 0 for cluster in range(n_clusters): inside_cluster = np.arange(cluster_size) + cluster * cluster_size outside_cluster = np.setdiff1d(range(n_variables), inside_cluster) # Belonging to the same cluster score += np.sum(C[inside_cluster, :][:, inside_cluster]) # Belonging to different clusters score -= np.sum(C[inside_cluster, :][:, outside_cluster]) score -= np.sum(C[outside_cluster, :][:, inside_cluster]) return score initial_C = C initial_score = score(C) initial_ordering = np.arange(n_variables) plt.figure() plt.imshow(C, interpolation='nearest') plt.title('Initial C') print 'Initial ordering:', initial_ordering print 'Initial covariance matrix score:', initial_score # Pretty dumb greedy optimization algorithm that continuously # swaps rows to improve the score def swap_rows(C, var1, var2): ''' Function to swap two rows in a covariance matrix, updating the appropriate columns as well. ''' D = C.copy() D[var2, :] = C[var1, :] D[var1, :] = C[var2, :] E = D.copy() E[:, var2] = D[:, var1] E[:, var1] = D[:, var2] return E current_C = C current_ordering = initial_ordering current_score = initial_score max_iter = 1000 for i in range(max_iter): # Find the best row swap to make best_C = current_C best_ordering = current_ordering best_score = current_score for row1 in range(n_variables): for row2 in range(n_variables): if row1 == row2: continue option_ordering = best_ordering.copy() option_ordering[row1] = best_ordering[row2] option_ordering[row2] = best_ordering[row1] option_C = swap_rows(best_C, row1, row2) option_score = score(option_C) if option_score > best_score: best_C = option_C best_ordering = option_ordering best_score = option_score if best_score > current_score: # Perform the best row swap current_C = best_C current_ordering = best_ordering current_score = best_score else: # No row swap found that improves the solution, we're done break # Output the result plt.figure() plt.imshow(current_C, interpolation='nearest') plt.title('Best C') print 'Best ordering:', current_ordering print 'Best score:', current_score print print 'Cluster [variables assigned to this cluster]' print '------------------------------------------------' for cluster in range(n_clusters): print 'Cluster %02d %s' % (cluster + 1, current_ordering[cluster*cluster_size:(cluster+1)*cluster_size])
Clustering a correlation matrix
Looks like a job for block modeling. Google for "block modeling" and the first few hits are helpful. Say we have a covariance matrix where N=100 and there are actually 5 clusters: What block modellin
Clustering a correlation matrix Looks like a job for block modeling. Google for "block modeling" and the first few hits are helpful. Say we have a covariance matrix where N=100 and there are actually 5 clusters: What block modelling is trying to do is find an ordering of the rows, so that the clusters become apparent as 'blocks': Below is a code example that performs a basic greedy search to accomplish this. It's probably too slow for your 250-300 variables, but it's a start. See if you can follow along with the comments: import numpy as np from matplotlib import pyplot as plt # This generates 100 variables that could possibly be assigned to 5 clusters n_variables = 100 n_clusters = 5 n_samples = 1000 # To keep this example simple, each cluster will have a fixed size cluster_size = n_variables // n_clusters # Assign each variable to a cluster belongs_to_cluster = np.repeat(range(n_clusters), cluster_size) np.random.shuffle(belongs_to_cluster) # This latent data is used to make variables that belong # to the same cluster correlated. latent = np.random.randn(n_clusters, n_samples) variables = [] for i in range(n_variables): variables.append( np.random.randn(n_samples) + latent[belongs_to_cluster[i], :] ) variables = np.array(variables) C = np.cov(variables) def score(C): ''' Function to assign a score to an ordered covariance matrix. High correlations within a cluster improve the score. High correlations between clusters decease the score. ''' score = 0 for cluster in range(n_clusters): inside_cluster = np.arange(cluster_size) + cluster * cluster_size outside_cluster = np.setdiff1d(range(n_variables), inside_cluster) # Belonging to the same cluster score += np.sum(C[inside_cluster, :][:, inside_cluster]) # Belonging to different clusters score -= np.sum(C[inside_cluster, :][:, outside_cluster]) score -= np.sum(C[outside_cluster, :][:, inside_cluster]) return score initial_C = C initial_score = score(C) initial_ordering = np.arange(n_variables) plt.figure() plt.imshow(C, interpolation='nearest') plt.title('Initial C') print 'Initial ordering:', initial_ordering print 'Initial covariance matrix score:', initial_score # Pretty dumb greedy optimization algorithm that continuously # swaps rows to improve the score def swap_rows(C, var1, var2): ''' Function to swap two rows in a covariance matrix, updating the appropriate columns as well. ''' D = C.copy() D[var2, :] = C[var1, :] D[var1, :] = C[var2, :] E = D.copy() E[:, var2] = D[:, var1] E[:, var1] = D[:, var2] return E current_C = C current_ordering = initial_ordering current_score = initial_score max_iter = 1000 for i in range(max_iter): # Find the best row swap to make best_C = current_C best_ordering = current_ordering best_score = current_score for row1 in range(n_variables): for row2 in range(n_variables): if row1 == row2: continue option_ordering = best_ordering.copy() option_ordering[row1] = best_ordering[row2] option_ordering[row2] = best_ordering[row1] option_C = swap_rows(best_C, row1, row2) option_score = score(option_C) if option_score > best_score: best_C = option_C best_ordering = option_ordering best_score = option_score if best_score > current_score: # Perform the best row swap current_C = best_C current_ordering = best_ordering current_score = best_score else: # No row swap found that improves the solution, we're done break # Output the result plt.figure() plt.imshow(current_C, interpolation='nearest') plt.title('Best C') print 'Best ordering:', current_ordering print 'Best score:', current_score print print 'Cluster [variables assigned to this cluster]' print '------------------------------------------------' for cluster in range(n_clusters): print 'Cluster %02d %s' % (cluster + 1, current_ordering[cluster*cluster_size:(cluster+1)*cluster_size])
Clustering a correlation matrix Looks like a job for block modeling. Google for "block modeling" and the first few hits are helpful. Say we have a covariance matrix where N=100 and there are actually 5 clusters: What block modellin
8,245
Clustering a correlation matrix
Have you looked at hierarchical clustering? It can work with similarities, not only distances. You can cut the dendrogram at a height where it splits into k clusters, but usually it is better to visually inspect the dendrogram and decide on a height to cut. Hierarchical clustering is also often used to produce a clever reordering for a similarity matrix visualization as seen in the other answer: it places more similar entries next to each other. This can serve as a validation tool for the user, too!
Clustering a correlation matrix
Have you looked at hierarchical clustering? It can work with similarities, not only distances. You can cut the dendrogram at a height where it splits into k clusters, but usually it is better to visua
Clustering a correlation matrix Have you looked at hierarchical clustering? It can work with similarities, not only distances. You can cut the dendrogram at a height where it splits into k clusters, but usually it is better to visually inspect the dendrogram and decide on a height to cut. Hierarchical clustering is also often used to produce a clever reordering for a similarity matrix visualization as seen in the other answer: it places more similar entries next to each other. This can serve as a validation tool for the user, too!
Clustering a correlation matrix Have you looked at hierarchical clustering? It can work with similarities, not only distances. You can cut the dendrogram at a height where it splits into k clusters, but usually it is better to visua
8,246
Clustering a correlation matrix
Have you looked into correlation clustering? This clustering algorithm uses the pair-wise positive/negative correlation information to automatically propose the optimal number of clusters with a well defined functional and a rigorous generative probabilistic interpretation.
Clustering a correlation matrix
Have you looked into correlation clustering? This clustering algorithm uses the pair-wise positive/negative correlation information to automatically propose the optimal number of clusters with a well
Clustering a correlation matrix Have you looked into correlation clustering? This clustering algorithm uses the pair-wise positive/negative correlation information to automatically propose the optimal number of clusters with a well defined functional and a rigorous generative probabilistic interpretation.
Clustering a correlation matrix Have you looked into correlation clustering? This clustering algorithm uses the pair-wise positive/negative correlation information to automatically propose the optimal number of clusters with a well
8,247
Clustering a correlation matrix
I would filter at some meaningful (statistical significance) threshold and then use the dulmage-mendelsohn decomposition to get the connected components. Maybe before you can try to remove some problem like transitive correlations (A highly correlated to B, B to C, C to D, so there is a component containing all of them, but in fact D to A is low). you can use some betweenness based algorithm. It's not a biclustering problem as someone suggested, as the correlation matrix is symmetrical and therefore there is no bi-something.
Clustering a correlation matrix
I would filter at some meaningful (statistical significance) threshold and then use the dulmage-mendelsohn decomposition to get the connected components. Maybe before you can try to remove some proble
Clustering a correlation matrix I would filter at some meaningful (statistical significance) threshold and then use the dulmage-mendelsohn decomposition to get the connected components. Maybe before you can try to remove some problem like transitive correlations (A highly correlated to B, B to C, C to D, so there is a component containing all of them, but in fact D to A is low). you can use some betweenness based algorithm. It's not a biclustering problem as someone suggested, as the correlation matrix is symmetrical and therefore there is no bi-something.
Clustering a correlation matrix I would filter at some meaningful (statistical significance) threshold and then use the dulmage-mendelsohn decomposition to get the connected components. Maybe before you can try to remove some proble
8,248
Dropping unused levels in facets with ggplot2 [closed]
Your example data just doesn't have any unused levels to drop. Check the behavior in this example: dat <- data.frame(x = runif(12), y = runif(12), grp1 = factor(rep(letters[1:4],times = 3)), grp2 = factor(rep(LETTERS[1:2],times = 6))) levels(dat$grp2) <- LETTERS[1:3] ggplot(dat,aes(x = x,y = y)) + facet_grid(grp1~grp2,drop = FALSE) + geom_point() ggplot(dat,aes(x = x,y = y)) + facet_grid(grp1~grp2,drop = TRUE) + geom_point() It may be that you're looking to change which factors are plotting on the vertical axis in each facet, in which case you want to set the scales argument and use facet_wrap: ggplot(tab, aes(names,val)) + geom_point() + coord_flip() + theme_bw() + facet_wrap(~groups,nrow = 3,scales = "free_x")
Dropping unused levels in facets with ggplot2 [closed]
Your example data just doesn't have any unused levels to drop. Check the behavior in this example: dat <- data.frame(x = runif(12), y = runif(12), grp1 = factor(rep
Dropping unused levels in facets with ggplot2 [closed] Your example data just doesn't have any unused levels to drop. Check the behavior in this example: dat <- data.frame(x = runif(12), y = runif(12), grp1 = factor(rep(letters[1:4],times = 3)), grp2 = factor(rep(LETTERS[1:2],times = 6))) levels(dat$grp2) <- LETTERS[1:3] ggplot(dat,aes(x = x,y = y)) + facet_grid(grp1~grp2,drop = FALSE) + geom_point() ggplot(dat,aes(x = x,y = y)) + facet_grid(grp1~grp2,drop = TRUE) + geom_point() It may be that you're looking to change which factors are plotting on the vertical axis in each facet, in which case you want to set the scales argument and use facet_wrap: ggplot(tab, aes(names,val)) + geom_point() + coord_flip() + theme_bw() + facet_wrap(~groups,nrow = 3,scales = "free_x")
Dropping unused levels in facets with ggplot2 [closed] Your example data just doesn't have any unused levels to drop. Check the behavior in this example: dat <- data.frame(x = runif(12), y = runif(12), grp1 = factor(rep
8,249
Visualizing the intersections of many sets
When you have a large number of sets, I would try something that is more linear and shows the links directly (like a network graph). Flare and Protovis both have utilities to handle these visualizations. See this question for some examples like this:
Visualizing the intersections of many sets
When you have a large number of sets, I would try something that is more linear and shows the links directly (like a network graph). Flare and Protovis both have utilities to handle these visualizati
Visualizing the intersections of many sets When you have a large number of sets, I would try something that is more linear and shows the links directly (like a network graph). Flare and Protovis both have utilities to handle these visualizations. See this question for some examples like this:
Visualizing the intersections of many sets When you have a large number of sets, I would try something that is more linear and shows the links directly (like a network graph). Flare and Protovis both have utilities to handle these visualizati
8,250
Visualizing the intersections of many sets
This won't compete with @Shane's answer because circular displays are really well suited for displaying complex relationships with high-dimensional datasets. For Venn diagrams, I've been using the venneuler R package. It has a simple yet intuitive interface and produce nifty diagrams with transparency, compared to the basic venn() function described in the Journal of Statistical Software. It does not handle more than 3 categories, though. Another project is eVenn and it deals with $K=4$ sets. More recently, I came across a new package that deal with higher-order relation sets, and probably allow to reproduce some of the Venn diagrams shown on Wikipedia or on this webpage, What is a Venn Diagram?, but it is also limited to $K=4$ sets. It is called VennDiagram, but see the reference paper: VennDiagram: a package for the generation of highly-customizable Venn and Euler diagrams in R (Chen and Boutros, BMC Bioinformatics 2011, 12:35). For further reference, you might be interested in Kestler et al., Generalized Venn diagrams: a new method of visualizing complex genetic set relations, Bioinformatics, 21(8), 1592-1595 (2004). Venn diagrams have their limitations, though. In this respect, I like the approach taken by Robert Kosara in Sightings: A Vennerable Challenge, or with Parallel Sets (but see also this discussion on Andrew Gelman weblog).
Visualizing the intersections of many sets
This won't compete with @Shane's answer because circular displays are really well suited for displaying complex relationships with high-dimensional datasets. For Venn diagrams, I've been using the ven
Visualizing the intersections of many sets This won't compete with @Shane's answer because circular displays are really well suited for displaying complex relationships with high-dimensional datasets. For Venn diagrams, I've been using the venneuler R package. It has a simple yet intuitive interface and produce nifty diagrams with transparency, compared to the basic venn() function described in the Journal of Statistical Software. It does not handle more than 3 categories, though. Another project is eVenn and it deals with $K=4$ sets. More recently, I came across a new package that deal with higher-order relation sets, and probably allow to reproduce some of the Venn diagrams shown on Wikipedia or on this webpage, What is a Venn Diagram?, but it is also limited to $K=4$ sets. It is called VennDiagram, but see the reference paper: VennDiagram: a package for the generation of highly-customizable Venn and Euler diagrams in R (Chen and Boutros, BMC Bioinformatics 2011, 12:35). For further reference, you might be interested in Kestler et al., Generalized Venn diagrams: a new method of visualizing complex genetic set relations, Bioinformatics, 21(8), 1592-1595 (2004). Venn diagrams have their limitations, though. In this respect, I like the approach taken by Robert Kosara in Sightings: A Vennerable Challenge, or with Parallel Sets (but see also this discussion on Andrew Gelman weblog).
Visualizing the intersections of many sets This won't compete with @Shane's answer because circular displays are really well suited for displaying complex relationships with high-dimensional datasets. For Venn diagrams, I've been using the ven
8,251
Visualizing the intersections of many sets
We developed a matrix-based approach for set intersections called UpSet, you can check it out at http://vcg.github.io/upset/. Here is an example: The Matrix on the left identifies the intersection a row represents, the last row here, for example, is the intersection of the "Action, Adventure, and Children" movie genres. The bars to the right show you the size of the intersection, 4 in this example. You can also plot attributes of the intersections or other selections, etc. Check out the website for details. There is now also a static version for R which you can find on the website mentioned above, or by going here: https://github.com/hms-dbmi/UpSetR/ A state of the art report on set visualization is accessible at http://www.cvast.tuwien.ac.at/SetViz - most of these are academic though and don't come with readily available code.
Visualizing the intersections of many sets
We developed a matrix-based approach for set intersections called UpSet, you can check it out at http://vcg.github.io/upset/. Here is an example: The Matrix on the left identifies the intersection a
Visualizing the intersections of many sets We developed a matrix-based approach for set intersections called UpSet, you can check it out at http://vcg.github.io/upset/. Here is an example: The Matrix on the left identifies the intersection a row represents, the last row here, for example, is the intersection of the "Action, Adventure, and Children" movie genres. The bars to the right show you the size of the intersection, 4 in this example. You can also plot attributes of the intersections or other selections, etc. Check out the website for details. There is now also a static version for R which you can find on the website mentioned above, or by going here: https://github.com/hms-dbmi/UpSetR/ A state of the art report on set visualization is accessible at http://www.cvast.tuwien.ac.at/SetViz - most of these are academic though and don't come with readily available code.
Visualizing the intersections of many sets We developed a matrix-based approach for set intersections called UpSet, you can check it out at http://vcg.github.io/upset/. Here is an example: The Matrix on the left identifies the intersection a
8,252
Three versions of discriminant analysis: differences and how to use them
"Fisher's Discriminant Analysis" is simply LDA in a situation of 2 classes. When there is only 2 classes computations by hand are feasible and the analysis is directly related to Multiple Regression. LDA is the direct extension of Fisher's idea on situation of any number of classes and uses matrix algebra devices (such as eigendecomposition) to compute it. So, the term "Fisher's Discriminant Analysis" can be seen as obsolete today. "Linear Discriminant analysis" should be used instead. See also. Discriminant analysis with 2+ classes (multi-class) is canonical by its algorithm (extracts dicriminants as canonical variates); rare term "Canonical Discriminant Analysis" usually stands simply for (multiclass) LDA therefore (or for LDA + QDA, omnibusly). Fisher used what was then called "Fisher classification functions" to classify objects after the discriminant function has been computed. Nowadays, a more general Bayes' approach is used within LDA procedure to classify objects. To your request for explanations of LDA I may send you to these my answers: extraction in LDA, classification in LDA, LDA among related procedures. Also this, this, this questions and answers. Just like ANOVA requires an assumption of equal variances, LDA requires an assumption of equal variance-covariance matrices (between the input variables) of the classes. This assumption is important for classification stage of the analysis. If the matrices substantially differ, observations will tend to be assigned to the class where variability is greater. To overcome the problem, QDA was invented. QDA is a modification of LDA which allows for the above heterogeneity of classes' covariance matrices. If you have the heterogeneity (as detected for example by Box's M test) and you don't have QDA at hand, you may still use LDA in the regime of using individual covariance matrices (rather than the pooled matrix) of the discriminants at classification. This partly solves the problem, though less effectively than in QDA, because - as just pointed - these are the matrices between the discriminants and not between the original variables (which matrices differed). Let me leave analyzing your example data for yourself. Reply to @zyxue's answer and comments LDA is what you defined FDA is in your answer. LDA first extracts linear constructs (called discriminants) that maximize the between to within separation, and then uses those to perform (gaussian) classification. If (as you say) LDA were not tied with the task to extract the discriminants LDA would appear to be just a gaussian classifier, no name "LDA" would be needed at all. It is that classification stage where LDA assumes both normality and variance-covariance homogeneity of classes. The extraction or "dimensionality reduction" stage of LDA assumes linearity and variance-covariance homogeneity, the two assumptions together make "linear separability" feasible. (We use single pooled $S_w$ matrix to produce discriminants which therefore have identity pooled within-class covariance matrix, that give us the right to apply the same set of discriminants to classify to all the classes. If all $S_w$s are same the said within-class covariances are all same, identity; that right to use them becomes absolute.) Gaussian classifier (the second stage of LDA) uses Bayes rule to assign observations to classes by the discriminants. The same result can be accomplished via so called Fisher linear classification functions which utilizes original features directly. However, Bayes' approach based on discriminants is a little bit general in that it will allow to use separate class discriminant covariance matrices too, in addition to the default way to use one, the pooled one. Also, it will allow to base classification on a subset of discriminants. When there are only two classes, both stages of LDA can be described together in a single pass because "latents extraction" and "observations classification" reduce then to the same task.
Three versions of discriminant analysis: differences and how to use them
"Fisher's Discriminant Analysis" is simply LDA in a situation of 2 classes. When there is only 2 classes computations by hand are feasible and the analysis is directly related to Multiple Regression.
Three versions of discriminant analysis: differences and how to use them "Fisher's Discriminant Analysis" is simply LDA in a situation of 2 classes. When there is only 2 classes computations by hand are feasible and the analysis is directly related to Multiple Regression. LDA is the direct extension of Fisher's idea on situation of any number of classes and uses matrix algebra devices (such as eigendecomposition) to compute it. So, the term "Fisher's Discriminant Analysis" can be seen as obsolete today. "Linear Discriminant analysis" should be used instead. See also. Discriminant analysis with 2+ classes (multi-class) is canonical by its algorithm (extracts dicriminants as canonical variates); rare term "Canonical Discriminant Analysis" usually stands simply for (multiclass) LDA therefore (or for LDA + QDA, omnibusly). Fisher used what was then called "Fisher classification functions" to classify objects after the discriminant function has been computed. Nowadays, a more general Bayes' approach is used within LDA procedure to classify objects. To your request for explanations of LDA I may send you to these my answers: extraction in LDA, classification in LDA, LDA among related procedures. Also this, this, this questions and answers. Just like ANOVA requires an assumption of equal variances, LDA requires an assumption of equal variance-covariance matrices (between the input variables) of the classes. This assumption is important for classification stage of the analysis. If the matrices substantially differ, observations will tend to be assigned to the class where variability is greater. To overcome the problem, QDA was invented. QDA is a modification of LDA which allows for the above heterogeneity of classes' covariance matrices. If you have the heterogeneity (as detected for example by Box's M test) and you don't have QDA at hand, you may still use LDA in the regime of using individual covariance matrices (rather than the pooled matrix) of the discriminants at classification. This partly solves the problem, though less effectively than in QDA, because - as just pointed - these are the matrices between the discriminants and not between the original variables (which matrices differed). Let me leave analyzing your example data for yourself. Reply to @zyxue's answer and comments LDA is what you defined FDA is in your answer. LDA first extracts linear constructs (called discriminants) that maximize the between to within separation, and then uses those to perform (gaussian) classification. If (as you say) LDA were not tied with the task to extract the discriminants LDA would appear to be just a gaussian classifier, no name "LDA" would be needed at all. It is that classification stage where LDA assumes both normality and variance-covariance homogeneity of classes. The extraction or "dimensionality reduction" stage of LDA assumes linearity and variance-covariance homogeneity, the two assumptions together make "linear separability" feasible. (We use single pooled $S_w$ matrix to produce discriminants which therefore have identity pooled within-class covariance matrix, that give us the right to apply the same set of discriminants to classify to all the classes. If all $S_w$s are same the said within-class covariances are all same, identity; that right to use them becomes absolute.) Gaussian classifier (the second stage of LDA) uses Bayes rule to assign observations to classes by the discriminants. The same result can be accomplished via so called Fisher linear classification functions which utilizes original features directly. However, Bayes' approach based on discriminants is a little bit general in that it will allow to use separate class discriminant covariance matrices too, in addition to the default way to use one, the pooled one. Also, it will allow to base classification on a subset of discriminants. When there are only two classes, both stages of LDA can be described together in a single pass because "latents extraction" and "observations classification" reduce then to the same task.
Three versions of discriminant analysis: differences and how to use them "Fisher's Discriminant Analysis" is simply LDA in a situation of 2 classes. When there is only 2 classes computations by hand are feasible and the analysis is directly related to Multiple Regression.
8,253
Three versions of discriminant analysis: differences and how to use them
I find it hard to agree that FDA is LDA for two-classes as @ttnphns suggested. I recommend two very informative and beautiful lectures on this topic by Professor Ali Ghodsi: LDA & QDA. In addition, page 108 of the book The Elements of Statistical Learning (pdf) has a description of LDA consistent with the lecture. FDA To me, LDA and QDA are similar as they are both classification techniques with Gaussian assumptions. A major difference between the two is that LDA assumes the feature covariance matrices of both classes are the same, which results in a linear decision boundary. In contrast, QDA is less strict and allows different feature covariance matrices for different classes, which leads to a quadratic decision boundary. See the following figure from scikit-learn for an idea how the quadratic decision boundary looks. Some comments on the subplots: Top row: when the covariance matrices are indeed the same in the data, LDA and QDA lead to the same decision boundaries. Bottom row: when the covariance matrices are different, LDA leads to bad performance as its assumption becomes invalid, while QDA performs classification much better. On the other hand, FDA is a very different species, having nothing to do with Gaussion assumption. What FDA tries to do is to find a linear transformation to maximize between-class mean distance while minimizing within-class variance. The 2nd lecture explains this idea beautifully. In contrast to LDA/QDA, FDA doesn't do classification, although the features obtained after transformation found by FDA could be used for classification, e.g. using LDA/QDA, or SVM or others.
Three versions of discriminant analysis: differences and how to use them
I find it hard to agree that FDA is LDA for two-classes as @ttnphns suggested. I recommend two very informative and beautiful lectures on this topic by Professor Ali Ghodsi: LDA & QDA. In addition, p
Three versions of discriminant analysis: differences and how to use them I find it hard to agree that FDA is LDA for two-classes as @ttnphns suggested. I recommend two very informative and beautiful lectures on this topic by Professor Ali Ghodsi: LDA & QDA. In addition, page 108 of the book The Elements of Statistical Learning (pdf) has a description of LDA consistent with the lecture. FDA To me, LDA and QDA are similar as they are both classification techniques with Gaussian assumptions. A major difference between the two is that LDA assumes the feature covariance matrices of both classes are the same, which results in a linear decision boundary. In contrast, QDA is less strict and allows different feature covariance matrices for different classes, which leads to a quadratic decision boundary. See the following figure from scikit-learn for an idea how the quadratic decision boundary looks. Some comments on the subplots: Top row: when the covariance matrices are indeed the same in the data, LDA and QDA lead to the same decision boundaries. Bottom row: when the covariance matrices are different, LDA leads to bad performance as its assumption becomes invalid, while QDA performs classification much better. On the other hand, FDA is a very different species, having nothing to do with Gaussion assumption. What FDA tries to do is to find a linear transformation to maximize between-class mean distance while minimizing within-class variance. The 2nd lecture explains this idea beautifully. In contrast to LDA/QDA, FDA doesn't do classification, although the features obtained after transformation found by FDA could be used for classification, e.g. using LDA/QDA, or SVM or others.
Three versions of discriminant analysis: differences and how to use them I find it hard to agree that FDA is LDA for two-classes as @ttnphns suggested. I recommend two very informative and beautiful lectures on this topic by Professor Ali Ghodsi: LDA & QDA. In addition, p
8,254
How to generate a large full-rank random correlation matrix with some strong correlations present?
Other answers came up with nice tricks to solve my problem in various ways. However, I found a principled approach that I think has a large advantage of being conceptually very clear and easy to adjust. In this thread: How to efficiently generate random positive-semidefinite correlation matrices? -- I described and provided the code for two efficient algorithms of generating random correlation matrices. Both come from a paper by Lewandowski, Kurowicka, and Joe (2009), that @ssdecontrol referred to in the comments above (thanks a lot!). Please see my answer there for a lot of figures, explanations, and matlab code. The so called "vine" method allows to generate random correlation matrices with any distribution of partial correlations and can be used to generate correlation matrices with large off-diagonal values. Here is the example figure from that thread: The only thing that changes between subplots, is one parameter that controls how much the distribution of partial correlations is concentrated around $\pm 1$. I copy my code to generate these matrices here as well, to show that it is not longer than the other methods suggested here. Please see my linked answer for some explanations. The values of betaparam for the figure above were ${50,20,10,5,2,1}$ (and dimensionality d was $100$). 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 Update: eigenvalues @psarka asks about the eigenvalues of these matrices. On the figure below I plot the eigenvalue spectra of the same six correlation matrices as above. Notice that they decrease gradually; in contrast, the method suggested by @psarka generally results in a correlation matrix with one large eigenvalue, but the rest being pretty uniform. Update. Really simple method: several factors Similar to what @ttnphns wrote in the comments above and @GottfriedHelms in his answer, one very simple way to achieve my goal is to randomly generate several ($k<n$) factor loadings $\mathbf W$ (random matrix of $k \times n$ 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 (as described in my question). This is very simple and does the trick. Here are some example correlation matrices for $k={100, 50, 20, 10, 5, 1}$: The only downside is that the resulting matrix will have $k$ large eigenvalues and then a sudden drop, as opposed to a nice decay shown above with the vine method. Here are the corresponding spectra: Here is the code: d = 100; %// number of dimensions k = 5; %// number of factors W = randn(d,k); S = W*W' + diag(rand(1,d)); S = diag(1./sqrt(diag(S))) * S * diag(1./sqrt(diag(S)));
How to generate a large full-rank random correlation matrix with some strong correlations present?
Other answers came up with nice tricks to solve my problem in various ways. However, I found a principled approach that I think has a large advantage of being conceptually very clear and easy to adjus
How to generate a large full-rank random correlation matrix with some strong correlations present? Other answers came up with nice tricks to solve my problem in various ways. However, I found a principled approach that I think has a large advantage of being conceptually very clear and easy to adjust. In this thread: How to efficiently generate random positive-semidefinite correlation matrices? -- I described and provided the code for two efficient algorithms of generating random correlation matrices. Both come from a paper by Lewandowski, Kurowicka, and Joe (2009), that @ssdecontrol referred to in the comments above (thanks a lot!). Please see my answer there for a lot of figures, explanations, and matlab code. The so called "vine" method allows to generate random correlation matrices with any distribution of partial correlations and can be used to generate correlation matrices with large off-diagonal values. Here is the example figure from that thread: The only thing that changes between subplots, is one parameter that controls how much the distribution of partial correlations is concentrated around $\pm 1$. I copy my code to generate these matrices here as well, to show that it is not longer than the other methods suggested here. Please see my linked answer for some explanations. The values of betaparam for the figure above were ${50,20,10,5,2,1}$ (and dimensionality d was $100$). 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 Update: eigenvalues @psarka asks about the eigenvalues of these matrices. On the figure below I plot the eigenvalue spectra of the same six correlation matrices as above. Notice that they decrease gradually; in contrast, the method suggested by @psarka generally results in a correlation matrix with one large eigenvalue, but the rest being pretty uniform. Update. Really simple method: several factors Similar to what @ttnphns wrote in the comments above and @GottfriedHelms in his answer, one very simple way to achieve my goal is to randomly generate several ($k<n$) factor loadings $\mathbf W$ (random matrix of $k \times n$ 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 (as described in my question). This is very simple and does the trick. Here are some example correlation matrices for $k={100, 50, 20, 10, 5, 1}$: The only downside is that the resulting matrix will have $k$ large eigenvalues and then a sudden drop, as opposed to a nice decay shown above with the vine method. Here are the corresponding spectra: Here is the code: d = 100; %// number of dimensions k = 5; %// number of factors W = randn(d,k); S = W*W' + diag(rand(1,d)); S = diag(1./sqrt(diag(S))) * S * diag(1./sqrt(diag(S)));
How to generate a large full-rank random correlation matrix with some strong correlations present? Other answers came up with nice tricks to solve my problem in various ways. However, I found a principled approach that I think has a large advantage of being conceptually very clear and easy to adjus
8,255
How to generate a large full-rank random correlation matrix with some strong correlations present?
A simple thing but maybe will work for benchmark purposes: took your 2. and injected some correlations into starting matrix. Distribution is somewhat uniform, and changing $a$ you can get concentration near 1 and -1 or near 0. import numpy as np from random import choice import matplotlib.pyplot as plt n = 100 a = 2 A = np.matrix([np.random.randn(n) + np.random.randn(1)*a for i in range(n)]) A = A*np.transpose(A) D_half = np.diag(np.diag(A)**(-0.5)) C = D_half*A*D_half vals = list(np.array(C.ravel())[0]) plt.hist(vals, range=(-1,1)) plt.show() plt.imshow(C, interpolation=None) plt.show()
How to generate a large full-rank random correlation matrix with some strong correlations present?
A simple thing but maybe will work for benchmark purposes: took your 2. and injected some correlations into starting matrix. Distribution is somewhat uniform, and changing $a$ you can get concentratio
How to generate a large full-rank random correlation matrix with some strong correlations present? A simple thing but maybe will work for benchmark purposes: took your 2. and injected some correlations into starting matrix. Distribution is somewhat uniform, and changing $a$ you can get concentration near 1 and -1 or near 0. import numpy as np from random import choice import matplotlib.pyplot as plt n = 100 a = 2 A = np.matrix([np.random.randn(n) + np.random.randn(1)*a for i in range(n)]) A = A*np.transpose(A) D_half = np.diag(np.diag(A)**(-0.5)) C = D_half*A*D_half vals = list(np.array(C.ravel())[0]) plt.hist(vals, range=(-1,1)) plt.show() plt.imshow(C, interpolation=None) plt.show()
How to generate a large full-rank random correlation matrix with some strong correlations present? A simple thing but maybe will work for benchmark purposes: took your 2. and injected some correlations into starting matrix. Distribution is somewhat uniform, and changing $a$ you can get concentratio
8,256
How to generate a large full-rank random correlation matrix with some strong correlations present?
Hmm, after I' done an example in my MatMate-language I see that there is already a python-answer, which might be preferable because python is widely used. But because you had still questions I show you my approach using the Matmate-matrix-language, perhaps it is more selfcommenting. Method 1 (Using MatMate): v=12 // 12 variables f=3 // subset-correlation based on 3 common factors vg = v / f // variables per subsets // generate hidden factor-matrix // randomu(rows,cols ,lowbound, ubound) gives uniform random matrix // without explicite bounds the default is: randomu(rows,cols,0,100) L = { randomu(vg,f) || randomu(vg,f)/100 || randomu(vg,f)/100 , _ randomu(vg,f)/100 || randomu(vg,f) || randomu(vg,f)/100 , _ randomu(vg,f)/100 || randomu(vg,f)/100 || randomu(vg,f) } // make sure there is itemspecific variance // by appending a diagonal-matrix with random positive entries L = L || mkdiag(randomu(v,1,10,20)) // make covariance and correlation matrix cov = L *' // L multiplied with its transpose cor = covtocorr(cov) set ccdezweite=3 ccfeldweite=8 list cor cor = 1.000, 0.321, 0.919, 0.489, 0.025, 0.019, 0.019, 0.030, 0.025, 0.017, 0.014, 0.014 0.321, 1.000, 0.540, 0.923, 0.016, 0.015, 0.012, 0.030, 0.033, 0.016, 0.012, 0.015 0.919, 0.540, 1.000, 0.679, 0.018, 0.014, 0.012, 0.029, 0.028, 0.014, 0.012, 0.012 0.489, 0.923, 0.679, 1.000, 0.025, 0.022, 0.020, 0.040, 0.031, 0.014, 0.011, 0.014 0.025, 0.016, 0.018, 0.025, 1.000, 0.815, 0.909, 0.758, 0.038, 0.012, 0.018, 0.014 0.019, 0.015, 0.014, 0.022, 0.815, 1.000, 0.943, 0.884, 0.035, 0.012, 0.014, 0.012 0.019, 0.012, 0.012, 0.020, 0.909, 0.943, 1.000, 0.831, 0.036, 0.013, 0.015, 0.010 0.030, 0.030, 0.029, 0.040, 0.758, 0.884, 0.831, 1.000, 0.041, 0.017, 0.022, 0.020 0.025, 0.033, 0.028, 0.031, 0.038, 0.035, 0.036, 0.041, 1.000, 0.831, 0.868, 0.780 0.017, 0.016, 0.014, 0.014, 0.012, 0.012, 0.013, 0.017, 0.831, 1.000, 0.876, 0.848 0.014, 0.012, 0.012, 0.011, 0.018, 0.014, 0.015, 0.022, 0.868, 0.876, 1.000, 0.904 0.014, 0.015, 0.012, 0.014, 0.014, 0.012, 0.010, 0.020, 0.780, 0.848, 0.904, 1.000 The problem here might be, that we define blocks of submatrices which have high correlations within with little correlation between and this is not programmatically but by the constant concatenation-expressions . Maybe this approach could be modeled more elegantly in python. Method 2(a) After that, there is a completely different approach, where we fill the possible remaining covariance by random amounts of 100 percent into a factor-loadings-matrix. This is done in Pari/GP: {L = matrix(8,8); \\ generate an empty factor-loadings-matrix for(r=1,8, rv=1.0; \\ remaining variance for variable is 1.0 for(c=1,8, pv=if(c<8,random(100)/100.0,1.0); \\ define randomly part of remaining variance cv= pv * rv; \\ compute current partial variance rv = rv - cv; \\ compute the now remaining variance sg = (-1)^(random(100) % 2) ; \\ also introduce randomly +- signs L[r,c] = sg*sqrt(cv) ; \\ compute factor loading as signed sqrt of cv ) );} cor = L * L~ and the produced correlation-matrix is 1.000 -0.7111 -0.08648 -0.7806 0.8394 -0.7674 0.6812 0.2765 -0.7111 1.000 0.06073 0.7485 -0.7550 0.8052 -0.8273 0.05863 -0.08648 0.06073 1.000 0.5146 -0.1614 0.1459 -0.4760 -0.01800 -0.7806 0.7485 0.5146 1.000 -0.8274 0.7644 -0.9373 -0.06388 0.8394 -0.7550 -0.1614 -0.8274 1.000 -0.5823 0.8065 -0.1929 -0.7674 0.8052 0.1459 0.7644 -0.5823 1.000 -0.7261 -0.4822 0.6812 -0.8273 -0.4760 -0.9373 0.8065 -0.7261 1.000 -0.1526 0.2765 0.05863 -0.01800 -0.06388 -0.1929 -0.4822 -0.1526 1.000 Possibly this generates a correlation-matrix with dominant principal components because of the cumulative generating-rule for the factor-loadings-matrix. Also it might be better to assure positive definiteness by making the last portion of variance a unique factor. I left it in the program to keep the focus on the general principle. A 100x100 correlation-matrix had the following frequencies of correlations (rounded to 1 dec place) e f e: entry(rounded) f: frequency ----------------------------------------------------- -1.000, 108.000 -0.900, 460.000 -0.800, 582.000 -0.700, 604.000 -0.600, 548.000 -0.500, 540.000 -0.400, 506.000 -0.300, 482.000 -0.200, 488.000 -0.100, 464.000 0.000, 434.000 0.100, 486.000 0.200, 454.000 0.300, 468.000 0.400, 462.000 0.500, 618.000 0.600, 556.000 0.700, 586.000 0.800, 536.000 0.900, 420.000 1.000, 198.000 [update]. Hmm, the 100x100 matrix is badly conditioned; Pari/GP cannot determine the eigenvalues correctly with the polroots(charpoly())-function even with 200 digits precision. I've done a Jacobi-rotation to pca-form on the loadingsmatrix L and find mostly extremely small eigenvalues, printed them in logarithms to base 10 (which give roughly the position of the decimal point). Read from left to right and then row by row: log_10(eigenvalues): 1.684, 1.444, 1.029, 0.818, 0.455, 0.241, 0.117, -0.423, -0.664, -1.040 -1.647, -1.799, -1.959, -2.298, -2.729, -3.059, -3.497, -3.833, -4.014, -4.467 -4.992, -5.396, -5.511, -6.366, -6.615, -6.834, -7.535, -8.138, -8.263, -8.766 -9.082, -9.482, -9.940, -10.167, -10.566, -11.110, -11.434, -11.788, -12.079, -12.722 -13.122, -13.322, -13.444, -13.933, -14.390, -14.614, -15.070, -15.334, -15.904, -16.278 -16.396, -16.708, -17.022, -17.746, -18.090, -18.358, -18.617, -18.903, -19.186, -19.476 -19.661, -19.764, -20.342, -20.648, -20.805, -20.922, -21.394, -21.740, -21.991, -22.291 -22.792, -23.184, -23.680, -24.100, -24.222, -24.631, -24.979, -25.161, -25.282, -26.211 -27.181, -27.626, -27.861, -28.054, -28.266, -28.369, -29.074, -29.329, -29.539, -29.689 -30.216, -30.784, -31.269, -31.760, -32.218, -32.446, -32.785, -33.003, -33.448, -34.318 [update 2] Method 2(b) An improvement might be to increase the itemspecific variance to some non-marginal level and reduce to a reasonably smaller number of common factors (for instance integer-squareroot of itemnumber): { dimr = 100; dimc = sqrtint(dimr); \\ 10 common factors L = matrix(dimr,dimr+dimc); \\ loadings matrix \\ with dimr itemspecific and \\ dimc common factors for(r=1,dim, vr=1.0; \\ complete variance per item vu=0.05+random(100)/1000.0; \\ random variance +0.05 \\ for itemspecific variance L[r,r]=sqrt(vu); \\ itemspecific factor loading vr=vr-vu; for(c=1,dimc, cv=if(c<dimc,random(100)/100,1.0)*vr; vr=vr-cv; L[r,dimr+c]=(-1)^(random(100) % 2)*sqrt(cv) ) );} cov=L*L~ cp=charpoly(cov) \\ does not work even with 200 digits precision pr=polroots(cp) \\ spurious negative and complex eigenvalues... The structure of the result in term of the distribution of correlations: remains similar (also the nasty non decomposability by PariGP), but the eigenvalues, when found by jacobi-rotation of the loadingsmatrix, have now a better structure, for a newly computed example I got the eigenvalues as log_10(eigenvalues): 1.677, 1.326, 1.063, 0.754, 0.415, 0.116, -0.262, -0.516, -0.587, -0.783 -0.835, -0.844, -0.851, -0.854, -0.858, -0.862, -0.862, -0.868, -0.872, -0.873 -0.878, -0.882, -0.884, -0.890, -0.895, -0.896, -0.896, -0.898, -0.902, -0.904 -0.904, -0.909, -0.911, -0.914, -0.920, -0.923, -0.925, -0.927, -0.931, -0.935 -0.939, -0.939, -0.943, -0.948, -0.951, -0.955, -0.956, -0.960, -0.967, -0.969 -0.973, -0.981, -0.986, -0.989, -0.997, -1.003, -1.005, -1.011, -1.014, -1.019 -1.022, -1.024, -1.031, -1.038, -1.040, -1.048, -1.051, -1.061, -1.064, -1.068 -1.070, -1.074, -1.092, -1.092, -1.108, -1.113, -1.120, -1.134, -1.139, -1.147 -1.150, -1.155, -1.158, -1.166, -1.171, -1.175, -1.184, -1.184, -1.192, -1.196 -1.200, -1.220, -1.237, -1.245, -1.252, -1.262, -1.269, -1.282, -1.287, -1.290
How to generate a large full-rank random correlation matrix with some strong correlations present?
Hmm, after I' done an example in my MatMate-language I see that there is already a python-answer, which might be preferable because python is widely used. But because you had still questions I show yo
How to generate a large full-rank random correlation matrix with some strong correlations present? Hmm, after I' done an example in my MatMate-language I see that there is already a python-answer, which might be preferable because python is widely used. But because you had still questions I show you my approach using the Matmate-matrix-language, perhaps it is more selfcommenting. Method 1 (Using MatMate): v=12 // 12 variables f=3 // subset-correlation based on 3 common factors vg = v / f // variables per subsets // generate hidden factor-matrix // randomu(rows,cols ,lowbound, ubound) gives uniform random matrix // without explicite bounds the default is: randomu(rows,cols,0,100) L = { randomu(vg,f) || randomu(vg,f)/100 || randomu(vg,f)/100 , _ randomu(vg,f)/100 || randomu(vg,f) || randomu(vg,f)/100 , _ randomu(vg,f)/100 || randomu(vg,f)/100 || randomu(vg,f) } // make sure there is itemspecific variance // by appending a diagonal-matrix with random positive entries L = L || mkdiag(randomu(v,1,10,20)) // make covariance and correlation matrix cov = L *' // L multiplied with its transpose cor = covtocorr(cov) set ccdezweite=3 ccfeldweite=8 list cor cor = 1.000, 0.321, 0.919, 0.489, 0.025, 0.019, 0.019, 0.030, 0.025, 0.017, 0.014, 0.014 0.321, 1.000, 0.540, 0.923, 0.016, 0.015, 0.012, 0.030, 0.033, 0.016, 0.012, 0.015 0.919, 0.540, 1.000, 0.679, 0.018, 0.014, 0.012, 0.029, 0.028, 0.014, 0.012, 0.012 0.489, 0.923, 0.679, 1.000, 0.025, 0.022, 0.020, 0.040, 0.031, 0.014, 0.011, 0.014 0.025, 0.016, 0.018, 0.025, 1.000, 0.815, 0.909, 0.758, 0.038, 0.012, 0.018, 0.014 0.019, 0.015, 0.014, 0.022, 0.815, 1.000, 0.943, 0.884, 0.035, 0.012, 0.014, 0.012 0.019, 0.012, 0.012, 0.020, 0.909, 0.943, 1.000, 0.831, 0.036, 0.013, 0.015, 0.010 0.030, 0.030, 0.029, 0.040, 0.758, 0.884, 0.831, 1.000, 0.041, 0.017, 0.022, 0.020 0.025, 0.033, 0.028, 0.031, 0.038, 0.035, 0.036, 0.041, 1.000, 0.831, 0.868, 0.780 0.017, 0.016, 0.014, 0.014, 0.012, 0.012, 0.013, 0.017, 0.831, 1.000, 0.876, 0.848 0.014, 0.012, 0.012, 0.011, 0.018, 0.014, 0.015, 0.022, 0.868, 0.876, 1.000, 0.904 0.014, 0.015, 0.012, 0.014, 0.014, 0.012, 0.010, 0.020, 0.780, 0.848, 0.904, 1.000 The problem here might be, that we define blocks of submatrices which have high correlations within with little correlation between and this is not programmatically but by the constant concatenation-expressions . Maybe this approach could be modeled more elegantly in python. Method 2(a) After that, there is a completely different approach, where we fill the possible remaining covariance by random amounts of 100 percent into a factor-loadings-matrix. This is done in Pari/GP: {L = matrix(8,8); \\ generate an empty factor-loadings-matrix for(r=1,8, rv=1.0; \\ remaining variance for variable is 1.0 for(c=1,8, pv=if(c<8,random(100)/100.0,1.0); \\ define randomly part of remaining variance cv= pv * rv; \\ compute current partial variance rv = rv - cv; \\ compute the now remaining variance sg = (-1)^(random(100) % 2) ; \\ also introduce randomly +- signs L[r,c] = sg*sqrt(cv) ; \\ compute factor loading as signed sqrt of cv ) );} cor = L * L~ and the produced correlation-matrix is 1.000 -0.7111 -0.08648 -0.7806 0.8394 -0.7674 0.6812 0.2765 -0.7111 1.000 0.06073 0.7485 -0.7550 0.8052 -0.8273 0.05863 -0.08648 0.06073 1.000 0.5146 -0.1614 0.1459 -0.4760 -0.01800 -0.7806 0.7485 0.5146 1.000 -0.8274 0.7644 -0.9373 -0.06388 0.8394 -0.7550 -0.1614 -0.8274 1.000 -0.5823 0.8065 -0.1929 -0.7674 0.8052 0.1459 0.7644 -0.5823 1.000 -0.7261 -0.4822 0.6812 -0.8273 -0.4760 -0.9373 0.8065 -0.7261 1.000 -0.1526 0.2765 0.05863 -0.01800 -0.06388 -0.1929 -0.4822 -0.1526 1.000 Possibly this generates a correlation-matrix with dominant principal components because of the cumulative generating-rule for the factor-loadings-matrix. Also it might be better to assure positive definiteness by making the last portion of variance a unique factor. I left it in the program to keep the focus on the general principle. A 100x100 correlation-matrix had the following frequencies of correlations (rounded to 1 dec place) e f e: entry(rounded) f: frequency ----------------------------------------------------- -1.000, 108.000 -0.900, 460.000 -0.800, 582.000 -0.700, 604.000 -0.600, 548.000 -0.500, 540.000 -0.400, 506.000 -0.300, 482.000 -0.200, 488.000 -0.100, 464.000 0.000, 434.000 0.100, 486.000 0.200, 454.000 0.300, 468.000 0.400, 462.000 0.500, 618.000 0.600, 556.000 0.700, 586.000 0.800, 536.000 0.900, 420.000 1.000, 198.000 [update]. Hmm, the 100x100 matrix is badly conditioned; Pari/GP cannot determine the eigenvalues correctly with the polroots(charpoly())-function even with 200 digits precision. I've done a Jacobi-rotation to pca-form on the loadingsmatrix L and find mostly extremely small eigenvalues, printed them in logarithms to base 10 (which give roughly the position of the decimal point). Read from left to right and then row by row: log_10(eigenvalues): 1.684, 1.444, 1.029, 0.818, 0.455, 0.241, 0.117, -0.423, -0.664, -1.040 -1.647, -1.799, -1.959, -2.298, -2.729, -3.059, -3.497, -3.833, -4.014, -4.467 -4.992, -5.396, -5.511, -6.366, -6.615, -6.834, -7.535, -8.138, -8.263, -8.766 -9.082, -9.482, -9.940, -10.167, -10.566, -11.110, -11.434, -11.788, -12.079, -12.722 -13.122, -13.322, -13.444, -13.933, -14.390, -14.614, -15.070, -15.334, -15.904, -16.278 -16.396, -16.708, -17.022, -17.746, -18.090, -18.358, -18.617, -18.903, -19.186, -19.476 -19.661, -19.764, -20.342, -20.648, -20.805, -20.922, -21.394, -21.740, -21.991, -22.291 -22.792, -23.184, -23.680, -24.100, -24.222, -24.631, -24.979, -25.161, -25.282, -26.211 -27.181, -27.626, -27.861, -28.054, -28.266, -28.369, -29.074, -29.329, -29.539, -29.689 -30.216, -30.784, -31.269, -31.760, -32.218, -32.446, -32.785, -33.003, -33.448, -34.318 [update 2] Method 2(b) An improvement might be to increase the itemspecific variance to some non-marginal level and reduce to a reasonably smaller number of common factors (for instance integer-squareroot of itemnumber): { dimr = 100; dimc = sqrtint(dimr); \\ 10 common factors L = matrix(dimr,dimr+dimc); \\ loadings matrix \\ with dimr itemspecific and \\ dimc common factors for(r=1,dim, vr=1.0; \\ complete variance per item vu=0.05+random(100)/1000.0; \\ random variance +0.05 \\ for itemspecific variance L[r,r]=sqrt(vu); \\ itemspecific factor loading vr=vr-vu; for(c=1,dimc, cv=if(c<dimc,random(100)/100,1.0)*vr; vr=vr-cv; L[r,dimr+c]=(-1)^(random(100) % 2)*sqrt(cv) ) );} cov=L*L~ cp=charpoly(cov) \\ does not work even with 200 digits precision pr=polroots(cp) \\ spurious negative and complex eigenvalues... The structure of the result in term of the distribution of correlations: remains similar (also the nasty non decomposability by PariGP), but the eigenvalues, when found by jacobi-rotation of the loadingsmatrix, have now a better structure, for a newly computed example I got the eigenvalues as log_10(eigenvalues): 1.677, 1.326, 1.063, 0.754, 0.415, 0.116, -0.262, -0.516, -0.587, -0.783 -0.835, -0.844, -0.851, -0.854, -0.858, -0.862, -0.862, -0.868, -0.872, -0.873 -0.878, -0.882, -0.884, -0.890, -0.895, -0.896, -0.896, -0.898, -0.902, -0.904 -0.904, -0.909, -0.911, -0.914, -0.920, -0.923, -0.925, -0.927, -0.931, -0.935 -0.939, -0.939, -0.943, -0.948, -0.951, -0.955, -0.956, -0.960, -0.967, -0.969 -0.973, -0.981, -0.986, -0.989, -0.997, -1.003, -1.005, -1.011, -1.014, -1.019 -1.022, -1.024, -1.031, -1.038, -1.040, -1.048, -1.051, -1.061, -1.064, -1.068 -1.070, -1.074, -1.092, -1.092, -1.108, -1.113, -1.120, -1.134, -1.139, -1.147 -1.150, -1.155, -1.158, -1.166, -1.171, -1.175, -1.184, -1.184, -1.192, -1.196 -1.200, -1.220, -1.237, -1.245, -1.252, -1.262, -1.269, -1.282, -1.287, -1.290
How to generate a large full-rank random correlation matrix with some strong correlations present? Hmm, after I' done an example in my MatMate-language I see that there is already a python-answer, which might be preferable because python is widely used. But because you had still questions I show yo
8,257
How to generate a large full-rank random correlation matrix with some strong correlations present?
Interesting question (as always!). How about finding a set of example matrices that exhibit the properties you desire, and then take convex combinations thereof, since if $A$ and $B$ are positive definite, then so is $\lambda A + (1-\lambda)B$. As a bonus, no rescaling of the diagonals will be necessary, by the convexity of the operation. By adjusting the $\lambda$ to being more concentrated towards 0 and 1 versus uniformly distributed, you could concentrate the samples on the edges of the polytope, or the interior. (You could use a beta/Dirichlet distribution to control the concentration vs uniformity). For example, you could let $A$ to be component-symmetric, and $B$ be toeplitz. Of course, you can always add another class $C$, and take $\lambda_A A + \lambda_B B + \lambda_C C$ such that $\sum \lambda = 1$ and $\lambda \geq 0$, and so on.
How to generate a large full-rank random correlation matrix with some strong correlations present?
Interesting question (as always!). How about finding a set of example matrices that exhibit the properties you desire, and then take convex combinations thereof, since if $A$ and $B$ are positive def
How to generate a large full-rank random correlation matrix with some strong correlations present? Interesting question (as always!). How about finding a set of example matrices that exhibit the properties you desire, and then take convex combinations thereof, since if $A$ and $B$ are positive definite, then so is $\lambda A + (1-\lambda)B$. As a bonus, no rescaling of the diagonals will be necessary, by the convexity of the operation. By adjusting the $\lambda$ to being more concentrated towards 0 and 1 versus uniformly distributed, you could concentrate the samples on the edges of the polytope, or the interior. (You could use a beta/Dirichlet distribution to control the concentration vs uniformity). For example, you could let $A$ to be component-symmetric, and $B$ be toeplitz. Of course, you can always add another class $C$, and take $\lambda_A A + \lambda_B B + \lambda_C C$ such that $\sum \lambda = 1$ and $\lambda \geq 0$, and so on.
How to generate a large full-rank random correlation matrix with some strong correlations present? Interesting question (as always!). How about finding a set of example matrices that exhibit the properties you desire, and then take convex combinations thereof, since if $A$ and $B$ are positive def
8,258
How to generate a large full-rank random correlation matrix with some strong correlations present?
R has a package (clusterGeneration) that implements the method in: Joe, H. (2006) Generating Random Correlation Matrices Based on Partial Correlations. Journal of Multivariate Analysis, 97, 2177--2189. Example: > (cormat10 = clusterGeneration::rcorrmatrix(10, alphad = 1/100000000000000)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1.000 0.344 -0.1406 -0.65786 -0.19411 0.246 0.688 -0.6146 0.36971 -0.1052 [2,] 0.344 1.000 -0.4256 -0.35512 0.15973 0.192 0.340 -0.4907 -0.30539 -0.6104 [3,] -0.141 -0.426 1.0000 0.01775 -0.61507 -0.485 -0.273 0.3492 -0.30284 0.1647 [4,] -0.658 -0.355 0.0178 1.00000 0.00528 -0.335 -0.124 0.5256 -0.00583 -0.0737 [5,] -0.194 0.160 -0.6151 0.00528 1.00000 0.273 -0.350 -0.0785 0.08285 0.0985 [6,] 0.246 0.192 -0.4847 -0.33531 0.27342 1.000 0.278 -0.2220 -0.11010 0.0720 [7,] 0.688 0.340 -0.2734 -0.12363 -0.34972 0.278 1.000 -0.6409 0.40314 -0.2800 [8,] -0.615 -0.491 0.3492 0.52557 -0.07852 -0.222 -0.641 1.0000 -0.50796 0.1461 [9,] 0.370 -0.305 -0.3028 -0.00583 0.08285 -0.110 0.403 -0.5080 1.00000 0.3219 [10,] -0.105 -0.610 0.1647 -0.07373 0.09847 0.072 -0.280 0.1461 0.32185 1.0000 > cormat10[lower.tri(cormat10)] %>% psych::describe() vars n mean sd median trimmed mad min max range skew kurtosis se X1 1 45 -0.07 0.35 -0.08 -0.07 0.4 -0.66 0.69 1.35 0.03 -1 0.05 Unfortunately, it doesn't seem possible to simulate correlations that follow a uniform-ish distribution with this. It seems make stronger correlations when alphad is set to very small values, but even at 1/100000000000000, the range of correlations would only go up to about 1.40. Nonetheless, I hope this might be of some use to someone.
How to generate a large full-rank random correlation matrix with some strong correlations present?
R has a package (clusterGeneration) that implements the method in: Joe, H. (2006) Generating Random Correlation Matrices Based on Partial Correlations. Journal of Multivariate Analysis, 97, 2177--218
How to generate a large full-rank random correlation matrix with some strong correlations present? R has a package (clusterGeneration) that implements the method in: Joe, H. (2006) Generating Random Correlation Matrices Based on Partial Correlations. Journal of Multivariate Analysis, 97, 2177--2189. Example: > (cormat10 = clusterGeneration::rcorrmatrix(10, alphad = 1/100000000000000)) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1.000 0.344 -0.1406 -0.65786 -0.19411 0.246 0.688 -0.6146 0.36971 -0.1052 [2,] 0.344 1.000 -0.4256 -0.35512 0.15973 0.192 0.340 -0.4907 -0.30539 -0.6104 [3,] -0.141 -0.426 1.0000 0.01775 -0.61507 -0.485 -0.273 0.3492 -0.30284 0.1647 [4,] -0.658 -0.355 0.0178 1.00000 0.00528 -0.335 -0.124 0.5256 -0.00583 -0.0737 [5,] -0.194 0.160 -0.6151 0.00528 1.00000 0.273 -0.350 -0.0785 0.08285 0.0985 [6,] 0.246 0.192 -0.4847 -0.33531 0.27342 1.000 0.278 -0.2220 -0.11010 0.0720 [7,] 0.688 0.340 -0.2734 -0.12363 -0.34972 0.278 1.000 -0.6409 0.40314 -0.2800 [8,] -0.615 -0.491 0.3492 0.52557 -0.07852 -0.222 -0.641 1.0000 -0.50796 0.1461 [9,] 0.370 -0.305 -0.3028 -0.00583 0.08285 -0.110 0.403 -0.5080 1.00000 0.3219 [10,] -0.105 -0.610 0.1647 -0.07373 0.09847 0.072 -0.280 0.1461 0.32185 1.0000 > cormat10[lower.tri(cormat10)] %>% psych::describe() vars n mean sd median trimmed mad min max range skew kurtosis se X1 1 45 -0.07 0.35 -0.08 -0.07 0.4 -0.66 0.69 1.35 0.03 -1 0.05 Unfortunately, it doesn't seem possible to simulate correlations that follow a uniform-ish distribution with this. It seems make stronger correlations when alphad is set to very small values, but even at 1/100000000000000, the range of correlations would only go up to about 1.40. Nonetheless, I hope this might be of some use to someone.
How to generate a large full-rank random correlation matrix with some strong correlations present? R has a package (clusterGeneration) that implements the method in: Joe, H. (2006) Generating Random Correlation Matrices Based on Partial Correlations. Journal of Multivariate Analysis, 97, 2177--218
8,259
The difference of kernels in SVM?
The linear kernel is what you would expect, a linear model. I believe that the polynomial kernel is similar, but the boundary is of some defined but arbitrary order (e.g. order 3: $ a= b_1 + b_2 \cdot X + b_3 \cdot X^2 + b_4 \cdot X^3$). RBF uses normal curves around the data points, and sums these so that the decision boundary can be defined by a type of topology condition such as curves where the sum is above a value of 0.5. (see this picture ) I am not certain what the sigmoid kernel is, unless it is similar to the logistic regression model where a logistic function is used to define curves according to where the logistic value is greater than some value (modeling probability), such as 0.5 like the normal case.
The difference of kernels in SVM?
The linear kernel is what you would expect, a linear model. I believe that the polynomial kernel is similar, but the boundary is of some defined but arbitrary order (e.g. order 3: $ a= b_1 + b_2 \cdo
The difference of kernels in SVM? The linear kernel is what you would expect, a linear model. I believe that the polynomial kernel is similar, but the boundary is of some defined but arbitrary order (e.g. order 3: $ a= b_1 + b_2 \cdot X + b_3 \cdot X^2 + b_4 \cdot X^3$). RBF uses normal curves around the data points, and sums these so that the decision boundary can be defined by a type of topology condition such as curves where the sum is above a value of 0.5. (see this picture ) I am not certain what the sigmoid kernel is, unless it is similar to the logistic regression model where a logistic function is used to define curves according to where the logistic value is greater than some value (modeling probability), such as 0.5 like the normal case.
The difference of kernels in SVM? The linear kernel is what you would expect, a linear model. I believe that the polynomial kernel is similar, but the boundary is of some defined but arbitrary order (e.g. order 3: $ a= b_1 + b_2 \cdo
8,260
The difference of kernels in SVM?
Relying on basic knowledge of reader about kernels. Linear Kernel: $K(X, Y) = X^T Y$ Polynomial kernel: $K(X, Y) = (γ\cdot X^T Y + r)^d , γ > 0$ Radial basis function (RBF) Kernel: $K(X, Y) = \exp(\|X-Y\|^2/2σ^2)$ which in simple form can be written as $\exp(-γ \cdot \|X - Y\|^2), γ > 0$ Sigmoid Kernel: $K(X, Y) = \tanh(γ\cdot X^TY + r) $ which is similar to the sigmoid function in logistic regression. Here $r$, $d$, and $γ$ are kernel parameters.
The difference of kernels in SVM?
Relying on basic knowledge of reader about kernels. Linear Kernel: $K(X, Y) = X^T Y$ Polynomial kernel: $K(X, Y) = (γ\cdot X^T Y + r)^d , γ > 0$ Radial basis function (RBF) Kernel: $K(X, Y) = \exp(\
The difference of kernels in SVM? Relying on basic knowledge of reader about kernels. Linear Kernel: $K(X, Y) = X^T Y$ Polynomial kernel: $K(X, Y) = (γ\cdot X^T Y + r)^d , γ > 0$ Radial basis function (RBF) Kernel: $K(X, Y) = \exp(\|X-Y\|^2/2σ^2)$ which in simple form can be written as $\exp(-γ \cdot \|X - Y\|^2), γ > 0$ Sigmoid Kernel: $K(X, Y) = \tanh(γ\cdot X^TY + r) $ which is similar to the sigmoid function in logistic regression. Here $r$, $d$, and $γ$ are kernel parameters.
The difference of kernels in SVM? Relying on basic knowledge of reader about kernels. Linear Kernel: $K(X, Y) = X^T Y$ Polynomial kernel: $K(X, Y) = (γ\cdot X^T Y + r)^d , γ > 0$ Radial basis function (RBF) Kernel: $K(X, Y) = \exp(\
8,261
The difference of kernels in SVM?
This question can be answered from theoretical and practical point of view. From theoretical according to No-Free Lunch theorem states that there are no guarantees for one kernel to work better than the other. That is a-priori you never know nor you can find out which kernel will work better. From practical point of view consult the following page: How to select kernel for SVM?
The difference of kernels in SVM?
This question can be answered from theoretical and practical point of view. From theoretical according to No-Free Lunch theorem states that there are no guarantees for one kernel to work better than t
The difference of kernels in SVM? This question can be answered from theoretical and practical point of view. From theoretical according to No-Free Lunch theorem states that there are no guarantees for one kernel to work better than the other. That is a-priori you never know nor you can find out which kernel will work better. From practical point of view consult the following page: How to select kernel for SVM?
The difference of kernels in SVM? This question can be answered from theoretical and practical point of view. From theoretical according to No-Free Lunch theorem states that there are no guarantees for one kernel to work better than t
8,262
The difference of kernels in SVM?
While reflecting on what a kernel is "good for" or when it should be used, there are no hard and fast rules. If you're classifier/regressor is performing well with a given kernel, it is appropriate, if not, consider changing to another. Insight into how your kernel may perform, specifically if it is a classification model, might be gained by reviewing some visualisation examples, e.g. https://gist.github.com/WittmannF/60680723ed8dd0cb993051a7448f7805
The difference of kernels in SVM?
While reflecting on what a kernel is "good for" or when it should be used, there are no hard and fast rules. If you're classifier/regressor is performing well with a given kernel, it is appropriate,
The difference of kernels in SVM? While reflecting on what a kernel is "good for" or when it should be used, there are no hard and fast rules. If you're classifier/regressor is performing well with a given kernel, it is appropriate, if not, consider changing to another. Insight into how your kernel may perform, specifically if it is a classification model, might be gained by reviewing some visualisation examples, e.g. https://gist.github.com/WittmannF/60680723ed8dd0cb993051a7448f7805
The difference of kernels in SVM? While reflecting on what a kernel is "good for" or when it should be used, there are no hard and fast rules. If you're classifier/regressor is performing well with a given kernel, it is appropriate,
8,263
What did my neural network just learn? What features does it care about and why?
It is true that it's hard to understand what a neural network is learning but there has been a lot of work on that front. We definitely can get some idea of what our network is looking for. Let's consider the case of a convolutional neural net for images. We have the interpretation for our first layer that we are sliding $K$ filters over the image, so our first hidden layer corresponds to the agreement between small chunks of the image and our various filters. We can visualize these filters to see what our first layer of representation is: This picture is of the first layer of filters from an AlexNet and is taken from this wonderful tutorial: http://cs231n.github.io/understanding-cnn/. This lets us interpret the first hidden layer as learning to represent the image, consisting of raw pixels, as a tensor where each coordinate is the agreement of a filter with a small region of the image. The next layer then is working with these filter activations. It's not so hard to understand the first hidden layer because we can just look at the filters to see how they behave, because they're directly applied to an input image. E.g. let's say you're working with a black and white image (so our filters are 2D rather than 3D) and you have a filter that's something like $$ \begin{bmatrix}0 & 1 & 0 \\ 1 & -4 & 1 \\ 0 & 1 & 0\end{bmatrix}. $$ Imagine applying this to a 3x3 region of an image (ignoring the bias term). If every pixel was the same color then you'd get $0$ since they'd cancel out. But if the upper half is different from the lower half, say, then you'll get a potentially large value. This filter, in fact, is an edge detector, and we can figure that out by actually just applying it to images and seeing what happens. But it's a lot harder to understand the deeper layers because the whole problem is we don't know how to interpret what we're applying the filters to. This paper by Erhan et al (2009) agrees with this: they say that first hidden layer visualizations are common (and that was back in 2009) but visualizing the deeper layers is the hard part. From that paper: The main experimental finding of this investigation is very surprising: the response of an internal unit to input images, as a function in image space, appears to be unimodal, or at least that the maximum is found reliably and consistently for all the random initializations tested. This is interesting because finding this dominant mode is relatively easy, and displaying it then provides a good characterization of what the unit does. Chris Olah et al (https://distill.pub/2017/feature-visualization/) build on this and discuss how in general you can (1) generate images that lead to large activations in order to get a sense of what the network is looking for; or (2) take actual input images and see how different parts of the image activate the network. That post focuses on (1). In the image below, taken from that linked article by Olah et al., the authors discuss the different aspects of the network that you can inspect. The left-most image shows the result of optimizing the activation of a particular neuron over the input image space, and so on. I would highly recommend reading that article in its entirety if you want a deeper understanding of this, and by reading its references you should have a great grasp of what's been done with this. Now of course this was all just for images where we as humans can make sense of the inputs. If you're working with something harder to interpret, like just a big vector of numbers, then you may not be able to make such cool visualizations, but in principle you could still consider these techniques for assessing the various neurons, layers, and etc.
What did my neural network just learn? What features does it care about and why?
It is true that it's hard to understand what a neural network is learning but there has been a lot of work on that front. We definitely can get some idea of what our network is looking for. Let's cons
What did my neural network just learn? What features does it care about and why? It is true that it's hard to understand what a neural network is learning but there has been a lot of work on that front. We definitely can get some idea of what our network is looking for. Let's consider the case of a convolutional neural net for images. We have the interpretation for our first layer that we are sliding $K$ filters over the image, so our first hidden layer corresponds to the agreement between small chunks of the image and our various filters. We can visualize these filters to see what our first layer of representation is: This picture is of the first layer of filters from an AlexNet and is taken from this wonderful tutorial: http://cs231n.github.io/understanding-cnn/. This lets us interpret the first hidden layer as learning to represent the image, consisting of raw pixels, as a tensor where each coordinate is the agreement of a filter with a small region of the image. The next layer then is working with these filter activations. It's not so hard to understand the first hidden layer because we can just look at the filters to see how they behave, because they're directly applied to an input image. E.g. let's say you're working with a black and white image (so our filters are 2D rather than 3D) and you have a filter that's something like $$ \begin{bmatrix}0 & 1 & 0 \\ 1 & -4 & 1 \\ 0 & 1 & 0\end{bmatrix}. $$ Imagine applying this to a 3x3 region of an image (ignoring the bias term). If every pixel was the same color then you'd get $0$ since they'd cancel out. But if the upper half is different from the lower half, say, then you'll get a potentially large value. This filter, in fact, is an edge detector, and we can figure that out by actually just applying it to images and seeing what happens. But it's a lot harder to understand the deeper layers because the whole problem is we don't know how to interpret what we're applying the filters to. This paper by Erhan et al (2009) agrees with this: they say that first hidden layer visualizations are common (and that was back in 2009) but visualizing the deeper layers is the hard part. From that paper: The main experimental finding of this investigation is very surprising: the response of an internal unit to input images, as a function in image space, appears to be unimodal, or at least that the maximum is found reliably and consistently for all the random initializations tested. This is interesting because finding this dominant mode is relatively easy, and displaying it then provides a good characterization of what the unit does. Chris Olah et al (https://distill.pub/2017/feature-visualization/) build on this and discuss how in general you can (1) generate images that lead to large activations in order to get a sense of what the network is looking for; or (2) take actual input images and see how different parts of the image activate the network. That post focuses on (1). In the image below, taken from that linked article by Olah et al., the authors discuss the different aspects of the network that you can inspect. The left-most image shows the result of optimizing the activation of a particular neuron over the input image space, and so on. I would highly recommend reading that article in its entirety if you want a deeper understanding of this, and by reading its references you should have a great grasp of what's been done with this. Now of course this was all just for images where we as humans can make sense of the inputs. If you're working with something harder to interpret, like just a big vector of numbers, then you may not be able to make such cool visualizations, but in principle you could still consider these techniques for assessing the various neurons, layers, and etc.
What did my neural network just learn? What features does it care about and why? It is true that it's hard to understand what a neural network is learning but there has been a lot of work on that front. We definitely can get some idea of what our network is looking for. Let's cons
8,264
What did my neural network just learn? What features does it care about and why?
Neural Network is one of the black box models that would not give "easy to understand" rules / or what has been learned. Specifically, what has been learned are the parameters in the model, but the parameters can be large: hundreds of thousands of the parameters is very normal. In addition, it is also not clear on the important features learned, you can understand the model uses all the features, with many complicated operations to derive the results, where not easy to say in plain English how the model transform each feature use it. In fact, the one layer neural network (without hidden layer) with logistic function as activation function is identical to logistic regression. Logistic regression is very rich in interpretations. Here is one example. But with complex neural network / more hidden layers, such interpretation will not apply.
What did my neural network just learn? What features does it care about and why?
Neural Network is one of the black box models that would not give "easy to understand" rules / or what has been learned. Specifically, what has been learned are the parameters in the model, but the pa
What did my neural network just learn? What features does it care about and why? Neural Network is one of the black box models that would not give "easy to understand" rules / or what has been learned. Specifically, what has been learned are the parameters in the model, but the parameters can be large: hundreds of thousands of the parameters is very normal. In addition, it is also not clear on the important features learned, you can understand the model uses all the features, with many complicated operations to derive the results, where not easy to say in plain English how the model transform each feature use it. In fact, the one layer neural network (without hidden layer) with logistic function as activation function is identical to logistic regression. Logistic regression is very rich in interpretations. Here is one example. But with complex neural network / more hidden layers, such interpretation will not apply.
What did my neural network just learn? What features does it care about and why? Neural Network is one of the black box models that would not give "easy to understand" rules / or what has been learned. Specifically, what has been learned are the parameters in the model, but the pa
8,265
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline?
Like you already observed yourself, your choice of features (feature selection) may have an impact on which hyperparameters for your algorithm are optimal, and which hyperparameters you select for your algorithm may have an impact on which choice of features would be optimal. So, yes, if you really really care about squeezing every single percent of performance out of your model, and you can afford the required amount of computation, the best solution is probably to do feature selection and hyperparamter tuning "at the same time". That's probably not easy (depending on how you do feature selection) though. The way I imagine it working would be like having different sets of features as candidates, and treating the selection of one set of features out of all those candidate sets as an additional hyperparameter. In practice that may not really be feasible though. In general, if you cannot afford to evaluate all the possible combinations, I'd recommend: Very loosely optimize hyperparameters, just to make sure you don't assign extremely bad values to some hyperparameters. This can often just be done by hand if you have a good intuitive understanding of your hyperparameters, or done with a very brief hyperparameter optimization procedure using just a bunch of features that you know to be decently good otherwise. Feature selection, with hyperparameters that are maybe not 100% optimized but at least not extremely terrible either. If you have at least a somewhat decently configured machine learning algorithm already, having good features will be significantly more important for your performance than micro-optimizing hyperparameters. Extreme examples: If you have no features, you can't predict anything. If you have a cheating feature that contains the class label, you can perfectly classify everything. Optimize hyperparameters with the features selected in the step above. This should be a good feature set now, where it actually may be worth optimizing hyperparams a bit. To address the additional question that Nikolas posted in the comments, concering how all these things (feature selection, hyperparameter optimization) interact with k-fold cross validation: I'd say it depends. Whenever you use data in one of the folds for anything at all, and then evaluate performance on that same fold, you get a biased estimate of your performance (you'll overestimate performance). So, if you use data in all the folds for the feature selection step, and then evaluate performance on each of those folds, you'll get biased estimates of performance for each of them (which is not good). Similarly, if you have data-driven hyperparameter optimization and use data from certain folds (or all folds), and then evaluate on those same folds, you'll again get biased estimates of performance. Possible solutions are: Repeat the complete pipeline within every fold separately (e.g. within each fold, do feature selection + hyperparameter optimization and training model). Doing this means that k-fold cross validation gives you unbiased estimates of the performance of this complete pipeline. Split your initial dataset into a ''preprocessing dataset'' and a ''train/test dataset''. You can do your feature selection + hyperparameter optimization on the ''preprocessing dataset''. Then, you fix your selected features and hyperparameters, and do k-fold cross validation on the ''train/test dataset''. Doing this means that k-fold cross validation gives you unbiased estimates of the performance of your ML algorithm given the fixed feature-set and hyperparameter values. Note how the two solutions result in slightly different estimates of performance. Which one is more interesting depends on your use-case, depends on how you plan to deploy your machine learning solutions in practice. If you're, for example, a company that intends to have the complete pipeline of feature selection + hyperparameter optimization + training running automatically every day/week/month/year/whatever, you'll also be interested in the performance of that complete pipeline, and you'll want the first solution. If, on the other hand, you can only afford to do the feature selection + hyperparameter optimization a single time in your life, and afterwards only somewhat regularly re-train your algorithm (with feature-set and hyperparam values fixed), then the performance of only that step will be what you're interested in, and you should go for the second solution
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe
Like you already observed yourself, your choice of features (feature selection) may have an impact on which hyperparameters for your algorithm are optimal, and which hyperparameters you select for you
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline? Like you already observed yourself, your choice of features (feature selection) may have an impact on which hyperparameters for your algorithm are optimal, and which hyperparameters you select for your algorithm may have an impact on which choice of features would be optimal. So, yes, if you really really care about squeezing every single percent of performance out of your model, and you can afford the required amount of computation, the best solution is probably to do feature selection and hyperparamter tuning "at the same time". That's probably not easy (depending on how you do feature selection) though. The way I imagine it working would be like having different sets of features as candidates, and treating the selection of one set of features out of all those candidate sets as an additional hyperparameter. In practice that may not really be feasible though. In general, if you cannot afford to evaluate all the possible combinations, I'd recommend: Very loosely optimize hyperparameters, just to make sure you don't assign extremely bad values to some hyperparameters. This can often just be done by hand if you have a good intuitive understanding of your hyperparameters, or done with a very brief hyperparameter optimization procedure using just a bunch of features that you know to be decently good otherwise. Feature selection, with hyperparameters that are maybe not 100% optimized but at least not extremely terrible either. If you have at least a somewhat decently configured machine learning algorithm already, having good features will be significantly more important for your performance than micro-optimizing hyperparameters. Extreme examples: If you have no features, you can't predict anything. If you have a cheating feature that contains the class label, you can perfectly classify everything. Optimize hyperparameters with the features selected in the step above. This should be a good feature set now, where it actually may be worth optimizing hyperparams a bit. To address the additional question that Nikolas posted in the comments, concering how all these things (feature selection, hyperparameter optimization) interact with k-fold cross validation: I'd say it depends. Whenever you use data in one of the folds for anything at all, and then evaluate performance on that same fold, you get a biased estimate of your performance (you'll overestimate performance). So, if you use data in all the folds for the feature selection step, and then evaluate performance on each of those folds, you'll get biased estimates of performance for each of them (which is not good). Similarly, if you have data-driven hyperparameter optimization and use data from certain folds (or all folds), and then evaluate on those same folds, you'll again get biased estimates of performance. Possible solutions are: Repeat the complete pipeline within every fold separately (e.g. within each fold, do feature selection + hyperparameter optimization and training model). Doing this means that k-fold cross validation gives you unbiased estimates of the performance of this complete pipeline. Split your initial dataset into a ''preprocessing dataset'' and a ''train/test dataset''. You can do your feature selection + hyperparameter optimization on the ''preprocessing dataset''. Then, you fix your selected features and hyperparameters, and do k-fold cross validation on the ''train/test dataset''. Doing this means that k-fold cross validation gives you unbiased estimates of the performance of your ML algorithm given the fixed feature-set and hyperparameter values. Note how the two solutions result in slightly different estimates of performance. Which one is more interesting depends on your use-case, depends on how you plan to deploy your machine learning solutions in practice. If you're, for example, a company that intends to have the complete pipeline of feature selection + hyperparameter optimization + training running automatically every day/week/month/year/whatever, you'll also be interested in the performance of that complete pipeline, and you'll want the first solution. If, on the other hand, you can only afford to do the feature selection + hyperparameter optimization a single time in your life, and afterwards only somewhat regularly re-train your algorithm (with feature-set and hyperparam values fixed), then the performance of only that step will be what you're interested in, and you should go for the second solution
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe Like you already observed yourself, your choice of features (feature selection) may have an impact on which hyperparameters for your algorithm are optimal, and which hyperparameters you select for you
8,266
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline?
No one mentioned approaches that make hyper-parameter tuning and feature selection the same so I will talk about it. For this case you should engineer all the features you want at the beginning and include them all. Research now in the statistics community have tried to make feature selection a tuning criterion. Basically you penalize a model in such a way that it is incentivized to choose only a few features that help it make the best prediction. But you add a tuning parameter to determine how big of a penalty you should incur. In other words you allow the model to pick the features for you and you more or less have control of the number of features. This actually reduces computation because you no longer have to decide which features but just how many features and the model does the rest. So then when you do cross-validation on the parameter then you are effectively doing cross-validation on feature selection as well. Already there are many ML models that incorporate this feature selection in some way or another. Doubly-regularized support vector machines which is like normal SVM but with feature selection Elastic net which deals with linear regression Drop-out regularization in neural networks (don't have reference for this one) Random forest normally does random subsets of the features so kind of handles feature selection for you In short, people have tried to incorporate parameter tuning and feature selection at the same time in order reduce complexity and be able to do cross-validation
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe
No one mentioned approaches that make hyper-parameter tuning and feature selection the same so I will talk about it. For this case you should engineer all the features you want at the beginning and i
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline? No one mentioned approaches that make hyper-parameter tuning and feature selection the same so I will talk about it. For this case you should engineer all the features you want at the beginning and include them all. Research now in the statistics community have tried to make feature selection a tuning criterion. Basically you penalize a model in such a way that it is incentivized to choose only a few features that help it make the best prediction. But you add a tuning parameter to determine how big of a penalty you should incur. In other words you allow the model to pick the features for you and you more or less have control of the number of features. This actually reduces computation because you no longer have to decide which features but just how many features and the model does the rest. So then when you do cross-validation on the parameter then you are effectively doing cross-validation on feature selection as well. Already there are many ML models that incorporate this feature selection in some way or another. Doubly-regularized support vector machines which is like normal SVM but with feature selection Elastic net which deals with linear regression Drop-out regularization in neural networks (don't have reference for this one) Random forest normally does random subsets of the features so kind of handles feature selection for you In short, people have tried to incorporate parameter tuning and feature selection at the same time in order reduce complexity and be able to do cross-validation
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe No one mentioned approaches that make hyper-parameter tuning and feature selection the same so I will talk about it. For this case you should engineer all the features you want at the beginning and i
8,267
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline?
@DennisSoemers has a great solution. I'll add a two similar solutions that are a bit more explicit and based on Feature Engineering and Selection: A Practical Approach for Predictive Models by Max Kuhn and Kjell Johnson. Kuhn uses the term resample to describe a fold of a dataset, but the dominant term on StackExchange seems to be fold, so I will use the term fold below. Option 1 - nested search If compute power is not a limiting factor, a nested validation approach is recommended, in which there are 3 levels of nesting: 1) the external folds, each fold with a different feature subset 2) the internal folds, each fold with a hyperparameter search 3) the internal folds of each hyperparameter search, each fold with a different hyperparameter set. Here's the algorithm: -> Split data into train and test sets. -> For each external fold of train set: -> Select feature subset. -> Split into external train and test sets. -> For each internal fold of external train set: -> Split into internal train and test sets. -> Perform hyperparameter tuning on the internal train set. Note that this step is another level of nesting in which the internal train set is split into multiple folds and different hyperparameter sets are trained and tested on different folds. -> Examine the performance of the best hyperparameter tuned model from each of the inner test folds. If performance is consistent, redo the internal hyperparameter tuning step on the entire external train set. -> Test the model with the best hyperparameter set on the external test set. -> Choose the feature set with the best external test score. -> Retrain the model on all of the training data using the best feature set and best hyperparameters for that feature set. Image from Chapter 11.2: Simple Filters The -> Select feature subset step is implied to be random, but there are other techniques, which are outlined in the book in Chapter 11. To clarify the -> Perform hyperparameter tuning step, you can read about the recommended approach of nested cross validation. The idea is to test the robustness of a training process by repeatedly performing the training and testing process on different folds of the data, and looking at the average of test results. Option 2 - separate hyperparameter and feature selection search -> Split data into hyperameter_train, feature_selection_train, and test sets. -> Select a reasonable subset of features using expert knowledge. -> Perform nested cross validation with the initial features and the hyperparameter_train set to find the best hyperparameters as outlined in option 1. -> Use the best hyperparameters and the feature_selection_train set to find the best set of features. Again, this process could be nested cross validation or not, depending on the computational cost that it would take and the cost that is tolerable. Here's how Kuhn and Johsnon phrase the process: When combining a global search method with a model that has tuning parameters, we recommend that, when possible, the feature set first be winnowed down using expert knowledge about the problem. Next, it is important to identify a reasonable range of tuning parameter values. If a sufficient number of samples are available, a proportion of them can be split off and used to find a range of potentially good parameter values using all of the features. The tuning parameter values may not be the perfect choice for feature subsets, but they should be reasonably effective for finding an optimal subset. Chapter 12.5: Global Search Methods
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe
@DennisSoemers has a great solution. I'll add a two similar solutions that are a bit more explicit and based on Feature Engineering and Selection: A Practical Approach for Predictive Models by Max Kuh
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline? @DennisSoemers has a great solution. I'll add a two similar solutions that are a bit more explicit and based on Feature Engineering and Selection: A Practical Approach for Predictive Models by Max Kuhn and Kjell Johnson. Kuhn uses the term resample to describe a fold of a dataset, but the dominant term on StackExchange seems to be fold, so I will use the term fold below. Option 1 - nested search If compute power is not a limiting factor, a nested validation approach is recommended, in which there are 3 levels of nesting: 1) the external folds, each fold with a different feature subset 2) the internal folds, each fold with a hyperparameter search 3) the internal folds of each hyperparameter search, each fold with a different hyperparameter set. Here's the algorithm: -> Split data into train and test sets. -> For each external fold of train set: -> Select feature subset. -> Split into external train and test sets. -> For each internal fold of external train set: -> Split into internal train and test sets. -> Perform hyperparameter tuning on the internal train set. Note that this step is another level of nesting in which the internal train set is split into multiple folds and different hyperparameter sets are trained and tested on different folds. -> Examine the performance of the best hyperparameter tuned model from each of the inner test folds. If performance is consistent, redo the internal hyperparameter tuning step on the entire external train set. -> Test the model with the best hyperparameter set on the external test set. -> Choose the feature set with the best external test score. -> Retrain the model on all of the training data using the best feature set and best hyperparameters for that feature set. Image from Chapter 11.2: Simple Filters The -> Select feature subset step is implied to be random, but there are other techniques, which are outlined in the book in Chapter 11. To clarify the -> Perform hyperparameter tuning step, you can read about the recommended approach of nested cross validation. The idea is to test the robustness of a training process by repeatedly performing the training and testing process on different folds of the data, and looking at the average of test results. Option 2 - separate hyperparameter and feature selection search -> Split data into hyperameter_train, feature_selection_train, and test sets. -> Select a reasonable subset of features using expert knowledge. -> Perform nested cross validation with the initial features and the hyperparameter_train set to find the best hyperparameters as outlined in option 1. -> Use the best hyperparameters and the feature_selection_train set to find the best set of features. Again, this process could be nested cross validation or not, depending on the computational cost that it would take and the cost that is tolerable. Here's how Kuhn and Johsnon phrase the process: When combining a global search method with a model that has tuning parameters, we recommend that, when possible, the feature set first be winnowed down using expert knowledge about the problem. Next, it is important to identify a reasonable range of tuning parameter values. If a sufficient number of samples are available, a proportion of them can be split off and used to find a range of potentially good parameter values using all of the features. The tuning parameter values may not be the perfect choice for feature subsets, but they should be reasonably effective for finding an optimal subset. Chapter 12.5: Global Search Methods
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe @DennisSoemers has a great solution. I'll add a two similar solutions that are a bit more explicit and based on Feature Engineering and Selection: A Practical Approach for Predictive Models by Max Kuh
8,268
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline?
I think you are overthinking quite a bit there. Feature selection, which is part of feature engineering, is usually helpful but some redundant features are not much harmful in early stage of a machine learning system. So best practice is that you generate all meaningful features first, then use them to select algorithms and tune models, after tuning the model you can trim the feature set or decide to use new features. The machine learning procedure is actually an iterating process, in which you do feature engineering, then try with some algorithms, then tune the models and go back until you are satisfied with the result.
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe
I think you are overthinking quite a bit there. Feature selection, which is part of feature engineering, is usually helpful but some redundant features are not much harmful in early stage of a machine
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipeline? I think you are overthinking quite a bit there. Feature selection, which is part of feature engineering, is usually helpful but some redundant features are not much harmful in early stage of a machine learning system. So best practice is that you generate all meaningful features first, then use them to select algorithms and tune models, after tuning the model you can trim the feature set or decide to use new features. The machine learning procedure is actually an iterating process, in which you do feature engineering, then try with some algorithms, then tune the models and go back until you are satisfied with the result.
How should Feature Selection and Hyperparameter optimization be ordered in the machine learning pipe I think you are overthinking quite a bit there. Feature selection, which is part of feature engineering, is usually helpful but some redundant features are not much harmful in early stage of a machine
8,269
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
The problem of NOT correcting the bias According to the paper In case of sparse gradients, for a reliable estimate of the second moment one needs to average over many gradients by chosing a small value of β2; however it is exactly this case of small β2 where a lack of initialisation bias correction would lead to initial steps that are much larger. Normally in practice $\beta_2$ is set much closer to 1 than $\beta_1$ (as suggested by the author $\beta_2=0.999$, $\beta_1=0.9$), so the update coefficients $1-\beta_2=0.001$ is much smaller than $1-\beta_1=0.1$. In the first step of training $m_1=0.1g_t$, $v_1=0.001g_t^2$, the $m_1/(\sqrt{v_1}+\epsilon)$ term in the parameter update can be very large if we use the biased estimation directly. On the other hand when using the bias-corrected estimation, $\hat{m_1}=g_1$ and $\hat{v_1}=g_1^2$, the $\hat{m_t}/(\sqrt{\hat{v_t}}+\epsilon)$ term becomes less sensitive to $\beta_1$ and $\beta_2$. How the bias is corrected The algorithm uses moving average to estimate the first and second moments. The biased estimation would be, we start at an arbitrary guess $m_0$, and update the estimation gradually by $m_t=\beta m_{t-1}+(1-\beta)g_t$. So it's obvious in the first few steps our moving average is heavily biased towards the initial $m_0$. To correct this, we can remove the effect of the initial guess (bias) out of the moving average. For example at time 1, $m_1=\beta m_0+(1-\beta)g_t$, we take out the $\beta m_0$ term from $m_1$ and divide it by $(1-\beta)$, which yields $\hat{m_1}=(m_1- \beta m_0)/(1-\beta)$. When $m_0=0$, $\hat{m_t}=m_t/(1-\beta^t)$. The full proof is given in Section 3 of the paper. As Mark L. Stone has well commented It's like multiplying by 2 (oh my, the result is biased), and then dividing by 2 to "correct" it. Somehow this is not exactly equivalent to the gradient at initial point is used for the initial values of these things, and then the first parameter update (of course it can be turned into the same form by changing the update rule (see the update of the answer), and I believe this line mainly aims at showing the unnecessity of introducing the bias, but perhaps it's worth noticing the difference) For example, the corrected first moment at time 2 $$\hat{m_2}=\frac{\beta(1-\beta)g_1+(1-\beta)g_2}{1-\beta^2}=\frac{\beta g_1+g_2}{\beta+1}$$ If using $g_1$ as the initial value with the same update rule, $$m_2=\beta g_1+(1-\beta)g_2$$ which will bias towards $g_1$ instead in the first few steps. Is bias correction really a big deal Since it only actually affects the first few steps of training, it seems not a very big issue, in many popular frameworks (e.g. keras, caffe) only the biased estimation is implemented. From my experience the biased estimation sometimes leads to undesirable situations where the loss won't go down (I haven't thoroughly tested that so I'm not exactly sure whether this is due to the biased estimation or something else), and a trick that I use is using a larger $\epsilon$ to moderate the initial step sizes. Update If you unfold the recursive update rules, essentially $\hat{m}_t$ is a weighted average of the gradients, $$\hat{m}_t=\frac{\beta^{t-1}g_1+\beta^{t-2}g_2+...+g_t}{\beta^{t-1}+\beta^{t-2}+...+1}$$ The denominator can be computed by the geometric sum formula, so it's equivalent to following update rule (which doesn't involve a bias term) $m_1\leftarrow g_1$ while not converge do $\qquad m_t\leftarrow \beta m_t + g_t$ (weighted sum) $\qquad \hat{m}_t\leftarrow \dfrac{(1-\beta)m_t}{1-\beta^t}$ (weighted average) Therefore it can be possibly done without introducing a bias term and correcting it. I think the paper put it in the bias-correction form for the convenience of comparing with other algorithms (e.g. RmsProp).
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
The problem of NOT correcting the bias According to the paper In case of sparse gradients, for a reliable estimate of the second moment one needs to average over many gradients by chosing a small v
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? The problem of NOT correcting the bias According to the paper In case of sparse gradients, for a reliable estimate of the second moment one needs to average over many gradients by chosing a small value of β2; however it is exactly this case of small β2 where a lack of initialisation bias correction would lead to initial steps that are much larger. Normally in practice $\beta_2$ is set much closer to 1 than $\beta_1$ (as suggested by the author $\beta_2=0.999$, $\beta_1=0.9$), so the update coefficients $1-\beta_2=0.001$ is much smaller than $1-\beta_1=0.1$. In the first step of training $m_1=0.1g_t$, $v_1=0.001g_t^2$, the $m_1/(\sqrt{v_1}+\epsilon)$ term in the parameter update can be very large if we use the biased estimation directly. On the other hand when using the bias-corrected estimation, $\hat{m_1}=g_1$ and $\hat{v_1}=g_1^2$, the $\hat{m_t}/(\sqrt{\hat{v_t}}+\epsilon)$ term becomes less sensitive to $\beta_1$ and $\beta_2$. How the bias is corrected The algorithm uses moving average to estimate the first and second moments. The biased estimation would be, we start at an arbitrary guess $m_0$, and update the estimation gradually by $m_t=\beta m_{t-1}+(1-\beta)g_t$. So it's obvious in the first few steps our moving average is heavily biased towards the initial $m_0$. To correct this, we can remove the effect of the initial guess (bias) out of the moving average. For example at time 1, $m_1=\beta m_0+(1-\beta)g_t$, we take out the $\beta m_0$ term from $m_1$ and divide it by $(1-\beta)$, which yields $\hat{m_1}=(m_1- \beta m_0)/(1-\beta)$. When $m_0=0$, $\hat{m_t}=m_t/(1-\beta^t)$. The full proof is given in Section 3 of the paper. As Mark L. Stone has well commented It's like multiplying by 2 (oh my, the result is biased), and then dividing by 2 to "correct" it. Somehow this is not exactly equivalent to the gradient at initial point is used for the initial values of these things, and then the first parameter update (of course it can be turned into the same form by changing the update rule (see the update of the answer), and I believe this line mainly aims at showing the unnecessity of introducing the bias, but perhaps it's worth noticing the difference) For example, the corrected first moment at time 2 $$\hat{m_2}=\frac{\beta(1-\beta)g_1+(1-\beta)g_2}{1-\beta^2}=\frac{\beta g_1+g_2}{\beta+1}$$ If using $g_1$ as the initial value with the same update rule, $$m_2=\beta g_1+(1-\beta)g_2$$ which will bias towards $g_1$ instead in the first few steps. Is bias correction really a big deal Since it only actually affects the first few steps of training, it seems not a very big issue, in many popular frameworks (e.g. keras, caffe) only the biased estimation is implemented. From my experience the biased estimation sometimes leads to undesirable situations where the loss won't go down (I haven't thoroughly tested that so I'm not exactly sure whether this is due to the biased estimation or something else), and a trick that I use is using a larger $\epsilon$ to moderate the initial step sizes. Update If you unfold the recursive update rules, essentially $\hat{m}_t$ is a weighted average of the gradients, $$\hat{m}_t=\frac{\beta^{t-1}g_1+\beta^{t-2}g_2+...+g_t}{\beta^{t-1}+\beta^{t-2}+...+1}$$ The denominator can be computed by the geometric sum formula, so it's equivalent to following update rule (which doesn't involve a bias term) $m_1\leftarrow g_1$ while not converge do $\qquad m_t\leftarrow \beta m_t + g_t$ (weighted sum) $\qquad \hat{m}_t\leftarrow \dfrac{(1-\beta)m_t}{1-\beta^t}$ (weighted average) Therefore it can be possibly done without introducing a bias term and correcting it. I think the paper put it in the bias-correction form for the convenience of comparing with other algorithms (e.g. RmsProp).
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? The problem of NOT correcting the bias According to the paper In case of sparse gradients, for a reliable estimate of the second moment one needs to average over many gradients by chosing a small v
8,270
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
An example, with some number crunching, might be intuitive and also help debunk the idea of using the initial gradient instead of $0$. Consider the 1D problem $f(x)=x$, where $f'(x)=1$. $\beta_1=0.9$ and $\beta_2=0.999$ as usual. The first few values of $m_t$ and $v_t$ (rounded to 4 places) are given below. \begin{array}{c|c|c|c} t&m_t&v_t&m_t/\sqrt{v_t}\\\hline 0&0&0&\mathrm{N/A}\\ 1&0.1000&0.001000&3.162\\ 2&0.1900&0.001999&4.250\\ 3&0.2710&0.002997&4.950\\ 4&0.3439&0.003994&5.442 \end{array} At $t=12$, we reach a high of $m_t/\sqrt{v_t}=6.568$, and from there it descends to $1$, the "correct" value of $m_t/\sqrt{v_t}$. In other words, with these parameters we may reach step sizes roughly $6.5$ times larger than what they should be, which may be undesirable. We can also see that initially $m_t$ and $v_t$ are very close to $0$. As dontloo shows, $m_t$ and $v_t$ are always going to start out close to the initially used value. As Mark L. Stone comments, What I don't understand is why the gradient at initial point is not used for the initial values of these things, and then the first parameter update. Then there would be no contamination by the initial zero values, which has to be undone. So there'd be no need for the bias correction. Consider, however, the context in which momentum estimates are often used: stochastic/mini-batch gradient descent. It should be expected that the initial (stochastic) gradient is not an accurate estimate of the true gradient. If we truly want an accurate estimate of the gradient, then we need to have nearly equal contributions from the first few gradients. Note then the expanded expressions for their choice of $m_t$, using $m_0=0$. \begin{align} m_1&=0.1g_1\\ m_2&=0.1g_2+0.09g_1\\ m_3&=0.1g_3+0.09g_2+0.081g_1\\ m_4&=0.1g_4+0.09g_3+0.081g_2+0.0729g_1 \end{align} It is apparent that $m_t$ shares nearly the same amount of the previous several $g_t$. Now consider setting $m_1=g_1$. \begin{align} m_1&=g_1\\ m_2&=0.1g_2+0.9g_1\\ m_3&=0.1g_3+0.09g_2+0.81g_1\\ m_4&=0.1g_4+0.09g_3+0.081g_2+0.729g_1 \end{align} As expected, $g_1$ now has a ten-fold influence on $m_t$. One could make the argument that the influence of $g_1$ in $m_t$ is rapidly diminishing, and hence largely irrelevant. But what about $v_t$? Based on our previous example, we should expect a thousand-fold influence. Let's compare $v_t$ and $\bar v_t$, where $v_0=0$ and $\bar v_1=g_1^2$. Doing the math, here's the $\%$ influence of $g_1$ on the $v$'s for several $t$. \begin{array}{c|c|c} t&\%\text{ of $g_1$ in $v_t$}&\%\text{ of $g_1$ in $\bar v_t$}\\\hline 1&100\%&100\%\\ 10&9.96\%&99.1\%\\ 100&0.951\%&90.5\%\\ 200&0.452\%&81.9\%\\ 300&0.286\%&74.1\%\\ 400&0.203\%&67.1\%\\ 500&0.154\%&60.7\%\\ 600&0.122\%&54.9\%\\ 1000&0.0582\%&36.8\%\\ 2000&0.0156\%&13.5\% \end{array} In my humble opinion, this is atrociously bad. Would I rather risk an initially inaccurate estimate of the gradient persisting in my momentum so significantly just to avoid a division by $1-\beta_2^t$? Absolutely not. For the not-so-mathematically inclined, how does their bias correction solve all of these issues? Let's go through it, one-by-one. At $t=12$, we reach a high of $m_t/\sqrt{v_t}=6.568$, and from there it descends to $1$, the "correct" value of $m_t/\sqrt{v_t}$. In other words, with these parameters we may reach step sizes roughly $6.5$ times larger than what they should be, which may be undesirable. The bias correction solves this issue by rescaling $m_t$ and $v_t$ to have roughly the same magnitude as $g_t$ and $g_t^2$. How exactly? It divides the total sum by the sum of the weights of each $g_t$. \begin{align} \hat m_1&=\frac{0.1g_1}{0.1}\\~\\ \hat m_2&=\frac{0.1g_2+0.09g_1}{0.1+0.09}\\~\\ \hat m_3&=\frac{0.1g_3+0.09g_2+0.081g_1}{0.1+0.09+0.081}\\~\\ \hat m_4&=\frac{0.1g_4+0.09g_3+0.081g_2+0.0729g_1}{0.1+0.09+0.081+0.0729} \end{align} It turns out this denominator can more simply be written as $1-\beta_1^t$. It can also be seen from the last table that by initializing $v_0=0$, we get a much more accurate momentum than initializing $v_1=g_1^2$. Indeed using $v_1=g_1^2$ actually introduces another, perhaps concerning, problem. Furthermore, we observe that using the "initial gradient" approach is subject significantly more to the choice of $\beta$. Although $\beta=0.9$ is not so bad, when $\beta=0.999$, it can cause the initial value to persist much longer. What should you understand from all this, intuitively? My take is that by initializing momentum to the first provided value, you become biased towards the initial value rather than biased towards $0$. In contrast, biased towards $0$ is remarkably simple, and much more intuitive, to fix. An alternative, equivalent, formula for computing $\hat m_t$, is actually presented by dontloo, but it has some semantic drawbacks. For large $t$, we can see that $1-\beta^t\approx1$, leaving us with $m_t\approx\hat m_t$, whilst with theirs they obtain $m_t\approx\hat m_t/(1-\beta_1)$. This causes $m_t$ to be influenced by the choice of $\beta_1$ as well as lose its meaning as the momentum approximation of $g_t$. Since it's influenced by $\beta_1$, it can no longer be directly compared to $g_t$. Though one could argue you shouldn't worry about the existence of $m_t$ and instead focus on $\hat m_t$, which is the same in both formulations, I would argue that letting $m_t$ be an approximation of $g_t$ is much more of an intuitive buildup than the latter. For some intuition on the momentum formulas, note also the similarity between the following: $$m_t=m_{t-1}+(1-\beta_1)(g_t-m_{t-1})$$ $$a_t=a_{t-1}+\frac1t(g_t-a_{t-1})$$ As it turns out, $a_t$ is the accumulating formula for the actual average of $g_t$. $m_t$ is then an approximation of this, where the newest gradient weighs in slightly more than the previous.
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
An example, with some number crunching, might be intuitive and also help debunk the idea of using the initial gradient instead of $0$. Consider the 1D problem $f(x)=x$, where $f'(x)=1$. $\beta_1=0.9$
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? An example, with some number crunching, might be intuitive and also help debunk the idea of using the initial gradient instead of $0$. Consider the 1D problem $f(x)=x$, where $f'(x)=1$. $\beta_1=0.9$ and $\beta_2=0.999$ as usual. The first few values of $m_t$ and $v_t$ (rounded to 4 places) are given below. \begin{array}{c|c|c|c} t&m_t&v_t&m_t/\sqrt{v_t}\\\hline 0&0&0&\mathrm{N/A}\\ 1&0.1000&0.001000&3.162\\ 2&0.1900&0.001999&4.250\\ 3&0.2710&0.002997&4.950\\ 4&0.3439&0.003994&5.442 \end{array} At $t=12$, we reach a high of $m_t/\sqrt{v_t}=6.568$, and from there it descends to $1$, the "correct" value of $m_t/\sqrt{v_t}$. In other words, with these parameters we may reach step sizes roughly $6.5$ times larger than what they should be, which may be undesirable. We can also see that initially $m_t$ and $v_t$ are very close to $0$. As dontloo shows, $m_t$ and $v_t$ are always going to start out close to the initially used value. As Mark L. Stone comments, What I don't understand is why the gradient at initial point is not used for the initial values of these things, and then the first parameter update. Then there would be no contamination by the initial zero values, which has to be undone. So there'd be no need for the bias correction. Consider, however, the context in which momentum estimates are often used: stochastic/mini-batch gradient descent. It should be expected that the initial (stochastic) gradient is not an accurate estimate of the true gradient. If we truly want an accurate estimate of the gradient, then we need to have nearly equal contributions from the first few gradients. Note then the expanded expressions for their choice of $m_t$, using $m_0=0$. \begin{align} m_1&=0.1g_1\\ m_2&=0.1g_2+0.09g_1\\ m_3&=0.1g_3+0.09g_2+0.081g_1\\ m_4&=0.1g_4+0.09g_3+0.081g_2+0.0729g_1 \end{align} It is apparent that $m_t$ shares nearly the same amount of the previous several $g_t$. Now consider setting $m_1=g_1$. \begin{align} m_1&=g_1\\ m_2&=0.1g_2+0.9g_1\\ m_3&=0.1g_3+0.09g_2+0.81g_1\\ m_4&=0.1g_4+0.09g_3+0.081g_2+0.729g_1 \end{align} As expected, $g_1$ now has a ten-fold influence on $m_t$. One could make the argument that the influence of $g_1$ in $m_t$ is rapidly diminishing, and hence largely irrelevant. But what about $v_t$? Based on our previous example, we should expect a thousand-fold influence. Let's compare $v_t$ and $\bar v_t$, where $v_0=0$ and $\bar v_1=g_1^2$. Doing the math, here's the $\%$ influence of $g_1$ on the $v$'s for several $t$. \begin{array}{c|c|c} t&\%\text{ of $g_1$ in $v_t$}&\%\text{ of $g_1$ in $\bar v_t$}\\\hline 1&100\%&100\%\\ 10&9.96\%&99.1\%\\ 100&0.951\%&90.5\%\\ 200&0.452\%&81.9\%\\ 300&0.286\%&74.1\%\\ 400&0.203\%&67.1\%\\ 500&0.154\%&60.7\%\\ 600&0.122\%&54.9\%\\ 1000&0.0582\%&36.8\%\\ 2000&0.0156\%&13.5\% \end{array} In my humble opinion, this is atrociously bad. Would I rather risk an initially inaccurate estimate of the gradient persisting in my momentum so significantly just to avoid a division by $1-\beta_2^t$? Absolutely not. For the not-so-mathematically inclined, how does their bias correction solve all of these issues? Let's go through it, one-by-one. At $t=12$, we reach a high of $m_t/\sqrt{v_t}=6.568$, and from there it descends to $1$, the "correct" value of $m_t/\sqrt{v_t}$. In other words, with these parameters we may reach step sizes roughly $6.5$ times larger than what they should be, which may be undesirable. The bias correction solves this issue by rescaling $m_t$ and $v_t$ to have roughly the same magnitude as $g_t$ and $g_t^2$. How exactly? It divides the total sum by the sum of the weights of each $g_t$. \begin{align} \hat m_1&=\frac{0.1g_1}{0.1}\\~\\ \hat m_2&=\frac{0.1g_2+0.09g_1}{0.1+0.09}\\~\\ \hat m_3&=\frac{0.1g_3+0.09g_2+0.081g_1}{0.1+0.09+0.081}\\~\\ \hat m_4&=\frac{0.1g_4+0.09g_3+0.081g_2+0.0729g_1}{0.1+0.09+0.081+0.0729} \end{align} It turns out this denominator can more simply be written as $1-\beta_1^t$. It can also be seen from the last table that by initializing $v_0=0$, we get a much more accurate momentum than initializing $v_1=g_1^2$. Indeed using $v_1=g_1^2$ actually introduces another, perhaps concerning, problem. Furthermore, we observe that using the "initial gradient" approach is subject significantly more to the choice of $\beta$. Although $\beta=0.9$ is not so bad, when $\beta=0.999$, it can cause the initial value to persist much longer. What should you understand from all this, intuitively? My take is that by initializing momentum to the first provided value, you become biased towards the initial value rather than biased towards $0$. In contrast, biased towards $0$ is remarkably simple, and much more intuitive, to fix. An alternative, equivalent, formula for computing $\hat m_t$, is actually presented by dontloo, but it has some semantic drawbacks. For large $t$, we can see that $1-\beta^t\approx1$, leaving us with $m_t\approx\hat m_t$, whilst with theirs they obtain $m_t\approx\hat m_t/(1-\beta_1)$. This causes $m_t$ to be influenced by the choice of $\beta_1$ as well as lose its meaning as the momentum approximation of $g_t$. Since it's influenced by $\beta_1$, it can no longer be directly compared to $g_t$. Though one could argue you shouldn't worry about the existence of $m_t$ and instead focus on $\hat m_t$, which is the same in both formulations, I would argue that letting $m_t$ be an approximation of $g_t$ is much more of an intuitive buildup than the latter. For some intuition on the momentum formulas, note also the similarity between the following: $$m_t=m_{t-1}+(1-\beta_1)(g_t-m_{t-1})$$ $$a_t=a_{t-1}+\frac1t(g_t-a_{t-1})$$ As it turns out, $a_t$ is the accumulating formula for the actual average of $g_t$. $m_t$ is then an approximation of this, where the newest gradient weighs in slightly more than the previous.
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? An example, with some number crunching, might be intuitive and also help debunk the idea of using the initial gradient instead of $0$. Consider the 1D problem $f(x)=x$, where $f'(x)=1$. $\beta_1=0.9$
8,271
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
This correction term isn't really about de-biasing the exponentially-weighted moving average filter, it is just that the optimum EWMA filter should have a transient component -- this is well known within signal processing: see, e.g., Sophocles J. Orfanidis, Applied Optimum Signal Processing, ch 6. Consider the following (convex) optimization problem, parameterized by $t$, which attempts to find $\mu(t)$ to minimize the exponentially weighted sum of squared errors: \begin{equation*} \underset{\mu \in \mathbb{R}}{\text{minimize}} \quad \frac{1}{2}\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} \bigl(x(t - \tau) - \mu\bigr)^2. \end{equation*} Differentiating the objective w.r.t. $\mu$ we get the optimum filter: \begin{align*} \sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} x(t - \tau) &= \mu \sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1}\\ \implies \mu(t) &= \frac{\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} x(t - \tau)}{\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1}}\\ \implies \mu(t) &\overset{(a)}= \frac{1 - \lambda}{1 - \lambda^{t}}\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} x(t - \tau), \end{align*} where $(a)$ follows by the formula for finite geometric sums. This is exactly the "de-biased" EWMA filter.
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
This correction term isn't really about de-biasing the exponentially-weighted moving average filter, it is just that the optimum EWMA filter should have a transient component -- this is well known wit
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? This correction term isn't really about de-biasing the exponentially-weighted moving average filter, it is just that the optimum EWMA filter should have a transient component -- this is well known within signal processing: see, e.g., Sophocles J. Orfanidis, Applied Optimum Signal Processing, ch 6. Consider the following (convex) optimization problem, parameterized by $t$, which attempts to find $\mu(t)$ to minimize the exponentially weighted sum of squared errors: \begin{equation*} \underset{\mu \in \mathbb{R}}{\text{minimize}} \quad \frac{1}{2}\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} \bigl(x(t - \tau) - \mu\bigr)^2. \end{equation*} Differentiating the objective w.r.t. $\mu$ we get the optimum filter: \begin{align*} \sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} x(t - \tau) &= \mu \sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1}\\ \implies \mu(t) &= \frac{\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} x(t - \tau)}{\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1}}\\ \implies \mu(t) &\overset{(a)}= \frac{1 - \lambda}{1 - \lambda^{t}}\sum_{\tau = 0}^{t - 1} \lambda^{t - \tau - 1} x(t - \tau), \end{align*} where $(a)$ follows by the formula for finite geometric sums. This is exactly the "de-biased" EWMA filter.
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? This correction term isn't really about de-biasing the exponentially-weighted moving average filter, it is just that the optimum EWMA filter should have a transient component -- this is well known wit
8,272
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
All the above answers are helpful. Why not just visualize the claims? Here is an animation that I created to demonstrate the following statement from the paper lack of initialisation bias correction would lead to initial steps that are much larger. As we can observe, without a bias correction the learning rate becomes too high initially. As a consequence, there is a large overshoot around the minimum.
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning?
All the above answers are helpful. Why not just visualize the claims? Here is an animation that I created to demonstrate the following statement from the paper lack of initialisation bias correction
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? All the above answers are helpful. Why not just visualize the claims? Here is an animation that I created to demonstrate the following statement from the paper lack of initialisation bias correction would lead to initial steps that are much larger. As we can observe, without a bias correction the learning rate becomes too high initially. As a consequence, there is a large overshoot around the minimum.
Why is it important to include a bias correction term for the Adam optimizer for Deep Learning? All the above answers are helpful. Why not just visualize the claims? Here is an animation that I created to demonstrate the following statement from the paper lack of initialisation bias correction
8,273
Difference between standard and spherical k-means algorithms
The question is: What is the difference between classical k-means and spherical k-means? Classic K-means: In classic k-means, we seek to minimize a Euclidean distance between the cluster center and the members of the cluster. The intuition behind this is that the radial distance from the cluster-center to the element location should "have sameness" or "be similar" for all elements of that cluster. The algorithm is: Set number of clusters (aka cluster count) Initialize by randomly assigning points in the space to cluster indices Repeat until converge For each point find the nearest cluster and assign point to cluster For each cluster, find the mean of member points and update center mean Error is norm of distance of clusters Spherical K-means: In spherical k-means, the idea is to set the center of each cluster such that it makes both uniform and minimal the angle between components. The intuition is like looking at stars - the points should have consistent spacing between each other. That spacing is simpler to quantify as "cosine similarity", but it means there are no "milky-way" galaxies forming large bright swathes across the sky of the data. (Yes, I'm trying to speak to grandma in this part of the description.) More technical version: Think about vectors, the things you graph as arrows with orientation, and fixed length. It can be translated anywhere and be the same vector. ref The orientation of the point in the space (its angle from a reference line) can be computed using linear algebra, particularly the dot product. If we move all the data so that their tail is at the same point, we can compare "vectors" by their angle, and group similar ones into a single cluster. For clarity, the lengths of the vectors are scaled, so that they are easier to "eyeball" compare. You could think of it as a constellation. The stars in a single cluster are close to each other in some sense. These are my eyeball considered constellations. The value of the general approach is that it allows us to contrive vectors which otherwise have no geometric dimension, such as in the tf-idf method, where the vectors are word frequencies in documents. Two "and" words added does not equal a "the". Words are non-continuous and non-numeric. They are non-physical in a geometric sense, but we can contrive them geometrically, and then use geometric methods to handle them. Spherical k-means can be used to cluster based on words. So the (2d random, continuous) data was this: $$ \begin{bmatrix} x1&y1&x2&y2&group\\ 0&-0.8&-0.2013&-0.7316&B\\ -0.8&0.1&-0.9524&0.3639&A\\ 0.2&0.3&0.2061&-0.1434&C\\ 0.8&0.1&0.4787&0.153&B\\ -0.7&0.2&-0.7276&0.3825&A\\ 0.9&0.9&0.748&0.6793&C\\ \end{bmatrix} $$ Some points: They project to a unit sphere to account for differences in document length. Let's work through an actual process, and see how (bad) my "eyeballing" was. The procedure is: (implicit in the problem) connect vectors tails at origin project onto unit sphere (to account for differences in document length) use clustering to minimize "cosine dissimilarity" $$ J = \sum_{i} d \left( x_{i},p_{c\left( i \right)} \right) $$ where $$ d \left( x,p \right) = 1- cos \left(x,p\right) = \frac{\langle x,p \rangle}{\left \|x \right \|\left \|p \right \|} $$ (more edits coming soon) Links: http://epub.wu.ac.at/4000/1/paper.pdf http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.111.8125&rep=rep1&type=pdf http://www.cs.gsu.edu/~wkim/index_files/papers/refinehd.pdf https://www.jstatsoft.org/article/view/v050i10 http://www.mathworks.com/matlabcentral/fileexchange/32987-the-spherical-k-means-algorithm https://ocw.mit.edu/courses/sloan-school-of-management/15-097-prediction-machine-learning-and-statistics-spring-2012/projects/MIT15_097S12_proj1.pdf
Difference between standard and spherical k-means algorithms
The question is: What is the difference between classical k-means and spherical k-means? Classic K-means: In classic k-means, we seek to minimize a Euclidean distance between the cluster center and
Difference between standard and spherical k-means algorithms The question is: What is the difference between classical k-means and spherical k-means? Classic K-means: In classic k-means, we seek to minimize a Euclidean distance between the cluster center and the members of the cluster. The intuition behind this is that the radial distance from the cluster-center to the element location should "have sameness" or "be similar" for all elements of that cluster. The algorithm is: Set number of clusters (aka cluster count) Initialize by randomly assigning points in the space to cluster indices Repeat until converge For each point find the nearest cluster and assign point to cluster For each cluster, find the mean of member points and update center mean Error is norm of distance of clusters Spherical K-means: In spherical k-means, the idea is to set the center of each cluster such that it makes both uniform and minimal the angle between components. The intuition is like looking at stars - the points should have consistent spacing between each other. That spacing is simpler to quantify as "cosine similarity", but it means there are no "milky-way" galaxies forming large bright swathes across the sky of the data. (Yes, I'm trying to speak to grandma in this part of the description.) More technical version: Think about vectors, the things you graph as arrows with orientation, and fixed length. It can be translated anywhere and be the same vector. ref The orientation of the point in the space (its angle from a reference line) can be computed using linear algebra, particularly the dot product. If we move all the data so that their tail is at the same point, we can compare "vectors" by their angle, and group similar ones into a single cluster. For clarity, the lengths of the vectors are scaled, so that they are easier to "eyeball" compare. You could think of it as a constellation. The stars in a single cluster are close to each other in some sense. These are my eyeball considered constellations. The value of the general approach is that it allows us to contrive vectors which otherwise have no geometric dimension, such as in the tf-idf method, where the vectors are word frequencies in documents. Two "and" words added does not equal a "the". Words are non-continuous and non-numeric. They are non-physical in a geometric sense, but we can contrive them geometrically, and then use geometric methods to handle them. Spherical k-means can be used to cluster based on words. So the (2d random, continuous) data was this: $$ \begin{bmatrix} x1&y1&x2&y2&group\\ 0&-0.8&-0.2013&-0.7316&B\\ -0.8&0.1&-0.9524&0.3639&A\\ 0.2&0.3&0.2061&-0.1434&C\\ 0.8&0.1&0.4787&0.153&B\\ -0.7&0.2&-0.7276&0.3825&A\\ 0.9&0.9&0.748&0.6793&C\\ \end{bmatrix} $$ Some points: They project to a unit sphere to account for differences in document length. Let's work through an actual process, and see how (bad) my "eyeballing" was. The procedure is: (implicit in the problem) connect vectors tails at origin project onto unit sphere (to account for differences in document length) use clustering to minimize "cosine dissimilarity" $$ J = \sum_{i} d \left( x_{i},p_{c\left( i \right)} \right) $$ where $$ d \left( x,p \right) = 1- cos \left(x,p\right) = \frac{\langle x,p \rangle}{\left \|x \right \|\left \|p \right \|} $$ (more edits coming soon) Links: http://epub.wu.ac.at/4000/1/paper.pdf http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.111.8125&rep=rep1&type=pdf http://www.cs.gsu.edu/~wkim/index_files/papers/refinehd.pdf https://www.jstatsoft.org/article/view/v050i10 http://www.mathworks.com/matlabcentral/fileexchange/32987-the-spherical-k-means-algorithm https://ocw.mit.edu/courses/sloan-school-of-management/15-097-prediction-machine-learning-and-statistics-spring-2012/projects/MIT15_097S12_proj1.pdf
Difference between standard and spherical k-means algorithms The question is: What is the difference between classical k-means and spherical k-means? Classic K-means: In classic k-means, we seek to minimize a Euclidean distance between the cluster center and
8,274
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality?
A very likely reason for 2 variables being correlated is that their changes are linked to a third variable. Other likely reasons are chance (if you test enough non-correlated variables for correlation, some will show correlation), or very complex mechanisms that involve multiple steps. See http://tylervigen.com/ for examples like this: To confidently state causation of A -> B, you need an experiment where you can control variable A and do not influence the other variables. Then you measure if the correlation of A and B still exists if you change your variable. For nearly all practical applications, it is almost not possible to not influence other (often unknown) variables as well, therefore the best we can do is to prove the absence of causation. To be able to state a causal relationship, you start with the hypothesis that 2 variables have a causal relationship, use an experiment to disprove the hypothesis and if you fail, you can state with a degree of certainty that the hypothesis is true. How high your degree of certainty needs to be depends on your field of research. In many fields it's common or necessary to run 2 parts of your experiment in parallel, one where the variable A is changed, and a control group where variable A isn't changed, but the experiment is otherwise exactly the same - e.g. in case of medicine you still stick subjects with a needle or make them swallow pills. If the experiment shows correlation between A and B, but not between A and B' (B of the control group), you can assume causation. There are also other ways to conclude causality, if an experiment is either not possible, or inadvisable for various reasons (morals, ethics, PR, cost, time). One common way is to use deduction. Taking an example from a comment: to prove that smoking causes cancer in humans, we can use an experiment to prove that smoking causes cancer in mice, then prove that there is a correlation between smoking and cancer in humans, and deduce that therefore it's extremely likely that smoking causes cancer in humans - this proof can be strengthened if we also disprove that cancer causes smoking. Another way to conclude causality is the exclusion of other causes of the correlation, leaving the causality as the best remaining explanation of the correlation - this method is not always applicable, because it is sometimes impossible to eliminate all possible causes of the correlation (called "back-door paths" in another answer). In the smoking/cancer example, we could probably use this approach to prove that smoking is responsible for tar in the lungs, because there are not that many possible sources for that. These other ways of "proving" causality are not always ideal from a scientific point of view, because they are not as conclusive as a simpler experiment. The global warming debate is a great example to show how it's a lot easier to dismiss causation that hasn't yet been proven conclusively with a repeatable experiment. For comic relief, here's an example of an experiment that's technically plausible, but not advisable due to non-scientific reasons (morals, ethics, PR, cost):
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho
A very likely reason for 2 variables being correlated is that their changes are linked to a third variable. Other likely reasons are chance (if you test enough non-correlated variables for correlation
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality? A very likely reason for 2 variables being correlated is that their changes are linked to a third variable. Other likely reasons are chance (if you test enough non-correlated variables for correlation, some will show correlation), or very complex mechanisms that involve multiple steps. See http://tylervigen.com/ for examples like this: To confidently state causation of A -> B, you need an experiment where you can control variable A and do not influence the other variables. Then you measure if the correlation of A and B still exists if you change your variable. For nearly all practical applications, it is almost not possible to not influence other (often unknown) variables as well, therefore the best we can do is to prove the absence of causation. To be able to state a causal relationship, you start with the hypothesis that 2 variables have a causal relationship, use an experiment to disprove the hypothesis and if you fail, you can state with a degree of certainty that the hypothesis is true. How high your degree of certainty needs to be depends on your field of research. In many fields it's common or necessary to run 2 parts of your experiment in parallel, one where the variable A is changed, and a control group where variable A isn't changed, but the experiment is otherwise exactly the same - e.g. in case of medicine you still stick subjects with a needle or make them swallow pills. If the experiment shows correlation between A and B, but not between A and B' (B of the control group), you can assume causation. There are also other ways to conclude causality, if an experiment is either not possible, or inadvisable for various reasons (morals, ethics, PR, cost, time). One common way is to use deduction. Taking an example from a comment: to prove that smoking causes cancer in humans, we can use an experiment to prove that smoking causes cancer in mice, then prove that there is a correlation between smoking and cancer in humans, and deduce that therefore it's extremely likely that smoking causes cancer in humans - this proof can be strengthened if we also disprove that cancer causes smoking. Another way to conclude causality is the exclusion of other causes of the correlation, leaving the causality as the best remaining explanation of the correlation - this method is not always applicable, because it is sometimes impossible to eliminate all possible causes of the correlation (called "back-door paths" in another answer). In the smoking/cancer example, we could probably use this approach to prove that smoking is responsible for tar in the lungs, because there are not that many possible sources for that. These other ways of "proving" causality are not always ideal from a scientific point of view, because they are not as conclusive as a simpler experiment. The global warming debate is a great example to show how it's a lot easier to dismiss causation that hasn't yet been proven conclusively with a repeatable experiment. For comic relief, here's an example of an experiment that's technically plausible, but not advisable due to non-scientific reasons (morals, ethics, PR, cost):
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho A very likely reason for 2 variables being correlated is that their changes are linked to a third variable. Other likely reasons are chance (if you test enough non-correlated variables for correlation
8,275
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality?
Regardless of whether the design is experimental or observational, an association between a variable A and an outcome Y reflects a causal relationship between A and Y if there are no open backdoor paths between A and Y. In an experimental design, this is most easily achieved by randomization of exposure or treatment assignment. Barring ideal randomization, the associational treatment effect is an unbiased estimate of the causal treatment effect under the assumptions of exchangeability (treatment assignment is independent of the counter-factual outcomes), positivity, etc... References Hernan, Robins. Causal Inference Pearl. Causal Inference in Statistics: An Overview PS You can google for Causal Inference & the following names (to begin with) for more information on the topic: Judea Pearl, Donald Rubin, Miguil Hernan.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho
Regardless of whether the design is experimental or observational, an association between a variable A and an outcome Y reflects a causal relationship between A and Y if there are no open backdoor pat
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality? Regardless of whether the design is experimental or observational, an association between a variable A and an outcome Y reflects a causal relationship between A and Y if there are no open backdoor paths between A and Y. In an experimental design, this is most easily achieved by randomization of exposure or treatment assignment. Barring ideal randomization, the associational treatment effect is an unbiased estimate of the causal treatment effect under the assumptions of exchangeability (treatment assignment is independent of the counter-factual outcomes), positivity, etc... References Hernan, Robins. Causal Inference Pearl. Causal Inference in Statistics: An Overview PS You can google for Causal Inference & the following names (to begin with) for more information on the topic: Judea Pearl, Donald Rubin, Miguil Hernan.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho Regardless of whether the design is experimental or observational, an association between a variable A and an outcome Y reflects a causal relationship between A and Y if there are no open backdoor pat
8,276
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality?
If A and B are correlated, and after you excluded coincidence, it is most likely that either A causes B, or B causes A, or some possibly unknown cause X causes both A and B. The first step would be to examine a possible mechanism. Could you think of how A could case B, or vice versa, or what kind of other cause X could cause both? (This is assuming that this examination is cheaper than performing an experiment trying to prove a cause). You hopefully end up in a position where an experiment to show causation looks worthwhile. You may proceed if you can't think of a mechanism (A causes B but we have no idea why is a possibility). In that experiment, you need to be able to manipulate the suspected cause at will (for example if the cause is "taking pill A" then some people will get the pill, others won't). Then you take the usual precautions, picking people getting or not getting the pill at random, with neither you nor those tested knowing who got the pill and who didn't. You also try to keep the rest of the experiment equal (giving pill A to people in a nice warm room with sunshine coming through the window while the other group gets a fake pill in a dirty, uncomfortable room just might affect your data). So if you concluded that the only difference is that pill, and the cause for getting or not getting the pill was a random decision that didn't affect anything else, then any correlation can be reasonably declared to be causal.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho
If A and B are correlated, and after you excluded coincidence, it is most likely that either A causes B, or B causes A, or some possibly unknown cause X causes both A and B. The first step would be t
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality? If A and B are correlated, and after you excluded coincidence, it is most likely that either A causes B, or B causes A, or some possibly unknown cause X causes both A and B. The first step would be to examine a possible mechanism. Could you think of how A could case B, or vice versa, or what kind of other cause X could cause both? (This is assuming that this examination is cheaper than performing an experiment trying to prove a cause). You hopefully end up in a position where an experiment to show causation looks worthwhile. You may proceed if you can't think of a mechanism (A causes B but we have no idea why is a possibility). In that experiment, you need to be able to manipulate the suspected cause at will (for example if the cause is "taking pill A" then some people will get the pill, others won't). Then you take the usual precautions, picking people getting or not getting the pill at random, with neither you nor those tested knowing who got the pill and who didn't. You also try to keep the rest of the experiment equal (giving pill A to people in a nice warm room with sunshine coming through the window while the other group gets a fake pill in a dirty, uncomfortable room just might affect your data). So if you concluded that the only difference is that pill, and the cause for getting or not getting the pill was a random decision that didn't affect anything else, then any correlation can be reasonably declared to be causal.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho If A and B are correlated, and after you excluded coincidence, it is most likely that either A causes B, or B causes A, or some possibly unknown cause X causes both A and B. The first step would be t
8,277
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality?
Consider an increase in divorce rate, correlated with an increase in lawyer income. Intuitively it seems obvious these the metrics should be correlated. More couples (demand) file for more divorces, so more lawyers (supply) raise their prices. It seems that an increase in divorce rate causes an increase in lawyer income, because the extra demand from the couples caused the lawyers to raise their prices. Or, is that backwards? What if the lawyers intentionally and independently raised their prices, then spent their new income on divorce advertisements? That also seems like a plausible explanation. This scenario illustrates the arbitrary number of third, explanatory variables that a statistical analysis can exhibit. Consider the following: You cannot measure every datapoint, You want to eliminate every non-explanatory datapoint, You can only justify why to eliminate a datapoint if you measure it. You have a conundrum. You cannot measure every datapoint, if you want to justify ignoring non-explanatory datapoints, you need to measure them. (You can eliminate some datapoints without measuring them, but you need to at least justify them.) No proof of causation can be correct in an unbounded system.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho
Consider an increase in divorce rate, correlated with an increase in lawyer income. Intuitively it seems obvious these the metrics should be correlated. More couples (demand) file for more divorces, s
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality? Consider an increase in divorce rate, correlated with an increase in lawyer income. Intuitively it seems obvious these the metrics should be correlated. More couples (demand) file for more divorces, so more lawyers (supply) raise their prices. It seems that an increase in divorce rate causes an increase in lawyer income, because the extra demand from the couples caused the lawyers to raise their prices. Or, is that backwards? What if the lawyers intentionally and independently raised their prices, then spent their new income on divorce advertisements? That also seems like a plausible explanation. This scenario illustrates the arbitrary number of third, explanatory variables that a statistical analysis can exhibit. Consider the following: You cannot measure every datapoint, You want to eliminate every non-explanatory datapoint, You can only justify why to eliminate a datapoint if you measure it. You have a conundrum. You cannot measure every datapoint, if you want to justify ignoring non-explanatory datapoints, you need to measure them. (You can eliminate some datapoints without measuring them, but you need to at least justify them.) No proof of causation can be correct in an unbounded system.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho Consider an increase in divorce rate, correlated with an increase in lawyer income. Intuitively it seems obvious these the metrics should be correlated. More couples (demand) file for more divorces, s
8,278
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality?
Interventional (experimental) data as described by gnasher and Peter is the most straightforward way to make a good case for a causal relationship. However, only Ash's answer mentions the possibility of deducing a causal relationship via observational data. In addition to the backdoor method that he mentions, the front door method is another way of establishing causality based on observational data and some causal assumptions. These were discovered by Judea Pearl. I tried to summarize and provide a reference to these here.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho
Interventional (experimental) data as described by gnasher and Peter is the most straightforward way to make a good case for a causal relationship. However, only Ash's answer mentions the possibility
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality? Interventional (experimental) data as described by gnasher and Peter is the most straightforward way to make a good case for a causal relationship. However, only Ash's answer mentions the possibility of deducing a causal relationship via observational data. In addition to the backdoor method that he mentions, the front door method is another way of establishing causality based on observational data and some causal assumptions. These were discovered by Judea Pearl. I tried to summarize and provide a reference to these here.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho Interventional (experimental) data as described by gnasher and Peter is the most straightforward way to make a good case for a causal relationship. However, only Ash's answer mentions the possibility
8,279
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality?
To make a causal statement, you need to have both Random Sampling and Random Assignment Random Sampling: each individual has an equal probability to be selected for the study Random Assignment: each individual in the experiment shows a little different trait. So when selecting a treatment and a control group from the above sampled group, an equal number of people with a similar trait should be in both the treatment and the control group. The treatment group is the group in which the medicine is given to people. The control group is the group in which the medicine is not given. You can also define a placebo group where subjects are not given a medicine but are told that they are being given. Finally, if the effects are visible in the treatment group but not in the control group, then we can establish causation.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho
To make a causal statement, you need to have both Random Sampling and Random Assignment Random Sampling: each individual has an equal probability to be selected for the study Random Assignment: each
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, how can I prove the causality? To make a causal statement, you need to have both Random Sampling and Random Assignment Random Sampling: each individual has an equal probability to be selected for the study Random Assignment: each individual in the experiment shows a little different trait. So when selecting a treatment and a control group from the above sampled group, an equal number of people with a similar trait should be in both the treatment and the control group. The treatment group is the group in which the medicine is given to people. The control group is the group in which the medicine is not given. You can also define a placebo group where subjects are not given a medicine but are told that they are being given. Finally, if the effects are visible in the treatment group but not in the control group, then we can establish causation.
If 'correlation doesn't imply causation', then if I find a statistically significant correlation, ho To make a causal statement, you need to have both Random Sampling and Random Assignment Random Sampling: each individual has an equal probability to be selected for the study Random Assignment: each
8,280
"Kernel density estimation" is a convolution of what?
Corresponding to any batch of data $X = (x_1, x_2, \ldots, x_n)$ is its "empirical density function" $$f_X(x) = \frac{1}{n}\sum_{i=1}^{n} \delta(x-x_i).$$ Here, $\delta$ is a "generalized function." Despite that name, it isn't a function at all: it's a new mathematical object that can be used only within integrals. Its defining property is that for any function $g$ of compact support that is continuous in a neighborhood of $0$, $$\int_{\mathbb{R}}\delta(x) g(x) dx = g(0).$$ (Names for $\delta$ include "atomic" or "point" measure and "Dirac delta function." In the following calculation this concept is extended to include functions $g$ which are continuous from one side only.) Justifying this characterization of $f_X$ is the observation that $$\eqalign{ \int_{-\infty}^{x} f_X(y) dy &= \int_{-\infty}^{x} \frac{1}{n}\sum_{i=1}^{n} \delta(y-x_i)dy \\ &= \frac{1}{n}\sum_{i=1}^{n} \int_{-\infty}^{x} \delta(y-x_i)dy \\ &= \frac{1}{n}\sum_{i=1}^{n} \int_{\mathbb{R}} I(y\le x) \delta(y-x_i)dy \\ &= \frac{1}{n}\sum_{i=1}^{n} I(x_i \le x) \\ &= F_X(x) }$$ where $F_X$ is the usual empirical CDF and $I$ is the usual characteristic function (equal to $1$ where its argument is true and $0$ otherwise). (I skip an elementary limiting argument needed to move from functions of compact support to functions defined over $\mathbb{R}$; because $I$ only needs to be defined for values within the range of $X$, which is compact, this is no problem.) The convolution of $f_X(x)$ with any other function $k$ is given, by definition, as $$\eqalign{ (f_X * k)(x) &= \int_{\mathbb{R}} f_X(x - y) k(y) dy \\ &=\int_{\mathbb{R}} \frac{1}{n}\sum_{i=1}^{n} \delta(x-y-x_i) k(y) dy \\ &= \frac{1}{n}\sum_{i=1}^{n}\int_{\mathbb{R}} \delta(x-y-x_i) k(y) dy \\ &=\frac{1}{n}\sum_{i=1}^{n} k(x_i-x). }$$ Letting $k(x) = K_h(-x)$ (which is the same as $K_h(x)$ for symmetric kernels--and most kernels are symmetric) we obtain the claimed result: the Wikipedia formula is a convolution.
"Kernel density estimation" is a convolution of what?
Corresponding to any batch of data $X = (x_1, x_2, \ldots, x_n)$ is its "empirical density function" $$f_X(x) = \frac{1}{n}\sum_{i=1}^{n} \delta(x-x_i).$$ Here, $\delta$ is a "generalized function."
"Kernel density estimation" is a convolution of what? Corresponding to any batch of data $X = (x_1, x_2, \ldots, x_n)$ is its "empirical density function" $$f_X(x) = \frac{1}{n}\sum_{i=1}^{n} \delta(x-x_i).$$ Here, $\delta$ is a "generalized function." Despite that name, it isn't a function at all: it's a new mathematical object that can be used only within integrals. Its defining property is that for any function $g$ of compact support that is continuous in a neighborhood of $0$, $$\int_{\mathbb{R}}\delta(x) g(x) dx = g(0).$$ (Names for $\delta$ include "atomic" or "point" measure and "Dirac delta function." In the following calculation this concept is extended to include functions $g$ which are continuous from one side only.) Justifying this characterization of $f_X$ is the observation that $$\eqalign{ \int_{-\infty}^{x} f_X(y) dy &= \int_{-\infty}^{x} \frac{1}{n}\sum_{i=1}^{n} \delta(y-x_i)dy \\ &= \frac{1}{n}\sum_{i=1}^{n} \int_{-\infty}^{x} \delta(y-x_i)dy \\ &= \frac{1}{n}\sum_{i=1}^{n} \int_{\mathbb{R}} I(y\le x) \delta(y-x_i)dy \\ &= \frac{1}{n}\sum_{i=1}^{n} I(x_i \le x) \\ &= F_X(x) }$$ where $F_X$ is the usual empirical CDF and $I$ is the usual characteristic function (equal to $1$ where its argument is true and $0$ otherwise). (I skip an elementary limiting argument needed to move from functions of compact support to functions defined over $\mathbb{R}$; because $I$ only needs to be defined for values within the range of $X$, which is compact, this is no problem.) The convolution of $f_X(x)$ with any other function $k$ is given, by definition, as $$\eqalign{ (f_X * k)(x) &= \int_{\mathbb{R}} f_X(x - y) k(y) dy \\ &=\int_{\mathbb{R}} \frac{1}{n}\sum_{i=1}^{n} \delta(x-y-x_i) k(y) dy \\ &= \frac{1}{n}\sum_{i=1}^{n}\int_{\mathbb{R}} \delta(x-y-x_i) k(y) dy \\ &=\frac{1}{n}\sum_{i=1}^{n} k(x_i-x). }$$ Letting $k(x) = K_h(-x)$ (which is the same as $K_h(x)$ for symmetric kernels--and most kernels are symmetric) we obtain the claimed result: the Wikipedia formula is a convolution.
"Kernel density estimation" is a convolution of what? Corresponding to any batch of data $X = (x_1, x_2, \ldots, x_n)$ is its "empirical density function" $$f_X(x) = \frac{1}{n}\sum_{i=1}^{n} \delta(x-x_i).$$ Here, $\delta$ is a "generalized function."
8,281
"Kernel density estimation" is a convolution of what?
Another convenient way of understanding this connection is from the modeling perspective. Recall that if $X$ and $Y$ are independent, then the PDF of $X+Y$ are the convolution of the marginal PDFs. In kernel density estimation (KDE), we may think about the problem via the following model $$ X = X' + \varepsilon,$$ where $X'$ has the uniform discrete distribution over the $n$ observed observations $\{x_1, x_2, \ldots, x_n\}$ with density $$ f(x') = \frac{1}{n} \sum_{i=1}^n \delta(x'- x_i),$$ as provided above by whuber and $\varepsilon$ is a continuous noise variable independent of $X'$. Then the density of $X$ is their convolution as given by the KDE formula. Depending on the PDF of $\varepsilon$, different kernel functions can be used, e.g., Gaussian kernel. I believe similar explanations can be made for kernel regression and local linear/polynomial regression, where the focus is more on the mean function. Nevertheless, the mean function is manifested by the density, especially if the Gaussian kernel is used.
"Kernel density estimation" is a convolution of what?
Another convenient way of understanding this connection is from the modeling perspective. Recall that if $X$ and $Y$ are independent, then the PDF of $X+Y$ are the convolution of the marginal PDFs. In
"Kernel density estimation" is a convolution of what? Another convenient way of understanding this connection is from the modeling perspective. Recall that if $X$ and $Y$ are independent, then the PDF of $X+Y$ are the convolution of the marginal PDFs. In kernel density estimation (KDE), we may think about the problem via the following model $$ X = X' + \varepsilon,$$ where $X'$ has the uniform discrete distribution over the $n$ observed observations $\{x_1, x_2, \ldots, x_n\}$ with density $$ f(x') = \frac{1}{n} \sum_{i=1}^n \delta(x'- x_i),$$ as provided above by whuber and $\varepsilon$ is a continuous noise variable independent of $X'$. Then the density of $X$ is their convolution as given by the KDE formula. Depending on the PDF of $\varepsilon$, different kernel functions can be used, e.g., Gaussian kernel. I believe similar explanations can be made for kernel regression and local linear/polynomial regression, where the focus is more on the mean function. Nevertheless, the mean function is manifested by the density, especially if the Gaussian kernel is used.
"Kernel density estimation" is a convolution of what? Another convenient way of understanding this connection is from the modeling perspective. Recall that if $X$ and $Y$ are independent, then the PDF of $X+Y$ are the convolution of the marginal PDFs. In
8,282
What is the difference between confidence intervals and hypothesis testing?
You can use a confidence interval (CI) for hypothesis testing. In the typical case, if the CI for an effect does not span 0 then you can reject the null hypothesis. But a CI can be used for more, whereas reporting whether it has been passed is the limit of the usefulness of a test. The reason you're recommended to use CI instead of just a t-test, for example, is because then you can do more than just test hypotheses. You can make a statement about the range of effects you believe to be likely (the ones in the CI). You can't do that with just a t-test. You can also use it to make statements about the null, which you can't do with a t-test. If the t-test doesn't reject the null then you just say that you can't reject the null, which isn't saying much. But if you have a narrow confidence interval around the null then you can suggest that the null, or a value close to it, is likely the true value and suggest the effect of the treatment, or independent variable, is too small to be meaningful (or that your experiment doesn't have enough power and precision to detect an effect important to you because the CI includes both that effect and 0). Added Later: I really should have said that, while you can use a CI like a test it isn't one. It's an estimate of a range where you think the parameter values lies. You can make test like inferences but you're just so much better off never talking about it that way. Which is better? A) The effect is 0.6, t(29) = 2.8, p < 0.05. This statistically significant effect is... (some discussion ensues about this statistical significance without any mention of or even strong ability to discuss the practical implication of the magnitude of the finding... under a Neyman-Pearson framework the magnitude of the t and p values is pretty much meaningless and all you can discuss is whether the effect is present or isn't found to be present. You can never really talk about there not actually being an effect based on the test.) or B) Using a 95% confidence interval I estimate the effect to be between 0.2 and 1.0. (some discussion ensues talking about the actual effect of interest, whether it's plausible values are ones that have any particular meaning and any use of the word significant for exactly what it's supposed to mean. In addition, the width of the CI can go directly to a discussion of whether this is a strong finding or whether you can only reach a more tentative conclusion) If you took a basic statistics class you might initially gravitate toward A. And there may be some cases where it is a better way to report a result. But for most work B is by far and away superior. A range estimate is not a test.
What is the difference between confidence intervals and hypothesis testing?
You can use a confidence interval (CI) for hypothesis testing. In the typical case, if the CI for an effect does not span 0 then you can reject the null hypothesis. But a CI can be used for more, whe
What is the difference between confidence intervals and hypothesis testing? You can use a confidence interval (CI) for hypothesis testing. In the typical case, if the CI for an effect does not span 0 then you can reject the null hypothesis. But a CI can be used for more, whereas reporting whether it has been passed is the limit of the usefulness of a test. The reason you're recommended to use CI instead of just a t-test, for example, is because then you can do more than just test hypotheses. You can make a statement about the range of effects you believe to be likely (the ones in the CI). You can't do that with just a t-test. You can also use it to make statements about the null, which you can't do with a t-test. If the t-test doesn't reject the null then you just say that you can't reject the null, which isn't saying much. But if you have a narrow confidence interval around the null then you can suggest that the null, or a value close to it, is likely the true value and suggest the effect of the treatment, or independent variable, is too small to be meaningful (or that your experiment doesn't have enough power and precision to detect an effect important to you because the CI includes both that effect and 0). Added Later: I really should have said that, while you can use a CI like a test it isn't one. It's an estimate of a range where you think the parameter values lies. You can make test like inferences but you're just so much better off never talking about it that way. Which is better? A) The effect is 0.6, t(29) = 2.8, p < 0.05. This statistically significant effect is... (some discussion ensues about this statistical significance without any mention of or even strong ability to discuss the practical implication of the magnitude of the finding... under a Neyman-Pearson framework the magnitude of the t and p values is pretty much meaningless and all you can discuss is whether the effect is present or isn't found to be present. You can never really talk about there not actually being an effect based on the test.) or B) Using a 95% confidence interval I estimate the effect to be between 0.2 and 1.0. (some discussion ensues talking about the actual effect of interest, whether it's plausible values are ones that have any particular meaning and any use of the word significant for exactly what it's supposed to mean. In addition, the width of the CI can go directly to a discussion of whether this is a strong finding or whether you can only reach a more tentative conclusion) If you took a basic statistics class you might initially gravitate toward A. And there may be some cases where it is a better way to report a result. But for most work B is by far and away superior. A range estimate is not a test.
What is the difference between confidence intervals and hypothesis testing? You can use a confidence interval (CI) for hypothesis testing. In the typical case, if the CI for an effect does not span 0 then you can reject the null hypothesis. But a CI can be used for more, whe
8,283
What is the difference between confidence intervals and hypothesis testing?
There is an equivalence between hypothesis tests and confidence intervals. (see e.g. http://en.wikipedia.org/wiki/Confidence_interval#Statistical_hypothesis_testing) I'll give a very specific example. Suppose we have sample $x_1, x_2, \ldots, x_n$ from a normal distribution with mean $\mu$ and variance 1, which we'll write as $\mathcal N(\mu,1)$. Suppose we think that $\mu = m$, and we want to test the null-hypothesis $H_0: \mu = m$, at level $0.05.$ So we make a test statistic, which in this case we will take to be the sample average: $v = (x_1 + x_2 + \cdots + x_n ) / n$. Now suppose $A(m)$ is the "acceptance region" for $v$ for this test. That means that $A(m)$ is the set of possible values of $v$ for which the null-hypothesis $\mu=m$ is accepted at level 0.05 (I use "accepted" as a shorthand for "not rejected" -- I am not suggesting that you would conclude the null hypothesis is true.). For this example, we can look at the $\mathcal N(m,1)$ normal distribution and choose any set that has probability at least 0.95 under this distribution. Now, a 95% confidence region for $\mu$ is the set of all $m$ for which $v$ is in $A(m)$. In other words, it is the set of all $m$ for which the null-hypothesis would be accepted for the observed $v$. That's why John says "If the CI for an effect does not span $0$ then you can reject the null hypothesis." (John is referring to the case of testing $\mu = 0$.) A related topic is the p-value. The p-value is the smallest level for a test at which we would reject the null-hypothesis. To tie it in with the discussion of confidence intervals, suppose we get a particular sample average $v$, from which we construct confidence intervals of different sizes. Suppose a 95% confidence interval for $\mu$ does not contain $m$. Then we can reject the null-hypothesis $\mu=m$ at level $0.05.$ Then suppose we grow the confidence interval until it just touches (but doesn't include) the value $m$, and suppose this is a 98% confidence interval. Then the p-value for the hypothesis $\mu=m$ is $0.02$ (which we get from $1-0.98$).
What is the difference between confidence intervals and hypothesis testing?
There is an equivalence between hypothesis tests and confidence intervals. (see e.g. http://en.wikipedia.org/wiki/Confidence_interval#Statistical_hypothesis_testing) I'll give a very specific example
What is the difference between confidence intervals and hypothesis testing? There is an equivalence between hypothesis tests and confidence intervals. (see e.g. http://en.wikipedia.org/wiki/Confidence_interval#Statistical_hypothesis_testing) I'll give a very specific example. Suppose we have sample $x_1, x_2, \ldots, x_n$ from a normal distribution with mean $\mu$ and variance 1, which we'll write as $\mathcal N(\mu,1)$. Suppose we think that $\mu = m$, and we want to test the null-hypothesis $H_0: \mu = m$, at level $0.05.$ So we make a test statistic, which in this case we will take to be the sample average: $v = (x_1 + x_2 + \cdots + x_n ) / n$. Now suppose $A(m)$ is the "acceptance region" for $v$ for this test. That means that $A(m)$ is the set of possible values of $v$ for which the null-hypothesis $\mu=m$ is accepted at level 0.05 (I use "accepted" as a shorthand for "not rejected" -- I am not suggesting that you would conclude the null hypothesis is true.). For this example, we can look at the $\mathcal N(m,1)$ normal distribution and choose any set that has probability at least 0.95 under this distribution. Now, a 95% confidence region for $\mu$ is the set of all $m$ for which $v$ is in $A(m)$. In other words, it is the set of all $m$ for which the null-hypothesis would be accepted for the observed $v$. That's why John says "If the CI for an effect does not span $0$ then you can reject the null hypothesis." (John is referring to the case of testing $\mu = 0$.) A related topic is the p-value. The p-value is the smallest level for a test at which we would reject the null-hypothesis. To tie it in with the discussion of confidence intervals, suppose we get a particular sample average $v$, from which we construct confidence intervals of different sizes. Suppose a 95% confidence interval for $\mu$ does not contain $m$. Then we can reject the null-hypothesis $\mu=m$ at level $0.05.$ Then suppose we grow the confidence interval until it just touches (but doesn't include) the value $m$, and suppose this is a 98% confidence interval. Then the p-value for the hypothesis $\mu=m$ is $0.02$ (which we get from $1-0.98$).
What is the difference between confidence intervals and hypothesis testing? There is an equivalence between hypothesis tests and confidence intervals. (see e.g. http://en.wikipedia.org/wiki/Confidence_interval#Statistical_hypothesis_testing) I'll give a very specific example
8,284
What is the difference between confidence intervals and hypothesis testing?
'Student' argued for confidence intervals on the grounds that they could show which effects were more important as well as which were more significant. For example, if you found two effects where the first had a confidence interval for its financial impact from £5 to £6, while the second had a confidence interval from £200 to £2800. The first is more statistically significant but the second is probably more important.
What is the difference between confidence intervals and hypothesis testing?
'Student' argued for confidence intervals on the grounds that they could show which effects were more important as well as which were more significant. For example, if you found two effects where the
What is the difference between confidence intervals and hypothesis testing? 'Student' argued for confidence intervals on the grounds that they could show which effects were more important as well as which were more significant. For example, if you found two effects where the first had a confidence interval for its financial impact from £5 to £6, while the second had a confidence interval from £200 to £2800. The first is more statistically significant but the second is probably more important.
What is the difference between confidence intervals and hypothesis testing? 'Student' argued for confidence intervals on the grounds that they could show which effects were more important as well as which were more significant. For example, if you found two effects where the
8,285
What math subjects would you suggest to prepare for data mining and machine learning?
The suggestions that @gung made are certainly worth following up. Having done the coursera course, I think your list is a good start. Some comments: linear algebra and matrix algebra are the same thing, so drop the latter. in calculus be sure to include partial differentiation. This is calculus applied to functions of more than one variable (symbolically, if, say, $z$ is a function of $x$ and $y$ then you want $\frac{\partial z}{\partial x}$ rather than $\frac{\rm{d}z}{\rm{d}x}$). Fortunately this isn't difficult. in calculus you don't need anything beyond basic integration (and maybe not even that). This is fortunate because integration is hard. add basic optimization, i.e. finding the maximum or minimum of a function, typically a function of more than one variable. An appreciation of gradient descent at the very least is essential. in terms of difficulty you probably want to be somewhere between the beginning and end of 1st year undergraduate. try to read some basic probability and statistics texts, online or otherwise, but don't worry too much (basic maths is a prerequisite anyway to understanding probability and statistics). If you do some courses such as the one you suggest you'll figure out what you need to learn and where your interests lie. One thing you don't want to do, at least at first, is spend a lot of time learning about hypothesis testing. You would rather want to steer towards understanding basic statistics — random variables, probability distributions (PFDs, CDFs), descriptive statistics — and then try to understand regression. I'd add the book Mathematics for Machine Learning by Marc Peter Deisenroth, published 2020, looks like an excellent foundation, including the above and more.
What math subjects would you suggest to prepare for data mining and machine learning?
The suggestions that @gung made are certainly worth following up. Having done the coursera course, I think your list is a good start. Some comments: linear algebra and matrix algebra are the same thi
What math subjects would you suggest to prepare for data mining and machine learning? The suggestions that @gung made are certainly worth following up. Having done the coursera course, I think your list is a good start. Some comments: linear algebra and matrix algebra are the same thing, so drop the latter. in calculus be sure to include partial differentiation. This is calculus applied to functions of more than one variable (symbolically, if, say, $z$ is a function of $x$ and $y$ then you want $\frac{\partial z}{\partial x}$ rather than $\frac{\rm{d}z}{\rm{d}x}$). Fortunately this isn't difficult. in calculus you don't need anything beyond basic integration (and maybe not even that). This is fortunate because integration is hard. add basic optimization, i.e. finding the maximum or minimum of a function, typically a function of more than one variable. An appreciation of gradient descent at the very least is essential. in terms of difficulty you probably want to be somewhere between the beginning and end of 1st year undergraduate. try to read some basic probability and statistics texts, online or otherwise, but don't worry too much (basic maths is a prerequisite anyway to understanding probability and statistics). If you do some courses such as the one you suggest you'll figure out what you need to learn and where your interests lie. One thing you don't want to do, at least at first, is spend a lot of time learning about hypothesis testing. You would rather want to steer towards understanding basic statistics — random variables, probability distributions (PFDs, CDFs), descriptive statistics — and then try to understand regression. I'd add the book Mathematics for Machine Learning by Marc Peter Deisenroth, published 2020, looks like an excellent foundation, including the above and more.
What math subjects would you suggest to prepare for data mining and machine learning? The suggestions that @gung made are certainly worth following up. Having done the coursera course, I think your list is a good start. Some comments: linear algebra and matrix algebra are the same thi
8,286
What math subjects would you suggest to prepare for data mining and machine learning?
There are a couple of excellent threads on this forum-- including THIS ONE that I have found particularly helpful for me in terms of developing a conceptual outline of the important skills for data science work. As mentioned above, there are many online courses available. For example Coursera now has a Data Science Specialization with a number of courses that would probably cover some of the tools you'd need for your work.
What math subjects would you suggest to prepare for data mining and machine learning?
There are a couple of excellent threads on this forum-- including THIS ONE that I have found particularly helpful for me in terms of developing a conceptual outline of the important skills for data sc
What math subjects would you suggest to prepare for data mining and machine learning? There are a couple of excellent threads on this forum-- including THIS ONE that I have found particularly helpful for me in terms of developing a conceptual outline of the important skills for data science work. As mentioned above, there are many online courses available. For example Coursera now has a Data Science Specialization with a number of courses that would probably cover some of the tools you'd need for your work.
What math subjects would you suggest to prepare for data mining and machine learning? There are a couple of excellent threads on this forum-- including THIS ONE that I have found particularly helpful for me in terms of developing a conceptual outline of the important skills for data sc
8,287
What math subjects would you suggest to prepare for data mining and machine learning?
If you are looking to bulk up on machine learning/data mining I would strongly urge optimization/linear algebra/statistics and probability. Here is a list of books for probability. Hope that helps.
What math subjects would you suggest to prepare for data mining and machine learning?
If you are looking to bulk up on machine learning/data mining I would strongly urge optimization/linear algebra/statistics and probability. Here is a list of books for probability. Hope that helps.
What math subjects would you suggest to prepare for data mining and machine learning? If you are looking to bulk up on machine learning/data mining I would strongly urge optimization/linear algebra/statistics and probability. Here is a list of books for probability. Hope that helps.
What math subjects would you suggest to prepare for data mining and machine learning? If you are looking to bulk up on machine learning/data mining I would strongly urge optimization/linear algebra/statistics and probability. Here is a list of books for probability. Hope that helps.
8,288
What math subjects would you suggest to prepare for data mining and machine learning?
As far as brushing very very basic math skills, i'm using these books: Elements of Mathematics for Economics and Finance. Mavron, Vassilis C., Phillips, Timothy N This books covers essential math skills (addition substraction), to partial differentiation, integration, matrix and determinants, and a small chapter on optimization, and also differential equation. It's targeted to economics and finance, but it's a small book, the sequence of chapters suits my need, and easy read for me. Statistical Analysis: Microsoft Excel 2010. Conrad Carlberg Covers basic statistical analysis, to multiple regression, and analysis of covariance, and it uses excel. Discovering Statistics Using R. Andy Field, Jeremy Miles, Zoë Field. Have not read it yet. It uses R. Elementary Linear Algebra. Ron Larson, David C. Falvo. Matrix Methods: Applied Linear Algebra By Richard Bronson, Gabriel B. Costa. covers elementary linear algebra and matrix calculus Those are the basic math books that i use to relate to data mining / machine learning Hope this helps
What math subjects would you suggest to prepare for data mining and machine learning?
As far as brushing very very basic math skills, i'm using these books: Elements of Mathematics for Economics and Finance. Mavron, Vassilis C., Phillips, Timothy N This books covers essential math skil
What math subjects would you suggest to prepare for data mining and machine learning? As far as brushing very very basic math skills, i'm using these books: Elements of Mathematics for Economics and Finance. Mavron, Vassilis C., Phillips, Timothy N This books covers essential math skills (addition substraction), to partial differentiation, integration, matrix and determinants, and a small chapter on optimization, and also differential equation. It's targeted to economics and finance, but it's a small book, the sequence of chapters suits my need, and easy read for me. Statistical Analysis: Microsoft Excel 2010. Conrad Carlberg Covers basic statistical analysis, to multiple regression, and analysis of covariance, and it uses excel. Discovering Statistics Using R. Andy Field, Jeremy Miles, Zoë Field. Have not read it yet. It uses R. Elementary Linear Algebra. Ron Larson, David C. Falvo. Matrix Methods: Applied Linear Algebra By Richard Bronson, Gabriel B. Costa. covers elementary linear algebra and matrix calculus Those are the basic math books that i use to relate to data mining / machine learning Hope this helps
What math subjects would you suggest to prepare for data mining and machine learning? As far as brushing very very basic math skills, i'm using these books: Elements of Mathematics for Economics and Finance. Mavron, Vassilis C., Phillips, Timothy N This books covers essential math skil
8,289
What math subjects would you suggest to prepare for data mining and machine learning?
There are quite a lot of relevant resources listed (and categorized) here, at the so-called "Open Source Data Science Masters". Specifically for mathematics they list: Linear Algebra & Programming Statistics Differential Equations & Calculus Pretty generic recommendations, although they do list some textbooks that you might find useful.
What math subjects would you suggest to prepare for data mining and machine learning?
There are quite a lot of relevant resources listed (and categorized) here, at the so-called "Open Source Data Science Masters". Specifically for mathematics they list: Linear Algebra & Programming St
What math subjects would you suggest to prepare for data mining and machine learning? There are quite a lot of relevant resources listed (and categorized) here, at the so-called "Open Source Data Science Masters". Specifically for mathematics they list: Linear Algebra & Programming Statistics Differential Equations & Calculus Pretty generic recommendations, although they do list some textbooks that you might find useful.
What math subjects would you suggest to prepare for data mining and machine learning? There are quite a lot of relevant resources listed (and categorized) here, at the so-called "Open Source Data Science Masters". Specifically for mathematics they list: Linear Algebra & Programming St
8,290
What math subjects would you suggest to prepare for data mining and machine learning?
Probability and statistics are essential. Some keywords are hypothesis test, multivariate normal distribution, Bayesian inference (joint probability, conditional probability), mean, variance, covariance, Kullback-Leibler divergence, ... Basic linear algebra is essential for machine learning. Topics that you could learn are Eigen decomposition and singular value decomposition. (Of course you should know how to compute a matrix product.) As TooTone already mentioned: optimization is important. You should know what gradient descent is and maybe have a look at Newton's method, Levenberg-Marquardt, Broyden-Fletcher-Goldfarb-Shanno. Calculus is not that important but it might be useful to know how to compute the partial derivatives of functions (Jacobi matrix, Hesse matrix, ...) and you should know what an integral is.
What math subjects would you suggest to prepare for data mining and machine learning?
Probability and statistics are essential. Some keywords are hypothesis test, multivariate normal distribution, Bayesian inference (joint probability, conditional probability), mean, variance, covarian
What math subjects would you suggest to prepare for data mining and machine learning? Probability and statistics are essential. Some keywords are hypothesis test, multivariate normal distribution, Bayesian inference (joint probability, conditional probability), mean, variance, covariance, Kullback-Leibler divergence, ... Basic linear algebra is essential for machine learning. Topics that you could learn are Eigen decomposition and singular value decomposition. (Of course you should know how to compute a matrix product.) As TooTone already mentioned: optimization is important. You should know what gradient descent is and maybe have a look at Newton's method, Levenberg-Marquardt, Broyden-Fletcher-Goldfarb-Shanno. Calculus is not that important but it might be useful to know how to compute the partial derivatives of functions (Jacobi matrix, Hesse matrix, ...) and you should know what an integral is.
What math subjects would you suggest to prepare for data mining and machine learning? Probability and statistics are essential. Some keywords are hypothesis test, multivariate normal distribution, Bayesian inference (joint probability, conditional probability), mean, variance, covarian
8,291
What math subjects would you suggest to prepare for data mining and machine learning?
Linear Algebra, Stats, Calculus. I think you can learn them in tandem w/ ML - or even after the basics. The starter courses / books do a great job with math primer chapters, and you learn the math essentials while learning ML. I made a podcast episode on the math you need for machine learning, and the resources for learning them: Machine Learning Guide #8
What math subjects would you suggest to prepare for data mining and machine learning?
Linear Algebra, Stats, Calculus. I think you can learn them in tandem w/ ML - or even after the basics. The starter courses / books do a great job with math primer chapters, and you learn the math ess
What math subjects would you suggest to prepare for data mining and machine learning? Linear Algebra, Stats, Calculus. I think you can learn them in tandem w/ ML - or even after the basics. The starter courses / books do a great job with math primer chapters, and you learn the math essentials while learning ML. I made a podcast episode on the math you need for machine learning, and the resources for learning them: Machine Learning Guide #8
What math subjects would you suggest to prepare for data mining and machine learning? Linear Algebra, Stats, Calculus. I think you can learn them in tandem w/ ML - or even after the basics. The starter courses / books do a great job with math primer chapters, and you learn the math ess
8,292
What math subjects would you suggest to prepare for data mining and machine learning?
Before Starting any machine learning course go through following mathematics course. Also don't try to dig in single attempt. Learn basic concepts then again brush-up your mathematics skills and repeat:- Mathematics Topics are as following:- Linear Algebra Probability Basic Calculus Maxima and minima of function
What math subjects would you suggest to prepare for data mining and machine learning?
Before Starting any machine learning course go through following mathematics course. Also don't try to dig in single attempt. Learn basic concepts then again brush-up your mathematics skills and repea
What math subjects would you suggest to prepare for data mining and machine learning? Before Starting any machine learning course go through following mathematics course. Also don't try to dig in single attempt. Learn basic concepts then again brush-up your mathematics skills and repeat:- Mathematics Topics are as following:- Linear Algebra Probability Basic Calculus Maxima and minima of function
What math subjects would you suggest to prepare for data mining and machine learning? Before Starting any machine learning course go through following mathematics course. Also don't try to dig in single attempt. Learn basic concepts then again brush-up your mathematics skills and repea
8,293
Understanding distance correlation computations
Distance covariance/correlation (= Brownian covariance/correlation) is computed in the following steps: Compute matrix of euclidean distances between N cases by variable $X$, and another likewise matrix by variable $Y$. Any of the two quantitative features, $X$ or $Y$, might be multivariate, not just univariate. Perform double centering of each matrix. See how double centering is usually done. However, in our case, when doing it do not square the distances initially and don't divide by $-2$ in the end. Row, column means and overall mean of the elements become zero. Multiply the two resultant matrices elementwise and compute the sum; or equivalently, unwrap the matrices into two column vectors and compute their summed cross-product. Average, dividing by the number of elements, N^2. Take square root. The result is the distance covariance between $X$ and $Y$. Distance variances are the distance covariances of $X$, of $Y$ with own selves, you compute them likewise, points 3-4-5. Distance correlation is obtained from the three numbers analogously how Pearson correlation is obtained from usual covariance and the pair of variances: divide the covariance by the sq. root of the product of two variances. Distance covariance (and correlation) is not the covariance (or correlation) between the distances themselves. It is the covariance (correlation) between the special scalar products (dot products) which the "double centered" matrices are comprised of. In euclidean space, a scalar product is the similarity univocally tied with the corresponding distance. If you have two points (vectors) you may express their closeness as scalar product instead of their distance without losing information. However, to compute a scalar product you have to refer to the origin point of the space (vectors come from the origin). Generally, one could place the origin where he likes, but often and convenient is to place it at the geometric middle of the cloud of the points, the mean. Because the mean belongs to the same space as the one spanned by the cloud the dimensionality would not swell out. Now, the usual double centering of the distance matrix (between the points of a cloud) is the operation of converting the distances to the scalar products while placing the origin at that geometric middle. In doing so the "network" of distances is equivalently replaced by the "burst" of vectors, of specific lengths and pairwise angles, from the origin: [The constellation on my example picture is planar which gives away that the "variable", say it was $X$, having generated it was two-dimensional. When $X$ is a single-column variable all points lie on one line, of course.] Just a bit formally about the double centering operation. Let have n points x p dimensions data $\bf X$ (in the univariate case, p=1). Let $\bf D$ be n x n matrix of euclidean distances between the n points. Let $\bf C$ be $\bf X$ with its columns centered. Then $\mathbf S = \text{double-centered } \mathbf D^2$ is equal to $\bf CC'$, the scalar products between rows after the cloud of points was centered. The principal property of the double centering is that $\frac{1}{2n} \mathbf {\sum D^2} = trace(\mathbf S) = trace(\mathbf {C'C})$, and this sum equals the negated sum of the off-diagonal elements of $\bf S$. Return to distance correlation. What are we doing when we compute distance covariance? We have converted both nets of distances into their corresponding bunches of vectors. And then we compute the covariation (and subsequently the correlation) between the corresponding values of the two bunches: each scalar product value (former distance value) of one configuration is being multiplied by its corresponding one of the other configuration. That can be seen as (as was said in point 3) computing the usual covariance between two variables, after vectorizing the two matrices in those "variables". Thus, we are covariating the two sets of similarities (the scalar products, which are the converted distances). Any sort of covariance is the cross-product of moments: you have to compute those moments, the deviations from the mean, first, - and the double centering was that computation. This is the answer to your question: a covariance needs to be based on moments but distances aren't moments. Additional taking of square root after (point 5) seems logical because in our case the moment was already itself a sort of covariance (a scalar product and a covariance are compeers structurally) and so it came that you a kind of multiplyed covariances twice. Therefore in order to descend back on the level of the values of the original data (and to be able to compute correlation value) one has to take the root afterwards. One important note should finally go. If we were doing double centering its classic way - that is, after squaring the euclidean distances - then we would end up with the distance covariance that is not true distance covariance and is not useful. It will appear degenerated into a quantity exactly related to the usual covariance (and distance correlation will be a function of linear Pearson correlation). What makes distance covariance/correlation unique and capable of measuring not linear association but a generic form of dependency, so that dCov=0 if and only if the variables are independent, - is the lack of squaring the distances when performing the double centering (see point 2). Actually, any power of the distances in the range $(0,2)$ would do, however, the standard form is do it on the power $1$. Why this power and not power $2$ facilitates the coefficient to become the measure of nonlinear interdependency is quite a tricky (for me) mathematical issue bearing of characteristic functions of distributions, and I would like to hear somebody more educated to explain here the mechanics of distance covariance/correlation with possibly simple words (I once attempted, unsuccessfully).
Understanding distance correlation computations
Distance covariance/correlation (= Brownian covariance/correlation) is computed in the following steps: Compute matrix of euclidean distances between N cases by variable $X$, and another likewise mat
Understanding distance correlation computations Distance covariance/correlation (= Brownian covariance/correlation) is computed in the following steps: Compute matrix of euclidean distances between N cases by variable $X$, and another likewise matrix by variable $Y$. Any of the two quantitative features, $X$ or $Y$, might be multivariate, not just univariate. Perform double centering of each matrix. See how double centering is usually done. However, in our case, when doing it do not square the distances initially and don't divide by $-2$ in the end. Row, column means and overall mean of the elements become zero. Multiply the two resultant matrices elementwise and compute the sum; or equivalently, unwrap the matrices into two column vectors and compute their summed cross-product. Average, dividing by the number of elements, N^2. Take square root. The result is the distance covariance between $X$ and $Y$. Distance variances are the distance covariances of $X$, of $Y$ with own selves, you compute them likewise, points 3-4-5. Distance correlation is obtained from the three numbers analogously how Pearson correlation is obtained from usual covariance and the pair of variances: divide the covariance by the sq. root of the product of two variances. Distance covariance (and correlation) is not the covariance (or correlation) between the distances themselves. It is the covariance (correlation) between the special scalar products (dot products) which the "double centered" matrices are comprised of. In euclidean space, a scalar product is the similarity univocally tied with the corresponding distance. If you have two points (vectors) you may express their closeness as scalar product instead of their distance without losing information. However, to compute a scalar product you have to refer to the origin point of the space (vectors come from the origin). Generally, one could place the origin where he likes, but often and convenient is to place it at the geometric middle of the cloud of the points, the mean. Because the mean belongs to the same space as the one spanned by the cloud the dimensionality would not swell out. Now, the usual double centering of the distance matrix (between the points of a cloud) is the operation of converting the distances to the scalar products while placing the origin at that geometric middle. In doing so the "network" of distances is equivalently replaced by the "burst" of vectors, of specific lengths and pairwise angles, from the origin: [The constellation on my example picture is planar which gives away that the "variable", say it was $X$, having generated it was two-dimensional. When $X$ is a single-column variable all points lie on one line, of course.] Just a bit formally about the double centering operation. Let have n points x p dimensions data $\bf X$ (in the univariate case, p=1). Let $\bf D$ be n x n matrix of euclidean distances between the n points. Let $\bf C$ be $\bf X$ with its columns centered. Then $\mathbf S = \text{double-centered } \mathbf D^2$ is equal to $\bf CC'$, the scalar products between rows after the cloud of points was centered. The principal property of the double centering is that $\frac{1}{2n} \mathbf {\sum D^2} = trace(\mathbf S) = trace(\mathbf {C'C})$, and this sum equals the negated sum of the off-diagonal elements of $\bf S$. Return to distance correlation. What are we doing when we compute distance covariance? We have converted both nets of distances into their corresponding bunches of vectors. And then we compute the covariation (and subsequently the correlation) between the corresponding values of the two bunches: each scalar product value (former distance value) of one configuration is being multiplied by its corresponding one of the other configuration. That can be seen as (as was said in point 3) computing the usual covariance between two variables, after vectorizing the two matrices in those "variables". Thus, we are covariating the two sets of similarities (the scalar products, which are the converted distances). Any sort of covariance is the cross-product of moments: you have to compute those moments, the deviations from the mean, first, - and the double centering was that computation. This is the answer to your question: a covariance needs to be based on moments but distances aren't moments. Additional taking of square root after (point 5) seems logical because in our case the moment was already itself a sort of covariance (a scalar product and a covariance are compeers structurally) and so it came that you a kind of multiplyed covariances twice. Therefore in order to descend back on the level of the values of the original data (and to be able to compute correlation value) one has to take the root afterwards. One important note should finally go. If we were doing double centering its classic way - that is, after squaring the euclidean distances - then we would end up with the distance covariance that is not true distance covariance and is not useful. It will appear degenerated into a quantity exactly related to the usual covariance (and distance correlation will be a function of linear Pearson correlation). What makes distance covariance/correlation unique and capable of measuring not linear association but a generic form of dependency, so that dCov=0 if and only if the variables are independent, - is the lack of squaring the distances when performing the double centering (see point 2). Actually, any power of the distances in the range $(0,2)$ would do, however, the standard form is do it on the power $1$. Why this power and not power $2$ facilitates the coefficient to become the measure of nonlinear interdependency is quite a tricky (for me) mathematical issue bearing of characteristic functions of distributions, and I would like to hear somebody more educated to explain here the mechanics of distance covariance/correlation with possibly simple words (I once attempted, unsuccessfully).
Understanding distance correlation computations Distance covariance/correlation (= Brownian covariance/correlation) is computed in the following steps: Compute matrix of euclidean distances between N cases by variable $X$, and another likewise mat
8,294
Understanding distance correlation computations
I think both of your questions are deeply linked. While the original diagonals in the distance matrix are 0, what's used for the covariance (which determines the numerator of the correlation) is the doubly centered values of the distances--which, for a vector with any variation, means that the diagonals will be negative. So let's step through a simple independent case and see if that gives us any intuition as to why the correlation is 0 when the two variables are independent. $(X,Y)= [(0,0),(0,1),(1,0),(1,1)]$ The distance matrix for $X$ and $Y$ are: $a=\left[\begin{array}{cccc} 0&0&1&1\\ 0&0&1&1\\ 1&1&0&0\\ 1&1&0&0\end{array}\right]$ $b=\left[\begin{array}{cccc} 0&1&0&1\\ 1&0&1&0\\ 0&1&0&1\\ 1&0&1&0\end{array}\right]$ The mean of every row and column is 0.5, the grand mean is also 0.5, and so we subtract 0.5 off from everything to get $A$: $A=\left[\begin{array}{rrrr} -.5&-.5&.5&.5\\ -.5&-.5&.5&.5\\ .5&.5&-.5&-.5\\ .5&.5&-.5&-.5\end{array}\right]$ $B=\left[\begin{array}{rrrr} -.5&.5&-.5&.5\\ .5&-.5&.5&-.5\\ -.5&.5&-.5&.5\\ .5&-.5&.5&-.5\end{array}\right]$ Now what happens when we compute the sample distance covariance, which is the average of the element-wise product of the two matrices? We can easily see of the 16 elements, 4 (the diagonal!) are $-.5\cdot-.5=.25$ pairs, 4 are $.5\cdot.5=.25$ pairs, and 8 are $-.5\cdot.5=-.25$ pairs, and so the overall average is $0$, which is what we wanted. That's an example, not a proof that it'll necessarily be the case that if the variables are independent, the distance correlation will be $0$, and that if the distance correlation is 0, then the variables are independent. (The proof of both claims can be found in the 2007 paper that introduced the distance correlation.) I find it intuitive that centering creates this desirable property (that $0$ has special significance). If we had just taken the average of the element-wise product of $a$ and $b$ we would have ended up with $0.25$, and it would have taken some effort to determine that this number corresponded to independence. Using the negative "mean" as the diagonal means that's naturally taken care of. But you may want to think about why double centering has this property: would it also work to do single centering (with either the row, column, or grand mean)? Could we not adjust any real distances and just set the diagonal to the negative of either the row sum, column sum, or grand sum? (As ttnphns points out, by itself this isn't enough, as the power also matters. We can do the same double centering but if we add them in quadrature we'll lose the if and only if property.)
Understanding distance correlation computations
I think both of your questions are deeply linked. While the original diagonals in the distance matrix are 0, what's used for the covariance (which determines the numerator of the correlation) is the d
Understanding distance correlation computations I think both of your questions are deeply linked. While the original diagonals in the distance matrix are 0, what's used for the covariance (which determines the numerator of the correlation) is the doubly centered values of the distances--which, for a vector with any variation, means that the diagonals will be negative. So let's step through a simple independent case and see if that gives us any intuition as to why the correlation is 0 when the two variables are independent. $(X,Y)= [(0,0),(0,1),(1,0),(1,1)]$ The distance matrix for $X$ and $Y$ are: $a=\left[\begin{array}{cccc} 0&0&1&1\\ 0&0&1&1\\ 1&1&0&0\\ 1&1&0&0\end{array}\right]$ $b=\left[\begin{array}{cccc} 0&1&0&1\\ 1&0&1&0\\ 0&1&0&1\\ 1&0&1&0\end{array}\right]$ The mean of every row and column is 0.5, the grand mean is also 0.5, and so we subtract 0.5 off from everything to get $A$: $A=\left[\begin{array}{rrrr} -.5&-.5&.5&.5\\ -.5&-.5&.5&.5\\ .5&.5&-.5&-.5\\ .5&.5&-.5&-.5\end{array}\right]$ $B=\left[\begin{array}{rrrr} -.5&.5&-.5&.5\\ .5&-.5&.5&-.5\\ -.5&.5&-.5&.5\\ .5&-.5&.5&-.5\end{array}\right]$ Now what happens when we compute the sample distance covariance, which is the average of the element-wise product of the two matrices? We can easily see of the 16 elements, 4 (the diagonal!) are $-.5\cdot-.5=.25$ pairs, 4 are $.5\cdot.5=.25$ pairs, and 8 are $-.5\cdot.5=-.25$ pairs, and so the overall average is $0$, which is what we wanted. That's an example, not a proof that it'll necessarily be the case that if the variables are independent, the distance correlation will be $0$, and that if the distance correlation is 0, then the variables are independent. (The proof of both claims can be found in the 2007 paper that introduced the distance correlation.) I find it intuitive that centering creates this desirable property (that $0$ has special significance). If we had just taken the average of the element-wise product of $a$ and $b$ we would have ended up with $0.25$, and it would have taken some effort to determine that this number corresponded to independence. Using the negative "mean" as the diagonal means that's naturally taken care of. But you may want to think about why double centering has this property: would it also work to do single centering (with either the row, column, or grand mean)? Could we not adjust any real distances and just set the diagonal to the negative of either the row sum, column sum, or grand sum? (As ttnphns points out, by itself this isn't enough, as the power also matters. We can do the same double centering but if we add them in quadrature we'll lose the if and only if property.)
Understanding distance correlation computations I think both of your questions are deeply linked. While the original diagonals in the distance matrix are 0, what's used for the covariance (which determines the numerator of the correlation) is the d
8,295
Accommodating entrenched views of p-values
There is indeed an argument to be had not to include the disclaimer. Frankly, I'd find a brief treatise on the nature of p-values in a journal article to be a little off-putting, and for a moment would have to pause and try to figure out if you'd done something particularly...esoteric...to warrant devoting that space to a definitional point. Basically, as a reviewer, I'd call it unnecessary because the reader should already know what a p-value is and does. I might even object to it because making such a note does not actually prevent any of the many crimes of analysis and interpretation that accompany p-values, it merely puts on a cloak of "trust me, I know what I'm doing". It's also a little odd - "I'm going to make a bold stand against p-values, but not so bold I don't report them". When I consider "entrenched views on p-values", I'm much less concerned about something like what you posted above, and much more concerned about reviewers' insistence on statistical significance in order to be published or the focus of the paper (put a star by a finding and suddenly its a Big Deal) or blending statistical significance with the significance of a finding.
Accommodating entrenched views of p-values
There is indeed an argument to be had not to include the disclaimer. Frankly, I'd find a brief treatise on the nature of p-values in a journal article to be a little off-putting, and for a moment woul
Accommodating entrenched views of p-values There is indeed an argument to be had not to include the disclaimer. Frankly, I'd find a brief treatise on the nature of p-values in a journal article to be a little off-putting, and for a moment would have to pause and try to figure out if you'd done something particularly...esoteric...to warrant devoting that space to a definitional point. Basically, as a reviewer, I'd call it unnecessary because the reader should already know what a p-value is and does. I might even object to it because making such a note does not actually prevent any of the many crimes of analysis and interpretation that accompany p-values, it merely puts on a cloak of "trust me, I know what I'm doing". It's also a little odd - "I'm going to make a bold stand against p-values, but not so bold I don't report them". When I consider "entrenched views on p-values", I'm much less concerned about something like what you posted above, and much more concerned about reviewers' insistence on statistical significance in order to be published or the focus of the paper (put a star by a finding and suddenly its a Big Deal) or blending statistical significance with the significance of a finding.
Accommodating entrenched views of p-values There is indeed an argument to be had not to include the disclaimer. Frankly, I'd find a brief treatise on the nature of p-values in a journal article to be a little off-putting, and for a moment woul
8,296
Accommodating entrenched views of p-values
The use of inferential statistics can be justified not only based on a population model, but also based on a randomization model. The latter does not make any assumptions about the way the sample has been obtained. In fact, Fisher was the one that suggested that the randomization model should be the basis for statistical inference (as opposed to Neyman and Pearson). See, for example: Ernst, M. D. (2004). Permutation methods: A basis for exact inference. Statistical Science, 19, 676-685. [link (open access)] Ludbrook, J. & Dudley, H. (1998). Why permutation tests are superior to t and F tests in biomedical research. American Statistician, 52, 127-132. [link (if you have JSTOR access)] I somehow doubt though that the editors or reviewers in question were using this as the reason for calling your disclaimer "confusing".
Accommodating entrenched views of p-values
The use of inferential statistics can be justified not only based on a population model, but also based on a randomization model. The latter does not make any assumptions about the way the sample has
Accommodating entrenched views of p-values The use of inferential statistics can be justified not only based on a population model, but also based on a randomization model. The latter does not make any assumptions about the way the sample has been obtained. In fact, Fisher was the one that suggested that the randomization model should be the basis for statistical inference (as opposed to Neyman and Pearson). See, for example: Ernst, M. D. (2004). Permutation methods: A basis for exact inference. Statistical Science, 19, 676-685. [link (open access)] Ludbrook, J. & Dudley, H. (1998). Why permutation tests are superior to t and F tests in biomedical research. American Statistician, 52, 127-132. [link (if you have JSTOR access)] I somehow doubt though that the editors or reviewers in question were using this as the reason for calling your disclaimer "confusing".
Accommodating entrenched views of p-values The use of inferential statistics can be justified not only based on a population model, but also based on a randomization model. The latter does not make any assumptions about the way the sample has
8,297
Accommodating entrenched views of p-values
I haven't had to do battle with any bad reviewers yet, so I wouldn't claim any knowledge of how to get out of a battle that's already begun. However, if their objections are a mere matter of obstructive ignorance, a little preemptive diversion might do the trick. If $p$ values are in fact necessary to report despite their non-negligible invalidity in a problematic study (a class into which all too many published articles fall), one might downplay them implicitly. Consider focusing your narrative instead—maybe even exclusively—on effect sizes. If your study is sufficiently representative to be usefully informative (this shouldn't necessitate perfectly random sampling, only caution in the generality of interpretations), your effect sizes ought to have broader implications than merely indicating the existence and directions of relationships or differences anyway. Focusing one's discussion on effect sizes can facilitate a deeper understanding of how much the relationships or differences matter in a practical sense, though this still needs to be considered in the context of the subject of study (e.g., one cannot conclude by size alone that an $r = .03$ is necessarily unimportant if it might pertain to a matter of life and death; Rosenthal, Rubin, & Rosnow, 2000). You can do this by discussing results in terms of "weak," "moderate," or "strong" relationships or "small" or "large" differences instead of referring to them as "significant" and "insignificant"; the latter two words shouldn't be necessary whatsoever to make most of the points researchers want to make. If the $p$ values are necessary, let them speak for themselves. Do meta-analysts a favor and just sandwich them in more comprehensive reports of valuable statistics: effect sizes, confidence intervals, and test statistics. Maybe hope for a day when readers and reviewers will ignore $p$ values and demand confidence intervals, so that the $p$ values can be ditched entirely. (Or maybe not! See post-postscript!) Another, potentially complementary option would be to expand on your footnote. Both your descriptions of the problem as reviewers have experienced it, and the presently accepted answer on this page, suggest that not enough information is conveyed to explain your motivation for including the footnote, nor enough to motivate the reader to follow your citation to the reference that you use to explain it so tersely. A single, additional sentence, even a brief quote from your reference, could go a long way toward explaining the value of your footnote and motivating readers to read deeper. Evidently, your footnote as is sooner motivates a simple, negative, dismissive reaction toward your understated attempt to disrupt their complacency about their improper assumptions. Readers might be a little less intellectually lazy if you spoonfeed them one or two of the main points about problems that they probably overlook routinely. Also, for many particular problems with $p$ values, consider citing not just that book, but also a fairly concise journal article that's freely available online presently (e.g., Goodman, 2008, Wagenmakers, 2007). That might help reduce any resistance due to the difficulty of obtaining a book and finding the relevant info within. P.S. Thanks to @rpierce for Wagenmakers (2007) and much of the logic of my answer, and to @FranciscoArceo for Goodman (2008)! See also Francisco's loosely related answer, as well as some other popular posts here on Cross Validated about interpreting $p$ values properly: What is the meaning of p values and t values in statistical tests? Understanding p-value P.P.S. @MichaelLew's counterpoint is also worth considering before tossing the $p$ values out entirely! See Senn (2001) and Lew (2013) for some rare and valuable (but only partial) defenses of $p$. [Edit]: Also, I brought up this question in a new question, "Why are 0.05 < p < 0.95 results called false positives?" In discussing my answer, the OP brought up Hurlbert and Lombardi (2009), which I brought up with my colleagues, one of whom then brought up Nuzzo (2014), a brand new Nature News article that led to even more references (Goodman, 2001, 1992; Gorroochurn, Hodge, Heiman, Durner, & Greenberg, 2007)...I am obviously not keeping up at this point, but Michael is just as clearly not alone in defending the possibility of extracting useful information from exact $p$ values (when they do "strictly apply", at least). References - Goodman, S. N. (1992). A comment on replication, P‐values and evidence. Statistics in Medicine, 11(7), 875–879. - Goodman, S. N. (2001). Of P-values and Bayes: A modest proposal. Epidemiology, 12(3), 295–297. Retrieved from http://swfsc.noaa.gov/uploadedFiles/Divisions/PRD/Programs/ETP_Cetacean_Assessment/Of_P_Values_and_Bayes__A_Modest_Proposal.6.pdf. - Goodman, S. (2008). A dirty dozen: Twelve P-value misconceptions. Seminars in Hematology, 45(3), 135–140. Retrieved from http://xa.yimg.com/kq/groups/18751725/636586767/name/twelve+P+value+misconceptions.pdf. - Gorroochurn, P., Hodge, S. E., Heiman, G. A., Durner, M., & Greenberg, D. A. (2007). Non-replication of association studies: “pseudo-failures” to replicate? Genetics in Medicine, 9(6), 325–331. Retrieved from http://www.nature.com/gim/journal/v9/n6/full/gim200755a.html. - Hurlbert, S. H., & Lombardi, C. M. (2009). Final collapse of the Neyman–Pearson decision theoretic framework and rise of the neoFisherian. Annales Zoologici Fennici, 46(5), 311–349. Retrieved from http://xa.yimg.com/kq/groups/1542294/508917937/name/HurlbertLombardi2009AZF.pdf. - Lew, M. J. (2013). To P or not to P: On the evidential nature of P-values and their place in scientific inference. arXiv:1311.0081 [stat.ME]. Retrieved from http://arxiv.org/abs/1311.0081. - Nuzzo, R. (2014, February 12). Scientific method: Statistical errors. Nature News, 506(7487). Retrieved from http://www.nature.com/news/scientific-method-statistical-errors-1.14700. - Rosenthal, R., Rosnow, R. L., & Rubin, D. B. (2000). Contrasts and effect sizes in behavioral research: A correlational approach. Cambridge University Press. - Senn, S. (2001). Two cheers for P-values? Journal of Epidemiology and Biostatistics, 6(2), 193–204. Retrieved from http://www.phil.vt.edu/dmayo/conference_2010/Senn%20Two%20Cheers%20Paper.pdf. - Wagenmakers, E. J. (2007). A practical solution to the pervasive problems of p values. Psychonomic Bulletin & Review, 14(5), 779–804. Retrieved from http://www.brainlife.org/reprint/2007/Wagenmakers_EJ071000.pdf.
Accommodating entrenched views of p-values
I haven't had to do battle with any bad reviewers yet, so I wouldn't claim any knowledge of how to get out of a battle that's already begun. However, if their objections are a mere matter of obstructi
Accommodating entrenched views of p-values I haven't had to do battle with any bad reviewers yet, so I wouldn't claim any knowledge of how to get out of a battle that's already begun. However, if their objections are a mere matter of obstructive ignorance, a little preemptive diversion might do the trick. If $p$ values are in fact necessary to report despite their non-negligible invalidity in a problematic study (a class into which all too many published articles fall), one might downplay them implicitly. Consider focusing your narrative instead—maybe even exclusively—on effect sizes. If your study is sufficiently representative to be usefully informative (this shouldn't necessitate perfectly random sampling, only caution in the generality of interpretations), your effect sizes ought to have broader implications than merely indicating the existence and directions of relationships or differences anyway. Focusing one's discussion on effect sizes can facilitate a deeper understanding of how much the relationships or differences matter in a practical sense, though this still needs to be considered in the context of the subject of study (e.g., one cannot conclude by size alone that an $r = .03$ is necessarily unimportant if it might pertain to a matter of life and death; Rosenthal, Rubin, & Rosnow, 2000). You can do this by discussing results in terms of "weak," "moderate," or "strong" relationships or "small" or "large" differences instead of referring to them as "significant" and "insignificant"; the latter two words shouldn't be necessary whatsoever to make most of the points researchers want to make. If the $p$ values are necessary, let them speak for themselves. Do meta-analysts a favor and just sandwich them in more comprehensive reports of valuable statistics: effect sizes, confidence intervals, and test statistics. Maybe hope for a day when readers and reviewers will ignore $p$ values and demand confidence intervals, so that the $p$ values can be ditched entirely. (Or maybe not! See post-postscript!) Another, potentially complementary option would be to expand on your footnote. Both your descriptions of the problem as reviewers have experienced it, and the presently accepted answer on this page, suggest that not enough information is conveyed to explain your motivation for including the footnote, nor enough to motivate the reader to follow your citation to the reference that you use to explain it so tersely. A single, additional sentence, even a brief quote from your reference, could go a long way toward explaining the value of your footnote and motivating readers to read deeper. Evidently, your footnote as is sooner motivates a simple, negative, dismissive reaction toward your understated attempt to disrupt their complacency about their improper assumptions. Readers might be a little less intellectually lazy if you spoonfeed them one or two of the main points about problems that they probably overlook routinely. Also, for many particular problems with $p$ values, consider citing not just that book, but also a fairly concise journal article that's freely available online presently (e.g., Goodman, 2008, Wagenmakers, 2007). That might help reduce any resistance due to the difficulty of obtaining a book and finding the relevant info within. P.S. Thanks to @rpierce for Wagenmakers (2007) and much of the logic of my answer, and to @FranciscoArceo for Goodman (2008)! See also Francisco's loosely related answer, as well as some other popular posts here on Cross Validated about interpreting $p$ values properly: What is the meaning of p values and t values in statistical tests? Understanding p-value P.P.S. @MichaelLew's counterpoint is also worth considering before tossing the $p$ values out entirely! See Senn (2001) and Lew (2013) for some rare and valuable (but only partial) defenses of $p$. [Edit]: Also, I brought up this question in a new question, "Why are 0.05 < p < 0.95 results called false positives?" In discussing my answer, the OP brought up Hurlbert and Lombardi (2009), which I brought up with my colleagues, one of whom then brought up Nuzzo (2014), a brand new Nature News article that led to even more references (Goodman, 2001, 1992; Gorroochurn, Hodge, Heiman, Durner, & Greenberg, 2007)...I am obviously not keeping up at this point, but Michael is just as clearly not alone in defending the possibility of extracting useful information from exact $p$ values (when they do "strictly apply", at least). References - Goodman, S. N. (1992). A comment on replication, P‐values and evidence. Statistics in Medicine, 11(7), 875–879. - Goodman, S. N. (2001). Of P-values and Bayes: A modest proposal. Epidemiology, 12(3), 295–297. Retrieved from http://swfsc.noaa.gov/uploadedFiles/Divisions/PRD/Programs/ETP_Cetacean_Assessment/Of_P_Values_and_Bayes__A_Modest_Proposal.6.pdf. - Goodman, S. (2008). A dirty dozen: Twelve P-value misconceptions. Seminars in Hematology, 45(3), 135–140. Retrieved from http://xa.yimg.com/kq/groups/18751725/636586767/name/twelve+P+value+misconceptions.pdf. - Gorroochurn, P., Hodge, S. E., Heiman, G. A., Durner, M., & Greenberg, D. A. (2007). Non-replication of association studies: “pseudo-failures” to replicate? Genetics in Medicine, 9(6), 325–331. Retrieved from http://www.nature.com/gim/journal/v9/n6/full/gim200755a.html. - Hurlbert, S. H., & Lombardi, C. M. (2009). Final collapse of the Neyman–Pearson decision theoretic framework and rise of the neoFisherian. Annales Zoologici Fennici, 46(5), 311–349. Retrieved from http://xa.yimg.com/kq/groups/1542294/508917937/name/HurlbertLombardi2009AZF.pdf. - Lew, M. J. (2013). To P or not to P: On the evidential nature of P-values and their place in scientific inference. arXiv:1311.0081 [stat.ME]. Retrieved from http://arxiv.org/abs/1311.0081. - Nuzzo, R. (2014, February 12). Scientific method: Statistical errors. Nature News, 506(7487). Retrieved from http://www.nature.com/news/scientific-method-statistical-errors-1.14700. - Rosenthal, R., Rosnow, R. L., & Rubin, D. B. (2000). Contrasts and effect sizes in behavioral research: A correlational approach. Cambridge University Press. - Senn, S. (2001). Two cheers for P-values? Journal of Epidemiology and Biostatistics, 6(2), 193–204. Retrieved from http://www.phil.vt.edu/dmayo/conference_2010/Senn%20Two%20Cheers%20Paper.pdf. - Wagenmakers, E. J. (2007). A practical solution to the pervasive problems of p values. Psychonomic Bulletin & Review, 14(5), 779–804. Retrieved from http://www.brainlife.org/reprint/2007/Wagenmakers_EJ071000.pdf.
Accommodating entrenched views of p-values I haven't had to do battle with any bad reviewers yet, so I wouldn't claim any knowledge of how to get out of a battle that's already begun. However, if their objections are a mere matter of obstructi
8,298
What are attention mechanisms exactly?
Attention is a method for aggregating a set of vectors $v_i$ into just one vector, often via a lookup vector $u$. Usually, $v_i$ is either the inputs to the model or the hidden states of previous time-steps, or the hidden states one level down (in the case of stacked LSTMs). The result is often called the context vector $c$, since it contains the context relevant to the current time-step. This additional context vector $c$ is then fed into the RNN/LSTM as well (it can be simply concatenated with the original input). Therefore, the context can be used to help with prediction. The simplest way to do this is to compute probability vector $p = \text{softmax}(V^Tu)$ and $c = \sum_i p_i v_i$ where $V$ is the concatenation of all previous $v_i$. A common lookup vector $u$ is the current hidden state $h_t$. There are many variations on this, and you can make things as complicated as you want. For example, instead using $v_i^T u$ as the logits, one may choose $f(v_i, u)$ instead, where $f$ is an arbitrary neural network. A common attention mechanism for sequence-to-sequence models uses $p = \text{softmax}(q^T \tanh(W_1 v_i + W_2 h_t))$, where $v$ are the hidden states of the encoder, and $h_t$ is the current hidden state of the decoder. $q$ and both $W$s are parameters. Some papers which show off different variations on the attention idea: Pointer Networks use attention to reference inputs in order to solve combinatorial optimization problems. Recurrent Entity Networks maintain separate memory states for different entities (people/objects) while reading text, and update the correct memory state using attention. Transformer models also make extensive use of attention. Their formulation of attention is slightly more general and also involves key vectors $k_i$: the attention weights $p$ are actually computed between the keys and the lookup, and the context is then constructed with the $v_i$. Here is a quick implementation of one form of attention, although I can't guarantee correctness beyond the fact that it passed some simple tests. Basic RNN: def rnn(inputs_split): bias = tf.get_variable('bias', shape = [hidden_dim, 1]) weight_hidden = tf.tile(tf.get_variable('hidden', shape = [1, hidden_dim, hidden_dim]), [batch, 1, 1]) weight_input = tf.tile(tf.get_variable('input', shape = [1, hidden_dim, in_dim]), [batch, 1, 1]) hidden_states = [tf.zeros((batch, hidden_dim, 1), tf.float32)] for i, input in enumerate(inputs_split): input = tf.reshape(input, (batch, in_dim, 1)) last_state = hidden_states[-1] hidden = tf.nn.tanh( tf.matmul(weight_input, input) + tf.matmul(weight_hidden, last_state) + bias ) hidden_states.append(hidden) return hidden_states[-1] With attention, we add only a few lines before the new hidden state is computed: if len(hidden_states) > 1: logits = tf.transpose(tf.reduce_mean(last_state * hidden_states[:-1], axis = [2, 3])) probs = tf.nn.softmax(logits) probs = tf.reshape(probs, (batch, -1, 1, 1)) context = tf.add_n([v * prob for (v, prob) in zip(hidden_states[:-1], tf.unstack(probs, axis = 1))]) else: context = tf.zeros_like(last_state) last_state = tf.concat([last_state, context], axis = 1) hidden = tf.nn.tanh( tf.matmul(weight_input, input) + tf.matmul(weight_hidden, last_state) + bias ) the full code
What are attention mechanisms exactly?
Attention is a method for aggregating a set of vectors $v_i$ into just one vector, often via a lookup vector $u$. Usually, $v_i$ is either the inputs to the model or the hidden states of previous time
What are attention mechanisms exactly? Attention is a method for aggregating a set of vectors $v_i$ into just one vector, often via a lookup vector $u$. Usually, $v_i$ is either the inputs to the model or the hidden states of previous time-steps, or the hidden states one level down (in the case of stacked LSTMs). The result is often called the context vector $c$, since it contains the context relevant to the current time-step. This additional context vector $c$ is then fed into the RNN/LSTM as well (it can be simply concatenated with the original input). Therefore, the context can be used to help with prediction. The simplest way to do this is to compute probability vector $p = \text{softmax}(V^Tu)$ and $c = \sum_i p_i v_i$ where $V$ is the concatenation of all previous $v_i$. A common lookup vector $u$ is the current hidden state $h_t$. There are many variations on this, and you can make things as complicated as you want. For example, instead using $v_i^T u$ as the logits, one may choose $f(v_i, u)$ instead, where $f$ is an arbitrary neural network. A common attention mechanism for sequence-to-sequence models uses $p = \text{softmax}(q^T \tanh(W_1 v_i + W_2 h_t))$, where $v$ are the hidden states of the encoder, and $h_t$ is the current hidden state of the decoder. $q$ and both $W$s are parameters. Some papers which show off different variations on the attention idea: Pointer Networks use attention to reference inputs in order to solve combinatorial optimization problems. Recurrent Entity Networks maintain separate memory states for different entities (people/objects) while reading text, and update the correct memory state using attention. Transformer models also make extensive use of attention. Their formulation of attention is slightly more general and also involves key vectors $k_i$: the attention weights $p$ are actually computed between the keys and the lookup, and the context is then constructed with the $v_i$. Here is a quick implementation of one form of attention, although I can't guarantee correctness beyond the fact that it passed some simple tests. Basic RNN: def rnn(inputs_split): bias = tf.get_variable('bias', shape = [hidden_dim, 1]) weight_hidden = tf.tile(tf.get_variable('hidden', shape = [1, hidden_dim, hidden_dim]), [batch, 1, 1]) weight_input = tf.tile(tf.get_variable('input', shape = [1, hidden_dim, in_dim]), [batch, 1, 1]) hidden_states = [tf.zeros((batch, hidden_dim, 1), tf.float32)] for i, input in enumerate(inputs_split): input = tf.reshape(input, (batch, in_dim, 1)) last_state = hidden_states[-1] hidden = tf.nn.tanh( tf.matmul(weight_input, input) + tf.matmul(weight_hidden, last_state) + bias ) hidden_states.append(hidden) return hidden_states[-1] With attention, we add only a few lines before the new hidden state is computed: if len(hidden_states) > 1: logits = tf.transpose(tf.reduce_mean(last_state * hidden_states[:-1], axis = [2, 3])) probs = tf.nn.softmax(logits) probs = tf.reshape(probs, (batch, -1, 1, 1)) context = tf.add_n([v * prob for (v, prob) in zip(hidden_states[:-1], tf.unstack(probs, axis = 1))]) else: context = tf.zeros_like(last_state) last_state = tf.concat([last_state, context], axis = 1) hidden = tf.nn.tanh( tf.matmul(weight_input, input) + tf.matmul(weight_hidden, last_state) + bias ) the full code
What are attention mechanisms exactly? Attention is a method for aggregating a set of vectors $v_i$ into just one vector, often via a lookup vector $u$. Usually, $v_i$ is either the inputs to the model or the hidden states of previous time
8,299
What does interaction depth mean in GBM?
Both of the previous answers are wrong. Package GBM uses interaction.depth parameter as a number of splits it has to perform on a tree (starting from a single node). As each split increases the total number of nodes by 3 and number of terminal nodes by 2 (node $\to$ {left node, right node, NA node}) the total number of nodes in the tree will be $3*N+1$ and the number of terminal nodes $2*N+1$. This can be verified by having a look at the output of pretty.gbm.tree function. The behaviour is rather misleading, as the user indeed expects the depth to be the depth of the resulting tree. It is not.
What does interaction depth mean in GBM?
Both of the previous answers are wrong. Package GBM uses interaction.depth parameter as a number of splits it has to perform on a tree (starting from a single node). As each split increases the total
What does interaction depth mean in GBM? Both of the previous answers are wrong. Package GBM uses interaction.depth parameter as a number of splits it has to perform on a tree (starting from a single node). As each split increases the total number of nodes by 3 and number of terminal nodes by 2 (node $\to$ {left node, right node, NA node}) the total number of nodes in the tree will be $3*N+1$ and the number of terminal nodes $2*N+1$. This can be verified by having a look at the output of pretty.gbm.tree function. The behaviour is rather misleading, as the user indeed expects the depth to be the depth of the resulting tree. It is not.
What does interaction depth mean in GBM? Both of the previous answers are wrong. Package GBM uses interaction.depth parameter as a number of splits it has to perform on a tree (starting from a single node). As each split increases the total
8,300
What does interaction depth mean in GBM?
I had a question on the interaction depth parameter in gbm in R. This may be a noob question, for which I apologize, but how does the parameter, which I believe denotes the number of terminal nodes in a tree, basically indicate X-way interaction among the predictors? Link between interaction.depth and the number of terminal nodes One as to see interaction.depth as the number of split nodes. An interaction.depth fixed at k will result in nodes with k+1 terminal nodes (omitting the NA nodes), so we have : $$interaction.depth=\#\{Terminal Nodes\}+1 $$ Link between interaction.depth and the interaction order The link between interaction.depth and interaction order is more tedious. Instead of reasoning with the interaction.depth, let's reason with the number of terminal nodes, which we will called J. Example: Let's say you have J=4 terminal nodes (interaction.depth=3) you can either : do the first split on the root, then the second split on the left node of the root and the third split on the right node of the root. The interaction order for this tree will be 2. do the first split on the root, then the second split on the left (respectively right) node of the root, and a third split on this very left (respectively right) node. The interaction order for this tree will be 3. So you cannot know in advance what will be the interaction order between your features in a given tree. However it is possible to upper bound this value. Let P be the interaction order of the features in a given tree. We have : $$P\leq min(J-1,n)$$ with n being the number of observations. For more details see the section 7 of the original article of Friedman.
What does interaction depth mean in GBM?
I had a question on the interaction depth parameter in gbm in R. This may be a noob question, for which I apologize, but how does the parameter, which I believe denotes the number of terminal nodes in
What does interaction depth mean in GBM? I had a question on the interaction depth parameter in gbm in R. This may be a noob question, for which I apologize, but how does the parameter, which I believe denotes the number of terminal nodes in a tree, basically indicate X-way interaction among the predictors? Link between interaction.depth and the number of terminal nodes One as to see interaction.depth as the number of split nodes. An interaction.depth fixed at k will result in nodes with k+1 terminal nodes (omitting the NA nodes), so we have : $$interaction.depth=\#\{Terminal Nodes\}+1 $$ Link between interaction.depth and the interaction order The link between interaction.depth and interaction order is more tedious. Instead of reasoning with the interaction.depth, let's reason with the number of terminal nodes, which we will called J. Example: Let's say you have J=4 terminal nodes (interaction.depth=3) you can either : do the first split on the root, then the second split on the left node of the root and the third split on the right node of the root. The interaction order for this tree will be 2. do the first split on the root, then the second split on the left (respectively right) node of the root, and a third split on this very left (respectively right) node. The interaction order for this tree will be 3. So you cannot know in advance what will be the interaction order between your features in a given tree. However it is possible to upper bound this value. Let P be the interaction order of the features in a given tree. We have : $$P\leq min(J-1,n)$$ with n being the number of observations. For more details see the section 7 of the original article of Friedman.
What does interaction depth mean in GBM? I had a question on the interaction depth parameter in gbm in R. This may be a noob question, for which I apologize, but how does the parameter, which I believe denotes the number of terminal nodes in