idx
int64 1
56k
| question
stringlengths 15
155
| answer
stringlengths 2
29.2k
β | question_cut
stringlengths 15
100
| answer_cut
stringlengths 2
200
β | conversation
stringlengths 47
29.3k
| conversation_cut
stringlengths 47
301
|
|---|---|---|---|---|---|---|
6,201
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
|
1) Yes. You can aggregate/de-aggregate (?) binomial data from individuals with the same covariates. This comes from the fact that the sufficient statistic for a binomial model is the total number of events for each covariate vector; and the Bernoulli is just a special case of the binomial. Intuitively, each Bernoulli trial that makes up a binomial outcome is independent, so there shouldn't be a difference between counting these as a single outcome or as separate individual trials.
2) Say we have $n$ unique covariate vectors $x_1, x_2, \ldots, x_n$, each of which has a binomial outcome on $N_i$ trials, i.e.
$$Y_i \sim \mathrm{Bin}(N_i, p_i)$$
You've specified a logistic regression model, so
$$\mathrm{logit}(p_i) = \sum_{k=1}^K \beta_k x_{ik}$$
although we'll see later that this isn't important.
The log-likelihood for this model is
$$\ell(\beta; Y) = \sum_{i=1}^n \log {N_i \choose Y_i} + Y_i \log(p_i) + (N_i - Y_i) \log(1-p_i)$$
and we maximise this with respect to $\beta$ (in the $p_i$ terms) to get our parameter estimates.
Now, consider that for each $i = 1, \ldots, n$, we split the binomial outcome into $N_i$ individual Bernoulli/binary outcomes, as you have done. Specifically, create
$$Z_{i1}, \ldots, Z_{iY_i} = 1$$
$$Z_{i(Y_i+1)}, \ldots, Z_{iN_i} = 0$$
That is, the first $Y_i$ are 1s and the rest are 0s. This is exactly what you did - but you could equally have done the first $(N_i - Y_i)$ as 0s and the rest as 1s, or any other ordering, right?
Your second model says that
$$Z_{ij} \sim \mathrm{Bernoulli}(p_i)$$
with the same regression model for $p_i$ as above. The log-likelihood for this model is
$$ \ell(\beta; Z) = \sum_{i=1}^n \sum_{j=1}^{N_i} Z_{ij}\log(p_i) + (1-Z_{ij})\log(1-p_i) $$
and because of the way we defined our $Z_{ij}$s, this can be simplified to
$$ \ell(\beta; Y) = \sum_{i=1}^n Y_i \log(p_i) + (N_i - Y_i)\log(1-p_i) $$
which should look pretty familiar.
To get the estimates in the second model, we maximise this with respect to $\beta$. The only difference between this and the first log-likelihood is the term $\log {N_i \choose Y_i}$, which is constant with respect to $\beta$, and so doesn't affect the maximisation and we'll get the same estimates.
3) Each observation has a deviance residual. In the binomial model, they are
$$ D_i = 2\left[Y_i \log \left( \frac{Y_i/N_i}{\hat{p}_i} \right) + (N_i-Y_i) \log \left( \frac{1-Y_i/N_i}{1-\hat{p}_i} \right)\right] $$
where $\hat{p}_i$ is the estimated probability from your model. Note that your binomial model is saturated (0 residual degrees of freedom) and has perfect fit: $\hat{p}_i = Y_i/N_i$ for all observations, so $D_i = 0$ for all $i$.
In the Bernoulli model,
$$ D_{ij} = 2\left[Z_{ij} \log \left( \frac{Z_{ij}}{\hat{p}_i} \right) + (1-Z_{ij}) \log \left(\frac{1-Z_{ij}}{1-\hat{p}_i} \right)\right] $$
Apart from the fact that you will now have $\sum_{i=1}^n N_i$ deviance residuals (instead of $n$ as with the binomial data), these will each be either
$$D_{ij} = -2\log(\hat{p}_i)$$
or
$$D_{ij} = -2\log(1-\hat{p}_i)$$
depending on whether $Z_{ij} = 1$ or $0$, and are obviously not the same as the above. Even if you sum these over $j$ to get a sum of deviance residuals for each $i$, you don't get the same:
$$ D_i = \sum_{j=1}^{N_i} D_{ij} = 2\left[Y_i \log \left( \frac{1}{\hat{p}_i} \right) + (N_i-Y_i) \log \left( \frac{1}{1-\hat{p}_i} \right)\right] $$
The fact that the AIC is different (but the change in deviance is not) comes back to the constant term that was the difference between the log-likelihoods of the two models. When calculating the deviance, this is cancelled out because it is the same in all models based on the same data. The AIC is defined as
$$AIC = 2K - 2\ell$$
and that combinatorial term is the difference between the $\ell$s:
$$AIC_{\mathrm{Bernoulli}} - AIC_{\mathrm{Binomial}} = 2\sum_{i=1}^n \log {N_i \choose Y_i} = 9.575$$
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
|
1) Yes. You can aggregate/de-aggregate (?) binomial data from individuals with the same covariates. This comes from the fact that the sufficient statistic for a binomial model is the total number of e
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
1) Yes. You can aggregate/de-aggregate (?) binomial data from individuals with the same covariates. This comes from the fact that the sufficient statistic for a binomial model is the total number of events for each covariate vector; and the Bernoulli is just a special case of the binomial. Intuitively, each Bernoulli trial that makes up a binomial outcome is independent, so there shouldn't be a difference between counting these as a single outcome or as separate individual trials.
2) Say we have $n$ unique covariate vectors $x_1, x_2, \ldots, x_n$, each of which has a binomial outcome on $N_i$ trials, i.e.
$$Y_i \sim \mathrm{Bin}(N_i, p_i)$$
You've specified a logistic regression model, so
$$\mathrm{logit}(p_i) = \sum_{k=1}^K \beta_k x_{ik}$$
although we'll see later that this isn't important.
The log-likelihood for this model is
$$\ell(\beta; Y) = \sum_{i=1}^n \log {N_i \choose Y_i} + Y_i \log(p_i) + (N_i - Y_i) \log(1-p_i)$$
and we maximise this with respect to $\beta$ (in the $p_i$ terms) to get our parameter estimates.
Now, consider that for each $i = 1, \ldots, n$, we split the binomial outcome into $N_i$ individual Bernoulli/binary outcomes, as you have done. Specifically, create
$$Z_{i1}, \ldots, Z_{iY_i} = 1$$
$$Z_{i(Y_i+1)}, \ldots, Z_{iN_i} = 0$$
That is, the first $Y_i$ are 1s and the rest are 0s. This is exactly what you did - but you could equally have done the first $(N_i - Y_i)$ as 0s and the rest as 1s, or any other ordering, right?
Your second model says that
$$Z_{ij} \sim \mathrm{Bernoulli}(p_i)$$
with the same regression model for $p_i$ as above. The log-likelihood for this model is
$$ \ell(\beta; Z) = \sum_{i=1}^n \sum_{j=1}^{N_i} Z_{ij}\log(p_i) + (1-Z_{ij})\log(1-p_i) $$
and because of the way we defined our $Z_{ij}$s, this can be simplified to
$$ \ell(\beta; Y) = \sum_{i=1}^n Y_i \log(p_i) + (N_i - Y_i)\log(1-p_i) $$
which should look pretty familiar.
To get the estimates in the second model, we maximise this with respect to $\beta$. The only difference between this and the first log-likelihood is the term $\log {N_i \choose Y_i}$, which is constant with respect to $\beta$, and so doesn't affect the maximisation and we'll get the same estimates.
3) Each observation has a deviance residual. In the binomial model, they are
$$ D_i = 2\left[Y_i \log \left( \frac{Y_i/N_i}{\hat{p}_i} \right) + (N_i-Y_i) \log \left( \frac{1-Y_i/N_i}{1-\hat{p}_i} \right)\right] $$
where $\hat{p}_i$ is the estimated probability from your model. Note that your binomial model is saturated (0 residual degrees of freedom) and has perfect fit: $\hat{p}_i = Y_i/N_i$ for all observations, so $D_i = 0$ for all $i$.
In the Bernoulli model,
$$ D_{ij} = 2\left[Z_{ij} \log \left( \frac{Z_{ij}}{\hat{p}_i} \right) + (1-Z_{ij}) \log \left(\frac{1-Z_{ij}}{1-\hat{p}_i} \right)\right] $$
Apart from the fact that you will now have $\sum_{i=1}^n N_i$ deviance residuals (instead of $n$ as with the binomial data), these will each be either
$$D_{ij} = -2\log(\hat{p}_i)$$
or
$$D_{ij} = -2\log(1-\hat{p}_i)$$
depending on whether $Z_{ij} = 1$ or $0$, and are obviously not the same as the above. Even if you sum these over $j$ to get a sum of deviance residuals for each $i$, you don't get the same:
$$ D_i = \sum_{j=1}^{N_i} D_{ij} = 2\left[Y_i \log \left( \frac{1}{\hat{p}_i} \right) + (N_i-Y_i) \log \left( \frac{1}{1-\hat{p}_i} \right)\right] $$
The fact that the AIC is different (but the change in deviance is not) comes back to the constant term that was the difference between the log-likelihoods of the two models. When calculating the deviance, this is cancelled out because it is the same in all models based on the same data. The AIC is defined as
$$AIC = 2K - 2\ell$$
and that combinatorial term is the difference between the $\ell$s:
$$AIC_{\mathrm{Bernoulli}} - AIC_{\mathrm{Binomial}} = 2\sum_{i=1}^n \log {N_i \choose Y_i} = 9.575$$
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
1) Yes. You can aggregate/de-aggregate (?) binomial data from individuals with the same covariates. This comes from the fact that the sufficient statistic for a binomial model is the total number of e
|
6,202
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
|
I just want make comments on the last paragraph, βThe fact that the AIC is different (but the change in deviance is not) comes back to the constant term that was the difference between the log-likelihoods of the two models. When calculating the change in deviance, this is cancelled out because it is the same in all models based on the same data." Unfortunately, this is not correct for the change in deviance. The deviance does not include the constant term Ex (extra constant term in the log-likelihood for the binomial data). Therefore, the change in deviance does nothing to do with the constant term EX. The deviance compares a given model to the full model. The fact that the deviances are different from Bernoulli/binary and binomial modelling but change in deviance is not is due to the difference in the full model log-likelihood values. These values are cancelled out in calculating the deviance changes. Therefore, Bernoulli and binomial logistic regression models yield an identical deviance changes provided the predicted probabilities pij and pi are the same. In fact, that is true for the probit and other link functions.
Let lBm and lBf denote the log-likelihood values from fitting model m and full model f to Bernoulli data. The deviance is then
DB=2(lBf - lBm)=-2(lBm β lBf).
Although the lBf is zero for the binary data, we have not simplified the DB and kept it as is. The deviance from the binomial modelling with the same covariates is
Db=2(lbf+Ex β (lbm+Ex))=2(lbf β lbm) = -2(lbm β lbf)
where the lbf+Ex and lbm+Ex are the log-likelihood values by the full and m models fitted to the binomial data. The extra constant term (Ex) is disappeared from the right hand side of the Db. Now look at change in deviances from Model 1 to Model 2. From Bernoulli modelling, we have change in deviance of
DBC=DB2-DB1=2(lBf β lBm2)-2(lBf β lBm1) =2(lBm1 β lBm2).
Similarly, change in deviance from binomial fitting is
DbC=DB2-DB1=2(lbf β lbm2)-2(lbf β lbm1) =2(lbm1 β lbm2).
It is immediately follows that the deviance changes are free from the log-likelihood contributions from full models, lBf and lbf. Therefore, we will get the same change in deviance, DBC = DbC, if lBm1 = lbm1 and lBm2 = lbm2. We know that is the case here and that why we are getting the same deviance changes from Bernoulli and binomial modelling. The difference between lbf and lBf leads to the different deviances.
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
|
I just want make comments on the last paragraph, βThe fact that the AIC is different (but the change in deviance is not) comes back to the constant term that was the difference between the log-likelih
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
I just want make comments on the last paragraph, βThe fact that the AIC is different (but the change in deviance is not) comes back to the constant term that was the difference between the log-likelihoods of the two models. When calculating the change in deviance, this is cancelled out because it is the same in all models based on the same data." Unfortunately, this is not correct for the change in deviance. The deviance does not include the constant term Ex (extra constant term in the log-likelihood for the binomial data). Therefore, the change in deviance does nothing to do with the constant term EX. The deviance compares a given model to the full model. The fact that the deviances are different from Bernoulli/binary and binomial modelling but change in deviance is not is due to the difference in the full model log-likelihood values. These values are cancelled out in calculating the deviance changes. Therefore, Bernoulli and binomial logistic regression models yield an identical deviance changes provided the predicted probabilities pij and pi are the same. In fact, that is true for the probit and other link functions.
Let lBm and lBf denote the log-likelihood values from fitting model m and full model f to Bernoulli data. The deviance is then
DB=2(lBf - lBm)=-2(lBm β lBf).
Although the lBf is zero for the binary data, we have not simplified the DB and kept it as is. The deviance from the binomial modelling with the same covariates is
Db=2(lbf+Ex β (lbm+Ex))=2(lbf β lbm) = -2(lbm β lbf)
where the lbf+Ex and lbm+Ex are the log-likelihood values by the full and m models fitted to the binomial data. The extra constant term (Ex) is disappeared from the right hand side of the Db. Now look at change in deviances from Model 1 to Model 2. From Bernoulli modelling, we have change in deviance of
DBC=DB2-DB1=2(lBf β lBm2)-2(lBf β lBm1) =2(lBm1 β lBm2).
Similarly, change in deviance from binomial fitting is
DbC=DB2-DB1=2(lbf β lbm2)-2(lbf β lbm1) =2(lbm1 β lbm2).
It is immediately follows that the deviance changes are free from the log-likelihood contributions from full models, lBf and lbf. Therefore, we will get the same change in deviance, DBC = DbC, if lBm1 = lbm1 and lBm2 = lbm2. We know that is the case here and that why we are getting the same deviance changes from Bernoulli and binomial modelling. The difference between lbf and lBf leads to the different deviances.
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
I just want make comments on the last paragraph, βThe fact that the AIC is different (but the change in deviance is not) comes back to the constant term that was the difference between the log-likelih
|
6,203
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
|
The AIC are different since the response data changes. The important thing is that differences (i.e. delta) in the AIC, within models with the same response, are the same for the binomial versus Bernoulli:
binom.data <- data.frame(Successes = c(2, 3, 3), Trials = c(3, 4,
5), X1 = c("Yes", "No", "Yes"),
X2 = c(10.7, 11.3, 9.9))
summary(bi_Full <- glm(formula = cbind(Successes, Trials -
Successes) ~ X1 + X2, family = binomial,
data = binom.data))
Call:
glm(formula = cbind(Successes, Trials - Successes) ~ X1 + X2,
family = binomial, data = binom.data)
Deviance Residuals:
[1] 0 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.9649 21.6072 -0.137 0.891
X1Yes -0.1897 2.5290 -0.075 0.940
X2 0.3596 1.9094 0.188 0.851
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 2.2846e-01 on 2 degrees of freedom
Residual deviance: 4.4409e-16 on 0 degrees of freedom
AIC: 11.473
Number of Fisher Scoring iterations: 4
summary(bi_X1 <- glm(formula = cbind(Successes, Trials -
Successes) ~ X1,family = binomial, data = binom.data))
Call:
glm(formula = cbind(Successes, Trials - Successes) ~ X1,
family = binomial,
data = binom.data)
Deviance Residuals:
1 2 3
0.1503 0.0000 -0.1150
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.0986 1.1547 0.951 0.341
X1Yes -0.5878 1.3663 -0.430 0.667
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 0.22846 on 2 degrees of freedom
Residual deviance: 0.03581 on 1 degrees of freedom
AIC: 9.5087
Number of Fisher Scoring iterations: 4
AIC(bi_Full) - AIC(bi_X1)
[1] 1.96419
bern.data <- data.frame(Successes = c("Yes", "Yes", "No", "Yes",
"Yes", "Yes", "No", "Yes", "Yes", "Yes", "No", "No"), X1 =
c("Yes", "Yes", "Yes", "No", "No", "No", "No", "Yes",
"Yes", "Yes", "Yes", "Yes"), X2 = c(10.7, 10.7, 10.7,
11.3, 11.3, 11.3, 11.3, 9.9, 9.9, 9.9, 9.9, 9.9))
summary(bern_Full <- glm(formula = bern.data$Success == 'Yes' ~
X1 + X2, family = binomial, data = bern.data))
Call:
glm(formula = bern.data$Success == "Yes" ~ X1 + X2,
family = binomial,
data = bern.data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.6651 -1.3537 0.7585 0.9281 1.0108
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.9649 21.6072 -0.137 0.891
X1Yes -0.1897 2.5290 -0.075 0.940
X2 0.3596 1.9094 0.188 0.851
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 15.276 on 11 degrees of freedom
Residual deviance: 15.048 on 9 degrees of freedom
AIC: 21.048
Number of Fisher Scoring iterations: 4
summary(bern_X1 <- glm(formula = bern.data$Success == 'Yes' ~ X1,
family = binomial, data = bern.data))
Call:
glm(formula = bern.data$Success == "Yes" ~ X1, family = binomial,
data = bern.data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.6651 -1.4006 0.7585 0.9695 0.9695
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.0986 1.1547 0.951 0.341
X1Yes -0.5878 1.3663 -0.430 0.667
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 15.276 on 11 degrees of freedom
Residual deviance: 15.084 on 10 degrees of freedom
AIC: 19.084
Number of Fisher Scoring iterations: 4
AIC(bern_Full) - AIC(bern_X1)
[1] 1.96419
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
|
The AIC are different since the response data changes. The important thing is that differences (i.e. delta) in the AIC, within models with the same response, are the same for the binomial versus Berno
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
The AIC are different since the response data changes. The important thing is that differences (i.e. delta) in the AIC, within models with the same response, are the same for the binomial versus Bernoulli:
binom.data <- data.frame(Successes = c(2, 3, 3), Trials = c(3, 4,
5), X1 = c("Yes", "No", "Yes"),
X2 = c(10.7, 11.3, 9.9))
summary(bi_Full <- glm(formula = cbind(Successes, Trials -
Successes) ~ X1 + X2, family = binomial,
data = binom.data))
Call:
glm(formula = cbind(Successes, Trials - Successes) ~ X1 + X2,
family = binomial, data = binom.data)
Deviance Residuals:
[1] 0 0 0
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.9649 21.6072 -0.137 0.891
X1Yes -0.1897 2.5290 -0.075 0.940
X2 0.3596 1.9094 0.188 0.851
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 2.2846e-01 on 2 degrees of freedom
Residual deviance: 4.4409e-16 on 0 degrees of freedom
AIC: 11.473
Number of Fisher Scoring iterations: 4
summary(bi_X1 <- glm(formula = cbind(Successes, Trials -
Successes) ~ X1,family = binomial, data = binom.data))
Call:
glm(formula = cbind(Successes, Trials - Successes) ~ X1,
family = binomial,
data = binom.data)
Deviance Residuals:
1 2 3
0.1503 0.0000 -0.1150
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.0986 1.1547 0.951 0.341
X1Yes -0.5878 1.3663 -0.430 0.667
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 0.22846 on 2 degrees of freedom
Residual deviance: 0.03581 on 1 degrees of freedom
AIC: 9.5087
Number of Fisher Scoring iterations: 4
AIC(bi_Full) - AIC(bi_X1)
[1] 1.96419
bern.data <- data.frame(Successes = c("Yes", "Yes", "No", "Yes",
"Yes", "Yes", "No", "Yes", "Yes", "Yes", "No", "No"), X1 =
c("Yes", "Yes", "Yes", "No", "No", "No", "No", "Yes",
"Yes", "Yes", "Yes", "Yes"), X2 = c(10.7, 10.7, 10.7,
11.3, 11.3, 11.3, 11.3, 9.9, 9.9, 9.9, 9.9, 9.9))
summary(bern_Full <- glm(formula = bern.data$Success == 'Yes' ~
X1 + X2, family = binomial, data = bern.data))
Call:
glm(formula = bern.data$Success == "Yes" ~ X1 + X2,
family = binomial,
data = bern.data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.6651 -1.3537 0.7585 0.9281 1.0108
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -2.9649 21.6072 -0.137 0.891
X1Yes -0.1897 2.5290 -0.075 0.940
X2 0.3596 1.9094 0.188 0.851
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 15.276 on 11 degrees of freedom
Residual deviance: 15.048 on 9 degrees of freedom
AIC: 21.048
Number of Fisher Scoring iterations: 4
summary(bern_X1 <- glm(formula = bern.data$Success == 'Yes' ~ X1,
family = binomial, data = bern.data))
Call:
glm(formula = bern.data$Success == "Yes" ~ X1, family = binomial,
data = bern.data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.6651 -1.4006 0.7585 0.9695 0.9695
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 1.0986 1.1547 0.951 0.341
X1Yes -0.5878 1.3663 -0.430 0.667
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 15.276 on 11 degrees of freedom
Residual deviance: 15.084 on 10 degrees of freedom
AIC: 19.084
Number of Fisher Scoring iterations: 4
AIC(bern_Full) - AIC(bern_X1)
[1] 1.96419
|
Logistic Regression: Bernoulli vs. Binomial Response Variables
The AIC are different since the response data changes. The important thing is that differences (i.e. delta) in the AIC, within models with the same response, are the same for the binomial versus Berno
|
6,204
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Actual odds of planes crashing aside, you're falling into a logical trap here:
...each time one flies on an airplane, it does not increase the likelihood that he will die in a future airplane crash.
This is completely correct: whether you've never flown before or you've flown thousands of times, the chance of dying is still (in your example) 0.0001.
So if you're deciding between the two-hop and one-hop option, you're probably thinking about two scenarios:
Future you, transferring between the two flights. Chance of dying on next flight: 0.0001.
Future you, about to board the only flight. Chance of dying on next flight: 0.0001.
Same thing, right? Well, only if you assume you lived through the first flight in the first case. Put another way, in option 1, you're actually already dead 1/10,000th of the time.
The general issue is that you're confusing two scenarios:
your probability of being alive after $N$ flights
your probability of being alive after $N$ flights given that you were alive after $N-1$ flights.
Your chances of surviving one flight are always $1 - 0.0001$, but overall, the chances of living to the end of $N$ flights are $(1 - 0.0001)^N$
The Opposition View: I tried to keep my answer on topic by pointing out the logical issue rather than digressing into the empirical ones.
That said, in this case we may be letting the logic obscure the science. If your friend actually believes that skipping one flight will save him from a 1 in 10,000 chance of dying in a plane crash, the debate could be framed differently:
Your statement: a two-hop flight gives you a 0.0001 chance of dying
His statement: a two-hop flight gives a 0.0002 chance of dying
If this is the debate, it turns out that you are more correct. The actual odds of dying in a plane crash are about 1 in 2 million in the worst case. So you're both completely wrong, in that your estimates of airline fatalities are crazy high, but he's about twice as wrong as you are.
This 1 in 2 million figure is, of course, very rough and likely an overestimate. It's approximately correct to assume constant chances of dying per flight because (as many have pointed out) most accidents happen on takeoff and landing. If you really want the details, there's a lot more detail in another answer.
Condensed version: Your friend is right about probability theory, but given the statistics he's crazy to modify his behavior.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Actual odds of planes crashing aside, you're falling into a logical trap here:
...each time one flies on an airplane, it does not increase the likelihood that he will die in a future airplane crash.
|
Are your chances of dying in a plane crash reduced if you fly direct?
Actual odds of planes crashing aside, you're falling into a logical trap here:
...each time one flies on an airplane, it does not increase the likelihood that he will die in a future airplane crash.
This is completely correct: whether you've never flown before or you've flown thousands of times, the chance of dying is still (in your example) 0.0001.
So if you're deciding between the two-hop and one-hop option, you're probably thinking about two scenarios:
Future you, transferring between the two flights. Chance of dying on next flight: 0.0001.
Future you, about to board the only flight. Chance of dying on next flight: 0.0001.
Same thing, right? Well, only if you assume you lived through the first flight in the first case. Put another way, in option 1, you're actually already dead 1/10,000th of the time.
The general issue is that you're confusing two scenarios:
your probability of being alive after $N$ flights
your probability of being alive after $N$ flights given that you were alive after $N-1$ flights.
Your chances of surviving one flight are always $1 - 0.0001$, but overall, the chances of living to the end of $N$ flights are $(1 - 0.0001)^N$
The Opposition View: I tried to keep my answer on topic by pointing out the logical issue rather than digressing into the empirical ones.
That said, in this case we may be letting the logic obscure the science. If your friend actually believes that skipping one flight will save him from a 1 in 10,000 chance of dying in a plane crash, the debate could be framed differently:
Your statement: a two-hop flight gives you a 0.0001 chance of dying
His statement: a two-hop flight gives a 0.0002 chance of dying
If this is the debate, it turns out that you are more correct. The actual odds of dying in a plane crash are about 1 in 2 million in the worst case. So you're both completely wrong, in that your estimates of airline fatalities are crazy high, but he's about twice as wrong as you are.
This 1 in 2 million figure is, of course, very rough and likely an overestimate. It's approximately correct to assume constant chances of dying per flight because (as many have pointed out) most accidents happen on takeoff and landing. If you really want the details, there's a lot more detail in another answer.
Condensed version: Your friend is right about probability theory, but given the statistics he's crazy to modify his behavior.
|
Are your chances of dying in a plane crash reduced if you fly direct?
Actual odds of planes crashing aside, you're falling into a logical trap here:
...each time one flies on an airplane, it does not increase the likelihood that he will die in a future airplane crash.
|
6,205
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Not only do you spend more time in-flight when you have two flights to your destination, even if the layover is collinear as the crow flies (since you will interrupt cruising speed), the greatest likelihood of accidents is in take-off and landing.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Not only do you spend more time in-flight when you have two flights to your destination, even if the layover is collinear as the crow flies (since you will interrupt cruising speed), the greatest like
|
Are your chances of dying in a plane crash reduced if you fly direct?
Not only do you spend more time in-flight when you have two flights to your destination, even if the layover is collinear as the crow flies (since you will interrupt cruising speed), the greatest likelihood of accidents is in take-off and landing.
|
Are your chances of dying in a plane crash reduced if you fly direct?
Not only do you spend more time in-flight when you have two flights to your destination, even if the layover is collinear as the crow flies (since you will interrupt cruising speed), the greatest like
|
6,206
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
I'm going to answer all your questions. No, theory, all numbers.
My point was that each time one flies on an airplane, it does not
increase the likelihood that he will die in a future airplane crash.
That is, each airplane flight is independent. Whether someone has
flown on 100 planes that year or just 1, both fliers still have a 1 in
10,000 chance of dying in their next plane crash.
This might be true as a standalone fact: independence of each crash occurrence. However, it's difficult to apply to a real life.
First, he probably meant to compare a frequent flyer vs. occasional flyer. If I fly a plane a couple of times a year to go to vacation, and his work involves weekly travel across the country, you must agree that he has a higher a chance of dying in a plane crash in the next year. We're not talking about one single flight, it's a lifestyle argument, or sample size in statistics.
Second, he's probably signed up to a frequent flyer program, which means that he always flies the same airline. Hence, the probability of a plane crash is probably more correlated in his case than in mine. So, the independence assumptions that you made is much weaker than it sounded first.
So, your friend is probably right.
Another point I made: say your destination is 4 hours away. If you
take a direct flight, you will be in the air, at risk of being in a
crash, for 4 hours. Now say you take 4 different connecting flights,
each flight about an hour long. In this scenario you will still be in
the air for roughly 4 hours. Thus, whether you take the direct flight
or save some money and take connecting flights, the amount of time you
spend at risk is roughly equal.
In 4 flights your cruising time is roughly the same as in 1 long flight, but you have 4 times more take-offs and descents. According to this web site, cruising is responsible for only 16% of fatalities. This graph shows the stats. You'll have more chance of dying in 4 short flights than in 1 long.
My final point was that shorter flights have a lower rate of crashes.
I just pulled that one out of nowhere. I've done zero research and
have zero data to back that up but...it seems logical.
This is probably not true. The shorter flights are more likely to be commuter flights, and these definitely have higher rates of fatalities according to this paper:
Throughout the period 1977β1994, scheduled commuter flights had far
higher crash rates than major airlines
Here, you can find some stats too. Look at the table "Which type of flying is safer" rows with Part 135 vs. 121.
If you're taking shorter flights with major airlines (which is less likely), there's still an argument on per mile basis. Per mile, the shorter flight must have higher fatality because, as I showed earlier, because you need to takeoff and land more times per mile, and these phases are the most dangerous in terms of fatalities.
UPDATE:
@AE question on what is not onboard fatalities. See this Boeing presentation with a ton of interesting data on airline crashes, where the airline accident is defined on p.3 as:
Airplane Accident: An occurrence associated with the operation of an
airplane that takes place between the time any person boards the
airplane with the intention of flight and such time as all such
persons have disembarked
then the external fatalities are defined on p.4 as:
External fatalities include on-ground fatalities as well as fatalities
on other aircraft involved.
The onboard means that death occurred to a passenger while he/she was onboard, see also CDC's reporting guideline here.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
I'm going to answer all your questions. No, theory, all numbers.
My point was that each time one flies on an airplane, it does not
increase the likelihood that he will die in a future airplane cras
|
Are your chances of dying in a plane crash reduced if you fly direct?
I'm going to answer all your questions. No, theory, all numbers.
My point was that each time one flies on an airplane, it does not
increase the likelihood that he will die in a future airplane crash.
That is, each airplane flight is independent. Whether someone has
flown on 100 planes that year or just 1, both fliers still have a 1 in
10,000 chance of dying in their next plane crash.
This might be true as a standalone fact: independence of each crash occurrence. However, it's difficult to apply to a real life.
First, he probably meant to compare a frequent flyer vs. occasional flyer. If I fly a plane a couple of times a year to go to vacation, and his work involves weekly travel across the country, you must agree that he has a higher a chance of dying in a plane crash in the next year. We're not talking about one single flight, it's a lifestyle argument, or sample size in statistics.
Second, he's probably signed up to a frequent flyer program, which means that he always flies the same airline. Hence, the probability of a plane crash is probably more correlated in his case than in mine. So, the independence assumptions that you made is much weaker than it sounded first.
So, your friend is probably right.
Another point I made: say your destination is 4 hours away. If you
take a direct flight, you will be in the air, at risk of being in a
crash, for 4 hours. Now say you take 4 different connecting flights,
each flight about an hour long. In this scenario you will still be in
the air for roughly 4 hours. Thus, whether you take the direct flight
or save some money and take connecting flights, the amount of time you
spend at risk is roughly equal.
In 4 flights your cruising time is roughly the same as in 1 long flight, but you have 4 times more take-offs and descents. According to this web site, cruising is responsible for only 16% of fatalities. This graph shows the stats. You'll have more chance of dying in 4 short flights than in 1 long.
My final point was that shorter flights have a lower rate of crashes.
I just pulled that one out of nowhere. I've done zero research and
have zero data to back that up but...it seems logical.
This is probably not true. The shorter flights are more likely to be commuter flights, and these definitely have higher rates of fatalities according to this paper:
Throughout the period 1977β1994, scheduled commuter flights had far
higher crash rates than major airlines
Here, you can find some stats too. Look at the table "Which type of flying is safer" rows with Part 135 vs. 121.
If you're taking shorter flights with major airlines (which is less likely), there's still an argument on per mile basis. Per mile, the shorter flight must have higher fatality because, as I showed earlier, because you need to takeoff and land more times per mile, and these phases are the most dangerous in terms of fatalities.
UPDATE:
@AE question on what is not onboard fatalities. See this Boeing presentation with a ton of interesting data on airline crashes, where the airline accident is defined on p.3 as:
Airplane Accident: An occurrence associated with the operation of an
airplane that takes place between the time any person boards the
airplane with the intention of flight and such time as all such
persons have disembarked
then the external fatalities are defined on p.4 as:
External fatalities include on-ground fatalities as well as fatalities
on other aircraft involved.
The onboard means that death occurred to a passenger while he/she was onboard, see also CDC's reporting guideline here.
|
Are your chances of dying in a plane crash reduced if you fly direct?
I'm going to answer all your questions. No, theory, all numbers.
My point was that each time one flies on an airplane, it does not
increase the likelihood that he will die in a future airplane cras
|
6,207
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
He stated that he prefers to fly direct to a destination, as it decreases the probability that he will die in an airplane crash.
If your friend is genuinely concerned about this incredibly low probability then they should not be flying at all, or, for that matter, driving to the airport.
His logic was that if the probability of a commercial airline crash is 1 in 10,000, flying on two planes to get to your destination would double your chance of death.
This is correct. I propose a game. Here are your choices:
Option 1 You flip a coin. Heads I win, tails, you win.
Option 2 You flip a coin. Heads I win, tails, you flip the coin again, heads, I win, tails, you win.
Me "winning" is you dying in a plane crash, you "winning" is you survive. Option 1 is you taking a single flight, option 2 is you attempting to take two flights, but you might only end up taking one if the first one crashes.
Are the two options the same in terms of their likely outcomes, or different? Which would you pick if I gave you this game? If we were betting money on it, what would be fair odds for me to give you?
My point was that each time one flies on an airplane, it does not increase the likelihood that he will die in a future airplane crash.
Correct. Each time you fly it decreases the likelihood that you will die in a future crash because you might die in the current flight, and so there will be no future flight to die in!
That is, each airplane flight is independent. Whether someone has flown on 100 planes that year or just 1, both fliers still have a 1 in 10,000 chance of dying in their next plane crash.
Sure, but you had to survive those 100 flights.
In my game, suppose you choose option two. You flip tails. You are saying "the next one is still 50-50", but you should be saying "if I'd chosen option 1 and flipped that tails, I'd be safe now, instead of once again in danger of flipping heads". When you get off that plane having lived, you lived. Had you gotten off dead, you wouldn't be at any risk of dying on the following flight.
If you take a direct flight, you will be in the air, at risk of being in a crash, for 4 hours. Now say you take 4 different connecting flights, each flight about an hour long. In this scenario you will still be in the air for roughly 4 hours. Thus, whether you take the direct flight or save some money and take connecting flights, the amount of time you spend at risk is roughly equal.
No, that is empirically false. The vast majority of fatal commercial air disasters occur at takeoff or landing, and there is one of those per leg. Being in the air for four hours is only slightly more risky than being in the air for one, but four takeoffs are much riskier than one takeoff.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
He stated that he prefers to fly direct to a destination, as it decreases the probability that he will die in an airplane crash.
If your friend is genuinely concerned about this incredibly low proba
|
Are your chances of dying in a plane crash reduced if you fly direct?
He stated that he prefers to fly direct to a destination, as it decreases the probability that he will die in an airplane crash.
If your friend is genuinely concerned about this incredibly low probability then they should not be flying at all, or, for that matter, driving to the airport.
His logic was that if the probability of a commercial airline crash is 1 in 10,000, flying on two planes to get to your destination would double your chance of death.
This is correct. I propose a game. Here are your choices:
Option 1 You flip a coin. Heads I win, tails, you win.
Option 2 You flip a coin. Heads I win, tails, you flip the coin again, heads, I win, tails, you win.
Me "winning" is you dying in a plane crash, you "winning" is you survive. Option 1 is you taking a single flight, option 2 is you attempting to take two flights, but you might only end up taking one if the first one crashes.
Are the two options the same in terms of their likely outcomes, or different? Which would you pick if I gave you this game? If we were betting money on it, what would be fair odds for me to give you?
My point was that each time one flies on an airplane, it does not increase the likelihood that he will die in a future airplane crash.
Correct. Each time you fly it decreases the likelihood that you will die in a future crash because you might die in the current flight, and so there will be no future flight to die in!
That is, each airplane flight is independent. Whether someone has flown on 100 planes that year or just 1, both fliers still have a 1 in 10,000 chance of dying in their next plane crash.
Sure, but you had to survive those 100 flights.
In my game, suppose you choose option two. You flip tails. You are saying "the next one is still 50-50", but you should be saying "if I'd chosen option 1 and flipped that tails, I'd be safe now, instead of once again in danger of flipping heads". When you get off that plane having lived, you lived. Had you gotten off dead, you wouldn't be at any risk of dying on the following flight.
If you take a direct flight, you will be in the air, at risk of being in a crash, for 4 hours. Now say you take 4 different connecting flights, each flight about an hour long. In this scenario you will still be in the air for roughly 4 hours. Thus, whether you take the direct flight or save some money and take connecting flights, the amount of time you spend at risk is roughly equal.
No, that is empirically false. The vast majority of fatal commercial air disasters occur at takeoff or landing, and there is one of those per leg. Being in the air for four hours is only slightly more risky than being in the air for one, but four takeoffs are much riskier than one takeoff.
|
Are your chances of dying in a plane crash reduced if you fly direct?
He stated that he prefers to fly direct to a destination, as it decreases the probability that he will die in an airplane crash.
If your friend is genuinely concerned about this incredibly low proba
|
6,208
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Simple answer. You are correct in assuming the probability is the same for each flight, but when you make a connection you're effectively "rolling the dice" again.
Furthermore, it's commonly known that the most dangerous points of any flight are take off and landingβthus taking a connection exposes yourself to these risks a second time.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Simple answer. You are correct in assuming the probability is the same for each flight, but when you make a connection you're effectively "rolling the dice" again.
Furthermore, it's commonly known th
|
Are your chances of dying in a plane crash reduced if you fly direct?
Simple answer. You are correct in assuming the probability is the same for each flight, but when you make a connection you're effectively "rolling the dice" again.
Furthermore, it's commonly known that the most dangerous points of any flight are take off and landingβthus taking a connection exposes yourself to these risks a second time.
|
Are your chances of dying in a plane crash reduced if you fly direct?
Simple answer. You are correct in assuming the probability is the same for each flight, but when you make a connection you're effectively "rolling the dice" again.
Furthermore, it's commonly known th
|
6,209
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Your friend is right (on the probability theoretical side, not in in practice).
Apply your logic to throwing dice: you are saying that the chances of not throwing snake eyes once in 100 throws (i.e. surviving 100 flights) are the same as those of not throwing snake eyes in one throw (i.e. surviving one flight). If you really think that, then I'm really interested in playing dice with you.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Your friend is right (on the probability theoretical side, not in in practice).
Apply your logic to throwing dice: you are saying that the chances of not throwing snake eyes once in 100 throws (i.e.
|
Are your chances of dying in a plane crash reduced if you fly direct?
Your friend is right (on the probability theoretical side, not in in practice).
Apply your logic to throwing dice: you are saying that the chances of not throwing snake eyes once in 100 throws (i.e. surviving 100 flights) are the same as those of not throwing snake eyes in one throw (i.e. surviving one flight). If you really think that, then I'm really interested in playing dice with you.
|
Are your chances of dying in a plane crash reduced if you fly direct?
Your friend is right (on the probability theoretical side, not in in practice).
Apply your logic to throwing dice: you are saying that the chances of not throwing snake eyes once in 100 throws (i.e.
|
6,210
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Your chances of a coin flip coming up heads or tails are 50/50, on EVERY flip.
However, it is highly unlikely you would ever get a run of 10 heads in a row.
A little mathematics can be a dangerous thing :-)
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
Your chances of a coin flip coming up heads or tails are 50/50, on EVERY flip.
However, it is highly unlikely you would ever get a run of 10 heads in a row.
A little mathematics can be a dangerous thi
|
Are your chances of dying in a plane crash reduced if you fly direct?
Your chances of a coin flip coming up heads or tails are 50/50, on EVERY flip.
However, it is highly unlikely you would ever get a run of 10 heads in a row.
A little mathematics can be a dangerous thing :-)
|
Are your chances of dying in a plane crash reduced if you fly direct?
Your chances of a coin flip coming up heads or tails are 50/50, on EVERY flip.
However, it is highly unlikely you would ever get a run of 10 heads in a row.
A little mathematics can be a dangerous thi
|
6,211
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
An intuitive way of looking at this, in my opinion, is the concept of micromort (one-in-a-million probability of death).
According to Wikipedia, you'll 'accumulate' roughly one micromort due to accidents for each 1000 miles traveled and roughly one micromort due to terrorism for every 12'000 miles (in the U.S.).
This implicitly assumes that the probability of a fatal incident is proportional to the number of miles flown, independent of the number of takeoffs and landings. You'll likely get an opinion on how justified this is on https://aviation.stackexchange.com/ .
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
An intuitive way of looking at this, in my opinion, is the concept of micromort (one-in-a-million probability of death).
According to Wikipedia, you'll 'accumulate' roughly one micromort due to accide
|
Are your chances of dying in a plane crash reduced if you fly direct?
An intuitive way of looking at this, in my opinion, is the concept of micromort (one-in-a-million probability of death).
According to Wikipedia, you'll 'accumulate' roughly one micromort due to accidents for each 1000 miles traveled and roughly one micromort due to terrorism for every 12'000 miles (in the U.S.).
This implicitly assumes that the probability of a fatal incident is proportional to the number of miles flown, independent of the number of takeoffs and landings. You'll likely get an opinion on how justified this is on https://aviation.stackexchange.com/ .
|
Are your chances of dying in a plane crash reduced if you fly direct?
An intuitive way of looking at this, in my opinion, is the concept of micromort (one-in-a-million probability of death).
According to Wikipedia, you'll 'accumulate' roughly one micromort due to accide
|
6,212
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
I believe that you and your friend have missed one important variable. That is are the chances of dying in a plane crash disproportionately concentrated in the takeoff and landing. Off the top of my head, I believe the answer is yes.
Your friend's argument is, if you fly direct for 1000 miles, versus flying two flights for 500 miles each, you've flown the same 1000 miles in each case, and therefore your chances of dying are comparable.
Your version (of my argument) would be something like "if you fly direct, you've taken off and landed once, whereas the other way, you've taken off and landed twice." If my premise (about take off and landing) is correct, the second way is almost twice as dangerous as the first. And even if my premise is wrong, that's the question you should ask.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
I believe that you and your friend have missed one important variable. That is are the chances of dying in a plane crash disproportionately concentrated in the takeoff and landing. Off the top of my h
|
Are your chances of dying in a plane crash reduced if you fly direct?
I believe that you and your friend have missed one important variable. That is are the chances of dying in a plane crash disproportionately concentrated in the takeoff and landing. Off the top of my head, I believe the answer is yes.
Your friend's argument is, if you fly direct for 1000 miles, versus flying two flights for 500 miles each, you've flown the same 1000 miles in each case, and therefore your chances of dying are comparable.
Your version (of my argument) would be something like "if you fly direct, you've taken off and landed once, whereas the other way, you've taken off and landed twice." If my premise (about take off and landing) is correct, the second way is almost twice as dangerous as the first. And even if my premise is wrong, that's the question you should ask.
|
Are your chances of dying in a plane crash reduced if you fly direct?
I believe that you and your friend have missed one important variable. That is are the chances of dying in a plane crash disproportionately concentrated in the takeoff and landing. Off the top of my h
|
6,213
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
You have to ask yourself what this βprobability of dying in plane crashβ represents and how it applies to your problem (or not).
Look at it this way:
If you never fly at all, your chances to die in a plane crash are going to be much lower (but not nil, cf. El Al Flight 1862 or Air France Flight 4590).
If you fly every day for most of your life, your chances to die in a plane crash are obviously higher than if you don't.
It seems to me that there is plausible model of how plane crash deaths happen that make them completely unrelated to being in an airplane.
Consequently, I would guess that this 1 in 10,000 figure does not quite mean what you think it means. Maybe it's an average based on comparing deaths in plane crash to other causes of death or it's a reasonable estimate of the risk based on a typical βflying profileβ in your country but it can't possibly be exactly the same for people with widely different plane-taking behaviour.
The difference between one flight and two flights might be tiny and your scenario also invites thinking about the difference between one flight (one take-off/one landing) and time spent in the air but if you do accept that people who never fly have a lower risk of dying in a plane crash than people who fly constantly, you can't assume than the probably of dying in a plane crash in completely independent from the number of flights you take.
|
Are your chances of dying in a plane crash reduced if you fly direct?
|
You have to ask yourself what this βprobability of dying in plane crashβ represents and how it applies to your problem (or not).
Look at it this way:
If you never fly at all, your chances to die in a
|
Are your chances of dying in a plane crash reduced if you fly direct?
You have to ask yourself what this βprobability of dying in plane crashβ represents and how it applies to your problem (or not).
Look at it this way:
If you never fly at all, your chances to die in a plane crash are going to be much lower (but not nil, cf. El Al Flight 1862 or Air France Flight 4590).
If you fly every day for most of your life, your chances to die in a plane crash are obviously higher than if you don't.
It seems to me that there is plausible model of how plane crash deaths happen that make them completely unrelated to being in an airplane.
Consequently, I would guess that this 1 in 10,000 figure does not quite mean what you think it means. Maybe it's an average based on comparing deaths in plane crash to other causes of death or it's a reasonable estimate of the risk based on a typical βflying profileβ in your country but it can't possibly be exactly the same for people with widely different plane-taking behaviour.
The difference between one flight and two flights might be tiny and your scenario also invites thinking about the difference between one flight (one take-off/one landing) and time spent in the air but if you do accept that people who never fly have a lower risk of dying in a plane crash than people who fly constantly, you can't assume than the probably of dying in a plane crash in completely independent from the number of flights you take.
|
Are your chances of dying in a plane crash reduced if you fly direct?
You have to ask yourself what this βprobability of dying in plane crashβ represents and how it applies to your problem (or not).
Look at it this way:
If you never fly at all, your chances to die in a
|
6,214
|
Computing p-value using bootstrap with R
|
You are using bootstrap to generate data under the empirical distribution of the observed data. This can be useful to give a confidence interval on the difference between the two means:
> quantile(b3$t,c(0.025,0.975))
2.5% 97.5%
0.4166667 5.5833333
To get a $p$-value, you need to generate permutations under the null hypothesis. This can be done eg like this:
diff2 = function(d1,i){
d = d1;
d$group <- d$group[i]; # randomly re-assign groups
Mean= tapply(X=d$time, INDEX=d$group, mean)
Diff = Mean[1]-Mean[2]
Diff
}
> set.seed(1234)
> b4 = boot(data = sleep, statistic = diff2, R = 5000)
> mean(abs(b4$t) > abs(b4$t0))
[1] 0.046
In this solution, the size of groups is not fixed, you randomly reassign a group to each individual by bootstraping from the initial group set. It seems legit to me, however a more classical solution is to fix the number of individuals of each group, so you just permute the groups instead of bootstraping (this is usually motivated by the design of the experiment, where the group sizes are fixed beforehand):
> R <- 10000; d <- sleep
> b5 <- numeric(R); for(i in 1:R) {
+ d$group <- sample(d$group, length(d$group));
+ b5[i] <- mean(d$time[d$group==1])-mean(d$time[d$group==2]);
+ }
> mean(abs(b5) > 3)
[1] 0.0372
|
Computing p-value using bootstrap with R
|
You are using bootstrap to generate data under the empirical distribution of the observed data. This can be useful to give a confidence interval on the difference between the two means:
> quantile(b3$
|
Computing p-value using bootstrap with R
You are using bootstrap to generate data under the empirical distribution of the observed data. This can be useful to give a confidence interval on the difference between the two means:
> quantile(b3$t,c(0.025,0.975))
2.5% 97.5%
0.4166667 5.5833333
To get a $p$-value, you need to generate permutations under the null hypothesis. This can be done eg like this:
diff2 = function(d1,i){
d = d1;
d$group <- d$group[i]; # randomly re-assign groups
Mean= tapply(X=d$time, INDEX=d$group, mean)
Diff = Mean[1]-Mean[2]
Diff
}
> set.seed(1234)
> b4 = boot(data = sleep, statistic = diff2, R = 5000)
> mean(abs(b4$t) > abs(b4$t0))
[1] 0.046
In this solution, the size of groups is not fixed, you randomly reassign a group to each individual by bootstraping from the initial group set. It seems legit to me, however a more classical solution is to fix the number of individuals of each group, so you just permute the groups instead of bootstraping (this is usually motivated by the design of the experiment, where the group sizes are fixed beforehand):
> R <- 10000; d <- sleep
> b5 <- numeric(R); for(i in 1:R) {
+ d$group <- sample(d$group, length(d$group));
+ b5[i] <- mean(d$time[d$group==1])-mean(d$time[d$group==2]);
+ }
> mean(abs(b5) > 3)
[1] 0.0372
|
Computing p-value using bootstrap with R
You are using bootstrap to generate data under the empirical distribution of the observed data. This can be useful to give a confidence interval on the difference between the two means:
> quantile(b3$
|
6,215
|
Computing p-value using bootstrap with R
|
There are numerous ways of calculating bootstrap CIs and p-values. The main issue is that it is impossible for the bootstrap to generate data under a null hypothesis. The permutation test is a viable resampling based alternative to this. To use a proper bootstrap you must make some assumptions about the sampling distribution of the test statistic.
A comment about lack of invariance of testing: it is entirely possible to find 95% CIs not inclusive of the null yet a p > 0.05 or vice versa. To have better agreement, the calculation of bootstrap samples under the null must be dope as $\beta^*_0 = \hat{\beta} - \hat{\beta}^*$ rather than $\beta^*_0 = \hat{\beta}^* - \hat{\beta} $. That is to say if the density is skewed right in the bootstrap sample, the density must be skewed left in the null. It is not really possible to invert tests for CIs with non-analytical (e.g. resampling) solutions such as this.
normal bootstrap
One approach is a normal bootstrap where you take the mean and standard deviation of the bootstrap distribution, calculate the sampling distribution under the null by shifting the distribution and using the normal percentiles from the null distribution at the point of the estimate in the original bootstrap sample. This is a reasonable approach when the bootstrap distribution is normal, visual inspection usually suffices here. Results using this approach are usually very close to robust, or sandwich based error estimation which is robust against heteroscedasticity and/or finite sample variance assumptions. The assumption of a normal test statistic is a stronger condition of the assumptions in the next bootstrap test I will discuss.
percentile bootstrap
Another approach is the percentile bootstrap which is what I think most of us consider when we speak of the bootstrap. Here, the bootstrapped distribution of parameter estimates an empirical distribution of the sample under the alternative hypothesis. This distribution can possibly be non-normal. A 95% CI is easily calculated by taking the empirical quantiles. But one important assumption is that such a distribution is pivotal. This means that if the underlying parameter changes, the shape of the distribution is only shifted by a constant, and the scale does not necessarily change. This is a strong assumption! If this holds, you can generate the "distribution of the statistic under the null hypothesis" (DSNH or $\mathcal{F}_0^*$) by subtracting the bootstrap distribution from the estimates, then calculating what percentage of the DSNH is "more extreme" than your estimate by using $2 \times \min (\mathcal{F}_0^*(\hat{\beta}), 1-\mathcal{F}_0^*(\hat{\beta}))$
Studentized bootstrap
The easiest bootstrap solution to calculating $p$-values is to use a studentized bootstrap. With each bootstrap iteration, calculate the statistic and its standard error and return the student statistic. This gives a bootstrapped student distribution for the hypothesis which can be used to calculate cis and p-values very easily. This also underlies the intuition behind the bias-corrected-accelerated bootstrap. The t-distribution shifts much more easily under the null since outlying results are downweighted by their corresponding high variance.
Programming example
As an example, I'll use the city data in the bootstrap package. The bootstrap confidence intervals are calculated with this code:
ratio <- function(d, w) sum(d$x * w)/sum(d$u * w)
city.boot <- boot(city, ratio, R = 999, stype = "w", sim = "ordinary")
boot.ci(city.boot, conf = c(0.90, 0.95),
type = c("norm", "basic", "perc", "bca"))
and produce this output:
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 999 bootstrap replicates
CALL :
boot.ci(boot.out = city.boot, conf = c(0.9, 0.95), type = c("norm",
"basic", "perc", "bca"))
Intervals :
Level Normal Basic
90% ( 1.111, 1.837 ) ( 1.030, 1.750 )
95% ( 1.042, 1.906 ) ( 0.895, 1.790 )
Level Percentile BCa
90% ( 1.291, 2.011 ) ( 1.292, 2.023 )
95% ( 1.251, 2.146 ) ( 1.255, 2.155 )
Calculations and Intervals on Original Scale
The 95% CI for the normal bootstrap is obtained by calculating:
with(city.boot, 2*t0 - mean(t) + qnorm(c(0.025, 0.975)) %o% sqrt(var(t)[1,1]))
The p-value is thus obtained:
> with(city.boot, pnorm(abs((2*t0 - mean(t) - 1) / sqrt(var(t)[1,1])), lower.tail=F)*2)
[1] 0.0315
Which agrees that the 95% normal CI does not include the null ratio value of 1.
The percentile CI is obtained (with some differences due to methods for ties):
quantile(city.boot$t, c(0.025, 0.975))
And the p-value for the percentile bootstrap is:
cvs <- quantile(city.boot$t0 - city.boot$t + 1, c(0.025, 0.975))
mean(city.boot$t > cvs[1] & city.boot$t < cvs[2])
Gives a p of 0.035 which also agrees with the confidence interval in terms of the exclusion of 1 from the value. We cannot in general observe that, while the width of the percentile CI is nearly as wide as the normal CI and that the percentile CI is further from the null that the percentile CI should provide lower p-values. This is because the shape of the sampling distribution underlying the CI for the percentile method is non-normal.
|
Computing p-value using bootstrap with R
|
There are numerous ways of calculating bootstrap CIs and p-values. The main issue is that it is impossible for the bootstrap to generate data under a null hypothesis. The permutation test is a viable
|
Computing p-value using bootstrap with R
There are numerous ways of calculating bootstrap CIs and p-values. The main issue is that it is impossible for the bootstrap to generate data under a null hypothesis. The permutation test is a viable resampling based alternative to this. To use a proper bootstrap you must make some assumptions about the sampling distribution of the test statistic.
A comment about lack of invariance of testing: it is entirely possible to find 95% CIs not inclusive of the null yet a p > 0.05 or vice versa. To have better agreement, the calculation of bootstrap samples under the null must be dope as $\beta^*_0 = \hat{\beta} - \hat{\beta}^*$ rather than $\beta^*_0 = \hat{\beta}^* - \hat{\beta} $. That is to say if the density is skewed right in the bootstrap sample, the density must be skewed left in the null. It is not really possible to invert tests for CIs with non-analytical (e.g. resampling) solutions such as this.
normal bootstrap
One approach is a normal bootstrap where you take the mean and standard deviation of the bootstrap distribution, calculate the sampling distribution under the null by shifting the distribution and using the normal percentiles from the null distribution at the point of the estimate in the original bootstrap sample. This is a reasonable approach when the bootstrap distribution is normal, visual inspection usually suffices here. Results using this approach are usually very close to robust, or sandwich based error estimation which is robust against heteroscedasticity and/or finite sample variance assumptions. The assumption of a normal test statistic is a stronger condition of the assumptions in the next bootstrap test I will discuss.
percentile bootstrap
Another approach is the percentile bootstrap which is what I think most of us consider when we speak of the bootstrap. Here, the bootstrapped distribution of parameter estimates an empirical distribution of the sample under the alternative hypothesis. This distribution can possibly be non-normal. A 95% CI is easily calculated by taking the empirical quantiles. But one important assumption is that such a distribution is pivotal. This means that if the underlying parameter changes, the shape of the distribution is only shifted by a constant, and the scale does not necessarily change. This is a strong assumption! If this holds, you can generate the "distribution of the statistic under the null hypothesis" (DSNH or $\mathcal{F}_0^*$) by subtracting the bootstrap distribution from the estimates, then calculating what percentage of the DSNH is "more extreme" than your estimate by using $2 \times \min (\mathcal{F}_0^*(\hat{\beta}), 1-\mathcal{F}_0^*(\hat{\beta}))$
Studentized bootstrap
The easiest bootstrap solution to calculating $p$-values is to use a studentized bootstrap. With each bootstrap iteration, calculate the statistic and its standard error and return the student statistic. This gives a bootstrapped student distribution for the hypothesis which can be used to calculate cis and p-values very easily. This also underlies the intuition behind the bias-corrected-accelerated bootstrap. The t-distribution shifts much more easily under the null since outlying results are downweighted by their corresponding high variance.
Programming example
As an example, I'll use the city data in the bootstrap package. The bootstrap confidence intervals are calculated with this code:
ratio <- function(d, w) sum(d$x * w)/sum(d$u * w)
city.boot <- boot(city, ratio, R = 999, stype = "w", sim = "ordinary")
boot.ci(city.boot, conf = c(0.90, 0.95),
type = c("norm", "basic", "perc", "bca"))
and produce this output:
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 999 bootstrap replicates
CALL :
boot.ci(boot.out = city.boot, conf = c(0.9, 0.95), type = c("norm",
"basic", "perc", "bca"))
Intervals :
Level Normal Basic
90% ( 1.111, 1.837 ) ( 1.030, 1.750 )
95% ( 1.042, 1.906 ) ( 0.895, 1.790 )
Level Percentile BCa
90% ( 1.291, 2.011 ) ( 1.292, 2.023 )
95% ( 1.251, 2.146 ) ( 1.255, 2.155 )
Calculations and Intervals on Original Scale
The 95% CI for the normal bootstrap is obtained by calculating:
with(city.boot, 2*t0 - mean(t) + qnorm(c(0.025, 0.975)) %o% sqrt(var(t)[1,1]))
The p-value is thus obtained:
> with(city.boot, pnorm(abs((2*t0 - mean(t) - 1) / sqrt(var(t)[1,1])), lower.tail=F)*2)
[1] 0.0315
Which agrees that the 95% normal CI does not include the null ratio value of 1.
The percentile CI is obtained (with some differences due to methods for ties):
quantile(city.boot$t, c(0.025, 0.975))
And the p-value for the percentile bootstrap is:
cvs <- quantile(city.boot$t0 - city.boot$t + 1, c(0.025, 0.975))
mean(city.boot$t > cvs[1] & city.boot$t < cvs[2])
Gives a p of 0.035 which also agrees with the confidence interval in terms of the exclusion of 1 from the value. We cannot in general observe that, while the width of the percentile CI is nearly as wide as the normal CI and that the percentile CI is further from the null that the percentile CI should provide lower p-values. This is because the shape of the sampling distribution underlying the CI for the percentile method is non-normal.
|
Computing p-value using bootstrap with R
There are numerous ways of calculating bootstrap CIs and p-values. The main issue is that it is impossible for the bootstrap to generate data under a null hypothesis. The permutation test is a viable
|
6,216
|
Computing p-value using bootstrap with R
|
The answer of Elvis relies on permutations but in my opinion it does not make clear what is wrong with the original bootstrap approach. Let me discuss a solution based solely on bootstrap.
The crucial problem of your original simulation is that bootstrap always provides you with the TRUE distribution of the test statistic. However, when computing the p-value you have to compare the obtained value of the test statistic to its distribution UNDER H0, i.e. not with the true distribution!
[Let's make it clear. For example, it is known that the test statistic T of the classical t-test has the classical "central" t-distribution under H0 and a noncentral distribution in general. However, everyone is familiar with the fact that the observed value of T is compared to the classical "central" t-distribution, i.e. one does not try to obtain the true [noncenral] t-distribution to make the comparison with T.]
Your p-value 0.4804 is so large, because the observed value "t0" of the test statistic Mean[1]-Mean[2] lies very close to the centre of the bootstrapped sample "t". It is natural and typically it is always so [i.e. irrespective of the validity of H0], because the bootstrapped sample "t" emulates the the ACTUAL distribution of Mean[1]-Mean[2]. But, as noted above [and also by Elvis], what you really need is the distribution of Mean[1]-Mean[2] UNDER H0. It is obvious that
under H0 the distribution of Mean[1]-Mean[2] will be centered around 0,
its shape does not depend on the validity of H0.
These two points imply that the distribution of Mean[1]-Mean[2] under H0 can be emulated by the bootstrapped sample "t" SHIFTED so that it is centered around 0. In R:
b3.under.H0 <- b3$t - mean(b3$t)
and the corresponding p-value will be:
mean(abs(b3.under.H0) > abs(b3$t0))
which gives you a "very nice" value of 0.0232. :-)
Let me note that the the point "2)" mentioned above is called "translation equivariance" of the test statistic and it does NOT have to hold in general! I.e. for some test statistics, shifting of the bootstrapped "t" does not provide you with a valid estimate of the distribution of the test statistic under HO! Have a look at this discussion and especially at the reply of P. Dalgaard.
Your testing problem does yields a perfectly symmetric distribution of the test statistic, but keep in mind that there are some problems with obtaining TWO-SIDED p-values in case of skewed bootstrapped distribution of the test statistic. Again, read the above link.
[And finally, I would use the "pure" permutation test in your situation; i.e. the second half of Elvis answer. :-)]
|
Computing p-value using bootstrap with R
|
The answer of Elvis relies on permutations but in my opinion it does not make clear what is wrong with the original bootstrap approach. Let me discuss a solution based solely on bootstrap.
The crucial
|
Computing p-value using bootstrap with R
The answer of Elvis relies on permutations but in my opinion it does not make clear what is wrong with the original bootstrap approach. Let me discuss a solution based solely on bootstrap.
The crucial problem of your original simulation is that bootstrap always provides you with the TRUE distribution of the test statistic. However, when computing the p-value you have to compare the obtained value of the test statistic to its distribution UNDER H0, i.e. not with the true distribution!
[Let's make it clear. For example, it is known that the test statistic T of the classical t-test has the classical "central" t-distribution under H0 and a noncentral distribution in general. However, everyone is familiar with the fact that the observed value of T is compared to the classical "central" t-distribution, i.e. one does not try to obtain the true [noncenral] t-distribution to make the comparison with T.]
Your p-value 0.4804 is so large, because the observed value "t0" of the test statistic Mean[1]-Mean[2] lies very close to the centre of the bootstrapped sample "t". It is natural and typically it is always so [i.e. irrespective of the validity of H0], because the bootstrapped sample "t" emulates the the ACTUAL distribution of Mean[1]-Mean[2]. But, as noted above [and also by Elvis], what you really need is the distribution of Mean[1]-Mean[2] UNDER H0. It is obvious that
under H0 the distribution of Mean[1]-Mean[2] will be centered around 0,
its shape does not depend on the validity of H0.
These two points imply that the distribution of Mean[1]-Mean[2] under H0 can be emulated by the bootstrapped sample "t" SHIFTED so that it is centered around 0. In R:
b3.under.H0 <- b3$t - mean(b3$t)
and the corresponding p-value will be:
mean(abs(b3.under.H0) > abs(b3$t0))
which gives you a "very nice" value of 0.0232. :-)
Let me note that the the point "2)" mentioned above is called "translation equivariance" of the test statistic and it does NOT have to hold in general! I.e. for some test statistics, shifting of the bootstrapped "t" does not provide you with a valid estimate of the distribution of the test statistic under HO! Have a look at this discussion and especially at the reply of P. Dalgaard.
Your testing problem does yields a perfectly symmetric distribution of the test statistic, but keep in mind that there are some problems with obtaining TWO-SIDED p-values in case of skewed bootstrapped distribution of the test statistic. Again, read the above link.
[And finally, I would use the "pure" permutation test in your situation; i.e. the second half of Elvis answer. :-)]
|
Computing p-value using bootstrap with R
The answer of Elvis relies on permutations but in my opinion it does not make clear what is wrong with the original bootstrap approach. Let me discuss a solution based solely on bootstrap.
The crucial
|
6,217
|
How to derive the least square estimator for multiple linear regression?
|
The derivation in matrix notation
Starting from $y= Xb +\epsilon $, which really is just the same as
$\begin{bmatrix}
y_{1} \\
y_{2} \\
\vdots \\
y_{N}
\end{bmatrix}
=
\begin{bmatrix}
x_{11} & x_{12} & \cdots & x_{1K} \\
x_{21} & x_{22} & \cdots & x_{2K} \\
\vdots & \ddots & \ddots & \vdots \\
x_{N1} & x_{N2} & \cdots & x_{NK}
\end{bmatrix}
*
\begin{bmatrix}
b_{1} \\
b_{2} \\
\vdots \\
b_{K}
\end{bmatrix}
+
\begin{bmatrix}
\epsilon_{1} \\
\epsilon_{2} \\
\vdots \\
\epsilon_{N}
\end{bmatrix} $
it all comes down to minimzing $e'e$:
$\epsilon'\epsilon = \begin{bmatrix}
e_{1} & e_{2} & \cdots & e_{N} \\
\end{bmatrix}
\begin{bmatrix}
e_{1} \\
e_{2} \\
\vdots \\
e_{N}
\end{bmatrix} = \sum_{i=1}^{N}e_{i}^{2}
$
So minimizing $e'e'$ gives us:
$min_{b}$ $e'e = (y-Xb)'(y-Xb)$
$min_{b}$ $e'e = y'y - 2b'X'y + b'X'Xb$
$\frac{\partial(e'e)}{\partial b} = -2X'y + 2X'Xb \stackrel{!}{=} 0$
$X'Xb=X'y$
$b=(X'X)^{-1}X'y$
One last mathematical thing, the second order condition for a minimum requires that the matrix $X'X$ is positive definite. This requirement is fulfilled in case $X$ has full rank.
The more accurate derivation which goes trough all the steps in greater dept can be found under http://economictheoryblog.com/2015/02/19/ols_estimator/
|
How to derive the least square estimator for multiple linear regression?
|
The derivation in matrix notation
Starting from $y= Xb +\epsilon $, which really is just the same as
$\begin{bmatrix}
y_{1} \\
y_{2} \\
\vdots \\
y_{N}
\end{bmatrix}
=
\begin{bmatrix}
x_{11} & x_{12}
|
How to derive the least square estimator for multiple linear regression?
The derivation in matrix notation
Starting from $y= Xb +\epsilon $, which really is just the same as
$\begin{bmatrix}
y_{1} \\
y_{2} \\
\vdots \\
y_{N}
\end{bmatrix}
=
\begin{bmatrix}
x_{11} & x_{12} & \cdots & x_{1K} \\
x_{21} & x_{22} & \cdots & x_{2K} \\
\vdots & \ddots & \ddots & \vdots \\
x_{N1} & x_{N2} & \cdots & x_{NK}
\end{bmatrix}
*
\begin{bmatrix}
b_{1} \\
b_{2} \\
\vdots \\
b_{K}
\end{bmatrix}
+
\begin{bmatrix}
\epsilon_{1} \\
\epsilon_{2} \\
\vdots \\
\epsilon_{N}
\end{bmatrix} $
it all comes down to minimzing $e'e$:
$\epsilon'\epsilon = \begin{bmatrix}
e_{1} & e_{2} & \cdots & e_{N} \\
\end{bmatrix}
\begin{bmatrix}
e_{1} \\
e_{2} \\
\vdots \\
e_{N}
\end{bmatrix} = \sum_{i=1}^{N}e_{i}^{2}
$
So minimizing $e'e'$ gives us:
$min_{b}$ $e'e = (y-Xb)'(y-Xb)$
$min_{b}$ $e'e = y'y - 2b'X'y + b'X'Xb$
$\frac{\partial(e'e)}{\partial b} = -2X'y + 2X'Xb \stackrel{!}{=} 0$
$X'Xb=X'y$
$b=(X'X)^{-1}X'y$
One last mathematical thing, the second order condition for a minimum requires that the matrix $X'X$ is positive definite. This requirement is fulfilled in case $X$ has full rank.
The more accurate derivation which goes trough all the steps in greater dept can be found under http://economictheoryblog.com/2015/02/19/ols_estimator/
|
How to derive the least square estimator for multiple linear regression?
The derivation in matrix notation
Starting from $y= Xb +\epsilon $, which really is just the same as
$\begin{bmatrix}
y_{1} \\
y_{2} \\
\vdots \\
y_{N}
\end{bmatrix}
=
\begin{bmatrix}
x_{11} & x_{12}
|
6,218
|
How to derive the least square estimator for multiple linear regression?
|
It is possible to estimate just one coefficient in a multiple regression without estimating the others.
The estimate of $\beta_1$ is obtained by removing the effects of $x_2$ from the other variables and then regressing the residuals of $y$ against the residuals of $x_1$. This is explained and illustrated How exactly does one control for other variables? and How to normalize (a) regression coefficient?. The beauty of this approach is that it requires no calculus, no linear algebra, can be visualized using just two-dimensional geometry, is numerically stable, and exploits just one fundamental idea of multiple regression: that of taking out (or "controlling for") the effects of a single variable.
In the present case the multiple regression can be done using three ordinary regression steps:
Regress $y$ on $x_2$ (without a constant term!). Let the fit be $y = \alpha_{y,2}x_2 + \delta$. The estimate is $$\alpha_{y,2} = \frac{\sum_i y_i x_{2i}}{\sum_i x_{2i}^2}.$$ Therefore the residuals are $$\delta = y - \alpha_{y,2}x_2.$$ Geometrically, $\delta$ is what is left of $y$ after its projection onto $x_2$ is subtracted.
Regress $x_1$ on $x_2$ (without a constant term). Let the fit be $x_1 = \alpha_{1,2}x_2 + \gamma$. The estimate is $$\alpha_{1,2} = \frac{\sum_i x_{1i} x_{2i}}{\sum_i x_{2i}^2}.$$ The residuals are $$\gamma = x_1 - \alpha_{1,2}x_2.$$ Geometrically, $\gamma$ is what is left of $x_1$ after its projection onto $x_2$ is subtracted.
Regress $\delta$ on $\gamma$ (without a constant term). The estimate is $$\hat\beta_1 = \frac{\sum_i \delta_i \gamma_i}{\sum_i \gamma_i^2}.$$ The fit will be $\delta = \hat\beta_1 \gamma + \varepsilon$. Geometrically, $\hat\beta_1$ is the component of $\delta$ (which represents $y$ with $x_2$ taken out) in the $\gamma$ direction (which represents $x_1$ with $x_2$ taken out).
Notice that $\beta_2$ has not been estimated. It easily can be recovered from what has been obtained so far (just as $\hat\beta_0$ in the ordinary regression case is easily obtained from the slope estimate $\hat\beta_1$). The $\varepsilon$ are the residuals for the bivariate regression of $y$ on $x_1$ and $x_2$.
The parallel with ordinary regression is strong: steps (1) and (2) are analogs of subtracting the means in the usual formula. If you let $x_2$ be a vector of ones, you will in fact recover the usual formula.
This generalizes in the obvious way to regression with more than two variables: to estimate $\hat\beta_1$, regress $y$ and $x_1$ separately against all the other variables, then regress their residuals against each other. At that point none of the other coefficients in the multiple regression of $y$ have yet been estimated.
|
How to derive the least square estimator for multiple linear regression?
|
It is possible to estimate just one coefficient in a multiple regression without estimating the others.
The estimate of $\beta_1$ is obtained by removing the effects of $x_2$ from the other variables
|
How to derive the least square estimator for multiple linear regression?
It is possible to estimate just one coefficient in a multiple regression without estimating the others.
The estimate of $\beta_1$ is obtained by removing the effects of $x_2$ from the other variables and then regressing the residuals of $y$ against the residuals of $x_1$. This is explained and illustrated How exactly does one control for other variables? and How to normalize (a) regression coefficient?. The beauty of this approach is that it requires no calculus, no linear algebra, can be visualized using just two-dimensional geometry, is numerically stable, and exploits just one fundamental idea of multiple regression: that of taking out (or "controlling for") the effects of a single variable.
In the present case the multiple regression can be done using three ordinary regression steps:
Regress $y$ on $x_2$ (without a constant term!). Let the fit be $y = \alpha_{y,2}x_2 + \delta$. The estimate is $$\alpha_{y,2} = \frac{\sum_i y_i x_{2i}}{\sum_i x_{2i}^2}.$$ Therefore the residuals are $$\delta = y - \alpha_{y,2}x_2.$$ Geometrically, $\delta$ is what is left of $y$ after its projection onto $x_2$ is subtracted.
Regress $x_1$ on $x_2$ (without a constant term). Let the fit be $x_1 = \alpha_{1,2}x_2 + \gamma$. The estimate is $$\alpha_{1,2} = \frac{\sum_i x_{1i} x_{2i}}{\sum_i x_{2i}^2}.$$ The residuals are $$\gamma = x_1 - \alpha_{1,2}x_2.$$ Geometrically, $\gamma$ is what is left of $x_1$ after its projection onto $x_2$ is subtracted.
Regress $\delta$ on $\gamma$ (without a constant term). The estimate is $$\hat\beta_1 = \frac{\sum_i \delta_i \gamma_i}{\sum_i \gamma_i^2}.$$ The fit will be $\delta = \hat\beta_1 \gamma + \varepsilon$. Geometrically, $\hat\beta_1$ is the component of $\delta$ (which represents $y$ with $x_2$ taken out) in the $\gamma$ direction (which represents $x_1$ with $x_2$ taken out).
Notice that $\beta_2$ has not been estimated. It easily can be recovered from what has been obtained so far (just as $\hat\beta_0$ in the ordinary regression case is easily obtained from the slope estimate $\hat\beta_1$). The $\varepsilon$ are the residuals for the bivariate regression of $y$ on $x_1$ and $x_2$.
The parallel with ordinary regression is strong: steps (1) and (2) are analogs of subtracting the means in the usual formula. If you let $x_2$ be a vector of ones, you will in fact recover the usual formula.
This generalizes in the obvious way to regression with more than two variables: to estimate $\hat\beta_1$, regress $y$ and $x_1$ separately against all the other variables, then regress their residuals against each other. At that point none of the other coefficients in the multiple regression of $y$ have yet been estimated.
|
How to derive the least square estimator for multiple linear regression?
It is possible to estimate just one coefficient in a multiple regression without estimating the others.
The estimate of $\beta_1$ is obtained by removing the effects of $x_2$ from the other variables
|
6,219
|
How to derive the least square estimator for multiple linear regression?
|
The ordinary least squares estimate of $\beta$ is a linear function of the response variable. Simply put, the OLS estimate of the coefficients, the $\beta$'s, can be written using only the dependent variable ($Y_i$'s) and the independent variables ($X_{ki}$'s).
To explain this fact for a general regression model, you need to understand a little linear algebra. Suppose you would like to estimate the coefficients $(\beta_0, \beta_1, ...,\beta_k)$ in a multiple regression model,
$$
Y_i = \beta_0+\beta_1X_{1i}+...+\beta_kX_{ki}+\epsilon_i
$$
where $\epsilon_i \overset{iid}{\sim} N(0,\sigma^2)$ for $i=1,...,n$. The design matrix $\mathbf{X}$ is a $n\times k$ matrix where each column contains the $n$ observations of the $k^{th}$ dependent variable $X_k$. You can find many explanations and derivations here of the formula used to calculate the estimated coefficients $\boldsymbol{\hat{\beta}}=(\hat{\beta}_0, \hat{\beta}_1, ..., \hat{\beta}_k)$, which is
$$
\boldsymbol{\hat{\beta}}=(\mathbf{X}^\prime \mathbf{X})^{-1}\mathbf{X}^\prime \mathbf{Y}
$$
assuming that the inverse $(\mathbf{X}^\prime \mathbf{X})^{-1}$ exists. The estimated coefficients are functions of the data, not of the other estimated coefficients.
|
How to derive the least square estimator for multiple linear regression?
|
The ordinary least squares estimate of $\beta$ is a linear function of the response variable. Simply put, the OLS estimate of the coefficients, the $\beta$'s, can be written using only the dependent v
|
How to derive the least square estimator for multiple linear regression?
The ordinary least squares estimate of $\beta$ is a linear function of the response variable. Simply put, the OLS estimate of the coefficients, the $\beta$'s, can be written using only the dependent variable ($Y_i$'s) and the independent variables ($X_{ki}$'s).
To explain this fact for a general regression model, you need to understand a little linear algebra. Suppose you would like to estimate the coefficients $(\beta_0, \beta_1, ...,\beta_k)$ in a multiple regression model,
$$
Y_i = \beta_0+\beta_1X_{1i}+...+\beta_kX_{ki}+\epsilon_i
$$
where $\epsilon_i \overset{iid}{\sim} N(0,\sigma^2)$ for $i=1,...,n$. The design matrix $\mathbf{X}$ is a $n\times k$ matrix where each column contains the $n$ observations of the $k^{th}$ dependent variable $X_k$. You can find many explanations and derivations here of the formula used to calculate the estimated coefficients $\boldsymbol{\hat{\beta}}=(\hat{\beta}_0, \hat{\beta}_1, ..., \hat{\beta}_k)$, which is
$$
\boldsymbol{\hat{\beta}}=(\mathbf{X}^\prime \mathbf{X})^{-1}\mathbf{X}^\prime \mathbf{Y}
$$
assuming that the inverse $(\mathbf{X}^\prime \mathbf{X})^{-1}$ exists. The estimated coefficients are functions of the data, not of the other estimated coefficients.
|
How to derive the least square estimator for multiple linear regression?
The ordinary least squares estimate of $\beta$ is a linear function of the response variable. Simply put, the OLS estimate of the coefficients, the $\beta$'s, can be written using only the dependent v
|
6,220
|
How to derive the least square estimator for multiple linear regression?
|
One small minor note on theory vs. practice. Mathematically $\beta_0, \beta_1, \beta_2 ... \beta_n$ can be estimated with the following formula:
$$ \hat{\beta} = (X'X)^{-1} X'Y$$
where $X$ is the original input data and $Y$ is the variable that we want to estimate. This follows from minimizing the error. I will proove this before making a small practical point.
Let $e_i$ be the error the linear regression makes at point $i$. Then:
$$ e_i = y_i - \hat{y_i} $$
The total squared error we make is now:
$$ \sum_{i=1}^n e_i^2 = \sum_{i=1}^n (y_i - \hat{y_i})^2$$
Because we have a linear model we know that:
$$ \hat{y_i} = \beta_0 + \beta_1 x_{1,i} + \beta_2 x_{2,i} + ... + \beta_n x_{n,i} $$
Which can be rewritten in matrix notation as:
$$ \hat{Y} = X\beta $$
We know that
$$ \sum_{i=1}^n e_i^2 = E'E $$
We want to minimize the total square error, such that the following expression should be as small as possible
$$ E'E = (Y-\hat{Y})' (Y-\hat{Y}) $$
This is equal to:
$$ E'E = (Y-X\beta)' (Y-X\beta)$$
The rewriting might seem confusing but it follows from linear algebra. Notice that the matrices behave similar to variables when we are multiplying them in some regards.
We want to find the values of $\beta$ such that this expression is as small as possible. We will need to differentiate and set the derivative equal to zero. We use the chain rule here.
$$ \frac{dE'E}{d\beta} = - 2 X'Y + 2 X'X\beta = 0$$
This gives:
$$ X'X\beta = X'Y $$
Such that finally:
$$ \beta = (X'X)^{-1} X'Y $$
So mathematically we seem to have found a solution. There is one problem though, and that is that $(X'X)^{-1}$ is very hard to calculate if the matrix $X$ is very very large. This might give numerical accuracy issues. Another way to find the optimal values for $\beta$ in this situation is to use a gradient descent type of method. The function that we want to optimize is unbounded and convex so we would also use a gradient method in practice if need be.
|
How to derive the least square estimator for multiple linear regression?
|
One small minor note on theory vs. practice. Mathematically $\beta_0, \beta_1, \beta_2 ... \beta_n$ can be estimated with the following formula:
$$ \hat{\beta} = (X'X)^{-1} X'Y$$
where $X$ is the ori
|
How to derive the least square estimator for multiple linear regression?
One small minor note on theory vs. practice. Mathematically $\beta_0, \beta_1, \beta_2 ... \beta_n$ can be estimated with the following formula:
$$ \hat{\beta} = (X'X)^{-1} X'Y$$
where $X$ is the original input data and $Y$ is the variable that we want to estimate. This follows from minimizing the error. I will proove this before making a small practical point.
Let $e_i$ be the error the linear regression makes at point $i$. Then:
$$ e_i = y_i - \hat{y_i} $$
The total squared error we make is now:
$$ \sum_{i=1}^n e_i^2 = \sum_{i=1}^n (y_i - \hat{y_i})^2$$
Because we have a linear model we know that:
$$ \hat{y_i} = \beta_0 + \beta_1 x_{1,i} + \beta_2 x_{2,i} + ... + \beta_n x_{n,i} $$
Which can be rewritten in matrix notation as:
$$ \hat{Y} = X\beta $$
We know that
$$ \sum_{i=1}^n e_i^2 = E'E $$
We want to minimize the total square error, such that the following expression should be as small as possible
$$ E'E = (Y-\hat{Y})' (Y-\hat{Y}) $$
This is equal to:
$$ E'E = (Y-X\beta)' (Y-X\beta)$$
The rewriting might seem confusing but it follows from linear algebra. Notice that the matrices behave similar to variables when we are multiplying them in some regards.
We want to find the values of $\beta$ such that this expression is as small as possible. We will need to differentiate and set the derivative equal to zero. We use the chain rule here.
$$ \frac{dE'E}{d\beta} = - 2 X'Y + 2 X'X\beta = 0$$
This gives:
$$ X'X\beta = X'Y $$
Such that finally:
$$ \beta = (X'X)^{-1} X'Y $$
So mathematically we seem to have found a solution. There is one problem though, and that is that $(X'X)^{-1}$ is very hard to calculate if the matrix $X$ is very very large. This might give numerical accuracy issues. Another way to find the optimal values for $\beta$ in this situation is to use a gradient descent type of method. The function that we want to optimize is unbounded and convex so we would also use a gradient method in practice if need be.
|
How to derive the least square estimator for multiple linear regression?
One small minor note on theory vs. practice. Mathematically $\beta_0, \beta_1, \beta_2 ... \beta_n$ can be estimated with the following formula:
$$ \hat{\beta} = (X'X)^{-1} X'Y$$
where $X$ is the ori
|
6,221
|
How to derive the least square estimator for multiple linear regression?
|
A simple derivation can be done just by using the geometric interpretation of LR.
Linear regression can be interpreted as the projection of $Y$ onto the column space $X$. Thus, the error, $\hat{\epsilon}$ is orthogonal to the column space of $X$.
Therefore, the inner product between $X'$ and the error must be 0, i.e.,
$<X', y-X\hat{\beta}> = 0$
$X'y - X'X\hat{\beta} = 0$
$X'y = X'X\hat{\beta}$
Which implies that,
$(X'X)^{-1}X'y = \hat{\beta}$.
Now the same can be done by:
(1) Projecting $Y$ onto $X_2$ (error $\delta = Y-X_2 \hat{D}$), $\hat{D} = (X_2'X_2)^{-1}X_2'y$,
(2) Projecting $X_1$ onto $X_2$ (error $\gamma = X_1 - X_2 \hat{G}$), $\hat{G} = (X_2'X_2)^{-1}X_2X_1$,
and finally,
(3) Projecting $\delta$ onto $\gamma$, $\hat{\beta}_1$
|
How to derive the least square estimator for multiple linear regression?
|
A simple derivation can be done just by using the geometric interpretation of LR.
Linear regression can be interpreted as the projection of $Y$ onto the column space $X$. Thus, the error, $\hat{\epsi
|
How to derive the least square estimator for multiple linear regression?
A simple derivation can be done just by using the geometric interpretation of LR.
Linear regression can be interpreted as the projection of $Y$ onto the column space $X$. Thus, the error, $\hat{\epsilon}$ is orthogonal to the column space of $X$.
Therefore, the inner product between $X'$ and the error must be 0, i.e.,
$<X', y-X\hat{\beta}> = 0$
$X'y - X'X\hat{\beta} = 0$
$X'y = X'X\hat{\beta}$
Which implies that,
$(X'X)^{-1}X'y = \hat{\beta}$.
Now the same can be done by:
(1) Projecting $Y$ onto $X_2$ (error $\delta = Y-X_2 \hat{D}$), $\hat{D} = (X_2'X_2)^{-1}X_2'y$,
(2) Projecting $X_1$ onto $X_2$ (error $\gamma = X_1 - X_2 \hat{G}$), $\hat{G} = (X_2'X_2)^{-1}X_2X_1$,
and finally,
(3) Projecting $\delta$ onto $\gamma$, $\hat{\beta}_1$
|
How to derive the least square estimator for multiple linear regression?
A simple derivation can be done just by using the geometric interpretation of LR.
Linear regression can be interpreted as the projection of $Y$ onto the column space $X$. Thus, the error, $\hat{\epsi
|
6,222
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
|
I'm not sure that multicollinearity is what's going on here. It certainly could be, but from the information given I can't conclude that, and I don't want to start there. My first guess is that this might be a multiple comparisons issue. That is, if you run enough tests, something will show up, even if there's nothing there.
One of the issues that I harp on is that the problem of multiple comparisons is always discussed in terms of examining many pairwise comparisonsβe.g., running t-tests on every unique pairing of levels. (For a humorous treatment of multiple comparisons, look here.) This leaves people with the impression that that is the only place this problem shows up. But this is simply not trueβthe problem of multiple comparisons shows up everywhere. For instance, if you run a regression with 4 explanatory variables, the same issues exist. In a well-designed experiment, IV's can be orthogonal, but people routinely worry about using Bonferroni corrections on sets of a-priori, orthogonal contrasts, and don't think twice about factorial ANOVA's. To my mind this is inconsistent.
The global F test is what's called a 'simultaneous' test. This checks to see if all of your predictors are unrelated to the response variable. The simultaneous test provides some protection against the problem of multiple comparisons without having to go the power-losing Bonferroni route. Unfortunately, my interpretation of what you report is that you have a null finding.
Several things mitigate against this interpretation. First, with only 43 data, you almost certainly don't have much power. It's quite possible that there is a real effect, but you just can't resolve it without more data. Second, like both @andrea and @Dimitriy, I worry about the appropriateness of treating 4-level categorical variables as numeric. This may well not be appropriate, and could have any number of effects, including diminishing your ability to detect what is really there. Lastly, I'm not sure that significance testing is quite as important as people believe. A $p$ of $.11$ is kind of low; is there really something going on there? maybe! who knows?βthere's no 'bright line' at .05 that demarcates real effects from mere appearance.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
|
I'm not sure that multicollinearity is what's going on here. It certainly could be, but from the information given I can't conclude that, and I don't want to start there. My first guess is that this
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
I'm not sure that multicollinearity is what's going on here. It certainly could be, but from the information given I can't conclude that, and I don't want to start there. My first guess is that this might be a multiple comparisons issue. That is, if you run enough tests, something will show up, even if there's nothing there.
One of the issues that I harp on is that the problem of multiple comparisons is always discussed in terms of examining many pairwise comparisonsβe.g., running t-tests on every unique pairing of levels. (For a humorous treatment of multiple comparisons, look here.) This leaves people with the impression that that is the only place this problem shows up. But this is simply not trueβthe problem of multiple comparisons shows up everywhere. For instance, if you run a regression with 4 explanatory variables, the same issues exist. In a well-designed experiment, IV's can be orthogonal, but people routinely worry about using Bonferroni corrections on sets of a-priori, orthogonal contrasts, and don't think twice about factorial ANOVA's. To my mind this is inconsistent.
The global F test is what's called a 'simultaneous' test. This checks to see if all of your predictors are unrelated to the response variable. The simultaneous test provides some protection against the problem of multiple comparisons without having to go the power-losing Bonferroni route. Unfortunately, my interpretation of what you report is that you have a null finding.
Several things mitigate against this interpretation. First, with only 43 data, you almost certainly don't have much power. It's quite possible that there is a real effect, but you just can't resolve it without more data. Second, like both @andrea and @Dimitriy, I worry about the appropriateness of treating 4-level categorical variables as numeric. This may well not be appropriate, and could have any number of effects, including diminishing your ability to detect what is really there. Lastly, I'm not sure that significance testing is quite as important as people believe. A $p$ of $.11$ is kind of low; is there really something going on there? maybe! who knows?βthere's no 'bright line' at .05 that demarcates real effects from mere appearance.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
I'm not sure that multicollinearity is what's going on here. It certainly could be, but from the information given I can't conclude that, and I don't want to start there. My first guess is that this
|
6,223
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
|
I would like to suggest that this phenomenon (of a non-significant overall test despite a significant individual variable) can be understood as a kind of aggregate "masking effect" and that although it conceivably could arise from multicollinear explanatory variables, it need not do that at all. It also turns out not to be due to multiple comparison adjustments, either. Thus this answer is adding some qualifications to the answers that have already appeared, which on the contrary suggest that either multicollinearity or multiple comparisons should be looked at as the culprits.
To establish the plausibility of these assertions, let's generate a collection of perfectly orthogonal variables--just as non-collinear as possible--and a dependent variable that explicitly is determined solely by the first of the explanands (plus a good amount of random error independent of everything else). In R this can be done (reproducibly, if you wish to experiment) as
set.seed(17)
p <- 5 # Number of explanatory variables
x <- as.matrix(do.call(expand.grid, lapply(as.list(1:p), function(i) c(-1,1))))
y <- x[,1] + rnorm(2^p, mean=0, sd=2)
It's unimportant that the explanatory variables are binary; what matters is their orthogonality, which we can check to make sure the code is working as expected, which can be done by inspecting their correlations. Indeed, the correlation matrix is interesting: the small coefficients suggest y has little to do with any of the variables except the first (which is by design) and the off-diagonal zeros confirm the orthogonality of the explanatory variables:
> cor(cbind(x,y))
Var1 Var2 Var3 Var4 Var5 y
Var1 1.00 0.000 0.000 0.000 0.00 0.486
Var2 0.00 1.000 0.000 0.000 0.00 0.088
Var3 0.00 0.000 1.000 0.000 0.00 0.044
Var4 0.00 0.000 0.000 1.000 0.00 -0.014
Var5 0.00 0.000 0.000 0.000 1.00 -0.167
y 0.49 0.088 0.044 -0.014 -0.17 1.000
Let's run a series of regressions, using only the first variable, then the first two, and so on. For brevity and easy comparison, in each one I show only the line for the first variable and the overall F-test:
>temp <- sapply(1:p, function(i) print(summary(lm(y ~ x[, 1:i]))))
# Estimate Std. Error t value Pr(>|t|)
1 x[, 1:i] 0.898 0.294 3.05 0.0048 **
F-statistic: 9.29 on 1 and 30 DF, p-value: 0.00478
2 x[, 1:i]Var1 0.898 0.298 3.01 0.0053 **
F-statistic: 4.68 on 2 and 29 DF, p-value: 0.0173
3 x[, 1:i]Var1 0.8975 0.3029 2.96 0.0062 **
F-statistic: 3.05 on 3 and 28 DF, p-value: 0.0451
4 x[, 1:i]Var1 0.8975 0.3084 2.91 0.0072 **
F-statistic: 2.21 on 4 and 27 DF, p-value: 0.095
5 x[, 1:i]Var1 0.8975 0.3084 2.91 0.0073 **
F-statistic: 1.96 on 5 and 26 DF, p-value: 0.118
Look at how (a) the significance of the first variable barely changes, (a') the first variable remains significant (p < .05) even when adjusting for multiple comparisons (e.g., apply Bonferroni by multiplying the nominal p-value by the number of explanatory variables), (b) the coefficient of the first variable barely changes, but (c) the overall significance grows exponentially, quickly inflating to a non-significant level.
I interpret this as demonstrating that including explanatory variables that are largely independent of the dependent variable can "mask" the overall p-value of the regression. When the new variables are orthogonal to existing ones and to the dependent variable, they will not change the individual p-values. (The small changes seen here are because the random error added to y is, by accident, slightly correlated with all the other variables.) One lesson to draw from this is that parsimony is valuable: using as few variables as needed can strengthen the significance of the results.
I am not saying that this is necessarily happening for the dataset in the question, about which little has been disclosed. But knowledge that this masking effect can happen should inform our interpretation of the results as well as our strategies for variable selection and model building.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
|
I would like to suggest that this phenomenon (of a non-significant overall test despite a significant individual variable) can be understood as a kind of aggregate "masking effect" and that although i
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
I would like to suggest that this phenomenon (of a non-significant overall test despite a significant individual variable) can be understood as a kind of aggregate "masking effect" and that although it conceivably could arise from multicollinear explanatory variables, it need not do that at all. It also turns out not to be due to multiple comparison adjustments, either. Thus this answer is adding some qualifications to the answers that have already appeared, which on the contrary suggest that either multicollinearity or multiple comparisons should be looked at as the culprits.
To establish the plausibility of these assertions, let's generate a collection of perfectly orthogonal variables--just as non-collinear as possible--and a dependent variable that explicitly is determined solely by the first of the explanands (plus a good amount of random error independent of everything else). In R this can be done (reproducibly, if you wish to experiment) as
set.seed(17)
p <- 5 # Number of explanatory variables
x <- as.matrix(do.call(expand.grid, lapply(as.list(1:p), function(i) c(-1,1))))
y <- x[,1] + rnorm(2^p, mean=0, sd=2)
It's unimportant that the explanatory variables are binary; what matters is their orthogonality, which we can check to make sure the code is working as expected, which can be done by inspecting their correlations. Indeed, the correlation matrix is interesting: the small coefficients suggest y has little to do with any of the variables except the first (which is by design) and the off-diagonal zeros confirm the orthogonality of the explanatory variables:
> cor(cbind(x,y))
Var1 Var2 Var3 Var4 Var5 y
Var1 1.00 0.000 0.000 0.000 0.00 0.486
Var2 0.00 1.000 0.000 0.000 0.00 0.088
Var3 0.00 0.000 1.000 0.000 0.00 0.044
Var4 0.00 0.000 0.000 1.000 0.00 -0.014
Var5 0.00 0.000 0.000 0.000 1.00 -0.167
y 0.49 0.088 0.044 -0.014 -0.17 1.000
Let's run a series of regressions, using only the first variable, then the first two, and so on. For brevity and easy comparison, in each one I show only the line for the first variable and the overall F-test:
>temp <- sapply(1:p, function(i) print(summary(lm(y ~ x[, 1:i]))))
# Estimate Std. Error t value Pr(>|t|)
1 x[, 1:i] 0.898 0.294 3.05 0.0048 **
F-statistic: 9.29 on 1 and 30 DF, p-value: 0.00478
2 x[, 1:i]Var1 0.898 0.298 3.01 0.0053 **
F-statistic: 4.68 on 2 and 29 DF, p-value: 0.0173
3 x[, 1:i]Var1 0.8975 0.3029 2.96 0.0062 **
F-statistic: 3.05 on 3 and 28 DF, p-value: 0.0451
4 x[, 1:i]Var1 0.8975 0.3084 2.91 0.0072 **
F-statistic: 2.21 on 4 and 27 DF, p-value: 0.095
5 x[, 1:i]Var1 0.8975 0.3084 2.91 0.0073 **
F-statistic: 1.96 on 5 and 26 DF, p-value: 0.118
Look at how (a) the significance of the first variable barely changes, (a') the first variable remains significant (p < .05) even when adjusting for multiple comparisons (e.g., apply Bonferroni by multiplying the nominal p-value by the number of explanatory variables), (b) the coefficient of the first variable barely changes, but (c) the overall significance grows exponentially, quickly inflating to a non-significant level.
I interpret this as demonstrating that including explanatory variables that are largely independent of the dependent variable can "mask" the overall p-value of the regression. When the new variables are orthogonal to existing ones and to the dependent variable, they will not change the individual p-values. (The small changes seen here are because the random error added to y is, by accident, slightly correlated with all the other variables.) One lesson to draw from this is that parsimony is valuable: using as few variables as needed can strengthen the significance of the results.
I am not saying that this is necessarily happening for the dataset in the question, about which little has been disclosed. But knowledge that this masking effect can happen should inform our interpretation of the results as well as our strategies for variable selection and model building.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
I would like to suggest that this phenomenon (of a non-significant overall test despite a significant individual variable) can be understood as a kind of aggregate "masking effect" and that although i
|
6,224
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
|
You frequently have this happen when you have a high degree of collinearity among your explanatory variables. The ANOVA F is a joint test that all the regressors are jointly uninformative. When your Xs contain similar information, the model cannot attribute the explanatory power to one regressor or another, but their combination can explain much of the variation in the response variable.
Also, the fact that you seem to be treating you categorical variables as if they were continuous may be problematic. You are explicitly imposing restrictions like bumping $x_{1}$ from 1 to 2 has the same effect on $y$ as bumping it from 3 to 4. Sometime's that's OK, but often it's not.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
|
You frequently have this happen when you have a high degree of collinearity among your explanatory variables. The ANOVA F is a joint test that all the regressors are jointly uninformative. When your X
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
You frequently have this happen when you have a high degree of collinearity among your explanatory variables. The ANOVA F is a joint test that all the regressors are jointly uninformative. When your Xs contain similar information, the model cannot attribute the explanatory power to one regressor or another, but their combination can explain much of the variation in the response variable.
Also, the fact that you seem to be treating you categorical variables as if they were continuous may be problematic. You are explicitly imposing restrictions like bumping $x_{1}$ from 1 to 2 has the same effect on $y$ as bumping it from 3 to 4. Sometime's that's OK, but often it's not.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
You frequently have this happen when you have a high degree of collinearity among your explanatory variables. The ANOVA F is a joint test that all the regressors are jointly uninformative. When your X
|
6,225
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
|
The example in whuber's answer is very to the point (+1), to which I want to elaborate the rationale behind it from the theoretical perspective. For a better exposition, suppose the number of regressors is $2$ and the number of observations is $n$, so the model can be written as:
\begin{align}
y_i = \beta_0 + \beta_1X_{1, i} + \beta_2X_{2, i} + \epsilon_i, \quad
i = 1, 2, \ldots, n.
\end{align}
Further suppose the relation among $y = (y_1, \ldots, y_n)$, $X_1 = (X_{1,1}, \ldots, X_{1, n})$, $X_2 = (X_{2, 1}, \ldots, X_{2, n})$ is as set up by whuber: $X_1$ and $X_2$ are orthogonal, $y$ and $X_1$ are highly correlated, $y$ and $X_2$ are (almost) uncorrelated. We are interested in testing
The single $\beta_1$ is $0$:
\begin{align}
H_0: \beta_1 = 0 \text{ v.s. } H_1: \beta_1 \neq 0. \tag{1}
\end{align}
All $\beta$s are 0:
\begin{align}
H_0: \beta_1 = \beta_2 = 0 \text{ v.s. } H_1: \beta_1 \neq 0 \text{ or }
\beta_2 \neq 0. \tag{2}
\end{align}
It is well-known that the testing procedures applying to problem $(1)$ and $(2)$ are $t$-test and $F$-test respectively. However, the key to explain the posed paradox is recognizing the $t$-test to problem $(1)$ can also be viewed as an equivalent $F$-test, so that we are actually applying the partial $F$-test to problem $(1)$ and the overall $F$-test to problem $(2)$ respectively (a good reference to this is Applied Linear Statistical Models, Section 7.3 by Kutner et al.), whose testing statistics are
\begin{align}
F^{(1)} = \frac{MSR(X_1|X_2)}{MSE} = \frac{SSR(X_1, X_2) - SSR(X_2)}{MSE} \tag{3}
\end{align}
and
\begin{align}
F^{(2)} = \frac{MSR(X_1, X_2)}{MSE} = \frac{SSR(X_1, X_2)}{2MSE} \tag{4}
\end{align}
respectively. At the significance level $\alpha$, $F^{(1)}$ and $F^{(2)}$ are compared with critical points (($1 - \alpha$)-$F$-quantiles) $q_1^* = F_{1, n - 3}(1 - \alpha)$ and $q_2^*= F_{2, n - 3}(1 - \alpha)$ respectively to determine whether $H_0$ should be rejected.
Under this specific setting, it is clear that $SSR(X_2) \approx 0$, which implies that $F^{(1)}$ is approximately $2$ times of $F^{(2)}$, however, the ratio of $q_1^*$ and $q_2^*$ is less than $2$, making the null hypothesis in $(1)$ is more likely to be rejected than the null hypothesis in $(2)$: for example, if $F^{(1)}$ is slightly greater than $q_1^*$, hence the null hypothesis in $(1)$ is (barely) rejected, then $F^{(2)} \approx 0.5F^{(1)}$ is slightly greater than $0.5q_1^*$, which will be less than $q_2^*$, as it is supposed to be considerably greater than $0.5q_1^*$. Hence the null hypothesis in $(2)$ cannot be rejected at the same significance level $\alpha$.
Now let's replicate whuber's example to illustrate the above point. As can be read from the output below, $F^{(1)} = 3.012^2 = 9.072 > q_1^* = 7.597663$, $F^{(2)} = 4.684 < q_2^* = 5.420445$, hence at $\alpha = 0.01$, $H_0$ in $(1)$ is rejected but in $(2)$ is not rejected. The reason is that the ratio of $F^{(1)}$ and $F^{(2)}$ is $F^{(1)}/F^{(2)} = 1.94$, which is considerably greater than the ratio of cutoff points $q_1^*/q_2^* = 1.40$.
> set.seed(17)
> p <- 5 # Number of explanatory variables
> x <- as.matrix(do.call(expand.grid, lapply(as.list(1:p), function(i) c(-1,1))))
> y <- x[,1] + rnorm(2^p, mean=0, sd=2)
> X <- as.data.frame(x)
>
> m <- lm(y ~ Var1 + Var2, X)
> summary(m)
Call:
lm(formula = y ~ Var1 + Var2, data = X)
Residuals:
Min 1Q Median 3Q Max
-3.13861 -1.34150 0.09369 1.10478 2.85457
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.5185 0.2980 1.740 0.09244 .
Var1 0.8975 0.2980 3.012 0.00534 **
Var2 0.1624 0.2980 0.545 0.58982
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
Residual standard error: 1.686 on 29 degrees of freedom
Multiple R-squared: 0.2442, Adjusted R-squared: 0.192
F-statistic: 4.684 on 2 and 29 DF, p-value: 0.01726
> qf(0.99, 1, 29)
[1] 7.597663
>
> qf(0.99, 2, 29)
[1] 5.420445
To illustrate the "insignificance of overall $F$-test inflation" effect as the number of regressors $p$, consider the same scenario as above but now $p$ ranges from $2$ to $29$ (the penultimate maximum number of regressors that $F$-test works fine).
q1 <- qf(0.99, 1, 29:2)
q2 <- qf(0.99, 2:29, 29:2)
F1 <- q1 + 0.5 # This simulates the case that t-test barely rejects H0.
F2 <- F1/(2:29) # F2 is approximately 1/p of F1 by setting.
plot(2:29, q2, xlab = "# of predictors", ylab = "")
points(2:29, q1, pch = 2)
lines(2:29, F1)
lines(2:29, F2, lty = "dashed")
legend("topleft",
c("t-test threshold (q1)",
"F-test threshold (q2)",
"t-test stat (F1)",
"F-test stat (F2)"),
pch = c(2, 1, NA, NA),
lty = c(NA, NA, "solid", "dashed"))
The graph is as follows. It can be seen that the dashed line is always below thresholds (hence $F$-tests are always insignificant), and as $p$ increases, the gap between the dots and the dashed line also increases, indicating that the $F$-test becomes more insignificant.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
|
The example in whuber's answer is very to the point (+1), to which I want to elaborate the rationale behind it from the theoretical perspective. For a better exposition, suppose the number of regress
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-significant overall F-statistic
The example in whuber's answer is very to the point (+1), to which I want to elaborate the rationale behind it from the theoretical perspective. For a better exposition, suppose the number of regressors is $2$ and the number of observations is $n$, so the model can be written as:
\begin{align}
y_i = \beta_0 + \beta_1X_{1, i} + \beta_2X_{2, i} + \epsilon_i, \quad
i = 1, 2, \ldots, n.
\end{align}
Further suppose the relation among $y = (y_1, \ldots, y_n)$, $X_1 = (X_{1,1}, \ldots, X_{1, n})$, $X_2 = (X_{2, 1}, \ldots, X_{2, n})$ is as set up by whuber: $X_1$ and $X_2$ are orthogonal, $y$ and $X_1$ are highly correlated, $y$ and $X_2$ are (almost) uncorrelated. We are interested in testing
The single $\beta_1$ is $0$:
\begin{align}
H_0: \beta_1 = 0 \text{ v.s. } H_1: \beta_1 \neq 0. \tag{1}
\end{align}
All $\beta$s are 0:
\begin{align}
H_0: \beta_1 = \beta_2 = 0 \text{ v.s. } H_1: \beta_1 \neq 0 \text{ or }
\beta_2 \neq 0. \tag{2}
\end{align}
It is well-known that the testing procedures applying to problem $(1)$ and $(2)$ are $t$-test and $F$-test respectively. However, the key to explain the posed paradox is recognizing the $t$-test to problem $(1)$ can also be viewed as an equivalent $F$-test, so that we are actually applying the partial $F$-test to problem $(1)$ and the overall $F$-test to problem $(2)$ respectively (a good reference to this is Applied Linear Statistical Models, Section 7.3 by Kutner et al.), whose testing statistics are
\begin{align}
F^{(1)} = \frac{MSR(X_1|X_2)}{MSE} = \frac{SSR(X_1, X_2) - SSR(X_2)}{MSE} \tag{3}
\end{align}
and
\begin{align}
F^{(2)} = \frac{MSR(X_1, X_2)}{MSE} = \frac{SSR(X_1, X_2)}{2MSE} \tag{4}
\end{align}
respectively. At the significance level $\alpha$, $F^{(1)}$ and $F^{(2)}$ are compared with critical points (($1 - \alpha$)-$F$-quantiles) $q_1^* = F_{1, n - 3}(1 - \alpha)$ and $q_2^*= F_{2, n - 3}(1 - \alpha)$ respectively to determine whether $H_0$ should be rejected.
Under this specific setting, it is clear that $SSR(X_2) \approx 0$, which implies that $F^{(1)}$ is approximately $2$ times of $F^{(2)}$, however, the ratio of $q_1^*$ and $q_2^*$ is less than $2$, making the null hypothesis in $(1)$ is more likely to be rejected than the null hypothesis in $(2)$: for example, if $F^{(1)}$ is slightly greater than $q_1^*$, hence the null hypothesis in $(1)$ is (barely) rejected, then $F^{(2)} \approx 0.5F^{(1)}$ is slightly greater than $0.5q_1^*$, which will be less than $q_2^*$, as it is supposed to be considerably greater than $0.5q_1^*$. Hence the null hypothesis in $(2)$ cannot be rejected at the same significance level $\alpha$.
Now let's replicate whuber's example to illustrate the above point. As can be read from the output below, $F^{(1)} = 3.012^2 = 9.072 > q_1^* = 7.597663$, $F^{(2)} = 4.684 < q_2^* = 5.420445$, hence at $\alpha = 0.01$, $H_0$ in $(1)$ is rejected but in $(2)$ is not rejected. The reason is that the ratio of $F^{(1)}$ and $F^{(2)}$ is $F^{(1)}/F^{(2)} = 1.94$, which is considerably greater than the ratio of cutoff points $q_1^*/q_2^* = 1.40$.
> set.seed(17)
> p <- 5 # Number of explanatory variables
> x <- as.matrix(do.call(expand.grid, lapply(as.list(1:p), function(i) c(-1,1))))
> y <- x[,1] + rnorm(2^p, mean=0, sd=2)
> X <- as.data.frame(x)
>
> m <- lm(y ~ Var1 + Var2, X)
> summary(m)
Call:
lm(formula = y ~ Var1 + Var2, data = X)
Residuals:
Min 1Q Median 3Q Max
-3.13861 -1.34150 0.09369 1.10478 2.85457
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.5185 0.2980 1.740 0.09244 .
Var1 0.8975 0.2980 3.012 0.00534 **
Var2 0.1624 0.2980 0.545 0.58982
---
Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1
Residual standard error: 1.686 on 29 degrees of freedom
Multiple R-squared: 0.2442, Adjusted R-squared: 0.192
F-statistic: 4.684 on 2 and 29 DF, p-value: 0.01726
> qf(0.99, 1, 29)
[1] 7.597663
>
> qf(0.99, 2, 29)
[1] 5.420445
To illustrate the "insignificance of overall $F$-test inflation" effect as the number of regressors $p$, consider the same scenario as above but now $p$ ranges from $2$ to $29$ (the penultimate maximum number of regressors that $F$-test works fine).
q1 <- qf(0.99, 1, 29:2)
q2 <- qf(0.99, 2:29, 29:2)
F1 <- q1 + 0.5 # This simulates the case that t-test barely rejects H0.
F2 <- F1/(2:29) # F2 is approximately 1/p of F1 by setting.
plot(2:29, q2, xlab = "# of predictors", ylab = "")
points(2:29, q1, pch = 2)
lines(2:29, F1)
lines(2:29, F2, lty = "dashed")
legend("topleft",
c("t-test threshold (q1)",
"F-test threshold (q2)",
"t-test stat (F1)",
"F-test stat (F2)"),
pch = c(2, 1, NA, NA),
lty = c(NA, NA, "solid", "dashed"))
The graph is as follows. It can be seen that the dashed line is always below thresholds (hence $F$-tests are always insignificant), and as $p$ increases, the gap between the dots and the dashed line also increases, indicating that the $F$-test becomes more insignificant.
|
Significance contradiction in linear regression: significant t-test for a coefficient vs non-signifi
The example in whuber's answer is very to the point (+1), to which I want to elaborate the rationale behind it from the theoretical perspective. For a better exposition, suppose the number of regress
|
6,226
|
Confidence interval for median
|
Here is an illustration on a classical R dataset:
> x = faithful$waiting
> bootmed = apply(matrix(sample(x, rep=TRUE, 10^4*length(x)), nrow=10^4), 1, median)
> quantile(bootmed, c(.025, 0.975))
2.5% 97.5%
73.5 77
which gives a (73.5, 77) confidence interval on the median.
(Note: Corrected version, thanks to John. I used $10^3$ in the nrow earlier, which led to the confusion!)
|
Confidence interval for median
|
Here is an illustration on a classical R dataset:
> x = faithful$waiting
> bootmed = apply(matrix(sample(x, rep=TRUE, 10^4*length(x)), nrow=10^4), 1, median)
> quantile(bootmed, c(.025, 0.975))
|
Confidence interval for median
Here is an illustration on a classical R dataset:
> x = faithful$waiting
> bootmed = apply(matrix(sample(x, rep=TRUE, 10^4*length(x)), nrow=10^4), 1, median)
> quantile(bootmed, c(.025, 0.975))
2.5% 97.5%
73.5 77
which gives a (73.5, 77) confidence interval on the median.
(Note: Corrected version, thanks to John. I used $10^3$ in the nrow earlier, which led to the confusion!)
|
Confidence interval for median
Here is an illustration on a classical R dataset:
> x = faithful$waiting
> bootmed = apply(matrix(sample(x, rep=TRUE, 10^4*length(x)), nrow=10^4), 1, median)
> quantile(bootmed, c(.025, 0.975))
|
6,227
|
Confidence interval for median
|
Another approach is based on quantiles of the binomial distribution.
e.g.:
> x=faithful$waiting
> sort(x)[qbinom(c(.025,.975), length(x), 0.5)]
[1] 73 77
|
Confidence interval for median
|
Another approach is based on quantiles of the binomial distribution.
e.g.:
> x=faithful$waiting
> sort(x)[qbinom(c(.025,.975), length(x), 0.5)]
[1] 73 77
|
Confidence interval for median
Another approach is based on quantiles of the binomial distribution.
e.g.:
> x=faithful$waiting
> sort(x)[qbinom(c(.025,.975), length(x), 0.5)]
[1] 73 77
|
Confidence interval for median
Another approach is based on quantiles of the binomial distribution.
e.g.:
> x=faithful$waiting
> sort(x)[qbinom(c(.025,.975), length(x), 0.5)]
[1] 73 77
|
6,228
|
Confidence interval for median
|
Check out bootstrap resampling. Search R help for the boot function. Depending on your data with resampling you can estimate confidence intervals for just about anything.
|
Confidence interval for median
|
Check out bootstrap resampling. Search R help for the boot function. Depending on your data with resampling you can estimate confidence intervals for just about anything.
|
Confidence interval for median
Check out bootstrap resampling. Search R help for the boot function. Depending on your data with resampling you can estimate confidence intervals for just about anything.
|
Confidence interval for median
Check out bootstrap resampling. Search R help for the boot function. Depending on your data with resampling you can estimate confidence intervals for just about anything.
|
6,229
|
Confidence interval for median
|
And there are other approaches:
One is based on Wilcoxon Rank Sum test applied for one sample with continuity correction. In R this can be supplied as:
wilcox.test(x,conf.level=0.95,alternative="two.sided",correct=TRUE)
And there is the David Olive's CI for median discussed here:
CI for Median
|
Confidence interval for median
|
And there are other approaches:
One is based on Wilcoxon Rank Sum test applied for one sample with continuity correction. In R this can be supplied as:
wilcox.test(x,conf.level=0.95,alternative="two.s
|
Confidence interval for median
And there are other approaches:
One is based on Wilcoxon Rank Sum test applied for one sample with continuity correction. In R this can be supplied as:
wilcox.test(x,conf.level=0.95,alternative="two.sided",correct=TRUE)
And there is the David Olive's CI for median discussed here:
CI for Median
|
Confidence interval for median
And there are other approaches:
One is based on Wilcoxon Rank Sum test applied for one sample with continuity correction. In R this can be supplied as:
wilcox.test(x,conf.level=0.95,alternative="two.s
|
6,230
|
Confidence interval for median
|
The result based on the qbinom approach isn't correct for small samples. Suppose that x has 10 components. Then qbinom(c(.025,.975),10,.5) gives 2 and 8. The resulting interval doesn't treat order statistics at the lower tail symmetrically with those from the upper tail; you should get either 2 and 9, or 3 and 8. The right answer is 2 and 9. You can check against proc univariate in SAS. Catch here is you need no more than .025 probability below and above; the lower quantile doesn't do this, as it gives at least .025 at or below. You get saved on the bottom because the count that should be 1 should get mapped to the second order statistic, counting 0, and so the "off by one" cancels. This fortuitous canceling does not happen on top, and so you get the wrong answer here. The code sort(x)[qbinom(c(.025,.975),length(x),.5)+c(0,1)]
almost works, and .5 can be replaced by other quantile values to get confidence intervals for other quantiles, but it won't be right when there exists a such that P[X<=a]=.025. See, for ex, Higgins, Nonparametric Statisitcs.
|
Confidence interval for median
|
The result based on the qbinom approach isn't correct for small samples. Suppose that x has 10 components. Then qbinom(c(.025,.975),10,.5) gives 2 and 8. The resulting interval doesn't treat order
|
Confidence interval for median
The result based on the qbinom approach isn't correct for small samples. Suppose that x has 10 components. Then qbinom(c(.025,.975),10,.5) gives 2 and 8. The resulting interval doesn't treat order statistics at the lower tail symmetrically with those from the upper tail; you should get either 2 and 9, or 3 and 8. The right answer is 2 and 9. You can check against proc univariate in SAS. Catch here is you need no more than .025 probability below and above; the lower quantile doesn't do this, as it gives at least .025 at or below. You get saved on the bottom because the count that should be 1 should get mapped to the second order statistic, counting 0, and so the "off by one" cancels. This fortuitous canceling does not happen on top, and so you get the wrong answer here. The code sort(x)[qbinom(c(.025,.975),length(x),.5)+c(0,1)]
almost works, and .5 can be replaced by other quantile values to get confidence intervals for other quantiles, but it won't be right when there exists a such that P[X<=a]=.025. See, for ex, Higgins, Nonparametric Statisitcs.
|
Confidence interval for median
The result based on the qbinom approach isn't correct for small samples. Suppose that x has 10 components. Then qbinom(c(.025,.975),10,.5) gives 2 and 8. The resulting interval doesn't treat order
|
6,231
|
Polynomial regression using scikit-learn
|
Given data $\mathbf{x}$, a column vector, and $\mathbf{y}$, the target vector, you can perform polynomial regression by appending polynomials of $\mathbf{x}$. For example, consider if
$$ \mathbf{x} = \begin{bmatrix}
2 \\[0.3em]
-1 \\[0.3em]
\frac{1}{3}
\end{bmatrix}$$
Using just this vector in linear regression implies the model:
$$ y = \alpha_1 x $$
We can add columns that are powers of the vector above, which represent adding polynomials to the regression. Below we show this for polynomials up to power 3:
$$
X = \begin{bmatrix}
2 & 4 & 8 \\[0.3em]
-1 & 1 & -1 \\[0.3em]
\frac{1}{3} & \frac{1}{3^2} & \frac{1}{3^3}
\end{bmatrix}$$
This is our new data matrix that we use in sklearn's linear regression, and it represents the model:
$$ y = \alpha_1 x + \alpha_2x^2 + \alpha_3x^3$$
Note that I did not add a constant vector of $1$'s, as sklearn will automatically include this.
|
Polynomial regression using scikit-learn
|
Given data $\mathbf{x}$, a column vector, and $\mathbf{y}$, the target vector, you can perform polynomial regression by appending polynomials of $\mathbf{x}$. For example, consider if
$$ \mathbf{x} =
|
Polynomial regression using scikit-learn
Given data $\mathbf{x}$, a column vector, and $\mathbf{y}$, the target vector, you can perform polynomial regression by appending polynomials of $\mathbf{x}$. For example, consider if
$$ \mathbf{x} = \begin{bmatrix}
2 \\[0.3em]
-1 \\[0.3em]
\frac{1}{3}
\end{bmatrix}$$
Using just this vector in linear regression implies the model:
$$ y = \alpha_1 x $$
We can add columns that are powers of the vector above, which represent adding polynomials to the regression. Below we show this for polynomials up to power 3:
$$
X = \begin{bmatrix}
2 & 4 & 8 \\[0.3em]
-1 & 1 & -1 \\[0.3em]
\frac{1}{3} & \frac{1}{3^2} & \frac{1}{3^3}
\end{bmatrix}$$
This is our new data matrix that we use in sklearn's linear regression, and it represents the model:
$$ y = \alpha_1 x + \alpha_2x^2 + \alpha_3x^3$$
Note that I did not add a constant vector of $1$'s, as sklearn will automatically include this.
|
Polynomial regression using scikit-learn
Given data $\mathbf{x}$, a column vector, and $\mathbf{y}$, the target vector, you can perform polynomial regression by appending polynomials of $\mathbf{x}$. For example, consider if
$$ \mathbf{x} =
|
6,232
|
Polynomial regression using scikit-learn
|
Theory
Polynomial regression is a special case of linear regression. With the main idea of how do you select your features. Looking at the multivariate regression with 2 variables: x1 and x2. Linear regression will look like this: y = a1 * x1 + a2 * x2.
Now you want to have a polynomial regression (let's make 2 degree polynomial). We will create a few additional features: x1*x2, x1^2 and x2^2. So we will get your 'linear regression':
y = a1 * x1 + a2 * x2 + a3 * x1*x2 + a4 * x1^2 + a5 * x2^2
This nicely shows an important concept curse of dimensionality, because the number of new features grows much faster than linearly with the growth of degree of polynomial.
Practice with scikit-learn
You do not need to do all this in scikit. Polynomial regression is already available there (in 0.15 version. Check how to update it here).
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
X = [[0.44, 0.68], [0.99, 0.23]]
vector = [109.85, 155.72]
predict= [[0.49, 0.18]]
#Edit: added second square bracket above to fix the ValueError problem
poly = PolynomialFeatures(degree=2)
X_ = poly.fit_transform(X)
predict_ = poly.fit_transform(predict)
clf = linear_model.LinearRegression()
clf.fit(X_, vector)
print clf.predict(predict_)
|
Polynomial regression using scikit-learn
|
Theory
Polynomial regression is a special case of linear regression. With the main idea of how do you select your features. Looking at the multivariate regression with 2 variables: x1 and x2. Linear r
|
Polynomial regression using scikit-learn
Theory
Polynomial regression is a special case of linear regression. With the main idea of how do you select your features. Looking at the multivariate regression with 2 variables: x1 and x2. Linear regression will look like this: y = a1 * x1 + a2 * x2.
Now you want to have a polynomial regression (let's make 2 degree polynomial). We will create a few additional features: x1*x2, x1^2 and x2^2. So we will get your 'linear regression':
y = a1 * x1 + a2 * x2 + a3 * x1*x2 + a4 * x1^2 + a5 * x2^2
This nicely shows an important concept curse of dimensionality, because the number of new features grows much faster than linearly with the growth of degree of polynomial.
Practice with scikit-learn
You do not need to do all this in scikit. Polynomial regression is already available there (in 0.15 version. Check how to update it here).
from sklearn.preprocessing import PolynomialFeatures
from sklearn import linear_model
X = [[0.44, 0.68], [0.99, 0.23]]
vector = [109.85, 155.72]
predict= [[0.49, 0.18]]
#Edit: added second square bracket above to fix the ValueError problem
poly = PolynomialFeatures(degree=2)
X_ = poly.fit_transform(X)
predict_ = poly.fit_transform(predict)
clf = linear_model.LinearRegression()
clf.fit(X_, vector)
print clf.predict(predict_)
|
Polynomial regression using scikit-learn
Theory
Polynomial regression is a special case of linear regression. With the main idea of how do you select your features. Looking at the multivariate regression with 2 variables: x1 and x2. Linear r
|
6,233
|
Polynomial regression using scikit-learn
|
In case you are using a multivariate regression and not just a univariate regression, do not forget the cross terms. For instance if you have two variables $x_1$ and $x_2$, and you want polynomials up to power 2, you should use $y = a_1x_1 + a_2x_2 + a_3x_1^2 + a_4x_2^2 + a_5x_1x_2$ where the last term ($a_5x_1x_2$) is the one I am talking about.
|
Polynomial regression using scikit-learn
|
In case you are using a multivariate regression and not just a univariate regression, do not forget the cross terms. For instance if you have two variables $x_1$ and $x_2$, and you want polynomials up
|
Polynomial regression using scikit-learn
In case you are using a multivariate regression and not just a univariate regression, do not forget the cross terms. For instance if you have two variables $x_1$ and $x_2$, and you want polynomials up to power 2, you should use $y = a_1x_1 + a_2x_2 + a_3x_1^2 + a_4x_2^2 + a_5x_1x_2$ where the last term ($a_5x_1x_2$) is the one I am talking about.
|
Polynomial regression using scikit-learn
In case you are using a multivariate regression and not just a univariate regression, do not forget the cross terms. For instance if you have two variables $x_1$ and $x_2$, and you want polynomials up
|
6,234
|
Polynomial regression using scikit-learn
|
Using a similar approach to @Cam.Davidson.Pilon, I wrote a couple functions to help demo this approach in Python. It can be expanded by adding more terms in the np.concatenate vectors. The output for the y_pred would not change, but getting the coefficients, regr.coef_[0][2], would need to be included.
from sklearn import linear_model
import numpy as np
from matplotlib import pyplot as plt
def regress_2nd_order(x, y):
# The x values are transformed into the second order matrix
X = np.concatenate([x, x**2], axis=1)
# Use model to fit to the data
regr.fit(X, y)
# Extract the values of interest for forming the equation...
# y_pred = c0 + c1 * x + c2 * x^2
c0 = round(regr.intercept_[0],2)
c1 = round(regr.coef_[0][0],2)
c2 = round(regr.coef_[0][1],4)
# c3 = round(regr.coef_[0][2],4)
# Another way to get this is using the `regr.predict` function
# Predict will calculate the values for you
y_pred = regr.predict(X)
# Print the intercept (c0) and the corresponding coefficients
print('Scikit learn - \nEquation: %.2f + %.2f*T + %.5f*T^2' % (c0,c1,c2) )
# return y_pred, (c0, c1, c2, c3)
return y_pred, (c0, c1, c2)
def socket_temp(x, y):
# Include only the predicted y-vector
y_pred = regress_2nd_order(x, y)[0]
fig, ax = plt.subplots(1,1, figsize=(10,10))
ax.plot(x, y_pred, ls='', marker='*', label='predicted')
ax.plot(x, y, ls='', marker='.', label='iddt')
ax.legend()
For my use, I had temperature as my y variable, and a dynamic supply current (IDDT) output as my x variable. Here are the values I used for x and y and the output vector, y_pred:
'iddt' 'temp' 'y_pred'
0 627.23 20.0 20.42
1 627.38 19.9 20.52
2 612.39 9.7 10.32
3 612.48 9.7 10.38
4 597.73 -0.1 0.19
5 597.78 -0.2 0.22
6 583.24 -10.1 -9.99
7 583.24 -10.0 -9.99
8 569.22 -19.9 -19.99
9 568.97 -19.9 -20.17
10 555.62 -29.8 -29.83
11 555.99 -29.8 -29.56
12 541.15 -40.1 -40.45
13 541.50 -40.1 -40.19
14 639.88 30.3 28.89
15 640.11 30.2 29.05
16 656.61 40.2 39.92
17 656.62 40.3 39.92
18 672.73 50.4 50.33
19 672.68 50.4 50.30
20 689.56 60.6 61.01
21 689.26 60.6 60.82
22 705.30 70.8 70.79
23 705.22 70.8 70.75
24 722.27 81.0 81.14
25 722.24 81.0 81.12
|
Polynomial regression using scikit-learn
|
Using a similar approach to @Cam.Davidson.Pilon, I wrote a couple functions to help demo this approach in Python. It can be expanded by adding more terms in the np.concatenate vectors. The output for
|
Polynomial regression using scikit-learn
Using a similar approach to @Cam.Davidson.Pilon, I wrote a couple functions to help demo this approach in Python. It can be expanded by adding more terms in the np.concatenate vectors. The output for the y_pred would not change, but getting the coefficients, regr.coef_[0][2], would need to be included.
from sklearn import linear_model
import numpy as np
from matplotlib import pyplot as plt
def regress_2nd_order(x, y):
# The x values are transformed into the second order matrix
X = np.concatenate([x, x**2], axis=1)
# Use model to fit to the data
regr.fit(X, y)
# Extract the values of interest for forming the equation...
# y_pred = c0 + c1 * x + c2 * x^2
c0 = round(regr.intercept_[0],2)
c1 = round(regr.coef_[0][0],2)
c2 = round(regr.coef_[0][1],4)
# c3 = round(regr.coef_[0][2],4)
# Another way to get this is using the `regr.predict` function
# Predict will calculate the values for you
y_pred = regr.predict(X)
# Print the intercept (c0) and the corresponding coefficients
print('Scikit learn - \nEquation: %.2f + %.2f*T + %.5f*T^2' % (c0,c1,c2) )
# return y_pred, (c0, c1, c2, c3)
return y_pred, (c0, c1, c2)
def socket_temp(x, y):
# Include only the predicted y-vector
y_pred = regress_2nd_order(x, y)[0]
fig, ax = plt.subplots(1,1, figsize=(10,10))
ax.plot(x, y_pred, ls='', marker='*', label='predicted')
ax.plot(x, y, ls='', marker='.', label='iddt')
ax.legend()
For my use, I had temperature as my y variable, and a dynamic supply current (IDDT) output as my x variable. Here are the values I used for x and y and the output vector, y_pred:
'iddt' 'temp' 'y_pred'
0 627.23 20.0 20.42
1 627.38 19.9 20.52
2 612.39 9.7 10.32
3 612.48 9.7 10.38
4 597.73 -0.1 0.19
5 597.78 -0.2 0.22
6 583.24 -10.1 -9.99
7 583.24 -10.0 -9.99
8 569.22 -19.9 -19.99
9 568.97 -19.9 -20.17
10 555.62 -29.8 -29.83
11 555.99 -29.8 -29.56
12 541.15 -40.1 -40.45
13 541.50 -40.1 -40.19
14 639.88 30.3 28.89
15 640.11 30.2 29.05
16 656.61 40.2 39.92
17 656.62 40.3 39.92
18 672.73 50.4 50.33
19 672.68 50.4 50.30
20 689.56 60.6 61.01
21 689.26 60.6 60.82
22 705.30 70.8 70.79
23 705.22 70.8 70.75
24 722.27 81.0 81.14
25 722.24 81.0 81.12
|
Polynomial regression using scikit-learn
Using a similar approach to @Cam.Davidson.Pilon, I wrote a couple functions to help demo this approach in Python. It can be expanded by adding more terms in the np.concatenate vectors. The output for
|
6,235
|
How to decide which glm family to use?
|
GLM families comprise a link function as well as a mean-variance relationship. For Poisson GLMs, the link function is a log, and the mean-variance relationship is the identity. Despite the warnings that most statistical software gives you, it's completely reasonable to model a relationship in continuous data in which the relationship between two variables is linear on the log scale, and the variance increases in accordance with the mean.
This, essentially, is the rationale for choosing the link and variance function in a GLM. Of course, there are several assumptions behind this process. You can make a more robust model by using quasilikelihood (see ?quasipoisson) or robust standard errors (see package sandwich or gee).
You have correctly noted that many densities are 0 in your data. Under Poisson probability models, it is appropriate to occasionally sample 0s in the data, so it's not necessarily the case that these observations are leading to bias in your estimates of rates.
To inspect the assumptions behind GLMs, it is usually helpful to look at the Pearson residuals. These account for the mean variance relationship and show the statistician whether particular observations, such as these 0s, are egregiously affecting estimation and results.
|
How to decide which glm family to use?
|
GLM families comprise a link function as well as a mean-variance relationship. For Poisson GLMs, the link function is a log, and the mean-variance relationship is the identity. Despite the warnings th
|
How to decide which glm family to use?
GLM families comprise a link function as well as a mean-variance relationship. For Poisson GLMs, the link function is a log, and the mean-variance relationship is the identity. Despite the warnings that most statistical software gives you, it's completely reasonable to model a relationship in continuous data in which the relationship between two variables is linear on the log scale, and the variance increases in accordance with the mean.
This, essentially, is the rationale for choosing the link and variance function in a GLM. Of course, there are several assumptions behind this process. You can make a more robust model by using quasilikelihood (see ?quasipoisson) or robust standard errors (see package sandwich or gee).
You have correctly noted that many densities are 0 in your data. Under Poisson probability models, it is appropriate to occasionally sample 0s in the data, so it's not necessarily the case that these observations are leading to bias in your estimates of rates.
To inspect the assumptions behind GLMs, it is usually helpful to look at the Pearson residuals. These account for the mean variance relationship and show the statistician whether particular observations, such as these 0s, are egregiously affecting estimation and results.
|
How to decide which glm family to use?
GLM families comprise a link function as well as a mean-variance relationship. For Poisson GLMs, the link function is a log, and the mean-variance relationship is the identity. Despite the warnings th
|
6,236
|
How to decide which glm family to use?
|
Generalized linear model is defined in terms of linear predictor
$$
\eta = \boldsymbol{X} \beta
$$
that is passed through the link function $g$:
$$ g(E(Y\,|\,\boldsymbol{X})) = \eta $$
It models the relation between the dependent variable $Y$ and independent variables $\boldsymbol{X} = X_1,X_2,\dots,X_k$. More precisely, it models a conditional expectation of $Y$ given $\boldsymbol{X}$,
$$
E(Y\,|\,\boldsymbol{X} ) = \mu = g^{-1}(\eta)
$$
so the model can be defined in probabilistic terms as
$$
Y\,|\,\boldsymbol{X} \sim f(\mu, \sigma^2)
$$
where $f$ is a probability distribution of the exponential family. So first thing to notice is that $f$ is not the distribution of $Y$, but $Y$ follows it conditionally on $\boldsymbol{X}$. The choice of this distribution depends on your knowledge (what you can assume) about the relation between $Y$ and $\boldsymbol{X}$. So anywhere you read about the distribution, what is meant is the conditional distribution.
If your outcome is continuous and unbounded, then the most "default" choice is the Gaussian distribution (a.k.a. normal distribution), i.e. the standard linear regression (unless you use other link function then the default identity link).
If you are dealing with continuous non-negative outcome, then you could consider the Gamma distribution, or Inverse Gaussian distribution.
If your outcome is discrete, or more precisely, you are dealing with counts (how many times something happen in given time interval), then the most common choice of the distribution to start with is Poisson distribution. The problem with Poisson distribution is that it is rather inflexible in the fact that it assumes that mean is equal to variance, if this assumption is not met, you may consider using quasi-Poisson family, or negative binomial distribution (see also Definition of dispersion parameter for quasipoisson family).
If your outcome is binary (zeros and ones), proportions of "successes" and "failures" (values between 0 and 1), or their counts, you can use Binomial distribution, i.e. the logistic regression model. If there is more then two categories, you would use multinomial distribution in multinomial regression.
On another hand, in practice, if you are interested in building a predictive model, you may be interested in testing few different distributions, and in the end learn that one of them gives you more accurate results then the others even if it is not the most "appropriate" in terms of theoretical considerations (e.g. in theory you should use Poisson, but in practice standard linear regression works best for your data).
|
How to decide which glm family to use?
|
Generalized linear model is defined in terms of linear predictor
$$
\eta = \boldsymbol{X} \beta
$$
that is passed through the link function $g$:
$$ g(E(Y\,|\,\boldsymbol{X})) = \eta $$
It models the r
|
How to decide which glm family to use?
Generalized linear model is defined in terms of linear predictor
$$
\eta = \boldsymbol{X} \beta
$$
that is passed through the link function $g$:
$$ g(E(Y\,|\,\boldsymbol{X})) = \eta $$
It models the relation between the dependent variable $Y$ and independent variables $\boldsymbol{X} = X_1,X_2,\dots,X_k$. More precisely, it models a conditional expectation of $Y$ given $\boldsymbol{X}$,
$$
E(Y\,|\,\boldsymbol{X} ) = \mu = g^{-1}(\eta)
$$
so the model can be defined in probabilistic terms as
$$
Y\,|\,\boldsymbol{X} \sim f(\mu, \sigma^2)
$$
where $f$ is a probability distribution of the exponential family. So first thing to notice is that $f$ is not the distribution of $Y$, but $Y$ follows it conditionally on $\boldsymbol{X}$. The choice of this distribution depends on your knowledge (what you can assume) about the relation between $Y$ and $\boldsymbol{X}$. So anywhere you read about the distribution, what is meant is the conditional distribution.
If your outcome is continuous and unbounded, then the most "default" choice is the Gaussian distribution (a.k.a. normal distribution), i.e. the standard linear regression (unless you use other link function then the default identity link).
If you are dealing with continuous non-negative outcome, then you could consider the Gamma distribution, or Inverse Gaussian distribution.
If your outcome is discrete, or more precisely, you are dealing with counts (how many times something happen in given time interval), then the most common choice of the distribution to start with is Poisson distribution. The problem with Poisson distribution is that it is rather inflexible in the fact that it assumes that mean is equal to variance, if this assumption is not met, you may consider using quasi-Poisson family, or negative binomial distribution (see also Definition of dispersion parameter for quasipoisson family).
If your outcome is binary (zeros and ones), proportions of "successes" and "failures" (values between 0 and 1), or their counts, you can use Binomial distribution, i.e. the logistic regression model. If there is more then two categories, you would use multinomial distribution in multinomial regression.
On another hand, in practice, if you are interested in building a predictive model, you may be interested in testing few different distributions, and in the end learn that one of them gives you more accurate results then the others even if it is not the most "appropriate" in terms of theoretical considerations (e.g. in theory you should use Poisson, but in practice standard linear regression works best for your data).
|
How to decide which glm family to use?
Generalized linear model is defined in terms of linear predictor
$$
\eta = \boldsymbol{X} \beta
$$
that is passed through the link function $g$:
$$ g(E(Y\,|\,\boldsymbol{X})) = \eta $$
It models the r
|
6,237
|
How to decide which glm family to use?
|
This is a somewhat broad question, you are asking for how to do modelling, and there are entire books dedicated to that. For example, when dealing with count data, consider the following:
In addition to choosing a distribution, you have to choose a link function. With count data you could try poisson or negative binomial distribution, and log link function. A reason for the log link is given here: Goodness of fit and which model to choose linear regression or Poisson If your patches have very different areas, maybe you should include logarithm of area as an offset, to model counts per unit area and not absolute counts. For an explication of offset in count data regression, see When to use an offset in a Poisson regression?
EDIT
This answer was originally posted to another question, which was merged with this one. While the answer is general, it commented specifics of a data set and problem which no more are in the question. The original question can be found in the following link: Family in GLM - how to choose the right one?
|
How to decide which glm family to use?
|
This is a somewhat broad question, you are asking for how to do modelling, and there are entire books dedicated to that. For example, when dealing with count data, consider the following:
In addition
|
How to decide which glm family to use?
This is a somewhat broad question, you are asking for how to do modelling, and there are entire books dedicated to that. For example, when dealing with count data, consider the following:
In addition to choosing a distribution, you have to choose a link function. With count data you could try poisson or negative binomial distribution, and log link function. A reason for the log link is given here: Goodness of fit and which model to choose linear regression or Poisson If your patches have very different areas, maybe you should include logarithm of area as an offset, to model counts per unit area and not absolute counts. For an explication of offset in count data regression, see When to use an offset in a Poisson regression?
EDIT
This answer was originally posted to another question, which was merged with this one. While the answer is general, it commented specifics of a data set and problem which no more are in the question. The original question can be found in the following link: Family in GLM - how to choose the right one?
|
How to decide which glm family to use?
This is a somewhat broad question, you are asking for how to do modelling, and there are entire books dedicated to that. For example, when dealing with count data, consider the following:
In addition
|
6,238
|
Regression to the mean vs gambler's fallacy
|
I think the confusion can be resolved by considering that the concept of "regression to the mean" really has nothing to do with the past. It's merely the tautological observation that at each iteration of an experiment we expect the average outcome. So if we previously had an above average outcome then we expect a worse result, or if we had a below average outcome we expect a better one. The key point is that the expectation itself does not depend on any previous history as it does in the gambler's fallacy.
|
Regression to the mean vs gambler's fallacy
|
I think the confusion can be resolved by considering that the concept of "regression to the mean" really has nothing to do with the past. It's merely the tautological observation that at each iterati
|
Regression to the mean vs gambler's fallacy
I think the confusion can be resolved by considering that the concept of "regression to the mean" really has nothing to do with the past. It's merely the tautological observation that at each iteration of an experiment we expect the average outcome. So if we previously had an above average outcome then we expect a worse result, or if we had a below average outcome we expect a better one. The key point is that the expectation itself does not depend on any previous history as it does in the gambler's fallacy.
|
Regression to the mean vs gambler's fallacy
I think the confusion can be resolved by considering that the concept of "regression to the mean" really has nothing to do with the past. It's merely the tautological observation that at each iterati
|
6,239
|
Regression to the mean vs gambler's fallacy
|
If you were to find yourself in such a position, as a rational person (and assuming a fair coin), your best bet would be to just guess. If you were to find yourself in such a position as a superstitious gambler, your best bet would be to look at the prior events and try to justify your reasoning about the past - e.g. "Wow, heads are hot, time to ante up!" or "There's no way we're gonna see another heads - the probability of that kind of streak is incredibly low!".
The gambler's fallacy is not realizing that every particular string of 20 coin tosses us insanely unlikely - for instance, it's very unlikely to flip 10 heads and then 10 tails, very unlikely to flip alternating heads and tails, very unlikely to split in 4's, etc. It's even very unlikely to flip HHTHHTTTHT.. because for any string there's only one way for that to happen out of many many different outcomes. Thus, conflating any of these as "likely" or "unlikely" is a fallacy, as they are all equiprobable.
Regression to the mean is the rightly-founded belief that in the long run, your observations should converge to a finite expected value. For instance - my bet that 10 of 20 coin tosses is a good one because there are many ways of achieving it. A bet on 15 of 20 is substantially less likely since there are far fewer strings that achieve that final count. It's worth noting that if you sit around and flip (fair) coins long enough, you will ultimately end up with something that's roughly 50/50 - but you won't end up with something that doesn't have "streaks" or other improbable events in it. That is the core of the difference between these two concepts.
TL;DR: Regression to the mean says that over time, you'll end up with a distribution that mirrors the expected in any experiment. Gambler's fallacy (wrongly) says that each individual flip of a coin has memory as to the previous results, which should impact the next independent outcome.
|
Regression to the mean vs gambler's fallacy
|
If you were to find yourself in such a position, as a rational person (and assuming a fair coin), your best bet would be to just guess. If you were to find yourself in such a position as a superstitio
|
Regression to the mean vs gambler's fallacy
If you were to find yourself in such a position, as a rational person (and assuming a fair coin), your best bet would be to just guess. If you were to find yourself in such a position as a superstitious gambler, your best bet would be to look at the prior events and try to justify your reasoning about the past - e.g. "Wow, heads are hot, time to ante up!" or "There's no way we're gonna see another heads - the probability of that kind of streak is incredibly low!".
The gambler's fallacy is not realizing that every particular string of 20 coin tosses us insanely unlikely - for instance, it's very unlikely to flip 10 heads and then 10 tails, very unlikely to flip alternating heads and tails, very unlikely to split in 4's, etc. It's even very unlikely to flip HHTHHTTTHT.. because for any string there's only one way for that to happen out of many many different outcomes. Thus, conflating any of these as "likely" or "unlikely" is a fallacy, as they are all equiprobable.
Regression to the mean is the rightly-founded belief that in the long run, your observations should converge to a finite expected value. For instance - my bet that 10 of 20 coin tosses is a good one because there are many ways of achieving it. A bet on 15 of 20 is substantially less likely since there are far fewer strings that achieve that final count. It's worth noting that if you sit around and flip (fair) coins long enough, you will ultimately end up with something that's roughly 50/50 - but you won't end up with something that doesn't have "streaks" or other improbable events in it. That is the core of the difference between these two concepts.
TL;DR: Regression to the mean says that over time, you'll end up with a distribution that mirrors the expected in any experiment. Gambler's fallacy (wrongly) says that each individual flip of a coin has memory as to the previous results, which should impact the next independent outcome.
|
Regression to the mean vs gambler's fallacy
If you were to find yourself in such a position, as a rational person (and assuming a fair coin), your best bet would be to just guess. If you were to find yourself in such a position as a superstitio
|
6,240
|
Regression to the mean vs gambler's fallacy
|
Here's a simple example: you've decided to toss a total of 200 coins. So far you've tossed 100 of them and you've gotten extremely lucky: 100% came up heads (incredible, I know, but let's just keep things simple).
Conditional on 100 heads in the 100 first tosses, you expect to have 150 heads total at the end of the game. An extreme example of the gambler's fallacy would be to think that you still only expect 100 heads total (i.e. the expected value before starting the game), even after getting 100 in the first 100 tosses. The gambler fallaciously thinks the next 100 tosses must be tails. An example of regression to the mean (in this context) is that your head-rate of 100% is expected to fall to 150/200 = 75% (i.e. toward the mean of 50%) as you finish the game.
|
Regression to the mean vs gambler's fallacy
|
Here's a simple example: you've decided to toss a total of 200 coins. So far you've tossed 100 of them and you've gotten extremely lucky: 100% came up heads (incredible, I know, but let's just keep
|
Regression to the mean vs gambler's fallacy
Here's a simple example: you've decided to toss a total of 200 coins. So far you've tossed 100 of them and you've gotten extremely lucky: 100% came up heads (incredible, I know, but let's just keep things simple).
Conditional on 100 heads in the 100 first tosses, you expect to have 150 heads total at the end of the game. An extreme example of the gambler's fallacy would be to think that you still only expect 100 heads total (i.e. the expected value before starting the game), even after getting 100 in the first 100 tosses. The gambler fallaciously thinks the next 100 tosses must be tails. An example of regression to the mean (in this context) is that your head-rate of 100% is expected to fall to 150/200 = 75% (i.e. toward the mean of 50%) as you finish the game.
|
Regression to the mean vs gambler's fallacy
Here's a simple example: you've decided to toss a total of 200 coins. So far you've tossed 100 of them and you've gotten extremely lucky: 100% came up heads (incredible, I know, but let's just keep
|
6,241
|
Regression to the mean vs gambler's fallacy
|
I always try to remember that regression toward the mean isn't a compensatory mechanism for observing outliers.
There's no cause-and-effect relationship between having an outstanding gambling run, then going 50-50 after that. It's just a helpful way to remember that, when you're sampling from a distribution, you're most likely to see values close to the mean (think of what Chebyshev's inequality has to say here).
|
Regression to the mean vs gambler's fallacy
|
I always try to remember that regression toward the mean isn't a compensatory mechanism for observing outliers.
There's no cause-and-effect relationship between having an outstanding gambling run, th
|
Regression to the mean vs gambler's fallacy
I always try to remember that regression toward the mean isn't a compensatory mechanism for observing outliers.
There's no cause-and-effect relationship between having an outstanding gambling run, then going 50-50 after that. It's just a helpful way to remember that, when you're sampling from a distribution, you're most likely to see values close to the mean (think of what Chebyshev's inequality has to say here).
|
Regression to the mean vs gambler's fallacy
I always try to remember that regression toward the mean isn't a compensatory mechanism for observing outliers.
There's no cause-and-effect relationship between having an outstanding gambling run, th
|
6,242
|
Regression to the mean vs gambler's fallacy
|
The key is that we don't have any information that will help us with the next event (gambler's fallacy), because the next event isn't dependent on the previous event. We can make a reasonable guess about how a series of trials will go. This reasonable guess is the average aka our expected mean result. So when we watch a deviation in the mean trend back toward the mean, over time/trials, then we witnessing a regression to the mean.
As you can see regression to the mean is an observed series of actions, it isn't a predictor. As more trials are conducted things will more closely approximate a normal/Gaussian distribution. This means that I'm not making any assumptions or guess on what the next result will be. Using the law of large numbers I can theorize that even though things might be trending one way currently, over time things will balance themselves out. When they do balance themselves out the result set has regressed to the mean. It is important to note here that we aren't saying that future trials are dependent on past results. I'm merely observing a change in the balance of the data.
The gambler's fallacy as I understand it is more immediate in it's goals and focuses on prediction of future events. This tracks with what a gambler desires. Typically games of chance are tilted against the gambler over the long term, so a gambler wants to know what the next trial will be because they want to capitalize on this knowledge. This leads the gambler to falsely assume that the next trial is dependent on the previous trial. This can lead to neutral choices like:
The last five times the roulette wheel landed on black, so therefore next time I'm betting big on red.
Or the choice can be self-serving:
I've gotten a full house the last 5 hands, so I'm going to bet big because I'm on a winning streak and can't lose.
So as you can see there are few key differences:
Regression to the mean doesn't assume that independent trials are dependent like the gambler's fallacy.
Regression to the mean is applied over a large amount of data/trials, where the gambler's fallacy is concerned with the next trial.
Regression to the mean describes what has already taken place. Gambler's fallacy attempts to predict the future based on an expected average, and past results.
|
Regression to the mean vs gambler's fallacy
|
The key is that we don't have any information that will help us with the next event (gambler's fallacy), because the next event isn't dependent on the previous event. We can make a reasonable guess ab
|
Regression to the mean vs gambler's fallacy
The key is that we don't have any information that will help us with the next event (gambler's fallacy), because the next event isn't dependent on the previous event. We can make a reasonable guess about how a series of trials will go. This reasonable guess is the average aka our expected mean result. So when we watch a deviation in the mean trend back toward the mean, over time/trials, then we witnessing a regression to the mean.
As you can see regression to the mean is an observed series of actions, it isn't a predictor. As more trials are conducted things will more closely approximate a normal/Gaussian distribution. This means that I'm not making any assumptions or guess on what the next result will be. Using the law of large numbers I can theorize that even though things might be trending one way currently, over time things will balance themselves out. When they do balance themselves out the result set has regressed to the mean. It is important to note here that we aren't saying that future trials are dependent on past results. I'm merely observing a change in the balance of the data.
The gambler's fallacy as I understand it is more immediate in it's goals and focuses on prediction of future events. This tracks with what a gambler desires. Typically games of chance are tilted against the gambler over the long term, so a gambler wants to know what the next trial will be because they want to capitalize on this knowledge. This leads the gambler to falsely assume that the next trial is dependent on the previous trial. This can lead to neutral choices like:
The last five times the roulette wheel landed on black, so therefore next time I'm betting big on red.
Or the choice can be self-serving:
I've gotten a full house the last 5 hands, so I'm going to bet big because I'm on a winning streak and can't lose.
So as you can see there are few key differences:
Regression to the mean doesn't assume that independent trials are dependent like the gambler's fallacy.
Regression to the mean is applied over a large amount of data/trials, where the gambler's fallacy is concerned with the next trial.
Regression to the mean describes what has already taken place. Gambler's fallacy attempts to predict the future based on an expected average, and past results.
|
Regression to the mean vs gambler's fallacy
The key is that we don't have any information that will help us with the next event (gambler's fallacy), because the next event isn't dependent on the previous event. We can make a reasonable guess ab
|
6,243
|
Regression to the mean vs gambler's fallacy
|
Are students with higher grades who score worse on retest cheaters?
The question received a substantial edit since the last of six answers.
The edited question contains an example of regression to the mean in the context
of student scores on a $100$ question true-false test and an retest for the
top performers on an equivalent test. The retest shows substantially more average scores for the group of top performers
on the first test. What's going on? Were the students cheating the first time?
No, it is important to control for regression to the mean. Test performance for multiple choice tests is a combination of luck in guessing and ability/knowledge.
Some portion of the top performers' scores was due to good luck, which was not necessarily
repeatable the second time.
Or should they just stay away from the roulette wheel?
Let's first assume that no skill at all was involved, that the student's were just flipping (fair)
coins to determine their answers. What's the expected score? Well, each answer has independently a
$50\%$ chance of being the correct one, so we expect $50\%$ of $100$ or a score of $50$.
But, that's an expected value. Some will do better merely by chance.
The probability of scoring at least $60\%$ correctly according
to the binomial distribution is approximately $2.8\%$. So, in a group of $3000$ students, the
expected number of students to get a grade of $60%$ or better is $85$.
Now let's assume indeed there were $85$ students with a score of $60\%$ or better and retest them.
What's the expected score on retest under the same coin-flipping method? Its still $50\%$ of $100$!
What's the probability that a student being retested in this manner will score above $60\%$?
It's still $2.8\%$! So we should expect only $2$ of the $85$ ($2.8\% \cdot 85$) to score at least $60\%$ on retest.
Under this setup it is a fallacy to assume an expected score on retest different from the expected
score on the first test -- they are both $50\%$ of $100$. The gambler's fallacy would be to assume that
the good luck of the high scoring students is more likely to be balanced out by bad luck on retest.
Under this fallacy, you'd bet on the expected retest scores to be below $50$. The hot-handed fallacy
(here) would be to assume that the good luck of the high scoring students is more likely to continue
and bet on the expected retest scores to be above $50$.
Lucky coins and lucky flips
Reality is a bit more complicated. Let's update our model. First, it doesn't matter what the actual answers are
if we are just flipping coins, so let's just score by number of heads. So far, the model is equivalent.
Now let's assume $1000$ coins are biased to be heads with probability of $55\%$ (good coins $G$),
$1000$ coins are biased to be heads with probability of $45\%$ (bad coins $B$), and $1000$ have equal probability of being
heads or tails (fair coins $F$) and randomly distribute these.
This is analogous to assuming higher and lower ability/knowledge under the test taking example, but it is easier to reason
correctly about inanimate objects.
The expected score is $(55 \cdot 1000 + 45 \cdot 1000 + 50 \cdot 1000)/3000 = 50$ for any student given the random distribution. So,
the expected score for the first test has not changed.
Now, the probability of scoring at least $60\%$ correctly, again using the binomial distribution is $18.3\%$ for good coins,
$0.2\%$ for bad coins, and of course $2.8\%$ still for the fair coins. The probability of scoring at least $60\%$ is, since an
equal number of each type of coin was randomly distributed, the average of these, or $7.1\%$. The expected number of students
scoring at least $60\%$ correctly is $21$.
Now, if we do indeed have $21$ scoring at least $60\%$ correctly under this setup of biased coins, what's the expected score on retest?
Not $50\%$ of $100$ anymore! Now you can work it out with Bayes theorem, but since we used equal size groups the probability of having a
type of coin given a outcome is (here) proportional to the probability of the outcome given the type of coin. In other words, there is
a $86\% = 18.3\%/(18.3\% + 0.2\% + 2.8\%)$ chance that those scoring at least 60% had a good coin, $1\% = 0.2\%/(18.3\% + 0.2\% + 2.8\%)$ had a bad coin,
and $13\%$ had a fair coin. The expected value of scores on retest is therefore $86\% \cdot 55 + 1\% \cdot 45 + 13\% \cdot 50 = 54.25$ out of $100$. This is lower than
actual scores of the first round, at least $60$, but higher than the expected value of scores before the first round, $50$.
So even when some coins are better than others, randomness in the coin flips means that selecting the top performers from a test will still exhibit some regression to the mean in a retest.
In this modified model, hot-handedness is no longer an outright fallacy -- scoring better in the first round does mean a higher probability
of having a good coin! However, gambler's fallacy is still a fallacy -- those who experienced good luck cannot be expected to be compensated
with bad luck on retest.
|
Regression to the mean vs gambler's fallacy
|
Are students with higher grades who score worse on retest cheaters?
The question received a substantial edit since the last of six answers.
The edited question contains an example of regression to the
|
Regression to the mean vs gambler's fallacy
Are students with higher grades who score worse on retest cheaters?
The question received a substantial edit since the last of six answers.
The edited question contains an example of regression to the mean in the context
of student scores on a $100$ question true-false test and an retest for the
top performers on an equivalent test. The retest shows substantially more average scores for the group of top performers
on the first test. What's going on? Were the students cheating the first time?
No, it is important to control for regression to the mean. Test performance for multiple choice tests is a combination of luck in guessing and ability/knowledge.
Some portion of the top performers' scores was due to good luck, which was not necessarily
repeatable the second time.
Or should they just stay away from the roulette wheel?
Let's first assume that no skill at all was involved, that the student's were just flipping (fair)
coins to determine their answers. What's the expected score? Well, each answer has independently a
$50\%$ chance of being the correct one, so we expect $50\%$ of $100$ or a score of $50$.
But, that's an expected value. Some will do better merely by chance.
The probability of scoring at least $60\%$ correctly according
to the binomial distribution is approximately $2.8\%$. So, in a group of $3000$ students, the
expected number of students to get a grade of $60%$ or better is $85$.
Now let's assume indeed there were $85$ students with a score of $60\%$ or better and retest them.
What's the expected score on retest under the same coin-flipping method? Its still $50\%$ of $100$!
What's the probability that a student being retested in this manner will score above $60\%$?
It's still $2.8\%$! So we should expect only $2$ of the $85$ ($2.8\% \cdot 85$) to score at least $60\%$ on retest.
Under this setup it is a fallacy to assume an expected score on retest different from the expected
score on the first test -- they are both $50\%$ of $100$. The gambler's fallacy would be to assume that
the good luck of the high scoring students is more likely to be balanced out by bad luck on retest.
Under this fallacy, you'd bet on the expected retest scores to be below $50$. The hot-handed fallacy
(here) would be to assume that the good luck of the high scoring students is more likely to continue
and bet on the expected retest scores to be above $50$.
Lucky coins and lucky flips
Reality is a bit more complicated. Let's update our model. First, it doesn't matter what the actual answers are
if we are just flipping coins, so let's just score by number of heads. So far, the model is equivalent.
Now let's assume $1000$ coins are biased to be heads with probability of $55\%$ (good coins $G$),
$1000$ coins are biased to be heads with probability of $45\%$ (bad coins $B$), and $1000$ have equal probability of being
heads or tails (fair coins $F$) and randomly distribute these.
This is analogous to assuming higher and lower ability/knowledge under the test taking example, but it is easier to reason
correctly about inanimate objects.
The expected score is $(55 \cdot 1000 + 45 \cdot 1000 + 50 \cdot 1000)/3000 = 50$ for any student given the random distribution. So,
the expected score for the first test has not changed.
Now, the probability of scoring at least $60\%$ correctly, again using the binomial distribution is $18.3\%$ for good coins,
$0.2\%$ for bad coins, and of course $2.8\%$ still for the fair coins. The probability of scoring at least $60\%$ is, since an
equal number of each type of coin was randomly distributed, the average of these, or $7.1\%$. The expected number of students
scoring at least $60\%$ correctly is $21$.
Now, if we do indeed have $21$ scoring at least $60\%$ correctly under this setup of biased coins, what's the expected score on retest?
Not $50\%$ of $100$ anymore! Now you can work it out with Bayes theorem, but since we used equal size groups the probability of having a
type of coin given a outcome is (here) proportional to the probability of the outcome given the type of coin. In other words, there is
a $86\% = 18.3\%/(18.3\% + 0.2\% + 2.8\%)$ chance that those scoring at least 60% had a good coin, $1\% = 0.2\%/(18.3\% + 0.2\% + 2.8\%)$ had a bad coin,
and $13\%$ had a fair coin. The expected value of scores on retest is therefore $86\% \cdot 55 + 1\% \cdot 45 + 13\% \cdot 50 = 54.25$ out of $100$. This is lower than
actual scores of the first round, at least $60$, but higher than the expected value of scores before the first round, $50$.
So even when some coins are better than others, randomness in the coin flips means that selecting the top performers from a test will still exhibit some regression to the mean in a retest.
In this modified model, hot-handedness is no longer an outright fallacy -- scoring better in the first round does mean a higher probability
of having a good coin! However, gambler's fallacy is still a fallacy -- those who experienced good luck cannot be expected to be compensated
with bad luck on retest.
|
Regression to the mean vs gambler's fallacy
Are students with higher grades who score worse on retest cheaters?
The question received a substantial edit since the last of six answers.
The edited question contains an example of regression to the
|
6,244
|
Regression to the mean vs gambler's fallacy
|
According to the gambler's fallacy shouldn't it be expected the same
probability for the scoring and not necessarily more likely close to 50?
No. You trapped in Gambler's fallacy.
Assuming large enough number of question asked in the second time, the ratio of their success will still remain the same for high scorers from the first test. Your expectation that second test's average would be as high as their previous test for high scorers from the first test, sequence of random events, is a Gambler's fallacy itself. Because you expected that the difference between frequent events should balanced out, so that that second test should averaged high too. Meaning, "if they average 80 in the previous test, they should average close to 80 in the second test" is a gambler's fallacy itself. There is no law of averages but regression to the mean is there.
For example, in coin-toss, the difference between number of head and tails will increase over time, not balanced out, that's the fallacy.
See blog post Understanding the empirical law of large numbers and the gambler's fallacy
|
Regression to the mean vs gambler's fallacy
|
According to the gambler's fallacy shouldn't it be expected the same
probability for the scoring and not necessarily more likely close to 50?
No. You trapped in Gambler's fallacy.
Assuming large enou
|
Regression to the mean vs gambler's fallacy
According to the gambler's fallacy shouldn't it be expected the same
probability for the scoring and not necessarily more likely close to 50?
No. You trapped in Gambler's fallacy.
Assuming large enough number of question asked in the second time, the ratio of their success will still remain the same for high scorers from the first test. Your expectation that second test's average would be as high as their previous test for high scorers from the first test, sequence of random events, is a Gambler's fallacy itself. Because you expected that the difference between frequent events should balanced out, so that that second test should averaged high too. Meaning, "if they average 80 in the previous test, they should average close to 80 in the second test" is a gambler's fallacy itself. There is no law of averages but regression to the mean is there.
For example, in coin-toss, the difference between number of head and tails will increase over time, not balanced out, that's the fallacy.
See blog post Understanding the empirical law of large numbers and the gambler's fallacy
|
Regression to the mean vs gambler's fallacy
According to the gambler's fallacy shouldn't it be expected the same
probability for the scoring and not necessarily more likely close to 50?
No. You trapped in Gambler's fallacy.
Assuming large enou
|
6,245
|
Regression to the mean vs gambler's fallacy
|
I could be wrong but I have always thought the difference to be in the assumption of independence.
In the Gambler's fallacy the issue is the misunderstanding of independence. Sure over some large N number of coin tosses you will be around a 50-50 split, but if by chance you are not then the thought that your next T tosses will help even out the odds is wrong because there each coin toss is independent of the previous.
Regression towards the mean is, where I see it used, some idea that draws are dependent on previous draws or a previous calculated average/values. For example let use NBA shooting percentage. If player A has made on average 40% of his shots during his career and starts off a new year by shooting 70% in his first 5 games its reasonable to think that he will regress to the mean of his career average. There are dependent factors that can and will influence his play: hot/cold streaks, teammate play, confidence, and the simple fact that if he were to maintain 70% shooting for the year he would absolutely annihilate multiple records that are simply impossible physical feats (under the current performance abilities of professional basket ball players). As you play more games your shooting percentage will likely drop closer to your career average.
|
Regression to the mean vs gambler's fallacy
|
I could be wrong but I have always thought the difference to be in the assumption of independence.
In the Gambler's fallacy the issue is the misunderstanding of independence. Sure over some large N n
|
Regression to the mean vs gambler's fallacy
I could be wrong but I have always thought the difference to be in the assumption of independence.
In the Gambler's fallacy the issue is the misunderstanding of independence. Sure over some large N number of coin tosses you will be around a 50-50 split, but if by chance you are not then the thought that your next T tosses will help even out the odds is wrong because there each coin toss is independent of the previous.
Regression towards the mean is, where I see it used, some idea that draws are dependent on previous draws or a previous calculated average/values. For example let use NBA shooting percentage. If player A has made on average 40% of his shots during his career and starts off a new year by shooting 70% in his first 5 games its reasonable to think that he will regress to the mean of his career average. There are dependent factors that can and will influence his play: hot/cold streaks, teammate play, confidence, and the simple fact that if he were to maintain 70% shooting for the year he would absolutely annihilate multiple records that are simply impossible physical feats (under the current performance abilities of professional basket ball players). As you play more games your shooting percentage will likely drop closer to your career average.
|
Regression to the mean vs gambler's fallacy
I could be wrong but I have always thought the difference to be in the assumption of independence.
In the Gambler's fallacy the issue is the misunderstanding of independence. Sure over some large N n
|
6,246
|
Regression to the mean vs gambler's fallacy
|
Thanks your answers I think I could understand the difference between the Regression to the mean and Gambler's fallacy. Even more, I built a database to help me illustrate in the "real" case.
I built this situation: I collected 1000 students and I put them to do a test randomly answering questions .
The test score ranges from 01 to 05. As they are randomly answering questions, so each score has a 20% chance of being achieved. So for the first test the number of students with a score 05 should be something close to 200
(1.1) $1000*0,20$
(1.2) $200$
I Had 196 students with score 05 which is very close to the expected 200 students.
So I put those 196 students repeat the test is exepected 39 students with score 05.
(2.1) $196*0,20$
(2.2) $39$
Well, according to the result I got 42 students which is within the expected.
For those who got score 05 I put them to repeat the test and so and forth...
Therefore, the expected numbers were:
Expected RETEST 03
(3.1) $42*0,20$
(3.2) $8$
(3.3) Outcomes (8)
Expected RETEST 04
(4.1) $8*0,20$
(4.2) $1,2$
(4.3) Outcomes (2)
Expected RETEST 05
(4.1) $2*0,20$
(4.2) $0,1$
(4.3) Outcomes (0)
If I'm expecting for a student who gets score 05 four times I shall to face the probability of $0,20^4$, i.e, 1,2 student per 1000. However If I expect for a student who gets score 05 five times I should have at least 3.500 samples in order to get 1,12 student with score 05 in all tests
(5.1.) $0,20^5 = 0,00032$
(5.2.) $0,00032 * 3500 = 1.2$
Therefore the probability of the one student gets score 05 in the all 05 tests has nothing to do with his last score, I mean, I must not calculate the probability on the each test singly. I must look for those 05 tests like one event and calculate the probability for that event.
|
Regression to the mean vs gambler's fallacy
|
Thanks your answers I think I could understand the difference between the Regression to the mean and Gambler's fallacy. Even more, I built a database to help me illustrate in the "real" case.
I built
|
Regression to the mean vs gambler's fallacy
Thanks your answers I think I could understand the difference between the Regression to the mean and Gambler's fallacy. Even more, I built a database to help me illustrate in the "real" case.
I built this situation: I collected 1000 students and I put them to do a test randomly answering questions .
The test score ranges from 01 to 05. As they are randomly answering questions, so each score has a 20% chance of being achieved. So for the first test the number of students with a score 05 should be something close to 200
(1.1) $1000*0,20$
(1.2) $200$
I Had 196 students with score 05 which is very close to the expected 200 students.
So I put those 196 students repeat the test is exepected 39 students with score 05.
(2.1) $196*0,20$
(2.2) $39$
Well, according to the result I got 42 students which is within the expected.
For those who got score 05 I put them to repeat the test and so and forth...
Therefore, the expected numbers were:
Expected RETEST 03
(3.1) $42*0,20$
(3.2) $8$
(3.3) Outcomes (8)
Expected RETEST 04
(4.1) $8*0,20$
(4.2) $1,2$
(4.3) Outcomes (2)
Expected RETEST 05
(4.1) $2*0,20$
(4.2) $0,1$
(4.3) Outcomes (0)
If I'm expecting for a student who gets score 05 four times I shall to face the probability of $0,20^4$, i.e, 1,2 student per 1000. However If I expect for a student who gets score 05 five times I should have at least 3.500 samples in order to get 1,12 student with score 05 in all tests
(5.1.) $0,20^5 = 0,00032$
(5.2.) $0,00032 * 3500 = 1.2$
Therefore the probability of the one student gets score 05 in the all 05 tests has nothing to do with his last score, I mean, I must not calculate the probability on the each test singly. I must look for those 05 tests like one event and calculate the probability for that event.
|
Regression to the mean vs gambler's fallacy
Thanks your answers I think I could understand the difference between the Regression to the mean and Gambler's fallacy. Even more, I built a database to help me illustrate in the "real" case.
I built
|
6,247
|
Regression to the mean vs gambler's fallacy
|
They are saying the same thing. You were mostly confused because no single experiment in the coin flip example has extreme result (H/T 50/50). Change it to "flipping ten fair coins at the same time in every experiment", and gamblers want to get all of them right. Then an extreme measurement would be that you happen to see all of them are heads.
Gambler fallacy:
Treat each gamble outcome (coin flipping result) as IID. If you already know the distribution those IID shares, then the next prediction should come directly from the known distribution and has nothing to do with historical (or future) results (aka other IID).
Regression to the mean:
Treat each test outcome as IID (since the student is assumed to be guessing randomly and have no real skill). If you already know the distribution those IID shares, then the next prediction comes directly from the known distribution and has nothing to do with historical (or future) results (aka other IID) (exactly as before up to here). But, by CLT, if you observed extreme values in one measurement (e.g by chance you were only sampling the top 10% students from the first test), you should know the result from your next observation/measurement will still be generated from the known distribution (and thus more likely to be closer to the mean than staying at the extreme).
So fundamentally, they both say the next measurement will come from the distribution instead of past results.
|
Regression to the mean vs gambler's fallacy
|
They are saying the same thing. You were mostly confused because no single experiment in the coin flip example has extreme result (H/T 50/50). Change it to "flipping ten fair coins at the same time in
|
Regression to the mean vs gambler's fallacy
They are saying the same thing. You were mostly confused because no single experiment in the coin flip example has extreme result (H/T 50/50). Change it to "flipping ten fair coins at the same time in every experiment", and gamblers want to get all of them right. Then an extreme measurement would be that you happen to see all of them are heads.
Gambler fallacy:
Treat each gamble outcome (coin flipping result) as IID. If you already know the distribution those IID shares, then the next prediction should come directly from the known distribution and has nothing to do with historical (or future) results (aka other IID).
Regression to the mean:
Treat each test outcome as IID (since the student is assumed to be guessing randomly and have no real skill). If you already know the distribution those IID shares, then the next prediction comes directly from the known distribution and has nothing to do with historical (or future) results (aka other IID) (exactly as before up to here). But, by CLT, if you observed extreme values in one measurement (e.g by chance you were only sampling the top 10% students from the first test), you should know the result from your next observation/measurement will still be generated from the known distribution (and thus more likely to be closer to the mean than staying at the extreme).
So fundamentally, they both say the next measurement will come from the distribution instead of past results.
|
Regression to the mean vs gambler's fallacy
They are saying the same thing. You were mostly confused because no single experiment in the coin flip example has extreme result (H/T 50/50). Change it to "flipping ten fair coins at the same time in
|
6,248
|
Regression to the mean vs gambler's fallacy
|
Let X and Y be two i.i.d. uniform random variables on [0,1]. Suppose we observe them one after another.
Gambler's Fallacy:
P( Y | X ) != P( Y )
This is, of course, nonsense because X and Y are independent.
Regression to the mean:
P( Y < X | X = 1) != P( Y < X )
This is true: LHS is 1, LHS < 1
|
Regression to the mean vs gambler's fallacy
|
Let X and Y be two i.i.d. uniform random variables on [0,1]. Suppose we observe them one after another.
Gambler's Fallacy:
P( Y | X ) != P( Y )
This is, of course, nonsense because X and Y are indepe
|
Regression to the mean vs gambler's fallacy
Let X and Y be two i.i.d. uniform random variables on [0,1]. Suppose we observe them one after another.
Gambler's Fallacy:
P( Y | X ) != P( Y )
This is, of course, nonsense because X and Y are independent.
Regression to the mean:
P( Y < X | X = 1) != P( Y < X )
This is true: LHS is 1, LHS < 1
|
Regression to the mean vs gambler's fallacy
Let X and Y be two i.i.d. uniform random variables on [0,1]. Suppose we observe them one after another.
Gambler's Fallacy:
P( Y | X ) != P( Y )
This is, of course, nonsense because X and Y are indepe
|
6,249
|
Regression to the mean vs gambler's fallacy
|
Regression to the mean is basically just a special case (or corollary) of the Gambler's fallacy. The confusion easily arises from looking at the wrong variable.
Gambler's fallacy rule advises: the best prediction of the next event is the expected value, the history does not matter.
Example: you have 5 tails in a row, the best prediction for the next toss is still 50/50.
Regression to the mean advises: given an expected value, if we observe an outcome that deviates from it, we should expect the next outcome to be closer to the expected value. Basically, this is a special case of the Gambler's fallacy advice. Example: you have 5 tails in a row, the chances of that are 1/32; the best prediction for the next toss is still 50/50 (or 1/2), which is regression to the mean for the odds (1/32 -> 1/2)
Note that regression to the mean rule is usually more useful in the context of performance, where the chances are distributed more finely. Given an average skill X, if you performed at a level X+10 this time, chances are the next time you'll perform closer to your true mean, which is still X.
|
Regression to the mean vs gambler's fallacy
|
Regression to the mean is basically just a special case (or corollary) of the Gambler's fallacy. The confusion easily arises from looking at the wrong variable.
Gambler's fallacy rule advises: the bes
|
Regression to the mean vs gambler's fallacy
Regression to the mean is basically just a special case (or corollary) of the Gambler's fallacy. The confusion easily arises from looking at the wrong variable.
Gambler's fallacy rule advises: the best prediction of the next event is the expected value, the history does not matter.
Example: you have 5 tails in a row, the best prediction for the next toss is still 50/50.
Regression to the mean advises: given an expected value, if we observe an outcome that deviates from it, we should expect the next outcome to be closer to the expected value. Basically, this is a special case of the Gambler's fallacy advice. Example: you have 5 tails in a row, the chances of that are 1/32; the best prediction for the next toss is still 50/50 (or 1/2), which is regression to the mean for the odds (1/32 -> 1/2)
Note that regression to the mean rule is usually more useful in the context of performance, where the chances are distributed more finely. Given an average skill X, if you performed at a level X+10 this time, chances are the next time you'll perform closer to your true mean, which is still X.
|
Regression to the mean vs gambler's fallacy
Regression to the mean is basically just a special case (or corollary) of the Gambler's fallacy. The confusion easily arises from looking at the wrong variable.
Gambler's fallacy rule advises: the bes
|
6,250
|
Regression to the mean vs gambler's fallacy
|
Iβm going to try to simplify.
After flipping 10 heads;
Gamblerβs fallacy says that the next flip is more likely to be tails.
Regression to the mean says the next flip is 50/50, BUT the following series of tosses should go back to an even distribution.
In other words: RTTM isnβt making a specific occurrence prediction.
Did I get that right?
|
Regression to the mean vs gambler's fallacy
|
Iβm going to try to simplify.
After flipping 10 heads;
Gamblerβs fallacy says that the next flip is more likely to be tails.
Regression to the mean says the next flip is 50/50, BUT the following seri
|
Regression to the mean vs gambler's fallacy
Iβm going to try to simplify.
After flipping 10 heads;
Gamblerβs fallacy says that the next flip is more likely to be tails.
Regression to the mean says the next flip is 50/50, BUT the following series of tosses should go back to an even distribution.
In other words: RTTM isnβt making a specific occurrence prediction.
Did I get that right?
|
Regression to the mean vs gambler's fallacy
Iβm going to try to simplify.
After flipping 10 heads;
Gamblerβs fallacy says that the next flip is more likely to be tails.
Regression to the mean says the next flip is 50/50, BUT the following seri
|
6,251
|
Regression to the mean vs gambler's fallacy
|
A random walk will depart from the starting point increasingly as a measure of distance in time and decreasingly so in proportion to the total distance traveled. There is no controversy therein. For example, gambling on coin tosses will exaggerate the total amount won or lost with time, but the relative amount will tend to 50-50.
I wonder how one eliminates bias on a test one is supposed to answer randomly, perhaps by asking questions like
"What tastes more like bacon, 5 or 7?
A: 5
B: 7"
I suppose the correct answers should be randomized as well.
In the real world, students who get 90% or better on an actual science test might average 87% on the next one due to randomness of performance. That is something that has to be considered when analyzing the meaning of outcomes of an experiment, one has to be careful not to forget that the classification itself is arbitrary, and that the population isn't static.
|
Regression to the mean vs gambler's fallacy
|
A random walk will depart from the starting point increasingly as a measure of distance in time and decreasingly so in proportion to the total distance traveled. There is no controversy therein. For e
|
Regression to the mean vs gambler's fallacy
A random walk will depart from the starting point increasingly as a measure of distance in time and decreasingly so in proportion to the total distance traveled. There is no controversy therein. For example, gambling on coin tosses will exaggerate the total amount won or lost with time, but the relative amount will tend to 50-50.
I wonder how one eliminates bias on a test one is supposed to answer randomly, perhaps by asking questions like
"What tastes more like bacon, 5 or 7?
A: 5
B: 7"
I suppose the correct answers should be randomized as well.
In the real world, students who get 90% or better on an actual science test might average 87% on the next one due to randomness of performance. That is something that has to be considered when analyzing the meaning of outcomes of an experiment, one has to be careful not to forget that the classification itself is arbitrary, and that the population isn't static.
|
Regression to the mean vs gambler's fallacy
A random walk will depart from the starting point increasingly as a measure of distance in time and decreasingly so in proportion to the total distance traveled. There is no controversy therein. For e
|
6,252
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df})}$?
|
Georges Monette and I introduced the GVIF in the paper "Generalized collinearity diagnostics," JASA 87:178-183, 1992 (link). As we explained, the GVIF represents the squared ratio of hypervolumes of the joint-confidence ellipsoid for a subset of coefficients to the "utopian" ellipsoid that would be obtained if the regressors in this subset were uncorrelated with regressors in the complementary subset. In the case of a single coefficient, this specializes to the usual VIF. To make GVIFs comparable across dimensions, we suggested using GVIF^(1/(2*Df)), where Df is the number of coefficients in the subset. In effect, this reduces the GVIF to a linear measure, and for the VIF, where Df = 1, is proportional to the inflation due to collinearity in the confidence interval for the coefficient.
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df}
|
Georges Monette and I introduced the GVIF in the paper "Generalized collinearity diagnostics," JASA 87:178-183, 1992 (link). As we explained, the GVIF represents the squared ratio of hypervolumes of t
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df})}$?
Georges Monette and I introduced the GVIF in the paper "Generalized collinearity diagnostics," JASA 87:178-183, 1992 (link). As we explained, the GVIF represents the squared ratio of hypervolumes of the joint-confidence ellipsoid for a subset of coefficients to the "utopian" ellipsoid that would be obtained if the regressors in this subset were uncorrelated with regressors in the complementary subset. In the case of a single coefficient, this specializes to the usual VIF. To make GVIFs comparable across dimensions, we suggested using GVIF^(1/(2*Df)), where Df is the number of coefficients in the subset. In effect, this reduces the GVIF to a linear measure, and for the VIF, where Df = 1, is proportional to the inflation due to collinearity in the confidence interval for the coefficient.
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df}
Georges Monette and I introduced the GVIF in the paper "Generalized collinearity diagnostics," JASA 87:178-183, 1992 (link). As we explained, the GVIF represents the squared ratio of hypervolumes of t
|
6,253
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df})}$?
|
I ran into exactly the same question and tried to work my way through. See my detailed answer below.
First of all, I found 4 options producing similar VIF values in R:
β’ corvif command from the AED package,
β’ vif command from the car package,
β’ vif command from the rms package,
β’ vif command from the DAAG package.
Using these commands on a set of predictors not including any factors / categorical variables or polynomial terms is strait forward. All three commands produce the same numerical output even though the corvif command from the AED package labels the results as GVIF.
However, typically, GVIF only comes into play for factors and polynomial variables. Variables which require more than 1 coefficient and thus more than 1 degree of freedom are typically evaluated using the GVIF. For one-coefficient terms VIF equals GVIF.
Thus, you may apply standard rules of thumb on whether collinearity may be a problem, such as a 3, 5 or 10 threshold. However, some caution could (should) be applied (see: http://www.nkd-group.com/ghdash/mba555/PDF/VIF%20article.pdf).
In case of multi-coefficient terms, as for e.g. categorical predictors, the 4 packages produce different outputs. The vif commands from the rms and DAAG packages produce VIF values, whereas the other two produce GVIF values.
Let us have a look at VIF values from the rms and DAAG packages first:
TNAP ICE RegB RegC RegD RegE
1.994 2.195 3.074 3.435 2.907 2.680
TNAP and ICE are continuous predictors and Reg is a categorical variable presented by the dummies RegB to RegE. In this case RegA is the baseline. All VIF values are rather moderate and usually nothing to worry about. The problem with this result is, that it is affected by the baseline of the categorical variable. In order to be sure of not having a VIF value above an acceptable level, it would be necessary to redo this analysis for every level of the categorical variable being the baseline. In this case five times.
Applying the corvif command from the AED package or vif command from the car package, GVIF values are produced:
| GVIF | Df | GVIF^(1/2Df) |
TNAP | 1.993964 | 1 | 1.412078 |
ICE | 2.195035 | 1 | 1.481565 |
Reg | 55.511089 | 5 | 1.494301 |
The GVIF is calculated for sets of related regressors such as a for a set of dummy regressors. For the two continuous variables TNAP and ICE this is the same as the VIF values before. For the categorical variable Reg, we now get one very high GVIF value, even though the VIF values for the single levels of the categorical variable were all moderate (as shown above).
However, the interpretation is different. For the two continuous variables, $GVIF^{(1/(2 \times Df))}$ (which is basically the square root of the VIF/GVIF value as DF = 1) is the proportional change of the standard error and confidence interval of their coefficients due to the level of collinearity. The $GVIF^{(1/(2 \times Df))}$ value of the categorical variable is a similar measure for the reduction in precision of the coefficients' estimation due to collinearity (even though not ready for quoting also look at http://socserv2.socsci.mcmaster.ca/jfox/papers/linear-models-problems.pdf).
If we then simply apply the same standard rules of thumb for $GVIF^{(1/(2 \times Df))}$ values as recommended in literature for the VIF, we simply need to square $GVIF^{(1/(2 \times Df))}$.
Reading through all the forum posts, short notes in the web and scientific papers, it seems that there is quite some confusion going on. In peer reviewed papers, I found the values for $GVIF^{(1/(2 \times Df))}$ ignored and the same standard rules suggested for the VIF are applied to the GVIF values. In another paper, GVIF values of close to 100 are excepted because of a reasonably small $GVIF^{(1/(2 \times Df))}$ (due to a high DF). The rule of $GVIF^{(1/(2 \times Df))} < 2$ is applied in some publications, which would equal to an ordinary VIF of 4 for one-coefficient variables.
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df}
|
I ran into exactly the same question and tried to work my way through. See my detailed answer below.
First of all, I found 4 options producing similar VIF values in R:
β’ corvif command from the AED
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df})}$?
I ran into exactly the same question and tried to work my way through. See my detailed answer below.
First of all, I found 4 options producing similar VIF values in R:
β’ corvif command from the AED package,
β’ vif command from the car package,
β’ vif command from the rms package,
β’ vif command from the DAAG package.
Using these commands on a set of predictors not including any factors / categorical variables or polynomial terms is strait forward. All three commands produce the same numerical output even though the corvif command from the AED package labels the results as GVIF.
However, typically, GVIF only comes into play for factors and polynomial variables. Variables which require more than 1 coefficient and thus more than 1 degree of freedom are typically evaluated using the GVIF. For one-coefficient terms VIF equals GVIF.
Thus, you may apply standard rules of thumb on whether collinearity may be a problem, such as a 3, 5 or 10 threshold. However, some caution could (should) be applied (see: http://www.nkd-group.com/ghdash/mba555/PDF/VIF%20article.pdf).
In case of multi-coefficient terms, as for e.g. categorical predictors, the 4 packages produce different outputs. The vif commands from the rms and DAAG packages produce VIF values, whereas the other two produce GVIF values.
Let us have a look at VIF values from the rms and DAAG packages first:
TNAP ICE RegB RegC RegD RegE
1.994 2.195 3.074 3.435 2.907 2.680
TNAP and ICE are continuous predictors and Reg is a categorical variable presented by the dummies RegB to RegE. In this case RegA is the baseline. All VIF values are rather moderate and usually nothing to worry about. The problem with this result is, that it is affected by the baseline of the categorical variable. In order to be sure of not having a VIF value above an acceptable level, it would be necessary to redo this analysis for every level of the categorical variable being the baseline. In this case five times.
Applying the corvif command from the AED package or vif command from the car package, GVIF values are produced:
| GVIF | Df | GVIF^(1/2Df) |
TNAP | 1.993964 | 1 | 1.412078 |
ICE | 2.195035 | 1 | 1.481565 |
Reg | 55.511089 | 5 | 1.494301 |
The GVIF is calculated for sets of related regressors such as a for a set of dummy regressors. For the two continuous variables TNAP and ICE this is the same as the VIF values before. For the categorical variable Reg, we now get one very high GVIF value, even though the VIF values for the single levels of the categorical variable were all moderate (as shown above).
However, the interpretation is different. For the two continuous variables, $GVIF^{(1/(2 \times Df))}$ (which is basically the square root of the VIF/GVIF value as DF = 1) is the proportional change of the standard error and confidence interval of their coefficients due to the level of collinearity. The $GVIF^{(1/(2 \times Df))}$ value of the categorical variable is a similar measure for the reduction in precision of the coefficients' estimation due to collinearity (even though not ready for quoting also look at http://socserv2.socsci.mcmaster.ca/jfox/papers/linear-models-problems.pdf).
If we then simply apply the same standard rules of thumb for $GVIF^{(1/(2 \times Df))}$ values as recommended in literature for the VIF, we simply need to square $GVIF^{(1/(2 \times Df))}$.
Reading through all the forum posts, short notes in the web and scientific papers, it seems that there is quite some confusion going on. In peer reviewed papers, I found the values for $GVIF^{(1/(2 \times Df))}$ ignored and the same standard rules suggested for the VIF are applied to the GVIF values. In another paper, GVIF values of close to 100 are excepted because of a reasonably small $GVIF^{(1/(2 \times Df))}$ (due to a high DF). The rule of $GVIF^{(1/(2 \times Df))} < 2$ is applied in some publications, which would equal to an ordinary VIF of 4 for one-coefficient variables.
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df}
I ran into exactly the same question and tried to work my way through. See my detailed answer below.
First of all, I found 4 options producing similar VIF values in R:
β’ corvif command from the AED
|
6,254
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df})}$?
|
Fox & Monette (original citation for GVIF, GVIF^1/2df) suggest taking GVIF to the power of 1/2df makes the value of the GVIF comparable across different number of parameters. "It is analagous to taking the square root of the usual variance-inflation factor" ( from An R and S-Plus Companion to Applied Regression by John Fox). So yes, squaring it and applying the usual VIF "rule of thumb" seems reasonable.
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df}
|
Fox & Monette (original citation for GVIF, GVIF^1/2df) suggest taking GVIF to the power of 1/2df makes the value of the GVIF comparable across different number of parameters. "It is analagous to takin
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df})}$?
Fox & Monette (original citation for GVIF, GVIF^1/2df) suggest taking GVIF to the power of 1/2df makes the value of the GVIF comparable across different number of parameters. "It is analagous to taking the square root of the usual variance-inflation factor" ( from An R and S-Plus Companion to Applied Regression by John Fox). So yes, squaring it and applying the usual VIF "rule of thumb" seems reasonable.
|
Which variance inflation factor should I be using: $\text{GVIF}$ or $\text{GVIF}^{1/(2\cdot\text{df}
Fox & Monette (original citation for GVIF, GVIF^1/2df) suggest taking GVIF to the power of 1/2df makes the value of the GVIF comparable across different number of parameters. "It is analagous to takin
|
6,255
|
Looking for a good and complete probability and statistics book
|
If you are searching for proofs, I have been working for some time on a free stats textbook that collects lots of proofs of elementary and less elementary facts that are difficult to find in probability and statistics books (because they are scattered here and there). You can have a look at it at http://www.statlect.com/
|
Looking for a good and complete probability and statistics book
|
If you are searching for proofs, I have been working for some time on a free stats textbook that collects lots of proofs of elementary and less elementary facts that are difficult to find in probabili
|
Looking for a good and complete probability and statistics book
If you are searching for proofs, I have been working for some time on a free stats textbook that collects lots of proofs of elementary and less elementary facts that are difficult to find in probability and statistics books (because they are scattered here and there). You can have a look at it at http://www.statlect.com/
|
Looking for a good and complete probability and statistics book
If you are searching for proofs, I have been working for some time on a free stats textbook that collects lots of proofs of elementary and less elementary facts that are difficult to find in probabili
|
6,256
|
Looking for a good and complete probability and statistics book
|
If you want to read probability as a story, read the best book ever by Feller. I am also guessing that you do not want to go to the level of measure theoretic definition of probabilities which has specialized books. another beginner level book is from Ross. Other specialized applications have specialized books. so more information will gather better suggestions.
|
Looking for a good and complete probability and statistics book
|
If you want to read probability as a story, read the best book ever by Feller. I am also guessing that you do not want to go to the level of measure theoretic definition of probabilities which has spe
|
Looking for a good and complete probability and statistics book
If you want to read probability as a story, read the best book ever by Feller. I am also guessing that you do not want to go to the level of measure theoretic definition of probabilities which has specialized books. another beginner level book is from Ross. Other specialized applications have specialized books. so more information will gather better suggestions.
|
Looking for a good and complete probability and statistics book
If you want to read probability as a story, read the best book ever by Feller. I am also guessing that you do not want to go to the level of measure theoretic definition of probabilities which has spe
|
6,257
|
Looking for a good and complete probability and statistics book
|
I would recommend two books not mentioned, as well as several already mentioned.
The first is E.T. Jaynes "Probability: The Language of Science." It is polemic and he is a very partisan author, but it is very good.
The second is Leonard Jimmie Savage's "The Foundations of Statistics." You will probably be very surprised when you first start reading it as you will not expect it to go the route it goes.
Both are writing foundational work in Bayesian probability and Bayesian statistics. The above works are non-Bayesian.
Both books are completely contained and self-sufficient. Indeed, they build from the foundation upward. Both approach it axiomatically.
|
Looking for a good and complete probability and statistics book
|
I would recommend two books not mentioned, as well as several already mentioned.
The first is E.T. Jaynes "Probability: The Language of Science." It is polemic and he is a very partisan author, but i
|
Looking for a good and complete probability and statistics book
I would recommend two books not mentioned, as well as several already mentioned.
The first is E.T. Jaynes "Probability: The Language of Science." It is polemic and he is a very partisan author, but it is very good.
The second is Leonard Jimmie Savage's "The Foundations of Statistics." You will probably be very surprised when you first start reading it as you will not expect it to go the route it goes.
Both are writing foundational work in Bayesian probability and Bayesian statistics. The above works are non-Bayesian.
Both books are completely contained and self-sufficient. Indeed, they build from the foundation upward. Both approach it axiomatically.
|
Looking for a good and complete probability and statistics book
I would recommend two books not mentioned, as well as several already mentioned.
The first is E.T. Jaynes "Probability: The Language of Science." It is polemic and he is a very partisan author, but i
|
6,258
|
Looking for a good and complete probability and statistics book
|
Finding a single, comprehensive book will be very difficult. If you're asking because you want to do some self-study, get a couple of used texts instead of a single new one. You can get classics for $3-10 dollars if you look around online.
Feller's "Introduction to Probability" is great for its completeness and expository style, but I don't like the exercises much. And the exposition would not make it so good for a reference. He tends to have a lot of long examples, which is great for fostering understanding, and not so great for looking things up.
I enjoyed Allan Gut's "An Intermediate Course in Probability". There is some overlap with Feller, but it goes into greater depth on those topics. He covers the various transformations, order statistics (which, if I recall, Feller only does by example).
Ross' Introduction to Probability Models is pretty comprehensive, but it is very example oriented. Again, that is not my favorite style (I'd rather they saved those examples for exercises with hints, and kept them out of the main flow), but if it works for you, I can recommend it.
You might as well consider Cacoullos' "Exercises in Probability" and Mosteller's "50 Challenging Exercises in Probability".
|
Looking for a good and complete probability and statistics book
|
Finding a single, comprehensive book will be very difficult. If you're asking because you want to do some self-study, get a couple of used texts instead of a single new one. You can get classics for
|
Looking for a good and complete probability and statistics book
Finding a single, comprehensive book will be very difficult. If you're asking because you want to do some self-study, get a couple of used texts instead of a single new one. You can get classics for $3-10 dollars if you look around online.
Feller's "Introduction to Probability" is great for its completeness and expository style, but I don't like the exercises much. And the exposition would not make it so good for a reference. He tends to have a lot of long examples, which is great for fostering understanding, and not so great for looking things up.
I enjoyed Allan Gut's "An Intermediate Course in Probability". There is some overlap with Feller, but it goes into greater depth on those topics. He covers the various transformations, order statistics (which, if I recall, Feller only does by example).
Ross' Introduction to Probability Models is pretty comprehensive, but it is very example oriented. Again, that is not my favorite style (I'd rather they saved those examples for exercises with hints, and kept them out of the main flow), but if it works for you, I can recommend it.
You might as well consider Cacoullos' "Exercises in Probability" and Mosteller's "50 Challenging Exercises in Probability".
|
Looking for a good and complete probability and statistics book
Finding a single, comprehensive book will be very difficult. If you're asking because you want to do some self-study, get a couple of used texts instead of a single new one. You can get classics for
|
6,259
|
Looking for a good and complete probability and statistics book
|
For the probability side I like Probability and Random Processes by Grimmett & Stirzaker. It has a nice way of giving intuitive explanations whilst still being fairly rigorous and providing some proofs at least.
For the Statistics side I've had Theory of Statistics by Schervish on my wish list for a while now but not got around to buying it, so I can only say I've heard good things about it...it's supposed to be a graduate level introduction so possibly more rigorous than the other Schervish book you mention.
|
Looking for a good and complete probability and statistics book
|
For the probability side I like Probability and Random Processes by Grimmett & Stirzaker. It has a nice way of giving intuitive explanations whilst still being fairly rigorous and providing some proo
|
Looking for a good and complete probability and statistics book
For the probability side I like Probability and Random Processes by Grimmett & Stirzaker. It has a nice way of giving intuitive explanations whilst still being fairly rigorous and providing some proofs at least.
For the Statistics side I've had Theory of Statistics by Schervish on my wish list for a while now but not got around to buying it, so I can only say I've heard good things about it...it's supposed to be a graduate level introduction so possibly more rigorous than the other Schervish book you mention.
|
Looking for a good and complete probability and statistics book
For the probability side I like Probability and Random Processes by Grimmett & Stirzaker. It has a nice way of giving intuitive explanations whilst still being fairly rigorous and providing some proo
|
6,260
|
Looking for a good and complete probability and statistics book
|
I recommend Probability Theory and Mathematical Statistics by Marek Fisz, because:
It contains most of the common proof, but without making the book too difficult as an introduction book
It is quite theoretical, but still contain enough well-designed examples to illustrate points
Exercises are meaningful. Some of them are more advanced famous
results
|
Looking for a good and complete probability and statistics book
|
I recommend Probability Theory and Mathematical Statistics by Marek Fisz, because:
It contains most of the common proof, but without making the book too difficult as an introduction book
It is quite
|
Looking for a good and complete probability and statistics book
I recommend Probability Theory and Mathematical Statistics by Marek Fisz, because:
It contains most of the common proof, but without making the book too difficult as an introduction book
It is quite theoretical, but still contain enough well-designed examples to illustrate points
Exercises are meaningful. Some of them are more advanced famous
results
|
Looking for a good and complete probability and statistics book
I recommend Probability Theory and Mathematical Statistics by Marek Fisz, because:
It contains most of the common proof, but without making the book too difficult as an introduction book
It is quite
|
6,261
|
Looking for a good and complete probability and statistics book
|
As noted by many others, there is no single good text for any scientific subject simply because any given authors or group of authors use a set of assumptions regarding the readers' level of understanding and diversity of knowns and unknowns in the user's brain. Said this, my suggestion for someone knows basics in calculus and linear algebra is to begin with the "modern mathematical statistics with applications" by Devore and Berk.
|
Looking for a good and complete probability and statistics book
|
As noted by many others, there is no single good text for any scientific subject simply because any given authors or group of authors use a set of assumptions regarding the readers' level of understan
|
Looking for a good and complete probability and statistics book
As noted by many others, there is no single good text for any scientific subject simply because any given authors or group of authors use a set of assumptions regarding the readers' level of understanding and diversity of knowns and unknowns in the user's brain. Said this, my suggestion for someone knows basics in calculus and linear algebra is to begin with the "modern mathematical statistics with applications" by Devore and Berk.
|
Looking for a good and complete probability and statistics book
As noted by many others, there is no single good text for any scientific subject simply because any given authors or group of authors use a set of assumptions regarding the readers' level of understan
|
6,262
|
Looking for a good and complete probability and statistics book
|
You can read Student's Solutions Guide for Introduction to Probability, Statistics, and Random Processes book. It provides clear examples and exercises with "additional questions" at the end of each chapter which really help improve learning and there is a logical progression from one idea to another.
|
Looking for a good and complete probability and statistics book
|
You can read Student's Solutions Guide for Introduction to Probability, Statistics, and Random Processes book. It provides clear examples and exercises with "additional questions" at the end of each c
|
Looking for a good and complete probability and statistics book
You can read Student's Solutions Guide for Introduction to Probability, Statistics, and Random Processes book. It provides clear examples and exercises with "additional questions" at the end of each chapter which really help improve learning and there is a logical progression from one idea to another.
|
Looking for a good and complete probability and statistics book
You can read Student's Solutions Guide for Introduction to Probability, Statistics, and Random Processes book. It provides clear examples and exercises with "additional questions" at the end of each c
|
6,263
|
What does the logit value actually mean?
|
The logit $L$ of a probability $p$ is defined as
$$L = \ln\frac{p}{1-p}$$
The term $\frac{p}{1-p}$ is called odds. The natural logarithm of the odds is known as log-odds or logit.
The inverse function is
$$p = \frac{1}{1+e^{-L}}$$
Probabilities range from zero to one, i.e., $p\in[0,1]$, whereas logits can be any real number ($\mathbb{R}$, from minus infinity to infinity; $L\in (-\infty,\infty)$).
A probability of $0.5$ corresponds to a logit of $0$. Negative logit values indicate probabilities smaller than $0.5$, positive logits indicate probabilities greater than $0.5$. The relationship is symmetrical: Logits of $-0.2$ and $0.2$ correspond to probabilities of $0.45$ and $0.55$, respectively. Note: The absolute distance to $0.5$ is identical for both probabilities.
This graph shows the non-linear relationship between logits and probabilities:
The answer to your question is: There is a probability of about $0.55$ that a case belongs to group B.
|
What does the logit value actually mean?
|
The logit $L$ of a probability $p$ is defined as
$$L = \ln\frac{p}{1-p}$$
The term $\frac{p}{1-p}$ is called odds. The natural logarithm of the odds is known as log-odds or logit.
The inverse function
|
What does the logit value actually mean?
The logit $L$ of a probability $p$ is defined as
$$L = \ln\frac{p}{1-p}$$
The term $\frac{p}{1-p}$ is called odds. The natural logarithm of the odds is known as log-odds or logit.
The inverse function is
$$p = \frac{1}{1+e^{-L}}$$
Probabilities range from zero to one, i.e., $p\in[0,1]$, whereas logits can be any real number ($\mathbb{R}$, from minus infinity to infinity; $L\in (-\infty,\infty)$).
A probability of $0.5$ corresponds to a logit of $0$. Negative logit values indicate probabilities smaller than $0.5$, positive logits indicate probabilities greater than $0.5$. The relationship is symmetrical: Logits of $-0.2$ and $0.2$ correspond to probabilities of $0.45$ and $0.55$, respectively. Note: The absolute distance to $0.5$ is identical for both probabilities.
This graph shows the non-linear relationship between logits and probabilities:
The answer to your question is: There is a probability of about $0.55$ that a case belongs to group B.
|
What does the logit value actually mean?
The logit $L$ of a probability $p$ is defined as
$$L = \ln\frac{p}{1-p}$$
The term $\frac{p}{1-p}$ is called odds. The natural logarithm of the odds is known as log-odds or logit.
The inverse function
|
6,264
|
What does the logit value actually mean?
|
To add a more modern (but not very deep) perspective, consider how it's used in deep learning (ha, pun intended...):
logit is referred to the output of a function (e.g. a Neural Net) just before it's normalization (which we usually use the softmax). This is also known as the code. So if for label $y$ we have score $f_y(x)$ then the logit is:
$$ logit = \log \left( \frac{ e^{f_y(x)} }{Z} \right) = score = f_y(x)$$
Where $Z$ is the standard partition function.
By the way, this is all over the place in the pytorch and tensorflow documentation.
So you can interpret it as:
the (unnormalized) score for a label or (functional confidence) for a specific class/label.
One of the many references: https://stackoverflow.com/questions/41455101/what-is-the-meaning-of-the-word-logits-in-tensorflow
|
What does the logit value actually mean?
|
To add a more modern (but not very deep) perspective, consider how it's used in deep learning (ha, pun intended...):
logit is referred to the output of a function (e.g. a Neural Net) just before it's
|
What does the logit value actually mean?
To add a more modern (but not very deep) perspective, consider how it's used in deep learning (ha, pun intended...):
logit is referred to the output of a function (e.g. a Neural Net) just before it's normalization (which we usually use the softmax). This is also known as the code. So if for label $y$ we have score $f_y(x)$ then the logit is:
$$ logit = \log \left( \frac{ e^{f_y(x)} }{Z} \right) = score = f_y(x)$$
Where $Z$ is the standard partition function.
By the way, this is all over the place in the pytorch and tensorflow documentation.
So you can interpret it as:
the (unnormalized) score for a label or (functional confidence) for a specific class/label.
One of the many references: https://stackoverflow.com/questions/41455101/what-is-the-meaning-of-the-word-logits-in-tensorflow
|
What does the logit value actually mean?
To add a more modern (but not very deep) perspective, consider how it's used in deep learning (ha, pun intended...):
logit is referred to the output of a function (e.g. a Neural Net) just before it's
|
6,265
|
What does the logit value actually mean?
|
Could you maybe specify your model and give a screenshot of the output, then I could give you an detailed answer, but as a first try.... you may want to check out also the following examples on these websites:
http://www.ats.ucla.edu/stat/stata/seminars/stata_logistic/default.htm
http://www.ats.ucla.edu/stat/stata/dae/logit.htm
http://www.ats.ucla.edu/stat/stata/faq/oratio.htm
http://www.ats.ucla.edu/stat/mult_pkg/faq/general/odds_ratio.htm
so if the coefficient is 0.2 it depends on the variable, I guess you have a dummy, which is e.g. 0 for group B and 1 for group A?
odds ratio is given by:
$OR = e^b$
so in your case: $e^{70.20}$
This would be the odds ratio of your group variable corresponding to your reference group.
|
What does the logit value actually mean?
|
Could you maybe specify your model and give a screenshot of the output, then I could give you an detailed answer, but as a first try.... you may want to check out also the following examples on these
|
What does the logit value actually mean?
Could you maybe specify your model and give a screenshot of the output, then I could give you an detailed answer, but as a first try.... you may want to check out also the following examples on these websites:
http://www.ats.ucla.edu/stat/stata/seminars/stata_logistic/default.htm
http://www.ats.ucla.edu/stat/stata/dae/logit.htm
http://www.ats.ucla.edu/stat/stata/faq/oratio.htm
http://www.ats.ucla.edu/stat/mult_pkg/faq/general/odds_ratio.htm
so if the coefficient is 0.2 it depends on the variable, I guess you have a dummy, which is e.g. 0 for group B and 1 for group A?
odds ratio is given by:
$OR = e^b$
so in your case: $e^{70.20}$
This would be the odds ratio of your group variable corresponding to your reference group.
|
What does the logit value actually mean?
Could you maybe specify your model and give a screenshot of the output, then I could give you an detailed answer, but as a first try.... you may want to check out also the following examples on these
|
6,266
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
|
For machine learning, I've predominantly seen the usage OP describes, but I've also encountered lots of confusion coming from this usage.
Historically, I guess what happened (at least in my field, analytical chemistry) is that as models became more complex, at some point people noticed that independent data is needed for verification and validation purposes (in our terminology, almost all testing that is routinely done with models would be considered part of verification which in turn is part of the much wider task of method validation). Enter the validation set and methods such as cross validation (with its original purpose of estimating generalization error).
Later, people started to use generalization error estimates from what we call internal verification/validation such as cross validation or a random split to refine/optimize their models. Enter hyperparameter tuning.
Again, it was realized that estimating generalization error of the refined model needs independent data. And a new name was needed as well, as the usage of "validation set" for the data used for refining/optimizing had already been established. Enter the test set.
Thus we have the situation where a so-called validation set is used for model development/optimization/refining and is therefore not suitable any more for the purpose of model verification and validation.
Someone with e.g. an analytical chemistry (or engineering) background will certainly refer to the data they use/acquire for method validation purposes as their validation data* - and that is correct usage of the terms in these fields.
*(unless they know the different use of terminology in machine learning, in which case they'd usually explain what exactly they are talking about).
Personally, in order to avoid the ongoing confusion that comes from this clash of terminology between fields, I've moved to using "optimization data/set" for the data used for hyperparameter tuning (Andrew Ng's development set is fine with me as well) and "verification data/set" for the final independent test data (the testing we typically do is actually verification rather than validation, so that avoids another common mistake: the testing we typically do is not even close to a full method validation in analytical chemistry, and it's good to be aware of that)
Another strategy I find helpful to avoid confusion is moving from splitting into 3 data sets back to splitting into training and verification data, and then describing the hyperparameter tuning as part of the training procedure which happens to include another split into data used to fit the model parameters and data used to optimize the hyperparameters.
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
|
For machine learning, I've predominantly seen the usage OP describes, but I've also encountered lots of confusion coming from this usage.
Historically, I guess what happened (at least in my field, an
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
For machine learning, I've predominantly seen the usage OP describes, but I've also encountered lots of confusion coming from this usage.
Historically, I guess what happened (at least in my field, analytical chemistry) is that as models became more complex, at some point people noticed that independent data is needed for verification and validation purposes (in our terminology, almost all testing that is routinely done with models would be considered part of verification which in turn is part of the much wider task of method validation). Enter the validation set and methods such as cross validation (with its original purpose of estimating generalization error).
Later, people started to use generalization error estimates from what we call internal verification/validation such as cross validation or a random split to refine/optimize their models. Enter hyperparameter tuning.
Again, it was realized that estimating generalization error of the refined model needs independent data. And a new name was needed as well, as the usage of "validation set" for the data used for refining/optimizing had already been established. Enter the test set.
Thus we have the situation where a so-called validation set is used for model development/optimization/refining and is therefore not suitable any more for the purpose of model verification and validation.
Someone with e.g. an analytical chemistry (or engineering) background will certainly refer to the data they use/acquire for method validation purposes as their validation data* - and that is correct usage of the terms in these fields.
*(unless they know the different use of terminology in machine learning, in which case they'd usually explain what exactly they are talking about).
Personally, in order to avoid the ongoing confusion that comes from this clash of terminology between fields, I've moved to using "optimization data/set" for the data used for hyperparameter tuning (Andrew Ng's development set is fine with me as well) and "verification data/set" for the final independent test data (the testing we typically do is actually verification rather than validation, so that avoids another common mistake: the testing we typically do is not even close to a full method validation in analytical chemistry, and it's good to be aware of that)
Another strategy I find helpful to avoid confusion is moving from splitting into 3 data sets back to splitting into training and verification data, and then describing the hyperparameter tuning as part of the training procedure which happens to include another split into data used to fit the model parameters and data used to optimize the hyperparameters.
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
For machine learning, I've predominantly seen the usage OP describes, but I've also encountered lots of confusion coming from this usage.
Historically, I guess what happened (at least in my field, an
|
6,267
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
|
Apparently, the terms are used ambiguously, but I always seen them used as that there are three (or more) sets of data: train set used for training the model, validation set for assessing the performance of the model when tuning it, and held-out test set that you use at the very end to assess the performance of the model. These names are used in Google's Machine Learning Crash Course, the Deep Learning with Python book by FranΓ§ois Chollet, the Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow book by AurΓ©lien GΓ©ron, The Elements of Statistical Learning by Trevor Hastie, Robert Tibshirani, and Jerome Friedman, and a number of other books.
If you find this naming convention confusing, you can, as Andrew Ng, use the train/dev/test naming, where the dev set is used for development.
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
|
Apparently, the terms are used ambiguously, but I always seen them used as that there are three (or more) sets of data: train set used for training the model, validation set for assessing the performa
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
Apparently, the terms are used ambiguously, but I always seen them used as that there are three (or more) sets of data: train set used for training the model, validation set for assessing the performance of the model when tuning it, and held-out test set that you use at the very end to assess the performance of the model. These names are used in Google's Machine Learning Crash Course, the Deep Learning with Python book by FranΓ§ois Chollet, the Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow book by AurΓ©lien GΓ©ron, The Elements of Statistical Learning by Trevor Hastie, Robert Tibshirani, and Jerome Friedman, and a number of other books.
If you find this naming convention confusing, you can, as Andrew Ng, use the train/dev/test naming, where the dev set is used for development.
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
Apparently, the terms are used ambiguously, but I always seen them used as that there are three (or more) sets of data: train set used for training the model, validation set for assessing the performa
|
6,268
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
|
I was taught that you have a train/test split for tuning then you have a validation set to 'validate' that you haven't overfitted your test split. If you have a small dataset then you just have your train/test split, I would never call it a train/validation split because I think of validation as the final step to 'validate' all of your results, whereas test is to 'test' your model on unseen data. But you could easily flip them and it's all the same!
I have noticed the terms used back and forth but it doesn't really matter what you call it as long as everyone is on the same page.
EDIT after some digging:
Your usage is the correct usage although it is known that the flip side is frequently used (although incorrectly). Wiki even has a section reviewing this discrepancy.
Pure conjecture but I think it most likely stems from this:
Where if you just have a simple split it is train/test and this split used to be a standard way to tune for simple models so the 'test' set was everything.
And to add further to this, it seems if you only do 5 fold cross validation then you are doing 5 train sets and 5 test sets. BUT if you then add a third holdout set then you now have 5 train sets, 5 validation sets, and 1 test set.
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
|
I was taught that you have a train/test split for tuning then you have a validation set to 'validate' that you haven't overfitted your test split. If you have a small dataset then you just have your
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
I was taught that you have a train/test split for tuning then you have a validation set to 'validate' that you haven't overfitted your test split. If you have a small dataset then you just have your train/test split, I would never call it a train/validation split because I think of validation as the final step to 'validate' all of your results, whereas test is to 'test' your model on unseen data. But you could easily flip them and it's all the same!
I have noticed the terms used back and forth but it doesn't really matter what you call it as long as everyone is on the same page.
EDIT after some digging:
Your usage is the correct usage although it is known that the flip side is frequently used (although incorrectly). Wiki even has a section reviewing this discrepancy.
Pure conjecture but I think it most likely stems from this:
Where if you just have a simple split it is train/test and this split used to be a standard way to tune for simple models so the 'test' set was everything.
And to add further to this, it seems if you only do 5 fold cross validation then you are doing 5 train sets and 5 test sets. BUT if you then add a third holdout set then you now have 5 train sets, 5 validation sets, and 1 test set.
|
Why is it that my colleagues and I learned opposite definitions for test and validation sets?
I was taught that you have a train/test split for tuning then you have a validation set to 'validate' that you haven't overfitted your test split. If you have a small dataset then you just have your
|
6,269
|
What is the relationship between orthogonal, correlation and independence?
|
Independence is a statistical concept. Two random variables $X$ and $Y$ are statistically independent if their joint distribution is the product of the marginal distributions, i.e.
$$
f(x, y) = f(x) f(y)
$$
if each variable has a density $f$, or more generally
$$
F(x, y) = F(x) F(y)
$$
where $F$ denotes each random variable's cumulative distribution function.
Correlation is a weaker but related statistical concept. The (Pearson) correlation of two random variables is the expectancy of the product of the standardized variables, i.e.
$$
\newcommand{\E}{\mathbf E}
\rho = \E \left [
\frac{X - \E[X]}{\sqrt{\E[(X - \E[X])^2]}}
\frac{Y - \E[Y]}{\sqrt{\E[(Y - \E[Y])^2]}}
\right ].
$$
The variables are uncorrelated if $\rho = 0$. It can be shown that two random variables that are independent are necessarily uncorrelated, but not vice versa.
Orthogonality is a concept that originated in geometry, and was generalized in linear algebra and related fields of mathematics. In linear algebra, orthogonality of two vectors $u$ and $v$ is defined in inner product spaces, i.e. vector spaces with an inner product $\langle u, v \rangle$, as the condition that
$$
\langle u, v \rangle = 0.
$$
The inner product can be defined in different ways (resulting in different inner product spaces). If the vectors are given in the form of sequences of numbers, $u = (u_1, u_2, \ldots u_n)$, then a typical choice is the dot product, $\langle u, v \rangle = \sum_{i = 1}^n u_i v_i$.
Orthogonality is therefore not a statistical concept per se, and the confusion you observe is likely due to different translations of the linear algebra concept to statistics:
a) Formally, a space of random variables can be considered as a vector space. It is then possible to define an inner product in that space, in different ways. One common choice is to define it as the covariance:
$$
\langle X, Y \rangle = \mathrm{cov} (X, Y)
= \E [ (X - \E[X]) (Y - \E[Y]) ].
$$
Since the correlation of two random variables is zero exactly if the covariance is zero, according to this definition uncorrelatedness is the same as orthogonality. (Another possibility is to define the inner product of random variables simply as the expectancy of the product.)
b) Not all the variables we consider in statistics are random variables. Especially in linear regression, we have independent variables which are not considered random but predefined. Independent variables are usually given as sequences of numbers, for which orthogonality is naturally defined by the dot product (see above). We can then investigate the statistical consequences of regression models where the independent variables are or are not orthogonal. In this context, orthogonality does not have a specifically statistical definition, and even more: it does not apply to random variables.
Addition responding to Silverfish's comment: Orthogonality is not only relevant with respect to the original regressors but also with respect to contrasts, because (sets of) simple contrasts (specified by contrast vectors) can be seen as transformations of the design matrix, i.e. the set of independent variables, into a new set of independent variables. Orthogonality for contrasts is defined via the dot product. If the original regressors are mutually orthogonal and one applies orthogonal contrasts, the new regressors are mutually orthogonal, too. This ensures that the set of contrasts can be seen as describing a decomposition of variance, e.g. into main effects and interactions, the idea underlying ANOVA.
Since according to variant a), uncorrelatedness and orthogonality are just different names for the same thing, in my opinion it is best to avoid using the term in that sense. If we want to talk about uncorrelatedness of random variables, let's just say so and not complicate matters by using another word with a different background and different implications. This also frees up the term orthogonality to be used according to variant b), which is highly useful especially in discussing multiple regression. And the other way around, we should avoid applying the term correlation to independent variables, since they are not random variables.
Rodgers et al.'s presentation is largely in line with this view, especially as they understand orthogonality to be distinct from uncorrelatedness. However, they do apply the term correlation to non-random variables (sequences of numbers). This only makes sense statistically with respect to the sample correlation coefficient $r$. I would still recommend to avoid this use of the term, unless the number sequence is considered as a sequence of realizations of a random variable.
I've scattered links to the answers to the two related questions throughout the above text, which should help you put them into the context of this answer.
|
What is the relationship between orthogonal, correlation and independence?
|
Independence is a statistical concept. Two random variables $X$ and $Y$ are statistically independent if their joint distribution is the product of the marginal distributions, i.e.
$$
f(x, y) = f(x) f
|
What is the relationship between orthogonal, correlation and independence?
Independence is a statistical concept. Two random variables $X$ and $Y$ are statistically independent if their joint distribution is the product of the marginal distributions, i.e.
$$
f(x, y) = f(x) f(y)
$$
if each variable has a density $f$, or more generally
$$
F(x, y) = F(x) F(y)
$$
where $F$ denotes each random variable's cumulative distribution function.
Correlation is a weaker but related statistical concept. The (Pearson) correlation of two random variables is the expectancy of the product of the standardized variables, i.e.
$$
\newcommand{\E}{\mathbf E}
\rho = \E \left [
\frac{X - \E[X]}{\sqrt{\E[(X - \E[X])^2]}}
\frac{Y - \E[Y]}{\sqrt{\E[(Y - \E[Y])^2]}}
\right ].
$$
The variables are uncorrelated if $\rho = 0$. It can be shown that two random variables that are independent are necessarily uncorrelated, but not vice versa.
Orthogonality is a concept that originated in geometry, and was generalized in linear algebra and related fields of mathematics. In linear algebra, orthogonality of two vectors $u$ and $v$ is defined in inner product spaces, i.e. vector spaces with an inner product $\langle u, v \rangle$, as the condition that
$$
\langle u, v \rangle = 0.
$$
The inner product can be defined in different ways (resulting in different inner product spaces). If the vectors are given in the form of sequences of numbers, $u = (u_1, u_2, \ldots u_n)$, then a typical choice is the dot product, $\langle u, v \rangle = \sum_{i = 1}^n u_i v_i$.
Orthogonality is therefore not a statistical concept per se, and the confusion you observe is likely due to different translations of the linear algebra concept to statistics:
a) Formally, a space of random variables can be considered as a vector space. It is then possible to define an inner product in that space, in different ways. One common choice is to define it as the covariance:
$$
\langle X, Y \rangle = \mathrm{cov} (X, Y)
= \E [ (X - \E[X]) (Y - \E[Y]) ].
$$
Since the correlation of two random variables is zero exactly if the covariance is zero, according to this definition uncorrelatedness is the same as orthogonality. (Another possibility is to define the inner product of random variables simply as the expectancy of the product.)
b) Not all the variables we consider in statistics are random variables. Especially in linear regression, we have independent variables which are not considered random but predefined. Independent variables are usually given as sequences of numbers, for which orthogonality is naturally defined by the dot product (see above). We can then investigate the statistical consequences of regression models where the independent variables are or are not orthogonal. In this context, orthogonality does not have a specifically statistical definition, and even more: it does not apply to random variables.
Addition responding to Silverfish's comment: Orthogonality is not only relevant with respect to the original regressors but also with respect to contrasts, because (sets of) simple contrasts (specified by contrast vectors) can be seen as transformations of the design matrix, i.e. the set of independent variables, into a new set of independent variables. Orthogonality for contrasts is defined via the dot product. If the original regressors are mutually orthogonal and one applies orthogonal contrasts, the new regressors are mutually orthogonal, too. This ensures that the set of contrasts can be seen as describing a decomposition of variance, e.g. into main effects and interactions, the idea underlying ANOVA.
Since according to variant a), uncorrelatedness and orthogonality are just different names for the same thing, in my opinion it is best to avoid using the term in that sense. If we want to talk about uncorrelatedness of random variables, let's just say so and not complicate matters by using another word with a different background and different implications. This also frees up the term orthogonality to be used according to variant b), which is highly useful especially in discussing multiple regression. And the other way around, we should avoid applying the term correlation to independent variables, since they are not random variables.
Rodgers et al.'s presentation is largely in line with this view, especially as they understand orthogonality to be distinct from uncorrelatedness. However, they do apply the term correlation to non-random variables (sequences of numbers). This only makes sense statistically with respect to the sample correlation coefficient $r$. I would still recommend to avoid this use of the term, unless the number sequence is considered as a sequence of realizations of a random variable.
I've scattered links to the answers to the two related questions throughout the above text, which should help you put them into the context of this answer.
|
What is the relationship between orthogonal, correlation and independence?
Independence is a statistical concept. Two random variables $X$ and $Y$ are statistically independent if their joint distribution is the product of the marginal distributions, i.e.
$$
f(x, y) = f(x) f
|
6,270
|
What is the relationship between orthogonal, correlation and independence?
|
Here is the relationship: If X and Y are uncorrelated, then X-E[X] is orthogonal to Y-E[Y].
Unlike that independent is a stronger concept of uncorrelated, i.e., independent will lead to uncorrelated, (non-)orthogonal and (un)correlated can happen at the same time.
I am being the TA of probability this semester, so I make a short video about Independence, Correlation, Orthogonality.
https://youtu.be/s5lCl3aQ_A4
Hope it helps.
|
What is the relationship between orthogonal, correlation and independence?
|
Here is the relationship: If X and Y are uncorrelated, then X-E[X] is orthogonal to Y-E[Y].
Unlike that independent is a stronger concept of uncorrelated, i.e., independent will lead to uncorrelated,
|
What is the relationship between orthogonal, correlation and independence?
Here is the relationship: If X and Y are uncorrelated, then X-E[X] is orthogonal to Y-E[Y].
Unlike that independent is a stronger concept of uncorrelated, i.e., independent will lead to uncorrelated, (non-)orthogonal and (un)correlated can happen at the same time.
I am being the TA of probability this semester, so I make a short video about Independence, Correlation, Orthogonality.
https://youtu.be/s5lCl3aQ_A4
Hope it helps.
|
What is the relationship between orthogonal, correlation and independence?
Here is the relationship: If X and Y are uncorrelated, then X-E[X] is orthogonal to Y-E[Y].
Unlike that independent is a stronger concept of uncorrelated, i.e., independent will lead to uncorrelated,
|
6,271
|
What is the relationship between orthogonal, correlation and independence?
|
Here is my intuitive view: Stating that x and y are uncorrelated/orthogonal are both ways of saying that knowledge of the value of x or y does not enable a prediction of the other -- x and y are independent of each other -- assuming that any relationship is linear.
The correlation coefficient provides an indication of how well knowledge of x (or y) enables us to predict y (or x). Assuming linear relationships.
In a plane, a vector along the X axis can be varied in magnitude without changing its component along the Y axis -- the X and Y axes are orthogonal and the vector along X is orthogonal to any along Y. Varying the magnitude of a vector not along X, will cause both the X and Y components to vary. The vector is no longer orthogonal to Y.
If two variables are uncorrelated they are orthogonal and if two variables are orthogonal, they are uncorrelated. Correlation and orthogonality are simply different, though equivalent -- algebraic and geometric -- ways of expressing the notion of linear independence. As an analogy, consider the solution of a pair of linear equations in two variables by plotting (geometric) and by determinants (algebraic).
With respect to the linearity assumption -- let x be time, let y be a sine function. Over one period, x and y are both orthogonal and uncorrelated using the usual means for computing both. However knowledge of x enables us to predict y precisely. Linearity is a crucial aspect of correlation and orthogonality.
Though not part of the question, I note that correlation and non-orthogonality do not equate to causality. x and y can be correlated because they both have some, possibly hidden, dependence on a third variable. Consumption of ice-cream goes up in the summer, people go to the beach more often in the summer. The two are correlated, but neither "causes" the other. See https://en.wikipedia.org/wiki/Correlation_does_not_imply_causation for more on this point.
|
What is the relationship between orthogonal, correlation and independence?
|
Here is my intuitive view: Stating that x and y are uncorrelated/orthogonal are both ways of saying that knowledge of the value of x or y does not enable a prediction of the other -- x and y are in
|
What is the relationship between orthogonal, correlation and independence?
Here is my intuitive view: Stating that x and y are uncorrelated/orthogonal are both ways of saying that knowledge of the value of x or y does not enable a prediction of the other -- x and y are independent of each other -- assuming that any relationship is linear.
The correlation coefficient provides an indication of how well knowledge of x (or y) enables us to predict y (or x). Assuming linear relationships.
In a plane, a vector along the X axis can be varied in magnitude without changing its component along the Y axis -- the X and Y axes are orthogonal and the vector along X is orthogonal to any along Y. Varying the magnitude of a vector not along X, will cause both the X and Y components to vary. The vector is no longer orthogonal to Y.
If two variables are uncorrelated they are orthogonal and if two variables are orthogonal, they are uncorrelated. Correlation and orthogonality are simply different, though equivalent -- algebraic and geometric -- ways of expressing the notion of linear independence. As an analogy, consider the solution of a pair of linear equations in two variables by plotting (geometric) and by determinants (algebraic).
With respect to the linearity assumption -- let x be time, let y be a sine function. Over one period, x and y are both orthogonal and uncorrelated using the usual means for computing both. However knowledge of x enables us to predict y precisely. Linearity is a crucial aspect of correlation and orthogonality.
Though not part of the question, I note that correlation and non-orthogonality do not equate to causality. x and y can be correlated because they both have some, possibly hidden, dependence on a third variable. Consumption of ice-cream goes up in the summer, people go to the beach more often in the summer. The two are correlated, but neither "causes" the other. See https://en.wikipedia.org/wiki/Correlation_does_not_imply_causation for more on this point.
|
What is the relationship between orthogonal, correlation and independence?
Here is my intuitive view: Stating that x and y are uncorrelated/orthogonal are both ways of saying that knowledge of the value of x or y does not enable a prediction of the other -- x and y are in
|
6,272
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
There are some strong voices in the Econometrics community against the validity of the Ljung-Box $Q$-statistic for testing for autocorrelation based on the residuals from an autoregressive model (i.e. with lagged dependent variables in the regressor matrix), see particularly Maddala (2001) "Introduction to Econometrics (3d edition), ch 6.7, and 13. 5 p 528. Maddala literally laments the widespread use of this test, and instead considers as appropriate the "Langrange Multiplier" test of Breusch and Godfrey.
Maddala's argument against the Ljung-Box test is the same as the one raised against another omnipresent autocorrelation test, the "Durbin-Watson" one: with lagged dependent variables in the regressor matrix, the test is biased in favor of maintaining the null hypothesis of "no-autocorrelation" (the Monte-Carlo results obtained in @javlacalle answer allude to this fact). Maddala also mentions the low power of the test, see for example Davies, N., & Newbold, P. (1979). Some power studies of a portmanteau test of time series model specification. Biometrika, 66(1), 153-155.
Hayashi(2000), ch. 2.10 "Testing For serial correlation", presents a unified theoretical analysis, and I believe, clarifies the matter. Hayashi starts from zero:
For the Ljung-Box $Q$-statistic to be asymptotically distributed as a chi-square, it must be the case that the process $\{z_t\}$ (whatever $z$ represents), whose sample autocorrelations we feed into the statistic is, under the null hypothesis of no autocorrelation, a martingale-difference sequence, i.e. that it satisfies
$$E(z_t \mid z_{t-1}, z_{t-2},...) = 0$$
and also it exhibits "own" conditional homoskedasticity
$$E(z^2_t \mid z_{t-1}, z_{t-2},...) = \sigma^2 >0$$
Under these conditions the Ljung-Box $Q$-statistic (which is a corrected-for-finite-samples variant of the original Box-Pierce $Q$-statistic), has asymptotically a chi-squared distribution, and its use has asymptotic justification.
Assume now that we have specified an autoregressive model (that perhaps includes also independent regressors in addition to lagged dependent variables), say
$$y_t = \mathbf x_t'\beta + \phi(L)y_t + u_t$$
where $\phi(L)$ is a polynomial in the lag operator, and we want to test for serial correlation by using the residuals of the estimation. So here $z_t \equiv \hat u_t$.
Hayashi shows that in order for the Ljung-Box $Q$-statistic based on the sample autocorrelations of the residuals, to have an asymptotic chi-square distribution under the null hypothesis of no autocorrelation, it must be the case that all regressors are "strictly exogenous" to the error term in the following sense:
$$E(\mathbf x_t\cdot u_s) = 0 ,\;\; E(y_t\cdot u_s)=0 \;\;\forall t,s$$
The "for all $t,s$" is the crucial requirement here, the one that reflects strict exogeneity. And it does not hold when lagged dependent variables exist in the regressor matrix. This is easily seen: set $s= t-1$ and then
$$E[y_t u_{t-1}] = E[(\mathbf x_t'\beta + \phi(L)y_t + u_t)u_{t-1}] =$$
$$ E[\mathbf x_t'\beta \cdot u_{t-1}]+ E[\phi(L)y_t \cdot u_{t-1}]+E[u_t \cdot u_{t-1}] \neq 0 $$
even if the $X$'s are independent of the error term, and even if the error term has no-autocorrelation: the term $E[\phi(L)y_t \cdot u_{t-1}]$ is not zero.
But this proves that the Ljung-Box $Q$ statistic is not valid in an autoregressive model, because it cannot be said to have an asymptotic chi-square distribution under the null.
Assume now that a weaker condition than strict exogeneity is satisfied, namely that
$$E(u_t \mid \mathbf x_t, \mathbf x_{t-1},...,\phi(L)y_t, u_{t-1}, u_{t-2},...) = 0$$
The strength of this condition is "inbetween" strict exogeneity and orthogonality. Under the null of no autocorrelation of the error term, this condition is "automatically" satisfied by an autoregressive model, with respect to the lagged dependent variables (for the $X$'s it must be separately assumed of course).
Then, there exists another statistic based on the residual sample autocorrelations, (not the Ljung-Box one), that does have an asymptotic chi-square distribution under the null. This other statistic can be calculated, as a convenience, by using the "auxiliary regression" route: regress the residuals $\{\hat u_t\}$ on the full regressor matrix and on past residuals (up to the lag we have used in the specification), obtain the uncentered $R^2$ from this auxilliary regression and multiply it by the sample size.
This statistic is used in what we call the "Breusch-Godfrey test for serial correlation".
It appears then that, when the regressors include lagged dependent variables (and so in all cases of autoregressive models also), the Ljung-Box test should be abandoned in favor of the Breusch-Godfrey LM test., not because "it performs worse", but because it does not possess asymptotic justification. Quite an impressive result, especially judging from the ubiquitous presence and application of the former.
UPDATE: Responding to doubts raised in the comments as to whether all the above apply also to "pure" time series models or not (i.e. without "$x$"-regressors), I have posted a detailed examination for the AR(1) model, in https://stats.stackexchange.com/a/205262/28746 .
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
There are some strong voices in the Econometrics community against the validity of the Ljung-Box $Q$-statistic for testing for autocorrelation based on the residuals from an autoregressive model (i.e.
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
There are some strong voices in the Econometrics community against the validity of the Ljung-Box $Q$-statistic for testing for autocorrelation based on the residuals from an autoregressive model (i.e. with lagged dependent variables in the regressor matrix), see particularly Maddala (2001) "Introduction to Econometrics (3d edition), ch 6.7, and 13. 5 p 528. Maddala literally laments the widespread use of this test, and instead considers as appropriate the "Langrange Multiplier" test of Breusch and Godfrey.
Maddala's argument against the Ljung-Box test is the same as the one raised against another omnipresent autocorrelation test, the "Durbin-Watson" one: with lagged dependent variables in the regressor matrix, the test is biased in favor of maintaining the null hypothesis of "no-autocorrelation" (the Monte-Carlo results obtained in @javlacalle answer allude to this fact). Maddala also mentions the low power of the test, see for example Davies, N., & Newbold, P. (1979). Some power studies of a portmanteau test of time series model specification. Biometrika, 66(1), 153-155.
Hayashi(2000), ch. 2.10 "Testing For serial correlation", presents a unified theoretical analysis, and I believe, clarifies the matter. Hayashi starts from zero:
For the Ljung-Box $Q$-statistic to be asymptotically distributed as a chi-square, it must be the case that the process $\{z_t\}$ (whatever $z$ represents), whose sample autocorrelations we feed into the statistic is, under the null hypothesis of no autocorrelation, a martingale-difference sequence, i.e. that it satisfies
$$E(z_t \mid z_{t-1}, z_{t-2},...) = 0$$
and also it exhibits "own" conditional homoskedasticity
$$E(z^2_t \mid z_{t-1}, z_{t-2},...) = \sigma^2 >0$$
Under these conditions the Ljung-Box $Q$-statistic (which is a corrected-for-finite-samples variant of the original Box-Pierce $Q$-statistic), has asymptotically a chi-squared distribution, and its use has asymptotic justification.
Assume now that we have specified an autoregressive model (that perhaps includes also independent regressors in addition to lagged dependent variables), say
$$y_t = \mathbf x_t'\beta + \phi(L)y_t + u_t$$
where $\phi(L)$ is a polynomial in the lag operator, and we want to test for serial correlation by using the residuals of the estimation. So here $z_t \equiv \hat u_t$.
Hayashi shows that in order for the Ljung-Box $Q$-statistic based on the sample autocorrelations of the residuals, to have an asymptotic chi-square distribution under the null hypothesis of no autocorrelation, it must be the case that all regressors are "strictly exogenous" to the error term in the following sense:
$$E(\mathbf x_t\cdot u_s) = 0 ,\;\; E(y_t\cdot u_s)=0 \;\;\forall t,s$$
The "for all $t,s$" is the crucial requirement here, the one that reflects strict exogeneity. And it does not hold when lagged dependent variables exist in the regressor matrix. This is easily seen: set $s= t-1$ and then
$$E[y_t u_{t-1}] = E[(\mathbf x_t'\beta + \phi(L)y_t + u_t)u_{t-1}] =$$
$$ E[\mathbf x_t'\beta \cdot u_{t-1}]+ E[\phi(L)y_t \cdot u_{t-1}]+E[u_t \cdot u_{t-1}] \neq 0 $$
even if the $X$'s are independent of the error term, and even if the error term has no-autocorrelation: the term $E[\phi(L)y_t \cdot u_{t-1}]$ is not zero.
But this proves that the Ljung-Box $Q$ statistic is not valid in an autoregressive model, because it cannot be said to have an asymptotic chi-square distribution under the null.
Assume now that a weaker condition than strict exogeneity is satisfied, namely that
$$E(u_t \mid \mathbf x_t, \mathbf x_{t-1},...,\phi(L)y_t, u_{t-1}, u_{t-2},...) = 0$$
The strength of this condition is "inbetween" strict exogeneity and orthogonality. Under the null of no autocorrelation of the error term, this condition is "automatically" satisfied by an autoregressive model, with respect to the lagged dependent variables (for the $X$'s it must be separately assumed of course).
Then, there exists another statistic based on the residual sample autocorrelations, (not the Ljung-Box one), that does have an asymptotic chi-square distribution under the null. This other statistic can be calculated, as a convenience, by using the "auxiliary regression" route: regress the residuals $\{\hat u_t\}$ on the full regressor matrix and on past residuals (up to the lag we have used in the specification), obtain the uncentered $R^2$ from this auxilliary regression and multiply it by the sample size.
This statistic is used in what we call the "Breusch-Godfrey test for serial correlation".
It appears then that, when the regressors include lagged dependent variables (and so in all cases of autoregressive models also), the Ljung-Box test should be abandoned in favor of the Breusch-Godfrey LM test., not because "it performs worse", but because it does not possess asymptotic justification. Quite an impressive result, especially judging from the ubiquitous presence and application of the former.
UPDATE: Responding to doubts raised in the comments as to whether all the above apply also to "pure" time series models or not (i.e. without "$x$"-regressors), I have posted a detailed examination for the AR(1) model, in https://stats.stackexchange.com/a/205262/28746 .
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
There are some strong voices in the Econometrics community against the validity of the Ljung-Box $Q$-statistic for testing for autocorrelation based on the residuals from an autoregressive model (i.e.
|
6,273
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
Conjecture
I don't know about any study comparing these tests. I had the suspicion that the Ljung-Box test is more appropriate in the context of time series models like ARIMA models, where the explanatory variables are lags of the dependent variables. The Breusch-Godfrey test could be more appropriate for a general regression model where the classical assumptions are met (in particular exogenous regressors).
My conjecture is that the distribution of the Breusch-Godfrey test (which relies on the residuals from a regression fitted by Ordinary Least Squares), may be affected by the fact that explanatory variables are not exogenous.
I did a small simulation exercise to check this and the results suggest the opposite: the Breusch-Godfrey test performs better than the Ljung-Box test when testing for autocorrelation in the residuals of an autoregressive model. Details and R code to reproduce or modify the exercise are given below.
Small simulation exercise
A typical application of the Ljung-Box test is to test for serial correlation in the residuals from a fitted ARIMA model. Here, I generate data from an AR(3) model and fit an AR(3) model.
The residuals satisfy the null hypothesis of no autocorrelation, therefore, we would expect uniformly distributed p-values. The null hypothesis should be rejected in a percentage of cases close to a chosen significance level, e.g. 5%.
Ljung-Box test:
## Ljung-Box test
n <- 200 # number of observations
niter <- 5000 # number of iterations
LB.pvals <- matrix(nrow=niter, ncol=4)
set.seed(123)
for (i in seq_len(niter))
{
# Generate data from an AR(3) model and store the residuals
x <- arima.sim(n, model=list(ar=c(0.6, -0.5, 0.4)))
resid <- residuals(arima(x, order=c(3,0,0)))
# Store p-value of the Ljung-Box for different lag orders
LB.pvals[i,1] <- Box.test(resid, lag=1, type="Ljung-Box")$p.value
LB.pvals[i,2] <- Box.test(resid, lag=2, type="Ljung-Box")$p.value
LB.pvals[i,3] <- Box.test(resid, lag=3, type="Ljung-Box")$p.value
LB.pvals[i,4] <- Box.test(resid, lag=4, type="Ljung-Box", fitdf=3)$p.value
}
sum(LB.pvals[,1] < 0.05)/niter
# [1] 0
sum(LB.pvals[,2] < 0.05)/niter
# [1] 0
sum(LB.pvals[,3] < 0.05)/niter
# [1] 0
sum(LB.pvals[,4] < 0.05)/niter
# [1] 0.0644
par(mfrow=c(2,2))
hist(LB.pvals[,1]); hist(LB.pvals[,2]); hist(LB.pvals[,3]); hist(LB.pvals[,4])
The results show that the null hypothesis is rejected in very rare cases. For a 5% level, the rate of rejections is much lower than 5%. The distribution of the p-values show a bias towards non-rejection of the null.
Edit
In principle fitdf=3 should be set in all cases. This will account for the degrees of freedom that are lost after fitting the AR(3) model to get the residuals. However, for lags of order lower than 4, this will lead to negative or zero degrees of freedom, rendering the test inapplicable. According to the documentation ?stats::Box.test: These tests are sometimes applied to the residuals from an ARMA(p, q) fit, in which case the references suggest a better approximation to the null-hypothesis distribution is obtained by setting fitdf = p+q, provided of course that lag > fitdf.
Breusch-Godfrey test:
## Breusch-Godfrey test
require("lmtest")
n <- 200 # number of observations
niter <- 5000 # number of iterations
BG.pvals <- matrix(nrow=niter, ncol=4)
set.seed(123)
for (i in seq_len(niter))
{
# Generate data from an AR(3) model and store the residuals
x <- arima.sim(n, model=list(ar=c(0.6, -0.5, 0.4)))
# create explanatory variables, lags of the dependent variable
Mlags <- cbind(
filter(x, c(0,1), method= "conv", sides=1),
filter(x, c(0,0,1), method= "conv", sides=1),
filter(x, c(0,0,0,1), method= "conv", sides=1))
colnames(Mlags) <- paste("lag", seq_len(ncol(Mlags)))
# store p-value of the Breusch-Godfrey test
BG.pvals[i,1] <- bgtest(x ~ 1+Mlags, order=1, type="F", fill=NA)$p.value
BG.pvals[i,2] <- bgtest(x ~ 1+Mlags, order=2, type="F", fill=NA)$p.value
BG.pvals[i,3] <- bgtest(x ~ 1+Mlags, order=3, type="F", fill=NA)$p.value
BG.pvals[i,4] <- bgtest(x ~ 1+Mlags, order=4, type="F", fill=NA)$p.value
}
sum(BG.pvals[,1] < 0.05)/niter
# [1] 0.0476
sum(BG.pvals[,2] < 0.05)/niter
# [1] 0.0438
sum(BG.pvals[,3] < 0.05)/niter
# [1] 0.047
sum(BG.pvals[,4] < 0.05)/niter
# [1] 0.0468
par(mfrow=c(2,2))
hist(BG.pvals[,1]); hist(BG.pvals[,2]); hist(BG.pvals[,3]); hist(BG.pvals[,4])
The results for the Breusch-Godfrey test look more sensible. The p-values are uniformly distributed and rejection rates are closer to the significance level (as expected under the null hypothesis).
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
Conjecture
I don't know about any study comparing these tests. I had the suspicion that the Ljung-Box test is more appropriate in the context of time series models like ARIMA models, where the explana
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
Conjecture
I don't know about any study comparing these tests. I had the suspicion that the Ljung-Box test is more appropriate in the context of time series models like ARIMA models, where the explanatory variables are lags of the dependent variables. The Breusch-Godfrey test could be more appropriate for a general regression model where the classical assumptions are met (in particular exogenous regressors).
My conjecture is that the distribution of the Breusch-Godfrey test (which relies on the residuals from a regression fitted by Ordinary Least Squares), may be affected by the fact that explanatory variables are not exogenous.
I did a small simulation exercise to check this and the results suggest the opposite: the Breusch-Godfrey test performs better than the Ljung-Box test when testing for autocorrelation in the residuals of an autoregressive model. Details and R code to reproduce or modify the exercise are given below.
Small simulation exercise
A typical application of the Ljung-Box test is to test for serial correlation in the residuals from a fitted ARIMA model. Here, I generate data from an AR(3) model and fit an AR(3) model.
The residuals satisfy the null hypothesis of no autocorrelation, therefore, we would expect uniformly distributed p-values. The null hypothesis should be rejected in a percentage of cases close to a chosen significance level, e.g. 5%.
Ljung-Box test:
## Ljung-Box test
n <- 200 # number of observations
niter <- 5000 # number of iterations
LB.pvals <- matrix(nrow=niter, ncol=4)
set.seed(123)
for (i in seq_len(niter))
{
# Generate data from an AR(3) model and store the residuals
x <- arima.sim(n, model=list(ar=c(0.6, -0.5, 0.4)))
resid <- residuals(arima(x, order=c(3,0,0)))
# Store p-value of the Ljung-Box for different lag orders
LB.pvals[i,1] <- Box.test(resid, lag=1, type="Ljung-Box")$p.value
LB.pvals[i,2] <- Box.test(resid, lag=2, type="Ljung-Box")$p.value
LB.pvals[i,3] <- Box.test(resid, lag=3, type="Ljung-Box")$p.value
LB.pvals[i,4] <- Box.test(resid, lag=4, type="Ljung-Box", fitdf=3)$p.value
}
sum(LB.pvals[,1] < 0.05)/niter
# [1] 0
sum(LB.pvals[,2] < 0.05)/niter
# [1] 0
sum(LB.pvals[,3] < 0.05)/niter
# [1] 0
sum(LB.pvals[,4] < 0.05)/niter
# [1] 0.0644
par(mfrow=c(2,2))
hist(LB.pvals[,1]); hist(LB.pvals[,2]); hist(LB.pvals[,3]); hist(LB.pvals[,4])
The results show that the null hypothesis is rejected in very rare cases. For a 5% level, the rate of rejections is much lower than 5%. The distribution of the p-values show a bias towards non-rejection of the null.
Edit
In principle fitdf=3 should be set in all cases. This will account for the degrees of freedom that are lost after fitting the AR(3) model to get the residuals. However, for lags of order lower than 4, this will lead to negative or zero degrees of freedom, rendering the test inapplicable. According to the documentation ?stats::Box.test: These tests are sometimes applied to the residuals from an ARMA(p, q) fit, in which case the references suggest a better approximation to the null-hypothesis distribution is obtained by setting fitdf = p+q, provided of course that lag > fitdf.
Breusch-Godfrey test:
## Breusch-Godfrey test
require("lmtest")
n <- 200 # number of observations
niter <- 5000 # number of iterations
BG.pvals <- matrix(nrow=niter, ncol=4)
set.seed(123)
for (i in seq_len(niter))
{
# Generate data from an AR(3) model and store the residuals
x <- arima.sim(n, model=list(ar=c(0.6, -0.5, 0.4)))
# create explanatory variables, lags of the dependent variable
Mlags <- cbind(
filter(x, c(0,1), method= "conv", sides=1),
filter(x, c(0,0,1), method= "conv", sides=1),
filter(x, c(0,0,0,1), method= "conv", sides=1))
colnames(Mlags) <- paste("lag", seq_len(ncol(Mlags)))
# store p-value of the Breusch-Godfrey test
BG.pvals[i,1] <- bgtest(x ~ 1+Mlags, order=1, type="F", fill=NA)$p.value
BG.pvals[i,2] <- bgtest(x ~ 1+Mlags, order=2, type="F", fill=NA)$p.value
BG.pvals[i,3] <- bgtest(x ~ 1+Mlags, order=3, type="F", fill=NA)$p.value
BG.pvals[i,4] <- bgtest(x ~ 1+Mlags, order=4, type="F", fill=NA)$p.value
}
sum(BG.pvals[,1] < 0.05)/niter
# [1] 0.0476
sum(BG.pvals[,2] < 0.05)/niter
# [1] 0.0438
sum(BG.pvals[,3] < 0.05)/niter
# [1] 0.047
sum(BG.pvals[,4] < 0.05)/niter
# [1] 0.0468
par(mfrow=c(2,2))
hist(BG.pvals[,1]); hist(BG.pvals[,2]); hist(BG.pvals[,3]); hist(BG.pvals[,4])
The results for the Breusch-Godfrey test look more sensible. The p-values are uniformly distributed and rejection rates are closer to the significance level (as expected under the null hypothesis).
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
Conjecture
I don't know about any study comparing these tests. I had the suspicion that the Ljung-Box test is more appropriate in the context of time series models like ARIMA models, where the explana
|
6,274
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
Greene (Econometric Analysis, 7th Edition, p. 963, section 20.7.2):
"The essential difference between the Godfrey-Breusch [GB] and the
Box-Pierce [BP] tests is the use of partial correlations (controlling
for $X$ and the other variables) in the former and simple correlations
in the latter. Under the null hypothesis, there is no autocorrelation
in $e_t$, and no correlation between $x_t$ and $e_s$ in any event, so
the two tests are asymptotically equivalent. On the other hand,
because it does not condition on $x_t$, the [BP] test is less powerful
than the [GB] test when the null hypothesis is false, as intuition
might suggest."
(I know that the question asks about Ljung-Box and the above refers to Box-Pierce, but the former is a simple refinement of the latter and hence any comparison between GB and BP would also apply to a comparison between GB and LB.)
As other answers have already explained in more rigorous fashion, Greene also suggests that there is nothing to gain (other than some computational efficiency perhaps) from using Ljung-Box versus Godfrey-Breusch but potentially much to lose (the validity of the test).
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
Greene (Econometric Analysis, 7th Edition, p. 963, section 20.7.2):
"The essential difference between the Godfrey-Breusch [GB] and the
Box-Pierce [BP] tests is the use of partial correlations (con
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
Greene (Econometric Analysis, 7th Edition, p. 963, section 20.7.2):
"The essential difference between the Godfrey-Breusch [GB] and the
Box-Pierce [BP] tests is the use of partial correlations (controlling
for $X$ and the other variables) in the former and simple correlations
in the latter. Under the null hypothesis, there is no autocorrelation
in $e_t$, and no correlation between $x_t$ and $e_s$ in any event, so
the two tests are asymptotically equivalent. On the other hand,
because it does not condition on $x_t$, the [BP] test is less powerful
than the [GB] test when the null hypothesis is false, as intuition
might suggest."
(I know that the question asks about Ljung-Box and the above refers to Box-Pierce, but the former is a simple refinement of the latter and hence any comparison between GB and BP would also apply to a comparison between GB and LB.)
As other answers have already explained in more rigorous fashion, Greene also suggests that there is nothing to gain (other than some computational efficiency perhaps) from using Ljung-Box versus Godfrey-Breusch but potentially much to lose (the validity of the test).
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
Greene (Econometric Analysis, 7th Edition, p. 963, section 20.7.2):
"The essential difference between the Godfrey-Breusch [GB] and the
Box-Pierce [BP] tests is the use of partial correlations (con
|
6,275
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
It seems that Box-Pierce and Ljung-Box tests are mainly univariate tests, but there are some assumptions behind the Breusch-Godfrey test when testing if linear structure is left behind on residuals of time series regression (MA or AR process).
Here is link to discussion:
http://www.stata.com/meeting/new-orleans13/abstracts/materials/nola13-baum.pdf
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
It seems that Box-Pierce and Ljung-Box tests are mainly univariate tests, but there are some assumptions behind the Breusch-Godfrey test when testing if linear structure is left behind on residuals of
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
It seems that Box-Pierce and Ljung-Box tests are mainly univariate tests, but there are some assumptions behind the Breusch-Godfrey test when testing if linear structure is left behind on residuals of time series regression (MA or AR process).
Here is link to discussion:
http://www.stata.com/meeting/new-orleans13/abstracts/materials/nola13-baum.pdf
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
It seems that Box-Pierce and Ljung-Box tests are mainly univariate tests, but there are some assumptions behind the Breusch-Godfrey test when testing if linear structure is left behind on residuals of
|
6,276
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
The main difference between the tests is the following:
The Breusch-Godfrey test is as Lagrange Multiplier test derived from
the (correctly specified) likelihood function (and thus from
first principles).
The Ljung-Box test is based on second moments of the residuals of a stationary process (and thus of a comparatively more ad-hoc nature).
The Breusch-Godfrey test is as Lagrange Multiplier test asymptotically equivalent to the uniformly most powerful test. Be that as it may, it is only asymptotically most powerful w.r.t. the alternative hypothesis of omitted regressors (irrespective of whether they are lagged variables or not). The strong point of the Ljung-Box test may be its power against a wide range of alternative hypotheses.
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
The main difference between the tests is the following:
The Breusch-Godfrey test is as Lagrange Multiplier test derived from
the (correctly specified) likelihood function (and thus from
first princip
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
The main difference between the tests is the following:
The Breusch-Godfrey test is as Lagrange Multiplier test derived from
the (correctly specified) likelihood function (and thus from
first principles).
The Ljung-Box test is based on second moments of the residuals of a stationary process (and thus of a comparatively more ad-hoc nature).
The Breusch-Godfrey test is as Lagrange Multiplier test asymptotically equivalent to the uniformly most powerful test. Be that as it may, it is only asymptotically most powerful w.r.t. the alternative hypothesis of omitted regressors (irrespective of whether they are lagged variables or not). The strong point of the Ljung-Box test may be its power against a wide range of alternative hypotheses.
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
The main difference between the tests is the following:
The Breusch-Godfrey test is as Lagrange Multiplier test derived from
the (correctly specified) likelihood function (and thus from
first princip
|
6,277
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
Looking further in Hayashi (2000) pp 146-147:
..when the regressors are not strictly exogenous we need to modify the
Q statistics to restore its asymptotic distribution
Basically we only have to assume that that the errors do not depend on the lagged regressors and they are conditionally homoskedastic.
Modifying the code of @javlacalle by (1) including fitdf=3 and (2) adding some more lags as seems reasonable in practice gives the following.
Ljung-Box test:
## Ljung-Box test
n <- 200 # number of observations
niter <- 5000 # number of iterations
LB.pvals <- matrix(nrow=niter, ncol=4)
set.seed(123)
for (i in seq_len(niter))
{
# Generate data from an AR(3) model and store the residuals
x <- arima.sim(n, model=list(ar=c(0.6, -0.5, 0.4)))
resid <- residuals(arima(x, order=c(3,0,0)))
# Store p-value of the Ljung-Box for different lag orders
LB.pvals[i,1] <- Box.test(resid, lag=10, fitdf=3, type="Ljung-Box")$p.value
LB.pvals[i,2] <- Box.test(resid, lag=11, fitdf=3, type="Ljung-Box")$p.value
LB.pvals[i,3] <- Box.test(resid, lag=12, fitdf=3, type="Ljung-Box")$p.value
LB.pvals[i,4] <- Box.test(resid, lag=13, fitdf=3, type="Ljung-Box")$p.value
}
sum(LB.pvals[,1] < 0.05)/niter
# [1] 0
sum(LB.pvals[,2] < 0.05)/niter
# [1] 0
sum(LB.pvals[,3] < 0.05)/niter
# [1] 0
sum(LB.pvals[,4] < 0.05)/niter
# [1] 0.0644
par(mfrow=c(2,2))
hist(LB.pvals[,1]); hist(LB.pvals[,2]); hist(LB.pvals[,3]); hist(LB.pvals[,4])
To me, it looks identical to the Breusch-Godfrey test simulation. In that case, and considering Hayashi's proof later in the book it seems that the Ljung-Box test is valid in presence of lagged dependent variables after all. I'm I doing wrong here?
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
|
Looking further in Hayashi (2000) pp 146-147:
..when the regressors are not strictly exogenous we need to modify the
Q statistics to restore its asymptotic distribution
Basically we only have to ass
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
Looking further in Hayashi (2000) pp 146-147:
..when the regressors are not strictly exogenous we need to modify the
Q statistics to restore its asymptotic distribution
Basically we only have to assume that that the errors do not depend on the lagged regressors and they are conditionally homoskedastic.
Modifying the code of @javlacalle by (1) including fitdf=3 and (2) adding some more lags as seems reasonable in practice gives the following.
Ljung-Box test:
## Ljung-Box test
n <- 200 # number of observations
niter <- 5000 # number of iterations
LB.pvals <- matrix(nrow=niter, ncol=4)
set.seed(123)
for (i in seq_len(niter))
{
# Generate data from an AR(3) model and store the residuals
x <- arima.sim(n, model=list(ar=c(0.6, -0.5, 0.4)))
resid <- residuals(arima(x, order=c(3,0,0)))
# Store p-value of the Ljung-Box for different lag orders
LB.pvals[i,1] <- Box.test(resid, lag=10, fitdf=3, type="Ljung-Box")$p.value
LB.pvals[i,2] <- Box.test(resid, lag=11, fitdf=3, type="Ljung-Box")$p.value
LB.pvals[i,3] <- Box.test(resid, lag=12, fitdf=3, type="Ljung-Box")$p.value
LB.pvals[i,4] <- Box.test(resid, lag=13, fitdf=3, type="Ljung-Box")$p.value
}
sum(LB.pvals[,1] < 0.05)/niter
# [1] 0
sum(LB.pvals[,2] < 0.05)/niter
# [1] 0
sum(LB.pvals[,3] < 0.05)/niter
# [1] 0
sum(LB.pvals[,4] < 0.05)/niter
# [1] 0.0644
par(mfrow=c(2,2))
hist(LB.pvals[,1]); hist(LB.pvals[,2]); hist(LB.pvals[,3]); hist(LB.pvals[,4])
To me, it looks identical to the Breusch-Godfrey test simulation. In that case, and considering Hayashi's proof later in the book it seems that the Ljung-Box test is valid in presence of lagged dependent variables after all. I'm I doing wrong here?
|
Testing for autocorrelation: Ljung-Box versus Breusch-Godfrey
Looking further in Hayashi (2000) pp 146-147:
..when the regressors are not strictly exogenous we need to modify the
Q statistics to restore its asymptotic distribution
Basically we only have to ass
|
6,278
|
Purpose of the link function in generalized linear model
|
A.J. Dobson pointed out the following things in her book:
Linear regression assumes that the conditional distribution of the response variable is normally distributed. Generalized linear models can have response variables with conditional distributions other than the Normal distribution β they may even be categorical rather than continuous. Thus they may not range from $-\infty$ to $+\infty$.
Relationship between the response and explanatory variables need not be of the simple linear form.
This is why we need the link function as a component of the generalized linear model. It links the mean of the dependent variable $Y_i$, which is $E(Y_i)=\mu_i$ to the linear term $x_i^T\beta$ in such a way that the range of the non-linearly transformed mean $g(\mu_i)$ ranges from $-\infty$ to $+\infty$. Thus you can actually form a linear equation
$g(\mu_i)$=$x_i^T\beta$
and use an iteratively reweighted least squares method for maximum likelihood estimation of the model parameters.
|
Purpose of the link function in generalized linear model
|
A.J. Dobson pointed out the following things in her book:
Linear regression assumes that the conditional distribution of the response variable is normally distributed. Generalized linear models can h
|
Purpose of the link function in generalized linear model
A.J. Dobson pointed out the following things in her book:
Linear regression assumes that the conditional distribution of the response variable is normally distributed. Generalized linear models can have response variables with conditional distributions other than the Normal distribution β they may even be categorical rather than continuous. Thus they may not range from $-\infty$ to $+\infty$.
Relationship between the response and explanatory variables need not be of the simple linear form.
This is why we need the link function as a component of the generalized linear model. It links the mean of the dependent variable $Y_i$, which is $E(Y_i)=\mu_i$ to the linear term $x_i^T\beta$ in such a way that the range of the non-linearly transformed mean $g(\mu_i)$ ranges from $-\infty$ to $+\infty$. Thus you can actually form a linear equation
$g(\mu_i)$=$x_i^T\beta$
and use an iteratively reweighted least squares method for maximum likelihood estimation of the model parameters.
|
Purpose of the link function in generalized linear model
A.J. Dobson pointed out the following things in her book:
Linear regression assumes that the conditional distribution of the response variable is normally distributed. Generalized linear models can h
|
6,279
|
Purpose of the link function in generalized linear model
|
It may help you to read my answer here: Difference between logit and probit models, which discusses GLiM links somewhat extensively.
The basic way of explaining this issue is laid out clearly by @BlainWaan, and Wikipedia: The actual parameter (e.g., $p$ for a binomial response--i.e., logistic regression) cannot range from negative infinity to positive infinity, but your predicted parameter will. The second big reason is that without a properly specified link, the variances of your residuals will not be constant (a required assumption for inference with an Ordinary Least Squares estimate) or handled correctly.
Another way to go at this issue is that by using the identity link (this is another way of saying / thinking about 'not using' a link function) means that you are thinking about your situation incorrectly in a way that necessarily distorts the picture of your situation that you derive from your analysis. For example, unless the true probabilities that you are trying to model (again for logistic regression situations) exist only in the middle of the range (where they are fairly linear), and the range of $X$ you are examining is centered on the point where $p=.5$, your betas will be biased and your predicted $\hat p_{x_i}$'s will be far from the true values. In addition, your inferences will be distorted as well (e.g., the type I error rate won't equal $\alpha$).
|
Purpose of the link function in generalized linear model
|
It may help you to read my answer here: Difference between logit and probit models, which discusses GLiM links somewhat extensively.
The basic way of explaining this issue is laid out clearly by @Blai
|
Purpose of the link function in generalized linear model
It may help you to read my answer here: Difference between logit and probit models, which discusses GLiM links somewhat extensively.
The basic way of explaining this issue is laid out clearly by @BlainWaan, and Wikipedia: The actual parameter (e.g., $p$ for a binomial response--i.e., logistic regression) cannot range from negative infinity to positive infinity, but your predicted parameter will. The second big reason is that without a properly specified link, the variances of your residuals will not be constant (a required assumption for inference with an Ordinary Least Squares estimate) or handled correctly.
Another way to go at this issue is that by using the identity link (this is another way of saying / thinking about 'not using' a link function) means that you are thinking about your situation incorrectly in a way that necessarily distorts the picture of your situation that you derive from your analysis. For example, unless the true probabilities that you are trying to model (again for logistic regression situations) exist only in the middle of the range (where they are fairly linear), and the range of $X$ you are examining is centered on the point where $p=.5$, your betas will be biased and your predicted $\hat p_{x_i}$'s will be far from the true values. In addition, your inferences will be distorted as well (e.g., the type I error rate won't equal $\alpha$).
|
Purpose of the link function in generalized linear model
It may help you to read my answer here: Difference between logit and probit models, which discusses GLiM links somewhat extensively.
The basic way of explaining this issue is laid out clearly by @Blai
|
6,280
|
Good methods for density plots of non-negative variables in R?
|
An alternative is the approach of Kooperberg and colleagues, based on estimating the density using splines to approximate the log-density of the data. I'll show an example using the data from @whuber's answer, which will allow for a comparison of approaches.
set.seed(17)
x <- rexp(1000)
You'll need the logspline package installed for this; install it if it is not:
install.packages("logspline")
Load the package and estimate the density using the logspline() function:
require("logspline")
m <- logspline(x)
In the following, I assume that the object d from @whuber's answer is present in the workspace.
plot(d, type="n", main="Default, truncated, and logspline densities",
xlim=c(-1, 5), ylim = c(0, 1))
polygon(density(x, kernel="gaussian", bw=h), col="#6060ff80", border=NA)
polygon(d, col="#ff606080", border=NA)
plot(m, add = TRUE, col = "red", lwd = 3, xlim = c(-0.001, max(x)))
curve(exp(-x), from=0, to=max(x), lty=2, add=TRUE)
rug(x, side = 3)
The resulting plot is shown below, with the logspline density shown by the red line
Additionally, the support for the density can be specified via arguments lbound and ubound. If we wish to assume that the density is 0 to the left of 0 and there is a discontinuity at 0, we could use lbound = 0 in the call to logspline(), for example
m2 <- logspline(x, lbound = 0)
Yielding the following density estimate (shown here with the original m logspline fit as the previous figure was already getting busy).
plot.new()
plot.window(xlim = c(-1, max(x)), ylim = c(0, 1.2))
title(main = "Logspline densities with & without a lower bound",
ylab = "Density", xlab = "x")
plot(m, col = "red", xlim = c(0, max(x)), lwd = 3, add = TRUE)
plot(m2, col = "blue", xlim = c(0, max(x)), lwd = 2, add = TRUE)
curve(exp(-x), from=0, to=max(x), lty=2, add=TRUE)
rug(x, side = 3)
axis(1)
axis(2)
box()
The resulting plot is shown below
In this case, exploiting knowledge of x results in a density estimate that doesn't tend to 0 at $x = 0$, but is similar to the standard logspline fit elsewhere over x
|
Good methods for density plots of non-negative variables in R?
|
An alternative is the approach of Kooperberg and colleagues, based on estimating the density using splines to approximate the log-density of the data. I'll show an example using the data from @whuber'
|
Good methods for density plots of non-negative variables in R?
An alternative is the approach of Kooperberg and colleagues, based on estimating the density using splines to approximate the log-density of the data. I'll show an example using the data from @whuber's answer, which will allow for a comparison of approaches.
set.seed(17)
x <- rexp(1000)
You'll need the logspline package installed for this; install it if it is not:
install.packages("logspline")
Load the package and estimate the density using the logspline() function:
require("logspline")
m <- logspline(x)
In the following, I assume that the object d from @whuber's answer is present in the workspace.
plot(d, type="n", main="Default, truncated, and logspline densities",
xlim=c(-1, 5), ylim = c(0, 1))
polygon(density(x, kernel="gaussian", bw=h), col="#6060ff80", border=NA)
polygon(d, col="#ff606080", border=NA)
plot(m, add = TRUE, col = "red", lwd = 3, xlim = c(-0.001, max(x)))
curve(exp(-x), from=0, to=max(x), lty=2, add=TRUE)
rug(x, side = 3)
The resulting plot is shown below, with the logspline density shown by the red line
Additionally, the support for the density can be specified via arguments lbound and ubound. If we wish to assume that the density is 0 to the left of 0 and there is a discontinuity at 0, we could use lbound = 0 in the call to logspline(), for example
m2 <- logspline(x, lbound = 0)
Yielding the following density estimate (shown here with the original m logspline fit as the previous figure was already getting busy).
plot.new()
plot.window(xlim = c(-1, max(x)), ylim = c(0, 1.2))
title(main = "Logspline densities with & without a lower bound",
ylab = "Density", xlab = "x")
plot(m, col = "red", xlim = c(0, max(x)), lwd = 3, add = TRUE)
plot(m2, col = "blue", xlim = c(0, max(x)), lwd = 2, add = TRUE)
curve(exp(-x), from=0, to=max(x), lty=2, add=TRUE)
rug(x, side = 3)
axis(1)
axis(2)
box()
The resulting plot is shown below
In this case, exploiting knowledge of x results in a density estimate that doesn't tend to 0 at $x = 0$, but is similar to the standard logspline fit elsewhere over x
|
Good methods for density plots of non-negative variables in R?
An alternative is the approach of Kooperberg and colleagues, based on estimating the density using splines to approximate the log-density of the data. I'll show an example using the data from @whuber'
|
6,281
|
Good methods for density plots of non-negative variables in R?
|
One solution, borrowed from approaches to edge-weighting of spatial statistics, is to truncate the density on the left at zero but to up-weight the data that are closest to zero. The idea is that each value $x$ is "spread" into a kernel of unit total area centered at $x$; any part of the kernel that would spill over into negative territory is removed and the kernel is renormalized to unit area.
For instance, with a Gaussian kernel $K_h(y,x) = \exp(-\frac{1}{2}((y-x)/h)^2) / \sqrt{2\pi}$, the renormalization weight is
$$w(x) = 1 / \int_0^\infty K(y,x) dy = \frac{1}{1 - \Phi_{x, h}(0)}$$
where $\Phi$ is the cumulative distribution function of a Normal variate of mean $x$ and standard deviation $h$. Comparable formulas are available for other kernels.
This is simpler--and much faster in computation--than trying to narrow the bandwidths near $0$. It is difficult to prescribe exactly how the bandwidths should be changed near $0$, anyway. Nevertheless, this method is also ad hoc: there will still be some bias near $0$. It appears to work better than the default density estimate. Here is a comparison using a largish dataset:
The blue shows the default density while the red shows the density adjusted for the edge at $0$. The true underlying distribution is traced as a dotted line for reference.
R code
The density function in R will complain that the sum of weights is not unity, because it wants the integral over all real numbers to be unity, whereas this approach makes the integral over positive numbers equal to unity. As a check, the latter integral is estimated as a Riemann sum.
set.seed(17)
x <- rexp(1000)
#
# Compute a bandwidth.
#
h <- density(x, kernel="gaussian")$bw # $
#
# Compute edge weights.
#
w <- 1 / pnorm(0, mean=x, sd=h, lower.tail=FALSE)
#
# The truncated weighted density is what we want.
#
d <- density(x, bw=h, kernel="gaussian", weights=w / length(x))
d$y[d$x < 0] <- 0
#
# Check: the integral ought to be close to 1:
#
sum(d$y * diff(d$x)[1])
#
# Plot the two density estimates.
#
par(mfrow=c(1,1))
plot(d, type="n", main="Default and truncated densities", xlim=c(-1, 5))
polygon(density(x, kernel="gaussian", bw=h), col="#6060ff80", border=NA)
polygon(d, col="#ff606080", border=NA)
curve(exp(-x), from=0, to=max(x), lty=2, add=TRUE)
|
Good methods for density plots of non-negative variables in R?
|
One solution, borrowed from approaches to edge-weighting of spatial statistics, is to truncate the density on the left at zero but to up-weight the data that are closest to zero. The idea is that eac
|
Good methods for density plots of non-negative variables in R?
One solution, borrowed from approaches to edge-weighting of spatial statistics, is to truncate the density on the left at zero but to up-weight the data that are closest to zero. The idea is that each value $x$ is "spread" into a kernel of unit total area centered at $x$; any part of the kernel that would spill over into negative territory is removed and the kernel is renormalized to unit area.
For instance, with a Gaussian kernel $K_h(y,x) = \exp(-\frac{1}{2}((y-x)/h)^2) / \sqrt{2\pi}$, the renormalization weight is
$$w(x) = 1 / \int_0^\infty K(y,x) dy = \frac{1}{1 - \Phi_{x, h}(0)}$$
where $\Phi$ is the cumulative distribution function of a Normal variate of mean $x$ and standard deviation $h$. Comparable formulas are available for other kernels.
This is simpler--and much faster in computation--than trying to narrow the bandwidths near $0$. It is difficult to prescribe exactly how the bandwidths should be changed near $0$, anyway. Nevertheless, this method is also ad hoc: there will still be some bias near $0$. It appears to work better than the default density estimate. Here is a comparison using a largish dataset:
The blue shows the default density while the red shows the density adjusted for the edge at $0$. The true underlying distribution is traced as a dotted line for reference.
R code
The density function in R will complain that the sum of weights is not unity, because it wants the integral over all real numbers to be unity, whereas this approach makes the integral over positive numbers equal to unity. As a check, the latter integral is estimated as a Riemann sum.
set.seed(17)
x <- rexp(1000)
#
# Compute a bandwidth.
#
h <- density(x, kernel="gaussian")$bw # $
#
# Compute edge weights.
#
w <- 1 / pnorm(0, mean=x, sd=h, lower.tail=FALSE)
#
# The truncated weighted density is what we want.
#
d <- density(x, bw=h, kernel="gaussian", weights=w / length(x))
d$y[d$x < 0] <- 0
#
# Check: the integral ought to be close to 1:
#
sum(d$y * diff(d$x)[1])
#
# Plot the two density estimates.
#
par(mfrow=c(1,1))
plot(d, type="n", main="Default and truncated densities", xlim=c(-1, 5))
polygon(density(x, kernel="gaussian", bw=h), col="#6060ff80", border=NA)
polygon(d, col="#ff606080", border=NA)
curve(exp(-x), from=0, to=max(x), lty=2, add=TRUE)
|
Good methods for density plots of non-negative variables in R?
One solution, borrowed from approaches to edge-weighting of spatial statistics, is to truncate the density on the left at zero but to up-weight the data that are closest to zero. The idea is that eac
|
6,282
|
Good methods for density plots of non-negative variables in R?
|
To compare distributions by groups (which you say is the goal in one of your comments) why not something simpler? Parallel box plots work nicely if N is large; parallel strip plots work if N is small (and both show outliers well, which you say is a problem in your data).
|
Good methods for density plots of non-negative variables in R?
|
To compare distributions by groups (which you say is the goal in one of your comments) why not something simpler? Parallel box plots work nicely if N is large; parallel strip plots work if N is small
|
Good methods for density plots of non-negative variables in R?
To compare distributions by groups (which you say is the goal in one of your comments) why not something simpler? Parallel box plots work nicely if N is large; parallel strip plots work if N is small (and both show outliers well, which you say is a problem in your data).
|
Good methods for density plots of non-negative variables in R?
To compare distributions by groups (which you say is the goal in one of your comments) why not something simpler? Parallel box plots work nicely if N is large; parallel strip plots work if N is small
|
6,283
|
Good methods for density plots of non-negative variables in R?
|
As StΓ©phane comments you can use from = 0 and, additionally, you can represent your values under the density curve with rug (x)
|
Good methods for density plots of non-negative variables in R?
|
As StΓ©phane comments you can use from = 0 and, additionally, you can represent your values under the density curve with rug (x)
|
Good methods for density plots of non-negative variables in R?
As StΓ©phane comments you can use from = 0 and, additionally, you can represent your values under the density curve with rug (x)
|
Good methods for density plots of non-negative variables in R?
As StΓ©phane comments you can use from = 0 and, additionally, you can represent your values under the density curve with rug (x)
|
6,284
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
|
Because (as is well-known) a uniform distribution on the unit sphere $S^{D-1}$ is obtained by normalizing a $D$-variate normal distribution and the dot product $t$ of normalized vectors is their correlation coefficient, the answers to the three questions are:
$u= (t+1)/2$ has a Beta$((D-1)/2,(D-1)/2)$ distribution.
The variance of $t$ equals $1/D$ (as speculated in the question).
The standardized distribution of $t$ approaches normality at a rate of $O\left(\frac{1}{D}\right).$
Method
The exact distribution of the dot product of unit vectors is easily obtained geometrically, because this is the component of the second vector in the direction of the first. Since the second vector is independent of the first and is uniformly distributed on the unit sphere, its component in the first direction is distributed the same as any coordinate of the sphere. (Notice that the distribution of the first vector does not matter.)
Finding the Density
Letting that coordinate be the last, the density at $t \in [-1,1]$ is therefore proportional to the surface area lying at a height between $t$ and $t+dt$ on the unit sphere. That proportion occurs within a belt of height $dt$ and radius $\sqrt{1-t^2},$ which is essentially a conical frustum constructed out of an $S^{D-2}$ of radius $\sqrt{1-t^2},$ of height $dt$, and slope $1/\sqrt{1-t^2}$. Whence the probability is proportional to
$$\frac{\left(\sqrt{1 - t^2}\right)^{D-2}}{\sqrt{1 - t^2}}\,dt = (1 - t^2)^{(D-3)/2} dt.$$
Letting $u=(t+1)/2 \in [0,1]$ entails $t = 2u-1$. Substituting that into the preceding gives the probability element up to a normalizing constant:
$$f_D(u)du \; \propto \; (1 - (2u-1)^2)^{(D-3)/2} d(2u-1) = 2^{D-2}(u-u^2)^{(D-3)/2}du.$$
It is immediate that $u=(t+1)/2$ has a Beta$((D-1)/2, (D-1)/2)$ distribution, because (by definition) its density also is proportional to
$$u^{(D-1)/2-1}\left(1-u\right)^{(D-1)/2-1} = (u-u^2)^{(D-3)/2} \; \propto \; f_D(u).$$
Determining the Limiting Behavior
Information about the limiting behavior follows easily from this using elementary techniques: $f_D$ can be integrated to obtain the constant of proportionality $\frac{\Gamma \left(\frac{D}{2}\right)}{\sqrt{\pi } \Gamma \left(\frac{D-1}{2}\right)}$; $t^k f_D(t)$ can be integrated (using properties of Beta functions, for instance) to obtain moments, showing that the variance is $1/D$ and shrinks to $0$ (whence, by Chebyshev's Theorem, the probability is becoming concentrated near $t=0$); and the limiting distribution is then found by considering values of the density of the standardized distribution, proportional to $f_D(t/\sqrt{D}),$ for small values of $t$:
$$\eqalign{
\log(f_D(t/\sqrt{D})) &= C(D) + \frac{D-3}{2}\log\left(1 - \frac{t^2}{D}\right) \\
&=C(D) -\left(1/2 + \frac{3}{2D}\right)t^2 + O\left(\frac{t^4}{D}\right) \\
&\to C -\frac{1}{2}t^2
}$$
where the $C$'s represent (log) constants of integration. Evidently the rate at which this approaches normality (for which the log density equals $-\frac{1}{2}t^2$) is $O\left(\frac{1}{D}\right).$
This plot shows the densities of the dot product for $D=4, 6, 10$, as standardized to unit variance, and their limiting density. The values at $0$ increase with $D$ (from blue through red, gold, and then green for the standard normal density). The density for $D=1000$ would be indistinguishable from the normal density at this resolution.
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
|
Because (as is well-known) a uniform distribution on the unit sphere $S^{D-1}$ is obtained by normalizing a $D$-variate normal distribution and the dot product $t$ of normalized vectors is their corr
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
Because (as is well-known) a uniform distribution on the unit sphere $S^{D-1}$ is obtained by normalizing a $D$-variate normal distribution and the dot product $t$ of normalized vectors is their correlation coefficient, the answers to the three questions are:
$u= (t+1)/2$ has a Beta$((D-1)/2,(D-1)/2)$ distribution.
The variance of $t$ equals $1/D$ (as speculated in the question).
The standardized distribution of $t$ approaches normality at a rate of $O\left(\frac{1}{D}\right).$
Method
The exact distribution of the dot product of unit vectors is easily obtained geometrically, because this is the component of the second vector in the direction of the first. Since the second vector is independent of the first and is uniformly distributed on the unit sphere, its component in the first direction is distributed the same as any coordinate of the sphere. (Notice that the distribution of the first vector does not matter.)
Finding the Density
Letting that coordinate be the last, the density at $t \in [-1,1]$ is therefore proportional to the surface area lying at a height between $t$ and $t+dt$ on the unit sphere. That proportion occurs within a belt of height $dt$ and radius $\sqrt{1-t^2},$ which is essentially a conical frustum constructed out of an $S^{D-2}$ of radius $\sqrt{1-t^2},$ of height $dt$, and slope $1/\sqrt{1-t^2}$. Whence the probability is proportional to
$$\frac{\left(\sqrt{1 - t^2}\right)^{D-2}}{\sqrt{1 - t^2}}\,dt = (1 - t^2)^{(D-3)/2} dt.$$
Letting $u=(t+1)/2 \in [0,1]$ entails $t = 2u-1$. Substituting that into the preceding gives the probability element up to a normalizing constant:
$$f_D(u)du \; \propto \; (1 - (2u-1)^2)^{(D-3)/2} d(2u-1) = 2^{D-2}(u-u^2)^{(D-3)/2}du.$$
It is immediate that $u=(t+1)/2$ has a Beta$((D-1)/2, (D-1)/2)$ distribution, because (by definition) its density also is proportional to
$$u^{(D-1)/2-1}\left(1-u\right)^{(D-1)/2-1} = (u-u^2)^{(D-3)/2} \; \propto \; f_D(u).$$
Determining the Limiting Behavior
Information about the limiting behavior follows easily from this using elementary techniques: $f_D$ can be integrated to obtain the constant of proportionality $\frac{\Gamma \left(\frac{D}{2}\right)}{\sqrt{\pi } \Gamma \left(\frac{D-1}{2}\right)}$; $t^k f_D(t)$ can be integrated (using properties of Beta functions, for instance) to obtain moments, showing that the variance is $1/D$ and shrinks to $0$ (whence, by Chebyshev's Theorem, the probability is becoming concentrated near $t=0$); and the limiting distribution is then found by considering values of the density of the standardized distribution, proportional to $f_D(t/\sqrt{D}),$ for small values of $t$:
$$\eqalign{
\log(f_D(t/\sqrt{D})) &= C(D) + \frac{D-3}{2}\log\left(1 - \frac{t^2}{D}\right) \\
&=C(D) -\left(1/2 + \frac{3}{2D}\right)t^2 + O\left(\frac{t^4}{D}\right) \\
&\to C -\frac{1}{2}t^2
}$$
where the $C$'s represent (log) constants of integration. Evidently the rate at which this approaches normality (for which the log density equals $-\frac{1}{2}t^2$) is $O\left(\frac{1}{D}\right).$
This plot shows the densities of the dot product for $D=4, 6, 10$, as standardized to unit variance, and their limiting density. The values at $0$ increase with $D$ (from blue through red, gold, and then green for the standard normal density). The density for $D=1000$ would be indistinguishable from the normal density at this resolution.
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
Because (as is well-known) a uniform distribution on the unit sphere $S^{D-1}$ is obtained by normalizing a $D$-variate normal distribution and the dot product $t$ of normalized vectors is their corr
|
6,285
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
|
Let's find the distribution and then the variance follows by standard results. Consider the vector product and write it on it's cosine form, i.e. note that we have $$P(x'y\leq t)=P(|x||y|\cos\theta\leq t)=P(\cos\theta\leq t)=\mathbb{E}P(\cos\theta\leq t\mid y),$$ where $\theta$ is the angle between $x$ and $y$. In the last step I have used that for any events $A$ and $B$ $$\mathbb EP(A\mid B):=\mathbb{E}[\mathbb{E}[\chi_A\mid B]]=\mathbb{E}\chi_A=P(A).$$ Now consider the term $P(\cos\theta\leq t\mid y)$ . It is clear that since $x$ is choosen uniformly with respect to the sphere surface, it does not matter what $y$ actually is, only the angle between $x$ and $y$ matters. Thus, the term inside the expectation is actually constant as a function of $y$ and we can w.l.o.g. assume that $y=[1,0,0,\dots ]'.$ Then we get that $$P(x'y\leq t)=P\left( x_1\leq t\right).$$ but since $x_1$ is the first coordinate of a normalized Gaussian vector in $\mathbb{R}^n,$ we have that $x'y$ is Gaussian with variance $1/n$ by invoking the asymptotic result of this paper.
For an explicit result of the variance, use the fact that the dot product is mean zero by independence and, as shown above, distributed like the first coordinate of $x$. By these results, finding $\text{Var}(x'y)$ amounts to finding $\mathbb{E}x_1^2$. Now, note that per construction $x'x=1$ and so we can write $$1=\mathbb{E}x'x=\mathbb{E}\sum_{i=1}^nx_i^2=\sum_{i=1}^n\mathbb{E}x_i^2=n\mathbb{E}x_1^2,$$ where the last equality follows from that the coordinates of $x$ are identically distributed. Putting things together, we have found that $\text{Var}(x'y)=\mathbb{E}x_1^2=1/n$
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
|
Let's find the distribution and then the variance follows by standard results. Consider the vector product and write it on it's cosine form, i.e. note that we have $$P(x'y\leq t)=P(|x||y|\cos\theta\le
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
Let's find the distribution and then the variance follows by standard results. Consider the vector product and write it on it's cosine form, i.e. note that we have $$P(x'y\leq t)=P(|x||y|\cos\theta\leq t)=P(\cos\theta\leq t)=\mathbb{E}P(\cos\theta\leq t\mid y),$$ where $\theta$ is the angle between $x$ and $y$. In the last step I have used that for any events $A$ and $B$ $$\mathbb EP(A\mid B):=\mathbb{E}[\mathbb{E}[\chi_A\mid B]]=\mathbb{E}\chi_A=P(A).$$ Now consider the term $P(\cos\theta\leq t\mid y)$ . It is clear that since $x$ is choosen uniformly with respect to the sphere surface, it does not matter what $y$ actually is, only the angle between $x$ and $y$ matters. Thus, the term inside the expectation is actually constant as a function of $y$ and we can w.l.o.g. assume that $y=[1,0,0,\dots ]'.$ Then we get that $$P(x'y\leq t)=P\left( x_1\leq t\right).$$ but since $x_1$ is the first coordinate of a normalized Gaussian vector in $\mathbb{R}^n,$ we have that $x'y$ is Gaussian with variance $1/n$ by invoking the asymptotic result of this paper.
For an explicit result of the variance, use the fact that the dot product is mean zero by independence and, as shown above, distributed like the first coordinate of $x$. By these results, finding $\text{Var}(x'y)$ amounts to finding $\mathbb{E}x_1^2$. Now, note that per construction $x'x=1$ and so we can write $$1=\mathbb{E}x'x=\mathbb{E}\sum_{i=1}^nx_i^2=\sum_{i=1}^n\mathbb{E}x_i^2=n\mathbb{E}x_1^2,$$ where the last equality follows from that the coordinates of $x$ are identically distributed. Putting things together, we have found that $\text{Var}(x'y)=\mathbb{E}x_1^2=1/n$
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
Let's find the distribution and then the variance follows by standard results. Consider the vector product and write it on it's cosine form, i.e. note that we have $$P(x'y\leq t)=P(|x||y|\cos\theta\le
|
6,286
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
|
To answer the first part of your question, denote $Z = \langle X,Y \rangle = \sum X_i Y_i$. Define
$$
f_{Z_i}(z_i) = \int_{-\infty}^\infty f_{Z_1,\ldots,Z_D}(z_1,\ldots,z_D) \: d z_i
$$
The product of the $i^{th}$ elements of $X$ and $Y$ denoted here as $Z_i$ will be distributed according to the joint distribution of $X_i$ and $Y_i$.
$$
f_{Z_i}(z_i) = \int_{-\infty}^\infty f_{X_i,Y_i}(x,\frac{z_i}{x})\frac{1}{|x|}dx
$$
then since $Z = \sum Z_i$,
$$
f_Z(z) = \int_{-\infty}^\infty \ldots \int_{-\infty}^\infty f_{Z_1,\ldots,Z_D} (z_1,\ldots,z_d) \: \delta(z - \sum z_i)\: dz_1\ldots d z_d
$$
For the second part, I think that if you want to say anything interesting about the asymptotic behaviour of $\sigma$ you need to at least assume independence of $X$ and $Y$, and then apply a CLT.
For instance if you were willing to assume that the $\{Z_1,\ldots,Z_D\}$ are i.i.d with $\mathbb{E}[Z_i] = \mu$ and $\mathbb{V}[Z_i] = \sigma^2$ you could say that $\sigma^2(D) = \frac{\sigma^2}{D}$ and $\lim_{D\to\infty} \sigma^2(D) = 0$.
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
|
To answer the first part of your question, denote $Z = \langle X,Y \rangle = \sum X_i Y_i$. Define
$$
f_{Z_i}(z_i) = \int_{-\infty}^\infty f_{Z_1,\ldots,Z_D}(z_1,\ldots,z_D) \: d z_i
$$
The product
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
To answer the first part of your question, denote $Z = \langle X,Y \rangle = \sum X_i Y_i$. Define
$$
f_{Z_i}(z_i) = \int_{-\infty}^\infty f_{Z_1,\ldots,Z_D}(z_1,\ldots,z_D) \: d z_i
$$
The product of the $i^{th}$ elements of $X$ and $Y$ denoted here as $Z_i$ will be distributed according to the joint distribution of $X_i$ and $Y_i$.
$$
f_{Z_i}(z_i) = \int_{-\infty}^\infty f_{X_i,Y_i}(x,\frac{z_i}{x})\frac{1}{|x|}dx
$$
then since $Z = \sum Z_i$,
$$
f_Z(z) = \int_{-\infty}^\infty \ldots \int_{-\infty}^\infty f_{Z_1,\ldots,Z_D} (z_1,\ldots,z_d) \: \delta(z - \sum z_i)\: dz_1\ldots d z_d
$$
For the second part, I think that if you want to say anything interesting about the asymptotic behaviour of $\sigma$ you need to at least assume independence of $X$ and $Y$, and then apply a CLT.
For instance if you were willing to assume that the $\{Z_1,\ldots,Z_D\}$ are i.i.d with $\mathbb{E}[Z_i] = \mu$ and $\mathbb{V}[Z_i] = \sigma^2$ you could say that $\sigma^2(D) = \frac{\sigma^2}{D}$ and $\lim_{D\to\infty} \sigma^2(D) = 0$.
|
Distribution of scalar products of two random unit vectors in $D$ dimensions
To answer the first part of your question, denote $Z = \langle X,Y \rangle = \sum X_i Y_i$. Define
$$
f_{Z_i}(z_i) = \int_{-\infty}^\infty f_{Z_1,\ldots,Z_D}(z_1,\ldots,z_D) \: d z_i
$$
The product
|
6,287
|
Why do naive Bayesian classifiers perform so well?
|
This paper seems to prove (I can't follow the math) that bayes is good not only when features are independent, but also when dependencies of features from each other are similar between features:
In this paper, we propose a novel explanation on the
superb classiο¬cation performance of naive Bayes. We
show that, essentially, the dependence distribution; i.e.,
how the local dependence of a node distributes in each
class, evenly or unevenly, and how the local dependencies of all nodes work together, consistently (supporting a certain classiο¬cation) or inconsistently (canceling each other out), plays a crucial role. Therefore,
no matter how strong the dependences among attributes
are, naive Bayes can still be optimal if the dependences
distribute evenly in classes, or if the dependences cancel each other out
|
Why do naive Bayesian classifiers perform so well?
|
This paper seems to prove (I can't follow the math) that bayes is good not only when features are independent, but also when dependencies of features from each other are similar between features:
In
|
Why do naive Bayesian classifiers perform so well?
This paper seems to prove (I can't follow the math) that bayes is good not only when features are independent, but also when dependencies of features from each other are similar between features:
In this paper, we propose a novel explanation on the
superb classiο¬cation performance of naive Bayes. We
show that, essentially, the dependence distribution; i.e.,
how the local dependence of a node distributes in each
class, evenly or unevenly, and how the local dependencies of all nodes work together, consistently (supporting a certain classiο¬cation) or inconsistently (canceling each other out), plays a crucial role. Therefore,
no matter how strong the dependences among attributes
are, naive Bayes can still be optimal if the dependences
distribute evenly in classes, or if the dependences cancel each other out
|
Why do naive Bayesian classifiers perform so well?
This paper seems to prove (I can't follow the math) that bayes is good not only when features are independent, but also when dependencies of features from each other are similar between features:
In
|
6,288
|
Why do naive Bayesian classifiers perform so well?
|
Most Machine Learning problems are easy!
See for example at John Langford's blog. What he's really saying is that ML makes problems easy, and this presents a problem for researchers in terms of whether they should try to apply methods to a wide range of simple problems or attack more difficult problems. However the by-product is that for many problems the data is Linearly Separable (or at least nearly), in which case any linear classifier will work well! It just so happens that the authors of the original spam filter paper chose to use Naive Bayes, but had they used a Perceptron, SVM, Fisher Discriminant Analysis, Logistic Regression, AdaBoost, or pretty much anything else it probably would have worked as well.
The fact that it is relatively easy to code the algorithm helps. For example to code up the SVM you either need to have a QP Solver, or you need to code up the SMO algorithm which is not a trivial task. You could of course download libsvm but in the early days that option wasn't available. However there are many other simple algorithms (including the Perceptron mentioned above) that are just as easy to code (and allows incremental updates as the question mentions).
For tough nonlinear problems methods that can deal with nonlinearites are needed of course. But even this can be a relatively simple task when Kernel Methods are employed. The question often then becomes "How do I design an effective kernel function for my data" rather than "Which classifier should I use".
|
Why do naive Bayesian classifiers perform so well?
|
Most Machine Learning problems are easy!
See for example at John Langford's blog. What he's really saying is that ML makes problems easy, and this presents a problem for researchers in terms of whethe
|
Why do naive Bayesian classifiers perform so well?
Most Machine Learning problems are easy!
See for example at John Langford's blog. What he's really saying is that ML makes problems easy, and this presents a problem for researchers in terms of whether they should try to apply methods to a wide range of simple problems or attack more difficult problems. However the by-product is that for many problems the data is Linearly Separable (or at least nearly), in which case any linear classifier will work well! It just so happens that the authors of the original spam filter paper chose to use Naive Bayes, but had they used a Perceptron, SVM, Fisher Discriminant Analysis, Logistic Regression, AdaBoost, or pretty much anything else it probably would have worked as well.
The fact that it is relatively easy to code the algorithm helps. For example to code up the SVM you either need to have a QP Solver, or you need to code up the SMO algorithm which is not a trivial task. You could of course download libsvm but in the early days that option wasn't available. However there are many other simple algorithms (including the Perceptron mentioned above) that are just as easy to code (and allows incremental updates as the question mentions).
For tough nonlinear problems methods that can deal with nonlinearites are needed of course. But even this can be a relatively simple task when Kernel Methods are employed. The question often then becomes "How do I design an effective kernel function for my data" rather than "Which classifier should I use".
|
Why do naive Bayesian classifiers perform so well?
Most Machine Learning problems are easy!
See for example at John Langford's blog. What he's really saying is that ML makes problems easy, and this presents a problem for researchers in terms of whethe
|
6,289
|
Why do naive Bayesian classifiers perform so well?
|
Having used Naive Bayesian Classifiers extensively in segmentation classification tools, my experience is consistent with published papers showing NBC to be comparable in accuracy to linear discriminant and CART/CHAID when all of the predictor variables are available.
(By accuracy both "hit rate" in predicting the correct solution as the most likely one, as well as calibration, meaning a, say, 75% membership estimate is right in 70%-80% of cases.)
My two cents is that NBC works so well because:
Inter-correlation among predictor variables is not as strong as one
might think (mutual information scores of 0.05 to 0.15 are typical)
NBC can handle discrete polytomous variables well, not requiring us to crudely dichotomize them or treat ordinal variables as cardinal.
NBC uses all the variables simultaneously whereas CART/CHAID use just a few
And that's when all the variables are observed. What makes NBC really pull away from the pack is that it gracefully degrades when one or more predictor variables are missing or not observed. CART/CHAID and linear discriminant analysis stop flat in that case.
|
Why do naive Bayesian classifiers perform so well?
|
Having used Naive Bayesian Classifiers extensively in segmentation classification tools, my experience is consistent with published papers showing NBC to be comparable in accuracy to linear discrimina
|
Why do naive Bayesian classifiers perform so well?
Having used Naive Bayesian Classifiers extensively in segmentation classification tools, my experience is consistent with published papers showing NBC to be comparable in accuracy to linear discriminant and CART/CHAID when all of the predictor variables are available.
(By accuracy both "hit rate" in predicting the correct solution as the most likely one, as well as calibration, meaning a, say, 75% membership estimate is right in 70%-80% of cases.)
My two cents is that NBC works so well because:
Inter-correlation among predictor variables is not as strong as one
might think (mutual information scores of 0.05 to 0.15 are typical)
NBC can handle discrete polytomous variables well, not requiring us to crudely dichotomize them or treat ordinal variables as cardinal.
NBC uses all the variables simultaneously whereas CART/CHAID use just a few
And that's when all the variables are observed. What makes NBC really pull away from the pack is that it gracefully degrades when one or more predictor variables are missing or not observed. CART/CHAID and linear discriminant analysis stop flat in that case.
|
Why do naive Bayesian classifiers perform so well?
Having used Naive Bayesian Classifiers extensively in segmentation classification tools, my experience is consistent with published papers showing NBC to be comparable in accuracy to linear discrimina
|
6,290
|
Good accuracy despite high loss value
|
I have experienced a similar issue.
I have trained my neural network binary classifier with a cross entropy loss. Here the result of the cross entropy as a function of epoch. Red is for the training set and blue is for the test set.
By showing the accuracy, I had the surprise to get a better accuracy for epoch 1000 compared to epoch 50, even for the test set!
To understand relationships between cross entropy and accuracy, I have dug into a simpler model, the logistic regression (with one input and one output). In the following, I just illustrate this relationship in 3 special cases.
In general, the parameter where the cross entropy is minimum is not the parameter where the accuracy is maximum. However, we may expect some relationship between cross entropy and accuracy.
[ In the following, I assume that you know what is cross entropy, why we use it instead of accuracy to train model, etc. If not, please read this first: How do interpret an cross entropy score? ]
Illustration 1 This one is to show that the parameter where the cross entropy is minimum is not the parameter where the accuracy is maximum, and to understand why.
Here is my sample data. I have 5 points, and for example input -1 has lead to output 0.
Cross entropy.
After minimizing the cross entropy, I obtain an accuracy of 0.6. The cut between 0 and 1 is done at x=0.52.
For the 5 values, I obtain respectively a cross entropy of: 0.14, 0.30, 1.07, 0.97, 0.43.
Accuracy.
After maximizing the accuracy on a grid, I obtain many different parameters leading to 0.8. This can be shown directly, by selecting the cut x=-0.1. Well, you can also select x=0.95 to cut the sets.
In the first case, the cross entropy is large. Indeed, the fourth point is far away from the cut, so has a large cross entropy. Namely, I obtain respectively a cross entropy of: 0.01, 0.31, 0.47, 5.01, 0.004.
In the second case, the cross entropy is large too. In that case, the third point is far away from the cut, so has a large cross entropy. I obtain respectively a cross entropy of: 5e-5, 2e-3, 4.81, 0.6, 0.6.
The $a$ minimizing the cross entropy is 1.27. For this $a$, we can show the evolution of cross entropy and accuracy when $b$ varies (on the same graph).
Illustration 2 Here I take $n=100$. I took the data as a sample under the logit model with a slope $a=0.3$ and an intercept $b=0.5$. I selected a seed to have a large effect, but many seeds lead to a related behavior.
Here, I plot only the most interesting graph. The $b$ minimizing the cross entropy is 0.42. For this $b$, we can show the evolution of cross entropy and accuracy when $a$ varies (on the same graph).
Here is an interesting thing: The plot looks like my initial problem. The cross entropy is rising, the selected $a$ becomes so large, however the accuracy continues to rise (and then stops to rise).
We couldn't select the model with this larger accuracy (first because here we know that the underlying model is with $a=0.3$!).
Illustration 3 Here I take $n=10000$, with $a=1$ and $b=0$. Now, we can observe a strong relationship between accuracy and cross entropy.
I think that if the model has enough capacity (enough to contain the true model), and if the data is large (i.e. sample size goes to infinity), then cross entropy may be minimum when accuracy is maximum, at least for the logistic model. I have no proof of this, if someone has a reference, please share.
Bibliography: The subject linking cross entropy and accuracy is interesting and complex, but I cannot find articles dealing with this... To study accuracy is interesting because despite being an improper scoring rule, everyone can understand its meaning.
Note: First, I would like to find an answer on this website, posts dealing with relationship between accuracy and cross entropy are numerous but with few answers, see: Comparable traing and test cross-entropies result in very different accuracies ; Validation loss going down, but validation accuracy worsening ; Doubt on categorical cross entropy loss function ; Interpreting log-loss as percentage ...
|
Good accuracy despite high loss value
|
I have experienced a similar issue.
I have trained my neural network binary classifier with a cross entropy loss. Here the result of the cross entropy as a function of epoch. Red is for the training s
|
Good accuracy despite high loss value
I have experienced a similar issue.
I have trained my neural network binary classifier with a cross entropy loss. Here the result of the cross entropy as a function of epoch. Red is for the training set and blue is for the test set.
By showing the accuracy, I had the surprise to get a better accuracy for epoch 1000 compared to epoch 50, even for the test set!
To understand relationships between cross entropy and accuracy, I have dug into a simpler model, the logistic regression (with one input and one output). In the following, I just illustrate this relationship in 3 special cases.
In general, the parameter where the cross entropy is minimum is not the parameter where the accuracy is maximum. However, we may expect some relationship between cross entropy and accuracy.
[ In the following, I assume that you know what is cross entropy, why we use it instead of accuracy to train model, etc. If not, please read this first: How do interpret an cross entropy score? ]
Illustration 1 This one is to show that the parameter where the cross entropy is minimum is not the parameter where the accuracy is maximum, and to understand why.
Here is my sample data. I have 5 points, and for example input -1 has lead to output 0.
Cross entropy.
After minimizing the cross entropy, I obtain an accuracy of 0.6. The cut between 0 and 1 is done at x=0.52.
For the 5 values, I obtain respectively a cross entropy of: 0.14, 0.30, 1.07, 0.97, 0.43.
Accuracy.
After maximizing the accuracy on a grid, I obtain many different parameters leading to 0.8. This can be shown directly, by selecting the cut x=-0.1. Well, you can also select x=0.95 to cut the sets.
In the first case, the cross entropy is large. Indeed, the fourth point is far away from the cut, so has a large cross entropy. Namely, I obtain respectively a cross entropy of: 0.01, 0.31, 0.47, 5.01, 0.004.
In the second case, the cross entropy is large too. In that case, the third point is far away from the cut, so has a large cross entropy. I obtain respectively a cross entropy of: 5e-5, 2e-3, 4.81, 0.6, 0.6.
The $a$ minimizing the cross entropy is 1.27. For this $a$, we can show the evolution of cross entropy and accuracy when $b$ varies (on the same graph).
Illustration 2 Here I take $n=100$. I took the data as a sample under the logit model with a slope $a=0.3$ and an intercept $b=0.5$. I selected a seed to have a large effect, but many seeds lead to a related behavior.
Here, I plot only the most interesting graph. The $b$ minimizing the cross entropy is 0.42. For this $b$, we can show the evolution of cross entropy and accuracy when $a$ varies (on the same graph).
Here is an interesting thing: The plot looks like my initial problem. The cross entropy is rising, the selected $a$ becomes so large, however the accuracy continues to rise (and then stops to rise).
We couldn't select the model with this larger accuracy (first because here we know that the underlying model is with $a=0.3$!).
Illustration 3 Here I take $n=10000$, with $a=1$ and $b=0$. Now, we can observe a strong relationship between accuracy and cross entropy.
I think that if the model has enough capacity (enough to contain the true model), and if the data is large (i.e. sample size goes to infinity), then cross entropy may be minimum when accuracy is maximum, at least for the logistic model. I have no proof of this, if someone has a reference, please share.
Bibliography: The subject linking cross entropy and accuracy is interesting and complex, but I cannot find articles dealing with this... To study accuracy is interesting because despite being an improper scoring rule, everyone can understand its meaning.
Note: First, I would like to find an answer on this website, posts dealing with relationship between accuracy and cross entropy are numerous but with few answers, see: Comparable traing and test cross-entropies result in very different accuracies ; Validation loss going down, but validation accuracy worsening ; Doubt on categorical cross entropy loss function ; Interpreting log-loss as percentage ...
|
Good accuracy despite high loss value
I have experienced a similar issue.
I have trained my neural network binary classifier with a cross entropy loss. Here the result of the cross entropy as a function of epoch. Red is for the training s
|
6,291
|
Good accuracy despite high loss value
|
One important thing to note as well is that the cross entropy is not a bounded loss. Which means that a single very wrong prediction can potentially make your loss "blow up". In that sense it is possible that there are one or a few outliers that are classified extremely badly and that are making the loss explode, but at the same time your model is still learning on the rest of the dataset.
In the following example I use a very simple dataset in which there is an outlier in the test data. There are 2 classes "zero" and "one".
Here is how the dataset looks like:
As you can see the 2 classes are extremely easy to separate:above 0.5 it is class "zero". There is also a single outlier of class "one" in the middle of class "zero" only in the test set. This outlier is important as it will mess with the loss function.
I train a 1 hidden neural network on this dataset, you can see the results:
The loss starts increasing, but the accuracy continue to increase nonetheless.
Plotting a histogram of the loss function per samples shows clearly the issue: the loss is actually very low for most samples (the big bar at 0) and there is one outlier with a huge loss (small bar at 17). Since the total loss is the average you get a high loss on that set even though it is performing very well on all the points but one.
Bonus: Code for the data and model
import tensorflow.keras as keras
import numpy as np
np.random.seed(0)
x_train_2 = np.hstack([1/2+1/2*np.random.uniform(size=10), 1/2-1.5*np.random.uniform(size=10)])
y_train_2 = np.array([0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1])
x_test_2 = np.hstack([1/2+1/2*np.random.uniform(size=10), 1/2-1.5*np.random.uniform(size=10)])
y_test_2 = np.array([0,0,0,1,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1])
keras.backend.clear_session()
m = keras.models.Sequential([
keras.layers.Input((1,)),
keras.layers.Dense(3, activation="relu"),
keras.layers.Dense(1, activation="sigmoid")
])
m.compile(
optimizer=keras.optimizers.Adam(lr=0.05), loss="binary_crossentropy", metrics=["accuracy"])
history = m.fit(x_train_2, y_train_2, validation_data=(x_test_2, y_test_2), batch_size=20, epochs=300, verbose=0)
TL;DR
Your loss might be hijacked by a few outliers, check the distribution of your loss function on individual samples of your validation set. If there are a cluster of values around the mean then you are overfitting. If there are just a few values very high above a low majority group then your loss is being affected by outliers :)
|
Good accuracy despite high loss value
|
One important thing to note as well is that the cross entropy is not a bounded loss. Which means that a single very wrong prediction can potentially make your loss "blow up". In that sense it is possi
|
Good accuracy despite high loss value
One important thing to note as well is that the cross entropy is not a bounded loss. Which means that a single very wrong prediction can potentially make your loss "blow up". In that sense it is possible that there are one or a few outliers that are classified extremely badly and that are making the loss explode, but at the same time your model is still learning on the rest of the dataset.
In the following example I use a very simple dataset in which there is an outlier in the test data. There are 2 classes "zero" and "one".
Here is how the dataset looks like:
As you can see the 2 classes are extremely easy to separate:above 0.5 it is class "zero". There is also a single outlier of class "one" in the middle of class "zero" only in the test set. This outlier is important as it will mess with the loss function.
I train a 1 hidden neural network on this dataset, you can see the results:
The loss starts increasing, but the accuracy continue to increase nonetheless.
Plotting a histogram of the loss function per samples shows clearly the issue: the loss is actually very low for most samples (the big bar at 0) and there is one outlier with a huge loss (small bar at 17). Since the total loss is the average you get a high loss on that set even though it is performing very well on all the points but one.
Bonus: Code for the data and model
import tensorflow.keras as keras
import numpy as np
np.random.seed(0)
x_train_2 = np.hstack([1/2+1/2*np.random.uniform(size=10), 1/2-1.5*np.random.uniform(size=10)])
y_train_2 = np.array([0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1])
x_test_2 = np.hstack([1/2+1/2*np.random.uniform(size=10), 1/2-1.5*np.random.uniform(size=10)])
y_test_2 = np.array([0,0,0,1,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1])
keras.backend.clear_session()
m = keras.models.Sequential([
keras.layers.Input((1,)),
keras.layers.Dense(3, activation="relu"),
keras.layers.Dense(1, activation="sigmoid")
])
m.compile(
optimizer=keras.optimizers.Adam(lr=0.05), loss="binary_crossentropy", metrics=["accuracy"])
history = m.fit(x_train_2, y_train_2, validation_data=(x_test_2, y_test_2), batch_size=20, epochs=300, verbose=0)
TL;DR
Your loss might be hijacked by a few outliers, check the distribution of your loss function on individual samples of your validation set. If there are a cluster of values around the mean then you are overfitting. If there are just a few values very high above a low majority group then your loss is being affected by outliers :)
|
Good accuracy despite high loss value
One important thing to note as well is that the cross entropy is not a bounded loss. Which means that a single very wrong prediction can potentially make your loss "blow up". In that sense it is possi
|
6,292
|
Good accuracy despite high loss value
|
ahstat gives very good illustrations.
Inspired by these illustrations, i conclude to 2 possible reasons.
1. Model is too simple to extract required features for prediction. In your Illustration 1, it's a manifold problem and need to one more layer to get 100% accuracy.
2. Data has too many noisy label.(compare Illustration 1 and 3)
As for Illustration 2, it explains why we cannot add too much L1/L2 regularization on the model.
|
Good accuracy despite high loss value
|
ahstat gives very good illustrations.
Inspired by these illustrations, i conclude to 2 possible reasons.
1. Model is too simple to extract required features for prediction. In your Illustration 1, i
|
Good accuracy despite high loss value
ahstat gives very good illustrations.
Inspired by these illustrations, i conclude to 2 possible reasons.
1. Model is too simple to extract required features for prediction. In your Illustration 1, it's a manifold problem and need to one more layer to get 100% accuracy.
2. Data has too many noisy label.(compare Illustration 1 and 3)
As for Illustration 2, it explains why we cannot add too much L1/L2 regularization on the model.
|
Good accuracy despite high loss value
ahstat gives very good illustrations.
Inspired by these illustrations, i conclude to 2 possible reasons.
1. Model is too simple to extract required features for prediction. In your Illustration 1, i
|
6,293
|
Good accuracy despite high loss value
|
In categorical cross entropy case accuracy measures true positive i.e accuracy is discrete values, while the logloss of softmax loss so to speak is a continuous variable that measures the models performance against false negatives. A wrong prediction affects accuracy slightly but penalizes the loss disproportionately. Assuming you have a balanced dataset.
So what causes loss-vs-accuracy discrepancy ?
when model predictions are bolder loss drops and accuracy stays constant. Implying model is performing well against its classes
a single wrong prediction with confidence will drop accuracy slightly but loss will increase i.e over fitted model may have good accuracy but poor loss
For categorical cross entropy loss a dumb model that just guesses should have a loss of y=-ln(1/n) where n is number or classes that are balanced. Further apply probability with imbalance between your classes to calculate expected chance logloss first as baseline. Once you know that you can then evaluate how well the model is trained and use loss as a proxy to accuracy to infer model performance.
|
Good accuracy despite high loss value
|
In categorical cross entropy case accuracy measures true positive i.e accuracy is discrete values, while the logloss of softmax loss so to speak is a continuous variable that measures the models perfo
|
Good accuracy despite high loss value
In categorical cross entropy case accuracy measures true positive i.e accuracy is discrete values, while the logloss of softmax loss so to speak is a continuous variable that measures the models performance against false negatives. A wrong prediction affects accuracy slightly but penalizes the loss disproportionately. Assuming you have a balanced dataset.
So what causes loss-vs-accuracy discrepancy ?
when model predictions are bolder loss drops and accuracy stays constant. Implying model is performing well against its classes
a single wrong prediction with confidence will drop accuracy slightly but loss will increase i.e over fitted model may have good accuracy but poor loss
For categorical cross entropy loss a dumb model that just guesses should have a loss of y=-ln(1/n) where n is number or classes that are balanced. Further apply probability with imbalance between your classes to calculate expected chance logloss first as baseline. Once you know that you can then evaluate how well the model is trained and use loss as a proxy to accuracy to infer model performance.
|
Good accuracy despite high loss value
In categorical cross entropy case accuracy measures true positive i.e accuracy is discrete values, while the logloss of softmax loss so to speak is a continuous variable that measures the models perfo
|
6,294
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
|
Let the data be $\mathbf{x}=(x_1, \ldots, x_n)$. Write $F(\mathbf{x})$ for the empirical distribution. By definition, for any function $f$,
$$\mathbb{E}_{F(\mathbf{x})}[f(X)] = \frac{1}{n}\sum_{i=1}^n f(x_i).$$
Let the model $M$ have density $e^{f(x)}$ where $f$ is defined on the support of the model. The cross-entropy of $F(\mathbf{x})$ and $M$ is defined to be
$$H(F(\mathbf{x}), M) = -\mathbb{E}_{F(\mathbf{x})}[\log(e^{f(X)}] = -\mathbb{E}_{F(\mathbf{x})}[f(X)] =-\frac{1}{n}\sum_{i=1}^n f(x_i).\tag{1}$$
Assuming $x$ is a simple random sample, its negative log likelihood is
$$-\log(L(\mathbf{x}))=-\log \prod_{i=1}^n e^{f(x_i)} = -\sum_{i=1}^n f(x_i)\tag{2}$$
by virtue of the properties of logarithms (they convert products to sums).
Expression $(2)$ is a constant $n$ times expression $(1)$. Because loss functions are used in statistics only by comparing them, it makes no difference that one is a (positive) constant times the other. It is in this sense that the negative log likelihood "is a" cross-entropy in the quotation.
It takes a bit more imagination to justify the second assertion of the quotation. The connection with squared error is clear, because for a "Gaussian model" that predicts values $p(x)$ at points $x$, the value of $f$ at any such point is
$$f(x; p, \sigma) = -\frac{1}{2}\left(\log(2\pi \sigma^2) + \frac{(x-p(x))^2}{\sigma^2}\right),$$
which is the squared error $(x-p(x))^2$ but rescaled by $1/(2\sigma^2)$ and shifted by a function of $\sigma$. One way to make the quotation correct is to assume it does not consider $\sigma$ part of the "model"--$\sigma$ must be determined somehow independently of the data. In that case differences between mean squared errors are proportional to differences between cross-entropies or log-likelihoods, thereby making all three equivalent for model fitting purposes.
(Ordinarily, though, $\sigma = \sigma(x)$ is fit as part of the modeling process, in which case the quotation would not be quite correct.)
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
|
Let the data be $\mathbf{x}=(x_1, \ldots, x_n)$. Write $F(\mathbf{x})$ for the empirical distribution. By definition, for any function $f$,
$$\mathbb{E}_{F(\mathbf{x})}[f(X)] = \frac{1}{n}\sum_{i=1}^
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
Let the data be $\mathbf{x}=(x_1, \ldots, x_n)$. Write $F(\mathbf{x})$ for the empirical distribution. By definition, for any function $f$,
$$\mathbb{E}_{F(\mathbf{x})}[f(X)] = \frac{1}{n}\sum_{i=1}^n f(x_i).$$
Let the model $M$ have density $e^{f(x)}$ where $f$ is defined on the support of the model. The cross-entropy of $F(\mathbf{x})$ and $M$ is defined to be
$$H(F(\mathbf{x}), M) = -\mathbb{E}_{F(\mathbf{x})}[\log(e^{f(X)}] = -\mathbb{E}_{F(\mathbf{x})}[f(X)] =-\frac{1}{n}\sum_{i=1}^n f(x_i).\tag{1}$$
Assuming $x$ is a simple random sample, its negative log likelihood is
$$-\log(L(\mathbf{x}))=-\log \prod_{i=1}^n e^{f(x_i)} = -\sum_{i=1}^n f(x_i)\tag{2}$$
by virtue of the properties of logarithms (they convert products to sums).
Expression $(2)$ is a constant $n$ times expression $(1)$. Because loss functions are used in statistics only by comparing them, it makes no difference that one is a (positive) constant times the other. It is in this sense that the negative log likelihood "is a" cross-entropy in the quotation.
It takes a bit more imagination to justify the second assertion of the quotation. The connection with squared error is clear, because for a "Gaussian model" that predicts values $p(x)$ at points $x$, the value of $f$ at any such point is
$$f(x; p, \sigma) = -\frac{1}{2}\left(\log(2\pi \sigma^2) + \frac{(x-p(x))^2}{\sigma^2}\right),$$
which is the squared error $(x-p(x))^2$ but rescaled by $1/(2\sigma^2)$ and shifted by a function of $\sigma$. One way to make the quotation correct is to assume it does not consider $\sigma$ part of the "model"--$\sigma$ must be determined somehow independently of the data. In that case differences between mean squared errors are proportional to differences between cross-entropies or log-likelihoods, thereby making all three equivalent for model fitting purposes.
(Ordinarily, though, $\sigma = \sigma(x)$ is fit as part of the modeling process, in which case the quotation would not be quite correct.)
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
Let the data be $\mathbf{x}=(x_1, \ldots, x_n)$. Write $F(\mathbf{x})$ for the empirical distribution. By definition, for any function $f$,
$$\mathbb{E}_{F(\mathbf{x})}[f(X)] = \frac{1}{n}\sum_{i=1}^
|
6,295
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
|
For readers of the Deep Learning book, I would like to add to the excellent accepted answer that the authors explain their statement in detail in section 5.5.1 namely the Example: Linear Regression as Maximum Likelihood.
There, they list exactly the constraint mentioned in the accepted answer:
$p(y | x) = \mathcal{N}\big(y; \hat{y}(x; w), \sigma^2\big)$. The function $\hat{y}(x; w)$ gives the prediction of the mean of the Gaussian. In this example, we assume that the variance is fixed to some constant $\sigma^2$ chosen by the user.
Then, they show that the minimization of the MSE corresponds to the Maximum Likelihood Estimate and thus the minimization of the cross-entropy between the empirical distribution and $p(y|x)$.
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
|
For readers of the Deep Learning book, I would like to add to the excellent accepted answer that the authors explain their statement in detail in section 5.5.1 namely the Example: Linear Regression as
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
For readers of the Deep Learning book, I would like to add to the excellent accepted answer that the authors explain their statement in detail in section 5.5.1 namely the Example: Linear Regression as Maximum Likelihood.
There, they list exactly the constraint mentioned in the accepted answer:
$p(y | x) = \mathcal{N}\big(y; \hat{y}(x; w), \sigma^2\big)$. The function $\hat{y}(x; w)$ gives the prediction of the mean of the Gaussian. In this example, we assume that the variance is fixed to some constant $\sigma^2$ chosen by the user.
Then, they show that the minimization of the MSE corresponds to the Maximum Likelihood Estimate and thus the minimization of the cross-entropy between the empirical distribution and $p(y|x)$.
|
Why is mean squared error the cross-entropy between the empirical distribution and a Gaussian model?
For readers of the Deep Learning book, I would like to add to the excellent accepted answer that the authors explain their statement in detail in section 5.5.1 namely the Example: Linear Regression as
|
6,296
|
Which search range for determining SVM optimal C and gamma parameters?
|
Check out A practical guide to SVM Classification for some pointers, particularly page 5.
We recommend a "grid-search" on $C$ and $\gamma$ using cross-validation. Various pairs of $(C,\gamma)$ values are tried and the one with the best cross-validation accuracy is
picked. We found that trying exponentially growing sequences of $C$ and $\gamma$ is a
practical method to identify good parameters (for example, $C = 2^{-5},2^{-3},\ldots,2^{15};\gamma = 2^{-15},2^{-13},\ldots,2^{3}$).
Remember to normalize your data first and if you can, gather more data because from the looks of it, your problem might be heavily underdetermined.
|
Which search range for determining SVM optimal C and gamma parameters?
|
Check out A practical guide to SVM Classification for some pointers, particularly page 5.
We recommend a "grid-search" on $C$ and $\gamma$ using cross-validation. Various pairs of $(C,\gamma)$ value
|
Which search range for determining SVM optimal C and gamma parameters?
Check out A practical guide to SVM Classification for some pointers, particularly page 5.
We recommend a "grid-search" on $C$ and $\gamma$ using cross-validation. Various pairs of $(C,\gamma)$ values are tried and the one with the best cross-validation accuracy is
picked. We found that trying exponentially growing sequences of $C$ and $\gamma$ is a
practical method to identify good parameters (for example, $C = 2^{-5},2^{-3},\ldots,2^{15};\gamma = 2^{-15},2^{-13},\ldots,2^{3}$).
Remember to normalize your data first and if you can, gather more data because from the looks of it, your problem might be heavily underdetermined.
|
Which search range for determining SVM optimal C and gamma parameters?
Check out A practical guide to SVM Classification for some pointers, particularly page 5.
We recommend a "grid-search" on $C$ and $\gamma$ using cross-validation. Various pairs of $(C,\gamma)$ value
|
6,297
|
Which search range for determining SVM optimal C and gamma parameters?
|
Check out section 2.3.2 of this paper by Chapelle and Zien. They have a nice heuristic to select a good search range for $\sigma$ of the RBF kernel and $C$ for the SVM. I quote
To determine good values of the remaining free parameters (eg, by CV),
it is important to search on the right scale. We therefore fix default
values for $C$ and $\sigma$ that have the right order of magnitude. In
a $c$-class problem we use the $1/c$ quantile of the pairwise
distances $D^\rho_{ij}$ of all data-points as a default for $\sigma$.
The default for $C$ is the inverses of the empirical variance $s^2$ in
features space, which can be calculated by $s^2 = \frac{1}{n} \sum_i K_{ii} - \frac{1}{n^2}\sum_{i,j} K_{ij}$
from a $n\times n$ kernel
matrix $K$.
Afterwards, they use multiples (e.g. $2^k$ for $k\in \{-2,...,2\}$) of the default value as search range in a grid-search using cross-validation. That always worked very well for me.
Of course, we @ciri said, normalizing the data etc. is always a good idea.
|
Which search range for determining SVM optimal C and gamma parameters?
|
Check out section 2.3.2 of this paper by Chapelle and Zien. They have a nice heuristic to select a good search range for $\sigma$ of the RBF kernel and $C$ for the SVM. I quote
To determine good valu
|
Which search range for determining SVM optimal C and gamma parameters?
Check out section 2.3.2 of this paper by Chapelle and Zien. They have a nice heuristic to select a good search range for $\sigma$ of the RBF kernel and $C$ for the SVM. I quote
To determine good values of the remaining free parameters (eg, by CV),
it is important to search on the right scale. We therefore fix default
values for $C$ and $\sigma$ that have the right order of magnitude. In
a $c$-class problem we use the $1/c$ quantile of the pairwise
distances $D^\rho_{ij}$ of all data-points as a default for $\sigma$.
The default for $C$ is the inverses of the empirical variance $s^2$ in
features space, which can be calculated by $s^2 = \frac{1}{n} \sum_i K_{ii} - \frac{1}{n^2}\sum_{i,j} K_{ij}$
from a $n\times n$ kernel
matrix $K$.
Afterwards, they use multiples (e.g. $2^k$ for $k\in \{-2,...,2\}$) of the default value as search range in a grid-search using cross-validation. That always worked very well for me.
Of course, we @ciri said, normalizing the data etc. is always a good idea.
|
Which search range for determining SVM optimal C and gamma parameters?
Check out section 2.3.2 of this paper by Chapelle and Zien. They have a nice heuristic to select a good search range for $\sigma$ of the RBF kernel and $C$ for the SVM. I quote
To determine good valu
|
6,298
|
How to interpret OOB and confusion matrix for random forest?
|
The confusion matrix is calculated at a specific point determined by the cutoff on the votes. Depending on your needs, i.e., better precision (reduce false positives) or better sensitivity (reduce false negatives) you may prefer a different cutoff.
For this purpose I recommend plotting (i) a ROC curve, (ii) a recall-precision and (iii) a calibrating curve in order to select the cutoff that best fits your purposes. All these can be easily plotted using the 2 following functions from the ROCR R library (available also on CRAN):
pred.obj <- prediction(predictions, labels,...)
performance(pred.obj, measure, ...)
For example:
rf <- randomForest (x,y,...);
OOB.votes <- predict (rf,x,type="prob");
OOB.pred <- OOB.votes[,2];
pred.obj <- prediction (OOB.pred,y);
RP.perf <- performance(pred.obj, "rec","prec");
plot (RP.perf);
ROC.perf <- performance(pred.obj, "fpr","tpr");
plot (ROC.perf);
plot (RP.perf@alpha.values[[1]],RP.perf@x.values[[1]]);
lines (RP.perf@alpha.values[[1]],RP.perf@y.values[[1]]);
lines (ROC.perf@alpha.values[[1]],ROC.perf@x.values[[1]]);
|
How to interpret OOB and confusion matrix for random forest?
|
The confusion matrix is calculated at a specific point determined by the cutoff on the votes. Depending on your needs, i.e., better precision (reduce false positives) or better sensitivity (reduce fal
|
How to interpret OOB and confusion matrix for random forest?
The confusion matrix is calculated at a specific point determined by the cutoff on the votes. Depending on your needs, i.e., better precision (reduce false positives) or better sensitivity (reduce false negatives) you may prefer a different cutoff.
For this purpose I recommend plotting (i) a ROC curve, (ii) a recall-precision and (iii) a calibrating curve in order to select the cutoff that best fits your purposes. All these can be easily plotted using the 2 following functions from the ROCR R library (available also on CRAN):
pred.obj <- prediction(predictions, labels,...)
performance(pred.obj, measure, ...)
For example:
rf <- randomForest (x,y,...);
OOB.votes <- predict (rf,x,type="prob");
OOB.pred <- OOB.votes[,2];
pred.obj <- prediction (OOB.pred,y);
RP.perf <- performance(pred.obj, "rec","prec");
plot (RP.perf);
ROC.perf <- performance(pred.obj, "fpr","tpr");
plot (ROC.perf);
plot (RP.perf@alpha.values[[1]],RP.perf@x.values[[1]]);
lines (RP.perf@alpha.values[[1]],RP.perf@y.values[[1]]);
lines (ROC.perf@alpha.values[[1]],ROC.perf@x.values[[1]]);
|
How to interpret OOB and confusion matrix for random forest?
The confusion matrix is calculated at a specific point determined by the cutoff on the votes. Depending on your needs, i.e., better precision (reduce false positives) or better sensitivity (reduce fal
|
6,299
|
How to interpret OOB and confusion matrix for random forest?
|
Your set is sharply unbalanced -- RF usually fails in this scenario (i.e. predicts well only the bigger class).
You should try balancing your set either by sampling the "0" class only to have about the same size as "1" class or by playing with classwt parameter.
|
How to interpret OOB and confusion matrix for random forest?
|
Your set is sharply unbalanced -- RF usually fails in this scenario (i.e. predicts well only the bigger class).
You should try balancing your set either by sampling the "0" class only to have about t
|
How to interpret OOB and confusion matrix for random forest?
Your set is sharply unbalanced -- RF usually fails in this scenario (i.e. predicts well only the bigger class).
You should try balancing your set either by sampling the "0" class only to have about the same size as "1" class or by playing with classwt parameter.
|
How to interpret OOB and confusion matrix for random forest?
Your set is sharply unbalanced -- RF usually fails in this scenario (i.e. predicts well only the bigger class).
You should try balancing your set either by sampling the "0" class only to have about t
|
6,300
|
How to interpret OOB and confusion matrix for random forest?
|
Based on your confusion matrix, you've got 5,908 data points and the vast, vast majority of them are of type 0 ('employee stayed'). The classifier can therefore get away with being "lazy" and picking the majority class unless it's absolutely certain that an example belongs to the other class. Note that your overall error rate is ~7%, which is quite close to the percent of Class1 examples!
You've got a few options:
Discard Class0 examples until you have roughly balanced classes. I don't know if there's literature on how to choose an optimally representative subset (maybe someone else can weigh in?), but you could start by dropping examples at random. You can pass a subset argument to randomForest, which should make this trivial to test.
Adjust your loss function/class weights to compensate for the disproportionate number of Class0. You essentially want to make it much more expensive for the classifier to misclassify a Class1 example than Class0 one. It might make sense to try Class0 = 1/0.07 ~= 14x Class1 to start, but you may want to adjust this based on your business demands (how much worse is one kind of error). I think the classwt parameter is what you're looking for here.
Use stratified sampling to ensure that you've got examples from both classes in the trees' training data. It's possible that some of your trees were trained on only Class0 data, which will obviously bode poorly for their generalization performance. Check out the strata argument.
|
How to interpret OOB and confusion matrix for random forest?
|
Based on your confusion matrix, you've got 5,908 data points and the vast, vast majority of them are of type 0 ('employee stayed'). The classifier can therefore get away with being "lazy" and picking
|
How to interpret OOB and confusion matrix for random forest?
Based on your confusion matrix, you've got 5,908 data points and the vast, vast majority of them are of type 0 ('employee stayed'). The classifier can therefore get away with being "lazy" and picking the majority class unless it's absolutely certain that an example belongs to the other class. Note that your overall error rate is ~7%, which is quite close to the percent of Class1 examples!
You've got a few options:
Discard Class0 examples until you have roughly balanced classes. I don't know if there's literature on how to choose an optimally representative subset (maybe someone else can weigh in?), but you could start by dropping examples at random. You can pass a subset argument to randomForest, which should make this trivial to test.
Adjust your loss function/class weights to compensate for the disproportionate number of Class0. You essentially want to make it much more expensive for the classifier to misclassify a Class1 example than Class0 one. It might make sense to try Class0 = 1/0.07 ~= 14x Class1 to start, but you may want to adjust this based on your business demands (how much worse is one kind of error). I think the classwt parameter is what you're looking for here.
Use stratified sampling to ensure that you've got examples from both classes in the trees' training data. It's possible that some of your trees were trained on only Class0 data, which will obviously bode poorly for their generalization performance. Check out the strata argument.
|
How to interpret OOB and confusion matrix for random forest?
Based on your confusion matrix, you've got 5,908 data points and the vast, vast majority of them are of type 0 ('employee stayed'). The classifier can therefore get away with being "lazy" and picking
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.