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
|
|---|---|---|---|---|---|---|
46,401
|
How Do I Know If A Markov Chain Follows The Markov Property?
|
An initial and simple test for this would be to see if the data show evidence of the weather being affected by the weather two days ago when you're already conditioning on the weather one day ago. To do this you would form a $3 \times 3 \times 3$ contingency table for three consecutive days and use this to conduct a test of conditional independence to see if the Markov property is violated. If you find evidence that the weather two days ago is not independent of the weather today, conditional on the weather one day ago, that is a violation of the Markov property (and suggests that there is auto-correlation in the data that goes back more than one period).
|
How Do I Know If A Markov Chain Follows The Markov Property?
|
An initial and simple test for this would be to see if the data show evidence of the weather being affected by the weather two days ago when you're already conditioning on the weather one day ago. To
|
How Do I Know If A Markov Chain Follows The Markov Property?
An initial and simple test for this would be to see if the data show evidence of the weather being affected by the weather two days ago when you're already conditioning on the weather one day ago. To do this you would form a $3 \times 3 \times 3$ contingency table for three consecutive days and use this to conduct a test of conditional independence to see if the Markov property is violated. If you find evidence that the weather two days ago is not independent of the weather today, conditional on the weather one day ago, that is a violation of the Markov property (and suggests that there is auto-correlation in the data that goes back more than one period).
|
How Do I Know If A Markov Chain Follows The Markov Property?
An initial and simple test for this would be to see if the data show evidence of the weather being affected by the weather two days ago when you're already conditioning on the weather one day ago. To
|
46,402
|
How Do I Know If A Markov Chain Follows The Markov Property?
|
You can easily test this by doing multinomial regression.
To fit the null hypothesis of a first order Markov chain you would include the previous state as a covariate in the model. You then estimate 6 parameters which translates into an estimate of the
$3\times3$ transition matrix.
To fit the alternative hypothesis that you have a 2. order Markov chain, you instead include both the state at time $t-1$ and $t-2$ and an interaction between those as covariates. You then estimate 18 parameters which translates into an estimate of $27$ transition probabilities (from each of the $3\times 3=9$ second order states the chain can transition only to three possible states).
You can then test the null against the alternative using a likelihood ratio test in the usual way.
The following shows an R implementation of the above as well as the test of conditional independence proposed by @Ben via log-linear models. The resulting identical LRT-statistics suggest that the tests are equivalent.
# Simulate some data
n <- 100
set.seed(4)
x <- factor(sample(1:3, n, replace = TRUE))
y <- x[-(1:2)]
xlag1 <- x[-c(1,n)]
xlag2 <- x[-((n - 1):n)]
# Fit the null hypothesis
library(VGAM)
#> Loading required package: stats4
#> Loading required package: splines
mod0 <- vglm(y ~ xlag1, family = multinomial())
predictvglm(mod0, newdata = data.frame(xlag1 = factor(1:3)), type = "response")
#> 1 2 3
#> 1 0.4166667 0.3055556 0.2777778
#> 2 0.3636364 0.3636364 0.2727273
#> 3 0.3103448 0.3448276 0.3448276
# Fit the alternative
mod1 <- update(mod0, .~xlag1*xlag2)
predictvglm(mod1, newdata = expand.grid(xlag1 = factor(1:3),xlag2 = factor(1:3)), type = "response")
#> 1 2 3
#> 1 0.2000000 0.46666667 0.3333333
#> 2 0.3636364 0.18181818 0.4545455
#> 3 0.3333333 0.33333333 0.3333333
#> 4 0.7500000 0.08333333 0.1666667
#> 5 0.3333333 0.50000000 0.1666667
#> 6 0.4444444 0.33333333 0.2222222
#> 7 0.3333333 0.33333333 0.3333333
#> 8 0.4000000 0.40000000 0.2000000
#> 9 0.1818182 0.36363636 0.4545455
# Test the null against the alternative
anova(mod0, mod1, test="LRT", type = "I")
#> Analysis of Deviance Table
#>
#> Model 1: y ~ xlag1
#> Model 2: y ~ xlag1 + xlag2 + xlag1:xlag2
#> Resid. Df Resid. Dev Df Deviance Pr(>Chi)
#> 1 190 213.56
#> 2 178 198.24 12 15.322 0.2243
# Testing conditional independence as suggested Ben via log-linear models
tables <- table(y,xlag2,xlag1)
tables
#> , , xlag1 = 1
#>
#> xlag2
#> y 1 2 3
#> 1 3 9 3
#> 2 7 1 3
#> 3 5 2 3
#>
#> , , xlag1 = 2
#>
#> xlag2
#> y 1 2 3
#> 1 4 4 4
#> 2 2 6 4
#> 3 5 2 2
#>
#> , , xlag1 = 3
#>
#> xlag2
#> y 1 2 3
#> 1 3 4 2
#> 2 3 3 4
#> 3 3 2 5
library(MASS)
loglin(tables, list(c(1,3),c(2,3)))
#> 2 iterations: deviation 0
#> $lrt
#> [1] 15.32195
#>
#> $pearson
#> [1] 14.73557
#>
#> $df
#> [1] 12
#>
#> $margin
#> $margin[[1]]
#> [1] "y" "xlag1"
#>
#> $margin[[2]]
#> [1] "xlag2" "xlag1"
```
|
How Do I Know If A Markov Chain Follows The Markov Property?
|
You can easily test this by doing multinomial regression.
To fit the null hypothesis of a first order Markov chain you would include the previous state as a covariate in the model. You then estimate
|
How Do I Know If A Markov Chain Follows The Markov Property?
You can easily test this by doing multinomial regression.
To fit the null hypothesis of a first order Markov chain you would include the previous state as a covariate in the model. You then estimate 6 parameters which translates into an estimate of the
$3\times3$ transition matrix.
To fit the alternative hypothesis that you have a 2. order Markov chain, you instead include both the state at time $t-1$ and $t-2$ and an interaction between those as covariates. You then estimate 18 parameters which translates into an estimate of $27$ transition probabilities (from each of the $3\times 3=9$ second order states the chain can transition only to three possible states).
You can then test the null against the alternative using a likelihood ratio test in the usual way.
The following shows an R implementation of the above as well as the test of conditional independence proposed by @Ben via log-linear models. The resulting identical LRT-statistics suggest that the tests are equivalent.
# Simulate some data
n <- 100
set.seed(4)
x <- factor(sample(1:3, n, replace = TRUE))
y <- x[-(1:2)]
xlag1 <- x[-c(1,n)]
xlag2 <- x[-((n - 1):n)]
# Fit the null hypothesis
library(VGAM)
#> Loading required package: stats4
#> Loading required package: splines
mod0 <- vglm(y ~ xlag1, family = multinomial())
predictvglm(mod0, newdata = data.frame(xlag1 = factor(1:3)), type = "response")
#> 1 2 3
#> 1 0.4166667 0.3055556 0.2777778
#> 2 0.3636364 0.3636364 0.2727273
#> 3 0.3103448 0.3448276 0.3448276
# Fit the alternative
mod1 <- update(mod0, .~xlag1*xlag2)
predictvglm(mod1, newdata = expand.grid(xlag1 = factor(1:3),xlag2 = factor(1:3)), type = "response")
#> 1 2 3
#> 1 0.2000000 0.46666667 0.3333333
#> 2 0.3636364 0.18181818 0.4545455
#> 3 0.3333333 0.33333333 0.3333333
#> 4 0.7500000 0.08333333 0.1666667
#> 5 0.3333333 0.50000000 0.1666667
#> 6 0.4444444 0.33333333 0.2222222
#> 7 0.3333333 0.33333333 0.3333333
#> 8 0.4000000 0.40000000 0.2000000
#> 9 0.1818182 0.36363636 0.4545455
# Test the null against the alternative
anova(mod0, mod1, test="LRT", type = "I")
#> Analysis of Deviance Table
#>
#> Model 1: y ~ xlag1
#> Model 2: y ~ xlag1 + xlag2 + xlag1:xlag2
#> Resid. Df Resid. Dev Df Deviance Pr(>Chi)
#> 1 190 213.56
#> 2 178 198.24 12 15.322 0.2243
# Testing conditional independence as suggested Ben via log-linear models
tables <- table(y,xlag2,xlag1)
tables
#> , , xlag1 = 1
#>
#> xlag2
#> y 1 2 3
#> 1 3 9 3
#> 2 7 1 3
#> 3 5 2 3
#>
#> , , xlag1 = 2
#>
#> xlag2
#> y 1 2 3
#> 1 4 4 4
#> 2 2 6 4
#> 3 5 2 2
#>
#> , , xlag1 = 3
#>
#> xlag2
#> y 1 2 3
#> 1 3 4 2
#> 2 3 3 4
#> 3 3 2 5
library(MASS)
loglin(tables, list(c(1,3),c(2,3)))
#> 2 iterations: deviation 0
#> $lrt
#> [1] 15.32195
#>
#> $pearson
#> [1] 14.73557
#>
#> $df
#> [1] 12
#>
#> $margin
#> $margin[[1]]
#> [1] "y" "xlag1"
#>
#> $margin[[2]]
#> [1] "xlag2" "xlag1"
```
|
How Do I Know If A Markov Chain Follows The Markov Property?
You can easily test this by doing multinomial regression.
To fit the null hypothesis of a first order Markov chain you would include the previous state as a covariate in the model. You then estimate
|
46,403
|
Can we consider the loadings as a proxy for correlation, in a Principal Component Analysis (PCA)?
|
You can answer the questions yourself if you look at how the PCA is defined. For this, let $\mathbb{X}$ denote the $n\times p$ data matrix, and let $S = [s_{ij}]$ be the sample covariance matrix, e.g. $S = (n-1)^{-1} (\mathbb{X}^\top H \mathbb{X})$, where $H = I_n - \frac{1}{b}1_n1_n^\top$ is the centering matrix.
For simplicity, let's assume $\mathbb{X}$ has full rank. Consider the spectral decomposition of $S$,
$$S = \Gamma\Lambda \Gamma^\top,$$ where $\Gamma = [\gamma_1|\cdots|\gamma_p]$, $\Lambda = \text{diag}(\lambda_1,\ldots,\lambda_p)$, with $\gamma_i$ the $i$th eigenvector associated to the $i$the eigen value $\lambda_i$. The $i$th principal component (PC) is defined as
$$
y_i = X\gamma_i,
$$
and the sample product moment correlation between the $i$the PC and, say, $X_{j}$ the $j$th variable (i.e. the $j$the column of $\mathbb{X}$) is
$$r_{y_i, X_j} = \frac{S_{y_i,X_j}}{\sqrt{S_{y_i}^2 S_{X_j}^2}},$$
where $S_{y_i, X_j}$ is the sample covariance between $y_i$ and $X_j$. With some algebra, it is possible to show that
\begin{align*}
r_{y_i, X_j} = \frac{\gamma_{ij}\sqrt{\lambda_i}}{s_{kk}}, \text{for all }i,j\in\{1,\ldots,p\},\tag{*}
\end{align*}
where $\gamma_{ij}$ is the $j$the element of $\gamma_{i}$ and $s_{kk}$ is the standard deviation of $X_j$.
As you can see from (*), both the sign and the magnitude of the correlation are related to the loadings of the PCA, e.g. the eigenvectors of $S$. However, the correlation itself depends also on the variance of $X_j$ and on the $i$th eigenvalue. Thus a loading of $\pm 1$ doesn't necessarily imply a correlation equal to $\pm 1$. However, the higher the loading the higher the correlation, ceteris paribus.
Be careful when you interpret the results of a PCA, because the sign of the correlation is arbitrary, because if $\gamma_i$ is an eigenvector of $S$, then $-\gamma_i$ is also a valid eigenvector. When interpreting the PCA, indeed, we care about the sign and magnitude of loadings of a variable relative to others.
For instance, if $X_1$ and $X_2$ have got high loadings with a different sign, then we can say that they are correlated with the PC in question, with one variable being positively correlated and the other negatively correlated; but it is not meaningful to ask which one has got positive and which negative value since the sign is arbitrary.
|
Can we consider the loadings as a proxy for correlation, in a Principal Component Analysis (PCA)?
|
You can answer the questions yourself if you look at how the PCA is defined. For this, let $\mathbb{X}$ denote the $n\times p$ data matrix, and let $S = [s_{ij}]$ be the sample covariance matrix, e.g.
|
Can we consider the loadings as a proxy for correlation, in a Principal Component Analysis (PCA)?
You can answer the questions yourself if you look at how the PCA is defined. For this, let $\mathbb{X}$ denote the $n\times p$ data matrix, and let $S = [s_{ij}]$ be the sample covariance matrix, e.g. $S = (n-1)^{-1} (\mathbb{X}^\top H \mathbb{X})$, where $H = I_n - \frac{1}{b}1_n1_n^\top$ is the centering matrix.
For simplicity, let's assume $\mathbb{X}$ has full rank. Consider the spectral decomposition of $S$,
$$S = \Gamma\Lambda \Gamma^\top,$$ where $\Gamma = [\gamma_1|\cdots|\gamma_p]$, $\Lambda = \text{diag}(\lambda_1,\ldots,\lambda_p)$, with $\gamma_i$ the $i$th eigenvector associated to the $i$the eigen value $\lambda_i$. The $i$th principal component (PC) is defined as
$$
y_i = X\gamma_i,
$$
and the sample product moment correlation between the $i$the PC and, say, $X_{j}$ the $j$th variable (i.e. the $j$the column of $\mathbb{X}$) is
$$r_{y_i, X_j} = \frac{S_{y_i,X_j}}{\sqrt{S_{y_i}^2 S_{X_j}^2}},$$
where $S_{y_i, X_j}$ is the sample covariance between $y_i$ and $X_j$. With some algebra, it is possible to show that
\begin{align*}
r_{y_i, X_j} = \frac{\gamma_{ij}\sqrt{\lambda_i}}{s_{kk}}, \text{for all }i,j\in\{1,\ldots,p\},\tag{*}
\end{align*}
where $\gamma_{ij}$ is the $j$the element of $\gamma_{i}$ and $s_{kk}$ is the standard deviation of $X_j$.
As you can see from (*), both the sign and the magnitude of the correlation are related to the loadings of the PCA, e.g. the eigenvectors of $S$. However, the correlation itself depends also on the variance of $X_j$ and on the $i$th eigenvalue. Thus a loading of $\pm 1$ doesn't necessarily imply a correlation equal to $\pm 1$. However, the higher the loading the higher the correlation, ceteris paribus.
Be careful when you interpret the results of a PCA, because the sign of the correlation is arbitrary, because if $\gamma_i$ is an eigenvector of $S$, then $-\gamma_i$ is also a valid eigenvector. When interpreting the PCA, indeed, we care about the sign and magnitude of loadings of a variable relative to others.
For instance, if $X_1$ and $X_2$ have got high loadings with a different sign, then we can say that they are correlated with the PC in question, with one variable being positively correlated and the other negatively correlated; but it is not meaningful to ask which one has got positive and which negative value since the sign is arbitrary.
|
Can we consider the loadings as a proxy for correlation, in a Principal Component Analysis (PCA)?
You can answer the questions yourself if you look at how the PCA is defined. For this, let $\mathbb{X}$ denote the $n\times p$ data matrix, and let $S = [s_{ij}]$ be the sample covariance matrix, e.g.
|
46,404
|
Tweedie Dispersion Parameter Estimation Methods
|
Tweedie generalized linear models assume a mean-variance relationship with variance power $p$, defined by
$$E(y_i)=\mu_i$$
and
$${\rm var}(y_i)=\phi \mu_i^p$$
where $y_i$ is the $i$th observation, $\mu_i$ is the expected value, $\phi$ is the dispersion and $p$ is the mean-variance power parameter, also called the Tweedie index parameter.
The purpose of the tweedie.profile function is to estimate $p$ by profile maximum likelihood.
The dispersion $\phi$ is a nuisance parameter in the profile likelihood, as are the glm regression coefficients.
It is a requirement of the profile likelihood method in statistics that all nuisance parameters be set to their maximum likelihood estimates.
It would be invalid to use the Pearson estimator for $\phi$ is this context because then the resulting likelihood for $p$ would not be a profile likelihood and differences in log-likelihoods would not have their usual meaning.
We recommend that you use tweedie.profile to guide your choice of the Tweedie index parameter. Then you can fit a generalized linear model treating $p$ as a known parameter, for example by:
library(statmod)
fit <- glm(y~x, family=tweedie(var.power=p, link.power=0))
summary(fit)
In the above code, the summary function in R will by default use the Pearson estimator for $\phi$.
The use of the Pearson estimator is not specific to Tweedie distributions, but is a generic property of the summary.glm function in R.
The fact that tweedie.profile and summary.glm use different estimators for $\phi$ does not cause any problems for the process.
As hinted at in Section 6.8 of our book (Dunn & Smyth, 2018), I would ideally prefer to use modified profile likelihood for both $p$ and $\phi$, but that is difficult to implement. The above process is much simpler and will still give good results.
I see that I answered a related question from another poster 3 years ago:
GLM Tweedie dispersion parameter.
Reference
Dunn PK, Smyth GK (2018). Generalized linear models with examples in R. Springer, New York, NY.
|
Tweedie Dispersion Parameter Estimation Methods
|
Tweedie generalized linear models assume a mean-variance relationship with variance power $p$, defined by
$$E(y_i)=\mu_i$$
and
$${\rm var}(y_i)=\phi \mu_i^p$$
where $y_i$ is the $i$th observation, $\m
|
Tweedie Dispersion Parameter Estimation Methods
Tweedie generalized linear models assume a mean-variance relationship with variance power $p$, defined by
$$E(y_i)=\mu_i$$
and
$${\rm var}(y_i)=\phi \mu_i^p$$
where $y_i$ is the $i$th observation, $\mu_i$ is the expected value, $\phi$ is the dispersion and $p$ is the mean-variance power parameter, also called the Tweedie index parameter.
The purpose of the tweedie.profile function is to estimate $p$ by profile maximum likelihood.
The dispersion $\phi$ is a nuisance parameter in the profile likelihood, as are the glm regression coefficients.
It is a requirement of the profile likelihood method in statistics that all nuisance parameters be set to their maximum likelihood estimates.
It would be invalid to use the Pearson estimator for $\phi$ is this context because then the resulting likelihood for $p$ would not be a profile likelihood and differences in log-likelihoods would not have their usual meaning.
We recommend that you use tweedie.profile to guide your choice of the Tweedie index parameter. Then you can fit a generalized linear model treating $p$ as a known parameter, for example by:
library(statmod)
fit <- glm(y~x, family=tweedie(var.power=p, link.power=0))
summary(fit)
In the above code, the summary function in R will by default use the Pearson estimator for $\phi$.
The use of the Pearson estimator is not specific to Tweedie distributions, but is a generic property of the summary.glm function in R.
The fact that tweedie.profile and summary.glm use different estimators for $\phi$ does not cause any problems for the process.
As hinted at in Section 6.8 of our book (Dunn & Smyth, 2018), I would ideally prefer to use modified profile likelihood for both $p$ and $\phi$, but that is difficult to implement. The above process is much simpler and will still give good results.
I see that I answered a related question from another poster 3 years ago:
GLM Tweedie dispersion parameter.
Reference
Dunn PK, Smyth GK (2018). Generalized linear models with examples in R. Springer, New York, NY.
|
Tweedie Dispersion Parameter Estimation Methods
Tweedie generalized linear models assume a mean-variance relationship with variance power $p$, defined by
$$E(y_i)=\mu_i$$
and
$${\rm var}(y_i)=\phi \mu_i^p$$
where $y_i$ is the $i$th observation, $\m
|
46,405
|
How to improve difference-in-differences graph?
|
I can tell that the treatment group starts out lower than the control group and, while the treatment group winds up lower than the control group, the treatment group has closed the gap. For difference-in-differences, this is exactly what I would want to see.
One possible improvement is to put standard errors on the four point estimates. Maybe more useful than that would be to plot the differences between control and treatment groups along with the standard errors of the differences.
If you just want to look fancy, bright colors tend to do the trick, though they will convey no additional information.
|
How to improve difference-in-differences graph?
|
I can tell that the treatment group starts out lower than the control group and, while the treatment group winds up lower than the control group, the treatment group has closed the gap. For difference
|
How to improve difference-in-differences graph?
I can tell that the treatment group starts out lower than the control group and, while the treatment group winds up lower than the control group, the treatment group has closed the gap. For difference-in-differences, this is exactly what I would want to see.
One possible improvement is to put standard errors on the four point estimates. Maybe more useful than that would be to plot the differences between control and treatment groups along with the standard errors of the differences.
If you just want to look fancy, bright colors tend to do the trick, though they will convey no additional information.
|
How to improve difference-in-differences graph?
I can tell that the treatment group starts out lower than the control group and, while the treatment group winds up lower than the control group, the treatment group has closed the gap. For difference
|
46,406
|
How to improve difference-in-differences graph?
|
This is what I finally did, perhaps this helps someone with a similar scenario:
|
How to improve difference-in-differences graph?
|
This is what I finally did, perhaps this helps someone with a similar scenario:
|
How to improve difference-in-differences graph?
This is what I finally did, perhaps this helps someone with a similar scenario:
|
How to improve difference-in-differences graph?
This is what I finally did, perhaps this helps someone with a similar scenario:
|
46,407
|
Reframing a HMM problem as an RNN
|
The hidden nodes (states) in an HMM are random variables, while in an RNN only the input nodes could be considered random variables, all the other nodes are just deterministic nonlinear functions.
Thus, it is difficult to formulate an HMM with an RNN. However, some attempts have been made to combine the ideas of dynamic Bayesian networks (DBNs), of which HMMs would be examples, and neural networks, e.g. the VRRN, alpha-nets, or GenHMM. How much those still resemble vanilla RNNs or DBNs is up for discussion.
|
Reframing a HMM problem as an RNN
|
The hidden nodes (states) in an HMM are random variables, while in an RNN only the input nodes could be considered random variables, all the other nodes are just deterministic nonlinear functions.
Thu
|
Reframing a HMM problem as an RNN
The hidden nodes (states) in an HMM are random variables, while in an RNN only the input nodes could be considered random variables, all the other nodes are just deterministic nonlinear functions.
Thus, it is difficult to formulate an HMM with an RNN. However, some attempts have been made to combine the ideas of dynamic Bayesian networks (DBNs), of which HMMs would be examples, and neural networks, e.g. the VRRN, alpha-nets, or GenHMM. How much those still resemble vanilla RNNs or DBNs is up for discussion.
|
Reframing a HMM problem as an RNN
The hidden nodes (states) in an HMM are random variables, while in an RNN only the input nodes could be considered random variables, all the other nodes are just deterministic nonlinear functions.
Thu
|
46,408
|
Reframing a HMM problem as an RNN
|
Neural networks can be used to amortize the optimization part, effectively learning an adaptive solution given a corpus of data.
The connection with VAEs is pretty easy to see here.
So, in your notation, instead of optimizing for $Q*$, you would learn an approximate posterior.
See the Structured Inference Networks and Deep Markov Models presented in:
R. G. Krishnan, U. Shalit, and D. Sontag, “Structured Inference Networks for Nonlinear State Space Models.” 31st AAAI Conference on Artificial Intelligence, AAAI, 2017. doi: 10.48550/ARXIV.1609.09869.
|
Reframing a HMM problem as an RNN
|
Neural networks can be used to amortize the optimization part, effectively learning an adaptive solution given a corpus of data.
The connection with VAEs is pretty easy to see here.
So, in your notati
|
Reframing a HMM problem as an RNN
Neural networks can be used to amortize the optimization part, effectively learning an adaptive solution given a corpus of data.
The connection with VAEs is pretty easy to see here.
So, in your notation, instead of optimizing for $Q*$, you would learn an approximate posterior.
See the Structured Inference Networks and Deep Markov Models presented in:
R. G. Krishnan, U. Shalit, and D. Sontag, “Structured Inference Networks for Nonlinear State Space Models.” 31st AAAI Conference on Artificial Intelligence, AAAI, 2017. doi: 10.48550/ARXIV.1609.09869.
|
Reframing a HMM problem as an RNN
Neural networks can be used to amortize the optimization part, effectively learning an adaptive solution given a corpus of data.
The connection with VAEs is pretty easy to see here.
So, in your notati
|
46,409
|
Wilcoxon rank sum test correct vectors order
|
In R, the Wilcoxon rank sum test statistic $W$ is calculated as the sum of ranks in the first sample minus the expected value of the rank sum of $x$ under the null ($\frac{m^2+m}{2}$, where $m$ is the sample size of $x$). Since the distribution of rank sums under the null is symmetric about it's mean, this gives equivalent inference as using the sum of ranks of the second variable as the test statistic, which you can see in the equal p-values for both your tests. (There are a few different forms of calculating the statistic for this test, and, as noted in the R help files for wilcox.test, none of these is canonical.)
Here's the math by hand for calculating $W$ the way R does for your example. First, note that $E[\text{rank}(x)] = \frac{64 + 8}{2} = 36$.
Obs
x
rank(x)
y
rank(y)
1
1
3.5
2
9
2
2
9
4
15
3
3
13
1
3.5
4
3
13
1
3.5
5
3
13
1
3.5
6
5
16
2
9
7
2
9
2
9
8
1
3.5
1
3.5
80 — 36 = 44
56 – 36 = 20
Ranking:
The observations with value $1$ share the $1^{\text{st}} - 6^{\text{th}}$ ranks, so they each get the average of $1+2+3+4+5+6 = 3.5$
For similar reasons the observations with value $2$, which share the $7^{\text{th}} - 11^{\text{th}}$ ranks, each get the average of those ranks: $9$.
The observations with value $3$ each get average rank $13$.
The observations with values $4$ and $5$ get ranks $15$ and $16$, respectively.
You can see how switching the order of x and y in the command would produce the two different test statistic values. Since these test statistics are deviations for the mean of the distribution of rank sums under the null hypothesis, they give the same probability of being observed, assuming the null hypothesis is true. So p-value = 0.2063 regardless of order, and your conclusions—almost certainly failing to reject the null hypothesis unless you are using a huge value of $\alpha$—are the same in either case.
|
Wilcoxon rank sum test correct vectors order
|
In R, the Wilcoxon rank sum test statistic $W$ is calculated as the sum of ranks in the first sample minus the expected value of the rank sum of $x$ under the null ($\frac{m^2+m}{2}$, where $m$ is th
|
Wilcoxon rank sum test correct vectors order
In R, the Wilcoxon rank sum test statistic $W$ is calculated as the sum of ranks in the first sample minus the expected value of the rank sum of $x$ under the null ($\frac{m^2+m}{2}$, where $m$ is the sample size of $x$). Since the distribution of rank sums under the null is symmetric about it's mean, this gives equivalent inference as using the sum of ranks of the second variable as the test statistic, which you can see in the equal p-values for both your tests. (There are a few different forms of calculating the statistic for this test, and, as noted in the R help files for wilcox.test, none of these is canonical.)
Here's the math by hand for calculating $W$ the way R does for your example. First, note that $E[\text{rank}(x)] = \frac{64 + 8}{2} = 36$.
Obs
x
rank(x)
y
rank(y)
1
1
3.5
2
9
2
2
9
4
15
3
3
13
1
3.5
4
3
13
1
3.5
5
3
13
1
3.5
6
5
16
2
9
7
2
9
2
9
8
1
3.5
1
3.5
80 — 36 = 44
56 – 36 = 20
Ranking:
The observations with value $1$ share the $1^{\text{st}} - 6^{\text{th}}$ ranks, so they each get the average of $1+2+3+4+5+6 = 3.5$
For similar reasons the observations with value $2$, which share the $7^{\text{th}} - 11^{\text{th}}$ ranks, each get the average of those ranks: $9$.
The observations with value $3$ each get average rank $13$.
The observations with values $4$ and $5$ get ranks $15$ and $16$, respectively.
You can see how switching the order of x and y in the command would produce the two different test statistic values. Since these test statistics are deviations for the mean of the distribution of rank sums under the null hypothesis, they give the same probability of being observed, assuming the null hypothesis is true. So p-value = 0.2063 regardless of order, and your conclusions—almost certainly failing to reject the null hypothesis unless you are using a huge value of $\alpha$—are the same in either case.
|
Wilcoxon rank sum test correct vectors order
In R, the Wilcoxon rank sum test statistic $W$ is calculated as the sum of ranks in the first sample minus the expected value of the rank sum of $x$ under the null ($\frac{m^2+m}{2}$, where $m$ is th
|
46,410
|
What is G-computation and G-estimation in causal inference
|
This is a short beginner-friendly guide to g-computation for estimating the average treatment effect https://github.com/kathoffman/causal-inference-visual-guides/blob/master/visual-guides/G-Computation.pdf .
A more in-depth introduction can be found at https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6074945/ .
The g-formula is particularly useful when there is time-varying exposure and time-varying confounding. Standard methods, like multivariable regression, will yield bias effect estimates in these scenarios while g-formula based methods will remain unbiased.
As an example, here is a recent paper that compares using a method based on the g-computation formula, along with a "question-first" approach (i.e., starting with the estimand of interest) compared to using cox proportional hazards for estimating the effect of corticosteroids on covid mortality, https://www.medrxiv.org/content/10.1101/2022.05.27.22275037v4
The authors use an RCT as a benchmark for the "true" effect and show that the modern causal inference g-method recovers the truth where the standard approaches fails.
|
What is G-computation and G-estimation in causal inference
|
This is a short beginner-friendly guide to g-computation for estimating the average treatment effect https://github.com/kathoffman/causal-inference-visual-guides/blob/master/visual-guides/G-Computatio
|
What is G-computation and G-estimation in causal inference
This is a short beginner-friendly guide to g-computation for estimating the average treatment effect https://github.com/kathoffman/causal-inference-visual-guides/blob/master/visual-guides/G-Computation.pdf .
A more in-depth introduction can be found at https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6074945/ .
The g-formula is particularly useful when there is time-varying exposure and time-varying confounding. Standard methods, like multivariable regression, will yield bias effect estimates in these scenarios while g-formula based methods will remain unbiased.
As an example, here is a recent paper that compares using a method based on the g-computation formula, along with a "question-first" approach (i.e., starting with the estimand of interest) compared to using cox proportional hazards for estimating the effect of corticosteroids on covid mortality, https://www.medrxiv.org/content/10.1101/2022.05.27.22275037v4
The authors use an RCT as a benchmark for the "true" effect and show that the modern causal inference g-method recovers the truth where the standard approaches fails.
|
What is G-computation and G-estimation in causal inference
This is a short beginner-friendly guide to g-computation for estimating the average treatment effect https://github.com/kathoffman/causal-inference-visual-guides/blob/master/visual-guides/G-Computatio
|
46,411
|
What is the distribution of a random linear combination of gamma random variables?
|
A direct attack (via integration) on computing the density looks intractable.
Instead, we may more easily compute the characteristic function of $Y$ (when the scale factor $b=1,$ which we may assume without any loss of generality simply by changing the units in which we express $Y$) as
$$\begin{aligned}
\phi_Y(t;a) &= E\left[e^{itY}\right] = E\left[e^{it(UX_1+(1-U)X_2)}\right] = E_U\left[E_{X_1,X_2}\left[e^{it(UX_1+(1-U)X_2)}\right]\right]\\
&= E_U\left[ E_{X_1} \left[e^{it UX_1}\right]\, E_{X_2} \left[e^{it (1-U)X_2}\right]\right]\\
&= E_U\left[(1 - i U t)^{-a}\, (1 - i(1-U)t)^{-a}\right]\\
&= \int_0^1 \left((1 - iut)(1 - i(1-u)t)\right)^{-a}\,\mathrm{d}u\\
&= \frac{_2F_1\left(1, 2-2a, 2-a; \frac{i}{2i+t}\right)\ {-}\ _2F_1\left(1, 2-2a, 2-a; \frac{i+t}{2i + t}\right)}{(a-1)t(2i + t)(1 - it)^{a-1}}.
\end{aligned}$$
The hypergeo library for R will efficiently compute these hypergeometric functions, as shown in these graphs of $\phi_Y$ for a range of $a.$
The solid graph plots the real part of $\phi_Y$ and the dotted graph plots its imaginary part.
(There is a technical problem: the foregoing formula is not defined for positive integral values of $a.$ You can get close enough by computing the average of $\phi_Y(t;a\pm2\epsilon)$ when $a$ is within $\epsilon$ of an integer and $\epsilon$ is small. It doesn't have to be terribly small for this to be highly accurate; I used $\epsilon = 10^{-5}.$ Smaller values will cause too much loss of precision in double precision floating point calculations.)
That answers the question. However, often it's more useful to have a density or distribution function. Either can be obtained through a Fourier transform. The density, for instance, is
$$f_Y(y;a) = \frac{1}{2\pi}\int_{\mathbb R} e^{- i y t} \phi_Y(t;a)\,\mathrm{d}t.$$
Numerical integration is possible, albeit a little slow for small values of $a.$ For $a=3/2$ it took half a minute to generate 101 points on the curve below, which matches the histogram of 100,000 values of $Y$ generated directly from its definition.
For $a=6$ the time dropped to four seconds; for $a=7.5$ to under half a second; etc. The timing is a rather irregular function of $a$ (odd multiples of $1/2$ tend to be very quick to compute) so take some care if you need many evaluations of $f_Y.$
This is the full R code.
#
# The characteristic function of Y.
#
library(hypergeo)
phi. <- function(t, a) {
(hypergeo(1, 2 - 2*a, 2 - a, 1.i / (2.i + t)) -
hypergeo(1, 2 - 2*a, 2 - a, (1.i + t) / (2.i + t))) /
(t * (2.i + t) * (1 - 1.i * t)^(a-1) * (1 - a))
}
phi <- function(t, a, eps=1e-5) {
ifelse(t == 0, 1,
if(isTRUE(abs(a - round(a)) > eps)) phi.(t, a) else {
(phi.(t, a - 2*eps) + phi.(t, a + 2*eps)) / 2
})
}
#
# Test `phi` by plotting it.
#
par(mfrow=c(1,3))
for (s in c(bquote(1/4), bquote(3/2), bquote(10))) {
a <- eval(s)
plot(c(-3,3), c(-1,1), type="n",
ylab="", yaxp=c(-1,1,2),
xlab=expression(italic(t)), cex.lab = 1.5,
main=bquote(italic(a)==.(s)), cex.main = 1.5)
curve(Im(phi(x, a)), add=TRUE, lty = 3, n=201)
curve(Re(phi(x, a)), add=TRUE, n=201)
}
par(mfrow=c(1,1))
#
# The density of Y.
#
f <- Vectorize(function(x, a, ...) {
h <- function(t) Re(exp(-1.i * t * x) * phi(t, a)) / (2 * pi)
integrate(h, -Inf, Inf, ...)$value
}, "x")
#
# Test with direct simulation of Y.
#
a <- 5/2 # Watch out for small or integral values -- integration can take time
b <- 1
n <- 1e5
X.1 <- rgamma(n, a, b)
X.2 <- rgamma(n, a, b)
U <- runif(n)
Y <- U * X.1 + (1 - U) * X.2
hist(Y, freq=FALSE, breaks=100)
system.time(
# Many subdivisions are needed for small values of `a`.
curve(f(x, a, subdivisions=5e3, rel.tol=1e-3, abs.tol=1e-4), n=101, lwd=2, add = TRUE)
)
|
What is the distribution of a random linear combination of gamma random variables?
|
A direct attack (via integration) on computing the density looks intractable.
Instead, we may more easily compute the characteristic function of $Y$ (when the scale factor $b=1,$ which we may assume w
|
What is the distribution of a random linear combination of gamma random variables?
A direct attack (via integration) on computing the density looks intractable.
Instead, we may more easily compute the characteristic function of $Y$ (when the scale factor $b=1,$ which we may assume without any loss of generality simply by changing the units in which we express $Y$) as
$$\begin{aligned}
\phi_Y(t;a) &= E\left[e^{itY}\right] = E\left[e^{it(UX_1+(1-U)X_2)}\right] = E_U\left[E_{X_1,X_2}\left[e^{it(UX_1+(1-U)X_2)}\right]\right]\\
&= E_U\left[ E_{X_1} \left[e^{it UX_1}\right]\, E_{X_2} \left[e^{it (1-U)X_2}\right]\right]\\
&= E_U\left[(1 - i U t)^{-a}\, (1 - i(1-U)t)^{-a}\right]\\
&= \int_0^1 \left((1 - iut)(1 - i(1-u)t)\right)^{-a}\,\mathrm{d}u\\
&= \frac{_2F_1\left(1, 2-2a, 2-a; \frac{i}{2i+t}\right)\ {-}\ _2F_1\left(1, 2-2a, 2-a; \frac{i+t}{2i + t}\right)}{(a-1)t(2i + t)(1 - it)^{a-1}}.
\end{aligned}$$
The hypergeo library for R will efficiently compute these hypergeometric functions, as shown in these graphs of $\phi_Y$ for a range of $a.$
The solid graph plots the real part of $\phi_Y$ and the dotted graph plots its imaginary part.
(There is a technical problem: the foregoing formula is not defined for positive integral values of $a.$ You can get close enough by computing the average of $\phi_Y(t;a\pm2\epsilon)$ when $a$ is within $\epsilon$ of an integer and $\epsilon$ is small. It doesn't have to be terribly small for this to be highly accurate; I used $\epsilon = 10^{-5}.$ Smaller values will cause too much loss of precision in double precision floating point calculations.)
That answers the question. However, often it's more useful to have a density or distribution function. Either can be obtained through a Fourier transform. The density, for instance, is
$$f_Y(y;a) = \frac{1}{2\pi}\int_{\mathbb R} e^{- i y t} \phi_Y(t;a)\,\mathrm{d}t.$$
Numerical integration is possible, albeit a little slow for small values of $a.$ For $a=3/2$ it took half a minute to generate 101 points on the curve below, which matches the histogram of 100,000 values of $Y$ generated directly from its definition.
For $a=6$ the time dropped to four seconds; for $a=7.5$ to under half a second; etc. The timing is a rather irregular function of $a$ (odd multiples of $1/2$ tend to be very quick to compute) so take some care if you need many evaluations of $f_Y.$
This is the full R code.
#
# The characteristic function of Y.
#
library(hypergeo)
phi. <- function(t, a) {
(hypergeo(1, 2 - 2*a, 2 - a, 1.i / (2.i + t)) -
hypergeo(1, 2 - 2*a, 2 - a, (1.i + t) / (2.i + t))) /
(t * (2.i + t) * (1 - 1.i * t)^(a-1) * (1 - a))
}
phi <- function(t, a, eps=1e-5) {
ifelse(t == 0, 1,
if(isTRUE(abs(a - round(a)) > eps)) phi.(t, a) else {
(phi.(t, a - 2*eps) + phi.(t, a + 2*eps)) / 2
})
}
#
# Test `phi` by plotting it.
#
par(mfrow=c(1,3))
for (s in c(bquote(1/4), bquote(3/2), bquote(10))) {
a <- eval(s)
plot(c(-3,3), c(-1,1), type="n",
ylab="", yaxp=c(-1,1,2),
xlab=expression(italic(t)), cex.lab = 1.5,
main=bquote(italic(a)==.(s)), cex.main = 1.5)
curve(Im(phi(x, a)), add=TRUE, lty = 3, n=201)
curve(Re(phi(x, a)), add=TRUE, n=201)
}
par(mfrow=c(1,1))
#
# The density of Y.
#
f <- Vectorize(function(x, a, ...) {
h <- function(t) Re(exp(-1.i * t * x) * phi(t, a)) / (2 * pi)
integrate(h, -Inf, Inf, ...)$value
}, "x")
#
# Test with direct simulation of Y.
#
a <- 5/2 # Watch out for small or integral values -- integration can take time
b <- 1
n <- 1e5
X.1 <- rgamma(n, a, b)
X.2 <- rgamma(n, a, b)
U <- runif(n)
Y <- U * X.1 + (1 - U) * X.2
hist(Y, freq=FALSE, breaks=100)
system.time(
# Many subdivisions are needed for small values of `a`.
curve(f(x, a, subdivisions=5e3, rel.tol=1e-3, abs.tol=1e-4), n=101, lwd=2, add = TRUE)
)
|
What is the distribution of a random linear combination of gamma random variables?
A direct attack (via integration) on computing the density looks intractable.
Instead, we may more easily compute the characteristic function of $Y$ (when the scale factor $b=1,$ which we may assume w
|
46,412
|
Statistical interpretation of diagonal of Cholesky decomposition?
|
If the $X_i$ variables follow a normal distribution with covariance matrix $\Sigma$ and
$$\Sigma = LDL'$$
then the diagonal elements of $D$ are the conditional variances of each $X_i$ conditional on $X_1,\ldots,X_{i-1}$.
And, as you have already said, the elements of the $i$th row of $L$ give the regression coefficients of $X_i$ on $X_1,\ldots,X_{i-1}$.
More generally, if the $X_i$ are not normally distributed, then the elements of $L$ define the best linear predictor for $X_i$ based on $X_1,\ldots,X_{i-1}$ and the diagonal elements of $D$ give the variances of the residuals from these linear regressions.
In other words, the elements of $D$ gives the variance of each $X_i$ not explained by linear regression on $X_1,\ldots,X_{i-1}$.
In your question, you are computing the LDL decomposition not of a covariance matrix but of a squared data matrix.
If each column of the data matrix $X$ was mean-corrected, then $X'X$ would be a sample covariance matrix, and the theoretical interpretation for the Cholesky decomposition would hold in an estimated sense.
If the data is not mean-corrected, then $X'X$ is not a covariance matrix and the interpretation does not hold.
The Cholesky decomposition algorithm, when properly coded with forward and backward equations, is a marvelously efficient and stable numerical algorithm that does not require any matrix inversions.
So I am a bit surprised that you are trying to approximate it, especially with equations that look to me to be somewhat inefficient.
There also exist Cholesky algorithms that produce banded $L$ matrices, i.e., which limit the number of previous variables than each $X_i$ depends on.
Banded Cholesky algorithms are appropriate for auto-regressive processes.
I wrote Fortran subroutines to do such things when I was a PhD student back in the 1980s!
If you are dealing with auto-regressive time series, then you could look into state-space models, which can be viewed as an implementation of an LDL Cholesky decomposition for time series.
|
Statistical interpretation of diagonal of Cholesky decomposition?
|
If the $X_i$ variables follow a normal distribution with covariance matrix $\Sigma$ and
$$\Sigma = LDL'$$
then the diagonal elements of $D$ are the conditional variances of each $X_i$ conditional on $
|
Statistical interpretation of diagonal of Cholesky decomposition?
If the $X_i$ variables follow a normal distribution with covariance matrix $\Sigma$ and
$$\Sigma = LDL'$$
then the diagonal elements of $D$ are the conditional variances of each $X_i$ conditional on $X_1,\ldots,X_{i-1}$.
And, as you have already said, the elements of the $i$th row of $L$ give the regression coefficients of $X_i$ on $X_1,\ldots,X_{i-1}$.
More generally, if the $X_i$ are not normally distributed, then the elements of $L$ define the best linear predictor for $X_i$ based on $X_1,\ldots,X_{i-1}$ and the diagonal elements of $D$ give the variances of the residuals from these linear regressions.
In other words, the elements of $D$ gives the variance of each $X_i$ not explained by linear regression on $X_1,\ldots,X_{i-1}$.
In your question, you are computing the LDL decomposition not of a covariance matrix but of a squared data matrix.
If each column of the data matrix $X$ was mean-corrected, then $X'X$ would be a sample covariance matrix, and the theoretical interpretation for the Cholesky decomposition would hold in an estimated sense.
If the data is not mean-corrected, then $X'X$ is not a covariance matrix and the interpretation does not hold.
The Cholesky decomposition algorithm, when properly coded with forward and backward equations, is a marvelously efficient and stable numerical algorithm that does not require any matrix inversions.
So I am a bit surprised that you are trying to approximate it, especially with equations that look to me to be somewhat inefficient.
There also exist Cholesky algorithms that produce banded $L$ matrices, i.e., which limit the number of previous variables than each $X_i$ depends on.
Banded Cholesky algorithms are appropriate for auto-regressive processes.
I wrote Fortran subroutines to do such things when I was a PhD student back in the 1980s!
If you are dealing with auto-regressive time series, then you could look into state-space models, which can be viewed as an implementation of an LDL Cholesky decomposition for time series.
|
Statistical interpretation of diagonal of Cholesky decomposition?
If the $X_i$ variables follow a normal distribution with covariance matrix $\Sigma$ and
$$\Sigma = LDL'$$
then the diagonal elements of $D$ are the conditional variances of each $X_i$ conditional on $
|
46,413
|
How to find the PMF of a weighted sum of IID Bernoulli random variables with constant sum of weights
|
You can write out the generating functions for this distribution quite easily, which is sufficient to characterise the distribution. For example, the characteristic function for $Y$ is:
$$\begin{align}
\phi_Y(t)
&\equiv \mathbb{E}(e^{itY}) \\[12pt]
&= \prod_{j=1}^k \mathbb{E}(e^{it a_j X_j}) \\[6pt]
&= \prod_{j=1}^k (1-p+pe^{i t a_j}). \\[6pt]
\end{align}$$
It is also notable that the Bernoulli terms with $a_j=0$ contribute nothing to the distribution, so you can simplify things a bit by eliminating these values and taking $a_1,...,a_r$ to be only the positive integers in the set (with $r \leqslant k$), so you then have the smaller form:
$$\begin{align}
\phi_Y(t)
&= \prod_{j=1}^r (1-p+pe^{i t a_j}). \\[6pt]
\end{align}$$
You can expand this out to get:
$$\begin{align}
\phi_Y(t)
&= (1-p+pe^{i t a_1}) \cdots (1-p+pe^{i t a_r}) \\[12pt]
&= ((1-p)+pe^{i t a_1}) \cdots ((1-p)+pe^{i t a_r}) \\[12pt]
&= (1-p)^r + p (1-p)^{r-1} \sum_{j} e^{i t a_j} + p^2 (1-p)^{r-2} \sum_{j \neq l} e^{i t (a_j+a_l)} \\[6pt]
&\quad + p^3 (1-p)^{r-3} \sum_{j \neq l \neq m} e^{i t (a_j+a_l+a_m)} + \cdots + p^r e^{i t a_1+\cdots + a_r}. \\[6pt]
\end{align}$$
The probability mass function is obtained by Fourier inversion of this function, which gives:
$$\begin{align}
p_Y(y)
&= (1-p)^r \mathbb{I}(y=0) + p (1-p)^{r-1} \sum_{j} \mathbb{I}(y=a_j) \\[6pt]
&\quad + p^2 (1-p)^{r-2} \sum_{j \neq l} \mathbb{I}(y=a_j+a_l) \\[6pt]
&\quad + p^3 (1-p)^{r-3} \sum_{j \neq l \neq m} \mathbb{I}(y=a_j+a_l+a_m) + \cdots + p^r \mathbb{I}(y=k). \\[6pt]
\end{align}$$
Approximation: If $r$ is large and you don't have values of $a_j$ that "dominate" the sum then you could reasonably approximate the distribution by a normal distribution. (Formally, this would be based on the Lyapunov CLT and it would require you to set conditions on the size of the weights. Roughly speaking, you would need weights that each become "small" in comparison to $k$ in the limit, but see the theorem for more details.) The moments are simple to obtain:
$$\begin{align}
\mathbb{E}(Y)
&= \sum_{j=1}^r \mathbb{E}(a_j X_j) \\[6pt]
&= \sum_{j=1}^r a_j \mathbb{E}(X_j) \\[6pt]
&= p \sum_{j=1}^r a_j \\[6pt]
&= p k, \\[6pt]
\mathbb{V}(Y)
&= \sum_{j=1}^r \mathbb{V}(a_j X_j) \\[6pt]
&= \sum_{j=1}^r a_j^2 \mathbb{V}(X_j) \\[6pt]
&= p (1-p) \sum_{j=1}^r a_j^2. \\[6pt]
\end{align}$$
Using formulae for higher-moments of linear functions you can also find the skewness and kurtosis:
$$\begin{align}
\mathbb{Skew}(Y)
&= - \frac{2(p - \tfrac{1}{2})}{\sqrt{p(1-p)}} \cdot \frac{\sum_j a_j^3}{(\sum_j a_j^2)^{3/2}}, \\[12pt]
\mathbb{ExKurt}(Y)
&= \frac{1 - 6p(1-p)}{p(1-p)} \cdot \frac{\sum_j a_j^4}{(\sum_j a_j^2)^2}. \\[6pt]
\end{align}$$
If we are willing to employ the CLT (i.e., if the required conditions on $\mathbf{a}$ hold) then for large $n$ we would have the approximate distribution:
$$Y \overset{\text{Approx}}{\sim} \text{N} \bigg( pk, p (1-p) \sum_{j} a_j^2 \bigg).$$
(In practice you would also "discretise" this normal approximation by taking the density at the integer points in the support and then normalising to sum to one.)
Progamming this in R: I don't program in MATLAB so unfortunately I can't tell you how to implement this distribution there. (Perhaps someone else can answer that part.) Below I give the approximating distribution function programmed in R. (It is also quite simple to generate the CDF, quantile function, etc., but I won't go that far here.)
ddistapprox <- function(y, a, prob, log = FALSE) {
#Set parameters and find moments
IND <- (a != 0)
aa <- a[IND]
kk <- sum(aa)
rr <- length(aa)
MEAN <- prob*kk
VAR <- prob*(1-prob)*sum(aa^2)
#Generate mass functin
MASS <- dnorm(0:kk, mean = MEAN, sd = sqrt(VAR), log = TRUE)
MASS <- MASS - matrixStats::logSumExp(MASS)
#Generate output
OUT <- rep(-Inf, length(y))
for (i in 1:length(y)) {
if (y[i] %in% (0:kk)) { OUT[i] <- MASS[y[i]+1] } }
#Return output
if (log) { OUT } else { exp(OUT) } }
We can check the accuracy of this approximation with a simulation example. To do this, I will consider an example with set values of $\mathbf{a}$ and $p$ and simulate the random variable of interest $N=10^6$ times to obtain empirical estimates of the probabilities. We can then compare this against the distributional approximation to see how accurate it is. The barplot below shows the distribution approximation with approximate probabilities shown as red bars and empirical estimates of the probabilities shown as black dots. As you can see from the plot, the approximation is reasonable in this case, but it could be improved by taking account of the kurtosis of the distribution (i.e., using a generalisation of the normal distribution that allows variation of kurtosis).
#Set probability parameter and weight vector
p <- 0.5
a <- c(3, 0, 1, 1, 2, 4, 1, 0, 0, 2, 2, 0, 1, 3, 1, 0, 0, 2, 3, 1,
5, 0, 1, 1, 1, 2, 3, 0)
#Get details of reduced vector a
IND <- (a != 0)
aa <- a[IND]
rr <- length(aa)
kk <- sum(aa)
#Generate simulations and empirical estimates of probabilities
N <- 10^6
SIM.Y <- rep(0, N)
for (s in 1:N) {
x <- sample(c(0,1), size = rr, replace = TRUE, prob = c(1-p, p))
SIM.Y[s] <- sum(aa*x) }
SIM.PROBS <- rep(0, kk+1)
for (i in 0:kk) {
SIM.PROBS[i+1] <- sum(SIM.Y == i)/N }
names(SIM.PROBS) <- 0:sum(a)
#Generate approximate probability mass function (from normal approximation)
APPROX.PROBS <- ddistapprox(0:sum(a), a, prob = p)
names(APPROX.PROBS) <- c(0, NA, NA, NA, NA, 5, NA, NA, NA, NA, 10,
NA, NA, NA, NA, 15, NA, NA, NA, NA, 20,
NA, NA, NA, NA, 25, NA, NA, NA, NA, 30,
NA, NA, NA, NA, 35, NA, NA, NA, NA, 40)
#Plot the approximate probabilities against the simulated probabilities
BARPLOT <- barplot(APPROX.PROBS, ylim = c(0,0.1), col = 'red',
xlab = 'Value', ylab = 'Approximate Probability')
points(x = BARPLOT, y = SIM.PROBS, pch = 19)
|
How to find the PMF of a weighted sum of IID Bernoulli random variables with constant sum of weights
|
You can write out the generating functions for this distribution quite easily, which is sufficient to characterise the distribution. For example, the characteristic function for $Y$ is:
$$\begin{alig
|
How to find the PMF of a weighted sum of IID Bernoulli random variables with constant sum of weights
You can write out the generating functions for this distribution quite easily, which is sufficient to characterise the distribution. For example, the characteristic function for $Y$ is:
$$\begin{align}
\phi_Y(t)
&\equiv \mathbb{E}(e^{itY}) \\[12pt]
&= \prod_{j=1}^k \mathbb{E}(e^{it a_j X_j}) \\[6pt]
&= \prod_{j=1}^k (1-p+pe^{i t a_j}). \\[6pt]
\end{align}$$
It is also notable that the Bernoulli terms with $a_j=0$ contribute nothing to the distribution, so you can simplify things a bit by eliminating these values and taking $a_1,...,a_r$ to be only the positive integers in the set (with $r \leqslant k$), so you then have the smaller form:
$$\begin{align}
\phi_Y(t)
&= \prod_{j=1}^r (1-p+pe^{i t a_j}). \\[6pt]
\end{align}$$
You can expand this out to get:
$$\begin{align}
\phi_Y(t)
&= (1-p+pe^{i t a_1}) \cdots (1-p+pe^{i t a_r}) \\[12pt]
&= ((1-p)+pe^{i t a_1}) \cdots ((1-p)+pe^{i t a_r}) \\[12pt]
&= (1-p)^r + p (1-p)^{r-1} \sum_{j} e^{i t a_j} + p^2 (1-p)^{r-2} \sum_{j \neq l} e^{i t (a_j+a_l)} \\[6pt]
&\quad + p^3 (1-p)^{r-3} \sum_{j \neq l \neq m} e^{i t (a_j+a_l+a_m)} + \cdots + p^r e^{i t a_1+\cdots + a_r}. \\[6pt]
\end{align}$$
The probability mass function is obtained by Fourier inversion of this function, which gives:
$$\begin{align}
p_Y(y)
&= (1-p)^r \mathbb{I}(y=0) + p (1-p)^{r-1} \sum_{j} \mathbb{I}(y=a_j) \\[6pt]
&\quad + p^2 (1-p)^{r-2} \sum_{j \neq l} \mathbb{I}(y=a_j+a_l) \\[6pt]
&\quad + p^3 (1-p)^{r-3} \sum_{j \neq l \neq m} \mathbb{I}(y=a_j+a_l+a_m) + \cdots + p^r \mathbb{I}(y=k). \\[6pt]
\end{align}$$
Approximation: If $r$ is large and you don't have values of $a_j$ that "dominate" the sum then you could reasonably approximate the distribution by a normal distribution. (Formally, this would be based on the Lyapunov CLT and it would require you to set conditions on the size of the weights. Roughly speaking, you would need weights that each become "small" in comparison to $k$ in the limit, but see the theorem for more details.) The moments are simple to obtain:
$$\begin{align}
\mathbb{E}(Y)
&= \sum_{j=1}^r \mathbb{E}(a_j X_j) \\[6pt]
&= \sum_{j=1}^r a_j \mathbb{E}(X_j) \\[6pt]
&= p \sum_{j=1}^r a_j \\[6pt]
&= p k, \\[6pt]
\mathbb{V}(Y)
&= \sum_{j=1}^r \mathbb{V}(a_j X_j) \\[6pt]
&= \sum_{j=1}^r a_j^2 \mathbb{V}(X_j) \\[6pt]
&= p (1-p) \sum_{j=1}^r a_j^2. \\[6pt]
\end{align}$$
Using formulae for higher-moments of linear functions you can also find the skewness and kurtosis:
$$\begin{align}
\mathbb{Skew}(Y)
&= - \frac{2(p - \tfrac{1}{2})}{\sqrt{p(1-p)}} \cdot \frac{\sum_j a_j^3}{(\sum_j a_j^2)^{3/2}}, \\[12pt]
\mathbb{ExKurt}(Y)
&= \frac{1 - 6p(1-p)}{p(1-p)} \cdot \frac{\sum_j a_j^4}{(\sum_j a_j^2)^2}. \\[6pt]
\end{align}$$
If we are willing to employ the CLT (i.e., if the required conditions on $\mathbf{a}$ hold) then for large $n$ we would have the approximate distribution:
$$Y \overset{\text{Approx}}{\sim} \text{N} \bigg( pk, p (1-p) \sum_{j} a_j^2 \bigg).$$
(In practice you would also "discretise" this normal approximation by taking the density at the integer points in the support and then normalising to sum to one.)
Progamming this in R: I don't program in MATLAB so unfortunately I can't tell you how to implement this distribution there. (Perhaps someone else can answer that part.) Below I give the approximating distribution function programmed in R. (It is also quite simple to generate the CDF, quantile function, etc., but I won't go that far here.)
ddistapprox <- function(y, a, prob, log = FALSE) {
#Set parameters and find moments
IND <- (a != 0)
aa <- a[IND]
kk <- sum(aa)
rr <- length(aa)
MEAN <- prob*kk
VAR <- prob*(1-prob)*sum(aa^2)
#Generate mass functin
MASS <- dnorm(0:kk, mean = MEAN, sd = sqrt(VAR), log = TRUE)
MASS <- MASS - matrixStats::logSumExp(MASS)
#Generate output
OUT <- rep(-Inf, length(y))
for (i in 1:length(y)) {
if (y[i] %in% (0:kk)) { OUT[i] <- MASS[y[i]+1] } }
#Return output
if (log) { OUT } else { exp(OUT) } }
We can check the accuracy of this approximation with a simulation example. To do this, I will consider an example with set values of $\mathbf{a}$ and $p$ and simulate the random variable of interest $N=10^6$ times to obtain empirical estimates of the probabilities. We can then compare this against the distributional approximation to see how accurate it is. The barplot below shows the distribution approximation with approximate probabilities shown as red bars and empirical estimates of the probabilities shown as black dots. As you can see from the plot, the approximation is reasonable in this case, but it could be improved by taking account of the kurtosis of the distribution (i.e., using a generalisation of the normal distribution that allows variation of kurtosis).
#Set probability parameter and weight vector
p <- 0.5
a <- c(3, 0, 1, 1, 2, 4, 1, 0, 0, 2, 2, 0, 1, 3, 1, 0, 0, 2, 3, 1,
5, 0, 1, 1, 1, 2, 3, 0)
#Get details of reduced vector a
IND <- (a != 0)
aa <- a[IND]
rr <- length(aa)
kk <- sum(aa)
#Generate simulations and empirical estimates of probabilities
N <- 10^6
SIM.Y <- rep(0, N)
for (s in 1:N) {
x <- sample(c(0,1), size = rr, replace = TRUE, prob = c(1-p, p))
SIM.Y[s] <- sum(aa*x) }
SIM.PROBS <- rep(0, kk+1)
for (i in 0:kk) {
SIM.PROBS[i+1] <- sum(SIM.Y == i)/N }
names(SIM.PROBS) <- 0:sum(a)
#Generate approximate probability mass function (from normal approximation)
APPROX.PROBS <- ddistapprox(0:sum(a), a, prob = p)
names(APPROX.PROBS) <- c(0, NA, NA, NA, NA, 5, NA, NA, NA, NA, 10,
NA, NA, NA, NA, 15, NA, NA, NA, NA, 20,
NA, NA, NA, NA, 25, NA, NA, NA, NA, 30,
NA, NA, NA, NA, 35, NA, NA, NA, NA, 40)
#Plot the approximate probabilities against the simulated probabilities
BARPLOT <- barplot(APPROX.PROBS, ylim = c(0,0.1), col = 'red',
xlab = 'Value', ylab = 'Approximate Probability')
points(x = BARPLOT, y = SIM.PROBS, pch = 19)
|
How to find the PMF of a weighted sum of IID Bernoulli random variables with constant sum of weights
You can write out the generating functions for this distribution quite easily, which is sufficient to characterise the distribution. For example, the characteristic function for $Y$ is:
$$\begin{alig
|
46,414
|
Bernoulli distribution with random means
|
Since all variables are IID, this is quite straightforward. First we compute the conditional moments:
$$\begin{align}
\mathbb{E}(S' | \mathbf{p})
&= \mathbb{E} \bigg( \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n X_{ij} \bigg|\mathbf{p}\bigg) \\[6pt]
&= \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n \mathbb{E}(X_{ij}|p_i) \\[6pt]
&= \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n p_i \\[6pt]
&= \frac{1}{k} \sum_{i=1}^k p_i, \\[12pt]
\mathbb{V}(S' | \mathbf{p})
&= \mathbb{V} \bigg( \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n X_{ij} \bigg| \mathbf{p}\bigg) \quad \quad \quad \quad \\[6pt]
&= \frac{1}{n^2 k^2} \sum_{i=1}^k \sum_{j=1}^n \mathbb{V}(X_{ij}|p_i) \\[6pt]
&= \frac{1}{n^2 k^2} \sum_{i=1}^k \sum_{j=1}^n p_i (1-p_i) \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k p_i (1-p_i). \\[12pt]
\end{align}$$
Then we use the law of iterated expectation and the law of iterated variance to compute the unconditional moments:
$$\begin{align}
\mathbb{E}(S')
&= \mathbb{E}(\mathbb{E}(S' | \mathbf{p})) \\[6pt]
&= \mathbb{E} \bigg( \frac{1}{k} \sum_{i=1}^k p_i \bigg) \\[6pt]
&= \frac{1}{k} \sum_{i=1}^k \mathbb{E}(p_i)) \\[6pt]
&= \frac{1}{k} \sum_{i=1}^k \frac{1}{2} \\[6pt]
&= \frac{1}{2}, \\[12pt]
\quad \quad \quad \quad \quad
\mathbb{V}(S')
&= \mathbb{E}(\mathbb{V}(S' | \mathbf{p})) + \mathbb{V}(\mathbb{E}(S' | \mathbf{p})) \\[6pt]
&= \mathbb{E} \bigg( \frac{1}{n k^2} \sum_{i=1}^k p_i (1-p_i) \bigg) + \mathbb{V} \bigg( \frac{1}{k} \sum_{i=1}^k p_i \bigg) \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k \mathbb{E}(p_i (1-p_i)) + \frac{1}{k^2} \sum_{i=1}^k \mathbb{V}(p_i) \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k \bigg( \frac{1}{2} - \frac{1}{3} \bigg) + \frac{1}{k^2} \sum_{i=1}^k \frac{1}{12} \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k \frac{1}{6} + \frac{1}{k^2} \sum_{i=1}^k \frac{1}{12} \\[6pt]
&= \frac{1}{6 n k} + \frac{1}{12 k} \\[6pt]
&= \frac{1}{12 k} \cdot \frac{n+2}{n}. \\[6pt]
\end{align}$$
As a sanity check, we observe that $\mathbb{V}(S') \rightarrow 0$ as $\min(k,n) \rightarrow \infty$, which is what we would expect from the law of large numbers.
|
Bernoulli distribution with random means
|
Since all variables are IID, this is quite straightforward. First we compute the conditional moments:
$$\begin{align}
\mathbb{E}(S' | \mathbf{p})
&= \mathbb{E} \bigg( \frac{1}{nk} \sum_{i=1}^k \sum_
|
Bernoulli distribution with random means
Since all variables are IID, this is quite straightforward. First we compute the conditional moments:
$$\begin{align}
\mathbb{E}(S' | \mathbf{p})
&= \mathbb{E} \bigg( \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n X_{ij} \bigg|\mathbf{p}\bigg) \\[6pt]
&= \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n \mathbb{E}(X_{ij}|p_i) \\[6pt]
&= \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n p_i \\[6pt]
&= \frac{1}{k} \sum_{i=1}^k p_i, \\[12pt]
\mathbb{V}(S' | \mathbf{p})
&= \mathbb{V} \bigg( \frac{1}{nk} \sum_{i=1}^k \sum_{j=1}^n X_{ij} \bigg| \mathbf{p}\bigg) \quad \quad \quad \quad \\[6pt]
&= \frac{1}{n^2 k^2} \sum_{i=1}^k \sum_{j=1}^n \mathbb{V}(X_{ij}|p_i) \\[6pt]
&= \frac{1}{n^2 k^2} \sum_{i=1}^k \sum_{j=1}^n p_i (1-p_i) \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k p_i (1-p_i). \\[12pt]
\end{align}$$
Then we use the law of iterated expectation and the law of iterated variance to compute the unconditional moments:
$$\begin{align}
\mathbb{E}(S')
&= \mathbb{E}(\mathbb{E}(S' | \mathbf{p})) \\[6pt]
&= \mathbb{E} \bigg( \frac{1}{k} \sum_{i=1}^k p_i \bigg) \\[6pt]
&= \frac{1}{k} \sum_{i=1}^k \mathbb{E}(p_i)) \\[6pt]
&= \frac{1}{k} \sum_{i=1}^k \frac{1}{2} \\[6pt]
&= \frac{1}{2}, \\[12pt]
\quad \quad \quad \quad \quad
\mathbb{V}(S')
&= \mathbb{E}(\mathbb{V}(S' | \mathbf{p})) + \mathbb{V}(\mathbb{E}(S' | \mathbf{p})) \\[6pt]
&= \mathbb{E} \bigg( \frac{1}{n k^2} \sum_{i=1}^k p_i (1-p_i) \bigg) + \mathbb{V} \bigg( \frac{1}{k} \sum_{i=1}^k p_i \bigg) \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k \mathbb{E}(p_i (1-p_i)) + \frac{1}{k^2} \sum_{i=1}^k \mathbb{V}(p_i) \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k \bigg( \frac{1}{2} - \frac{1}{3} \bigg) + \frac{1}{k^2} \sum_{i=1}^k \frac{1}{12} \\[6pt]
&= \frac{1}{n k^2} \sum_{i=1}^k \frac{1}{6} + \frac{1}{k^2} \sum_{i=1}^k \frac{1}{12} \\[6pt]
&= \frac{1}{6 n k} + \frac{1}{12 k} \\[6pt]
&= \frac{1}{12 k} \cdot \frac{n+2}{n}. \\[6pt]
\end{align}$$
As a sanity check, we observe that $\mathbb{V}(S') \rightarrow 0$ as $\min(k,n) \rightarrow \infty$, which is what we would expect from the law of large numbers.
|
Bernoulli distribution with random means
Since all variables are IID, this is quite straightforward. First we compute the conditional moments:
$$\begin{align}
\mathbb{E}(S' | \mathbf{p})
&= \mathbb{E} \bigg( \frac{1}{nk} \sum_{i=1}^k \sum_
|
46,415
|
Predict non-negative continuous variable between 0 to 100
|
Scale your data to lie between 0 and 1, then use beta regression.
A beta regression models the response as conditionally beta distributed, i.e., bounded between 0 and 1 (just like a negative binomial regression models your data as conditionally negbin distributed). The beta is the most common such distribution. (The uniform distribution would be another one, but since it is not flexible at all, it does not make sense to plug it into a regression. The beta, in contrast, can have a lot of different shapes: essentially, you would model a dependence of the two parameters of a beta distribution on your predictors.)
In R, you can use the betareg package. We have a beta-regression tag. Unfortunately, I do not know of any literature, I recommend searching and perhaps looking at the betareg vignettes.
|
Predict non-negative continuous variable between 0 to 100
|
Scale your data to lie between 0 and 1, then use beta regression.
A beta regression models the response as conditionally beta distributed, i.e., bounded between 0 and 1 (just like a negative binomial
|
Predict non-negative continuous variable between 0 to 100
Scale your data to lie between 0 and 1, then use beta regression.
A beta regression models the response as conditionally beta distributed, i.e., bounded between 0 and 1 (just like a negative binomial regression models your data as conditionally negbin distributed). The beta is the most common such distribution. (The uniform distribution would be another one, but since it is not flexible at all, it does not make sense to plug it into a regression. The beta, in contrast, can have a lot of different shapes: essentially, you would model a dependence of the two parameters of a beta distribution on your predictors.)
In R, you can use the betareg package. We have a beta-regression tag. Unfortunately, I do not know of any literature, I recommend searching and perhaps looking at the betareg vignettes.
|
Predict non-negative continuous variable between 0 to 100
Scale your data to lie between 0 and 1, then use beta regression.
A beta regression models the response as conditionally beta distributed, i.e., bounded between 0 and 1 (just like a negative binomial
|
46,416
|
How to model a probability distribution to phone call duration?
|
But is there a more rigorous way of modeling?
Visually comparing a theoretical distribution to an observed histogram is an important practice toward being rigorous in our inferences.
Like a real-world intuition behind one of those options?
This would require domain-specific knowledge about phone calls that perhaps I don't have. There are multiple distributions that appear similar to yours prima facie, and I do not know which specific theoretical distribution is 'best' according to my background information. But perhaps there isn't an available way to know other than to evaluate and compare models trained on the data. Some speculations I might have about the general shape:
Unimodality is suggesting there is no evidence here of clusters of phone calls.
Hypothesis: The tiny strip near zero might be those automatic calls along with the occassional "oh s**t I just dialed the wrong number" calls.
Most of the rest of the weight not being close to zero even on the left-side of the mode might be suggestive that for most calls there is a minimum length that is useful to humans for verbally getting information across.
The right skew suggests that occasional calls go much longer than the typical call length. For me these longer calls are catching up with old friends that I don't see often, but it could be for other reasons in general.
Sanity check: Phone calls should not have negative duration, and the histogram agrees with that constraint.
In addition, how to tune the parameters to fit the curve?
There are too many ways to summarize for how to fit the parameters of a distribution to data. The choices often depend on whether you are approaching this from a Bayesian or likelihood perspective. Let me mention two estimation techniques in these broad areas, though I cannot emphasize enough that this barely scratches the surface.
Maximum a posteriori estimation
Maximum likelihood estimation
Do you know a tool for that?
For the simple cases, which yours might be, I often use SciPy to fit distributions to data. By default it uses maximum likelihood estimation, but method of moments can be used by passing method="MM" into the fit method. You could use the code in this answer to train (all?) the available SciPy distributions on your data, but this seems wasteful (if not asking for spurious results).
Taking a more practical stance of training only specific distributions, let's consider how you can do this with the gamma distribution as an example.
from scipy.stats import gamma
data = <an array of your data goes here>
parameters = gamma.fit(data) # include `floc=0` if you don't want the location parameter.
A list of available statistical functions is found in this reference.
If SciPy doesn't have a distribution you are interested in, like if you wanted to construct mixture model, you can build your own using using scipy.stats.rv_continuous or scipy.stats.rv_discrete as base classes. See this Stack Overflow Q/A for an example.
In your case you can probably model you distribution as a mixture distribution between a Dirac delta distribution centered at zero with something like gamma distribution. SciPy's base class should work for that with some customized code, but for building custom mixtures I have become a fan of pymc.Mixture.
Should I use moments of the distribution?
If the best-fitting distribution has finite moments to some sufficiently large order, then you can use them to report typical moments such as the mean, variance, skewness and kurtosis. Eye-balling your histogram, my guess is that the mean and variance are finite, but there are methods for examining whether your distribution is fat-tailed. I believe videos 11-14 cover tails and their estimation in this (fairly good in my opinion) video series on quantitative risk management. Which moments you use, and how you use them, will depend on what you are trying to accomplish with the analysis.
|
How to model a probability distribution to phone call duration?
|
But is there a more rigorous way of modeling?
Visually comparing a theoretical distribution to an observed histogram is an important practice toward being rigorous in our inferences.
Like a real-wo
|
How to model a probability distribution to phone call duration?
But is there a more rigorous way of modeling?
Visually comparing a theoretical distribution to an observed histogram is an important practice toward being rigorous in our inferences.
Like a real-world intuition behind one of those options?
This would require domain-specific knowledge about phone calls that perhaps I don't have. There are multiple distributions that appear similar to yours prima facie, and I do not know which specific theoretical distribution is 'best' according to my background information. But perhaps there isn't an available way to know other than to evaluate and compare models trained on the data. Some speculations I might have about the general shape:
Unimodality is suggesting there is no evidence here of clusters of phone calls.
Hypothesis: The tiny strip near zero might be those automatic calls along with the occassional "oh s**t I just dialed the wrong number" calls.
Most of the rest of the weight not being close to zero even on the left-side of the mode might be suggestive that for most calls there is a minimum length that is useful to humans for verbally getting information across.
The right skew suggests that occasional calls go much longer than the typical call length. For me these longer calls are catching up with old friends that I don't see often, but it could be for other reasons in general.
Sanity check: Phone calls should not have negative duration, and the histogram agrees with that constraint.
In addition, how to tune the parameters to fit the curve?
There are too many ways to summarize for how to fit the parameters of a distribution to data. The choices often depend on whether you are approaching this from a Bayesian or likelihood perspective. Let me mention two estimation techniques in these broad areas, though I cannot emphasize enough that this barely scratches the surface.
Maximum a posteriori estimation
Maximum likelihood estimation
Do you know a tool for that?
For the simple cases, which yours might be, I often use SciPy to fit distributions to data. By default it uses maximum likelihood estimation, but method of moments can be used by passing method="MM" into the fit method. You could use the code in this answer to train (all?) the available SciPy distributions on your data, but this seems wasteful (if not asking for spurious results).
Taking a more practical stance of training only specific distributions, let's consider how you can do this with the gamma distribution as an example.
from scipy.stats import gamma
data = <an array of your data goes here>
parameters = gamma.fit(data) # include `floc=0` if you don't want the location parameter.
A list of available statistical functions is found in this reference.
If SciPy doesn't have a distribution you are interested in, like if you wanted to construct mixture model, you can build your own using using scipy.stats.rv_continuous or scipy.stats.rv_discrete as base classes. See this Stack Overflow Q/A for an example.
In your case you can probably model you distribution as a mixture distribution between a Dirac delta distribution centered at zero with something like gamma distribution. SciPy's base class should work for that with some customized code, but for building custom mixtures I have become a fan of pymc.Mixture.
Should I use moments of the distribution?
If the best-fitting distribution has finite moments to some sufficiently large order, then you can use them to report typical moments such as the mean, variance, skewness and kurtosis. Eye-balling your histogram, my guess is that the mean and variance are finite, but there are methods for examining whether your distribution is fat-tailed. I believe videos 11-14 cover tails and their estimation in this (fairly good in my opinion) video series on quantitative risk management. Which moments you use, and how you use them, will depend on what you are trying to accomplish with the analysis.
|
How to model a probability distribution to phone call duration?
But is there a more rigorous way of modeling?
Visually comparing a theoretical distribution to an observed histogram is an important practice toward being rigorous in our inferences.
Like a real-wo
|
46,417
|
How to model a probability distribution to phone call duration?
|
Treating time as continuous, candidate distributions that come to mind are log-normal, gamma, and Weibull. You can use a time-to-event regression package to fit various models and compare the AIC for which provides the best fit. You can plot the Kaplan-Meier estimator of the survival function and overlay the fitted parametric curve. If there is no censoring you could plot a histogram and overlay the fitted density. It looks like there is a spike at time=0. You could model only the non-zero times or try a finite mixture model that includes 0.
|
How to model a probability distribution to phone call duration?
|
Treating time as continuous, candidate distributions that come to mind are log-normal, gamma, and Weibull. You can use a time-to-event regression package to fit various models and compare the AIC for
|
How to model a probability distribution to phone call duration?
Treating time as continuous, candidate distributions that come to mind are log-normal, gamma, and Weibull. You can use a time-to-event regression package to fit various models and compare the AIC for which provides the best fit. You can plot the Kaplan-Meier estimator of the survival function and overlay the fitted parametric curve. If there is no censoring you could plot a histogram and overlay the fitted density. It looks like there is a spike at time=0. You could model only the non-zero times or try a finite mixture model that includes 0.
|
How to model a probability distribution to phone call duration?
Treating time as continuous, candidate distributions that come to mind are log-normal, gamma, and Weibull. You can use a time-to-event regression package to fit various models and compare the AIC for
|
46,418
|
How to model a probability distribution to phone call duration?
|
It is usually a bad idea to fit a probability density function, bot in the least because the shape and the results would be very sensitive to the choice of the bin size.
Robust and simple options for comparing empirical distribution with parametric ones include QQ-plot (mostly to get the intuitive idea) and the Kolmiogorov-Smirnov test (both based on comparing cdf rather than the pdf.)
|
How to model a probability distribution to phone call duration?
|
It is usually a bad idea to fit a probability density function, bot in the least because the shape and the results would be very sensitive to the choice of the bin size.
Robust and simple options for
|
How to model a probability distribution to phone call duration?
It is usually a bad idea to fit a probability density function, bot in the least because the shape and the results would be very sensitive to the choice of the bin size.
Robust and simple options for comparing empirical distribution with parametric ones include QQ-plot (mostly to get the intuitive idea) and the Kolmiogorov-Smirnov test (both based on comparing cdf rather than the pdf.)
|
How to model a probability distribution to phone call duration?
It is usually a bad idea to fit a probability density function, bot in the least because the shape and the results would be very sensitive to the choice of the bin size.
Robust and simple options for
|
46,419
|
How to model a probability distribution to phone call duration?
|
From a practical point of view, whether a proposed calculation or test or assumption makes sense depends on the purpose. What are you going to do with the distribution once you have fitted it? If you want to use the distribution as input to simulation, then you could just use the empirical model. If you want to input the distribution to a queueing-theory model then some thought has to be given to the actions that might be taken based on the results. Some queueing-theory results are not particularly sensitive to service-time distribution, and call-center planning has to contend with forecasting error and agent attendance variability as well. If you want to apply queueing-theory, as opposed to simulation, then the question is not "what is the best-fit distribution", it is "what is the best fit of the distributions that are mathematically tractable", which may steer you to Erlang, mixed-Erland, Gamma, or LogNormal. Gamma-family is attractive mathematically, lognormal is often a good fit. Plus, "how much does the fitted or assumed distribution affect resulting management decisions?".
|
How to model a probability distribution to phone call duration?
|
From a practical point of view, whether a proposed calculation or test or assumption makes sense depends on the purpose. What are you going to do with the distribution once you have fitted it? If you
|
How to model a probability distribution to phone call duration?
From a practical point of view, whether a proposed calculation or test or assumption makes sense depends on the purpose. What are you going to do with the distribution once you have fitted it? If you want to use the distribution as input to simulation, then you could just use the empirical model. If you want to input the distribution to a queueing-theory model then some thought has to be given to the actions that might be taken based on the results. Some queueing-theory results are not particularly sensitive to service-time distribution, and call-center planning has to contend with forecasting error and agent attendance variability as well. If you want to apply queueing-theory, as opposed to simulation, then the question is not "what is the best-fit distribution", it is "what is the best fit of the distributions that are mathematically tractable", which may steer you to Erlang, mixed-Erland, Gamma, or LogNormal. Gamma-family is attractive mathematically, lognormal is often a good fit. Plus, "how much does the fitted or assumed distribution affect resulting management decisions?".
|
How to model a probability distribution to phone call duration?
From a practical point of view, whether a proposed calculation or test or assumption makes sense depends on the purpose. What are you going to do with the distribution once you have fitted it? If you
|
46,420
|
Converting a circular outcome variable to a linear one
|
I don't want to complicate my model (using a linear mixed effects model) by using circular statistics, so I was wondering if I can use the absolute deviation expressed as a percentage of 180?
...Is this a legitimate fix?
There is not sufficient information in order to tell whether this is legitimate or not.
The problem with circular systems is that they wrap around themselves. For instance it you make three quarter turns to the left then you end up one quarter turn to the right.
So a large random step/movement/change/deviation/effect (whatever you want to call it) might end up as being measured/observed as a small step and in the opposite direction. What you observe as a single quarter step might in reality be three quarter steps.
If you treat the circle as a linear variable then you will not be taking this into account and you will wrongly interpret the values.
If the nature of your data is such that you do not get this effect of revolving/wrappingaround the circle. That is, if your changes are small enough that you will not see values, or only negligible few values, that make a deviation of more than a half circle, then you can use a linearized variable.
You speak about 'using the absolute value only' and you want to ignore the direction of change. It is unclear why you (need to) do this. Depending on the task and data that you have you might choose to do this. It is not wrong in principle and it does occur. However, in order to be able to say whether it is good for your case, the details about the case need to be know.
|
Converting a circular outcome variable to a linear one
|
I don't want to complicate my model (using a linear mixed effects model) by using circular statistics, so I was wondering if I can use the absolute deviation expressed as a percentage of 180?
...Is th
|
Converting a circular outcome variable to a linear one
I don't want to complicate my model (using a linear mixed effects model) by using circular statistics, so I was wondering if I can use the absolute deviation expressed as a percentage of 180?
...Is this a legitimate fix?
There is not sufficient information in order to tell whether this is legitimate or not.
The problem with circular systems is that they wrap around themselves. For instance it you make three quarter turns to the left then you end up one quarter turn to the right.
So a large random step/movement/change/deviation/effect (whatever you want to call it) might end up as being measured/observed as a small step and in the opposite direction. What you observe as a single quarter step might in reality be three quarter steps.
If you treat the circle as a linear variable then you will not be taking this into account and you will wrongly interpret the values.
If the nature of your data is such that you do not get this effect of revolving/wrappingaround the circle. That is, if your changes are small enough that you will not see values, or only negligible few values, that make a deviation of more than a half circle, then you can use a linearized variable.
You speak about 'using the absolute value only' and you want to ignore the direction of change. It is unclear why you (need to) do this. Depending on the task and data that you have you might choose to do this. It is not wrong in principle and it does occur. However, in order to be able to say whether it is good for your case, the details about the case need to be know.
|
Converting a circular outcome variable to a linear one
I don't want to complicate my model (using a linear mixed effects model) by using circular statistics, so I was wondering if I can use the absolute deviation expressed as a percentage of 180?
...Is th
|
46,421
|
Converting a circular outcome variable to a linear one
|
You cannot validly linearize a circular measure which spans 360°, assuming the circularity of that measure is valid.
Any transformation which "linearizes" a circular measure must necessarily privilege some value as being maximally linearly distant from some other value by virtue of lying on the other side of whatever point the transformation uses as its point of either "unwinding" or "flattening" the circle. This maximal linear distance will be a fiction created entirely as an artifact of the transformation, and will not exist in the original circular measure. The same holds true in a continuous circular measure of degrees, radians, etc. In fact, by carefully choosing the privileged point in your transformation function, you could probably fabricate any relationship you wanted between outcome and predictor, by ensuring that certain linearized values become either the largest, smallest, or middlemost.
Modular measurements—whether discrete or continuous—have important characteristics which have no representation in linear forms. This is why treating the modular numbers adorning the face of a clock make no sense as truly (linear) natural numbers. For a simple example, as we actually read the 12 hour clock, $1 - 12 = 1$, $3 - 9 = 9 - 3 = 6$, etc. But linearizing the clock's hours into integers would mean that $1 - 12 = -11$, and that $3 - 9 \ne 9 - 3$.
|
Converting a circular outcome variable to a linear one
|
You cannot validly linearize a circular measure which spans 360°, assuming the circularity of that measure is valid.
Any transformation which "linearizes" a circular measure must necessarily privilege
|
Converting a circular outcome variable to a linear one
You cannot validly linearize a circular measure which spans 360°, assuming the circularity of that measure is valid.
Any transformation which "linearizes" a circular measure must necessarily privilege some value as being maximally linearly distant from some other value by virtue of lying on the other side of whatever point the transformation uses as its point of either "unwinding" or "flattening" the circle. This maximal linear distance will be a fiction created entirely as an artifact of the transformation, and will not exist in the original circular measure. The same holds true in a continuous circular measure of degrees, radians, etc. In fact, by carefully choosing the privileged point in your transformation function, you could probably fabricate any relationship you wanted between outcome and predictor, by ensuring that certain linearized values become either the largest, smallest, or middlemost.
Modular measurements—whether discrete or continuous—have important characteristics which have no representation in linear forms. This is why treating the modular numbers adorning the face of a clock make no sense as truly (linear) natural numbers. For a simple example, as we actually read the 12 hour clock, $1 - 12 = 1$, $3 - 9 = 9 - 3 = 6$, etc. But linearizing the clock's hours into integers would mean that $1 - 12 = -11$, and that $3 - 9 \ne 9 - 3$.
|
Converting a circular outcome variable to a linear one
You cannot validly linearize a circular measure which spans 360°, assuming the circularity of that measure is valid.
Any transformation which "linearizes" a circular measure must necessarily privilege
|
46,422
|
Converting a circular outcome variable to a linear one
|
Since you are interested in deviation from 0 (and not the direction), it would be appropriate to use $|\theta|$ as your variable.
You've defined the problem in a way such that $-90$ and $+90$ (and similarly, $-2$ and $+2$) are the same outcome so one can take the absolute value and replace the circular problem with a linear scale going from $0$ to $180$.
Your solution is equivalent to what I describe but rescaling (dividing by $1.8$) to go from $0$ to $100$ instead.
Circular statistics are vital when we care about position on a circle and need to account for the ends of the line wrapping around. In your problem instead of connecting the ends of the line together we are folding the line in half (not just matching $-180$ to $180$, but matching every $-\theta$ to $\theta$).
|
Converting a circular outcome variable to a linear one
|
Since you are interested in deviation from 0 (and not the direction), it would be appropriate to use $|\theta|$ as your variable.
You've defined the problem in a way such that $-90$ and $+90$ (and sim
|
Converting a circular outcome variable to a linear one
Since you are interested in deviation from 0 (and not the direction), it would be appropriate to use $|\theta|$ as your variable.
You've defined the problem in a way such that $-90$ and $+90$ (and similarly, $-2$ and $+2$) are the same outcome so one can take the absolute value and replace the circular problem with a linear scale going from $0$ to $180$.
Your solution is equivalent to what I describe but rescaling (dividing by $1.8$) to go from $0$ to $100$ instead.
Circular statistics are vital when we care about position on a circle and need to account for the ends of the line wrapping around. In your problem instead of connecting the ends of the line together we are folding the line in half (not just matching $-180$ to $180$, but matching every $-\theta$ to $\theta$).
|
Converting a circular outcome variable to a linear one
Since you are interested in deviation from 0 (and not the direction), it would be appropriate to use $|\theta|$ as your variable.
You've defined the problem in a way such that $-90$ and $+90$ (and sim
|
46,423
|
Is there a scenario where Bayes update results in no belief update when the prior has nonzero probability mass everywhere?
|
Let $X \sim U(a, a+1)$ for some unknown $a$ which is either 0 or 1. Suppose your prior on $a$ is uniform. Then suppose you observe $x = 1$. You can see via a symmetry argument that your posterior should be the same as your prior, since this gives you no information about $a$.
|
Is there a scenario where Bayes update results in no belief update when the prior has nonzero probab
|
Let $X \sim U(a, a+1)$ for some unknown $a$ which is either 0 or 1. Suppose your prior on $a$ is uniform. Then suppose you observe $x = 1$. You can see via a symmetry argument that your posterior sho
|
Is there a scenario where Bayes update results in no belief update when the prior has nonzero probability mass everywhere?
Let $X \sim U(a, a+1)$ for some unknown $a$ which is either 0 or 1. Suppose your prior on $a$ is uniform. Then suppose you observe $x = 1$. You can see via a symmetry argument that your posterior should be the same as your prior, since this gives you no information about $a$.
|
Is there a scenario where Bayes update results in no belief update when the prior has nonzero probab
Let $X \sim U(a, a+1)$ for some unknown $a$ which is either 0 or 1. Suppose your prior on $a$ is uniform. Then suppose you observe $x = 1$. You can see via a symmetry argument that your posterior sho
|
46,424
|
PCA leads to some highly Correlated Principal Components
|
You're right that the principal components should all be mutually orthogonal, so this is not expected. I think you probably have columns in your data matrix which are linearly dependent.
If the column rank of your data matrix is < 64, it is not possible to find 64 mutually orthogonal vectors in its column space. It might be better behavior for the package to return an error, or maybe fewer than 64 columns, in this case, but that is not what prcomp does.
Example:
m <- matrix(c(1,0,0,0,0,0,1,0,0), nrow=3)
cor(prcomp(m)$x)
Claims there are three principal components with pairwise correlation +/- 1. Something similar is probably happening in your data.
|
PCA leads to some highly Correlated Principal Components
|
You're right that the principal components should all be mutually orthogonal, so this is not expected. I think you probably have columns in your data matrix which are linearly dependent.
If the column
|
PCA leads to some highly Correlated Principal Components
You're right that the principal components should all be mutually orthogonal, so this is not expected. I think you probably have columns in your data matrix which are linearly dependent.
If the column rank of your data matrix is < 64, it is not possible to find 64 mutually orthogonal vectors in its column space. It might be better behavior for the package to return an error, or maybe fewer than 64 columns, in this case, but that is not what prcomp does.
Example:
m <- matrix(c(1,0,0,0,0,0,1,0,0), nrow=3)
cor(prcomp(m)$x)
Claims there are three principal components with pairwise correlation +/- 1. Something similar is probably happening in your data.
|
PCA leads to some highly Correlated Principal Components
You're right that the principal components should all be mutually orthogonal, so this is not expected. I think you probably have columns in your data matrix which are linearly dependent.
If the column
|
46,425
|
Likelihood term in Cox Proportional Hazards Model
|
Rewrite your last expression in terms of both the baseline hazard $h_0(t)$ and the covariate-associated hazard ratios:
$$\frac{h_0(t_j)\exp(\beta x_j)}{\sum_k h_0(t_j)\exp(\beta x_k)}= \frac{\exp(\beta x_j)}{\sum_k \exp(\beta x_k)}$$
where $k$ represents the people at risk in time $t_j$. That's the value of the proportional-hazards assumption: the baseline hazard function just factors out of the further calculations that estimate the coefficient values.
You shouldn't call the result a "maximum likelihood estimate"; as AdamO notes in another answer, it's based on a "partial likelihood" as the procedure doesn't take into account the baseline hazard.
|
Likelihood term in Cox Proportional Hazards Model
|
Rewrite your last expression in terms of both the baseline hazard $h_0(t)$ and the covariate-associated hazard ratios:
$$\frac{h_0(t_j)\exp(\beta x_j)}{\sum_k h_0(t_j)\exp(\beta x_k)}= \frac{\exp(\bet
|
Likelihood term in Cox Proportional Hazards Model
Rewrite your last expression in terms of both the baseline hazard $h_0(t)$ and the covariate-associated hazard ratios:
$$\frac{h_0(t_j)\exp(\beta x_j)}{\sum_k h_0(t_j)\exp(\beta x_k)}= \frac{\exp(\beta x_j)}{\sum_k \exp(\beta x_k)}$$
where $k$ represents the people at risk in time $t_j$. That's the value of the proportional-hazards assumption: the baseline hazard function just factors out of the further calculations that estimate the coefficient values.
You shouldn't call the result a "maximum likelihood estimate"; as AdamO notes in another answer, it's based on a "partial likelihood" as the procedure doesn't take into account the baseline hazard.
|
Likelihood term in Cox Proportional Hazards Model
Rewrite your last expression in terms of both the baseline hazard $h_0(t)$ and the covariate-associated hazard ratios:
$$\frac{h_0(t_j)\exp(\beta x_j)}{\sum_k h_0(t_j)\exp(\beta x_k)}= \frac{\exp(\bet
|
46,426
|
Likelihood term in Cox Proportional Hazards Model
|
The $h()$ is not a probability, it is a hazard, although they are monotonically related. The Cox model is not a full likelihood procedure, it maximizes a partial likelihood. Even though we don't directly estimate the hazard function as a nuisance parameter (which would be a conditional likelihood approach), we pretend we know what order people enter and leave the cohort, and who fails or is censored. This grouping, called the risk sets, is the key to the "normalizing" factor here. If we had a logistic regression, we would simply use the covariates to predict the probability of being a "case" in an analysis. However, since the sums of hazards don't normalize to any constant or have any bounds or constraints aside from being positive, we need to consider how many others are in a risk set to sort of rank the risk of a particular subject being a case in a particular risk set.
|
Likelihood term in Cox Proportional Hazards Model
|
The $h()$ is not a probability, it is a hazard, although they are monotonically related. The Cox model is not a full likelihood procedure, it maximizes a partial likelihood. Even though we don't direc
|
Likelihood term in Cox Proportional Hazards Model
The $h()$ is not a probability, it is a hazard, although they are monotonically related. The Cox model is not a full likelihood procedure, it maximizes a partial likelihood. Even though we don't directly estimate the hazard function as a nuisance parameter (which would be a conditional likelihood approach), we pretend we know what order people enter and leave the cohort, and who fails or is censored. This grouping, called the risk sets, is the key to the "normalizing" factor here. If we had a logistic regression, we would simply use the covariates to predict the probability of being a "case" in an analysis. However, since the sums of hazards don't normalize to any constant or have any bounds or constraints aside from being positive, we need to consider how many others are in a risk set to sort of rank the risk of a particular subject being a case in a particular risk set.
|
Likelihood term in Cox Proportional Hazards Model
The $h()$ is not a probability, it is a hazard, although they are monotonically related. The Cox model is not a full likelihood procedure, it maximizes a partial likelihood. Even though we don't direc
|
46,427
|
Insignificant F-test in linear regression - when to stop?
|
Short Answer
After spending several days thinking about this and running simulations, I can't agree with the usual recommendations. But if someone can see a flaw in my logic (which there easily might be) please do comment.
My conclusion is this. If your goal is to look at a series of predictors of interest one-by-one, then I think the ANOVA is not really relevant to that question and a better "general approach" (if we must have one) would be to Bonferroni correct your individual $t$-tests. The key points are:
If you want to keep your false positives under control, ANOVA followed by unadjusted $t$-tests does not do this. Especially if some of your predictors are real and some not (it only takes one "real" predictor successfully detected to unlock the ANOVA and open up the without-ANOVA false positive chances of the remaining tests).
Adjusting your $t$-tests (e.g. Bonferroni) does control your false positives and is in some cases, actually more powerful than the ANOVA. (When aggregated across all adjusted tests).
Adding an over-arching ANOVA to your adjusted $t$-tests is therefore not necessary (false-positives already under control). And it actually will (by its very design) mask some of the true positives you would otherwise have discovered.
The real strength of ANOVA is in detecting combinations of predictors and there are many situations where it is brilliant at that (dummies of categorical variables, combinations that are too weak to detect individually, correlated predictors that can be "lumped together"). It is precisely its excellent power in these situations that causes the trade-off that makes it unable to capture all the cases that Bonferroni-adjusted tests would make.
If you want a better intuition for why Bonferroni can beat ANOVA think of it this way: under the null both must reject 5% of cases (or close to that for the aggregate of your Bonferroni-tests). So the set of datasets where Bonferroni can reject cannot be a subset of those for ANOVA. Which is to say, if ANOVA does better at one thing, it must do worse than Bonferroni at something else.
Wouldn't it be better anyway if we estimated our coefficients and their errors? ;p A significant predictor might be small with small error; then you're pretty confident it isn't that interesting. A non-significant predictor might be very large but with a large error; OK, you're not confident in the result you got, but it looks promising!
Long Answer
As a stats educator I have always told my (unfortunate) students "well, what is the point of looking at the individual $t$ statistics if the $F$ tells us that the overall picture looks just like noise?". So, this question (and @whuber's example) actually kept me awake last night (not even joking), trying to figure out if I've been talking rubbish. And I think I have. The final answer I've arrived at isn't what I've been taught, nor what I've been teaching for the last decade, so if anyone with more experience/education than I can point out a flaw in my thinking I'd certainly be grateful.
Edit: Most of this was done looking at uncorrelated predictors. After taking the post down a couple of days to look at correlated predictors, the picture is a bit more murky, but I still come to the same conclusion. Small section on correlated predictors added right at the bottom.
My Answer
The answer I have reached is the opposite from what I have always thought. I now think the $F$-statistic does not devalue the results of any given significant $t$-test and should not be a barrier to checking the $t$-tests. But, that it can add value to non-significant $t$-tests.
That is to say: don't use the $F$ as a filter for your individual $t$-stats. But do use it to test interesting compound hypotheses.
The key here is that the $F$ has a different goal than the individual $t$-tests and should, I think, be used in line with this. If your goal is to test the predictors individually, then you might do better to just Bonferroni-adjust your $t$-tests-of-interest and look only at those. If your goal is specifically to see whether a bunch of predictors together can predict your dv, then the $F$-statistic has the upper hand and can detect things that your individual $t$-tests (even before corrections) could not.
The fact that ANOVA is so well crafted to pick up combinations of predictors actually directs it away from detecting individual significant predictors and means it can quite naturally appear to contradict your $t$-tests, just because it is asking a different question.
This conclusion came from looking at simulations based on @whuber's example, and a geometric visualisation to help me think this through. In case you're interested, more details follow... Usual caveats apply, that we are usually better informed by estimating effects and their CIs than looking at significance; also these results are what I've found with some preliminary simulations -- but someone might leap in and say I'm all wrong!
The Simulation
I wanted to understand @whuber's example more generally -- rather than one isolated example, so I ran a whole bunch of simulations that ran similar examples 10000 times. I also realised that this specific case (perfectly uncorrelated predictors) can be transformed into a super intuitive geometric interpretation. You can see a simulation along with the geometric interpretation below.
Each row in the table in the figure corresponds to adding an extra predictor to the model -- you can see the beta of the added predictor, and the % significant according to the ANOVA vs the % of cases where at least one of the Bonferroni-adjusted $t$-tests came out significant. So, row 4, for example has 4 predictors, with betas of 0, 0, 0 and 0. Clearly this is the null case, so we're relieved to see lots of 5% values in there.
The plot shows all the simulations that correspond with the second row of the table: where we have two predictors. The axes give the $t$ statistics for the slopes on those two variables; each dot is a simulation. Those dots outside the circle will be significant under the ANOVA, those dots outside the square will have at least one significant Bonferroni-corrected $t$. (The circle was calculated based on the fact that the $F$ in this uncorrelated case is the mean of the squared $t$ statistics). Brightly coloured dots are those simulations that are called significant by only one of our two methods (ANOVA, Bonferroni $t$).
Now, here is the plot of 10000 simulations based on @whuber's example, with number of predictors set to 10:
It really surprised me to find that, in this case, the Bonferroni approach is consistently more powerful than the ANOVA?! But, looking at the graph, we can see why: all those red dots that land in that little "blind spot" of the ANOVA, which is exactly where we'd like it to be.
This held even with a lower effect size and so, lower power (correction to earlier, due to change in approach to the Bonferroni):
Where the ANOVA comes into its own is when looking at combinations of predictors. Say, if we add a second meaningful predictor to the model:
...albeit, the Bonferroni lags but is not too too far behind! But still, we can see that, whereas the ANOVA has a blind spot on the "only one meaningful predictor" case, the Bonferronied-$t$ has its corresponding blindspot in the "combination of predictors" case (the cyan dots). And the more meaningful predictors we add to the model, the further and further the Bonferronied-$t$ starts to fall behind:
So What?
The key takeaway for me from all of this, was that the $F$-statistic is actually somewhat apples and oranges with the $t$-tests. It isn't necessarily the perfect umbrella test, if you want to check predictors one-by-one for significance. It is (I think?) the most powerful option for detecting departures from noise overall: by sitting its circle on the contours of the distribution of dots in the plots, it means the non-rejection region is the smallest possible. But we gain that power in detecting combinations that are very hard for us to interpret.
If you are in a situation where you have ten predictors that all have $t$-statistics of 1.4, it will be able to detect that as "unusual" (a.k.a. significant). But what are you going to do with that? How are you going to then decipher which of those is really behind this? Your $t$-tests aren't going to be much use. If, instead, you use the Bonferroni-adjusted $t$ statistics, you do lose power overall, potentially quite a lot. But you actually gain some power in the situations that you can interpret and that are in line with your objectives. And, crucially, here is the key point: doing so is completely consistent; starting with an ANOVA is mixing together two different questions as if they were one.
So, I think (as it stands at present), I can no longer justify this approach of using the $F$ as a gateway to the $t$ tests.
On the other hand, you might be specifically interested in the combination of a set of predictors. For example, if there is too much noise to detect them individually, or if they don't make sense individually (such as dummies of a categorical variable). In that case, ANOVA really is the stuff!
Code
Here is the code, in case you want to play with it. Sorry it's so long, but I like that you can tweak almost every aspect of the simulation:
library(ggplot2)
library(gridExtra)
# choose your betas to try different possiblities. You can change the number of betas and it will change the number of xs -- which will also change the dataset size according whuber's approach
betas <- c( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c( 1, 0, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c(.5, 0, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c(.7, .7, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c( 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)*.5
data.multiplier <- 1 # set this at 1 to reproduce @whuber's example. A higher number adds more data to the dataset (e.g. 2 will double the rows up)
# crude attempt to always start out with 80%ish power for the one-predictor cases
num.predictors <- length(betas)
num.data <- 2 ^ num.predictors * data.multiplier
noise.sigma <- sqrt(1/8) * sqrt(num.data)
num.sims <- 500 # Number of simulations(reduced to 500 here as better to play with)
set.seed(1)
run.anova.on.subset = function(i, x, y){
test <- summary(lm(y ~ x[, 1:i]))
F <- test$fstatistic
num.coeffs <- nrow(test$coefficients)
p.F <- 1-pf(F["value"], F["numdf"], F["dendf"])
p.ts <- as.numeric(test$coefficients[2:num.coeffs, "Pr(>|t|)"])
ts <- as.numeric(test$coefficients[2:num.coeffs, "t value" ])
names(p.F) <- NULL
c(
t1 = ts[1],
t2 = if(i > 1) ts[2] else NA,
Bonferroni = any(p.ts < .05 / i),
ANOVA = p.F < .05
)
}
generate.dataset.and.run.all.Fs = function(){
# this is @whuber's setup with orthogonal predictors of which only one contributes to y
x <- as.matrix(do.call(expand.grid, replicate(num.predictors, c(-1, 1), simplify = FALSE)))
x <- do.call(rbind, replicate(data.multiplier, x, simplify = FALSE))
y <- x %*% betas + rnorm(n=num.data, mean=0, sd=noise.sigma)
sapply(1:num.predictors, run.anova.on.subset, x, y)
}
runs <- replicate(num.sims, generate.dataset.and.run.all.Fs())
# convert simulation results into a table of powers and dataframe of ts from each simulation
power.table <- apply(runs, 1:2, mean)[3:nrow(runs),]
power.df <- as.data.frame(t(power.table))
ts.df = as.data.frame(t(runs[, 2, ]))
predictors.df = data.frame(
beta = betas,
Bonf. = sprintf("%.0f%%", power.df$Bonferroni * 100),
F = sprintf("%.0f%%", power.df$ANOVA * 100)
)
# critical values. f is F transformed to scale of t
Fcrit = qf(.95,2,num.data-3)
fcrit = sqrt(2*Fcrit)
Boncrit = qt((1-.05/(2*2)), num.data-3)
# coords for the circle and square on the plot
Boncrit.df = data.frame(
t1 = c(Boncrit, Boncrit, -Boncrit, -Boncrit, Boncrit),
t2 = c(Boncrit, -Boncrit, -Boncrit, Boncrit, Boncrit)
)
thetas = seq(0,2*pi, length.out=300)
circle = data.frame(
t1 = cos(thetas) * fcrit,
t2 = sin(thetas) * fcrit
)
# expand xlimits to fit in power table
xlims <- c(min(c(ts.df$t1, circle$t1)), max(ts.df$t1))
RHside <- xlims[2]
xlims[2] <- xlims[2] + diff(xlims)*.5
plot = ggplot(aes(t1,t2), data=ts.df) +
geom_point(aes(colour=interaction(Bonferroni,ANOVA))) +
geom_path(data=circle, size=1) +
geom_path(data=Boncrit.df, linetype="dashed", size=1) +
scale_colour_manual(values=c("grey", "red", "cyan", "black")) +
scale_x_continuous(limits=xlims) +
annotation_custom(tableGrob(predictors.df, theme=ttheme_minimal()), xmin=RHside) +
theme_classic() +
theme(legend.position = "none")
print(plot)
Correlated Predictors
Once we start to look at correlated predictors, things get a little more complicated. The Bonferroni approach suffers badly when we have two correlated predictors, as the individual $t$-tests must incorporate uncertainty about "which" of them is the "cause" (please read that word loosely!). The ANOVA, on the other hand can just say, hey, these two look interesting; I award you significant!
But, here's the thing. Every way I look at it, it loops back to the same problem. If anything, the points made in the earlier section are more acute here: the ANOVA is far more powerful, by focussing on detecting scenarios that we cannot interpret (that is, if our goal is to look predictor by predictor). In the figure below, the "cyan" column shows that (in this scenario) we have about 20% of experiments come back significant on the ANOVA, but not on the Bonferroni-$t$ (cyan dots in the figure), so we are stuck trying to interpret them.
And, again, because the rejection region must always cover 95% (ish for Bonferroni) of cases in the null, this increased power on the cyan cases must come at a cost. The cost is that a proportion of cases (up to 6% for this scenario) are red dots -- significant under Bonferroni, but not under the ANOVA. Those are cases that would have been interpretable, but we stopped because of the ANOVA. If we just focus on those cases where we would successfully detect the first predictor with Bonferroni (Bonferroni $t$ True Positives -- "BtTP"), the last column of the table ("BtTPs.blocked") shows that the ANOVA would actually cause us to miss 20% of those in the 10-predictor case!
If you think, hey but you're using the Bonferroni-adjusted $t$ values, that's why you're getting these rubbish results... Firstly, the "FtFP" (F-and-then-$t$ False Positives) shows that using the ANOVA followed by unadjusted $t$s produces at least one false positive in up to 22% of our samples. Secondly, the ANOVA isn't meant to allow us to use non-adjusted $t$s here. Indeed, we hope that the ANOVA will be significant to "allow" us to look at the our true positives on predictor 1. But that then does nothing to control the errors on predictors 2-10.
(For full clarity: in the above simulation, each odd numbered predictor has a correlation of 0.6 with the predictor after it. But the rest of the correlations are zero.)
Again, the final point is: this is not anti-ANOVA! Indeed, this suggests that if you have two strongly correlated predictors that sit together and make a nice "thing" -- why not blob them together into one $F$ statistic and test both at the same time? That, as well as the cases from before (dummies and combinations that are hard to detect individually). There are many cases where the ANOVA is far the better tool. It is just a case of picking the right tool for the job. But, when it comes to testing a series of individual predictors of a regression, I don't believe ANOVA is the right umbrella for that job.
|
Insignificant F-test in linear regression - when to stop?
|
Short Answer
After spending several days thinking about this and running simulations, I can't agree with the usual recommendations. But if someone can see a flaw in my logic (which there easily might
|
Insignificant F-test in linear regression - when to stop?
Short Answer
After spending several days thinking about this and running simulations, I can't agree with the usual recommendations. But if someone can see a flaw in my logic (which there easily might be) please do comment.
My conclusion is this. If your goal is to look at a series of predictors of interest one-by-one, then I think the ANOVA is not really relevant to that question and a better "general approach" (if we must have one) would be to Bonferroni correct your individual $t$-tests. The key points are:
If you want to keep your false positives under control, ANOVA followed by unadjusted $t$-tests does not do this. Especially if some of your predictors are real and some not (it only takes one "real" predictor successfully detected to unlock the ANOVA and open up the without-ANOVA false positive chances of the remaining tests).
Adjusting your $t$-tests (e.g. Bonferroni) does control your false positives and is in some cases, actually more powerful than the ANOVA. (When aggregated across all adjusted tests).
Adding an over-arching ANOVA to your adjusted $t$-tests is therefore not necessary (false-positives already under control). And it actually will (by its very design) mask some of the true positives you would otherwise have discovered.
The real strength of ANOVA is in detecting combinations of predictors and there are many situations where it is brilliant at that (dummies of categorical variables, combinations that are too weak to detect individually, correlated predictors that can be "lumped together"). It is precisely its excellent power in these situations that causes the trade-off that makes it unable to capture all the cases that Bonferroni-adjusted tests would make.
If you want a better intuition for why Bonferroni can beat ANOVA think of it this way: under the null both must reject 5% of cases (or close to that for the aggregate of your Bonferroni-tests). So the set of datasets where Bonferroni can reject cannot be a subset of those for ANOVA. Which is to say, if ANOVA does better at one thing, it must do worse than Bonferroni at something else.
Wouldn't it be better anyway if we estimated our coefficients and their errors? ;p A significant predictor might be small with small error; then you're pretty confident it isn't that interesting. A non-significant predictor might be very large but with a large error; OK, you're not confident in the result you got, but it looks promising!
Long Answer
As a stats educator I have always told my (unfortunate) students "well, what is the point of looking at the individual $t$ statistics if the $F$ tells us that the overall picture looks just like noise?". So, this question (and @whuber's example) actually kept me awake last night (not even joking), trying to figure out if I've been talking rubbish. And I think I have. The final answer I've arrived at isn't what I've been taught, nor what I've been teaching for the last decade, so if anyone with more experience/education than I can point out a flaw in my thinking I'd certainly be grateful.
Edit: Most of this was done looking at uncorrelated predictors. After taking the post down a couple of days to look at correlated predictors, the picture is a bit more murky, but I still come to the same conclusion. Small section on correlated predictors added right at the bottom.
My Answer
The answer I have reached is the opposite from what I have always thought. I now think the $F$-statistic does not devalue the results of any given significant $t$-test and should not be a barrier to checking the $t$-tests. But, that it can add value to non-significant $t$-tests.
That is to say: don't use the $F$ as a filter for your individual $t$-stats. But do use it to test interesting compound hypotheses.
The key here is that the $F$ has a different goal than the individual $t$-tests and should, I think, be used in line with this. If your goal is to test the predictors individually, then you might do better to just Bonferroni-adjust your $t$-tests-of-interest and look only at those. If your goal is specifically to see whether a bunch of predictors together can predict your dv, then the $F$-statistic has the upper hand and can detect things that your individual $t$-tests (even before corrections) could not.
The fact that ANOVA is so well crafted to pick up combinations of predictors actually directs it away from detecting individual significant predictors and means it can quite naturally appear to contradict your $t$-tests, just because it is asking a different question.
This conclusion came from looking at simulations based on @whuber's example, and a geometric visualisation to help me think this through. In case you're interested, more details follow... Usual caveats apply, that we are usually better informed by estimating effects and their CIs than looking at significance; also these results are what I've found with some preliminary simulations -- but someone might leap in and say I'm all wrong!
The Simulation
I wanted to understand @whuber's example more generally -- rather than one isolated example, so I ran a whole bunch of simulations that ran similar examples 10000 times. I also realised that this specific case (perfectly uncorrelated predictors) can be transformed into a super intuitive geometric interpretation. You can see a simulation along with the geometric interpretation below.
Each row in the table in the figure corresponds to adding an extra predictor to the model -- you can see the beta of the added predictor, and the % significant according to the ANOVA vs the % of cases where at least one of the Bonferroni-adjusted $t$-tests came out significant. So, row 4, for example has 4 predictors, with betas of 0, 0, 0 and 0. Clearly this is the null case, so we're relieved to see lots of 5% values in there.
The plot shows all the simulations that correspond with the second row of the table: where we have two predictors. The axes give the $t$ statistics for the slopes on those two variables; each dot is a simulation. Those dots outside the circle will be significant under the ANOVA, those dots outside the square will have at least one significant Bonferroni-corrected $t$. (The circle was calculated based on the fact that the $F$ in this uncorrelated case is the mean of the squared $t$ statistics). Brightly coloured dots are those simulations that are called significant by only one of our two methods (ANOVA, Bonferroni $t$).
Now, here is the plot of 10000 simulations based on @whuber's example, with number of predictors set to 10:
It really surprised me to find that, in this case, the Bonferroni approach is consistently more powerful than the ANOVA?! But, looking at the graph, we can see why: all those red dots that land in that little "blind spot" of the ANOVA, which is exactly where we'd like it to be.
This held even with a lower effect size and so, lower power (correction to earlier, due to change in approach to the Bonferroni):
Where the ANOVA comes into its own is when looking at combinations of predictors. Say, if we add a second meaningful predictor to the model:
...albeit, the Bonferroni lags but is not too too far behind! But still, we can see that, whereas the ANOVA has a blind spot on the "only one meaningful predictor" case, the Bonferronied-$t$ has its corresponding blindspot in the "combination of predictors" case (the cyan dots). And the more meaningful predictors we add to the model, the further and further the Bonferronied-$t$ starts to fall behind:
So What?
The key takeaway for me from all of this, was that the $F$-statistic is actually somewhat apples and oranges with the $t$-tests. It isn't necessarily the perfect umbrella test, if you want to check predictors one-by-one for significance. It is (I think?) the most powerful option for detecting departures from noise overall: by sitting its circle on the contours of the distribution of dots in the plots, it means the non-rejection region is the smallest possible. But we gain that power in detecting combinations that are very hard for us to interpret.
If you are in a situation where you have ten predictors that all have $t$-statistics of 1.4, it will be able to detect that as "unusual" (a.k.a. significant). But what are you going to do with that? How are you going to then decipher which of those is really behind this? Your $t$-tests aren't going to be much use. If, instead, you use the Bonferroni-adjusted $t$ statistics, you do lose power overall, potentially quite a lot. But you actually gain some power in the situations that you can interpret and that are in line with your objectives. And, crucially, here is the key point: doing so is completely consistent; starting with an ANOVA is mixing together two different questions as if they were one.
So, I think (as it stands at present), I can no longer justify this approach of using the $F$ as a gateway to the $t$ tests.
On the other hand, you might be specifically interested in the combination of a set of predictors. For example, if there is too much noise to detect them individually, or if they don't make sense individually (such as dummies of a categorical variable). In that case, ANOVA really is the stuff!
Code
Here is the code, in case you want to play with it. Sorry it's so long, but I like that you can tweak almost every aspect of the simulation:
library(ggplot2)
library(gridExtra)
# choose your betas to try different possiblities. You can change the number of betas and it will change the number of xs -- which will also change the dataset size according whuber's approach
betas <- c( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c( 1, 0, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c(.5, 0, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c(.7, .7, 0, 0, 0, 0, 0, 0, 0, 0)
betas <- c( 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)*.5
data.multiplier <- 1 # set this at 1 to reproduce @whuber's example. A higher number adds more data to the dataset (e.g. 2 will double the rows up)
# crude attempt to always start out with 80%ish power for the one-predictor cases
num.predictors <- length(betas)
num.data <- 2 ^ num.predictors * data.multiplier
noise.sigma <- sqrt(1/8) * sqrt(num.data)
num.sims <- 500 # Number of simulations(reduced to 500 here as better to play with)
set.seed(1)
run.anova.on.subset = function(i, x, y){
test <- summary(lm(y ~ x[, 1:i]))
F <- test$fstatistic
num.coeffs <- nrow(test$coefficients)
p.F <- 1-pf(F["value"], F["numdf"], F["dendf"])
p.ts <- as.numeric(test$coefficients[2:num.coeffs, "Pr(>|t|)"])
ts <- as.numeric(test$coefficients[2:num.coeffs, "t value" ])
names(p.F) <- NULL
c(
t1 = ts[1],
t2 = if(i > 1) ts[2] else NA,
Bonferroni = any(p.ts < .05 / i),
ANOVA = p.F < .05
)
}
generate.dataset.and.run.all.Fs = function(){
# this is @whuber's setup with orthogonal predictors of which only one contributes to y
x <- as.matrix(do.call(expand.grid, replicate(num.predictors, c(-1, 1), simplify = FALSE)))
x <- do.call(rbind, replicate(data.multiplier, x, simplify = FALSE))
y <- x %*% betas + rnorm(n=num.data, mean=0, sd=noise.sigma)
sapply(1:num.predictors, run.anova.on.subset, x, y)
}
runs <- replicate(num.sims, generate.dataset.and.run.all.Fs())
# convert simulation results into a table of powers and dataframe of ts from each simulation
power.table <- apply(runs, 1:2, mean)[3:nrow(runs),]
power.df <- as.data.frame(t(power.table))
ts.df = as.data.frame(t(runs[, 2, ]))
predictors.df = data.frame(
beta = betas,
Bonf. = sprintf("%.0f%%", power.df$Bonferroni * 100),
F = sprintf("%.0f%%", power.df$ANOVA * 100)
)
# critical values. f is F transformed to scale of t
Fcrit = qf(.95,2,num.data-3)
fcrit = sqrt(2*Fcrit)
Boncrit = qt((1-.05/(2*2)), num.data-3)
# coords for the circle and square on the plot
Boncrit.df = data.frame(
t1 = c(Boncrit, Boncrit, -Boncrit, -Boncrit, Boncrit),
t2 = c(Boncrit, -Boncrit, -Boncrit, Boncrit, Boncrit)
)
thetas = seq(0,2*pi, length.out=300)
circle = data.frame(
t1 = cos(thetas) * fcrit,
t2 = sin(thetas) * fcrit
)
# expand xlimits to fit in power table
xlims <- c(min(c(ts.df$t1, circle$t1)), max(ts.df$t1))
RHside <- xlims[2]
xlims[2] <- xlims[2] + diff(xlims)*.5
plot = ggplot(aes(t1,t2), data=ts.df) +
geom_point(aes(colour=interaction(Bonferroni,ANOVA))) +
geom_path(data=circle, size=1) +
geom_path(data=Boncrit.df, linetype="dashed", size=1) +
scale_colour_manual(values=c("grey", "red", "cyan", "black")) +
scale_x_continuous(limits=xlims) +
annotation_custom(tableGrob(predictors.df, theme=ttheme_minimal()), xmin=RHside) +
theme_classic() +
theme(legend.position = "none")
print(plot)
Correlated Predictors
Once we start to look at correlated predictors, things get a little more complicated. The Bonferroni approach suffers badly when we have two correlated predictors, as the individual $t$-tests must incorporate uncertainty about "which" of them is the "cause" (please read that word loosely!). The ANOVA, on the other hand can just say, hey, these two look interesting; I award you significant!
But, here's the thing. Every way I look at it, it loops back to the same problem. If anything, the points made in the earlier section are more acute here: the ANOVA is far more powerful, by focussing on detecting scenarios that we cannot interpret (that is, if our goal is to look predictor by predictor). In the figure below, the "cyan" column shows that (in this scenario) we have about 20% of experiments come back significant on the ANOVA, but not on the Bonferroni-$t$ (cyan dots in the figure), so we are stuck trying to interpret them.
And, again, because the rejection region must always cover 95% (ish for Bonferroni) of cases in the null, this increased power on the cyan cases must come at a cost. The cost is that a proportion of cases (up to 6% for this scenario) are red dots -- significant under Bonferroni, but not under the ANOVA. Those are cases that would have been interpretable, but we stopped because of the ANOVA. If we just focus on those cases where we would successfully detect the first predictor with Bonferroni (Bonferroni $t$ True Positives -- "BtTP"), the last column of the table ("BtTPs.blocked") shows that the ANOVA would actually cause us to miss 20% of those in the 10-predictor case!
If you think, hey but you're using the Bonferroni-adjusted $t$ values, that's why you're getting these rubbish results... Firstly, the "FtFP" (F-and-then-$t$ False Positives) shows that using the ANOVA followed by unadjusted $t$s produces at least one false positive in up to 22% of our samples. Secondly, the ANOVA isn't meant to allow us to use non-adjusted $t$s here. Indeed, we hope that the ANOVA will be significant to "allow" us to look at the our true positives on predictor 1. But that then does nothing to control the errors on predictors 2-10.
(For full clarity: in the above simulation, each odd numbered predictor has a correlation of 0.6 with the predictor after it. But the rest of the correlations are zero.)
Again, the final point is: this is not anti-ANOVA! Indeed, this suggests that if you have two strongly correlated predictors that sit together and make a nice "thing" -- why not blob them together into one $F$ statistic and test both at the same time? That, as well as the cases from before (dummies and combinations that are hard to detect individually). There are many cases where the ANOVA is far the better tool. It is just a case of picking the right tool for the job. But, when it comes to testing a series of individual predictors of a regression, I don't believe ANOVA is the right umbrella for that job.
|
Insignificant F-test in linear regression - when to stop?
Short Answer
After spending several days thinking about this and running simulations, I can't agree with the usual recommendations. But if someone can see a flaw in my logic (which there easily might
|
46,428
|
Subscript notation in expectations (variational autoencoder)
|
It means expectation with respect to $q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})$. So:
$$\mathbb{E}_{q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})}[\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})] = \int_{\mathbb{R}^d} q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)}) \log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z}) d \mathbf{z} $$
Where without further information on the dimensionality of $\mathbf{z}$ I have assumed it to be in $\mathbb{R}^d$.
To further clarify, note that the underlying random vector/source of randomness is $\mathbf{z}$, of which you are computing the expectation of a function $f(\mathbf{z})$, where $f(\mathbf{z}) = \log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})$. And this underlying source of randomness is captured in the distribution $q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})$.
Addressing comments.
In response to:
The part confuses me is that in $f(\mathbf{z})$, $\mathbf{z}$ plays the role of a condition which seems like it is fixed?
As a disclaimer, I've not yet read the paper "Auto-encoding variational Bayes" by Kingma and Welling in sufficient depth. I therefore cannot appropriately supply context-specific interpretations e.g. what is a decoder/encoder etc. However, that may not be necessary at this stage as I suspect the issue is not of a contextual nature.
I used the notation $f(\mathbf{z})$ without including other arguments, purely to indicate where the source of the randomness is coming from - there are other arguments in $f$ which I've neglected to mention.
'Decompressing' what is inside the expectation :
$$\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z}) = \log p(\mathbf{x}^{(i)} | \mathbf{z}; \theta) = \log p(\mathbf{x} | \mathbf{z}; \theta) \left. \right|_{\mathbf{x} = \mathbf{x}^{(i)}}$$
Where $\left. \right|_{\mathbf{x} = \mathbf{x}^{(i)}}$ means 'evaluated at $\mathbf{x} = \mathbf{x}^{(i)}$', and I have used the semi-colon to indicate that the fixed, but unknown parameter $\theta$ parametrises the conditional distribution, and that it is not being treated as a random variable (at least in the 1st part of the paper).
Consider the function $f(\mathbf{x}, \mathbf{z}, \theta) = \log p(\mathbf{x} | \mathbf{z}; \theta)$.
Now $f$ is a completely deterministic function - if I input a value of the observed data $\mathbf{x} = \mathbf{x}^{(i)}$, a value of the latent variable $\mathbf{z} = \mathbf{z}^{(i)}$, and a value of the parameter $\theta = \theta_0$, it will output a fixed number i.e. the log-conditional density of observing $\mathbf{x}^{(i)}$, given that the latent variable is observed to be $\mathbf{z}^{(i)}$, for a particular parameter value $\theta_0$.
Now consider the case where we fix the random variables $\mathbf{x} = \mathbf{x}^{(i)}$ and $\mathbf{z} = \mathbf{z}^{(i)}$, but where we don't know $\theta$. In this case, $f(\mathbf{x}^{(i)}, \mathbf{z}^{(i)}, \theta)$ can only freely vary in $\theta$, and is still deterministic. This is because we have fixed the random variable $\mathbf{x}$ using the observed data $\mathbf{x}^{(i)}$, and fixed the random variable $\mathbf{z}$ by conditioning on an observation of the latent variable $\mathbf{z}^{(i)}$. I suspect that this what you might be thinking of when you say "$\mathbf{z}$ plays the role of a condition which seems like it is fixed". This is not the situation we are in.
The situation we are in is $f(\mathbf{x}^{(i)}, \mathbf{z}, \theta) = \log p(\mathbf{x}^{(i)} | \mathbf{z}; \theta)$. Here, the training data, having been observed is fixed at $\mathbf{x} = \mathbf{x}^{(i)}$, but now $f(\mathbf{x}^{(i)}, \mathbf{z}, \theta)$ can freely vary in both the parameter $\theta$ and also in the latent variable $\mathbf{z}$. Additionally, the output of this function is now random, and this is due solely to one of its inputs, the latent variable $\mathbf{z}$, being random. Hence the key distinction to be aware of is that we are not conditioning on an observation of the latent variable $\mathbf{z}^{(i)}$, rather, conditioning on the latent random variable $\mathbf{z}$.
The key distinction I believe you are overlooking is that of conditioning on a random variable, and conditioning on an observed value of a random variable.
Now what you are doing when taking expectation with respect to $q(\mathbf{z} | \mathbf{x}^{(i)}; \phi)$ is that you are 'averaging out the randomness' of the unknown latent variable $\mathbf{z}$ altogether. Meaning that computing the expectation
$$\begin{align}
\mathbb{E}_{q(\mathbf{z} | \mathbf{x}^{(i)}; \phi)}[\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})] &= \int_{\mathbb{R}^d} q(\mathbf{z} | \mathbf{x}^{(i)}; \phi) \log p(\mathbf{x}^{(i)} | \mathbf{z}; \theta) d \mathbf{z} \\
&= h(\phi, \theta)
\end{align}$$
Will give you a deterministic function $h$ that can only vary in the model parameter $\theta$ and the variational parameter $\phi$, both of which, in the initial parts of the paper, are not treated as random variables, rather global parameters we'd like to estimate.
As a sanity check, if you go back to the main equation, note the evidence lower bound evaluated at training data point $i$ is denoted as $\mathcal{L}(\theta, \phi; \mathbf{x}^{(i)})$, and the fact that as specified, it can only freely vary in $\theta$ and $\phi$.
|
Subscript notation in expectations (variational autoencoder)
|
It means expectation with respect to $q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})$. So:
$$\mathbb{E}_{q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})}[\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})] = \int_{\math
|
Subscript notation in expectations (variational autoencoder)
It means expectation with respect to $q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})$. So:
$$\mathbb{E}_{q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})}[\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})] = \int_{\mathbb{R}^d} q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)}) \log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z}) d \mathbf{z} $$
Where without further information on the dimensionality of $\mathbf{z}$ I have assumed it to be in $\mathbb{R}^d$.
To further clarify, note that the underlying random vector/source of randomness is $\mathbf{z}$, of which you are computing the expectation of a function $f(\mathbf{z})$, where $f(\mathbf{z}) = \log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})$. And this underlying source of randomness is captured in the distribution $q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})$.
Addressing comments.
In response to:
The part confuses me is that in $f(\mathbf{z})$, $\mathbf{z}$ plays the role of a condition which seems like it is fixed?
As a disclaimer, I've not yet read the paper "Auto-encoding variational Bayes" by Kingma and Welling in sufficient depth. I therefore cannot appropriately supply context-specific interpretations e.g. what is a decoder/encoder etc. However, that may not be necessary at this stage as I suspect the issue is not of a contextual nature.
I used the notation $f(\mathbf{z})$ without including other arguments, purely to indicate where the source of the randomness is coming from - there are other arguments in $f$ which I've neglected to mention.
'Decompressing' what is inside the expectation :
$$\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z}) = \log p(\mathbf{x}^{(i)} | \mathbf{z}; \theta) = \log p(\mathbf{x} | \mathbf{z}; \theta) \left. \right|_{\mathbf{x} = \mathbf{x}^{(i)}}$$
Where $\left. \right|_{\mathbf{x} = \mathbf{x}^{(i)}}$ means 'evaluated at $\mathbf{x} = \mathbf{x}^{(i)}$', and I have used the semi-colon to indicate that the fixed, but unknown parameter $\theta$ parametrises the conditional distribution, and that it is not being treated as a random variable (at least in the 1st part of the paper).
Consider the function $f(\mathbf{x}, \mathbf{z}, \theta) = \log p(\mathbf{x} | \mathbf{z}; \theta)$.
Now $f$ is a completely deterministic function - if I input a value of the observed data $\mathbf{x} = \mathbf{x}^{(i)}$, a value of the latent variable $\mathbf{z} = \mathbf{z}^{(i)}$, and a value of the parameter $\theta = \theta_0$, it will output a fixed number i.e. the log-conditional density of observing $\mathbf{x}^{(i)}$, given that the latent variable is observed to be $\mathbf{z}^{(i)}$, for a particular parameter value $\theta_0$.
Now consider the case where we fix the random variables $\mathbf{x} = \mathbf{x}^{(i)}$ and $\mathbf{z} = \mathbf{z}^{(i)}$, but where we don't know $\theta$. In this case, $f(\mathbf{x}^{(i)}, \mathbf{z}^{(i)}, \theta)$ can only freely vary in $\theta$, and is still deterministic. This is because we have fixed the random variable $\mathbf{x}$ using the observed data $\mathbf{x}^{(i)}$, and fixed the random variable $\mathbf{z}$ by conditioning on an observation of the latent variable $\mathbf{z}^{(i)}$. I suspect that this what you might be thinking of when you say "$\mathbf{z}$ plays the role of a condition which seems like it is fixed". This is not the situation we are in.
The situation we are in is $f(\mathbf{x}^{(i)}, \mathbf{z}, \theta) = \log p(\mathbf{x}^{(i)} | \mathbf{z}; \theta)$. Here, the training data, having been observed is fixed at $\mathbf{x} = \mathbf{x}^{(i)}$, but now $f(\mathbf{x}^{(i)}, \mathbf{z}, \theta)$ can freely vary in both the parameter $\theta$ and also in the latent variable $\mathbf{z}$. Additionally, the output of this function is now random, and this is due solely to one of its inputs, the latent variable $\mathbf{z}$, being random. Hence the key distinction to be aware of is that we are not conditioning on an observation of the latent variable $\mathbf{z}^{(i)}$, rather, conditioning on the latent random variable $\mathbf{z}$.
The key distinction I believe you are overlooking is that of conditioning on a random variable, and conditioning on an observed value of a random variable.
Now what you are doing when taking expectation with respect to $q(\mathbf{z} | \mathbf{x}^{(i)}; \phi)$ is that you are 'averaging out the randomness' of the unknown latent variable $\mathbf{z}$ altogether. Meaning that computing the expectation
$$\begin{align}
\mathbb{E}_{q(\mathbf{z} | \mathbf{x}^{(i)}; \phi)}[\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})] &= \int_{\mathbb{R}^d} q(\mathbf{z} | \mathbf{x}^{(i)}; \phi) \log p(\mathbf{x}^{(i)} | \mathbf{z}; \theta) d \mathbf{z} \\
&= h(\phi, \theta)
\end{align}$$
Will give you a deterministic function $h$ that can only vary in the model parameter $\theta$ and the variational parameter $\phi$, both of which, in the initial parts of the paper, are not treated as random variables, rather global parameters we'd like to estimate.
As a sanity check, if you go back to the main equation, note the evidence lower bound evaluated at training data point $i$ is denoted as $\mathcal{L}(\theta, \phi; \mathbf{x}^{(i)})$, and the fact that as specified, it can only freely vary in $\theta$ and $\phi$.
|
Subscript notation in expectations (variational autoencoder)
It means expectation with respect to $q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})$. So:
$$\mathbb{E}_{q_{\phi}(\mathbf{z} | \mathbf{x}^{(i)})}[\log p_{\theta}(\mathbf{x}^{(i)} | \mathbf{z})] = \int_{\math
|
46,429
|
Independence of variables in expectation
|
No, it's not enough. Although $X$ and $Y$ are independent, the events $\{X<Y\}$ and $\{X>2\}$ are not. Let's say $Y$ is a constant random variable and is equal to $2$ with probability $1$. Then, $$E[I(X<2)I(X>2)]=0$$
But, $E[I(X<2)]E[I(X>2)]$ depends on $X$.
|
Independence of variables in expectation
|
No, it's not enough. Although $X$ and $Y$ are independent, the events $\{X<Y\}$ and $\{X>2\}$ are not. Let's say $Y$ is a constant random variable and is equal to $2$ with probability $1$. Then, $$E[I
|
Independence of variables in expectation
No, it's not enough. Although $X$ and $Y$ are independent, the events $\{X<Y\}$ and $\{X>2\}$ are not. Let's say $Y$ is a constant random variable and is equal to $2$ with probability $1$. Then, $$E[I(X<2)I(X>2)]=0$$
But, $E[I(X<2)]E[I(X>2)]$ depends on $X$.
|
Independence of variables in expectation
No, it's not enough. Although $X$ and $Y$ are independent, the events $\{X<Y\}$ and $\{X>2\}$ are not. Let's say $Y$ is a constant random variable and is equal to $2$ with probability $1$. Then, $$E[I
|
46,430
|
What is the expected distance to the nearest molecule?
|
Consider $d$ dimensions. The distribution to the nearest neighbor of any point can be approximated by supposing $N$ neighbors are independently, uniformly, and randomly situated within a radius of one unit from that point (where the distance unit and $N$ are chosen to reproduce the molecular density; preferably $N$ is large).
The chance that one given neighbor is further than a distance $r$ (for $0\le r \le 1$) is the relative volume of the spherical shell between the balls of radii $r$ and $1,$ equal to
$$S_{d}(r) = 1 - r^d.$$
Since the neighbor positions are independent, the chance that all are further than distance $r$ is
$$S_{N;d}(r) = (1-r^d)^N.$$
This (the survival function) determines the distribution of the distance $R$ to the nearest neighbor. Its expectation is the integral of the survival function,
$$E[R] = \int_0^1 S_{N;d}(r)\,\mathrm{d}r = \int_0^1 (1-r^d)^N\,\mathrm{d}r = B(N+1,1/d)/d$$
where $B$ is the Beta function
$$B(a,b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}.$$
For instance, here is a histogram of 50,000 simulated values of $R$ with $N=500-1$ neighbors.
On it I have superimposed the graph of the density function $-d/dr\, S_{499;3}(r)$ in red to show the agreement and I have plotted a vertical line to show $E[R].$
|
What is the expected distance to the nearest molecule?
|
Consider $d$ dimensions. The distribution to the nearest neighbor of any point can be approximated by supposing $N$ neighbors are independently, uniformly, and randomly situated within a radius of on
|
What is the expected distance to the nearest molecule?
Consider $d$ dimensions. The distribution to the nearest neighbor of any point can be approximated by supposing $N$ neighbors are independently, uniformly, and randomly situated within a radius of one unit from that point (where the distance unit and $N$ are chosen to reproduce the molecular density; preferably $N$ is large).
The chance that one given neighbor is further than a distance $r$ (for $0\le r \le 1$) is the relative volume of the spherical shell between the balls of radii $r$ and $1,$ equal to
$$S_{d}(r) = 1 - r^d.$$
Since the neighbor positions are independent, the chance that all are further than distance $r$ is
$$S_{N;d}(r) = (1-r^d)^N.$$
This (the survival function) determines the distribution of the distance $R$ to the nearest neighbor. Its expectation is the integral of the survival function,
$$E[R] = \int_0^1 S_{N;d}(r)\,\mathrm{d}r = \int_0^1 (1-r^d)^N\,\mathrm{d}r = B(N+1,1/d)/d$$
where $B$ is the Beta function
$$B(a,b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}.$$
For instance, here is a histogram of 50,000 simulated values of $R$ with $N=500-1$ neighbors.
On it I have superimposed the graph of the density function $-d/dr\, S_{499;3}(r)$ in red to show the agreement and I have plotted a vertical line to show $E[R].$
|
What is the expected distance to the nearest molecule?
Consider $d$ dimensions. The distribution to the nearest neighbor of any point can be approximated by supposing $N$ neighbors are independently, uniformly, and randomly situated within a radius of on
|
46,431
|
Why this OLS fitting will converge to (0,-0.5)?
|
This is a law of large numbers in action.
Let $\rho$ be the parameter (the lag-1 correlation) and let $\varepsilon_i$ be a sequence of iid standard Normal variables, so that for $i=1, 2, \ldots,$ the model is
$$y_{i+1} = \rho y_i + \varepsilon_{i+1}$$
and $y_0=0.$ Therefore the first differences are
$$x_{i+1} = y_{i+1} - y_i = (\rho-1)y_i + \varepsilon_{i+1}.$$
Because $y_0=0,$ inductively the $x_i$ and $y_i$ all have expectations of zero.
Because $\rho \lt 1,$ notice that $x$ and $y$ move in opposite directions: they must be negatively correlated. You might (intuitively) think that the amount of correlation depends on $\rho.$ However, it also depends on the variances of the $x_i$ and $y_i.$ We need to examine these.
As in the question, stop the series at $n$ and regress $y$ against $x.$ The slope estimate is
$$\hat \beta = \frac{\sum_i (y_i-\bar y)(x_i - \bar x)}{\sum_i (x_i-\bar x)} \approx \frac{\sum_i y_i x_i}{\sum_i x_i^2}$$
because, for large $n,$ the means $\bar y$ and $\bar x$ will be close to their expectations, which are zero.
Again because $n$ is large, the empirical values in the fraction can be approximated by their expectations (a law of large numbers),
$$\frac{\sum_i y_i x_i}{\sum_i x_i^2} \approx \frac{E\left[\sum_i y_i x_i\right]}{E\left[\sum_i x_i^2\right]}.$$
Find those expectations from the definition of the series $(y_i).$ I will begin with a useful auxiliary calculation:
$$\begin{aligned}
E\left[\sum_i y_i^2\right] &= \sum_i E\left[y_i^2\right] = \sum_i E\left[(\varepsilon_{i+1} + \rho y_i)^2\right]\\
&= \sum_i E\left[(\varepsilon_{i+1})^2\right] + 2\rho \sum_i E\left[\varepsilon_{i+1} y_i\right] + \rho^2 \sum_i E\left[ y_i^2\right]\\
&= n + 0 + \rho^2 E\left[\sum_i y_i^2\right]
\end{aligned}$$
which is justified because the $\varepsilon_i$ have zero expectation, unit variance, and are independent of each other (whence, in particular, $\varepsilon_{i+1}$ is independent of $y_i$). Solving this equation gives
$$E\left[\sum_i y_i^2\right] = \frac{n}{1-\rho^2}.$$
With this (standard) result in hand we obtain, using similar calculations,
$$E\left[\sum_i y_i x_i\right] = -\frac{n}{1+\rho}$$
and
$$E\left[\sum_i x_i^2\right] = \frac{2n}{1+\rho},$$
whence
$$\hat \beta \approx \left(-\frac{n}{1+\rho}\right)\,/\,\left(\frac{2n}{1+\rho}\right) = -\frac{1}{2}.$$
(You can carry out this analysis rigorously using the Delta method, which applies because the denominator of $\hat\beta,$ $\sum_i x_i^2,$ will stay away from zero.)
Finally, because the linear regression passes through the point of averages and the means of the $x_i$ and $y_i$ are each close to $0,$ the constant term will be close to $0,$ too.
|
Why this OLS fitting will converge to (0,-0.5)?
|
This is a law of large numbers in action.
Let $\rho$ be the parameter (the lag-1 correlation) and let $\varepsilon_i$ be a sequence of iid standard Normal variables, so that for $i=1, 2, \ldots,$ the
|
Why this OLS fitting will converge to (0,-0.5)?
This is a law of large numbers in action.
Let $\rho$ be the parameter (the lag-1 correlation) and let $\varepsilon_i$ be a sequence of iid standard Normal variables, so that for $i=1, 2, \ldots,$ the model is
$$y_{i+1} = \rho y_i + \varepsilon_{i+1}$$
and $y_0=0.$ Therefore the first differences are
$$x_{i+1} = y_{i+1} - y_i = (\rho-1)y_i + \varepsilon_{i+1}.$$
Because $y_0=0,$ inductively the $x_i$ and $y_i$ all have expectations of zero.
Because $\rho \lt 1,$ notice that $x$ and $y$ move in opposite directions: they must be negatively correlated. You might (intuitively) think that the amount of correlation depends on $\rho.$ However, it also depends on the variances of the $x_i$ and $y_i.$ We need to examine these.
As in the question, stop the series at $n$ and regress $y$ against $x.$ The slope estimate is
$$\hat \beta = \frac{\sum_i (y_i-\bar y)(x_i - \bar x)}{\sum_i (x_i-\bar x)} \approx \frac{\sum_i y_i x_i}{\sum_i x_i^2}$$
because, for large $n,$ the means $\bar y$ and $\bar x$ will be close to their expectations, which are zero.
Again because $n$ is large, the empirical values in the fraction can be approximated by their expectations (a law of large numbers),
$$\frac{\sum_i y_i x_i}{\sum_i x_i^2} \approx \frac{E\left[\sum_i y_i x_i\right]}{E\left[\sum_i x_i^2\right]}.$$
Find those expectations from the definition of the series $(y_i).$ I will begin with a useful auxiliary calculation:
$$\begin{aligned}
E\left[\sum_i y_i^2\right] &= \sum_i E\left[y_i^2\right] = \sum_i E\left[(\varepsilon_{i+1} + \rho y_i)^2\right]\\
&= \sum_i E\left[(\varepsilon_{i+1})^2\right] + 2\rho \sum_i E\left[\varepsilon_{i+1} y_i\right] + \rho^2 \sum_i E\left[ y_i^2\right]\\
&= n + 0 + \rho^2 E\left[\sum_i y_i^2\right]
\end{aligned}$$
which is justified because the $\varepsilon_i$ have zero expectation, unit variance, and are independent of each other (whence, in particular, $\varepsilon_{i+1}$ is independent of $y_i$). Solving this equation gives
$$E\left[\sum_i y_i^2\right] = \frac{n}{1-\rho^2}.$$
With this (standard) result in hand we obtain, using similar calculations,
$$E\left[\sum_i y_i x_i\right] = -\frac{n}{1+\rho}$$
and
$$E\left[\sum_i x_i^2\right] = \frac{2n}{1+\rho},$$
whence
$$\hat \beta \approx \left(-\frac{n}{1+\rho}\right)\,/\,\left(\frac{2n}{1+\rho}\right) = -\frac{1}{2}.$$
(You can carry out this analysis rigorously using the Delta method, which applies because the denominator of $\hat\beta,$ $\sum_i x_i^2,$ will stay away from zero.)
Finally, because the linear regression passes through the point of averages and the means of the $x_i$ and $y_i$ are each close to $0,$ the constant term will be close to $0,$ too.
|
Why this OLS fitting will converge to (0,-0.5)?
This is a law of large numbers in action.
Let $\rho$ be the parameter (the lag-1 correlation) and let $\varepsilon_i$ be a sequence of iid standard Normal variables, so that for $i=1, 2, \ldots,$ the
|
46,432
|
Trick to remember when to reject null (p-values vs alpha)
|
This surely will not top the list of possible "cool undergraduate-level tips", but simply recalling the definition of a p-value might be helpful (quoted from Wikipedia):
The probability of obtaining test results at least as extreme as the
results actually observed, under the assumption that the null
hypothesis is correct.
So the smaller the probability, the smaller significance level at which we are willing to reject.
|
Trick to remember when to reject null (p-values vs alpha)
|
This surely will not top the list of possible "cool undergraduate-level tips", but simply recalling the definition of a p-value might be helpful (quoted from Wikipedia):
The probability of obtaining
|
Trick to remember when to reject null (p-values vs alpha)
This surely will not top the list of possible "cool undergraduate-level tips", but simply recalling the definition of a p-value might be helpful (quoted from Wikipedia):
The probability of obtaining test results at least as extreme as the
results actually observed, under the assumption that the null
hypothesis is correct.
So the smaller the probability, the smaller significance level at which we are willing to reject.
|
Trick to remember when to reject null (p-values vs alpha)
This surely will not top the list of possible "cool undergraduate-level tips", but simply recalling the definition of a p-value might be helpful (quoted from Wikipedia):
The probability of obtaining
|
46,433
|
Trick to remember when to reject null (p-values vs alpha)
|
The standard mnemonic for remembering how to make a conclusion in a hypothesis test is:
If p is low, the null must go!
As to why this is the case, the best explanation of a classical hypothesis test is that it is the inductive anologue of a proof by contradiction. In a proof by contradiction we begin with a null hypothesis, show that this leads logically to a contradiction, and therefore reject the initial premise that the null is true. In a classical hypothesis test, we begin with a null hypothesis, show that this leads to a highly implausible result in favour of the alternative (so not quite a deductive contradiction, but close), and therefore reject the initial premise that the null is true. The p-value in this test is the probability of a result at least as conducive to the alternative hypothesis, assuming the null is true (see formal explanation here). If this is low then it means that something very implausible happened (under the assumption that the null is true) which gives the "contradiction" in the "inductive proof by contradiction".
|
Trick to remember when to reject null (p-values vs alpha)
|
The standard mnemonic for remembering how to make a conclusion in a hypothesis test is:
If p is low, the null must go!
As to why this is the case, the best explanation of a classical hypothesis test
|
Trick to remember when to reject null (p-values vs alpha)
The standard mnemonic for remembering how to make a conclusion in a hypothesis test is:
If p is low, the null must go!
As to why this is the case, the best explanation of a classical hypothesis test is that it is the inductive anologue of a proof by contradiction. In a proof by contradiction we begin with a null hypothesis, show that this leads logically to a contradiction, and therefore reject the initial premise that the null is true. In a classical hypothesis test, we begin with a null hypothesis, show that this leads to a highly implausible result in favour of the alternative (so not quite a deductive contradiction, but close), and therefore reject the initial premise that the null is true. The p-value in this test is the probability of a result at least as conducive to the alternative hypothesis, assuming the null is true (see formal explanation here). If this is low then it means that something very implausible happened (under the assumption that the null is true) which gives the "contradiction" in the "inductive proof by contradiction".
|
Trick to remember when to reject null (p-values vs alpha)
The standard mnemonic for remembering how to make a conclusion in a hypothesis test is:
If p is low, the null must go!
As to why this is the case, the best explanation of a classical hypothesis test
|
46,434
|
Trick to remember when to reject null (p-values vs alpha)
|
Fisher is said to have given the interpretion of $p$-values as a "measure of surprise", given you believe in the null hypothesis. This may actually be confusing, since low $p$-value then indicates strong surprise.
Instead, we can introduce $p$-values as "measure of
compatibility with the null". (suggested by Christian Hennig)
Then: low p = low compatibility
In Cox And Hinkley's 1974 text, they use the p-value "as a measure of the consistency of the data with the null hypothesis" (p.66). Earlier, Cox (1958) described a significance test as "concerned with the extent to which the data are consistent with the null hypothesis".(p. 362)
|
Trick to remember when to reject null (p-values vs alpha)
|
Fisher is said to have given the interpretion of $p$-values as a "measure of surprise", given you believe in the null hypothesis. This may actually be confusing, since low $p$-value then indicates str
|
Trick to remember when to reject null (p-values vs alpha)
Fisher is said to have given the interpretion of $p$-values as a "measure of surprise", given you believe in the null hypothesis. This may actually be confusing, since low $p$-value then indicates strong surprise.
Instead, we can introduce $p$-values as "measure of
compatibility with the null". (suggested by Christian Hennig)
Then: low p = low compatibility
In Cox And Hinkley's 1974 text, they use the p-value "as a measure of the consistency of the data with the null hypothesis" (p.66). Earlier, Cox (1958) described a significance test as "concerned with the extent to which the data are consistent with the null hypothesis".(p. 362)
|
Trick to remember when to reject null (p-values vs alpha)
Fisher is said to have given the interpretion of $p$-values as a "measure of surprise", given you believe in the null hypothesis. This may actually be confusing, since low $p$-value then indicates str
|
46,435
|
Trick to remember when to reject null (p-values vs alpha)
|
I've found that some of my students are helped by thinking of the p-value as a percentile. They are familiar with the concepts of being in the top 10% of a class by GPAs, or "among the 1%" in terms of wealth.
So for your example, a p-value of 0.04 means "Our observed value of the test statistic $T$ was among the top 4% possible values of $T$ under $H_0$ that are least like $H_0$ and most like $H_A$."
In other words, "Our observed test statistic was among the top 5% most un-$H_0$-like values, but not among the top 1%."
|
Trick to remember when to reject null (p-values vs alpha)
|
I've found that some of my students are helped by thinking of the p-value as a percentile. They are familiar with the concepts of being in the top 10% of a class by GPAs, or "among the 1%" in terms of
|
Trick to remember when to reject null (p-values vs alpha)
I've found that some of my students are helped by thinking of the p-value as a percentile. They are familiar with the concepts of being in the top 10% of a class by GPAs, or "among the 1%" in terms of wealth.
So for your example, a p-value of 0.04 means "Our observed value of the test statistic $T$ was among the top 4% possible values of $T$ under $H_0$ that are least like $H_0$ and most like $H_A$."
In other words, "Our observed test statistic was among the top 5% most un-$H_0$-like values, but not among the top 1%."
|
Trick to remember when to reject null (p-values vs alpha)
I've found that some of my students are helped by thinking of the p-value as a percentile. They are familiar with the concepts of being in the top 10% of a class by GPAs, or "among the 1%" in terms of
|
46,436
|
SGD for Gaussian Process estimation
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
This conference paper from NeurIPs 2020 may contain what you are looking for - it contains some theoretical guarantees on using mini-batch stochastic gradient descent in context of Gaussian processes.
|
SGD for Gaussian Process estimation
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
SGD for Gaussian Process estimation
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
This conference paper from NeurIPs 2020 may contain what you are looking for - it contains some theoretical guarantees on using mini-batch stochastic gradient descent in context of Gaussian processes.
|
SGD for Gaussian Process estimation
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
46,437
|
$\text{Var}(y)$ in linear regression
|
Since $y_i \sim \mathcal N(\beta_0+\beta_1x_i,\sigma^2 )$, the variance of each sample $y_i$ is $\sigma^2$. This is a conditional variance, $\operatorname{Var}(y|x)$.
The sample variance of all samples $y$ is a marginal variance. It's given by the common formulas
$$\operatorname{Var}(y)
=\mathbb E\left[y^2\right]- E\left[y\right]^2
=\mathbb E\left[(y-\mathbb E\left[y\right])^2\right]
$$
If $y = \beta_0+\beta_1x+\epsilon$, we can use variance identities and the fact that $\operatorname{Cov}(x,\epsilon)=0$ to show that:
$$\operatorname{Var}(y)=\operatorname{Var}(\beta_0+\beta_1x+\epsilon)\\
=\operatorname{Var}(\beta_1x)+\color{blue}{\operatorname{Var}(\epsilon)}+2\operatorname{Cov}(\beta_1x,\epsilon)\\
=\beta_1^2\operatorname{Var}(x)+\color{blue}{\sigma^2}+2\beta_1\color{red}{\operatorname{Cov}(x,\epsilon)}\\
=\beta_1^2\operatorname{Var}(x)+\sigma^2
$$
Thus, both are right, but they refer to different things.
|
$\text{Var}(y)$ in linear regression
|
Since $y_i \sim \mathcal N(\beta_0+\beta_1x_i,\sigma^2 )$, the variance of each sample $y_i$ is $\sigma^2$. This is a conditional variance, $\operatorname{Var}(y|x)$.
The sample variance of all sample
|
$\text{Var}(y)$ in linear regression
Since $y_i \sim \mathcal N(\beta_0+\beta_1x_i,\sigma^2 )$, the variance of each sample $y_i$ is $\sigma^2$. This is a conditional variance, $\operatorname{Var}(y|x)$.
The sample variance of all samples $y$ is a marginal variance. It's given by the common formulas
$$\operatorname{Var}(y)
=\mathbb E\left[y^2\right]- E\left[y\right]^2
=\mathbb E\left[(y-\mathbb E\left[y\right])^2\right]
$$
If $y = \beta_0+\beta_1x+\epsilon$, we can use variance identities and the fact that $\operatorname{Cov}(x,\epsilon)=0$ to show that:
$$\operatorname{Var}(y)=\operatorname{Var}(\beta_0+\beta_1x+\epsilon)\\
=\operatorname{Var}(\beta_1x)+\color{blue}{\operatorname{Var}(\epsilon)}+2\operatorname{Cov}(\beta_1x,\epsilon)\\
=\beta_1^2\operatorname{Var}(x)+\color{blue}{\sigma^2}+2\beta_1\color{red}{\operatorname{Cov}(x,\epsilon)}\\
=\beta_1^2\operatorname{Var}(x)+\sigma^2
$$
Thus, both are right, but they refer to different things.
|
$\text{Var}(y)$ in linear regression
Since $y_i \sim \mathcal N(\beta_0+\beta_1x_i,\sigma^2 )$, the variance of each sample $y_i$ is $\sigma^2$. This is a conditional variance, $\operatorname{Var}(y|x)$.
The sample variance of all sample
|
46,438
|
Regression with flexible functional form
|
This sounds like a great job for GAMs via the mgcv package. Use a penalized smoothing spline to estimate $g$ and add an additive effect of $X$. The model would look like gam(y ~ x + s(z).
library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.8-31. For overview type 'help("mgcv-package")'.
z = rnorm(1000)
x = rnorm(1000)
y = 2 + 0.25*x + sin(pi*z) + rnorm(1000, 0, 0.3)
d = data.frame(x, y, z)
model = gam(y ~ x + s(z), data = d)
summary(model)
#>
#> Family: gaussian
#> Link function: identity
#>
#> Formula:
#> y ~ x + s(z)
#>
#> Parametric coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 1.968566 0.009514 206.91 <2e-16 ***
#> x 0.262245 0.009888 26.52 <2e-16 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Approximate significance of smooth terms:
#> edf Ref.df F p-value
#> s(z) 8.977 9 625.1 <2e-16 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> R-sq.(adj) = 0.865 Deviance explained = 86.6%
#> GCV = 0.091407 Scale est. = 0.090404 n = 1000
Created on 2020-10-20 by the reprex package (v0.3.0)
|
Regression with flexible functional form
|
This sounds like a great job for GAMs via the mgcv package. Use a penalized smoothing spline to estimate $g$ and add an additive effect of $X$. The model would look like gam(y ~ x + s(z).
library(mg
|
Regression with flexible functional form
This sounds like a great job for GAMs via the mgcv package. Use a penalized smoothing spline to estimate $g$ and add an additive effect of $X$. The model would look like gam(y ~ x + s(z).
library(mgcv)
#> Loading required package: nlme
#> This is mgcv 1.8-31. For overview type 'help("mgcv-package")'.
z = rnorm(1000)
x = rnorm(1000)
y = 2 + 0.25*x + sin(pi*z) + rnorm(1000, 0, 0.3)
d = data.frame(x, y, z)
model = gam(y ~ x + s(z), data = d)
summary(model)
#>
#> Family: gaussian
#> Link function: identity
#>
#> Formula:
#> y ~ x + s(z)
#>
#> Parametric coefficients:
#> Estimate Std. Error t value Pr(>|t|)
#> (Intercept) 1.968566 0.009514 206.91 <2e-16 ***
#> x 0.262245 0.009888 26.52 <2e-16 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Approximate significance of smooth terms:
#> edf Ref.df F p-value
#> s(z) 8.977 9 625.1 <2e-16 ***
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> R-sq.(adj) = 0.865 Deviance explained = 86.6%
#> GCV = 0.091407 Scale est. = 0.090404 n = 1000
Created on 2020-10-20 by the reprex package (v0.3.0)
|
Regression with flexible functional form
This sounds like a great job for GAMs via the mgcv package. Use a penalized smoothing spline to estimate $g$ and add an additive effect of $X$. The model would look like gam(y ~ x + s(z).
library(mg
|
46,439
|
Regression with flexible functional form
|
This model is a partially linear regression models, and in your case, $g(Z)$ is a nuisance parameter. See page 62 of this link for a primer on the subject. Of especial note in application is Robinson's Transformation (Section 7.7 on page 62 of the linked file).
Inference is particularly tricky in these settings, since it's hard to say anything about the asymptotics of $g(Z)$ in a general sense, so you typically need to assume it lies in some space. A recent very general approach to inference was proposed by Chernozhukov et al. (2017) if of interest.
|
Regression with flexible functional form
|
This model is a partially linear regression models, and in your case, $g(Z)$ is a nuisance parameter. See page 62 of this link for a primer on the subject. Of especial note in application is Robinson'
|
Regression with flexible functional form
This model is a partially linear regression models, and in your case, $g(Z)$ is a nuisance parameter. See page 62 of this link for a primer on the subject. Of especial note in application is Robinson's Transformation (Section 7.7 on page 62 of the linked file).
Inference is particularly tricky in these settings, since it's hard to say anything about the asymptotics of $g(Z)$ in a general sense, so you typically need to assume it lies in some space. A recent very general approach to inference was proposed by Chernozhukov et al. (2017) if of interest.
|
Regression with flexible functional form
This model is a partially linear regression models, and in your case, $g(Z)$ is a nuisance parameter. See page 62 of this link for a primer on the subject. Of especial note in application is Robinson'
|
46,440
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
|
The overall and predictor-specific worm plots share the feature that "different shapes indicate different inadequacies in the model", as explained in the article Analysis of longitudinal multilevel experiments using GAMLSSs by Gustavo Thomas et al: https://arxiv.org/pdf/1810.03085.pdf.
Section 12.4 of the book Flexible Regression and Smoothing: Using GAMLSS in R. by Rigby et al. is worth a read, as it provides a comprehensive tour of how to interpret worm plots. The section concludes with these statements: "In general, it may not always be possible to build a model without areas of misfits." and "In any case, extra care is needed when a model with many areas of misfits is used to support conclusions.". However, calibration is mentioned as one solution to be used in order to minimize misfits.
How you correct the model misfit depends on the nature of the problems detected in the worm plots. If those problems suggest the need to consider nonlinear effects for one of your continuous predictor to improve model fit, than you would need to model the effect of that predictor nonlinearly rather than linearly. (Other types of corrections may involve specifying a different type of distribution for the response variable given the predictors and random effects in your model, omitting or including predictors from various parts of the model, transforming predictors, etc.)
Note that, according to the help file for the cs() function:
The function scs() differs from the function cs() in that allows cross validation of the smoothing parameters unlike the cs() which fixes the effective degrees of freedom, df. Note that the recommended smoothing function is now the function pb() which allows the estimation of the smoothing parameters using a local maximum likelihood. The function pb() is based on the penalised beta splines (P-splines) of Eilers and Marx (1996).
So you might want to consider using pb() in your model rather than cs().
Addendum:
Here is some R code for generating data for a model where a quadratic fit would work better than a linear or even a smooth fit. It will help you build some intuition for what you can expect worm plots to look like. The data were generated according to https://www.theanalysisfactor.com/r-tutorial-4/.
14, 15, 16, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30),
Outcome = c(126.6, 101.8, 71.6, 101.6, 68.1, 62.9, 45.5, 41.9,
46.3, 34.1, 38.2, 41.7, 24.7, 41.5, 36.6, 19.6,
22.8, 29.6, 23.5, 15.3, 13.4, 26.8, 9.8, 18.8, 25.9, 19.3)),
.Names = c("Time", "Outcome"),
row.names = c(1L, 2L, 3L, 5L, 7L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 19L, 20L, 21L, 22L, 23L, 25L, 26L, 27L, 28L, 29L, 30L, 31L),
class = "data.frame")
Data
The header of the data looks like this:
Time Outcome
1 0 126.6
2 1 101.8
3 2 71.6
5 4 101.6
7 6 68.1
9 8 62.9```
The plot of the Outcome variable versus the predictor variable Time can be obtained with:
```library(ggplot2)
theme_set(theme_bw())
ggplot(Data, aes(x = Time, y = Outcome)) +
geom_point(size=3, colour="dodgerblue")
Now, fit the 3 possible models for these data within the gamlss framework:
linear.model <- gamlss(Outcome ~ Time, data = Data, family=NO)
quadratic.model <- gamlss(Outcome ~ Time + I(Time^2), data = Data, family=NO)
smooth.model <- gamlss(Outcome ~ pb(Time), data = Data, family=NO)
summary(linear.model)
summary(quadratic.model)
summary(smooth.model)
Compare the (generalized) AIC values of the 3 fitted models:
GAIC(linear.model, quadratic.model, smooth.model)
The quadratic model comes as the "winner" since it has the smallest AIC value:
df AIC
quadratic.model 4.000000 197.0357
smooth.model 5.251898 197.8349
linear.model 3.000000 219.0893
Now construct the worm plots for the Time predictor:
wp(linear.model, xvar=Time)
wp(quadratic.model, xvar=Time)
wp(smooth.model, xvar=Time)
The worm plot for the linear model fit shows some misfit problems:
The worm plots for the quadratic and smooth model fits look a bit better than the worm plot for the linear model fit.
We can also plot the model residuals directly against the Time predictor:
Data$linear.model.residuals <- residuals(linear.model)
Data$quadratic.model.residuals <- residuals(quadratic.model)
Data$smooth.model.residuals <- residuals(smooth.model)
plot1 <- ggplot(Data, aes(x = Time, y = linear.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Linear Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3))
plot2 <- ggplot(Data, aes(x = Time, y = quadratic.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Quadratic Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3))
plot3 <- ggplot(Data, aes(x = Time, y = smooth.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Smooth Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3))
library(cowplot)
plot_grid(plot1, plot2, plot3, ncol=3)
These last plots make it a bit easier to discern that there is a quadratic pattern present in the residuals for the linear model, which needs to be accounted for in the model.
If you wanted to, you could pull apart the plot of residuals versus Time for the linear model and examine the portions of the plot corresponding to the division of Time in intervals used in the corresponding worm plot:
w.linear <- wp(linear.model, xvar=Time, main="Given: Time")
w.linear
The cutpoints for the division of the range of observed values of Time is reported in the $classes portion of the R output for w.linear:
> w.linear
$classes
[,1] [,2]
[1,] -0.5 8.5
[2,] 8.5 15.5
[3,] 15.5 24.5
[4,] 24.5 30.5
$coef
[,1] [,2] [,3] [,4]
[1,] 0.6061177 0.79644473 0.26190049 -0.29589027
[2,] -1.0467772 -0.54040972 0.08504976 -0.05550396
[3,] -0.1400464 -0.64524770 -0.15331613 0.02095304
[4,] 0.7161490 -0.03070935 -0.08930395 -0.19956330
These cutpoints are -0.5, 8.5, 15.5, 24.5 and 30.5. We can plot the residuals versus Time and draw vertical lines for only the "middle" cutpoints:
plot11 <- ggplot(Data, aes(x = Time, y = linear.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Linear Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3)) +
geom_vline(xintercept = w.linear$classes[1,2],
colour="blue", linetype=3, size=1.5) +
geom_vline(xintercept = w.linear$classes[2,2],
colour="blue", linetype=3, size=1.5) +
geom_vline(xintercept = w.linear$classes[3,2],
colour="blue", linetype=3, size=1.5)
plot11
This allows us to zoom in on specific time intervals and determine how the model fit breaks down in those intervals:
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
|
The overall and predictor-specific worm plots share the feature that "different shapes indicate different inadequacies in the model", as explained in the article Analysis of longitudinal multilevel ex
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
The overall and predictor-specific worm plots share the feature that "different shapes indicate different inadequacies in the model", as explained in the article Analysis of longitudinal multilevel experiments using GAMLSSs by Gustavo Thomas et al: https://arxiv.org/pdf/1810.03085.pdf.
Section 12.4 of the book Flexible Regression and Smoothing: Using GAMLSS in R. by Rigby et al. is worth a read, as it provides a comprehensive tour of how to interpret worm plots. The section concludes with these statements: "In general, it may not always be possible to build a model without areas of misfits." and "In any case, extra care is needed when a model with many areas of misfits is used to support conclusions.". However, calibration is mentioned as one solution to be used in order to minimize misfits.
How you correct the model misfit depends on the nature of the problems detected in the worm plots. If those problems suggest the need to consider nonlinear effects for one of your continuous predictor to improve model fit, than you would need to model the effect of that predictor nonlinearly rather than linearly. (Other types of corrections may involve specifying a different type of distribution for the response variable given the predictors and random effects in your model, omitting or including predictors from various parts of the model, transforming predictors, etc.)
Note that, according to the help file for the cs() function:
The function scs() differs from the function cs() in that allows cross validation of the smoothing parameters unlike the cs() which fixes the effective degrees of freedom, df. Note that the recommended smoothing function is now the function pb() which allows the estimation of the smoothing parameters using a local maximum likelihood. The function pb() is based on the penalised beta splines (P-splines) of Eilers and Marx (1996).
So you might want to consider using pb() in your model rather than cs().
Addendum:
Here is some R code for generating data for a model where a quadratic fit would work better than a linear or even a smooth fit. It will help you build some intuition for what you can expect worm plots to look like. The data were generated according to https://www.theanalysisfactor.com/r-tutorial-4/.
14, 15, 16, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30),
Outcome = c(126.6, 101.8, 71.6, 101.6, 68.1, 62.9, 45.5, 41.9,
46.3, 34.1, 38.2, 41.7, 24.7, 41.5, 36.6, 19.6,
22.8, 29.6, 23.5, 15.3, 13.4, 26.8, 9.8, 18.8, 25.9, 19.3)),
.Names = c("Time", "Outcome"),
row.names = c(1L, 2L, 3L, 5L, 7L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 19L, 20L, 21L, 22L, 23L, 25L, 26L, 27L, 28L, 29L, 30L, 31L),
class = "data.frame")
Data
The header of the data looks like this:
Time Outcome
1 0 126.6
2 1 101.8
3 2 71.6
5 4 101.6
7 6 68.1
9 8 62.9```
The plot of the Outcome variable versus the predictor variable Time can be obtained with:
```library(ggplot2)
theme_set(theme_bw())
ggplot(Data, aes(x = Time, y = Outcome)) +
geom_point(size=3, colour="dodgerblue")
Now, fit the 3 possible models for these data within the gamlss framework:
linear.model <- gamlss(Outcome ~ Time, data = Data, family=NO)
quadratic.model <- gamlss(Outcome ~ Time + I(Time^2), data = Data, family=NO)
smooth.model <- gamlss(Outcome ~ pb(Time), data = Data, family=NO)
summary(linear.model)
summary(quadratic.model)
summary(smooth.model)
Compare the (generalized) AIC values of the 3 fitted models:
GAIC(linear.model, quadratic.model, smooth.model)
The quadratic model comes as the "winner" since it has the smallest AIC value:
df AIC
quadratic.model 4.000000 197.0357
smooth.model 5.251898 197.8349
linear.model 3.000000 219.0893
Now construct the worm plots for the Time predictor:
wp(linear.model, xvar=Time)
wp(quadratic.model, xvar=Time)
wp(smooth.model, xvar=Time)
The worm plot for the linear model fit shows some misfit problems:
The worm plots for the quadratic and smooth model fits look a bit better than the worm plot for the linear model fit.
We can also plot the model residuals directly against the Time predictor:
Data$linear.model.residuals <- residuals(linear.model)
Data$quadratic.model.residuals <- residuals(quadratic.model)
Data$smooth.model.residuals <- residuals(smooth.model)
plot1 <- ggplot(Data, aes(x = Time, y = linear.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Linear Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3))
plot2 <- ggplot(Data, aes(x = Time, y = quadratic.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Quadratic Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3))
plot3 <- ggplot(Data, aes(x = Time, y = smooth.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Smooth Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3))
library(cowplot)
plot_grid(plot1, plot2, plot3, ncol=3)
These last plots make it a bit easier to discern that there is a quadratic pattern present in the residuals for the linear model, which needs to be accounted for in the model.
If you wanted to, you could pull apart the plot of residuals versus Time for the linear model and examine the portions of the plot corresponding to the division of Time in intervals used in the corresponding worm plot:
w.linear <- wp(linear.model, xvar=Time, main="Given: Time")
w.linear
The cutpoints for the division of the range of observed values of Time is reported in the $classes portion of the R output for w.linear:
> w.linear
$classes
[,1] [,2]
[1,] -0.5 8.5
[2,] 8.5 15.5
[3,] 15.5 24.5
[4,] 24.5 30.5
$coef
[,1] [,2] [,3] [,4]
[1,] 0.6061177 0.79644473 0.26190049 -0.29589027
[2,] -1.0467772 -0.54040972 0.08504976 -0.05550396
[3,] -0.1400464 -0.64524770 -0.15331613 0.02095304
[4,] 0.7161490 -0.03070935 -0.08930395 -0.19956330
These cutpoints are -0.5, 8.5, 15.5, 24.5 and 30.5. We can plot the residuals versus Time and draw vertical lines for only the "middle" cutpoints:
plot11 <- ggplot(Data, aes(x = Time, y = linear.model.residuals)) +
geom_point(size=3, colour="darkgrey") +
geom_hline(yintercept = 0, linetype=2, colour="red") +
ggtitle("Linear Model Residuals vs. Time") +
coord_cartesian(ylim=c(-3,3)) +
geom_vline(xintercept = w.linear$classes[1,2],
colour="blue", linetype=3, size=1.5) +
geom_vline(xintercept = w.linear$classes[2,2],
colour="blue", linetype=3, size=1.5) +
geom_vline(xintercept = w.linear$classes[3,2],
colour="blue", linetype=3, size=1.5)
plot11
This allows us to zoom in on specific time intervals and determine how the model fit breaks down in those intervals:
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
The overall and predictor-specific worm plots share the feature that "different shapes indicate different inadequacies in the model", as explained in the article Analysis of longitudinal multilevel ex
|
46,441
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
|
A worm plot is basically a qq plot, so what you are doing is trying to find the best functional form of the covariates that yields a normal quantile Residual. This indicates a better fit.
You checked the information criterion, and you could also do a likelihood ratio test. But if the model has a better fit, there isn't anything wrong with cubic splines.
I would also advise you to check the residuals diagnostic using the plot function on the fitted gamlss object. This will give you another view, complementary to the worm plot.
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
|
A worm plot is basically a qq plot, so what you are doing is trying to find the best functional form of the covariates that yields a normal quantile Residual. This indicates a better fit.
You checked
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
A worm plot is basically a qq plot, so what you are doing is trying to find the best functional form of the covariates that yields a normal quantile Residual. This indicates a better fit.
You checked the information criterion, and you could also do a likelihood ratio test. But if the model has a better fit, there isn't anything wrong with cubic splines.
I would also advise you to check the residuals diagnostic using the plot function on the fitted gamlss object. This will give you another view, complementary to the worm plot.
|
Is smoothing an appropriate solution to deal with model diagnostics in a GAMLSS?
A worm plot is basically a qq plot, so what you are doing is trying to find the best functional form of the covariates that yields a normal quantile Residual. This indicates a better fit.
You checked
|
46,442
|
Impossible to overfit when the data generating process is deterministic?
|
If the DGP is noiseless, it is not possible to encounter overfitting problem. That’s true. In fact you can see the overfitting also as the problem to fit the noise (irreducible error) and not only the signal. For example in regression context you can improve the fit, at most in $R^2$ term the perfect fit can achieved, regardless the noise. However the bias problem remain.
To me this sounds too good to be true. Perhaps the caveat is that the
models here use the same set of regressors as the DGP, i.e. all the
relevant variables are being considered and no irrelevant variables
are included. This is unlikely to hold in practice. If the sets of
regressors in the models vs. the DGP differ, there might be different
story.
In regression case the problem is precisely this one.
More in general you can also misspecify the functional form. Flexibility is not a free lunch here even if to discover the bias is hard in practice. In fact only if you know the true functional form and the correct/true set of dependent variables your work is perfect.
EDIT: Giving some definitions is always a good idea. What is overfitting? From the cited book or from Wikipedia also (https://en.wikipedia.org/wiki/Overfitting) is easy to verify that overfitting appear when in sample performance of estimated model in notably worse than out of sample counterpart. However, this is more a consequence of overfitting than its definition. It represents the starting point for some rule like Optimism of the Training Error Rate (page 228 of the book above). I do not give you a formal definition of overfitting here, however this deals with the fact that a model encounters overfitting when it fits not only the structure/signal but also the noise. Note that structure/signal and noise/error are referred on the "true model" (=DGP). From this we can understand why the common rules work.
If the true model is noiseless
$y=f(X_1)$ where $X_1$ is the correct set of independent variables
but we estimate
$\hat{y}=\hat{g}(X_2)$ where $X_2$ is a wrong set of independent variables and/or $g$ is an incorrect functional form
regardless the fact that in-sample error of the estimated model is zero or not, is well possible that his out of sample error is bigger. Therefore, following the standard rule/practice it seems like we've encountered overfitting, while the problem is not overfitting but bias.
Moreover, if the estimated model is well specified and the true model is noiseless the prediction error is zero. Therefore for any misspecified model, it is impossible to overfit (the well specified model is unbeatable even in sample). Moreover yet, if we deal with noiseless true model, bias-variance tradeoff disappear and the bias become the only problem even in prediction.
|
Impossible to overfit when the data generating process is deterministic?
|
If the DGP is noiseless, it is not possible to encounter overfitting problem. That’s true. In fact you can see the overfitting also as the problem to fit the noise (irreducible error) and not only the
|
Impossible to overfit when the data generating process is deterministic?
If the DGP is noiseless, it is not possible to encounter overfitting problem. That’s true. In fact you can see the overfitting also as the problem to fit the noise (irreducible error) and not only the signal. For example in regression context you can improve the fit, at most in $R^2$ term the perfect fit can achieved, regardless the noise. However the bias problem remain.
To me this sounds too good to be true. Perhaps the caveat is that the
models here use the same set of regressors as the DGP, i.e. all the
relevant variables are being considered and no irrelevant variables
are included. This is unlikely to hold in practice. If the sets of
regressors in the models vs. the DGP differ, there might be different
story.
In regression case the problem is precisely this one.
More in general you can also misspecify the functional form. Flexibility is not a free lunch here even if to discover the bias is hard in practice. In fact only if you know the true functional form and the correct/true set of dependent variables your work is perfect.
EDIT: Giving some definitions is always a good idea. What is overfitting? From the cited book or from Wikipedia also (https://en.wikipedia.org/wiki/Overfitting) is easy to verify that overfitting appear when in sample performance of estimated model in notably worse than out of sample counterpart. However, this is more a consequence of overfitting than its definition. It represents the starting point for some rule like Optimism of the Training Error Rate (page 228 of the book above). I do not give you a formal definition of overfitting here, however this deals with the fact that a model encounters overfitting when it fits not only the structure/signal but also the noise. Note that structure/signal and noise/error are referred on the "true model" (=DGP). From this we can understand why the common rules work.
If the true model is noiseless
$y=f(X_1)$ where $X_1$ is the correct set of independent variables
but we estimate
$\hat{y}=\hat{g}(X_2)$ where $X_2$ is a wrong set of independent variables and/or $g$ is an incorrect functional form
regardless the fact that in-sample error of the estimated model is zero or not, is well possible that his out of sample error is bigger. Therefore, following the standard rule/practice it seems like we've encountered overfitting, while the problem is not overfitting but bias.
Moreover, if the estimated model is well specified and the true model is noiseless the prediction error is zero. Therefore for any misspecified model, it is impossible to overfit (the well specified model is unbeatable even in sample). Moreover yet, if we deal with noiseless true model, bias-variance tradeoff disappear and the bias become the only problem even in prediction.
|
Impossible to overfit when the data generating process is deterministic?
If the DGP is noiseless, it is not possible to encounter overfitting problem. That’s true. In fact you can see the overfitting also as the problem to fit the noise (irreducible error) and not only the
|
46,443
|
Impossible to overfit when the data generating process is deterministic?
|
I agree that overfitting is not possible when the data-generating process is deterministic. However, this is not "too good to be true" because generalization is still a problem.
Consider that we can take our model $\hat{f}$ to be a Lagrange polynomial (or any other "look-up-table"-like interpolator) of whatever order is necessary to get 100% accuracy on all data.
Each time you give me another $\{x,y\}$, I'll simply increase the complexity of my model by adding some new terms - i.e. raise the order of my polynomial $\hat{f}$.
With a deterministic $f$, one can perhaps call this "perfect fitting." But we know for generalization reasons that such a model probably won't work well outside the training data on which "over/underfitting" are defined.
However, sometimes when people say "overfitting" they also mean "won't generalize well" in which case nothing can save you. We can't guarantee perfect generalization performance in any situation unless we get to sample every possible $\{x,y\}$ (infinitely often in the stochastic case) which is really not much different than saying you already know $f$.
Edit
I feel like you know the above already, and that your confusion stems from this:
"If there is a range models to choose from, the highly flexible ones will have low bias and high variance and will tend to overfit. The inflexible ones will have high bias and low variance and will tend to underfit."
That concept makes sense when talking about performance on a specific set of data points. It doesn't hold when considering all possible data points ("generalization performance"). There is nothing about a "highly flexible" model that will definitively cause low bias for inputs it wasn't trained on.
So I took your definition of under/overfitting to mean "on the training data." (I mean, even the word "fit" implies that). If you meant "in generalization" then the fallacy in your reasoning is the above quoted text.
Also, from wikipedia on the Bias-Variance Trade-Off:
"It is an often made fallacy to assume that complex models must have high variance (and thus low bias); High variance models are 'complex' in some sense, but the reverse needs not be true."
I think the key is to understand that for generalization performance, low bias comes from model correctness, not complexity.
Unprincipled complexity only reduces "bias" if you're talking about training set performance. This is not the precisely defined bias $E(f - \hat{f})$ in the bias-variance decomposition, which involves an expectation taken over all possible inputs.
Thus, I think your underlying confusion was thinking that highly flexible models have low bias in the expected value (generalization) sense, while that is only true if the expected value is approximated by a sample mean over the training set (on which we define the word "fit").
A sort of corollary to this idea is that if you have a huge, encompassingly representative amount of training data, then a massively complex model (like those of modern deep learning) can lower bias on a sample mean error that closely approximates the actual mean. But it should be noted that most of the successful massive models aren't full of "unprincipled complexity" - they often take advantage of crucial structures inherent to the data (e.g. using convolution on images, etc). Moreover, understanding the surprising generalization ability of massive deep models is still a point of research to this day (and research on the many ways that generalization ability can silently fail too, e.g. adversarial inputs).
|
Impossible to overfit when the data generating process is deterministic?
|
I agree that overfitting is not possible when the data-generating process is deterministic. However, this is not "too good to be true" because generalization is still a problem.
Consider that we can t
|
Impossible to overfit when the data generating process is deterministic?
I agree that overfitting is not possible when the data-generating process is deterministic. However, this is not "too good to be true" because generalization is still a problem.
Consider that we can take our model $\hat{f}$ to be a Lagrange polynomial (or any other "look-up-table"-like interpolator) of whatever order is necessary to get 100% accuracy on all data.
Each time you give me another $\{x,y\}$, I'll simply increase the complexity of my model by adding some new terms - i.e. raise the order of my polynomial $\hat{f}$.
With a deterministic $f$, one can perhaps call this "perfect fitting." But we know for generalization reasons that such a model probably won't work well outside the training data on which "over/underfitting" are defined.
However, sometimes when people say "overfitting" they also mean "won't generalize well" in which case nothing can save you. We can't guarantee perfect generalization performance in any situation unless we get to sample every possible $\{x,y\}$ (infinitely often in the stochastic case) which is really not much different than saying you already know $f$.
Edit
I feel like you know the above already, and that your confusion stems from this:
"If there is a range models to choose from, the highly flexible ones will have low bias and high variance and will tend to overfit. The inflexible ones will have high bias and low variance and will tend to underfit."
That concept makes sense when talking about performance on a specific set of data points. It doesn't hold when considering all possible data points ("generalization performance"). There is nothing about a "highly flexible" model that will definitively cause low bias for inputs it wasn't trained on.
So I took your definition of under/overfitting to mean "on the training data." (I mean, even the word "fit" implies that). If you meant "in generalization" then the fallacy in your reasoning is the above quoted text.
Also, from wikipedia on the Bias-Variance Trade-Off:
"It is an often made fallacy to assume that complex models must have high variance (and thus low bias); High variance models are 'complex' in some sense, but the reverse needs not be true."
I think the key is to understand that for generalization performance, low bias comes from model correctness, not complexity.
Unprincipled complexity only reduces "bias" if you're talking about training set performance. This is not the precisely defined bias $E(f - \hat{f})$ in the bias-variance decomposition, which involves an expectation taken over all possible inputs.
Thus, I think your underlying confusion was thinking that highly flexible models have low bias in the expected value (generalization) sense, while that is only true if the expected value is approximated by a sample mean over the training set (on which we define the word "fit").
A sort of corollary to this idea is that if you have a huge, encompassingly representative amount of training data, then a massively complex model (like those of modern deep learning) can lower bias on a sample mean error that closely approximates the actual mean. But it should be noted that most of the successful massive models aren't full of "unprincipled complexity" - they often take advantage of crucial structures inherent to the data (e.g. using convolution on images, etc). Moreover, understanding the surprising generalization ability of massive deep models is still a point of research to this day (and research on the many ways that generalization ability can silently fail too, e.g. adversarial inputs).
|
Impossible to overfit when the data generating process is deterministic?
I agree that overfitting is not possible when the data-generating process is deterministic. However, this is not "too good to be true" because generalization is still a problem.
Consider that we can t
|
46,444
|
Impossible to overfit when the data generating process is deterministic?
|
We can treat Machine Learning book by Mitchell (1997) as an authoritative reference on this subject. On p. 67 he defines overfitting
Definition: Given a hypothesis space $H$, a hypothesis $h \in H$ is said to overfit the training data if there exists some alternative
hypothesis $h' \in H$, such that $h$ has smaller error than $h'$ over
the training examples, but $h'$ has a smaller error than $h$ over the
entire distribution of instances.
Say, that you are given a sample of points from a noiseless polynomial function. You are to find the function using the polynomial regression model. You can easily imagine how given small sample, you could find many different solutions that fit the training sample perfectly, though do not fit well the entire distribution. An extreme case would be single datapoint, in such case finding the correct model would be impossible, so the solution would surely not generalize.
Someone can argue, that the above example does not fit the definition, since $h$ fits the training data equally well as $h'$, so this does not satisfy the definition criteria. My counterargument is, that in such case many big enough neural networks can't overfit as well, you just need make them fit the training data perfectly.
Another argument, may be that the example misses the point, since overfitting is about model fitting to noise, rather than to signal, hence it does not generalize. First, the definition above does not say anything about the noise. Second, if that would be the case, than we must conclude that the definition does not apply noiseless functions, so there is no answer to this question.
|
Impossible to overfit when the data generating process is deterministic?
|
We can treat Machine Learning book by Mitchell (1997) as an authoritative reference on this subject. On p. 67 he defines overfitting
Definition: Given a hypothesis space $H$, a hypothesis $h \in H$ i
|
Impossible to overfit when the data generating process is deterministic?
We can treat Machine Learning book by Mitchell (1997) as an authoritative reference on this subject. On p. 67 he defines overfitting
Definition: Given a hypothesis space $H$, a hypothesis $h \in H$ is said to overfit the training data if there exists some alternative
hypothesis $h' \in H$, such that $h$ has smaller error than $h'$ over
the training examples, but $h'$ has a smaller error than $h$ over the
entire distribution of instances.
Say, that you are given a sample of points from a noiseless polynomial function. You are to find the function using the polynomial regression model. You can easily imagine how given small sample, you could find many different solutions that fit the training sample perfectly, though do not fit well the entire distribution. An extreme case would be single datapoint, in such case finding the correct model would be impossible, so the solution would surely not generalize.
Someone can argue, that the above example does not fit the definition, since $h$ fits the training data equally well as $h'$, so this does not satisfy the definition criteria. My counterargument is, that in such case many big enough neural networks can't overfit as well, you just need make them fit the training data perfectly.
Another argument, may be that the example misses the point, since overfitting is about model fitting to noise, rather than to signal, hence it does not generalize. First, the definition above does not say anything about the noise. Second, if that would be the case, than we must conclude that the definition does not apply noiseless functions, so there is no answer to this question.
|
Impossible to overfit when the data generating process is deterministic?
We can treat Machine Learning book by Mitchell (1997) as an authoritative reference on this subject. On p. 67 he defines overfitting
Definition: Given a hypothesis space $H$, a hypothesis $h \in H$ i
|
46,445
|
Is it a must to include a random slope in a mixed model?
|
There is considerable disagreement on this topic.
I like to keep it simple. If you have a priori reasons to believe that the fixed effect in question should vary by subject (or whatever the grouping variable is) then you should fit random slopes. Obviously, this is provided that the data supports such a model. Often a model containing random slopes will have a singular fit, either because the correlation between the slopes and intercepts is estimated close to, or at, +/- 1, or because the variance in the random slopes is estimated close to, or at, 0. In the former case, a model fitted without such correlation can be fitted, but in the latter case the only solution is usually to remove the random slopes.
If the model converges without warnings, then I would retain the random slopes. I would not do any statistical test to decide whether to retain them, because I had a priori reasons to include them in the first place and just because they weren't significant in this sample is not a reason to exclude them if I believe they should be present in the population.
Having said that, I can't really argue with the approach of testing with a likelihood ratio, and removing the slopes if they don't offer an improved fit, on the basis of model parsimony. It's just my preference to retain them.
I am not familiar with the argument to retain random slopes if a cross-level interaction is fitted in the fixed part of the model. Does this refer to random slopes for the interaction only ?
|
Is it a must to include a random slope in a mixed model?
|
There is considerable disagreement on this topic.
I like to keep it simple. If you have a priori reasons to believe that the fixed effect in question should vary by subject (or whatever the grouping v
|
Is it a must to include a random slope in a mixed model?
There is considerable disagreement on this topic.
I like to keep it simple. If you have a priori reasons to believe that the fixed effect in question should vary by subject (or whatever the grouping variable is) then you should fit random slopes. Obviously, this is provided that the data supports such a model. Often a model containing random slopes will have a singular fit, either because the correlation between the slopes and intercepts is estimated close to, or at, +/- 1, or because the variance in the random slopes is estimated close to, or at, 0. In the former case, a model fitted without such correlation can be fitted, but in the latter case the only solution is usually to remove the random slopes.
If the model converges without warnings, then I would retain the random slopes. I would not do any statistical test to decide whether to retain them, because I had a priori reasons to include them in the first place and just because they weren't significant in this sample is not a reason to exclude them if I believe they should be present in the population.
Having said that, I can't really argue with the approach of testing with a likelihood ratio, and removing the slopes if they don't offer an improved fit, on the basis of model parsimony. It's just my preference to retain them.
I am not familiar with the argument to retain random slopes if a cross-level interaction is fitted in the fixed part of the model. Does this refer to random slopes for the interaction only ?
|
Is it a must to include a random slope in a mixed model?
There is considerable disagreement on this topic.
I like to keep it simple. If you have a priori reasons to believe that the fixed effect in question should vary by subject (or whatever the grouping v
|
46,446
|
How to measure whether a discrete distribution is uniform or not?
|
Your suggestion should work.
I'm going to make another suggestion, which also yields an integer value for the discrepancy from uniformity. As indicated in comments, we don't really have enough information to say whether it's better for your application.
The usual chi-squared goodness of fit statistic is $\sum_i (O_i-E_i)^2/E_i$ (where $O_i$ is the observed count in category $i$ and $E_i$ is the expected count). When used for deviation from perfect uniformity, $E_i=N/k$, where $N=\sum_i O_i$ is the total count and $k$ is the number of categories.
This chi-squared statistic from uniformity is also related to the simple variance of the counts.
Note that this statistic simplifies in the uniformity case, as follows:
\begin{eqnarray}
\sum_i (O_i-E_i)^2/E_i &=& \sum_i (O_i-N/k)^2/(N/k)\\
&=& \frac{k}{N} \sum_i (O_i-N/k)^2\\
&=& \frac{k}{N} \sum_i [O_i^2-2N/k\cdot O_i+(N/k)^2]\\
&=& \frac{k}{N} [\sum_i O_i^2-2N/k \sum_i O_i+\sum_i (N/k)^2)]\\
&=& \frac{k}{N} [\sum_i O_i^2-2N/k\cdot N+ k\cdot(N/k)^2)]\\
&=& (\frac{k}{N} \sum_i O_i^2)-2N+ N\\
&=& (\frac{k}{N} \sum_i O_i^2)-N
\end{eqnarray}
A simple linear rescaling of the chi-squared statistic is then $\sum_i O_i^2$, which will be integer-valued.
With $r={N\mod k}$, you could compute the smallest possible such value by putting $\lfloor N/k\rfloor$ (the average count rounded down) into $k-r$ bins and $\lceil N/k \rceil$ (the same, rounded up) into $r$ bins. It would be reasonable - but not necessary - to subtract the sum of squared counts for this arrangement from the above sum of squared counts. This would give an arrangement like $[1,2,1,2,2]$ get the value $0$, since it cannot be made smaller. If you'd like such an arrangement to get a non-zero value, the value of $\sum O_i^2$ under exactly equal allocation is $N^2/k$, but this won't be an integer in such cases, so you'd need to round that down before subtracting from $\sum O_i^2$ (rounding down would mean the difference $(\sum O_i^2)-\lfloor N^2/k\rfloor$ would only be exactly zero when the spread was perfectly uniform).
|
How to measure whether a discrete distribution is uniform or not?
|
Your suggestion should work.
I'm going to make another suggestion, which also yields an integer value for the discrepancy from uniformity. As indicated in comments, we don't really have enough informa
|
How to measure whether a discrete distribution is uniform or not?
Your suggestion should work.
I'm going to make another suggestion, which also yields an integer value for the discrepancy from uniformity. As indicated in comments, we don't really have enough information to say whether it's better for your application.
The usual chi-squared goodness of fit statistic is $\sum_i (O_i-E_i)^2/E_i$ (where $O_i$ is the observed count in category $i$ and $E_i$ is the expected count). When used for deviation from perfect uniformity, $E_i=N/k$, where $N=\sum_i O_i$ is the total count and $k$ is the number of categories.
This chi-squared statistic from uniformity is also related to the simple variance of the counts.
Note that this statistic simplifies in the uniformity case, as follows:
\begin{eqnarray}
\sum_i (O_i-E_i)^2/E_i &=& \sum_i (O_i-N/k)^2/(N/k)\\
&=& \frac{k}{N} \sum_i (O_i-N/k)^2\\
&=& \frac{k}{N} \sum_i [O_i^2-2N/k\cdot O_i+(N/k)^2]\\
&=& \frac{k}{N} [\sum_i O_i^2-2N/k \sum_i O_i+\sum_i (N/k)^2)]\\
&=& \frac{k}{N} [\sum_i O_i^2-2N/k\cdot N+ k\cdot(N/k)^2)]\\
&=& (\frac{k}{N} \sum_i O_i^2)-2N+ N\\
&=& (\frac{k}{N} \sum_i O_i^2)-N
\end{eqnarray}
A simple linear rescaling of the chi-squared statistic is then $\sum_i O_i^2$, which will be integer-valued.
With $r={N\mod k}$, you could compute the smallest possible such value by putting $\lfloor N/k\rfloor$ (the average count rounded down) into $k-r$ bins and $\lceil N/k \rceil$ (the same, rounded up) into $r$ bins. It would be reasonable - but not necessary - to subtract the sum of squared counts for this arrangement from the above sum of squared counts. This would give an arrangement like $[1,2,1,2,2]$ get the value $0$, since it cannot be made smaller. If you'd like such an arrangement to get a non-zero value, the value of $\sum O_i^2$ under exactly equal allocation is $N^2/k$, but this won't be an integer in such cases, so you'd need to round that down before subtracting from $\sum O_i^2$ (rounding down would mean the difference $(\sum O_i^2)-\lfloor N^2/k\rfloor$ would only be exactly zero when the spread was perfectly uniform).
|
How to measure whether a discrete distribution is uniform or not?
Your suggestion should work.
I'm going to make another suggestion, which also yields an integer value for the discrepancy from uniformity. As indicated in comments, we don't really have enough informa
|
46,447
|
How to measure whether a discrete distribution is uniform or not?
|
You can just as well use entropy in the discrete case as in the continuous case. The discrete uniform distribution on, say, $\{ 1,2,\dotsc,n \}$ also maximizes entropy among all distributions on that same support. Note that it does not matter if that support set is integers on just indices into some discrete set $\{ x_1, x_2, \dotsc, x_n \}$ since the entropy
$$
H=-\sum_i p_i \log p_i
$$
does not involve at all the actual values in the support set. That is an important difference from the continuous entropy $-\int f(x)\log f(x)\; dx$ which actually uses the values in the support via the differential $d x$.
So just use entropy, but there are also other possibilities.
|
How to measure whether a discrete distribution is uniform or not?
|
You can just as well use entropy in the discrete case as in the continuous case. The discrete uniform distribution on, say, $\{ 1,2,\dotsc,n \}$ also maximizes entropy among all distributions on that
|
How to measure whether a discrete distribution is uniform or not?
You can just as well use entropy in the discrete case as in the continuous case. The discrete uniform distribution on, say, $\{ 1,2,\dotsc,n \}$ also maximizes entropy among all distributions on that same support. Note that it does not matter if that support set is integers on just indices into some discrete set $\{ x_1, x_2, \dotsc, x_n \}$ since the entropy
$$
H=-\sum_i p_i \log p_i
$$
does not involve at all the actual values in the support set. That is an important difference from the continuous entropy $-\int f(x)\log f(x)\; dx$ which actually uses the values in the support via the differential $d x$.
So just use entropy, but there are also other possibilities.
|
How to measure whether a discrete distribution is uniform or not?
You can just as well use entropy in the discrete case as in the continuous case. The discrete uniform distribution on, say, $\{ 1,2,\dotsc,n \}$ also maximizes entropy among all distributions on that
|
46,448
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest reliability?
|
Yes, you can do this and interpret it as you think. I have read about such an interpretation in the second chapter of Sophia Rabe-Hesketh and Anders Skrondal's Multilevel and Longitudinal Modeling using Stata book (Volume 1).
A more detailed explanation follows. Edit: I also added a simulation to demonstrate what is going on. Hat tip to Ariel Muldoon for a helpful blog post that aided me in creating this simulation.
In a random intercept model with no predictors,
$$y_{ij} = \beta_0 + u_{0j} + \epsilon_{ij}$$
we get two variances, one for $u_{0j}$, which is $\psi$, and one for $\epsilon_{ij}$, which is $\theta$.
From these we can express between-subject dependence or reliability ($\rho$) as:
$$\rho = \frac{\psi}{\psi+\theta}$$
In this equation, $\psi$ is the variance of subjects' true scores $\beta_0 + u_{0j}$ and $\theta$ is the measurement error variance, or squared standard error of measurement. $\rho$ becomes a test-retest reliability because of the repeated measurements.
In contrast to the Pearson correlation coefficient, $\rho$ is influenced by any linear transformations of measurements, which could include practice effects or experimentally-induced increases from time 1 to time 2. Thus, if you know of something in your data that induces linear changes, you must account for it in your mixed model.
In your case, you have a time-varying experimental manipulation (call it $x_1$). Including $x_1$ as a predictor in your random intercept model,
$$y_{ij} = \beta_0 + \beta_1x_1 +u_{0j} + \epsilon_{ij}$$
will (likely) have an effect on both $\psi$ and $\theta$. In so doing, the resulting estimates of $\psi$ and $\theta$ are no longer influenced by $x_1$, and you have an estimate of test-retest reliability robust to experimental effects.
Simulation
set.seed(807)
npart=1000 # number of particpants
ntime=3 # numer of observations (timepoints) per participant
mu=2.5 # mean value on the Likert item
sdp=1 # standard deviation of participant random effect (variance==1)
sd=.7071 # standard deviation of within participant (residual; variance = .5)
participant = rep(rep(1:npart, each = nobs),ntime) # creating 1000 participants w/ 3 repeats
participant = participant[order(participant)]
time = rep(rep(1:ntime, each=1),1000) # creating a time variable
parteff = rnorm(npart, 0, sdp) # drawing from normal for participant deviation
parteff = rep(parteff, each=ntime) # ensuring participant effect is same for three observations
timeeff = rnorm(npart*ntime, 0, sd) # drawing from normal for within-participant residual
dat=data.frame(participant, time, parteff, timeeff) # create data frame
dat$resp = with(dat, mu + parteff + timeeff ) # creating response for each individual
#Variance components model
library(lme4)
m1 <- lmer(resp ~ 1 + (1|participant), dat)
summary(m1) # estimates close to simulated values
Linear mixed model fit by REML ['lmerMod']
Formula: resp ~ 1 + (1 | participant)
Data: dat
REML criterion at convergence: 8523.8
Scaled residuals:
Min 1Q Median 3Q Max
-3.13381 -0.57238 0.01722 0.57846 2.84918
Random effects:
Groups Name Variance Std.Dev.
participant (Intercept) 1.0110 1.0055
Residual 0.5314 0.7289
Number of obs: 3000, groups: participant, 1000
Fixed effects:
Estimate Std. Error t value
(Intercept) 2.54142 0.03447 73.73
#Add treatment variable x1 which turns on at time 3
dat$trtmt = rep(c(0,0,1),1000)
b1 = .4 #average amount by which particpant's score increases b/c of treatment
x1 = runif(npart, .05, 1.5)
library(dplyr)
dat <- dat %>% mutate(resp2=case_when
(time==3 ~ (mu+b1*x1+parteff+timeeff),
TRUE ~ resp))
glimpse(dat)
#run m1 without covariate for trtmt
m2 <- lmer(resp2 ~ 1 + (1|participant), dat)
summary(m2)
Linear mixed model fit by REML ['lmerMod']
Formula: resp2 ~ 1 + (1 | participant)
Data: dat
REML criterion at convergence: 8659.9
Scaled residuals:
Min 1Q Median 3Q Max
-2.72238 -0.56861 0.01894 0.57177 3.10610
Random effects:
Groups Name Variance Std.Dev.
participant (Intercept) 1.0070 1.0035
Residual 0.5669 0.7529
Number of obs: 3000, groups: participant, 1000
Fixed effects:
Estimate Std. Error t value
(Intercept) 2.64169 0.03458 76.39
#add trtmt as a fixed effect predictor
m3 <- lmer(resp2 ~ 1 + trtmt + (1|participant), dat)
summary(m3)
Linear mixed model fit by REML ['lmerMod']
Formula: resp2 ~ 1 + trtmt + (1 | participant)
Data: dat
REML criterion at convergence: 8546.7
Scaled residuals:
Min 1Q Median 3Q Max
-3.06878 -0.57650 0.02712 0.57887 2.89709
Random effects:
Groups Name Variance Std.Dev.
participant (Intercept) 1.0178 1.0088
Residual 0.5346 0.7311
Number of obs: 3000, groups: participant, 1000
Fixed effects:
Estimate Std. Error t value
(Intercept) 2.53746 0.03585 70.78
trtmt 0.31270 0.02832 11.04
Correlation of Fixed Effects:
(Intr)
trtmt -0.263
> texreg::screenreg(c(m1, m2, m3))
======================================================================
Model 1 Model 2 Model 3
----------------------------------------------------------------------
(Intercept) 2.54 *** 2.64 *** 2.54 ***
(0.03) (0.03) (0.04)
trtmt 0.31 ***
(0.03)
----------------------------------------------------------------------
AIC 8529.83 8665.86 8554.72
BIC 8547.85 8683.88 8578.75
Log Likelihood -4261.92 -4329.93 -4273.36
Num. obs. 3000 3000 3000
Num. groups: participant 1000 1000 1000
Var: participant (Intercept) 1.01 1.01 1.02
Var: Residual 0.53 0.57 0.53
======================================================================
*** p < 0.001; ** p < 0.01; * p < 0.05
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest relia
|
Yes, you can do this and interpret it as you think. I have read about such an interpretation in the second chapter of Sophia Rabe-Hesketh and Anders Skrondal's Multilevel and Longitudinal Modeling usi
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest reliability?
Yes, you can do this and interpret it as you think. I have read about such an interpretation in the second chapter of Sophia Rabe-Hesketh and Anders Skrondal's Multilevel and Longitudinal Modeling using Stata book (Volume 1).
A more detailed explanation follows. Edit: I also added a simulation to demonstrate what is going on. Hat tip to Ariel Muldoon for a helpful blog post that aided me in creating this simulation.
In a random intercept model with no predictors,
$$y_{ij} = \beta_0 + u_{0j} + \epsilon_{ij}$$
we get two variances, one for $u_{0j}$, which is $\psi$, and one for $\epsilon_{ij}$, which is $\theta$.
From these we can express between-subject dependence or reliability ($\rho$) as:
$$\rho = \frac{\psi}{\psi+\theta}$$
In this equation, $\psi$ is the variance of subjects' true scores $\beta_0 + u_{0j}$ and $\theta$ is the measurement error variance, or squared standard error of measurement. $\rho$ becomes a test-retest reliability because of the repeated measurements.
In contrast to the Pearson correlation coefficient, $\rho$ is influenced by any linear transformations of measurements, which could include practice effects or experimentally-induced increases from time 1 to time 2. Thus, if you know of something in your data that induces linear changes, you must account for it in your mixed model.
In your case, you have a time-varying experimental manipulation (call it $x_1$). Including $x_1$ as a predictor in your random intercept model,
$$y_{ij} = \beta_0 + \beta_1x_1 +u_{0j} + \epsilon_{ij}$$
will (likely) have an effect on both $\psi$ and $\theta$. In so doing, the resulting estimates of $\psi$ and $\theta$ are no longer influenced by $x_1$, and you have an estimate of test-retest reliability robust to experimental effects.
Simulation
set.seed(807)
npart=1000 # number of particpants
ntime=3 # numer of observations (timepoints) per participant
mu=2.5 # mean value on the Likert item
sdp=1 # standard deviation of participant random effect (variance==1)
sd=.7071 # standard deviation of within participant (residual; variance = .5)
participant = rep(rep(1:npart, each = nobs),ntime) # creating 1000 participants w/ 3 repeats
participant = participant[order(participant)]
time = rep(rep(1:ntime, each=1),1000) # creating a time variable
parteff = rnorm(npart, 0, sdp) # drawing from normal for participant deviation
parteff = rep(parteff, each=ntime) # ensuring participant effect is same for three observations
timeeff = rnorm(npart*ntime, 0, sd) # drawing from normal for within-participant residual
dat=data.frame(participant, time, parteff, timeeff) # create data frame
dat$resp = with(dat, mu + parteff + timeeff ) # creating response for each individual
#Variance components model
library(lme4)
m1 <- lmer(resp ~ 1 + (1|participant), dat)
summary(m1) # estimates close to simulated values
Linear mixed model fit by REML ['lmerMod']
Formula: resp ~ 1 + (1 | participant)
Data: dat
REML criterion at convergence: 8523.8
Scaled residuals:
Min 1Q Median 3Q Max
-3.13381 -0.57238 0.01722 0.57846 2.84918
Random effects:
Groups Name Variance Std.Dev.
participant (Intercept) 1.0110 1.0055
Residual 0.5314 0.7289
Number of obs: 3000, groups: participant, 1000
Fixed effects:
Estimate Std. Error t value
(Intercept) 2.54142 0.03447 73.73
#Add treatment variable x1 which turns on at time 3
dat$trtmt = rep(c(0,0,1),1000)
b1 = .4 #average amount by which particpant's score increases b/c of treatment
x1 = runif(npart, .05, 1.5)
library(dplyr)
dat <- dat %>% mutate(resp2=case_when
(time==3 ~ (mu+b1*x1+parteff+timeeff),
TRUE ~ resp))
glimpse(dat)
#run m1 without covariate for trtmt
m2 <- lmer(resp2 ~ 1 + (1|participant), dat)
summary(m2)
Linear mixed model fit by REML ['lmerMod']
Formula: resp2 ~ 1 + (1 | participant)
Data: dat
REML criterion at convergence: 8659.9
Scaled residuals:
Min 1Q Median 3Q Max
-2.72238 -0.56861 0.01894 0.57177 3.10610
Random effects:
Groups Name Variance Std.Dev.
participant (Intercept) 1.0070 1.0035
Residual 0.5669 0.7529
Number of obs: 3000, groups: participant, 1000
Fixed effects:
Estimate Std. Error t value
(Intercept) 2.64169 0.03458 76.39
#add trtmt as a fixed effect predictor
m3 <- lmer(resp2 ~ 1 + trtmt + (1|participant), dat)
summary(m3)
Linear mixed model fit by REML ['lmerMod']
Formula: resp2 ~ 1 + trtmt + (1 | participant)
Data: dat
REML criterion at convergence: 8546.7
Scaled residuals:
Min 1Q Median 3Q Max
-3.06878 -0.57650 0.02712 0.57887 2.89709
Random effects:
Groups Name Variance Std.Dev.
participant (Intercept) 1.0178 1.0088
Residual 0.5346 0.7311
Number of obs: 3000, groups: participant, 1000
Fixed effects:
Estimate Std. Error t value
(Intercept) 2.53746 0.03585 70.78
trtmt 0.31270 0.02832 11.04
Correlation of Fixed Effects:
(Intr)
trtmt -0.263
> texreg::screenreg(c(m1, m2, m3))
======================================================================
Model 1 Model 2 Model 3
----------------------------------------------------------------------
(Intercept) 2.54 *** 2.64 *** 2.54 ***
(0.03) (0.03) (0.04)
trtmt 0.31 ***
(0.03)
----------------------------------------------------------------------
AIC 8529.83 8665.86 8554.72
BIC 8547.85 8683.88 8578.75
Log Likelihood -4261.92 -4329.93 -4273.36
Num. obs. 3000 3000 3000
Num. groups: participant 1000 1000 1000
Var: participant (Intercept) 1.01 1.01 1.02
Var: Residual 0.53 0.57 0.53
======================================================================
*** p < 0.001; ** p < 0.01; * p < 0.05
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest relia
Yes, you can do this and interpret it as you think. I have read about such an interpretation in the second chapter of Sophia Rabe-Hesketh and Anders Skrondal's Multilevel and Longitudinal Modeling usi
|
46,449
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest reliability?
|
This post really helped me and I wanted to thank you.
In case other users ran to the same issue I had - I am adding a slight change to the simulation above. The only thing here is that this shows that Pearson corr for two times measurements is exactly the same as $\rho$. Nothing special - only nice to see the numbers match :) Also, ever so slight correction in the participant vector to make this work.
Cheers
Nitzan
set.seed(807)
npart=1000 # number of particpants
ntime=2 # numer of observations (timepoints) per participant
mu=2.5 # mean value on the Likert item
sdp=1 # standard deviation of participant random effect (variance==1)
sd=.7071 # standard deviation of within participant (residual; variance = .5)
participant = rep(rep(1:npart, each = nobs),ntime) # creating 1000 participants w/ 3 repeats
participant = participant[order(participant)]
time = rep(rep(1:ntime, each=1),1000) # creating a time variable
parteff = rnorm(npart, 0, sdp) # drawing from normal for participant deviation
parteff = rep(parteff, each=ntime) # ensuring participant effect is same for three observations
timeeff = rnorm(npart*ntime, 0, sd) # drawing from normal for within-participant residual
dat=data.frame(participant, time, parteff, timeeff) # create data frame
dat$resp = with(dat, mu + parteff + timeeff ) # creating response for each individual
#Variance components model
library(lme4)
m1 <- lmer(resp ~ 1 + (1|participant), dat)
summary(m1) # estimates close to simulated values
#calculate pearson corr
library(reshape2)
df.wide <-dcast(dat,participant~time,mean,value.var='resp')[,-1]
cor(df.wide)
#get the same from the HLM fit
print(VarCorr(m1))
.95478^2/(.95478^2+0.74685^2)
```
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest relia
|
This post really helped me and I wanted to thank you.
In case other users ran to the same issue I had - I am adding a slight change to the simulation above. The only thing here is that this shows that
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest reliability?
This post really helped me and I wanted to thank you.
In case other users ran to the same issue I had - I am adding a slight change to the simulation above. The only thing here is that this shows that Pearson corr for two times measurements is exactly the same as $\rho$. Nothing special - only nice to see the numbers match :) Also, ever so slight correction in the participant vector to make this work.
Cheers
Nitzan
set.seed(807)
npart=1000 # number of particpants
ntime=2 # numer of observations (timepoints) per participant
mu=2.5 # mean value on the Likert item
sdp=1 # standard deviation of participant random effect (variance==1)
sd=.7071 # standard deviation of within participant (residual; variance = .5)
participant = rep(rep(1:npart, each = nobs),ntime) # creating 1000 participants w/ 3 repeats
participant = participant[order(participant)]
time = rep(rep(1:ntime, each=1),1000) # creating a time variable
parteff = rnorm(npart, 0, sdp) # drawing from normal for participant deviation
parteff = rep(parteff, each=ntime) # ensuring participant effect is same for three observations
timeeff = rnorm(npart*ntime, 0, sd) # drawing from normal for within-participant residual
dat=data.frame(participant, time, parteff, timeeff) # create data frame
dat$resp = with(dat, mu + parteff + timeeff ) # creating response for each individual
#Variance components model
library(lme4)
m1 <- lmer(resp ~ 1 + (1|participant), dat)
summary(m1) # estimates close to simulated values
#calculate pearson corr
library(reshape2)
df.wide <-dcast(dat,participant~time,mean,value.var='resp')[,-1]
cor(df.wide)
#get the same from the HLM fit
print(VarCorr(m1))
.95478^2/(.95478^2+0.74685^2)
```
|
Conditional intraclass correlation (ICC) from a linear mixed model as evidence for test-retest relia
This post really helped me and I wanted to thank you.
In case other users ran to the same issue I had - I am adding a slight change to the simulation above. The only thing here is that this shows that
|
46,450
|
Does a significant interaction necessarily implies that at least one of the simple effects will be significant?
|
Considering that the interaction between two variables is significant, is it always the case that at least one of the two simple effects will be significant?
No, not at all.
If so, is there any proof or a counter example?
Yes, it is easy to create a counter example:
> set.seed(1)
> N <- 200
> A <- rep(c(0,0,1,1), times = N/4)
> B <- rep(c(0,1), times = N/2)
> y <- A*B + rnorm(N)
> summary(lm(y ~ A*B))
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.0407 0.1317 -0.31 0.7579
A 0.2250 0.1863 1.21 0.2287
B 0.0789 0.1863 0.42 0.6723
A:B 0.6971 0.2635 2.65 0.0088 **
I would always advise against relying on statistical significance, which relies on p-values (that depend on sample size) and arbitrary significance levels.
Edit:
Following the update, I have to say that I hope the procedure in the edited question is not something that is being used in practice, but anyway, yes of course we can find a counterexample. Just set the seed in your code to, for example, 276
|
Does a significant interaction necessarily implies that at least one of the simple effects will be s
|
Considering that the interaction between two variables is significant, is it always the case that at least one of the two simple effects will be significant?
No, not at all.
If so, is there any proo
|
Does a significant interaction necessarily implies that at least one of the simple effects will be significant?
Considering that the interaction between two variables is significant, is it always the case that at least one of the two simple effects will be significant?
No, not at all.
If so, is there any proof or a counter example?
Yes, it is easy to create a counter example:
> set.seed(1)
> N <- 200
> A <- rep(c(0,0,1,1), times = N/4)
> B <- rep(c(0,1), times = N/2)
> y <- A*B + rnorm(N)
> summary(lm(y ~ A*B))
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.0407 0.1317 -0.31 0.7579
A 0.2250 0.1863 1.21 0.2287
B 0.0789 0.1863 0.42 0.6723
A:B 0.6971 0.2635 2.65 0.0088 **
I would always advise against relying on statistical significance, which relies on p-values (that depend on sample size) and arbitrary significance levels.
Edit:
Following the update, I have to say that I hope the procedure in the edited question is not something that is being used in practice, but anyway, yes of course we can find a counterexample. Just set the seed in your code to, for example, 276
|
Does a significant interaction necessarily implies that at least one of the simple effects will be s
Considering that the interaction between two variables is significant, is it always the case that at least one of the two simple effects will be significant?
No, not at all.
If so, is there any proo
|
46,451
|
Understanding why a $p$-value is too small
|
A few general thoughts:
It's very rare that real-world data follow a specific distribution exactly. This doesn't stop us from using a specific distribution as a model in order to answer questions. A model doesn't have to be perfect, but good enough for the purpose.
With such a huge sample size, even tiny deviations from a Skellam distribution will result in very small p-values. This is just a result of the consistency of the tests. The power to detect smaller and smaller deviations increases with increasing sample size (see also here). In the second case, a p-value of $2\times 10^{-13}$ means that there is a lot of evidence against the null hypothesis that the data come from a Skellam distribution. Specifically, there are $-\log_{2}(2\times 10^{-13})\approx 42.19$ bits of information agains the test hypothesis (this is called the $S$-value).
A failure to reject the null hypothesis does not mean that it is true. It means that there is not enough evidence to reject the notion that your data are compatible with a Skellam distribution with a high enough confidence. There may be infinitely many distributions other than the Skellam distribution that are compatible with your data.
Histograms are suboptimal to check the agreement between the data and a specified distribution. I recommend to use Q-Q-plots instead (more information here). Another very useful visualization tool is the hanging rootogram. A good paper on this can be found here. I show how to apply a hanging rootogram to check the fit to a Poisson distribution in this answer.
In the light of the points above, here are some questions that you might find useful to ask yourself:
What's your specific goal? Why do you want to show that the data are following a Skellam distribution?
How large do the deviations from a Skellam distribution have to be in order for you to deem the model of a Skellam distribution unsuitable for the task?
Both of these questions require subject matter knowledge which I don't have.
|
Understanding why a $p$-value is too small
|
A few general thoughts:
It's very rare that real-world data follow a specific distribution exactly. This doesn't stop us from using a specific distribution as a model in order to answer questions. A
|
Understanding why a $p$-value is too small
A few general thoughts:
It's very rare that real-world data follow a specific distribution exactly. This doesn't stop us from using a specific distribution as a model in order to answer questions. A model doesn't have to be perfect, but good enough for the purpose.
With such a huge sample size, even tiny deviations from a Skellam distribution will result in very small p-values. This is just a result of the consistency of the tests. The power to detect smaller and smaller deviations increases with increasing sample size (see also here). In the second case, a p-value of $2\times 10^{-13}$ means that there is a lot of evidence against the null hypothesis that the data come from a Skellam distribution. Specifically, there are $-\log_{2}(2\times 10^{-13})\approx 42.19$ bits of information agains the test hypothesis (this is called the $S$-value).
A failure to reject the null hypothesis does not mean that it is true. It means that there is not enough evidence to reject the notion that your data are compatible with a Skellam distribution with a high enough confidence. There may be infinitely many distributions other than the Skellam distribution that are compatible with your data.
Histograms are suboptimal to check the agreement between the data and a specified distribution. I recommend to use Q-Q-plots instead (more information here). Another very useful visualization tool is the hanging rootogram. A good paper on this can be found here. I show how to apply a hanging rootogram to check the fit to a Poisson distribution in this answer.
In the light of the points above, here are some questions that you might find useful to ask yourself:
What's your specific goal? Why do you want to show that the data are following a Skellam distribution?
How large do the deviations from a Skellam distribution have to be in order for you to deem the model of a Skellam distribution unsuitable for the task?
Both of these questions require subject matter knowledge which I don't have.
|
Understanding why a $p$-value is too small
A few general thoughts:
It's very rare that real-world data follow a specific distribution exactly. This doesn't stop us from using a specific distribution as a model in order to answer questions. A
|
46,452
|
Amount of Possible Bootstrap Samples
|
A standard technique is the "stars and bars" construction.
By "distinct bootstrap resample" what you mean is a sequence of $N$ elements of a set of size $N$ without paying attention to their order. Enumerate this set as $\{x_1, x_2, \ldots, x_N\}.$ Corresponding to any such sequence is the unique ordered sequence in which all of the $x_1$ in the bootstrap sample (if any) precede all the $x_2$ in the sample, which precede all the $x_3$ in the sample, etc. This sequence, in turn, is determined by the counts $n_j$ of each $x_j.$
Draw a diagram of this sequence by placing $n_1$ stars * (representing the $n_1$ copies of $x_1$ in the sample) followed by a bar | to their right, then $n_2$ stars (representing the $n_2$ copies of $x_2$ in the sample) followed by another bar, and so on, until placing the last $n_N$ stars (but not followed by any bar).
For instance, in a set of $N=5$ elements suppose the bootstrap sample is $(x_1,x_5,x_3,x_4,x_3).$ Its ordered version is $(x_1,x_3,x_3,x_4,x_5),$ for which the counts are $(n_i) = (1,0,2,1,1).$ Its stars-and-bars diagram therefore is
* | | * * | * | *
Clearly such a diagram always has $N$ stars (because the bootstrap sample has $N$ elements) and $N-1$ bars (because they separate $N$ groups of stars). Numbering the $N+N-1$ symbols left to right as $1,2,\ldots, 2N-1,$ note that the bars in this example have the numbers $\{2,3,6,8\}\subset\{1,2,\ldots,9\}.$
Conversely, corresponding to any diagram of $N$ stars and $N-1$ bars and an enumeration of $N$ observations we can recover the bootstrap sample. E.g., the diagram
| | | * * * | | * * | * * * |
with $N=8$ stars and $7$ bars corresponds to the (sorted) bootstrap sample $(x_4,x_4,x_4,\,x_6,x_6,\,x_7,x_7,x_7)$ of an eight-element set. The bars appear at positions $\{1,2,3,7,8,11,15\}\subset\{1,2,\ldots,15\}.$
To count the distinct bootstrap samples, then, it suffices to count the distinct stars and bars diagrams. But each such diagram corresponds to an $N-1$-element subset of $N+N-1=2N-1$ positions: namely, the positions in which the bars are located. By definition, this count is the binomial coefficient $\binom{2N-1}{N-1},$ QED.
Application
There are very efficient methods to sample without replacement and to return that result in order. Thus, you can create bootstrap samples very efficiently with stars and bars.
To illustrate, here is an R implementation. Given a dataset x, it generates an array, samples, whose columns represent all possible bootstrap resamples of x in terms of the positions of the bars. (This makes it impractical to apply to real problems, where $\binom{2N-1}{N-1}$ is so large that samples cannot be stored or even computed in reasonable time.) Because the relative chance of a resample with counts $(n_i)$ is $1/\prod (n_i!),$ columns cannot be selected uniformly from this array: the draws must be weighted by these relative chances. A caller-specified number N of resamples is returned in an array, one column per resample.
sample.boot <- function(N=1, x) {
n <- length(x)
samples <- combn(2*n-1, n-1) # Columns represent possible bootstrap samples
counts <- apply(rbind(0, samples, 2*n), 2, diff) - 1 # Counts the stars between the bars
p <- exp(-colSums(lfactorial(counts))) # Relative chances of the samples
p <- p / sum(p)
j <- sample.int(ncol(samples), N, replace=TRUE, prob=p)
apply(counts[, j, drop=FALSE], 2, function(i) rep(x, i)) # Replicates each `x[i]` `n.i[i]` times
}
E.g., the commands
X <- sample.boot(1e5, c("a", "b", "c"))
table(apply(X, 2, paste0, collapse=""))
produce the output
aaa aab aac abb abc acc bbb bbc bcc ccc
3655 11171 11127 11031 22145 11224 3725 11148 11105 3669
The first line is the ordered bootstrap resample and beneath it are the counts of how many times each resample appeared among $10^5$ draws. For instance, the chances of aaa, bbb, and ccc are all $1/3^3,$ for expected frequencies of $10^5/3^3 \approx 3704.$ The actual frequencies in this experiment were $3655,$ $3725,$ and $3669,$ differing from their expectations by small amounts attributable to the randomness of the drawing.
References
Richard Stanley, Enumerative Combinatorics (Volume I), Second Edition. Available at http://www-math.mit.edu/~rstan/ec/.
Almost any resource on mathematical problem solving at an elementary level ("elementary" does not mean "easy" or "unsophisticated"!). See https://brilliant.org/wiki/integer-equations-star-and-bars/ for instance.
|
Amount of Possible Bootstrap Samples
|
A standard technique is the "stars and bars" construction.
By "distinct bootstrap resample" what you mean is a sequence of $N$ elements of a set of size $N$ without paying attention to their order. E
|
Amount of Possible Bootstrap Samples
A standard technique is the "stars and bars" construction.
By "distinct bootstrap resample" what you mean is a sequence of $N$ elements of a set of size $N$ without paying attention to their order. Enumerate this set as $\{x_1, x_2, \ldots, x_N\}.$ Corresponding to any such sequence is the unique ordered sequence in which all of the $x_1$ in the bootstrap sample (if any) precede all the $x_2$ in the sample, which precede all the $x_3$ in the sample, etc. This sequence, in turn, is determined by the counts $n_j$ of each $x_j.$
Draw a diagram of this sequence by placing $n_1$ stars * (representing the $n_1$ copies of $x_1$ in the sample) followed by a bar | to their right, then $n_2$ stars (representing the $n_2$ copies of $x_2$ in the sample) followed by another bar, and so on, until placing the last $n_N$ stars (but not followed by any bar).
For instance, in a set of $N=5$ elements suppose the bootstrap sample is $(x_1,x_5,x_3,x_4,x_3).$ Its ordered version is $(x_1,x_3,x_3,x_4,x_5),$ for which the counts are $(n_i) = (1,0,2,1,1).$ Its stars-and-bars diagram therefore is
* | | * * | * | *
Clearly such a diagram always has $N$ stars (because the bootstrap sample has $N$ elements) and $N-1$ bars (because they separate $N$ groups of stars). Numbering the $N+N-1$ symbols left to right as $1,2,\ldots, 2N-1,$ note that the bars in this example have the numbers $\{2,3,6,8\}\subset\{1,2,\ldots,9\}.$
Conversely, corresponding to any diagram of $N$ stars and $N-1$ bars and an enumeration of $N$ observations we can recover the bootstrap sample. E.g., the diagram
| | | * * * | | * * | * * * |
with $N=8$ stars and $7$ bars corresponds to the (sorted) bootstrap sample $(x_4,x_4,x_4,\,x_6,x_6,\,x_7,x_7,x_7)$ of an eight-element set. The bars appear at positions $\{1,2,3,7,8,11,15\}\subset\{1,2,\ldots,15\}.$
To count the distinct bootstrap samples, then, it suffices to count the distinct stars and bars diagrams. But each such diagram corresponds to an $N-1$-element subset of $N+N-1=2N-1$ positions: namely, the positions in which the bars are located. By definition, this count is the binomial coefficient $\binom{2N-1}{N-1},$ QED.
Application
There are very efficient methods to sample without replacement and to return that result in order. Thus, you can create bootstrap samples very efficiently with stars and bars.
To illustrate, here is an R implementation. Given a dataset x, it generates an array, samples, whose columns represent all possible bootstrap resamples of x in terms of the positions of the bars. (This makes it impractical to apply to real problems, where $\binom{2N-1}{N-1}$ is so large that samples cannot be stored or even computed in reasonable time.) Because the relative chance of a resample with counts $(n_i)$ is $1/\prod (n_i!),$ columns cannot be selected uniformly from this array: the draws must be weighted by these relative chances. A caller-specified number N of resamples is returned in an array, one column per resample.
sample.boot <- function(N=1, x) {
n <- length(x)
samples <- combn(2*n-1, n-1) # Columns represent possible bootstrap samples
counts <- apply(rbind(0, samples, 2*n), 2, diff) - 1 # Counts the stars between the bars
p <- exp(-colSums(lfactorial(counts))) # Relative chances of the samples
p <- p / sum(p)
j <- sample.int(ncol(samples), N, replace=TRUE, prob=p)
apply(counts[, j, drop=FALSE], 2, function(i) rep(x, i)) # Replicates each `x[i]` `n.i[i]` times
}
E.g., the commands
X <- sample.boot(1e5, c("a", "b", "c"))
table(apply(X, 2, paste0, collapse=""))
produce the output
aaa aab aac abb abc acc bbb bbc bcc ccc
3655 11171 11127 11031 22145 11224 3725 11148 11105 3669
The first line is the ordered bootstrap resample and beneath it are the counts of how many times each resample appeared among $10^5$ draws. For instance, the chances of aaa, bbb, and ccc are all $1/3^3,$ for expected frequencies of $10^5/3^3 \approx 3704.$ The actual frequencies in this experiment were $3655,$ $3725,$ and $3669,$ differing from their expectations by small amounts attributable to the randomness of the drawing.
References
Richard Stanley, Enumerative Combinatorics (Volume I), Second Edition. Available at http://www-math.mit.edu/~rstan/ec/.
Almost any resource on mathematical problem solving at an elementary level ("elementary" does not mean "easy" or "unsophisticated"!). See https://brilliant.org/wiki/integer-equations-star-and-bars/ for instance.
|
Amount of Possible Bootstrap Samples
A standard technique is the "stars and bars" construction.
By "distinct bootstrap resample" what you mean is a sequence of $N$ elements of a set of size $N$ without paying attention to their order. E
|
46,453
|
Can we validate accuracy using precision and recall?
|
Assuming we know the sample size $N$ we can get the Accuracy from knowing Precision and Recall. Precision is defined as $\frac{TP}{TP+FP}$ and Recall is defined as $\frac{TP}{TP+FN}$, $TP$ is the number of True Positives, $FP$ is the number of False Positives and $FN$ is the number of True Negatives. Now given that $N = TP+TN+FP+FN$ the only thing we do not know if the number of $TN$. We can solve for $TN = N-(TP+FP+FN)$, given that we can calculate the Accuracy as $\frac{TP+TN}{N}$. If we do not know that total number of samples examined, $N$, then we are stuck.
In general, Precision and Recall (and their harmonic mean, the $F_1$ score) are intuitive measurements indeed but they do not account for the correct classification of negative examples (True Negatives) and that is on certain occasions inconvenient (or outright misleading).
|
Can we validate accuracy using precision and recall?
|
Assuming we know the sample size $N$ we can get the Accuracy from knowing Precision and Recall. Precision is defined as $\frac{TP}{TP+FP}$ and Recall is defined as $\frac{TP}{TP+FN}$, $TP$ is the numb
|
Can we validate accuracy using precision and recall?
Assuming we know the sample size $N$ we can get the Accuracy from knowing Precision and Recall. Precision is defined as $\frac{TP}{TP+FP}$ and Recall is defined as $\frac{TP}{TP+FN}$, $TP$ is the number of True Positives, $FP$ is the number of False Positives and $FN$ is the number of True Negatives. Now given that $N = TP+TN+FP+FN$ the only thing we do not know if the number of $TN$. We can solve for $TN = N-(TP+FP+FN)$, given that we can calculate the Accuracy as $\frac{TP+TN}{N}$. If we do not know that total number of samples examined, $N$, then we are stuck.
In general, Precision and Recall (and their harmonic mean, the $F_1$ score) are intuitive measurements indeed but they do not account for the correct classification of negative examples (True Negatives) and that is on certain occasions inconvenient (or outright misleading).
|
Can we validate accuracy using precision and recall?
Assuming we know the sample size $N$ we can get the Accuracy from knowing Precision and Recall. Precision is defined as $\frac{TP}{TP+FP}$ and Recall is defined as $\frac{TP}{TP+FN}$, $TP$ is the numb
|
46,454
|
Can we validate accuracy using precision and recall?
|
No, because you know nothing about true negatives, $TN$. Think about the confusion matrix with $FN,FP,TP$ entries known, which are used to calculate precision and recall, which means you have more information than precision/recall. But, even with these three known, you can adjust $TN$ as much as you can to change the accuracy.
|
Can we validate accuracy using precision and recall?
|
No, because you know nothing about true negatives, $TN$. Think about the confusion matrix with $FN,FP,TP$ entries known, which are used to calculate precision and recall, which means you have more inf
|
Can we validate accuracy using precision and recall?
No, because you know nothing about true negatives, $TN$. Think about the confusion matrix with $FN,FP,TP$ entries known, which are used to calculate precision and recall, which means you have more information than precision/recall. But, even with these three known, you can adjust $TN$ as much as you can to change the accuracy.
|
Can we validate accuracy using precision and recall?
No, because you know nothing about true negatives, $TN$. Think about the confusion matrix with $FN,FP,TP$ entries known, which are used to calculate precision and recall, which means you have more inf
|
46,455
|
Can we validate accuracy using precision and recall?
|
No, it's not possible to calculate the accuracy solely based on Precision and Recall. Building up on the previous answers, even if you know the sample size $N$, you'd still need more information.
Given that:
$N = TP+TN+FP+FN \implies TN = N-(TP+FP+FN)$
Precision is defined as $P = \frac{TP}{TP+FN}$
Recall is defined as $R = \frac{TP}{TP+FN}$
Accuracy is defined as $Acc = \frac{TN+TP}{N}$
We have:
$Acc = \frac{TN+TP}{N} = \frac{N-(TP+FP+FN)+TP}{N}=\frac{N-FP-FN}{N}$
In order to continue, we would need to have $FP$ and $FN$, or simply $TP$. We can obtain $FP = \frac{TP \cdot (1-P)}{P}$ from the Precision definition, and $FN = \frac{TP \cdot (1-R)}{R}$ from the Recall definition. But without knowing the value of $TP$, we cannot reach a solution.
|
Can we validate accuracy using precision and recall?
|
No, it's not possible to calculate the accuracy solely based on Precision and Recall. Building up on the previous answers, even if you know the sample size $N$, you'd still need more information.
Give
|
Can we validate accuracy using precision and recall?
No, it's not possible to calculate the accuracy solely based on Precision and Recall. Building up on the previous answers, even if you know the sample size $N$, you'd still need more information.
Given that:
$N = TP+TN+FP+FN \implies TN = N-(TP+FP+FN)$
Precision is defined as $P = \frac{TP}{TP+FN}$
Recall is defined as $R = \frac{TP}{TP+FN}$
Accuracy is defined as $Acc = \frac{TN+TP}{N}$
We have:
$Acc = \frac{TN+TP}{N} = \frac{N-(TP+FP+FN)+TP}{N}=\frac{N-FP-FN}{N}$
In order to continue, we would need to have $FP$ and $FN$, or simply $TP$. We can obtain $FP = \frac{TP \cdot (1-P)}{P}$ from the Precision definition, and $FN = \frac{TP \cdot (1-R)}{R}$ from the Recall definition. But without knowing the value of $TP$, we cannot reach a solution.
|
Can we validate accuracy using precision and recall?
No, it's not possible to calculate the accuracy solely based on Precision and Recall. Building up on the previous answers, even if you know the sample size $N$, you'd still need more information.
Give
|
46,456
|
How is the Herfindahl-Hirschman index different from entropy?
|
In biology, these are called measures of diversity, and while that application is different, there must be some value in the comparison. See for example this wiki or this book by Anne Magurran. In that application $p_i$ is population share (probability that an individual sampled from the population is of species $i$.) For a very different application What is the probability that a person will die on their birthday?.
Anne Magurran strongly advises use of the Simpson index. The reason is that it does not depend so strongly on the long tail of small $p_i$'s, while the Shannon index (entropy) depends more on this. For that reason the Shannon index depends in practice on sample size (to a stronger degree than the Simpson index). But that might not be important in your economic application. In biology there is the aspect of unsampled species, if you have a full census of firms that should not be a problem. One idea to aid interpretation, to put such indices on a similar footing, is converting them to an equivalent number of species, the number of species which, with all $p_i$'s equal, would give the observed index value. For your application this would be equivalent number of firms. With this interpretation there are the Hill numbers
$$ H_a = \left( \sum_i p_i^a \right)^{\frac1{1-a}}
$$ which gives Simpson for $a=2$ (transformed), Shannon index for $a=1$ and number of species for $a=0$. This again shows that Shannon is closer to the number of species than is Simpson, so depends to a stronger degree on the many small $p_i$'s. So, qualitatively, the Simpson index depends more on the larger firms, while the Shannon index has a stronger influence from the smaller ones.
|
How is the Herfindahl-Hirschman index different from entropy?
|
In biology, these are called measures of diversity, and while that application is different, there must be some value in the comparison. See for example this wiki or this book by Anne Magurran. In tha
|
How is the Herfindahl-Hirschman index different from entropy?
In biology, these are called measures of diversity, and while that application is different, there must be some value in the comparison. See for example this wiki or this book by Anne Magurran. In that application $p_i$ is population share (probability that an individual sampled from the population is of species $i$.) For a very different application What is the probability that a person will die on their birthday?.
Anne Magurran strongly advises use of the Simpson index. The reason is that it does not depend so strongly on the long tail of small $p_i$'s, while the Shannon index (entropy) depends more on this. For that reason the Shannon index depends in practice on sample size (to a stronger degree than the Simpson index). But that might not be important in your economic application. In biology there is the aspect of unsampled species, if you have a full census of firms that should not be a problem. One idea to aid interpretation, to put such indices on a similar footing, is converting them to an equivalent number of species, the number of species which, with all $p_i$'s equal, would give the observed index value. For your application this would be equivalent number of firms. With this interpretation there are the Hill numbers
$$ H_a = \left( \sum_i p_i^a \right)^{\frac1{1-a}}
$$ which gives Simpson for $a=2$ (transformed), Shannon index for $a=1$ and number of species for $a=0$. This again shows that Shannon is closer to the number of species than is Simpson, so depends to a stronger degree on the many small $p_i$'s. So, qualitatively, the Simpson index depends more on the larger firms, while the Shannon index has a stronger influence from the smaller ones.
|
How is the Herfindahl-Hirschman index different from entropy?
In biology, these are called measures of diversity, and while that application is different, there must be some value in the comparison. See for example this wiki or this book by Anne Magurran. In tha
|
46,457
|
How is the Herfindahl-Hirschman index different from entropy?
|
I believe many sources refer to them as similar simply because both functionals are often used towards the same goal - quantifying the diversity/information of a given probability distribution. The HHI index in fact has many other names in different scientific disciplines, most notably the Simpson index.
An extensive and very readeable qualitative discussion can be found both in the Wikipedia article linked above and this paper, among many other sources.
For what it's worth, one can get
$$ HHI(p) \geq \exp(-H(p))$$
via (weighted) Jensen's as follows:
$$ \exp(-H(p)) = \exp\left(\sum_i p_i\log p_i\right) = \prod_i p_i^{p_i} \overset{Jensen's}{\leq} \sum_i p_i\cdot p_i = HHI(p).$$
|
How is the Herfindahl-Hirschman index different from entropy?
|
I believe many sources refer to them as similar simply because both functionals are often used towards the same goal - quantifying the diversity/information of a given probability distribution. The HH
|
How is the Herfindahl-Hirschman index different from entropy?
I believe many sources refer to them as similar simply because both functionals are often used towards the same goal - quantifying the diversity/information of a given probability distribution. The HHI index in fact has many other names in different scientific disciplines, most notably the Simpson index.
An extensive and very readeable qualitative discussion can be found both in the Wikipedia article linked above and this paper, among many other sources.
For what it's worth, one can get
$$ HHI(p) \geq \exp(-H(p))$$
via (weighted) Jensen's as follows:
$$ \exp(-H(p)) = \exp\left(\sum_i p_i\log p_i\right) = \prod_i p_i^{p_i} \overset{Jensen's}{\leq} \sum_i p_i\cdot p_i = HHI(p).$$
|
How is the Herfindahl-Hirschman index different from entropy?
I believe many sources refer to them as similar simply because both functionals are often used towards the same goal - quantifying the diversity/information of a given probability distribution. The HH
|
46,458
|
How is the Herfindahl-Hirschman index different from entropy?
|
A few comments. Let $P = (p_1, p_2, \ldots, p_N)$ be a probability distribution (so that $0 \le p_i \le 1$ and $\sum_i p_i = 1$).
The measures are conceptually very closely related. The entropy is the expected surprise of a random draw from the distribution $P$ (where the surprise of an event with probability $p$ is defined to be $-\log(p)$). The HHI is the expected probability of a random draw from the distribution $P$. Probability is sort-of inverse to surprise, since it measures how likely something is, as opposed to how surprising it is.
The HHI is also the probability that two different random samples from $P$ have the same value.
Both measures ignore zero probabilities ($p\log(p)$ is defined to be zero if $p=0$ by convention).
There is also a numerical relationship between them. Let $\overline{P} = \frac{1}{N-1}(1-p_1, \ldots, 1-p_N)$. This is a probability distribution, which you could call the complement of $P$. Using the fact that $\log(1-p_i) \approx -p_i$ for $p_i \approx 0$, you can obtain
$$H(\overline{P}) \approx \frac{-1}{N-1}HHI(P) + \log(N-1) + \frac{1}{N-1}$$
provided that all the $p_i$ are fairly small, and you take natural log. So, morally, up to addition and multiplication by positive scalars, $HHI$ is the negative of the entropy of the "complement" distribution, which in turn is a kind of negative of the original distribution.
There is a paper about this on the arXiv which you could look at to see how these ideas are pursued. However, I would take its grandiose claims about "discovering extropy" with a grain of salt, as at least one of the authors is known to be a bit of a crank!
I think the main qualitative difference between the two measures is that entropy is only defined up to a scalar, because it depends on a choice of base for the logarithm ($e$ and $2$ being common choices) whereas for $HHI$ there is a natural scaling factor of $1$.
It seems that HHI is a very reasonable thing to use as a measure of diversity. However, I can't shake the feeling that entropy is "better" in terms of theoretical properties (such as those listed in Wikipedia).
|
How is the Herfindahl-Hirschman index different from entropy?
|
A few comments. Let $P = (p_1, p_2, \ldots, p_N)$ be a probability distribution (so that $0 \le p_i \le 1$ and $\sum_i p_i = 1$).
The measures are conceptually very closely related. The entropy is t
|
How is the Herfindahl-Hirschman index different from entropy?
A few comments. Let $P = (p_1, p_2, \ldots, p_N)$ be a probability distribution (so that $0 \le p_i \le 1$ and $\sum_i p_i = 1$).
The measures are conceptually very closely related. The entropy is the expected surprise of a random draw from the distribution $P$ (where the surprise of an event with probability $p$ is defined to be $-\log(p)$). The HHI is the expected probability of a random draw from the distribution $P$. Probability is sort-of inverse to surprise, since it measures how likely something is, as opposed to how surprising it is.
The HHI is also the probability that two different random samples from $P$ have the same value.
Both measures ignore zero probabilities ($p\log(p)$ is defined to be zero if $p=0$ by convention).
There is also a numerical relationship between them. Let $\overline{P} = \frac{1}{N-1}(1-p_1, \ldots, 1-p_N)$. This is a probability distribution, which you could call the complement of $P$. Using the fact that $\log(1-p_i) \approx -p_i$ for $p_i \approx 0$, you can obtain
$$H(\overline{P}) \approx \frac{-1}{N-1}HHI(P) + \log(N-1) + \frac{1}{N-1}$$
provided that all the $p_i$ are fairly small, and you take natural log. So, morally, up to addition and multiplication by positive scalars, $HHI$ is the negative of the entropy of the "complement" distribution, which in turn is a kind of negative of the original distribution.
There is a paper about this on the arXiv which you could look at to see how these ideas are pursued. However, I would take its grandiose claims about "discovering extropy" with a grain of salt, as at least one of the authors is known to be a bit of a crank!
I think the main qualitative difference between the two measures is that entropy is only defined up to a scalar, because it depends on a choice of base for the logarithm ($e$ and $2$ being common choices) whereas for $HHI$ there is a natural scaling factor of $1$.
It seems that HHI is a very reasonable thing to use as a measure of diversity. However, I can't shake the feeling that entropy is "better" in terms of theoretical properties (such as those listed in Wikipedia).
|
How is the Herfindahl-Hirschman index different from entropy?
A few comments. Let $P = (p_1, p_2, \ldots, p_N)$ be a probability distribution (so that $0 \le p_i \le 1$ and $\sum_i p_i = 1$).
The measures are conceptually very closely related. The entropy is t
|
46,459
|
How is the Herfindahl-Hirschman index different from entropy?
|
The first thing to notice is that each of these measures is in opposite directions, and they are also on different scales. In order to compare them in the same direction and scale, I am going to compare scaled versions of the negated HHI and entropy. Specifically, I will begin by comparing the following functions:
$$\begin{aligned}
R(\mathbf{p}) &\equiv \frac{n-1}{n} \bigg( 1 - \sum_{i=1}^n p_i^2 \bigg), \\[6pt]
S(\mathbf{p}) &\equiv - \frac{1}{\log n} \sum_{i=1}^n p_i \log p_i. \\[6pt]
\end{aligned}$$
The HHI and the entropy are affine transformations of these two functions, so if we compare these two scaled functions, we will get simple corresponding results for the measures of interest. To see why I have chosen to examine these two functions, consider the special input vectors $\mathbf{u} \equiv (\tfrac{1}{n},...,\tfrac{1}{n})$ (all probabilities equal) and $\mathbf{m} \equiv (1,0,...,0)$ (one probability dominating). At these extremes we have the following results:
$$\begin{matrix}
R(\mathbf{m}) = 0 & & & & R(\mathbf{u}) = 1, \\[6pt]
S(\mathbf{m}) = 0 & & & & S(\mathbf{u}) = 1. \\[6pt]
\end{matrix}$$
You can see from the above that the scaled functions I am using range between zero and one; they attain the zero value when one probability dominates the others and they attain unity when all the probabilities are equal. This means that both functions $R$ and $S$ are scaled measures of equality.
Rates-of-change of scaled equality measures: From the above forms of the functions, hopefully you can get a sense of the difference in the scaled measures. Below we will show the rates-of-change of the measures for a change in the probability vector. We will show that increasing a given probability will increase or decrease $R$ depending on whether that probability is below or above the arithmetic mean of the other probabilities. Contrarily, increasing a given probability will increase or decrease $S$ depending on whether that probability is below or above the geometric mean of the other probabilities.
We will examine rates-of-change as we alter one of the probabilities, with corresponding changes in other probabilities. To retain the norming requirement for the probability vector, we will consider that increasing the probability $p_k$ by some small amount $d p$ is accompanied by a corresponding change in all the other probabilties of $- \tfrac{1}{n-1} d p$. Thus, we have:
$$\frac{d p_i}{d p_k} = - \frac{1}{n-1}
\quad \quad \quad \text{for } i \neq k.$$
Using the chain rule for total derivatives, for any $\mathbb{p}$ in the interior of its allowable range we therefore have:
$$\begin{aligned}
\frac{d R}{d p_k} (\mathbf{p})
&= \sum_{i=1}^n \frac{d p_i}{d p_k} \cdot \frac{\partial R}{\partial p_i} (\mathbf{p}) \\[6pt]
&= \frac{\partial R}{\partial p_k} (\mathbf{p}) + \sum_{i \neq k} \frac{d p_i}{d p_k} \cdot \frac{\partial R}{\partial p_i} (\mathbf{p}) \\[6pt]
&= - \frac{n-1}{n} \cdot 2 p_k + \sum_{i \neq k} \frac{1}{n-1} \cdot \frac{n-1}{n} \cdot 2 p_i \\[6pt]
&= - 2 \cdot \frac{n-1}{n} \Bigg[ p_k - \frac{1}{n-1} \sum_{i \neq k} p_i \Bigg], \\[6pt]
\end{aligned}$$
and:
$$\begin{aligned}
\frac{d S}{d p_k} (\mathbf{p})
&= \sum_{i=1}^n \frac{d p_i}{d p_k} \cdot \frac{\partial S}{\partial p_i} (\mathbf{p}) \\[6pt]
&= \frac{\partial S}{\partial p_k} (\mathbf{p}) + \sum_{i \neq k} \frac{d p_i}{d p_k} \cdot \frac{\partial S}{\partial p_i} (\mathbf{p}) \\[6pt]
&= - \frac{1}{\log n} \Bigg[ (1 + \log p_k) - \frac{1}{n-1} \sum_{i \neq k} (1 + \log p_i) \Bigg] \\[6pt]
&= - \frac{1}{\log n} \Bigg[ \log p_k - \frac{1}{n-1} \sum_{i \neq k} \log p_i \Bigg]. \\[6pt]
\end{aligned}$$
We can see that the two measures have different "cross-over points" for when an increase to $p_k$ increases or decreases the measure. For the measure $R$ the cross-over point is where $p_k$ is equal to the arithmetic mean of the other probabilities; below this point, increasing $p_k$ increases the measured equality between the elements and so it increases $R$. For the measure $S$ the cross-over point is where $p_k$ is equal to the geometric mean of the other probabilities; below this point, increasing $p_k$ increases the measured equality between the elements and so it increases $R$.
Relative rates-of-change and limiting cases: Aside from having different "cross-over" points, the two measures also change at different rates relative to one another when we change $p_k$. For a small increase in the probability $p_k$ we have:
$$\frac{dR}{dS} (\mathbf{p}) = \frac{d R}{d p_k} (\mathbf{p}) \Bigg/ \frac{d S}{d p_k} (\mathbf{p}) = \frac{2 (n-1) \log n}{n} \cdot \frac{p_k - \frac{1}{n-1} \sum_{i \neq k} p_i}{\log p_k - \frac{1}{n-1} \sum_{i \neq k} \log p_i}.$$
It is useful to examing this relative rate-of-change in the extreme cases. In particular, we have:
$$\lim_{p_k \uparrow 1} \frac{dR}{dS} (\mathbf{p}) = 0
\quad \quad \quad
\lim_{p_k \downarrow 0} \frac{dR}{dS} (\mathbf{p}) = 2 \cdot \frac{n-1}{n} \cdot \frac{\log n}{\sum_{i \neq k} \log p_i}.$$
This shows that when $p_k$ is a dominating probability, which is near one, increasing it further will decrease $S$ much more rapidly than it decreases $R$. Contrarily, when $p_k$ is a dominated probability, which is near zero, increasing it increases $S$ much more rapidly than it increases $R$, and this is especially pronounced when $n$ is large.
|
How is the Herfindahl-Hirschman index different from entropy?
|
The first thing to notice is that each of these measures is in opposite directions, and they are also on different scales. In order to compare them in the same direction and scale, I am going to comp
|
How is the Herfindahl-Hirschman index different from entropy?
The first thing to notice is that each of these measures is in opposite directions, and they are also on different scales. In order to compare them in the same direction and scale, I am going to compare scaled versions of the negated HHI and entropy. Specifically, I will begin by comparing the following functions:
$$\begin{aligned}
R(\mathbf{p}) &\equiv \frac{n-1}{n} \bigg( 1 - \sum_{i=1}^n p_i^2 \bigg), \\[6pt]
S(\mathbf{p}) &\equiv - \frac{1}{\log n} \sum_{i=1}^n p_i \log p_i. \\[6pt]
\end{aligned}$$
The HHI and the entropy are affine transformations of these two functions, so if we compare these two scaled functions, we will get simple corresponding results for the measures of interest. To see why I have chosen to examine these two functions, consider the special input vectors $\mathbf{u} \equiv (\tfrac{1}{n},...,\tfrac{1}{n})$ (all probabilities equal) and $\mathbf{m} \equiv (1,0,...,0)$ (one probability dominating). At these extremes we have the following results:
$$\begin{matrix}
R(\mathbf{m}) = 0 & & & & R(\mathbf{u}) = 1, \\[6pt]
S(\mathbf{m}) = 0 & & & & S(\mathbf{u}) = 1. \\[6pt]
\end{matrix}$$
You can see from the above that the scaled functions I am using range between zero and one; they attain the zero value when one probability dominates the others and they attain unity when all the probabilities are equal. This means that both functions $R$ and $S$ are scaled measures of equality.
Rates-of-change of scaled equality measures: From the above forms of the functions, hopefully you can get a sense of the difference in the scaled measures. Below we will show the rates-of-change of the measures for a change in the probability vector. We will show that increasing a given probability will increase or decrease $R$ depending on whether that probability is below or above the arithmetic mean of the other probabilities. Contrarily, increasing a given probability will increase or decrease $S$ depending on whether that probability is below or above the geometric mean of the other probabilities.
We will examine rates-of-change as we alter one of the probabilities, with corresponding changes in other probabilities. To retain the norming requirement for the probability vector, we will consider that increasing the probability $p_k$ by some small amount $d p$ is accompanied by a corresponding change in all the other probabilties of $- \tfrac{1}{n-1} d p$. Thus, we have:
$$\frac{d p_i}{d p_k} = - \frac{1}{n-1}
\quad \quad \quad \text{for } i \neq k.$$
Using the chain rule for total derivatives, for any $\mathbb{p}$ in the interior of its allowable range we therefore have:
$$\begin{aligned}
\frac{d R}{d p_k} (\mathbf{p})
&= \sum_{i=1}^n \frac{d p_i}{d p_k} \cdot \frac{\partial R}{\partial p_i} (\mathbf{p}) \\[6pt]
&= \frac{\partial R}{\partial p_k} (\mathbf{p}) + \sum_{i \neq k} \frac{d p_i}{d p_k} \cdot \frac{\partial R}{\partial p_i} (\mathbf{p}) \\[6pt]
&= - \frac{n-1}{n} \cdot 2 p_k + \sum_{i \neq k} \frac{1}{n-1} \cdot \frac{n-1}{n} \cdot 2 p_i \\[6pt]
&= - 2 \cdot \frac{n-1}{n} \Bigg[ p_k - \frac{1}{n-1} \sum_{i \neq k} p_i \Bigg], \\[6pt]
\end{aligned}$$
and:
$$\begin{aligned}
\frac{d S}{d p_k} (\mathbf{p})
&= \sum_{i=1}^n \frac{d p_i}{d p_k} \cdot \frac{\partial S}{\partial p_i} (\mathbf{p}) \\[6pt]
&= \frac{\partial S}{\partial p_k} (\mathbf{p}) + \sum_{i \neq k} \frac{d p_i}{d p_k} \cdot \frac{\partial S}{\partial p_i} (\mathbf{p}) \\[6pt]
&= - \frac{1}{\log n} \Bigg[ (1 + \log p_k) - \frac{1}{n-1} \sum_{i \neq k} (1 + \log p_i) \Bigg] \\[6pt]
&= - \frac{1}{\log n} \Bigg[ \log p_k - \frac{1}{n-1} \sum_{i \neq k} \log p_i \Bigg]. \\[6pt]
\end{aligned}$$
We can see that the two measures have different "cross-over points" for when an increase to $p_k$ increases or decreases the measure. For the measure $R$ the cross-over point is where $p_k$ is equal to the arithmetic mean of the other probabilities; below this point, increasing $p_k$ increases the measured equality between the elements and so it increases $R$. For the measure $S$ the cross-over point is where $p_k$ is equal to the geometric mean of the other probabilities; below this point, increasing $p_k$ increases the measured equality between the elements and so it increases $R$.
Relative rates-of-change and limiting cases: Aside from having different "cross-over" points, the two measures also change at different rates relative to one another when we change $p_k$. For a small increase in the probability $p_k$ we have:
$$\frac{dR}{dS} (\mathbf{p}) = \frac{d R}{d p_k} (\mathbf{p}) \Bigg/ \frac{d S}{d p_k} (\mathbf{p}) = \frac{2 (n-1) \log n}{n} \cdot \frac{p_k - \frac{1}{n-1} \sum_{i \neq k} p_i}{\log p_k - \frac{1}{n-1} \sum_{i \neq k} \log p_i}.$$
It is useful to examing this relative rate-of-change in the extreme cases. In particular, we have:
$$\lim_{p_k \uparrow 1} \frac{dR}{dS} (\mathbf{p}) = 0
\quad \quad \quad
\lim_{p_k \downarrow 0} \frac{dR}{dS} (\mathbf{p}) = 2 \cdot \frac{n-1}{n} \cdot \frac{\log n}{\sum_{i \neq k} \log p_i}.$$
This shows that when $p_k$ is a dominating probability, which is near one, increasing it further will decrease $S$ much more rapidly than it decreases $R$. Contrarily, when $p_k$ is a dominated probability, which is near zero, increasing it increases $S$ much more rapidly than it increases $R$, and this is especially pronounced when $n$ is large.
|
How is the Herfindahl-Hirschman index different from entropy?
The first thing to notice is that each of these measures is in opposite directions, and they are also on different scales. In order to compare them in the same direction and scale, I am going to comp
|
46,460
|
How many tests should we do to estimate the percentage of people who contracted COVID-19 in Lombardy?
|
This is actually a handbook example of determining the sample size needed for estimating binomial proportion (e.g. Jones et al, 2004, Naing, 2003 for other references and examples).
First of all, to make it more precise, we are talking about finding such sample size, that with probability $\alpha$, the difference between the true probability of being infected $p$ and it's estimate $\hat p$ is not greater then $(100\times\delta\,)\%$
$$
\Pr(|p - \hat p| \le \delta p) = \alpha
$$
Given that the target population is large, we would usually assume binomial distribution to represent it, i.e. we say that it is large enough, that the chance of randomly sampling someone more then once is negligible. The distribution is parametrized by probability of "success" (here, probability of being infected) $p$ and the number of samples we draw $n$. Let's denote the observed number of infected people as $k$, in such case, $\hat p = k/n$ is the fraction of infected people in the sample and we treat it as an estimate of the number of infected people in the whole population. If we wanted to calculate confidence interval for $\hat p$, we could use normal approximation
$$
\hat p \pm z_\alpha \sqrt{\frac{\hat p(1-\hat p)}{n}}
$$
where $z_\alpha$ is the ordinate from standard normal distribution, where for $z$ drawn from standard normal distribution we have $\Pr(-z_\alpha < z < z_\alpha) = \alpha$. You are saying, that you'd like to see this interval to be equal to $\hat p \pm \delta p$. As discussed in the linked resources, you can solve this, so that for given $p$, precision $\delta$, and certanity $\alpha$, you can guesstimate the sample size needed
$$
n \approx \Big(\frac{z_\alpha}{\delta p}\Big)^2 \; p(1-p)
$$
Assuming $(100 \times \alpha)\% = 99\%$ confidence interval, we can plot this for different values of $p$, to find out that for $100 \times p > 4 \%$ the needed sample sizes are generally not much larger then $2000$ samples.
For example, for $p=0.04$ ($4\%$ infected) this yields:
> z <- function(alpha) qnorm(alpha)
> n <- function(p, alpha=0.99, delta=0.25) (z(alpha)/(p*delta))^2 * p*(1-p)
> n(0.04)
[1] 2078.167
To convince yourself, you can verify this by simulation, where you would draw $n$ samples from binomial distribution with probability of infection $p$, repeat this procedure $R$ times, and then verify how often was your result not further then $(100 \times \delta) \%$ from the true value:
> set.seed(123)
> sim <- function(p, n, delta, nsim=50000) mean(abs(p - rbinom(nsim, n, p)/n) / p <= delta)
> sim(0.04, 2078, 0.25)
[1] 0.97858
So we wanted to be $99\%$ sure and the approximation gives us, while the in the simulation, in $97.8\%$ cases the result was within the interval. Not bad.
Notice that this is just a simple approximation for the calculation, assuming simple random sampling. In case of whole population locked in their houses, sampling individuals at random may be not as hard as in case of most of the usual surveys. On another hand, things may not go as smooth as planned, or you may be willing to use other sampling schema, to have higher chance for it being representative, what would make calculating it more complicated. Moreover, the tests used aren't perfect and give false results as described, for example by New York Times, or Washington Post, and you'd need to account for that as well. Also you need to remember, there were many examples where such simple problems get more complicated then expected, e.g. social surveys on Trump's support before the election got very wrong, nonetheless that they used state of art survey methodology.
|
How many tests should we do to estimate the percentage of people who contracted COVID-19 in Lombardy
|
This is actually a handbook example of determining the sample size needed for estimating binomial proportion (e.g. Jones et al, 2004, Naing, 2003 for other references and examples).
First of all, to m
|
How many tests should we do to estimate the percentage of people who contracted COVID-19 in Lombardy?
This is actually a handbook example of determining the sample size needed for estimating binomial proportion (e.g. Jones et al, 2004, Naing, 2003 for other references and examples).
First of all, to make it more precise, we are talking about finding such sample size, that with probability $\alpha$, the difference between the true probability of being infected $p$ and it's estimate $\hat p$ is not greater then $(100\times\delta\,)\%$
$$
\Pr(|p - \hat p| \le \delta p) = \alpha
$$
Given that the target population is large, we would usually assume binomial distribution to represent it, i.e. we say that it is large enough, that the chance of randomly sampling someone more then once is negligible. The distribution is parametrized by probability of "success" (here, probability of being infected) $p$ and the number of samples we draw $n$. Let's denote the observed number of infected people as $k$, in such case, $\hat p = k/n$ is the fraction of infected people in the sample and we treat it as an estimate of the number of infected people in the whole population. If we wanted to calculate confidence interval for $\hat p$, we could use normal approximation
$$
\hat p \pm z_\alpha \sqrt{\frac{\hat p(1-\hat p)}{n}}
$$
where $z_\alpha$ is the ordinate from standard normal distribution, where for $z$ drawn from standard normal distribution we have $\Pr(-z_\alpha < z < z_\alpha) = \alpha$. You are saying, that you'd like to see this interval to be equal to $\hat p \pm \delta p$. As discussed in the linked resources, you can solve this, so that for given $p$, precision $\delta$, and certanity $\alpha$, you can guesstimate the sample size needed
$$
n \approx \Big(\frac{z_\alpha}{\delta p}\Big)^2 \; p(1-p)
$$
Assuming $(100 \times \alpha)\% = 99\%$ confidence interval, we can plot this for different values of $p$, to find out that for $100 \times p > 4 \%$ the needed sample sizes are generally not much larger then $2000$ samples.
For example, for $p=0.04$ ($4\%$ infected) this yields:
> z <- function(alpha) qnorm(alpha)
> n <- function(p, alpha=0.99, delta=0.25) (z(alpha)/(p*delta))^2 * p*(1-p)
> n(0.04)
[1] 2078.167
To convince yourself, you can verify this by simulation, where you would draw $n$ samples from binomial distribution with probability of infection $p$, repeat this procedure $R$ times, and then verify how often was your result not further then $(100 \times \delta) \%$ from the true value:
> set.seed(123)
> sim <- function(p, n, delta, nsim=50000) mean(abs(p - rbinom(nsim, n, p)/n) / p <= delta)
> sim(0.04, 2078, 0.25)
[1] 0.97858
So we wanted to be $99\%$ sure and the approximation gives us, while the in the simulation, in $97.8\%$ cases the result was within the interval. Not bad.
Notice that this is just a simple approximation for the calculation, assuming simple random sampling. In case of whole population locked in their houses, sampling individuals at random may be not as hard as in case of most of the usual surveys. On another hand, things may not go as smooth as planned, or you may be willing to use other sampling schema, to have higher chance for it being representative, what would make calculating it more complicated. Moreover, the tests used aren't perfect and give false results as described, for example by New York Times, or Washington Post, and you'd need to account for that as well. Also you need to remember, there were many examples where such simple problems get more complicated then expected, e.g. social surveys on Trump's support before the election got very wrong, nonetheless that they used state of art survey methodology.
|
How many tests should we do to estimate the percentage of people who contracted COVID-19 in Lombardy
This is actually a handbook example of determining the sample size needed for estimating binomial proportion (e.g. Jones et al, 2004, Naing, 2003 for other references and examples).
First of all, to m
|
46,461
|
What is the meaning of $\sqrt{\mathrm{var}(X)\mathrm{var}(P)-[\mathrm{cov}(X,P)]^2}$?
|
It is the square root of the determinant of the covariance matrix (between $X$ and $P$). The determinant of the covariance matrix is called as Generalized Variance, which quantifies the co-variability of multivariate random variables to a scalar. What you write is the square root of it, so I believe it won't be too odd to call it as Generalized Deviation.
Edit: After some research, I found that, in some contexts, it's referred as Generalized Standard Deviation, or Wilk's standard deviation.
|
What is the meaning of $\sqrt{\mathrm{var}(X)\mathrm{var}(P)-[\mathrm{cov}(X,P)]^2}$?
|
It is the square root of the determinant of the covariance matrix (between $X$ and $P$). The determinant of the covariance matrix is called as Generalized Variance, which quantifies the co-variability
|
What is the meaning of $\sqrt{\mathrm{var}(X)\mathrm{var}(P)-[\mathrm{cov}(X,P)]^2}$?
It is the square root of the determinant of the covariance matrix (between $X$ and $P$). The determinant of the covariance matrix is called as Generalized Variance, which quantifies the co-variability of multivariate random variables to a scalar. What you write is the square root of it, so I believe it won't be too odd to call it as Generalized Deviation.
Edit: After some research, I found that, in some contexts, it's referred as Generalized Standard Deviation, or Wilk's standard deviation.
|
What is the meaning of $\sqrt{\mathrm{var}(X)\mathrm{var}(P)-[\mathrm{cov}(X,P)]^2}$?
It is the square root of the determinant of the covariance matrix (between $X$ and $P$). The determinant of the covariance matrix is called as Generalized Variance, which quantifies the co-variability
|
46,462
|
Least Squares removing first $k$ observations Woodbury formula?
|
You've basically laid out the key facts, I think you just need a hint on how to fit them all together. Here's a quick-and-dirty overview.
I think it's easier to see how to accomplish your goal if you build up from the Sherman-Morrison formula, which is just a special case of the Woodbury matrix identity. The Sherman-Morrison formula is a rank-1 update, while the Woodbury identity is a rank-$r$ update.
We have a matrix $X_{n \times p}$ with $n$ samples/observations of $p$ variables/features and $X$ is full rank. The product $X^\top X$ can be viewed as a sum of outer products. Denote $x_j$ the $j$th column of $X^\top$ (i.e. the transpose of the $j$th row of $X$). Suppose we leave out one row $k$. We have
$$
\begin{align}
X^\top X &= \sum_j x_j x_j^\top \\
&= x_k x_k^\top + \sum_{j\neq k} x_j x_j^\top \\
X^\top X - x_k x_k^\top &= \sum_{j\neq k} x_j x_j^\top.
\end{align}
$$
Relating this to the Sherman-Morrison formula can be done by inspection. Sherman-Morrison gives us
$$
(A + uv^\top)^{-1} = A^{-1} - \frac{A^{-1}uv^\top A^{-1}}{1+v^\top A^{-1} u},
$$
so we just need to make appropriate substitutions:
$$
\begin{align}
A &= X^\top X \\
u &= -x_k \\
v^\top &= x_k^\top.
\end{align}
$$
And of course we can repeat this for $r > 1$ indices and then we are splitting $A=X^\top X$ into the sum of two non-empty sets of outer products, $k\in \mathcal{S}$ and its complement. This leads us to the Woodbury identity, because now we have a rank-$r$ update to $A$. (Naturally, we can't leave out too many rows because then we have non-invertible matrix problems, and the procedure will blow up if the "denominator" is too close to 0, signaling that removing these rows is causing the matrix to become ill-conditioned.)
So the Woodbury identity will use
$$\begin{aligned}
C &= I_{r\times r}\\
U &= -X_{k\in\mathcal{S}}^\top \\
V &= X_{k\in\mathcal{S}}.
\end{aligned}$$
One caveat here is that we haven't characterized the loss of precision incurred by using floating-point arithmetic. Before implementing this in code, I would recommend studying the numerical conditioning of this procedure.
A colleague observes that eventually, for $r=|\mathcal{S}|$ too large, this becomes more expensive than the original problem. A better alternative is to form a QR factorization. This procedure is faster and more accurate and has its own update capabilities. I believe this is outlined in Golub & van Loan but I don't have my copy handy.
|
Least Squares removing first $k$ observations Woodbury formula?
|
You've basically laid out the key facts, I think you just need a hint on how to fit them all together. Here's a quick-and-dirty overview.
I think it's easier to see how to accomplish your goal if you
|
Least Squares removing first $k$ observations Woodbury formula?
You've basically laid out the key facts, I think you just need a hint on how to fit them all together. Here's a quick-and-dirty overview.
I think it's easier to see how to accomplish your goal if you build up from the Sherman-Morrison formula, which is just a special case of the Woodbury matrix identity. The Sherman-Morrison formula is a rank-1 update, while the Woodbury identity is a rank-$r$ update.
We have a matrix $X_{n \times p}$ with $n$ samples/observations of $p$ variables/features and $X$ is full rank. The product $X^\top X$ can be viewed as a sum of outer products. Denote $x_j$ the $j$th column of $X^\top$ (i.e. the transpose of the $j$th row of $X$). Suppose we leave out one row $k$. We have
$$
\begin{align}
X^\top X &= \sum_j x_j x_j^\top \\
&= x_k x_k^\top + \sum_{j\neq k} x_j x_j^\top \\
X^\top X - x_k x_k^\top &= \sum_{j\neq k} x_j x_j^\top.
\end{align}
$$
Relating this to the Sherman-Morrison formula can be done by inspection. Sherman-Morrison gives us
$$
(A + uv^\top)^{-1} = A^{-1} - \frac{A^{-1}uv^\top A^{-1}}{1+v^\top A^{-1} u},
$$
so we just need to make appropriate substitutions:
$$
\begin{align}
A &= X^\top X \\
u &= -x_k \\
v^\top &= x_k^\top.
\end{align}
$$
And of course we can repeat this for $r > 1$ indices and then we are splitting $A=X^\top X$ into the sum of two non-empty sets of outer products, $k\in \mathcal{S}$ and its complement. This leads us to the Woodbury identity, because now we have a rank-$r$ update to $A$. (Naturally, we can't leave out too many rows because then we have non-invertible matrix problems, and the procedure will blow up if the "denominator" is too close to 0, signaling that removing these rows is causing the matrix to become ill-conditioned.)
So the Woodbury identity will use
$$\begin{aligned}
C &= I_{r\times r}\\
U &= -X_{k\in\mathcal{S}}^\top \\
V &= X_{k\in\mathcal{S}}.
\end{aligned}$$
One caveat here is that we haven't characterized the loss of precision incurred by using floating-point arithmetic. Before implementing this in code, I would recommend studying the numerical conditioning of this procedure.
A colleague observes that eventually, for $r=|\mathcal{S}|$ too large, this becomes more expensive than the original problem. A better alternative is to form a QR factorization. This procedure is faster and more accurate and has its own update capabilities. I believe this is outlined in Golub & van Loan but I don't have my copy handy.
|
Least Squares removing first $k$ observations Woodbury formula?
You've basically laid out the key facts, I think you just need a hint on how to fit them all together. Here's a quick-and-dirty overview.
I think it's easier to see how to accomplish your goal if you
|
46,463
|
Least Squares removing first $k$ observations Woodbury formula?
|
Over here and here, the leave-one-out (LOOCV) formula uses Sherman-Morrison formula in its derivation. Deriving the leave-$k$-out would require the general formula by Woodbury, as you have suspected.
Here I use subscript $k$ as the indices for the rows to be left out from the training set, $(k)$ as the whole vector or matrix without the rows from $k$, and $[k]$ for submatrix containing only rows and columns from $k$. For convenience, the following matrices are defined
$$
\begin{aligned}
A &= X^TX \\
A_{(k)} &= X_{(k)}^TX_{(k)} \\
A_k &= X_k^TX_k \\
H &= XA^{-1}X^T \\
H_{[k]} &= X_kA^{-1}X_k^T
\end{aligned}
$$
$H$ is the so-called hat matrix, while $H_{[k]}$ is a submatrix of $H$. The original residual and the individual leave-$k$ out errors are described by
$$
\begin{align}
e_k&=z_k-X_k\hat\beta \\
e_{(k)}&=z_k-X_k\hat\beta_{(k)}\tag{1}\label{ek}
\end{align}
$$
where
$$
\hat\beta_{(k)}=A_{(k)}^{-1}X_{(k)}^Tz_{(k)}\tag{2}\label{beta1}
$$
We have the following identities
$$
\begin{align}
A_{(k)}=A-A_k \\
X_{(k)}^Tz_{(k)}=X^Tz-X_k^Tz_k \tag{3}\label{Xzk}
\end{align}
$$
From Woodbury identity we have the following
$$
\begin{aligned}
A_{(k)}^{-1}&=A^{-1}+A^{-1}X_k^T(I-X_k^TA^{-1}X_k)^{-1}X_kA^{-1}\\
&=A^{-1}+A^{-1}X_k^T(I-H_{[k]})^{-1}X_kA^{-1}
\end{aligned}
$$
Left multiplying $X_k$ gives us
$$
\begin{aligned}
X_kA_{(k)}^{-1}&=X_kA^{-1}+H_{[k]}(I-H_{[k]})^{-1}X_kA^{-1} \\
&=(I-H_{[k]})(I-H_{[k]})^{-1}X_kA^{-1}+H_{[k]}(I-H_{[k]})^{-1}X_kA^{-1} \\
&=(I-H_{[k]})^{-1}X_kA^{-1}
\end{aligned}
$$
Substituting $\eqref{Xzk}$ into $\eqref{beta1}$, we have from the above equation
$$
\begin{aligned}
X_k\hat\beta_{(k)}&=(I-H_{[k]})^{-1}X_kA^{-1}(X^Tz-X_k^Tz_k) \\
&= (I-H_{[k]})^{-1}(X_k\hat\beta - H_{[k]}z_k) \\
&= (I-H_{[k]})^{-1}(X_k\hat\beta - H_{[k]}z_k)
\end{aligned}
$$
This is finally inserted into the leave out formula $\eqref{ek}$ to get
$$
\begin{aligned}
e_{(k)} &= z_k-(I-H_{[k]})^{-1}(X_k\hat\beta - H_{[k]}z_k) \\
&= (I-H_{[k]})^{-1}\left[(I-H_{[k]})z_k-X_k\hat\beta+H_{[k]}z_k\right]\\
&= (I-H_{[k]})^{-1}(z_k-X_k\hat\beta) \\
&= (I-H_{[k]})^{-1}e_k
\end{aligned}
$$
which can be calculated by solving the following matrix equation to avoid the costly matrix inversion
$$
(I-H_{[k]})e_{(k)} = e_k
$$
Unlike the LOOCV formula which had only scalars, solving the above may not be as cheap, depending on the size of $k$.
Extra note regarding $H_{[k]}$: $H$ can be very big. If you have $n$ points, the size is $n\times n$. Fortunately, you don't need the whole matrix to calculate the submatrix. If $\hat\beta$ is written as follows
$$
\begin{aligned}
\hat\beta &= Mz \\
M &= A^{-1}X^T \\
\end{aligned}
$$
Then $M$ is typically determined by solving the following system
$$
AM = X^T
$$
The size of $B$ is $n\times m$, where $m$ is the number of bases. From here you can compute
$$
H_{[k]} = X_{k}M_k
$$
where $M_k$ are the columns from $M$ with the indices in $k$.
Another method is to use eigendecomposition on $X^TX$
$$
X^TX = PDP^T
$$
so that its inverse can calculated as
$$
(X^TX)^{-1} = PD^{-1}P^T
$$
Defining $Q=XP$, and $Q_{[k]}$ its $k$ rows, the hat matrix and its partial submatrix can be calculated as
$$
\begin{aligned}
H &= XPD^{-1}P^TX^T = QD^{-1}Q^T \\
H_{[k]} &= Q_{[k]}D^{-1}Q_{[k]}^T
\end{aligned}
$$
Of course, calculating eigendecomposition can still be expensive, and so is solving for $e_{(k)}$.
Therefore, this method is only worthwhile if the number of folds is large enough
compared to the data points. If the data is large, it might be better to stick with
the naive method for your typical 10-fold CV.
Here are some plots comparing the two approaches, for several folds and design matrix sizes.
(The code for the benchmark can be found here)
|
Least Squares removing first $k$ observations Woodbury formula?
|
Over here and here, the leave-one-out (LOOCV) formula uses Sherman-Morrison formula in its derivation. Deriving the leave-$k$-out would require the general formula by Woodbury, as you have suspected.
|
Least Squares removing first $k$ observations Woodbury formula?
Over here and here, the leave-one-out (LOOCV) formula uses Sherman-Morrison formula in its derivation. Deriving the leave-$k$-out would require the general formula by Woodbury, as you have suspected.
Here I use subscript $k$ as the indices for the rows to be left out from the training set, $(k)$ as the whole vector or matrix without the rows from $k$, and $[k]$ for submatrix containing only rows and columns from $k$. For convenience, the following matrices are defined
$$
\begin{aligned}
A &= X^TX \\
A_{(k)} &= X_{(k)}^TX_{(k)} \\
A_k &= X_k^TX_k \\
H &= XA^{-1}X^T \\
H_{[k]} &= X_kA^{-1}X_k^T
\end{aligned}
$$
$H$ is the so-called hat matrix, while $H_{[k]}$ is a submatrix of $H$. The original residual and the individual leave-$k$ out errors are described by
$$
\begin{align}
e_k&=z_k-X_k\hat\beta \\
e_{(k)}&=z_k-X_k\hat\beta_{(k)}\tag{1}\label{ek}
\end{align}
$$
where
$$
\hat\beta_{(k)}=A_{(k)}^{-1}X_{(k)}^Tz_{(k)}\tag{2}\label{beta1}
$$
We have the following identities
$$
\begin{align}
A_{(k)}=A-A_k \\
X_{(k)}^Tz_{(k)}=X^Tz-X_k^Tz_k \tag{3}\label{Xzk}
\end{align}
$$
From Woodbury identity we have the following
$$
\begin{aligned}
A_{(k)}^{-1}&=A^{-1}+A^{-1}X_k^T(I-X_k^TA^{-1}X_k)^{-1}X_kA^{-1}\\
&=A^{-1}+A^{-1}X_k^T(I-H_{[k]})^{-1}X_kA^{-1}
\end{aligned}
$$
Left multiplying $X_k$ gives us
$$
\begin{aligned}
X_kA_{(k)}^{-1}&=X_kA^{-1}+H_{[k]}(I-H_{[k]})^{-1}X_kA^{-1} \\
&=(I-H_{[k]})(I-H_{[k]})^{-1}X_kA^{-1}+H_{[k]}(I-H_{[k]})^{-1}X_kA^{-1} \\
&=(I-H_{[k]})^{-1}X_kA^{-1}
\end{aligned}
$$
Substituting $\eqref{Xzk}$ into $\eqref{beta1}$, we have from the above equation
$$
\begin{aligned}
X_k\hat\beta_{(k)}&=(I-H_{[k]})^{-1}X_kA^{-1}(X^Tz-X_k^Tz_k) \\
&= (I-H_{[k]})^{-1}(X_k\hat\beta - H_{[k]}z_k) \\
&= (I-H_{[k]})^{-1}(X_k\hat\beta - H_{[k]}z_k)
\end{aligned}
$$
This is finally inserted into the leave out formula $\eqref{ek}$ to get
$$
\begin{aligned}
e_{(k)} &= z_k-(I-H_{[k]})^{-1}(X_k\hat\beta - H_{[k]}z_k) \\
&= (I-H_{[k]})^{-1}\left[(I-H_{[k]})z_k-X_k\hat\beta+H_{[k]}z_k\right]\\
&= (I-H_{[k]})^{-1}(z_k-X_k\hat\beta) \\
&= (I-H_{[k]})^{-1}e_k
\end{aligned}
$$
which can be calculated by solving the following matrix equation to avoid the costly matrix inversion
$$
(I-H_{[k]})e_{(k)} = e_k
$$
Unlike the LOOCV formula which had only scalars, solving the above may not be as cheap, depending on the size of $k$.
Extra note regarding $H_{[k]}$: $H$ can be very big. If you have $n$ points, the size is $n\times n$. Fortunately, you don't need the whole matrix to calculate the submatrix. If $\hat\beta$ is written as follows
$$
\begin{aligned}
\hat\beta &= Mz \\
M &= A^{-1}X^T \\
\end{aligned}
$$
Then $M$ is typically determined by solving the following system
$$
AM = X^T
$$
The size of $B$ is $n\times m$, where $m$ is the number of bases. From here you can compute
$$
H_{[k]} = X_{k}M_k
$$
where $M_k$ are the columns from $M$ with the indices in $k$.
Another method is to use eigendecomposition on $X^TX$
$$
X^TX = PDP^T
$$
so that its inverse can calculated as
$$
(X^TX)^{-1} = PD^{-1}P^T
$$
Defining $Q=XP$, and $Q_{[k]}$ its $k$ rows, the hat matrix and its partial submatrix can be calculated as
$$
\begin{aligned}
H &= XPD^{-1}P^TX^T = QD^{-1}Q^T \\
H_{[k]} &= Q_{[k]}D^{-1}Q_{[k]}^T
\end{aligned}
$$
Of course, calculating eigendecomposition can still be expensive, and so is solving for $e_{(k)}$.
Therefore, this method is only worthwhile if the number of folds is large enough
compared to the data points. If the data is large, it might be better to stick with
the naive method for your typical 10-fold CV.
Here are some plots comparing the two approaches, for several folds and design matrix sizes.
(The code for the benchmark can be found here)
|
Least Squares removing first $k$ observations Woodbury formula?
Over here and here, the leave-one-out (LOOCV) formula uses Sherman-Morrison formula in its derivation. Deriving the leave-$k$-out would require the general formula by Woodbury, as you have suspected.
|
46,464
|
Probability of drawing the unfair die
|
The question seeks to find the probability that the die drawn is unfair given that it was thrown $5$ times and all throws were $3$s. Hence, we seek to calculate $\mathrm{P}(\mathrm{Unfair}\,|\,\text{5 threes})$. According to Bayes' theorem, we have:
$$
\mathrm{P}(\mathrm{Unfair}\,|\,\text{5 threes}) = \frac{\mathrm{P}(\text{5 threes}\,|\,\mathrm{Unfair})\cdot \mathrm{P}(\mathrm{Unfair})}{\mathrm{P}(\text{5 threes}\,|\,\mathrm{Fair})\cdot \mathrm{P}(\mathrm{Fair}) + \mathrm{P}(\text{5 threes}\,|\,\text{Unfair})\cdot \mathrm{P}(\text{Unfair})}
$$
Now what's the probability to get $5$ $3$s when you picked the unfair die? Well it's $1$ (100%) so $\mathrm{P}(\text{5 threes}\,|\,\text{Unfair}) = 1$ because it always shows a $3$. What's the probability of getting $5$ $3$s when you picked a fair die? It's $(1/6)^5$, so $\mathrm{P}(\text{5 threes}\,|\,\mathrm{Fair}) = (1/6)^5$.
All that's missing are the probabilities of picking a fair or an unfair die. Figure those out and put all values in the formula to get the answer. Can you take it from here?
I find it interesting to plot how the posterior probability of having picked the unfair die depends on the number of $3$s we got. Here is the plot:
So if we throw the die once and get a $3$, the posterior probability is $0.4$ that the die is unfair. After 2 throws, both being $3$s, it's already $0.8$ and after three throws, all of them being $3$s, it's $0.96$.
|
Probability of drawing the unfair die
|
The question seeks to find the probability that the die drawn is unfair given that it was thrown $5$ times and all throws were $3$s. Hence, we seek to calculate $\mathrm{P}(\mathrm{Unfair}\,|\,\text{5
|
Probability of drawing the unfair die
The question seeks to find the probability that the die drawn is unfair given that it was thrown $5$ times and all throws were $3$s. Hence, we seek to calculate $\mathrm{P}(\mathrm{Unfair}\,|\,\text{5 threes})$. According to Bayes' theorem, we have:
$$
\mathrm{P}(\mathrm{Unfair}\,|\,\text{5 threes}) = \frac{\mathrm{P}(\text{5 threes}\,|\,\mathrm{Unfair})\cdot \mathrm{P}(\mathrm{Unfair})}{\mathrm{P}(\text{5 threes}\,|\,\mathrm{Fair})\cdot \mathrm{P}(\mathrm{Fair}) + \mathrm{P}(\text{5 threes}\,|\,\text{Unfair})\cdot \mathrm{P}(\text{Unfair})}
$$
Now what's the probability to get $5$ $3$s when you picked the unfair die? Well it's $1$ (100%) so $\mathrm{P}(\text{5 threes}\,|\,\text{Unfair}) = 1$ because it always shows a $3$. What's the probability of getting $5$ $3$s when you picked a fair die? It's $(1/6)^5$, so $\mathrm{P}(\text{5 threes}\,|\,\mathrm{Fair}) = (1/6)^5$.
All that's missing are the probabilities of picking a fair or an unfair die. Figure those out and put all values in the formula to get the answer. Can you take it from here?
I find it interesting to plot how the posterior probability of having picked the unfair die depends on the number of $3$s we got. Here is the plot:
So if we throw the die once and get a $3$, the posterior probability is $0.4$ that the die is unfair. After 2 throws, both being $3$s, it's already $0.8$ and after three throws, all of them being $3$s, it's $0.96$.
|
Probability of drawing the unfair die
The question seeks to find the probability that the die drawn is unfair given that it was thrown $5$ times and all throws were $3$s. Hence, we seek to calculate $\mathrm{P}(\mathrm{Unfair}\,|\,\text{5
|
46,465
|
Probability of drawing the unfair die
|
According to Bayes’ theorem:
P(A | B) = ( P(A) * P(B | A) ) / ( P(A) * P(B | A) + P(not A) * P(B | not A) )
P(A) = P(unfair) = 1 / 10
P(not A) = P(fair) = 9 / 10
P(B | A) = P(5 threes | unfair) = 1
P(B | not A) = P(5 threes | fair) = 1 / (6^5)
P(A | B) = ( 1 / 10 * 1 ) / ( 1 / 10 * 1 + 9 /10 * (1 / (6**5) ) )
P(A | B) = 0.9988439306358382
P(B) = P(5 threes) = P(A) * P(B | A) + P(not A) * P(B | not A)
P(B) = 0.10011574074074074
|
Probability of drawing the unfair die
|
According to Bayes’ theorem:
P(A | B) = ( P(A) * P(B | A) ) / ( P(A) * P(B | A) + P(not A) * P(B | not A) )
P(A) = P(unfair) = 1 / 10
P(not A) = P(fair) = 9 / 10
P(B | A) = P(5 threes | unfair
|
Probability of drawing the unfair die
According to Bayes’ theorem:
P(A | B) = ( P(A) * P(B | A) ) / ( P(A) * P(B | A) + P(not A) * P(B | not A) )
P(A) = P(unfair) = 1 / 10
P(not A) = P(fair) = 9 / 10
P(B | A) = P(5 threes | unfair) = 1
P(B | not A) = P(5 threes | fair) = 1 / (6^5)
P(A | B) = ( 1 / 10 * 1 ) / ( 1 / 10 * 1 + 9 /10 * (1 / (6**5) ) )
P(A | B) = 0.9988439306358382
P(B) = P(5 threes) = P(A) * P(B | A) + P(not A) * P(B | not A)
P(B) = 0.10011574074074074
|
Probability of drawing the unfair die
According to Bayes’ theorem:
P(A | B) = ( P(A) * P(B | A) ) / ( P(A) * P(B | A) + P(not A) * P(B | not A) )
P(A) = P(unfair) = 1 / 10
P(not A) = P(fair) = 9 / 10
P(B | A) = P(5 threes | unfair
|
46,466
|
Recurring problem with retrospective data collection study designs I'm seeing
|
You are right that this is a very common scenario in medical research.
"I should note that these studies are not meant to invent a new method of treatment or change protocols, they are used to see what variables are of interest for future research."
OK, I take this to mean that you are interested in causal inference, not in prediction.
And from the comments:
"We have statisticians available to us. They suggest pooling variables with P<0.2 from a univariate regression of all variables, into a new multiple regression and report the variables under alpha in that 2nd regression model."
This is not advisable. For one thing, mediators will be associated with the outcome, which you should not be adjusting for. You might also end up adjusting for colliders and actually invoking otherwise non-present confounding. See here for things that can go wrong when including variables that have no business being in a regression model.
I am sorry to say that there is no substitute for expert knowledge about the subject matter when it comes to causal inference. It is really as simple as that. "Expert" is relative term. You don't have to have a PhD in the field. I thought I read in another post that you are a medical doctor nearing the end of your training. I would have thought that you would be able to come up with a plausible DAG for many scenarios. I have been involved in teaching these things to undergraduate medics for a number of years and I usually find that they are able to construct plausible DAGs quite well. It is normal for different people to come up with different DAGs because they make different abstractions and assumptions about the data. Also, when they are completely stumped they are usually able to find information online or from other resources to help and inform their DAGs.
|
Recurring problem with retrospective data collection study designs I'm seeing
|
You are right that this is a very common scenario in medical research.
"I should note that these studies are not meant to invent a new method of treatment or change protocols, they are used to see wh
|
Recurring problem with retrospective data collection study designs I'm seeing
You are right that this is a very common scenario in medical research.
"I should note that these studies are not meant to invent a new method of treatment or change protocols, they are used to see what variables are of interest for future research."
OK, I take this to mean that you are interested in causal inference, not in prediction.
And from the comments:
"We have statisticians available to us. They suggest pooling variables with P<0.2 from a univariate regression of all variables, into a new multiple regression and report the variables under alpha in that 2nd regression model."
This is not advisable. For one thing, mediators will be associated with the outcome, which you should not be adjusting for. You might also end up adjusting for colliders and actually invoking otherwise non-present confounding. See here for things that can go wrong when including variables that have no business being in a regression model.
I am sorry to say that there is no substitute for expert knowledge about the subject matter when it comes to causal inference. It is really as simple as that. "Expert" is relative term. You don't have to have a PhD in the field. I thought I read in another post that you are a medical doctor nearing the end of your training. I would have thought that you would be able to come up with a plausible DAG for many scenarios. I have been involved in teaching these things to undergraduate medics for a number of years and I usually find that they are able to construct plausible DAGs quite well. It is normal for different people to come up with different DAGs because they make different abstractions and assumptions about the data. Also, when they are completely stumped they are usually able to find information online or from other resources to help and inform their DAGs.
|
Recurring problem with retrospective data collection study designs I'm seeing
You are right that this is a very common scenario in medical research.
"I should note that these studies are not meant to invent a new method of treatment or change protocols, they are used to see wh
|
46,467
|
Reverse causality opposite definitions
|
Reverse causality is particularly problematic for DAGs because it often implies either a reversal of a causal path, or feedback loop (which would make it a Directed Cyclic Graph) rendering the usual DAG analysis invalid.
Nevertheless, a lot can still be said using DAGs even where reverse causality is present or suspected. You say
yet all claim that exactly their structure is the reverse causality:
They don't claim that their DAG structure is the one and only structure for reverse causality, only that it is one example of reverse causality.
In the first case, I don't agree that this is reverse causality. Renal failure and analgesics are both caused by diabetes and so this is a case of confounding, not reverse causality. I don't see any justification for drawing the arrow in the direction that they did. I would expect the dotted line to have no arrowhead at all, indicating that the two are correlated.
In the second case, the DAG a generic one, often seen in cases of unmeasured confounding. Again, I don't agree that there is any reverse causality, even from their description:
subclinical disease U results both in lack of exercise A and an increased risk of clinical disease Y . This form of confounding is often referred to as reverse causation
when L is unknown.
I don't agree with this. When L is also unobserved, U directly causes A and Y, which again is they standard definition of confounding. For a higher U, there is lower exercise and increased risk of death, Y. I don't see any reverse causality in this argument.
The third case is interesting because it has a bidirectional arc (causal effect pointing in both ways, which means it is not a DAG. Anyway, that is what I usually understand as reverse causality. Smoking causes cancer later in life. This is uncontroversial. However, a smoker who is diagnosed with lung cancer then reduces or stops their smoking as a direct consequence of being diagnosed, hence the arrow is also pointing the other way. One way to understand this is to realise that it isn't Lung Cancer itself which causes them to stop smoking. It is the diagnosis. Lung Cancer was already present before the diagnosis. The diagnosis is also not caused by lung cancer, rather it is the symptoms that lung cancer causes which then cause the patient to get the diagnosis, and it is the diagnosis which causes the reduction or cessation of smoking:
Of course this is still a problem in DAG theory because we now have a feedback loop due to diagnosis causing smoking. One way to resolve this is to split the smoking variable into Smoking prior to diagnosis and smoking after diagnosis:
One advantage to this, other than preserving the acyclicity, is that it preserves the temporal nature of the DAG - that is, variables occurring earlier in time are on the left and those occurring later are on the right. This explicitly recognises one of the defining characteristics of causality: In order for something to be a cause, it MUST occur before the thing which it is a cause of. This isn't something that is enforced in DAG theory, but it is a very good practice that can help in situations like this.
|
Reverse causality opposite definitions
|
Reverse causality is particularly problematic for DAGs because it often implies either a reversal of a causal path, or feedback loop (which would make it a Directed Cyclic Graph) rendering the usual D
|
Reverse causality opposite definitions
Reverse causality is particularly problematic for DAGs because it often implies either a reversal of a causal path, or feedback loop (which would make it a Directed Cyclic Graph) rendering the usual DAG analysis invalid.
Nevertheless, a lot can still be said using DAGs even where reverse causality is present or suspected. You say
yet all claim that exactly their structure is the reverse causality:
They don't claim that their DAG structure is the one and only structure for reverse causality, only that it is one example of reverse causality.
In the first case, I don't agree that this is reverse causality. Renal failure and analgesics are both caused by diabetes and so this is a case of confounding, not reverse causality. I don't see any justification for drawing the arrow in the direction that they did. I would expect the dotted line to have no arrowhead at all, indicating that the two are correlated.
In the second case, the DAG a generic one, often seen in cases of unmeasured confounding. Again, I don't agree that there is any reverse causality, even from their description:
subclinical disease U results both in lack of exercise A and an increased risk of clinical disease Y . This form of confounding is often referred to as reverse causation
when L is unknown.
I don't agree with this. When L is also unobserved, U directly causes A and Y, which again is they standard definition of confounding. For a higher U, there is lower exercise and increased risk of death, Y. I don't see any reverse causality in this argument.
The third case is interesting because it has a bidirectional arc (causal effect pointing in both ways, which means it is not a DAG. Anyway, that is what I usually understand as reverse causality. Smoking causes cancer later in life. This is uncontroversial. However, a smoker who is diagnosed with lung cancer then reduces or stops their smoking as a direct consequence of being diagnosed, hence the arrow is also pointing the other way. One way to understand this is to realise that it isn't Lung Cancer itself which causes them to stop smoking. It is the diagnosis. Lung Cancer was already present before the diagnosis. The diagnosis is also not caused by lung cancer, rather it is the symptoms that lung cancer causes which then cause the patient to get the diagnosis, and it is the diagnosis which causes the reduction or cessation of smoking:
Of course this is still a problem in DAG theory because we now have a feedback loop due to diagnosis causing smoking. One way to resolve this is to split the smoking variable into Smoking prior to diagnosis and smoking after diagnosis:
One advantage to this, other than preserving the acyclicity, is that it preserves the temporal nature of the DAG - that is, variables occurring earlier in time are on the left and those occurring later are on the right. This explicitly recognises one of the defining characteristics of causality: In order for something to be a cause, it MUST occur before the thing which it is a cause of. This isn't something that is enforced in DAG theory, but it is a very good practice that can help in situations like this.
|
Reverse causality opposite definitions
Reverse causality is particularly problematic for DAGs because it often implies either a reversal of a causal path, or feedback loop (which would make it a Directed Cyclic Graph) rendering the usual D
|
46,468
|
How to test for statistical significance with multiple visits and technical replicates?
|
However this solution doesn't take into account the two replicates for each visit or separate visits.
Correct.
How would I do this?
You need to account for repeated visits for each patient, and for repeated replicates within each visit for each patient. This is because measurements for the same patient are likely to be be more similar to measurements from other patients, and replicates for a patient's visit are likely to be more similar to each other than replicates for the same patients other visit.
One way to do this is with a mixed effects model, with random intercepts for patient, and also for visit.
In order to do this you will need to reformat your data into "long" format, where each row in the data corresponds to one measurement. So you will have 4 rows for each patient. Then you will have columns (variables) indicating the patient ID, the visit, replicate ID and an indicator for normal/MI. Something like this:
PatientID VisitID ReplicateID MI Value
A 1 1 1 1.0
A 1 2 1 1.1
A 2 1 1 2.0
A 2 2 1 1.6
B 1 1 0 0.2
B 1 2 0 0.3
B 2 1 0 0.2
B 2 2 0 0.5
In R, using syntax for the lme4 package you would use the following formula:
lmer(Value ~ MI + (1 | PatientID/VisitID), data = .... )
Your interest will centre on the estimate for MI, and you should check tjhat the model residuals are approximately normally distributed.
|
How to test for statistical significance with multiple visits and technical replicates?
|
However this solution doesn't take into account the two replicates for each visit or separate visits.
Correct.
How would I do this?
You need to account for repeated visits for each patient, and f
|
How to test for statistical significance with multiple visits and technical replicates?
However this solution doesn't take into account the two replicates for each visit or separate visits.
Correct.
How would I do this?
You need to account for repeated visits for each patient, and for repeated replicates within each visit for each patient. This is because measurements for the same patient are likely to be be more similar to measurements from other patients, and replicates for a patient's visit are likely to be more similar to each other than replicates for the same patients other visit.
One way to do this is with a mixed effects model, with random intercepts for patient, and also for visit.
In order to do this you will need to reformat your data into "long" format, where each row in the data corresponds to one measurement. So you will have 4 rows for each patient. Then you will have columns (variables) indicating the patient ID, the visit, replicate ID and an indicator for normal/MI. Something like this:
PatientID VisitID ReplicateID MI Value
A 1 1 1 1.0
A 1 2 1 1.1
A 2 1 1 2.0
A 2 2 1 1.6
B 1 1 0 0.2
B 1 2 0 0.3
B 2 1 0 0.2
B 2 2 0 0.5
In R, using syntax for the lme4 package you would use the following formula:
lmer(Value ~ MI + (1 | PatientID/VisitID), data = .... )
Your interest will centre on the estimate for MI, and you should check tjhat the model residuals are approximately normally distributed.
|
How to test for statistical significance with multiple visits and technical replicates?
However this solution doesn't take into account the two replicates for each visit or separate visits.
Correct.
How would I do this?
You need to account for repeated visits for each patient, and f
|
46,469
|
Variance Ratio Formula
|
You're right: indeed, there is an algebraic solution.
The optimization must occur over the set of $c$ for which the denominator is nonzero. I will leave to interested readers the special case where there exist nonzero $c$ for which the denominator nevertheless is zero: this is equivalent to at least one of the components of $X$ being constant.
This leaves us to deal with the generic case where all diagonal elements $\sigma_{ii}^2$ of $\Sigma$ are (strictly) positive. Writing
$$\Delta = \pmatrix{\sigma_{11} & 0 & \cdots & 0 \\ \vdots & \ddots & \cdots & 0 \\ 0 & 0 & \cdots & \sigma_{nn}}$$
we obtain the usual relationship between the covariance matrix and the correlation matrix $R,$
$$\Sigma = \Delta R\Delta.$$
Given $c\in\mathbb{R}^n\setminus\{0\},$ rescaling $$x = c\Delta \ne 0$$ gives
$$\frac{c^\prime\Sigma c}{c^\prime \operatorname{diag}(\Sigma) c} = \frac{x^\prime R x}{x^\prime x}.$$
Those familiar with PCA will already see the answer, but for the record let's obtain it using more fundamental results of linear algebra.
Because $\Sigma$ represents a positive-definite quadratic form, so does $R$ and therefore (by the Spectral Theorem) $R$ has an orthonormal eigenbasis $e_1, \ldots, e_n$ of eigenvectors with associated eigenvalues $\lambda_i\ge 0.$ Use this basis to express $x\ne 0$ as a linear combination
$$x = x_1 e_1 + \cdots + x_n e_n.$$
Then
$$\frac{x^\prime R x}{x^\prime x} = \frac{x_1^2\lambda_1 + \cdots +x_n^2\lambda_n}{x_1^2 + \cdots + x_n^2}$$
is a linear combination of the eigenvalues with coefficients $x_i^2 / (x_1^2 + \cdots + x_n^2)$ that are not all zero.
This set is (by definition) the convex hull of the eigenvalues, which will be the smallest closest interval containing them all. Clearly this is maximized by the largest eigenvalue of $R$ and minimized by the smallest one.
This generalizes the $n=2$ case because the eigenvalues of the correlation matrix with correlation coefficient $r$ are $1\pm r.$
Incidentally, because the eigenvalues are the roots of the characteristic polynomial of $R,$ we may consider this an algebraic solution, even though it's somewhat indirect (you still have to find the roots if you need explicit values).
|
Variance Ratio Formula
|
You're right: indeed, there is an algebraic solution.
The optimization must occur over the set of $c$ for which the denominator is nonzero. I will leave to interested readers the special case where t
|
Variance Ratio Formula
You're right: indeed, there is an algebraic solution.
The optimization must occur over the set of $c$ for which the denominator is nonzero. I will leave to interested readers the special case where there exist nonzero $c$ for which the denominator nevertheless is zero: this is equivalent to at least one of the components of $X$ being constant.
This leaves us to deal with the generic case where all diagonal elements $\sigma_{ii}^2$ of $\Sigma$ are (strictly) positive. Writing
$$\Delta = \pmatrix{\sigma_{11} & 0 & \cdots & 0 \\ \vdots & \ddots & \cdots & 0 \\ 0 & 0 & \cdots & \sigma_{nn}}$$
we obtain the usual relationship between the covariance matrix and the correlation matrix $R,$
$$\Sigma = \Delta R\Delta.$$
Given $c\in\mathbb{R}^n\setminus\{0\},$ rescaling $$x = c\Delta \ne 0$$ gives
$$\frac{c^\prime\Sigma c}{c^\prime \operatorname{diag}(\Sigma) c} = \frac{x^\prime R x}{x^\prime x}.$$
Those familiar with PCA will already see the answer, but for the record let's obtain it using more fundamental results of linear algebra.
Because $\Sigma$ represents a positive-definite quadratic form, so does $R$ and therefore (by the Spectral Theorem) $R$ has an orthonormal eigenbasis $e_1, \ldots, e_n$ of eigenvectors with associated eigenvalues $\lambda_i\ge 0.$ Use this basis to express $x\ne 0$ as a linear combination
$$x = x_1 e_1 + \cdots + x_n e_n.$$
Then
$$\frac{x^\prime R x}{x^\prime x} = \frac{x_1^2\lambda_1 + \cdots +x_n^2\lambda_n}{x_1^2 + \cdots + x_n^2}$$
is a linear combination of the eigenvalues with coefficients $x_i^2 / (x_1^2 + \cdots + x_n^2)$ that are not all zero.
This set is (by definition) the convex hull of the eigenvalues, which will be the smallest closest interval containing them all. Clearly this is maximized by the largest eigenvalue of $R$ and minimized by the smallest one.
This generalizes the $n=2$ case because the eigenvalues of the correlation matrix with correlation coefficient $r$ are $1\pm r.$
Incidentally, because the eigenvalues are the roots of the characteristic polynomial of $R,$ we may consider this an algebraic solution, even though it's somewhat indirect (you still have to find the roots if you need explicit values).
|
Variance Ratio Formula
You're right: indeed, there is an algebraic solution.
The optimization must occur over the set of $c$ for which the denominator is nonzero. I will leave to interested readers the special case where t
|
46,470
|
How reparameterize Beta distribution?
|
There is always the obvious inverse cdf representation:
$$X=F_{\alpha,\beta}^{-1}(U)$$
where $F_{\alpha,\beta}^{-1}(\cdot)$ is the inverse cdf (quantile function) of the Beta $\mathcal Be(\alpha,\beta)$ distribution.
Otherwise, the Wikipedia page lists a large collection of connections with other standard distributions, like the Gamma and the F distributions. For integer valued $\alpha$ and $\beta$, the Beta $\mathcal Be(\alpha,\beta)$ distribution is the distribution of an order statistic of a Uniform sample.
|
How reparameterize Beta distribution?
|
There is always the obvious inverse cdf representation:
$$X=F_{\alpha,\beta}^{-1}(U)$$
where $F_{\alpha,\beta}^{-1}(\cdot)$ is the inverse cdf (quantile function) of the Beta $\mathcal Be(\alpha,\beta
|
How reparameterize Beta distribution?
There is always the obvious inverse cdf representation:
$$X=F_{\alpha,\beta}^{-1}(U)$$
where $F_{\alpha,\beta}^{-1}(\cdot)$ is the inverse cdf (quantile function) of the Beta $\mathcal Be(\alpha,\beta)$ distribution.
Otherwise, the Wikipedia page lists a large collection of connections with other standard distributions, like the Gamma and the F distributions. For integer valued $\alpha$ and $\beta$, the Beta $\mathcal Be(\alpha,\beta)$ distribution is the distribution of an order statistic of a Uniform sample.
|
How reparameterize Beta distribution?
There is always the obvious inverse cdf representation:
$$X=F_{\alpha,\beta}^{-1}(U)$$
where $F_{\alpha,\beta}^{-1}(\cdot)$ is the inverse cdf (quantile function) of the Beta $\mathcal Be(\alpha,\beta
|
46,471
|
How reparameterize Beta distribution?
|
If you mean representing every beta-distributed random variable as some simple function of the two parameters $\alpha,\beta$ and some "standard beta" random variable, then probably it cannot be done.
One alternative to the simple standard way of parameterizing this family of distributions that has crossed my mind is as follows.
The expected value is $\mu=\dfrac\alpha{\alpha+\beta}.$
The variance is $\dfrac{\frac\alpha{\alpha+\beta} \cdot \frac\beta{\alpha+\beta}}{\alpha+\beta+1} = \dfrac{\mu(1-\mu)}{\alpha+\beta+1} = \dfrac{\mu(1-\mu)}\kappa$
where the last equality defines $\kappa.$
So we have
\begin{align}
\mu & = \alpha/(\alpha+\beta), \\
\kappa & = \alpha+\beta+1. \\[12pt]
\alpha & = (\kappa-1)\mu, \\
\beta & = (\kappa-1)(1-\mu).
\end{align}
$\mu$ is the mean and $\kappa$ is the concentration. With $\mu$ fixed, $\kappa$ is proportional to the reciprocal of the variance.
Postscript: It has occurred to me that what I said in the first paragraph above is mistaken, and I've crossed it out. One can use the beta distribution with $\alpha=\beta=1,$ which is the same as the uniform distribution on $[0,1].$ If $X$ has that distribution, then $F^{-1}(X)\sim\operatorname{Beta}(\alpha,\beta),$ where $F$ is the c.d.f. of the $\operatorname{Beta}(\alpha,\beta)$ distribution.
Postpostscript: The postscript above does not represent an alternative parametrization of the family of beta distributions, since the same pair of parameters still represents the same distribution.
|
How reparameterize Beta distribution?
|
If you mean representing every beta-distributed random variable as some simple function of the two parameters $\alpha,\beta$ and some "standard beta" random variable, then probably it cannot be done.
|
How reparameterize Beta distribution?
If you mean representing every beta-distributed random variable as some simple function of the two parameters $\alpha,\beta$ and some "standard beta" random variable, then probably it cannot be done.
One alternative to the simple standard way of parameterizing this family of distributions that has crossed my mind is as follows.
The expected value is $\mu=\dfrac\alpha{\alpha+\beta}.$
The variance is $\dfrac{\frac\alpha{\alpha+\beta} \cdot \frac\beta{\alpha+\beta}}{\alpha+\beta+1} = \dfrac{\mu(1-\mu)}{\alpha+\beta+1} = \dfrac{\mu(1-\mu)}\kappa$
where the last equality defines $\kappa.$
So we have
\begin{align}
\mu & = \alpha/(\alpha+\beta), \\
\kappa & = \alpha+\beta+1. \\[12pt]
\alpha & = (\kappa-1)\mu, \\
\beta & = (\kappa-1)(1-\mu).
\end{align}
$\mu$ is the mean and $\kappa$ is the concentration. With $\mu$ fixed, $\kappa$ is proportional to the reciprocal of the variance.
Postscript: It has occurred to me that what I said in the first paragraph above is mistaken, and I've crossed it out. One can use the beta distribution with $\alpha=\beta=1,$ which is the same as the uniform distribution on $[0,1].$ If $X$ has that distribution, then $F^{-1}(X)\sim\operatorname{Beta}(\alpha,\beta),$ where $F$ is the c.d.f. of the $\operatorname{Beta}(\alpha,\beta)$ distribution.
Postpostscript: The postscript above does not represent an alternative parametrization of the family of beta distributions, since the same pair of parameters still represents the same distribution.
|
How reparameterize Beta distribution?
If you mean representing every beta-distributed random variable as some simple function of the two parameters $\alpha,\beta$ and some "standard beta" random variable, then probably it cannot be done.
|
46,472
|
Advantage & disadvantage of PCA vs kernel PCA
|
Kernel PCA (kPCA) actually includes regular PCA as a special case--they're equivalent if the linear kernel is used. But, they have different properties in general. Here are some points of comparison:
Linear vs. nonlinear structure. kPCA can capture nonlinear structure in the data (if using a nonlinear kernel), whereas PCA cannot. This can be a big deal; if this capability is needed, PCA simply isn't an option and kPCA (or one of many other nonlinear dimensionality reduction techniques) must be used. If the data truly live on a linear manifold, kPCA can do no better than PCA. In fact, using a nonlinear kernel may give worse performance due to overfitting.
Interpretability. PCA provides a set of weights that define a linear mapping from the input space to the low-dimensional embedding space. These weights can provide useful information about the structure of the data. No such weights exist for kPCA with nonlinear kernels because the mapping is nonlinear. It's also nonparametric.
Inverse mapping. PCA provides an inverse mapping from the low-dimensional space back to the input space. So, input points can be approximately reconstructed from their low-dimensional images. kPCA doesn't inherently provide an inverse mapping, although it's possible to estimate one using additional methods (at the cost of extra complexity and computational resources).
Hyperparameters. Both methods require choosing the number of dimensions. kPCA also requires choosing the kernel function and any associated parameters (e.g. the bandwidth of an RBF kernel, or degree of a polynomial kernel). This choice (and the method/criterion employed to make it) is problem dependent. Typically, one needs to re-fit kPCA multiple times to compare different kernel/parameter choices.
Computational cost. PCA generally has lower memory and runtime requirements than kPCA, and can be scaled to massive datasets. Various strategies exist for scaling up kPCA, but this requires making approximations (e.g. see the Nystroem approximation).
As usual, the right tool for the job depends on the problem.
|
Advantage & disadvantage of PCA vs kernel PCA
|
Kernel PCA (kPCA) actually includes regular PCA as a special case--they're equivalent if the linear kernel is used. But, they have different properties in general. Here are some points of comparison:
|
Advantage & disadvantage of PCA vs kernel PCA
Kernel PCA (kPCA) actually includes regular PCA as a special case--they're equivalent if the linear kernel is used. But, they have different properties in general. Here are some points of comparison:
Linear vs. nonlinear structure. kPCA can capture nonlinear structure in the data (if using a nonlinear kernel), whereas PCA cannot. This can be a big deal; if this capability is needed, PCA simply isn't an option and kPCA (or one of many other nonlinear dimensionality reduction techniques) must be used. If the data truly live on a linear manifold, kPCA can do no better than PCA. In fact, using a nonlinear kernel may give worse performance due to overfitting.
Interpretability. PCA provides a set of weights that define a linear mapping from the input space to the low-dimensional embedding space. These weights can provide useful information about the structure of the data. No such weights exist for kPCA with nonlinear kernels because the mapping is nonlinear. It's also nonparametric.
Inverse mapping. PCA provides an inverse mapping from the low-dimensional space back to the input space. So, input points can be approximately reconstructed from their low-dimensional images. kPCA doesn't inherently provide an inverse mapping, although it's possible to estimate one using additional methods (at the cost of extra complexity and computational resources).
Hyperparameters. Both methods require choosing the number of dimensions. kPCA also requires choosing the kernel function and any associated parameters (e.g. the bandwidth of an RBF kernel, or degree of a polynomial kernel). This choice (and the method/criterion employed to make it) is problem dependent. Typically, one needs to re-fit kPCA multiple times to compare different kernel/parameter choices.
Computational cost. PCA generally has lower memory and runtime requirements than kPCA, and can be scaled to massive datasets. Various strategies exist for scaling up kPCA, but this requires making approximations (e.g. see the Nystroem approximation).
As usual, the right tool for the job depends on the problem.
|
Advantage & disadvantage of PCA vs kernel PCA
Kernel PCA (kPCA) actually includes regular PCA as a special case--they're equivalent if the linear kernel is used. But, they have different properties in general. Here are some points of comparison:
|
46,473
|
How do I deal with large amout missing values in a data set without dropping them?
|
Because NA values are informative for your dataset, you don't want to drop NAs or impute values. If a patient doesn't get an X-ray, they probably didn't break a bone.
So you want to learn from NA values. A common approach is to add an indicator column for NA values.
|
How do I deal with large amout missing values in a data set without dropping them?
|
Because NA values are informative for your dataset, you don't want to drop NAs or impute values. If a patient doesn't get an X-ray, they probably didn't break a bone.
So you want to learn from NA val
|
How do I deal with large amout missing values in a data set without dropping them?
Because NA values are informative for your dataset, you don't want to drop NAs or impute values. If a patient doesn't get an X-ray, they probably didn't break a bone.
So you want to learn from NA values. A common approach is to add an indicator column for NA values.
|
How do I deal with large amout missing values in a data set without dropping them?
Because NA values are informative for your dataset, you don't want to drop NAs or impute values. If a patient doesn't get an X-ray, they probably didn't break a bone.
So you want to learn from NA val
|
46,474
|
How do I deal with large amout missing values in a data set without dropping them?
|
A linear mixed effects model would allow you to have individuals with missing data and not need to convert everything over to categories. If ever you have a continuous variable, use it as a continuum if at all possible.
Here is a link to a paper that explains more about why. It is not just for psychologists, the same applies because the arguments are based on math, not opinion. https://www.researchgate.net/publication/282351876_The_problem_with_categorical_thinking_by_psychologists
If you have data on a bunch of known cases you can use to build the model, use a logistic generalized linear mixed-effects model aka logistic GLMM. In R it is in the lme4 library and uses GLMER for its call (Generalized Linear Mixed Effects Regression). You may also want to look into signal detection theory as it may help you out here. With a logistic GLMM you can use an individual patient's information in the model and it will give you the odds of them having/not having the outcome. Just be careful to add only relevant variables to your model. If there are too many predictors your model will not generalize well to new patients that were not used to fit the model. To remedy this, if you have enough data, split it at random into two data sets, fit the model on one data set and then see how well it predicts another data set by comparing the Akaike Information Criterion and Bayesian Information Criterion. Bootstrapping may also help with this.
GLMMs and LMMs in general deal very well with missing data. Unlike a traditional logistic regression, LMMs do not have the assumption of equal cell sizes. Don't be fooled if someone says that ANOVA/regression is robust to violations of its assumptions, especially if the cell sizes are unequal. They haven't done their homework and are just parroting what they heard in grad school. The math on that is clear.
|
How do I deal with large amout missing values in a data set without dropping them?
|
A linear mixed effects model would allow you to have individuals with missing data and not need to convert everything over to categories. If ever you have a continuous variable, use it as a continuum
|
How do I deal with large amout missing values in a data set without dropping them?
A linear mixed effects model would allow you to have individuals with missing data and not need to convert everything over to categories. If ever you have a continuous variable, use it as a continuum if at all possible.
Here is a link to a paper that explains more about why. It is not just for psychologists, the same applies because the arguments are based on math, not opinion. https://www.researchgate.net/publication/282351876_The_problem_with_categorical_thinking_by_psychologists
If you have data on a bunch of known cases you can use to build the model, use a logistic generalized linear mixed-effects model aka logistic GLMM. In R it is in the lme4 library and uses GLMER for its call (Generalized Linear Mixed Effects Regression). You may also want to look into signal detection theory as it may help you out here. With a logistic GLMM you can use an individual patient's information in the model and it will give you the odds of them having/not having the outcome. Just be careful to add only relevant variables to your model. If there are too many predictors your model will not generalize well to new patients that were not used to fit the model. To remedy this, if you have enough data, split it at random into two data sets, fit the model on one data set and then see how well it predicts another data set by comparing the Akaike Information Criterion and Bayesian Information Criterion. Bootstrapping may also help with this.
GLMMs and LMMs in general deal very well with missing data. Unlike a traditional logistic regression, LMMs do not have the assumption of equal cell sizes. Don't be fooled if someone says that ANOVA/regression is robust to violations of its assumptions, especially if the cell sizes are unequal. They haven't done their homework and are just parroting what they heard in grad school. The math on that is clear.
|
How do I deal with large amout missing values in a data set without dropping them?
A linear mixed effects model would allow you to have individuals with missing data and not need to convert everything over to categories. If ever you have a continuous variable, use it as a continuum
|
46,475
|
Alternatives to minimizing loss in regression
|
Rational choice theory says that any rational preference can be modeled with a utility function.
Therefore any (rational) decision process can be encoded in a loss function and posed as an optimization problem.
For example, L1 and L2 regularization can be viewed as encoding a preference for smaller parameters or more parsimonious models into the loss function. Any preference can be similarly encoded, assuming it's not irrational.
For example, suppose one wanted to use a regression function which optimized fit based not just on loss minimization but which also maximized nonlinear dependence or Shannon entropy?
Then you would adjust your utility function to include a term penalizing those things, just as we did for L1/L2 regularization.
Now, this might make the problem computationally intractable; for example, 0/1 loss is known to result in an NP-hard problem. In general, people prefer to study tractable problems so you won't find much off-the-shelf software that does this, but nothing is stopping you from writing down such a function and applying some sufficiently generalized optimizer to it.
If you retort that you have a preference in mind which cannot be modeled by a loss function, even in principle, then all I can say is that such a preference is irrational. Don't blame me, that's just modus tollens from the above theorem. You are free to have such a preference (there is good empirical evidence that most preferences that people actually hold are irrational in one way or another) but you will not find much literature on solving such problems in a formal regression context.
|
Alternatives to minimizing loss in regression
|
Rational choice theory says that any rational preference can be modeled with a utility function.
Therefore any (rational) decision process can be encoded in a loss function and posed as an optimizatio
|
Alternatives to minimizing loss in regression
Rational choice theory says that any rational preference can be modeled with a utility function.
Therefore any (rational) decision process can be encoded in a loss function and posed as an optimization problem.
For example, L1 and L2 regularization can be viewed as encoding a preference for smaller parameters or more parsimonious models into the loss function. Any preference can be similarly encoded, assuming it's not irrational.
For example, suppose one wanted to use a regression function which optimized fit based not just on loss minimization but which also maximized nonlinear dependence or Shannon entropy?
Then you would adjust your utility function to include a term penalizing those things, just as we did for L1/L2 regularization.
Now, this might make the problem computationally intractable; for example, 0/1 loss is known to result in an NP-hard problem. In general, people prefer to study tractable problems so you won't find much off-the-shelf software that does this, but nothing is stopping you from writing down such a function and applying some sufficiently generalized optimizer to it.
If you retort that you have a preference in mind which cannot be modeled by a loss function, even in principle, then all I can say is that such a preference is irrational. Don't blame me, that's just modus tollens from the above theorem. You are free to have such a preference (there is good empirical evidence that most preferences that people actually hold are irrational in one way or another) but you will not find much literature on solving such problems in a formal regression context.
|
Alternatives to minimizing loss in regression
Rational choice theory says that any rational preference can be modeled with a utility function.
Therefore any (rational) decision process can be encoded in a loss function and posed as an optimizatio
|
46,476
|
Alternatives to minimizing loss in regression
|
But is accuracy the only important virtue of a model?
The practical aspects of what a model's for is too nuanced for a theoretical discussion. Interpretation and generalizability come to mind. "Who will use this model?" should be a top line question in all statistical analyses.
Friedman's statement is defensible in a classical statistics framework: we have no fundamental reason to object to black-box prediction. If you want a Y-hat that's going to be very close to the Y you observe in the future, then "build your model as big as a house" as John Tukey would say.
This does not excuse overfitting, unless your question is ill defined [plural "you" being the proverbial statistician]. Overfitting is too often the result of analysts who encounter data rather than approach it. By going through hundreds of models and picking "the best", you are prone to build models that lack generality. We see it all the time.
Inadvertantly you also ask a different question: "Alternatives to minimizing loss in regression". Minimax estimators, estimators that minimize a loss function, are a subset of the class of method of moments estimators: estimators that give a zero to an estimating function. The goal of the MOMs is to find an unbiased estimator, rather than one that minimizes a loss.
|
Alternatives to minimizing loss in regression
|
But is accuracy the only important virtue of a model?
The practical aspects of what a model's for is too nuanced for a theoretical discussion. Interpretation and generalizability come to mind. "Who w
|
Alternatives to minimizing loss in regression
But is accuracy the only important virtue of a model?
The practical aspects of what a model's for is too nuanced for a theoretical discussion. Interpretation and generalizability come to mind. "Who will use this model?" should be a top line question in all statistical analyses.
Friedman's statement is defensible in a classical statistics framework: we have no fundamental reason to object to black-box prediction. If you want a Y-hat that's going to be very close to the Y you observe in the future, then "build your model as big as a house" as John Tukey would say.
This does not excuse overfitting, unless your question is ill defined [plural "you" being the proverbial statistician]. Overfitting is too often the result of analysts who encounter data rather than approach it. By going through hundreds of models and picking "the best", you are prone to build models that lack generality. We see it all the time.
Inadvertantly you also ask a different question: "Alternatives to minimizing loss in regression". Minimax estimators, estimators that minimize a loss function, are a subset of the class of method of moments estimators: estimators that give a zero to an estimating function. The goal of the MOMs is to find an unbiased estimator, rather than one that minimizes a loss.
|
Alternatives to minimizing loss in regression
But is accuracy the only important virtue of a model?
The practical aspects of what a model's for is too nuanced for a theoretical discussion. Interpretation and generalizability come to mind. "Who w
|
46,477
|
An easy decision when to use a spline or a polynomial
|
My RMS book and course notes go into detail about this. Briefly, polynomials are too restrictive, allow a point in one part of the curve to too greatly influence the fit in other parts of the curve, and the fits are not as good as segmented polynomials (splines). Polynomials cannot well approximate threshold effects or logarithmic shapes.
|
An easy decision when to use a spline or a polynomial
|
My RMS book and course notes go into detail about this. Briefly, polynomials are too restrictive, allow a point in one part of the curve to too greatly influence the fit in other parts of the curve,
|
An easy decision when to use a spline or a polynomial
My RMS book and course notes go into detail about this. Briefly, polynomials are too restrictive, allow a point in one part of the curve to too greatly influence the fit in other parts of the curve, and the fits are not as good as segmented polynomials (splines). Polynomials cannot well approximate threshold effects or logarithmic shapes.
|
An easy decision when to use a spline or a polynomial
My RMS book and course notes go into detail about this. Briefly, polynomials are too restrictive, allow a point in one part of the curve to too greatly influence the fit in other parts of the curve,
|
46,478
|
What is distribution of $\sin(x)$? If x is exponential distribution
|
The cumulative distribution function (cdf) of a variable $X$ with an exponential distribution can be written
$$F_\lambda(x) = \Pr(X\le x) = 1 - e^{-\lambda x}.$$
Consequently, for any interval determined by $0\le a\le b,$ the chance $X$ lies in this interval is
$$\Pr(a\lt X\le b) = F_\lambda(b)-F_\lambda(a) = e^{-\lambda a} - e^{-\lambda b}.$$
Let $T=\sin(X).$ Computing the CDF of $T$ using the graphical approach recommended at PDF of function of X, we find for $-1\lt t \le 1$ and $x = \arcsin(t)$ (a number between $-\pi/2$ and $\pi/2$) that the event $T\le t$ is the union of disjoint events
$$\mathcal{E}_i:2\pi j + \pi-x \le X \le 2\pi j + 2\pi + x,\ j=1,2,3,\ldots$$
together with the event
$$\mathcal{E}_0: 0 \le X \le x.$$
(This event is empty when $t\lt 0.$) Consequently the desired probability is the sum of probabilities of these events, which simplifies because these probabilities form a geometric sequence:
$$\eqalign{\Pr(T\le t) &= \Pr(X\in\mathcal{E}_0) + \sum_{j=1}^\infty\Pr(X\in\mathcal{E}_j) \\
&= 1-e^{-\lambda x} + \sum_{j=1}^\infty \left(e^{-\lambda(2\pi j + \pi -x)} - e^{-\lambda(2\pi j + 2\pi +x}\right) \\
&= 1-e^{-\lambda x} + \left(e^{-\lambda(\pi-x)} - e^{-\lambda(2\pi+x)}\right)\sum_{j=1}^\infty \left(e^{-\lambda 2\pi}\right)^j \\
&= 1-e^{-\lambda x} + \frac{e^{-\lambda(\pi-x)} - e^{-\lambda(2\pi+x)}}{1-e^{-\lambda 2\pi}} \\
&= 1-e^{-\lambda \arcsin(t)} + \frac{e^{-\lambda(\pi-\arcsin(t))} - e^{-\lambda(2\pi+\arcsin(t))}}{1-e^{-2\pi\lambda }},
}$$
with the first two terms $1-e^{-\lambda \arcsin(t)}$ not appearing when $\arcsin(t)\lt 0.$
Here are illustrations of the CDF, superimposed on the empirical distributions of samples of size 10,000. The theoretical curves (in red) coincide with the empirical distribution functions everywhere, demonstrating the correctness of these results. Beneath each CDF is a plot of the PDF of the underlying exponential distribution.
|
What is distribution of $\sin(x)$? If x is exponential distribution
|
The cumulative distribution function (cdf) of a variable $X$ with an exponential distribution can be written
$$F_\lambda(x) = \Pr(X\le x) = 1 - e^{-\lambda x}.$$
Consequently, for any interval determi
|
What is distribution of $\sin(x)$? If x is exponential distribution
The cumulative distribution function (cdf) of a variable $X$ with an exponential distribution can be written
$$F_\lambda(x) = \Pr(X\le x) = 1 - e^{-\lambda x}.$$
Consequently, for any interval determined by $0\le a\le b,$ the chance $X$ lies in this interval is
$$\Pr(a\lt X\le b) = F_\lambda(b)-F_\lambda(a) = e^{-\lambda a} - e^{-\lambda b}.$$
Let $T=\sin(X).$ Computing the CDF of $T$ using the graphical approach recommended at PDF of function of X, we find for $-1\lt t \le 1$ and $x = \arcsin(t)$ (a number between $-\pi/2$ and $\pi/2$) that the event $T\le t$ is the union of disjoint events
$$\mathcal{E}_i:2\pi j + \pi-x \le X \le 2\pi j + 2\pi + x,\ j=1,2,3,\ldots$$
together with the event
$$\mathcal{E}_0: 0 \le X \le x.$$
(This event is empty when $t\lt 0.$) Consequently the desired probability is the sum of probabilities of these events, which simplifies because these probabilities form a geometric sequence:
$$\eqalign{\Pr(T\le t) &= \Pr(X\in\mathcal{E}_0) + \sum_{j=1}^\infty\Pr(X\in\mathcal{E}_j) \\
&= 1-e^{-\lambda x} + \sum_{j=1}^\infty \left(e^{-\lambda(2\pi j + \pi -x)} - e^{-\lambda(2\pi j + 2\pi +x}\right) \\
&= 1-e^{-\lambda x} + \left(e^{-\lambda(\pi-x)} - e^{-\lambda(2\pi+x)}\right)\sum_{j=1}^\infty \left(e^{-\lambda 2\pi}\right)^j \\
&= 1-e^{-\lambda x} + \frac{e^{-\lambda(\pi-x)} - e^{-\lambda(2\pi+x)}}{1-e^{-\lambda 2\pi}} \\
&= 1-e^{-\lambda \arcsin(t)} + \frac{e^{-\lambda(\pi-\arcsin(t))} - e^{-\lambda(2\pi+\arcsin(t))}}{1-e^{-2\pi\lambda }},
}$$
with the first two terms $1-e^{-\lambda \arcsin(t)}$ not appearing when $\arcsin(t)\lt 0.$
Here are illustrations of the CDF, superimposed on the empirical distributions of samples of size 10,000. The theoretical curves (in red) coincide with the empirical distribution functions everywhere, demonstrating the correctness of these results. Beneath each CDF is a plot of the PDF of the underlying exponential distribution.
|
What is distribution of $\sin(x)$? If x is exponential distribution
The cumulative distribution function (cdf) of a variable $X$ with an exponential distribution can be written
$$F_\lambda(x) = \Pr(X\le x) = 1 - e^{-\lambda x}.$$
Consequently, for any interval determi
|
46,479
|
Integrating with a multivariate Gaussian
|
The means and covariances already evaluate all the integrals you need, allowing this result to be obtained purely algebraically. It actually has nothing to do with Normal distributions (except insofar as they have finite covariances in the first place).
Let $X=(X_1,X_2,\ldots,X_n)$ be a multivariate random variable with mean vector $$\mu = (\mu_1,\mu_2,\ldots,\mu_n)=(E[X_1], E[X_2], \ldots, E[X_n])$$ and covariance matrix $$C = (c_{ij}) = (E[X_iX_j] - E[X_i]E[X_j]) = (E[X_iX_j]-\mu_i\mu_j),$$ which can be rewritten $$E[X_iX_j] = c_{ij} + \mu_i\mu_j.$$
Let $A=(a_{ij})$ be any $n\times n$ matrix. The definition of matrix multiplication, linearity of expectation, the foregoing formula, and definition of the trace imply
$$\eqalign{
E\left[X^\prime A X\right] &= E\left[\sum_{i,j} X_i a_{ij} X_j\right] \\
&= \sum_{ij} E[X_iX_j] a_{ij} \\
&= \sum_{ij}(C_{ij} +\mu_i\mu_j) a_{ij} \\
&= \operatorname{Tr}(CA) + \mu^\prime A \mu.
}$$
Multiply everything by $1/2$ and let $X$ be multivariate normal.
|
Integrating with a multivariate Gaussian
|
The means and covariances already evaluate all the integrals you need, allowing this result to be obtained purely algebraically. It actually has nothing to do with Normal distributions (except insofa
|
Integrating with a multivariate Gaussian
The means and covariances already evaluate all the integrals you need, allowing this result to be obtained purely algebraically. It actually has nothing to do with Normal distributions (except insofar as they have finite covariances in the first place).
Let $X=(X_1,X_2,\ldots,X_n)$ be a multivariate random variable with mean vector $$\mu = (\mu_1,\mu_2,\ldots,\mu_n)=(E[X_1], E[X_2], \ldots, E[X_n])$$ and covariance matrix $$C = (c_{ij}) = (E[X_iX_j] - E[X_i]E[X_j]) = (E[X_iX_j]-\mu_i\mu_j),$$ which can be rewritten $$E[X_iX_j] = c_{ij} + \mu_i\mu_j.$$
Let $A=(a_{ij})$ be any $n\times n$ matrix. The definition of matrix multiplication, linearity of expectation, the foregoing formula, and definition of the trace imply
$$\eqalign{
E\left[X^\prime A X\right] &= E\left[\sum_{i,j} X_i a_{ij} X_j\right] \\
&= \sum_{ij} E[X_iX_j] a_{ij} \\
&= \sum_{ij}(C_{ij} +\mu_i\mu_j) a_{ij} \\
&= \operatorname{Tr}(CA) + \mu^\prime A \mu.
}$$
Multiply everything by $1/2$ and let $X$ be multivariate normal.
|
Integrating with a multivariate Gaussian
The means and covariances already evaluate all the integrals you need, allowing this result to be obtained purely algebraically. It actually has nothing to do with Normal distributions (except insofa
|
46,480
|
Integrating with a multivariate Gaussian
|
The solution posted by whuber gets at this idea but I wanted to make the approach more explicitly use the trace operator, use:
$$\mathbb{E}(u^TAu) = \mathbb{E}(tr(u^TAu)).$$
Note that the quadratic form inside the expectation is a scalar and trace of a scalar is the same scalar. Next use cyclic swap property of the trace operator:
$$\mathbb{E}(tr(u^TAu))= \mathbb{E}(tr(uu^TA)).$$
Now note that $A$ is a constant so you can factor that out:
$$ \mathbb{E}(tr(uu^TA))=tr(\mathbb{E}(uu^TA)).$$
Once more step:
$$tr(\mathbb{E}(uu^TA))= tr(\mathbb{E}(uu^T)A)$$
Next consider that by definition of the covariance matrix of a multivariate Gaussian:
$$ \mathbb{E}(uu^T) = C.$$
Stitch all of this together and you've got the result.
|
Integrating with a multivariate Gaussian
|
The solution posted by whuber gets at this idea but I wanted to make the approach more explicitly use the trace operator, use:
$$\mathbb{E}(u^TAu) = \mathbb{E}(tr(u^TAu)).$$
Note that the quadratic fo
|
Integrating with a multivariate Gaussian
The solution posted by whuber gets at this idea but I wanted to make the approach more explicitly use the trace operator, use:
$$\mathbb{E}(u^TAu) = \mathbb{E}(tr(u^TAu)).$$
Note that the quadratic form inside the expectation is a scalar and trace of a scalar is the same scalar. Next use cyclic swap property of the trace operator:
$$\mathbb{E}(tr(u^TAu))= \mathbb{E}(tr(uu^TA)).$$
Now note that $A$ is a constant so you can factor that out:
$$ \mathbb{E}(tr(uu^TA))=tr(\mathbb{E}(uu^TA)).$$
Once more step:
$$tr(\mathbb{E}(uu^TA))= tr(\mathbb{E}(uu^T)A)$$
Next consider that by definition of the covariance matrix of a multivariate Gaussian:
$$ \mathbb{E}(uu^T) = C.$$
Stitch all of this together and you've got the result.
|
Integrating with a multivariate Gaussian
The solution posted by whuber gets at this idea but I wanted to make the approach more explicitly use the trace operator, use:
$$\mathbb{E}(u^TAu) = \mathbb{E}(tr(u^TAu)).$$
Note that the quadratic fo
|
46,481
|
Difference between covariates and treatment confounders in propensity score matching
|
The definition of a confounder is somewhat complicated, but VanderWeele & Shpitser (2013) decided
A pre-exposure covariate C is a confounder for the effect of A on Y if
it is a member of some minimally sufficient adjustment set.
A sufficient adjustment set is a set of variables conditioning on which is sufficient to remove confounding. Using the language of causal graphs, it is a set of variables that blocks all back-door paths from treatment to the outcome and doesn't block any front-door paths. A minimally sufficient adjustment set is a sufficient adjustment set for which no proper subset is also a sufficient adjustment set.
The main result of Rosenbaum & Rubin (1983) is that, for a sufficient adjustment set, it is sufficient to condition on the conditional probability of treatment given that same set of variables to eliminate confounding. Formally, consider the collection $X$ of all variables $x_1, ... x_k$ that are not caused by the treatment ($A$) or outcome ($Y$). Now consider a subset of $X$, called $V$. If $Y^A \perp A|V$, that is, if $V$ is a sufficient adjustment set, then $Y^A \perp A|e(V)$, where $e(V)=P(A=1|V)$ is the propensity score. This means that we can estimate a treatment effect within strata of $e(V)$, and those treatment effects will be unbiased (i.e., free of confounding). This is what justifies propensity score matching, subclassification, and regression (although these all have additional requirements and assumptions, so don't go running off using them without understanding what else is required and how these techniques differ).
"Covariate" is usually not rigorously defined in the context of causal inference. It usually refers to $X$, the collection of variables not caused by treatment, some of which form a sufficient adjustment set. $X$ usually contains confounders, instrumental variables (variables that cause selection into treatment but have no direct effect on the outcome), prognostic variables (variables that cause variation in the outcome but are independent of the treatment), and irrelevant variables (variables that cause neither selection into treatment nor variation in the outcome). There may also be some bias-inducing variables that, when conditioned upon, induce bias in an effect estimate.
In propensity score (and other causal) analyses, it is up to the researcher to select a subset of $X$, namely $V$, that is a sufficient adjustment set. $V$ will then contain confounders (i.e., variables part of a minimally sufficient adjustment set) and other covariates (if any). Typically theory is used to select $V$, though there have been some attempts to use machine learning to select them (e.g., Shortreed & Ertefaie, 2017; Koch, Vock, & Wilson, 2018).
To sum up, a treatment effect estimate is unbiased conditional on a sufficient adjustment set. It is also unbiased conditional on a propensity score formed from that sufficient adjustment set. A sufficient adjustment set is a subset of variables not caused by treatment, often called covariates, that is sufficient to remove confounding. A confounder is a member of a minimally sufficient adjustment set. Adjustment sets will contain confounders and, though not necessarily, other covariates. Here's a Venn diagram to display these distinctions:
Koch, B., Vock, D. M., & Wolfson, J. (2018). Covariate selection with group lasso and doubly robust estimation of causal effects. Biometrics, 74(1), 8–17.
Rosenbaum, P. R., & Rubin, D. B. (1983). The central role of the propensity score in observational studies for causal effects. Biometrika, 70(1), 41–55.
VanderWeele, T. J., & Shpitser, I. (2013). On the definition of a confounder. Annals of Statistics, 41(1), 196–220.
Shortreed, S. M., & Ertefaie, A. (2017). Outcome-adaptive lasso: Variable selection for causal inference: Outcome-Adaptive Lasso. Biometrics, 73(4), 1111–1122.
|
Difference between covariates and treatment confounders in propensity score matching
|
The definition of a confounder is somewhat complicated, but VanderWeele & Shpitser (2013) decided
A pre-exposure covariate C is a confounder for the effect of A on Y if
it is a member of some minim
|
Difference between covariates and treatment confounders in propensity score matching
The definition of a confounder is somewhat complicated, but VanderWeele & Shpitser (2013) decided
A pre-exposure covariate C is a confounder for the effect of A on Y if
it is a member of some minimally sufficient adjustment set.
A sufficient adjustment set is a set of variables conditioning on which is sufficient to remove confounding. Using the language of causal graphs, it is a set of variables that blocks all back-door paths from treatment to the outcome and doesn't block any front-door paths. A minimally sufficient adjustment set is a sufficient adjustment set for which no proper subset is also a sufficient adjustment set.
The main result of Rosenbaum & Rubin (1983) is that, for a sufficient adjustment set, it is sufficient to condition on the conditional probability of treatment given that same set of variables to eliminate confounding. Formally, consider the collection $X$ of all variables $x_1, ... x_k$ that are not caused by the treatment ($A$) or outcome ($Y$). Now consider a subset of $X$, called $V$. If $Y^A \perp A|V$, that is, if $V$ is a sufficient adjustment set, then $Y^A \perp A|e(V)$, where $e(V)=P(A=1|V)$ is the propensity score. This means that we can estimate a treatment effect within strata of $e(V)$, and those treatment effects will be unbiased (i.e., free of confounding). This is what justifies propensity score matching, subclassification, and regression (although these all have additional requirements and assumptions, so don't go running off using them without understanding what else is required and how these techniques differ).
"Covariate" is usually not rigorously defined in the context of causal inference. It usually refers to $X$, the collection of variables not caused by treatment, some of which form a sufficient adjustment set. $X$ usually contains confounders, instrumental variables (variables that cause selection into treatment but have no direct effect on the outcome), prognostic variables (variables that cause variation in the outcome but are independent of the treatment), and irrelevant variables (variables that cause neither selection into treatment nor variation in the outcome). There may also be some bias-inducing variables that, when conditioned upon, induce bias in an effect estimate.
In propensity score (and other causal) analyses, it is up to the researcher to select a subset of $X$, namely $V$, that is a sufficient adjustment set. $V$ will then contain confounders (i.e., variables part of a minimally sufficient adjustment set) and other covariates (if any). Typically theory is used to select $V$, though there have been some attempts to use machine learning to select them (e.g., Shortreed & Ertefaie, 2017; Koch, Vock, & Wilson, 2018).
To sum up, a treatment effect estimate is unbiased conditional on a sufficient adjustment set. It is also unbiased conditional on a propensity score formed from that sufficient adjustment set. A sufficient adjustment set is a subset of variables not caused by treatment, often called covariates, that is sufficient to remove confounding. A confounder is a member of a minimally sufficient adjustment set. Adjustment sets will contain confounders and, though not necessarily, other covariates. Here's a Venn diagram to display these distinctions:
Koch, B., Vock, D. M., & Wolfson, J. (2018). Covariate selection with group lasso and doubly robust estimation of causal effects. Biometrics, 74(1), 8–17.
Rosenbaum, P. R., & Rubin, D. B. (1983). The central role of the propensity score in observational studies for causal effects. Biometrika, 70(1), 41–55.
VanderWeele, T. J., & Shpitser, I. (2013). On the definition of a confounder. Annals of Statistics, 41(1), 196–220.
Shortreed, S. M., & Ertefaie, A. (2017). Outcome-adaptive lasso: Variable selection for causal inference: Outcome-Adaptive Lasso. Biometrics, 73(4), 1111–1122.
|
Difference between covariates and treatment confounders in propensity score matching
The definition of a confounder is somewhat complicated, but VanderWeele & Shpitser (2013) decided
A pre-exposure covariate C is a confounder for the effect of A on Y if
it is a member of some minim
|
46,482
|
How is Logistic Regression related to Logistic Distribution?
|
One way of defining logistic regression is just introducing it as
$$ \DeclareMathOperator{\P}{\mathbb{P}}
\P(Y=1 \mid X=x) = \frac{1}{1+e^{-\eta(x)}}
$$
where $\eta(x)=\beta^T x$ is a linear predictor. This is just stating the model without saying where it comes from.
Alternatively we can try to develop the model from some underlying principle. Say there is maybe, a certain underlying, latent (not directly measurable) stress or antistress, we denote it by $\theta$, which determines the probability of a certain outcome. Maybe death (as in dose-response studies) or default, as in credit risk modeling. $\theta$ have some distribution that depends on $x$, say given by a cdf (cumulative distribution function) $F(\theta;x)$. Say the outcome of interest ($Y=1$) occurs when $\theta \le C$ for some threshold $C$. Then
$$
\P(Y=1 \mid X=x)=\P(\theta \le C\mid X=x) =F(C;x)
$$ and now the logistic distribution wiki have cdf $\frac1{1+e^{-\frac{x-\mu}{\sigma}}}$ and so if we assume the latent variable $\theta$ has a logistic distribution we finally arrive at, assuming the linear predictor $\eta(x)$ represent the mean $\mu$ via $\mu=\beta^T x$:
$$
\P(Y=1\mid x)= \frac1{1+e^{-\frac{C-\beta^T x}{\sigma}}}
$$ so in the case of a simple regression we get the intercept $C/\sigma$ and slope $\beta/\sigma$.
If the latent variable has some other distribution we get an alternative to the logit model. A normal distribution for the latent variable results in probit, for instance. A post related to this is Logistic Regression - Error Term and its Distribution.
|
How is Logistic Regression related to Logistic Distribution?
|
One way of defining logistic regression is just introducing it as
$$ \DeclareMathOperator{\P}{\mathbb{P}}
\P(Y=1 \mid X=x) = \frac{1}{1+e^{-\eta(x)}}
$$
where $\eta(x)=\beta^T x$ is a linear predict
|
How is Logistic Regression related to Logistic Distribution?
One way of defining logistic regression is just introducing it as
$$ \DeclareMathOperator{\P}{\mathbb{P}}
\P(Y=1 \mid X=x) = \frac{1}{1+e^{-\eta(x)}}
$$
where $\eta(x)=\beta^T x$ is a linear predictor. This is just stating the model without saying where it comes from.
Alternatively we can try to develop the model from some underlying principle. Say there is maybe, a certain underlying, latent (not directly measurable) stress or antistress, we denote it by $\theta$, which determines the probability of a certain outcome. Maybe death (as in dose-response studies) or default, as in credit risk modeling. $\theta$ have some distribution that depends on $x$, say given by a cdf (cumulative distribution function) $F(\theta;x)$. Say the outcome of interest ($Y=1$) occurs when $\theta \le C$ for some threshold $C$. Then
$$
\P(Y=1 \mid X=x)=\P(\theta \le C\mid X=x) =F(C;x)
$$ and now the logistic distribution wiki have cdf $\frac1{1+e^{-\frac{x-\mu}{\sigma}}}$ and so if we assume the latent variable $\theta$ has a logistic distribution we finally arrive at, assuming the linear predictor $\eta(x)$ represent the mean $\mu$ via $\mu=\beta^T x$:
$$
\P(Y=1\mid x)= \frac1{1+e^{-\frac{C-\beta^T x}{\sigma}}}
$$ so in the case of a simple regression we get the intercept $C/\sigma$ and slope $\beta/\sigma$.
If the latent variable has some other distribution we get an alternative to the logit model. A normal distribution for the latent variable results in probit, for instance. A post related to this is Logistic Regression - Error Term and its Distribution.
|
How is Logistic Regression related to Logistic Distribution?
One way of defining logistic regression is just introducing it as
$$ \DeclareMathOperator{\P}{\mathbb{P}}
\P(Y=1 \mid X=x) = \frac{1}{1+e^{-\eta(x)}}
$$
where $\eta(x)=\beta^T x$ is a linear predict
|
46,483
|
How is Logistic Regression related to Logistic Distribution?
|
One way to think of it is to consider the latent variable interpretation of logistic regression. In this interpretation, we consider a linear model for $Y^*$, a latent (i.e., unobserved) variable that represents the "propensity" for $Y=1$.
So, we have $Y^*=X\beta + \epsilon$. We get the observed values of $Y$ as $Y=I(Y^*>0)$, where $I(.)$ is the indicator function.
When $\epsilon$ is distributed as the logistic distribution with mean 0 and variance $\frac{\pi^2}{3}$, a logistic regression model correctly describes $Y$. That is, $P(Y=1)=\frac{1}{1+e^{-X \beta}}$ is the correct model for $Y$. When $\epsilon$ is distributed as the normal distribution with mean 0 and variance 1, a probit regression model correctly describes $Y$. The polychoric correlation between two variables $Y_1$ and $Y_2$ is the implied correlation of $Y^*_1$ and $Y^*_2$ assuming a probit model.
A benefit of the latent variable interpretation is that the model coefficients can be interpreted as the linear change in $Y^*$ corresponding to a 1-unit change in a predictor holding others constant, in contrast to the log odds ratio interpretation often used for logistic regression (and it seems almost impossible to interpret a probit regression coefficient). The modeled implied mean and standard deviation of $Y^*$ can be computed to see how much in standardized units of $Y^*$ a 1-unit change in a predictor is associated with, just as you would with a continuous outcome of arbitrary scale. In addition, this interpretation works regardless of whether logistic, probit, or some other type of regression model or error distribution is used.
|
How is Logistic Regression related to Logistic Distribution?
|
One way to think of it is to consider the latent variable interpretation of logistic regression. In this interpretation, we consider a linear model for $Y^*$, a latent (i.e., unobserved) variable that
|
How is Logistic Regression related to Logistic Distribution?
One way to think of it is to consider the latent variable interpretation of logistic regression. In this interpretation, we consider a linear model for $Y^*$, a latent (i.e., unobserved) variable that represents the "propensity" for $Y=1$.
So, we have $Y^*=X\beta + \epsilon$. We get the observed values of $Y$ as $Y=I(Y^*>0)$, where $I(.)$ is the indicator function.
When $\epsilon$ is distributed as the logistic distribution with mean 0 and variance $\frac{\pi^2}{3}$, a logistic regression model correctly describes $Y$. That is, $P(Y=1)=\frac{1}{1+e^{-X \beta}}$ is the correct model for $Y$. When $\epsilon$ is distributed as the normal distribution with mean 0 and variance 1, a probit regression model correctly describes $Y$. The polychoric correlation between two variables $Y_1$ and $Y_2$ is the implied correlation of $Y^*_1$ and $Y^*_2$ assuming a probit model.
A benefit of the latent variable interpretation is that the model coefficients can be interpreted as the linear change in $Y^*$ corresponding to a 1-unit change in a predictor holding others constant, in contrast to the log odds ratio interpretation often used for logistic regression (and it seems almost impossible to interpret a probit regression coefficient). The modeled implied mean and standard deviation of $Y^*$ can be computed to see how much in standardized units of $Y^*$ a 1-unit change in a predictor is associated with, just as you would with a continuous outcome of arbitrary scale. In addition, this interpretation works regardless of whether logistic, probit, or some other type of regression model or error distribution is used.
|
How is Logistic Regression related to Logistic Distribution?
One way to think of it is to consider the latent variable interpretation of logistic regression. In this interpretation, we consider a linear model for $Y^*$, a latent (i.e., unobserved) variable that
|
46,484
|
Gaussian Processes: A Crucial Assumption?
|
This assumption is not universally valid (of course). Moreover, in many cases it is not even necessary to make!
Relevant examples where it is obviously not valid are: strictly positive data (since a Gaussian has always a chance of being negative) or monotonic or convex data (same reason just for first and second derivatives).
That data is a realisation of a (stationary) Gaussian Field is a very strong assumption, which is not always necessary. Weaker assumptions will lead to weaker conclusions but in many cases these weaker conclusions are all you need.
Assumptions and possible conclusions in order of strength:
Assumption: Data is from a stationary Gaussian Field.
You are able to conclude: Hyperparameters from maximum likelihood and the full posterior/predictive distribution. Furthermore, the mean prediction is the best unbiased prediction in mean square.
Assumption: Data is from a second-order stationary process (i.e. mean and covariance function exist, full distribution not specified).
Possible conclusions: Predictive variance, best linear(!) unbiased estimate for the mean function.
Assumption: Data is deterministic, i.e. the problem is a pure interpolation problem.
Possible conclusion: "Mean" or maybe better the interpolating function.
This explains why Gaussian Process Regression is applicable in fields (such as computer experiments or numerical analysis) in which the normal or any other stochastic assumption does not make any sense.
For more details have a look at this nice overview: "Interpolation of Spatial Data - A Stochastic or a Deterministic Problem?".
|
Gaussian Processes: A Crucial Assumption?
|
This assumption is not universally valid (of course). Moreover, in many cases it is not even necessary to make!
Relevant examples where it is obviously not valid are: strictly positive data (since a G
|
Gaussian Processes: A Crucial Assumption?
This assumption is not universally valid (of course). Moreover, in many cases it is not even necessary to make!
Relevant examples where it is obviously not valid are: strictly positive data (since a Gaussian has always a chance of being negative) or monotonic or convex data (same reason just for first and second derivatives).
That data is a realisation of a (stationary) Gaussian Field is a very strong assumption, which is not always necessary. Weaker assumptions will lead to weaker conclusions but in many cases these weaker conclusions are all you need.
Assumptions and possible conclusions in order of strength:
Assumption: Data is from a stationary Gaussian Field.
You are able to conclude: Hyperparameters from maximum likelihood and the full posterior/predictive distribution. Furthermore, the mean prediction is the best unbiased prediction in mean square.
Assumption: Data is from a second-order stationary process (i.e. mean and covariance function exist, full distribution not specified).
Possible conclusions: Predictive variance, best linear(!) unbiased estimate for the mean function.
Assumption: Data is deterministic, i.e. the problem is a pure interpolation problem.
Possible conclusion: "Mean" or maybe better the interpolating function.
This explains why Gaussian Process Regression is applicable in fields (such as computer experiments or numerical analysis) in which the normal or any other stochastic assumption does not make any sense.
For more details have a look at this nice overview: "Interpolation of Spatial Data - A Stochastic or a Deterministic Problem?".
|
Gaussian Processes: A Crucial Assumption?
This assumption is not universally valid (of course). Moreover, in many cases it is not even necessary to make!
Relevant examples where it is obviously not valid are: strictly positive data (since a G
|
46,485
|
Gaussian Processes: A Crucial Assumption?
|
By definition, a random process is a collection of random variables indexed by the elements of some set $\mathbb T$ which is typically $\mathbb R$ or $\mathbb Z$. Thus, the random process is the set $\{X(t)\colon t \in \mathbb T\}$ where $X(t)$ is the called the $t$-th random variable.
By definition, a Gaussian random process $\{X(t)\colon t \in \mathbb T\}$is a random process for which
For all choices of $n>0$ and all choices of time instants $t_1, t_2, \ldots, t_n \in \mathbb T$, $X(t_1), X(t_2,), \ldots, X(t_n)$ have a jointly Gaussian (also called a multivariate Gaussian) distribution.
Members of Nitpickers Anonymous please note that for $n = 1$, the sole random variable $X(t)$ (where $t\in \mathbb T$) has just a univariate Gaussian distribution and not a multivariate Gaussian distribution. So, the multivariate Gaussianity of $X(t_1), X(t_2,), \ldots, X(t_n)$ is actually baked into the definition of Gaussian random process.
"But, but, but," you splutter, "it says arbitrary data set, not a Gaussian random process." Well, the canonical model for arbitrary data sets is that they are (independent) samples from a Gaussian distribution and we don't abandon that unless someone beats us over the head and insists that it is not so. So, the data can be modeled as multivariate Gaussian (which, I remind those who march to the beat of a different drummer, includes independent Gaussian as a special case.)
Well, that's enough thought for today.
|
Gaussian Processes: A Crucial Assumption?
|
By definition, a random process is a collection of random variables indexed by the elements of some set $\mathbb T$ which is typically $\mathbb R$ or $\mathbb Z$. Thus, the random process is the set $
|
Gaussian Processes: A Crucial Assumption?
By definition, a random process is a collection of random variables indexed by the elements of some set $\mathbb T$ which is typically $\mathbb R$ or $\mathbb Z$. Thus, the random process is the set $\{X(t)\colon t \in \mathbb T\}$ where $X(t)$ is the called the $t$-th random variable.
By definition, a Gaussian random process $\{X(t)\colon t \in \mathbb T\}$is a random process for which
For all choices of $n>0$ and all choices of time instants $t_1, t_2, \ldots, t_n \in \mathbb T$, $X(t_1), X(t_2,), \ldots, X(t_n)$ have a jointly Gaussian (also called a multivariate Gaussian) distribution.
Members of Nitpickers Anonymous please note that for $n = 1$, the sole random variable $X(t)$ (where $t\in \mathbb T$) has just a univariate Gaussian distribution and not a multivariate Gaussian distribution. So, the multivariate Gaussianity of $X(t_1), X(t_2,), \ldots, X(t_n)$ is actually baked into the definition of Gaussian random process.
"But, but, but," you splutter, "it says arbitrary data set, not a Gaussian random process." Well, the canonical model for arbitrary data sets is that they are (independent) samples from a Gaussian distribution and we don't abandon that unless someone beats us over the head and insists that it is not so. So, the data can be modeled as multivariate Gaussian (which, I remind those who march to the beat of a different drummer, includes independent Gaussian as a special case.)
Well, that's enough thought for today.
|
Gaussian Processes: A Crucial Assumption?
By definition, a random process is a collection of random variables indexed by the elements of some set $\mathbb T$ which is typically $\mathbb R$ or $\mathbb Z$. Thus, the random process is the set $
|
46,486
|
Why is sufficient statistics/data reduction normally taught in Statistics?
|
This answer is an oversimplification, bound to criticism, but I also believe it carries the essence behind the reason sufficient statistics are useful: the motivation for a sufficient statistics is the possibility it gives us of assessing information on the entire population without the need of all the data.
Say you get your grade on an exam and you want to know how well you did compared to your classmates. If you are given a sample mean and variance, you can do this without asking everyone's grades. Isn't it cool?
|
Why is sufficient statistics/data reduction normally taught in Statistics?
|
This answer is an oversimplification, bound to criticism, but I also believe it carries the essence behind the reason sufficient statistics are useful: the motivation for a sufficient statistics is th
|
Why is sufficient statistics/data reduction normally taught in Statistics?
This answer is an oversimplification, bound to criticism, but I also believe it carries the essence behind the reason sufficient statistics are useful: the motivation for a sufficient statistics is the possibility it gives us of assessing information on the entire population without the need of all the data.
Say you get your grade on an exam and you want to know how well you did compared to your classmates. If you are given a sample mean and variance, you can do this without asking everyone's grades. Isn't it cool?
|
Why is sufficient statistics/data reduction normally taught in Statistics?
This answer is an oversimplification, bound to criticism, but I also believe it carries the essence behind the reason sufficient statistics are useful: the motivation for a sufficient statistics is th
|
46,487
|
Why is sufficient statistics/data reduction normally taught in Statistics?
|
What you've been told is certainly NOT true. Data reduction is as important as ever. See for example Donoho's work on Compressed Sensing and thresholding estimators. Wavelet estimators and regularised estimators also work similarly - aim is to compress data on as few coefficient as possible. There is a parallel too with the concept of simplicity - compression allows us to describe data with a model as simple as possible (but not too simple) - Minimum Description/Message Length theories follow those lines.
The concept of sufficiency is nearly as old as the concept of (modern) statistics. It has been defined by Ronald A. Fisher on his seminal 1922 paper.
As you may read, a sufficient statistic is the one that summarises the whole of the relevant information provided by the sample. Mathematically, if $\theta$ is to be estimated, $T_1(X)$ a statistic which contains the whole of the information as to the value of $\theta$, and $T_2(X)$ any other statistic, then the surface of distribution of pairs $T_1(X)$ $T_2(X)$, for a given value of $\theta$, is such that for a given value of $T_1(X)$, the distribution of $T_2(X)$ does not involve $\theta$. When $T_1(X)$ is known, knowledge of the value of $T_2(X)$ throws no further light upon the value of $\theta$.
That is, once you know the value sufficient statistic for the parameter of the population to be estimated, you need no further information - you don't need to store/process any subset of your data. Everything that can be said about the data is compressed on this statistic.
|
Why is sufficient statistics/data reduction normally taught in Statistics?
|
What you've been told is certainly NOT true. Data reduction is as important as ever. See for example Donoho's work on Compressed Sensing and thresholding estimators. Wavelet estimators and regularised
|
Why is sufficient statistics/data reduction normally taught in Statistics?
What you've been told is certainly NOT true. Data reduction is as important as ever. See for example Donoho's work on Compressed Sensing and thresholding estimators. Wavelet estimators and regularised estimators also work similarly - aim is to compress data on as few coefficient as possible. There is a parallel too with the concept of simplicity - compression allows us to describe data with a model as simple as possible (but not too simple) - Minimum Description/Message Length theories follow those lines.
The concept of sufficiency is nearly as old as the concept of (modern) statistics. It has been defined by Ronald A. Fisher on his seminal 1922 paper.
As you may read, a sufficient statistic is the one that summarises the whole of the relevant information provided by the sample. Mathematically, if $\theta$ is to be estimated, $T_1(X)$ a statistic which contains the whole of the information as to the value of $\theta$, and $T_2(X)$ any other statistic, then the surface of distribution of pairs $T_1(X)$ $T_2(X)$, for a given value of $\theta$, is such that for a given value of $T_1(X)$, the distribution of $T_2(X)$ does not involve $\theta$. When $T_1(X)$ is known, knowledge of the value of $T_2(X)$ throws no further light upon the value of $\theta$.
That is, once you know the value sufficient statistic for the parameter of the population to be estimated, you need no further information - you don't need to store/process any subset of your data. Everything that can be said about the data is compressed on this statistic.
|
Why is sufficient statistics/data reduction normally taught in Statistics?
What you've been told is certainly NOT true. Data reduction is as important as ever. See for example Donoho's work on Compressed Sensing and thresholding estimators. Wavelet estimators and regularised
|
46,488
|
Why is sufficient statistics/data reduction normally taught in Statistics?
|
You are correct in suggesting that the availability of almost limitless computational resources means that the importance of data reduction is lessened. For example, resampling statistics, at one time too computationally expensive for practical use, allow the entire sample to be utilised directly without assumption of populations. However, data reduction and sufficient statistics remains just about as important as ever.
Data reduction allows you to see what the data say about the topic of interest without the overwhelming distraction of the data. (Something about forest and trees should go here, I suspect.) Choose a sufficient statistic relevant to the topic, and take extra care is there doesn't happen to be one.
|
Why is sufficient statistics/data reduction normally taught in Statistics?
|
You are correct in suggesting that the availability of almost limitless computational resources means that the importance of data reduction is lessened. For example, resampling statistics, at one time
|
Why is sufficient statistics/data reduction normally taught in Statistics?
You are correct in suggesting that the availability of almost limitless computational resources means that the importance of data reduction is lessened. For example, resampling statistics, at one time too computationally expensive for practical use, allow the entire sample to be utilised directly without assumption of populations. However, data reduction and sufficient statistics remains just about as important as ever.
Data reduction allows you to see what the data say about the topic of interest without the overwhelming distraction of the data. (Something about forest and trees should go here, I suspect.) Choose a sufficient statistic relevant to the topic, and take extra care is there doesn't happen to be one.
|
Why is sufficient statistics/data reduction normally taught in Statistics?
You are correct in suggesting that the availability of almost limitless computational resources means that the importance of data reduction is lessened. For example, resampling statistics, at one time
|
46,489
|
Where does linear regression fit into the bias-variance tradeoff?
|
OLS is an unbiased estimator assuming the model is true, which is to say,
Effects are exactly linear
All variables with non-zero effects are included
All interactions are included
no non-linear effects
and other small model inadequacies. See my answer at Why do irrelevant regressors become statistically significant in large samples?. The bias-variance decomposition is (from section 7.3 of ESL, second edition)
$$\DeclareMathOperator{\E}{\mathbb{E}}\begin{align}
\text{Err}(x_0)&=\E[(Y-\hat{f}(x_0)))^2\mid X=x_0] \\
&=\sigma^2_\epsilon + [\E \hat{f}(x_0)-f(x_0)]^2 + \E [\hat{f}(x_0)-\E\hat{f}(x_0)]^2 \\
&= \sigma^2_ \epsilon + \text{Bias}^2(\hat{f}(x_0)) + \text{Var}(\hat{f}(x_0))\\
&= \text{Irreducible Error}+\text{Bias}^2 + \text{Variance}.
\end{align} $$
If your model is correct, the $\text{Bias}^2$ term will be zero, but if the model is approximate, it will not.
|
Where does linear regression fit into the bias-variance tradeoff?
|
OLS is an unbiased estimator assuming the model is true, which is to say,
Effects are exactly linear
All variables with non-zero effects are included
All interactions are included
no non-linear effec
|
Where does linear regression fit into the bias-variance tradeoff?
OLS is an unbiased estimator assuming the model is true, which is to say,
Effects are exactly linear
All variables with non-zero effects are included
All interactions are included
no non-linear effects
and other small model inadequacies. See my answer at Why do irrelevant regressors become statistically significant in large samples?. The bias-variance decomposition is (from section 7.3 of ESL, second edition)
$$\DeclareMathOperator{\E}{\mathbb{E}}\begin{align}
\text{Err}(x_0)&=\E[(Y-\hat{f}(x_0)))^2\mid X=x_0] \\
&=\sigma^2_\epsilon + [\E \hat{f}(x_0)-f(x_0)]^2 + \E [\hat{f}(x_0)-\E\hat{f}(x_0)]^2 \\
&= \sigma^2_ \epsilon + \text{Bias}^2(\hat{f}(x_0)) + \text{Var}(\hat{f}(x_0))\\
&= \text{Irreducible Error}+\text{Bias}^2 + \text{Variance}.
\end{align} $$
If your model is correct, the $\text{Bias}^2$ term will be zero, but if the model is approximate, it will not.
|
Where does linear regression fit into the bias-variance tradeoff?
OLS is an unbiased estimator assuming the model is true, which is to say,
Effects are exactly linear
All variables with non-zero effects are included
All interactions are included
no non-linear effec
|
46,490
|
Where does linear regression fit into the bias-variance tradeoff?
|
Linear regression is a general term. When used, $y=ax+b+\epsilon$ is what comes to mind first, however $y=ax^2+bx+c+\epsilon$ is also linear regression, i.e. $x_2=x, x_1=x^2$ and $y=ax_1+bx_2+c+\epsilon$. It's just we use polynomial features. The data (target) can be of parabolic nature but it can still be estimated via linear regression if you use polynomial features. High bias occurs when you use overly simplistic model compared to the data; not specifically when you use the model $y=ax+b+\epsilon$.
Unbiased estimator is a slightly different concept. If an estimator, say $\hat{\theta}$ for a variable $\theta$ is unbiased, then we have $E[\hat{\theta}]=\theta$. A very simple unbiased estimator is the mean; it is also unbiased since if $\hat{\theta}=\mu$ then the expected value of it will equal to the mean: $E[\hat{\theta}]=E[\mu]=\mu=E[\theta]$. Therefore, let alone OLS, using just the mean is an unbiased estimation technique. So, having an unbiased estimator doesn't mean that your estimator fits well to your data.
|
Where does linear regression fit into the bias-variance tradeoff?
|
Linear regression is a general term. When used, $y=ax+b+\epsilon$ is what comes to mind first, however $y=ax^2+bx+c+\epsilon$ is also linear regression, i.e. $x_2=x, x_1=x^2$ and $y=ax_1+bx_2+c+\epsi
|
Where does linear regression fit into the bias-variance tradeoff?
Linear regression is a general term. When used, $y=ax+b+\epsilon$ is what comes to mind first, however $y=ax^2+bx+c+\epsilon$ is also linear regression, i.e. $x_2=x, x_1=x^2$ and $y=ax_1+bx_2+c+\epsilon$. It's just we use polynomial features. The data (target) can be of parabolic nature but it can still be estimated via linear regression if you use polynomial features. High bias occurs when you use overly simplistic model compared to the data; not specifically when you use the model $y=ax+b+\epsilon$.
Unbiased estimator is a slightly different concept. If an estimator, say $\hat{\theta}$ for a variable $\theta$ is unbiased, then we have $E[\hat{\theta}]=\theta$. A very simple unbiased estimator is the mean; it is also unbiased since if $\hat{\theta}=\mu$ then the expected value of it will equal to the mean: $E[\hat{\theta}]=E[\mu]=\mu=E[\theta]$. Therefore, let alone OLS, using just the mean is an unbiased estimation technique. So, having an unbiased estimator doesn't mean that your estimator fits well to your data.
|
Where does linear regression fit into the bias-variance tradeoff?
Linear regression is a general term. When used, $y=ax+b+\epsilon$ is what comes to mind first, however $y=ax^2+bx+c+\epsilon$ is also linear regression, i.e. $x_2=x, x_1=x^2$ and $y=ax_1+bx_2+c+\epsi
|
46,491
|
Resources for hierarchical modelling in R
|
If you just want a practical guide to fitting mixed models / multilevel models, then the link provided by Mark White is a very good one:
https://rpsychologist.com/r-guide-longitudinal-lme-lmer
However, if you seek to understand the theory, then I would highly recommend looking at mixed models - of which multilevel models can be thought of as a sub-type, then I would suggest the following:
Demidenko, E. (2013). Mixed models: theory and applications with R. John Wiley & Sons.
Bates, D. M. (2010). lme4: Mixed-effects modeling with R.
Bates, D., Mächler, M., Bolker, B., & Walker, S. (2014). Fitting linear mixed-effects models using lme4. arXiv preprint arXiv:1406.5823.
The latter two are both available for free on the internet.
|
Resources for hierarchical modelling in R
|
If you just want a practical guide to fitting mixed models / multilevel models, then the link provided by Mark White is a very good one:
https://rpsychologist.com/r-guide-longitudinal-lme-lmer
However
|
Resources for hierarchical modelling in R
If you just want a practical guide to fitting mixed models / multilevel models, then the link provided by Mark White is a very good one:
https://rpsychologist.com/r-guide-longitudinal-lme-lmer
However, if you seek to understand the theory, then I would highly recommend looking at mixed models - of which multilevel models can be thought of as a sub-type, then I would suggest the following:
Demidenko, E. (2013). Mixed models: theory and applications with R. John Wiley & Sons.
Bates, D. M. (2010). lme4: Mixed-effects modeling with R.
Bates, D., Mächler, M., Bolker, B., & Walker, S. (2014). Fitting linear mixed-effects models using lme4. arXiv preprint arXiv:1406.5823.
The latter two are both available for free on the internet.
|
Resources for hierarchical modelling in R
If you just want a practical guide to fitting mixed models / multilevel models, then the link provided by Mark White is a very good one:
https://rpsychologist.com/r-guide-longitudinal-lme-lmer
However
|
46,492
|
Resources for hierarchical modelling in R
|
My favorite is: https://rpsychologist.com/r-guide-longitudinal-lme-lmer. He shows both commonly-used packages, and he includes the equations alongside the code—so you can easily reference back to books from there.
|
Resources for hierarchical modelling in R
|
My favorite is: https://rpsychologist.com/r-guide-longitudinal-lme-lmer. He shows both commonly-used packages, and he includes the equations alongside the code—so you can easily reference back to book
|
Resources for hierarchical modelling in R
My favorite is: https://rpsychologist.com/r-guide-longitudinal-lme-lmer. He shows both commonly-used packages, and he includes the equations alongside the code—so you can easily reference back to books from there.
|
Resources for hierarchical modelling in R
My favorite is: https://rpsychologist.com/r-guide-longitudinal-lme-lmer. He shows both commonly-used packages, and he includes the equations alongside the code—so you can easily reference back to book
|
46,493
|
Resources for hierarchical modelling in R
|
Take a look at these:
GLMM FAQ Ben Bolker and others: https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html
nlme package: https://cran.r-project.org/web/packages/nlme/nlme.pdf, which allows non- linear mixed models and correlations structures
glmmTMB: https://cran.r-project.org/web/packages/glmmTMB/glmmTMB.pdf
Enjoy!
|
Resources for hierarchical modelling in R
|
Take a look at these:
GLMM FAQ Ben Bolker and others: https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html
nlme package: https://cran.r-project.org/web/packages/nlme/nlme.pdf, which allows non- lin
|
Resources for hierarchical modelling in R
Take a look at these:
GLMM FAQ Ben Bolker and others: https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html
nlme package: https://cran.r-project.org/web/packages/nlme/nlme.pdf, which allows non- linear mixed models and correlations structures
glmmTMB: https://cran.r-project.org/web/packages/glmmTMB/glmmTMB.pdf
Enjoy!
|
Resources for hierarchical modelling in R
Take a look at these:
GLMM FAQ Ben Bolker and others: https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html
nlme package: https://cran.r-project.org/web/packages/nlme/nlme.pdf, which allows non- lin
|
46,494
|
Resources for hierarchical modelling in R
|
I built R a package recently on Bayesian network modeling.
In the package description page you'll find varies examples of hierarchical models, their CPDs, graphical models structures, learning/inference algorithms and the corresponding R code.
|
Resources for hierarchical modelling in R
|
I built R a package recently on Bayesian network modeling.
In the package description page you'll find varies examples of hierarchical models, their CPDs, graphical models structures, learning/inferen
|
Resources for hierarchical modelling in R
I built R a package recently on Bayesian network modeling.
In the package description page you'll find varies examples of hierarchical models, their CPDs, graphical models structures, learning/inference algorithms and the corresponding R code.
|
Resources for hierarchical modelling in R
I built R a package recently on Bayesian network modeling.
In the package description page you'll find varies examples of hierarchical models, their CPDs, graphical models structures, learning/inferen
|
46,495
|
Resources for hierarchical modelling in R
|
I find this resource very helpful, it also contains methods for cross-sectional nested data:
https://methodenlehre.github.io/intro-to-rstats/hierarchical-linear-models.html
|
Resources for hierarchical modelling in R
|
I find this resource very helpful, it also contains methods for cross-sectional nested data:
https://methodenlehre.github.io/intro-to-rstats/hierarchical-linear-models.html
|
Resources for hierarchical modelling in R
I find this resource very helpful, it also contains methods for cross-sectional nested data:
https://methodenlehre.github.io/intro-to-rstats/hierarchical-linear-models.html
|
Resources for hierarchical modelling in R
I find this resource very helpful, it also contains methods for cross-sectional nested data:
https://methodenlehre.github.io/intro-to-rstats/hierarchical-linear-models.html
|
46,496
|
Do GEE and GLM estimate the same coefficients?
|
Yes. GEE and GLM will indeed have the same coefficients, but different standard errors. To check, run an example in R. I've taken this example from Chapter 25 of Applied Regression Analysis and Other Multivariable Methods, 5th by Kleinbaum, et. al (just because it's on my desk and references GEE and GLM):
library(geepack)
library(lme4)
#get book data from
mydf<-read.table("http://www.hmwu.idv.tw/web/bigdata/rstudio-readData/tab/ch25q04.txt", header=TRUE)
mydf<-data.frame(subj=mydf$subj, week=as.factor(mydf$week), fev=mydf$fev)
#Make 5th level the reference level to match book results
mydf$week<-relevel(mydf$week, ref="5")
#Fit GLM Mixed Model
mixed.model<-summary(lme4::lmer(fev~week+(1|subj),data=mydf))
mixed.model$coefficients
Estimate Std. Error t value
(Intercept) 6.99850 0.2590243 27.01870247
week1 2.81525 0.2439374 11.54087244
week2 -0.15025 0.2439374 -0.61593680
week3 0.00325 0.2439374 0.01332309
week4 -0.04700 0.2439374 -0.19267241
#Fit a gee model with any correlation structure. In this case AR1
gee.model<-summary(geeglm(fev~week, id=subj, waves=week, corstr="ar1", data=mydf))
gee.model$coefficients
[Estimate Std.err Wald Pr(>|W|)
(Intercept) 6.99850 0.2418413 8.374312e+02 0.0000000
week1 2.81525 0.2514376 1.253642e+02 0.0000000
week2 -0.15025 0.2051973 5.361492e-01 0.4640330
week3 0.00325 0.2075914 2.451027e-04 0.9875090
week4 -0.04700 0.2388983 3.870522e-02 0.8440338][1]
UPDATE
As Mark White pointed out in his comment, I did indeed previously fit a "single-level" Mixed Effects GLM. Since you didn't specify whether you wanted a "fixed effects" or "random" effects GLM model, I just picked "random" since that's the model fit in the book I selected from. But indeed, Mark is right that the coefficients do not necessarily agree in multilevel models, and someone provided a nice answer about that question previously. For your reference, I've added a "fixed" effects GLM model below using lm.
#Fit Traditional GLM Fixed Effect Model (i.e. not Random effects)
glm.fixed<-summary(lm(fev~week, data=mydf))
glm.fixed$coefficients
Estimate Std. Error t value Pr(>|t|)
(Intercept) 6.99850 0.2590243 27.01870247 7.696137e-68
week1 2.81525 0.3663157 7.68531179 7.287752e-13
week2 -0.15025 0.3663157 -0.41016538 6.821349e-01
week3 0.00325 0.3663157 0.00887213 9.929302e-01
week4 -0.04700 0.3663157 -0.12830465 8.980401e-01
Note the first and second columns of the output in each model. They coefficients are identity, but standard errors differ.
You also added a comment which asked, "And does this remain the case when we choose a non-linear link function?" Note first that this is a different question since non-linear link functions generally aren't General Linear Models but Generalized Linear models. In this case, the coefficients do not necessarily match. Here's an example again in R:
#Fit Generalized Linear Mixed Effects Model with, say, Binomail Link
nlmixed.model<-summary(lme4::glmer(I(mydf$fev>mean(mydf$fev))~week+(1|subj), family="binomial", data=mydf))
nlmixed.model$coefficients
#Fit GEE model with, say, Binomial Link
nlgee.model<-summary(geeglm(I(mydf$fev>mean(mydf$fev))~week, id=subj, waves=week, family="binomial", data=mydf))
nlgee.model$coefficients
|
Do GEE and GLM estimate the same coefficients?
|
Yes. GEE and GLM will indeed have the same coefficients, but different standard errors. To check, run an example in R. I've taken this example from Chapter 25 of Applied Regression Analysis and Othe
|
Do GEE and GLM estimate the same coefficients?
Yes. GEE and GLM will indeed have the same coefficients, but different standard errors. To check, run an example in R. I've taken this example from Chapter 25 of Applied Regression Analysis and Other Multivariable Methods, 5th by Kleinbaum, et. al (just because it's on my desk and references GEE and GLM):
library(geepack)
library(lme4)
#get book data from
mydf<-read.table("http://www.hmwu.idv.tw/web/bigdata/rstudio-readData/tab/ch25q04.txt", header=TRUE)
mydf<-data.frame(subj=mydf$subj, week=as.factor(mydf$week), fev=mydf$fev)
#Make 5th level the reference level to match book results
mydf$week<-relevel(mydf$week, ref="5")
#Fit GLM Mixed Model
mixed.model<-summary(lme4::lmer(fev~week+(1|subj),data=mydf))
mixed.model$coefficients
Estimate Std. Error t value
(Intercept) 6.99850 0.2590243 27.01870247
week1 2.81525 0.2439374 11.54087244
week2 -0.15025 0.2439374 -0.61593680
week3 0.00325 0.2439374 0.01332309
week4 -0.04700 0.2439374 -0.19267241
#Fit a gee model with any correlation structure. In this case AR1
gee.model<-summary(geeglm(fev~week, id=subj, waves=week, corstr="ar1", data=mydf))
gee.model$coefficients
[Estimate Std.err Wald Pr(>|W|)
(Intercept) 6.99850 0.2418413 8.374312e+02 0.0000000
week1 2.81525 0.2514376 1.253642e+02 0.0000000
week2 -0.15025 0.2051973 5.361492e-01 0.4640330
week3 0.00325 0.2075914 2.451027e-04 0.9875090
week4 -0.04700 0.2388983 3.870522e-02 0.8440338][1]
UPDATE
As Mark White pointed out in his comment, I did indeed previously fit a "single-level" Mixed Effects GLM. Since you didn't specify whether you wanted a "fixed effects" or "random" effects GLM model, I just picked "random" since that's the model fit in the book I selected from. But indeed, Mark is right that the coefficients do not necessarily agree in multilevel models, and someone provided a nice answer about that question previously. For your reference, I've added a "fixed" effects GLM model below using lm.
#Fit Traditional GLM Fixed Effect Model (i.e. not Random effects)
glm.fixed<-summary(lm(fev~week, data=mydf))
glm.fixed$coefficients
Estimate Std. Error t value Pr(>|t|)
(Intercept) 6.99850 0.2590243 27.01870247 7.696137e-68
week1 2.81525 0.3663157 7.68531179 7.287752e-13
week2 -0.15025 0.3663157 -0.41016538 6.821349e-01
week3 0.00325 0.3663157 0.00887213 9.929302e-01
week4 -0.04700 0.3663157 -0.12830465 8.980401e-01
Note the first and second columns of the output in each model. They coefficients are identity, but standard errors differ.
You also added a comment which asked, "And does this remain the case when we choose a non-linear link function?" Note first that this is a different question since non-linear link functions generally aren't General Linear Models but Generalized Linear models. In this case, the coefficients do not necessarily match. Here's an example again in R:
#Fit Generalized Linear Mixed Effects Model with, say, Binomail Link
nlmixed.model<-summary(lme4::glmer(I(mydf$fev>mean(mydf$fev))~week+(1|subj), family="binomial", data=mydf))
nlmixed.model$coefficients
#Fit GEE model with, say, Binomial Link
nlgee.model<-summary(geeglm(I(mydf$fev>mean(mydf$fev))~week, id=subj, waves=week, family="binomial", data=mydf))
nlgee.model$coefficients
|
Do GEE and GLM estimate the same coefficients?
Yes. GEE and GLM will indeed have the same coefficients, but different standard errors. To check, run an example in R. I've taken this example from Chapter 25 of Applied Regression Analysis and Othe
|
46,497
|
Do GEE and GLM estimate the same coefficients?
|
It depends on exactly what you mean and what you're assuming.
If you use the independence working correlation, the parameter estimates $\hat\beta$ in glm and GEE will be identical, with only the standard errors being potentially different
If you use another working correlation, the parameter estimates $\hat\beta$ will not be identical. They will estimate the same underlying parameter $\beta$ if $$E[Y_{it}|{\mathbf{X_{i}=x_i}]}=x_{it}\beta$$ for a linear model (or the equivalent with a link function for a generalised linear model). That is, they will estimate the same parameter if the marginal model is correctly specified with respect to past and future $x$, not just current $x$. (see this question).
If it's only true that $$E[Y_{it}|X_{it}=x_{it}]=x_{it}\beta$$ then the underlying parameters will differ (except with a diagonal working correlation matrix). What happens is that $Y_{it}-\mu_{it}$ is correlated with $X_{is}$ for $s\neq t$, and using a non-diagonal working correlation matrix brings terms like $(Y_{it}-\mu_{it})X_isV^{st}$ into the expectation of the estimating equations, where $V^{st}$ is the $(s,t)$ element of the inverse of the working covariance matrix.
It's also quite possible that even $$E[Y_{it}|X_{it}=x_{it}]=x_{it}\beta$$ isn't true, in which case the parameters and estimates will again depend on the working correlation matrix. For example, it could be that the difference in $Y$ for a one-unit difference in $X$ between people and within people might not be the same. The difference between smokers and non-smokers might be larger than that effect of starting or stopping smoking, either because duration matters or because there are other differences between smokers and non-smokers. Different working correlation structures will weight between-person and within-person contrasts differently. This paper talks about examples
|
Do GEE and GLM estimate the same coefficients?
|
It depends on exactly what you mean and what you're assuming.
If you use the independence working correlation, the parameter estimates $\hat\beta$ in glm and GEE will be identical, with only the stan
|
Do GEE and GLM estimate the same coefficients?
It depends on exactly what you mean and what you're assuming.
If you use the independence working correlation, the parameter estimates $\hat\beta$ in glm and GEE will be identical, with only the standard errors being potentially different
If you use another working correlation, the parameter estimates $\hat\beta$ will not be identical. They will estimate the same underlying parameter $\beta$ if $$E[Y_{it}|{\mathbf{X_{i}=x_i}]}=x_{it}\beta$$ for a linear model (or the equivalent with a link function for a generalised linear model). That is, they will estimate the same parameter if the marginal model is correctly specified with respect to past and future $x$, not just current $x$. (see this question).
If it's only true that $$E[Y_{it}|X_{it}=x_{it}]=x_{it}\beta$$ then the underlying parameters will differ (except with a diagonal working correlation matrix). What happens is that $Y_{it}-\mu_{it}$ is correlated with $X_{is}$ for $s\neq t$, and using a non-diagonal working correlation matrix brings terms like $(Y_{it}-\mu_{it})X_isV^{st}$ into the expectation of the estimating equations, where $V^{st}$ is the $(s,t)$ element of the inverse of the working covariance matrix.
It's also quite possible that even $$E[Y_{it}|X_{it}=x_{it}]=x_{it}\beta$$ isn't true, in which case the parameters and estimates will again depend on the working correlation matrix. For example, it could be that the difference in $Y$ for a one-unit difference in $X$ between people and within people might not be the same. The difference between smokers and non-smokers might be larger than that effect of starting or stopping smoking, either because duration matters or because there are other differences between smokers and non-smokers. Different working correlation structures will weight between-person and within-person contrasts differently. This paper talks about examples
|
Do GEE and GLM estimate the same coefficients?
It depends on exactly what you mean and what you're assuming.
If you use the independence working correlation, the parameter estimates $\hat\beta$ in glm and GEE will be identical, with only the stan
|
46,498
|
Do GEE and GLM estimate the same coefficients?
|
I think it may not.
The estimated equations, in their formulas, depend on the inverse of the working covariance matrix. If we change it, the beta coefficients will change too, because the entire equation will change.
While in the GLM the working correlation is not applicable - it's fixed, independent.
And it can be shown:
For the independence, the beta are the same. Notice, that GEE reports the original ones taken from the GLM, so we can compare the output from the GLM and GEE instatntly:
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "independence")))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 251.4 6.61 38.03 6.63 37.91
Days 10.5 1.24 8.45 1.50 6.97
But not, when we change the structure. They are close, but not identical.
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "AR-M", Mv=1)))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 253.5 10.71 23.67 6.36 39.88
Days 10.5 1.67 6.25 1.44 7.27
or
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "AR-M", Mv=2)))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 253.8 10.83 23.45 6.45 39.34
Days 10.4 1.57 6.65 1.46 7.18
>
or
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "unstructured")))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 252.04 7.33 34.40 10.09 24.97
Days 9.78 1.02 9.62 2.64 3.71
|
Do GEE and GLM estimate the same coefficients?
|
I think it may not.
The estimated equations, in their formulas, depend on the inverse of the working covariance matrix. If we change it, the beta coefficients will change too, because the entire equat
|
Do GEE and GLM estimate the same coefficients?
I think it may not.
The estimated equations, in their formulas, depend on the inverse of the working covariance matrix. If we change it, the beta coefficients will change too, because the entire equation will change.
While in the GLM the working correlation is not applicable - it's fixed, independent.
And it can be shown:
For the independence, the beta are the same. Notice, that GEE reports the original ones taken from the GLM, so we can compare the output from the GLM and GEE instatntly:
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "independence")))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 251.4 6.61 38.03 6.63 37.91
Days 10.5 1.24 8.45 1.50 6.97
But not, when we change the structure. They are close, but not identical.
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "AR-M", Mv=1)))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 253.5 10.71 23.67 6.36 39.88
Days 10.5 1.67 6.25 1.44 7.27
or
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "AR-M", Mv=2)))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 253.8 10.83 23.45 6.45 39.34
Days 10.4 1.57 6.65 1.46 7.18
>
or
> coef(summary(gee(Reaction ~ Days, id = Subject,data = sleepstudy,corstr = "unstructured")))
Beginning Cgee S-function, @(#) geeformula.q 4.13 98/01/27
running glm to get initial regression estimate
(Intercept) Days
251.4 10.5
Estimate Naive S.E. Naive z Robust S.E. Robust z
(Intercept) 252.04 7.33 34.40 10.09 24.97
Days 9.78 1.02 9.62 2.64 3.71
|
Do GEE and GLM estimate the same coefficients?
I think it may not.
The estimated equations, in their formulas, depend on the inverse of the working covariance matrix. If we change it, the beta coefficients will change too, because the entire equat
|
46,499
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
|
without explicitly finding the distribution of $(Y_1,Y_2)$ can I justify that the distribution is not jointly normal?
One obvious way would be to see that $Y_1$ and $Y_2$ cannot be opposite in sign, and therefore cannot be bivariate normal.
Equivalently, note that $Y_1Y_2=\text{sign}(X_1)X_1\,\text{sign}(X_2)X_2$ $=|X_1|\cdot |X_2|$ must be non-negative.
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
|
without explicitly finding the distribution of $(Y_1,Y_2)$ can I justify that the distribution is not jointly normal?
One obvious way would be to see that $Y_1$ and $Y_2$ cannot be opposite in sign,
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
without explicitly finding the distribution of $(Y_1,Y_2)$ can I justify that the distribution is not jointly normal?
One obvious way would be to see that $Y_1$ and $Y_2$ cannot be opposite in sign, and therefore cannot be bivariate normal.
Equivalently, note that $Y_1Y_2=\text{sign}(X_1)X_1\,\text{sign}(X_2)X_2$ $=|X_1|\cdot |X_2|$ must be non-negative.
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
without explicitly finding the distribution of $(Y_1,Y_2)$ can I justify that the distribution is not jointly normal?
One obvious way would be to see that $Y_1$ and $Y_2$ cannot be opposite in sign,
|
46,500
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
|
To see what happens, let's explicitly find the distribution.
You could see it as a transformation from the entire plane to the first and third quadrants.
Transform the first quadrant ($X_1>0, X_2>0$) to itself $Y_1,Y_2 = X_1,X_2$.
Mirror the third quadrant ($X_1<0, X_2<0$) to the first trough the origin $Y_1,Y_2 = -X_1,-X_2$.
Mirror the second quadrant ($X_1<0, X_2>0$) along the x-axis to the third quadrant $Y_1,Y_2 = X_1,-X_2$
Mirror the fourth quadrant ($X_1>0,X_2 <0$) along the y-axis to the third quadrant $Y_1,Y_2 = -X_1,X_2$.
Overall you map all four quadrants to only the first and third quadrant. This relates to the answer of Glen_b.
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
|
To see what happens, let's explicitly find the distribution.
You could see it as a transformation from the entire plane to the first and third quadrants.
Transform the first quadrant ($X_1>0, X_2>0
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
To see what happens, let's explicitly find the distribution.
You could see it as a transformation from the entire plane to the first and third quadrants.
Transform the first quadrant ($X_1>0, X_2>0$) to itself $Y_1,Y_2 = X_1,X_2$.
Mirror the third quadrant ($X_1<0, X_2<0$) to the first trough the origin $Y_1,Y_2 = -X_1,-X_2$.
Mirror the second quadrant ($X_1<0, X_2>0$) along the x-axis to the third quadrant $Y_1,Y_2 = X_1,-X_2$
Mirror the fourth quadrant ($X_1>0,X_2 <0$) along the y-axis to the third quadrant $Y_1,Y_2 = -X_1,X_2$.
Overall you map all four quadrants to only the first and third quadrant. This relates to the answer of Glen_b.
|
How to justify that $(Y_1,Y_2)$ is not bivariate normal without finding its exact distribution?
To see what happens, let's explicitly find the distribution.
You could see it as a transformation from the entire plane to the first and third quadrants.
Transform the first quadrant ($X_1>0, X_2>0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.