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
11,401
How to find local peaks/valleys in a series of data?
using Numpy ser = np.random.randint(-40, 40, 100) # 100 points peak = np.where(np.diff(ser) < 0)[0] or double_difference = np.diff(np.sign(np.diff(ser))) peak = np.where(double_difference == -2)[0] using Pandas ser = pd.Series(np.random.randint(2, 5, 100)) peak_df = ser[(ser.shift(1) < ser) & (ser.shift(-1) < ser)] peak = peak_df.index
How to find local peaks/valleys in a series of data?
using Numpy ser = np.random.randint(-40, 40, 100) # 100 points peak = np.where(np.diff(ser) < 0)[0] or double_difference = np.diff(np.sign(np.diff(ser))) peak = np.where(double_difference == -2)[0]
How to find local peaks/valleys in a series of data? using Numpy ser = np.random.randint(-40, 40, 100) # 100 points peak = np.where(np.diff(ser) < 0)[0] or double_difference = np.diff(np.sign(np.diff(ser))) peak = np.where(double_difference == -2)[0] using Pandas ser = pd.Series(np.random.randint(2, 5, 100)) peak_df = ser[(ser.shift(1) < ser) & (ser.shift(-1) < ser)] peak = peak_df.index
How to find local peaks/valleys in a series of data? using Numpy ser = np.random.randint(-40, 40, 100) # 100 points peak = np.where(np.diff(ser) < 0)[0] or double_difference = np.diff(np.sign(np.diff(ser))) peak = np.where(double_difference == -2)[0]
11,402
How to find local peaks/valleys in a series of data?
I have not enough reputation to comment direcly on stas-g's answer but this is a comment on an issue i found with stas-g's code I have vectors with incomplete data a = c(1.60676107, -1.84154137, -0.03814237, -3.01587711, 6.67004912, NA, NA, -0.94917515) # Looking at the data find_peaks(a, m=3) should return 5 # and find_peaks(-a, m= 3) should return 4 find_peaks(a, m = 3) # returns numeric(0) with the code as is find_peaks(-a, m) # returns an error The error is due to the evaluation of the all condition if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0)) In the first case the term to evaluate by all() returns FALSE before reaching NA and find_peaks(-a) fails because the all() returns NA and if(NA) fails. However adding na.rm = T to all() if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1], na.rm = T)) return(i + 1) else return(numeric(0)) does not solve the issue. find_peaks(-a,m=3) returns 4 but find_peaks(a, m = 3) returns numeric(0) again instead of 5 Padding NA with the last valid value before NA will add a local extremum to the results and find_peaks(a, m= 3) returns 5 and 7 The c++ function by caseyk does return 4 and 5 as we would expect from visual observation
How to find local peaks/valleys in a series of data?
I have not enough reputation to comment direcly on stas-g's answer but this is a comment on an issue i found with stas-g's code I have vectors with incomplete data a = c(1.60676107, -1.84154137, -0.03
How to find local peaks/valleys in a series of data? I have not enough reputation to comment direcly on stas-g's answer but this is a comment on an issue i found with stas-g's code I have vectors with incomplete data a = c(1.60676107, -1.84154137, -0.03814237, -3.01587711, 6.67004912, NA, NA, -0.94917515) # Looking at the data find_peaks(a, m=3) should return 5 # and find_peaks(-a, m= 3) should return 4 find_peaks(a, m = 3) # returns numeric(0) with the code as is find_peaks(-a, m) # returns an error The error is due to the evaluation of the all condition if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1])) return(i + 1) else return(numeric(0)) In the first case the term to evaluate by all() returns FALSE before reaching NA and find_peaks(-a) fails because the all() returns NA and if(NA) fails. However adding na.rm = T to all() if(all(x[c(z : i, (i + 2) : w)] <= x[i + 1], na.rm = T)) return(i + 1) else return(numeric(0)) does not solve the issue. find_peaks(-a,m=3) returns 4 but find_peaks(a, m = 3) returns numeric(0) again instead of 5 Padding NA with the last valid value before NA will add a local extremum to the results and find_peaks(a, m= 3) returns 5 and 7 The c++ function by caseyk does return 4 and 5 as we would expect from visual observation
How to find local peaks/valleys in a series of data? I have not enough reputation to comment direcly on stas-g's answer but this is a comment on an issue i found with stas-g's code I have vectors with incomplete data a = c(1.60676107, -1.84154137, -0.03
11,403
How to find local peaks/valleys in a series of data?
I work with long records of integer wind speeds including NAs. The integer values can have flat plateaus which count as peaks and ledges which don't count. My solution takes only 4.3 seconds to process a 11.5 million element vector on my PC: indx.localpeaks<-function(x) {dw1<-sign(diff(x)) # -1=down, 0=flat, 1=up names(dw1)<-c(1:length(dw1)) # tag names with original index i<-which(dw1==0) # are there flats? if (length(i)>0) dw1<-dw1[-i] # close up flats dw2<-diff(dw1) # second diff, peaks are -2 indx<-as.numeric(names(which(dw2== -2))) # original index of peaks return(indx) } So i<-indx.localpeaks(x) indexes sharp peaks and the back end of any plateau, but the front ends can be obtained by reversing the vector x and the resulting index j<-length(x)+1-rev(indx.localpeaks(rev(x))) To find troughs, negate the x vector k<-indx.localpeaks(-x) In the example below back ends of plateaus are shown by red circles and front ends by blue circles.
How to find local peaks/valleys in a series of data?
I work with long records of integer wind speeds including NAs. The integer values can have flat plateaus which count as peaks and ledges which don't count. My solution takes only 4.3 seconds to proces
How to find local peaks/valleys in a series of data? I work with long records of integer wind speeds including NAs. The integer values can have flat plateaus which count as peaks and ledges which don't count. My solution takes only 4.3 seconds to process a 11.5 million element vector on my PC: indx.localpeaks<-function(x) {dw1<-sign(diff(x)) # -1=down, 0=flat, 1=up names(dw1)<-c(1:length(dw1)) # tag names with original index i<-which(dw1==0) # are there flats? if (length(i)>0) dw1<-dw1[-i] # close up flats dw2<-diff(dw1) # second diff, peaks are -2 indx<-as.numeric(names(which(dw2== -2))) # original index of peaks return(indx) } So i<-indx.localpeaks(x) indexes sharp peaks and the back end of any plateau, but the front ends can be obtained by reversing the vector x and the resulting index j<-length(x)+1-rev(indx.localpeaks(rev(x))) To find troughs, negate the x vector k<-indx.localpeaks(-x) In the example below back ends of plateaus are shown by red circles and front ends by blue circles.
How to find local peaks/valleys in a series of data? I work with long records of integer wind speeds including NAs. The integer values can have flat plateaus which count as peaks and ledges which don't count. My solution takes only 4.3 seconds to proces
11,404
Generate random correlated data between a binary and a continuous variable
@ocram's approach will certainly work. In terms of the dependence properties it's somewhat restrictive though. Another method is to use a copula to derive a joint distribution. You can specify marginal distributions for success and age (if you have existing data this is especially simple) and a copula family. Varying the parameters of the copula will yield different degrees of dependence, and different copula families will give you various dependence relationships (e.g. strong upper tail dependence). A recent overview of doing this in R via the copula package is available here. See also the discussion in that paper for additional packages. You don't necessarily need an entire package though; here's a simple example using a Gaussian copula, marginal success probability 0.6, and gamma distributed ages. Vary r to control the dependence. r = 0.8 # correlation coefficient sigma = matrix(c(1,r,r,1), ncol=2) s = chol(sigma) n = 10000 z = s%*%matrix(rnorm(n*2), nrow=2) u = pnorm(z) age = qgamma(u[1,], 15, 0.5) age_bracket = cut(age, breaks = seq(0,max(age), by=5)) success = u[2,]>0.4 round(prop.table(table(age_bracket, success)),2) plot(density(age[!success]), main="Age by Success", xlab="age") lines(density(age[success]), lty=2) legend('topright', c("Failure", "Success"), lty=c(1,2)) Output: Table: success age_bracket FALSE TRUE (0,5] 0.00 0.00 (5,10] 0.00 0.00 (10,15] 0.03 0.00 (15,20] 0.07 0.03 (20,25] 0.10 0.09 (25,30] 0.07 0.13 (30,35] 0.04 0.14 (35,40] 0.02 0.11 (40,45] 0.01 0.07 (45,50] 0.00 0.04 (50,55] 0.00 0.02 (55,60] 0.00 0.01 (60,65] 0.00 0.00 (65,70] 0.00 0.00 (70,75] 0.00 0.00 (75,80] 0.00 0.00
Generate random correlated data between a binary and a continuous variable
@ocram's approach will certainly work. In terms of the dependence properties it's somewhat restrictive though. Another method is to use a copula to derive a joint distribution. You can specify margin
Generate random correlated data between a binary and a continuous variable @ocram's approach will certainly work. In terms of the dependence properties it's somewhat restrictive though. Another method is to use a copula to derive a joint distribution. You can specify marginal distributions for success and age (if you have existing data this is especially simple) and a copula family. Varying the parameters of the copula will yield different degrees of dependence, and different copula families will give you various dependence relationships (e.g. strong upper tail dependence). A recent overview of doing this in R via the copula package is available here. See also the discussion in that paper for additional packages. You don't necessarily need an entire package though; here's a simple example using a Gaussian copula, marginal success probability 0.6, and gamma distributed ages. Vary r to control the dependence. r = 0.8 # correlation coefficient sigma = matrix(c(1,r,r,1), ncol=2) s = chol(sigma) n = 10000 z = s%*%matrix(rnorm(n*2), nrow=2) u = pnorm(z) age = qgamma(u[1,], 15, 0.5) age_bracket = cut(age, breaks = seq(0,max(age), by=5)) success = u[2,]>0.4 round(prop.table(table(age_bracket, success)),2) plot(density(age[!success]), main="Age by Success", xlab="age") lines(density(age[success]), lty=2) legend('topright', c("Failure", "Success"), lty=c(1,2)) Output: Table: success age_bracket FALSE TRUE (0,5] 0.00 0.00 (5,10] 0.00 0.00 (10,15] 0.03 0.00 (15,20] 0.07 0.03 (20,25] 0.10 0.09 (25,30] 0.07 0.13 (30,35] 0.04 0.14 (35,40] 0.02 0.11 (40,45] 0.01 0.07 (45,50] 0.00 0.04 (50,55] 0.00 0.02 (55,60] 0.00 0.01 (60,65] 0.00 0.00 (65,70] 0.00 0.00 (70,75] 0.00 0.00 (75,80] 0.00 0.00
Generate random correlated data between a binary and a continuous variable @ocram's approach will certainly work. In terms of the dependence properties it's somewhat restrictive though. Another method is to use a copula to derive a joint distribution. You can specify margin
11,405
Generate random correlated data between a binary and a continuous variable
You can simulate the logistic regression model. More precisely, you can first generate values for the age variable (for example using a uniform distribution) and then compute probabilities of success using $$\pi ( x ) = \frac{\exp(\beta_0 + \beta_1 x)}{1 + \exp(\beta_0 + \beta_1 x)}$$ where $\beta_0$ and $\beta_1$ are constant regression coefficients to be specified. In particular, $\beta_1$ controls the magnitude of association between success and age. Having values of $\pi$, you can now generate values for the binary outcome variable using the Bernoulli distribution. Illustrative example in R: n <- 10 beta0 <- -1.6 beta1 <- 0.03 x <- runif(n=n, min=18, max=60) pi_x <- exp(beta0 + beta1 * x) / (1 + exp(beta0 + beta1 * x)) y <- rbinom(n=length(x), size=1, prob=pi_x) data <- data.frame(x, pi_x, y) names(data) <- c("age", "pi", "y") print(data) age pi y 1 44.99389 0.4377784 1 2 38.06071 0.3874180 0 3 48.84682 0.4664019 1 4 24.60762 0.2969694 0 5 39.21008 0.3956323 1 6 24.89943 0.2988003 0 7 51.21295 0.4841025 1 8 43.63633 0.4277811 0 9 33.05582 0.3524413 0 10 30.20088 0.3331497 1
Generate random correlated data between a binary and a continuous variable
You can simulate the logistic regression model. More precisely, you can first generate values for the age variable (for example using a uniform distribution) and then compute probabilities of success
Generate random correlated data between a binary and a continuous variable You can simulate the logistic regression model. More precisely, you can first generate values for the age variable (for example using a uniform distribution) and then compute probabilities of success using $$\pi ( x ) = \frac{\exp(\beta_0 + \beta_1 x)}{1 + \exp(\beta_0 + \beta_1 x)}$$ where $\beta_0$ and $\beta_1$ are constant regression coefficients to be specified. In particular, $\beta_1$ controls the magnitude of association between success and age. Having values of $\pi$, you can now generate values for the binary outcome variable using the Bernoulli distribution. Illustrative example in R: n <- 10 beta0 <- -1.6 beta1 <- 0.03 x <- runif(n=n, min=18, max=60) pi_x <- exp(beta0 + beta1 * x) / (1 + exp(beta0 + beta1 * x)) y <- rbinom(n=length(x), size=1, prob=pi_x) data <- data.frame(x, pi_x, y) names(data) <- c("age", "pi", "y") print(data) age pi y 1 44.99389 0.4377784 1 2 38.06071 0.3874180 0 3 48.84682 0.4664019 1 4 24.60762 0.2969694 0 5 39.21008 0.3956323 1 6 24.89943 0.2988003 0 7 51.21295 0.4841025 1 8 43.63633 0.4277811 0 9 33.05582 0.3524413 0 10 30.20088 0.3331497 1
Generate random correlated data between a binary and a continuous variable You can simulate the logistic regression model. More precisely, you can first generate values for the age variable (for example using a uniform distribution) and then compute probabilities of success
11,406
Generate random correlated data between a binary and a continuous variable
You can first generate the success/failure variable ($X$), and then generate the age ($Y$) with a different distribution depending on the value of $X$. That will give you correlation. To quantify the correlation, the simplest way is to shift $Y$ according to the value of $X$. The amount by which you shift will be a measure of the correlation.
Generate random correlated data between a binary and a continuous variable
You can first generate the success/failure variable ($X$), and then generate the age ($Y$) with a different distribution depending on the value of $X$. That will give you correlation. To quantify the
Generate random correlated data between a binary and a continuous variable You can first generate the success/failure variable ($X$), and then generate the age ($Y$) with a different distribution depending on the value of $X$. That will give you correlation. To quantify the correlation, the simplest way is to shift $Y$ according to the value of $X$. The amount by which you shift will be a measure of the correlation.
Generate random correlated data between a binary and a continuous variable You can first generate the success/failure variable ($X$), and then generate the age ($Y$) with a different distribution depending on the value of $X$. That will give you correlation. To quantify the
11,407
What is a null model in regression and how does it relate to the null hypothesis?
No, I would say "null model" essentially has the same meaning as "null hypothesis": the model if the null hypothesis is true. What this means, in a particular case, of course depends upon the concrete null hypothesis. Your interpretations as "the average value" (you probably want to say "the marginal distribution on response variable") not taking into account any predictors, is one possibility, corresponding to the null hypothesis of an "omnibus test", testing all the parameters (except the intercept) simultaneously. But interest could well focus on a model of the form $$ y_i = \beta_0 + \beta_1^T x_{1i} + \beta_2^T x_{2i} + \epsilon_i $$ where $x_1$ contains the predictors you know are affecting the outcome, so are not wanting to test, while $x_2$ contains the predictors you are testing. So the null hypothesis will be $\beta_2 =0$ and the null model would be $y_i = \beta_0 + \beta_1^T x_{1i} + \epsilon_i$. So it depends.
What is a null model in regression and how does it relate to the null hypothesis?
No, I would say "null model" essentially has the same meaning as "null hypothesis": the model if the null hypothesis is true. What this means, in a particular case, of course depends upon the concr
What is a null model in regression and how does it relate to the null hypothesis? No, I would say "null model" essentially has the same meaning as "null hypothesis": the model if the null hypothesis is true. What this means, in a particular case, of course depends upon the concrete null hypothesis. Your interpretations as "the average value" (you probably want to say "the marginal distribution on response variable") not taking into account any predictors, is one possibility, corresponding to the null hypothesis of an "omnibus test", testing all the parameters (except the intercept) simultaneously. But interest could well focus on a model of the form $$ y_i = \beta_0 + \beta_1^T x_{1i} + \beta_2^T x_{2i} + \epsilon_i $$ where $x_1$ contains the predictors you know are affecting the outcome, so are not wanting to test, while $x_2$ contains the predictors you are testing. So the null hypothesis will be $\beta_2 =0$ and the null model would be $y_i = \beta_0 + \beta_1^T x_{1i} + \epsilon_i$. So it depends.
What is a null model in regression and how does it relate to the null hypothesis? No, I would say "null model" essentially has the same meaning as "null hypothesis": the model if the null hypothesis is true. What this means, in a particular case, of course depends upon the concr
11,408
What is a null model in regression and how does it relate to the null hypothesis?
A null model is related to a null hypothesis. Take the following univariate model: $Y=\alpha+\beta_{1}X + \epsilon$ My null hypothesis would normally be that $\beta_{1}$ is statistically no different from zero. $H_{0}: \beta_{1}=0$ (null hypothesis) $H_{A}: \beta_{1}\neq 0$ (alternative hypothesis) For a univariate linear model, such as the above, if we were to reject the alternative hypothesis then we could drop $\beta_{1}X$ from the linear model and we'd be left with $Y = \alpha + \epsilon$ Which is your Null model and the same as mean of $Y$.
What is a null model in regression and how does it relate to the null hypothesis?
A null model is related to a null hypothesis. Take the following univariate model: $Y=\alpha+\beta_{1}X + \epsilon$ My null hypothesis would normally be that $\beta_{1}$ is statistically no different
What is a null model in regression and how does it relate to the null hypothesis? A null model is related to a null hypothesis. Take the following univariate model: $Y=\alpha+\beta_{1}X + \epsilon$ My null hypothesis would normally be that $\beta_{1}$ is statistically no different from zero. $H_{0}: \beta_{1}=0$ (null hypothesis) $H_{A}: \beta_{1}\neq 0$ (alternative hypothesis) For a univariate linear model, such as the above, if we were to reject the alternative hypothesis then we could drop $\beta_{1}X$ from the linear model and we'd be left with $Y = \alpha + \epsilon$ Which is your Null model and the same as mean of $Y$.
What is a null model in regression and how does it relate to the null hypothesis? A null model is related to a null hypothesis. Take the following univariate model: $Y=\alpha+\beta_{1}X + \epsilon$ My null hypothesis would normally be that $\beta_{1}$ is statistically no different
11,409
What is a null model in regression and how does it relate to the null hypothesis?
In regression, as described partially in the other two answers, the null model is the null hypothesis that all the regression parameters are 0. So you can interpret this as saying that under the null hypothesis, there is no trend and the best estimate/predictor of a new observation is the mean, which is 0 in the case of no intercept.
What is a null model in regression and how does it relate to the null hypothesis?
In regression, as described partially in the other two answers, the null model is the null hypothesis that all the regression parameters are 0. So you can interpret this as saying that under the null
What is a null model in regression and how does it relate to the null hypothesis? In regression, as described partially in the other two answers, the null model is the null hypothesis that all the regression parameters are 0. So you can interpret this as saying that under the null hypothesis, there is no trend and the best estimate/predictor of a new observation is the mean, which is 0 in the case of no intercept.
What is a null model in regression and how does it relate to the null hypothesis? In regression, as described partially in the other two answers, the null model is the null hypothesis that all the regression parameters are 0. So you can interpret this as saying that under the null
11,410
Why is logistic regression particularly prone to overfitting in high dimensions?
The existing answers aren't wrong, but I think the explanation could be a little more intuitive. There are three key ideas here. 1. Asymptotic Predictions In logistic regression we use a linear model to predict $\mu$, the log-odds that $y=1$ $$ \mu = \beta X $$ We then use the logistic/inverse logit function to convert this into a probability $$ P(y=1) = \frac{1}{1 + e^{-\mu}} $$ Importantly, this function never actually reaches values of $0$ or $1$. Instead, $y$ gets closer and closer to $0$ as $\mu$ becomes more negative, and closer to $1$ as it becomes more positive. 2. Perfect Separation Sometimes, you end up with situations where the model wants to predict $y=1$ or $y=0$. This happens when it's possible to draw a straight line through your data so that every $y=1$ on one side of the line, and $0$ on the other. This is called perfect separation. Perfect separation in 1D In 2D When this happens, the model tries to predict as close to $0$ and $1$ as possible, by predicting values of $\mu$ that are as low and high as possible. To do this, it must set the regression weights, $\beta$ as large as possible. Regularisation is a way of counteracting this: the model isn't allowed to set $\beta$ infinitely large, so $\mu$ can't be infinitely high or low, and the predicted $y$ can't get so close to $0$ or $1$. 3. Perfect Separation is more likely with more dimensions As a result, regularisation becomes more important when you have many predictors. To illustrate, here's the previously plotted data again, but without the second predictors. We see that it's no longer possible to draw a straight line that perfectly separates $y=0$ from $y=1$. Code # https://stats.stackexchange.com/questions/469799/why-is-logistic-regression-particularly-prone-to-overfitting library(tidyverse) theme_set(theme_classic(base_size = 20)) # Asymptotes mu = seq(-10, 10, .1) p = 1 / (1 + exp(-mu)) g = ggplot(data.frame(mu, p), aes(mu, p)) + geom_path() + geom_hline(yintercept=c(0, 1), linetype='dotted') + labs(x=expression(mu), y='P(y=1)') g g + coord_cartesian(xlim=c(-10, -9), ylim=c(0, .001)) # Perfect separation x = c(1, 2, 3, 4, 5, 6) y = c(0, 0, 0, 1, 1, 1) df = data.frame(x, y) ggplot(df, aes(x, y)) + geom_hline(yintercept=c(0, 1), linetype='dotted') + geom_smooth(method='glm', method.args=list(family=binomial), se=F) + geom_point(size=5) + geom_vline(xintercept=3.5, color='red', size=2, linetype='dashed') ## In 2D x1 = c(rnorm(100, -2, 1), rnorm(100, 2, 1)) x2 = c(rnorm(100, -2, 1), rnorm(100, 2, 1)) y = ifelse( x1 + x2 > 0, 1, 0) df = data.frame(x1, x2, y) ggplot(df, aes(x1, x2, color=factor(y))) + geom_point() + geom_abline(intercept=1, slope=-1, color='red', linetype='dashed') + scale_color_manual(values=c('blue', 'black')) + coord_equal(xlim=c(-5, 5), ylim=c(-5, 5)) + labs(color='y') ## Same data, but ignoring x2 ggplot(df, aes(x1, y)) + geom_hline(yintercept=c(0, 1), linetype='dotted') + geom_smooth(method='glm', method.args=list(family=binomial), se=T) + geom_point()
Why is logistic regression particularly prone to overfitting in high dimensions?
The existing answers aren't wrong, but I think the explanation could be a little more intuitive. There are three key ideas here. 1. Asymptotic Predictions In logistic regression we use a linear model
Why is logistic regression particularly prone to overfitting in high dimensions? The existing answers aren't wrong, but I think the explanation could be a little more intuitive. There are three key ideas here. 1. Asymptotic Predictions In logistic regression we use a linear model to predict $\mu$, the log-odds that $y=1$ $$ \mu = \beta X $$ We then use the logistic/inverse logit function to convert this into a probability $$ P(y=1) = \frac{1}{1 + e^{-\mu}} $$ Importantly, this function never actually reaches values of $0$ or $1$. Instead, $y$ gets closer and closer to $0$ as $\mu$ becomes more negative, and closer to $1$ as it becomes more positive. 2. Perfect Separation Sometimes, you end up with situations where the model wants to predict $y=1$ or $y=0$. This happens when it's possible to draw a straight line through your data so that every $y=1$ on one side of the line, and $0$ on the other. This is called perfect separation. Perfect separation in 1D In 2D When this happens, the model tries to predict as close to $0$ and $1$ as possible, by predicting values of $\mu$ that are as low and high as possible. To do this, it must set the regression weights, $\beta$ as large as possible. Regularisation is a way of counteracting this: the model isn't allowed to set $\beta$ infinitely large, so $\mu$ can't be infinitely high or low, and the predicted $y$ can't get so close to $0$ or $1$. 3. Perfect Separation is more likely with more dimensions As a result, regularisation becomes more important when you have many predictors. To illustrate, here's the previously plotted data again, but without the second predictors. We see that it's no longer possible to draw a straight line that perfectly separates $y=0$ from $y=1$. Code # https://stats.stackexchange.com/questions/469799/why-is-logistic-regression-particularly-prone-to-overfitting library(tidyverse) theme_set(theme_classic(base_size = 20)) # Asymptotes mu = seq(-10, 10, .1) p = 1 / (1 + exp(-mu)) g = ggplot(data.frame(mu, p), aes(mu, p)) + geom_path() + geom_hline(yintercept=c(0, 1), linetype='dotted') + labs(x=expression(mu), y='P(y=1)') g g + coord_cartesian(xlim=c(-10, -9), ylim=c(0, .001)) # Perfect separation x = c(1, 2, 3, 4, 5, 6) y = c(0, 0, 0, 1, 1, 1) df = data.frame(x, y) ggplot(df, aes(x, y)) + geom_hline(yintercept=c(0, 1), linetype='dotted') + geom_smooth(method='glm', method.args=list(family=binomial), se=F) + geom_point(size=5) + geom_vline(xintercept=3.5, color='red', size=2, linetype='dashed') ## In 2D x1 = c(rnorm(100, -2, 1), rnorm(100, 2, 1)) x2 = c(rnorm(100, -2, 1), rnorm(100, 2, 1)) y = ifelse( x1 + x2 > 0, 1, 0) df = data.frame(x1, x2, y) ggplot(df, aes(x1, x2, color=factor(y))) + geom_point() + geom_abline(intercept=1, slope=-1, color='red', linetype='dashed') + scale_color_manual(values=c('blue', 'black')) + coord_equal(xlim=c(-5, 5), ylim=c(-5, 5)) + labs(color='y') ## Same data, but ignoring x2 ggplot(df, aes(x1, y)) + geom_hline(yintercept=c(0, 1), linetype='dotted') + geom_smooth(method='glm', method.args=list(family=binomial), se=T) + geom_point()
Why is logistic regression particularly prone to overfitting in high dimensions? The existing answers aren't wrong, but I think the explanation could be a little more intuitive. There are three key ideas here. 1. Asymptotic Predictions In logistic regression we use a linear model
11,411
Why is logistic regression particularly prone to overfitting in high dimensions?
The asymptotic nature refers to the logistic curve itself. The optimizer, if not regularized, will enlarge the weights of the logistic regression to put $wx$ as far as possible to the left or right per sample to reduce the loss maximally. Lets assume one feature that provides perfect separation, one can imagine $wx$ getting larger and larger on each iteration. Optimization will fail in this case, that is unless the solution is regularized. $$\frac{1}{1 + e^{wx}}$$ A high dimensional model creates a large hypothesis space for the possible set of parameters. The optimizer will capitalize on that by choosing the solution with the highest weights. Higher weights will reduce the loss, which is the task of the optimizer, steepen the logistic curve, and give a higher conditional likelihood of the data. The model is overconfident, a paraphrase for overfitting in this setting. If there are several parameter configurations that have the same binary performance measure, the optimizer will always choose the configuration with the lowest loss. Due to the asymptotic nature of the logistic curve, the loss function can be reduced beyond the information provided by the binary labels. More pragmatic, regularization, which makes the coefficients smaller, can help to reduce overfitting. A more formal explanation of the relationship between unconstrained weights, regularization and overfitting can be found using Bayesian theory.
Why is logistic regression particularly prone to overfitting in high dimensions?
The asymptotic nature refers to the logistic curve itself. The optimizer, if not regularized, will enlarge the weights of the logistic regression to put $wx$ as far as possible to the left or right pe
Why is logistic regression particularly prone to overfitting in high dimensions? The asymptotic nature refers to the logistic curve itself. The optimizer, if not regularized, will enlarge the weights of the logistic regression to put $wx$ as far as possible to the left or right per sample to reduce the loss maximally. Lets assume one feature that provides perfect separation, one can imagine $wx$ getting larger and larger on each iteration. Optimization will fail in this case, that is unless the solution is regularized. $$\frac{1}{1 + e^{wx}}$$ A high dimensional model creates a large hypothesis space for the possible set of parameters. The optimizer will capitalize on that by choosing the solution with the highest weights. Higher weights will reduce the loss, which is the task of the optimizer, steepen the logistic curve, and give a higher conditional likelihood of the data. The model is overconfident, a paraphrase for overfitting in this setting. If there are several parameter configurations that have the same binary performance measure, the optimizer will always choose the configuration with the lowest loss. Due to the asymptotic nature of the logistic curve, the loss function can be reduced beyond the information provided by the binary labels. More pragmatic, regularization, which makes the coefficients smaller, can help to reduce overfitting. A more formal explanation of the relationship between unconstrained weights, regularization and overfitting can be found using Bayesian theory.
Why is logistic regression particularly prone to overfitting in high dimensions? The asymptotic nature refers to the logistic curve itself. The optimizer, if not regularized, will enlarge the weights of the logistic regression to put $wx$ as far as possible to the left or right pe
11,412
Why is logistic regression particularly prone to overfitting in high dimensions?
This has not to do with that specific log loss function. That loss function is related to binomial/binary regression and not specifically to the logistic regression. With other loss functions you would get the same 'problem'. So what is the case instead? Logistic regression is a special case of this binomial/binary regression and it is the logistic link function that has the asymptotic nature. In addition the 'overfitting' is mostly problematic for cases with perfect separation. Perfect separation and fitting with sigmoid curves If the samples are perfectly separated then the sigmoid shape of the logistic link function can make the fit 'perfect' (zero residuals and overfitted) by increasing the coefficients (to infinity). For instance, in the image below the true model is: $$p(x) = \frac{1}{1 + e^{-2x}}$$ But the data points, which are not equal or close to $p(x)$ but have values 0 or 1, happen to be perfectly separated classes (on one side they are all 0 and on the other side they are all 1), and as a result the fitted values $\hat{p}(x)$ are also fitted equal to 0 and 1 (which the sigmoid function allows by letting $b \to \infty$) $$\hat{p}(x) = \frac{1}{1 + e^{-bx}}$$ An analogous example, with a similar tendency to over fit, would be $y_i = sin(b \cdot x_i) + \epsilon_i$ So this is not so much dependent on the type of loss function (or the error distribution) and it is more about the model prediction being able to approach a perfect fit. In the example with this sin-wave you get the overfitting when you do not limit the frequency, in the case with logistic regression you get the over-fitting when you have perfect separation. Why does regularization work You can solve it with regularization, but you should have some good ways to know/estimate by what extent you wish to regularize. In the high-dimensional case it 'works' because the over-fitting (with features that link only to one or a few points/individuals) requires many parameters to be high in value. This will increase the regularization part of the cost function quickly. The regularization will make your fit tend towards 'using less features'. And that corresponds with your prior knowledge/believe that would be that your model should rely on only a few features, instead of a large collection of many itsy-bitsy tiny bits (which could easily be noise). Example For instance, say you wish to predict the probability to become president of the USA, then you might do well with some generalizing parameters like education, parents, money/wealth, gender, age. However your fitted classification model, if it is not regularized, might give weight to the many unique features from each single observation/president (and potentially reach perfect score/separation in the training set, but is not generalizing) and instead of putting weight on a single parameter like 'age' it might use instead things like 'smokes sigars and likes skinny dipping' (and many of them to account for each single president in the observed set). This fitting with overly many different parameters is reduced by regularization, because you might get a better (regularized) loss when there are less parameters with high values (which means that you make the model prefer the more general parameters). This regularization is actually a 'good thing' to do, even without the case of perfect separation.
Why is logistic regression particularly prone to overfitting in high dimensions?
This has not to do with that specific log loss function. That loss function is related to binomial/binary regression and not specifically to the logistic regression. With other loss functions you woul
Why is logistic regression particularly prone to overfitting in high dimensions? This has not to do with that specific log loss function. That loss function is related to binomial/binary regression and not specifically to the logistic regression. With other loss functions you would get the same 'problem'. So what is the case instead? Logistic regression is a special case of this binomial/binary regression and it is the logistic link function that has the asymptotic nature. In addition the 'overfitting' is mostly problematic for cases with perfect separation. Perfect separation and fitting with sigmoid curves If the samples are perfectly separated then the sigmoid shape of the logistic link function can make the fit 'perfect' (zero residuals and overfitted) by increasing the coefficients (to infinity). For instance, in the image below the true model is: $$p(x) = \frac{1}{1 + e^{-2x}}$$ But the data points, which are not equal or close to $p(x)$ but have values 0 or 1, happen to be perfectly separated classes (on one side they are all 0 and on the other side they are all 1), and as a result the fitted values $\hat{p}(x)$ are also fitted equal to 0 and 1 (which the sigmoid function allows by letting $b \to \infty$) $$\hat{p}(x) = \frac{1}{1 + e^{-bx}}$$ An analogous example, with a similar tendency to over fit, would be $y_i = sin(b \cdot x_i) + \epsilon_i$ So this is not so much dependent on the type of loss function (or the error distribution) and it is more about the model prediction being able to approach a perfect fit. In the example with this sin-wave you get the overfitting when you do not limit the frequency, in the case with logistic regression you get the over-fitting when you have perfect separation. Why does regularization work You can solve it with regularization, but you should have some good ways to know/estimate by what extent you wish to regularize. In the high-dimensional case it 'works' because the over-fitting (with features that link only to one or a few points/individuals) requires many parameters to be high in value. This will increase the regularization part of the cost function quickly. The regularization will make your fit tend towards 'using less features'. And that corresponds with your prior knowledge/believe that would be that your model should rely on only a few features, instead of a large collection of many itsy-bitsy tiny bits (which could easily be noise). Example For instance, say you wish to predict the probability to become president of the USA, then you might do well with some generalizing parameters like education, parents, money/wealth, gender, age. However your fitted classification model, if it is not regularized, might give weight to the many unique features from each single observation/president (and potentially reach perfect score/separation in the training set, but is not generalizing) and instead of putting weight on a single parameter like 'age' it might use instead things like 'smokes sigars and likes skinny dipping' (and many of them to account for each single president in the observed set). This fitting with overly many different parameters is reduced by regularization, because you might get a better (regularized) loss when there are less parameters with high values (which means that you make the model prefer the more general parameters). This regularization is actually a 'good thing' to do, even without the case of perfect separation.
Why is logistic regression particularly prone to overfitting in high dimensions? This has not to do with that specific log loss function. That loss function is related to binomial/binary regression and not specifically to the logistic regression. With other loss functions you woul
11,413
Why is logistic regression particularly prone to overfitting in high dimensions?
It seems to me that the answer is much simpler than what has been described so elegantly with others' answers. Overfitting increases when the sample size decreases. Overfitting is a function of the effective sample size. Overfitting is minimal for a given apparent sample size when Y is continuous, i.e., has highest information content. A binary Y with cell probabilities of 0.5 0.5 has lower information than a continuous variable and results in more overfitting because of the lower effective sample size. Y with probabilities 0.01 0.99 results in worse overfitting because of an even lower effective sample size. The effective sample size is proportional to min(a, b) where a and b are the two cell frequencies in the sample data. For continuous Y the effective and actual sample sizes are the same. This is covered in https://hbiostat.org/rms
Why is logistic regression particularly prone to overfitting in high dimensions?
It seems to me that the answer is much simpler than what has been described so elegantly with others' answers. Overfitting increases when the sample size decreases. Overfitting is a function of the
Why is logistic regression particularly prone to overfitting in high dimensions? It seems to me that the answer is much simpler than what has been described so elegantly with others' answers. Overfitting increases when the sample size decreases. Overfitting is a function of the effective sample size. Overfitting is minimal for a given apparent sample size when Y is continuous, i.e., has highest information content. A binary Y with cell probabilities of 0.5 0.5 has lower information than a continuous variable and results in more overfitting because of the lower effective sample size. Y with probabilities 0.01 0.99 results in worse overfitting because of an even lower effective sample size. The effective sample size is proportional to min(a, b) where a and b are the two cell frequencies in the sample data. For continuous Y the effective and actual sample sizes are the same. This is covered in https://hbiostat.org/rms
Why is logistic regression particularly prone to overfitting in high dimensions? It seems to me that the answer is much simpler than what has been described so elegantly with others' answers. Overfitting increases when the sample size decreases. Overfitting is a function of the
11,414
Why is logistic regression particularly prone to overfitting in high dimensions?
Logistic regression is a convex optimization problem (the likelihood function is concave), and it's known to not have a finite solution when it can fully separate the data, so the loss function can only reach its lowest value asymptomatically as the weights tend to ± infinity. This has the effect of tightening decision boundaries around each data point when the data is separable, asymptotically overfitting on the training set. On a more practical note, logistic regression is often trained with gradient descent. This is a shallow model with a smooth non-zero loss everywhere, so the gradient doesn't vanish easily numerically. Since the optimizer cannot reach an optimal solution via gradient steps with finite step sizes, it can iterate "forever", pushing the weights to increasingly extreme values, in an attempt to reach asymptotically zero loss. In high dimensions this problem is exacerbated because the model will have even more ways to separate the data, so gradient descent is more likely to overfit asymptotically, i.e. if you let it run for long. Note that early stopping is a form of regularization in itself, and that it can take a relatively long time for these models with vanilla gradient descent to overfit.
Why is logistic regression particularly prone to overfitting in high dimensions?
Logistic regression is a convex optimization problem (the likelihood function is concave), and it's known to not have a finite solution when it can fully separate the data, so the loss function can on
Why is logistic regression particularly prone to overfitting in high dimensions? Logistic regression is a convex optimization problem (the likelihood function is concave), and it's known to not have a finite solution when it can fully separate the data, so the loss function can only reach its lowest value asymptomatically as the weights tend to ± infinity. This has the effect of tightening decision boundaries around each data point when the data is separable, asymptotically overfitting on the training set. On a more practical note, logistic regression is often trained with gradient descent. This is a shallow model with a smooth non-zero loss everywhere, so the gradient doesn't vanish easily numerically. Since the optimizer cannot reach an optimal solution via gradient steps with finite step sizes, it can iterate "forever", pushing the weights to increasingly extreme values, in an attempt to reach asymptotically zero loss. In high dimensions this problem is exacerbated because the model will have even more ways to separate the data, so gradient descent is more likely to overfit asymptotically, i.e. if you let it run for long. Note that early stopping is a form of regularization in itself, and that it can take a relatively long time for these models with vanilla gradient descent to overfit.
Why is logistic regression particularly prone to overfitting in high dimensions? Logistic regression is a convex optimization problem (the likelihood function is concave), and it's known to not have a finite solution when it can fully separate the data, so the loss function can on
11,415
Why is logistic regression particularly prone to overfitting in high dimensions?
You give the source’s explanation yourself, where it says in your link: Imagine that you assign a unique id to each example, and map each id to its own feature. If you don't specify a regularization function, the model will become completely overfit. That's because the model would try to drive loss to zero on all examples and never get there, driving the weights for each indicator feature to +infinity or -infinity. This can happen in high dimensional data with feature crosses, when there’s a huge mass of rare crosses that happen only on one example each. And from Logistic Regression for Machine Learning: It’s an S-shaped curve that can take any real-valued number and map it into a value between 0 and 1, but never exactly at those limits. This "never exactly at those limits" is the point, the logistic regression can almost perfectly predict the class, but is never 100 % sure. Thus the weights can grow almost infinitely as soon as the classes are hit in the vast majority of cases, which can happen if you allow for higher dimensions with a huge mass of rare feature crosses. Part 1: paper on rare feature crosses Alert: I am not sure about Part 1, this is already edited a lot and it is still vague and might be wrong! Main point of change: an unconstrained MLE is for rare feature crosses, and the constrained MLE is the usual case in low dimensionality, meaning much more observations than features. I rather recommend part 2 as the main answer. Part 1 was merged with Part 2, it has been a separate answer before. I assume that the paper "The Impact of Regularization on High-dimensional Logistic Regression" which also uses this outstanding term "rare feature crosses" answers the question here. This would also be in line with the highly voted comment of @DemetriPananos: The question is probably about ... ... complete or quasi-complete separation. High dimensional space is weird, and there may exist some affine plane which perfectly or almost perfectly separates the 1s from the 0s. In such a case, the coefficients of the model are very large and the model will predict probability near 0 or 1 for each case respectively. Back to the paper, at best, read the abstract of the paper yourself. I just try to show the core of it here, and I am not a professional, perhaps someone can correct me in the following conclusions (with some luck, I got it right, though): The problem arises from models where the number of observations and parameters are comparable“ so that “the maximum likelihood estimator is biased. In the high-dimensional regime the underlying parameter vector is often structured (sparse, block-sparse, finite-alphabet, etc.). Which is nothing but the mass of rare feature crosses meant in your source’s explanation. Further: An advantage of RLR is that it allows parameter recovery even for instances where the (unconstrained) maximum likelihood estimate does not exist. I can only assume now that this (unconstrained) MLE does arise from a rare feature cross, with the problem of those observations that are not a rare feature cross and thus need to be "recovered" as parameters because they are dominated by the high weights that the rare feature crosses receive. In other words: in the usual case and in small dimensionality, a constrained MLE exists for each observation, it is calculated over a given number of observations that face a smaller number of features - thus it needs to be calculated by using constraints. With higher dimensionality, rare feature crosses arise where an unconstrained MLE exists, because parameters and observations become 1:1 cases then: one unique feature (~ parameter) = one isolated class assignment (~ observation). In these cases, those observations that are not mapped to just one feature lose their impact and need to be recovered by regularisation. #### An example from the universe: Think of a case where you can explain say that something is a planet or not from the planetary circles around the sun and you use three features for this (in this example, they are all classified as planets except for the sun). Then you add a dimension by making the earth the center instead. This means you do not need more "new" features, instead you just need a higher dimensionality of the same features that are used in the sun model to explain the circles - and that is the same as adding new features, just by using more dimensions of the original features. More details: You might just take three features to prove that all are planets around the sun as a binary problem: planet yes or no, as long as a function can explain the planetary circlre using just the three features. As a next step, you can take whatever dimensionality you want of those three features to improve your model around the earth instead. And adding those higher dimensionalities is the same as adding entirely new features. Then, those functions which perfectly explain a planet by an isolated multidimensional feature (a feature that never explains any other planet) can get very high weights in the model, while those planets that are not that isolated from each other in their functions, because their parabolic functions are rather similar, cannot have infinite weights because there will be a part of the planet circles that gets explained worse when improving the explanation of the other part to 100 %. Now if you go to a very sparse area adding more and more dimensionality, you will get to a model where finally all planets can be marked as planets according to some isolated features that are not used for the other planets' functions. These are the rare feature crosses, there is no interception anymore with any other features. Such features only explain one single planet with its planet function. And thus those high-dimensional features can get infinite weights. #### What is the final idea here to answer the question at all? I assume that the logistic regression which never reaches probability 1 or 0 leads to the infinite weights of the rare feature crosses which causes the model to overfit on the rare feature crosses. This is about a multi-layer design. In low dimensions, that is, if the polynomial degrees of the input are still low, the model with sigmoid activation is simple and saturation leading to overfitting is not the problem, but vanishing gradients (derivative is 0.25, take a couple of layers of backpropagation, and the weights are low) leading to underfitting. The particular problem of overfitting due to the sigmoid activation is for polynomial inputs in high dimensions which can cause these rare feature crosses in high dimensions that describe the training set perfectly but might not generalise to the testing set. The sigmoid curve of the logistic function causes underfitting in low dimensions and overfitting in high dimensions. We cannot repair the MLEs because they depend on the number of features and obervations, and we cannot just change the number of features or observations. Instead, we can reduce the weights of the rare feature crosses to recover the parameters that are no rare feature crosses. Which gives us the next conclusion: When the „number of observations and parameters are comparable“, so that you have a mass of rare feature crosses in great sparsity, you lose the ordering function of the MLEs for the rest that is not in this "mass". End of the abstract: ... and so in this paper we study regularized logistic regression (RLR), where a convex regularizer that encourages the desired structure is added to the negative of the log-likelihood function.” meaning a well-calibrated regularizer can solve the whole issue of the so much needed constraints by using a convex cost function of the weights (L1 and L2 are both tested) as part of the loss. Part 2: Intuition of rare feature crosses in maths and graphs Repeating the quote of your link at the beginning of this answer: This can happen in high dimensional data with feature crosses, when there’s a huge mass of rare crosses that happen only on one example each. The rare feature crosses can already be understood in a 2-dimensional graph with 2 classes (mathematically, a logistic regression is always for 2 classes, though it can be used to predict multiple classes with the One-vs-All method) that are scattered in slightly overlapping clouds of observations, see the middle row "Classification illustration" (and then after this example, think of the mass of rare feature crosses in 3dim "Classification illustration" in a sparse area): Source: https://stanford.edu/~shervine/teaching/cs-229/cheatsheet-machine-learning-tips-and-tricks The borderline between the two classes in the x1/x2 "Classification illustration" example shows the constant likelihood value y = 0.5 to be class 1 or 0. In this "Classification illustration", with every added dimension (not of new variables, but of the same explanatory variable to the power of 2, 3, 4 aso.) the borderline of the observations‘ classes gets more flexible. It is like adding new "explanation power", until you find all the dimensions you need to explain all labels. "Classification illustration", middle graph, (dim 2): When adding 1 dimension means to introduce x1^2 and / or x2^2, the graph has 2 features and 1 or 2 calculated "artificial" features, though there are just 2 original features. "Classification illustration", right graph, (e.g. dim 9): In very high dimensionality, the 2 classes can be assigned so well that perfect separation can be reached. Two different classes can be spread in quite some chaos, you might perfectly separate them when you go up to the power of 9, meaning to have 9 different x1 and / or x2 variables to assign the classes correctly. #### Deep Learning side-note START In the Deep Learning example (bottom row), the logistic regression is used as the activation function. Please note that this has to be kept apart from the classification example which is the better example to answer the question. The logistic regression is a sigmoid function. A wide variety of sigmoid functions including the logistic and hyperbolic tangent functions have been used as the activation function of artificial neurons (https://en.wikipedia.org/wiki/Sigmoid_function). They are used in order to enable nonlinear mapping of the output, so that large numbers do not change so much the activation value anymore, and this because of the asymptotical nature of the curve. The problem is still the same, since every single neuron can be seen as an isolated fitting problem that can also overfit for the same reasons as it is happening in the 2-D-classification example. Once the neuron knows that "it is right", it will allow to increase the probability = activation value to almost g(z) = 1 by admitting the weights to grow infinitely. From: https://stanford.edu/~shervine/teaching/cs-229/cheatsheet-deep-learning Mind that this Deep Learning paragraph should better be ignored in the direct answer of the question. It is not intuitive and just confusing to the reader since the actual problem of overfitting in neural networks is rather a problem of capacity, not of the activation function. A higher capacity leads to overfitting as well as the asymptotical nature of the logistic regression in higher dimensionality of the "Classification illustration". Better keep "Regression illustration" & "Classification illustration" separate from "Deep Learning illustration". Yet, here is a regression example of an overfitting Deep Learning model, please judge yourself whether that adds to the answer of the question: Regression and classification examples in a Deep Learning look like those without Deep Learning, see the classification example as follows. On the right, see the examples of underfitting (straight line on the right) vs. overfitting (very complex curve that hits every point): Capacity differences lead to the difference. It is unclear in what way the logistic regression in the activation function changes the capacity of a network. Definition Capacity: the more trainable parameters, the more functions can be learned and the more complex these functions can be. The capacity (number of layers, number of neurons, complexity of the propagation and activation function, and other parameters, seems to be comparable to the question's "higher dimensions", at least the results are the same and that is why I suspect the capacity to be the equivalent problem to the high dimensions of x1 and x2 in a non-Deep-Learning classification problem. My guess: the activation function (here: logistic regression) is part of the capacity of a neural network. This would justify this whole paragraph here. If instead the capacity were not partly changed by the choice of the activation function, then this Deep Learning paragraph would have no relevance in answering the question and should be ignored / deleted, as other parameters (number of layers, number of neurons) are not a problem specific to logistic regression. Here is another hint that the increased dimensionality is meant as the input also in the deep learning setting, see the green marker for the 5 higher dimensionalities. Source: sigmoid with 7 features (5 in high dimensions) which can be run at https://playground.tensorflow.org/#activation=sigmoid&batchSize=25&dataset=circle&regDataset=reg-gauss&learningRate=0.01&regularizationRate=0.3&noise=20&networkShape=5,4&seed=0.70944&showTestData=false&discretize=false&percTrainData=30&x=true&y=true&xTimesY=true&xSquared=true&ySquared=true&cosX=false&sinX=true&cosY=false&sinY=true&collectStats=false&problem=classification&initZero=false&hideText=false Strangely, all of the other activation functions have more overfitting than the sigmoid at the use of 5 higher dimensions in 7 features. In the tensorflow playground, you can just change the activation function to check this. The test result at 2760 epochs and 7 features (5 in high dimensions) as follows. Relu: Tanh: Linear: Perhaps the logistic regression is not "especially prone to overfitting in high dimensions" in neural networks? Or these are just too few dimensions added. If we added up to dimension x^9, it might be the case that the logistic regression in the activation functions will overfit the model more than ReLU and linear. I doubt that tanh will be so much different since it is also asymptotical to -1 and 1. #### Deep Learning side-note END Core part of this answer, at best looking at the simple classification problem in 2D: The increase in dimensionality has an effect as if you added new features, until finally every observation is assigned to the right class. After a certain increase in dimensionality you can hit every class. The resulting unstructured skippy borderline is an overfitting in itself because any visual generalisability is lost, not just to the human eye in this 2dim example, but also for the determination of the correct loss to keep the training relevant for the testing set - the loss simply vanishes to 0. If the regularisation does not punish high weights in order to increase the loss again, the weights of rare feature crosses (metaphorically the skippy borderline, but instead now in a sparse area in high dimensionality) grow without restrictions, overfitting the model. Switching to the other side, this means that the weights of more densely scattered observations (that share some features among each other so that they are no rare feature crosses) lose weight, relatively and also absolutely, possibly till 0, even though they are probably relevant in the testing set. See here how this looks mathematically. You see that the original two features x1 and x2 stay the only ones, there is no feature added! They are just used in different combinations and dimensionalities. From: https://medium.com/machine-learning-intuition/overfitting-what-they-are-regularization-e950c2d66d50 And here is another visualisation of the increased dimensionality meant in the question: The sigmoid activation function g(f(x)) can evaluate f(x) both as a multi-dimensional (= polynomial) regression and as a one-dimensional regression. This supports the idea that adding dimensionality is meant to add different combinations and dimensions of the already existing features (x1,x2) - and it is not to add "new original features" (x3,x4...) as "new dimensions". And it thus stands in contrast to the accepted answer above which explains the problem of the question by adding predictors (= original features): "As a result, regularisation becomes more important when you have many predictors." This statement seems just wrong to me. To the point. Why the accepted answer seems to be wrong: The overfitting issue is not because of added predictors (taking the name of the accepted answer here, = features). It is about using different combinations and dimensions of the existing predictors (features) as artificially new predictors (features). Staying in the examples: x1 and x2 is all what you need to get the overfitting problem explained, no x3 is needed for this. The accepted answer would be only right if it defined "many predictors" as "existing features together with their different combinations and dimensionalities" like x1^2 + x2^2 + x1x2, which I doubt it does, since there is no word about that. Thus in this case, a 200 points assigned accepted answer seems not to offer the true and complete explanation, though its basic direction is right, since: more predictors will tend to overfit the model due to the asymptotical nature of the logistic regression - IF these "more predictors" are the derived higher dimensions from already existing predictors.
Why is logistic regression particularly prone to overfitting in high dimensions?
You give the source’s explanation yourself, where it says in your link: Imagine that you assign a unique id to each example, and map each id to its own feature. If you don't specify a regularization
Why is logistic regression particularly prone to overfitting in high dimensions? You give the source’s explanation yourself, where it says in your link: Imagine that you assign a unique id to each example, and map each id to its own feature. If you don't specify a regularization function, the model will become completely overfit. That's because the model would try to drive loss to zero on all examples and never get there, driving the weights for each indicator feature to +infinity or -infinity. This can happen in high dimensional data with feature crosses, when there’s a huge mass of rare crosses that happen only on one example each. And from Logistic Regression for Machine Learning: It’s an S-shaped curve that can take any real-valued number and map it into a value between 0 and 1, but never exactly at those limits. This "never exactly at those limits" is the point, the logistic regression can almost perfectly predict the class, but is never 100 % sure. Thus the weights can grow almost infinitely as soon as the classes are hit in the vast majority of cases, which can happen if you allow for higher dimensions with a huge mass of rare feature crosses. Part 1: paper on rare feature crosses Alert: I am not sure about Part 1, this is already edited a lot and it is still vague and might be wrong! Main point of change: an unconstrained MLE is for rare feature crosses, and the constrained MLE is the usual case in low dimensionality, meaning much more observations than features. I rather recommend part 2 as the main answer. Part 1 was merged with Part 2, it has been a separate answer before. I assume that the paper "The Impact of Regularization on High-dimensional Logistic Regression" which also uses this outstanding term "rare feature crosses" answers the question here. This would also be in line with the highly voted comment of @DemetriPananos: The question is probably about ... ... complete or quasi-complete separation. High dimensional space is weird, and there may exist some affine plane which perfectly or almost perfectly separates the 1s from the 0s. In such a case, the coefficients of the model are very large and the model will predict probability near 0 or 1 for each case respectively. Back to the paper, at best, read the abstract of the paper yourself. I just try to show the core of it here, and I am not a professional, perhaps someone can correct me in the following conclusions (with some luck, I got it right, though): The problem arises from models where the number of observations and parameters are comparable“ so that “the maximum likelihood estimator is biased. In the high-dimensional regime the underlying parameter vector is often structured (sparse, block-sparse, finite-alphabet, etc.). Which is nothing but the mass of rare feature crosses meant in your source’s explanation. Further: An advantage of RLR is that it allows parameter recovery even for instances where the (unconstrained) maximum likelihood estimate does not exist. I can only assume now that this (unconstrained) MLE does arise from a rare feature cross, with the problem of those observations that are not a rare feature cross and thus need to be "recovered" as parameters because they are dominated by the high weights that the rare feature crosses receive. In other words: in the usual case and in small dimensionality, a constrained MLE exists for each observation, it is calculated over a given number of observations that face a smaller number of features - thus it needs to be calculated by using constraints. With higher dimensionality, rare feature crosses arise where an unconstrained MLE exists, because parameters and observations become 1:1 cases then: one unique feature (~ parameter) = one isolated class assignment (~ observation). In these cases, those observations that are not mapped to just one feature lose their impact and need to be recovered by regularisation. #### An example from the universe: Think of a case where you can explain say that something is a planet or not from the planetary circles around the sun and you use three features for this (in this example, they are all classified as planets except for the sun). Then you add a dimension by making the earth the center instead. This means you do not need more "new" features, instead you just need a higher dimensionality of the same features that are used in the sun model to explain the circles - and that is the same as adding new features, just by using more dimensions of the original features. More details: You might just take three features to prove that all are planets around the sun as a binary problem: planet yes or no, as long as a function can explain the planetary circlre using just the three features. As a next step, you can take whatever dimensionality you want of those three features to improve your model around the earth instead. And adding those higher dimensionalities is the same as adding entirely new features. Then, those functions which perfectly explain a planet by an isolated multidimensional feature (a feature that never explains any other planet) can get very high weights in the model, while those planets that are not that isolated from each other in their functions, because their parabolic functions are rather similar, cannot have infinite weights because there will be a part of the planet circles that gets explained worse when improving the explanation of the other part to 100 %. Now if you go to a very sparse area adding more and more dimensionality, you will get to a model where finally all planets can be marked as planets according to some isolated features that are not used for the other planets' functions. These are the rare feature crosses, there is no interception anymore with any other features. Such features only explain one single planet with its planet function. And thus those high-dimensional features can get infinite weights. #### What is the final idea here to answer the question at all? I assume that the logistic regression which never reaches probability 1 or 0 leads to the infinite weights of the rare feature crosses which causes the model to overfit on the rare feature crosses. This is about a multi-layer design. In low dimensions, that is, if the polynomial degrees of the input are still low, the model with sigmoid activation is simple and saturation leading to overfitting is not the problem, but vanishing gradients (derivative is 0.25, take a couple of layers of backpropagation, and the weights are low) leading to underfitting. The particular problem of overfitting due to the sigmoid activation is for polynomial inputs in high dimensions which can cause these rare feature crosses in high dimensions that describe the training set perfectly but might not generalise to the testing set. The sigmoid curve of the logistic function causes underfitting in low dimensions and overfitting in high dimensions. We cannot repair the MLEs because they depend on the number of features and obervations, and we cannot just change the number of features or observations. Instead, we can reduce the weights of the rare feature crosses to recover the parameters that are no rare feature crosses. Which gives us the next conclusion: When the „number of observations and parameters are comparable“, so that you have a mass of rare feature crosses in great sparsity, you lose the ordering function of the MLEs for the rest that is not in this "mass". End of the abstract: ... and so in this paper we study regularized logistic regression (RLR), where a convex regularizer that encourages the desired structure is added to the negative of the log-likelihood function.” meaning a well-calibrated regularizer can solve the whole issue of the so much needed constraints by using a convex cost function of the weights (L1 and L2 are both tested) as part of the loss. Part 2: Intuition of rare feature crosses in maths and graphs Repeating the quote of your link at the beginning of this answer: This can happen in high dimensional data with feature crosses, when there’s a huge mass of rare crosses that happen only on one example each. The rare feature crosses can already be understood in a 2-dimensional graph with 2 classes (mathematically, a logistic regression is always for 2 classes, though it can be used to predict multiple classes with the One-vs-All method) that are scattered in slightly overlapping clouds of observations, see the middle row "Classification illustration" (and then after this example, think of the mass of rare feature crosses in 3dim "Classification illustration" in a sparse area): Source: https://stanford.edu/~shervine/teaching/cs-229/cheatsheet-machine-learning-tips-and-tricks The borderline between the two classes in the x1/x2 "Classification illustration" example shows the constant likelihood value y = 0.5 to be class 1 or 0. In this "Classification illustration", with every added dimension (not of new variables, but of the same explanatory variable to the power of 2, 3, 4 aso.) the borderline of the observations‘ classes gets more flexible. It is like adding new "explanation power", until you find all the dimensions you need to explain all labels. "Classification illustration", middle graph, (dim 2): When adding 1 dimension means to introduce x1^2 and / or x2^2, the graph has 2 features and 1 or 2 calculated "artificial" features, though there are just 2 original features. "Classification illustration", right graph, (e.g. dim 9): In very high dimensionality, the 2 classes can be assigned so well that perfect separation can be reached. Two different classes can be spread in quite some chaos, you might perfectly separate them when you go up to the power of 9, meaning to have 9 different x1 and / or x2 variables to assign the classes correctly. #### Deep Learning side-note START In the Deep Learning example (bottom row), the logistic regression is used as the activation function. Please note that this has to be kept apart from the classification example which is the better example to answer the question. The logistic regression is a sigmoid function. A wide variety of sigmoid functions including the logistic and hyperbolic tangent functions have been used as the activation function of artificial neurons (https://en.wikipedia.org/wiki/Sigmoid_function). They are used in order to enable nonlinear mapping of the output, so that large numbers do not change so much the activation value anymore, and this because of the asymptotical nature of the curve. The problem is still the same, since every single neuron can be seen as an isolated fitting problem that can also overfit for the same reasons as it is happening in the 2-D-classification example. Once the neuron knows that "it is right", it will allow to increase the probability = activation value to almost g(z) = 1 by admitting the weights to grow infinitely. From: https://stanford.edu/~shervine/teaching/cs-229/cheatsheet-deep-learning Mind that this Deep Learning paragraph should better be ignored in the direct answer of the question. It is not intuitive and just confusing to the reader since the actual problem of overfitting in neural networks is rather a problem of capacity, not of the activation function. A higher capacity leads to overfitting as well as the asymptotical nature of the logistic regression in higher dimensionality of the "Classification illustration". Better keep "Regression illustration" & "Classification illustration" separate from "Deep Learning illustration". Yet, here is a regression example of an overfitting Deep Learning model, please judge yourself whether that adds to the answer of the question: Regression and classification examples in a Deep Learning look like those without Deep Learning, see the classification example as follows. On the right, see the examples of underfitting (straight line on the right) vs. overfitting (very complex curve that hits every point): Capacity differences lead to the difference. It is unclear in what way the logistic regression in the activation function changes the capacity of a network. Definition Capacity: the more trainable parameters, the more functions can be learned and the more complex these functions can be. The capacity (number of layers, number of neurons, complexity of the propagation and activation function, and other parameters, seems to be comparable to the question's "higher dimensions", at least the results are the same and that is why I suspect the capacity to be the equivalent problem to the high dimensions of x1 and x2 in a non-Deep-Learning classification problem. My guess: the activation function (here: logistic regression) is part of the capacity of a neural network. This would justify this whole paragraph here. If instead the capacity were not partly changed by the choice of the activation function, then this Deep Learning paragraph would have no relevance in answering the question and should be ignored / deleted, as other parameters (number of layers, number of neurons) are not a problem specific to logistic regression. Here is another hint that the increased dimensionality is meant as the input also in the deep learning setting, see the green marker for the 5 higher dimensionalities. Source: sigmoid with 7 features (5 in high dimensions) which can be run at https://playground.tensorflow.org/#activation=sigmoid&batchSize=25&dataset=circle&regDataset=reg-gauss&learningRate=0.01&regularizationRate=0.3&noise=20&networkShape=5,4&seed=0.70944&showTestData=false&discretize=false&percTrainData=30&x=true&y=true&xTimesY=true&xSquared=true&ySquared=true&cosX=false&sinX=true&cosY=false&sinY=true&collectStats=false&problem=classification&initZero=false&hideText=false Strangely, all of the other activation functions have more overfitting than the sigmoid at the use of 5 higher dimensions in 7 features. In the tensorflow playground, you can just change the activation function to check this. The test result at 2760 epochs and 7 features (5 in high dimensions) as follows. Relu: Tanh: Linear: Perhaps the logistic regression is not "especially prone to overfitting in high dimensions" in neural networks? Or these are just too few dimensions added. If we added up to dimension x^9, it might be the case that the logistic regression in the activation functions will overfit the model more than ReLU and linear. I doubt that tanh will be so much different since it is also asymptotical to -1 and 1. #### Deep Learning side-note END Core part of this answer, at best looking at the simple classification problem in 2D: The increase in dimensionality has an effect as if you added new features, until finally every observation is assigned to the right class. After a certain increase in dimensionality you can hit every class. The resulting unstructured skippy borderline is an overfitting in itself because any visual generalisability is lost, not just to the human eye in this 2dim example, but also for the determination of the correct loss to keep the training relevant for the testing set - the loss simply vanishes to 0. If the regularisation does not punish high weights in order to increase the loss again, the weights of rare feature crosses (metaphorically the skippy borderline, but instead now in a sparse area in high dimensionality) grow without restrictions, overfitting the model. Switching to the other side, this means that the weights of more densely scattered observations (that share some features among each other so that they are no rare feature crosses) lose weight, relatively and also absolutely, possibly till 0, even though they are probably relevant in the testing set. See here how this looks mathematically. You see that the original two features x1 and x2 stay the only ones, there is no feature added! They are just used in different combinations and dimensionalities. From: https://medium.com/machine-learning-intuition/overfitting-what-they-are-regularization-e950c2d66d50 And here is another visualisation of the increased dimensionality meant in the question: The sigmoid activation function g(f(x)) can evaluate f(x) both as a multi-dimensional (= polynomial) regression and as a one-dimensional regression. This supports the idea that adding dimensionality is meant to add different combinations and dimensions of the already existing features (x1,x2) - and it is not to add "new original features" (x3,x4...) as "new dimensions". And it thus stands in contrast to the accepted answer above which explains the problem of the question by adding predictors (= original features): "As a result, regularisation becomes more important when you have many predictors." This statement seems just wrong to me. To the point. Why the accepted answer seems to be wrong: The overfitting issue is not because of added predictors (taking the name of the accepted answer here, = features). It is about using different combinations and dimensions of the existing predictors (features) as artificially new predictors (features). Staying in the examples: x1 and x2 is all what you need to get the overfitting problem explained, no x3 is needed for this. The accepted answer would be only right if it defined "many predictors" as "existing features together with their different combinations and dimensionalities" like x1^2 + x2^2 + x1x2, which I doubt it does, since there is no word about that. Thus in this case, a 200 points assigned accepted answer seems not to offer the true and complete explanation, though its basic direction is right, since: more predictors will tend to overfit the model due to the asymptotical nature of the logistic regression - IF these "more predictors" are the derived higher dimensions from already existing predictors.
Why is logistic regression particularly prone to overfitting in high dimensions? You give the source’s explanation yourself, where it says in your link: Imagine that you assign a unique id to each example, and map each id to its own feature. If you don't specify a regularization
11,416
Why is logistic regression particularly prone to overfitting in high dimensions?
I would split logistic regression into three cases: modelling "binomial proportions" with no cell proportions being 0% or 100% modelling "Bernoulli data" something in between What's the difference? case 1 In case 1, your data cannot be separated using your predictors, because each feature $x_i$ has multiple records, with at least 1 "success" and at least 1 "failure". The loss function then becomes $$LogLoss=\sum_i n_i \left[f_i\log(p_i)+(1-f_i)\log(1-p_i)\right]$$ Where $f_i$ is the proportion of times $y=1$ in "cell" $i$, and $p_i=(1+\exp^{-x_i^Tw})$ is the modelled probability that $y=1$ in "cell" $i$. The number $n_i$ is the number of training samples you have for "cell" $i$. What defines a "cell"? The samples with the same set of features $x_i$ are all in the same cell. In case 1, regularisation may not be needed and can actually be harmful. It depends on how big the cell sizes ($n_i$) are. But the loss function looks totally different to the plot you show for this case - it is more like a squared error loss function, and is can be approximated by $\sum_i n_i\frac{(f_i-p_i)^2}{p_i(1-p_i)}$. This is also known as normal approximation to binomial proportion (and also underlies many gradient based algorithms for estimating the coefficients). Perfect prediction for each sample is impossible in this scenario, and you can think of the cells themselves as a form of regularisation. The predictions are constrained to be equal for samples in the same cell. Provided no cells are homogeneous (at least 1 of both outcomes) you cannot have a coefficient wander off to infinity. You can also think of this as being very similar to linear regression at the cell level on the observed "logits" $\log\left(\frac{f_i}{1-f_i}\right)=x_i^Tw+error$ with each record weighted towards the "high information" samples $n_ip_i(1-p_i)$ (Ie big cell size + prediction close to decision boundary), rather than unweighted. As a side note, you can save a lot of computing time by fitting your models as "case 1" - particularly if $n_i$ are large -compared to binary modelling the data in case 2. This is because you aggregate sums over "cells" rather than "samples". Also your degrees of freedom are defined by the number of "cells" rather than the number of "samples" (eg if you have 1 million samples but only 100 cells, then you can only fit 100 independent parameters). case 2 In this case, the predictors uniquely characterise each sample. This means we can fit the data with zero log loss by setting fitted values to $0$ or $1$. You can use the notation before as $n_i=1$ or $n_i>1,f_i\in\{0,1\}$. In this case we need some kind of regularisation, particularly if all the $n_i$ are small. Either "size of coefficients" (eg L1, L2) where large values for $w$ are penalised. You could also penalise "difference in coefficients" - such as needing unit which are "close" in feature space to have similar predictions - similar to forming cells like in case 1 (this is like pruning a regression tree). Interestingly, some regularisation approaches can be characterised as adding "pseudo data" to each cell such that you have a situation more like case 1. That is, for the records with $f_i=0$ we add pseudo data for a $y=1$ case in that cell, and if $f_i=1$ we add pseudo data for a $y=0$ case in that cell. The different levels of regularisation will determine how much "weight" to give the pseudo data vs the observed data. case 3 In this case you may have small segments of the sample that can be perfectly predicted. This is also likely to be where most real data lives. Can see that some kind of adaptive regularisation will likely help - where you focus more on regularising based on $n_i$. The difficult part is that many choices on what's best really depend on the data you're working with, and not the algorithm. This is one reason we have lots of different algorithms. In fact, the logistic regression MLE, if not penalised, will basically split the training sample into "case 1" and "case 2" datasets. Analytically this approach will minimise the log loss. The problem is computational issues tend to result in the algorithm stopping before this happens. Typically you see large coefficients with even larger standard errors when this happens. Easy enough to find these by simply looking at or filtering the coefficients (probably need to be a bit clever with visualising these if you have a huge number of coefficients).
Why is logistic regression particularly prone to overfitting in high dimensions?
I would split logistic regression into three cases: modelling "binomial proportions" with no cell proportions being 0% or 100% modelling "Bernoulli data" something in between What's the difference?
Why is logistic regression particularly prone to overfitting in high dimensions? I would split logistic regression into three cases: modelling "binomial proportions" with no cell proportions being 0% or 100% modelling "Bernoulli data" something in between What's the difference? case 1 In case 1, your data cannot be separated using your predictors, because each feature $x_i$ has multiple records, with at least 1 "success" and at least 1 "failure". The loss function then becomes $$LogLoss=\sum_i n_i \left[f_i\log(p_i)+(1-f_i)\log(1-p_i)\right]$$ Where $f_i$ is the proportion of times $y=1$ in "cell" $i$, and $p_i=(1+\exp^{-x_i^Tw})$ is the modelled probability that $y=1$ in "cell" $i$. The number $n_i$ is the number of training samples you have for "cell" $i$. What defines a "cell"? The samples with the same set of features $x_i$ are all in the same cell. In case 1, regularisation may not be needed and can actually be harmful. It depends on how big the cell sizes ($n_i$) are. But the loss function looks totally different to the plot you show for this case - it is more like a squared error loss function, and is can be approximated by $\sum_i n_i\frac{(f_i-p_i)^2}{p_i(1-p_i)}$. This is also known as normal approximation to binomial proportion (and also underlies many gradient based algorithms for estimating the coefficients). Perfect prediction for each sample is impossible in this scenario, and you can think of the cells themselves as a form of regularisation. The predictions are constrained to be equal for samples in the same cell. Provided no cells are homogeneous (at least 1 of both outcomes) you cannot have a coefficient wander off to infinity. You can also think of this as being very similar to linear regression at the cell level on the observed "logits" $\log\left(\frac{f_i}{1-f_i}\right)=x_i^Tw+error$ with each record weighted towards the "high information" samples $n_ip_i(1-p_i)$ (Ie big cell size + prediction close to decision boundary), rather than unweighted. As a side note, you can save a lot of computing time by fitting your models as "case 1" - particularly if $n_i$ are large -compared to binary modelling the data in case 2. This is because you aggregate sums over "cells" rather than "samples". Also your degrees of freedom are defined by the number of "cells" rather than the number of "samples" (eg if you have 1 million samples but only 100 cells, then you can only fit 100 independent parameters). case 2 In this case, the predictors uniquely characterise each sample. This means we can fit the data with zero log loss by setting fitted values to $0$ or $1$. You can use the notation before as $n_i=1$ or $n_i>1,f_i\in\{0,1\}$. In this case we need some kind of regularisation, particularly if all the $n_i$ are small. Either "size of coefficients" (eg L1, L2) where large values for $w$ are penalised. You could also penalise "difference in coefficients" - such as needing unit which are "close" in feature space to have similar predictions - similar to forming cells like in case 1 (this is like pruning a regression tree). Interestingly, some regularisation approaches can be characterised as adding "pseudo data" to each cell such that you have a situation more like case 1. That is, for the records with $f_i=0$ we add pseudo data for a $y=1$ case in that cell, and if $f_i=1$ we add pseudo data for a $y=0$ case in that cell. The different levels of regularisation will determine how much "weight" to give the pseudo data vs the observed data. case 3 In this case you may have small segments of the sample that can be perfectly predicted. This is also likely to be where most real data lives. Can see that some kind of adaptive regularisation will likely help - where you focus more on regularising based on $n_i$. The difficult part is that many choices on what's best really depend on the data you're working with, and not the algorithm. This is one reason we have lots of different algorithms. In fact, the logistic regression MLE, if not penalised, will basically split the training sample into "case 1" and "case 2" datasets. Analytically this approach will minimise the log loss. The problem is computational issues tend to result in the algorithm stopping before this happens. Typically you see large coefficients with even larger standard errors when this happens. Easy enough to find these by simply looking at or filtering the coefficients (probably need to be a bit clever with visualising these if you have a huge number of coefficients).
Why is logistic regression particularly prone to overfitting in high dimensions? I would split logistic regression into three cases: modelling "binomial proportions" with no cell proportions being 0% or 100% modelling "Bernoulli data" something in between What's the difference?
11,417
Why is logistic regression particularly prone to overfitting in high dimensions?
The overfitting nature of logistic regression is related to the curse of dimensionality in way that I would characterize as inversed curse, and not what your source refers to as asymptotic nature. It's a consequence of Manhattan distance being resistant to the curse of dimensionality. I could also say that it drives the loss to zero because it can. You can lookup a highly cited paper "On the Surprising Behavior of Distance Metrics in High Dimensional Space" by Aggarwal et al, here https://bib.dbvis.de/uploadedFiles/155.pdf They study different distance metrics and found that Manhattan distance is the most robust in high dimenional problems for the purpose of classification. Other metrics such as Euclidian distance can't tell the points apart. Now, all sigmoid fuctions have a linear term in Taylor approximation, see this one for example: Hence, the predictor $y(X\beta)\sim X\beta$, which is very similar to a Manhattan distance $L_1$. The log loss function is also linear around any point of choosing $\ln (x+e)=\ln x + \ln (1+e/x)\approx e/x$. Therefore, the predictors in logistic regressions even after applying the loss function are going to be separating points in high dimensions very robustly, and will have no trouble driving the loss function to zero. This is in contrast to OLS regression where the setup is such that Euclidian distance is used to separate points. This distance is never linear by construction, it's exactly quadratic. As I already wrote Euclidian distance doesn't work well in high dimensional problems. You can see now that asymptotic nature has nothing to do with logit's tendency to overfit. Also, what your source means by that concept is the following: when $|X\beta|\to\infty$ then we have the predictor $y(X\beta)$ tend to either 0 or 1. Hence, the "asymptotic" characterization. The loss at the edges is infinitely large.
Why is logistic regression particularly prone to overfitting in high dimensions?
The overfitting nature of logistic regression is related to the curse of dimensionality in way that I would characterize as inversed curse, and not what your source refers to as asymptotic nature. It'
Why is logistic regression particularly prone to overfitting in high dimensions? The overfitting nature of logistic regression is related to the curse of dimensionality in way that I would characterize as inversed curse, and not what your source refers to as asymptotic nature. It's a consequence of Manhattan distance being resistant to the curse of dimensionality. I could also say that it drives the loss to zero because it can. You can lookup a highly cited paper "On the Surprising Behavior of Distance Metrics in High Dimensional Space" by Aggarwal et al, here https://bib.dbvis.de/uploadedFiles/155.pdf They study different distance metrics and found that Manhattan distance is the most robust in high dimenional problems for the purpose of classification. Other metrics such as Euclidian distance can't tell the points apart. Now, all sigmoid fuctions have a linear term in Taylor approximation, see this one for example: Hence, the predictor $y(X\beta)\sim X\beta$, which is very similar to a Manhattan distance $L_1$. The log loss function is also linear around any point of choosing $\ln (x+e)=\ln x + \ln (1+e/x)\approx e/x$. Therefore, the predictors in logistic regressions even after applying the loss function are going to be separating points in high dimensions very robustly, and will have no trouble driving the loss function to zero. This is in contrast to OLS regression where the setup is such that Euclidian distance is used to separate points. This distance is never linear by construction, it's exactly quadratic. As I already wrote Euclidian distance doesn't work well in high dimensional problems. You can see now that asymptotic nature has nothing to do with logit's tendency to overfit. Also, what your source means by that concept is the following: when $|X\beta|\to\infty$ then we have the predictor $y(X\beta)$ tend to either 0 or 1. Hence, the "asymptotic" characterization. The loss at the edges is infinitely large.
Why is logistic regression particularly prone to overfitting in high dimensions? The overfitting nature of logistic regression is related to the curse of dimensionality in way that I would characterize as inversed curse, and not what your source refers to as asymptotic nature. It'
11,418
Positioning the arrows on a PCA biplot
There are many different ways to produce a PCA biplot and so there is no unique answer to your question. Here is a short overview. We assume that the data matrix $\mathbf X$ has $n$ data points in rows and is centered (i.e. column means are all zero). For now, we do not assume that it was standardized, i.e. we consider PCA on covariance matrix (not on correlation matrix). PCA amounts to a singular value decomposition $$\mathbf X=\mathbf{USV}^\top,$$ you can see my answer here for details: Relationship between SVD and PCA. How to use SVD to perform PCA? In a PCA biplot, two first principal components are plotted as a scatter plot, i.e. first column of $\mathbf U$ is plotted against its second column. But normalization can be different; e.g. one can use: Columns of $\mathbf U$: these are principal components scaled to unit sum of squares; Columns of $\sqrt{n-1}\mathbf U$: these are standardized principal components (unit variance); Columns of $\mathbf{US}$: these are "raw" principal components (projections on principal directions). Further, original variables are plotted as arrows; i.e. $(x,y)$ coordinates of an $i$-th arrow endpoint are given by the $i$-th value in the first and second column of $\mathbf V$. But again, one can choose different normalizations, e.g.: Columns of $\mathbf {VS}$: I don't know what an interpretation here could be; Columns of $\mathbf {VS}/\sqrt{n-1}$: these are loadings; Columns of $\mathbf V$: these are principal axes (aka principal directions, aka eigenvectors). Here is how all of that looks like for Fisher Iris dataset: Combining any subplot from above with any subplot from below would make up $9$ possible normalizations. But according to the original definition of a biplot introduced in Gabriel, 1971, The biplot graphic display of matrices with application to principal component analysis (this paper has 2k citations, by the way), matrices used for biplot should, when multiplied together, approximate $\mathbf X$ (that's the whole point). So a "proper biplot" can use e.g. $\mathbf{US}^\alpha \beta$ and $\mathbf{VS}^{(1-\alpha)} / \beta$. Therefore only three of the $9$ are "proper biplots": namely a combination of any subplot from above with the one directly below. [Whatever combination one uses, it might be necessary to scale arrows by some arbitrary constant factor so that both arrows and data points appear roughly on the same scale.] Using loadings, i.e. $\mathbf{VS}/\sqrt{n-1}$, for arrows has a large benefit in that they have useful interpretations (see also here about loadings). Length of the loading arrows approximates the standard deviation of original variables (squared length approximates variance), scalar products between any two arrows approximate the covariance between them, and cosines of the angles between arrows approximate correlations between original variables. To make a "proper biplot", one should choose $\mathbf U\sqrt{n-1}$, i.e. standardized PCs, for data points. Gabriel (1971) calls this "PCA biplot" and writes that This [particular choice] is likely to provide a most useful graphical aid in interpreting multivariate matrices of observations, provided, of course, that these can be adequately approximated at rank two. Using $\mathbf{US}$ and $\mathbf{V}$ allows a nice interpretation: arrows are projections of the original basis vectors onto the PC plane, see this illustration by @hxd1011. One can even opt to plot raw PCs $\mathbf {US}$ together with loadings. This is an "improper biplot", but was e.g. done by @vqv on the most elegant biplot I have ever seen: Visualizing a million, PCA edition -- it shows PCA of the wine dataset. The figure you posted (default outcome of R biplot function) is a "proper biplot" with $\mathbf U$ and $\mathbf{VS}$. The function scales two subplots such that they span the same area. Unfortunately, the biplot function makes a weird choice of scaling all arrows down by a factor of $0.8$ and displaying the text labels where the arrow endpoints should have been. (Also, biplot does not get the scaling correctly and in fact ends up plotting scores with $n/(n-1)$ sum of squares, instead of $1$. See this detailed investigation by @AntoniParellada: Arrows of underlying variables in PCA biplot in R.) PCA on correlation matrix If we further assume that the data matrix $\mathbf X$ has been standardized so that column standard deviations are all equal to $1$, then we are performing PCA on the correlation matrix. Here is how the same figure looks like: Here the loadings are even more attractive, because (in addition to the above mentioned properties), they give exactly (and not approximately) correlation coefficients between original variables and PCs. Correlations are all smaller than $1$ and loadings arrows have to be inside a "correlation circle" of radius $R=1$, which is sometimes drawn on a biplot as well (I plotted it on the corresponding subplot above). Note that the biplot by @vqv (linked above) was done for a PCA on correlation matrix, and also sports a correlation circle. Further reading: PCA and Correspondence analysis in their relation to Biplot - detailed treatment by @ttnphns. What is the proper association measure of a variable with a PCA component (on a biplot / loading plot)? - geometric explanation by @ttnphns of what the loading arrows on a biplot mean.
Positioning the arrows on a PCA biplot
There are many different ways to produce a PCA biplot and so there is no unique answer to your question. Here is a short overview. We assume that the data matrix $\mathbf X$ has $n$ data points in ro
Positioning the arrows on a PCA biplot There are many different ways to produce a PCA biplot and so there is no unique answer to your question. Here is a short overview. We assume that the data matrix $\mathbf X$ has $n$ data points in rows and is centered (i.e. column means are all zero). For now, we do not assume that it was standardized, i.e. we consider PCA on covariance matrix (not on correlation matrix). PCA amounts to a singular value decomposition $$\mathbf X=\mathbf{USV}^\top,$$ you can see my answer here for details: Relationship between SVD and PCA. How to use SVD to perform PCA? In a PCA biplot, two first principal components are plotted as a scatter plot, i.e. first column of $\mathbf U$ is plotted against its second column. But normalization can be different; e.g. one can use: Columns of $\mathbf U$: these are principal components scaled to unit sum of squares; Columns of $\sqrt{n-1}\mathbf U$: these are standardized principal components (unit variance); Columns of $\mathbf{US}$: these are "raw" principal components (projections on principal directions). Further, original variables are plotted as arrows; i.e. $(x,y)$ coordinates of an $i$-th arrow endpoint are given by the $i$-th value in the first and second column of $\mathbf V$. But again, one can choose different normalizations, e.g.: Columns of $\mathbf {VS}$: I don't know what an interpretation here could be; Columns of $\mathbf {VS}/\sqrt{n-1}$: these are loadings; Columns of $\mathbf V$: these are principal axes (aka principal directions, aka eigenvectors). Here is how all of that looks like for Fisher Iris dataset: Combining any subplot from above with any subplot from below would make up $9$ possible normalizations. But according to the original definition of a biplot introduced in Gabriel, 1971, The biplot graphic display of matrices with application to principal component analysis (this paper has 2k citations, by the way), matrices used for biplot should, when multiplied together, approximate $\mathbf X$ (that's the whole point). So a "proper biplot" can use e.g. $\mathbf{US}^\alpha \beta$ and $\mathbf{VS}^{(1-\alpha)} / \beta$. Therefore only three of the $9$ are "proper biplots": namely a combination of any subplot from above with the one directly below. [Whatever combination one uses, it might be necessary to scale arrows by some arbitrary constant factor so that both arrows and data points appear roughly on the same scale.] Using loadings, i.e. $\mathbf{VS}/\sqrt{n-1}$, for arrows has a large benefit in that they have useful interpretations (see also here about loadings). Length of the loading arrows approximates the standard deviation of original variables (squared length approximates variance), scalar products between any two arrows approximate the covariance between them, and cosines of the angles between arrows approximate correlations between original variables. To make a "proper biplot", one should choose $\mathbf U\sqrt{n-1}$, i.e. standardized PCs, for data points. Gabriel (1971) calls this "PCA biplot" and writes that This [particular choice] is likely to provide a most useful graphical aid in interpreting multivariate matrices of observations, provided, of course, that these can be adequately approximated at rank two. Using $\mathbf{US}$ and $\mathbf{V}$ allows a nice interpretation: arrows are projections of the original basis vectors onto the PC plane, see this illustration by @hxd1011. One can even opt to plot raw PCs $\mathbf {US}$ together with loadings. This is an "improper biplot", but was e.g. done by @vqv on the most elegant biplot I have ever seen: Visualizing a million, PCA edition -- it shows PCA of the wine dataset. The figure you posted (default outcome of R biplot function) is a "proper biplot" with $\mathbf U$ and $\mathbf{VS}$. The function scales two subplots such that they span the same area. Unfortunately, the biplot function makes a weird choice of scaling all arrows down by a factor of $0.8$ and displaying the text labels where the arrow endpoints should have been. (Also, biplot does not get the scaling correctly and in fact ends up plotting scores with $n/(n-1)$ sum of squares, instead of $1$. See this detailed investigation by @AntoniParellada: Arrows of underlying variables in PCA biplot in R.) PCA on correlation matrix If we further assume that the data matrix $\mathbf X$ has been standardized so that column standard deviations are all equal to $1$, then we are performing PCA on the correlation matrix. Here is how the same figure looks like: Here the loadings are even more attractive, because (in addition to the above mentioned properties), they give exactly (and not approximately) correlation coefficients between original variables and PCs. Correlations are all smaller than $1$ and loadings arrows have to be inside a "correlation circle" of radius $R=1$, which is sometimes drawn on a biplot as well (I plotted it on the corresponding subplot above). Note that the biplot by @vqv (linked above) was done for a PCA on correlation matrix, and also sports a correlation circle. Further reading: PCA and Correspondence analysis in their relation to Biplot - detailed treatment by @ttnphns. What is the proper association measure of a variable with a PCA component (on a biplot / loading plot)? - geometric explanation by @ttnphns of what the loading arrows on a biplot mean.
Positioning the arrows on a PCA biplot There are many different ways to produce a PCA biplot and so there is no unique answer to your question. Here is a short overview. We assume that the data matrix $\mathbf X$ has $n$ data points in ro
11,419
How to show that this integral of the normal distribution is finite?
Intuitively, the result is obvious because (a) $\phi$ is a rapidly decreasing function (its magnitude decreases at a quadratic exponential rate) and (b) $\Phi$ is bounded above and, for negative $x,$ is also rapidly decreasing at essentially the same rate as $\phi.$ Thus the fraction $\phi^2/\Phi$ decreases rapidly for both positive and negative $x,$ while remaining bounded in between, whence its integral is very nicely behaved and finite. The problem, then, is to make this intuition rigorous. The rigor merely parallels the foregoing argument by making suitable quantitative comparisons. When $x\gt 0,$ $\Phi(x)\ge 1/2$ (by a familiar symmetry argument). Whence (in this case) the integrand is bounded above in magnitude by $$\bigg|\frac{\phi(x)^2}{\Phi(x)}\bigg| \le 2\phi(x)^2 \lt 2\exp(-x^2)/\sqrt{2\pi}$$ which (because it is proportional to the density of another Normal distribution) has a finite integral. The harder part is the integral over negative $x.$ But here, the Mills Ratio is $$R(-x) = \frac{\Phi(x)}{\phi(x)}$$ which, as the linked post explains, is bounded below by $-x/(x^2+1).$ Thus, for large negative $x$ (say, $x \le -1$), $$\bigg|\frac{\phi(x)^2}{\Phi(x)}\bigg| = \bigg|\phi(x)\left(\frac{1}{R(-x)}\right)\bigg| \le \phi(x) \frac{x^2+1}{|x|} \le 2|x|\phi(x)$$ whose integral also converges (it can integrated exactly using elementary techniques). Since $\phi(x)^2/\Phi(x)$ is bounded on the remaining interval $[-1,0],$ we have established that its integral over the entire real line is bounded in magnitude by the sum of three convergent quantities, whence it is finite, QED. This argument continues to apply, essentially without change, to any integrand of the form $\phi(x)^k/\Phi(x)$ for $k\gt 1.$ It also shows (look more closely at the upper and lower bounds for Mills' Ratio) that the integral diverges when $k\le 1.$ (For a plot with $k=1$ -- which is just the inverse Mills' Ratio -- see the last figure of https://stats.stackexchange.com/a/166277/919.)
How to show that this integral of the normal distribution is finite?
Intuitively, the result is obvious because (a) $\phi$ is a rapidly decreasing function (its magnitude decreases at a quadratic exponential rate) and (b) $\Phi$ is bounded above and, for negative $x,$
How to show that this integral of the normal distribution is finite? Intuitively, the result is obvious because (a) $\phi$ is a rapidly decreasing function (its magnitude decreases at a quadratic exponential rate) and (b) $\Phi$ is bounded above and, for negative $x,$ is also rapidly decreasing at essentially the same rate as $\phi.$ Thus the fraction $\phi^2/\Phi$ decreases rapidly for both positive and negative $x,$ while remaining bounded in between, whence its integral is very nicely behaved and finite. The problem, then, is to make this intuition rigorous. The rigor merely parallels the foregoing argument by making suitable quantitative comparisons. When $x\gt 0,$ $\Phi(x)\ge 1/2$ (by a familiar symmetry argument). Whence (in this case) the integrand is bounded above in magnitude by $$\bigg|\frac{\phi(x)^2}{\Phi(x)}\bigg| \le 2\phi(x)^2 \lt 2\exp(-x^2)/\sqrt{2\pi}$$ which (because it is proportional to the density of another Normal distribution) has a finite integral. The harder part is the integral over negative $x.$ But here, the Mills Ratio is $$R(-x) = \frac{\Phi(x)}{\phi(x)}$$ which, as the linked post explains, is bounded below by $-x/(x^2+1).$ Thus, for large negative $x$ (say, $x \le -1$), $$\bigg|\frac{\phi(x)^2}{\Phi(x)}\bigg| = \bigg|\phi(x)\left(\frac{1}{R(-x)}\right)\bigg| \le \phi(x) \frac{x^2+1}{|x|} \le 2|x|\phi(x)$$ whose integral also converges (it can integrated exactly using elementary techniques). Since $\phi(x)^2/\Phi(x)$ is bounded on the remaining interval $[-1,0],$ we have established that its integral over the entire real line is bounded in magnitude by the sum of three convergent quantities, whence it is finite, QED. This argument continues to apply, essentially without change, to any integrand of the form $\phi(x)^k/\Phi(x)$ for $k\gt 1.$ It also shows (look more closely at the upper and lower bounds for Mills' Ratio) that the integral diverges when $k\le 1.$ (For a plot with $k=1$ -- which is just the inverse Mills' Ratio -- see the last figure of https://stats.stackexchange.com/a/166277/919.)
How to show that this integral of the normal distribution is finite? Intuitively, the result is obvious because (a) $\phi$ is a rapidly decreasing function (its magnitude decreases at a quadratic exponential rate) and (b) $\Phi$ is bounded above and, for negative $x,$
11,420
How to show that this integral of the normal distribution is finite?
Here is a self-contained elementary argument, by a comparison with the Laplace distribution. We show $$\int_{-\infty}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx<\frac{1}{2\sqrt{\pi}}+\sqrt{\frac\pi2}\simeq 1.535<\infty$$ The positive side of the integral has the bound $$\int_{0}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx< \int_{0}^{\infty}\frac{\phi(x)^2}{1/2}dx=\frac{1}{2\sqrt{\pi}}$$ The negative side of the integral has the bound $$\int_{-\infty}^{0}\frac{\phi(x)^2}{\Phi(x)}dx< \int_{-\infty}^{0}\sqrt{2\pi}\frac{f_L(x)^2}{F_L(x)}dx=\sqrt{\frac\pi2}\phantom{1<\infty}$$ Since the Laplace distribution has $f_L(x)=F_L(x)=\frac12 e^x$ on $x<0$, the integral is easy. To prove that $\phi^2/\Phi<\sqrt{2\pi} f_L^2/F_L$, we start by proving $$g(u)=\frac{-(2u+1)\exp\left(\frac{-u^2}2-u\right)}{\pi}<1$$ Using the first-derivative test, the maximum occurs at exactly $u_\max=-(3+\sqrt{17})/4$, and by numerical evaluation $g(u_\max)<1$. Thus for $x<0$, \begin{align} \phi(x)^2\frac{F_L(x)}{f_L^2(x)} &=\frac{\exp(-x^2)}{2\pi}\frac{\frac12 \exp(x)}{\frac14 \exp(2x)}\\ &=\frac{\exp(-x^2-x)}{\pi}\\ &=\int_{u=-\infty}^{x}\frac{-(2u+1)\exp(-u^2-u)}{\pi}du\\ &<\int_{u=-\infty}^{x}\exp(-u^2/2)du\\ &=\sqrt{2\pi}\Phi(x) \end{align} which is what we need.
How to show that this integral of the normal distribution is finite?
Here is a self-contained elementary argument, by a comparison with the Laplace distribution. We show $$\int_{-\infty}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx<\frac{1}{2\sqrt{\pi}}+\sqrt{\frac\pi2}\simeq 1
How to show that this integral of the normal distribution is finite? Here is a self-contained elementary argument, by a comparison with the Laplace distribution. We show $$\int_{-\infty}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx<\frac{1}{2\sqrt{\pi}}+\sqrt{\frac\pi2}\simeq 1.535<\infty$$ The positive side of the integral has the bound $$\int_{0}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx< \int_{0}^{\infty}\frac{\phi(x)^2}{1/2}dx=\frac{1}{2\sqrt{\pi}}$$ The negative side of the integral has the bound $$\int_{-\infty}^{0}\frac{\phi(x)^2}{\Phi(x)}dx< \int_{-\infty}^{0}\sqrt{2\pi}\frac{f_L(x)^2}{F_L(x)}dx=\sqrt{\frac\pi2}\phantom{1<\infty}$$ Since the Laplace distribution has $f_L(x)=F_L(x)=\frac12 e^x$ on $x<0$, the integral is easy. To prove that $\phi^2/\Phi<\sqrt{2\pi} f_L^2/F_L$, we start by proving $$g(u)=\frac{-(2u+1)\exp\left(\frac{-u^2}2-u\right)}{\pi}<1$$ Using the first-derivative test, the maximum occurs at exactly $u_\max=-(3+\sqrt{17})/4$, and by numerical evaluation $g(u_\max)<1$. Thus for $x<0$, \begin{align} \phi(x)^2\frac{F_L(x)}{f_L^2(x)} &=\frac{\exp(-x^2)}{2\pi}\frac{\frac12 \exp(x)}{\frac14 \exp(2x)}\\ &=\frac{\exp(-x^2-x)}{\pi}\\ &=\int_{u=-\infty}^{x}\frac{-(2u+1)\exp(-u^2-u)}{\pi}du\\ &<\int_{u=-\infty}^{x}\exp(-u^2/2)du\\ &=\sqrt{2\pi}\Phi(x) \end{align} which is what we need.
How to show that this integral of the normal distribution is finite? Here is a self-contained elementary argument, by a comparison with the Laplace distribution. We show $$\int_{-\infty}^{\infty}\frac{\phi(x)^2}{\Phi(x)}dx<\frac{1}{2\sqrt{\pi}}+\sqrt{\frac\pi2}\simeq 1
11,421
How to show that this integral of the normal distribution is finite?
The integral relates to the expectation value of the normal hazard function $$E_X[h(x)] = E_X\left[\dfrac{\phi(x)}{1-\Phi(x)}\right] = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{1-\Phi(x)}\right) \phi(x) dx = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{\Phi(x)}\right) \phi(x) dx$$ The last step is due to the symmetry. This hazard function will be approximately asymptotic to $x$ at positive infinity and will be smaller than $x^2$ (except in some region where it is finite). Since $E_X[x^2]$ is finite so must be $E_X[h(x)]$ The big difference between $x^2$, which is already resulting in a finite integral, and the hazard function $h(x)$ indicates that this is not a hard problem and there are probably many approaches to show that the integral does not diverge (as seen in many answers to the question). For instance, we can more precisely see this asymptotic behaviour of the hazard function in the expression $$log(1-F(t)) = log(S(t)) = -\int_{-\infty}^x h(t) dt$$ This can be related to the asymptotic behavior of the error function (as $\text{erfc}(x/\sqrt{2})/2 = 1-F(x)$), which has exponential bounds with factor $e^{-x^2}$ for $x>0$.
How to show that this integral of the normal distribution is finite?
The integral relates to the expectation value of the normal hazard function $$E_X[h(x)] = E_X\left[\dfrac{\phi(x)}{1-\Phi(x)}\right] = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{1-\Phi(x)}\right) \
How to show that this integral of the normal distribution is finite? The integral relates to the expectation value of the normal hazard function $$E_X[h(x)] = E_X\left[\dfrac{\phi(x)}{1-\Phi(x)}\right] = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{1-\Phi(x)}\right) \phi(x) dx = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{\Phi(x)}\right) \phi(x) dx$$ The last step is due to the symmetry. This hazard function will be approximately asymptotic to $x$ at positive infinity and will be smaller than $x^2$ (except in some region where it is finite). Since $E_X[x^2]$ is finite so must be $E_X[h(x)]$ The big difference between $x^2$, which is already resulting in a finite integral, and the hazard function $h(x)$ indicates that this is not a hard problem and there are probably many approaches to show that the integral does not diverge (as seen in many answers to the question). For instance, we can more precisely see this asymptotic behaviour of the hazard function in the expression $$log(1-F(t)) = log(S(t)) = -\int_{-\infty}^x h(t) dt$$ This can be related to the asymptotic behavior of the error function (as $\text{erfc}(x/\sqrt{2})/2 = 1-F(x)$), which has exponential bounds with factor $e^{-x^2}$ for $x>0$.
How to show that this integral of the normal distribution is finite? The integral relates to the expectation value of the normal hazard function $$E_X[h(x)] = E_X\left[\dfrac{\phi(x)}{1-\Phi(x)}\right] = \int_{-\infty}^{\infty} \left(\dfrac{\phi(x)}{1-\Phi(x)}\right) \
11,422
How to show that this integral of the normal distribution is finite?
Intuitive approach $\Phi(x)$ is changing in the interval $[0,1]$, whereas $\phi(x)^2$ is itself a normal distribution which is integrable. Thus, the only reason why the integral could not be finite, is because it diverges in the limit $x\rightarrow -\infty$. By L'Hôpital's rule: $$ \frac{\phi^2(x)}{\Phi(x)}\sim \frac{2\phi(x)\phi'(x)}{\phi(x)}\sim \phi'(x)= -\frac{2x}{\sigma^2}\phi(x)\\(\text{as }x\rightarrow -\infty) $$ In other words, the asymptotic form of the integrand for $x\rightarrow-\infty$ is $$ \frac{\phi^2(x)}{\Phi(x)}\sim -\frac{2x}{\sigma^2}\phi(x), $$ the integral of which converges in the desired limit. Rigorous approach Perhaps, a more rigorous way could be to show that in the limit $x\rightarrow -\infty$ the integrand decays faster than $1/x$,a nd hence convergent. We this apply the L'Hôpital's rule to the following: By L'Hôpital's rule: $$ \lim_{x\rightarrow -\infty}\frac{x\phi^2(x)}{\Phi(x)}= \lim_{x\rightarrow -\infty}\frac{\phi^2(x)+x\phi(x)\phi'(x)}{\phi(x)}= \lim_{x\rightarrow -\infty}\left[\phi(x)+x\phi'(x)\right]= \lim_{x\rightarrow -\infty}\left[1-\frac{x}{\sigma^2}\right]\phi(x)=0. $$Thus, the integral converges in the limit in question. Remarks: I appreciate @SextusEmpiricus remarks, which led to improvement of this answer. $$\phi(x)=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{x^2}{2\sigma^2}}$$
How to show that this integral of the normal distribution is finite?
Intuitive approach $\Phi(x)$ is changing in the interval $[0,1]$, whereas $\phi(x)^2$ is itself a normal distribution which is integrable. Thus, the only reason why the integral could not be finite, i
How to show that this integral of the normal distribution is finite? Intuitive approach $\Phi(x)$ is changing in the interval $[0,1]$, whereas $\phi(x)^2$ is itself a normal distribution which is integrable. Thus, the only reason why the integral could not be finite, is because it diverges in the limit $x\rightarrow -\infty$. By L'Hôpital's rule: $$ \frac{\phi^2(x)}{\Phi(x)}\sim \frac{2\phi(x)\phi'(x)}{\phi(x)}\sim \phi'(x)= -\frac{2x}{\sigma^2}\phi(x)\\(\text{as }x\rightarrow -\infty) $$ In other words, the asymptotic form of the integrand for $x\rightarrow-\infty$ is $$ \frac{\phi^2(x)}{\Phi(x)}\sim -\frac{2x}{\sigma^2}\phi(x), $$ the integral of which converges in the desired limit. Rigorous approach Perhaps, a more rigorous way could be to show that in the limit $x\rightarrow -\infty$ the integrand decays faster than $1/x$,a nd hence convergent. We this apply the L'Hôpital's rule to the following: By L'Hôpital's rule: $$ \lim_{x\rightarrow -\infty}\frac{x\phi^2(x)}{\Phi(x)}= \lim_{x\rightarrow -\infty}\frac{\phi^2(x)+x\phi(x)\phi'(x)}{\phi(x)}= \lim_{x\rightarrow -\infty}\left[\phi(x)+x\phi'(x)\right]= \lim_{x\rightarrow -\infty}\left[1-\frac{x}{\sigma^2}\right]\phi(x)=0. $$Thus, the integral converges in the limit in question. Remarks: I appreciate @SextusEmpiricus remarks, which led to improvement of this answer. $$\phi(x)=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{x^2}{2\sigma^2}}$$
How to show that this integral of the normal distribution is finite? Intuitive approach $\Phi(x)$ is changing in the interval $[0,1]$, whereas $\phi(x)^2$ is itself a normal distribution which is integrable. Thus, the only reason why the integral could not be finite, i
11,423
How to show that this integral of the normal distribution is finite?
The integral on any interval $[a, \infty)$ is clearly finite. Now $\varphi(x)$ is convex on $(-\infty, -1]$ and so the tangent line to $\varphi$ at any $x < -1$ lies below $\varphi$. This tangent intersects the $x$-axis in $x+x^{-1}$. This gives the lower bound $$\Phi(x) > -\frac1{2x} \varphi(x)$$ for all $x < -1$ and so $$\frac{\varphi(x)^2}{\Phi(x)} < -2x \varphi(x)$$ for all $x<-1$. This shows that the integral over $(-\infty, -1]$ is also finite.
How to show that this integral of the normal distribution is finite?
The integral on any interval $[a, \infty)$ is clearly finite. Now $\varphi(x)$ is convex on $(-\infty, -1]$ and so the tangent line to $\varphi$ at any $x < -1$ lies below $\varphi$. This tangent int
How to show that this integral of the normal distribution is finite? The integral on any interval $[a, \infty)$ is clearly finite. Now $\varphi(x)$ is convex on $(-\infty, -1]$ and so the tangent line to $\varphi$ at any $x < -1$ lies below $\varphi$. This tangent intersects the $x$-axis in $x+x^{-1}$. This gives the lower bound $$\Phi(x) > -\frac1{2x} \varphi(x)$$ for all $x < -1$ and so $$\frac{\varphi(x)^2}{\Phi(x)} < -2x \varphi(x)$$ for all $x<-1$. This shows that the integral over $(-\infty, -1]$ is also finite.
How to show that this integral of the normal distribution is finite? The integral on any interval $[a, \infty)$ is clearly finite. Now $\varphi(x)$ is convex on $(-\infty, -1]$ and so the tangent line to $\varphi$ at any $x < -1$ lies below $\varphi$. This tangent int
11,424
What is the difference between SVM and LDA?
LDA: Assumes: data is Normally distributed. All groups are identically distributed, in case the groups have different covariance matrices, LDA becomes Quadratic Discriminant Analysis. LDA is the best discriminator available in case all assumptions are actually met. QDA, by the way, is a non-linear classifier. SVM: Generalizes the Optimally Separating Hyperplane(OSH). OSH assumes that all groups are totally separable, SVM makes use of a 'slack variable' that allows a certain amount of overlap between the groups. SVM makes no assumptions about the data at all, meaning it is a very flexible method. The flexibility on the other hand often makes it more difficult to interpret the results from a SVM classifier, compared to LDA. SVM classification is an optimization problem, LDA has an analytical solution. The optimization problem for the SVM has a dual and a primal formulation that allows the user to optimize over either the number of data points or the number of variables, depending on which method is the most computationally feasible. SVM can also make use of kernels to transform the SVM classifier from a linear classifier into a non-linear classifier. Use your favorite search engine to search for 'SVM kernel trick' to see how SVM makes use of kernels to transform the parameter space. LDA makes use of the entire data set to estimate covariance matrices and thus is somewhat prone to outliers. SVM is optimized over a subset of the data, which is those data points that lie on the separating margin. The data points used for optimization are called support vectors, because they determine how the SVM discriminate between groups, and thus support the classification. As far as I know, SVM doesn't really discriminate well between more than two classes. An outlier robust alternative is to use logistic classification. LDA handles several classes well, as long as the assumptions are met. I believe, though (warning: terribly unsubstantiated claim) that several old benchmarks found that LDA usually perform quite well under a lot of circumstances and LDA/QDA are often goto methods in the initial analysis. LDA can be used for feature selection when $p>n$ with sparse LDA: https://web.stanford.edu/~hastie/Papers/sda_resubm_daniela-final.pdf. SVM cannot perform feature selection. In short: LDA and SVM have very little in common. Luckily, they are both tremendously useful.
What is the difference between SVM and LDA?
LDA: Assumes: data is Normally distributed. All groups are identically distributed, in case the groups have different covariance matrices, LDA becomes Quadratic Discriminant Analysis. LDA is the best
What is the difference between SVM and LDA? LDA: Assumes: data is Normally distributed. All groups are identically distributed, in case the groups have different covariance matrices, LDA becomes Quadratic Discriminant Analysis. LDA is the best discriminator available in case all assumptions are actually met. QDA, by the way, is a non-linear classifier. SVM: Generalizes the Optimally Separating Hyperplane(OSH). OSH assumes that all groups are totally separable, SVM makes use of a 'slack variable' that allows a certain amount of overlap between the groups. SVM makes no assumptions about the data at all, meaning it is a very flexible method. The flexibility on the other hand often makes it more difficult to interpret the results from a SVM classifier, compared to LDA. SVM classification is an optimization problem, LDA has an analytical solution. The optimization problem for the SVM has a dual and a primal formulation that allows the user to optimize over either the number of data points or the number of variables, depending on which method is the most computationally feasible. SVM can also make use of kernels to transform the SVM classifier from a linear classifier into a non-linear classifier. Use your favorite search engine to search for 'SVM kernel trick' to see how SVM makes use of kernels to transform the parameter space. LDA makes use of the entire data set to estimate covariance matrices and thus is somewhat prone to outliers. SVM is optimized over a subset of the data, which is those data points that lie on the separating margin. The data points used for optimization are called support vectors, because they determine how the SVM discriminate between groups, and thus support the classification. As far as I know, SVM doesn't really discriminate well between more than two classes. An outlier robust alternative is to use logistic classification. LDA handles several classes well, as long as the assumptions are met. I believe, though (warning: terribly unsubstantiated claim) that several old benchmarks found that LDA usually perform quite well under a lot of circumstances and LDA/QDA are often goto methods in the initial analysis. LDA can be used for feature selection when $p>n$ with sparse LDA: https://web.stanford.edu/~hastie/Papers/sda_resubm_daniela-final.pdf. SVM cannot perform feature selection. In short: LDA and SVM have very little in common. Luckily, they are both tremendously useful.
What is the difference between SVM and LDA? LDA: Assumes: data is Normally distributed. All groups are identically distributed, in case the groups have different covariance matrices, LDA becomes Quadratic Discriminant Analysis. LDA is the best
11,425
What is the difference between SVM and LDA?
Short and sweet answer: The answers above are very thorough, so here is a quick description of how LDA and SVM work. Support vector machines find a linear separator (linear combination, hyperplane) that separates the classes with the least error, and chooses the separator with the maximum margin (the width that the boundary could be increased before hitting a data point). E.g. which linear separator best separates the classes? The one with the maximum margin: Linear discriminant analysis finds the mean vectors of each class, then finds projection direction (rotation) that maximizes separation of means: It also takes into account within-class variance to find a projection which minimizes overlap of distributions (covariance) while maximizing the separation of means:
What is the difference between SVM and LDA?
Short and sweet answer: The answers above are very thorough, so here is a quick description of how LDA and SVM work. Support vector machines find a linear separator (linear combination, hyperplane) th
What is the difference between SVM and LDA? Short and sweet answer: The answers above are very thorough, so here is a quick description of how LDA and SVM work. Support vector machines find a linear separator (linear combination, hyperplane) that separates the classes with the least error, and chooses the separator with the maximum margin (the width that the boundary could be increased before hitting a data point). E.g. which linear separator best separates the classes? The one with the maximum margin: Linear discriminant analysis finds the mean vectors of each class, then finds projection direction (rotation) that maximizes separation of means: It also takes into account within-class variance to find a projection which minimizes overlap of distributions (covariance) while maximizing the separation of means:
What is the difference between SVM and LDA? Short and sweet answer: The answers above are very thorough, so here is a quick description of how LDA and SVM work. Support vector machines find a linear separator (linear combination, hyperplane) th
11,426
What is the difference between SVM and LDA?
SVM focuses only on the points that are difficult to classify, LDA focuses on all data points. Such difficult points are close to the decision boundary and are called Support Vectors. The decision boundary can be linear, but also e.g. an RBF kernel, or an polynomial kernel. Where LDA is a linear transformation to maximize separability. LDA assumes that the data points have the same covariance and the probability density is assumed to be normally distributed. SVM has no such assumption. LDA is generative, SVM is discriminative.
What is the difference between SVM and LDA?
SVM focuses only on the points that are difficult to classify, LDA focuses on all data points. Such difficult points are close to the decision boundary and are called Support Vectors. The decision bou
What is the difference between SVM and LDA? SVM focuses only on the points that are difficult to classify, LDA focuses on all data points. Such difficult points are close to the decision boundary and are called Support Vectors. The decision boundary can be linear, but also e.g. an RBF kernel, or an polynomial kernel. Where LDA is a linear transformation to maximize separability. LDA assumes that the data points have the same covariance and the probability density is assumed to be normally distributed. SVM has no such assumption. LDA is generative, SVM is discriminative.
What is the difference between SVM and LDA? SVM focuses only on the points that are difficult to classify, LDA focuses on all data points. Such difficult points are close to the decision boundary and are called Support Vectors. The decision bou
11,427
What to conclude from this lasso plot (glmnet)
I think when trying to interpret these plots of coefficients by $\lambda$, $\log(\lambda)$, or $\sum_i | \beta_i |$, it helps a lot to know how they look in some simple cases. In particular, how they look when your model design matrix is uncorrelated, vs. when there is correlation in your design. To that end, I created some correlated and uncorrelated data to demonstrate: x_uncorr <- matrix(runif(30000), nrow=10000) y_uncorr <- 1 + 2*x_uncorr[,1] - x_uncorr[,2] + .5*x_uncorr[,3] sigma <- matrix(c( 1, -.5, 0, -.5, 1, -.5, 0, -.5, 1), nrow=3, byrow=TRUE ) x_corr <- x_uncorr %*% sqrtm(sigma) y_corr <- y_uncorr <- 1 + 2*x_corr[,1] - x_corr[,2] + .5*x_corr[,3] The data x_uncorr has uncorrelated columns > round(cor(x_uncorr), 2) [,1] [,2] [,3] [1,] 1.00 0.01 0.00 [2,] 0.01 1.00 -0.01 [3,] 0.00 -0.01 1.00 while x_corr has a pre-set correlation between the columns > round(cor(x_corr), 2) [,1] [,2] [,3] [1,] 1.00 -0.49 0.00 [2,] -0.49 1.00 -0.51 [3,] 0.00 -0.51 1.00 Now lets look at the lasso plots for both of these cases. First the uncorrelated data gnet_uncorr <- glmnet(x_uncorr, y_uncorr) plot(gnet_uncorr) A couple features stand out The predictors go into the model in the order of their magnitude of true linear regression coefficient. The coefficient path of each feature is a line (with respect to $\sum_i | \beta_i |$) is piecewise linear, and only changes when a new predictor enters the model. This is only true for the plot with respect to $\sum_i | \beta_i |$, and is a good reason to prefer it over the others. When a new predictor enters the model, it affects the slope of the coefficient path of all predictors already in the model in a deterministic way. For example, when the second predictor enters the model, the slope of the first coefficient path is cut in half. When the third predictor enters the model, the slope of the coefficient path is one third its original value. These are all general facts that apply to lasso regression with uncorrelated data, and they can all be either proven by hand (good exercise!) or found in the literature. Now lets do correlated data gnet_corr <- glmnet(x_corr, y_corr) plot(gnet_corr) You can read some things off this plot by comparing it to the uncorrelated case The first and second predictor paths have the same structure as the uncorrelated case until the third predictor enters the model, even though they are correlated. This is a special feature of the two predictor case, which I can explain in another answer if there is interest, it would take me a little far afield of the current discussion. On the other hand, once the third predictor enters the model, we see deviations from the picture we would expect if all three features were uncorrelated. The coefficient of the second feature flattens out, and the third feature rises to its final value. Notice the slope of the first feature is unaffected, which we would not anticipate if there were no correlations! Essentially, resources spend on the coefficients within a group of three or larger may be "traded around" until the assignment of minimal $\sum | \beta_i |$ is found. So now let's look at your plot from the cars dataset and read some interesting things off (I reproduced your plot here so this discussion is easier to read): A word of warning: I wrote the following analysis predicated on the assumption that the curves show the standardized coefficients, in this example they do not. Non-standardized coefficients are not dimensionless, and not comparable, so no conclusions may be drawn from them in terms of predictive importance. For the following analysis to be valid, please pretend that the plot is of the standardized coefficients, and please perform you own analysis on standardized coefficient paths. As you say, the wt predictor seems very important. It enters the model first, and has a slow and steady descent to its final value. It does have a few correlations that make it a slightly bumpy ride, am in particular seems to have a drastic effect when it enters. am is also important. It comes in later, and is correlated with wt, as it affects the slope of wt in a violent way. It is also correlated with carb and qsec, because we do not see the predictable softening of slope when those enter. After these four variables have entered though, we do see the nice uncorrelated pattern, so it seems to be uncorrelated with all the predictors at the end. Something enters at around 2.25 on the x-axis, but its path itself is imperceptible, you can only detect it by its affect to the cyl and wt parameters. cyl is quite facinating. It enters second, so is important for small models. After other variables, and especially am enter, it is not so important anymore, and its trend reverses, eventually being all but removed. It seems like the effect of cyl can be completely captured by the variables that enter at the end of the process. Whether it is more appropriate to use cyl, or the complementary group of variables, really depends on the bias-variance tradeoff. Having the group in your final model would increase its variance significantly, but it may be the case that the lower bias makes up for it! That's a small introduction to how I've learned to read information off of these plots. I think they are tons of fun! Thanks for a great analysis. To report in simple terms, would you say that wt, am and cyl are 3 most important predictors of mpg. Also, if you want to create a model for prediction, which ones will you include based on this figure: wt, am and cyl ? Or some other combination. Also, you do not seem to need best lambda for analysis. Is it not important as in ridge regression? I'd say the case for wt and am are clear cut, they are important. cyl is much more subtle, it is important in a small model, but not at all relevant in a large one. I would not be able to make a determination of what to include based only on the figure, that really must be answered the context of what you are doing. You could say that if you want a three predictor model, then wt, am and cyl are good choices, as they are relevant in the grand scheme of things, and should end up having reasonable effect sizes in a small model. This is predicated on the assumption that you have some external reason to desire a small three predictor model though. It's true, this type of analysis looks over the entire spectrum of lambdas and lets you cull relationships over a range of model complexities. That said, for a final model, I think tuning an optimal lambda is very important. In the absence of other constraints, I would definitely use cross validation to find where along this spectrum the most predictive lambda is, and then use that lambda for a final model, and a final analysis. The reason I recommend this has more to do with the right hand side of the graph than the left hand side. For some of the larger lambdas, it could be the case that the model is overfit to the training data. In this case, anything you deduced from the plot in this regime would be properties of the noise in the dataset instead of the structure of the statistical process itself. Once you have an estimate of the optimal $\lambda$, you have a sense for how much of the plot can be trusted. In the other direction, sometimes there are outside constraints for how complex a model can be (implementation costs, legacy systems, explanatory minimalism, business interpretability, aesthetic patrimony) and this kind of inspection can really help you understand the shape of your data, and the tradeoffs you are making by choosing a smaller than optimal model.
What to conclude from this lasso plot (glmnet)
I think when trying to interpret these plots of coefficients by $\lambda$, $\log(\lambda)$, or $\sum_i | \beta_i |$, it helps a lot to know how they look in some simple cases. In particular, how they
What to conclude from this lasso plot (glmnet) I think when trying to interpret these plots of coefficients by $\lambda$, $\log(\lambda)$, or $\sum_i | \beta_i |$, it helps a lot to know how they look in some simple cases. In particular, how they look when your model design matrix is uncorrelated, vs. when there is correlation in your design. To that end, I created some correlated and uncorrelated data to demonstrate: x_uncorr <- matrix(runif(30000), nrow=10000) y_uncorr <- 1 + 2*x_uncorr[,1] - x_uncorr[,2] + .5*x_uncorr[,3] sigma <- matrix(c( 1, -.5, 0, -.5, 1, -.5, 0, -.5, 1), nrow=3, byrow=TRUE ) x_corr <- x_uncorr %*% sqrtm(sigma) y_corr <- y_uncorr <- 1 + 2*x_corr[,1] - x_corr[,2] + .5*x_corr[,3] The data x_uncorr has uncorrelated columns > round(cor(x_uncorr), 2) [,1] [,2] [,3] [1,] 1.00 0.01 0.00 [2,] 0.01 1.00 -0.01 [3,] 0.00 -0.01 1.00 while x_corr has a pre-set correlation between the columns > round(cor(x_corr), 2) [,1] [,2] [,3] [1,] 1.00 -0.49 0.00 [2,] -0.49 1.00 -0.51 [3,] 0.00 -0.51 1.00 Now lets look at the lasso plots for both of these cases. First the uncorrelated data gnet_uncorr <- glmnet(x_uncorr, y_uncorr) plot(gnet_uncorr) A couple features stand out The predictors go into the model in the order of their magnitude of true linear regression coefficient. The coefficient path of each feature is a line (with respect to $\sum_i | \beta_i |$) is piecewise linear, and only changes when a new predictor enters the model. This is only true for the plot with respect to $\sum_i | \beta_i |$, and is a good reason to prefer it over the others. When a new predictor enters the model, it affects the slope of the coefficient path of all predictors already in the model in a deterministic way. For example, when the second predictor enters the model, the slope of the first coefficient path is cut in half. When the third predictor enters the model, the slope of the coefficient path is one third its original value. These are all general facts that apply to lasso regression with uncorrelated data, and they can all be either proven by hand (good exercise!) or found in the literature. Now lets do correlated data gnet_corr <- glmnet(x_corr, y_corr) plot(gnet_corr) You can read some things off this plot by comparing it to the uncorrelated case The first and second predictor paths have the same structure as the uncorrelated case until the third predictor enters the model, even though they are correlated. This is a special feature of the two predictor case, which I can explain in another answer if there is interest, it would take me a little far afield of the current discussion. On the other hand, once the third predictor enters the model, we see deviations from the picture we would expect if all three features were uncorrelated. The coefficient of the second feature flattens out, and the third feature rises to its final value. Notice the slope of the first feature is unaffected, which we would not anticipate if there were no correlations! Essentially, resources spend on the coefficients within a group of three or larger may be "traded around" until the assignment of minimal $\sum | \beta_i |$ is found. So now let's look at your plot from the cars dataset and read some interesting things off (I reproduced your plot here so this discussion is easier to read): A word of warning: I wrote the following analysis predicated on the assumption that the curves show the standardized coefficients, in this example they do not. Non-standardized coefficients are not dimensionless, and not comparable, so no conclusions may be drawn from them in terms of predictive importance. For the following analysis to be valid, please pretend that the plot is of the standardized coefficients, and please perform you own analysis on standardized coefficient paths. As you say, the wt predictor seems very important. It enters the model first, and has a slow and steady descent to its final value. It does have a few correlations that make it a slightly bumpy ride, am in particular seems to have a drastic effect when it enters. am is also important. It comes in later, and is correlated with wt, as it affects the slope of wt in a violent way. It is also correlated with carb and qsec, because we do not see the predictable softening of slope when those enter. After these four variables have entered though, we do see the nice uncorrelated pattern, so it seems to be uncorrelated with all the predictors at the end. Something enters at around 2.25 on the x-axis, but its path itself is imperceptible, you can only detect it by its affect to the cyl and wt parameters. cyl is quite facinating. It enters second, so is important for small models. After other variables, and especially am enter, it is not so important anymore, and its trend reverses, eventually being all but removed. It seems like the effect of cyl can be completely captured by the variables that enter at the end of the process. Whether it is more appropriate to use cyl, or the complementary group of variables, really depends on the bias-variance tradeoff. Having the group in your final model would increase its variance significantly, but it may be the case that the lower bias makes up for it! That's a small introduction to how I've learned to read information off of these plots. I think they are tons of fun! Thanks for a great analysis. To report in simple terms, would you say that wt, am and cyl are 3 most important predictors of mpg. Also, if you want to create a model for prediction, which ones will you include based on this figure: wt, am and cyl ? Or some other combination. Also, you do not seem to need best lambda for analysis. Is it not important as in ridge regression? I'd say the case for wt and am are clear cut, they are important. cyl is much more subtle, it is important in a small model, but not at all relevant in a large one. I would not be able to make a determination of what to include based only on the figure, that really must be answered the context of what you are doing. You could say that if you want a three predictor model, then wt, am and cyl are good choices, as they are relevant in the grand scheme of things, and should end up having reasonable effect sizes in a small model. This is predicated on the assumption that you have some external reason to desire a small three predictor model though. It's true, this type of analysis looks over the entire spectrum of lambdas and lets you cull relationships over a range of model complexities. That said, for a final model, I think tuning an optimal lambda is very important. In the absence of other constraints, I would definitely use cross validation to find where along this spectrum the most predictive lambda is, and then use that lambda for a final model, and a final analysis. The reason I recommend this has more to do with the right hand side of the graph than the left hand side. For some of the larger lambdas, it could be the case that the model is overfit to the training data. In this case, anything you deduced from the plot in this regime would be properties of the noise in the dataset instead of the structure of the statistical process itself. Once you have an estimate of the optimal $\lambda$, you have a sense for how much of the plot can be trusted. In the other direction, sometimes there are outside constraints for how complex a model can be (implementation costs, legacy systems, explanatory minimalism, business interpretability, aesthetic patrimony) and this kind of inspection can really help you understand the shape of your data, and the tradeoffs you are making by choosing a smaller than optimal model.
What to conclude from this lasso plot (glmnet) I think when trying to interpret these plots of coefficients by $\lambda$, $\log(\lambda)$, or $\sum_i | \beta_i |$, it helps a lot to know how they look in some simple cases. In particular, how they
11,428
Difference between Primal, Dual and Kernel Ridge Regression
Short answer: no difference between Primal and Dual - it's only about the way of arriving to the solution. Kernel ridge regression is essentially the same as usual ridge regression, but uses the kernel trick to go non-linear. Linear Regression First of all, a usual Least Squares Linear Regression tries to fit a straight line to the set of data points in such a way that the sum of squared errors is minimal. We parametrize the best fit line with $\mathbb w$ and for each data point $(\mathbf x_i, y_i)$ we want $\mathbf w^T \mathbf x_i \approx y_i$. Let $e_i = y_i - \mathbf w^T \mathbf x_i$ be the error - the distance between predicted and true values. So our goal is to minimize the sum of squared errors $\sum e_i^2 = \| \mathbf e \|^2 = \| X \mathbf w - \mathbf y \|^2$ where $X = \begin{bmatrix} — \mathbf x_1 \,— \\ — \mathbf x_2 \,— \\ \vdots \\ — \mathbf x_n \,— \end{bmatrix}$ - a data matrix with each $\mathbf x_i$ being a row, and $\mathbf y = (y_1 , \ ... \ , y_n)$ a vector with all $y_i$'s. Thus, the objective is $\min\limits_{\mathbf w} \| X \mathbf w - \mathbf y \|^2$, and the solution is $\mathbf w = (X^T X)^{-1} X^T \mathbf y$ (known as "Normal Equation"). For a new unseen data point $\mathbf x$ we predict its target value $\hat y$ as $\hat y = \mathbf w^T \mathbf x$. Ridge Regression When there are many correlated variables in linear regression models, the coefficients $\mathbf w$ can become poorly determined and have lots of variance. One of the solutions to this problem is to restrict weights $\mathbf w$ so they don't exceed some budget $C$. This is equivalent to using $L_2$-regularization, also known as "weight decay": it will decrease the variance at the cost of sometimes missing the correct results (i.e. by introducing some bias). The objective now becomes $\min\limits_{\mathbf w} \| X \mathbf w - y \|^2 + \lambda \, \| \mathbf w \|^2$, with $\lambda$ being the regularization parameter. By going through the math, we obtain the following solution: $\mathbf w = (X^T X + \lambda \, I )^{-1} X^T \mathbf y$. It's very similar to the usual linear regression, but here we add $\lambda$ to each diagonal element of $X^T X$. Note that we can re-write $\mathbf w$ as $\mathbf w = X^T \, (X X^T + \lambda \, I)^{-1} \mathbf y$ (see here for details). For a new unseen data point $\mathbf x$ we predict its target value $\hat y$ as $\hat y = \mathbf x^T \mathbf w = \mathbf x^T X^T \, (X X^T + \lambda \, I)^{-1} \mathbf y$. Let $\boldsymbol \alpha = (X X^T + \lambda \, I)^{-1} \mathbf y$. Then $\hat y = \mathbf x^T X^T \boldsymbol \alpha = \sum\limits_{i=1}^{n} \alpha_i \cdot \mathbf x^T \mathbf x_i$. Ridge Regression Dual Form We can have a different look at our objective - and define the following quadratic program problem: $\min\limits_{\mathbf e, \mathbf w} \sum\limits_{i = 1}^n e_i^2$ s.t. $e_i = y_i - \mathbf w^T \mathbf x_i$ for $i = 1 \, .. \, n$ and $\| \mathbf w \|^2 \leqslant C$. It's the same objective, but expressed somewhat differently, and here the constraint on the size of $\mathbf w$ is explicit. To solve it, we define the Lagrangian $\mathcal L_p(\mathbf w, \mathbf e ; C)$ - this is the primal form that contains primal variables $\mathbf w$ and $\mathbf e$. Then we optimize it w.r.t. $\mathbf e$ and $\mathbf w$. To get the dual formulation, we put found $\mathbf e$ and $\mathbf w$ back to $\mathcal L_p(\mathbf w, \mathbf e ; C)$. So, $\mathcal L_p(\mathbf w, \mathbf e ; C) = \| \mathbf e \|^2 + \boldsymbol \beta^T (\mathbf y - X \mathbf w - \mathbf e) - \lambda \, (\| \mathbf w \|^2 - C)$. By taking derivatives w.r.t. $\mathbf w$ and $\mathbf e$, we obtain $\mathbf e = \cfrac{1}{2} \boldsymbol \beta$ and $\mathbf w = \cfrac{1}{2 \lambda} X^T \boldsymbol \beta$. By letting $\boldsymbol \alpha = \cfrac{1}{2 \lambda} \boldsymbol \beta$, and putting $\mathbf e$ and $\mathbf w$ back to $\mathcal L_p(\mathbf w, \mathbf e ; C)$, we get dual Lagrangian $\mathcal L_d(\boldsymbol \alpha, \lambda; C) = -\lambda^2 \| \boldsymbol \alpha \|^2 + 2 \lambda \, \boldsymbol \alpha^T y - \lambda \| X^T \boldsymbol \alpha \| - \lambda C$. If we take a derivative w.r.t. $\boldsymbol \alpha$, we get $\boldsymbol \alpha = (XX^T - \lambda I)^{-1} \mathbf y$ - the same answer as for usual Kernel Ridge regression. There's no need to take a derivative w.r.t $\lambda$ - it depends on $C$, which is a regularization parameter - and it makes $\lambda$ regularization parameter as well. Next, put $\boldsymbol \alpha$ to the primal form solution for $\mathbf w$, and get $\mathbf w = \cfrac{1}{2 \lambda} X^T \boldsymbol \beta = X^T \boldsymbol \alpha$. Thus, the dual form gives the same solution as usual Ridge Regression, and it's just a different way to come to the same solution. Kernel Ridge Regression Kernels are used to calculate inner product of two vectors in some feature space without even visiting it. We can view a kernel $k$ as $k(\mathbf x_1, \mathbf x_2) = \phi(\mathbf x_1)^T \phi(\mathbf x_2)$, although we don't know what $\phi(\cdot)$ is - we only know it exists. There are many kernels, e.g. RBF, Polynonial, etc. We can use kernels to make our Ridge Regression non-linear. Suppose we have a kernel $k(\mathbf x_1, \mathbf x_2) = \phi(\mathbf x_1)^T \phi(\mathbf x_2)$. Let $\Phi(X)$ be a matrix where each row is $\phi(\mathbf x_i)$, i.e. $\Phi(X) = \begin{bmatrix} — \phi(\mathbf x_1) \,— \\ — \phi(\mathbf x_2) \,— \\ \vdots \\ — \phi(\mathbf x_n) \,— \end{bmatrix}$ Now we can just take the solution for Ridge Regression and replace every $X$ with $\Phi(X)$: $\mathbf w = \Phi(X)^T \, (\Phi(X) \Phi(X)^T + \lambda \, I)^{-1} \mathbf y$. For a new unseen data point $\mathbf x$ we predict its target value $\hat y$ as $\hat y= \mathbf \phi(\mathbf x)^T \Phi(X)^T \, (\Phi(X) \Phi(X)^T + \lambda \, I)^{-1} \mathbf y$. First, we can replace $\Phi(X) \Phi(X)^T$ by a matrix $K$, calculated as $(K)_{ij} = k(\mathbf x_i, \mathbf x_j)$. Then, $\phi(\mathbf x)^T \Phi(X)^T$ is $\sum\limits_{i = 1}^n \phi(\mathbf x)^T \phi(\mathbf x_i) = \sum\limits_{i = 1}^n k(\mathbf x, \mathbf x_j)$. So here we managed to express every dot product of the problem in terms of kernels. Finally, by letting $\boldsymbol \alpha = (K + \lambda \, I)^{-1} \mathbf y$ (as previously), we obtain $\hat y= \sum\limits_{i = 1}^n \alpha_i k(\mathbf x, \mathbf x_j)$ References Machine Learning I class at TU Berlin Elements of Statistical Learning, http://statweb.stanford.edu/~tibs/ElemStatLearn/ http://mlwiki.org/index.php/Normal_Equation http://stat.wikia.com/wiki/Kernel_Ridge_Regression http://stat.rutgers.edu/home/tzhang/papers/ml02_dual.pdf http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf http://www.cs.nyu.edu/~mohri/mls/lecture_8.pdf
Difference between Primal, Dual and Kernel Ridge Regression
Short answer: no difference between Primal and Dual - it's only about the way of arriving to the solution. Kernel ridge regression is essentially the same as usual ridge regression, but uses the kerne
Difference between Primal, Dual and Kernel Ridge Regression Short answer: no difference between Primal and Dual - it's only about the way of arriving to the solution. Kernel ridge regression is essentially the same as usual ridge regression, but uses the kernel trick to go non-linear. Linear Regression First of all, a usual Least Squares Linear Regression tries to fit a straight line to the set of data points in such a way that the sum of squared errors is minimal. We parametrize the best fit line with $\mathbb w$ and for each data point $(\mathbf x_i, y_i)$ we want $\mathbf w^T \mathbf x_i \approx y_i$. Let $e_i = y_i - \mathbf w^T \mathbf x_i$ be the error - the distance between predicted and true values. So our goal is to minimize the sum of squared errors $\sum e_i^2 = \| \mathbf e \|^2 = \| X \mathbf w - \mathbf y \|^2$ where $X = \begin{bmatrix} — \mathbf x_1 \,— \\ — \mathbf x_2 \,— \\ \vdots \\ — \mathbf x_n \,— \end{bmatrix}$ - a data matrix with each $\mathbf x_i$ being a row, and $\mathbf y = (y_1 , \ ... \ , y_n)$ a vector with all $y_i$'s. Thus, the objective is $\min\limits_{\mathbf w} \| X \mathbf w - \mathbf y \|^2$, and the solution is $\mathbf w = (X^T X)^{-1} X^T \mathbf y$ (known as "Normal Equation"). For a new unseen data point $\mathbf x$ we predict its target value $\hat y$ as $\hat y = \mathbf w^T \mathbf x$. Ridge Regression When there are many correlated variables in linear regression models, the coefficients $\mathbf w$ can become poorly determined and have lots of variance. One of the solutions to this problem is to restrict weights $\mathbf w$ so they don't exceed some budget $C$. This is equivalent to using $L_2$-regularization, also known as "weight decay": it will decrease the variance at the cost of sometimes missing the correct results (i.e. by introducing some bias). The objective now becomes $\min\limits_{\mathbf w} \| X \mathbf w - y \|^2 + \lambda \, \| \mathbf w \|^2$, with $\lambda$ being the regularization parameter. By going through the math, we obtain the following solution: $\mathbf w = (X^T X + \lambda \, I )^{-1} X^T \mathbf y$. It's very similar to the usual linear regression, but here we add $\lambda$ to each diagonal element of $X^T X$. Note that we can re-write $\mathbf w$ as $\mathbf w = X^T \, (X X^T + \lambda \, I)^{-1} \mathbf y$ (see here for details). For a new unseen data point $\mathbf x$ we predict its target value $\hat y$ as $\hat y = \mathbf x^T \mathbf w = \mathbf x^T X^T \, (X X^T + \lambda \, I)^{-1} \mathbf y$. Let $\boldsymbol \alpha = (X X^T + \lambda \, I)^{-1} \mathbf y$. Then $\hat y = \mathbf x^T X^T \boldsymbol \alpha = \sum\limits_{i=1}^{n} \alpha_i \cdot \mathbf x^T \mathbf x_i$. Ridge Regression Dual Form We can have a different look at our objective - and define the following quadratic program problem: $\min\limits_{\mathbf e, \mathbf w} \sum\limits_{i = 1}^n e_i^2$ s.t. $e_i = y_i - \mathbf w^T \mathbf x_i$ for $i = 1 \, .. \, n$ and $\| \mathbf w \|^2 \leqslant C$. It's the same objective, but expressed somewhat differently, and here the constraint on the size of $\mathbf w$ is explicit. To solve it, we define the Lagrangian $\mathcal L_p(\mathbf w, \mathbf e ; C)$ - this is the primal form that contains primal variables $\mathbf w$ and $\mathbf e$. Then we optimize it w.r.t. $\mathbf e$ and $\mathbf w$. To get the dual formulation, we put found $\mathbf e$ and $\mathbf w$ back to $\mathcal L_p(\mathbf w, \mathbf e ; C)$. So, $\mathcal L_p(\mathbf w, \mathbf e ; C) = \| \mathbf e \|^2 + \boldsymbol \beta^T (\mathbf y - X \mathbf w - \mathbf e) - \lambda \, (\| \mathbf w \|^2 - C)$. By taking derivatives w.r.t. $\mathbf w$ and $\mathbf e$, we obtain $\mathbf e = \cfrac{1}{2} \boldsymbol \beta$ and $\mathbf w = \cfrac{1}{2 \lambda} X^T \boldsymbol \beta$. By letting $\boldsymbol \alpha = \cfrac{1}{2 \lambda} \boldsymbol \beta$, and putting $\mathbf e$ and $\mathbf w$ back to $\mathcal L_p(\mathbf w, \mathbf e ; C)$, we get dual Lagrangian $\mathcal L_d(\boldsymbol \alpha, \lambda; C) = -\lambda^2 \| \boldsymbol \alpha \|^2 + 2 \lambda \, \boldsymbol \alpha^T y - \lambda \| X^T \boldsymbol \alpha \| - \lambda C$. If we take a derivative w.r.t. $\boldsymbol \alpha$, we get $\boldsymbol \alpha = (XX^T - \lambda I)^{-1} \mathbf y$ - the same answer as for usual Kernel Ridge regression. There's no need to take a derivative w.r.t $\lambda$ - it depends on $C$, which is a regularization parameter - and it makes $\lambda$ regularization parameter as well. Next, put $\boldsymbol \alpha$ to the primal form solution for $\mathbf w$, and get $\mathbf w = \cfrac{1}{2 \lambda} X^T \boldsymbol \beta = X^T \boldsymbol \alpha$. Thus, the dual form gives the same solution as usual Ridge Regression, and it's just a different way to come to the same solution. Kernel Ridge Regression Kernels are used to calculate inner product of two vectors in some feature space without even visiting it. We can view a kernel $k$ as $k(\mathbf x_1, \mathbf x_2) = \phi(\mathbf x_1)^T \phi(\mathbf x_2)$, although we don't know what $\phi(\cdot)$ is - we only know it exists. There are many kernels, e.g. RBF, Polynonial, etc. We can use kernels to make our Ridge Regression non-linear. Suppose we have a kernel $k(\mathbf x_1, \mathbf x_2) = \phi(\mathbf x_1)^T \phi(\mathbf x_2)$. Let $\Phi(X)$ be a matrix where each row is $\phi(\mathbf x_i)$, i.e. $\Phi(X) = \begin{bmatrix} — \phi(\mathbf x_1) \,— \\ — \phi(\mathbf x_2) \,— \\ \vdots \\ — \phi(\mathbf x_n) \,— \end{bmatrix}$ Now we can just take the solution for Ridge Regression and replace every $X$ with $\Phi(X)$: $\mathbf w = \Phi(X)^T \, (\Phi(X) \Phi(X)^T + \lambda \, I)^{-1} \mathbf y$. For a new unseen data point $\mathbf x$ we predict its target value $\hat y$ as $\hat y= \mathbf \phi(\mathbf x)^T \Phi(X)^T \, (\Phi(X) \Phi(X)^T + \lambda \, I)^{-1} \mathbf y$. First, we can replace $\Phi(X) \Phi(X)^T$ by a matrix $K$, calculated as $(K)_{ij} = k(\mathbf x_i, \mathbf x_j)$. Then, $\phi(\mathbf x)^T \Phi(X)^T$ is $\sum\limits_{i = 1}^n \phi(\mathbf x)^T \phi(\mathbf x_i) = \sum\limits_{i = 1}^n k(\mathbf x, \mathbf x_j)$. So here we managed to express every dot product of the problem in terms of kernels. Finally, by letting $\boldsymbol \alpha = (K + \lambda \, I)^{-1} \mathbf y$ (as previously), we obtain $\hat y= \sum\limits_{i = 1}^n \alpha_i k(\mathbf x, \mathbf x_j)$ References Machine Learning I class at TU Berlin Elements of Statistical Learning, http://statweb.stanford.edu/~tibs/ElemStatLearn/ http://mlwiki.org/index.php/Normal_Equation http://stat.wikia.com/wiki/Kernel_Ridge_Regression http://stat.rutgers.edu/home/tzhang/papers/ml02_dual.pdf http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf http://www.cs.nyu.edu/~mohri/mls/lecture_8.pdf
Difference between Primal, Dual and Kernel Ridge Regression Short answer: no difference between Primal and Dual - it's only about the way of arriving to the solution. Kernel ridge regression is essentially the same as usual ridge regression, but uses the kerne
11,429
What exactly is multi-hot encoding and how is it different from one-hot?
Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector like [0,1,0,0,0]. If you would use multi-hot-encoding you would first label-encode your classes, thus having only a single number which represents the presence of a class (e.g. 1 for 'dog') and then convert the numerical labels to binary vectors of size $\lceil\text{log}_25\rceil = 3$. Examples: 'cat' = [0,0,0] 'dog' = [0,0,1] 'fish' = [0,1,0] 'bird' = [0,1,1] 'ant' = [1,0,0] This representation is basically the middle way between label-encoding, where you introduce false class relationships (0 < 1 < 2 < ... < 4, thus 'cat' < 'dog' < ... < 'ant') but only need a single value to represent class presence and one-hot-encoding, where you need a vector of size $n$ (which can be huge!) to represent all classes but have no false relationships. Note: multi-hot-encoding introduces false additive relationships, e.g. [0,0,1] + [0,1,0] = [0,1,1] that is 'dog' + 'fish' = 'bird'. That is the price you pay for the reduced representation.
What exactly is multi-hot encoding and how is it different from one-hot?
Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector lik
What exactly is multi-hot encoding and how is it different from one-hot? Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector like [0,1,0,0,0]. If you would use multi-hot-encoding you would first label-encode your classes, thus having only a single number which represents the presence of a class (e.g. 1 for 'dog') and then convert the numerical labels to binary vectors of size $\lceil\text{log}_25\rceil = 3$. Examples: 'cat' = [0,0,0] 'dog' = [0,0,1] 'fish' = [0,1,0] 'bird' = [0,1,1] 'ant' = [1,0,0] This representation is basically the middle way between label-encoding, where you introduce false class relationships (0 < 1 < 2 < ... < 4, thus 'cat' < 'dog' < ... < 'ant') but only need a single value to represent class presence and one-hot-encoding, where you need a vector of size $n$ (which can be huge!) to represent all classes but have no false relationships. Note: multi-hot-encoding introduces false additive relationships, e.g. [0,0,1] + [0,1,0] = [0,1,1] that is 'dog' + 'fish' = 'bird'. That is the price you pay for the reduced representation.
What exactly is multi-hot encoding and how is it different from one-hot? Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector lik
11,430
What exactly is multi-hot encoding and how is it different from one-hot?
The accepted answer seems rather eccentric to me. I think that is rarely done, if ever, and will usually yield bad results. There's a much more common, sensible use case for this. "Multi-hot encoding" doesn't seem to be a standard term, but I'm not sure there's any standard term. scikit-learn refers to a multi label binarizer. This is simply used for multi label problems. That is, problems where more than one label can be associated with each example. For example, say you are trying to detect whether certain types of animal are in a photo. Note that multiple types of animal can be in a single photo. Say the possible types of animal are ['cat', 'dog', 'fish', 'bird', 'ant']. A photo containing cats and dogs would be represented as [1, 1, 0, 0, 0].
What exactly is multi-hot encoding and how is it different from one-hot?
The accepted answer seems rather eccentric to me. I think that is rarely done, if ever, and will usually yield bad results. There's a much more common, sensible use case for this. "Multi-hot encoding"
What exactly is multi-hot encoding and how is it different from one-hot? The accepted answer seems rather eccentric to me. I think that is rarely done, if ever, and will usually yield bad results. There's a much more common, sensible use case for this. "Multi-hot encoding" doesn't seem to be a standard term, but I'm not sure there's any standard term. scikit-learn refers to a multi label binarizer. This is simply used for multi label problems. That is, problems where more than one label can be associated with each example. For example, say you are trying to detect whether certain types of animal are in a photo. Note that multiple types of animal can be in a single photo. Say the possible types of animal are ['cat', 'dog', 'fish', 'bird', 'ant']. A photo containing cats and dogs would be represented as [1, 1, 0, 0, 0].
What exactly is multi-hot encoding and how is it different from one-hot? The accepted answer seems rather eccentric to me. I think that is rarely done, if ever, and will usually yield bad results. There's a much more common, sensible use case for this. "Multi-hot encoding"
11,431
What exactly is multi-hot encoding and how is it different from one-hot?
I too find the accepted answer likely wrong. I could not find any reference to such an encoding anywhere. In Tensorflow and in Francois Chollet's (the creator of Keras) book: "Deep learning with python", multi-hot is a binary encoding of multiple tokens in a single vector. Meaning, you can encode a text in a single vector, where all the entries are zero, except the entries corresponding to a word present in the text is one. Please see the Tensorflow category_encoding output_mode parameter's description at https://www.tensorflow.org/api_docs/python/tf/keras/layers/CategoryEncoding#args
What exactly is multi-hot encoding and how is it different from one-hot?
I too find the accepted answer likely wrong. I could not find any reference to such an encoding anywhere. In Tensorflow and in Francois Chollet's (the creator of Keras) book: "Deep learning with pytho
What exactly is multi-hot encoding and how is it different from one-hot? I too find the accepted answer likely wrong. I could not find any reference to such an encoding anywhere. In Tensorflow and in Francois Chollet's (the creator of Keras) book: "Deep learning with python", multi-hot is a binary encoding of multiple tokens in a single vector. Meaning, you can encode a text in a single vector, where all the entries are zero, except the entries corresponding to a word present in the text is one. Please see the Tensorflow category_encoding output_mode parameter's description at https://www.tensorflow.org/api_docs/python/tf/keras/layers/CategoryEncoding#args
What exactly is multi-hot encoding and how is it different from one-hot? I too find the accepted answer likely wrong. I could not find any reference to such an encoding anywhere. In Tensorflow and in Francois Chollet's (the creator of Keras) book: "Deep learning with pytho
11,432
In machine learning, why are superscripts used instead of subscripts?
If $x$ denotes a vector $x \in \mathbb R^m$ then $x_i$ is a standard notation for the $i$-th coordinate of $x$, i.e. $$x = (x_1, x_2, \ldots, x_m)\in\mathbb R^m.$$ If you have a collection of $n$ such vectors, how would you denote an $i$-th vector? You cannot write $x_i$, this has other standard meaning. So sometimes people write $x^{(i)}$ and that is I believe why Andrew Ng does it. I.e. \begin{equation} x^{(1)} = (x_1^{(1)}, x_2^{(1)}, \ldots, x_m^{(1)}) \in \mathbb R^m\\ x^{(2)} = (x_1^{(2)}, x_2^{(2)}, \ldots, x_m^{(2)}) \in \mathbb R^m\\ \ldots \\ x^{(n)} = (x_1^{(n)}, x_2^{(n)}, \ldots, x_m^{(n)}) \in \mathbb R^m.\\ \end{equation}
In machine learning, why are superscripts used instead of subscripts?
If $x$ denotes a vector $x \in \mathbb R^m$ then $x_i$ is a standard notation for the $i$-th coordinate of $x$, i.e. $$x = (x_1, x_2, \ldots, x_m)\in\mathbb R^m.$$ If you have a collection of $n$ such
In machine learning, why are superscripts used instead of subscripts? If $x$ denotes a vector $x \in \mathbb R^m$ then $x_i$ is a standard notation for the $i$-th coordinate of $x$, i.e. $$x = (x_1, x_2, \ldots, x_m)\in\mathbb R^m.$$ If you have a collection of $n$ such vectors, how would you denote an $i$-th vector? You cannot write $x_i$, this has other standard meaning. So sometimes people write $x^{(i)}$ and that is I believe why Andrew Ng does it. I.e. \begin{equation} x^{(1)} = (x_1^{(1)}, x_2^{(1)}, \ldots, x_m^{(1)}) \in \mathbb R^m\\ x^{(2)} = (x_1^{(2)}, x_2^{(2)}, \ldots, x_m^{(2)}) \in \mathbb R^m\\ \ldots \\ x^{(n)} = (x_1^{(n)}, x_2^{(n)}, \ldots, x_m^{(n)}) \in \mathbb R^m.\\ \end{equation}
In machine learning, why are superscripts used instead of subscripts? If $x$ denotes a vector $x \in \mathbb R^m$ then $x_i$ is a standard notation for the $i$-th coordinate of $x$, i.e. $$x = (x_1, x_2, \ldots, x_m)\in\mathbb R^m.$$ If you have a collection of $n$ such
11,433
In machine learning, why are superscripts used instead of subscripts?
The use of super scripts as you have stated I believe is not very common in machine learning literature. I'd have to review Ng's course notes to confirm, but if he's putting that use there, I would say he would be origin of the proliferation of this notation. This is a possibility. Either way, not to be too unkind, but I don't think many of the online course students are publishing literature on machine learning, so this notation is not very common in the actual literature. After all, these are introductory courses in machine learning, not PhD level courses. What is very common with super scripts is to denote the iteration of an algorithm using super scripts. For example, you could write an iteration of Newton's method as $ \theta^{(t+1)} = \theta^{(t)} - H(\theta^{(t)}) ^{-1} \nabla \theta^{(t)}$ where $ H(\theta^{(t)}) $ is the Hessian and $\nabla \theta^{(t)}$ is the gradient. (...yes this is not quite the best way to implement Newton's method due to the inversion of the Hessian matrix...) Here, $\theta^{(t)}$ represents the value of $\theta$ in the $t^{th}$ iteration. This is the most common (but certainly not only) use of super scripts that I am aware of. EDIT: To clarify, in the original question, it appeared to suggest that in the ML notation, $x^{(i)}$ was equivalent to statistic's $x_i$ notation. In my answer, I state that this is not truly prevalent in ML literature. This is true. However, as pointed out by @amoeba, there is plenty of superscript notation in ML literature for data, but in these cases $x^{(i)}$ does not typically mean the $i^{th}$ observation of a single vector $x$.
In machine learning, why are superscripts used instead of subscripts?
The use of super scripts as you have stated I believe is not very common in machine learning literature. I'd have to review Ng's course notes to confirm, but if he's putting that use there, I would sa
In machine learning, why are superscripts used instead of subscripts? The use of super scripts as you have stated I believe is not very common in machine learning literature. I'd have to review Ng's course notes to confirm, but if he's putting that use there, I would say he would be origin of the proliferation of this notation. This is a possibility. Either way, not to be too unkind, but I don't think many of the online course students are publishing literature on machine learning, so this notation is not very common in the actual literature. After all, these are introductory courses in machine learning, not PhD level courses. What is very common with super scripts is to denote the iteration of an algorithm using super scripts. For example, you could write an iteration of Newton's method as $ \theta^{(t+1)} = \theta^{(t)} - H(\theta^{(t)}) ^{-1} \nabla \theta^{(t)}$ where $ H(\theta^{(t)}) $ is the Hessian and $\nabla \theta^{(t)}$ is the gradient. (...yes this is not quite the best way to implement Newton's method due to the inversion of the Hessian matrix...) Here, $\theta^{(t)}$ represents the value of $\theta$ in the $t^{th}$ iteration. This is the most common (but certainly not only) use of super scripts that I am aware of. EDIT: To clarify, in the original question, it appeared to suggest that in the ML notation, $x^{(i)}$ was equivalent to statistic's $x_i$ notation. In my answer, I state that this is not truly prevalent in ML literature. This is true. However, as pointed out by @amoeba, there is plenty of superscript notation in ML literature for data, but in these cases $x^{(i)}$ does not typically mean the $i^{th}$ observation of a single vector $x$.
In machine learning, why are superscripts used instead of subscripts? The use of super scripts as you have stated I believe is not very common in machine learning literature. I'd have to review Ng's course notes to confirm, but if he's putting that use there, I would sa
11,434
In machine learning, why are superscripts used instead of subscripts?
Superscripts are already used for exponentiation. In mathematics superscripts are used left and right depending on the field. The choice is always historical legacy, nothing more. Whoever first got into the field set the convention of using sub- or superscripts. Two examples. Superscripts are used to denote derivatives: $f(x)^{(n)}$ In tensor algebra both super and subscripts are used heavily for the same thing like $R^i_i$ could mean $i$ rows and $j$ columns. It's quite expressive: $T_i^k=R_i^jC_j^k$ Also I remember using scripts before letters (prescripts) in Physics, e.g. $^i_jB_k^l$. I think it was with tensors. Hence, the choice of superscripts by Ng is purely historical too. There's no real reason to use or not use them, or prefer them to subscripts. Actually, I believe that here ML people are using tensor notation. They definitely are well versed in the subject, e.g. see this paper.
In machine learning, why are superscripts used instead of subscripts?
Superscripts are already used for exponentiation. In mathematics superscripts are used left and right depending on the field. The choice is always historical legacy, nothing more. Whoever first got
In machine learning, why are superscripts used instead of subscripts? Superscripts are already used for exponentiation. In mathematics superscripts are used left and right depending on the field. The choice is always historical legacy, nothing more. Whoever first got into the field set the convention of using sub- or superscripts. Two examples. Superscripts are used to denote derivatives: $f(x)^{(n)}$ In tensor algebra both super and subscripts are used heavily for the same thing like $R^i_i$ could mean $i$ rows and $j$ columns. It's quite expressive: $T_i^k=R_i^jC_j^k$ Also I remember using scripts before letters (prescripts) in Physics, e.g. $^i_jB_k^l$. I think it was with tensors. Hence, the choice of superscripts by Ng is purely historical too. There's no real reason to use or not use them, or prefer them to subscripts. Actually, I believe that here ML people are using tensor notation. They definitely are well versed in the subject, e.g. see this paper.
In machine learning, why are superscripts used instead of subscripts? Superscripts are already used for exponentiation. In mathematics superscripts are used left and right depending on the field. The choice is always historical legacy, nothing more. Whoever first got
11,435
What happens when I include a squared variable in my regression?
Well, first of, the dummy variable is interpreted as a change in intercept. That is, your coefficient $\beta_3$ gives you the difference in the intercept when $D=1$, i.e. when $D=1$, the intercept is $\beta_0 + \beta_3$. That interpretation doesn't change when adding the squared $x_1$. Now, the point of adding a squared to the series is that you assume that the relationship wears off at a certain point. Looking at your second equation $$y = \beta _0 + \beta_1x_1+\beta_2x_1^2+\beta_3 D + \varepsilon$$ Taking the derivate w.r.t. $x_1$ yields $$\frac{\delta y}{\delta x_1} = \beta_1 + 2\beta_2 x_1$$ Solving this equation gives you the turning point of the relationship. As user1493368 explained, this is indeed reflecting an inverse U-shape if $\beta_1<0$ and vice versa. Take the following example: $$\hat{y} = 1.3 + 0.42 x_1 - 0.32 x_1^2 + 0.14D$$ The derivative w.r.t. $x_1$ is $$\frac{\delta y}{\delta x_1} = 0.42 - 2*0.32 x_1 $$ Solving for $x_1$ gives you $$\frac{\delta y}{\delta x_1} = 0 \iff x_1 \approx 0.66 $$ That is the point at which the relationship has its turning point. You can take a look at Wolfram-Alpha's output for the above function, for some visualization of your problem. Remember, when interpreting the ceteris paribus effect of a change in $x_1$ on $y$, you have to look at the equation: $$\Delta y = (\beta_1 + 2\beta_2x_1)\Delta x$$ That is, you can not interpret $\beta_1$ in isolation, once you added the squared regressor $x_1^2$! Regarding your insignificant $D$ after including the squared $x_1$, it points towards misspecification bias.
What happens when I include a squared variable in my regression?
Well, first of, the dummy variable is interpreted as a change in intercept. That is, your coefficient $\beta_3$ gives you the difference in the intercept when $D=1$, i.e. when $D=1$, the intercept is
What happens when I include a squared variable in my regression? Well, first of, the dummy variable is interpreted as a change in intercept. That is, your coefficient $\beta_3$ gives you the difference in the intercept when $D=1$, i.e. when $D=1$, the intercept is $\beta_0 + \beta_3$. That interpretation doesn't change when adding the squared $x_1$. Now, the point of adding a squared to the series is that you assume that the relationship wears off at a certain point. Looking at your second equation $$y = \beta _0 + \beta_1x_1+\beta_2x_1^2+\beta_3 D + \varepsilon$$ Taking the derivate w.r.t. $x_1$ yields $$\frac{\delta y}{\delta x_1} = \beta_1 + 2\beta_2 x_1$$ Solving this equation gives you the turning point of the relationship. As user1493368 explained, this is indeed reflecting an inverse U-shape if $\beta_1<0$ and vice versa. Take the following example: $$\hat{y} = 1.3 + 0.42 x_1 - 0.32 x_1^2 + 0.14D$$ The derivative w.r.t. $x_1$ is $$\frac{\delta y}{\delta x_1} = 0.42 - 2*0.32 x_1 $$ Solving for $x_1$ gives you $$\frac{\delta y}{\delta x_1} = 0 \iff x_1 \approx 0.66 $$ That is the point at which the relationship has its turning point. You can take a look at Wolfram-Alpha's output for the above function, for some visualization of your problem. Remember, when interpreting the ceteris paribus effect of a change in $x_1$ on $y$, you have to look at the equation: $$\Delta y = (\beta_1 + 2\beta_2x_1)\Delta x$$ That is, you can not interpret $\beta_1$ in isolation, once you added the squared regressor $x_1^2$! Regarding your insignificant $D$ after including the squared $x_1$, it points towards misspecification bias.
What happens when I include a squared variable in my regression? Well, first of, the dummy variable is interpreted as a change in intercept. That is, your coefficient $\beta_3$ gives you the difference in the intercept when $D=1$, i.e. when $D=1$, the intercept is
11,436
What happens when I include a squared variable in my regression?
A good example of including square of variable comes from labor economics. If you assume y as wage (or log of wage) and x as an age, then including x^2 means that you are testing the quadratic relationship between an age and wage earning. Wage increases with the age as people become more experienced but at the higher age, wage starts to increase at decreasing rate (people becomes older and they will not be so healthy to work as before) and at some point the wage doesn't grow (reaches the optimal wage level) and then starts to fall (they retire and their earnings starts to decrease). So, the relationship between wage and age is inverted U-shaped (life cycle effect). In general, for the example mentioned here, the coefficient on age is expected to be positive and than on age^2 to be negative.The point here is that there should be theoretical basis /empirical justification for including the square of the variable. The dummy variable, here, can be thought of as representing gender of the worker. You can also include interaction term of gender and age to examine the whether the gender differential varies by age.
What happens when I include a squared variable in my regression?
A good example of including square of variable comes from labor economics. If you assume y as wage (or log of wage) and x as an age, then including x^2 means that you are testing the quadratic relatio
What happens when I include a squared variable in my regression? A good example of including square of variable comes from labor economics. If you assume y as wage (or log of wage) and x as an age, then including x^2 means that you are testing the quadratic relationship between an age and wage earning. Wage increases with the age as people become more experienced but at the higher age, wage starts to increase at decreasing rate (people becomes older and they will not be so healthy to work as before) and at some point the wage doesn't grow (reaches the optimal wage level) and then starts to fall (they retire and their earnings starts to decrease). So, the relationship between wage and age is inverted U-shaped (life cycle effect). In general, for the example mentioned here, the coefficient on age is expected to be positive and than on age^2 to be negative.The point here is that there should be theoretical basis /empirical justification for including the square of the variable. The dummy variable, here, can be thought of as representing gender of the worker. You can also include interaction term of gender and age to examine the whether the gender differential varies by age.
What happens when I include a squared variable in my regression? A good example of including square of variable comes from labor economics. If you assume y as wage (or log of wage) and x as an age, then including x^2 means that you are testing the quadratic relatio
11,437
Monty Hall Problem with a Fallible Monty
Let's start with the regular Monty Hall problem. Three doors, behind one of which is a car. The other two have goats behind them. You pick door number 1 and Monty opens door number 2 to show you there is a goat behind that one. Should you switch your guess to door number 3? (Note that the numbers we use to refer to each door don't matter here. We could choose any order and the problem is the same, so to simplify things we can just use this numbering.) The answer of course is yes, as you already know, but let's go through the calculations to see how they change later. Let $C$ be the index of the door with the car and $M$ denote the event that Monty revealed that door 2 has a goat. We need to calculate $p(C=3|M)$. If this is larger than $1/2$, we need to switch our guess to that door (since we only have two remaining options). This probability is given by: $$ p(C=3|M)=\frac{p(M|C=3)}{p(M|C=1)+p(M|C=2)+p(M|C=3)} $$ (This is just applying Bayes' rule with a flat prior on $C$.) $p(M|C=3)$ equals 1: if the car is behind door number 3 then Monty had no choice but to open door number 2 as he did. $p(M|C=1)$ equals $1/2$: if the car is behind door 1, then Monty had a choice of opening either one of the remaining doors, 2 or 3. $p(M|C=2)$ equals 0, because Monty never opens the door that he knows has the car. Filling in these numbers, we get: $$ p(C=3|M)=\frac{1}{0.5+0+1}=\frac{2}{3} $$ Which is the result we're familiar with. Now let's consider the case where Monty doesn't have perfect knowledge of which door has the car. So, when he chooses his door (which we'll keep referring to as door number 2), he might accidentally choose the one with the car, because he thinks it has a goat. Let $C'$ be the door that Monty thinks has the car, and let $p(C'|C)$ be the probability that he thinks the car is in a certain place, conditional on its actual location. We'll assume that this is described by a single parameter $q$ that determines his accuracy, such that: $p(C'=x|C=x) = q = 1-p(C'\neq x|C=x)$. If $q$ equals 1, Monty is always right. If $q$ is 0, Monty is always wrong (which is still informative). If $q$ is $1/3$, Monty's information is no better than random guessing. This means that we now have: $$p(M|C=3) = \sum_x p(M|C'=x)p(C'=x|C=3)$$ $$= p(M|C'=1)p(C'=1|C=3) + p(M|C'=2)p(C'=2|C=3) + p(M|C'=3)p(C'=3|C=3)$$ $$= \frac{1}{2} \times \frac{1}{2}(1-q) + 0\times \frac{1}{2}(1-q) + 1 \times q$$ $$= \frac{1}{4} - \frac{q}{4} + q = \frac{3}{4}q+\frac{1}{4}$$ That is, if the car was truly behind door 3, there were three possibilities that could have played out: (1) Monty thought it was behind 1, (2) Monty thought 2 or (3) Monty thought 3. The last option occurs with probability $q$ (how often he gets it right), the other two split the probability that he gets it wrong $(1-q)$ between them. Then, given each scenario, what's the probability that he would have chosen to point at door number 2, as he did? If he thought the car was behind 1, that probability was 1 in 2, as he could have chosen 2 or 3. If he thought it was behind 2, he would have never chosen to point at 2. If he thought it was behind 3, he would always have chosen 2. We can similarly work out the remaining probabilities: $$p(M|C=1) = \sum_x p(M|C'=x)p(C'=x|C=1)$$ $$=\frac{1}{2}\times q + 1\times \frac{1}{2}(1-q)$$ $$=\frac{q}{2}+\frac{1}{2}-\frac{q}{2}=\frac{1}{2}$$ $$p(M|C=2) = \sum_x p(M|C'=x)p(C'=x|C=2)$$ $$=\frac{1}{2}\times\frac{1}{2}(1-q) + 1 \times\frac{1}{2}(1-q)$$ $$=\frac{3}{4}-\frac{3}{4}q$$ Filling this all in, we get: $$ p(C=3|M)=\frac{\frac{3}{4}q+\frac{1}{4}}{\frac{1}{2}+\frac{3}{4}-\frac{3}{4}q+\frac{3}{4}q+\frac{1}{4}} $$ $$ =\frac{0.75q+0.25}{1.5} $$ As a sanity check, when $q=1$, we can see that we get back our original answer of $\frac{1}{1.5}=\frac{2}{3}$. So, when should we switch? I'll assume for simplicity that we're not allowed to switch to the door Monty pointed to. And in fact, as long as Monty is at least somewhat likely to be correct (more so than random guessing), the door he points to will always be less likely than the others to have the car, so this isn't a viable option for us anyway. So we only need to consider the probabilities of doors 1 and 3. But whereas it used to be impossible for the car to be behind door 2, this option now has non-zero probability, and so it's no longer the case that we should switch when $p(C=3|M)>0.5$, but rather we should switch when $p(C=3|M)>p(C=1|M)$ (which used to be the same thing). This probability is given by $p(C=1|M)=\frac{0.5}{1.5}=\frac{1}{3}$, same as in the original Monty Hall problem. (This makes sense since Monty can never point towards door 1, regardless of what's behind it, and so he cannot provide information about that door. Rather, when his accuracy drops below 100%, the effect is that some probability "leaks" towards door 2 actually having the car.) So, we need to find $q$ such that $p(C=3|M) > \frac{1}{3}$: $$\frac{0.75q+0.25}{1.5}>\frac{1}{3}$$ $$0.75q+0.25 > 0.5$$ $$0.75q > 0.25$$ $$q > \frac{1}{3}$$ So basically, this was a very long-winded way to find out that, as long as Monty's knowledge about the car's true location is better than a random guess, you should switch doors (which is actually kind of obvious, when you think about it). We can also calculate how much more likely we are to win when we switch, as a function of Monty's accuracy, as this is given by: $$\frac{p(C=3|M)}{p(C=1|M)}$$ $$=\frac{\frac{0.75q+0.25}{1.5}}{\frac{1}{3}}=1.5q+0.5$$ (Which, when $q=1$, gives an answer of 2, matching the fact that we double our chances of winning by switching doors in the original Monty Hall problem.) Edit: People were asking about the scenario where we are allowed to switch to the door that Monty points to, which becomes advantageous when $q<\frac{1}{3}$, i.e. when Monty is a (somewhat) reliable "liar". In the most extreme scenario, when $q=0$, this means the door Monty thinks has the car actually for sure has a goat. Note, though, that the remaining two doors could still have either a car or a goat. The benefit of switching to door 2 is given by: $$ \frac{p(C=2|M)}{p(C=1|M)} = \frac{ \frac{0.75 - 0.75q}{1.5} } { \frac{1}{3} } = 1.5-1.5q $$ Which is only larger than 1 (and thus worth switching to that door) if $1.5q<0.5$, i.e. if $q<\frac{1}{3}$, which we already established was the tipping point. Interestingly, the maximum possible benefit for switching to door 2, when $q=0$, is only 1.5, as compared to a doubling of your winning odds in the original Monty Hall problem (when $q=1$). The general solution is given by combining these two switching strategies: when $q>\frac{1}{3}$, you always switch to door 3; otherwise, switch to door 2.
Monty Hall Problem with a Fallible Monty
Let's start with the regular Monty Hall problem. Three doors, behind one of which is a car. The other two have goats behind them. You pick door number 1 and Monty opens door number 2 to show you there
Monty Hall Problem with a Fallible Monty Let's start with the regular Monty Hall problem. Three doors, behind one of which is a car. The other two have goats behind them. You pick door number 1 and Monty opens door number 2 to show you there is a goat behind that one. Should you switch your guess to door number 3? (Note that the numbers we use to refer to each door don't matter here. We could choose any order and the problem is the same, so to simplify things we can just use this numbering.) The answer of course is yes, as you already know, but let's go through the calculations to see how they change later. Let $C$ be the index of the door with the car and $M$ denote the event that Monty revealed that door 2 has a goat. We need to calculate $p(C=3|M)$. If this is larger than $1/2$, we need to switch our guess to that door (since we only have two remaining options). This probability is given by: $$ p(C=3|M)=\frac{p(M|C=3)}{p(M|C=1)+p(M|C=2)+p(M|C=3)} $$ (This is just applying Bayes' rule with a flat prior on $C$.) $p(M|C=3)$ equals 1: if the car is behind door number 3 then Monty had no choice but to open door number 2 as he did. $p(M|C=1)$ equals $1/2$: if the car is behind door 1, then Monty had a choice of opening either one of the remaining doors, 2 or 3. $p(M|C=2)$ equals 0, because Monty never opens the door that he knows has the car. Filling in these numbers, we get: $$ p(C=3|M)=\frac{1}{0.5+0+1}=\frac{2}{3} $$ Which is the result we're familiar with. Now let's consider the case where Monty doesn't have perfect knowledge of which door has the car. So, when he chooses his door (which we'll keep referring to as door number 2), he might accidentally choose the one with the car, because he thinks it has a goat. Let $C'$ be the door that Monty thinks has the car, and let $p(C'|C)$ be the probability that he thinks the car is in a certain place, conditional on its actual location. We'll assume that this is described by a single parameter $q$ that determines his accuracy, such that: $p(C'=x|C=x) = q = 1-p(C'\neq x|C=x)$. If $q$ equals 1, Monty is always right. If $q$ is 0, Monty is always wrong (which is still informative). If $q$ is $1/3$, Monty's information is no better than random guessing. This means that we now have: $$p(M|C=3) = \sum_x p(M|C'=x)p(C'=x|C=3)$$ $$= p(M|C'=1)p(C'=1|C=3) + p(M|C'=2)p(C'=2|C=3) + p(M|C'=3)p(C'=3|C=3)$$ $$= \frac{1}{2} \times \frac{1}{2}(1-q) + 0\times \frac{1}{2}(1-q) + 1 \times q$$ $$= \frac{1}{4} - \frac{q}{4} + q = \frac{3}{4}q+\frac{1}{4}$$ That is, if the car was truly behind door 3, there were three possibilities that could have played out: (1) Monty thought it was behind 1, (2) Monty thought 2 or (3) Monty thought 3. The last option occurs with probability $q$ (how often he gets it right), the other two split the probability that he gets it wrong $(1-q)$ between them. Then, given each scenario, what's the probability that he would have chosen to point at door number 2, as he did? If he thought the car was behind 1, that probability was 1 in 2, as he could have chosen 2 or 3. If he thought it was behind 2, he would have never chosen to point at 2. If he thought it was behind 3, he would always have chosen 2. We can similarly work out the remaining probabilities: $$p(M|C=1) = \sum_x p(M|C'=x)p(C'=x|C=1)$$ $$=\frac{1}{2}\times q + 1\times \frac{1}{2}(1-q)$$ $$=\frac{q}{2}+\frac{1}{2}-\frac{q}{2}=\frac{1}{2}$$ $$p(M|C=2) = \sum_x p(M|C'=x)p(C'=x|C=2)$$ $$=\frac{1}{2}\times\frac{1}{2}(1-q) + 1 \times\frac{1}{2}(1-q)$$ $$=\frac{3}{4}-\frac{3}{4}q$$ Filling this all in, we get: $$ p(C=3|M)=\frac{\frac{3}{4}q+\frac{1}{4}}{\frac{1}{2}+\frac{3}{4}-\frac{3}{4}q+\frac{3}{4}q+\frac{1}{4}} $$ $$ =\frac{0.75q+0.25}{1.5} $$ As a sanity check, when $q=1$, we can see that we get back our original answer of $\frac{1}{1.5}=\frac{2}{3}$. So, when should we switch? I'll assume for simplicity that we're not allowed to switch to the door Monty pointed to. And in fact, as long as Monty is at least somewhat likely to be correct (more so than random guessing), the door he points to will always be less likely than the others to have the car, so this isn't a viable option for us anyway. So we only need to consider the probabilities of doors 1 and 3. But whereas it used to be impossible for the car to be behind door 2, this option now has non-zero probability, and so it's no longer the case that we should switch when $p(C=3|M)>0.5$, but rather we should switch when $p(C=3|M)>p(C=1|M)$ (which used to be the same thing). This probability is given by $p(C=1|M)=\frac{0.5}{1.5}=\frac{1}{3}$, same as in the original Monty Hall problem. (This makes sense since Monty can never point towards door 1, regardless of what's behind it, and so he cannot provide information about that door. Rather, when his accuracy drops below 100%, the effect is that some probability "leaks" towards door 2 actually having the car.) So, we need to find $q$ such that $p(C=3|M) > \frac{1}{3}$: $$\frac{0.75q+0.25}{1.5}>\frac{1}{3}$$ $$0.75q+0.25 > 0.5$$ $$0.75q > 0.25$$ $$q > \frac{1}{3}$$ So basically, this was a very long-winded way to find out that, as long as Monty's knowledge about the car's true location is better than a random guess, you should switch doors (which is actually kind of obvious, when you think about it). We can also calculate how much more likely we are to win when we switch, as a function of Monty's accuracy, as this is given by: $$\frac{p(C=3|M)}{p(C=1|M)}$$ $$=\frac{\frac{0.75q+0.25}{1.5}}{\frac{1}{3}}=1.5q+0.5$$ (Which, when $q=1$, gives an answer of 2, matching the fact that we double our chances of winning by switching doors in the original Monty Hall problem.) Edit: People were asking about the scenario where we are allowed to switch to the door that Monty points to, which becomes advantageous when $q<\frac{1}{3}$, i.e. when Monty is a (somewhat) reliable "liar". In the most extreme scenario, when $q=0$, this means the door Monty thinks has the car actually for sure has a goat. Note, though, that the remaining two doors could still have either a car or a goat. The benefit of switching to door 2 is given by: $$ \frac{p(C=2|M)}{p(C=1|M)} = \frac{ \frac{0.75 - 0.75q}{1.5} } { \frac{1}{3} } = 1.5-1.5q $$ Which is only larger than 1 (and thus worth switching to that door) if $1.5q<0.5$, i.e. if $q<\frac{1}{3}$, which we already established was the tipping point. Interestingly, the maximum possible benefit for switching to door 2, when $q=0$, is only 1.5, as compared to a doubling of your winning odds in the original Monty Hall problem (when $q=1$). The general solution is given by combining these two switching strategies: when $q>\frac{1}{3}$, you always switch to door 3; otherwise, switch to door 2.
Monty Hall Problem with a Fallible Monty Let's start with the regular Monty Hall problem. Three doors, behind one of which is a car. The other two have goats behind them. You pick door number 1 and Monty opens door number 2 to show you there
11,438
Monty Hall Problem with a Fallible Monty
This should be a fairly simple variation of the problem (though I note your limited maths background, so I guess that is relative). I would suggest that you first try to determine the solution conditional on whether Monte is infallible, or fully fallible. The first case is just the ordinary Monte Hall problem, so no work required there. In the second case, you would treat the door he picks as being random over all the doors, including the door with the prize (i.e., he might still pick a door with no prize, but this is now random). If you can calculate the probability of a win in each of these cases then you an use the law of total probability to determine the relevant win probabilities in the case where Monte has some specified level of fallibility (specified by a probability that we is infallible versus fully fallible).
Monty Hall Problem with a Fallible Monty
This should be a fairly simple variation of the problem (though I note your limited maths background, so I guess that is relative). I would suggest that you first try to determine the solution condit
Monty Hall Problem with a Fallible Monty This should be a fairly simple variation of the problem (though I note your limited maths background, so I guess that is relative). I would suggest that you first try to determine the solution conditional on whether Monte is infallible, or fully fallible. The first case is just the ordinary Monte Hall problem, so no work required there. In the second case, you would treat the door he picks as being random over all the doors, including the door with the prize (i.e., he might still pick a door with no prize, but this is now random). If you can calculate the probability of a win in each of these cases then you an use the law of total probability to determine the relevant win probabilities in the case where Monte has some specified level of fallibility (specified by a probability that we is infallible versus fully fallible).
Monty Hall Problem with a Fallible Monty This should be a fairly simple variation of the problem (though I note your limited maths background, so I guess that is relative). I would suggest that you first try to determine the solution condit
11,439
Monty Hall Problem with a Fallible Monty
Based on the comments on Ben's answer, I am going to offer up two different interpretations of this variant of Monty Hall, differing to Ruben van Bergen's. The first one I am going to call Liar Monty and the second one Unreliable Monty. In both versions the problem proceeds as follows: (0) There are three doors, behind one of which is a car and behind the other two are goats, distributed randomly. (1) Contestant chooses a door at random. (2) Monty picks a door different to the contestant's door and claims a goat is behind it. (3) Contestant is offered to switch to the third unpicked door, and the problem is "When should the contestant switch in order to maximise the probability of finding a car behind the door?" In Liar Monty, at step (2), if the contestant has picked a door containing a goat, then Monty picks a door containing the car with some predefined probability (i.e. there is a chance between 0 and 100% that he will lie that a goat is behind some door). Note that in this variant, Monty never picks a door containing the car (i.e. cannot lie) if the contestant chose the car in step (1). In Unreliable Monty, there is a predefined probability that the door Monty pick's in step (2) contains a car. I take from your comment on Ben's answer that this is the scenario you are interested in, and both of my versions differ from Ruben van Bergen's. Note that Unreliable Monty is not the same as Liar Monty; we will rigorously differentiate between these two cases later. But consider this, in this scenario, Monty's door can never contain the car more than $\frac{2}{3}$ of the time, since the contestant has a probability of choosing the car $\frac{1}{3}$ of the time. To answer the problem, we are going to have to use some equations. I am going to try and phrase my answer so that it is accessible. The two things that I hope are not too confusing are algebraic manipulation of symbols, and conditional probability. For the former, we will use symbols to denote the following: $$\begin{split} S &= \text{The car is behind the door the contestant can switch to.}\\ \bar{S} &= \text{The car is not behind the door the contestant can switch to.}\\ M &= \text{The car is behind the door Monty chose.}\\ \bar{M} &= \text{The car is not behind the door Monty chose.}\\ C &= \text{The car is behind the door the contestant chose in step (1).}\\ \bar{C} &= \text{The car is not behind the door the contestant chose in step (1).} \end{split} $$ We use $\Pr(*)$ to denote "the probability of $*$", so that, put together, something like $\Pr(\bar{M})$ means the probability that the car is not behind the door Monty chose. (I.e. wherever you see an expression involving the symbols, replace the symbols with the "English" equivalents.) We will also require some rudimentary understanding of conditional probability, which is roughly the probability of something happening if you have knowledge of another related event. This probability will be represented here by expressions such as $\Pr(S|\bar{M})$. The vertical bar $|$ can be thought of as the expression "if you know", so that $\Pr(S|\bar{M})$ can be read as "the probability that the door the contestant can switch to has the car, if you know that the car is not behind Monty's door. In the original Monty Hall problem, $\Pr(S|\bar{M}) = \frac{2}{3}$, which is larger than $\Pr(S) = \frac{1}{3}$, which corresponds to the case when Monty has not given you any information. I will now demonstrate that Unreliable Monty is equivalent to Liar Monty. In Liar Monty, we are given the quantity $\Pr(M|\bar{C})$, the probability that Monty will lie about his door, knowing that the contestant has not chosen the car. In Unreliable Monty, we are given the quantity $\Pr(M)$, the probability that Monty lies about his door. Using the definition of conditional probability $\Pr(M \text{ and } \bar{C}) = \Pr(\bar{C} | M) \Pr(M) = \Pr(M | \bar{C}) \Pr(\bar{C})$, and rearranging, we obtain: $$ \begin{split} \Pr(M) &= \frac{\Pr(M | \bar{C}) \Pr(\bar{C})}{\Pr(\bar{C} | M)}\\ \frac{3}{2} \Pr(M) &= \Pr(M | \bar{C}), \end{split}$$ since $\Pr(\bar{C})$, the probability that the car is not behind the contestant's chosen door is $\frac{2}{3}$ and $\Pr(\bar{C} | M)$, the probability that the car is not behind the contestant's chosen door, if we know that it is behind Monty's door, is one. Thus, we have shown the connection between Unreliable Monty (represented by LHS of the above equation) and Liar Monty (represented by the RHS). In the extreme case of Unreliable Monty, where Monty chooses a door that hides the car $\frac{2}{3}$ of the time, this is equivalent to Monty lying all the time in Liar Monty, if the contestant has picked a goat originally. Having shown this, I will now provide enough information to answer the Liar version of the Monty Hall Problem. We want to calculate $\Pr(S)$. Using the law of total probability: $$\begin{split} \Pr(S) &= \Pr(S|C)\Pr(C) + \Pr(S|\bar{C} \text{ and } M)\Pr(\bar{C} \text{ and } M) + \Pr(S|\bar{C} \text{ and } \bar{M})\Pr(\bar{C} \text{ and } \bar{M})\\ &= \Pr(\bar{C} \text{ and } \bar{M}) \end{split}$$ since $\Pr(S|C) = \Pr(S|\bar{C} \text{ and } M) = 0$ and $\Pr(S|\bar{C} \text{ and } \bar{M}) = 1$ (convince yourself of this!). Continuing: $$\begin{split} \Pr(S) &= \Pr(\bar{C} \text{ and } \bar{M})\\ &= \Pr(\bar{M} | \bar{C}) \Pr(\bar{C}) \\ &= \frac{2}{3} - \frac{2}{3}\Pr(M | \bar{C})) \end{split}$$ So you see, when Monty always lies (aka $\Pr(M | \bar{C})) = 1$) then you have a zero chance of winning if you always switch, and if he never lies then the probability the car is behind the door you can switch to, $\Pr(S)$, is $\frac{2}{3}$. From this you can work out the optimal strategies for both Liar, and Unreliable Monty. Addendum 1 In response to comment (emphasis mine): "I added more details in my comment to @alex - Monty is never hostile nor devious, just FALLIBLE, as sometimes he can be wrong for whatever reasons, and never actually opens the door. Research shows that Monty is wrong roughly 33.3% of the time, and the car actually turns out to be there. That is a Posterior Probability of being correct 66.6% of the time, correct? Monty never chooses YOUR door, and you will never choose his. Do these assumptions change anything?" This is as I understand, the Unreliable Monty Hall Problem introduced at the start of my answer. Therefore, if Monty's door contains the car $\frac{1}{3}$ of the time, we have the probability of winning when you switch to the last unpicked door as: $$ \begin{split} \Pr(S) &= \frac{2}{3} - \frac{2}{3}\Pr(M | \bar{C})\\ &= \frac{2}{3} - \frac{2}{3} \times \frac{3}{2}\Pr(M) \\ &= \frac{2}{3} - \frac{1}{3}\\ &= \frac{1}{3} \end{split}$$ Thus, there is no difference between switching, remaining with the original door or if allowed, switching to Monty's chosen door (in line with your intuition.)
Monty Hall Problem with a Fallible Monty
Based on the comments on Ben's answer, I am going to offer up two different interpretations of this variant of Monty Hall, differing to Ruben van Bergen's. The first one I am going to call Liar Monty
Monty Hall Problem with a Fallible Monty Based on the comments on Ben's answer, I am going to offer up two different interpretations of this variant of Monty Hall, differing to Ruben van Bergen's. The first one I am going to call Liar Monty and the second one Unreliable Monty. In both versions the problem proceeds as follows: (0) There are three doors, behind one of which is a car and behind the other two are goats, distributed randomly. (1) Contestant chooses a door at random. (2) Monty picks a door different to the contestant's door and claims a goat is behind it. (3) Contestant is offered to switch to the third unpicked door, and the problem is "When should the contestant switch in order to maximise the probability of finding a car behind the door?" In Liar Monty, at step (2), if the contestant has picked a door containing a goat, then Monty picks a door containing the car with some predefined probability (i.e. there is a chance between 0 and 100% that he will lie that a goat is behind some door). Note that in this variant, Monty never picks a door containing the car (i.e. cannot lie) if the contestant chose the car in step (1). In Unreliable Monty, there is a predefined probability that the door Monty pick's in step (2) contains a car. I take from your comment on Ben's answer that this is the scenario you are interested in, and both of my versions differ from Ruben van Bergen's. Note that Unreliable Monty is not the same as Liar Monty; we will rigorously differentiate between these two cases later. But consider this, in this scenario, Monty's door can never contain the car more than $\frac{2}{3}$ of the time, since the contestant has a probability of choosing the car $\frac{1}{3}$ of the time. To answer the problem, we are going to have to use some equations. I am going to try and phrase my answer so that it is accessible. The two things that I hope are not too confusing are algebraic manipulation of symbols, and conditional probability. For the former, we will use symbols to denote the following: $$\begin{split} S &= \text{The car is behind the door the contestant can switch to.}\\ \bar{S} &= \text{The car is not behind the door the contestant can switch to.}\\ M &= \text{The car is behind the door Monty chose.}\\ \bar{M} &= \text{The car is not behind the door Monty chose.}\\ C &= \text{The car is behind the door the contestant chose in step (1).}\\ \bar{C} &= \text{The car is not behind the door the contestant chose in step (1).} \end{split} $$ We use $\Pr(*)$ to denote "the probability of $*$", so that, put together, something like $\Pr(\bar{M})$ means the probability that the car is not behind the door Monty chose. (I.e. wherever you see an expression involving the symbols, replace the symbols with the "English" equivalents.) We will also require some rudimentary understanding of conditional probability, which is roughly the probability of something happening if you have knowledge of another related event. This probability will be represented here by expressions such as $\Pr(S|\bar{M})$. The vertical bar $|$ can be thought of as the expression "if you know", so that $\Pr(S|\bar{M})$ can be read as "the probability that the door the contestant can switch to has the car, if you know that the car is not behind Monty's door. In the original Monty Hall problem, $\Pr(S|\bar{M}) = \frac{2}{3}$, which is larger than $\Pr(S) = \frac{1}{3}$, which corresponds to the case when Monty has not given you any information. I will now demonstrate that Unreliable Monty is equivalent to Liar Monty. In Liar Monty, we are given the quantity $\Pr(M|\bar{C})$, the probability that Monty will lie about his door, knowing that the contestant has not chosen the car. In Unreliable Monty, we are given the quantity $\Pr(M)$, the probability that Monty lies about his door. Using the definition of conditional probability $\Pr(M \text{ and } \bar{C}) = \Pr(\bar{C} | M) \Pr(M) = \Pr(M | \bar{C}) \Pr(\bar{C})$, and rearranging, we obtain: $$ \begin{split} \Pr(M) &= \frac{\Pr(M | \bar{C}) \Pr(\bar{C})}{\Pr(\bar{C} | M)}\\ \frac{3}{2} \Pr(M) &= \Pr(M | \bar{C}), \end{split}$$ since $\Pr(\bar{C})$, the probability that the car is not behind the contestant's chosen door is $\frac{2}{3}$ and $\Pr(\bar{C} | M)$, the probability that the car is not behind the contestant's chosen door, if we know that it is behind Monty's door, is one. Thus, we have shown the connection between Unreliable Monty (represented by LHS of the above equation) and Liar Monty (represented by the RHS). In the extreme case of Unreliable Monty, where Monty chooses a door that hides the car $\frac{2}{3}$ of the time, this is equivalent to Monty lying all the time in Liar Monty, if the contestant has picked a goat originally. Having shown this, I will now provide enough information to answer the Liar version of the Monty Hall Problem. We want to calculate $\Pr(S)$. Using the law of total probability: $$\begin{split} \Pr(S) &= \Pr(S|C)\Pr(C) + \Pr(S|\bar{C} \text{ and } M)\Pr(\bar{C} \text{ and } M) + \Pr(S|\bar{C} \text{ and } \bar{M})\Pr(\bar{C} \text{ and } \bar{M})\\ &= \Pr(\bar{C} \text{ and } \bar{M}) \end{split}$$ since $\Pr(S|C) = \Pr(S|\bar{C} \text{ and } M) = 0$ and $\Pr(S|\bar{C} \text{ and } \bar{M}) = 1$ (convince yourself of this!). Continuing: $$\begin{split} \Pr(S) &= \Pr(\bar{C} \text{ and } \bar{M})\\ &= \Pr(\bar{M} | \bar{C}) \Pr(\bar{C}) \\ &= \frac{2}{3} - \frac{2}{3}\Pr(M | \bar{C})) \end{split}$$ So you see, when Monty always lies (aka $\Pr(M | \bar{C})) = 1$) then you have a zero chance of winning if you always switch, and if he never lies then the probability the car is behind the door you can switch to, $\Pr(S)$, is $\frac{2}{3}$. From this you can work out the optimal strategies for both Liar, and Unreliable Monty. Addendum 1 In response to comment (emphasis mine): "I added more details in my comment to @alex - Monty is never hostile nor devious, just FALLIBLE, as sometimes he can be wrong for whatever reasons, and never actually opens the door. Research shows that Monty is wrong roughly 33.3% of the time, and the car actually turns out to be there. That is a Posterior Probability of being correct 66.6% of the time, correct? Monty never chooses YOUR door, and you will never choose his. Do these assumptions change anything?" This is as I understand, the Unreliable Monty Hall Problem introduced at the start of my answer. Therefore, if Monty's door contains the car $\frac{1}{3}$ of the time, we have the probability of winning when you switch to the last unpicked door as: $$ \begin{split} \Pr(S) &= \frac{2}{3} - \frac{2}{3}\Pr(M | \bar{C})\\ &= \frac{2}{3} - \frac{2}{3} \times \frac{3}{2}\Pr(M) \\ &= \frac{2}{3} - \frac{1}{3}\\ &= \frac{1}{3} \end{split}$$ Thus, there is no difference between switching, remaining with the original door or if allowed, switching to Monty's chosen door (in line with your intuition.)
Monty Hall Problem with a Fallible Monty Based on the comments on Ben's answer, I am going to offer up two different interpretations of this variant of Monty Hall, differing to Ruben van Bergen's. The first one I am going to call Liar Monty
11,440
Monty Hall Problem with a Fallible Monty
For some reason, a moderator decided to delete my own answer to my own question, on the grounds that it contained "discussion." I don't really see HOW I can explain what is the Best Answer without discussing what makes it work for me, and how it can be applied in practice. I appreciate the insights and formulae which were provided in the previous answers. It appears to be that IF "Fallible Monty" is only 66% accurate in predicting the absence of a Prize/Car THEN there is ZERO benefit to switching from your original choice of doors....because his 33% error rate is the default base rate for the Prize being behind ANY door. One assumes, though, that IF Monty gets better than 66% at predicting where there is NO PRIZE THEN switching derives greater Utility.
Monty Hall Problem with a Fallible Monty
For some reason, a moderator decided to delete my own answer to my own question, on the grounds that it contained "discussion." I don't really see HOW I can explain what is the Best Answer without dis
Monty Hall Problem with a Fallible Monty For some reason, a moderator decided to delete my own answer to my own question, on the grounds that it contained "discussion." I don't really see HOW I can explain what is the Best Answer without discussing what makes it work for me, and how it can be applied in practice. I appreciate the insights and formulae which were provided in the previous answers. It appears to be that IF "Fallible Monty" is only 66% accurate in predicting the absence of a Prize/Car THEN there is ZERO benefit to switching from your original choice of doors....because his 33% error rate is the default base rate for the Prize being behind ANY door. One assumes, though, that IF Monty gets better than 66% at predicting where there is NO PRIZE THEN switching derives greater Utility.
Monty Hall Problem with a Fallible Monty For some reason, a moderator decided to delete my own answer to my own question, on the grounds that it contained "discussion." I don't really see HOW I can explain what is the Best Answer without dis
11,441
Why is the cost function of neural networks non-convex?
$\sum_i (y_i- \hat y_i)^2$ is indeed convex in $\hat y_i$. But if $\hat y_i = f(x_i ; \theta)$ it may not be convex in $\theta$, which is the situation with most non-linear models, and we actually care about convexity in $\theta$ because that's what we're optimizing the cost function over. For example, let's consider a network with 1 hidden layer of $N$ units and a linear output layer: our cost function is $$ g(\alpha, W) = \sum_i \left(y_i - \alpha_i\sigma(Wx_i)\right)^2 $$ where $x_i \in \mathbb R^p$ and $W \in \mathbb R^{N \times p}$ (and I'm omitting bias terms for simplicity). This is not necessarily convex when viewed as a function of $(\alpha, W)$ (depending on $\sigma$: if a linear activation function is used then this still can be convex). And the deeper our network gets, the less convex things are. Now define a function $h : \mathbb R \times \mathbb R \to \mathbb R$ by $h(u, v) = g(\alpha, W(u, v))$ where $W(u,v)$ is $W$ with $W_{11}$ set to $u$ and $W_{12}$ set to $v$. This allows us to visualize the cost function as these two weights vary. The figure below shows this for the sigmoid activation function with $n=50$, $p=3$, and $N=1$ (so an extremely simple architecture). All data (both $x$ and $y$) are iid $\mathcal N(0,1)$, as are any weights not being varied in the plotting function. You can see the lack of convexity here. Here's the R code that I used to make this figure (although some of the parameters are at slightly different values now than when I made it so they won't be identical): costfunc <- function(u, v, W, a, x, y, afunc) { W[1,1] <- u; W[1,2] <- v preds <- t(a) %*% afunc(W %*% t(x)) sum((y - preds)^2) } set.seed(1) n <- 75 # number of observations p <- 3 # number of predictors N <- 1 # number of hidden units x <- matrix(rnorm(n * p), n, p) y <- rnorm(n) # all noise a <- matrix(rnorm(N), N) W <- matrix(rnorm(N * p), N, p) afunc <- function(z) 1 / (1 + exp(-z)) # sigmoid l = 400 # dim of matrix of cost evaluations wvals <- seq(-50, 50, length = l) # where we evaluate costfunc fmtx <- matrix(0, l, l) for(i in 1:l) { for(j in 1:l) { fmtx[i,j] = costfunc(wvals[i], wvals[j], W, a, x, y, afunc) } } filled.contour(wvals, wvals, fmtx,plot.axes = { contour(wvals, wvals, fmtx, nlevels = 25, drawlabels = F, axes = FALSE, frame.plot = FALSE, add = TRUE); axis(1); axis(2) }, main = 'NN loss surface', xlab = expression(paste('W'[11])), ylab = expression(paste('W'[12])))
Why is the cost function of neural networks non-convex?
$\sum_i (y_i- \hat y_i)^2$ is indeed convex in $\hat y_i$. But if $\hat y_i = f(x_i ; \theta)$ it may not be convex in $\theta$, which is the situation with most non-linear models, and we actually car
Why is the cost function of neural networks non-convex? $\sum_i (y_i- \hat y_i)^2$ is indeed convex in $\hat y_i$. But if $\hat y_i = f(x_i ; \theta)$ it may not be convex in $\theta$, which is the situation with most non-linear models, and we actually care about convexity in $\theta$ because that's what we're optimizing the cost function over. For example, let's consider a network with 1 hidden layer of $N$ units and a linear output layer: our cost function is $$ g(\alpha, W) = \sum_i \left(y_i - \alpha_i\sigma(Wx_i)\right)^2 $$ where $x_i \in \mathbb R^p$ and $W \in \mathbb R^{N \times p}$ (and I'm omitting bias terms for simplicity). This is not necessarily convex when viewed as a function of $(\alpha, W)$ (depending on $\sigma$: if a linear activation function is used then this still can be convex). And the deeper our network gets, the less convex things are. Now define a function $h : \mathbb R \times \mathbb R \to \mathbb R$ by $h(u, v) = g(\alpha, W(u, v))$ where $W(u,v)$ is $W$ with $W_{11}$ set to $u$ and $W_{12}$ set to $v$. This allows us to visualize the cost function as these two weights vary. The figure below shows this for the sigmoid activation function with $n=50$, $p=3$, and $N=1$ (so an extremely simple architecture). All data (both $x$ and $y$) are iid $\mathcal N(0,1)$, as are any weights not being varied in the plotting function. You can see the lack of convexity here. Here's the R code that I used to make this figure (although some of the parameters are at slightly different values now than when I made it so they won't be identical): costfunc <- function(u, v, W, a, x, y, afunc) { W[1,1] <- u; W[1,2] <- v preds <- t(a) %*% afunc(W %*% t(x)) sum((y - preds)^2) } set.seed(1) n <- 75 # number of observations p <- 3 # number of predictors N <- 1 # number of hidden units x <- matrix(rnorm(n * p), n, p) y <- rnorm(n) # all noise a <- matrix(rnorm(N), N) W <- matrix(rnorm(N * p), N, p) afunc <- function(z) 1 / (1 + exp(-z)) # sigmoid l = 400 # dim of matrix of cost evaluations wvals <- seq(-50, 50, length = l) # where we evaluate costfunc fmtx <- matrix(0, l, l) for(i in 1:l) { for(j in 1:l) { fmtx[i,j] = costfunc(wvals[i], wvals[j], W, a, x, y, afunc) } } filled.contour(wvals, wvals, fmtx,plot.axes = { contour(wvals, wvals, fmtx, nlevels = 25, drawlabels = F, axes = FALSE, frame.plot = FALSE, add = TRUE); axis(1); axis(2) }, main = 'NN loss surface', xlab = expression(paste('W'[11])), ylab = expression(paste('W'[12])))
Why is the cost function of neural networks non-convex? $\sum_i (y_i- \hat y_i)^2$ is indeed convex in $\hat y_i$. But if $\hat y_i = f(x_i ; \theta)$ it may not be convex in $\theta$, which is the situation with most non-linear models, and we actually car
11,442
How to interpret regression coefficients when response was transformed by the 4th root?
The best solution is, at the outset, to choose a re-expression that has a meaning in the field of study. (For instance, when regressing body weights against independent factors, it's likely that either a cube root ($1/3$ power) or square root ($1/2$ power) will be indicated. Noting that weight is a good proxy for volume, the cube root is a length representing a characteristic linear size. This endows it with an intuitive, potentially interpretable meaning. Although the square root itself has no such clear interpretation, it is close to the $2/3$ power, which has dimensions of surface area: it might correspond to total skin area.) The fourth power is sufficiently close to the logarithm that you ought to consider using the log instead, whose meanings are well understood. But sometimes we really do find that a cube root or square root or some such fractional power does a great job and it has no obvious interpretation. Then, we must do a little arithmetic. The regression model shown in the question involves a dependent variable $Y$ ("Collections") and two independent variables $X_1$ ("Fees") and $X_2$ ("DIR"). It posits that $$Y^{1/4} = \beta_0 + \beta_1 X_1 + \beta_2 X_2 +\varepsilon.$$ The code estimates $\beta_0$ as $b_0=2.094573355$, $\beta_1$ as $b_1=0.000075223$, and $\beta_2$ as $b_2=0.000022279$. It also presumes $\varepsilon$ are iid normal with zero mean and it estimates their common variance (not shown). With these estimates, the fitted value of $Y^{1/4}$ is $$\widehat{Y^{1/4}} = b_0 + b_1 X_1 + b_2 X_2.$$ "Interpreting" regression coefficients normally means determining what change in the dependent variable is suggested by a given change in each independent variable. These changes are the derivatives $dY/dX_i$, which the Chain Rule tells us are equal to $4\beta_iY^3$. We would plug in the estimates, then, and say something like The regression estimates that a unit change in $X_i$ will be associated with a change in $Y$ of $4b_i\widehat{Y}^{3/4}$ = $4b_i\left(b_0+b_1X_1+b_2X_2\right)^3$. The dependence of the interpretation on $X_1$ and $X_2$ is not simply expressed in words, unlike the situations with no transformation of $Y$ (one unit change in $X_i$ is associated with a change of $b_i$ in $Y$) or with the logarithm (one percent change in $X_i$ is associated with $b_i$ percent change in $Y$). However, by keeping the first form of the interpretation, and computing $4b_1$ = $4\times 0.000075223$ = $0.000301$, we might state something like A unit change in fees is associated with a change in collections of $0.000301$ times the cube of the current collections; for instance, if the current collections are $10^4 = 10,000$, then a unit increase in fees is associated with an increase of $0.301$ in collections and if the current collections are $20^4 = 80,000$, then the same unit increase in fees is associated with an increase of $2.41$ in collections. When taking roots other than the fourth--say, when using $Y^p$ as the response rather than $Y$ itself, with $p$ nonzero--simply replace all appearances of "$4$" in this analysis by "$1/p$".
How to interpret regression coefficients when response was transformed by the 4th root?
The best solution is, at the outset, to choose a re-expression that has a meaning in the field of study. (For instance, when regressing body weights against independent factors, it's likely that eithe
How to interpret regression coefficients when response was transformed by the 4th root? The best solution is, at the outset, to choose a re-expression that has a meaning in the field of study. (For instance, when regressing body weights against independent factors, it's likely that either a cube root ($1/3$ power) or square root ($1/2$ power) will be indicated. Noting that weight is a good proxy for volume, the cube root is a length representing a characteristic linear size. This endows it with an intuitive, potentially interpretable meaning. Although the square root itself has no such clear interpretation, it is close to the $2/3$ power, which has dimensions of surface area: it might correspond to total skin area.) The fourth power is sufficiently close to the logarithm that you ought to consider using the log instead, whose meanings are well understood. But sometimes we really do find that a cube root or square root or some such fractional power does a great job and it has no obvious interpretation. Then, we must do a little arithmetic. The regression model shown in the question involves a dependent variable $Y$ ("Collections") and two independent variables $X_1$ ("Fees") and $X_2$ ("DIR"). It posits that $$Y^{1/4} = \beta_0 + \beta_1 X_1 + \beta_2 X_2 +\varepsilon.$$ The code estimates $\beta_0$ as $b_0=2.094573355$, $\beta_1$ as $b_1=0.000075223$, and $\beta_2$ as $b_2=0.000022279$. It also presumes $\varepsilon$ are iid normal with zero mean and it estimates their common variance (not shown). With these estimates, the fitted value of $Y^{1/4}$ is $$\widehat{Y^{1/4}} = b_0 + b_1 X_1 + b_2 X_2.$$ "Interpreting" regression coefficients normally means determining what change in the dependent variable is suggested by a given change in each independent variable. These changes are the derivatives $dY/dX_i$, which the Chain Rule tells us are equal to $4\beta_iY^3$. We would plug in the estimates, then, and say something like The regression estimates that a unit change in $X_i$ will be associated with a change in $Y$ of $4b_i\widehat{Y}^{3/4}$ = $4b_i\left(b_0+b_1X_1+b_2X_2\right)^3$. The dependence of the interpretation on $X_1$ and $X_2$ is not simply expressed in words, unlike the situations with no transformation of $Y$ (one unit change in $X_i$ is associated with a change of $b_i$ in $Y$) or with the logarithm (one percent change in $X_i$ is associated with $b_i$ percent change in $Y$). However, by keeping the first form of the interpretation, and computing $4b_1$ = $4\times 0.000075223$ = $0.000301$, we might state something like A unit change in fees is associated with a change in collections of $0.000301$ times the cube of the current collections; for instance, if the current collections are $10^4 = 10,000$, then a unit increase in fees is associated with an increase of $0.301$ in collections and if the current collections are $20^4 = 80,000$, then the same unit increase in fees is associated with an increase of $2.41$ in collections. When taking roots other than the fourth--say, when using $Y^p$ as the response rather than $Y$ itself, with $p$ nonzero--simply replace all appearances of "$4$" in this analysis by "$1/p$".
How to interpret regression coefficients when response was transformed by the 4th root? The best solution is, at the outset, to choose a re-expression that has a meaning in the field of study. (For instance, when regressing body weights against independent factors, it's likely that eithe
11,443
How to interpret regression coefficients when response was transformed by the 4th root?
An alternative to transformation here is to use a generalised linear model with link function power and power 1/4. What error family to use is open, which gives you more flexibility than you have with linear regression and an assumption of conditional normality. One major advantage of this procedure is that predictions are automatically produced on the original measurement scale, so there is no question of back-transforming.
How to interpret regression coefficients when response was transformed by the 4th root?
An alternative to transformation here is to use a generalised linear model with link function power and power 1/4. What error family to use is open, which gives you more flexibility than you have with
How to interpret regression coefficients when response was transformed by the 4th root? An alternative to transformation here is to use a generalised linear model with link function power and power 1/4. What error family to use is open, which gives you more flexibility than you have with linear regression and an assumption of conditional normality. One major advantage of this procedure is that predictions are automatically produced on the original measurement scale, so there is no question of back-transforming.
How to interpret regression coefficients when response was transformed by the 4th root? An alternative to transformation here is to use a generalised linear model with link function power and power 1/4. What error family to use is open, which gives you more flexibility than you have with
11,444
How to interpret regression coefficients when response was transformed by the 4th root?
I have seen papers using quartic root regression coefficients in thinking about percentage changes, while avoiding taking logs (and dropping observations). If we're interested in using quartic roots to calculate percentage changes, we know that: $\hat{Y} = (\alpha + \hat{\beta}_1 X_1 + \hat{\beta}_2 X_2)^4 \implies \frac{d\hat{Y}}{dX_1} = 4\hat{\beta}_1(\alpha+\hat{\beta}_1 X_1 + \hat{\beta}_2 X_2)^3$ For the equivalent of a log-level regression, in which we're interested in the percentage change in $Y$ resulting from a unit change in $X$, we have to know the levels of all the $X$ variables: $ \frac{d\hat{Y}/dX_1}{Y} = \frac{4\hat{\beta}_1}{\alpha + \hat{\beta}_1 X_1 + \hat{\beta}_2 X_2} $ For the equivalent of a log-log regression, in which we're interested in the percentage in $Y$ resulting from a percentage change in $X$, we'd have: $ \frac{d\hat{Y}}{dX_1}\frac{X_1}{\hat{Y}} = \frac{4\hat{\beta}_1 X_1}{\alpha + \hat{\beta}_1 X_1 + \hat{\beta}_2 X_2} $ It doesn't seem especially convenient (I prefer the log transformation), but it can be done, either evaluating the $X$ values at the sample means or at hypothetical values. I suppose, actually, you could replace the denominator with the sample average value of $Y^{1/4}$, and that would be a bit more convenient.
How to interpret regression coefficients when response was transformed by the 4th root?
I have seen papers using quartic root regression coefficients in thinking about percentage changes, while avoiding taking logs (and dropping observations). If we're interested in using quartic roots
How to interpret regression coefficients when response was transformed by the 4th root? I have seen papers using quartic root regression coefficients in thinking about percentage changes, while avoiding taking logs (and dropping observations). If we're interested in using quartic roots to calculate percentage changes, we know that: $\hat{Y} = (\alpha + \hat{\beta}_1 X_1 + \hat{\beta}_2 X_2)^4 \implies \frac{d\hat{Y}}{dX_1} = 4\hat{\beta}_1(\alpha+\hat{\beta}_1 X_1 + \hat{\beta}_2 X_2)^3$ For the equivalent of a log-level regression, in which we're interested in the percentage change in $Y$ resulting from a unit change in $X$, we have to know the levels of all the $X$ variables: $ \frac{d\hat{Y}/dX_1}{Y} = \frac{4\hat{\beta}_1}{\alpha + \hat{\beta}_1 X_1 + \hat{\beta}_2 X_2} $ For the equivalent of a log-log regression, in which we're interested in the percentage in $Y$ resulting from a percentage change in $X$, we'd have: $ \frac{d\hat{Y}}{dX_1}\frac{X_1}{\hat{Y}} = \frac{4\hat{\beta}_1 X_1}{\alpha + \hat{\beta}_1 X_1 + \hat{\beta}_2 X_2} $ It doesn't seem especially convenient (I prefer the log transformation), but it can be done, either evaluating the $X$ values at the sample means or at hypothetical values. I suppose, actually, you could replace the denominator with the sample average value of $Y^{1/4}$, and that would be a bit more convenient.
How to interpret regression coefficients when response was transformed by the 4th root? I have seen papers using quartic root regression coefficients in thinking about percentage changes, while avoiding taking logs (and dropping observations). If we're interested in using quartic roots
11,445
Backpropagation algorithm and error in hidden layer
I figured I'd answer a self-contained post here for anyone that's interested. This will be using the notation described here. Introduction The idea behind backpropagation is to have a set of "training examples" that we use to train our network. Each of these has a known answer, so we can plug them into the neural network and find how much it was wrong. For example, with handwriting recognition, you would have lots of handwritten characters alongside what they actually were. Then the neural network can be trained via backpropagation to "learn" how to recognize each symbol, so then when it's later presented with an unknown handwritten character it can identify what it is correctly. Specifically, we input some training sample into the neural network, see how good it did, then "trickle backwards" to find how much we can change each node's weights and bias to get a better result, and then adjust them accordingly. As we continue to do this, the network "learns". There are also other steps that may be included in the training process (for example, dropout), but I will focus mostly on backpropagation since that's what this question was about. Partial derivatives A partial derivative $\frac{\partial f}{\partial x}$ is a derivative of $f$ with respect to some variable $x$. For example, if $f(x, y)=x^2 + y^2$, $\frac{\partial f}{\partial x}=2x$, because $y^2$ is simply a constant with respect to $x$. Likewise, $\frac{\partial f}{\partial y}= 2y$, because $x^2$ is simply a constant with respect to $y$. A gradient of a function, designated $\nabla f$, is a function containing the partial derivative for every variable in f. Specifically: $$\nabla f(v_1, v_2, ..., v_n) = \frac{\partial f}{\partial v_1 }\mathbf{e}_1 + \cdots + \frac{\partial f}{\partial v_n }\mathbf{e}_n$$, where $e_i$ is a unit vector pointing in the direction of variable $v_1$. Now, once we have computed the $\nabla f$ for some function $f$, if we are at position $(v_1, v_2, ..., v_n)$, we can "slide down" $f$ by going in direction $-\nabla f(v_1, v_2, ..., v_n)$. With our example of $f(x, y)=x^2 + y^2$, the unit vectors are $e_1=(1, 0)$ and $e_2=(0, 1)$, because $v_1=x$ and $v_2=y$, and those vectors point in the direction of the $x$ and $y$ axes. Thus, $\nabla f(x, y) = 2x (1, 0) + 2y(0, 1)$. Now, to "slide down" our function $f$, let's say we are at a point $(-2, 4)$. Then we would need to move in direction $-\nabla f(-2, -4)= -(2 \cdot -2 \cdot (1, 0) + 2 \cdot 4 \cdot (0, 1)) = -((-4, 0) + (0, 8))=(4, -8)$. The magnitude of this vector will give us how steep the hill is (higher values means the hill is steeper). In this case, we have $\sqrt{4^2+(-8)^2}\approx 8.944$. Hadamard Product The Hadamard Product of two matrices $A, B \in R^{n\times m}$, is just like matrix addition, except instead of adding the matrices element-wise, we multiply them element-wise. Formally, while matrix addition is $A + B = C$, where $C \in R^{n \times m}$ such that $$C^i_j = A^i_j + B^i_j$$, The Hadamard Product $A \odot B = C$, where $C \in R^{n \times m}$ such that $$C^i_j = A^i_j \cdot B^i_j$$ Computing the gradients (most of this section is from Neilsen's book). We have a set of training samples, $(S, E)$, where $S_r$ is a single input training sample, and $E_r$ is the expected output value of that training sample. We also have our neural network, composed of weights $W$, and biases $B$. $r$ is used to prevent confusion from the $i$, $j$, and $k$ used in the definition of a feedforward network. Next, we define a cost function, $C(W, B, S^r, E^r)$ that takes in our neural network and a single training example, and outputs how good it did. Normally what is used is quadratic cost, which is defined by $$C(W, B, S^r, E^r) = 0.5\sum\limits_j (a^L_j - E^r_j)^2$$ where $a^L$ is the output to our neural network, given input sample $S^r$ Then we want to find $\frac{\partial C}{\partial w^i_j}$ and $\frac{\partial C}{\partial b^i_j}$ for each node in our feedforward neural network. We can call this the gradient of $C$ at each neuron because we consider $S^r$ and $E^r$ as constants, since we can't change them when we are trying to learn. And this makes sense - we want to move in a direction relative to $W$ and $B$ that minimizes cost, and moving in the negative direction of the gradient with respect to $W$ and $B$ will do this. To do this, we define $\delta^i_j=\frac{\partial C}{\partial z^i_j}$ as the error of neuron $j$ in layer $i$. We start with computing $a^L$ by plugging $S^r$ into our neural network. Then we compute the error of our output layer, $\delta^L$, via $$\delta^L_j = \frac{\partial C}{\partial a^L_j} \sigma^{ \prime}(z^L_j)$$. Which can also be written as $$\delta^L = \nabla_a C \odot \sigma^{ \prime}(z^L)$$. Next, we find the error $\delta^i$ in terms of the error in the next layer $\delta^{i+1}$, via $$\delta^i=((W^{i+1})^T \delta^{i+1}) \odot \sigma^{\prime}(z^i)$$ Now that we have the error of each node in our neural network, computing the gradient with respect to our weights and biases is easy: $$\frac{\partial C}{\partial w^i_{jk}}=\delta^i_j a^{i-1}_k=\delta^i(a^{i-1})^T$$ $$\frac{\partial C}{\partial b^i_j} = \delta^i_j$$ Note that the equation for the error of the output layer is the only equation that's dependent on the cost function, so, regardless of the cost function, the last three equations are the same. As an example, with quadratic cost, we get $$\delta ^L = (a^L - E^r) \odot \sigma ^ {\prime}(z^L)$$ for the error of the output layer. and then this equation can be plugged into the second equation to get the error of the $L-1^{\text{th}}$ layer: $$\delta^{L-1}=((W^{L})^T \delta^{L}) \odot \sigma^{\prime}(z^{L-1})$$ $$=((W^{L})^T ((a^L - E^r) \odot \sigma ^ {\prime}(z^L))) \odot \sigma^{\prime}(z^{L-1})$$ which we can repeat this process to find the error of any layer with respect to $C$, which then allows us to compute the gradient of any node's weights and bias with respect to $C$. I could write up an explanation and proof of these equations if desired, though one can also find proofs of them here. I'd encourage anyone that is reading this to prove these themselves though, beginning with the definition $\delta^i_j=\frac{\partial C}{\partial z^i_j}$ and applying the chain rule liberally. For some more examples, I made a list of some cost functions alongside their gradients here. Gradient Descent Now that we have these gradients, we need to use them learn. In the previous section, we found how to move to "slide down" the curve with respect to some point. In this case, because it's a gradient of some node with respect to weights and a bias of that node, our "coordinate" is the current weights and bias of that node. Since we've already found the gradients with respect to those coordinates, those values are already how much we need to change. We don't want to slide down the slope at a very fast speed, otherwise we risk sliding past the minimum. To prevent this, we want some "step size" $\eta$. Then, find the how much we should modify each weight and bias by, because we have already computed the gradient with respect to the current we have $$\Delta w^i_{jk}= -\eta \frac{\partial C}{\partial w^i_{jk}}$$ $$\Delta b^i_j = -\eta \frac{\partial C}{\partial b^i_j}$$ Thus, our new weights and biases are $$w^i_{jk} = w^i_{jk} + \Delta w^i_{jk}$$ $$b^i_j = b^i_j + \Delta b^i_j$$ Using this process on a neural network with only an input layer and an output layer is called the Delta Rule. Stochastic Gradient Descent Now that we know how to perform backpropagation for a single sample, we need some way of using this process to "learn" our entire training set. One option is simply performing backpropagation for each sample in our training data, one at a time. This is pretty inefficient though. A better approach is Stochastic Gradient Descent. Instead of performing backpropagation for each sample, we pick a small random sample (called a batch) of our training set, then perform backpropagation for each sample in that batch. The hope is that by doing this, we capture the "intent" of the data set, without having to compute the gradient of every sample. For example, if we had 1000 samples, we could pick a batch of size 50, then run backpropagation for each sample in this batch. The hope is that we were given a large enough training set that it represents the distribution of the actual data we are trying to learn well enough that picking a small random sample is sufficient to capture this information. However, doing backpropagation for each training example in our mini-batch isn't ideal, because we can end up "wiggling around" where training samples modify weights and biases in such a way that they cancel each other out and prevent them from getting to the minimum we are trying to get to. To prevent this, we want to go to the "average minimum," because the hope is that, on average, the samples' gradients are pointing down the slope. So, after choosing our batch randomly, we create a mini-batch which is a small random sample of our batch. Then, given a mini-batch with $n$ training samples, and only update the weights and biases after averaging the gradients of each sample in the mini-batch. Formally, we do $$\Delta w^{i}_{jk} = \frac{1}{n}\sum\limits_r \Delta w^{ri}_{jk}$$ and $$\Delta b^{i}_{j} = \frac{1}{n}\sum\limits_r \Delta b^{ri}_{j}$$ where $\Delta w^{ri}_{jk}$ is the computed change in weight for sample $r$, and $\Delta b^{ri}_{j}$ is the computed change in bias for sample $r$. Then, like before, we can update the weights and biases via: $$w^i_{jk} = w^i_{jk} + \Delta w^{i}_{jk}$$ $$b^i_j = b^i_j + \Delta b^{i}_{j}$$ This gives us some flexibility in how we want to perform gradient descent. If we have a function we are trying to learn with lots of local minima, this "wiggling around" behavior is actually desirable, because it means that we're much less likely to get "stuck" in one local minima, and more likely to "jump out" of one local minima and hopefully fall in another that is closer to the global minima. Thus we want small mini-batches. On the other hand, if we know that there are very few local minima, and generally gradient descent goes towards the global minima, we want larger mini-batches, because this "wiggling around" behavior will prevent us from going down the slope as fast as we would like. See here. One option is to pick the largest mini-batch possible, considering the entire batch as one mini-batch. This is called Batch Gradient Descent, since we are simply averaging the gradients of the batch. This is almost never used in practice, however, because it is very inefficient.
Backpropagation algorithm and error in hidden layer
I figured I'd answer a self-contained post here for anyone that's interested. This will be using the notation described here. Introduction The idea behind backpropagation is to have a set of "training
Backpropagation algorithm and error in hidden layer I figured I'd answer a self-contained post here for anyone that's interested. This will be using the notation described here. Introduction The idea behind backpropagation is to have a set of "training examples" that we use to train our network. Each of these has a known answer, so we can plug them into the neural network and find how much it was wrong. For example, with handwriting recognition, you would have lots of handwritten characters alongside what they actually were. Then the neural network can be trained via backpropagation to "learn" how to recognize each symbol, so then when it's later presented with an unknown handwritten character it can identify what it is correctly. Specifically, we input some training sample into the neural network, see how good it did, then "trickle backwards" to find how much we can change each node's weights and bias to get a better result, and then adjust them accordingly. As we continue to do this, the network "learns". There are also other steps that may be included in the training process (for example, dropout), but I will focus mostly on backpropagation since that's what this question was about. Partial derivatives A partial derivative $\frac{\partial f}{\partial x}$ is a derivative of $f$ with respect to some variable $x$. For example, if $f(x, y)=x^2 + y^2$, $\frac{\partial f}{\partial x}=2x$, because $y^2$ is simply a constant with respect to $x$. Likewise, $\frac{\partial f}{\partial y}= 2y$, because $x^2$ is simply a constant with respect to $y$. A gradient of a function, designated $\nabla f$, is a function containing the partial derivative for every variable in f. Specifically: $$\nabla f(v_1, v_2, ..., v_n) = \frac{\partial f}{\partial v_1 }\mathbf{e}_1 + \cdots + \frac{\partial f}{\partial v_n }\mathbf{e}_n$$, where $e_i$ is a unit vector pointing in the direction of variable $v_1$. Now, once we have computed the $\nabla f$ for some function $f$, if we are at position $(v_1, v_2, ..., v_n)$, we can "slide down" $f$ by going in direction $-\nabla f(v_1, v_2, ..., v_n)$. With our example of $f(x, y)=x^2 + y^2$, the unit vectors are $e_1=(1, 0)$ and $e_2=(0, 1)$, because $v_1=x$ and $v_2=y$, and those vectors point in the direction of the $x$ and $y$ axes. Thus, $\nabla f(x, y) = 2x (1, 0) + 2y(0, 1)$. Now, to "slide down" our function $f$, let's say we are at a point $(-2, 4)$. Then we would need to move in direction $-\nabla f(-2, -4)= -(2 \cdot -2 \cdot (1, 0) + 2 \cdot 4 \cdot (0, 1)) = -((-4, 0) + (0, 8))=(4, -8)$. The magnitude of this vector will give us how steep the hill is (higher values means the hill is steeper). In this case, we have $\sqrt{4^2+(-8)^2}\approx 8.944$. Hadamard Product The Hadamard Product of two matrices $A, B \in R^{n\times m}$, is just like matrix addition, except instead of adding the matrices element-wise, we multiply them element-wise. Formally, while matrix addition is $A + B = C$, where $C \in R^{n \times m}$ such that $$C^i_j = A^i_j + B^i_j$$, The Hadamard Product $A \odot B = C$, where $C \in R^{n \times m}$ such that $$C^i_j = A^i_j \cdot B^i_j$$ Computing the gradients (most of this section is from Neilsen's book). We have a set of training samples, $(S, E)$, where $S_r$ is a single input training sample, and $E_r$ is the expected output value of that training sample. We also have our neural network, composed of weights $W$, and biases $B$. $r$ is used to prevent confusion from the $i$, $j$, and $k$ used in the definition of a feedforward network. Next, we define a cost function, $C(W, B, S^r, E^r)$ that takes in our neural network and a single training example, and outputs how good it did. Normally what is used is quadratic cost, which is defined by $$C(W, B, S^r, E^r) = 0.5\sum\limits_j (a^L_j - E^r_j)^2$$ where $a^L$ is the output to our neural network, given input sample $S^r$ Then we want to find $\frac{\partial C}{\partial w^i_j}$ and $\frac{\partial C}{\partial b^i_j}$ for each node in our feedforward neural network. We can call this the gradient of $C$ at each neuron because we consider $S^r$ and $E^r$ as constants, since we can't change them when we are trying to learn. And this makes sense - we want to move in a direction relative to $W$ and $B$ that minimizes cost, and moving in the negative direction of the gradient with respect to $W$ and $B$ will do this. To do this, we define $\delta^i_j=\frac{\partial C}{\partial z^i_j}$ as the error of neuron $j$ in layer $i$. We start with computing $a^L$ by plugging $S^r$ into our neural network. Then we compute the error of our output layer, $\delta^L$, via $$\delta^L_j = \frac{\partial C}{\partial a^L_j} \sigma^{ \prime}(z^L_j)$$. Which can also be written as $$\delta^L = \nabla_a C \odot \sigma^{ \prime}(z^L)$$. Next, we find the error $\delta^i$ in terms of the error in the next layer $\delta^{i+1}$, via $$\delta^i=((W^{i+1})^T \delta^{i+1}) \odot \sigma^{\prime}(z^i)$$ Now that we have the error of each node in our neural network, computing the gradient with respect to our weights and biases is easy: $$\frac{\partial C}{\partial w^i_{jk}}=\delta^i_j a^{i-1}_k=\delta^i(a^{i-1})^T$$ $$\frac{\partial C}{\partial b^i_j} = \delta^i_j$$ Note that the equation for the error of the output layer is the only equation that's dependent on the cost function, so, regardless of the cost function, the last three equations are the same. As an example, with quadratic cost, we get $$\delta ^L = (a^L - E^r) \odot \sigma ^ {\prime}(z^L)$$ for the error of the output layer. and then this equation can be plugged into the second equation to get the error of the $L-1^{\text{th}}$ layer: $$\delta^{L-1}=((W^{L})^T \delta^{L}) \odot \sigma^{\prime}(z^{L-1})$$ $$=((W^{L})^T ((a^L - E^r) \odot \sigma ^ {\prime}(z^L))) \odot \sigma^{\prime}(z^{L-1})$$ which we can repeat this process to find the error of any layer with respect to $C$, which then allows us to compute the gradient of any node's weights and bias with respect to $C$. I could write up an explanation and proof of these equations if desired, though one can also find proofs of them here. I'd encourage anyone that is reading this to prove these themselves though, beginning with the definition $\delta^i_j=\frac{\partial C}{\partial z^i_j}$ and applying the chain rule liberally. For some more examples, I made a list of some cost functions alongside their gradients here. Gradient Descent Now that we have these gradients, we need to use them learn. In the previous section, we found how to move to "slide down" the curve with respect to some point. In this case, because it's a gradient of some node with respect to weights and a bias of that node, our "coordinate" is the current weights and bias of that node. Since we've already found the gradients with respect to those coordinates, those values are already how much we need to change. We don't want to slide down the slope at a very fast speed, otherwise we risk sliding past the minimum. To prevent this, we want some "step size" $\eta$. Then, find the how much we should modify each weight and bias by, because we have already computed the gradient with respect to the current we have $$\Delta w^i_{jk}= -\eta \frac{\partial C}{\partial w^i_{jk}}$$ $$\Delta b^i_j = -\eta \frac{\partial C}{\partial b^i_j}$$ Thus, our new weights and biases are $$w^i_{jk} = w^i_{jk} + \Delta w^i_{jk}$$ $$b^i_j = b^i_j + \Delta b^i_j$$ Using this process on a neural network with only an input layer and an output layer is called the Delta Rule. Stochastic Gradient Descent Now that we know how to perform backpropagation for a single sample, we need some way of using this process to "learn" our entire training set. One option is simply performing backpropagation for each sample in our training data, one at a time. This is pretty inefficient though. A better approach is Stochastic Gradient Descent. Instead of performing backpropagation for each sample, we pick a small random sample (called a batch) of our training set, then perform backpropagation for each sample in that batch. The hope is that by doing this, we capture the "intent" of the data set, without having to compute the gradient of every sample. For example, if we had 1000 samples, we could pick a batch of size 50, then run backpropagation for each sample in this batch. The hope is that we were given a large enough training set that it represents the distribution of the actual data we are trying to learn well enough that picking a small random sample is sufficient to capture this information. However, doing backpropagation for each training example in our mini-batch isn't ideal, because we can end up "wiggling around" where training samples modify weights and biases in such a way that they cancel each other out and prevent them from getting to the minimum we are trying to get to. To prevent this, we want to go to the "average minimum," because the hope is that, on average, the samples' gradients are pointing down the slope. So, after choosing our batch randomly, we create a mini-batch which is a small random sample of our batch. Then, given a mini-batch with $n$ training samples, and only update the weights and biases after averaging the gradients of each sample in the mini-batch. Formally, we do $$\Delta w^{i}_{jk} = \frac{1}{n}\sum\limits_r \Delta w^{ri}_{jk}$$ and $$\Delta b^{i}_{j} = \frac{1}{n}\sum\limits_r \Delta b^{ri}_{j}$$ where $\Delta w^{ri}_{jk}$ is the computed change in weight for sample $r$, and $\Delta b^{ri}_{j}$ is the computed change in bias for sample $r$. Then, like before, we can update the weights and biases via: $$w^i_{jk} = w^i_{jk} + \Delta w^{i}_{jk}$$ $$b^i_j = b^i_j + \Delta b^{i}_{j}$$ This gives us some flexibility in how we want to perform gradient descent. If we have a function we are trying to learn with lots of local minima, this "wiggling around" behavior is actually desirable, because it means that we're much less likely to get "stuck" in one local minima, and more likely to "jump out" of one local minima and hopefully fall in another that is closer to the global minima. Thus we want small mini-batches. On the other hand, if we know that there are very few local minima, and generally gradient descent goes towards the global minima, we want larger mini-batches, because this "wiggling around" behavior will prevent us from going down the slope as fast as we would like. See here. One option is to pick the largest mini-batch possible, considering the entire batch as one mini-batch. This is called Batch Gradient Descent, since we are simply averaging the gradients of the batch. This is almost never used in practice, however, because it is very inefficient.
Backpropagation algorithm and error in hidden layer I figured I'd answer a self-contained post here for anyone that's interested. This will be using the notation described here. Introduction The idea behind backpropagation is to have a set of "training
11,446
Backpropagation algorithm and error in hidden layer
I haven't dealt with Neural Networks for some years now, but I think you will find everything you need here: Neural Networks - A Systematic Introduction, Chapter 7: The backpropagation algorithm I apologize for not writing the direct answer here, but since I have to look up the details to remember (like you) and given that the answer without some backup may be even useless, I hope this is ok. However, if any questions remain, drop a comment and I'll see what I can do.
Backpropagation algorithm and error in hidden layer
I haven't dealt with Neural Networks for some years now, but I think you will find everything you need here: Neural Networks - A Systematic Introduction, Chapter 7: The backpropagation algorithm I apo
Backpropagation algorithm and error in hidden layer I haven't dealt with Neural Networks for some years now, but I think you will find everything you need here: Neural Networks - A Systematic Introduction, Chapter 7: The backpropagation algorithm I apologize for not writing the direct answer here, but since I have to look up the details to remember (like you) and given that the answer without some backup may be even useless, I hope this is ok. However, if any questions remain, drop a comment and I'll see what I can do.
Backpropagation algorithm and error in hidden layer I haven't dealt with Neural Networks for some years now, but I think you will find everything you need here: Neural Networks - A Systematic Introduction, Chapter 7: The backpropagation algorithm I apo
11,447
Backpropagation algorithm and error in hidden layer
I'll address the main confusion first: there is no error of a hidden layer. There's only an error of the output. The backpropagation = "back" (chain rule of differentiation) + "propagation" (information travels between layers). I'll explain. The backpropagation term comes from the following intuition: your inputs propagate through layers into the outputs. Once you got the outputs, you compare them to actual observations and compute errors and their cost. Then you, sort of, propagate these errors backwards all the way to the inputs, while attributing the change in loss function to each weight and bias in the layers. The backward direction stems from the chain rule in calculus. Here's how the chain rule works. Suppose your inputs are $x$, and you have two layer network that ultimately outputs $\hat y$. The output of a hidden layer with one parameter $\theta$ is $g(x|\theta)$, and the NN output from the last layer is then $\hat y=f(g(x|\theta)|\phi)$, where $\phi$ a single parameter of the output layer. You compare the output $\hat y$ with observation $y$, then compute the loss $L(y,\hat y)$. So, you want to decrease the loss $L(y,\hat y(x|\theta,\phi))$, and in order to do this you want to try to change parameters by $\Delta\theta,\Delta\phi$ somehow. One way to do it is to see how sensitive is the output to the parameter changes, and it's measured by the gradient. So you go and compute it: $$\frac{\partial L}{\partial \phi}=\frac{\partial f}{\partial\phi}\frac{\partial}{\partial f}L$$ $$\frac{\partial L}{\partial \theta}=\frac{\partial g}{\partial\theta}\frac{\partial f}{\partial g}\frac{\partial}{\partial f}L$$ You can see how we, sort of, move backwards while calculating the sensitivities (slopes) of hidden layer parameters (weights) $\frac{\partial L}{\partial \theta}$. If you have more layers then the expression for gradient becomes longer with each layer, adding derivatives from the left. This is why it's called backpropagation. I don't like the term, but it's what ML folks use. Once you got the gradient, you can now use it to determine in which direction and by how much to change your parameters for the next iteration. As you can see there is NO loss or error of a hidden layer. All we get is the sensitivity of the loss (error) $L(y,\hat y)$ to the weights in hidden layers.
Backpropagation algorithm and error in hidden layer
I'll address the main confusion first: there is no error of a hidden layer. There's only an error of the output. The backpropagation = "back" (chain rule of differentiation) + "propagation" (informati
Backpropagation algorithm and error in hidden layer I'll address the main confusion first: there is no error of a hidden layer. There's only an error of the output. The backpropagation = "back" (chain rule of differentiation) + "propagation" (information travels between layers). I'll explain. The backpropagation term comes from the following intuition: your inputs propagate through layers into the outputs. Once you got the outputs, you compare them to actual observations and compute errors and their cost. Then you, sort of, propagate these errors backwards all the way to the inputs, while attributing the change in loss function to each weight and bias in the layers. The backward direction stems from the chain rule in calculus. Here's how the chain rule works. Suppose your inputs are $x$, and you have two layer network that ultimately outputs $\hat y$. The output of a hidden layer with one parameter $\theta$ is $g(x|\theta)$, and the NN output from the last layer is then $\hat y=f(g(x|\theta)|\phi)$, where $\phi$ a single parameter of the output layer. You compare the output $\hat y$ with observation $y$, then compute the loss $L(y,\hat y)$. So, you want to decrease the loss $L(y,\hat y(x|\theta,\phi))$, and in order to do this you want to try to change parameters by $\Delta\theta,\Delta\phi$ somehow. One way to do it is to see how sensitive is the output to the parameter changes, and it's measured by the gradient. So you go and compute it: $$\frac{\partial L}{\partial \phi}=\frac{\partial f}{\partial\phi}\frac{\partial}{\partial f}L$$ $$\frac{\partial L}{\partial \theta}=\frac{\partial g}{\partial\theta}\frac{\partial f}{\partial g}\frac{\partial}{\partial f}L$$ You can see how we, sort of, move backwards while calculating the sensitivities (slopes) of hidden layer parameters (weights) $\frac{\partial L}{\partial \theta}$. If you have more layers then the expression for gradient becomes longer with each layer, adding derivatives from the left. This is why it's called backpropagation. I don't like the term, but it's what ML folks use. Once you got the gradient, you can now use it to determine in which direction and by how much to change your parameters for the next iteration. As you can see there is NO loss or error of a hidden layer. All we get is the sensitivity of the loss (error) $L(y,\hat y)$ to the weights in hidden layers.
Backpropagation algorithm and error in hidden layer I'll address the main confusion first: there is no error of a hidden layer. There's only an error of the output. The backpropagation = "back" (chain rule of differentiation) + "propagation" (informati
11,448
Explain in layperson's terms why predictive models aren't causally interpretable
First of all, I don't think this should be treated as a strict dichotomy: "predictive models can never establish causal inference." There are various situations in which a predictive model gives us "pretty darn good" confidence that a given causal relationship exists. So what I'd say is that predictive models - no matter how sophisticated - are often insufficient to establish causality with a high degree of confidence. Now, how to explain this to people who don't know stats/math at all? Here's one approach: You've heard it said that "correlation is not causation." What that means is just that just because two variables (call them A and B) are correlated, that doesn't mean one causes the other. This can happen when the correlation is due to a third "confounding" variable that is correlated with both A and B. For example: just because having a college degree is correlated with high earnings as an adult doesn't mean that getting a degree CAUSED those earnings to go up - it could be that "having rich parents" both allows people to get a degree and then separately helps them earn more (even if going to college actually does nothing). Predictive models try to account for this problem by statistically "controlling for" confounding variables. So in the above case we could use statistical modeling to analyze the relationship between a degree and earnings after accounting for the fact that people with rich parents are more likely to have a degree. Unfortunately, it's never possible in practice to control for EVERY confounding variable. This is partly because important variables (like the student's "personal motivation") may not exist or be impossible to measure. Even controlling for "parents being rich" is tricky - what single number could perfectly capture a family's entire economic situation? And how can we be sure that the data we have are accurate? Do any of us know PRECISELY how "rich" our parents were when we were growing up? Another problem with predictive models is that even if you COULD control for everything they can't distinguish between A causing B or B causing A. So if we were trying to analyze the effect of depression on opiate use, no matter what control variables we include we can't be sure that the effect we observe isn't just due to opiate use CAUSING depression. Note that this is probably NOT a problem for our earlier example because it's impossible for your earnings as an adult to CAUSE you to have gone to college earlier in your life. This is one way in which our theoretical understanding of how these variables work helps us to understand the threats to causal inference. The only way to completely ensure that a relationship between A and B is causal is to experimentally control how people get "assigned" to different values of A (e.g. to get a college degree or not). If assignment to A is completely random then we can be sure that NOTHING else influenced A, which means that you don't have to worry about ANY confounding variables (even B) in analyzing the relationship between A and B. However, for reasons that are obvious when we're considering college degrees, random assignment is often infeasible or downright unethical. So we have to use other research design approaches to approximate the causal power of random assignment. Critically, these other approaches (instrumental variables, regression discontinuity, natural experiments) rely on the features of the world itself, and the data collection process, rather than statistical/mathematical methods, to address issues of confounding variables.
Explain in layperson's terms why predictive models aren't causally interpretable
First of all, I don't think this should be treated as a strict dichotomy: "predictive models can never establish causal inference." There are various situations in which a predictive model gives us "p
Explain in layperson's terms why predictive models aren't causally interpretable First of all, I don't think this should be treated as a strict dichotomy: "predictive models can never establish causal inference." There are various situations in which a predictive model gives us "pretty darn good" confidence that a given causal relationship exists. So what I'd say is that predictive models - no matter how sophisticated - are often insufficient to establish causality with a high degree of confidence. Now, how to explain this to people who don't know stats/math at all? Here's one approach: You've heard it said that "correlation is not causation." What that means is just that just because two variables (call them A and B) are correlated, that doesn't mean one causes the other. This can happen when the correlation is due to a third "confounding" variable that is correlated with both A and B. For example: just because having a college degree is correlated with high earnings as an adult doesn't mean that getting a degree CAUSED those earnings to go up - it could be that "having rich parents" both allows people to get a degree and then separately helps them earn more (even if going to college actually does nothing). Predictive models try to account for this problem by statistically "controlling for" confounding variables. So in the above case we could use statistical modeling to analyze the relationship between a degree and earnings after accounting for the fact that people with rich parents are more likely to have a degree. Unfortunately, it's never possible in practice to control for EVERY confounding variable. This is partly because important variables (like the student's "personal motivation") may not exist or be impossible to measure. Even controlling for "parents being rich" is tricky - what single number could perfectly capture a family's entire economic situation? And how can we be sure that the data we have are accurate? Do any of us know PRECISELY how "rich" our parents were when we were growing up? Another problem with predictive models is that even if you COULD control for everything they can't distinguish between A causing B or B causing A. So if we were trying to analyze the effect of depression on opiate use, no matter what control variables we include we can't be sure that the effect we observe isn't just due to opiate use CAUSING depression. Note that this is probably NOT a problem for our earlier example because it's impossible for your earnings as an adult to CAUSE you to have gone to college earlier in your life. This is one way in which our theoretical understanding of how these variables work helps us to understand the threats to causal inference. The only way to completely ensure that a relationship between A and B is causal is to experimentally control how people get "assigned" to different values of A (e.g. to get a college degree or not). If assignment to A is completely random then we can be sure that NOTHING else influenced A, which means that you don't have to worry about ANY confounding variables (even B) in analyzing the relationship between A and B. However, for reasons that are obvious when we're considering college degrees, random assignment is often infeasible or downright unethical. So we have to use other research design approaches to approximate the causal power of random assignment. Critically, these other approaches (instrumental variables, regression discontinuity, natural experiments) rely on the features of the world itself, and the data collection process, rather than statistical/mathematical methods, to address issues of confounding variables.
Explain in layperson's terms why predictive models aren't causally interpretable First of all, I don't think this should be treated as a strict dichotomy: "predictive models can never establish causal inference." There are various situations in which a predictive model gives us "p
11,449
Explain in layperson's terms why predictive models aren't causally interpretable
I think this explanation is best approached sequentially. Start with a simple story: When my dog Winston wags his tail, that indicates he is happy. For instance, he never wags it at the vet, wags it a bit when I get his leash, and wags a whole lot when I also grab a tennis ball. But if I wag Winston's tail for him, it usually has the opposite effect. In other words, a "wagging tail" is a good predictor of my dog's state of mind, but I cannot use this knowledge to make him happy (except as a kind of proxy variable in experiments). Here the causality is pretty straightforward, so the contrast between prediction and cause is stark. The next parable is both more realistic and closer to home: If you look at the performance of salespeople at my company, the ones with expensive cars are the most productive. While it is possible that clients find luxury cars impressive, and that makes selling to them easier, our sales happen over the phone, so it is unlikely that giving our salespeople nice cars will boost revenue (unless there is a promise to let the customer take the Porsche for a spin after the deal is sealed). The causality goes the other way here, though there is a slight potential for the correlation between sales and cars to be causal. Now for another example: It is evident that people who have our app installed on their phone buy more than folks that only shop in person and/or through the website. The app sends notifications and it makes it much easier to buy stuff with just a click. But people don't just install the app for no reason. They do it because they expect to buy more, which the app makes more convenient, so comparing customers with and without the app is like comparing apples and orangutans. They are very different people. Here there is causality in both directions, but arguably the high intent $ \rightarrow$ expenditures mechanism dominates the app install $\rightarrow$ expenditures. When a causal explanation works in both directions, you can usually settle the debate with an experiment to see which one is the most important. The real world is vastly more complicated than these fairly simple stories, and our intuition can often lead us astray at a great cost. Here are two more good examples from industry of mistaking correlation for causation: Ascarza, Eva. Retention Futility: Targeting High-Risk Customers Might Be Ineffective. Journal of Marketing Research (JMR) 55, no. 1 (February 2018): 80–98. Blake, T., Nosko, C. and Tadelis, S. (2015), Consumer Heterogeneity and Paid Search Effectiveness: A Large-Scale Field Experiment. Econometrica, 83: 155-174. https://doi.org/10.3982/ECTA12423
Explain in layperson's terms why predictive models aren't causally interpretable
I think this explanation is best approached sequentially. Start with a simple story: When my dog Winston wags his tail, that indicates he is happy. For instance, he never wags it at the vet, wags it
Explain in layperson's terms why predictive models aren't causally interpretable I think this explanation is best approached sequentially. Start with a simple story: When my dog Winston wags his tail, that indicates he is happy. For instance, he never wags it at the vet, wags it a bit when I get his leash, and wags a whole lot when I also grab a tennis ball. But if I wag Winston's tail for him, it usually has the opposite effect. In other words, a "wagging tail" is a good predictor of my dog's state of mind, but I cannot use this knowledge to make him happy (except as a kind of proxy variable in experiments). Here the causality is pretty straightforward, so the contrast between prediction and cause is stark. The next parable is both more realistic and closer to home: If you look at the performance of salespeople at my company, the ones with expensive cars are the most productive. While it is possible that clients find luxury cars impressive, and that makes selling to them easier, our sales happen over the phone, so it is unlikely that giving our salespeople nice cars will boost revenue (unless there is a promise to let the customer take the Porsche for a spin after the deal is sealed). The causality goes the other way here, though there is a slight potential for the correlation between sales and cars to be causal. Now for another example: It is evident that people who have our app installed on their phone buy more than folks that only shop in person and/or through the website. The app sends notifications and it makes it much easier to buy stuff with just a click. But people don't just install the app for no reason. They do it because they expect to buy more, which the app makes more convenient, so comparing customers with and without the app is like comparing apples and orangutans. They are very different people. Here there is causality in both directions, but arguably the high intent $ \rightarrow$ expenditures mechanism dominates the app install $\rightarrow$ expenditures. When a causal explanation works in both directions, you can usually settle the debate with an experiment to see which one is the most important. The real world is vastly more complicated than these fairly simple stories, and our intuition can often lead us astray at a great cost. Here are two more good examples from industry of mistaking correlation for causation: Ascarza, Eva. Retention Futility: Targeting High-Risk Customers Might Be Ineffective. Journal of Marketing Research (JMR) 55, no. 1 (February 2018): 80–98. Blake, T., Nosko, C. and Tadelis, S. (2015), Consumer Heterogeneity and Paid Search Effectiveness: A Large-Scale Field Experiment. Econometrica, 83: 155-174. https://doi.org/10.3982/ECTA12423
Explain in layperson's terms why predictive models aren't causally interpretable I think this explanation is best approached sequentially. Start with a simple story: When my dog Winston wags his tail, that indicates he is happy. For instance, he never wags it at the vet, wags it
11,450
Explain in layperson's terms why predictive models aren't causally interpretable
I don't think you even need to posit a covariate adjustment set $\textbf{Z}$ nor the indexation of black-box models to convey in layman terms the main point. Assume the following: $y$ is number of people drowning in a given month in a given city $x$ is number of ice-cream sold in a given month in a given city $u$ is temperature in a given month in a given city, the unobserved confounder $x$ will be highly predictive of $y$, and most likely a model just using $x$ as a predictor will outperform models that use noisier measurements of the real causes or their instrumental variables. Clearly, the best predictive model is not necessarily the one that gives the most consistent causal estimate.
Explain in layperson's terms why predictive models aren't causally interpretable
I don't think you even need to posit a covariate adjustment set $\textbf{Z}$ nor the indexation of black-box models to convey in layman terms the main point. Assume the following: $y$ is number of pe
Explain in layperson's terms why predictive models aren't causally interpretable I don't think you even need to posit a covariate adjustment set $\textbf{Z}$ nor the indexation of black-box models to convey in layman terms the main point. Assume the following: $y$ is number of people drowning in a given month in a given city $x$ is number of ice-cream sold in a given month in a given city $u$ is temperature in a given month in a given city, the unobserved confounder $x$ will be highly predictive of $y$, and most likely a model just using $x$ as a predictor will outperform models that use noisier measurements of the real causes or their instrumental variables. Clearly, the best predictive model is not necessarily the one that gives the most consistent causal estimate.
Explain in layperson's terms why predictive models aren't causally interpretable I don't think you even need to posit a covariate adjustment set $\textbf{Z}$ nor the indexation of black-box models to convey in layman terms the main point. Assume the following: $y$ is number of pe
11,451
Explain in layperson's terms why predictive models aren't causally interpretable
Correlation does not equal causation. Predictive models using advanced techniques such as machine learning can be quite good at finding associations between predictive variables and an outcome, but this isn't the same as determining the causal relationships between those variables. For example, as a researcher you may find a strong correlation between homelessness ($Y$) and illegal drug use ($X$) in a city, and could even state with a high degree of accuracy you can predict a person is homeless if you know they're a drug user. Can you confidently report to the city government that illegal drug use causes homelessness: $X \rightarrow Y$, and therefore reducing drug use will reduce homelessness? No, not without either deducing or collecting more information about the causal relationship between $X$ and $Y$. Perhaps it's the reverse, homelessness causes a higher risk for illegal drug use: $X \leftarrow Y$? Or perhaps $X$ and $Y$ are not as closely related, or even completely independent, and there's in fact a third variable such as mental illness ($Z$) that causes both homelessness and illegal drug use: $X \leftarrow Z \rightarrow Y$? In both of these cases the structure of your causal inference model will have to be altered from what you might see in a typical predictive model. There are many other possibilities as well (such as mediator and collider variables) which must be accounted for or ruled out in order to draw a complete picture of the cause and effect relationships.
Explain in layperson's terms why predictive models aren't causally interpretable
Correlation does not equal causation. Predictive models using advanced techniques such as machine learning can be quite good at finding associations between predictive variables and an outcome, but th
Explain in layperson's terms why predictive models aren't causally interpretable Correlation does not equal causation. Predictive models using advanced techniques such as machine learning can be quite good at finding associations between predictive variables and an outcome, but this isn't the same as determining the causal relationships between those variables. For example, as a researcher you may find a strong correlation between homelessness ($Y$) and illegal drug use ($X$) in a city, and could even state with a high degree of accuracy you can predict a person is homeless if you know they're a drug user. Can you confidently report to the city government that illegal drug use causes homelessness: $X \rightarrow Y$, and therefore reducing drug use will reduce homelessness? No, not without either deducing or collecting more information about the causal relationship between $X$ and $Y$. Perhaps it's the reverse, homelessness causes a higher risk for illegal drug use: $X \leftarrow Y$? Or perhaps $X$ and $Y$ are not as closely related, or even completely independent, and there's in fact a third variable such as mental illness ($Z$) that causes both homelessness and illegal drug use: $X \leftarrow Z \rightarrow Y$? In both of these cases the structure of your causal inference model will have to be altered from what you might see in a typical predictive model. There are many other possibilities as well (such as mediator and collider variables) which must be accounted for or ruled out in order to draw a complete picture of the cause and effect relationships.
Explain in layperson's terms why predictive models aren't causally interpretable Correlation does not equal causation. Predictive models using advanced techniques such as machine learning can be quite good at finding associations between predictive variables and an outcome, but th
11,452
Explain in layperson's terms why predictive models aren't causally interpretable
Oo Oo! I'm a mathematical layperson! Let's see if I can do this: TLDR: I use predictions (or "predictive models") to prepare for events beyond my control without having to know what actually causes them. I might posit that a lay predictive model is "whether the weather report says it will rain this weekend". I may not care what will cause it to rain or not rain on this particular weekend, I cannot change it, and I only care about whether to pack my fishing equipment. Contrast this with something I want to control: The weather in my house!!! If I keep my roof in good shape, it probably will not rain. If I set the thermostat for 74 degrees, it will probably stay between 72 and 76 degrees. If I keep my windows closed, it will probably not be windy. Etc. I can depend on known, causal chains to control some things. But, I use predictive models to prepare for things beyond my control.
Explain in layperson's terms why predictive models aren't causally interpretable
Oo Oo! I'm a mathematical layperson! Let's see if I can do this: TLDR: I use predictions (or "predictive models") to prepare for events beyond my control without having to know what actually causes t
Explain in layperson's terms why predictive models aren't causally interpretable Oo Oo! I'm a mathematical layperson! Let's see if I can do this: TLDR: I use predictions (or "predictive models") to prepare for events beyond my control without having to know what actually causes them. I might posit that a lay predictive model is "whether the weather report says it will rain this weekend". I may not care what will cause it to rain or not rain on this particular weekend, I cannot change it, and I only care about whether to pack my fishing equipment. Contrast this with something I want to control: The weather in my house!!! If I keep my roof in good shape, it probably will not rain. If I set the thermostat for 74 degrees, it will probably stay between 72 and 76 degrees. If I keep my windows closed, it will probably not be windy. Etc. I can depend on known, causal chains to control some things. But, I use predictive models to prepare for things beyond my control.
Explain in layperson's terms why predictive models aren't causally interpretable Oo Oo! I'm a mathematical layperson! Let's see if I can do this: TLDR: I use predictions (or "predictive models") to prepare for events beyond my control without having to know what actually causes t
11,453
Explain in layperson's terms why predictive models aren't causally interpretable
The basic problem is that a non-causal predictive model may fail if used for interventions. Start with a very simple example where an important part of the real world has: $$ Cause \rightarrow \mathit{Effect} \rightarrow Measurement $$ Because we imagine Measurement is nearly perfect, the best predictive model will prefer it to a noisier Cause, but Measurement can only be known after Effect, so it cannot inform policies or interventions. Changing Measurement by some other means won't change Effect at all. ~ * ~ Possibly that's sufficient, but more detail below. ~ * ~ If Measurement is something like income or health or quality, you can of course measure it ahead of time, but then it's not really the right measurement, because it hasn't taken Effect into account yet. The predictions won't be as good. Here you would have done better to use Cause, if known. Often Cause is not known, and Measurement could be as good a predictor as you like. In the ultimate example, we have entangled particles: $$ \mathit{Spin\ 1} \leftarrow \mathit{Hidden\ Cause} \rightarrow \mathit{Spin\ 2} $$ In this case, Spin 2 is a perfect predictor of Spin 1, but it can't ever be used to change Spin 1: they both simply reflect a hidden common cause. In a less extreme example, ice-cream sales and drownings are both caused by heat, but also other things: $$Other1 \rightarrow Sales \leftarrow \mathbf{Heat} \rightarrow Drownings \leftarrow Other2$$ We can't reduce drownings by banning ice-cream, and we can't do much about Heat, however predictive, but we can make policies about Other2. (And ice-cream sales could be an early warning allowing us to act.) Usually there is no one perfect Measurement, so we manufacture one: our predictive model cleverly combines Many things. But even if it correctly accounts for dependencies among Many things, it doesn't help policy or interventions if Many things are downstream of Effect. If Measurement is downstream of both Cause and Effect, then the model can fail in stranger ways, esp. if it was cleverly trying to control things statistically.
Explain in layperson's terms why predictive models aren't causally interpretable
The basic problem is that a non-causal predictive model may fail if used for interventions. Start with a very simple example where an important part of the real world has: $$ Cause \rightarrow \mathit
Explain in layperson's terms why predictive models aren't causally interpretable The basic problem is that a non-causal predictive model may fail if used for interventions. Start with a very simple example where an important part of the real world has: $$ Cause \rightarrow \mathit{Effect} \rightarrow Measurement $$ Because we imagine Measurement is nearly perfect, the best predictive model will prefer it to a noisier Cause, but Measurement can only be known after Effect, so it cannot inform policies or interventions. Changing Measurement by some other means won't change Effect at all. ~ * ~ Possibly that's sufficient, but more detail below. ~ * ~ If Measurement is something like income or health or quality, you can of course measure it ahead of time, but then it's not really the right measurement, because it hasn't taken Effect into account yet. The predictions won't be as good. Here you would have done better to use Cause, if known. Often Cause is not known, and Measurement could be as good a predictor as you like. In the ultimate example, we have entangled particles: $$ \mathit{Spin\ 1} \leftarrow \mathit{Hidden\ Cause} \rightarrow \mathit{Spin\ 2} $$ In this case, Spin 2 is a perfect predictor of Spin 1, but it can't ever be used to change Spin 1: they both simply reflect a hidden common cause. In a less extreme example, ice-cream sales and drownings are both caused by heat, but also other things: $$Other1 \rightarrow Sales \leftarrow \mathbf{Heat} \rightarrow Drownings \leftarrow Other2$$ We can't reduce drownings by banning ice-cream, and we can't do much about Heat, however predictive, but we can make policies about Other2. (And ice-cream sales could be an early warning allowing us to act.) Usually there is no one perfect Measurement, so we manufacture one: our predictive model cleverly combines Many things. But even if it correctly accounts for dependencies among Many things, it doesn't help policy or interventions if Many things are downstream of Effect. If Measurement is downstream of both Cause and Effect, then the model can fail in stranger ways, esp. if it was cleverly trying to control things statistically.
Explain in layperson's terms why predictive models aren't causally interpretable The basic problem is that a non-causal predictive model may fail if used for interventions. Start with a very simple example where an important part of the real world has: $$ Cause \rightarrow \mathit
11,454
Explain in layperson's terms why predictive models aren't causally interpretable
If it's a person who really knows barely anything about statistics and causation I would provide some examples that are straightforward. If you have data on the number of bathrooms in someone's largest house, you can classify the person as a billionaire or not, in the sense that billionaire mansions have numerous bathrooms. I'd assume you could achieve some precise estimates in this problem. However, increasing the number of bathrooms in someone's house won't make them billionaires. So you could use such a model to identify billionaires, but not to make someone a billionaire. Correlation, but not causation. Another common example is the ice cream consumption relationship to shark attacks (being confounded by temperature). In some places, you could get some reasonable prediction of shark attacks based on ice cream consumption. But throwing more sharks in beaches wouldn't make people eat more ice cream (at least not to the same extent you measured with the confounded estimate). I agree with Graham Wright that this should not be a dichotomy. You can have predictions based on causal models, for example. If the person knows some statistics, I would go for a different approach, like the other answers, but if it's my not-even-high-school-diploma grandma, I would go for the intuitive examples I gave above.
Explain in layperson's terms why predictive models aren't causally interpretable
If it's a person who really knows barely anything about statistics and causation I would provide some examples that are straightforward. If you have data on the number of bathrooms in someone's larges
Explain in layperson's terms why predictive models aren't causally interpretable If it's a person who really knows barely anything about statistics and causation I would provide some examples that are straightforward. If you have data on the number of bathrooms in someone's largest house, you can classify the person as a billionaire or not, in the sense that billionaire mansions have numerous bathrooms. I'd assume you could achieve some precise estimates in this problem. However, increasing the number of bathrooms in someone's house won't make them billionaires. So you could use such a model to identify billionaires, but not to make someone a billionaire. Correlation, but not causation. Another common example is the ice cream consumption relationship to shark attacks (being confounded by temperature). In some places, you could get some reasonable prediction of shark attacks based on ice cream consumption. But throwing more sharks in beaches wouldn't make people eat more ice cream (at least not to the same extent you measured with the confounded estimate). I agree with Graham Wright that this should not be a dichotomy. You can have predictions based on causal models, for example. If the person knows some statistics, I would go for a different approach, like the other answers, but if it's my not-even-high-school-diploma grandma, I would go for the intuitive examples I gave above.
Explain in layperson's terms why predictive models aren't causally interpretable If it's a person who really knows barely anything about statistics and causation I would provide some examples that are straightforward. If you have data on the number of bathrooms in someone's larges
11,455
After bootstrapping regression analysis, all p-values are multiple of 0.001996
Suppose you have a regression coefficient estimate of 1.2. To compute its p-value, you need to know the probability of observing a coefficient that large (or larger) under the null hypothesis. To do this, you have to know the null distribution of this coefficient. Bootstrap resampling is one way to estimate this null distribution. For a regression, across your 500 bootstrap samples, you're going to get a distribution of regression coefficients with a mean that will be close to 1.2. Let's say the mean of the bootstrap-sampled coefficients is 1.19. Let's also say that your null hypothesis is that the true value of the coefficient is 0. This means that the null distribution of this coefficient should have a mean of 0. We can make our 500 bootstrap-sampled coefficients have a mean of 0 by simply subtracting their current mean of 1.19. This now allows us to use the bootstrap distribution as an estimate of the null distribution. Then, to calculate a (two-tailed) p-value, we can simply calculate the proportion of our 500 shifted coefficients whose absolute value is larger than the observed value of 1.2. For instance, if 6 of them are larger, that gives us a p-value of 6/500 = 0.012. Notice that any p-value that we calculate this way will always be some integer number divided by 500. So the only p-values that can come out of this calculation are values that are an integer multiple of 0.002, i.e. 1/500. The values you got were multiples not of 0.002, but of 0.001996. This turns out to be pretty much exactly equal to 1/501. The reason for this discrepancy of 1, is that the "regular" p-value calculated from a bootstrap has a bias. The regular formula is $\hat{p}=\frac{x}{N}$, where $x$ is the number of bootstrap-sampled coefficients that were larger than your observed value, and $N$ is the number of bootstrap samples. The bias-corrected formula is $\hat{p}=\frac{x+1}{N+1}$. So, any p-value resulting from this formula will be an integer multiple of $\frac{1}{N+1}$, which in your case is 1/501.
After bootstrapping regression analysis, all p-values are multiple of 0.001996
Suppose you have a regression coefficient estimate of 1.2. To compute its p-value, you need to know the probability of observing a coefficient that large (or larger) under the null hypothesis. To do t
After bootstrapping regression analysis, all p-values are multiple of 0.001996 Suppose you have a regression coefficient estimate of 1.2. To compute its p-value, you need to know the probability of observing a coefficient that large (or larger) under the null hypothesis. To do this, you have to know the null distribution of this coefficient. Bootstrap resampling is one way to estimate this null distribution. For a regression, across your 500 bootstrap samples, you're going to get a distribution of regression coefficients with a mean that will be close to 1.2. Let's say the mean of the bootstrap-sampled coefficients is 1.19. Let's also say that your null hypothesis is that the true value of the coefficient is 0. This means that the null distribution of this coefficient should have a mean of 0. We can make our 500 bootstrap-sampled coefficients have a mean of 0 by simply subtracting their current mean of 1.19. This now allows us to use the bootstrap distribution as an estimate of the null distribution. Then, to calculate a (two-tailed) p-value, we can simply calculate the proportion of our 500 shifted coefficients whose absolute value is larger than the observed value of 1.2. For instance, if 6 of them are larger, that gives us a p-value of 6/500 = 0.012. Notice that any p-value that we calculate this way will always be some integer number divided by 500. So the only p-values that can come out of this calculation are values that are an integer multiple of 0.002, i.e. 1/500. The values you got were multiples not of 0.002, but of 0.001996. This turns out to be pretty much exactly equal to 1/501. The reason for this discrepancy of 1, is that the "regular" p-value calculated from a bootstrap has a bias. The regular formula is $\hat{p}=\frac{x}{N}$, where $x$ is the number of bootstrap-sampled coefficients that were larger than your observed value, and $N$ is the number of bootstrap samples. The bias-corrected formula is $\hat{p}=\frac{x+1}{N+1}$. So, any p-value resulting from this formula will be an integer multiple of $\frac{1}{N+1}$, which in your case is 1/501.
After bootstrapping regression analysis, all p-values are multiple of 0.001996 Suppose you have a regression coefficient estimate of 1.2. To compute its p-value, you need to know the probability of observing a coefficient that large (or larger) under the null hypothesis. To do t
11,456
How to perform post-hoc test on lmer model?
You could use emmeans::emmeans() or lmerTest::difflsmeans(), or multcomp::glht(). I prefer emmeans (previously lsmeans). library(emmeans) emmeans(model, list(pairwise ~ Group), adjust = "tukey") The next option is difflsmeans. Note difflsmeans cannot correct for multiple comparisons, and uses the Satterthwaite method for calculating degrees of freedom as default instead of the Kenward-Roger method used by default by emmeans, so it might be best to explicitly specify the method you prefer. library(lmerTest) difflsmeans(model, test.effs = "Group", ddf="Kenward-Roger") The multcomp::glht() method is described in the other answer to this question, by Hack-R. Also, you can get the ANOVA p-values by loading lmerTest and then using anova. library(lmerTest) lmerTest::anova(model) Just to be clear, you intended for the Value to be assessed three times for each subject, right? It looks like Group is "within-subjects", not "between-subjects."
How to perform post-hoc test on lmer model?
You could use emmeans::emmeans() or lmerTest::difflsmeans(), or multcomp::glht(). I prefer emmeans (previously lsmeans). library(emmeans) emmeans(model, list(pairwise ~ Group), adjust = "tukey") The
How to perform post-hoc test on lmer model? You could use emmeans::emmeans() or lmerTest::difflsmeans(), or multcomp::glht(). I prefer emmeans (previously lsmeans). library(emmeans) emmeans(model, list(pairwise ~ Group), adjust = "tukey") The next option is difflsmeans. Note difflsmeans cannot correct for multiple comparisons, and uses the Satterthwaite method for calculating degrees of freedom as default instead of the Kenward-Roger method used by default by emmeans, so it might be best to explicitly specify the method you prefer. library(lmerTest) difflsmeans(model, test.effs = "Group", ddf="Kenward-Roger") The multcomp::glht() method is described in the other answer to this question, by Hack-R. Also, you can get the ANOVA p-values by loading lmerTest and then using anova. library(lmerTest) lmerTest::anova(model) Just to be clear, you intended for the Value to be assessed three times for each subject, right? It looks like Group is "within-subjects", not "between-subjects."
How to perform post-hoc test on lmer model? You could use emmeans::emmeans() or lmerTest::difflsmeans(), or multcomp::glht(). I prefer emmeans (previously lsmeans). library(emmeans) emmeans(model, list(pairwise ~ Group), adjust = "tukey") The
11,457
How to perform post-hoc test on lmer model?
After you've fit your lmer model you can do ANOVA, MANOVA, and multiple comparison procedures on the model object, like this: library(multcomp) summary(glht(model, linfct = mcp(Group = "Tukey")), test = adjusted("holm")) Simultaneous Tests for General Linear Hypotheses Multiple Comparisons of Means: Tukey Contrasts Fit: lmer(formula = Value ~ Group + (1 | Subject), data = data) Linear Hypotheses: Estimate Std. Error z value Pr(>|z|) G2 - G1 == 0 -1.12666 0.46702 -2.412 0.0378 * G3 - G1 == 0 0.03828 0.46702 0.082 0.9347 G3 - G2 == 0 1.16495 0.46702 2.494 0.0378 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Adjusted p values reported -- holm method) As for the convention in academic papers, that's going to vary a lot by field, journal, and specific subject matter. So for that case just review related articles and see what they do.
How to perform post-hoc test on lmer model?
After you've fit your lmer model you can do ANOVA, MANOVA, and multiple comparison procedures on the model object, like this: library(multcomp) summary(glht(model, linfct = mcp(Group = "Tukey")), test
How to perform post-hoc test on lmer model? After you've fit your lmer model you can do ANOVA, MANOVA, and multiple comparison procedures on the model object, like this: library(multcomp) summary(glht(model, linfct = mcp(Group = "Tukey")), test = adjusted("holm")) Simultaneous Tests for General Linear Hypotheses Multiple Comparisons of Means: Tukey Contrasts Fit: lmer(formula = Value ~ Group + (1 | Subject), data = data) Linear Hypotheses: Estimate Std. Error z value Pr(>|z|) G2 - G1 == 0 -1.12666 0.46702 -2.412 0.0378 * G3 - G1 == 0 0.03828 0.46702 0.082 0.9347 G3 - G2 == 0 1.16495 0.46702 2.494 0.0378 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Adjusted p values reported -- holm method) As for the convention in academic papers, that's going to vary a lot by field, journal, and specific subject matter. So for that case just review related articles and see what they do.
How to perform post-hoc test on lmer model? After you've fit your lmer model you can do ANOVA, MANOVA, and multiple comparison procedures on the model object, like this: library(multcomp) summary(glht(model, linfct = mcp(Group = "Tukey")), test
11,458
How to perform post-hoc test on lmer model?
Why not just do a pairwise t.test, with either holm or bonferroni correction, between your groups, using the fitted values from the model, since you see that your group2 varies significantly in your linear model? You could then draw a comparison between all 3 groups from your data. In which case, you could just write: PT <- pairwise.t.test(fitted.Values,Group, method=bonferroni)
How to perform post-hoc test on lmer model?
Why not just do a pairwise t.test, with either holm or bonferroni correction, between your groups, using the fitted values from the model, since you see that your group2 varies significantly in your l
How to perform post-hoc test on lmer model? Why not just do a pairwise t.test, with either holm or bonferroni correction, between your groups, using the fitted values from the model, since you see that your group2 varies significantly in your linear model? You could then draw a comparison between all 3 groups from your data. In which case, you could just write: PT <- pairwise.t.test(fitted.Values,Group, method=bonferroni)
How to perform post-hoc test on lmer model? Why not just do a pairwise t.test, with either holm or bonferroni correction, between your groups, using the fitted values from the model, since you see that your group2 varies significantly in your l
11,459
The paradox of i.i.d. data (at least for me)
I think you are confusing an estimated model of a distribution with a random variable. Let's rewrite the independence assumption as follows: $$ P(X_n | \theta, X_{i_1}, X_{i_2}, \dots, X_{i_k}) = P(X_n | \theta) \tag{1} $$ which says that if you know the underlying distribution of $X_n$ (and, for example, can identify it by a set of parameters $\theta$) then the distribution does not change given that you have observed a few samples from it. For example, think of $X_n$ as the random variable representing the outcome of the $n$-th toss of a coin. Knowing the probability of head and tail for the coin (which, btw, assume is encoded in $\theta$) is enough to know the distribution of $X_n$. In particular, the outcome of the previous tosses does not change the probability of head or tail for the $n$-th toss, and $(1)$ holds. Note, however, that $P(\theta | X_n) \neq P(\theta | X_{i_1}, X_{i_2}, \dots, X_{i_k})$.
The paradox of i.i.d. data (at least for me)
I think you are confusing an estimated model of a distribution with a random variable. Let's rewrite the independence assumption as follows: $$ P(X_n | \theta, X_{i_1}, X_{i_2}, \dots, X_{i_k}) = P(X_
The paradox of i.i.d. data (at least for me) I think you are confusing an estimated model of a distribution with a random variable. Let's rewrite the independence assumption as follows: $$ P(X_n | \theta, X_{i_1}, X_{i_2}, \dots, X_{i_k}) = P(X_n | \theta) \tag{1} $$ which says that if you know the underlying distribution of $X_n$ (and, for example, can identify it by a set of parameters $\theta$) then the distribution does not change given that you have observed a few samples from it. For example, think of $X_n$ as the random variable representing the outcome of the $n$-th toss of a coin. Knowing the probability of head and tail for the coin (which, btw, assume is encoded in $\theta$) is enough to know the distribution of $X_n$. In particular, the outcome of the previous tosses does not change the probability of head or tail for the $n$-th toss, and $(1)$ holds. Note, however, that $P(\theta | X_n) \neq P(\theta | X_{i_1}, X_{i_2}, \dots, X_{i_k})$.
The paradox of i.i.d. data (at least for me) I think you are confusing an estimated model of a distribution with a random variable. Let's rewrite the independence assumption as follows: $$ P(X_n | \theta, X_{i_1}, X_{i_2}, \dots, X_{i_k}) = P(X_
11,460
The paradox of i.i.d. data (at least for me)
If you take a Bayesian approach and treat parameters describing the distribution of $X$ as a random variable/vector, then the observations indeed are not independent, but they would be conditionally independent given knowledge of $\theta$ hence $P(X_n \mid X_{n-1}, \ldots X_1, \theta) = P(X_n \mid \theta)$ would hold. In a classical statistical approach, $\theta$ is not a random variable. Calculations are done as if we know what $\theta$ is. In some sense, you're always conditioning on $\theta$ (even if you don't know the value). When you wrote, "... provide information about the distribution structure, and as a result about $X_n$" you implicitly were adopting a Bayesian approach but not doing it precisely. You're writing a property of IID samples that a frequentist would write, but the corresponding statement in a Bayesian setup would involve conditioning on $\theta$. Bayesian vs. Classical statisticians Let $x_i$ be the result of flipping a lopsided, unfair coin. We don't know the probability the coin lands heads. To the classical statistician, the frequentist, $P(x_i = H)$ is some parameter, let's call it $\theta$. Observe that $\theta$ here is a scalar, like the number 1/3. We may not know what the number is, but it's some number! It is not random! To the Bayesian statistician, $\theta$ itself is a random variable! This is extremely different! The key idea here is that the Bayesian statistician extends the tools of probability to situations where the classical statistician doesn't. To the frequentist, $\theta$ isn't a random variable because it only has one possible value! Multiple outcomes are not possible! In the Bayesian's imagination though, multiple values of $\theta$ are possible, and the Bayesian is willing to model that uncertainty (in his own mind) using the tools of probability. Where is this going? Let's say we flip the coin $n$ times. One flip does not affect the outcome of the other. The classical statistician would call these independent flips (and indeed they are). We'll have: $$P(x_n=H \mid x_{n-1}, x_{n-2}, \ldots,x_{1}) = P(x_n=H) = \theta $$ Where $\theta$ is some unknown parameter. (Remember, we don't know what it is, but it's not a random variable! It's some number.) A Bayesian deep into subjective probability would say that what matters is the probability from her perspective!. If she sees 10 heads in a row, an 11th head is more likely because 10 heads in a row leads one to believe the coin is lopsided in favor of heads. $$P(x_{11} = H \mid x_{10}=H, x_{9}=H, \ldots,x_{1}=H) > P(x_1 = H)$$ What has happened here? What is different?! Updating beliefs about a latent random variable $\theta$! If $\theta$ is treated as a random variable, the flips aren't independent anymore. But, the flips are conditionally independent given the value of $\theta$. $$P(x_{11} = H \mid x_{10}=H, x_{9}=H, \ldots,x_{1}=H, \theta) = P(x_1 = H \mid \theta) = \theta $$ Conditioning on $\theta$ in a sense connects how the Bayesian and the classical statistician models the problem. Or to put it another way, the frequentist and the Bayesian statistician will agree if the Bayesian conditions on $\theta$. Further notes I've tried my best to give a short intro here, but what I've done is at best quite superficial and the concepts are in some sense quite deep. If you want to take a dive into the philosophy of probability, Savage's 1954 book, Foundation of Statistics is a classic. Google for bayesian vs. frequentist and a ton of stuff will come up. Another way to think about IID draws is de Finetti's theorem and the notion of exchangeability. In a Bayesian framework, exchangeability is equivalent to independence conditional on some latent random variable (in this case, the lopsidedness of the coin).
The paradox of i.i.d. data (at least for me)
If you take a Bayesian approach and treat parameters describing the distribution of $X$ as a random variable/vector, then the observations indeed are not independent, but they would be conditionally i
The paradox of i.i.d. data (at least for me) If you take a Bayesian approach and treat parameters describing the distribution of $X$ as a random variable/vector, then the observations indeed are not independent, but they would be conditionally independent given knowledge of $\theta$ hence $P(X_n \mid X_{n-1}, \ldots X_1, \theta) = P(X_n \mid \theta)$ would hold. In a classical statistical approach, $\theta$ is not a random variable. Calculations are done as if we know what $\theta$ is. In some sense, you're always conditioning on $\theta$ (even if you don't know the value). When you wrote, "... provide information about the distribution structure, and as a result about $X_n$" you implicitly were adopting a Bayesian approach but not doing it precisely. You're writing a property of IID samples that a frequentist would write, but the corresponding statement in a Bayesian setup would involve conditioning on $\theta$. Bayesian vs. Classical statisticians Let $x_i$ be the result of flipping a lopsided, unfair coin. We don't know the probability the coin lands heads. To the classical statistician, the frequentist, $P(x_i = H)$ is some parameter, let's call it $\theta$. Observe that $\theta$ here is a scalar, like the number 1/3. We may not know what the number is, but it's some number! It is not random! To the Bayesian statistician, $\theta$ itself is a random variable! This is extremely different! The key idea here is that the Bayesian statistician extends the tools of probability to situations where the classical statistician doesn't. To the frequentist, $\theta$ isn't a random variable because it only has one possible value! Multiple outcomes are not possible! In the Bayesian's imagination though, multiple values of $\theta$ are possible, and the Bayesian is willing to model that uncertainty (in his own mind) using the tools of probability. Where is this going? Let's say we flip the coin $n$ times. One flip does not affect the outcome of the other. The classical statistician would call these independent flips (and indeed they are). We'll have: $$P(x_n=H \mid x_{n-1}, x_{n-2}, \ldots,x_{1}) = P(x_n=H) = \theta $$ Where $\theta$ is some unknown parameter. (Remember, we don't know what it is, but it's not a random variable! It's some number.) A Bayesian deep into subjective probability would say that what matters is the probability from her perspective!. If she sees 10 heads in a row, an 11th head is more likely because 10 heads in a row leads one to believe the coin is lopsided in favor of heads. $$P(x_{11} = H \mid x_{10}=H, x_{9}=H, \ldots,x_{1}=H) > P(x_1 = H)$$ What has happened here? What is different?! Updating beliefs about a latent random variable $\theta$! If $\theta$ is treated as a random variable, the flips aren't independent anymore. But, the flips are conditionally independent given the value of $\theta$. $$P(x_{11} = H \mid x_{10}=H, x_{9}=H, \ldots,x_{1}=H, \theta) = P(x_1 = H \mid \theta) = \theta $$ Conditioning on $\theta$ in a sense connects how the Bayesian and the classical statistician models the problem. Or to put it another way, the frequentist and the Bayesian statistician will agree if the Bayesian conditions on $\theta$. Further notes I've tried my best to give a short intro here, but what I've done is at best quite superficial and the concepts are in some sense quite deep. If you want to take a dive into the philosophy of probability, Savage's 1954 book, Foundation of Statistics is a classic. Google for bayesian vs. frequentist and a ton of stuff will come up. Another way to think about IID draws is de Finetti's theorem and the notion of exchangeability. In a Bayesian framework, exchangeability is equivalent to independence conditional on some latent random variable (in this case, the lopsidedness of the coin).
The paradox of i.i.d. data (at least for me) If you take a Bayesian approach and treat parameters describing the distribution of $X$ as a random variable/vector, then the observations indeed are not independent, but they would be conditionally i
11,461
What do the fully connected layers do in CNNs?
The output from the convolutional layers represents high-level features in the data. While that output could be flattened and connected to the output layer, adding a fully-connected layer is a (usually) cheap way of learning non-linear combinations of these features. Essentially the convolutional layers are providing a meaningful, low-dimensional, and somewhat invariant feature space, and the fully-connected layer is learning a (possibly non-linear) function in that space. NOTE: It is trivial to convert from FC layers to Conv layers. Converting these top FC layers to Conv layers can be helpful as this page describes.
What do the fully connected layers do in CNNs?
The output from the convolutional layers represents high-level features in the data. While that output could be flattened and connected to the output layer, adding a fully-connected layer is a (usual
What do the fully connected layers do in CNNs? The output from the convolutional layers represents high-level features in the data. While that output could be flattened and connected to the output layer, adding a fully-connected layer is a (usually) cheap way of learning non-linear combinations of these features. Essentially the convolutional layers are providing a meaningful, low-dimensional, and somewhat invariant feature space, and the fully-connected layer is learning a (possibly non-linear) function in that space. NOTE: It is trivial to convert from FC layers to Conv layers. Converting these top FC layers to Conv layers can be helpful as this page describes.
What do the fully connected layers do in CNNs? The output from the convolutional layers represents high-level features in the data. While that output could be flattened and connected to the output layer, adding a fully-connected layer is a (usual
11,462
What do the fully connected layers do in CNNs?
I found this answer by Anil-Sharma on Quora helpful. We can divide the whole network (for classification) into two parts: Feature extraction: In the conventional classification algorithms, like SVMs, we used to extract features from the data to make the classification work. The convolutional layers are serving the same purpose of feature extraction. CNNs capture better representation of data and hence we don’t need to do feature engineering. Classification: After feature extraction we need to classify the data into various classes, this can be done using a fully connected (FC) neural network. In place of fully connected layers, we can also use a conventional classifier like SVM. But we generally end up adding FC layers to make the model end-to-end trainable.
What do the fully connected layers do in CNNs?
I found this answer by Anil-Sharma on Quora helpful. We can divide the whole network (for classification) into two parts: Feature extraction: In the conventional classification algorithms, like SVMs
What do the fully connected layers do in CNNs? I found this answer by Anil-Sharma on Quora helpful. We can divide the whole network (for classification) into two parts: Feature extraction: In the conventional classification algorithms, like SVMs, we used to extract features from the data to make the classification work. The convolutional layers are serving the same purpose of feature extraction. CNNs capture better representation of data and hence we don’t need to do feature engineering. Classification: After feature extraction we need to classify the data into various classes, this can be done using a fully connected (FC) neural network. In place of fully connected layers, we can also use a conventional classifier like SVM. But we generally end up adding FC layers to make the model end-to-end trainable.
What do the fully connected layers do in CNNs? I found this answer by Anil-Sharma on Quora helpful. We can divide the whole network (for classification) into two parts: Feature extraction: In the conventional classification algorithms, like SVMs
11,463
What is the intuition of invertible process in time series?
In the AR($\infty$) representation, the most recent error can be written as a linear function of current and past observations: $$w_t = \sum_{j=0}^\infty (-\theta)^j x_{t-j}$$ For an invertible process, $|\theta|<1$ and so the most recent observations have higher weight than observations from the more distant past. But when $|\theta| > 1$, the weights increase as lags increase, so the more distant the observations the greater their influence on the current error. When $|\theta|=1$, the weights are constant in size, and the distant observations have the same influence as the recent observations. As neither of these situations make much sense, we prefer the invertible processes.
What is the intuition of invertible process in time series?
In the AR($\infty$) representation, the most recent error can be written as a linear function of current and past observations: $$w_t = \sum_{j=0}^\infty (-\theta)^j x_{t-j}$$ For an invertible proces
What is the intuition of invertible process in time series? In the AR($\infty$) representation, the most recent error can be written as a linear function of current and past observations: $$w_t = \sum_{j=0}^\infty (-\theta)^j x_{t-j}$$ For an invertible process, $|\theta|<1$ and so the most recent observations have higher weight than observations from the more distant past. But when $|\theta| > 1$, the weights increase as lags increase, so the more distant the observations the greater their influence on the current error. When $|\theta|=1$, the weights are constant in size, and the distant observations have the same influence as the recent observations. As neither of these situations make much sense, we prefer the invertible processes.
What is the intuition of invertible process in time series? In the AR($\infty$) representation, the most recent error can be written as a linear function of current and past observations: $$w_t = \sum_{j=0}^\infty (-\theta)^j x_{t-j}$$ For an invertible proces
11,464
What is the intuition of invertible process in time series?
A time series is invertible if errors can be inverted into a representation of past observations. For the time series data, the error ($\epsilon$) at time $t$ ($\epsilon_t$) can be represented as: $$\epsilon_t = \sum\limits_{i=0}^{\infty}(-\theta)^i \, y_{t-i}$$ With every lagged value ($y_{t-i})$, its coefficient is $i^{th}$ power of $\theta$ term. So, the infinite series converges to a finite value only if $|\theta|<1$, which also means that recent past observations are given more weight than distant past observations. Therefore, time series is invertible if $|\theta|<1$ (possibility of representing errors as linear combination of past observations)
What is the intuition of invertible process in time series?
A time series is invertible if errors can be inverted into a representation of past observations. For the time series data, the error ($\epsilon$) at time $t$ ($\epsilon_t$) can be represented as: $$\
What is the intuition of invertible process in time series? A time series is invertible if errors can be inverted into a representation of past observations. For the time series data, the error ($\epsilon$) at time $t$ ($\epsilon_t$) can be represented as: $$\epsilon_t = \sum\limits_{i=0}^{\infty}(-\theta)^i \, y_{t-i}$$ With every lagged value ($y_{t-i})$, its coefficient is $i^{th}$ power of $\theta$ term. So, the infinite series converges to a finite value only if $|\theta|<1$, which also means that recent past observations are given more weight than distant past observations. Therefore, time series is invertible if $|\theta|<1$ (possibility of representing errors as linear combination of past observations)
What is the intuition of invertible process in time series? A time series is invertible if errors can be inverted into a representation of past observations. For the time series data, the error ($\epsilon$) at time $t$ ($\epsilon_t$) can be represented as: $$\
11,465
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level?
For the most part, people use probability-symmetric confidence intervals (CIs). For example, a 95% confidence interval is made by cutting off probability 0.025 from each tail of the relevant distribution. For CIs based on the symmetrical normal and Student t distributions, the probability-symmetric interval is the shortest. However, notice that the usual phrase is to find "a 95% CI," not the 95% CI." This recognizes the possibility of alternatives to the probability-symmetric rule. CI for normal mean, SD known. Suppose you have a random sample of size $n=16$ from a normal population with unknown $\mu$ and known $\sigma=10.$ Then if $\bar X = 103.2$ the usual (probability-symmetric) CI for $\mu$ is $\bar X \pm 1.96(\sigma/\sqrt{n})$ or $(98.30, 108.10)$ of length $9.80.$ qz = qnorm(c(.025,.975)); qz [1] -1.959964 1.959964 103.2 + qz*10/sqrt(16) [1] 98.30009 108.09991 diff(103.2 + qz*10/sqrt(16)) [1] 9.79982 However, another possible 95% CI for $\mu$ is $(98.07, 107.90)$ of length $9.84.$ This interval also has 95% 'coverage probability'. This is very seldom done in practice because (a) it takes a little extra trouble, (b) for practical purposes the result is the same, and (c) the alternative interval is a little longer. qz = qnorm(c(.02,.97)); qz [1] -2.053749 1.880794 103.2 + qz*10/sqrt(16) [1] 98.06563 107.90198 diff(103.2 + qz*10/sqrt(16)) [1] 9.836356 CI for normal SD, mean unknown. Now suppose we hava a sample of size $n=16$ for a normal population with unknown $\mu$ and $\sigma$ and we want a 05% CI for $\sigma.$ If $S = 10.2$ then the probability-symmetric 95% CI for $\sigma,$ based on $\frac{(n-1)S^2}{\sigma^2} \sim \mathsf{Chisq}(\nu=n-1=16),$ is of the form $\left(\sqrt{\frac{(n-1)S^2}{U}}, \sqrt{\frac{(n-1)S^2}{L}}\right),$ where $L$ and $U$ cut probability 0.025 from the lower and upper tails, respectively, of $\mathsf{Chisq}(15).$ For our data, this computes to $(7.53,15.79)$ of length $8.25.$ qc=qchisq(c(.975,.025),15); qc [1] 27.488393 6.262138 sqrt(15*10.2^2/qc) [1] 7.53479 15.78645 diff(sqrt(15*10.2^2/qc)) [1] 8.251661 However, this is clearly not the shortest 95% CI based on this chi-squared distribution. If we cut probability 0.03 from the lower tail of the distribution and probability 0.02 from its upper tail, we can get the 95% CI $(7.43, 15.49)$ of length $8.06.$ qc=qchisq(c(.98,.03),15); qc [1] 28.259496 6.503225 sqrt(15*10.2^2/qc) [1] 7.431279 15.491070 diff(sqrt(15*10.2^2/qc)) [1] 8.05979 Moreover, cutting probability $0.04$ from the lower tail $(0.01$ from the upper), we'd get a CI of width $7.88.$ But a 4.5%-0.5% split gives a slightly longer interval than that. By trial and error (or a grid search) one could find (nearly) the shortest possible 95% CI. In my experience, even though such intervals are shorter, this is not usually done because (a) it is extra trouble and (b) for practical purposes, the result may be about the same. [However, in a practical application, if we were to get too far from cutting equal probabilities from the two tails, one may wonder whether a one-sided confidence interval (giving an upper or lower confidence bound on $\sigma)$ might be more useful.] Addendum. A plot of lengths of 95% CIs for $\sigma$ against the probability cut from the lower tail of $\mathsf{Chisq}(15).$ The minimum length $7.879782$ occurs when probability $0.041$ is cut from the lower tail. lp = seq(0.001, .049, by=.001) m = length(lp); len=numeric(m) for(i in 1:m) { L = qchisq(lp[i], 15) U = qchisq(.95+lp[i], 15) lcl = sqrt(15*10.2^2/U) ucl = sqrt(15*10.2^2/L) len[i] = ucl-lcl } plot(lp, len, type="l", lwd=2) min(len) [1] 7.879782 lp[len==min(len)] [1] 0.041
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l
For the most part, people use probability-symmetric confidence intervals (CIs). For example, a 95% confidence interval is made by cutting off probability 0.025 from each tail of the relevant distribut
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level? For the most part, people use probability-symmetric confidence intervals (CIs). For example, a 95% confidence interval is made by cutting off probability 0.025 from each tail of the relevant distribution. For CIs based on the symmetrical normal and Student t distributions, the probability-symmetric interval is the shortest. However, notice that the usual phrase is to find "a 95% CI," not the 95% CI." This recognizes the possibility of alternatives to the probability-symmetric rule. CI for normal mean, SD known. Suppose you have a random sample of size $n=16$ from a normal population with unknown $\mu$ and known $\sigma=10.$ Then if $\bar X = 103.2$ the usual (probability-symmetric) CI for $\mu$ is $\bar X \pm 1.96(\sigma/\sqrt{n})$ or $(98.30, 108.10)$ of length $9.80.$ qz = qnorm(c(.025,.975)); qz [1] -1.959964 1.959964 103.2 + qz*10/sqrt(16) [1] 98.30009 108.09991 diff(103.2 + qz*10/sqrt(16)) [1] 9.79982 However, another possible 95% CI for $\mu$ is $(98.07, 107.90)$ of length $9.84.$ This interval also has 95% 'coverage probability'. This is very seldom done in practice because (a) it takes a little extra trouble, (b) for practical purposes the result is the same, and (c) the alternative interval is a little longer. qz = qnorm(c(.02,.97)); qz [1] -2.053749 1.880794 103.2 + qz*10/sqrt(16) [1] 98.06563 107.90198 diff(103.2 + qz*10/sqrt(16)) [1] 9.836356 CI for normal SD, mean unknown. Now suppose we hava a sample of size $n=16$ for a normal population with unknown $\mu$ and $\sigma$ and we want a 05% CI for $\sigma.$ If $S = 10.2$ then the probability-symmetric 95% CI for $\sigma,$ based on $\frac{(n-1)S^2}{\sigma^2} \sim \mathsf{Chisq}(\nu=n-1=16),$ is of the form $\left(\sqrt{\frac{(n-1)S^2}{U}}, \sqrt{\frac{(n-1)S^2}{L}}\right),$ where $L$ and $U$ cut probability 0.025 from the lower and upper tails, respectively, of $\mathsf{Chisq}(15).$ For our data, this computes to $(7.53,15.79)$ of length $8.25.$ qc=qchisq(c(.975,.025),15); qc [1] 27.488393 6.262138 sqrt(15*10.2^2/qc) [1] 7.53479 15.78645 diff(sqrt(15*10.2^2/qc)) [1] 8.251661 However, this is clearly not the shortest 95% CI based on this chi-squared distribution. If we cut probability 0.03 from the lower tail of the distribution and probability 0.02 from its upper tail, we can get the 95% CI $(7.43, 15.49)$ of length $8.06.$ qc=qchisq(c(.98,.03),15); qc [1] 28.259496 6.503225 sqrt(15*10.2^2/qc) [1] 7.431279 15.491070 diff(sqrt(15*10.2^2/qc)) [1] 8.05979 Moreover, cutting probability $0.04$ from the lower tail $(0.01$ from the upper), we'd get a CI of width $7.88.$ But a 4.5%-0.5% split gives a slightly longer interval than that. By trial and error (or a grid search) one could find (nearly) the shortest possible 95% CI. In my experience, even though such intervals are shorter, this is not usually done because (a) it is extra trouble and (b) for practical purposes, the result may be about the same. [However, in a practical application, if we were to get too far from cutting equal probabilities from the two tails, one may wonder whether a one-sided confidence interval (giving an upper or lower confidence bound on $\sigma)$ might be more useful.] Addendum. A plot of lengths of 95% CIs for $\sigma$ against the probability cut from the lower tail of $\mathsf{Chisq}(15).$ The minimum length $7.879782$ occurs when probability $0.041$ is cut from the lower tail. lp = seq(0.001, .049, by=.001) m = length(lp); len=numeric(m) for(i in 1:m) { L = qchisq(lp[i], 15) U = qchisq(.95+lp[i], 15) lcl = sqrt(15*10.2^2/U) ucl = sqrt(15*10.2^2/L) len[i] = ucl-lcl } plot(lp, len, type="l", lwd=2) min(len) [1] 7.879782 lp[len==min(len)] [1] 0.041
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l For the most part, people use probability-symmetric confidence intervals (CIs). For example, a 95% confidence interval is made by cutting off probability 0.025 from each tail of the relevant distribut
11,466
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level?
Some theory on optimal confidence intervals Confidence intervals are formed from pivotal quantities, which are functions of the data and parameter of interest that have a distribution that does not depend on the parameters of the problem. Confidence "intervals" are a special case of the broader class of confidence sets, which need not be connected intervals. However, for the purposes of simplicity, we will restrict the present answer to cases where the confidence set is a single interval (i.e., a confidence interval). Suppose we want to form a confidence interval for the unknown parameter $\phi$ at confidence level $1-\alpha$ using the data $\mathbf{x}$. Consider a continuous pivotal quantity $H(\mathbf{x}, \phi)$ with a distribution that has quantile function $Q_H$. (Note that this function does not depend on the parameter $\phi$ or the data since it is a pivotal quantity.) Using the pivotal quantity, we can choose any value $0 \leqslant \theta \leqslant \alpha$ and form a probability interval from the quantile function. We then "invert" the inequality expression to turn this into an interval statement for the parameter of interest: $$\begin{align} 1-\alpha &= \mathbb{P}(Q_H(\theta) \leqslant H(\mathbf{X}, \phi) \leqslant Q_H(1-\alpha+\theta)) \\[6pt] &= \mathbb{P}(L_\mathbf{X}(\alpha, \theta) \leqslant \phi \leqslant U_\mathbf{X}(\alpha, \theta)). \\[6pt] \end{align}$$ Substituting the observed data $\mathbf{x}$ then gives the general form for the confidence interval: $$\text{CI}_\phi(1-\alpha) \equiv \Big[ L_\mathbf{x}(\alpha, \theta), U_\mathbf{x}(\alpha, \theta) \Big].$$ The functions $L_\mathbf{x}$ and $U_\mathbf{x}$ are lower and upper bound functions for the interval, and they depend on the confidence level for the interval and our choice of $\theta$. This latter parameter represents the left tail area used in the initial probability interval for the pivotal quantity, and it can be varied over the above range. If we want to form the optimal (shortest) confidence interval at the confidence level $1-\alpha$, we need to solve the following optimisation problem: $$\underset{0 \leqslant \theta \leqslant \alpha}{\text{Minimise}} \ \text{Length}(\theta) \quad \quad \quad \quad \quad \text{Length}(\theta) \equiv U_\mathbf{x}(\alpha, \theta) - L_\mathbf{x}(\alpha, \theta)$$ Generally speaking, the minimising value $\hat{\theta}$ will depend on the data $\mathbf{x}$ and the value $\alpha$ determining the confidence level. The length of the resulting optimal (shortest) confidence interval will likewise depend on the data and the confidence level. We will see below that in some cases the optimising point does not depend on the data values at all, but even in this case the resulting length of the optimised interval depends on the data and confidence level (just as you would expect). In problems involving a continuous pivotal quantity, this optimisation can usually be solved using standard calculus method. (And thankfully, for some intervals the work has already been done for you in some functions in the stat.extend package.) Below we give some examples looking at confidence intervals for the population mean and standard deviation for normal data. Assuming that the optimisation part leads to a minimising value for all data values, this will give you a confidence interval that is the shortest interval formed from inversion of the initial pivotal quantity. We will also show how to compute these intervals directly from existing R functions. It is important to note that there will be other confidence intervals formed with other methods that may be shorter for particular samples.$^\dagger$ Example 1 (CI of population mean for normal data): Suppose we observe data $X_1,...,X_n \sim \text{IID N}(\mu, \sigma^2)$ known to come from a normal distribution with unknown parameters. In order to form a CI for the mean parameter $\mu$ we can use the well-known pivotal quantity: $$\sqrt{n} \cdot \frac{\bar{X}_n - \mu}{S_n} \sim \text{St}(n-1).$$ Suppose we let $t_{n-1, \alpha}$ denote the critical point of the T-distribution with $n-1$ degrees-of-freedom and with upper tail $\alpha$. Using the above pivotal quantity, and choosing any value $0 \leqslant \theta \leqslant \alpha$, we have: $$\begin{align} 1-\alpha &= \mathbb{P} \Bigg( -t_{n-1, \theta} \leqslant \sqrt{n} \cdot \frac{\bar{X}_n - \mu}{S_n} \leqslant t_{n-1, \alpha-\theta} \Bigg) \\[6pt] &= \mathbb{P} \Bigg( \bar{X}_n - \frac{t_{n-1, \alpha-\theta}}{\sqrt{n}} \cdot S_n \leqslant \mu \leqslant \bar{X}_n + \frac{t_{n-1, \theta}}{\sqrt{n}} \cdot S_n \Bigg), \\[6pt] \end{align}$$ giving the confidence interval: $$\text{CI}_\mu(1-\alpha) = \Bigg[ \bar{x}_n - \frac{t_{n-1, \alpha-\theta}}{\sqrt{n}} \cdot s_n , \ \bar{x}_n + \frac{t_{n-1, \theta}}{\sqrt{n}} \cdot s_n \Bigg],$$ with length function: $$\text{Length}(\theta) = ( t_{n-1, \alpha-\theta} + t_{n-1, \theta}) \cdot \frac{s_n}{\sqrt{n}}.$$ In order to minimise this function, we can observe that the critical point function is a convex function of its tail area, which means that the length function is maximised at the point where the upper tail areas in the two parts are the same. (I leave it to the reader to perform the relevant calculus steps to demonstrate this.) This gives the solution: $$\alpha - \hat{\theta} = \hat{\theta} \quad \quad \implies \quad \quad \hat{\theta} = \frac{\alpha}{2}.$$ Thus, we can confirm that the optimal (shortest) confidence interval in this case is the symmetric confidence interval: $$\text{CI}_\mu(1-\alpha) = \Bigg[ \bar{x}_n \pm \frac{t_{n-1, \alpha/2}}{\sqrt{n}} \cdot s_n \Bigg].$$ In this particular case, we see that the standard symmetric interval (with each tail area the same) is the optimal confidence interval. Varying the relative tail areas away from equal areas increases the length of the interval and so it is not advisable. This standard confidence interval can be programmed using the CONF.mean function in the stat.extend package. #Generate some data set.seed(1) n <- 60 MEAN <- 12 SDEV <- 3 DATA <- rnorm(n, mean = MEAN, sd = SDEV) #Compute 95% confidence interval for the mean library(stat.extend) CONF.mean(alpha = 0.05, x = DATA) Confidence Interval (CI) 95.00% CI for mean parameter for infinite population Interval uses 60 data points from data DATA with sample variance = 6.5818 and assumed kurtosis = 3.0000 [10.6225837668173, 14.0231144933285] Example 2 (CI of population standard deviation for normal data): Continuing the above problem, suppose we now want to form a CI for the standard deviation parameter $\sigma$. To do this we can use the well-known pivotal quantity: $$\sqrt{n-1} \cdot \frac{S_n}{\sigma} \sim \text{Chi}(n-1).$$ Suppose we let $\chi_{n-1, \alpha}$ denote the critical point of the chi distribution with $n-1$ degrees-of-freedom and with upper tail $\alpha$. Using the above pivotal quantity, and choosing any value $0 \leqslant \theta \leqslant \alpha$, we have: $$\begin{align} 1-\alpha &= \mathbb{P} \Bigg( \chi_{n-1, \theta} \leqslant \sqrt{n-1} \cdot \frac{S_n}{\sigma} \leqslant \chi_{n-1, 1-\alpha+\theta} \Bigg) \\[6pt] &= \mathbb{P} \Bigg( \frac{\sqrt{n-1} \cdot S_n}{\chi_{n-1, 1-\alpha+\theta}} \leqslant \sigma \leqslant \frac{\sqrt{n-1} \cdot S_n}{\chi_{n-1, \theta}} \Bigg), \\[6pt] \end{align}$$ giving the confidence interval: $$\text{CI}_{\sigma}(1-\alpha) = \Bigg[ \frac{\sqrt{n-1} \cdot s_n}{\chi_{n-1, 1-\alpha+\theta}}, \ \frac{\sqrt{n-1} \cdot s_n}{\chi_{n-1, \theta}} \Bigg],$$ with length function: $$\text{Length}(\theta) = \Bigg( \frac{1}{\chi_{n-1, \theta}} - \frac{1}{\chi_{n-1, 1-\alpha+\theta}} \Bigg) \cdot \sqrt{n-1} \cdot s_n.$$ This function can be minimised numerically to yield the minimising value $\hat{\theta}$, which gives the optimal (shortest) confidence interval for the population standard deviation. Unlike in the case of a confidence interval for the population mean, the optimal interval in this case does not have equal tail areas for the upper and lower tail. This problem is examined in Tate and Klett (1959), where the authors look at the corresponding interval for the population variance. This confidence interval can be programmed using the CONF.var function in the stat.extend package. #Compute 95% confidence interval for the variance CONF.var(alpha = 0.05, x = DATA, kurt = 3) Confidence Interval (CI) 95.00% CI for variance parameter for infinite population Interval uses 60 data points from data DATA with sample variance = 6.5818 and assumed kurtosis = 3.0000 Computed using nlm optimisation with 8 iterations (code = 3) [4.50233916286611, 9.41710949707062] $^\dagger$ To see this, suppose you have a parameter $\theta \in \Theta$ and consider the class of confidence intervals constructed as follows. Choose some event $Y \in \mathscr{Y}$ using an exogenous random variable $Y$ with fixed probability $\mathbb{P}(Y = \mathscr{Y}) = \alpha$ and choose some point $\mathbf{x}_0$ for the observable data of interest. Then form the interval: $$\text{CI}(1-\alpha) = \begin{cases} [\theta_0] & & & \text{if } \mathbf{x} = \mathbf{x}_0 \text{ or } Y \in \mathscr{Y}, \\[6pt] \Theta & & & \text{if } \mathbf{x} \neq \mathbf{x}_0 \text{ and } Y \notin \mathscr{Y}. \\[6pt] \end{cases}$$ Assuming that $\mathbf{x}$ is continuous we have $\mathbb{P}(\mathbf{x} \neq \mathbf{x}_0) = 0$ and so the interval has the required coverage probability for all $\theta \in \Theta$. If $\mathbf{x} = \mathbf{x}_0$ then this interval is composed of a single point and so has length zero. This demonstrates that it is possible to formulate a confidence interval with length zero at an individual data outcome.
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l
Some theory on optimal confidence intervals Confidence intervals are formed from pivotal quantities, which are functions of the data and parameter of interest that have a distribution that does not de
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level? Some theory on optimal confidence intervals Confidence intervals are formed from pivotal quantities, which are functions of the data and parameter of interest that have a distribution that does not depend on the parameters of the problem. Confidence "intervals" are a special case of the broader class of confidence sets, which need not be connected intervals. However, for the purposes of simplicity, we will restrict the present answer to cases where the confidence set is a single interval (i.e., a confidence interval). Suppose we want to form a confidence interval for the unknown parameter $\phi$ at confidence level $1-\alpha$ using the data $\mathbf{x}$. Consider a continuous pivotal quantity $H(\mathbf{x}, \phi)$ with a distribution that has quantile function $Q_H$. (Note that this function does not depend on the parameter $\phi$ or the data since it is a pivotal quantity.) Using the pivotal quantity, we can choose any value $0 \leqslant \theta \leqslant \alpha$ and form a probability interval from the quantile function. We then "invert" the inequality expression to turn this into an interval statement for the parameter of interest: $$\begin{align} 1-\alpha &= \mathbb{P}(Q_H(\theta) \leqslant H(\mathbf{X}, \phi) \leqslant Q_H(1-\alpha+\theta)) \\[6pt] &= \mathbb{P}(L_\mathbf{X}(\alpha, \theta) \leqslant \phi \leqslant U_\mathbf{X}(\alpha, \theta)). \\[6pt] \end{align}$$ Substituting the observed data $\mathbf{x}$ then gives the general form for the confidence interval: $$\text{CI}_\phi(1-\alpha) \equiv \Big[ L_\mathbf{x}(\alpha, \theta), U_\mathbf{x}(\alpha, \theta) \Big].$$ The functions $L_\mathbf{x}$ and $U_\mathbf{x}$ are lower and upper bound functions for the interval, and they depend on the confidence level for the interval and our choice of $\theta$. This latter parameter represents the left tail area used in the initial probability interval for the pivotal quantity, and it can be varied over the above range. If we want to form the optimal (shortest) confidence interval at the confidence level $1-\alpha$, we need to solve the following optimisation problem: $$\underset{0 \leqslant \theta \leqslant \alpha}{\text{Minimise}} \ \text{Length}(\theta) \quad \quad \quad \quad \quad \text{Length}(\theta) \equiv U_\mathbf{x}(\alpha, \theta) - L_\mathbf{x}(\alpha, \theta)$$ Generally speaking, the minimising value $\hat{\theta}$ will depend on the data $\mathbf{x}$ and the value $\alpha$ determining the confidence level. The length of the resulting optimal (shortest) confidence interval will likewise depend on the data and the confidence level. We will see below that in some cases the optimising point does not depend on the data values at all, but even in this case the resulting length of the optimised interval depends on the data and confidence level (just as you would expect). In problems involving a continuous pivotal quantity, this optimisation can usually be solved using standard calculus method. (And thankfully, for some intervals the work has already been done for you in some functions in the stat.extend package.) Below we give some examples looking at confidence intervals for the population mean and standard deviation for normal data. Assuming that the optimisation part leads to a minimising value for all data values, this will give you a confidence interval that is the shortest interval formed from inversion of the initial pivotal quantity. We will also show how to compute these intervals directly from existing R functions. It is important to note that there will be other confidence intervals formed with other methods that may be shorter for particular samples.$^\dagger$ Example 1 (CI of population mean for normal data): Suppose we observe data $X_1,...,X_n \sim \text{IID N}(\mu, \sigma^2)$ known to come from a normal distribution with unknown parameters. In order to form a CI for the mean parameter $\mu$ we can use the well-known pivotal quantity: $$\sqrt{n} \cdot \frac{\bar{X}_n - \mu}{S_n} \sim \text{St}(n-1).$$ Suppose we let $t_{n-1, \alpha}$ denote the critical point of the T-distribution with $n-1$ degrees-of-freedom and with upper tail $\alpha$. Using the above pivotal quantity, and choosing any value $0 \leqslant \theta \leqslant \alpha$, we have: $$\begin{align} 1-\alpha &= \mathbb{P} \Bigg( -t_{n-1, \theta} \leqslant \sqrt{n} \cdot \frac{\bar{X}_n - \mu}{S_n} \leqslant t_{n-1, \alpha-\theta} \Bigg) \\[6pt] &= \mathbb{P} \Bigg( \bar{X}_n - \frac{t_{n-1, \alpha-\theta}}{\sqrt{n}} \cdot S_n \leqslant \mu \leqslant \bar{X}_n + \frac{t_{n-1, \theta}}{\sqrt{n}} \cdot S_n \Bigg), \\[6pt] \end{align}$$ giving the confidence interval: $$\text{CI}_\mu(1-\alpha) = \Bigg[ \bar{x}_n - \frac{t_{n-1, \alpha-\theta}}{\sqrt{n}} \cdot s_n , \ \bar{x}_n + \frac{t_{n-1, \theta}}{\sqrt{n}} \cdot s_n \Bigg],$$ with length function: $$\text{Length}(\theta) = ( t_{n-1, \alpha-\theta} + t_{n-1, \theta}) \cdot \frac{s_n}{\sqrt{n}}.$$ In order to minimise this function, we can observe that the critical point function is a convex function of its tail area, which means that the length function is maximised at the point where the upper tail areas in the two parts are the same. (I leave it to the reader to perform the relevant calculus steps to demonstrate this.) This gives the solution: $$\alpha - \hat{\theta} = \hat{\theta} \quad \quad \implies \quad \quad \hat{\theta} = \frac{\alpha}{2}.$$ Thus, we can confirm that the optimal (shortest) confidence interval in this case is the symmetric confidence interval: $$\text{CI}_\mu(1-\alpha) = \Bigg[ \bar{x}_n \pm \frac{t_{n-1, \alpha/2}}{\sqrt{n}} \cdot s_n \Bigg].$$ In this particular case, we see that the standard symmetric interval (with each tail area the same) is the optimal confidence interval. Varying the relative tail areas away from equal areas increases the length of the interval and so it is not advisable. This standard confidence interval can be programmed using the CONF.mean function in the stat.extend package. #Generate some data set.seed(1) n <- 60 MEAN <- 12 SDEV <- 3 DATA <- rnorm(n, mean = MEAN, sd = SDEV) #Compute 95% confidence interval for the mean library(stat.extend) CONF.mean(alpha = 0.05, x = DATA) Confidence Interval (CI) 95.00% CI for mean parameter for infinite population Interval uses 60 data points from data DATA with sample variance = 6.5818 and assumed kurtosis = 3.0000 [10.6225837668173, 14.0231144933285] Example 2 (CI of population standard deviation for normal data): Continuing the above problem, suppose we now want to form a CI for the standard deviation parameter $\sigma$. To do this we can use the well-known pivotal quantity: $$\sqrt{n-1} \cdot \frac{S_n}{\sigma} \sim \text{Chi}(n-1).$$ Suppose we let $\chi_{n-1, \alpha}$ denote the critical point of the chi distribution with $n-1$ degrees-of-freedom and with upper tail $\alpha$. Using the above pivotal quantity, and choosing any value $0 \leqslant \theta \leqslant \alpha$, we have: $$\begin{align} 1-\alpha &= \mathbb{P} \Bigg( \chi_{n-1, \theta} \leqslant \sqrt{n-1} \cdot \frac{S_n}{\sigma} \leqslant \chi_{n-1, 1-\alpha+\theta} \Bigg) \\[6pt] &= \mathbb{P} \Bigg( \frac{\sqrt{n-1} \cdot S_n}{\chi_{n-1, 1-\alpha+\theta}} \leqslant \sigma \leqslant \frac{\sqrt{n-1} \cdot S_n}{\chi_{n-1, \theta}} \Bigg), \\[6pt] \end{align}$$ giving the confidence interval: $$\text{CI}_{\sigma}(1-\alpha) = \Bigg[ \frac{\sqrt{n-1} \cdot s_n}{\chi_{n-1, 1-\alpha+\theta}}, \ \frac{\sqrt{n-1} \cdot s_n}{\chi_{n-1, \theta}} \Bigg],$$ with length function: $$\text{Length}(\theta) = \Bigg( \frac{1}{\chi_{n-1, \theta}} - \frac{1}{\chi_{n-1, 1-\alpha+\theta}} \Bigg) \cdot \sqrt{n-1} \cdot s_n.$$ This function can be minimised numerically to yield the minimising value $\hat{\theta}$, which gives the optimal (shortest) confidence interval for the population standard deviation. Unlike in the case of a confidence interval for the population mean, the optimal interval in this case does not have equal tail areas for the upper and lower tail. This problem is examined in Tate and Klett (1959), where the authors look at the corresponding interval for the population variance. This confidence interval can be programmed using the CONF.var function in the stat.extend package. #Compute 95% confidence interval for the variance CONF.var(alpha = 0.05, x = DATA, kurt = 3) Confidence Interval (CI) 95.00% CI for variance parameter for infinite population Interval uses 60 data points from data DATA with sample variance = 6.5818 and assumed kurtosis = 3.0000 Computed using nlm optimisation with 8 iterations (code = 3) [4.50233916286611, 9.41710949707062] $^\dagger$ To see this, suppose you have a parameter $\theta \in \Theta$ and consider the class of confidence intervals constructed as follows. Choose some event $Y \in \mathscr{Y}$ using an exogenous random variable $Y$ with fixed probability $\mathbb{P}(Y = \mathscr{Y}) = \alpha$ and choose some point $\mathbf{x}_0$ for the observable data of interest. Then form the interval: $$\text{CI}(1-\alpha) = \begin{cases} [\theta_0] & & & \text{if } \mathbf{x} = \mathbf{x}_0 \text{ or } Y \in \mathscr{Y}, \\[6pt] \Theta & & & \text{if } \mathbf{x} \neq \mathbf{x}_0 \text{ and } Y \notin \mathscr{Y}. \\[6pt] \end{cases}$$ Assuming that $\mathbf{x}$ is continuous we have $\mathbb{P}(\mathbf{x} \neq \mathbf{x}_0) = 0$ and so the interval has the required coverage probability for all $\theta \in \Theta$. If $\mathbf{x} = \mathbf{x}_0$ then this interval is composed of a single point and so has length zero. This demonstrates that it is possible to formulate a confidence interval with length zero at an individual data outcome.
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l Some theory on optimal confidence intervals Confidence intervals are formed from pivotal quantities, which are functions of the data and parameter of interest that have a distribution that does not de
11,467
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level?
Shortest confidence interval is an ambiguous term There is no such thing as the shortest confidence interval. This is because the confidence interval is a function of the data $X$. And while you can make the confidence interval shorter for some particular observation, this comes at the cost of increasing the size of intervals for other possible observations. Only when you define some way to apply some weighted average over all the observations, then you could possibly (but I believe not certainly or at least not easily) construct some confidence interval with the 'shortest' length. Conditioning on observation versus conditioning on the parameter: Contrast with credible intervals, where shortest interval makes more sense. This contrasts with credible intervals. Confidence intervals relate to the probability that the parameter is inside the interval conditional on the parameter. Credible intervals relate to the probability that the parameter is inside the interval conditional on the observation. For credible intervals you can construct a shortest interval for each observation individually (by choosing the interval that encloses the highest density of the posterior). Changing the interval for one observation does not influence the intervals for other observations. For confidence intervals you could make the intervals smallest in a sense that these intervals relate to hypothesis tests. Then you can make the shortest decision boundaries/intervals (which are functions of the parameters, the hypotheses). Some related questions In this question... The basic logic of constructing a confidence interval ..the topic was to get a 'shortest interval' but there is no unambiguous solution when 'shortest' is not unambiguously defined. That same question also clarifies something about the 'relative tail sizes'. What we can control are the tails of the distribution of the observation conditional on the parameter. Often this coincides with the confidence interval*, and we can think of the confidence interval as distribution around the point estimate of the parameter. However, this symmetry may not need to be, as we can see in the case like the following: let's consider the observation/sample $\hat{\theta}$ from a distribution parameterized by $\theta$ following $${\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$$ You see this in the image below (for details see the particular question). In that image the red and green lines depict the confidence interval boundaries as a function of the observed $\hat{\theta}$. But you can consider them also as a function of $\theta$, and it is actually in that view how the boundaries are determined (see the projected conditional pdf's and how the boundaries enclose symmetrically the highest $\alpha\%$ of those pdf's but do not provide a symmetric confidence interval, and some boundaries may even become infinite). In this question... Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals ... you see a comparison between credible intervals and confidence interval. For a given observation, credible intervals, when they are the highest density posterior interval, are (often) shorter than confidence intervals. This is because confidence intervals do not need to coincide with the highest density interval conditional on the observation. On the other hand, note that in the vertical direction (for a given true parameter) the boundaries of the confidence interval are enclosing a shortest interval. *(often this coincides with the confidence interval) We see an example in this question... Differences between a frequentist and a Bayesian density prediction where we see a sketch for an (prediction) interval based on a t-distribution. There is a certain duality to the construction of the interval: We can construct a frequentist prediction interval with the interpretation that No matter what the value of $\mu$ and $\sigma$ is, the value $X_{n+1}$ will be $x\%$ of the time inside the prediction interval. but also: Given a hypothetical predicted value $\tilde{X}_{n+1}$ in the prediction range, the observations $\bar{X}$ and $s$ (the sample mean and sample deviation) will be occuring within some range that occurs $x$ percent of the time. (That means we will only include those values in the prediction range for which we make our observations $x\%$ of the time, such that we will never fail more than $x\%$ of the time) So instead of considering the distribution of $X_{n+1}$ given the data $\bar{X}$ and $s$, we consider the other way around, we consider the distribution of the data $\bar{X}$ and $s$ given $X_{n+1}$. In the image we see the interval boundaries around the observed mean (in the example, which is about prediction interval instead of confidence interval, observed additional point $X_{n+1}$). But the boundaries should actually be considered the other way around. It is the hypothetical observation that is inside the boundaries of a hypothesis test related to each of the parameters inside the confidence interval (in the example it is a prediction interval).
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l
Shortest confidence interval is an ambiguous term There is no such thing as the shortest confidence interval. This is because the confidence interval is a function of the data $X$. And while you can m
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level? Shortest confidence interval is an ambiguous term There is no such thing as the shortest confidence interval. This is because the confidence interval is a function of the data $X$. And while you can make the confidence interval shorter for some particular observation, this comes at the cost of increasing the size of intervals for other possible observations. Only when you define some way to apply some weighted average over all the observations, then you could possibly (but I believe not certainly or at least not easily) construct some confidence interval with the 'shortest' length. Conditioning on observation versus conditioning on the parameter: Contrast with credible intervals, where shortest interval makes more sense. This contrasts with credible intervals. Confidence intervals relate to the probability that the parameter is inside the interval conditional on the parameter. Credible intervals relate to the probability that the parameter is inside the interval conditional on the observation. For credible intervals you can construct a shortest interval for each observation individually (by choosing the interval that encloses the highest density of the posterior). Changing the interval for one observation does not influence the intervals for other observations. For confidence intervals you could make the intervals smallest in a sense that these intervals relate to hypothesis tests. Then you can make the shortest decision boundaries/intervals (which are functions of the parameters, the hypotheses). Some related questions In this question... The basic logic of constructing a confidence interval ..the topic was to get a 'shortest interval' but there is no unambiguous solution when 'shortest' is not unambiguously defined. That same question also clarifies something about the 'relative tail sizes'. What we can control are the tails of the distribution of the observation conditional on the parameter. Often this coincides with the confidence interval*, and we can think of the confidence interval as distribution around the point estimate of the parameter. However, this symmetry may not need to be, as we can see in the case like the following: let's consider the observation/sample $\hat{\theta}$ from a distribution parameterized by $\theta$ following $${\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$$ You see this in the image below (for details see the particular question). In that image the red and green lines depict the confidence interval boundaries as a function of the observed $\hat{\theta}$. But you can consider them also as a function of $\theta$, and it is actually in that view how the boundaries are determined (see the projected conditional pdf's and how the boundaries enclose symmetrically the highest $\alpha\%$ of those pdf's but do not provide a symmetric confidence interval, and some boundaries may even become infinite). In this question... Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals ... you see a comparison between credible intervals and confidence interval. For a given observation, credible intervals, when they are the highest density posterior interval, are (often) shorter than confidence intervals. This is because confidence intervals do not need to coincide with the highest density interval conditional on the observation. On the other hand, note that in the vertical direction (for a given true parameter) the boundaries of the confidence interval are enclosing a shortest interval. *(often this coincides with the confidence interval) We see an example in this question... Differences between a frequentist and a Bayesian density prediction where we see a sketch for an (prediction) interval based on a t-distribution. There is a certain duality to the construction of the interval: We can construct a frequentist prediction interval with the interpretation that No matter what the value of $\mu$ and $\sigma$ is, the value $X_{n+1}$ will be $x\%$ of the time inside the prediction interval. but also: Given a hypothetical predicted value $\tilde{X}_{n+1}$ in the prediction range, the observations $\bar{X}$ and $s$ (the sample mean and sample deviation) will be occuring within some range that occurs $x$ percent of the time. (That means we will only include those values in the prediction range for which we make our observations $x\%$ of the time, such that we will never fail more than $x\%$ of the time) So instead of considering the distribution of $X_{n+1}$ given the data $\bar{X}$ and $s$, we consider the other way around, we consider the distribution of the data $\bar{X}$ and $s$ given $X_{n+1}$. In the image we see the interval boundaries around the observed mean (in the example, which is about prediction interval instead of confidence interval, observed additional point $X_{n+1}$). But the boundaries should actually be considered the other way around. It is the hypothetical observation that is inside the boundaries of a hypothesis test related to each of the parameters inside the confidence interval (in the example it is a prediction interval).
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l Shortest confidence interval is an ambiguous term There is no such thing as the shortest confidence interval. This is because the confidence interval is a function of the data $X$. And while you can m
11,468
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level?
The shortest possible confidence interval for any particular parameter is the empty interval with length 0. A confidence interval isn't just an interval. It's a procedure for constructing an interval from a sample. So, your procedure can be "For this particular sample, I'll take the empty interval, and then for every other sample (from this repeatable experiment which I am definitely doing) I'll randomly take either the empty interval with probability 0.05, or the set of all possible values of the paramater, with probability 0.95." According to the definition, this is a 95% confidence interval. Of course, this is a silly example. But it's important to remember that properties of a confidence interval, like its length, are random variables. What you are probably looking for is the interval with the shortest expected length.
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l
The shortest possible confidence interval for any particular parameter is the empty interval with length 0. A confidence interval isn't just an interval. It's a procedure for constructing an interval
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level? The shortest possible confidence interval for any particular parameter is the empty interval with length 0. A confidence interval isn't just an interval. It's a procedure for constructing an interval from a sample. So, your procedure can be "For this particular sample, I'll take the empty interval, and then for every other sample (from this repeatable experiment which I am definitely doing) I'll randomly take either the empty interval with probability 0.05, or the set of all possible values of the paramater, with probability 0.95." According to the definition, this is a 95% confidence interval. Of course, this is a silly example. But it's important to remember that properties of a confidence interval, like its length, are random variables. What you are probably looking for is the interval with the shortest expected length.
What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence l The shortest possible confidence interval for any particular parameter is the empty interval with length 0. A confidence interval isn't just an interval. It's a procedure for constructing an interval
11,469
How can you visualize the relationship between 3 categorical variables?
This is an interesting data set to try to represent graphically, partly because it's not really categorical. Both 3-level factors are ordinal and there is possible interplay between them (presumably, it's harder for a mild baseline to have substantial improvement -- or maybe substantial improvement means something different for each baseline). With multiple variables, there isn't usually a single view that shows all the features you might care about. Some factors will be easier to compare than others. I think your original view is good and would be better with Nick Cox's suggestions: removing duplicate legends and using an ordinal color scale. If you're most interesting in seeing the difference between treatments, you can emphasize the change by using a stacked area plot instead of stacked bars. I'm usually wary of stacking in general because it's harder to read the middle values, but it does re-enforce the fixed-sum nature of this data. And it makes it easy to read the sum moderate+substantial if that's relevant. I've flipped the order of the improvement levels so that higher is better for the frequency. Without stacking, the equivalent is a slope graph. It's easier to read each level, but harder to understand the interplay. You have to keep in mind that the third line is directly dependent on the other two. Given the ordinal nature of the data, it may be helpful to convert the improvement value into a numeric score, as is often done with Likert data. For instance, none=0, moderate=1, substantial=2. Then you can graph that variable on a continuous scale. The downside is that you have to find a reasonable scoring (e.g., maybe 0, 1 and 5 would be a truer representation). Colophon: These plots were made with the Graph Builder feature in the software package JMP (which I help develop). Though made interactively, a script, for instance, for the area plot, without the coloring customizations, is: Graph Builder( Graph Spacing( 15 ), Variables( X( :treatment ), Y( :frequency ), Group X( :baseline ), Overlay( :improvement ) ), Elements( Area( X, Y ) ) );
How can you visualize the relationship between 3 categorical variables?
This is an interesting data set to try to represent graphically, partly because it's not really categorical. Both 3-level factors are ordinal and there is possible interplay between them (presumably,
How can you visualize the relationship between 3 categorical variables? This is an interesting data set to try to represent graphically, partly because it's not really categorical. Both 3-level factors are ordinal and there is possible interplay between them (presumably, it's harder for a mild baseline to have substantial improvement -- or maybe substantial improvement means something different for each baseline). With multiple variables, there isn't usually a single view that shows all the features you might care about. Some factors will be easier to compare than others. I think your original view is good and would be better with Nick Cox's suggestions: removing duplicate legends and using an ordinal color scale. If you're most interesting in seeing the difference between treatments, you can emphasize the change by using a stacked area plot instead of stacked bars. I'm usually wary of stacking in general because it's harder to read the middle values, but it does re-enforce the fixed-sum nature of this data. And it makes it easy to read the sum moderate+substantial if that's relevant. I've flipped the order of the improvement levels so that higher is better for the frequency. Without stacking, the equivalent is a slope graph. It's easier to read each level, but harder to understand the interplay. You have to keep in mind that the third line is directly dependent on the other two. Given the ordinal nature of the data, it may be helpful to convert the improvement value into a numeric score, as is often done with Likert data. For instance, none=0, moderate=1, substantial=2. Then you can graph that variable on a continuous scale. The downside is that you have to find a reasonable scoring (e.g., maybe 0, 1 and 5 would be a truer representation). Colophon: These plots were made with the Graph Builder feature in the software package JMP (which I help develop). Though made interactively, a script, for instance, for the area plot, without the coloring customizations, is: Graph Builder( Graph Spacing( 15 ), Variables( X( :treatment ), Y( :frequency ), Group X( :baseline ), Overlay( :improvement ) ), Elements( Area( X, Y ) ) );
How can you visualize the relationship between 3 categorical variables? This is an interesting data set to try to represent graphically, partly because it's not really categorical. Both 3-level factors are ordinal and there is possible interplay between them (presumably,
11,470
How can you visualize the relationship between 3 categorical variables?
First, here is my reading from the graph provided of the data for those who wish to play (experiment, if you like). NB off-by-one errors are certainly possible, as are gross errors. improvement treatment baseline frequency none 0 mild 5 moderate 0 mild 41 substantial 0 mild 4 none 1 mild 19 moderate 1 mild 19 substantial 1 mild 12 none 0 moderate 19 moderate 0 moderate 24 substantial 0 moderate 7 none 1 moderate 20 moderate 1 moderate 14 substantial 1 moderate 16 none 0 severe 7 moderate 0 severe 21 substantial 0 severe 22 none 1 severe 12 moderate 1 severe 15 substantial 1 severe 23 Here is a reworking of the original design. One detail of the original data makes things simple: the number of people in each of the predictor combinations is the same, so plotting frequencies and plotting percents are the same. Here instead of a stacked (subdivided, segmented) bar chart, we separate out bars in a two-way bar chart or table plot design. Much of the detail in graphics is just that, detail. Several small weaknesses in a graph can undermine its effectiveness and several small improvements can help too. To spell it out: Three panels are not needed here, with their repetition of axes, legend and text. A legend is always curse as well as blessing, obliging the reader to go "back and forth" mentally (or memorise the legend, not something that appeals, however easy it might be). Informative text right by the bars is easier to follow. The fruit salad colour coding is dispensable. It seems arbitrary too: "substantial" improvement is a big deal, but I find even strong yellow a subdued colour. But we don't need colour when we have text to explain. Although some will shriek with horror at violating the distinction between Figure and Table, we can show the frequencies too. It's helpful to be able to think "4 people in this category". There is homage here to the traditional plotting of response on the vertical axis, just as in the original. All that said, it is hard to see much structure in these data. When that's so, it is also hard to share the blame between (a) data without much structure and (b) the weaknesses of a graphical design for picking out not only predictor effects but also possible interactions. Treatment seems less important than baseline condition. But then, if the baseline was "mild", how much scope was there for "substantial" improvement? I'll stop there to stop making a fool of myself when the study of mental health data is certainly not a specialism, especially if the data turn out to be fake. But if they are real, we could do with a much larger sample size. (We usually say that, but there you go.) EDIT The graph may naturally be complicated by an ordinal colour scheme if so desired: For the record: the graphs used Stata code, including my own program tabplot downloadable using ssc inst tabplot. tabplot improvement group [w=frequency] , showval /// xmla(1.5 "mild" 3.5 "moderate" 5.5 "severe", noticks labgap(*4) labsize(medsmall)) /// xla(1 "0" 2 "1" 3 "0" 4 "1" 5 "0" 6 "1") /// xtitle(baseline and treatment) xsc(titlegap(*4)) bfcolor(emerald*0.2) tabplot improvement group [w=frequency] , showval /// xmla(1.5 "mild" 3.5 "moderate" 5.5 "severe", noticks labgap(*4) labsize(medsmall)) /// xla(1 "0" 2 "1" 3 "0" 4 "1" 5 "0" 6 "1") /// xtitle(baseline and treatment) xsc(titlegap(*2)) /// sep(improvement2) bar3(bfcolor(emerald*0.2)) bar2(bfcolor(emerald*0.6)) /// bar1(bfcolor(emerald)) barall(blcolor(green))
How can you visualize the relationship between 3 categorical variables?
First, here is my reading from the graph provided of the data for those who wish to play (experiment, if you like). NB off-by-one errors are certainly possible, as are gross errors. improvement
How can you visualize the relationship between 3 categorical variables? First, here is my reading from the graph provided of the data for those who wish to play (experiment, if you like). NB off-by-one errors are certainly possible, as are gross errors. improvement treatment baseline frequency none 0 mild 5 moderate 0 mild 41 substantial 0 mild 4 none 1 mild 19 moderate 1 mild 19 substantial 1 mild 12 none 0 moderate 19 moderate 0 moderate 24 substantial 0 moderate 7 none 1 moderate 20 moderate 1 moderate 14 substantial 1 moderate 16 none 0 severe 7 moderate 0 severe 21 substantial 0 severe 22 none 1 severe 12 moderate 1 severe 15 substantial 1 severe 23 Here is a reworking of the original design. One detail of the original data makes things simple: the number of people in each of the predictor combinations is the same, so plotting frequencies and plotting percents are the same. Here instead of a stacked (subdivided, segmented) bar chart, we separate out bars in a two-way bar chart or table plot design. Much of the detail in graphics is just that, detail. Several small weaknesses in a graph can undermine its effectiveness and several small improvements can help too. To spell it out: Three panels are not needed here, with their repetition of axes, legend and text. A legend is always curse as well as blessing, obliging the reader to go "back and forth" mentally (or memorise the legend, not something that appeals, however easy it might be). Informative text right by the bars is easier to follow. The fruit salad colour coding is dispensable. It seems arbitrary too: "substantial" improvement is a big deal, but I find even strong yellow a subdued colour. But we don't need colour when we have text to explain. Although some will shriek with horror at violating the distinction between Figure and Table, we can show the frequencies too. It's helpful to be able to think "4 people in this category". There is homage here to the traditional plotting of response on the vertical axis, just as in the original. All that said, it is hard to see much structure in these data. When that's so, it is also hard to share the blame between (a) data without much structure and (b) the weaknesses of a graphical design for picking out not only predictor effects but also possible interactions. Treatment seems less important than baseline condition. But then, if the baseline was "mild", how much scope was there for "substantial" improvement? I'll stop there to stop making a fool of myself when the study of mental health data is certainly not a specialism, especially if the data turn out to be fake. But if they are real, we could do with a much larger sample size. (We usually say that, but there you go.) EDIT The graph may naturally be complicated by an ordinal colour scheme if so desired: For the record: the graphs used Stata code, including my own program tabplot downloadable using ssc inst tabplot. tabplot improvement group [w=frequency] , showval /// xmla(1.5 "mild" 3.5 "moderate" 5.5 "severe", noticks labgap(*4) labsize(medsmall)) /// xla(1 "0" 2 "1" 3 "0" 4 "1" 5 "0" 6 "1") /// xtitle(baseline and treatment) xsc(titlegap(*4)) bfcolor(emerald*0.2) tabplot improvement group [w=frequency] , showval /// xmla(1.5 "mild" 3.5 "moderate" 5.5 "severe", noticks labgap(*4) labsize(medsmall)) /// xla(1 "0" 2 "1" 3 "0" 4 "1" 5 "0" 6 "1") /// xtitle(baseline and treatment) xsc(titlegap(*2)) /// sep(improvement2) bar3(bfcolor(emerald*0.2)) bar2(bfcolor(emerald*0.6)) /// bar1(bfcolor(emerald)) barall(blcolor(green))
How can you visualize the relationship between 3 categorical variables? First, here is my reading from the graph provided of the data for those who wish to play (experiment, if you like). NB off-by-one errors are certainly possible, as are gross errors. improvement
11,471
How can you visualize the relationship between 3 categorical variables?
Isn't Mosaic plot specially designed for this purpose? In R it would be like library(vcd) d = read.table("data.dat", header=TRUE) tab = xtabs(frequency ~ treatment+baseline+improvement, data=d) mosaic(data=tab,~ treatment+baseline+improvement, shade=TRUE, cex=2.5) Each categorical variables goes to one edge of the square, which is subdivided by its labels. (Thus, if you subdivide each edge at one level only, at most 4 categorical variables can be represented. IMHO, beyond 3 it becomes messy and harder to interpret). The size of the rectangles is proportional to frequency. This is the main idea behind mosaic plot and it is the same in this answer and the answer of Paweł Kleka. The differences are in layouts of those rectangles and "niceties" provided by a specific R-package used for this type of plot. As you see from the answer of Paweł Kleka, the graphics package subdivides the upper edge at 2 levels instead of using the right edge. I used vcd package with default options, so that color indicates the degree of association between the variables. Grey means that data are consistent with (you cannot reject the hypothesis of) variable independence. Blue means that positive association exist between "severe" baseline and "substantial" improvement for both "0" and "1" treatment. (Surprise, surprise! I translate it as follows: if you have a severe depression, you will likely get substantially better whether you have a treatment or not. Correct me if I am wrong.) One can adjust the plot according to one's needs, see, for example, here. The package also has several vignettes, google "vcd mosaic example" (as I just did). Wikipedia article cited at the very beginning also explains how to construct this type of plot and intuition behind it. When you compare my picture with the picture in the answer of Paweł Kleka, it does not matter, that 'treatment' is on the left edge of each picture. You can easily change the edge location by changing the last line of my code and adjust the layout according to your needs. The common practice is that to the left goes the most important variable or the variable with the least number of labels. You can also change the order of labels (for example, so, that at the right edge the order is "none moderate substantial") by making the corresponding factor variable in R ordered and adjusting its levels.
How can you visualize the relationship between 3 categorical variables?
Isn't Mosaic plot specially designed for this purpose? In R it would be like library(vcd) d = read.table("data.dat", header=TRUE) tab = xtabs(frequency ~ treatment+baseline+improvement, data=d) mosa
How can you visualize the relationship between 3 categorical variables? Isn't Mosaic plot specially designed for this purpose? In R it would be like library(vcd) d = read.table("data.dat", header=TRUE) tab = xtabs(frequency ~ treatment+baseline+improvement, data=d) mosaic(data=tab,~ treatment+baseline+improvement, shade=TRUE, cex=2.5) Each categorical variables goes to one edge of the square, which is subdivided by its labels. (Thus, if you subdivide each edge at one level only, at most 4 categorical variables can be represented. IMHO, beyond 3 it becomes messy and harder to interpret). The size of the rectangles is proportional to frequency. This is the main idea behind mosaic plot and it is the same in this answer and the answer of Paweł Kleka. The differences are in layouts of those rectangles and "niceties" provided by a specific R-package used for this type of plot. As you see from the answer of Paweł Kleka, the graphics package subdivides the upper edge at 2 levels instead of using the right edge. I used vcd package with default options, so that color indicates the degree of association between the variables. Grey means that data are consistent with (you cannot reject the hypothesis of) variable independence. Blue means that positive association exist between "severe" baseline and "substantial" improvement for both "0" and "1" treatment. (Surprise, surprise! I translate it as follows: if you have a severe depression, you will likely get substantially better whether you have a treatment or not. Correct me if I am wrong.) One can adjust the plot according to one's needs, see, for example, here. The package also has several vignettes, google "vcd mosaic example" (as I just did). Wikipedia article cited at the very beginning also explains how to construct this type of plot and intuition behind it. When you compare my picture with the picture in the answer of Paweł Kleka, it does not matter, that 'treatment' is on the left edge of each picture. You can easily change the edge location by changing the last line of my code and adjust the layout according to your needs. The common practice is that to the left goes the most important variable or the variable with the least number of labels. You can also change the order of labels (for example, so, that at the right edge the order is "none moderate substantial") by making the corresponding factor variable in R ordered and adjusting its levels.
How can you visualize the relationship between 3 categorical variables? Isn't Mosaic plot specially designed for this purpose? In R it would be like library(vcd) d = read.table("data.dat", header=TRUE) tab = xtabs(frequency ~ treatment+baseline+improvement, data=d) mosa
11,472
How can you visualize the relationship between 3 categorical variables?
I'm fond of using a 2-level x-axis for data like this. So your x-axis categories for a single chart might be: Treatment=0, Baseline=Mild Treatment=0, Baseline=Moderate Treatment=0, Baseline=Severe Treatment=1, Baseline=Mild Treatment=1, Baseline=Moderate Treatment=1, Baseline=Severe ...with the same counts by categories [none/moderate/substantial] histogram bars.
How can you visualize the relationship between 3 categorical variables?
I'm fond of using a 2-level x-axis for data like this. So your x-axis categories for a single chart might be: Treatment=0, Baseline=Mild Treatment=0, Baseline=Moderate Treatment=0, Baseline=Severe T
How can you visualize the relationship between 3 categorical variables? I'm fond of using a 2-level x-axis for data like this. So your x-axis categories for a single chart might be: Treatment=0, Baseline=Mild Treatment=0, Baseline=Moderate Treatment=0, Baseline=Severe Treatment=1, Baseline=Mild Treatment=1, Baseline=Moderate Treatment=1, Baseline=Severe ...with the same counts by categories [none/moderate/substantial] histogram bars.
How can you visualize the relationship between 3 categorical variables? I'm fond of using a 2-level x-axis for data like this. So your x-axis categories for a single chart might be: Treatment=0, Baseline=Mild Treatment=0, Baseline=Moderate Treatment=0, Baseline=Severe T
11,473
How can you visualize the relationship between 3 categorical variables?
I sugest use mosaic plot mosaicplot(table(moz), sort = c(3,1,2), color = T)
How can you visualize the relationship between 3 categorical variables?
I sugest use mosaic plot mosaicplot(table(moz), sort = c(3,1,2), color = T)
How can you visualize the relationship between 3 categorical variables? I sugest use mosaic plot mosaicplot(table(moz), sort = c(3,1,2), color = T)
How can you visualize the relationship between 3 categorical variables? I sugest use mosaic plot mosaicplot(table(moz), sort = c(3,1,2), color = T)
11,474
How can you visualize the relationship between 3 categorical variables?
The information can also be conveyed using following simple line chart: The improvement is shown by different line types while the baseline group is shown in colors. These and the x-axis parameter (treatment here) can also be interchanged if desired.
How can you visualize the relationship between 3 categorical variables?
The information can also be conveyed using following simple line chart: The improvement is shown by different line types while the baseline group is shown in colors. These and the x-axis parameter (
How can you visualize the relationship between 3 categorical variables? The information can also be conveyed using following simple line chart: The improvement is shown by different line types while the baseline group is shown in colors. These and the x-axis parameter (treatment here) can also be interchanged if desired.
How can you visualize the relationship between 3 categorical variables? The information can also be conveyed using following simple line chart: The improvement is shown by different line types while the baseline group is shown in colors. These and the x-axis parameter (
11,475
How can you visualize the relationship between 3 categorical variables?
An option I'd consider is to use parallel sets. Some of the comparisons will be easier than others, but you can still see the relations among three categorical variables. Here it is an example with Titanic Survival data: In R (given your tags) I have used ggparallel for implementing it. Some folks have discussed here on CV how to implement it in other ways.
How can you visualize the relationship between 3 categorical variables?
An option I'd consider is to use parallel sets. Some of the comparisons will be easier than others, but you can still see the relations among three categorical variables. Here it is an example with T
How can you visualize the relationship between 3 categorical variables? An option I'd consider is to use parallel sets. Some of the comparisons will be easier than others, but you can still see the relations among three categorical variables. Here it is an example with Titanic Survival data: In R (given your tags) I have used ggparallel for implementing it. Some folks have discussed here on CV how to implement it in other ways.
How can you visualize the relationship between 3 categorical variables? An option I'd consider is to use parallel sets. Some of the comparisons will be easier than others, but you can still see the relations among three categorical variables. Here it is an example with T
11,476
How can you visualize the relationship between 3 categorical variables?
Similar to parallel sets, as posted by nazareno above, you can use alluvial plots which are available from the alluvial R package. http://www.r-bloggers.com/alluvial-diagrams/
How can you visualize the relationship between 3 categorical variables?
Similar to parallel sets, as posted by nazareno above, you can use alluvial plots which are available from the alluvial R package. http://www.r-bloggers.com/alluvial-diagrams/
How can you visualize the relationship between 3 categorical variables? Similar to parallel sets, as posted by nazareno above, you can use alluvial plots which are available from the alluvial R package. http://www.r-bloggers.com/alluvial-diagrams/
How can you visualize the relationship between 3 categorical variables? Similar to parallel sets, as posted by nazareno above, you can use alluvial plots which are available from the alluvial R package. http://www.r-bloggers.com/alluvial-diagrams/
11,477
How to understand that MLE of Variance is biased in a Gaussian distribution?
Intuition The bias is "coming from" (not at all a technical term) the fact that $E[\bar{x}^2]$ is biased for $\mu^2$. The natural question is, "well, what's the intuition for why $E[\bar{x}^2]$ is biased for $\mu^2$"? The intuition is that in a non-squared sample mean, sometimes we miss the true value $\mu$ by over-estimating and sometimes by under-estimating. But, without squaring, the tendency to over-estimate and under-estimate will cancel each other out. However, when we square $\bar{x}$ the tendency to under-estimate (miss the true value of $\mu$ by a negative number) also gets squared and thus becomes positive. Thus, it no longer cancels out and there is a slight tendency to over-estimate. If the intuition behind why $x^2$ is biased for $\mu^2$ is still unclear, try to understand the intuition behind Jensen's inequality (good intuitive explanation here) and apply it to $E[x^2]$. Let's prove that the MLE of variance for an iid sample is biased. Then we will analytically verify our intuition. Proof Let $\hat{\sigma}^2 = \frac{1}{N}\sum_{n = 1}^N (x_n - \bar{x})^2$. We want to show $E[\hat{\sigma}^2] \neq \sigma^2$. $$E[\hat{\sigma}^2] = E[\frac{1}{N}\sum_{n = 1}^N (x_n - \bar{x})^2] = \frac{1}{N}E[\sum_{n = 1}^N (x_n^2 - 2x_n\bar{x} + \bar{x}^2)] = \frac{1}{N}E[\sum_{n = 1}^N x_n^2 - \sum_{n = 1}^N 2x_n\bar{x} + \sum_{n = 1}^N \bar{x}^2]$$ Using the fact that $\sum_{n = 1}^N x_n = N\bar{x}$ and $\sum_{n = 1}^N \bar{x}^2 = N\bar{x}^2$, $$\frac{1}{N}E[\sum_{n = 1}^N x_n^2 - \sum_{n = 1}^N 2x_n\bar{x} + \sum_{n = 1}^N \bar{x}^2] = \frac{1}{N}E[\sum_{n = 1}^N x_n^2 - 2N\bar{x}^2 + N\bar{x}^2]=\frac{1}{N}E[\sum_{n = 1}^N x_n^2 - N\bar{x}^2] = \frac{1}{N}E[\sum_{n = 1}^N x_n^2] - E[\bar{x}^2] = \frac{1}{N}\sum_{n = 1}^N E[x_n^2] - E[\bar{x}^2] \\= E[x_n^2] - E[\bar{x}^2]$$ With the last step following since due to $E[x_n^2]$ being equal across $n$ due to coming from the same distribution. Now, recall the definition of variance that says $\sigma^2_x = E[x^2] - E[x]^2$. From here, we get the following $$E[x_n^2] - E[\bar{x}^2] = \sigma^2_x + E[x_n]^2 - \sigma^2_\bar{x} - E[x_n]^2 = \sigma^2_x - \sigma^2_\bar{x} = \sigma^2_x - Var(\bar{x}) = \sigma^2_x - Var(\frac{1}{N}\sum_{n = 1}^Nx_n) = \sigma^2_x - \bigg(\frac{1}{N}\bigg)^2Var(\sum_{n = 1}^Nx_n)$$ Notice that we've appropriately squared the constant $\frac{1}{N}$ when taking it out of $Var()$. Pay special attention to that! $$\sigma^2_x - \bigg(\frac{1}{N}\bigg)^2Var(\sum_{n = 1}^Nx_n) = \sigma^2_x - \bigg(\frac{1}{N}\bigg)^2N \sigma^2_x = \sigma^2_x - \frac{1}{N}\sigma^2_x = \frac{N-1}{N}\sigma^2_x$$ which is, of course, not equal to $\sigma_x^2$. Analytically Verify our Intuition We can somewhat verify the intuition by assuming we know the value of $\mu$ and plugging it into the above proof. Since we now know $\mu$, we no longer have the need to estimate $\mu^2$ and thus we never over-estimate it with $E[\bar{x}^2]$. Let's see that this "removes" the bias in $\hat{\sigma}^2$. Let $\hat{\sigma}_\mu^2 = \frac{1}{N}\sum_{n = 1}^N (x_n - \mu)^2$. From the above proof, let's pick up from $E[x_n^2] - E[\bar{x}^2]$ replacing $\bar{x}$ with the true value $\mu$. $$E[x_n^2] - E[\mu^2] = E[x_n^2] - \mu^2 = \sigma^2_x + E[x_n]^2 - \mu^2= \sigma^2_x$$ which is unbiased!
How to understand that MLE of Variance is biased in a Gaussian distribution?
Intuition The bias is "coming from" (not at all a technical term) the fact that $E[\bar{x}^2]$ is biased for $\mu^2$. The natural question is, "well, what's the intuition for why $E[\bar{x}^2]$ is bia
How to understand that MLE of Variance is biased in a Gaussian distribution? Intuition The bias is "coming from" (not at all a technical term) the fact that $E[\bar{x}^2]$ is biased for $\mu^2$. The natural question is, "well, what's the intuition for why $E[\bar{x}^2]$ is biased for $\mu^2$"? The intuition is that in a non-squared sample mean, sometimes we miss the true value $\mu$ by over-estimating and sometimes by under-estimating. But, without squaring, the tendency to over-estimate and under-estimate will cancel each other out. However, when we square $\bar{x}$ the tendency to under-estimate (miss the true value of $\mu$ by a negative number) also gets squared and thus becomes positive. Thus, it no longer cancels out and there is a slight tendency to over-estimate. If the intuition behind why $x^2$ is biased for $\mu^2$ is still unclear, try to understand the intuition behind Jensen's inequality (good intuitive explanation here) and apply it to $E[x^2]$. Let's prove that the MLE of variance for an iid sample is biased. Then we will analytically verify our intuition. Proof Let $\hat{\sigma}^2 = \frac{1}{N}\sum_{n = 1}^N (x_n - \bar{x})^2$. We want to show $E[\hat{\sigma}^2] \neq \sigma^2$. $$E[\hat{\sigma}^2] = E[\frac{1}{N}\sum_{n = 1}^N (x_n - \bar{x})^2] = \frac{1}{N}E[\sum_{n = 1}^N (x_n^2 - 2x_n\bar{x} + \bar{x}^2)] = \frac{1}{N}E[\sum_{n = 1}^N x_n^2 - \sum_{n = 1}^N 2x_n\bar{x} + \sum_{n = 1}^N \bar{x}^2]$$ Using the fact that $\sum_{n = 1}^N x_n = N\bar{x}$ and $\sum_{n = 1}^N \bar{x}^2 = N\bar{x}^2$, $$\frac{1}{N}E[\sum_{n = 1}^N x_n^2 - \sum_{n = 1}^N 2x_n\bar{x} + \sum_{n = 1}^N \bar{x}^2] = \frac{1}{N}E[\sum_{n = 1}^N x_n^2 - 2N\bar{x}^2 + N\bar{x}^2]=\frac{1}{N}E[\sum_{n = 1}^N x_n^2 - N\bar{x}^2] = \frac{1}{N}E[\sum_{n = 1}^N x_n^2] - E[\bar{x}^2] = \frac{1}{N}\sum_{n = 1}^N E[x_n^2] - E[\bar{x}^2] \\= E[x_n^2] - E[\bar{x}^2]$$ With the last step following since due to $E[x_n^2]$ being equal across $n$ due to coming from the same distribution. Now, recall the definition of variance that says $\sigma^2_x = E[x^2] - E[x]^2$. From here, we get the following $$E[x_n^2] - E[\bar{x}^2] = \sigma^2_x + E[x_n]^2 - \sigma^2_\bar{x} - E[x_n]^2 = \sigma^2_x - \sigma^2_\bar{x} = \sigma^2_x - Var(\bar{x}) = \sigma^2_x - Var(\frac{1}{N}\sum_{n = 1}^Nx_n) = \sigma^2_x - \bigg(\frac{1}{N}\bigg)^2Var(\sum_{n = 1}^Nx_n)$$ Notice that we've appropriately squared the constant $\frac{1}{N}$ when taking it out of $Var()$. Pay special attention to that! $$\sigma^2_x - \bigg(\frac{1}{N}\bigg)^2Var(\sum_{n = 1}^Nx_n) = \sigma^2_x - \bigg(\frac{1}{N}\bigg)^2N \sigma^2_x = \sigma^2_x - \frac{1}{N}\sigma^2_x = \frac{N-1}{N}\sigma^2_x$$ which is, of course, not equal to $\sigma_x^2$. Analytically Verify our Intuition We can somewhat verify the intuition by assuming we know the value of $\mu$ and plugging it into the above proof. Since we now know $\mu$, we no longer have the need to estimate $\mu^2$ and thus we never over-estimate it with $E[\bar{x}^2]$. Let's see that this "removes" the bias in $\hat{\sigma}^2$. Let $\hat{\sigma}_\mu^2 = \frac{1}{N}\sum_{n = 1}^N (x_n - \mu)^2$. From the above proof, let's pick up from $E[x_n^2] - E[\bar{x}^2]$ replacing $\bar{x}$ with the true value $\mu$. $$E[x_n^2] - E[\mu^2] = E[x_n^2] - \mu^2 = \sigma^2_x + E[x_n]^2 - \mu^2= \sigma^2_x$$ which is unbiased!
How to understand that MLE of Variance is biased in a Gaussian distribution? Intuition The bias is "coming from" (not at all a technical term) the fact that $E[\bar{x}^2]$ is biased for $\mu^2$. The natural question is, "well, what's the intuition for why $E[\bar{x}^2]$ is bia
11,478
How to understand that MLE of Variance is biased in a Gaussian distribution?
The maximum likelihood estimates of mean and variance for a Gaussian distribution are: \begin{align*} \hat{\mu} &= \frac{1}{N} \sum_{i=1}^N x_i \\ \hat{\sigma}^2 &= \frac{1}{N} \sum_{i=1}^N (x_i - \hat{\mu})^2 \\ \end{align*} Suppose the real mean and variance for the Gaussian distribution is $\mu$ and $\sigma^2$. First, we show $\hat{\mu}$ is unbiased, \begin{align*} \mathbb{E}[ \hat{\mu}] &= \mathbb{E} \left[ \frac{1}{N} \sum_{i=1}^N x_i \right ] \\ &= \frac{1}{N} \sum_{i=1}^N \mathbb{E} [x_i] \\ &= \frac{1}{N} \sum_{i=1}^N \mu \\ &= \mu \end{align*} Next, we show $\hat{\sigma}^2$ is biased, \begin{align} \mathbb{E}[ \hat{\sigma}^2] &= \mathbb{E} \left[ \frac{1}{N} \sum_{i=1}^N (x_i - \hat{\mu})^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N (x_i - \hat{\mu})^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N x_i^2 - \sum_{i=1}^N x_i \hat{\mu} - \sum_{i=1}^N \hat{\mu} x_i + \sum_{i=1}^N \hat{\mu}^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N x_i^2 - N \hat{\mu}^2 - N\hat{\mu}^2 + N\hat{\mu}^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N x_i^2 - N \hat{\mu}^2 \right ] \\ &= \mathbb{E}[x^2] - \mathbb{E}[\hat{\mu}^2] \\ &= \mathbb{E}[x^2] - \mathbb{E} \left[ \left( \frac{1}{N} \sum_i^N x_{i=1} \right ) \left( \frac{1}{N} \sum_{j=1}^N x_j \right ) \right] \\ &= \mathbb{E}[x^2] - \frac{1}{N^2} \mathbb{E} \left[ \sum_{i=1}^N \sum_{j=1}^N x_i x_j \right] \\ &= \mathbb{E}[x^2] - \frac{1}{N^2} \mathbb{E} \left[ \sum_{i=1}^N \sum_{j=1}^N \mathbb{I}(i = j) x_i x_j + \sum_{i=1}^N \sum_{j=1}^N \mathbb{I}(i \ne j) x_i x_j \right] \\ &= \mathbb{E}[x^2] - \frac{1}{N^2} N \mathbb{E}[x^2] - \frac{1}{N^2} N(N - 1) \mu^2 \\ &= \frac{N - 1}{N} \mathbb{E}[x^2] - \frac{N-1}{N} \mu^2 \\ &= \frac{N - 1}{N} \left(\sigma^2 + \mu^2 \right ) - \frac{N-1}{N} \mu^2 \\ &= \frac{N - 1}{N} \sigma^2 \end{align} So $\hat{\sigma}^2$ is an underestimation of $\sigma^2$. When $N=2$ as shown in the plot in the question, $\hat{\sigma}^2 = \frac{1}{2} \sigma^2$, which is a significant underestimation.
How to understand that MLE of Variance is biased in a Gaussian distribution?
The maximum likelihood estimates of mean and variance for a Gaussian distribution are: \begin{align*} \hat{\mu} &= \frac{1}{N} \sum_{i=1}^N x_i \\ \hat{\sigma}^2 &= \frac{1}{N} \sum_{i=1}^N (x_i - \ha
How to understand that MLE of Variance is biased in a Gaussian distribution? The maximum likelihood estimates of mean and variance for a Gaussian distribution are: \begin{align*} \hat{\mu} &= \frac{1}{N} \sum_{i=1}^N x_i \\ \hat{\sigma}^2 &= \frac{1}{N} \sum_{i=1}^N (x_i - \hat{\mu})^2 \\ \end{align*} Suppose the real mean and variance for the Gaussian distribution is $\mu$ and $\sigma^2$. First, we show $\hat{\mu}$ is unbiased, \begin{align*} \mathbb{E}[ \hat{\mu}] &= \mathbb{E} \left[ \frac{1}{N} \sum_{i=1}^N x_i \right ] \\ &= \frac{1}{N} \sum_{i=1}^N \mathbb{E} [x_i] \\ &= \frac{1}{N} \sum_{i=1}^N \mu \\ &= \mu \end{align*} Next, we show $\hat{\sigma}^2$ is biased, \begin{align} \mathbb{E}[ \hat{\sigma}^2] &= \mathbb{E} \left[ \frac{1}{N} \sum_{i=1}^N (x_i - \hat{\mu})^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N (x_i - \hat{\mu})^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N x_i^2 - \sum_{i=1}^N x_i \hat{\mu} - \sum_{i=1}^N \hat{\mu} x_i + \sum_{i=1}^N \hat{\mu}^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N x_i^2 - N \hat{\mu}^2 - N\hat{\mu}^2 + N\hat{\mu}^2 \right ] \\ &= \frac{1}{N} \mathbb{E} \left[ \sum_{i=1}^N x_i^2 - N \hat{\mu}^2 \right ] \\ &= \mathbb{E}[x^2] - \mathbb{E}[\hat{\mu}^2] \\ &= \mathbb{E}[x^2] - \mathbb{E} \left[ \left( \frac{1}{N} \sum_i^N x_{i=1} \right ) \left( \frac{1}{N} \sum_{j=1}^N x_j \right ) \right] \\ &= \mathbb{E}[x^2] - \frac{1}{N^2} \mathbb{E} \left[ \sum_{i=1}^N \sum_{j=1}^N x_i x_j \right] \\ &= \mathbb{E}[x^2] - \frac{1}{N^2} \mathbb{E} \left[ \sum_{i=1}^N \sum_{j=1}^N \mathbb{I}(i = j) x_i x_j + \sum_{i=1}^N \sum_{j=1}^N \mathbb{I}(i \ne j) x_i x_j \right] \\ &= \mathbb{E}[x^2] - \frac{1}{N^2} N \mathbb{E}[x^2] - \frac{1}{N^2} N(N - 1) \mu^2 \\ &= \frac{N - 1}{N} \mathbb{E}[x^2] - \frac{N-1}{N} \mu^2 \\ &= \frac{N - 1}{N} \left(\sigma^2 + \mu^2 \right ) - \frac{N-1}{N} \mu^2 \\ &= \frac{N - 1}{N} \sigma^2 \end{align} So $\hat{\sigma}^2$ is an underestimation of $\sigma^2$. When $N=2$ as shown in the plot in the question, $\hat{\sigma}^2 = \frac{1}{2} \sigma^2$, which is a significant underestimation.
How to understand that MLE of Variance is biased in a Gaussian distribution? The maximum likelihood estimates of mean and variance for a Gaussian distribution are: \begin{align*} \hat{\mu} &= \frac{1}{N} \sum_{i=1}^N x_i \\ \hat{\sigma}^2 &= \frac{1}{N} \sum_{i=1}^N (x_i - \ha
11,479
Weakly informative prior distributions for scale parameters
I would recommend using a "Beta distribution of the second kind" (Beta2 for short) for a mildly informative distribution, and to use the conjugate inverse gamma distribution if you have strong prior beliefs. The reason I say this is that the conjugate prior is non-robust in the sense that, if the prior and data conflict, the prior has an unbounded influence on the posterior distribution. Such behaviour is what I would call "dogmatic", and not justified by mild prior information. The property which determines robustness is the tail-behaviour of the prior and of the likelihood. A very good article outlining the technical details is here. For example, a likelihood can be chosen (say a t-distribution) such that as an observation $y_i \rightarrow \infty$ (i.e. becomes arbitrarily large) it is discarded from the analysis of a location parameter (much in the same way that you would intuitively do with such an observation). The rate of "discarding" depends on how heavy the tails of the distribution are. Some slides which show an application in the hierarchical modelling context can be found here (shows the mathematical form of the Beta2 distribution), with a paper here. If you are not in the hierarchical modeling context, then I would suggest comparing the posterior (or whatever results you are creating) but use the Jeffreys prior for a scale parameter, which is given by $p(\sigma)\propto\frac{1}{\sigma}$. This can be created as a limit of the Beta2 density as both its parameters converge to zero. For an approximation you could use small values. But I would try to work out the solution analytically if at all possible (and if not a complete analytical solution, get the analytical solution as far progressed as you possibly can), because you will not only save yourself some computational time, but you are also likely to understand what is happening in your model better. A further alternative is to specify your prior information in the form of constraints (mean equal to $M$, variance equal to $V$, IQR equal to $IQR$, etc. with the values of $M,V,IQR$ specified by yourself), and then use the maximum entropy distribution (search any work by Edwin Jaynes or Larry Bretthorst for a good explanation of what Maximum Entropy is and what it is not) with respect to Jeffreys' "invariant measure" $m(\sigma)=\frac{1}{\sigma}$. MaxEnt is the "Rolls Royce" version, while the Beta2 is more a "sedan" version. The reason for this is that the MaxEnt distribution "assumes the least" subject to the constraints you have put into it (e.g., no constraints means you just get the Jeffreys prior), whereas the Beta2 distribution may contain some "hidden" features which may or may not be desirable in your specific case (e.g., if the prior information is more reliable than the data, then Beta2 is bad). The other nice property of MaxEnt distribution is that if there are no unspecified constraints operating in the data generating mechanism then the MaxEnt distribution is overwhelmingly the most likely distribution that you will see (we're talking odds way over billions and trillions to one). Therefore, if the distribution you see is not the MaxEnt one, then there is likely additional constraints which you have not specified operating on the true process, and the observed values can provide a clue as to what that constraint might be.
Weakly informative prior distributions for scale parameters
I would recommend using a "Beta distribution of the second kind" (Beta2 for short) for a mildly informative distribution, and to use the conjugate inverse gamma distribution if you have strong prior b
Weakly informative prior distributions for scale parameters I would recommend using a "Beta distribution of the second kind" (Beta2 for short) for a mildly informative distribution, and to use the conjugate inverse gamma distribution if you have strong prior beliefs. The reason I say this is that the conjugate prior is non-robust in the sense that, if the prior and data conflict, the prior has an unbounded influence on the posterior distribution. Such behaviour is what I would call "dogmatic", and not justified by mild prior information. The property which determines robustness is the tail-behaviour of the prior and of the likelihood. A very good article outlining the technical details is here. For example, a likelihood can be chosen (say a t-distribution) such that as an observation $y_i \rightarrow \infty$ (i.e. becomes arbitrarily large) it is discarded from the analysis of a location parameter (much in the same way that you would intuitively do with such an observation). The rate of "discarding" depends on how heavy the tails of the distribution are. Some slides which show an application in the hierarchical modelling context can be found here (shows the mathematical form of the Beta2 distribution), with a paper here. If you are not in the hierarchical modeling context, then I would suggest comparing the posterior (or whatever results you are creating) but use the Jeffreys prior for a scale parameter, which is given by $p(\sigma)\propto\frac{1}{\sigma}$. This can be created as a limit of the Beta2 density as both its parameters converge to zero. For an approximation you could use small values. But I would try to work out the solution analytically if at all possible (and if not a complete analytical solution, get the analytical solution as far progressed as you possibly can), because you will not only save yourself some computational time, but you are also likely to understand what is happening in your model better. A further alternative is to specify your prior information in the form of constraints (mean equal to $M$, variance equal to $V$, IQR equal to $IQR$, etc. with the values of $M,V,IQR$ specified by yourself), and then use the maximum entropy distribution (search any work by Edwin Jaynes or Larry Bretthorst for a good explanation of what Maximum Entropy is and what it is not) with respect to Jeffreys' "invariant measure" $m(\sigma)=\frac{1}{\sigma}$. MaxEnt is the "Rolls Royce" version, while the Beta2 is more a "sedan" version. The reason for this is that the MaxEnt distribution "assumes the least" subject to the constraints you have put into it (e.g., no constraints means you just get the Jeffreys prior), whereas the Beta2 distribution may contain some "hidden" features which may or may not be desirable in your specific case (e.g., if the prior information is more reliable than the data, then Beta2 is bad). The other nice property of MaxEnt distribution is that if there are no unspecified constraints operating in the data generating mechanism then the MaxEnt distribution is overwhelmingly the most likely distribution that you will see (we're talking odds way over billions and trillions to one). Therefore, if the distribution you see is not the MaxEnt one, then there is likely additional constraints which you have not specified operating on the true process, and the observed values can provide a clue as to what that constraint might be.
Weakly informative prior distributions for scale parameters I would recommend using a "Beta distribution of the second kind" (Beta2 for short) for a mildly informative distribution, and to use the conjugate inverse gamma distribution if you have strong prior b
11,480
Weakly informative prior distributions for scale parameters
The following paper by Daniels compares a variety of shrinkage priors for the variance. These are proper priors but I am not sure how many could be called non-informative if any. But, he also provides a list of noninformative priors (not all proper). Below is the reference. M. J. Daniels (1999), A prior for the variance in hierarchical models, Canadian J. Stat., vol. 27, no. 3, pp. 567–578. Priors Flat: $K$ (constant) Location-scale: $\tau^{-2}$ Right-invariant Haar: $\tau^{-1}$ Jeffreys': $1/(\sigma^2 + \tau^2)$ Proper Jeffreys': $\sigma / (2(\sigma^2 + \tau^2)^{3/2})$ Uniform shrinkage: $\sigma^2 / (\sigma^2 + \tau^2)$ DuMouchel: $\sigma/(2\tau(\sigma+\tau)^2)$ Another more recent paper in a related vein is the following. A. Gelman (2006), Prior distributions for variance parameters in hierarchical models, Bayesian Analysis, vol. 1, no. 3, pp. 515–533.
Weakly informative prior distributions for scale parameters
The following paper by Daniels compares a variety of shrinkage priors for the variance. These are proper priors but I am not sure how many could be called non-informative if any. But, he also provide
Weakly informative prior distributions for scale parameters The following paper by Daniels compares a variety of shrinkage priors for the variance. These are proper priors but I am not sure how many could be called non-informative if any. But, he also provides a list of noninformative priors (not all proper). Below is the reference. M. J. Daniels (1999), A prior for the variance in hierarchical models, Canadian J. Stat., vol. 27, no. 3, pp. 567–578. Priors Flat: $K$ (constant) Location-scale: $\tau^{-2}$ Right-invariant Haar: $\tau^{-1}$ Jeffreys': $1/(\sigma^2 + \tau^2)$ Proper Jeffreys': $\sigma / (2(\sigma^2 + \tau^2)^{3/2})$ Uniform shrinkage: $\sigma^2 / (\sigma^2 + \tau^2)$ DuMouchel: $\sigma/(2\tau(\sigma+\tau)^2)$ Another more recent paper in a related vein is the following. A. Gelman (2006), Prior distributions for variance parameters in hierarchical models, Bayesian Analysis, vol. 1, no. 3, pp. 515–533.
Weakly informative prior distributions for scale parameters The following paper by Daniels compares a variety of shrinkage priors for the variance. These are proper priors but I am not sure how many could be called non-informative if any. But, he also provide
11,481
Weakly informative prior distributions for scale parameters
(The question is stale, but the issue is not) Personally, I think your intuition makes some sense. That is to say, if you don't need the mathematical tidiness of conjugacy, then whatever distribution you would use for a location parameter, you should use the same one for the log of a scale parameter. So, what you're saying is: use the equivalent of a normal prior. Would you actually use a normal prior for a location parameter? Most people would say that, unless you make the variance huge, that's probably a bit "too dogmatic", for reasons explained in the other answers here (unbounded influence). An exception would be if you're doing empirical bayes; that is, using your data to estimate the parameters of your prior. If you want to be "weakly informative", you'd probably choose a distribution with fatter tails; the obvious candidates are t distributions. Gelman's latest advice seems to be to use a t with df of 3-7. (Note that the link also supports my suggestion that you want to do the same thing for log of scale that you would do for location) So instead of a lognormal, you could use a log-student-t. To accomplish this in stan, you might do something like: real log_sigma_y; //declare at the top of your model block //...some more code for your model log_sigma_y <- log(sigma_y); increment_log_prob(-log_sigma_y); log_sigma_y ~ student_t(3,1,3); //This is a 'weakly informative prior'. However, I think that if the code above is too complex for you, you could probably get away with a lognormal prior, with two caveats. First, make the variance of that prior a few times wider than your rough guess of how "unsure you are"; you want a weakly informative prior, not a strongly informative one. And second, once you fit your model, check the posterior median of the parameter, and make sure the log of it is not too far from the center of the lognormal. "Not too far" probably means: less than two standard deviations, and preferably not much more than one SD.
Weakly informative prior distributions for scale parameters
(The question is stale, but the issue is not) Personally, I think your intuition makes some sense. That is to say, if you don't need the mathematical tidiness of conjugacy, then whatever distribution
Weakly informative prior distributions for scale parameters (The question is stale, but the issue is not) Personally, I think your intuition makes some sense. That is to say, if you don't need the mathematical tidiness of conjugacy, then whatever distribution you would use for a location parameter, you should use the same one for the log of a scale parameter. So, what you're saying is: use the equivalent of a normal prior. Would you actually use a normal prior for a location parameter? Most people would say that, unless you make the variance huge, that's probably a bit "too dogmatic", for reasons explained in the other answers here (unbounded influence). An exception would be if you're doing empirical bayes; that is, using your data to estimate the parameters of your prior. If you want to be "weakly informative", you'd probably choose a distribution with fatter tails; the obvious candidates are t distributions. Gelman's latest advice seems to be to use a t with df of 3-7. (Note that the link also supports my suggestion that you want to do the same thing for log of scale that you would do for location) So instead of a lognormal, you could use a log-student-t. To accomplish this in stan, you might do something like: real log_sigma_y; //declare at the top of your model block //...some more code for your model log_sigma_y <- log(sigma_y); increment_log_prob(-log_sigma_y); log_sigma_y ~ student_t(3,1,3); //This is a 'weakly informative prior'. However, I think that if the code above is too complex for you, you could probably get away with a lognormal prior, with two caveats. First, make the variance of that prior a few times wider than your rough guess of how "unsure you are"; you want a weakly informative prior, not a strongly informative one. And second, once you fit your model, check the posterior median of the parameter, and make sure the log of it is not too far from the center of the lognormal. "Not too far" probably means: less than two standard deviations, and preferably not much more than one SD.
Weakly informative prior distributions for scale parameters (The question is stale, but the issue is not) Personally, I think your intuition makes some sense. That is to say, if you don't need the mathematical tidiness of conjugacy, then whatever distribution
11,482
Weakly informative prior distributions for scale parameters
For hierarchical model scale parameters, I have mostly ended up using Andrew Gelman's suggestion of using a folded, noncentral t-distribution. This has worked pretty decently for me.
Weakly informative prior distributions for scale parameters
For hierarchical model scale parameters, I have mostly ended up using Andrew Gelman's suggestion of using a folded, noncentral t-distribution. This has worked pretty decently for me.
Weakly informative prior distributions for scale parameters For hierarchical model scale parameters, I have mostly ended up using Andrew Gelman's suggestion of using a folded, noncentral t-distribution. This has worked pretty decently for me.
Weakly informative prior distributions for scale parameters For hierarchical model scale parameters, I have mostly ended up using Andrew Gelman's suggestion of using a folded, noncentral t-distribution. This has worked pretty decently for me.
11,483
Why do neural networks need feature selection / engineering?
What if the "sufficiently deep" network is intractably huge, either making model training too expensive (AWS fees add up!) or because you need to deploy the network in a resource-constrained environment? How can you know, a priori that the network is well-parameterized? It can take a lot of experimentation to find a network that works well. What if the data you're working with is not "friendly" to standard analysis methods, such as a binary string comprising thousands or millions of bits, where each sequence has a different length? What if you're interested in user-level data, but you're forced to work with a database that only collects transaction-level data? Suppose your data are the form of integers such as $12, 32, 486, 7$, and your task is to predict the sum of the digits, so the target in this example is $3, 5, 18, 7$. It's dirt simple to parse each digit into an array and then sum the array ("feature engineering") but challenging otherwise. We would like to live in a world where data analysis is "turnkey," but these kinds of solutions usually only exist in special instances. Lots of work went into developing deep CNNs for image classification - prior work had a step that transformed each image into a fixed-length vector. Feature engineering lets the practitioner directly transform knowledge about the problem into a fixed-length vector amenable to feed-forward networks. Feature selection can solve the problem of including so many irrelevant features that any signal is lost, as well as dramatically reducing the number of parameters to the model.
Why do neural networks need feature selection / engineering?
What if the "sufficiently deep" network is intractably huge, either making model training too expensive (AWS fees add up!) or because you need to deploy the network in a resource-constrained environme
Why do neural networks need feature selection / engineering? What if the "sufficiently deep" network is intractably huge, either making model training too expensive (AWS fees add up!) or because you need to deploy the network in a resource-constrained environment? How can you know, a priori that the network is well-parameterized? It can take a lot of experimentation to find a network that works well. What if the data you're working with is not "friendly" to standard analysis methods, such as a binary string comprising thousands or millions of bits, where each sequence has a different length? What if you're interested in user-level data, but you're forced to work with a database that only collects transaction-level data? Suppose your data are the form of integers such as $12, 32, 486, 7$, and your task is to predict the sum of the digits, so the target in this example is $3, 5, 18, 7$. It's dirt simple to parse each digit into an array and then sum the array ("feature engineering") but challenging otherwise. We would like to live in a world where data analysis is "turnkey," but these kinds of solutions usually only exist in special instances. Lots of work went into developing deep CNNs for image classification - prior work had a step that transformed each image into a fixed-length vector. Feature engineering lets the practitioner directly transform knowledge about the problem into a fixed-length vector amenable to feed-forward networks. Feature selection can solve the problem of including so many irrelevant features that any signal is lost, as well as dramatically reducing the number of parameters to the model.
Why do neural networks need feature selection / engineering? What if the "sufficiently deep" network is intractably huge, either making model training too expensive (AWS fees add up!) or because you need to deploy the network in a resource-constrained environme
11,484
Why do neural networks need feature selection / engineering?
The key words here are priors and scale. As a simple example, imagine you're trying to predict a person's age from a photograph. With a dataset of images and ages, you could train a deep-learning model to make the predictions. This is objectively really inefficient because 90% of the image is useless, and only the region with the person is actually useful. In particular, the person's face, their body and maybe their clothing. On the other hand, you could instead use a pre-trained object detection network to first extract bounding boxes for the person, crop the image, and then pass it through the network. This process will significantly improve the accuracy of your model for a number of reasons: 1) All of the networks resources (i.e. weights) can focus on the actual task of age prediction, as opposed to having to first find the person first. This is especially important because the person's face contains useful features. Otherwise, the finer features that you need may get lost in the first few layers. In theory a big-enough network might solve this, but it would be woefully inefficient. The cropped image is also considerably more regular than the original image. Whereas the original image has a ton of noise, its arguable the discrepancies in the cropped image are much more highly correlated with the objective. 2) The cropped image can be normalized to have the same scale. This helps the second network deal with scaling issues, because in the original image, people can occur near or far away. Normalizing scale beforehand makes it so that the cropped image is guaranteed to have a person in it that fills the full cropped image (despite being pixilated if they were far away). To see how this can help scale, a cropped body that's half the width and height of the original image has 4x less pixels to process, and hence the same network applied to this image would have 4x the original network's receptive field at each layer. For example, in the kaggle lung competition, a common theme in the top solutions was some kind of preprocessing on lung images that cropped them as much as possible and isolated the components of each lung. This is especially important in 3D images since the effect is cubic: by removing 20% of each dimension, you get rid of nearly half the pixels!
Why do neural networks need feature selection / engineering?
The key words here are priors and scale. As a simple example, imagine you're trying to predict a person's age from a photograph. With a dataset of images and ages, you could train a deep-learning mode
Why do neural networks need feature selection / engineering? The key words here are priors and scale. As a simple example, imagine you're trying to predict a person's age from a photograph. With a dataset of images and ages, you could train a deep-learning model to make the predictions. This is objectively really inefficient because 90% of the image is useless, and only the region with the person is actually useful. In particular, the person's face, their body and maybe their clothing. On the other hand, you could instead use a pre-trained object detection network to first extract bounding boxes for the person, crop the image, and then pass it through the network. This process will significantly improve the accuracy of your model for a number of reasons: 1) All of the networks resources (i.e. weights) can focus on the actual task of age prediction, as opposed to having to first find the person first. This is especially important because the person's face contains useful features. Otherwise, the finer features that you need may get lost in the first few layers. In theory a big-enough network might solve this, but it would be woefully inefficient. The cropped image is also considerably more regular than the original image. Whereas the original image has a ton of noise, its arguable the discrepancies in the cropped image are much more highly correlated with the objective. 2) The cropped image can be normalized to have the same scale. This helps the second network deal with scaling issues, because in the original image, people can occur near or far away. Normalizing scale beforehand makes it so that the cropped image is guaranteed to have a person in it that fills the full cropped image (despite being pixilated if they were far away). To see how this can help scale, a cropped body that's half the width and height of the original image has 4x less pixels to process, and hence the same network applied to this image would have 4x the original network's receptive field at each layer. For example, in the kaggle lung competition, a common theme in the top solutions was some kind of preprocessing on lung images that cropped them as much as possible and isolated the components of each lung. This is especially important in 3D images since the effect is cubic: by removing 20% of each dimension, you get rid of nearly half the pixels!
Why do neural networks need feature selection / engineering? The key words here are priors and scale. As a simple example, imagine you're trying to predict a person's age from a photograph. With a dataset of images and ages, you could train a deep-learning mode
11,485
Why do neural networks need feature selection / engineering?
My intuition about this phenomenon is connected to the complexity of the model to be learned. A deep neural network can indeed approximate any function in theory, but the dimension of the parameter space can be really large, like in the millions. So, actually finding a good neural network is really difficult. I like to think about feature engineering as giving a head start to the algorithm, providing it some extra information regarding the data representation which is good enough in some sense. Of course, this is not a formal explanation, this question might be really hard to answer with scientific rigor.
Why do neural networks need feature selection / engineering?
My intuition about this phenomenon is connected to the complexity of the model to be learned. A deep neural network can indeed approximate any function in theory, but the dimension of the parameter sp
Why do neural networks need feature selection / engineering? My intuition about this phenomenon is connected to the complexity of the model to be learned. A deep neural network can indeed approximate any function in theory, but the dimension of the parameter space can be really large, like in the millions. So, actually finding a good neural network is really difficult. I like to think about feature engineering as giving a head start to the algorithm, providing it some extra information regarding the data representation which is good enough in some sense. Of course, this is not a formal explanation, this question might be really hard to answer with scientific rigor.
Why do neural networks need feature selection / engineering? My intuition about this phenomenon is connected to the complexity of the model to be learned. A deep neural network can indeed approximate any function in theory, but the dimension of the parameter sp
11,486
Relationship between ridge regression and PCA regression
Let $\mathbf X$ be the centered $n \times p$ predictor matrix and consider its singular value decomposition $\mathbf X = \mathbf{USV}^\top$ with $\mathbf S$ being a diagonal matrix with diagonal elements $s_i$. The fitted values of ordinary least squares (OLS) regression are given by $$\hat {\mathbf y}_\mathrm{OLS} = \mathbf X \beta_\mathrm{OLS} = \mathbf X (\mathbf X^\top \mathbf X)^{-1} \mathbf X^\top \mathbf y = \mathbf U \mathbf U^\top \mathbf y.$$ The fitted values of the ridge regression are given by $$\hat {\mathbf y}_\mathrm{ridge} = \mathbf X \beta_\mathrm{ridge} = \mathbf X (\mathbf X^\top \mathbf X + \lambda \mathbf I)^{-1} \mathbf X^\top \mathbf y = \mathbf U\: \mathrm{diag}\left\{\frac{s_i^2}{s_i^2+\lambda}\right\}\mathbf U^\top \mathbf y.$$ The fitted values of the PCA regression (PCR) with $k$ components are given by $$\hat {\mathbf y}_\mathrm{PCR} = \mathbf X_\mathrm{PCA} \beta_\mathrm{PCR} = \mathbf U\: \mathrm{diag}\left\{1,\ldots, 1, 0, \ldots 0\right\}\mathbf U^\top \mathbf y,$$ where there are $k$ ones followed by zeroes. From here we can see that: If $\lambda=0$ then $\hat {\mathbf y}_\mathrm{ridge} = \hat {\mathbf y}_\mathrm{OLS}$. If $\lambda>0$ then the larger the singular value $s_i$, the less it will be penalized in ridge regression. Small singular values ($s_i^2 \approx \lambda$ and smaller) are penalized the most. In contrast, in PCA regression, large singular values are kept intact, and the small ones (after certain number $k$) are completely removed. This would correspond to $\lambda=0$ for the first $k$ ones and $\lambda=\infty$ for the rest. This means that ridge regression can be seen as a "smooth version" of PCR. (This intuition is useful but does not always hold; e.g. if all $s_i$ are approximately equal, then ridge regression will only be able to penalize all principal components of $\mathbf X$ approximately equally and can strongly differ from PCR). Ridge regression tends to perform better in practice (e.g. to have higher cross-validated performance). Answering now your question specifically: if $\lambda \to 0$, then $\hat {\mathbf y}_\mathrm{ridge} \to \hat {\mathbf y}_\mathrm{OLS}$. I don't see how it can correspond to removing the smallest $s_i$. I think this is wrong. One good reference is The Elements of Statistical Learning, Section 3.4.1 "Ridge regression". See also this thread: Interpretation of ridge regularization in regression and in particular the answer by @BrianBorchers.
Relationship between ridge regression and PCA regression
Let $\mathbf X$ be the centered $n \times p$ predictor matrix and consider its singular value decomposition $\mathbf X = \mathbf{USV}^\top$ with $\mathbf S$ being a diagonal matrix with diagonal eleme
Relationship between ridge regression and PCA regression Let $\mathbf X$ be the centered $n \times p$ predictor matrix and consider its singular value decomposition $\mathbf X = \mathbf{USV}^\top$ with $\mathbf S$ being a diagonal matrix with diagonal elements $s_i$. The fitted values of ordinary least squares (OLS) regression are given by $$\hat {\mathbf y}_\mathrm{OLS} = \mathbf X \beta_\mathrm{OLS} = \mathbf X (\mathbf X^\top \mathbf X)^{-1} \mathbf X^\top \mathbf y = \mathbf U \mathbf U^\top \mathbf y.$$ The fitted values of the ridge regression are given by $$\hat {\mathbf y}_\mathrm{ridge} = \mathbf X \beta_\mathrm{ridge} = \mathbf X (\mathbf X^\top \mathbf X + \lambda \mathbf I)^{-1} \mathbf X^\top \mathbf y = \mathbf U\: \mathrm{diag}\left\{\frac{s_i^2}{s_i^2+\lambda}\right\}\mathbf U^\top \mathbf y.$$ The fitted values of the PCA regression (PCR) with $k$ components are given by $$\hat {\mathbf y}_\mathrm{PCR} = \mathbf X_\mathrm{PCA} \beta_\mathrm{PCR} = \mathbf U\: \mathrm{diag}\left\{1,\ldots, 1, 0, \ldots 0\right\}\mathbf U^\top \mathbf y,$$ where there are $k$ ones followed by zeroes. From here we can see that: If $\lambda=0$ then $\hat {\mathbf y}_\mathrm{ridge} = \hat {\mathbf y}_\mathrm{OLS}$. If $\lambda>0$ then the larger the singular value $s_i$, the less it will be penalized in ridge regression. Small singular values ($s_i^2 \approx \lambda$ and smaller) are penalized the most. In contrast, in PCA regression, large singular values are kept intact, and the small ones (after certain number $k$) are completely removed. This would correspond to $\lambda=0$ for the first $k$ ones and $\lambda=\infty$ for the rest. This means that ridge regression can be seen as a "smooth version" of PCR. (This intuition is useful but does not always hold; e.g. if all $s_i$ are approximately equal, then ridge regression will only be able to penalize all principal components of $\mathbf X$ approximately equally and can strongly differ from PCR). Ridge regression tends to perform better in practice (e.g. to have higher cross-validated performance). Answering now your question specifically: if $\lambda \to 0$, then $\hat {\mathbf y}_\mathrm{ridge} \to \hat {\mathbf y}_\mathrm{OLS}$. I don't see how it can correspond to removing the smallest $s_i$. I think this is wrong. One good reference is The Elements of Statistical Learning, Section 3.4.1 "Ridge regression". See also this thread: Interpretation of ridge regularization in regression and in particular the answer by @BrianBorchers.
Relationship between ridge regression and PCA regression Let $\mathbf X$ be the centered $n \times p$ predictor matrix and consider its singular value decomposition $\mathbf X = \mathbf{USV}^\top$ with $\mathbf S$ being a diagonal matrix with diagonal eleme
11,487
Relationship between ridge regression and PCA regression
Elements of Statistical Learning has a great discussion on this connection. The way I interpreted this connection and logic is as follows: PCA is a Linear Combination of the Feature Variables, attempting to maximize the variance of the data explained by the new space. Data that suffers from multicollinearity (or more predictors than rows of data) leads to a Covariance Matrix that does not have full Rank. With this Covariance Matrix, we cannot invert to determine the Least Squares solution; this causes the numerical approximation of the Least Squares Coefficients to blow up to infinity. Ridge Regression introduces the penalty Lambda on the Covariance Matrix to allow for matrix inversion and convergence of the LS Coefficients. The PCA connection is that Ridge Regression is calculating the Linear Combinations of the Features to determine where the multicollinearity is occurring. The Linear Combinations of Features (Principle Component Analysis) with the smallest variance (and hence smaller singular values and smaller eigenvalues in PCA) are the ones penalized the hardest. Think of it this way; for the Linear Combinations of Features with smallest variance, we have found the Features that are most alike, hence causing the multicollinearity. Since Ridge does not reduce the Feature set, whichever direction this Linear Combination is describing, the original Feature corresponding to that direction is penalized the most.
Relationship between ridge regression and PCA regression
Elements of Statistical Learning has a great discussion on this connection. The way I interpreted this connection and logic is as follows: PCA is a Linear Combination of the Feature Variables, attem
Relationship between ridge regression and PCA regression Elements of Statistical Learning has a great discussion on this connection. The way I interpreted this connection and logic is as follows: PCA is a Linear Combination of the Feature Variables, attempting to maximize the variance of the data explained by the new space. Data that suffers from multicollinearity (or more predictors than rows of data) leads to a Covariance Matrix that does not have full Rank. With this Covariance Matrix, we cannot invert to determine the Least Squares solution; this causes the numerical approximation of the Least Squares Coefficients to blow up to infinity. Ridge Regression introduces the penalty Lambda on the Covariance Matrix to allow for matrix inversion and convergence of the LS Coefficients. The PCA connection is that Ridge Regression is calculating the Linear Combinations of the Features to determine where the multicollinearity is occurring. The Linear Combinations of Features (Principle Component Analysis) with the smallest variance (and hence smaller singular values and smaller eigenvalues in PCA) are the ones penalized the hardest. Think of it this way; for the Linear Combinations of Features with smallest variance, we have found the Features that are most alike, hence causing the multicollinearity. Since Ridge does not reduce the Feature set, whichever direction this Linear Combination is describing, the original Feature corresponding to that direction is penalized the most.
Relationship between ridge regression and PCA regression Elements of Statistical Learning has a great discussion on this connection. The way I interpreted this connection and logic is as follows: PCA is a Linear Combination of the Feature Variables, attem
11,488
Relationship between ridge regression and PCA regression
Consider the linear equation $$ \mathbf X \beta = \mathbf y\,, $$ and the SVD of $\mathbf X$, $$ \mathbf X = \mathbf U \,\mathbf S \,\mathbf V^T, $$ where $\mathbf S = \text{diag}(s_i)$ is the diagonal matrix of singular values. Ordinary least squares determines the parameter vector $\beta$ as $$ \beta_{OLS} = \mathbf V \,\mathbf S^{-1} \,\mathbf U^T \, \mathbf y $$ However, this approach fails as soon there is one singular value which is zero (as then the inverse does not exists). Moreover, even if no $s_i$ is excatly zero, numerically small singular values can render the matrix ill-conditioned and lead to a solution which is highly susceptible to errors. Ridge regression and PCA present two methods to avoid these problems. Ridge regression replaces $\mathbf S^{-1}$ in the above equation for $\beta$ by \begin{align} \mathbf S^{-1}_{\text{ridge}} &= \text{diag}\bigg(\frac{s_i}{s^2_i+\alpha}\bigg),\\ \beta_{\text{ridge}} &= \ \mathbf V \,\mathbf S_{\text{ridge}}^{-1} \,\mathbf U^T \, \mathbf y \end{align} PCA replaces $\mathbf S^{-1}$ by \begin{align} \mathbf S^{-1}_{\text{PCA}} &= \text{diag}\bigg(\frac{1}{s_i} \, \theta(s_i-\gamma)\bigg)\,,\\ \beta_{\text{PCA}} &= \ \mathbf V \,\mathbf S_{\text{PCA}}^{-1} \,\mathbf U^T \, \mathbf y \end{align} wehre $\theta$ is the step function, and $\gamma$ is the threshold parameter. Both methods thus weaken the impact of subspaces corresponding to small singular values. PCA does that in a hard way, while the ridge is a smoother approach. More abstractly, feel free to come up with your own regularization scheme $$ \mathbf S^{-1}_{\text{myReg}} = \text{diag}\big(R(s_i)\big)\,, $$ where $R(x)$ is a function that should approach zero for $x\rightarrow 0$ and $R(x)\rightarrow x^{-1}$ for $x$ large. But remember, there's no free lunch.
Relationship between ridge regression and PCA regression
Consider the linear equation $$ \mathbf X \beta = \mathbf y\,, $$ and the SVD of $\mathbf X$, $$ \mathbf X = \mathbf U \,\mathbf S \,\mathbf V^T, $$ where $\mathbf S = \text{diag}(s_i)$ is the dia
Relationship between ridge regression and PCA regression Consider the linear equation $$ \mathbf X \beta = \mathbf y\,, $$ and the SVD of $\mathbf X$, $$ \mathbf X = \mathbf U \,\mathbf S \,\mathbf V^T, $$ where $\mathbf S = \text{diag}(s_i)$ is the diagonal matrix of singular values. Ordinary least squares determines the parameter vector $\beta$ as $$ \beta_{OLS} = \mathbf V \,\mathbf S^{-1} \,\mathbf U^T \, \mathbf y $$ However, this approach fails as soon there is one singular value which is zero (as then the inverse does not exists). Moreover, even if no $s_i$ is excatly zero, numerically small singular values can render the matrix ill-conditioned and lead to a solution which is highly susceptible to errors. Ridge regression and PCA present two methods to avoid these problems. Ridge regression replaces $\mathbf S^{-1}$ in the above equation for $\beta$ by \begin{align} \mathbf S^{-1}_{\text{ridge}} &= \text{diag}\bigg(\frac{s_i}{s^2_i+\alpha}\bigg),\\ \beta_{\text{ridge}} &= \ \mathbf V \,\mathbf S_{\text{ridge}}^{-1} \,\mathbf U^T \, \mathbf y \end{align} PCA replaces $\mathbf S^{-1}$ by \begin{align} \mathbf S^{-1}_{\text{PCA}} &= \text{diag}\bigg(\frac{1}{s_i} \, \theta(s_i-\gamma)\bigg)\,,\\ \beta_{\text{PCA}} &= \ \mathbf V \,\mathbf S_{\text{PCA}}^{-1} \,\mathbf U^T \, \mathbf y \end{align} wehre $\theta$ is the step function, and $\gamma$ is the threshold parameter. Both methods thus weaken the impact of subspaces corresponding to small singular values. PCA does that in a hard way, while the ridge is a smoother approach. More abstractly, feel free to come up with your own regularization scheme $$ \mathbf S^{-1}_{\text{myReg}} = \text{diag}\big(R(s_i)\big)\,, $$ where $R(x)$ is a function that should approach zero for $x\rightarrow 0$ and $R(x)\rightarrow x^{-1}$ for $x$ large. But remember, there's no free lunch.
Relationship between ridge regression and PCA regression Consider the linear equation $$ \mathbf X \beta = \mathbf y\,, $$ and the SVD of $\mathbf X$, $$ \mathbf X = \mathbf U \,\mathbf S \,\mathbf V^T, $$ where $\mathbf S = \text{diag}(s_i)$ is the dia
11,489
What is a block in experimental design?
The block is a factor. The main aim of blocking is to reduce the unexplained variation $(SS_{Residual})$ of a design -compared to non-blocked design-. We are not interested in the block effect per se , rather we block when we suspect the the background "noise" would counfound the effect of the actual factor. We group experimental units into "homogeneous" blocks where all levels of the main factor are equally represented. The analysis of variance of a Randomized Control Block design splits the residual term of an equivalent single factor Complete Randomized design in block and residual components. We should note, however, that the latter component has fewer degrees of freedom than in single factor CR designs, leading to higher estimates for $MS_{Residual} = {SS_{Residual}}/{d.f.}$. The decision to block or not to block should be made when we reckon that the decrease in the residuals will more than compensate for the decrease in d.f. Usually an additive model is fitted to RCB design data, in which the response variable is an additive combination of the factor and the block effects and it is assumed that no interaction exists between the two. I think this is accounted for by the fact that RCB does not enable us to tell apart the interaction BxF from the within Block variability and the variability within experimental units. The bottom line is that we have to assume no interaction since we can't measure it. We can test whether it is present either visually or with Tukey's test, though. A good resource on experimental design is this.
What is a block in experimental design?
The block is a factor. The main aim of blocking is to reduce the unexplained variation $(SS_{Residual})$ of a design -compared to non-blocked design-. We are not interested in the block effect per se
What is a block in experimental design? The block is a factor. The main aim of blocking is to reduce the unexplained variation $(SS_{Residual})$ of a design -compared to non-blocked design-. We are not interested in the block effect per se , rather we block when we suspect the the background "noise" would counfound the effect of the actual factor. We group experimental units into "homogeneous" blocks where all levels of the main factor are equally represented. The analysis of variance of a Randomized Control Block design splits the residual term of an equivalent single factor Complete Randomized design in block and residual components. We should note, however, that the latter component has fewer degrees of freedom than in single factor CR designs, leading to higher estimates for $MS_{Residual} = {SS_{Residual}}/{d.f.}$. The decision to block or not to block should be made when we reckon that the decrease in the residuals will more than compensate for the decrease in d.f. Usually an additive model is fitted to RCB design data, in which the response variable is an additive combination of the factor and the block effects and it is assumed that no interaction exists between the two. I think this is accounted for by the fact that RCB does not enable us to tell apart the interaction BxF from the within Block variability and the variability within experimental units. The bottom line is that we have to assume no interaction since we can't measure it. We can test whether it is present either visually or with Tukey's test, though. A good resource on experimental design is this.
What is a block in experimental design? The block is a factor. The main aim of blocking is to reduce the unexplained variation $(SS_{Residual})$ of a design -compared to non-blocked design-. We are not interested in the block effect per se
11,490
What is a block in experimental design?
Here is a concise answer. A lot of details and examples might be found in most documents treating the design of experiments; especially in agronomy. Often, the researcher is not interested in the block effect per se, but he only wants to account for the variability in response between blocks. So, I use to view the block as a factor with a particular role. Of note, the block effect is typically considered as a random effect. Finally, if you expect the 'treatment effect' to differ from block to block, then interactions should be considered.
What is a block in experimental design?
Here is a concise answer. A lot of details and examples might be found in most documents treating the design of experiments; especially in agronomy. Often, the researcher is not interested in the bloc
What is a block in experimental design? Here is a concise answer. A lot of details and examples might be found in most documents treating the design of experiments; especially in agronomy. Often, the researcher is not interested in the block effect per se, but he only wants to account for the variability in response between blocks. So, I use to view the block as a factor with a particular role. Of note, the block effect is typically considered as a random effect. Finally, if you expect the 'treatment effect' to differ from block to block, then interactions should be considered.
What is a block in experimental design? Here is a concise answer. A lot of details and examples might be found in most documents treating the design of experiments; especially in agronomy. Often, the researcher is not interested in the bloc
11,491
What is a block in experimental design?
Here's a paraphrase of my favorite explanation, from my former teacher Freedom King. You are studying how bread dough and baking temperature affect the tastiness of bread. You have a rating scale for tastiness. And let's say you're purchasing packaged bread dough from some food company rather than mixing it yourself. Each baked loaf of bread is an experimental unit. Let's say that you have 2 doughs and 8 temperatures, you can fit 4 loaves of bread in the oven at once and you want to run $n=160$ loaves. In a completely randomized $2\times2$ factorial layout (no blocks), you would completely randomly decide the order in which the breads are baked. For each loaf, you would preheat the oven, open a package of bread dough, and bake it. This would involve running the oven 160 times, once for each loaf of bread. Alternatively, you could treat oven run as a blocking factor. In this case, you would run the oven 40 times, which might make data collection faster. Each oven run would have four loaves, but not necessarily two of each dough type. (The exact proportion would be chosen randomly.) You would have 5 oven runs for each temperature; this could help you to account for variability among same-temperature oven runs. Even fancier, you could block by dough as well as oven run. In this design, you would have exactly two of each type of dough in each of the oven runs. When I have time to think it through, I'll update this further with the appropriate fancy names for those experiment designs.
What is a block in experimental design?
Here's a paraphrase of my favorite explanation, from my former teacher Freedom King. You are studying how bread dough and baking temperature affect the tastiness of bread. You have a rating scale for
What is a block in experimental design? Here's a paraphrase of my favorite explanation, from my former teacher Freedom King. You are studying how bread dough and baking temperature affect the tastiness of bread. You have a rating scale for tastiness. And let's say you're purchasing packaged bread dough from some food company rather than mixing it yourself. Each baked loaf of bread is an experimental unit. Let's say that you have 2 doughs and 8 temperatures, you can fit 4 loaves of bread in the oven at once and you want to run $n=160$ loaves. In a completely randomized $2\times2$ factorial layout (no blocks), you would completely randomly decide the order in which the breads are baked. For each loaf, you would preheat the oven, open a package of bread dough, and bake it. This would involve running the oven 160 times, once for each loaf of bread. Alternatively, you could treat oven run as a blocking factor. In this case, you would run the oven 40 times, which might make data collection faster. Each oven run would have four loaves, but not necessarily two of each dough type. (The exact proportion would be chosen randomly.) You would have 5 oven runs for each temperature; this could help you to account for variability among same-temperature oven runs. Even fancier, you could block by dough as well as oven run. In this design, you would have exactly two of each type of dough in each of the oven runs. When I have time to think it through, I'll update this further with the appropriate fancy names for those experiment designs.
What is a block in experimental design? Here's a paraphrase of my favorite explanation, from my former teacher Freedom King. You are studying how bread dough and baking temperature affect the tastiness of bread. You have a rating scale for
11,492
What is a block in experimental design?
Experimental designs are a combination of three structures: The treatment structure: How are treatments formed from factors of interest? The design structure: How are experimental units grouped and assigned to treatments? The response structure: How are observations taken? Blocks are "factors" that belong to the design structure (to distinguish, it's not a bad idea to call them "blocking factors" vs "treatment factors"). They are good examples of nuisance parameters: model parameters you have to have and whose presence you must account for, but whose values are not particularly interesting. Please note that this has nothing to do with the nature of a factor -- blocking factors may be fixed or random, just as treatment factors may be fixed or random. My personal rule of thumb regarding where a factor belongs in an experimental design is this: If I want to estimate the parameters associated with the factor and compare them either within the factor or other factor parameters, then it belongs to the treatment structure. If I don't care about the values of the associated parameters and don't care to compare them, the factor belongs to the design structure. Thus, in the bread example elsewhere in this thread, I have to worry about run-to-run differences. But I don't care to compare Run 1 vs Run 24. Oven run belongs to the design structure. I do want to compare the two dough recipes: recipe belongs to the treatment structure. I care about oven temperature: that belongs to the treatment structure, too. Let's build an Experimental Design. The Design Structure has one factor (oven run, Run), and the Treatment Structure two factors (Recipe and Temperature). Because every run has to be a single (nominal) temperature, Temperature and Run must occur at the same level of the experimental design. However, there is space for 4 loaves in each Run. Obviously, we can choose to bake 1, 2, 3 or 4 loaves per run. If we bake one loaf per run, and randomize the order of Recipe presentation we get a Completely Randomized Design (CRD) Structure. If we bake two loaves, one of each Recipe per Run, we have a Randomized Complete Block Design (RCB) Structure. Please note that it is important that each Recipe occur within each Run. Without that balance, Recipe comparisons will be contaminated by Run differences. Remember: the goal of blocking is to get rid of Run differences. If we bake three loaves per Run, we would probably be crazy: 3 is not a factor of 160, so we will have one or two different-sized blocks. The other reasonable possibility is four loaves per Run. In this case we would bake two loaves of each recipe in each Run. Again, this is a RCB Structure. We can estimate the within-run variability using differences between the two loaves of each Recipe in each Run. If we choose one of the RCB Design Structures, Temperature effects are completely randomized at the Run level. Recipe is nested within temperature and has a different error structure than temperature, because each dough appears within each run. The contrasts looking at recipe and recipe by dough non-additivity (interaction) do not have run-to-run variability in them. Technically, this is called variously a split-plot design structure or a repeated-measures design structure. Which would the investigator use? Probably the RCB with four loaves: 40 runs vs 80 vs 160 carries a lot of weight. However, this can be modified -- if the concern is home ovens rather than industrial production, there may well be reason to use the CRD if it is believed that home bakers rarely bake multiple loaves.
What is a block in experimental design?
Experimental designs are a combination of three structures: The treatment structure: How are treatments formed from factors of interest? The design structure: How are experimental units grouped and
What is a block in experimental design? Experimental designs are a combination of three structures: The treatment structure: How are treatments formed from factors of interest? The design structure: How are experimental units grouped and assigned to treatments? The response structure: How are observations taken? Blocks are "factors" that belong to the design structure (to distinguish, it's not a bad idea to call them "blocking factors" vs "treatment factors"). They are good examples of nuisance parameters: model parameters you have to have and whose presence you must account for, but whose values are not particularly interesting. Please note that this has nothing to do with the nature of a factor -- blocking factors may be fixed or random, just as treatment factors may be fixed or random. My personal rule of thumb regarding where a factor belongs in an experimental design is this: If I want to estimate the parameters associated with the factor and compare them either within the factor or other factor parameters, then it belongs to the treatment structure. If I don't care about the values of the associated parameters and don't care to compare them, the factor belongs to the design structure. Thus, in the bread example elsewhere in this thread, I have to worry about run-to-run differences. But I don't care to compare Run 1 vs Run 24. Oven run belongs to the design structure. I do want to compare the two dough recipes: recipe belongs to the treatment structure. I care about oven temperature: that belongs to the treatment structure, too. Let's build an Experimental Design. The Design Structure has one factor (oven run, Run), and the Treatment Structure two factors (Recipe and Temperature). Because every run has to be a single (nominal) temperature, Temperature and Run must occur at the same level of the experimental design. However, there is space for 4 loaves in each Run. Obviously, we can choose to bake 1, 2, 3 or 4 loaves per run. If we bake one loaf per run, and randomize the order of Recipe presentation we get a Completely Randomized Design (CRD) Structure. If we bake two loaves, one of each Recipe per Run, we have a Randomized Complete Block Design (RCB) Structure. Please note that it is important that each Recipe occur within each Run. Without that balance, Recipe comparisons will be contaminated by Run differences. Remember: the goal of blocking is to get rid of Run differences. If we bake three loaves per Run, we would probably be crazy: 3 is not a factor of 160, so we will have one or two different-sized blocks. The other reasonable possibility is four loaves per Run. In this case we would bake two loaves of each recipe in each Run. Again, this is a RCB Structure. We can estimate the within-run variability using differences between the two loaves of each Recipe in each Run. If we choose one of the RCB Design Structures, Temperature effects are completely randomized at the Run level. Recipe is nested within temperature and has a different error structure than temperature, because each dough appears within each run. The contrasts looking at recipe and recipe by dough non-additivity (interaction) do not have run-to-run variability in them. Technically, this is called variously a split-plot design structure or a repeated-measures design structure. Which would the investigator use? Probably the RCB with four loaves: 40 runs vs 80 vs 160 carries a lot of weight. However, this can be modified -- if the concern is home ovens rather than industrial production, there may well be reason to use the CRD if it is believed that home bakers rarely bake multiple loaves.
What is a block in experimental design? Experimental designs are a combination of three structures: The treatment structure: How are treatments formed from factors of interest? The design structure: How are experimental units grouped and
11,493
What is a block in experimental design?
I think most of the time it’s just a matter of convention, likely proper to each field. I think that in medical context, in a two factors anova one of the factors is almost always called "treatment" and the other "block". Typically, as ocram says, the block effect will be a random effect, but I don’t think this is systematic. Let says you want to assess the effectiveness of different medical treatments: First design: each patient takes only one treatment, and the efficiency is measured on an appropriate scale. You suspect that the sex of the patient is of interest: you will have a "block" of male and a block of female patients. In this case, the block is a factor with a fixed effect. Second design: each patients tries all treatments at different moments. As there is some variability between patients, you consider each patient as a "block". You are interested in the existence of such a variability in the population, but not in its value in these particular patients. In this case, the block is a factor with a random effect. Well, I only teach this stuff, trying to stick with the conventions of the domain (in France) as I got them from textbooks, but I never participated to a clinical trial (and don’t want to)... so this is just my two cents...!
What is a block in experimental design?
I think most of the time it’s just a matter of convention, likely proper to each field. I think that in medical context, in a two factors anova one of the factors is almost always called "treatment" a
What is a block in experimental design? I think most of the time it’s just a matter of convention, likely proper to each field. I think that in medical context, in a two factors anova one of the factors is almost always called "treatment" and the other "block". Typically, as ocram says, the block effect will be a random effect, but I don’t think this is systematic. Let says you want to assess the effectiveness of different medical treatments: First design: each patient takes only one treatment, and the efficiency is measured on an appropriate scale. You suspect that the sex of the patient is of interest: you will have a "block" of male and a block of female patients. In this case, the block is a factor with a fixed effect. Second design: each patients tries all treatments at different moments. As there is some variability between patients, you consider each patient as a "block". You are interested in the existence of such a variability in the population, but not in its value in these particular patients. In this case, the block is a factor with a random effect. Well, I only teach this stuff, trying to stick with the conventions of the domain (in France) as I got them from textbooks, but I never participated to a clinical trial (and don’t want to)... so this is just my two cents...!
What is a block in experimental design? I think most of the time it’s just a matter of convention, likely proper to each field. I think that in medical context, in a two factors anova one of the factors is almost always called "treatment" a
11,494
What is the importance of probabilistic machine learning?
Contemporary machine learning, as a field, requires more familiarity with Bayesian methods and with probabilistic mathematics than does traditional statistics or even the quantitative social sciences, where frequentist statistical methods still dominate. Those coming from Physics are less likely to be surprised by the importance of probabilities in ML since quantum physics is so thoroughly probabilistic (indeed, many key probabilistic algorithms are named after physicists). In fact, three of the leading ML textbooks (while all broad enough in their coverage to be considered fair overviews of ML) are written by authors who explicitly favor probabilistic methods (and McKay and Bishop were both trained as physicists): Kevin Murphy's Machine Learning: A Probabilistic Perspective (an encyclopedic, nearly comprehensive reference-style work) Christopher Bishop's Pattern Recognition and Machine Learning (a rigorous introduction that assumes much less background knowledge) David McKay's Information Theory, Inference, and Learning Algorithms (foregrounding information theory, but welcoming Bayesian methods) My point: the most widely used ML textbooks reflect the same probabilistic focus you describe in your Intro to ML course. In terms of your specific question, Zoubin Ghahramani, another influential proponent of probabilistic ML, argues that the dominant frequentist version of ML--deep learning--suffers from six limitations that explicitly probabilistic, Bayesian methods often avoid: very data hungry very compute-intensive to train and deploy poor at representing uncertainty and knowing what they don't know easily fooled by adversarial examples finicky to optimize (non-convex, choice of architecture and hyperparameters) uninterpretable black boxes, lacking transparency, difficult to trust Ghahramani elaborates on these points in many great tutorials and in this non-specialist overview article from Nature (2015) on Probabilistic Machine Learning and Artificial Intelligence. Ghahramani's article emphasizes that probabilistic methods are crucial whenever you don't have enough data. He explains (section 7) that nonparametric Bayesian models can expand to match datasets of any size with a potentially infinite number of parameters. And he notes that many datasets that may seem enormous (millions of training examples) are in fact large collections of small datasets, where probabilistic methods remain crucial to handle the uncertainties stemming from insufficient data. A similar thesis grounds Part III of the renowned book Deep Learning, where Ian Goodfellow, Yoshua Bengio, and Aaron Courville argue that "Deep Learning Research" must become probabilistic in order to become more data efficient. Because probabilistic models effectively "know what they don't know", they can help prevent terrible decisions based on unfounded extrapolations from insufficient data. As the questions we ask and the models we build become increasingly complex, the risks of insufficient data rise. And as the decisions we base upon our ML models become increasingly high-stake, the dangers associated with models that are confidently wrong (unable to pull back and say "hey, wait, I've never really seen inputs like this before") increase as well. Since both of those trends seem irreversible--ML growing in both popularity and importance--I expect probabilistic methods to become more and more widespread over time. As long as our datasets remain small relative to the complexity of our questions and to the risks of giving bad answers, we should use probabilistic models that know their own limitations. The best probabilistic models have something analogous to our human capacity to recognize feelings of confusion and disorientation (registering huge or compounding uncertainties). They can effectively warn us when they are entering uncharted territory and thereby prevent us from making potentially catastrophic decisions when they are nearing or exceeding their limits.
What is the importance of probabilistic machine learning?
Contemporary machine learning, as a field, requires more familiarity with Bayesian methods and with probabilistic mathematics than does traditional statistics or even the quantitative social sciences,
What is the importance of probabilistic machine learning? Contemporary machine learning, as a field, requires more familiarity with Bayesian methods and with probabilistic mathematics than does traditional statistics or even the quantitative social sciences, where frequentist statistical methods still dominate. Those coming from Physics are less likely to be surprised by the importance of probabilities in ML since quantum physics is so thoroughly probabilistic (indeed, many key probabilistic algorithms are named after physicists). In fact, three of the leading ML textbooks (while all broad enough in their coverage to be considered fair overviews of ML) are written by authors who explicitly favor probabilistic methods (and McKay and Bishop were both trained as physicists): Kevin Murphy's Machine Learning: A Probabilistic Perspective (an encyclopedic, nearly comprehensive reference-style work) Christopher Bishop's Pattern Recognition and Machine Learning (a rigorous introduction that assumes much less background knowledge) David McKay's Information Theory, Inference, and Learning Algorithms (foregrounding information theory, but welcoming Bayesian methods) My point: the most widely used ML textbooks reflect the same probabilistic focus you describe in your Intro to ML course. In terms of your specific question, Zoubin Ghahramani, another influential proponent of probabilistic ML, argues that the dominant frequentist version of ML--deep learning--suffers from six limitations that explicitly probabilistic, Bayesian methods often avoid: very data hungry very compute-intensive to train and deploy poor at representing uncertainty and knowing what they don't know easily fooled by adversarial examples finicky to optimize (non-convex, choice of architecture and hyperparameters) uninterpretable black boxes, lacking transparency, difficult to trust Ghahramani elaborates on these points in many great tutorials and in this non-specialist overview article from Nature (2015) on Probabilistic Machine Learning and Artificial Intelligence. Ghahramani's article emphasizes that probabilistic methods are crucial whenever you don't have enough data. He explains (section 7) that nonparametric Bayesian models can expand to match datasets of any size with a potentially infinite number of parameters. And he notes that many datasets that may seem enormous (millions of training examples) are in fact large collections of small datasets, where probabilistic methods remain crucial to handle the uncertainties stemming from insufficient data. A similar thesis grounds Part III of the renowned book Deep Learning, where Ian Goodfellow, Yoshua Bengio, and Aaron Courville argue that "Deep Learning Research" must become probabilistic in order to become more data efficient. Because probabilistic models effectively "know what they don't know", they can help prevent terrible decisions based on unfounded extrapolations from insufficient data. As the questions we ask and the models we build become increasingly complex, the risks of insufficient data rise. And as the decisions we base upon our ML models become increasingly high-stake, the dangers associated with models that are confidently wrong (unable to pull back and say "hey, wait, I've never really seen inputs like this before") increase as well. Since both of those trends seem irreversible--ML growing in both popularity and importance--I expect probabilistic methods to become more and more widespread over time. As long as our datasets remain small relative to the complexity of our questions and to the risks of giving bad answers, we should use probabilistic models that know their own limitations. The best probabilistic models have something analogous to our human capacity to recognize feelings of confusion and disorientation (registering huge or compounding uncertainties). They can effectively warn us when they are entering uncharted territory and thereby prevent us from making potentially catastrophic decisions when they are nearing or exceeding their limits.
What is the importance of probabilistic machine learning? Contemporary machine learning, as a field, requires more familiarity with Bayesian methods and with probabilistic mathematics than does traditional statistics or even the quantitative social sciences,
11,495
Does caret train function for glmnet cross-validate for both alpha and lambda?
train does tune over both. Basically, you only need alpha when training and can get predictions across different values of lambda using predict.glmnet. Maybe a value of lambda = "all" or something else would be more informative. Max
Does caret train function for glmnet cross-validate for both alpha and lambda?
train does tune over both. Basically, you only need alpha when training and can get predictions across different values of lambda using predict.glmnet. Maybe a value of lambda = "all" or something el
Does caret train function for glmnet cross-validate for both alpha and lambda? train does tune over both. Basically, you only need alpha when training and can get predictions across different values of lambda using predict.glmnet. Maybe a value of lambda = "all" or something else would be more informative. Max
Does caret train function for glmnet cross-validate for both alpha and lambda? train does tune over both. Basically, you only need alpha when training and can get predictions across different values of lambda using predict.glmnet. Maybe a value of lambda = "all" or something el
11,496
Does caret train function for glmnet cross-validate for both alpha and lambda?
Old question, but I recently had to deal with this problem and found this question as a reference. Here is an alternative approach: The glmnet vignette (https://web.stanford.edu/~hastie/glmnet/glmnet_alpha.html) specifically addresses this issue, recommending to specify the cross validation folds using the foldids argument and validate $\lambda$ over a grid of $\alpha$. This uses the same cv folds to validate $\lambda$ for each $\alpha$ in your grid. The reason this may be superior to validating $\alpha$ and $\lambda$ simultaneously is that cv.glmnet validates $\lambda$ using a 'warm start' to select $\lambda$ rather than just randomly selecting $\lambda > 0$ i.e. speeding up validation and improving likelihood of have the optimal $\lambda$ in your grid (since fine grids are more computationally expensive).
Does caret train function for glmnet cross-validate for both alpha and lambda?
Old question, but I recently had to deal with this problem and found this question as a reference. Here is an alternative approach: The glmnet vignette (https://web.stanford.edu/~hastie/glmnet/glmne
Does caret train function for glmnet cross-validate for both alpha and lambda? Old question, but I recently had to deal with this problem and found this question as a reference. Here is an alternative approach: The glmnet vignette (https://web.stanford.edu/~hastie/glmnet/glmnet_alpha.html) specifically addresses this issue, recommending to specify the cross validation folds using the foldids argument and validate $\lambda$ over a grid of $\alpha$. This uses the same cv folds to validate $\lambda$ for each $\alpha$ in your grid. The reason this may be superior to validating $\alpha$ and $\lambda$ simultaneously is that cv.glmnet validates $\lambda$ using a 'warm start' to select $\lambda$ rather than just randomly selecting $\lambda > 0$ i.e. speeding up validation and improving likelihood of have the optimal $\lambda$ in your grid (since fine grids are more computationally expensive).
Does caret train function for glmnet cross-validate for both alpha and lambda? Old question, but I recently had to deal with this problem and found this question as a reference. Here is an alternative approach: The glmnet vignette (https://web.stanford.edu/~hastie/glmnet/glmne
11,497
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R?
You're probably getting that error because two or more of your independent variables are perfectly collinear (e.g. mis-coding dummy variables to make identical copies). Use cor() on your data or alias() on your model for closer inspection.
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R?
You're probably getting that error because two or more of your independent variables are perfectly collinear (e.g. mis-coding dummy variables to make identical copies). Use cor() on your data or alia
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R? You're probably getting that error because two or more of your independent variables are perfectly collinear (e.g. mis-coding dummy variables to make identical copies). Use cor() on your data or alias() on your model for closer inspection.
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R? You're probably getting that error because two or more of your independent variables are perfectly collinear (e.g. mis-coding dummy variables to make identical copies). Use cor() on your data or alia
11,498
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R?
Error "not defined because of singularities" will occur due to strong correlation between your independent variables. This can be avoided by having n-1 dummy variables. In your case, for Treatment variable, you should use 3 binary dummy variables (Treat1, Treat2, Treat3). In R programing, linear regression functin lm() will result in "NA" as co-efficient for highly correlated variables.
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R?
Error "not defined because of singularities" will occur due to strong correlation between your independent variables. This can be avoided by having n-1 dummy variables. In your case, for Treatment var
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R? Error "not defined because of singularities" will occur due to strong correlation between your independent variables. This can be avoided by having n-1 dummy variables. In your case, for Treatment variable, you should use 3 binary dummy variables (Treat1, Treat2, Treat3). In R programing, linear regression functin lm() will result in "NA" as co-efficient for highly correlated variables.
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R? Error "not defined because of singularities" will occur due to strong correlation between your independent variables. This can be avoided by having n-1 dummy variables. In your case, for Treatment var
11,499
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R?
In my (somewhat limited) experiece, it is most likely due to high levels of colinearity between two or more varaibles. I would suggest using the VIF function to identify which varaibles are the most significant contributors in this respect, and take this into consideration when selecting the varaibles for elimination in the next iteration of your model. In terms of interpreting VIF values, some suggest that under a value of 5 is an okay level, with a value of 5-10 acceptable in some circumstances. I usuaully don't rely on specific value thresholds too much, with the values still giving you a relative indication of issues of potenital colinearity.
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R?
In my (somewhat limited) experiece, it is most likely due to high levels of colinearity between two or more varaibles. I would suggest using the VIF function to identify which varaibles are the most s
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R? In my (somewhat limited) experiece, it is most likely due to high levels of colinearity between two or more varaibles. I would suggest using the VIF function to identify which varaibles are the most significant contributors in this respect, and take this into consideration when selecting the varaibles for elimination in the next iteration of your model. In terms of interpreting VIF values, some suggest that under a value of 5 is an okay level, with a value of 5-10 acceptable in some circumstances. I usuaully don't rely on specific value thresholds too much, with the values still giving you a relative indication of issues of potenital colinearity.
How to deal with an error such as "Coefficients: 14 not defined because of singularities" in R? In my (somewhat limited) experiece, it is most likely due to high levels of colinearity between two or more varaibles. I would suggest using the VIF function to identify which varaibles are the most s
11,500
Coefficient of Determination ($r^2$): I have never fully grasped the interpretation
Start with the basic idea of variation. Your beginning model is the sum of the squared deviations from the mean. The R^2 value is the proportion of that variation that is accounted for by using an alternative model. For example, R-squared tells you how much of the variation in Y you can get rid of by summing up the squared distances from a regression line, rather than the mean. I think this is made perfectly clear if we think about the simple regression problem plotted out. Consider a typical scatterplot where you have a predictor X along the horizontal axis and a response Y along the vertical axis. The mean is a horizontal line on the plot where Y is constant. The total variation in Y is the sum of squared differences between the mean of Y and each individual data point. It's the distance between the mean line and every individual point squared and added up. You can also calculate another measure of variability after you have the regression line from the model. This is the difference between each Y point and the regression line. Rather than each (Y - the mean) squared we get (Y - the point on the regression line) squared. If the regression line is anything but horizontal, we're going to get less total distance when we use this fitted regression line rather than the mean--that is there is less unexplained variation. The ratio between the extra variation explained and the original variation is your R^2. It's the proportion of the original variation in your response that is explained by fitting that regression line. Here is some R code for a graph with the mean, the regression line, and segments from the regression line to each point to help visualize: library(ggplot2) data(faithful) plotdata <- aggregate( eruptions ~ waiting , data = faithful, FUN = mean) linefit1 <- lm(eruptions ~ waiting, data = plotdata) plotdata$expected <- predict(linefit1) plotdata$sign <- residuals(linefit1) > 0 p <- ggplot(plotdata, aes(y=eruptions, x=waiting, xend=waiting, yend=expected) ) p + geom_point(shape = 1, size = 3) + geom_smooth(method=lm, se=FALSE) + geom_segment(aes(y=eruptions, x=waiting, xend=waiting, yend=expected, colour = sign), data = plotdata) + theme(legend.position="none") + geom_hline(yintercept = mean(plotdata$eruptions), size = 1)
Coefficient of Determination ($r^2$): I have never fully grasped the interpretation
Start with the basic idea of variation. Your beginning model is the sum of the squared deviations from the mean. The R^2 value is the proportion of that variation that is accounted for by using an a
Coefficient of Determination ($r^2$): I have never fully grasped the interpretation Start with the basic idea of variation. Your beginning model is the sum of the squared deviations from the mean. The R^2 value is the proportion of that variation that is accounted for by using an alternative model. For example, R-squared tells you how much of the variation in Y you can get rid of by summing up the squared distances from a regression line, rather than the mean. I think this is made perfectly clear if we think about the simple regression problem plotted out. Consider a typical scatterplot where you have a predictor X along the horizontal axis and a response Y along the vertical axis. The mean is a horizontal line on the plot where Y is constant. The total variation in Y is the sum of squared differences between the mean of Y and each individual data point. It's the distance between the mean line and every individual point squared and added up. You can also calculate another measure of variability after you have the regression line from the model. This is the difference between each Y point and the regression line. Rather than each (Y - the mean) squared we get (Y - the point on the regression line) squared. If the regression line is anything but horizontal, we're going to get less total distance when we use this fitted regression line rather than the mean--that is there is less unexplained variation. The ratio between the extra variation explained and the original variation is your R^2. It's the proportion of the original variation in your response that is explained by fitting that regression line. Here is some R code for a graph with the mean, the regression line, and segments from the regression line to each point to help visualize: library(ggplot2) data(faithful) plotdata <- aggregate( eruptions ~ waiting , data = faithful, FUN = mean) linefit1 <- lm(eruptions ~ waiting, data = plotdata) plotdata$expected <- predict(linefit1) plotdata$sign <- residuals(linefit1) > 0 p <- ggplot(plotdata, aes(y=eruptions, x=waiting, xend=waiting, yend=expected) ) p + geom_point(shape = 1, size = 3) + geom_smooth(method=lm, se=FALSE) + geom_segment(aes(y=eruptions, x=waiting, xend=waiting, yend=expected, colour = sign), data = plotdata) + theme(legend.position="none") + geom_hline(yintercept = mean(plotdata$eruptions), size = 1)
Coefficient of Determination ($r^2$): I have never fully grasped the interpretation Start with the basic idea of variation. Your beginning model is the sum of the squared deviations from the mean. The R^2 value is the proportion of that variation that is accounted for by using an a