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
|
|---|---|---|---|---|---|---|
42,701
|
Observations for a bivariate Gaussian mixture
|
In an alternative way you could use the requirement and sufficient condition that you have independence iff the combined probability of $X_1$ and $X_2$ is the product of the probability of $X_1$ and $X_2$.
$$f_{(X_1,X_2)} = f_{X_1} f_{X_2}$$
And this you could work out more easily (more easily in the sense that the part after your 'notice that...' is not so trivial):
$W$ as mixture of $X$ and $Y$
$$f_{(W_1,W_2)} = a f_{(X_1,X_2)} + b f_{(Y_1,Y_2)}$$
$W$ as product of PDFs of mixture of $X_1$ and $Y_1$ and mixture of $X_2$ and $Y_2$ (only iff $W_1$ and $W_2$ are independent)
$$f_{(W_1,W_2)} = \hphantom{\frac{1}{2}} f_{W_1}f_{W_2} \hphantom{+ \frac{1}{2} f_{(Y_1,Y_2)}}$$
Which leads to:
$$a f_{X_1}f_{X_2} + b f_{Y_1}f_{Y_2} = (a f_{X_1} + b f_{Y_1})(a f_{X_2}+ b f_{Y_2})$$
And, for any $a+b=1$, you get after some algebra:
$$(f_{X_1}-f_{Y_1}) (f_{X_2}-f_{Y_2}) = 0$$
So either $$f_{X_1} = f_{Y_1} \qquad or \qquad f_{X_2} = f_{Y_2}$$
Note that this generalizes your results to other multivariate distributions, allows adding more variables e.g. if $f_{X_1} = f_{Y_1} = f_{Z_1}$, and allows to use different mixing ratios.
The algebra in steps:
starting from:
$$a f_{X_1}f_{X_2} + b f_{Y_1}f_{Y_2} = (a f_{X_1} + b f_{Y_1})(a f_{X_2}+ b f_{Y_2})$$
bring the terms on the right hand side to the left and group by $a f_{X_1}$ and $b f_{Y_1}$
$$a f_{X_1}(f_{X_2} - (a f_{X_2}+ b f_{Y_2}) ) + b f_{Y_1}(f_{Y_2}- (a f_{X_2}+ b f_{Y_2})) = 0$$
simplify using $a+b=1$
$$a f_{X_1}(bf_{X_2} - (b f_{Y_2}) ) + b f_{Y_1}(a f_{Y_2}- (a f_{X_2})) = 0$$
divide by $a$ and $b$
$$ f_{X_1}(f_{X_2} - f_{Y_2} ) + f_{Y_1}(f_{Y_2}- f_{X_2}) = 0$$
|
Observations for a bivariate Gaussian mixture
|
In an alternative way you could use the requirement and sufficient condition that you have independence iff the combined probability of $X_1$ and $X_2$ is the product of the probability of $X_1$ and $
|
Observations for a bivariate Gaussian mixture
In an alternative way you could use the requirement and sufficient condition that you have independence iff the combined probability of $X_1$ and $X_2$ is the product of the probability of $X_1$ and $X_2$.
$$f_{(X_1,X_2)} = f_{X_1} f_{X_2}$$
And this you could work out more easily (more easily in the sense that the part after your 'notice that...' is not so trivial):
$W$ as mixture of $X$ and $Y$
$$f_{(W_1,W_2)} = a f_{(X_1,X_2)} + b f_{(Y_1,Y_2)}$$
$W$ as product of PDFs of mixture of $X_1$ and $Y_1$ and mixture of $X_2$ and $Y_2$ (only iff $W_1$ and $W_2$ are independent)
$$f_{(W_1,W_2)} = \hphantom{\frac{1}{2}} f_{W_1}f_{W_2} \hphantom{+ \frac{1}{2} f_{(Y_1,Y_2)}}$$
Which leads to:
$$a f_{X_1}f_{X_2} + b f_{Y_1}f_{Y_2} = (a f_{X_1} + b f_{Y_1})(a f_{X_2}+ b f_{Y_2})$$
And, for any $a+b=1$, you get after some algebra:
$$(f_{X_1}-f_{Y_1}) (f_{X_2}-f_{Y_2}) = 0$$
So either $$f_{X_1} = f_{Y_1} \qquad or \qquad f_{X_2} = f_{Y_2}$$
Note that this generalizes your results to other multivariate distributions, allows adding more variables e.g. if $f_{X_1} = f_{Y_1} = f_{Z_1}$, and allows to use different mixing ratios.
The algebra in steps:
starting from:
$$a f_{X_1}f_{X_2} + b f_{Y_1}f_{Y_2} = (a f_{X_1} + b f_{Y_1})(a f_{X_2}+ b f_{Y_2})$$
bring the terms on the right hand side to the left and group by $a f_{X_1}$ and $b f_{Y_1}$
$$a f_{X_1}(f_{X_2} - (a f_{X_2}+ b f_{Y_2}) ) + b f_{Y_1}(f_{Y_2}- (a f_{X_2}+ b f_{Y_2})) = 0$$
simplify using $a+b=1$
$$a f_{X_1}(bf_{X_2} - (b f_{Y_2}) ) + b f_{Y_1}(a f_{Y_2}- (a f_{X_2})) = 0$$
divide by $a$ and $b$
$$ f_{X_1}(f_{X_2} - f_{Y_2} ) + f_{Y_1}(f_{Y_2}- f_{X_2}) = 0$$
|
Observations for a bivariate Gaussian mixture
In an alternative way you could use the requirement and sufficient condition that you have independence iff the combined probability of $X_1$ and $X_2$ is the product of the probability of $X_1$ and $
|
42,702
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
|
The chi-squared test is valid here, it is testing the hypothesis that
$$H_0: \phi = 1$$ with $\phi = \frac{1}{\theta}$ the overdispersion parameter. It basically performs a likelihood-ratio test to compare both models (see ?anova). This is valid since your model with fixed overdispersion parameter is nested in the one where the overdispersion is freely estimated. The test statistic will follow a $\chi_1^2$ distribution, since your extended model has one additional estimated parameter. If you are unsure, you can always run some simulations under $H_0$ to prove this null-distribution.
Note that the null-distribution would be an even mixture between a point mass at 0 and $\chi_1^2$ if you were to test $$H_0: \phi = 0$$, since this would put the overdispersion at the edge of the parameter space. However, this does not apply here since $\phi$ can shrink to values smaller than 1.
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
|
The chi-squared test is valid here, it is testing the hypothesis that
$$H_0: \phi = 1$$ with $\phi = \frac{1}{\theta}$ the overdispersion parameter. It basically performs a likelihood-ratio test to c
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
The chi-squared test is valid here, it is testing the hypothesis that
$$H_0: \phi = 1$$ with $\phi = \frac{1}{\theta}$ the overdispersion parameter. It basically performs a likelihood-ratio test to compare both models (see ?anova). This is valid since your model with fixed overdispersion parameter is nested in the one where the overdispersion is freely estimated. The test statistic will follow a $\chi_1^2$ distribution, since your extended model has one additional estimated parameter. If you are unsure, you can always run some simulations under $H_0$ to prove this null-distribution.
Note that the null-distribution would be an even mixture between a point mass at 0 and $\chi_1^2$ if you were to test $$H_0: \phi = 0$$, since this would put the overdispersion at the edge of the parameter space. However, this does not apply here since $\phi$ can shrink to values smaller than 1.
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
The chi-squared test is valid here, it is testing the hypothesis that
$$H_0: \phi = 1$$ with $\phi = \frac{1}{\theta}$ the overdispersion parameter. It basically performs a likelihood-ratio test to c
|
42,703
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
|
ANOVA is used to compare nested models, i.e., models $M_1$ and $M_2$ where all predictors that appear in $M_1$ also appear in $M_2$, but $M_2$ contains additional ones. ANOVA then answers the question whether the additional predictors explain more variance than we would expect by chance alone.
Of course, one could also see this as an example of constrained model fitting: we could see $M_1$ as containing the same predictors as $M_2$, but with the parameter estimates of the additional predictors constrained to be zero.
Your use case is different, even if it is also a case of constrained parameter estimates. I don't know whether ANOVA would be valid here. (You could run a few simulations.)
I would recommend an approach using cross-validation (CV) and scoring-rules as follows. For each of the $k$ folds of your CV:
Fit both negative binomial (NB) regression models to the in-sample data.
Predict conditional NB distributions for your out-of-sample data.
Assess the quality of these conditional distributions for the holdout using proper scoring rules. If you want to use the Brier or the spherical score, you will need to calculate the sum of squared NB probability masses; see here on how to do this.
Repeat this process $k$ times and average the scores. Go with the model that yields the smallest score.
A few points to keep in mind:
I'd recommend running the entire CV multiple times with different seeds for the random number generator. See how consistently one model outperforms the other in terms of the score.
Similarly, use multiple different scores to see how robust your results are. The Brier, spherical and logarithmic scores are probably the most common ones. Merkle & Steyvers (2013, Decision Analysis) may be helpful.
The approach above does not consider parameter estimation uncertainty - strictly speaking, the predictions should not use the NB distribution, but an (even) more overdispersed one to account for this. Compare how we use the $t$ distribution for predicting in an OLS context, even if we assume normally distributed residuals. If you want to get fancy, you could bootstrap within each CV fold to account for this uncertainty, but I don't know whether this is worth the additional effort.
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
|
ANOVA is used to compare nested models, i.e., models $M_1$ and $M_2$ where all predictors that appear in $M_1$ also appear in $M_2$, but $M_2$ contains additional ones. ANOVA then answers the question
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
ANOVA is used to compare nested models, i.e., models $M_1$ and $M_2$ where all predictors that appear in $M_1$ also appear in $M_2$, but $M_2$ contains additional ones. ANOVA then answers the question whether the additional predictors explain more variance than we would expect by chance alone.
Of course, one could also see this as an example of constrained model fitting: we could see $M_1$ as containing the same predictors as $M_2$, but with the parameter estimates of the additional predictors constrained to be zero.
Your use case is different, even if it is also a case of constrained parameter estimates. I don't know whether ANOVA would be valid here. (You could run a few simulations.)
I would recommend an approach using cross-validation (CV) and scoring-rules as follows. For each of the $k$ folds of your CV:
Fit both negative binomial (NB) regression models to the in-sample data.
Predict conditional NB distributions for your out-of-sample data.
Assess the quality of these conditional distributions for the holdout using proper scoring rules. If you want to use the Brier or the spherical score, you will need to calculate the sum of squared NB probability masses; see here on how to do this.
Repeat this process $k$ times and average the scores. Go with the model that yields the smallest score.
A few points to keep in mind:
I'd recommend running the entire CV multiple times with different seeds for the random number generator. See how consistently one model outperforms the other in terms of the score.
Similarly, use multiple different scores to see how robust your results are. The Brier, spherical and logarithmic scores are probably the most common ones. Merkle & Steyvers (2013, Decision Analysis) may be helpful.
The approach above does not consider parameter estimation uncertainty - strictly speaking, the predictions should not use the NB distribution, but an (even) more overdispersed one to account for this. Compare how we use the $t$ distribution for predicting in an OLS context, even if we assume normally distributed residuals. If you want to get fancy, you could bootstrap within each CV fold to account for this uncertainty, but I don't know whether this is worth the additional effort.
|
Compare glm.nb vs glm(..., negative.binomial(k), ..) models
ANOVA is used to compare nested models, i.e., models $M_1$ and $M_2$ where all predictors that appear in $M_1$ also appear in $M_2$, but $M_2$ contains additional ones. ANOVA then answers the question
|
42,704
|
Hints for exercise 7.3 from The elements of statistical learning
|
Some hints: You correctly note
$$ X_{-i}^TX_{-i}=X^TX-\vec{x}_i\vec{x}_i^T$$($\vec{x_i}$ is a column vector),
and that you need to find $$\hat{\vec{\beta}}_{-i} = (X_{-i}^TX_{-i})^{-1}X_{-i}^T\vec{y}_{-i},$$ the estimated coefficients obtained by leaving out sample $i$. This will lead you to the new predicted value for sample $i$, $$ \hat f^{-i}(\vec{x}_i) = \vec{x}_i\hat{\vec{\beta}}_{-i}.$$
It will be useful to note that
$$X_{-i}^T\vec{y}_{-i} = X^T\vec{y} - \vec{x}_iy_i,$$ and that you can use the Sherman-Morrison formula to find the inverse of $(X^TX-\vec{x}_i\vec{x}_i^T)$. Also note that $$ \vec{x}_i^T(X^TX)^{-1}\vec{x}_i = S_{ii}.$$
You can then work out what you get for
$$\hat{\vec{\beta}}_{-i} = (X^TX-\vec{x}_i\vec{x}_i^T)^{-1}\left[X^Ty - \vec{x}_iy_i\right]$$ with a little algebra. Can you finish from here?
|
Hints for exercise 7.3 from The elements of statistical learning
|
Some hints: You correctly note
$$ X_{-i}^TX_{-i}=X^TX-\vec{x}_i\vec{x}_i^T$$($\vec{x_i}$ is a column vector),
and that you need to find $$\hat{\vec{\beta}}_{-i} = (X_{-i}^TX_{-i})^{-1}X_{-i}^T\vec{y}
|
Hints for exercise 7.3 from The elements of statistical learning
Some hints: You correctly note
$$ X_{-i}^TX_{-i}=X^TX-\vec{x}_i\vec{x}_i^T$$($\vec{x_i}$ is a column vector),
and that you need to find $$\hat{\vec{\beta}}_{-i} = (X_{-i}^TX_{-i})^{-1}X_{-i}^T\vec{y}_{-i},$$ the estimated coefficients obtained by leaving out sample $i$. This will lead you to the new predicted value for sample $i$, $$ \hat f^{-i}(\vec{x}_i) = \vec{x}_i\hat{\vec{\beta}}_{-i}.$$
It will be useful to note that
$$X_{-i}^T\vec{y}_{-i} = X^T\vec{y} - \vec{x}_iy_i,$$ and that you can use the Sherman-Morrison formula to find the inverse of $(X^TX-\vec{x}_i\vec{x}_i^T)$. Also note that $$ \vec{x}_i^T(X^TX)^{-1}\vec{x}_i = S_{ii}.$$
You can then work out what you get for
$$\hat{\vec{\beta}}_{-i} = (X^TX-\vec{x}_i\vec{x}_i^T)^{-1}\left[X^Ty - \vec{x}_iy_i\right]$$ with a little algebra. Can you finish from here?
|
Hints for exercise 7.3 from The elements of statistical learning
Some hints: You correctly note
$$ X_{-i}^TX_{-i}=X^TX-\vec{x}_i\vec{x}_i^T$$($\vec{x_i}$ is a column vector),
and that you need to find $$\hat{\vec{\beta}}_{-i} = (X_{-i}^TX_{-i})^{-1}X_{-i}^T\vec{y}
|
42,705
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacent states?
|
I'll answer question b) because it's more general, and question a) can just be thought of as a special case of b) where the adjacency matrix is simply the identity matrix. I'll give you the exact method, though approximate methods might be called for because the computation of the exact solution scales rapidly with number of people. I don't think there's a solution that scales better, but maybe someone can correct me.
It helps to look at it by doing the explicit case for a small number of people, adding more, and looking for the pattern.
Let's start with the probability of adjacent states for any two people. The probability that the first person is in state $i$, and the second person is in state $j$ is
$$
P(i,j) = p_i p_j,
$$
where $p_l = S_l/N,$ where $S_l$ is the number of people in state $l,$ and $N=\sum_l S_l.$ They are adjacent if $M_{i j} = 1,$ where $M_{i j}$ is the $i,j$th element of the adjacency matrix. Thus the probability they are adjacent is,
$$
\begin{split}
P_2 &= \sum_{i=1}^k \sum_{j=1}^k P(i,j) M_{i j} \\
&= 2 \sum_{i=1}^{k-1} \sum_{j=i+1}^k p_i p_j M_{i j} + \sum_{i=1}^k p_i^2,
\end{split}
$$
where I'm defining $P_m$ to be the probability that there's at least one adjacent pair in a group of $m$ people, and $k$ is the number of states. I'm also assuming that all diagonal elements of $M$ are one. As with the Birthday problem, however, it is more helpful to find the probability that they are not adjacent, which is,
$$
Q_2 = 1-P_2 = 2 \sum_{i=1}^{k-1} \sum_{j=i+1}^k p_i p_j (1 - M_{i j}).
$$
Let's look at it for $3$ people. It's easy to see that,
$$
Q_3 = \sum_{i,j,l} p_i p_j p_l (1 - M_{i j}) (1 - M_{i l}) (1 - M_{j l}).
$$
However, now it's also easy to see why this calculation can become intractable for a large number of people. The above cannot be factored in terms of $Q_2$ because $M_{i l}$ and $M_{j l}$ must appear in the $i,j$ sums, so an inductive process with which we determine $Q_{m+1}$ in terms of $Q_m$ seems to be out of the question. It must be solved explicitly for any value. However, as I did with the case of $2$ people, you can generally take the upper "right triangle" of the $m$-dimensional array of possible sets of people from mutually exclusive states, with the appropriate coefficient telling us how many ways that can happen. For example, in the case of three people where $i$, $j$, and $l$ are all different, there are $3! = 6$ ways that states $i$, $j$, and $l$ can appear through the three samples.
For $m$ people,
$$
\begin{split}
Q_m &= \sum_{i_1=1}^k \sum_{i_2=1}^k \cdots \sum_{i_m=1}^k \left( p_{i_m} \prod_{j=1}^{m-1} p_{i_j} \prod_{l=j+1}^m (1 - M_{i_j, i_l}) \right) \\
&= m! \sum_{i_1=1}^{k-m+1} \sum_{i_2=i_1+1}^{k-m+2} \cdots \sum_{i_m=i_{m-1}+1}^k \left( p_{i_m} \prod_{j=1}^{m-1} p_{i_j} \prod_{l=j+1}^m (1 - M_{i_j, i_l}) \right).
\end{split}
$$
The second line reduces it from a sum over $k^m$ terms to a sum over $k \choose m$ terms, which still scales very poorly. Also, each term involves a product over $m (m+1)/2$ factors. So overall, this is an $O({k \choose m} m^2)$ computation. If we ignore adjacency and answer question (a) then it becomes $O({k \choose m} m).$ But maybe you'll get lucky and the value of $m$ for which the probability first surpasses 50% will be very small.
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacen
|
I'll answer question b) because it's more general, and question a) can just be thought of as a special case of b) where the adjacency matrix is simply the identity matrix. I'll give you the exact meth
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacent states?
I'll answer question b) because it's more general, and question a) can just be thought of as a special case of b) where the adjacency matrix is simply the identity matrix. I'll give you the exact method, though approximate methods might be called for because the computation of the exact solution scales rapidly with number of people. I don't think there's a solution that scales better, but maybe someone can correct me.
It helps to look at it by doing the explicit case for a small number of people, adding more, and looking for the pattern.
Let's start with the probability of adjacent states for any two people. The probability that the first person is in state $i$, and the second person is in state $j$ is
$$
P(i,j) = p_i p_j,
$$
where $p_l = S_l/N,$ where $S_l$ is the number of people in state $l,$ and $N=\sum_l S_l.$ They are adjacent if $M_{i j} = 1,$ where $M_{i j}$ is the $i,j$th element of the adjacency matrix. Thus the probability they are adjacent is,
$$
\begin{split}
P_2 &= \sum_{i=1}^k \sum_{j=1}^k P(i,j) M_{i j} \\
&= 2 \sum_{i=1}^{k-1} \sum_{j=i+1}^k p_i p_j M_{i j} + \sum_{i=1}^k p_i^2,
\end{split}
$$
where I'm defining $P_m$ to be the probability that there's at least one adjacent pair in a group of $m$ people, and $k$ is the number of states. I'm also assuming that all diagonal elements of $M$ are one. As with the Birthday problem, however, it is more helpful to find the probability that they are not adjacent, which is,
$$
Q_2 = 1-P_2 = 2 \sum_{i=1}^{k-1} \sum_{j=i+1}^k p_i p_j (1 - M_{i j}).
$$
Let's look at it for $3$ people. It's easy to see that,
$$
Q_3 = \sum_{i,j,l} p_i p_j p_l (1 - M_{i j}) (1 - M_{i l}) (1 - M_{j l}).
$$
However, now it's also easy to see why this calculation can become intractable for a large number of people. The above cannot be factored in terms of $Q_2$ because $M_{i l}$ and $M_{j l}$ must appear in the $i,j$ sums, so an inductive process with which we determine $Q_{m+1}$ in terms of $Q_m$ seems to be out of the question. It must be solved explicitly for any value. However, as I did with the case of $2$ people, you can generally take the upper "right triangle" of the $m$-dimensional array of possible sets of people from mutually exclusive states, with the appropriate coefficient telling us how many ways that can happen. For example, in the case of three people where $i$, $j$, and $l$ are all different, there are $3! = 6$ ways that states $i$, $j$, and $l$ can appear through the three samples.
For $m$ people,
$$
\begin{split}
Q_m &= \sum_{i_1=1}^k \sum_{i_2=1}^k \cdots \sum_{i_m=1}^k \left( p_{i_m} \prod_{j=1}^{m-1} p_{i_j} \prod_{l=j+1}^m (1 - M_{i_j, i_l}) \right) \\
&= m! \sum_{i_1=1}^{k-m+1} \sum_{i_2=i_1+1}^{k-m+2} \cdots \sum_{i_m=i_{m-1}+1}^k \left( p_{i_m} \prod_{j=1}^{m-1} p_{i_j} \prod_{l=j+1}^m (1 - M_{i_j, i_l}) \right).
\end{split}
$$
The second line reduces it from a sum over $k^m$ terms to a sum over $k \choose m$ terms, which still scales very poorly. Also, each term involves a product over $m (m+1)/2$ factors. So overall, this is an $O({k \choose m} m^2)$ computation. If we ignore adjacency and answer question (a) then it becomes $O({k \choose m} m).$ But maybe you'll get lucky and the value of $m$ for which the probability first surpasses 50% will be very small.
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacen
I'll answer question b) because it's more general, and question a) can just be thought of as a special case of b) where the adjacency matrix is simply the identity matrix. I'll give you the exact meth
|
42,706
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacent states?
|
It is possible to solve this using Markov Matrices to model the random process of selecting people. This approach requires quite a bet of effort to set up but it does have a structured way to get your answer.
Markov matrices are used to model a random process which can move between discrete "states" (to avoid confusion between US states and the markov states I will refer to markov states as "Phases").
In this context the markov phase is the list of all the states you chose Americans from. For example if the first american is from Washington the phase is {WA}, then if the next american is from Texas the phase is {TX,WA}. The order you chose people in is irrelevant so {TX, WA} is the same phase as {WA, TX}.
Before sampling begins we start in phase {0} where no Americans have been chosen. We define a single phase {E} (meaning "ending") where you have chosen two americans from adjacent states, the random process of choosing americans continues until {E} is reached. Continuing from phase {TX, WA}, if the next american is from Oregon then the phase transitions to {E} since Oregon is beside Washington.
{E} is known as an "absorbing state" because once the random process reaches {E} it cannot change to a different phase.
You must create a list of all possible phases which can occur before reaching {E}.
Now you need to calculate the Markov matrix $M$ for the probability of transitioning between states. First of all let $P$ be the vector of probabilities of sampling an American from a state. Then $P_{florida}$ is the chance of picking someone from Florida.
The entries in the Markov matrix $M_{ij}$ is the probability of transition from phase $i$ to phase $j$. For example, to transition from {WA} to {TX, WA} is $P_{Texas}$. The probability of transitioning from {WA} to {E} is $P_{Washington}+P_{Idaho}+P_{Oregon}$. And the probability of transitioning from {E} to {E} is 1.
You always start sampling from {0}. After 1 American has been sampled the probability of being in {E} is $M_{\{0\}\{E\}}$. After 2 Americans have been sampled then the probability of being in {E} is $(MM)_{\{0\}\{E\}}$ (The matrix M is multiplied by itself and then you get the probability from row {0} and column {E}).
Likewise after 3 Americans have been sampled the probability of being in {E} is $(MMM)_{\{0\}\{E\}}$. You need to keep multiplying M by itself until the probability is at least 50%
It takes a lot of effort to find $M$ but once you have that it's straightforward to get the result.
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacen
|
It is possible to solve this using Markov Matrices to model the random process of selecting people. This approach requires quite a bet of effort to set up but it does have a structured way to get your
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacent states?
It is possible to solve this using Markov Matrices to model the random process of selecting people. This approach requires quite a bet of effort to set up but it does have a structured way to get your answer.
Markov matrices are used to model a random process which can move between discrete "states" (to avoid confusion between US states and the markov states I will refer to markov states as "Phases").
In this context the markov phase is the list of all the states you chose Americans from. For example if the first american is from Washington the phase is {WA}, then if the next american is from Texas the phase is {TX,WA}. The order you chose people in is irrelevant so {TX, WA} is the same phase as {WA, TX}.
Before sampling begins we start in phase {0} where no Americans have been chosen. We define a single phase {E} (meaning "ending") where you have chosen two americans from adjacent states, the random process of choosing americans continues until {E} is reached. Continuing from phase {TX, WA}, if the next american is from Oregon then the phase transitions to {E} since Oregon is beside Washington.
{E} is known as an "absorbing state" because once the random process reaches {E} it cannot change to a different phase.
You must create a list of all possible phases which can occur before reaching {E}.
Now you need to calculate the Markov matrix $M$ for the probability of transitioning between states. First of all let $P$ be the vector of probabilities of sampling an American from a state. Then $P_{florida}$ is the chance of picking someone from Florida.
The entries in the Markov matrix $M_{ij}$ is the probability of transition from phase $i$ to phase $j$. For example, to transition from {WA} to {TX, WA} is $P_{Texas}$. The probability of transitioning from {WA} to {E} is $P_{Washington}+P_{Idaho}+P_{Oregon}$. And the probability of transitioning from {E} to {E} is 1.
You always start sampling from {0}. After 1 American has been sampled the probability of being in {E} is $M_{\{0\}\{E\}}$. After 2 Americans have been sampled then the probability of being in {E} is $(MM)_{\{0\}\{E\}}$ (The matrix M is multiplied by itself and then you get the probability from row {0} and column {E}).
Likewise after 3 Americans have been sampled the probability of being in {E} is $(MMM)_{\{0\}\{E\}}$. You need to keep multiplying M by itself until the probability is at least 50%
It takes a lot of effort to find $M$ but once you have that it's straightforward to get the result.
|
How many Americans, randomly chosen, are needed to have a 50% chance two live in the same or adjacen
It is possible to solve this using Markov Matrices to model the random process of selecting people. This approach requires quite a bet of effort to set up but it does have a structured way to get your
|
42,707
|
Why is $z$-value more meaningful than $p$-value for very low $p$-values?
|
A lower $p$-value does not indicate the assumptions were violated. Some really low $p$-values like $2.22\times10^{-16}$ just indicate the limit of the machine, something called machine epsilon. Once a number gets that low, the machine can't go any lower, so spits it out or zero.
The reason one could report the $z$ at that point is $z$ can be interpreted meaningfully within certain contexts. A small $p$ is just really really really small. Additionally, at that point, it is irrelevant. There is a meaningful difference between $p_a=.35$ and $p_b=.09$. However, there is little substantive difference between $p_1=.0000000001$ and $p_2=.0000000000000000001$, even though $\frac{p_1}{p_2}$ is many times larger than $\frac{p_a}{p_b}$.
Finally, the author claims that as $p$-values get really small, failure to meet statistical assumptions have more effects on the magnitude of the $p$-value. We almost never fully meet assumptions of statistical tests, but if we have a $p$-value of .04, and we did a decent job of meeting the assumptions of the test, its magnitude could vary between .02 and say, .06. However, if we have a $p$-value like $p_2$, the author is saying it could be as different as $p_1$ in reality. So at that level, the number you get is not reliable - it is a false precision.
This does not apply to the $z$ much as the change in $p$, as large as from $p_1$ to $p_2$, is just a 3 point change in $z$ from about 6 to 9. And on $z$, if we are concerned with the uncertainty about it, we can always report its confidence interval. Of course, we could do the same for a tiny $p$ but that would be very unconventional and barely interpretable.
|
Why is $z$-value more meaningful than $p$-value for very low $p$-values?
|
A lower $p$-value does not indicate the assumptions were violated. Some really low $p$-values like $2.22\times10^{-16}$ just indicate the limit of the machine, something called machine epsilon. Once a
|
Why is $z$-value more meaningful than $p$-value for very low $p$-values?
A lower $p$-value does not indicate the assumptions were violated. Some really low $p$-values like $2.22\times10^{-16}$ just indicate the limit of the machine, something called machine epsilon. Once a number gets that low, the machine can't go any lower, so spits it out or zero.
The reason one could report the $z$ at that point is $z$ can be interpreted meaningfully within certain contexts. A small $p$ is just really really really small. Additionally, at that point, it is irrelevant. There is a meaningful difference between $p_a=.35$ and $p_b=.09$. However, there is little substantive difference between $p_1=.0000000001$ and $p_2=.0000000000000000001$, even though $\frac{p_1}{p_2}$ is many times larger than $\frac{p_a}{p_b}$.
Finally, the author claims that as $p$-values get really small, failure to meet statistical assumptions have more effects on the magnitude of the $p$-value. We almost never fully meet assumptions of statistical tests, but if we have a $p$-value of .04, and we did a decent job of meeting the assumptions of the test, its magnitude could vary between .02 and say, .06. However, if we have a $p$-value like $p_2$, the author is saying it could be as different as $p_1$ in reality. So at that level, the number you get is not reliable - it is a false precision.
This does not apply to the $z$ much as the change in $p$, as large as from $p_1$ to $p_2$, is just a 3 point change in $z$ from about 6 to 9. And on $z$, if we are concerned with the uncertainty about it, we can always report its confidence interval. Of course, we could do the same for a tiny $p$ but that would be very unconventional and barely interpretable.
|
Why is $z$-value more meaningful than $p$-value for very low $p$-values?
A lower $p$-value does not indicate the assumptions were violated. Some really low $p$-values like $2.22\times10^{-16}$ just indicate the limit of the machine, something called machine epsilon. Once a
|
42,708
|
How to compute expected values of compound events?
|
This is an exercise in using indicator variables. An indicator has a value of $1$ to signify some condition holds and has a value of $0$ otherwise. Seemingly difficult problems about probability and expectation can have simple solutions that exploit indicators and linearity of expectation--even when the random variables involved are not independent. For those new to these ideas, full details are given below.
Call the engineers "X" and "Y". Model X's selection by means of $17$ indicator variables $X_i,\ i=1,2,\ldots,17$, where $$\left\{\matrix{X_i=1 & \text{ when X selects i}\\X_i=0 & \text{ otherwise.}}\right.$$
Similarly define indicator variables $Y_i$ for Y's selection.
We may express the conditions in the problem algebraically:
The indicator that $i$ is selected by both is $X_iY_i$.
The indicator that $i$ is selected by neither is $(1-X_i)(1-Y_i)$.
The indicator that $i$ is selected only by X is $X_i(1-Y_i)$.
The indicator that $i$ is selected only by Y is $(1-X_i)Y_i$.
The total number selected by $X$ is $$4 = X_1 + X_2 + \cdots + X_{17} = \sum_{i=1}^{17}X_i.$$
Clearly all $34$ variables are identically distributed. Let $\mu$ be their common expectation. Because
$$4 = E[4] = E\left[\sum_{i=1}^{17}X_i\right] = \sum_{i=1}^{17}E[X_i] = \sum_{i=1}^{17}\mu = 17\mu,$$
we deduce
$$\mu = \frac{4}{17}.$$
Although the variables are not independent, the $X_i$ are assumed independent of the $Y_i$.
a. Expected number of items selected by both
The total number of items selected by both is the sum of the $X_iY_i$. Thus the expected number is
$$E\left[\sum_{i=1}^{17} X_iY_i\right] = \sum_{i=1}^{17} E\left[X_iY_i\right] = \sum_{i=1}^{17} E\left[X_i\right]E\left[Y_i\right] = \sum_{i=1}^{17} \frac{4}{17}\frac{4}{17} = \frac{4^2}{17}.$$
The independence of $X_i$ and $Y_i$ was needed to express each $E[X_iY_i]$ as the product of $E[X_i]$ and $E[Y_i]$.
b. Expected number of items selected by neither
The total number of items selected by neither is the sum of the $(1-X_i)(1-Y_i)$. Since all $1-X_i$ are independent of all $1-Y_i$, exactly the same method used in (a) applies; the only change is that $4/17$ is replaced by $E[1-X_i]=E[1-Y_i]=13/17$. The value must be $$E\left[\sum_{i=1}^{17} (1-X_i)(1-Y_i)\right] =\frac{13^2}{17}.$$
c. Expected number of items selected by exactly one
This can be solved as in (a) or (b), giving $4/17\times 13/17 = 52/17$ as the chance of being selected only by X and $13/17\times 4/17=52/17$ as the chance of being selected only by Y. The answer is the sum of these (disjoint) events, equal to $104/17$.
A shortcut (or check of the work) is to note that every item falls into exactly one of the categories both, neither, or exactly one, and therefore the answer must be the difference between the total ($17$) and the sum of the answers to (a) and (b):
$$17 - \frac{4^2}{17} - \frac{13^2}{17} = \frac{104}{17}.$$
Check via simulation
Let's perform 10,000 (say) simulations of these selections and track the outcomes. We may output (a) the average number of items selected by both, (b) the average number of items selected by neither, and (c) the average number of items selected by exactly one. Beneath this output, as a reference, let's print the answers given in (a), (b), and (c). We won't try to be efficient: the objective is to model the selection process as described and to count up the events directly, without any arithmetical tricks. Here is some R code that does that in a fairly perspicuous way while still taking only about one second:
n.sim <- 1e4 # Number of iterations
n <- 17 # Number of items
k <- 4 # Numbers chosen by each engineer
set.seed(17) # Creates reproducible output
sim <- replicate(n.sim, {
x <- sample.int(n, k) # X chooses `k` items
y <- sample.int(n, k) # Y chooses 'k' items
x.and.y <- intersect(x,y) # Find those chosen by both
not.x.and.not.y <- setdiff(1:n, union(x,y)) # ... .... chosen by neither
x.only <- setdiff(x, y) # ... .... chosen only by x
y.only <- setdiff(y, x) # ... .... chosen only by y
c(Both=length(x.and.y), # Count those chosen by both
Neither=length(not.x.and.not.y), # Count those chosen by neither
One=length(x.only) + length(y.only) # Count those chosen by one
)
})
signif(rbind(Simulation=rowMeans(sim), # Average the simulations
Theory=c(k^2/n, (n-k)^2/n, n-(k^2+(n-k)^2)/n)), 4) # Give theoretical values
The two lines of output--average across many simulated trials and the theoretical answers previously given--are close enough to support the correctness of the answers:
Both Neither One
Simulation 0.9315 9.932 6.137
Theory 0.9412 9.941 6.118
|
How to compute expected values of compound events?
|
This is an exercise in using indicator variables. An indicator has a value of $1$ to signify some condition holds and has a value of $0$ otherwise. Seemingly difficult problems about probability and
|
How to compute expected values of compound events?
This is an exercise in using indicator variables. An indicator has a value of $1$ to signify some condition holds and has a value of $0$ otherwise. Seemingly difficult problems about probability and expectation can have simple solutions that exploit indicators and linearity of expectation--even when the random variables involved are not independent. For those new to these ideas, full details are given below.
Call the engineers "X" and "Y". Model X's selection by means of $17$ indicator variables $X_i,\ i=1,2,\ldots,17$, where $$\left\{\matrix{X_i=1 & \text{ when X selects i}\\X_i=0 & \text{ otherwise.}}\right.$$
Similarly define indicator variables $Y_i$ for Y's selection.
We may express the conditions in the problem algebraically:
The indicator that $i$ is selected by both is $X_iY_i$.
The indicator that $i$ is selected by neither is $(1-X_i)(1-Y_i)$.
The indicator that $i$ is selected only by X is $X_i(1-Y_i)$.
The indicator that $i$ is selected only by Y is $(1-X_i)Y_i$.
The total number selected by $X$ is $$4 = X_1 + X_2 + \cdots + X_{17} = \sum_{i=1}^{17}X_i.$$
Clearly all $34$ variables are identically distributed. Let $\mu$ be their common expectation. Because
$$4 = E[4] = E\left[\sum_{i=1}^{17}X_i\right] = \sum_{i=1}^{17}E[X_i] = \sum_{i=1}^{17}\mu = 17\mu,$$
we deduce
$$\mu = \frac{4}{17}.$$
Although the variables are not independent, the $X_i$ are assumed independent of the $Y_i$.
a. Expected number of items selected by both
The total number of items selected by both is the sum of the $X_iY_i$. Thus the expected number is
$$E\left[\sum_{i=1}^{17} X_iY_i\right] = \sum_{i=1}^{17} E\left[X_iY_i\right] = \sum_{i=1}^{17} E\left[X_i\right]E\left[Y_i\right] = \sum_{i=1}^{17} \frac{4}{17}\frac{4}{17} = \frac{4^2}{17}.$$
The independence of $X_i$ and $Y_i$ was needed to express each $E[X_iY_i]$ as the product of $E[X_i]$ and $E[Y_i]$.
b. Expected number of items selected by neither
The total number of items selected by neither is the sum of the $(1-X_i)(1-Y_i)$. Since all $1-X_i$ are independent of all $1-Y_i$, exactly the same method used in (a) applies; the only change is that $4/17$ is replaced by $E[1-X_i]=E[1-Y_i]=13/17$. The value must be $$E\left[\sum_{i=1}^{17} (1-X_i)(1-Y_i)\right] =\frac{13^2}{17}.$$
c. Expected number of items selected by exactly one
This can be solved as in (a) or (b), giving $4/17\times 13/17 = 52/17$ as the chance of being selected only by X and $13/17\times 4/17=52/17$ as the chance of being selected only by Y. The answer is the sum of these (disjoint) events, equal to $104/17$.
A shortcut (or check of the work) is to note that every item falls into exactly one of the categories both, neither, or exactly one, and therefore the answer must be the difference between the total ($17$) and the sum of the answers to (a) and (b):
$$17 - \frac{4^2}{17} - \frac{13^2}{17} = \frac{104}{17}.$$
Check via simulation
Let's perform 10,000 (say) simulations of these selections and track the outcomes. We may output (a) the average number of items selected by both, (b) the average number of items selected by neither, and (c) the average number of items selected by exactly one. Beneath this output, as a reference, let's print the answers given in (a), (b), and (c). We won't try to be efficient: the objective is to model the selection process as described and to count up the events directly, without any arithmetical tricks. Here is some R code that does that in a fairly perspicuous way while still taking only about one second:
n.sim <- 1e4 # Number of iterations
n <- 17 # Number of items
k <- 4 # Numbers chosen by each engineer
set.seed(17) # Creates reproducible output
sim <- replicate(n.sim, {
x <- sample.int(n, k) # X chooses `k` items
y <- sample.int(n, k) # Y chooses 'k' items
x.and.y <- intersect(x,y) # Find those chosen by both
not.x.and.not.y <- setdiff(1:n, union(x,y)) # ... .... chosen by neither
x.only <- setdiff(x, y) # ... .... chosen only by x
y.only <- setdiff(y, x) # ... .... chosen only by y
c(Both=length(x.and.y), # Count those chosen by both
Neither=length(not.x.and.not.y), # Count those chosen by neither
One=length(x.only) + length(y.only) # Count those chosen by one
)
})
signif(rbind(Simulation=rowMeans(sim), # Average the simulations
Theory=c(k^2/n, (n-k)^2/n, n-(k^2+(n-k)^2)/n)), 4) # Give theoretical values
The two lines of output--average across many simulated trials and the theoretical answers previously given--are close enough to support the correctness of the answers:
Both Neither One
Simulation 0.9315 9.932 6.137
Theory 0.9412 9.941 6.118
|
How to compute expected values of compound events?
This is an exercise in using indicator variables. An indicator has a value of $1$ to signify some condition holds and has a value of $0$ otherwise. Seemingly difficult problems about probability and
|
42,709
|
Understanding direction of greatest variance in PCA
|
Your confusion here comes from misunderstanding of how Cartesian coordinates work. Remember: the orthogonal distances of the points from the axis labeled $\mathbf{v}$ are the $u$ coordinates. That is, they measure the distance parallel to the vector $\mathbf{u}$ from the origin. You are absolutely correct that the variability of these distances away from the vector $\mathbf{v}$ is greater than the corresponding variance of the distances from the vector $\mathbf{u}$ --- but these distances are the $u$ coordinates, not the $v$ coordinates!
|
Understanding direction of greatest variance in PCA
|
Your confusion here comes from misunderstanding of how Cartesian coordinates work. Remember: the orthogonal distances of the points from the axis labeled $\mathbf{v}$ are the $u$ coordinates. That i
|
Understanding direction of greatest variance in PCA
Your confusion here comes from misunderstanding of how Cartesian coordinates work. Remember: the orthogonal distances of the points from the axis labeled $\mathbf{v}$ are the $u$ coordinates. That is, they measure the distance parallel to the vector $\mathbf{u}$ from the origin. You are absolutely correct that the variability of these distances away from the vector $\mathbf{v}$ is greater than the corresponding variance of the distances from the vector $\mathbf{u}$ --- but these distances are the $u$ coordinates, not the $v$ coordinates!
|
Understanding direction of greatest variance in PCA
Your confusion here comes from misunderstanding of how Cartesian coordinates work. Remember: the orthogonal distances of the points from the axis labeled $\mathbf{v}$ are the $u$ coordinates. That i
|
42,710
|
Understanding direction of greatest variance in PCA
|
The direction of greatest variance represents the direction in which you would encounter all the greatest variation in the data points (Minimum, maximum, average) values; their variance or possibly range should be highest. In our case, it is the direction 'u'. In the direction 'v', the data points do not vary as much as they do in the direction 'u'
|
Understanding direction of greatest variance in PCA
|
The direction of greatest variance represents the direction in which you would encounter all the greatest variation in the data points (Minimum, maximum, average) values; their variance or possibly ra
|
Understanding direction of greatest variance in PCA
The direction of greatest variance represents the direction in which you would encounter all the greatest variation in the data points (Minimum, maximum, average) values; their variance or possibly range should be highest. In our case, it is the direction 'u'. In the direction 'v', the data points do not vary as much as they do in the direction 'u'
|
Understanding direction of greatest variance in PCA
The direction of greatest variance represents the direction in which you would encounter all the greatest variation in the data points (Minimum, maximum, average) values; their variance or possibly ra
|
42,711
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functions?
|
I believe they mention this in the footnote to chapter 3 (first page)
One may choose to ignore the discreteness of the target values, and use a regression treatment, where all targets happen to be say ±1 for binary classification. This is known as least-squares classification, see section 6.5.
Looking at 6.5 http://www.gaussianprocess.org/gpml/chapters/RW6.pdf they mention the advantage of using sigmoid functions is that the outputs can be be interpreted probabilistically (ie, the probability that an example has a positive response).
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functio
|
I believe they mention this in the footnote to chapter 3 (first page)
One may choose to ignore the discreteness of the target values, and use a regression treatment, where all targets happen to be sa
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functions?
I believe they mention this in the footnote to chapter 3 (first page)
One may choose to ignore the discreteness of the target values, and use a regression treatment, where all targets happen to be say ±1 for binary classification. This is known as least-squares classification, see section 6.5.
Looking at 6.5 http://www.gaussianprocess.org/gpml/chapters/RW6.pdf they mention the advantage of using sigmoid functions is that the outputs can be be interpreted probabilistically (ie, the probability that an example has a positive response).
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functio
I believe they mention this in the footnote to chapter 3 (first page)
One may choose to ignore the discreteness of the target values, and use a regression treatment, where all targets happen to be sa
|
42,712
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functions?
|
The problem with this approach is that the number of terms in $p(\mathbf y|\mathbf f)$ would grow exponentially with the number of negatively-labelled points in the training set, so the closed-form solution to (3.9) would have exponential time complexity. More specifically, if we assume, without loss of generality, that
$$
\mathbf y_1=\ldots=\mathbf y_a=-1 \enspace,\enspace \mathbf y_{a+1}=\ldots=\mathbf y_n=+1 \enspace,
$$
then
$$
p(\mathbf y|\mathbf f)
= \left(\prod_{i=1}^a (1-g(\mathbf f_i))\right)
\prod_{i=a+1}^n g(\mathbf f_i) \enspace.
$$
To obtain a closed-form solution to (3.9), we have to expand the first product into a sum of (unnormalised) Gaussian functions, so that we can integrate each one separately:
$$
\prod_{i=1}^a (1-g(\mathbf f_i))
= \sum_{I\in \mathcal{P}\{1,\ldots,a\}} (-1)^{|I|}\exp\left\{
-\frac{1}{2}\sum_{i\in I}\mathbf f^2_i
\right\} \enspace.
$$
There are $2^a$ sets in the power set $\mathcal P\{1,\ldots,a\}$ of the negatively-labelled-point indices $\{1,\ldots,a\}$, so solving (3.9) would involve computing $2^a$ Gaussian integrals.
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functio
|
The problem with this approach is that the number of terms in $p(\mathbf y|\mathbf f)$ would grow exponentially with the number of negatively-labelled points in the training set, so the closed-form so
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functions?
The problem with this approach is that the number of terms in $p(\mathbf y|\mathbf f)$ would grow exponentially with the number of negatively-labelled points in the training set, so the closed-form solution to (3.9) would have exponential time complexity. More specifically, if we assume, without loss of generality, that
$$
\mathbf y_1=\ldots=\mathbf y_a=-1 \enspace,\enspace \mathbf y_{a+1}=\ldots=\mathbf y_n=+1 \enspace,
$$
then
$$
p(\mathbf y|\mathbf f)
= \left(\prod_{i=1}^a (1-g(\mathbf f_i))\right)
\prod_{i=a+1}^n g(\mathbf f_i) \enspace.
$$
To obtain a closed-form solution to (3.9), we have to expand the first product into a sum of (unnormalised) Gaussian functions, so that we can integrate each one separately:
$$
\prod_{i=1}^a (1-g(\mathbf f_i))
= \sum_{I\in \mathcal{P}\{1,\ldots,a\}} (-1)^{|I|}\exp\left\{
-\frac{1}{2}\sum_{i\in I}\mathbf f^2_i
\right\} \enspace.
$$
There are $2^a$ sets in the power set $\mathcal P\{1,\ldots,a\}$ of the negatively-labelled-point indices $\{1,\ldots,a\}$, so solving (3.9) would involve computing $2^a$ Gaussian integrals.
|
In Gaussian Process binary classification, why are sigmoid functions preferred over Gaussian functio
The problem with this approach is that the number of terms in $p(\mathbf y|\mathbf f)$ would grow exponentially with the number of negatively-labelled points in the training set, so the closed-form so
|
42,713
|
How to determine random effects in mixed model
|
You can test if the variance in slopes (and covariance between slope and intercept) is significant by modeling one model with just the random intercept and another model with the random slope and intercept. Then you can do a nested model comparison between the two:
mod1 <- lmer(... + (1|state), ...)
mod2 <- lmer(... + (1+predictor|state), ...)
anova(mod1,mod2)
This will give you a p-value that you need to correct, though. You can do so with this code:
1-(.5*pchisq(anova(mod1,mod2, refit=FALSE)$Chisq[[2]],df=2)+
.5*pchisq(anova(mod1,mod2, refit=FALSE)$Chisq[[2]],df=1))
P-value correction is found here or here.
|
How to determine random effects in mixed model
|
You can test if the variance in slopes (and covariance between slope and intercept) is significant by modeling one model with just the random intercept and another model with the random slope and inte
|
How to determine random effects in mixed model
You can test if the variance in slopes (and covariance between slope and intercept) is significant by modeling one model with just the random intercept and another model with the random slope and intercept. Then you can do a nested model comparison between the two:
mod1 <- lmer(... + (1|state), ...)
mod2 <- lmer(... + (1+predictor|state), ...)
anova(mod1,mod2)
This will give you a p-value that you need to correct, though. You can do so with this code:
1-(.5*pchisq(anova(mod1,mod2, refit=FALSE)$Chisq[[2]],df=2)+
.5*pchisq(anova(mod1,mod2, refit=FALSE)$Chisq[[2]],df=1))
P-value correction is found here or here.
|
How to determine random effects in mixed model
You can test if the variance in slopes (and covariance between slope and intercept) is significant by modeling one model with just the random intercept and another model with the random slope and inte
|
42,714
|
How to determine random effects in mixed model
|
Exploratory analyses for describing correlation structures in dependent data include variograms for continuous spatio-temporal data, intraclass correlation coefficients for clustered data, lorelograms for binary outcomes.
Other descriptive statistics include bootstrapped or profile likelihood confidence intervals for variance components in random effects models, goodness-of-fit tests with unstructured covariance structures or saturated specification of random and fixed effects.
Formal inference for the hypothesis of random effects having 0 dispersion can be done testing nested models with likelihood ratio tests. Be sure to change software settings to fit models with maximum likelihood and not REML when conducting these tests.
|
How to determine random effects in mixed model
|
Exploratory analyses for describing correlation structures in dependent data include variograms for continuous spatio-temporal data, intraclass correlation coefficients for clustered data, lorelograms
|
How to determine random effects in mixed model
Exploratory analyses for describing correlation structures in dependent data include variograms for continuous spatio-temporal data, intraclass correlation coefficients for clustered data, lorelograms for binary outcomes.
Other descriptive statistics include bootstrapped or profile likelihood confidence intervals for variance components in random effects models, goodness-of-fit tests with unstructured covariance structures or saturated specification of random and fixed effects.
Formal inference for the hypothesis of random effects having 0 dispersion can be done testing nested models with likelihood ratio tests. Be sure to change software settings to fit models with maximum likelihood and not REML when conducting these tests.
|
How to determine random effects in mixed model
Exploratory analyses for describing correlation structures in dependent data include variograms for continuous spatio-temporal data, intraclass correlation coefficients for clustered data, lorelograms
|
42,715
|
How to do weight normalization in VGG network for style transfer?
|
"-is that capturing the activation maps for all images in imagenet (training set) and then adjust the relu weights based on those sums across all images, all positions for each filter element?"
I suppose your guess is correct. I've came across the normalised network that they used and inspected its activation matrices for several images. Their mean tends to be below 1. The normalised model is made publicly available by the authors: http://bethgelab.org/media/uploads/deeptextures/vgg_normalised.caffemodel
I hope this link helps.
|
How to do weight normalization in VGG network for style transfer?
|
"-is that capturing the activation maps for all images in imagenet (training set) and then adjust the relu weights based on those sums across all images, all positions for each filter element?"
I sup
|
How to do weight normalization in VGG network for style transfer?
"-is that capturing the activation maps for all images in imagenet (training set) and then adjust the relu weights based on those sums across all images, all positions for each filter element?"
I suppose your guess is correct. I've came across the normalised network that they used and inspected its activation matrices for several images. Their mean tends to be below 1. The normalised model is made publicly available by the authors: http://bethgelab.org/media/uploads/deeptextures/vgg_normalised.caffemodel
I hope this link helps.
|
How to do weight normalization in VGG network for style transfer?
"-is that capturing the activation maps for all images in imagenet (training set) and then adjust the relu weights based on those sums across all images, all positions for each filter element?"
I sup
|
42,716
|
Alternatives to three dimensional scatter plot
|
I think what primarily needs to be added to your list is coplots, but let's work our way up to that. The starting point for visualizing two continuous variables should always be a scatterplot. With more than two variables, that generalizes naturally to a scatterplot matrix (although if you have lots of variables, you may need to break that up into multiple matrices, see: How to extract information from a scatterplot matrix when you have large N, discrete data, & many variables?). The thing to recognize is that a scatterplot matrix is a set of 2D marginal projections from a higher-dimensional space. But those margins may not be the most interesting or informative. Exactly which margins you might want to look at is a tricky question (cf., projection pursuit), but the simplest possible next set to examine is the set that makes the variables orthogonal, i.e., scatterplots of the variables that result from a principal components analysis. You mention using this for data reduction and looking at the scatterplot of the first two principal components. The thinking behind that is reasonable, but you don't have to only look at the first two, others might be worth exploring (cf., Examples of PCA where PCs with low variance are “useful”), so you can / should make a scatterplot matrix of those, too. Another possibility with the output of a PCA is to make a biplot, which overlays the way the original variables are related to the principal components (as arrows) on top of the scatterplot. You could also combine a scatterplot matrix of the principal components with biplots.
All of the above are marginal, as I mentioned. A coplot is conditional (the top part of my answer here contrasts conditional vs. marginal). Literally, 'coplot' is a blended word from 'conditional plot'. In a coplot, you are taking slices (or subsets) of the data on the other dimensions and plotting the data in those subsets in a series of scatterplots. Once you learn how to read them, they are a nice addition to your set of options for exploring patterns in higher-dimensional data.
To illustrate these ideas, here is an example with the RandU dataset (pseudorandom data generated by an algorithm that was popular in the 1970's):
data(randu)
windows()
pairs(randu)
pca = princomp(randu)
attr(pca$scores, "dimnames")[[1]][1:400] = "o"
windows()
par(mfrow=c(3,3), mar=rep(.5,4), oma=rep(2,4))
for(i in 1:3){
for(j in 1:3){
if(i<j){
plot(y=pca$scores[,i], x=pca$scores[,j], axes=FALSE); box()
} else if(i==j){
plot(density(pca$scores[,i]), axes=FALSE, main=""); box()
text(0, .5, labels=colnames(pca$scores)[i])
} else {
biplot(pca, choices=c(j,i), main="", xaxp=c(-10,10,1), yaxp=c(-10,10,1))
}
}
}
windows()
coplot(y~x|z, randu)
|
Alternatives to three dimensional scatter plot
|
I think what primarily needs to be added to your list is coplots, but let's work our way up to that. The starting point for visualizing two continuous variables should always be a scatterplot. With
|
Alternatives to three dimensional scatter plot
I think what primarily needs to be added to your list is coplots, but let's work our way up to that. The starting point for visualizing two continuous variables should always be a scatterplot. With more than two variables, that generalizes naturally to a scatterplot matrix (although if you have lots of variables, you may need to break that up into multiple matrices, see: How to extract information from a scatterplot matrix when you have large N, discrete data, & many variables?). The thing to recognize is that a scatterplot matrix is a set of 2D marginal projections from a higher-dimensional space. But those margins may not be the most interesting or informative. Exactly which margins you might want to look at is a tricky question (cf., projection pursuit), but the simplest possible next set to examine is the set that makes the variables orthogonal, i.e., scatterplots of the variables that result from a principal components analysis. You mention using this for data reduction and looking at the scatterplot of the first two principal components. The thinking behind that is reasonable, but you don't have to only look at the first two, others might be worth exploring (cf., Examples of PCA where PCs with low variance are “useful”), so you can / should make a scatterplot matrix of those, too. Another possibility with the output of a PCA is to make a biplot, which overlays the way the original variables are related to the principal components (as arrows) on top of the scatterplot. You could also combine a scatterplot matrix of the principal components with biplots.
All of the above are marginal, as I mentioned. A coplot is conditional (the top part of my answer here contrasts conditional vs. marginal). Literally, 'coplot' is a blended word from 'conditional plot'. In a coplot, you are taking slices (or subsets) of the data on the other dimensions and plotting the data in those subsets in a series of scatterplots. Once you learn how to read them, they are a nice addition to your set of options for exploring patterns in higher-dimensional data.
To illustrate these ideas, here is an example with the RandU dataset (pseudorandom data generated by an algorithm that was popular in the 1970's):
data(randu)
windows()
pairs(randu)
pca = princomp(randu)
attr(pca$scores, "dimnames")[[1]][1:400] = "o"
windows()
par(mfrow=c(3,3), mar=rep(.5,4), oma=rep(2,4))
for(i in 1:3){
for(j in 1:3){
if(i<j){
plot(y=pca$scores[,i], x=pca$scores[,j], axes=FALSE); box()
} else if(i==j){
plot(density(pca$scores[,i]), axes=FALSE, main=""); box()
text(0, .5, labels=colnames(pca$scores)[i])
} else {
biplot(pca, choices=c(j,i), main="", xaxp=c(-10,10,1), yaxp=c(-10,10,1))
}
}
}
windows()
coplot(y~x|z, randu)
|
Alternatives to three dimensional scatter plot
I think what primarily needs to be added to your list is coplots, but let's work our way up to that. The starting point for visualizing two continuous variables should always be a scatterplot. With
|
42,717
|
Chinese Restaurant process (CRP)
|
This implementation is using the Polya urn representation of the Dirichlet process like described by Blackwell and MacQueen (1973). In the link you've provided this particular part of the process is described as "With probability α/(1+α) he sits down at a new table." Conceptually one can think of this as capturing the idea that in principle there are an infinite number of possible tables to join.
The only difference under a weighted Chinese restaurant process in terms of the random number check is the probability of deciding to start a new table (cluster) will be different.
|
Chinese Restaurant process (CRP)
|
This implementation is using the Polya urn representation of the Dirichlet process like described by Blackwell and MacQueen (1973). In the link you've provided this particular part of the process is
|
Chinese Restaurant process (CRP)
This implementation is using the Polya urn representation of the Dirichlet process like described by Blackwell and MacQueen (1973). In the link you've provided this particular part of the process is described as "With probability α/(1+α) he sits down at a new table." Conceptually one can think of this as capturing the idea that in principle there are an infinite number of possible tables to join.
The only difference under a weighted Chinese restaurant process in terms of the random number check is the probability of deciding to start a new table (cluster) will be different.
|
Chinese Restaurant process (CRP)
This implementation is using the Polya urn representation of the Dirichlet process like described by Blackwell and MacQueen (1973). In the link you've provided this particular part of the process is
|
42,718
|
Chinese Restaurant process (CRP)
|
The CRP is a model used with graphical models to simulate how many clusters you have.
It's not applied to data points. In fact, it is a prior, and does not depend on the data at all.
|
Chinese Restaurant process (CRP)
|
The CRP is a model used with graphical models to simulate how many clusters you have.
It's not applied to data points. In fact, it is a prior, and does not depend on the data at all.
|
Chinese Restaurant process (CRP)
The CRP is a model used with graphical models to simulate how many clusters you have.
It's not applied to data points. In fact, it is a prior, and does not depend on the data at all.
|
Chinese Restaurant process (CRP)
The CRP is a model used with graphical models to simulate how many clusters you have.
It's not applied to data points. In fact, it is a prior, and does not depend on the data at all.
|
42,719
|
Integrating previous model's parameters as priors for Bayesian modeling of new data
|
In general, informing a prior requires a lot of judgment calls (and justification in the write up). There are several steps:
Collect the relevant previous studies that could inform the present one. This step is much like collecting previous studies for meta-analysis. You want to be sure it doesn't suffer from the file-drawer problem, whereby you'd only use published research that happened to reach significance and not the unpublished studies that happened not reach significance. In your case, this step might be easy because you've already restricted yourself to considering one specific previous study. (But then be careful not to dismiss "inconvenient" results of previous studies.)
Decide how to use the results of the previous studies to inform the present study. In general, previous studies might use different designs, different variables, different analyses. It's an artful translation from the parameters of different previous models to priors on the parameters in a new model. In your case, this step might be easy if your second study is the same structure as the previous study --- the mapping of parameters from previous analysis to new analysis is direct.
If you have an MCMC-sampled posterior distribution of the previous study, then figure out how to inform the mathematically-specified prior of the new study. In general, this step is not trivial because the posterior distribution of the previous study is, presumably, a complex multi-dimensional distribution almost certainly with correlations of parameters, and probably with skewed and/or kurtotic tails. You need to decide what sort of mathematical distribution can reasonably approximate the MCMC sample. Then you need to put that mathematical expression in the prior of JAGS. In your case, since you're doing linear regression, it could be important to include the correlations of the parameters.
If the structure of the second study is exactly the same as the first study, then you are, essentially, just collecting more data in the same study, and you can just collapse the two data sets into one. But presumably there is something different about the second study, so you can't just use the posterior of the first study directly and exactly for the second study, because if you did that's tantamount to saying you're just collecting more data in the same study. Instead, to capture the fact that there's something different about the second study, you should "relax" the prior, that is, make it more uncertain, because you're not sure how much the prior research really should apply to the second study. How much should you relax the prior? Well, remember the first sentence about a lot of judgment calls?
Other respondents may, of course, have more specific recommendations and might even point to examples in the literature that use informed priors. I'd just say to keep the above in mind as you read those examples.
|
Integrating previous model's parameters as priors for Bayesian modeling of new data
|
In general, informing a prior requires a lot of judgment calls (and justification in the write up). There are several steps:
Collect the relevant previous studies that could inform the present one. T
|
Integrating previous model's parameters as priors for Bayesian modeling of new data
In general, informing a prior requires a lot of judgment calls (and justification in the write up). There are several steps:
Collect the relevant previous studies that could inform the present one. This step is much like collecting previous studies for meta-analysis. You want to be sure it doesn't suffer from the file-drawer problem, whereby you'd only use published research that happened to reach significance and not the unpublished studies that happened not reach significance. In your case, this step might be easy because you've already restricted yourself to considering one specific previous study. (But then be careful not to dismiss "inconvenient" results of previous studies.)
Decide how to use the results of the previous studies to inform the present study. In general, previous studies might use different designs, different variables, different analyses. It's an artful translation from the parameters of different previous models to priors on the parameters in a new model. In your case, this step might be easy if your second study is the same structure as the previous study --- the mapping of parameters from previous analysis to new analysis is direct.
If you have an MCMC-sampled posterior distribution of the previous study, then figure out how to inform the mathematically-specified prior of the new study. In general, this step is not trivial because the posterior distribution of the previous study is, presumably, a complex multi-dimensional distribution almost certainly with correlations of parameters, and probably with skewed and/or kurtotic tails. You need to decide what sort of mathematical distribution can reasonably approximate the MCMC sample. Then you need to put that mathematical expression in the prior of JAGS. In your case, since you're doing linear regression, it could be important to include the correlations of the parameters.
If the structure of the second study is exactly the same as the first study, then you are, essentially, just collecting more data in the same study, and you can just collapse the two data sets into one. But presumably there is something different about the second study, so you can't just use the posterior of the first study directly and exactly for the second study, because if you did that's tantamount to saying you're just collecting more data in the same study. Instead, to capture the fact that there's something different about the second study, you should "relax" the prior, that is, make it more uncertain, because you're not sure how much the prior research really should apply to the second study. How much should you relax the prior? Well, remember the first sentence about a lot of judgment calls?
Other respondents may, of course, have more specific recommendations and might even point to examples in the literature that use informed priors. I'd just say to keep the above in mind as you read those examples.
|
Integrating previous model's parameters as priors for Bayesian modeling of new data
In general, informing a prior requires a lot of judgment calls (and justification in the write up). There are several steps:
Collect the relevant previous studies that could inform the present one. T
|
42,720
|
Flat prior in Bayesian? Confidence intervals in classical statistics turn into credible interval?
|
I am going to be snotty and say "no." Of course, an element of this is your wording of the question "can I." No. I forbid it. You cannot say that or anything at all like it. I also forbid you to say "turnip" for the entire month of May. Not just this May, but every May.
In a more serious vein, the answer is still "no," but only for a couple of very picky reasons that should be thought of as more of a personal/professional opinion rather than a canonical answer. Bayesian, Likelihoodist and Frequentist statistics do not answer the same type of question they answer three, often similar, questions.
The Frequentist answers the question of the probability of seeing the observed data, given a null hypothesis is the true state of nature. The Bayesian is answering a question regarding the probability a hypothesis is true, given an observed sample and any prior knowledge. Incidentally, the calculation formula and/or value is conceptually similar and may map to the same value.
So, 2+2=4 and 6-2=4, but they are not the same question. It can be a bit more complex because some tests for particular priors look notationally the same but are not the same. Consider the simple case of a normal density function/likelihood with a known variance of one where the open question is whether the center of location is less than four and a sample size of n. Because of how the problem marginalizes out both appear to use the same formula $$z=\sqrt{n}(\bar{x}-\mu),$$ but they are not the same formula at all. What is a constant for one is a variable for another and vice versa.
The interval is a bit more complex, though. There are an infinite number of possible confidence intervals and infinite possible numbers of credible intervals for the same problem, but for different reasons. You are deciding that the formulas, as above, are the same. For the same reason, they are not the same at all.
There is another, more subtle, problem here. You are forcing the prior to be flat, but it is rare to have no information at all. So the Bayesian answer is invalid in the presence of actual, but unused, information. Of course, if it is a true flat prior due to true, total ignorance then the answer is still "no," but not for the reason of this objection.
Finally, the answer is still "no" because you should be creating an interval that solves a problem as statistics is a branch of rhetoric, not mathematics. One of the two schools will be better at creating the argument you are trying solve and the other will not be as good. There is a utility or cost function question here as to how you should decide between the schools.
You risk being "irrational," and as "scholars," we should not do that. Again, as above, I forbid it. Indeed, if it will help, I will throw in a "verily." So, verily, I say unto you that it is forbidden for you to say the contents of your long quote above. And, forsooth, it is forbidden to you to say "turnip," for the entire month of May.
This inability to say "turnip," is your penance for having tried to mix and match two schools of thought. You are fain to obey this command, for otherwise, the end of all is nigh should you ever say the long quote above, or "turnip" during any month of May.
I do hope you have confidence that the answer is a credible solution to your problem (couldn't pass it up, no matter how hard I tried).
|
Flat prior in Bayesian? Confidence intervals in classical statistics turn into credible interval?
|
I am going to be snotty and say "no." Of course, an element of this is your wording of the question "can I." No. I forbid it. You cannot say that or anything at all like it. I also forbid you to
|
Flat prior in Bayesian? Confidence intervals in classical statistics turn into credible interval?
I am going to be snotty and say "no." Of course, an element of this is your wording of the question "can I." No. I forbid it. You cannot say that or anything at all like it. I also forbid you to say "turnip" for the entire month of May. Not just this May, but every May.
In a more serious vein, the answer is still "no," but only for a couple of very picky reasons that should be thought of as more of a personal/professional opinion rather than a canonical answer. Bayesian, Likelihoodist and Frequentist statistics do not answer the same type of question they answer three, often similar, questions.
The Frequentist answers the question of the probability of seeing the observed data, given a null hypothesis is the true state of nature. The Bayesian is answering a question regarding the probability a hypothesis is true, given an observed sample and any prior knowledge. Incidentally, the calculation formula and/or value is conceptually similar and may map to the same value.
So, 2+2=4 and 6-2=4, but they are not the same question. It can be a bit more complex because some tests for particular priors look notationally the same but are not the same. Consider the simple case of a normal density function/likelihood with a known variance of one where the open question is whether the center of location is less than four and a sample size of n. Because of how the problem marginalizes out both appear to use the same formula $$z=\sqrt{n}(\bar{x}-\mu),$$ but they are not the same formula at all. What is a constant for one is a variable for another and vice versa.
The interval is a bit more complex, though. There are an infinite number of possible confidence intervals and infinite possible numbers of credible intervals for the same problem, but for different reasons. You are deciding that the formulas, as above, are the same. For the same reason, they are not the same at all.
There is another, more subtle, problem here. You are forcing the prior to be flat, but it is rare to have no information at all. So the Bayesian answer is invalid in the presence of actual, but unused, information. Of course, if it is a true flat prior due to true, total ignorance then the answer is still "no," but not for the reason of this objection.
Finally, the answer is still "no" because you should be creating an interval that solves a problem as statistics is a branch of rhetoric, not mathematics. One of the two schools will be better at creating the argument you are trying solve and the other will not be as good. There is a utility or cost function question here as to how you should decide between the schools.
You risk being "irrational," and as "scholars," we should not do that. Again, as above, I forbid it. Indeed, if it will help, I will throw in a "verily." So, verily, I say unto you that it is forbidden for you to say the contents of your long quote above. And, forsooth, it is forbidden to you to say "turnip," for the entire month of May.
This inability to say "turnip," is your penance for having tried to mix and match two schools of thought. You are fain to obey this command, for otherwise, the end of all is nigh should you ever say the long quote above, or "turnip" during any month of May.
I do hope you have confidence that the answer is a credible solution to your problem (couldn't pass it up, no matter how hard I tried).
|
Flat prior in Bayesian? Confidence intervals in classical statistics turn into credible interval?
I am going to be snotty and say "no." Of course, an element of this is your wording of the question "can I." No. I forbid it. You cannot say that or anything at all like it. I also forbid you to
|
42,721
|
Optimum approximate theory D-Optimal design
|
OK, this is a bit complicated, but i will try to explain some issues here.
First of all, you need to know that you can calculate the
theoretical (i.e. the maximum possible) and practically obtained
(i.e. the ones that you get in a given configuration of cards and
their sets) values for D-efficiency. The "quality" of the plan (for
example in DCE method) is assessed with these coefficients, where
the practical and theoretical value give information about the
extent to which the reduced (partial) card plan will give you similar
possibilities of calculating statistical coefficients on the results
obtained by full plan method. The case is therefore very
complicated; here we have a plan that allows us to "theoretically
obtain D = 3.8" and practical D for a specific variant, D = 3.68,
which gives an approximate percentage result of 3.38 / 3.80 = 97% of
the plan effectiveness.
The most complicated issue is obtaining the maximum theoretical
plan, or in other words, the maximum D for a particular plan. The
calculation of the maximum D is related to how many main effects and
interaction effects in the resulting analysis plan then we want to use.
There are many examples of such information obtaining, but all of
them are very illegible. Why? Well - we do not know what analysis
plan the researcher set up for himself and for what plan he
calculated the maximum possible D that could be obtained. In the
example above, we can create a matrix only for main effects, for
interactive effects, or for first or second order interactive
effects. The maximum value of D will vary depending on these
findings. I admit that I do not know for what plan this indicator
was obtained and I hope that someone has figured out this example
with D = 3.8.
Anyway - the matter is complicated by the fact that different
programs have different algorithms for measuring D and often the
same plans in R or other software will give completely different D
and other indicators. The reason is often an encoding issue:
orthogonal encoding, dummy encoding, or effect encoding changes the
practical D values (you will get different wr values if you encode
your data -1, 0 and 1 than if you encode them 1 2 and 3) ... which
should be interpreted in the context of theoretical D ... which in
turn depends on the size of your research plan of analyzes.
Due to this chaos, for some time published articles do not interpret
D or other indicators, but simply give their raw values. Instead,
the researcher tries to justify somehow the research plan he chooses
and maximize the practically obtained indicators simply for such a
plan. Now it's time for the R exercise in the example above.
For Your example we got in R
library(AlgDesign)
dat <- gen.factorial(5, 3)
des <- optFederov(~ quad(.), dat, nTrials=15, evaluateI=TRUE)
des$D
which should give us the value of d
[1] 3.675919
Knowing that
The D-efficiency values are a function of the number of points in
the design, the number of independent variables in the model, and the
maximum standard error for prediction over the design points.
and
The best design is the one with the highest D-efficiency. Other
reported efficiencies (e.g. A, G, I) help choose an optimal design
when various models produce similar D-efficiencies.
we can check all of possibilities and use best one. In "dat" variable we have full plan of 125 possibilities/cards/research conditions/whatever. So we can check any variant between 5 cards for optFederov (minimal number) and all cards used. We will create an array variable that will allow us to save all the possibilities.
min <- 10
max <- 125
eff_table <- matrix(ncol = 6, nrow = max)
colnames(eff_table) <- c("nTrials", "D", "A", "I", "Ge", "Dea")
for (loop_num in min:max) {
des <- optFederov( ~ quad(.), dat, nTrials=loop_num,
evaluateI=TRUE, crit = "D", nRepeats = 100)
eff_table[loop_num, 1] <- loop_num
eff_table[loop_num, 2] <- des$D
eff_table[loop_num, 3] <- des$A
eff_table[loop_num, 4] <- des$I
eff_table[loop_num, 5] <- des$Ge
eff_table[loop_num, 6] <- des$Dea
}
Counting will take a while. Check differences with nRepeats and without; In my opinion, we should always use multiple retry, which is with this option. Then we get the best possible configuration in this regard. In
eff_table
You should get all informations for subsequent options for the number of cards. Something like this
nTrials D A I Ge Dea
(...)
[14,] 14 3.704358 0.8132031 7.820313 0.893 0.887
[15,] 15 3.675919 1.2555973 8.848874 0.775 0.749
[16,] 16 3.666758 1.2910678 8.807469 0.742 0.706
[17,] 17 3.667087 1.3115654 8.693003 0.704 0.657
[18,] 18 3.674348 1.1586909 8.544911 0.778 0.752
(...)
You can now choose the best practical option for your research plan and compare the ratios. Note: one can also get with this method estimates for the full factorial plan, which are the maximum values you can get at all with mentioned method. On this basis, you can decide which plan is the best ... and calculate the percentage effectiveness ratio in relation to the full plan.
Hope that will help You a bit. Feel free to ask and comment on this.
Additional informations and issues:
The D-efficiency values are a function of the number of points in the
design, the number of independent variables in the model, and the
maximum standard error for prediction over the design points. The
best design is the one with the highest D-efficiency. Other reported
efficiencies (e.g. A, G, I) help choose an optimal design when
various models produce similar D-efficiencies.
https://itl.nist.gov/div898/handbook/pri/section5/pri521.htm
interesting example of D counting:
https://legacy.sawtoothsoftware.com/forum/23896/calculate-design-efficiency-manually
D-Efficiency definition and general formulas: D-efficiency is the
relative number of runs (expressed as a percent) required by a
hypothetical orthogonal design to achieve the same determinant value.
It provides a way of comparing designs across different sample sizes.
https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/D-Optimal_Designs.pdf
Other ideas about maximum D:
How to derive variance-covariance matrix of coefficients in linear regression
|
Optimum approximate theory D-Optimal design
|
OK, this is a bit complicated, but i will try to explain some issues here.
First of all, you need to know that you can calculate the
theoretical (i.e. the maximum possible) and practically obtained
(
|
Optimum approximate theory D-Optimal design
OK, this is a bit complicated, but i will try to explain some issues here.
First of all, you need to know that you can calculate the
theoretical (i.e. the maximum possible) and practically obtained
(i.e. the ones that you get in a given configuration of cards and
their sets) values for D-efficiency. The "quality" of the plan (for
example in DCE method) is assessed with these coefficients, where
the practical and theoretical value give information about the
extent to which the reduced (partial) card plan will give you similar
possibilities of calculating statistical coefficients on the results
obtained by full plan method. The case is therefore very
complicated; here we have a plan that allows us to "theoretically
obtain D = 3.8" and practical D for a specific variant, D = 3.68,
which gives an approximate percentage result of 3.38 / 3.80 = 97% of
the plan effectiveness.
The most complicated issue is obtaining the maximum theoretical
plan, or in other words, the maximum D for a particular plan. The
calculation of the maximum D is related to how many main effects and
interaction effects in the resulting analysis plan then we want to use.
There are many examples of such information obtaining, but all of
them are very illegible. Why? Well - we do not know what analysis
plan the researcher set up for himself and for what plan he
calculated the maximum possible D that could be obtained. In the
example above, we can create a matrix only for main effects, for
interactive effects, or for first or second order interactive
effects. The maximum value of D will vary depending on these
findings. I admit that I do not know for what plan this indicator
was obtained and I hope that someone has figured out this example
with D = 3.8.
Anyway - the matter is complicated by the fact that different
programs have different algorithms for measuring D and often the
same plans in R or other software will give completely different D
and other indicators. The reason is often an encoding issue:
orthogonal encoding, dummy encoding, or effect encoding changes the
practical D values (you will get different wr values if you encode
your data -1, 0 and 1 than if you encode them 1 2 and 3) ... which
should be interpreted in the context of theoretical D ... which in
turn depends on the size of your research plan of analyzes.
Due to this chaos, for some time published articles do not interpret
D or other indicators, but simply give their raw values. Instead,
the researcher tries to justify somehow the research plan he chooses
and maximize the practically obtained indicators simply for such a
plan. Now it's time for the R exercise in the example above.
For Your example we got in R
library(AlgDesign)
dat <- gen.factorial(5, 3)
des <- optFederov(~ quad(.), dat, nTrials=15, evaluateI=TRUE)
des$D
which should give us the value of d
[1] 3.675919
Knowing that
The D-efficiency values are a function of the number of points in
the design, the number of independent variables in the model, and the
maximum standard error for prediction over the design points.
and
The best design is the one with the highest D-efficiency. Other
reported efficiencies (e.g. A, G, I) help choose an optimal design
when various models produce similar D-efficiencies.
we can check all of possibilities and use best one. In "dat" variable we have full plan of 125 possibilities/cards/research conditions/whatever. So we can check any variant between 5 cards for optFederov (minimal number) and all cards used. We will create an array variable that will allow us to save all the possibilities.
min <- 10
max <- 125
eff_table <- matrix(ncol = 6, nrow = max)
colnames(eff_table) <- c("nTrials", "D", "A", "I", "Ge", "Dea")
for (loop_num in min:max) {
des <- optFederov( ~ quad(.), dat, nTrials=loop_num,
evaluateI=TRUE, crit = "D", nRepeats = 100)
eff_table[loop_num, 1] <- loop_num
eff_table[loop_num, 2] <- des$D
eff_table[loop_num, 3] <- des$A
eff_table[loop_num, 4] <- des$I
eff_table[loop_num, 5] <- des$Ge
eff_table[loop_num, 6] <- des$Dea
}
Counting will take a while. Check differences with nRepeats and without; In my opinion, we should always use multiple retry, which is with this option. Then we get the best possible configuration in this regard. In
eff_table
You should get all informations for subsequent options for the number of cards. Something like this
nTrials D A I Ge Dea
(...)
[14,] 14 3.704358 0.8132031 7.820313 0.893 0.887
[15,] 15 3.675919 1.2555973 8.848874 0.775 0.749
[16,] 16 3.666758 1.2910678 8.807469 0.742 0.706
[17,] 17 3.667087 1.3115654 8.693003 0.704 0.657
[18,] 18 3.674348 1.1586909 8.544911 0.778 0.752
(...)
You can now choose the best practical option for your research plan and compare the ratios. Note: one can also get with this method estimates for the full factorial plan, which are the maximum values you can get at all with mentioned method. On this basis, you can decide which plan is the best ... and calculate the percentage effectiveness ratio in relation to the full plan.
Hope that will help You a bit. Feel free to ask and comment on this.
Additional informations and issues:
The D-efficiency values are a function of the number of points in the
design, the number of independent variables in the model, and the
maximum standard error for prediction over the design points. The
best design is the one with the highest D-efficiency. Other reported
efficiencies (e.g. A, G, I) help choose an optimal design when
various models produce similar D-efficiencies.
https://itl.nist.gov/div898/handbook/pri/section5/pri521.htm
interesting example of D counting:
https://legacy.sawtoothsoftware.com/forum/23896/calculate-design-efficiency-manually
D-Efficiency definition and general formulas: D-efficiency is the
relative number of runs (expressed as a percent) required by a
hypothetical orthogonal design to achieve the same determinant value.
It provides a way of comparing designs across different sample sizes.
https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/D-Optimal_Designs.pdf
Other ideas about maximum D:
How to derive variance-covariance matrix of coefficients in linear regression
|
Optimum approximate theory D-Optimal design
OK, this is a bit complicated, but i will try to explain some issues here.
First of all, you need to know that you can calculate the
theoretical (i.e. the maximum possible) and practically obtained
(
|
42,722
|
Finding the best cookie recipe. Hyper-parameter optimization using noisy local comparison
|
If you're interested in use (more than in development), you should give a try to rankade, our ranking system. Rankade is free and easy to use, it can manage small to large playing groups (composed by players or 'cookies', as per your needs, or whatever), and it features rankings, stats, and more. It doesn't cover all of your tasks, maybe, but it should be useful to rank $n$ cookies from best to worst, both with global and partial rankings.
Ghosts' feature allows you to create a group without any account but your. Rankade's algorithm can manage, within different scopes, any kind of match. Due to faction structure, you can record outputs for 1-on-1 comparison, or for 2+ items as well (even mixing both kinds of 'matches'), while Bradley-Terry model or other ranking system (like most known Elo or Glicko - here's a comparison) don't. It's surely true that it's pretty hard to give a consistent score to each cookie you taste, but a multiple comparison (e.g. 3-6 cookies per 'match') should be suitable and useful, in your work. If you have more than one tester with different reliability, you can use weight feature for their 'matches'.
|
Finding the best cookie recipe. Hyper-parameter optimization using noisy local comparison
|
If you're interested in use (more than in development), you should give a try to rankade, our ranking system. Rankade is free and easy to use, it can manage small to large playing groups (composed by
|
Finding the best cookie recipe. Hyper-parameter optimization using noisy local comparison
If you're interested in use (more than in development), you should give a try to rankade, our ranking system. Rankade is free and easy to use, it can manage small to large playing groups (composed by players or 'cookies', as per your needs, or whatever), and it features rankings, stats, and more. It doesn't cover all of your tasks, maybe, but it should be useful to rank $n$ cookies from best to worst, both with global and partial rankings.
Ghosts' feature allows you to create a group without any account but your. Rankade's algorithm can manage, within different scopes, any kind of match. Due to faction structure, you can record outputs for 1-on-1 comparison, or for 2+ items as well (even mixing both kinds of 'matches'), while Bradley-Terry model or other ranking system (like most known Elo or Glicko - here's a comparison) don't. It's surely true that it's pretty hard to give a consistent score to each cookie you taste, but a multiple comparison (e.g. 3-6 cookies per 'match') should be suitable and useful, in your work. If you have more than one tester with different reliability, you can use weight feature for their 'matches'.
|
Finding the best cookie recipe. Hyper-parameter optimization using noisy local comparison
If you're interested in use (more than in development), you should give a try to rankade, our ranking system. Rankade is free and easy to use, it can manage small to large playing groups (composed by
|
42,723
|
What is the distribution of the maximum of independent non identical Binomial variables?
|
As whuber correctly points out in the comments, the random variable $X$ is discrete with support on the same space as the original random variables. Hence, the maximum possible value of $X$ is $m$, and it does not make sense to use a normal approximation (or any other approximation) that would allow a larger maximum than this.
The distribution function for $X$ can be obtained by standard methods, but it is an ugly distribution. For all $x = 0, 1, 2, ..., m$ you have:
$$\begin{equation} \begin{aligned}
F_X(x) \equiv \mathbb{P}(X \leqslant x)
&= \prod_{i=1}^n \mathbb{P}(Y_i \leqslant x) \\[6pt]
&= \prod_{i=1}^n \sum_{r=0}^x \text{Bin}( r |m, p_i) \\[6pt]
&= \prod_{i=1}^n \sum_{r=0}^x {m \choose r} p_i^r (1-p_i)^{m-r}. \\[6pt]
\end{aligned} \end{equation}$$
Particular values of this distribution function are given by:
$$\begin{equation} \begin{aligned}
F_X(0) &= \prod_{i=1}^n (1-p_i)^m, \\[6pt]
F_X(1) &= \prod_{i=1}^n [ (1-p_i)^m + m p_i (1-p_i)^{m-1}], \\[6pt]
F_X(2) &= \prod_{i=1}^n [ (1-p_i)^m + m p_i (1-p_i)^{m-1} + \tfrac{m(m-1)}{2} p_i^2 (1-p_i)^{m-2}], \\[6pt]
&\text{ } \text{ } \vdots \\[6pt]
F_X(m-1) &= \prod_{i=1}^n [ (1-p_i)^m + m p_i (1-p_i)^{m-1} + \cdots + m p_i^{m-1}(1-p_i) ], \\[6pt]
F_X(m) &= 1. \\[6pt]
\end{aligned} \end{equation}$$
This cannot be simplified any further for the general case. Even in the case of equal probabilities where $p_1 = \cdots = p_n$ the simplification reduces the product to a simple power, but this still gives a distribution with quite a complicated form. So long as $m$ is not too large, it should be possible to obtain the probability mass function analytically, which would give all the moments, etc.
|
What is the distribution of the maximum of independent non identical Binomial variables?
|
As whuber correctly points out in the comments, the random variable $X$ is discrete with support on the same space as the original random variables. Hence, the maximum possible value of $X$ is $m$, a
|
What is the distribution of the maximum of independent non identical Binomial variables?
As whuber correctly points out in the comments, the random variable $X$ is discrete with support on the same space as the original random variables. Hence, the maximum possible value of $X$ is $m$, and it does not make sense to use a normal approximation (or any other approximation) that would allow a larger maximum than this.
The distribution function for $X$ can be obtained by standard methods, but it is an ugly distribution. For all $x = 0, 1, 2, ..., m$ you have:
$$\begin{equation} \begin{aligned}
F_X(x) \equiv \mathbb{P}(X \leqslant x)
&= \prod_{i=1}^n \mathbb{P}(Y_i \leqslant x) \\[6pt]
&= \prod_{i=1}^n \sum_{r=0}^x \text{Bin}( r |m, p_i) \\[6pt]
&= \prod_{i=1}^n \sum_{r=0}^x {m \choose r} p_i^r (1-p_i)^{m-r}. \\[6pt]
\end{aligned} \end{equation}$$
Particular values of this distribution function are given by:
$$\begin{equation} \begin{aligned}
F_X(0) &= \prod_{i=1}^n (1-p_i)^m, \\[6pt]
F_X(1) &= \prod_{i=1}^n [ (1-p_i)^m + m p_i (1-p_i)^{m-1}], \\[6pt]
F_X(2) &= \prod_{i=1}^n [ (1-p_i)^m + m p_i (1-p_i)^{m-1} + \tfrac{m(m-1)}{2} p_i^2 (1-p_i)^{m-2}], \\[6pt]
&\text{ } \text{ } \vdots \\[6pt]
F_X(m-1) &= \prod_{i=1}^n [ (1-p_i)^m + m p_i (1-p_i)^{m-1} + \cdots + m p_i^{m-1}(1-p_i) ], \\[6pt]
F_X(m) &= 1. \\[6pt]
\end{aligned} \end{equation}$$
This cannot be simplified any further for the general case. Even in the case of equal probabilities where $p_1 = \cdots = p_n$ the simplification reduces the product to a simple power, but this still gives a distribution with quite a complicated form. So long as $m$ is not too large, it should be possible to obtain the probability mass function analytically, which would give all the moments, etc.
|
What is the distribution of the maximum of independent non identical Binomial variables?
As whuber correctly points out in the comments, the random variable $X$ is discrete with support on the same space as the original random variables. Hence, the maximum possible value of $X$ is $m$, a
|
42,724
|
"ARIMA" versus "ARMA on differenced data" gives different prediction interval
|
The prediction intervals from ARIMA(p,1,q) for the original data as produced by the function Arima will be correct, while those from ARIMA(p,0,q) for differenced data produced by manually undifferencing the forecasts the way you do that will be incorrect.
Illustration
Suppose the last observed value is $x_t=100$. Suppose the point forecasts for $t+1$, $t+2$ and $t+3$ from ARIMA(p,0,q) for differenced data are
\begin{aligned}
\widehat{\Delta x}_{t+1}^{point} &= 0.0, \\
\widehat{\Delta x}_{t+2}^{point} &= 0.5, \\
\widehat{\Delta x}_{t+3}^{point} &= 0.0. \\
\end{aligned}
Suppose the lower end of the 80% prediction interval is
\begin{aligned}
\widehat{\Delta x}_{t+1}^{0.1} &= -1.0, \\
\widehat{\Delta x}_{t+2}^{0.1} &= -0.5, \\
\widehat{\Delta x}_{t+3}^{0.1} &= -1.0; \\
\end{aligned}
and the upper end is
\begin{aligned}
\widehat{\Delta x}_{t+1}^{0.9} &= 1.0, \\
\widehat{\Delta x}_{t+2}^{0.9} &= 1.5, \\
\widehat{\Delta x}_{t+3}^{0.9} &= 1.0. \\
\end{aligned}
(I assume symmetric prediction intervals here, but they could as well be asymmetric.)
To obtain forecasts for the original data (the data in levels), you need to undifference. Undifferencing is done by cummulatively summing the forecasts for the differenced data. That yields the point forecasts
\begin{aligned}
\hat x_{t+1}^{point} &= x_t + \widehat{\Delta x}_{t+1}^{point} &= 100+0.0 &= 100.0, \\
\hat x_{t+2}^{point} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} &= 100+0.0+0.5 &= 100.5, \\
\hat x_{t+3}^{point} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{point} &= 100+0.0+0.5+0.0 &= 100.5. \\
\end{aligned}
Now what about the prediction intervals?
The correct way
The lower and upper forecasts are obtained in the same way as the point forecasts -- by summing up the forecasted differences:
\begin{aligned}
\hat x_{t+1}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} &= 100-1.0 &= 99.0, \\
\hat x_{t+2}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} + \widehat{\Delta x}_{t+2}^{0.1} &= 100-1.0-0.5 &= 98.5, \\
\hat x_{t+3}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} + \widehat{\Delta x}_{t+2}^{0.1} + \widehat{\Delta x}_{t+3}^{0.1} &= 100-1.0-0.5-1.0 &= 97.5; \\
\end{aligned}
and
\begin{aligned}
\hat x_{t+1}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} &= 100+1.0 &= 101.0, \\
\hat x_{t+2}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} + \widehat{\Delta x}_{t+2}^{0.9} &= 100+1.0+1.5 &= 102.5, \\
\hat x_{t+3}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} + \widehat{\Delta x}_{t+2}^{0.9} + \widehat{\Delta x}_{t+3}^{0.9} &= 100+1.0+1.5+1.0 &= 103.5. \\
\end{aligned}
As you see, the uncertainty has efectively cumulatively summed up this way: the uncertainty over $x_{t+3}$ ($\pm 3$) is greater than that for $x_{t+2}$ ($\pm 2$), which in turn is greater than that for $x_{t+1}$ ($\pm 1$). This is natural, as the further into the future, the less sure we can be.
The incorrect way
One may incorrectly try to obtain the lower and upper forecasts without cumulative summation but using only the last upper and lower values of $\widehat {\Delta x}_{t+h}$ around the point forecast $\hat x_{t+h}$ instead, which produces wrongly narrow prediction intervals:
\begin{aligned}
\hat x_{t+1}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} & &= 100-1.0 &= 99.0, \\
\hat x_{t+2}^{0.1} &= \hat x_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.1} &= 100.0-0.5 &= 99.5, \\
\hat x_{t+3}^{0.1} &= \hat x_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.9} &= 100.5-1.0 &= 99.5; \\
\end{aligned}
and
\begin{aligned}
\hat x_{t+1}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} & &= 100+1.0 &= 101.0, \\
\hat x_{t+2}^{0.9} &= \hat x_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.1} &= 100.0+1.5 &= 101.5, \\
\hat x_{t+3}^{0.9} &= \hat x_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.9} &= 100.5+1.0 &= 101.5. \\
\end{aligned}
You can see explicitly that the wrong elements are summed here. Also, the outcome is counterintuitive: the prediction interval for $t+3$ is just as narrow as for $t+1$ or $t+2$. Just think about it: can we be equally certain over what will happen at time $t+3$ (the distant future) as at $t+2$ (medium distant future) and at $t+1$ (the near future)?
|
"ARIMA" versus "ARMA on differenced data" gives different prediction interval
|
The prediction intervals from ARIMA(p,1,q) for the original data as produced by the function Arima will be correct, while those from ARIMA(p,0,q) for differenced data produced by manually undifferenci
|
"ARIMA" versus "ARMA on differenced data" gives different prediction interval
The prediction intervals from ARIMA(p,1,q) for the original data as produced by the function Arima will be correct, while those from ARIMA(p,0,q) for differenced data produced by manually undifferencing the forecasts the way you do that will be incorrect.
Illustration
Suppose the last observed value is $x_t=100$. Suppose the point forecasts for $t+1$, $t+2$ and $t+3$ from ARIMA(p,0,q) for differenced data are
\begin{aligned}
\widehat{\Delta x}_{t+1}^{point} &= 0.0, \\
\widehat{\Delta x}_{t+2}^{point} &= 0.5, \\
\widehat{\Delta x}_{t+3}^{point} &= 0.0. \\
\end{aligned}
Suppose the lower end of the 80% prediction interval is
\begin{aligned}
\widehat{\Delta x}_{t+1}^{0.1} &= -1.0, \\
\widehat{\Delta x}_{t+2}^{0.1} &= -0.5, \\
\widehat{\Delta x}_{t+3}^{0.1} &= -1.0; \\
\end{aligned}
and the upper end is
\begin{aligned}
\widehat{\Delta x}_{t+1}^{0.9} &= 1.0, \\
\widehat{\Delta x}_{t+2}^{0.9} &= 1.5, \\
\widehat{\Delta x}_{t+3}^{0.9} &= 1.0. \\
\end{aligned}
(I assume symmetric prediction intervals here, but they could as well be asymmetric.)
To obtain forecasts for the original data (the data in levels), you need to undifference. Undifferencing is done by cummulatively summing the forecasts for the differenced data. That yields the point forecasts
\begin{aligned}
\hat x_{t+1}^{point} &= x_t + \widehat{\Delta x}_{t+1}^{point} &= 100+0.0 &= 100.0, \\
\hat x_{t+2}^{point} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} &= 100+0.0+0.5 &= 100.5, \\
\hat x_{t+3}^{point} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{point} &= 100+0.0+0.5+0.0 &= 100.5. \\
\end{aligned}
Now what about the prediction intervals?
The correct way
The lower and upper forecasts are obtained in the same way as the point forecasts -- by summing up the forecasted differences:
\begin{aligned}
\hat x_{t+1}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} &= 100-1.0 &= 99.0, \\
\hat x_{t+2}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} + \widehat{\Delta x}_{t+2}^{0.1} &= 100-1.0-0.5 &= 98.5, \\
\hat x_{t+3}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} + \widehat{\Delta x}_{t+2}^{0.1} + \widehat{\Delta x}_{t+3}^{0.1} &= 100-1.0-0.5-1.0 &= 97.5; \\
\end{aligned}
and
\begin{aligned}
\hat x_{t+1}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} &= 100+1.0 &= 101.0, \\
\hat x_{t+2}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} + \widehat{\Delta x}_{t+2}^{0.9} &= 100+1.0+1.5 &= 102.5, \\
\hat x_{t+3}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} + \widehat{\Delta x}_{t+2}^{0.9} + \widehat{\Delta x}_{t+3}^{0.9} &= 100+1.0+1.5+1.0 &= 103.5. \\
\end{aligned}
As you see, the uncertainty has efectively cumulatively summed up this way: the uncertainty over $x_{t+3}$ ($\pm 3$) is greater than that for $x_{t+2}$ ($\pm 2$), which in turn is greater than that for $x_{t+1}$ ($\pm 1$). This is natural, as the further into the future, the less sure we can be.
The incorrect way
One may incorrectly try to obtain the lower and upper forecasts without cumulative summation but using only the last upper and lower values of $\widehat {\Delta x}_{t+h}$ around the point forecast $\hat x_{t+h}$ instead, which produces wrongly narrow prediction intervals:
\begin{aligned}
\hat x_{t+1}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{0.1} & &= 100-1.0 &= 99.0, \\
\hat x_{t+2}^{0.1} &= \hat x_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.1} &= 100.0-0.5 &= 99.5, \\
\hat x_{t+3}^{0.1} &= \hat x_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.1} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.9} &= 100.5-1.0 &= 99.5; \\
\end{aligned}
and
\begin{aligned}
\hat x_{t+1}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{0.9} & &= 100+1.0 &= 101.0, \\
\hat x_{t+2}^{0.9} &= \hat x_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{0.1} &= 100.0+1.5 &= 101.5, \\
\hat x_{t+3}^{0.9} &= \hat x_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.9} &= x_t + \widehat{\Delta x}_{t+1}^{point} + \widehat{\Delta x}_{t+2}^{point} + \widehat{\Delta x}_{t+3}^{0.9} &= 100.5+1.0 &= 101.5. \\
\end{aligned}
You can see explicitly that the wrong elements are summed here. Also, the outcome is counterintuitive: the prediction interval for $t+3$ is just as narrow as for $t+1$ or $t+2$. Just think about it: can we be equally certain over what will happen at time $t+3$ (the distant future) as at $t+2$ (medium distant future) and at $t+1$ (the near future)?
|
"ARIMA" versus "ARMA on differenced data" gives different prediction interval
The prediction intervals from ARIMA(p,1,q) for the original data as produced by the function Arima will be correct, while those from ARIMA(p,0,q) for differenced data produced by manually undifferenci
|
42,725
|
What can go wrong with MLE if I substitute some first-stage estimates instead of some parameters?
|
Your technique is essentially maximizing the conditional log-likelihood, conditioned on $\tilde \theta_{m+1},\ldots,\tilde \theta_k$. The complete maximum log-likelihood is the maximum of this conditional maximum across all these other parameters. This is very frequently used to produce likelihood scans, especially when $k=m+1$ and there is only one conditionalized parameter. The maximum log-likelihood as a function of $\tilde \theta_k$ is useful in setting a confidence interval on $\theta_k$.
Philosophically, it is always the case that there are conditional parameters that are fixed -- you could always add extra parameters into your model. Every likelihood function is a conditional likelihood function, and vice versa; the maximization of a conditional log-likelihood function has all the statistical properties you might expect from maximizing a likelihood function. The only differences are non-statistical in nature, dealing with the assumptions behind the maximization. For example, how reasonable is it to simplify the model? Typically you might like to know that you have an exact value for $\tilde \theta_k$, or that there is some domain-specific (non-statistical) argument for it to have a certain value. For example, in OLS (a type of likelihood maximization), it is assumed that the errors are symmetric, gaussian, and independent of the explanatory variables (e.g. non-heteroskedastic). You could always add parameters for skewness, non-gaussianity, and heteroskedasity, but this is frequently judged to be unnecessary.*
In your case, you just have a statistical estimate, with some confidence interval. The critical question is whether your estimates are taken from the same data that is used during the likelihood maximization, or from an independent dataset. In the latter case, you are performing a very common procedure. One ad-hoc procedure you could try to propagate uncertainties from $\tilde \theta$ onto your final result could be to sample your $\tilde \theta$ from within their confidence intervals in a sort of parametric bootstrap, and maximize the conditional log-likelihood for each sample, yielding an expanded confidence interval. Another technique is to let the parameters float in the log-likelihood, but add constraint terms for their confidence intervals; for example, multiplying the likelihood by a gaussian p.d.f. $\exp(-(\theta_k-\tilde \theta_k)^2/2\sigma_k^2)$, ignoring irrelevant constants.
On the other hand, if your estimates $\tilde \theta$ are made with the same data used in the likelihood maximization, yours is a more questionable procedure. Taking the set of $\tilde \theta$ as fixed givens, the conditional log-likelihood maximization is statistically valid, but it is not guaranteed to play nice with whatever confidence intervals you have for your $\tilde \theta$. The above procedures for adding constraint terms to the likelihood or parametrically sampling the parameters are invalid because the parameters are then double-penalized by the same dataset. You could scan through $\tilde \theta_{m+1},\ldots,\tilde \theta_k$, in a grid covering a reasonable confidence interval. Only you can determine if this is better/easier than simply maximizing the entire log-likelihood.
NOTES
Perhaps not the best example, because it is usually recommended that you study the diagnostic plots/residuals for an OLS regression to check for these things. The better examples that I could come up with are domain specific.
|
What can go wrong with MLE if I substitute some first-stage estimates instead of some parameters?
|
Your technique is essentially maximizing the conditional log-likelihood, conditioned on $\tilde \theta_{m+1},\ldots,\tilde \theta_k$. The complete maximum log-likelihood is the maximum of this conditi
|
What can go wrong with MLE if I substitute some first-stage estimates instead of some parameters?
Your technique is essentially maximizing the conditional log-likelihood, conditioned on $\tilde \theta_{m+1},\ldots,\tilde \theta_k$. The complete maximum log-likelihood is the maximum of this conditional maximum across all these other parameters. This is very frequently used to produce likelihood scans, especially when $k=m+1$ and there is only one conditionalized parameter. The maximum log-likelihood as a function of $\tilde \theta_k$ is useful in setting a confidence interval on $\theta_k$.
Philosophically, it is always the case that there are conditional parameters that are fixed -- you could always add extra parameters into your model. Every likelihood function is a conditional likelihood function, and vice versa; the maximization of a conditional log-likelihood function has all the statistical properties you might expect from maximizing a likelihood function. The only differences are non-statistical in nature, dealing with the assumptions behind the maximization. For example, how reasonable is it to simplify the model? Typically you might like to know that you have an exact value for $\tilde \theta_k$, or that there is some domain-specific (non-statistical) argument for it to have a certain value. For example, in OLS (a type of likelihood maximization), it is assumed that the errors are symmetric, gaussian, and independent of the explanatory variables (e.g. non-heteroskedastic). You could always add parameters for skewness, non-gaussianity, and heteroskedasity, but this is frequently judged to be unnecessary.*
In your case, you just have a statistical estimate, with some confidence interval. The critical question is whether your estimates are taken from the same data that is used during the likelihood maximization, or from an independent dataset. In the latter case, you are performing a very common procedure. One ad-hoc procedure you could try to propagate uncertainties from $\tilde \theta$ onto your final result could be to sample your $\tilde \theta$ from within their confidence intervals in a sort of parametric bootstrap, and maximize the conditional log-likelihood for each sample, yielding an expanded confidence interval. Another technique is to let the parameters float in the log-likelihood, but add constraint terms for their confidence intervals; for example, multiplying the likelihood by a gaussian p.d.f. $\exp(-(\theta_k-\tilde \theta_k)^2/2\sigma_k^2)$, ignoring irrelevant constants.
On the other hand, if your estimates $\tilde \theta$ are made with the same data used in the likelihood maximization, yours is a more questionable procedure. Taking the set of $\tilde \theta$ as fixed givens, the conditional log-likelihood maximization is statistically valid, but it is not guaranteed to play nice with whatever confidence intervals you have for your $\tilde \theta$. The above procedures for adding constraint terms to the likelihood or parametrically sampling the parameters are invalid because the parameters are then double-penalized by the same dataset. You could scan through $\tilde \theta_{m+1},\ldots,\tilde \theta_k$, in a grid covering a reasonable confidence interval. Only you can determine if this is better/easier than simply maximizing the entire log-likelihood.
NOTES
Perhaps not the best example, because it is usually recommended that you study the diagnostic plots/residuals for an OLS regression to check for these things. The better examples that I could come up with are domain specific.
|
What can go wrong with MLE if I substitute some first-stage estimates instead of some parameters?
Your technique is essentially maximizing the conditional log-likelihood, conditioned on $\tilde \theta_{m+1},\ldots,\tilde \theta_k$. The complete maximum log-likelihood is the maximum of this conditi
|
42,726
|
Is there an accepted method to determine an approximate dimension for manifold learning
|
I am not quite sure if I understood your confusion correctly, if you accept the embedding principle (i.e. the "manifold assumption") the only way you can "decide" your dimension is to construct a projector to low-dimensional manifold. [Levina&Bickel] pointed out that eigenvalue(spectral projector) and projection are two mainstream methods at their time.
The method you pointed out ("dimension expansion") is one way to construct projector (approximately). It is widely used in statistics and biostatistics (say [Sampson&Guttorp]) not only because of its performance but also due to its relatively easy idea and control of error rate for general observations. And not surprisingly, in most applications, favorite predictive algorithm will be a spline regression/thin-plate spline since its performance can be dominated by a Taylor-like term.
Since [Levina&Bickel] is published, it has never overcome this dimension expansion method in practice since MLE is based on conditionality evidence functional (due to Birnbaum's theorem) which most people will argue that it is not reasonable to use when the inference is on the design (the dimension of the observation is usually part of design of the experiment, not observation of the experiment).
I do not know what do you mean by unsatisfactory. If you think there is one way of figuring out the projector exactly(in closed form) for a general manifold(which is the case for most observations embedded in an infinite-dimensional space), that is an unsolved mathematical problem. If you mean the result does not come out in expected successful rate, then you will probably be disappointed in most "machine learning" publications.
Reference
[Sampson&Guttorp]Sampson, Paul D., and Peter Guttorp. "Nonparametric estimation of nonstationary spatial covariance structure." Journal of the American Statistical Association 87.417 (1992): 108-119.
[Perrin&Wendy]Perrin, Olivier, and Wendy Meiring. "Nonstationarity in Rn is second-order stationarity in R2n." Journal of applied probability (2003): 815-820.
[Levina&Bickel]Levina, Elizaveta, and Peter J. Bickel. "Maximum likelihood estimation of intrinsic dimension." Ann Arbor MI 48109 (2004): 1092.
|
Is there an accepted method to determine an approximate dimension for manifold learning
|
I am not quite sure if I understood your confusion correctly, if you accept the embedding principle (i.e. the "manifold assumption") the only way you can "decide" your dimension is to construct a proj
|
Is there an accepted method to determine an approximate dimension for manifold learning
I am not quite sure if I understood your confusion correctly, if you accept the embedding principle (i.e. the "manifold assumption") the only way you can "decide" your dimension is to construct a projector to low-dimensional manifold. [Levina&Bickel] pointed out that eigenvalue(spectral projector) and projection are two mainstream methods at their time.
The method you pointed out ("dimension expansion") is one way to construct projector (approximately). It is widely used in statistics and biostatistics (say [Sampson&Guttorp]) not only because of its performance but also due to its relatively easy idea and control of error rate for general observations. And not surprisingly, in most applications, favorite predictive algorithm will be a spline regression/thin-plate spline since its performance can be dominated by a Taylor-like term.
Since [Levina&Bickel] is published, it has never overcome this dimension expansion method in practice since MLE is based on conditionality evidence functional (due to Birnbaum's theorem) which most people will argue that it is not reasonable to use when the inference is on the design (the dimension of the observation is usually part of design of the experiment, not observation of the experiment).
I do not know what do you mean by unsatisfactory. If you think there is one way of figuring out the projector exactly(in closed form) for a general manifold(which is the case for most observations embedded in an infinite-dimensional space), that is an unsolved mathematical problem. If you mean the result does not come out in expected successful rate, then you will probably be disappointed in most "machine learning" publications.
Reference
[Sampson&Guttorp]Sampson, Paul D., and Peter Guttorp. "Nonparametric estimation of nonstationary spatial covariance structure." Journal of the American Statistical Association 87.417 (1992): 108-119.
[Perrin&Wendy]Perrin, Olivier, and Wendy Meiring. "Nonstationarity in Rn is second-order stationarity in R2n." Journal of applied probability (2003): 815-820.
[Levina&Bickel]Levina, Elizaveta, and Peter J. Bickel. "Maximum likelihood estimation of intrinsic dimension." Ann Arbor MI 48109 (2004): 1092.
|
Is there an accepted method to determine an approximate dimension for manifold learning
I am not quite sure if I understood your confusion correctly, if you accept the embedding principle (i.e. the "manifold assumption") the only way you can "decide" your dimension is to construct a proj
|
42,727
|
Semi-Hidden Markov Model with parameters of the emission probabilities depending on regressors
|
Here is some quick R code to get you started. Major caveats: I wrote this myself, so it could be buggy, statistically incorrect, poorly styled... use at your own risk!
params_are_valid <- function(params) {
stopifnot("lambdas" %in% names(params)) # Poisson parameters for each hidden state
stopifnot(all(params$lambas >= 0.0))
stopifnot(length(params$lambdas) == params$n_hidden_states)
stopifnot("mu" %in% names(params)) # Initial distribution over hidden states
stopifnot(length(params$mu) == params$n_hidden_states)
stopifnot(isTRUE(all.equal(sum(params$mu), 1.0))) # Probabilities sum to 1
stopifnot(all(params$mu >= 0.0))
stopifnot("P" %in% names(params)) # Transition probabilities for hidden state
stopifnot(nrow(params$P) == params$n_hidden_states && ncol(params$P) == params$n_hidden_states)
stopifnot(isTRUE(all.equal(rowSums(params$P), rep(1, params$n_hidden_states)))) # Probabilities sum to 1
stopifnot(all(params$P >= 0))
return(TRUE)
}
baum_welch_poisson <- function(observed_y, params) {
## Baum-Welch algorithm for HMM with discrete hidden x
## Discrete observations y (NAs allowed) with y|x ~ Poisson(params$lambdas[x])
## Written following Ramon van Handel's HMM notes, page 40, algorithm 3.2
## https://www.princeton.edu/~rvan/orf557/hmm080728.pdf
## Careful, his observation index is in {0, 1, ... , n} while I use {1, 2, ... , length(observed_y)}
y_length <- length(observed_y)
stopifnot(y_length > 1)
stopifnot(all(observed_y >= 0 | is.na(observed_y)))
stopifnot(all(observed_y %% 1 == 0 | is.na(observed_y))) # Integer observations
stopifnot(params_are_valid(params))
c <- vector("numeric", y_length)
if(is.na(observed_y[1])) {
upsilon <- rep(1, params$n_hidden_states)
} else {
upsilon <- dpois(observed_y[1], lambda=params$lambdas)
}
stopifnot(length(upsilon) == params$n_hidden_states)
c[1] <- sum(upsilon * params$mu)
## Matrix pi_contemporaneous gives probabilities over x_k conditional on {y_1, y_2, ... , y_k}
## Notation in van Handel's HMM notes is pi_k, whereas pi_{k|n} conditions on full history of y
pi_contemporaneous <- matrix(NA, params$n_hidden_states, y_length)
pi_contemporaneous[, 1] <- upsilon * params$mu / c[1]
upsilon_list <- list()
upsilon_list[[1]] <- upsilon
for(k in seq(2, y_length)) {
## Forward loop
if(is.na(observed_y[k])) {
upsilon <- rep(1, params$n_hidden_states)
} else {
upsilon <- dpois(observed_y[k], lambda=params$lambdas)
}
upsilon_list[[k]] <- upsilon # Cache for backward loop
pi_tilde <- upsilon * t(params$P) %*% pi_contemporaneous[, k-1]
c[k] <- sum(pi_tilde)
pi_contemporaneous[, k] <- pi_tilde / c[k]
}
beta <- matrix(NA, params$n_hidden_states, y_length)
beta[, y_length] <- 1 / c[y_length]
## Matrix pi gives probabilities over x conditional on full history of y
## Notation in van Handel's HMM notes is pi_{k|n}, as opposed to pi_k
pi <- matrix(NA, params$n_hidden_states, y_length)
pi[, y_length] <- pi_contemporaneous[, y_length]
pi_transition_list <- list() # List of posterior probabilities over hidden x transitions
for(k in seq(1, y_length - 1)) {
## Backward loop
upsilon <- diag(upsilon_list[[y_length - k + 1]], params$n_hidden_states, params$n_hidden_states)
pi_matrix <- diag(pi_contemporaneous[, y_length - k],
params$n_hidden_states, params$n_hidden_states)
beta_matrix <- diag(beta[, y_length - k + 1], params$n_hidden_states, params$n_hidden_states)
beta[, y_length - k] <- params$P %*% upsilon %*% beta[, y_length - k + 1] / c[y_length - k]
pi_transition_list[[y_length - k]] <- pi_matrix %*% params$P %*% upsilon %*% beta_matrix
stopifnot(isTRUE(all.equal(sum(pi_transition_list[[y_length - k]]), 1.0)))
pi[, y_length - k] <- rowSums(pi_transition_list[[y_length - k]])
}
loglik <- sum(log(c))
return(list(loglik=loglik, pi=pi, pi_transition_list=pi_transition_list))
}
## Notice that params0$lambas is zero for first hidden state, i.e. first hidden state represents a stockout
params0 <- list("n_hidden_states"=2,
"mu"=c(0.10, 0.90), # Initial distribution over hidden states
"P"=rbind(c(0.50, 0.50),
c(0.10, 0.90)), # Transition probabilities for hidden state
"lambdas"=c(0, 2)) # Observe y|x ~ Poisson(lambdas[x])
observations <- c(1, 2, 3, NA, NA, 0, 0, 0, 5, 5, 0, 5, 6, 7, NA, 5, 8, 9, 0, 6)
bw_list <- baum_welch_poisson(observations, params0)
round(bw_list$pi, 3) # Posterior probabilities over hidden states given observations (first row is stockout state)
bw_list$pi[, which(observations != 0)] # Sanity check: we're certain we're in hidden state 2 whenever observations > 0
bw_list$pi[, which(observations == 0 |
is.na(observations))] # When observations are zero (or NA), we could be in either state
The code runs Baum-Welch on a simple two-state HMM with Poisson observations. In this case, I set the poisson rate (lambda) to be zero for the first hidden state (and positive for the second hidden state), which makes the first hidden state a "stockout" state as in your example.
The example does not actually fit parameters (estimate them from data) -- for that you would need to write e.g. an expectation-maximization (EM) function.
|
Semi-Hidden Markov Model with parameters of the emission probabilities depending on regressors
|
Here is some quick R code to get you started. Major caveats: I wrote this myself, so it could be buggy, statistically incorrect, poorly styled... use at your own risk!
params_are_valid <- function(p
|
Semi-Hidden Markov Model with parameters of the emission probabilities depending on regressors
Here is some quick R code to get you started. Major caveats: I wrote this myself, so it could be buggy, statistically incorrect, poorly styled... use at your own risk!
params_are_valid <- function(params) {
stopifnot("lambdas" %in% names(params)) # Poisson parameters for each hidden state
stopifnot(all(params$lambas >= 0.0))
stopifnot(length(params$lambdas) == params$n_hidden_states)
stopifnot("mu" %in% names(params)) # Initial distribution over hidden states
stopifnot(length(params$mu) == params$n_hidden_states)
stopifnot(isTRUE(all.equal(sum(params$mu), 1.0))) # Probabilities sum to 1
stopifnot(all(params$mu >= 0.0))
stopifnot("P" %in% names(params)) # Transition probabilities for hidden state
stopifnot(nrow(params$P) == params$n_hidden_states && ncol(params$P) == params$n_hidden_states)
stopifnot(isTRUE(all.equal(rowSums(params$P), rep(1, params$n_hidden_states)))) # Probabilities sum to 1
stopifnot(all(params$P >= 0))
return(TRUE)
}
baum_welch_poisson <- function(observed_y, params) {
## Baum-Welch algorithm for HMM with discrete hidden x
## Discrete observations y (NAs allowed) with y|x ~ Poisson(params$lambdas[x])
## Written following Ramon van Handel's HMM notes, page 40, algorithm 3.2
## https://www.princeton.edu/~rvan/orf557/hmm080728.pdf
## Careful, his observation index is in {0, 1, ... , n} while I use {1, 2, ... , length(observed_y)}
y_length <- length(observed_y)
stopifnot(y_length > 1)
stopifnot(all(observed_y >= 0 | is.na(observed_y)))
stopifnot(all(observed_y %% 1 == 0 | is.na(observed_y))) # Integer observations
stopifnot(params_are_valid(params))
c <- vector("numeric", y_length)
if(is.na(observed_y[1])) {
upsilon <- rep(1, params$n_hidden_states)
} else {
upsilon <- dpois(observed_y[1], lambda=params$lambdas)
}
stopifnot(length(upsilon) == params$n_hidden_states)
c[1] <- sum(upsilon * params$mu)
## Matrix pi_contemporaneous gives probabilities over x_k conditional on {y_1, y_2, ... , y_k}
## Notation in van Handel's HMM notes is pi_k, whereas pi_{k|n} conditions on full history of y
pi_contemporaneous <- matrix(NA, params$n_hidden_states, y_length)
pi_contemporaneous[, 1] <- upsilon * params$mu / c[1]
upsilon_list <- list()
upsilon_list[[1]] <- upsilon
for(k in seq(2, y_length)) {
## Forward loop
if(is.na(observed_y[k])) {
upsilon <- rep(1, params$n_hidden_states)
} else {
upsilon <- dpois(observed_y[k], lambda=params$lambdas)
}
upsilon_list[[k]] <- upsilon # Cache for backward loop
pi_tilde <- upsilon * t(params$P) %*% pi_contemporaneous[, k-1]
c[k] <- sum(pi_tilde)
pi_contemporaneous[, k] <- pi_tilde / c[k]
}
beta <- matrix(NA, params$n_hidden_states, y_length)
beta[, y_length] <- 1 / c[y_length]
## Matrix pi gives probabilities over x conditional on full history of y
## Notation in van Handel's HMM notes is pi_{k|n}, as opposed to pi_k
pi <- matrix(NA, params$n_hidden_states, y_length)
pi[, y_length] <- pi_contemporaneous[, y_length]
pi_transition_list <- list() # List of posterior probabilities over hidden x transitions
for(k in seq(1, y_length - 1)) {
## Backward loop
upsilon <- diag(upsilon_list[[y_length - k + 1]], params$n_hidden_states, params$n_hidden_states)
pi_matrix <- diag(pi_contemporaneous[, y_length - k],
params$n_hidden_states, params$n_hidden_states)
beta_matrix <- diag(beta[, y_length - k + 1], params$n_hidden_states, params$n_hidden_states)
beta[, y_length - k] <- params$P %*% upsilon %*% beta[, y_length - k + 1] / c[y_length - k]
pi_transition_list[[y_length - k]] <- pi_matrix %*% params$P %*% upsilon %*% beta_matrix
stopifnot(isTRUE(all.equal(sum(pi_transition_list[[y_length - k]]), 1.0)))
pi[, y_length - k] <- rowSums(pi_transition_list[[y_length - k]])
}
loglik <- sum(log(c))
return(list(loglik=loglik, pi=pi, pi_transition_list=pi_transition_list))
}
## Notice that params0$lambas is zero for first hidden state, i.e. first hidden state represents a stockout
params0 <- list("n_hidden_states"=2,
"mu"=c(0.10, 0.90), # Initial distribution over hidden states
"P"=rbind(c(0.50, 0.50),
c(0.10, 0.90)), # Transition probabilities for hidden state
"lambdas"=c(0, 2)) # Observe y|x ~ Poisson(lambdas[x])
observations <- c(1, 2, 3, NA, NA, 0, 0, 0, 5, 5, 0, 5, 6, 7, NA, 5, 8, 9, 0, 6)
bw_list <- baum_welch_poisson(observations, params0)
round(bw_list$pi, 3) # Posterior probabilities over hidden states given observations (first row is stockout state)
bw_list$pi[, which(observations != 0)] # Sanity check: we're certain we're in hidden state 2 whenever observations > 0
bw_list$pi[, which(observations == 0 |
is.na(observations))] # When observations are zero (or NA), we could be in either state
The code runs Baum-Welch on a simple two-state HMM with Poisson observations. In this case, I set the poisson rate (lambda) to be zero for the first hidden state (and positive for the second hidden state), which makes the first hidden state a "stockout" state as in your example.
The example does not actually fit parameters (estimate them from data) -- for that you would need to write e.g. an expectation-maximization (EM) function.
|
Semi-Hidden Markov Model with parameters of the emission probabilities depending on regressors
Here is some quick R code to get you started. Major caveats: I wrote this myself, so it could be buggy, statistically incorrect, poorly styled... use at your own risk!
params_are_valid <- function(p
|
42,728
|
Why do we have to use action-value function in model-free reinforcement learning instead of just state-value function?
|
This is only true when using temporal difference learning alone, i.e. Q-learning. In that setting you are learning the optimal state-action-value function Q* and then taking actions that maximize Q*. If instead, you learned V*, you know the real value of the state that you are in if you followed an optimal policy but that doesn't help you make a decision which action to choose (because V is not a function of a). If you knew the model, you could see what reward you would get for each action and what state you would end up in, thus effectively calculating Q* from V*.
|
Why do we have to use action-value function in model-free reinforcement learning instead of just sta
|
This is only true when using temporal difference learning alone, i.e. Q-learning. In that setting you are learning the optimal state-action-value function Q* and then taking actions that maximize Q*.
|
Why do we have to use action-value function in model-free reinforcement learning instead of just state-value function?
This is only true when using temporal difference learning alone, i.e. Q-learning. In that setting you are learning the optimal state-action-value function Q* and then taking actions that maximize Q*. If instead, you learned V*, you know the real value of the state that you are in if you followed an optimal policy but that doesn't help you make a decision which action to choose (because V is not a function of a). If you knew the model, you could see what reward you would get for each action and what state you would end up in, thus effectively calculating Q* from V*.
|
Why do we have to use action-value function in model-free reinforcement learning instead of just sta
This is only true when using temporal difference learning alone, i.e. Q-learning. In that setting you are learning the optimal state-action-value function Q* and then taking actions that maximize Q*.
|
42,729
|
Minumum Sample Size for Permutation Test
|
You partially answered your own question. Consider the reason you're often performing a permutation test. It's usually in circumstances where you have little faith in any particular parametric distribution or for some other reason want a non-parametric solution. In that case, how does one estimate power? You could be doing the permutation test in situations where the populations have multimodal distributions, uniform distributions, any combination for your conditions that don't match, etc. All of those might have different power functions.
Keep in mind that the way power is estimated requires an assumption of some world where you know effect size and distribution of the effect. Since you have no notion of the latter you can't estimate power a priori. The best you could do is estimate power for some particular distribution you might think is close, subset of likely distributions, or taking your data as the population. But the latter leaves you know way to get to power other than post hoc.
|
Minumum Sample Size for Permutation Test
|
You partially answered your own question. Consider the reason you're often performing a permutation test. It's usually in circumstances where you have little faith in any particular parametric distrib
|
Minumum Sample Size for Permutation Test
You partially answered your own question. Consider the reason you're often performing a permutation test. It's usually in circumstances where you have little faith in any particular parametric distribution or for some other reason want a non-parametric solution. In that case, how does one estimate power? You could be doing the permutation test in situations where the populations have multimodal distributions, uniform distributions, any combination for your conditions that don't match, etc. All of those might have different power functions.
Keep in mind that the way power is estimated requires an assumption of some world where you know effect size and distribution of the effect. Since you have no notion of the latter you can't estimate power a priori. The best you could do is estimate power for some particular distribution you might think is close, subset of likely distributions, or taking your data as the population. But the latter leaves you know way to get to power other than post hoc.
|
Minumum Sample Size for Permutation Test
You partially answered your own question. Consider the reason you're often performing a permutation test. It's usually in circumstances where you have little faith in any particular parametric distrib
|
42,730
|
Minumum Sample Size for Permutation Test
|
I would wager permutation tests inflate the false negative rate in a small sample. Here's an extreme example to illustrate, but this applies with less extreme examples too:
r=1 with sample size 4
there are 4! = 24 permutations
Therefore: at least 1/24 ( = .042) permutations will have r=1 so p(r=1) >= 0.42. This is far greater than the real p-value of r=1, which is practically 0. The worst part is, with a p-threshold of .01, this result is not significant. Which is crazy; r=1 is the most significant possible.
This is because when you shuffle among existing values, you are not getting a true null distribution. The existing values are shuffled in order but not value. The values themselves are quantized. The values contributed to significance. This can, and will, bias the "null" shuffled distribution to something more significant. This holds for r-values less extreme than 1, and should be true for models other than correlation.
|
Minumum Sample Size for Permutation Test
|
I would wager permutation tests inflate the false negative rate in a small sample. Here's an extreme example to illustrate, but this applies with less extreme examples too:
r=1 with sample size 4
the
|
Minumum Sample Size for Permutation Test
I would wager permutation tests inflate the false negative rate in a small sample. Here's an extreme example to illustrate, but this applies with less extreme examples too:
r=1 with sample size 4
there are 4! = 24 permutations
Therefore: at least 1/24 ( = .042) permutations will have r=1 so p(r=1) >= 0.42. This is far greater than the real p-value of r=1, which is practically 0. The worst part is, with a p-threshold of .01, this result is not significant. Which is crazy; r=1 is the most significant possible.
This is because when you shuffle among existing values, you are not getting a true null distribution. The existing values are shuffled in order but not value. The values themselves are quantized. The values contributed to significance. This can, and will, bias the "null" shuffled distribution to something more significant. This holds for r-values less extreme than 1, and should be true for models other than correlation.
|
Minumum Sample Size for Permutation Test
I would wager permutation tests inflate the false negative rate in a small sample. Here's an extreme example to illustrate, but this applies with less extreme examples too:
r=1 with sample size 4
the
|
42,731
|
Robust time-series regression for outlier detection
|
I took your 90 days of data (24 hourly readings per day) and analyzed it using AUTOBOX a piece of software that I have helped develop using a 28 day forecast horizon. The documentation for the approach can be found in the User Guide available from the AFS website. I will try and give you you a general overview here. The data is analyzed in a parent-to-child approach where a model is initially developed for the daily totals and here incorporating memory,daily effects and anomalies, level shifts , local time trends etc.. This "parent model" leads to forecasts and confidence limits based upon possible different daily error variances which also differed by hour ( and the potential for anomalies to arise in the future using simulation procedures. The next step is to identify 24 causal models using the parent as a possible predictor using memory as needed , level shifts as needed while identifying and remedying possible anomalies/level shifts/local time trends. As an example of this let me show you the graphical output for hour 0,6,9,15,and 18 . As an example consider the model for hour 4 . GROUPT, the daily total series is significant along with three days of the week (2,3,and 4). Additionally 5 unusual values (outliers) were found at periods 89,55,19,78 and 2. There is a level shift (permanent change upwards in the mean value) at period 20 and a partial daily effect (day 3) starting at period 19 . Now we have 24 sets of forecasts for the children for the next 28 days and a set of forecasts for the parent for the next 28 days. We reconcile these two to obtain the final forecasts for 24 hours for the 28 day forecast. The reconciliation can be done in a parent-to-child or a child-to-parent manner. Following are snapshots of both procedures. . Clearly 90 days of data insufficient to capture , weekly effects, holiday effects , specific days of the month effects , long-weekend effects , week-in-month effects, monthly effects etc.. but if you had a longer series you can get the picture as to what might be possible. The detailed output can be made available to you or any interested party by contacting me as it is to voluminous to post. With this analysis one might want to creatively program the approach with free R tools but there are a lot of pitfalls awaiting such enterprise. Hope this helps your research into what I think is a very important statistical problem regarding detecting exceptional events and accounting for their effect in the forecast horizon.
|
Robust time-series regression for outlier detection
|
I took your 90 days of data (24 hourly readings per day) and analyzed it using AUTOBOX a piece of software that I have helped develop using a 28 day forecast horizon. The documentation for the approac
|
Robust time-series regression for outlier detection
I took your 90 days of data (24 hourly readings per day) and analyzed it using AUTOBOX a piece of software that I have helped develop using a 28 day forecast horizon. The documentation for the approach can be found in the User Guide available from the AFS website. I will try and give you you a general overview here. The data is analyzed in a parent-to-child approach where a model is initially developed for the daily totals and here incorporating memory,daily effects and anomalies, level shifts , local time trends etc.. This "parent model" leads to forecasts and confidence limits based upon possible different daily error variances which also differed by hour ( and the potential for anomalies to arise in the future using simulation procedures. The next step is to identify 24 causal models using the parent as a possible predictor using memory as needed , level shifts as needed while identifying and remedying possible anomalies/level shifts/local time trends. As an example of this let me show you the graphical output for hour 0,6,9,15,and 18 . As an example consider the model for hour 4 . GROUPT, the daily total series is significant along with three days of the week (2,3,and 4). Additionally 5 unusual values (outliers) were found at periods 89,55,19,78 and 2. There is a level shift (permanent change upwards in the mean value) at period 20 and a partial daily effect (day 3) starting at period 19 . Now we have 24 sets of forecasts for the children for the next 28 days and a set of forecasts for the parent for the next 28 days. We reconcile these two to obtain the final forecasts for 24 hours for the 28 day forecast. The reconciliation can be done in a parent-to-child or a child-to-parent manner. Following are snapshots of both procedures. . Clearly 90 days of data insufficient to capture , weekly effects, holiday effects , specific days of the month effects , long-weekend effects , week-in-month effects, monthly effects etc.. but if you had a longer series you can get the picture as to what might be possible. The detailed output can be made available to you or any interested party by contacting me as it is to voluminous to post. With this analysis one might want to creatively program the approach with free R tools but there are a lot of pitfalls awaiting such enterprise. Hope this helps your research into what I think is a very important statistical problem regarding detecting exceptional events and accounting for their effect in the forecast horizon.
|
Robust time-series regression for outlier detection
I took your 90 days of data (24 hourly readings per day) and analyzed it using AUTOBOX a piece of software that I have helped develop using a 28 day forecast horizon. The documentation for the approac
|
42,732
|
Neural network language model - prediction for the word at the center or the right of context words
|
The task of finding missing words in a text sometimes referred to as text imputation, or sentence completion.
One paper exploring it with ANN: Solving Text Imputation Using Recurrent Neural Networks. Arathi Mani. CS224D report. 2016. http://cs224d.stanford.edu/reports/ManiArathi.pdf
In this paper, we have shown that the bidirectional RNN yields the best Levenshetein and perplexity
scores out of the three models tested for our missing data problem where we try to impute a single
word into a sentence that is missing exactly one word from an unknown location.
One paper comparing several approaches including RNN:
Zweig, Geoffrey, John C. Platt, Christopher Meek, Christopher JC Burges, Ainur Yessenalina, and Qiang Liu. "Computational approaches to sentence completion." In Proceedings of the 50th Annual Meeting of the Association for Computational Linguistics: Long Papers-Volume 1, pp. 601-610. Association for Computational Linguistics, 2012. https://scholar.google.com/scholar?cluster=4615153328130310080&hl=en&as_sdt=0,22 ; http://www.aclweb.org/anthology/P/P12/P12-1063.pdf
This paper studies the problem of sentencelevel
semantic coherence by answering SAT-style
sentence completion questions
|
Neural network language model - prediction for the word at the center or the right of context words
|
The task of finding missing words in a text sometimes referred to as text imputation, or sentence completion.
One paper exploring it with ANN: Solving Text Imputation Using Recurrent Neural Networks.
|
Neural network language model - prediction for the word at the center or the right of context words
The task of finding missing words in a text sometimes referred to as text imputation, or sentence completion.
One paper exploring it with ANN: Solving Text Imputation Using Recurrent Neural Networks. Arathi Mani. CS224D report. 2016. http://cs224d.stanford.edu/reports/ManiArathi.pdf
In this paper, we have shown that the bidirectional RNN yields the best Levenshetein and perplexity
scores out of the three models tested for our missing data problem where we try to impute a single
word into a sentence that is missing exactly one word from an unknown location.
One paper comparing several approaches including RNN:
Zweig, Geoffrey, John C. Platt, Christopher Meek, Christopher JC Burges, Ainur Yessenalina, and Qiang Liu. "Computational approaches to sentence completion." In Proceedings of the 50th Annual Meeting of the Association for Computational Linguistics: Long Papers-Volume 1, pp. 601-610. Association for Computational Linguistics, 2012. https://scholar.google.com/scholar?cluster=4615153328130310080&hl=en&as_sdt=0,22 ; http://www.aclweb.org/anthology/P/P12/P12-1063.pdf
This paper studies the problem of sentencelevel
semantic coherence by answering SAT-style
sentence completion questions
|
Neural network language model - prediction for the word at the center or the right of context words
The task of finding missing words in a text sometimes referred to as text imputation, or sentence completion.
One paper exploring it with ANN: Solving Text Imputation Using Recurrent Neural Networks.
|
42,733
|
Neural network language model - prediction for the word at the center or the right of context words
|
What you are describing is Tomas Mikolov's Word2vec model Word2vec. His implementation has 2 parts the Skip-gram model and the CBOW model. Paper here
CBOW, which is what you need, is trained to predict the target word t from the contextual words that surround it, c, i.e. the goal is to maximise P(t | c) over the training set Quora nice explanation on his paper
|
Neural network language model - prediction for the word at the center or the right of context words
|
What you are describing is Tomas Mikolov's Word2vec model Word2vec. His implementation has 2 parts the Skip-gram model and the CBOW model. Paper here
CBOW, which is what you need, is trained to predic
|
Neural network language model - prediction for the word at the center or the right of context words
What you are describing is Tomas Mikolov's Word2vec model Word2vec. His implementation has 2 parts the Skip-gram model and the CBOW model. Paper here
CBOW, which is what you need, is trained to predict the target word t from the contextual words that surround it, c, i.e. the goal is to maximise P(t | c) over the training set Quora nice explanation on his paper
|
Neural network language model - prediction for the word at the center or the right of context words
What you are describing is Tomas Mikolov's Word2vec model Word2vec. His implementation has 2 parts the Skip-gram model and the CBOW model. Paper here
CBOW, which is what you need, is trained to predic
|
42,734
|
How to approximate (log-)likelihood from model specification using particle filters
|
You can think of these different particle filters as different pieces of measurement equipment (like scales or rulers). When we're outside of pure geometry, it's difficult to know exactly how big an object is, and we might get slightly different answers if we measure it a few times with different equipment. Similarly, when we don't have the closed form of the likelihood, we might get different answers depending on exactly how we measure.
When the full likelihood is difficult to compute exactly, particle filters can give an approximate likelihood by walking through the steps of your simulated process and estimating the likelihood associated with each step. Then you can get the full likelihood by multiplying the steps together (or adding up the log-likelihoods), as they suggest just after "step 3" of their description in section 3.5.2.
These are Monte Carlo estimates, so there will be some sampling error (e.g. the jaggedness in the red lines of your figure), but they should asymptotically converge to the true value as the number of particles increases.
The authors were concerned about how well this algorithm will perform when the number of samples is small/finite, so they give it a tweak that makes it less noisy. This tweak changes the estimates of the likelihood (hopefully by bringing them closer to the true value). If we think of the particle filter as a scale that weighs objects, their robust version is like a scale that tries to minimize random noise (e.g. from air currents occasionally pushing down on the scale), but which might introduce other artifacts.
|
How to approximate (log-)likelihood from model specification using particle filters
|
You can think of these different particle filters as different pieces of measurement equipment (like scales or rulers). When we're outside of pure geometry, it's difficult to know exactly how big an
|
How to approximate (log-)likelihood from model specification using particle filters
You can think of these different particle filters as different pieces of measurement equipment (like scales or rulers). When we're outside of pure geometry, it's difficult to know exactly how big an object is, and we might get slightly different answers if we measure it a few times with different equipment. Similarly, when we don't have the closed form of the likelihood, we might get different answers depending on exactly how we measure.
When the full likelihood is difficult to compute exactly, particle filters can give an approximate likelihood by walking through the steps of your simulated process and estimating the likelihood associated with each step. Then you can get the full likelihood by multiplying the steps together (or adding up the log-likelihoods), as they suggest just after "step 3" of their description in section 3.5.2.
These are Monte Carlo estimates, so there will be some sampling error (e.g. the jaggedness in the red lines of your figure), but they should asymptotically converge to the true value as the number of particles increases.
The authors were concerned about how well this algorithm will perform when the number of samples is small/finite, so they give it a tweak that makes it less noisy. This tweak changes the estimates of the likelihood (hopefully by bringing them closer to the true value). If we think of the particle filter as a scale that weighs objects, their robust version is like a scale that tries to minimize random noise (e.g. from air currents occasionally pushing down on the scale), but which might introduce other artifacts.
|
How to approximate (log-)likelihood from model specification using particle filters
You can think of these different particle filters as different pieces of measurement equipment (like scales or rulers). When we're outside of pure geometry, it's difficult to know exactly how big an
|
42,735
|
How to approximate (log-)likelihood from model specification using particle filters
|
Differing from your model, I can give you some ideas based on my experience. Let's say you have a state space model:
$y_t = ax_t + \alpha_t$
$x_{t+1} = bx_t + e_t, \quad e_t \sim N(0, 1)$
A regular assumption on a state space model is that $\alpha_t$ is also a random variable from Gaussian distribution, e.g., $N(0, 2)$. We can use the maximum likelihood method to estimate parameters $a$ and $b$ under a Gaussian distributed on $\alpha_t$. However, if we consider $\alpha_t$ is a random number from an $\alpha$ stable distribution, then the pdf is not analytically expressible.
A possible way to handle this kind of problem is to use Approximate Bayesian Computation (ABC) method. Please read the following link to learn this method if you like.
https://en.wikipedia.org/wiki/Approximate_Bayesian_computation
|
How to approximate (log-)likelihood from model specification using particle filters
|
Differing from your model, I can give you some ideas based on my experience. Let's say you have a state space model:
$y_t = ax_t + \alpha_t$
$x_{t+1} = bx_t + e_t, \quad e_t \sim N(0, 1)$
A regular as
|
How to approximate (log-)likelihood from model specification using particle filters
Differing from your model, I can give you some ideas based on my experience. Let's say you have a state space model:
$y_t = ax_t + \alpha_t$
$x_{t+1} = bx_t + e_t, \quad e_t \sim N(0, 1)$
A regular assumption on a state space model is that $\alpha_t$ is also a random variable from Gaussian distribution, e.g., $N(0, 2)$. We can use the maximum likelihood method to estimate parameters $a$ and $b$ under a Gaussian distributed on $\alpha_t$. However, if we consider $\alpha_t$ is a random number from an $\alpha$ stable distribution, then the pdf is not analytically expressible.
A possible way to handle this kind of problem is to use Approximate Bayesian Computation (ABC) method. Please read the following link to learn this method if you like.
https://en.wikipedia.org/wiki/Approximate_Bayesian_computation
|
How to approximate (log-)likelihood from model specification using particle filters
Differing from your model, I can give you some ideas based on my experience. Let's say you have a state space model:
$y_t = ax_t + \alpha_t$
$x_{t+1} = bx_t + e_t, \quad e_t \sim N(0, 1)$
A regular as
|
42,736
|
Using empirical Bayesian estimation (Gamma-Poisson) to analyze high arrival counts (n ~= 5000)
|
As a first observation, your z-scores are not going to give you what you want. A large z-score tells you that the new arrival count is anomalously large, not that the arrival curve is accelerating.
Secondly, I would strongly advise you start with a simpler approach. There are a few possibilities for this 'simpler approach', but here's the one I'd recommend:
Smooth your arrival curve using EWMA with some small half-life, then take the diff. This smoothed-diff is a one-sided way to approximate the derivative at some timescale.
Smooth-diff again to get the second derivative.
Rank the second derivative values cross-sectionally.
Simple approaches like these are great because they take a few minutes to implement and they get you 70% of the performance of a more complex model. You might not end up using it in production, but a) it gives you something to fall back on if all else fails and b) it allows you to build out the rest of your data-processing pipeline.
|
Using empirical Bayesian estimation (Gamma-Poisson) to analyze high arrival counts (n ~= 5000)
|
As a first observation, your z-scores are not going to give you what you want. A large z-score tells you that the new arrival count is anomalously large, not that the arrival curve is accelerating.
Se
|
Using empirical Bayesian estimation (Gamma-Poisson) to analyze high arrival counts (n ~= 5000)
As a first observation, your z-scores are not going to give you what you want. A large z-score tells you that the new arrival count is anomalously large, not that the arrival curve is accelerating.
Secondly, I would strongly advise you start with a simpler approach. There are a few possibilities for this 'simpler approach', but here's the one I'd recommend:
Smooth your arrival curve using EWMA with some small half-life, then take the diff. This smoothed-diff is a one-sided way to approximate the derivative at some timescale.
Smooth-diff again to get the second derivative.
Rank the second derivative values cross-sectionally.
Simple approaches like these are great because they take a few minutes to implement and they get you 70% of the performance of a more complex model. You might not end up using it in production, but a) it gives you something to fall back on if all else fails and b) it allows you to build out the rest of your data-processing pipeline.
|
Using empirical Bayesian estimation (Gamma-Poisson) to analyze high arrival counts (n ~= 5000)
As a first observation, your z-scores are not going to give you what you want. A large z-score tells you that the new arrival count is anomalously large, not that the arrival curve is accelerating.
Se
|
42,737
|
Expected root of quadratic random polynomial
|
Your $Z_1$ and $Z_2$ are not well defined until you have made a choice of which complex root to take. That choice could affect their distributions. (It actually does not, by virtue of the symmetries of $A$, $B$, and $C$ around $0$.)
Regardless, since $Z_1+Z_2=-B/A$ is well-defined, suppose you have made such a choice and that the $Z_i$ have finite expectations. From the independence of $A$ and $B$ and the fact that the density of $A$ does not approach zero near $A=0$, it follows from I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that? that $-B/A$ has no expectation. But since $E[-B/A]=E[Z_1+Z_2]$, that creates a contradiction demonstrating at least one of $Z_1$ and $Z_2$ cannot have an expectation.
You can also argue from the symmetry of this problem that the expectation of $\sqrt{B^2-4AC}/(2A)$, if it exists, must be zero. (The distribution of $(A,B,C)$ and the distribution of $(-A,B,-C)$ are the same, but the corresponding distributions of $\sqrt{B^2-4AC}/(2A)$ are negatives of each other. Ergo, their expectations must be negatives of each other, too.) Therefore the expectation of each $Z_i$ is just $E[-B/(2A)]$. This has a simpler expression as an integral:
$$E[-B/2A] = \frac{1}{4}\int_{-1}^1 \int_{-1}^1 -\frac{b}{2a} da db$$
We might try to evaluate it as an iterated integral (according to Fubini's Theorem). However, the inner integral (with respect to $a$) diverges at $0$:
$$\lim_{t\to 0^{+}} \int_t^1 \frac{-da}{a} = \lim_{t\to 0^{+}}\log(t) \to -\infty$$
while
$$\lim_{t\to 0^{-}} \int_{-1}^t \frac{-da}{a} = \lim_{t\to 0^{-}}(-\log(-t)) \to \infty,$$
demonstrating it is undefined. That is why it is invalid to change the order of integration--Fubini's Theorem does not apply--to obtain $0$ for the integral over $b$ and thus get the (wrong) value of $0$ for the expectation.
In either analysis, the source of the difficulty is clear: $A$ has a non-negligible density in any neighborhood of zero.
|
Expected root of quadratic random polynomial
|
Your $Z_1$ and $Z_2$ are not well defined until you have made a choice of which complex root to take. That choice could affect their distributions. (It actually does not, by virtue of the symmetrie
|
Expected root of quadratic random polynomial
Your $Z_1$ and $Z_2$ are not well defined until you have made a choice of which complex root to take. That choice could affect their distributions. (It actually does not, by virtue of the symmetries of $A$, $B$, and $C$ around $0$.)
Regardless, since $Z_1+Z_2=-B/A$ is well-defined, suppose you have made such a choice and that the $Z_i$ have finite expectations. From the independence of $A$ and $B$ and the fact that the density of $A$ does not approach zero near $A=0$, it follows from I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that? that $-B/A$ has no expectation. But since $E[-B/A]=E[Z_1+Z_2]$, that creates a contradiction demonstrating at least one of $Z_1$ and $Z_2$ cannot have an expectation.
You can also argue from the symmetry of this problem that the expectation of $\sqrt{B^2-4AC}/(2A)$, if it exists, must be zero. (The distribution of $(A,B,C)$ and the distribution of $(-A,B,-C)$ are the same, but the corresponding distributions of $\sqrt{B^2-4AC}/(2A)$ are negatives of each other. Ergo, their expectations must be negatives of each other, too.) Therefore the expectation of each $Z_i$ is just $E[-B/(2A)]$. This has a simpler expression as an integral:
$$E[-B/2A] = \frac{1}{4}\int_{-1}^1 \int_{-1}^1 -\frac{b}{2a} da db$$
We might try to evaluate it as an iterated integral (according to Fubini's Theorem). However, the inner integral (with respect to $a$) diverges at $0$:
$$\lim_{t\to 0^{+}} \int_t^1 \frac{-da}{a} = \lim_{t\to 0^{+}}\log(t) \to -\infty$$
while
$$\lim_{t\to 0^{-}} \int_{-1}^t \frac{-da}{a} = \lim_{t\to 0^{-}}(-\log(-t)) \to \infty,$$
demonstrating it is undefined. That is why it is invalid to change the order of integration--Fubini's Theorem does not apply--to obtain $0$ for the integral over $b$ and thus get the (wrong) value of $0$ for the expectation.
In either analysis, the source of the difficulty is clear: $A$ has a non-negligible density in any neighborhood of zero.
|
Expected root of quadratic random polynomial
Your $Z_1$ and $Z_2$ are not well defined until you have made a choice of which complex root to take. That choice could affect their distributions. (It actually does not, by virtue of the symmetrie
|
42,738
|
What are periodic version of splines?
|
The Venables Ripley book discusses periodic splines. Basically, by specifying (correctly) the periodicity, the data are aggregated into replications over a period and splines are fit to interpolate the trend. For instance, using the AirPassengers dataset from R to model flight trends, I might use a categorical fixed effect for annual effects and a spline to interpolate the residual monthly trends. My spline interpolation is arguably a bad one, but finding a good fitting spline is another topic altogether :) This example is perhaps a bit more useful because it deals with averaging out other auto-regressive trends.
My from-scratch method fits the periodic spline with a discontinuity at the end-point, but one could easily address this by duplicating these data over two periods and fitting the spline to the central half.
matplot(matrix(log(AirPassengers), ncol=12), type='l', axes=F, ylab='log(Passengers)', xlab='Month')
axis(1, at=1:12, labels=month.abb)
axis(2)
box()
title('Monthly air passenger data 1949:1960')
ap <- data.frame('lflights'= log(c(AirPassengers)), month=month.abb, year=rep(1949:1960, each=12))
ap$month.n <- match(ap$month, month.abb)
ap$monthly.diff <- lm(lflights ~ factor(year), data=ap)$residuals
matplot(matrix(ap$monthly.diff, ncol=12), type='l', axes=F, ylab='log(Passengers)', xlab='Month')
axis(1, at=1:12, labels=month.abb)
axis(2)
box()
title('Monthly residuals for air passenger data 1949:1960')
library(splines)
ap$monthly.pred <- lm(monthly.diff~bs(month.n, degree=2, knots = c(5)), data=ap)$fitted
lines(1:12, ap$monthly.pred[1:12], lwd=2)
|
What are periodic version of splines?
|
The Venables Ripley book discusses periodic splines. Basically, by specifying (correctly) the periodicity, the data are aggregated into replications over a period and splines are fit to interpolate th
|
What are periodic version of splines?
The Venables Ripley book discusses periodic splines. Basically, by specifying (correctly) the periodicity, the data are aggregated into replications over a period and splines are fit to interpolate the trend. For instance, using the AirPassengers dataset from R to model flight trends, I might use a categorical fixed effect for annual effects and a spline to interpolate the residual monthly trends. My spline interpolation is arguably a bad one, but finding a good fitting spline is another topic altogether :) This example is perhaps a bit more useful because it deals with averaging out other auto-regressive trends.
My from-scratch method fits the periodic spline with a discontinuity at the end-point, but one could easily address this by duplicating these data over two periods and fitting the spline to the central half.
matplot(matrix(log(AirPassengers), ncol=12), type='l', axes=F, ylab='log(Passengers)', xlab='Month')
axis(1, at=1:12, labels=month.abb)
axis(2)
box()
title('Monthly air passenger data 1949:1960')
ap <- data.frame('lflights'= log(c(AirPassengers)), month=month.abb, year=rep(1949:1960, each=12))
ap$month.n <- match(ap$month, month.abb)
ap$monthly.diff <- lm(lflights ~ factor(year), data=ap)$residuals
matplot(matrix(ap$monthly.diff, ncol=12), type='l', axes=F, ylab='log(Passengers)', xlab='Month')
axis(1, at=1:12, labels=month.abb)
axis(2)
box()
title('Monthly residuals for air passenger data 1949:1960')
library(splines)
ap$monthly.pred <- lm(monthly.diff~bs(month.n, degree=2, knots = c(5)), data=ap)$fitted
lines(1:12, ap$monthly.pred[1:12], lwd=2)
|
What are periodic version of splines?
The Venables Ripley book discusses periodic splines. Basically, by specifying (correctly) the periodicity, the data are aggregated into replications over a period and splines are fit to interpolate th
|
42,739
|
Fractional output dimensions of "sliding-windows" (convolutions, pooling etc) in neural networks
|
The fraction part comes from the stride operation. Without stride, the output size should be output_no_stride = input + 2*pad - filter + 1 = 224. With stride, the conventional formula to use is output_with_stride = floor((input + 2*pad - filter) / stride) + 1 = 112.
In many programming languages, the default behavior of integer division is "round toward zero" so the floor operation can be omitted when the numerator and denominator are positive integers. (Ref: Caffe's convolution implementation, Cudnn docs)
Comparing the output dimension with and without stride
output_with_stride = floor((input + 2*pad - filter) / stride) + 1
= floor((output_no_stride - 1) / stride) + 1
= ceil(output_no_stride / stride)
Caffe's pooling is a bit complicated, it first replaces the floor with ceiling, then decreases the size by one if the last pooling does not start strictly inside the image, as shown in the code.
pooled_height_ = static_cast<int>(ceil(static_cast<float>(
height_ + 2 * pad_h_ - kernel_h_) / stride_h_)) + 1;
pooled_width_ = static_cast<int>(ceil(static_cast<float>(
width_ + 2 * pad_w_ - kernel_w_) / stride_w_)) + 1;
if (pad_h_ || pad_w_) {
// If we have padding, ensure that the last pooling starts strictly
// inside the image (instead of at the padding); otherwise clip the last.
if ((pooled_height_ - 1) * stride_h_ >= height_ + pad_h_) {
--pooled_height_;
}
if ((pooled_width_ - 1) * stride_w_ >= width_ + pad_w_) {
--pooled_width_;
}
CHECK_LT((pooled_height_ - 1) * stride_h_, height_ + pad_h_);
CHECK_LT((pooled_width_ - 1) * stride_w_, width_ + pad_w_);
}
I think the result is mostly aligned with the conventional formula except when the last pooling is entirely outside the original input.
|
Fractional output dimensions of "sliding-windows" (convolutions, pooling etc) in neural networks
|
The fraction part comes from the stride operation. Without stride, the output size should be output_no_stride = input + 2*pad - filter + 1 = 224. With stride, the conventional formula to use is output
|
Fractional output dimensions of "sliding-windows" (convolutions, pooling etc) in neural networks
The fraction part comes from the stride operation. Without stride, the output size should be output_no_stride = input + 2*pad - filter + 1 = 224. With stride, the conventional formula to use is output_with_stride = floor((input + 2*pad - filter) / stride) + 1 = 112.
In many programming languages, the default behavior of integer division is "round toward zero" so the floor operation can be omitted when the numerator and denominator are positive integers. (Ref: Caffe's convolution implementation, Cudnn docs)
Comparing the output dimension with and without stride
output_with_stride = floor((input + 2*pad - filter) / stride) + 1
= floor((output_no_stride - 1) / stride) + 1
= ceil(output_no_stride / stride)
Caffe's pooling is a bit complicated, it first replaces the floor with ceiling, then decreases the size by one if the last pooling does not start strictly inside the image, as shown in the code.
pooled_height_ = static_cast<int>(ceil(static_cast<float>(
height_ + 2 * pad_h_ - kernel_h_) / stride_h_)) + 1;
pooled_width_ = static_cast<int>(ceil(static_cast<float>(
width_ + 2 * pad_w_ - kernel_w_) / stride_w_)) + 1;
if (pad_h_ || pad_w_) {
// If we have padding, ensure that the last pooling starts strictly
// inside the image (instead of at the padding); otherwise clip the last.
if ((pooled_height_ - 1) * stride_h_ >= height_ + pad_h_) {
--pooled_height_;
}
if ((pooled_width_ - 1) * stride_w_ >= width_ + pad_w_) {
--pooled_width_;
}
CHECK_LT((pooled_height_ - 1) * stride_h_, height_ + pad_h_);
CHECK_LT((pooled_width_ - 1) * stride_w_, width_ + pad_w_);
}
I think the result is mostly aligned with the conventional formula except when the last pooling is entirely outside the original input.
|
Fractional output dimensions of "sliding-windows" (convolutions, pooling etc) in neural networks
The fraction part comes from the stride operation. Without stride, the output size should be output_no_stride = input + 2*pad - filter + 1 = 224. With stride, the conventional formula to use is output
|
42,740
|
Convergence Criteria for Stochastic Gradient Descent
|
I would suggest having some held-out data that forms a validation dataset. You can compute your loss function on the validation dataset periodically (it would probably be too expensive after each iteration, so after each epoch seems to make sense) and stop training once the validation loss has stabilized.
If you're in a purely online setting where you don't have any data ahead of time I suppose you could compute an average loss of the examples in each epoch, and wait for that average loss to converge, but of course that could lead to overfitting...
It looks like Vowpal Wabbit (an online learning system that implements SGD amongst other optimizers) uses a technique called Progressive Cross-Validation which is similar to using a holdout set, but allows you to use more data while training the model, see:
http://hunch.net/~jl/projects/prediction_bounds/progressive_validation/coltfinal.pdf
Vowpal Wabbit has an interesting approach, it computes error metrics after each example, but prints the diagnostics with an exponential backoff, so at first you get frequent updates (to help diagnose early problems), and then less frequent updates as time goes on.
Vowpal Wabbit displays two error metrics, the average progressive loss overall, and the average progressive loss since the last time the diagnostics were printed. You can read some details about the VW diagnostics below:
https://github.com/JohnLangford/vowpal_wabbit/wiki/Tutorial#vws-diagnostic-information
|
Convergence Criteria for Stochastic Gradient Descent
|
I would suggest having some held-out data that forms a validation dataset. You can compute your loss function on the validation dataset periodically (it would probably be too expensive after each iter
|
Convergence Criteria for Stochastic Gradient Descent
I would suggest having some held-out data that forms a validation dataset. You can compute your loss function on the validation dataset periodically (it would probably be too expensive after each iteration, so after each epoch seems to make sense) and stop training once the validation loss has stabilized.
If you're in a purely online setting where you don't have any data ahead of time I suppose you could compute an average loss of the examples in each epoch, and wait for that average loss to converge, but of course that could lead to overfitting...
It looks like Vowpal Wabbit (an online learning system that implements SGD amongst other optimizers) uses a technique called Progressive Cross-Validation which is similar to using a holdout set, but allows you to use more data while training the model, see:
http://hunch.net/~jl/projects/prediction_bounds/progressive_validation/coltfinal.pdf
Vowpal Wabbit has an interesting approach, it computes error metrics after each example, but prints the diagnostics with an exponential backoff, so at first you get frequent updates (to help diagnose early problems), and then less frequent updates as time goes on.
Vowpal Wabbit displays two error metrics, the average progressive loss overall, and the average progressive loss since the last time the diagnostics were printed. You can read some details about the VW diagnostics below:
https://github.com/JohnLangford/vowpal_wabbit/wiki/Tutorial#vws-diagnostic-information
|
Convergence Criteria for Stochastic Gradient Descent
I would suggest having some held-out data that forms a validation dataset. You can compute your loss function on the validation dataset periodically (it would probably be too expensive after each iter
|
42,741
|
Sample size needed for Gaussian process classification
|
Classification can need more points than regression, for a few reasons:
1) If there are only 2 classes, the response variable contains much less information than a continuous variable, which could take many values.
2) With a small number of points, it's especially easy to get complete separation, which makes the maximum likelihood estimate undefined.
With ~10 points, it would be really difficult to tell what's going on, even if your predictor variable is one-dimensional. This graph was generated randomly with 10 independent coin flips. Even though one could easily imagine adding a curve that wiggled up and down to fit the points better, doing so would be a mistake. For this reason, it probably doesn't make sense to even start thinking about nonlinear classifiers before you have a few dozen points.
At the very least, you'd want to heavily constrain the GP model to keep it from overfitting, and/or have a pre-determined kernel based on first principles. With so few points, the model-fitting process is likely to either blow up (if your constraints are too weak) or produce something that just matches your initial assumptions (if your constraints are too strong).
|
Sample size needed for Gaussian process classification
|
Classification can need more points than regression, for a few reasons:
1) If there are only 2 classes, the response variable contains much less information than a continuous variable, which could tak
|
Sample size needed for Gaussian process classification
Classification can need more points than regression, for a few reasons:
1) If there are only 2 classes, the response variable contains much less information than a continuous variable, which could take many values.
2) With a small number of points, it's especially easy to get complete separation, which makes the maximum likelihood estimate undefined.
With ~10 points, it would be really difficult to tell what's going on, even if your predictor variable is one-dimensional. This graph was generated randomly with 10 independent coin flips. Even though one could easily imagine adding a curve that wiggled up and down to fit the points better, doing so would be a mistake. For this reason, it probably doesn't make sense to even start thinking about nonlinear classifiers before you have a few dozen points.
At the very least, you'd want to heavily constrain the GP model to keep it from overfitting, and/or have a pre-determined kernel based on first principles. With so few points, the model-fitting process is likely to either blow up (if your constraints are too weak) or produce something that just matches your initial assumptions (if your constraints are too strong).
|
Sample size needed for Gaussian process classification
Classification can need more points than regression, for a few reasons:
1) If there are only 2 classes, the response variable contains much less information than a continuous variable, which could tak
|
42,742
|
Sample size needed for Gaussian process classification
|
that rule of thumb is wrong. GP is used in high dimensional settings with d >> n without any problems (genomics, mri) lets say 500 000 voxels in one image used to classify 100 subjects into 2 classes. I don't know if there is any theoretical bound, actual number would depend a lot on the nature of the data at hand, so how strong is the signal and what proportion of features are pure noise.
|
Sample size needed for Gaussian process classification
|
that rule of thumb is wrong. GP is used in high dimensional settings with d >> n without any problems (genomics, mri) lets say 500 000 voxels in one image used to classify 100 subjects into 2 classes.
|
Sample size needed for Gaussian process classification
that rule of thumb is wrong. GP is used in high dimensional settings with d >> n without any problems (genomics, mri) lets say 500 000 voxels in one image used to classify 100 subjects into 2 classes. I don't know if there is any theoretical bound, actual number would depend a lot on the nature of the data at hand, so how strong is the signal and what proportion of features are pure noise.
|
Sample size needed for Gaussian process classification
that rule of thumb is wrong. GP is used in high dimensional settings with d >> n without any problems (genomics, mri) lets say 500 000 voxels in one image used to classify 100 subjects into 2 classes.
|
42,743
|
How are calculations done for REML?
|
Here is a simple example with calculations that shows the idea. We work in the linear model $Y = X\beta + e, e\sim N(0, \Sigma(\theta))$, where $Y$ is the $N \times 1$ response vector, $X$ the $n\times p$ design matrix, and $\theta$ parametrizes the covariance matrix. Suppose interest lies in estimating $\theta$.
Assume $X$ has full column rank and let $A$ be an (any!) $n \times (n-p)$matrix with orthonormal columns such that $A'X = 0$, then Harville, 1974 showed that the likelihood for $A'Y$ is:
\begin{align}
RL(\theta; Y)=(2\pi)^{-(n-p)/2}\vert X'X\vert^{1/2}\vert X' \Sigma^{-1}X\vert^{-1/2}\vert \Sigma \vert^{-1/2}\exp\left(-\frac{1}{2}r'\Sigma^{-1}r \right),
\end{align}
where $r = QY:=\left(I - X(X'\Sigma^{-1}X)^{-1}X'\Sigma^{-1}\right)Y$. REML entails maximization of this likelihood over $\theta$ only, instead of maximizing the usual likelihood:
\begin{align}
L(\theta, \beta; Y) = (2\pi)^{-n/2}\vert \Sigma\vert^{-1/2}\exp\left(-\frac{1}{2}[Y - X\beta]'\Sigma^{-1}[Y-X\beta]\right),
\end{align}
which gives MLEs for $(\theta, \beta)$.
To get some easy calculations, suppose $X = 1_n$, a vector of ones, and $\Sigma = \sigma^2I$. The log-restricted likelihood, up to terms that does not depend on $\sigma^2$, is in this particular case:
\begin{align}
RL(\theta ; Y) &\propto \log\vert \sigma^{2} n\vert^{1/2}+\log\vert\sigma^2I\vert^{-1/2} -\frac{1}{2\sigma^2}SSE \\
&\propto -\frac{n-1}{2}\log(\sigma^2) -\frac{1}{2\sigma^2}SSE,
\end{align}
which is maximized at $\sigma^2 = SSE/(n-1)$. Note the following which was used to get the restricted log-likelihood:
When $\Sigma = \sigma^2I$, $Q = I - X(X'X)^{-1}X'$, which does not depend on $\sigma^2$.
When $X = 1_n$, $X'X = n$
$SSE = (Y - 1_n\bar{Y})'(Y - 1_n\bar{Y})$, since $Q = I - 1_n1_n'/n$.
It is conceptually easy to generalize to a general linear mean function $X\beta$ and general covariance matrix $\Sigma(\theta)$; $\hat{\theta} = \arg \max RL(\theta; Y)$. However, the actual computations will generally require a little more work.
|
How are calculations done for REML?
|
Here is a simple example with calculations that shows the idea. We work in the linear model $Y = X\beta + e, e\sim N(0, \Sigma(\theta))$, where $Y$ is the $N \times 1$ response vector, $X$ the $n\time
|
How are calculations done for REML?
Here is a simple example with calculations that shows the idea. We work in the linear model $Y = X\beta + e, e\sim N(0, \Sigma(\theta))$, where $Y$ is the $N \times 1$ response vector, $X$ the $n\times p$ design matrix, and $\theta$ parametrizes the covariance matrix. Suppose interest lies in estimating $\theta$.
Assume $X$ has full column rank and let $A$ be an (any!) $n \times (n-p)$matrix with orthonormal columns such that $A'X = 0$, then Harville, 1974 showed that the likelihood for $A'Y$ is:
\begin{align}
RL(\theta; Y)=(2\pi)^{-(n-p)/2}\vert X'X\vert^{1/2}\vert X' \Sigma^{-1}X\vert^{-1/2}\vert \Sigma \vert^{-1/2}\exp\left(-\frac{1}{2}r'\Sigma^{-1}r \right),
\end{align}
where $r = QY:=\left(I - X(X'\Sigma^{-1}X)^{-1}X'\Sigma^{-1}\right)Y$. REML entails maximization of this likelihood over $\theta$ only, instead of maximizing the usual likelihood:
\begin{align}
L(\theta, \beta; Y) = (2\pi)^{-n/2}\vert \Sigma\vert^{-1/2}\exp\left(-\frac{1}{2}[Y - X\beta]'\Sigma^{-1}[Y-X\beta]\right),
\end{align}
which gives MLEs for $(\theta, \beta)$.
To get some easy calculations, suppose $X = 1_n$, a vector of ones, and $\Sigma = \sigma^2I$. The log-restricted likelihood, up to terms that does not depend on $\sigma^2$, is in this particular case:
\begin{align}
RL(\theta ; Y) &\propto \log\vert \sigma^{2} n\vert^{1/2}+\log\vert\sigma^2I\vert^{-1/2} -\frac{1}{2\sigma^2}SSE \\
&\propto -\frac{n-1}{2}\log(\sigma^2) -\frac{1}{2\sigma^2}SSE,
\end{align}
which is maximized at $\sigma^2 = SSE/(n-1)$. Note the following which was used to get the restricted log-likelihood:
When $\Sigma = \sigma^2I$, $Q = I - X(X'X)^{-1}X'$, which does not depend on $\sigma^2$.
When $X = 1_n$, $X'X = n$
$SSE = (Y - 1_n\bar{Y})'(Y - 1_n\bar{Y})$, since $Q = I - 1_n1_n'/n$.
It is conceptually easy to generalize to a general linear mean function $X\beta$ and general covariance matrix $\Sigma(\theta)$; $\hat{\theta} = \arg \max RL(\theta; Y)$. However, the actual computations will generally require a little more work.
|
How are calculations done for REML?
Here is a simple example with calculations that shows the idea. We work in the linear model $Y = X\beta + e, e\sim N(0, \Sigma(\theta))$, where $Y$ is the $N \times 1$ response vector, $X$ the $n\time
|
42,744
|
Deviance vs Gini coefficient in GLM
|
As also mentioned in the link Scortchi supplies the Gini coefficient (or the proportional c-statistic or AUC) only contains information how well the model ranks the outcomes and no information about the calibration.
The deviance in a binary glm model is going twice the negative value of logarithmic scoring rule as shown here
> model <- glm(formula= vs ~ wt + disp, data=mtcars, family=binomial)
>
> # the negative deviance
> -model$deviance
[1] -21.40039
>
> # the logarithmic scoring rule
> ps <- predict(model, type = "response")
> with(mtcars, sum(vs * log(ps) + (1 - vs) * log(1 - ps)))
[1] -10.70019
The logarithmic scoring rule does provide information about the calibration. You may also want to see this post.
|
Deviance vs Gini coefficient in GLM
|
As also mentioned in the link Scortchi supplies the Gini coefficient (or the proportional c-statistic or AUC) only contains information how well the model ranks the outcomes and no information about t
|
Deviance vs Gini coefficient in GLM
As also mentioned in the link Scortchi supplies the Gini coefficient (or the proportional c-statistic or AUC) only contains information how well the model ranks the outcomes and no information about the calibration.
The deviance in a binary glm model is going twice the negative value of logarithmic scoring rule as shown here
> model <- glm(formula= vs ~ wt + disp, data=mtcars, family=binomial)
>
> # the negative deviance
> -model$deviance
[1] -21.40039
>
> # the logarithmic scoring rule
> ps <- predict(model, type = "response")
> with(mtcars, sum(vs * log(ps) + (1 - vs) * log(1 - ps)))
[1] -10.70019
The logarithmic scoring rule does provide information about the calibration. You may also want to see this post.
|
Deviance vs Gini coefficient in GLM
As also mentioned in the link Scortchi supplies the Gini coefficient (or the proportional c-statistic or AUC) only contains information how well the model ranks the outcomes and no information about t
|
42,745
|
Why scale cost functions by 1/n in a neural network?
|
In terms of mini-batch learning, $n$ should be the size of the batch instead of the total amount of training data (which in your case should be infinite).
Gradients are scaled by $1/n$ because we are taking the average of the batch, so the same learning rate can be used regardless of the size of the batch.
Edit
I found this later in that page, which shows how to set hyper-parameters in the context of mini-batch learning. So it might seem that the formula and the paragraph you refer to are talking about full batch learning, in which case $n$ should be the total number of training data.
Edit
So now the question would become "why you use the total training data size in regularization, instead of the batch size?"
I don't know whether there's a theoretical interpretation for this, for me it is just to make the hyper-parameters stay irrelevant to the batch size, since we are not summing the regularization term across the batch.
|
Why scale cost functions by 1/n in a neural network?
|
In terms of mini-batch learning, $n$ should be the size of the batch instead of the total amount of training data (which in your case should be infinite).
Gradients are scaled by $1/n$ because we ar
|
Why scale cost functions by 1/n in a neural network?
In terms of mini-batch learning, $n$ should be the size of the batch instead of the total amount of training data (which in your case should be infinite).
Gradients are scaled by $1/n$ because we are taking the average of the batch, so the same learning rate can be used regardless of the size of the batch.
Edit
I found this later in that page, which shows how to set hyper-parameters in the context of mini-batch learning. So it might seem that the formula and the paragraph you refer to are talking about full batch learning, in which case $n$ should be the total number of training data.
Edit
So now the question would become "why you use the total training data size in regularization, instead of the batch size?"
I don't know whether there's a theoretical interpretation for this, for me it is just to make the hyper-parameters stay irrelevant to the batch size, since we are not summing the regularization term across the batch.
|
Why scale cost functions by 1/n in a neural network?
In terms of mini-batch learning, $n$ should be the size of the batch instead of the total amount of training data (which in your case should be infinite).
Gradients are scaled by $1/n$ because we ar
|
42,746
|
Cluster Boostrap with Unequally Sized Clusters
|
This is explained quite nicely in Sherman and leCessie's paper, "A comparison between bootstrap methods and generalized estimating equations for correlated outcomes in generlized linear models." On page 905, they note:
"If as often may be the case, there are blocks of different sizes, then the algorithm can be modified as follows: let $m_i$, denote the number of blocks of size $i$, $i = 1,. . . ,I$. For each $i$ resample $m_i$ times with replacement from the $m_i$ blocks and compute $\hat{\beta}^*$ from the $n = \sum_{i=1}^Iim_i$ resampled observations. This conditioning on block size guarantees a total resarnple size
equal to the original sample size, making the bootstrap replicates "comparable". If,
however, $I$ is large it may be more attractive to resample $m$ times from the entire set of blocks.
We will call this the "All Block" bootstrap. This algorithm gives a random total sample size, $n^*$, say,
which makes the replicates less comparable. A reasonable approach to make them more comparable is to let the replicate be $(n^*/n)^{1/2}\hat{\beta}^*$, as suggested by Efron and Tibshirani (1993, p.101) for a whole block bootstrap in the time series setting."
REFERENCES:
Michael Sherman & Saskia le Cessie (1997) A comparison between
bootstrap methods and generalized estimating equations for correlated outcomes in
generalized linear models, Communications in Statistics - Simulation and Computation, 26:3,
901-925, DOI: 10.1080/03610919708813417
|
Cluster Boostrap with Unequally Sized Clusters
|
This is explained quite nicely in Sherman and leCessie's paper, "A comparison between bootstrap methods and generalized estimating equations for correlated outcomes in generlized linear models." On p
|
Cluster Boostrap with Unequally Sized Clusters
This is explained quite nicely in Sherman and leCessie's paper, "A comparison between bootstrap methods and generalized estimating equations for correlated outcomes in generlized linear models." On page 905, they note:
"If as often may be the case, there are blocks of different sizes, then the algorithm can be modified as follows: let $m_i$, denote the number of blocks of size $i$, $i = 1,. . . ,I$. For each $i$ resample $m_i$ times with replacement from the $m_i$ blocks and compute $\hat{\beta}^*$ from the $n = \sum_{i=1}^Iim_i$ resampled observations. This conditioning on block size guarantees a total resarnple size
equal to the original sample size, making the bootstrap replicates "comparable". If,
however, $I$ is large it may be more attractive to resample $m$ times from the entire set of blocks.
We will call this the "All Block" bootstrap. This algorithm gives a random total sample size, $n^*$, say,
which makes the replicates less comparable. A reasonable approach to make them more comparable is to let the replicate be $(n^*/n)^{1/2}\hat{\beta}^*$, as suggested by Efron and Tibshirani (1993, p.101) for a whole block bootstrap in the time series setting."
REFERENCES:
Michael Sherman & Saskia le Cessie (1997) A comparison between
bootstrap methods and generalized estimating equations for correlated outcomes in
generalized linear models, Communications in Statistics - Simulation and Computation, 26:3,
901-925, DOI: 10.1080/03610919708813417
|
Cluster Boostrap with Unequally Sized Clusters
This is explained quite nicely in Sherman and leCessie's paper, "A comparison between bootstrap methods and generalized estimating equations for correlated outcomes in generlized linear models." On p
|
42,747
|
Cluster Boostrap with Unequally Sized Clusters
|
I wrote something in R for my own use, based on the quote from Sherman and Cessie (1997) in StatsStudent's answer.
It implements bootstrap replicates on clustered data with clusters of different sizes.
It makes sure that clusters sampled more than once (due to replacement) are treated as distinct clusters within bootstrap samples (especially important in estimations involving fixed-effects along the cluster dimension).
Finally, note that this approach allows to compute the one-way cluster bootstrap standard error of any statistic computed via a custom, user-provided function. In this respect, it is more flexible than sandwich::vcovBS or sandwich::vcovCL which accept only some fitted model objects as input.
EDIT (improvement)
The Sherman and Cessie (1997) approach that draws clusters from pools of same-size clusters is incorrect I think. More precisely, the same-size-cluster pools are systematically smaller than the full pool of clusters. Therefore, this approach produces standard errors biased towards zero. The most extreme case being when every cluster is of different size (e.g. clustering on year level and no cross-section has the same size). In this case, the same cluster gets sampled for every size, all bootstrap replicates are thus identical and the standard error is exactly zero. I leave my old code implementing this approach at the end of my answer.
The better solution is to draw in the full pool of clusters such that the replicate data set has, on average, the same size as the original data set.
library(boot)
library(sandwich)
data("PetersenCL", package = "sandwich")
# construct an unbalanced panel with different numbers of firms every year.
datalist <- list()
for(yr in 1:7){
datalist[[yr]] <- subset(PetersenCL, (firm %in% c(1:(2*yr)) & year == yr))
}
data <- bind_rows(datalist)
cluster_var <- "year"
cluster_names = unique(data[,cluster_var])
# get the different cluster sizeS. This is necessary to cluster bootstrapping with clusters of different sizes.
sizes <- table(data[,cluster_var])
# don't bother the size of every cluster. Use the average cluster size only.
avg_cl_size <- mean(sizes)
# sample size of original data
N <- nrow(data)
# Number of draws, for the bootstrap replicate data sets to be as large as original data, on average.
n_draws <- N/avg_cl_size
ran.gen_cluster <- function(original_data, arg_list){
cl_boot_dat <- NULL
# for later: non-unique names of clusters (repeated when there is more than one obs. in a cluster)
nu_cl_names <- as.character(original_data[,cluster_var])
# sample, in the vector of names of clusters, N/avg_cl_size
sample_cl <- sample(x = cluster_names,
size = n_draws,
replace = TRUE)
# because of replacement, some names are sampled more than once
# we need to give them a new cluster identifier, otherwise a cluster sampled more than once
# will be "incorrectly treated as one large cluster rather than two distinct clusters" (by the fixed effects) (Cameron and Miller, 2015)
sample_cl_tab <- table(sample_cl)
for(n in 1:max(sample_cl_tab)){ # from 1 to the max number of times a name was sampled bc of replacement
# vector to select obs. that are within the sampled clusters.
names_n <- names(sample_cl_tab[sample_cl_tab == n])
sel <- nu_cl_names %in% names_n
# select data accordingly to the cluster sampling (duplicating n times observations from clusters sampled n times)
clda <- original_data[sel,][rep(seq_len(sum(sel)), n), ]
#identify row names without periods, and add ".0"
row.names(clda)[grep("\\.", row.names(clda), invert = TRUE)] <- paste0(grep("\\.", row.names(clda), invert = TRUE, value = TRUE),".0")
# add the suffix due to the repetition after the existing cluster identifier.
clda[,cluster_var] <- paste0(clda[,cluster_var], sub(".*\\.","_",row.names(clda)))
# stack the bootstrap samples iteratively
cl_boot_dat <- rbind(cl_boot_dat, clda)
}
return(cl_boot_dat)
}
#the returned data ARE NOT the same dimension as input data. It only has the same dimension on average over bootstrap replicates.
test_boot_d <- ran.gen_cluster(original_data = data)
dim(test_boot_d)
dim(data)
# test new clusters are not duplicated (correct if anyDuplicated returns 0)
base::anyDuplicated(test_boot_d[,c("firm","year")])
# custom estimation function
est_fun <- function(est_data){
est <- lm(as.formula("y ~ x"), est_data)
# statistics we want to evaluate the variance of:
return(est$coefficients)
}
# Run the bootstrap (see ?boot::boot for more details on the arguments)
set.seed(1234)
boot(data = data,
statistic = est_fun,
ran.gen = ran.gen_cluster,
mle = list(), # this argument cannot be left empty
sim = "parametric",
parallel = "no",
R = 400)
Test that it computes the same standard error as sandwich::vcovBS and compare with the asymptotic solution of sandwich::vcovCL
set.seed(1234)
sdw_bs <- vcovBS(lm(as.formula("y ~ x"), data), cluster = ~year, R=400, type = "xy")#
sqrt(sdw_bs["x","x"])
sdw_cl <- vcovCL(lm(as.formula("y ~ x"), data), cluster = ~year)
sqrt(sdw_cl["x","x"])
OLDER, FLAWED APPROACH
library(boot)
library(sandwich)
## Make some necessary objects
# unbalanced panel data
data("PetersenCL", package = "sandwich")
data <- subset(PetersenCL, !(firm %in% c(1:10) & year == 10))
cluster_var <- "firm"
# get the different cluster sizeS. This is necessary to cluster bootstrapping with clusters of different sizes.
sizes <- table(data[,cluster_var])
u_sizes <- sort(unique(sizes))
# names and numbers of clusters of every sizes
cl_names <- list()
n_clusters <- list()
for(s in u_sizes){
cl_names[[s]] <- names(sizes[sizes == s])
n_clusters[[s]] <- length(cl_names[[s]])
}
par_list <- list(unique_sizes = u_sizes,
cluster_names = cl_names,
number_clusters = n_clusters)
## Design the bootstrap sampling function.
# It will tell boot::boot how to sample data at each replicate
ran.gen_cluster_bysize <- function(original_data, arg_list){
cl_boot_dat <- NULL
# non-unique names of clusters (repeated when there is more than one obs. in a cluster)
nu_cl_names <- as.character(original_data[,cluster_var])
for(s in arg_list[["unique_sizes"]]){
# sample, in the vector of names of clusters of size s, as many draws as there are clusters of that size, with replacement
sample_cl_s <- sample(arg_list[["cluster_names"]][[s]],
arg_list[["number_clusters"]][[s]],
replace = TRUE)
# because of replacement, some names are sampled more than once
sample_cl_s_tab <- table(sample_cl_s)
# we need to give them a new cluster identifier, otherwise a cluster sampled more than once
# will be "incorrectly treated as one large cluster rather than two distinct clusters" (by the fixed effects) (Cameron 2015)
for(n in 1:max(sample_cl_s_tab)){ # from 1 to the max number of times a name was sampled bc of replacement
# vector to select obs. that are within the sampled clusters.
names_n <- names(sample_cl_s_tab[sample_cl_s_tab == n])
sel <- nu_cl_names %in% names_n
# select data accordingly to the cluster sampling (duplicating n times observations from clusters sampled n times)
clda <- original_data[sel,][rep(seq_len(sum(sel)), n), ]
#identify row names without periods, and add ".0"
row.names(clda)[grep("\\.", row.names(clda), invert = TRUE)] <- paste0(grep("\\.", row.names(clda), invert = TRUE, value = TRUE),".0")
# add the suffix due to the repetition after the existing cluster identifier.
clda[,cluster_var] <- paste0(clda[,cluster_var], sub(".*\\.","_",row.names(clda)))
# stack the bootstrap samples iteratively
cl_boot_dat <- rbind(cl_boot_dat, clda)
}
}
return(cl_boot_dat)
}
#test that the returned data are the same dimension as input
test_boot_d <- ran.gen_cluster_bysize(original_data = data,
arg_list = par_list)
dim(test_boot_d)
dim(data)
# test new clusters are not duplicated (correct if anyDuplicated returns 0)
base::anyDuplicated(test_boot_d[,c("firm","year")])
## Custom ("black-box") estimation function
est_fun <- function(est_data){
est <- lm(as.formula("y ~ x"), est_data)
# statistics we want to evaluate the variance of:
return(est$coefficients[2])
}
# see ?boot::boot for more details on these arguments
boot(data = data,
statistic = est_fun,
ran.gen = ran.gen_cluster_bysize,
mle = par_list,
sim = "parametric",
parallel = "no",
R = 200)
With this clustering structure, the result is close to the asymptotic solution (available for unbalanced data, but only for lm or glm objects):
sdw_cl <- vcovCL(lm(as.formula("y ~ x"), data), cluster = ~firm)
sqrt(sdw_cl["x","x"])
But it does not replicate the result from vcovBS, even for balanced data:
## compare with sandwich::vcovBS, on balanced panel data
set.seed(1234)
custom_bs <- boot(data = PetersenCL,
statistic = est_fun,
ran.gen = ran.gen_cluster_bysize,
mle = par_list,
sim = "parametric",
parallel = "no",
R = 200)
sd(custom_bs$t[,2])
set.seed(1234)
sdw_bs <- vcovBS(lm(as.formula("y ~ x"), PetersenCL), cluster = ~firm, R=200)#
sqrt(sdw_bs["x","x"])
|
Cluster Boostrap with Unequally Sized Clusters
|
I wrote something in R for my own use, based on the quote from Sherman and Cessie (1997) in StatsStudent's answer.
It implements bootstrap replicates on clustered data with clusters of different sizes
|
Cluster Boostrap with Unequally Sized Clusters
I wrote something in R for my own use, based on the quote from Sherman and Cessie (1997) in StatsStudent's answer.
It implements bootstrap replicates on clustered data with clusters of different sizes.
It makes sure that clusters sampled more than once (due to replacement) are treated as distinct clusters within bootstrap samples (especially important in estimations involving fixed-effects along the cluster dimension).
Finally, note that this approach allows to compute the one-way cluster bootstrap standard error of any statistic computed via a custom, user-provided function. In this respect, it is more flexible than sandwich::vcovBS or sandwich::vcovCL which accept only some fitted model objects as input.
EDIT (improvement)
The Sherman and Cessie (1997) approach that draws clusters from pools of same-size clusters is incorrect I think. More precisely, the same-size-cluster pools are systematically smaller than the full pool of clusters. Therefore, this approach produces standard errors biased towards zero. The most extreme case being when every cluster is of different size (e.g. clustering on year level and no cross-section has the same size). In this case, the same cluster gets sampled for every size, all bootstrap replicates are thus identical and the standard error is exactly zero. I leave my old code implementing this approach at the end of my answer.
The better solution is to draw in the full pool of clusters such that the replicate data set has, on average, the same size as the original data set.
library(boot)
library(sandwich)
data("PetersenCL", package = "sandwich")
# construct an unbalanced panel with different numbers of firms every year.
datalist <- list()
for(yr in 1:7){
datalist[[yr]] <- subset(PetersenCL, (firm %in% c(1:(2*yr)) & year == yr))
}
data <- bind_rows(datalist)
cluster_var <- "year"
cluster_names = unique(data[,cluster_var])
# get the different cluster sizeS. This is necessary to cluster bootstrapping with clusters of different sizes.
sizes <- table(data[,cluster_var])
# don't bother the size of every cluster. Use the average cluster size only.
avg_cl_size <- mean(sizes)
# sample size of original data
N <- nrow(data)
# Number of draws, for the bootstrap replicate data sets to be as large as original data, on average.
n_draws <- N/avg_cl_size
ran.gen_cluster <- function(original_data, arg_list){
cl_boot_dat <- NULL
# for later: non-unique names of clusters (repeated when there is more than one obs. in a cluster)
nu_cl_names <- as.character(original_data[,cluster_var])
# sample, in the vector of names of clusters, N/avg_cl_size
sample_cl <- sample(x = cluster_names,
size = n_draws,
replace = TRUE)
# because of replacement, some names are sampled more than once
# we need to give them a new cluster identifier, otherwise a cluster sampled more than once
# will be "incorrectly treated as one large cluster rather than two distinct clusters" (by the fixed effects) (Cameron and Miller, 2015)
sample_cl_tab <- table(sample_cl)
for(n in 1:max(sample_cl_tab)){ # from 1 to the max number of times a name was sampled bc of replacement
# vector to select obs. that are within the sampled clusters.
names_n <- names(sample_cl_tab[sample_cl_tab == n])
sel <- nu_cl_names %in% names_n
# select data accordingly to the cluster sampling (duplicating n times observations from clusters sampled n times)
clda <- original_data[sel,][rep(seq_len(sum(sel)), n), ]
#identify row names without periods, and add ".0"
row.names(clda)[grep("\\.", row.names(clda), invert = TRUE)] <- paste0(grep("\\.", row.names(clda), invert = TRUE, value = TRUE),".0")
# add the suffix due to the repetition after the existing cluster identifier.
clda[,cluster_var] <- paste0(clda[,cluster_var], sub(".*\\.","_",row.names(clda)))
# stack the bootstrap samples iteratively
cl_boot_dat <- rbind(cl_boot_dat, clda)
}
return(cl_boot_dat)
}
#the returned data ARE NOT the same dimension as input data. It only has the same dimension on average over bootstrap replicates.
test_boot_d <- ran.gen_cluster(original_data = data)
dim(test_boot_d)
dim(data)
# test new clusters are not duplicated (correct if anyDuplicated returns 0)
base::anyDuplicated(test_boot_d[,c("firm","year")])
# custom estimation function
est_fun <- function(est_data){
est <- lm(as.formula("y ~ x"), est_data)
# statistics we want to evaluate the variance of:
return(est$coefficients)
}
# Run the bootstrap (see ?boot::boot for more details on the arguments)
set.seed(1234)
boot(data = data,
statistic = est_fun,
ran.gen = ran.gen_cluster,
mle = list(), # this argument cannot be left empty
sim = "parametric",
parallel = "no",
R = 400)
Test that it computes the same standard error as sandwich::vcovBS and compare with the asymptotic solution of sandwich::vcovCL
set.seed(1234)
sdw_bs <- vcovBS(lm(as.formula("y ~ x"), data), cluster = ~year, R=400, type = "xy")#
sqrt(sdw_bs["x","x"])
sdw_cl <- vcovCL(lm(as.formula("y ~ x"), data), cluster = ~year)
sqrt(sdw_cl["x","x"])
OLDER, FLAWED APPROACH
library(boot)
library(sandwich)
## Make some necessary objects
# unbalanced panel data
data("PetersenCL", package = "sandwich")
data <- subset(PetersenCL, !(firm %in% c(1:10) & year == 10))
cluster_var <- "firm"
# get the different cluster sizeS. This is necessary to cluster bootstrapping with clusters of different sizes.
sizes <- table(data[,cluster_var])
u_sizes <- sort(unique(sizes))
# names and numbers of clusters of every sizes
cl_names <- list()
n_clusters <- list()
for(s in u_sizes){
cl_names[[s]] <- names(sizes[sizes == s])
n_clusters[[s]] <- length(cl_names[[s]])
}
par_list <- list(unique_sizes = u_sizes,
cluster_names = cl_names,
number_clusters = n_clusters)
## Design the bootstrap sampling function.
# It will tell boot::boot how to sample data at each replicate
ran.gen_cluster_bysize <- function(original_data, arg_list){
cl_boot_dat <- NULL
# non-unique names of clusters (repeated when there is more than one obs. in a cluster)
nu_cl_names <- as.character(original_data[,cluster_var])
for(s in arg_list[["unique_sizes"]]){
# sample, in the vector of names of clusters of size s, as many draws as there are clusters of that size, with replacement
sample_cl_s <- sample(arg_list[["cluster_names"]][[s]],
arg_list[["number_clusters"]][[s]],
replace = TRUE)
# because of replacement, some names are sampled more than once
sample_cl_s_tab <- table(sample_cl_s)
# we need to give them a new cluster identifier, otherwise a cluster sampled more than once
# will be "incorrectly treated as one large cluster rather than two distinct clusters" (by the fixed effects) (Cameron 2015)
for(n in 1:max(sample_cl_s_tab)){ # from 1 to the max number of times a name was sampled bc of replacement
# vector to select obs. that are within the sampled clusters.
names_n <- names(sample_cl_s_tab[sample_cl_s_tab == n])
sel <- nu_cl_names %in% names_n
# select data accordingly to the cluster sampling (duplicating n times observations from clusters sampled n times)
clda <- original_data[sel,][rep(seq_len(sum(sel)), n), ]
#identify row names without periods, and add ".0"
row.names(clda)[grep("\\.", row.names(clda), invert = TRUE)] <- paste0(grep("\\.", row.names(clda), invert = TRUE, value = TRUE),".0")
# add the suffix due to the repetition after the existing cluster identifier.
clda[,cluster_var] <- paste0(clda[,cluster_var], sub(".*\\.","_",row.names(clda)))
# stack the bootstrap samples iteratively
cl_boot_dat <- rbind(cl_boot_dat, clda)
}
}
return(cl_boot_dat)
}
#test that the returned data are the same dimension as input
test_boot_d <- ran.gen_cluster_bysize(original_data = data,
arg_list = par_list)
dim(test_boot_d)
dim(data)
# test new clusters are not duplicated (correct if anyDuplicated returns 0)
base::anyDuplicated(test_boot_d[,c("firm","year")])
## Custom ("black-box") estimation function
est_fun <- function(est_data){
est <- lm(as.formula("y ~ x"), est_data)
# statistics we want to evaluate the variance of:
return(est$coefficients[2])
}
# see ?boot::boot for more details on these arguments
boot(data = data,
statistic = est_fun,
ran.gen = ran.gen_cluster_bysize,
mle = par_list,
sim = "parametric",
parallel = "no",
R = 200)
With this clustering structure, the result is close to the asymptotic solution (available for unbalanced data, but only for lm or glm objects):
sdw_cl <- vcovCL(lm(as.formula("y ~ x"), data), cluster = ~firm)
sqrt(sdw_cl["x","x"])
But it does not replicate the result from vcovBS, even for balanced data:
## compare with sandwich::vcovBS, on balanced panel data
set.seed(1234)
custom_bs <- boot(data = PetersenCL,
statistic = est_fun,
ran.gen = ran.gen_cluster_bysize,
mle = par_list,
sim = "parametric",
parallel = "no",
R = 200)
sd(custom_bs$t[,2])
set.seed(1234)
sdw_bs <- vcovBS(lm(as.formula("y ~ x"), PetersenCL), cluster = ~firm, R=200)#
sqrt(sdw_bs["x","x"])
|
Cluster Boostrap with Unequally Sized Clusters
I wrote something in R for my own use, based on the quote from Sherman and Cessie (1997) in StatsStudent's answer.
It implements bootstrap replicates on clustered data with clusters of different sizes
|
42,748
|
$\min D_\textrm{KL}(p(x_1,\dots,x_n) \mid\mid q_1(x_1)\cdots q_n(x_n))$ gives the marginals of $p(x_1,\dots,x_n)$?
|
Using logarithmic identities, we can rewrite the KL divergence as
$$\sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log p(x_1, ..., x_n) - \sum_{i = 1}^n \sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i).$$
Note that only the second term depends on the univariate distributions over which we optimize, so we can focus on it and ignore the first term. For each $i$ we have
\begin{align}
-\sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i)
&= -\sum_{x_i} \sum_{x_1, ..., x_{i - 1}, x_{i + 1}, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i) \\
&= -\sum_{x_i} p_i(x_i) \log q_i(x_i).
\end{align}
Optimizing this quantity is equivalent to optimizing
$$\sum_{x_i} p_i(x_i) \log p_i(x_i) - \sum_{x_i} p_i(x_i) \log q_i(x_i) = D_\text{KL}(p_i(x_i) \mid\mid q_i(x_i)),$$
since the first term is again constant as a function of $q_i$. This KL divergence is minimal when $q_i(x_i) = p_i(x_i)$, proving that the optimal $q_i(x_i)$ is the marginal distribution $p_i(x_i)$.
|
$\min D_\textrm{KL}(p(x_1,\dots,x_n) \mid\mid q_1(x_1)\cdots q_n(x_n))$ gives the marginals of $p(x_
|
Using logarithmic identities, we can rewrite the KL divergence as
$$\sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log p(x_1, ..., x_n) - \sum_{i = 1}^n \sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i).$$
|
$\min D_\textrm{KL}(p(x_1,\dots,x_n) \mid\mid q_1(x_1)\cdots q_n(x_n))$ gives the marginals of $p(x_1,\dots,x_n)$?
Using logarithmic identities, we can rewrite the KL divergence as
$$\sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log p(x_1, ..., x_n) - \sum_{i = 1}^n \sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i).$$
Note that only the second term depends on the univariate distributions over which we optimize, so we can focus on it and ignore the first term. For each $i$ we have
\begin{align}
-\sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i)
&= -\sum_{x_i} \sum_{x_1, ..., x_{i - 1}, x_{i + 1}, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i) \\
&= -\sum_{x_i} p_i(x_i) \log q_i(x_i).
\end{align}
Optimizing this quantity is equivalent to optimizing
$$\sum_{x_i} p_i(x_i) \log p_i(x_i) - \sum_{x_i} p_i(x_i) \log q_i(x_i) = D_\text{KL}(p_i(x_i) \mid\mid q_i(x_i)),$$
since the first term is again constant as a function of $q_i$. This KL divergence is minimal when $q_i(x_i) = p_i(x_i)$, proving that the optimal $q_i(x_i)$ is the marginal distribution $p_i(x_i)$.
|
$\min D_\textrm{KL}(p(x_1,\dots,x_n) \mid\mid q_1(x_1)\cdots q_n(x_n))$ gives the marginals of $p(x_
Using logarithmic identities, we can rewrite the KL divergence as
$$\sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log p(x_1, ..., x_n) - \sum_{i = 1}^n \sum_{x_1, ..., x_n} p(x_1, ..., x_n) \log q_i(x_i).$$
|
42,749
|
Expectation of log likelihood ratio
|
The integral in question is in fact the Kullback-Leibler divergance between $F(\cdot,θ_0)$ and $F(\cdot,\hat{θ})$. You cannot generally say that it converges to anything (especially considering the fact that you parametric assumption may be wrong). However, for certain distribution families it has good estimates.
You might want to look at Vladimir Spokoiny publications, who has spent quite a lot of time working on this sort of problems. For instance, you might consider useful this article about exponential family distributions (2005).
|
Expectation of log likelihood ratio
|
The integral in question is in fact the Kullback-Leibler divergance between $F(\cdot,θ_0)$ and $F(\cdot,\hat{θ})$. You cannot generally say that it converges to anything (especially considering the fa
|
Expectation of log likelihood ratio
The integral in question is in fact the Kullback-Leibler divergance between $F(\cdot,θ_0)$ and $F(\cdot,\hat{θ})$. You cannot generally say that it converges to anything (especially considering the fact that you parametric assumption may be wrong). However, for certain distribution families it has good estimates.
You might want to look at Vladimir Spokoiny publications, who has spent quite a lot of time working on this sort of problems. For instance, you might consider useful this article about exponential family distributions (2005).
|
Expectation of log likelihood ratio
The integral in question is in fact the Kullback-Leibler divergance between $F(\cdot,θ_0)$ and $F(\cdot,\hat{θ})$. You cannot generally say that it converges to anything (especially considering the fa
|
42,750
|
Expectation of log likelihood ratio
|
You cannot say, in general, that the finite sample expectation of the log likelihood ratio will be 1, even though it asymptotically converges in probability to 1. "Around 1" is a reasonable guess, but it's possible to make the finite sample bias arbitrarily large with any number of contrived distributions.
The actual distribution of the log likelihood ratio under the null hypothesis is extremely complex except when considering distributions which are conserved under convolution, like normal or gamma(theta, 1) RVs.
|
Expectation of log likelihood ratio
|
You cannot say, in general, that the finite sample expectation of the log likelihood ratio will be 1, even though it asymptotically converges in probability to 1. "Around 1" is a reasonable guess, but
|
Expectation of log likelihood ratio
You cannot say, in general, that the finite sample expectation of the log likelihood ratio will be 1, even though it asymptotically converges in probability to 1. "Around 1" is a reasonable guess, but it's possible to make the finite sample bias arbitrarily large with any number of contrived distributions.
The actual distribution of the log likelihood ratio under the null hypothesis is extremely complex except when considering distributions which are conserved under convolution, like normal or gamma(theta, 1) RVs.
|
Expectation of log likelihood ratio
You cannot say, in general, that the finite sample expectation of the log likelihood ratio will be 1, even though it asymptotically converges in probability to 1. "Around 1" is a reasonable guess, but
|
42,751
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quotient of two independent variables?
|
Yes and no. By having a sufficiently deep tree (at least two splits deep) and splitting on both $x_1$ and $x_2$, tree based model like xgboost (or LightGBM or catboost) can eventually approximate (given enough data) any relationship between $x_1\times x_2$ and your prediction target of interest. Of course, if you know that some function $f(x_1\times x_2)$ is a predictor of your outcome of interest, then specifying a feature that is that exact transformation of $x_1$ and $x_2$ is what you should do.
What to do in practice? If you have a lot of data and are not that sure that the interaction matters, perhaps don't specify it as a feature. If you don't have a lot of data and suspect it's an important feature, you probably want to put this feature into xgboost. If you are inbetween - try it out using an appropriate cross-validation scheme.
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quoti
|
Yes and no. By having a sufficiently deep tree (at least two splits deep) and splitting on both $x_1$ and $x_2$, tree based model like xgboost (or LightGBM or catboost) can eventually approximate (giv
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quotient of two independent variables?
Yes and no. By having a sufficiently deep tree (at least two splits deep) and splitting on both $x_1$ and $x_2$, tree based model like xgboost (or LightGBM or catboost) can eventually approximate (given enough data) any relationship between $x_1\times x_2$ and your prediction target of interest. Of course, if you know that some function $f(x_1\times x_2)$ is a predictor of your outcome of interest, then specifying a feature that is that exact transformation of $x_1$ and $x_2$ is what you should do.
What to do in practice? If you have a lot of data and are not that sure that the interaction matters, perhaps don't specify it as a feature. If you don't have a lot of data and suspect it's an important feature, you probably want to put this feature into xgboost. If you are inbetween - try it out using an appropriate cross-validation scheme.
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quoti
Yes and no. By having a sufficiently deep tree (at least two splits deep) and splitting on both $x_1$ and $x_2$, tree based model like xgboost (or LightGBM or catboost) can eventually approximate (giv
|
42,752
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quotient of two independent variables?
|
The answer to your question depends on what class of split rules you allow in the fitting of a decision tree. If the only class of allowable splits are on a single variable you will never be able to capture the interaction behavior described in the post. In fact what you will see that allows you to diagnose something like this has occurred is a repetition of splits in the decision tree on the two interacting variables and the repeated splits may occur several times. If you allow classes of splitting rules that allow for polynomials up to the order of the interaction you think may occur in your data (here 2nd order) then you will be able to capture the behavior in the decision tree that is fit to the data.
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quoti
|
The answer to your question depends on what class of split rules you allow in the fitting of a decision tree. If the only class of allowable splits are on a single variable you will never be able to c
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quotient of two independent variables?
The answer to your question depends on what class of split rules you allow in the fitting of a decision tree. If the only class of allowable splits are on a single variable you will never be able to capture the interaction behavior described in the post. In fact what you will see that allows you to diagnose something like this has occurred is a repetition of splits in the decision tree on the two interacting variables and the repeated splits may occur several times. If you allow classes of splitting rules that allow for polynomials up to the order of the interaction you think may occur in your data (here 2nd order) then you will be able to capture the behavior in the decision tree that is fit to the data.
|
Can a decision tree automatically detect the effect on the dependent variable from the product/quoti
The answer to your question depends on what class of split rules you allow in the fitting of a decision tree. If the only class of allowable splits are on a single variable you will never be able to c
|
42,753
|
What is the distribution for the time before K successes happen in N trials?
|
Suppose that $X_1,X_2,\dotsc,X_N$ are iid with the unit exponential distribution with density $f(x) = e^{-x}, x\ge 0$. (You can adapt the results to some other rate). But, each $X_i$ (the waiting time before person $i$ makes his phone call) will only be realized with some probability $p$, and with probability $1-p$ the call is not done and we do not observe that $X_i$. The number of realized calls $r$ has the binomial distribution $\text{bin}(N,p)$. So, reorder the variables so the realized calls (conditional on $r$) is $X_1,\dotsc,X_r$. Then, assuming that $K\le r$, you asked for the distribution of the order statistic $X_{K:r}$. Now, the theory of exponential order statistics is especially simple, so, using results taken from the book: Barry Arnold: "A First Course in Order Statistics", which I will not rederive here (but the proofs are really simple, and can be found here: https://math.stackexchange.com/questions/80475/order-statistics-of-i-i-d-exponentially-distributed-sample), transform the order statistics to exponential spacings, given by
$$
Z_1 = r X_{1:r}, \\
Z_2 = (r-1)(X_{2:r}-X_{1:r}) \\
\vdots \\
Z_r = X_{r:r}-X_{r-1:r}.
$$
Then the surprising and simple result is that the variables $Z_1, Z_2, \dotsc,Z_r$ are iid distributed unit exponential.
By some algebra we get that $X_{K:r}$ has the same distribution as
$\sum_{i=1}^K \frac1{r-i+1} Z_i$, that is, a linear combination of independent exponential random variables. If all the coefficients in the linear combination were equal, this would be a gamma distribution. Now it is a more complicated distribution which have been studied in http://www.tandfonline.com/doi/abs/10.1080/03610928308828483?journalCode=lsta20, for instance.
Now, you need to decide what you want to do in the case that $K>r$. Barring that problem, what you need now is simply the mixture distribution of $X_{K:r}$ over the binomial distribution of $r$.
|
What is the distribution for the time before K successes happen in N trials?
|
Suppose that $X_1,X_2,\dotsc,X_N$ are iid with the unit exponential distribution with density $f(x) = e^{-x}, x\ge 0$. (You can adapt the results to some other rate). But, each $X_i$ (the waiting time
|
What is the distribution for the time before K successes happen in N trials?
Suppose that $X_1,X_2,\dotsc,X_N$ are iid with the unit exponential distribution with density $f(x) = e^{-x}, x\ge 0$. (You can adapt the results to some other rate). But, each $X_i$ (the waiting time before person $i$ makes his phone call) will only be realized with some probability $p$, and with probability $1-p$ the call is not done and we do not observe that $X_i$. The number of realized calls $r$ has the binomial distribution $\text{bin}(N,p)$. So, reorder the variables so the realized calls (conditional on $r$) is $X_1,\dotsc,X_r$. Then, assuming that $K\le r$, you asked for the distribution of the order statistic $X_{K:r}$. Now, the theory of exponential order statistics is especially simple, so, using results taken from the book: Barry Arnold: "A First Course in Order Statistics", which I will not rederive here (but the proofs are really simple, and can be found here: https://math.stackexchange.com/questions/80475/order-statistics-of-i-i-d-exponentially-distributed-sample), transform the order statistics to exponential spacings, given by
$$
Z_1 = r X_{1:r}, \\
Z_2 = (r-1)(X_{2:r}-X_{1:r}) \\
\vdots \\
Z_r = X_{r:r}-X_{r-1:r}.
$$
Then the surprising and simple result is that the variables $Z_1, Z_2, \dotsc,Z_r$ are iid distributed unit exponential.
By some algebra we get that $X_{K:r}$ has the same distribution as
$\sum_{i=1}^K \frac1{r-i+1} Z_i$, that is, a linear combination of independent exponential random variables. If all the coefficients in the linear combination were equal, this would be a gamma distribution. Now it is a more complicated distribution which have been studied in http://www.tandfonline.com/doi/abs/10.1080/03610928308828483?journalCode=lsta20, for instance.
Now, you need to decide what you want to do in the case that $K>r$. Barring that problem, what you need now is simply the mixture distribution of $X_{K:r}$ over the binomial distribution of $r$.
|
What is the distribution for the time before K successes happen in N trials?
Suppose that $X_1,X_2,\dotsc,X_N$ are iid with the unit exponential distribution with density $f(x) = e^{-x}, x\ge 0$. (You can adapt the results to some other rate). But, each $X_i$ (the waiting time
|
42,754
|
What is the distribution for the time before K successes happen in N trials?
|
If N is fixed and K is random, then the number of successes K is such that $K \sim Bin(N,p)$. You are not guaranteed to get K successes for any fixed K if N is also fixed.
Alternatively, if N is random and K is fixed, and you are wondering about the distribution of the number of trials, N, until K successes are achieved, then N $\sim NegBin(K,p)$ (note that different texts have different definitions of the negative binomial -- sometimes they only count failures rather than total trials).
The sum of k IID standard Expos is Gamma(k,1).
Assuming the negative binomial scenario, you have $T \mid N \sim Gamma(N,1)$ and $N \sim NegBin(K,p)$.
I don't know if there is a nice formula for this hierarchical model but you should be able to get the expectation easily using the law of total expectation, conditioning on N. E(T) = E(E(T|N))
|
What is the distribution for the time before K successes happen in N trials?
|
If N is fixed and K is random, then the number of successes K is such that $K \sim Bin(N,p)$. You are not guaranteed to get K successes for any fixed K if N is also fixed.
Alternatively, if N is rand
|
What is the distribution for the time before K successes happen in N trials?
If N is fixed and K is random, then the number of successes K is such that $K \sim Bin(N,p)$. You are not guaranteed to get K successes for any fixed K if N is also fixed.
Alternatively, if N is random and K is fixed, and you are wondering about the distribution of the number of trials, N, until K successes are achieved, then N $\sim NegBin(K,p)$ (note that different texts have different definitions of the negative binomial -- sometimes they only count failures rather than total trials).
The sum of k IID standard Expos is Gamma(k,1).
Assuming the negative binomial scenario, you have $T \mid N \sim Gamma(N,1)$ and $N \sim NegBin(K,p)$.
I don't know if there is a nice formula for this hierarchical model but you should be able to get the expectation easily using the law of total expectation, conditioning on N. E(T) = E(E(T|N))
|
What is the distribution for the time before K successes happen in N trials?
If N is fixed and K is random, then the number of successes K is such that $K \sim Bin(N,p)$. You are not guaranteed to get K successes for any fixed K if N is also fixed.
Alternatively, if N is rand
|
42,755
|
What is the distribution for the time before K successes happen in N trials?
|
The time is the $K$'th order statistic of $N'$ iid exponential distributions where $N'$ is binomial distributed with parameters $N, p$. Each order statistic is distributed as in this solution described below, which you mix over the outcomes of $N'$.
Let $\lambda$ be the rate of $T$. Then the first order statistic of $N'$ exponential distributions having rate $\lambda$ is exponentially distributed with rate $N' \lambda$ since it's as if $N'$ Poisson processes race against each other and the winner's time is the same as the waiting time of the superposition. The second order statistic adds on an exponential distribution with rate $(N'-1)\lambda$ since one less Poisson process is racing, and so on...
|
What is the distribution for the time before K successes happen in N trials?
|
The time is the $K$'th order statistic of $N'$ iid exponential distributions where $N'$ is binomial distributed with parameters $N, p$. Each order statistic is distributed as in this solution describ
|
What is the distribution for the time before K successes happen in N trials?
The time is the $K$'th order statistic of $N'$ iid exponential distributions where $N'$ is binomial distributed with parameters $N, p$. Each order statistic is distributed as in this solution described below, which you mix over the outcomes of $N'$.
Let $\lambda$ be the rate of $T$. Then the first order statistic of $N'$ exponential distributions having rate $\lambda$ is exponentially distributed with rate $N' \lambda$ since it's as if $N'$ Poisson processes race against each other and the winner's time is the same as the waiting time of the superposition. The second order statistic adds on an exponential distribution with rate $(N'-1)\lambda$ since one less Poisson process is racing, and so on...
|
What is the distribution for the time before K successes happen in N trials?
The time is the $K$'th order statistic of $N'$ iid exponential distributions where $N'$ is binomial distributed with parameters $N, p$. Each order statistic is distributed as in this solution describ
|
42,756
|
chi-squared goodness-of-fit: effect size and power
|
$\lambda =\omega^2N$, see Cohen, Jacob (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.), page 549, formula 12.7.1.
Hence the effect size you mention is Cohen's omega ($\omega$, sometimes written "w").
$\omega=\sqrt{\frac{\chi2}{N}}$. The $p_{0i}$ and $p_{1i}$ in the formula you give in your question are proportions, not counts. $\omega$ generally has not an upper bound of 1 (except when there are just two cells of expected proportions of 0.5), but it's not really a problem if you use it for sample size calculations.
Similarly, you don't need tables to define an effect size of minimal interest. In fact in his book Cohen tends to advise against using them, see his introductory remarks of section 7.2.3 of his book, p. 224:
[...]
The best guide here, as always, is the development of some sense of
magnitude ad hoc, for a particular problem or a particular field.
Since it is a function of proportions, the investigator should
generally be able to express the size of the effect he wishes to be
able to detect by writing a set of alternate-hypothetical proportions
[...] and, with the null-hypothetical
proportions, compute w.
[...]
In other words, you have to define what a "minimally interesting table" would look like in your scenario. For example, you can ask yourself how many cells should deviate from their expected value and by how much in terms of proportions, for you to consider such a table as an interesting departure from the null hypothesis.
Once you defined this hypothetical, minimally interesting table, you calculate its effect size $\omega$. From that, you can calculate the sample size required to detect this "minimally interesting effect size".
As for the other effect sizes you mention, Cramér's V and Phi are meant as measures of association, in other words they are meant for contingency tables, not one-way tables. There's a variant of Cramér's V for one-way tables, but it does not really bring a lot more information than Cohen's $\omega$, and is not meant for power calculations.
I'm not familiar with the Johnston-Berry-Mielke $E$, but from the article you mention its purpose seems to be an easier interpretation than $\omega$, not power calculations.
|
chi-squared goodness-of-fit: effect size and power
|
$\lambda =\omega^2N$, see Cohen, Jacob (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.), page 549, formula 12.7.1.
Hence the effect size you mention is Cohen's omega ($\omega$,
|
chi-squared goodness-of-fit: effect size and power
$\lambda =\omega^2N$, see Cohen, Jacob (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.), page 549, formula 12.7.1.
Hence the effect size you mention is Cohen's omega ($\omega$, sometimes written "w").
$\omega=\sqrt{\frac{\chi2}{N}}$. The $p_{0i}$ and $p_{1i}$ in the formula you give in your question are proportions, not counts. $\omega$ generally has not an upper bound of 1 (except when there are just two cells of expected proportions of 0.5), but it's not really a problem if you use it for sample size calculations.
Similarly, you don't need tables to define an effect size of minimal interest. In fact in his book Cohen tends to advise against using them, see his introductory remarks of section 7.2.3 of his book, p. 224:
[...]
The best guide here, as always, is the development of some sense of
magnitude ad hoc, for a particular problem or a particular field.
Since it is a function of proportions, the investigator should
generally be able to express the size of the effect he wishes to be
able to detect by writing a set of alternate-hypothetical proportions
[...] and, with the null-hypothetical
proportions, compute w.
[...]
In other words, you have to define what a "minimally interesting table" would look like in your scenario. For example, you can ask yourself how many cells should deviate from their expected value and by how much in terms of proportions, for you to consider such a table as an interesting departure from the null hypothesis.
Once you defined this hypothetical, minimally interesting table, you calculate its effect size $\omega$. From that, you can calculate the sample size required to detect this "minimally interesting effect size".
As for the other effect sizes you mention, Cramér's V and Phi are meant as measures of association, in other words they are meant for contingency tables, not one-way tables. There's a variant of Cramér's V for one-way tables, but it does not really bring a lot more information than Cohen's $\omega$, and is not meant for power calculations.
I'm not familiar with the Johnston-Berry-Mielke $E$, but from the article you mention its purpose seems to be an easier interpretation than $\omega$, not power calculations.
|
chi-squared goodness-of-fit: effect size and power
$\lambda =\omega^2N$, see Cohen, Jacob (1988). Statistical Power Analysis for the Behavioral Sciences (2nd ed.), page 549, formula 12.7.1.
Hence the effect size you mention is Cohen's omega ($\omega$,
|
42,757
|
Dispersion of points on 2D or 3D
|
In situations like this, people often use the variance-covariance matrix. Along the main diagonal, the variance for each dimension is listed. Each $i, j$th off diagonal element (where $i\ne j$) lists the covariance of variables $i$ and $j$. In this way, every aspect of the dispersion is listed separately.
On the other hand, if you need a single number for simple comparisons, the determinant is sometimes used.
|
Dispersion of points on 2D or 3D
|
In situations like this, people often use the variance-covariance matrix. Along the main diagonal, the variance for each dimension is listed. Each $i, j$th off diagonal element (where $i\ne j$) list
|
Dispersion of points on 2D or 3D
In situations like this, people often use the variance-covariance matrix. Along the main diagonal, the variance for each dimension is listed. Each $i, j$th off diagonal element (where $i\ne j$) lists the covariance of variables $i$ and $j$. In this way, every aspect of the dispersion is listed separately.
On the other hand, if you need a single number for simple comparisons, the determinant is sometimes used.
|
Dispersion of points on 2D or 3D
In situations like this, people often use the variance-covariance matrix. Along the main diagonal, the variance for each dimension is listed. Each $i, j$th off diagonal element (where $i\ne j$) list
|
42,758
|
Identification of Bayesian models
|
"An unidentified Bayesian model is one in which the prior and posterior are exactly the same, and nothing is learned from the data". While this is not a main concerns, the mentioned point stays valid in Bayesian setting, if from some $\Theta_1 \ne \Theta_2$, $p(x|\Theta_1)=p(x|\Theta_2)$ then the posterior distribution will not converge to a "prior independent" solution and the prior will lead a part of inference (even in the asymptotical limit of observations number) which may be an undersirable property.
For your to last question, there is a closely related question with answer on this site : Is there any reason to prefer a bayesian model with few variables?.
Moreover consider that adding an extra parameter $\theta_2$ through $p(\theta_1|\theta_2)$ and hyperprior on $\theta_2$, $p(\theta_1)$ writes:
$$
p(\theta_1)=\int_R p(\theta_1|\theta_2)p(\theta_2)d\theta_2
$$
I do not know if there are some general results relating
$var(\theta_1)$ and $var(\theta_2)$ but for example $
var(\theta_1) \ngtr var(\theta_1|\theta_2=\alpha)$ in general. So adding an hyperparameter to the model does not systematically result in a prior model of higher variance.
|
Identification of Bayesian models
|
"An unidentified Bayesian model is one in which the prior and posterior are exactly the same, and nothing is learned from the data". While this is not a main concerns, the mentioned point stays valid
|
Identification of Bayesian models
"An unidentified Bayesian model is one in which the prior and posterior are exactly the same, and nothing is learned from the data". While this is not a main concerns, the mentioned point stays valid in Bayesian setting, if from some $\Theta_1 \ne \Theta_2$, $p(x|\Theta_1)=p(x|\Theta_2)$ then the posterior distribution will not converge to a "prior independent" solution and the prior will lead a part of inference (even in the asymptotical limit of observations number) which may be an undersirable property.
For your to last question, there is a closely related question with answer on this site : Is there any reason to prefer a bayesian model with few variables?.
Moreover consider that adding an extra parameter $\theta_2$ through $p(\theta_1|\theta_2)$ and hyperprior on $\theta_2$, $p(\theta_1)$ writes:
$$
p(\theta_1)=\int_R p(\theta_1|\theta_2)p(\theta_2)d\theta_2
$$
I do not know if there are some general results relating
$var(\theta_1)$ and $var(\theta_2)$ but for example $
var(\theta_1) \ngtr var(\theta_1|\theta_2=\alpha)$ in general. So adding an hyperparameter to the model does not systematically result in a prior model of higher variance.
|
Identification of Bayesian models
"An unidentified Bayesian model is one in which the prior and posterior are exactly the same, and nothing is learned from the data". While this is not a main concerns, the mentioned point stays valid
|
42,759
|
Whether to Use Continuity Correction When Conducting a Test of Equality of 2 Proportions
|
So, Yates showed that the use of Pearson’s chi-squared has the implication of p–values which underestimate the true p–values based on the binomial distribution, but that you already know. Actually, statisticians tend to disagree about whether to use it: some statisticians argue that expected frequency lower that five should imply the use of that correction, while others use ten as that value, while others make the case that Yates' Correction should be used in every chi-squared tests with contingency tables 2 X 2.
|
Whether to Use Continuity Correction When Conducting a Test of Equality of 2 Proportions
|
So, Yates showed that the use of Pearson’s chi-squared has the implication of p–values which underestimate the true p–values based on the binomial distribution, but that you already know. Actually, st
|
Whether to Use Continuity Correction When Conducting a Test of Equality of 2 Proportions
So, Yates showed that the use of Pearson’s chi-squared has the implication of p–values which underestimate the true p–values based on the binomial distribution, but that you already know. Actually, statisticians tend to disagree about whether to use it: some statisticians argue that expected frequency lower that five should imply the use of that correction, while others use ten as that value, while others make the case that Yates' Correction should be used in every chi-squared tests with contingency tables 2 X 2.
|
Whether to Use Continuity Correction When Conducting a Test of Equality of 2 Proportions
So, Yates showed that the use of Pearson’s chi-squared has the implication of p–values which underestimate the true p–values based on the binomial distribution, but that you already know. Actually, st
|
42,760
|
Removing interaction term from repeated measures two-way ANOVA in R: Anova() function in car package
|
While I'm no expert in repeated measures ANOVA, I have some familiarity with the Anova() function in car.
Type I or sequential Anova estimates a sequence of models in an effectively arbitrary order, each time permanently removing the previously tested regressor from the subsequent step. Many of its steps are not necessarily interesting simply because the full model isn't being considered in the tests. While Type III Anova seems overall like a snake pit, that you don't touch unless you absolutely know what you're doing (e.g. specify correct contrasts, correctly interpret coefficients, and assorted philosophical conundrums).
As for Type II Anova, in my understanding and as a general principle it estimates a sequence of models with carefully chosen tests, each time removing a single regressor from the model while respecting the principle of marginality. The "principle of marginality" requires that when comparing a model that includes a variable with a model that doesn't include it, all higher-order terms that incorporate said variable (e.g. interactions) should be removed from both models. The full model is used in each step if it doesn't conflict with the principle of marginality. For a more detailed account of how Anova(..., type=2) works and its theoretical underpinnings see Fox and Weisberg (2011), Fox (2016) or even Venables and Ripley (2002) (the relevant sections that tackle the principle of marginality are relatively short reads).
So without any other info (and unless ?Anova has indications to the contrary for these specific models), by looking at the table above I would assume that:
the F-test associated with diet:time_fac interaction term was estimated by comparing the full model against the model that doesn't include the interaction term (as usual).
the F-test associated with the time_fac main-effect regressor was estimated by comparing two models that both had the interaction term removed: the model that includes both diet and time_fac vs the model that includes only diet.
the F-test associated with the diet main-effect regressor is similar to the above: the model that includes both diet and time_fac vs the model that includes only time_fac.
So to answer your question, the interaction term is automatically removed as required by the principle of marginality, so the main effects are tested without the confounding effect of the interaction term. If the interaction term is significant, you disregard the main effects; otherwise, you consider the main effects alone.
|
Removing interaction term from repeated measures two-way ANOVA in R: Anova() function in car package
|
While I'm no expert in repeated measures ANOVA, I have some familiarity with the Anova() function in car.
Type I or sequential Anova estimates a sequence of models in an effectively arbitrary order,
|
Removing interaction term from repeated measures two-way ANOVA in R: Anova() function in car package
While I'm no expert in repeated measures ANOVA, I have some familiarity with the Anova() function in car.
Type I or sequential Anova estimates a sequence of models in an effectively arbitrary order, each time permanently removing the previously tested regressor from the subsequent step. Many of its steps are not necessarily interesting simply because the full model isn't being considered in the tests. While Type III Anova seems overall like a snake pit, that you don't touch unless you absolutely know what you're doing (e.g. specify correct contrasts, correctly interpret coefficients, and assorted philosophical conundrums).
As for Type II Anova, in my understanding and as a general principle it estimates a sequence of models with carefully chosen tests, each time removing a single regressor from the model while respecting the principle of marginality. The "principle of marginality" requires that when comparing a model that includes a variable with a model that doesn't include it, all higher-order terms that incorporate said variable (e.g. interactions) should be removed from both models. The full model is used in each step if it doesn't conflict with the principle of marginality. For a more detailed account of how Anova(..., type=2) works and its theoretical underpinnings see Fox and Weisberg (2011), Fox (2016) or even Venables and Ripley (2002) (the relevant sections that tackle the principle of marginality are relatively short reads).
So without any other info (and unless ?Anova has indications to the contrary for these specific models), by looking at the table above I would assume that:
the F-test associated with diet:time_fac interaction term was estimated by comparing the full model against the model that doesn't include the interaction term (as usual).
the F-test associated with the time_fac main-effect regressor was estimated by comparing two models that both had the interaction term removed: the model that includes both diet and time_fac vs the model that includes only diet.
the F-test associated with the diet main-effect regressor is similar to the above: the model that includes both diet and time_fac vs the model that includes only time_fac.
So to answer your question, the interaction term is automatically removed as required by the principle of marginality, so the main effects are tested without the confounding effect of the interaction term. If the interaction term is significant, you disregard the main effects; otherwise, you consider the main effects alone.
|
Removing interaction term from repeated measures two-way ANOVA in R: Anova() function in car package
While I'm no expert in repeated measures ANOVA, I have some familiarity with the Anova() function in car.
Type I or sequential Anova estimates a sequence of models in an effectively arbitrary order,
|
42,761
|
The meaning of tensors in the neural network community [duplicate]
|
Tensors in the neural network community = vector (1D-tensor), matrix/array (2D-tensor), or multi-dimensional array (nD-tensor, with $n > 2$).
Examples:
Related: Why the sudden fascination with tensors?
|
The meaning of tensors in the neural network community [duplicate]
|
Tensors in the neural network community = vector (1D-tensor), matrix/array (2D-tensor), or multi-dimensional array (nD-tensor, with $n > 2$).
Examples:
Related: Why the sudden fascination with te
|
The meaning of tensors in the neural network community [duplicate]
Tensors in the neural network community = vector (1D-tensor), matrix/array (2D-tensor), or multi-dimensional array (nD-tensor, with $n > 2$).
Examples:
Related: Why the sudden fascination with tensors?
|
The meaning of tensors in the neural network community [duplicate]
Tensors in the neural network community = vector (1D-tensor), matrix/array (2D-tensor), or multi-dimensional array (nD-tensor, with $n > 2$).
Examples:
Related: Why the sudden fascination with te
|
42,762
|
Confidence-interval / p-value duality vs. frequentist interpretation of CIs
|
You use different null hypotheses in each situation.
When performing a hypothesis test, you set the null hypothesis to some value you are attempting to test the implausibility of. Let's consider the following model:
$$ Y = \beta * X + \epsilon $$
You will collect some data and with it, compute an estimate of $\beta$, which we will call $\hat{\beta}$. Then, you will generally set up a hypothesis test as follows:
$$ H_0 : \beta = 0 $$
$$ H_1 : \beta \neq 0 $$
The p-value is computed in the ordinary way for whatever test you are using. To compute a confidence interval, you use the following null hypothesis, which tests whether or not the true value for $\beta$ is equal to the estimated value you observed.
$$ H_0 : \beta = \hat{\beta} $$
$$ H_1 : \beta \neq \hat{\beta} $$
Say you are trying to compute a 95% confidence interval. You would find the bounds of the rejection region of the null distribution (that is, where p = 0.025 for both one-tailed tests) and, after converting your test statistic back to the units of $\beta$, you have your confidence interval.
This is where the duality of hypothesis testing and confidence interval computation comes in - this confidence interval contains the true value for $\beta$ for the same reason that setting $\alpha$ to 0.05 gives you a 5% Type I error rate. Of course, this depends on your test of choice actually being able to maintain the nominal Type I error rate for your dataset, but that's a separate issue entirely.
|
Confidence-interval / p-value duality vs. frequentist interpretation of CIs
|
You use different null hypotheses in each situation.
When performing a hypothesis test, you set the null hypothesis to some value you are attempting to test the implausibility of. Let's consider the f
|
Confidence-interval / p-value duality vs. frequentist interpretation of CIs
You use different null hypotheses in each situation.
When performing a hypothesis test, you set the null hypothesis to some value you are attempting to test the implausibility of. Let's consider the following model:
$$ Y = \beta * X + \epsilon $$
You will collect some data and with it, compute an estimate of $\beta$, which we will call $\hat{\beta}$. Then, you will generally set up a hypothesis test as follows:
$$ H_0 : \beta = 0 $$
$$ H_1 : \beta \neq 0 $$
The p-value is computed in the ordinary way for whatever test you are using. To compute a confidence interval, you use the following null hypothesis, which tests whether or not the true value for $\beta$ is equal to the estimated value you observed.
$$ H_0 : \beta = \hat{\beta} $$
$$ H_1 : \beta \neq \hat{\beta} $$
Say you are trying to compute a 95% confidence interval. You would find the bounds of the rejection region of the null distribution (that is, where p = 0.025 for both one-tailed tests) and, after converting your test statistic back to the units of $\beta$, you have your confidence interval.
This is where the duality of hypothesis testing and confidence interval computation comes in - this confidence interval contains the true value for $\beta$ for the same reason that setting $\alpha$ to 0.05 gives you a 5% Type I error rate. Of course, this depends on your test of choice actually being able to maintain the nominal Type I error rate for your dataset, but that's a separate issue entirely.
|
Confidence-interval / p-value duality vs. frequentist interpretation of CIs
You use different null hypotheses in each situation.
When performing a hypothesis test, you set the null hypothesis to some value you are attempting to test the implausibility of. Let's consider the f
|
42,763
|
Relation between covariance and joint distribution
|
I would ask the opposite question: what is the implications of zero covariance for any surviving dependence? The two variables can certainly be stochastically dependent even though their covariance is zero, but what kind of dependencies, and what kind of bivariate joint distributions, are excluded if covariance is zero?
Some examples:
a) Many-many "named" bivariate continuous joint distributions (i.e. joint distributions where the two marginals belong to the same family).
b) Bivariate continuous distributions of the Farlie-Gumbel-Morgenstern family
$$H_{X,Y}(x,y)=F_X(x)G_Y(y)\left(1+\alpha\big(1-F_X(x)\big)\big(1-F_Y(y)\big)\right), \;\; \alpha <1$$
for two random variables with arbitrary marginal distribution functions $F_X(x)$ and $G_y(y)$. Here $\alpha =0$ is necessary and sufficient for zero covariance and stochastic independence. So here you cannot have the one without the other.
c) Finally one must remember that although covariance is usually described as "reflecting the "linear" dependence among two variables", this may mislead because when a random variable $X$ is a pure non-linear function of another one $Y$, almost always their covariance will be non-zero. Consider a very simple case, let
$$X = Y^2 \implies \text{Cov}(X,Y) = E(XY) - E(X)E(Y) = E(Y^3) - E(Y^2)E(Y)$$
This in general won't be zero.
etc. Certainly, infinite ways to model stochastic dependence with zero covariance do exist, but the above shows that if one wants to go that way, "off-the-shelf" bivariate distributions won't do, nor will the postulation of a purely non-linear relationship.
This is why Copulas is perhaps the way to go, as a comment suggested since, from this perspective, they allow us a systematic way to model dependence with any marginal distributions. This is important, because when looking at data, we can more easily describe a distribution for each data series separately, and it is convenient here to call on our stock of well-known and studied marginal distribution families (and each variable may appear to have a marginal that belongs to a different family). Their joint distributions may be non-standard and so non already studied. Then we look at Copulas to describe the dependence.
|
Relation between covariance and joint distribution
|
I would ask the opposite question: what is the implications of zero covariance for any surviving dependence? The two variables can certainly be stochastically dependent even though their covariance is
|
Relation between covariance and joint distribution
I would ask the opposite question: what is the implications of zero covariance for any surviving dependence? The two variables can certainly be stochastically dependent even though their covariance is zero, but what kind of dependencies, and what kind of bivariate joint distributions, are excluded if covariance is zero?
Some examples:
a) Many-many "named" bivariate continuous joint distributions (i.e. joint distributions where the two marginals belong to the same family).
b) Bivariate continuous distributions of the Farlie-Gumbel-Morgenstern family
$$H_{X,Y}(x,y)=F_X(x)G_Y(y)\left(1+\alpha\big(1-F_X(x)\big)\big(1-F_Y(y)\big)\right), \;\; \alpha <1$$
for two random variables with arbitrary marginal distribution functions $F_X(x)$ and $G_y(y)$. Here $\alpha =0$ is necessary and sufficient for zero covariance and stochastic independence. So here you cannot have the one without the other.
c) Finally one must remember that although covariance is usually described as "reflecting the "linear" dependence among two variables", this may mislead because when a random variable $X$ is a pure non-linear function of another one $Y$, almost always their covariance will be non-zero. Consider a very simple case, let
$$X = Y^2 \implies \text{Cov}(X,Y) = E(XY) - E(X)E(Y) = E(Y^3) - E(Y^2)E(Y)$$
This in general won't be zero.
etc. Certainly, infinite ways to model stochastic dependence with zero covariance do exist, but the above shows that if one wants to go that way, "off-the-shelf" bivariate distributions won't do, nor will the postulation of a purely non-linear relationship.
This is why Copulas is perhaps the way to go, as a comment suggested since, from this perspective, they allow us a systematic way to model dependence with any marginal distributions. This is important, because when looking at data, we can more easily describe a distribution for each data series separately, and it is convenient here to call on our stock of well-known and studied marginal distribution families (and each variable may appear to have a marginal that belongs to a different family). Their joint distributions may be non-standard and so non already studied. Then we look at Copulas to describe the dependence.
|
Relation between covariance and joint distribution
I would ask the opposite question: what is the implications of zero covariance for any surviving dependence? The two variables can certainly be stochastically dependent even though their covariance is
|
42,764
|
Can I get a Cholesky decomposition from the inverse of a matrix?
|
You can avoid inverting the matrix by generating draws by means of the eigendecomposition method. According to this method, the draws are generated by doing this product:
$$
(V D)^\top X^\top \,,
$$
where $V$ is the eigenvectors of the matrix, $D$ is a diagonal
matrix containing the square roots of the eigenvalues and
$X$ is a matrix containing draws from the standard univariate
$N(0,1)$ distribution.
It is straightforward to adapt this method and avoid recovering the original
covariance matrix by using these results: 1) the eigenvalues of a matrix $A$ are the reciprocal of the eigenvalues of its inverse $A^{-1}$; 2) the eigenvectors of a matrix A are also eigenvectors of its inverse $A^{-1}$.
Example:
Let's say that the original covariance matrix is the following:
$$
A = \left[
\begin{array}{rrr}
1 & 0.8 & -0.4 \\
0.8 & 2 & 0.3 \\
-0.4 & 0.3 & 3
\end{array}
\right] \,.
$$
But you have the inverse of this matrix, $B=A^{-1}$:
$$
A^{-1}= B = \left[
\begin{array}{rrr}
1.699 & -0.725 & 0.299 \\
-0.725 & 0.817 & -0.178 \\
0.299 & -0.178 & 0.391
\end{array}
\right] \,.
$$
The eigendecomposition method based on the original matrix $A$
yields the following covariance matrix for a sample of draws:
A <- rbind(c(1,0.8,-0.4), c(0.8,2,0.3), c(-0.4,0.3,3))
e1 <- eigen(A, symmetric=TRUE)
set.seed(1)
X <- matrix(rnorm(5000*ncol(A)), ncol=ncol(A))
draws1 <- t(e1$vectors %*% sqrt(diag(e1$values)) %*% t(X))
draws1.cov <- cov(draws1)
draws1.cov
# [,1] [,2] [,3]
#[1,] 0.9765023 0.8030752 -0.3970233
#[2,] 0.8030752 1.9941052 0.3229827
#[3,] -0.3970233 0.3229827 3.1689348
Using the matrix that you have (the inverse of A), you just need to
invert the eigenvalues:
B <- solve(A)
e2 <- eigen(B, symmetric=TRUE)
e2$values <- 1/e2$values
draws2 <- t(e2$vectors %*% sqrt(diag(e2$values)) %*% t(X))
draws2.cov <- cov(draws2)
draws2.cov
# [,1] [,2] [,3]
#[1,] 0.9765023 0.8030752 -0.3970233
#[2,] 0.8030752 1.9941052 0.3229827
#[3,] -0.3970233 0.3229827 3.1689348
A covariance matrix closely matching the original one is obtained and we didn't need to invert B in order to recover the original covariance matrix A.
A small simulation to check the validity of this approach:
set.seed(3)
niter <- 1000
m <- matrix(0, nrow=ncol(A), ncol=ncol(A))
for (i in seq_len(niter))
{
X <- matrix(rnorm(5000*ncol(A)), ncol=ncol(A))
draws2 <- t(e2$vectors %*% sqrt(diag(e2$values)) %*% t(X))
m <- m + cov(draws2)
}
m/niter
# average covariance matrix
# [,1] [,2] [,3]
#[1,] 1.0005129 0.7995872 -0.4005644
#[2,] 0.7995872 1.9993231 0.2990850
#[3,] -0.4005644 0.2990850 2.9957277
# original covariance matrix 'A'
# [,1] [,2] [,3]
#[1,] 1.0 0.8 -0.4
#[2,] 0.8 2.0 0.3
#[3,] -0.4 0.3 3.0
We can see that the covariance matrix of the draws are on average very close to the original covariance matrix A.
|
Can I get a Cholesky decomposition from the inverse of a matrix?
|
You can avoid inverting the matrix by generating draws by means of the eigendecomposition method. According to this method, the draws are generated by doing this product:
$$
(V D)^\top X^\top \,,
$$
w
|
Can I get a Cholesky decomposition from the inverse of a matrix?
You can avoid inverting the matrix by generating draws by means of the eigendecomposition method. According to this method, the draws are generated by doing this product:
$$
(V D)^\top X^\top \,,
$$
where $V$ is the eigenvectors of the matrix, $D$ is a diagonal
matrix containing the square roots of the eigenvalues and
$X$ is a matrix containing draws from the standard univariate
$N(0,1)$ distribution.
It is straightforward to adapt this method and avoid recovering the original
covariance matrix by using these results: 1) the eigenvalues of a matrix $A$ are the reciprocal of the eigenvalues of its inverse $A^{-1}$; 2) the eigenvectors of a matrix A are also eigenvectors of its inverse $A^{-1}$.
Example:
Let's say that the original covariance matrix is the following:
$$
A = \left[
\begin{array}{rrr}
1 & 0.8 & -0.4 \\
0.8 & 2 & 0.3 \\
-0.4 & 0.3 & 3
\end{array}
\right] \,.
$$
But you have the inverse of this matrix, $B=A^{-1}$:
$$
A^{-1}= B = \left[
\begin{array}{rrr}
1.699 & -0.725 & 0.299 \\
-0.725 & 0.817 & -0.178 \\
0.299 & -0.178 & 0.391
\end{array}
\right] \,.
$$
The eigendecomposition method based on the original matrix $A$
yields the following covariance matrix for a sample of draws:
A <- rbind(c(1,0.8,-0.4), c(0.8,2,0.3), c(-0.4,0.3,3))
e1 <- eigen(A, symmetric=TRUE)
set.seed(1)
X <- matrix(rnorm(5000*ncol(A)), ncol=ncol(A))
draws1 <- t(e1$vectors %*% sqrt(diag(e1$values)) %*% t(X))
draws1.cov <- cov(draws1)
draws1.cov
# [,1] [,2] [,3]
#[1,] 0.9765023 0.8030752 -0.3970233
#[2,] 0.8030752 1.9941052 0.3229827
#[3,] -0.3970233 0.3229827 3.1689348
Using the matrix that you have (the inverse of A), you just need to
invert the eigenvalues:
B <- solve(A)
e2 <- eigen(B, symmetric=TRUE)
e2$values <- 1/e2$values
draws2 <- t(e2$vectors %*% sqrt(diag(e2$values)) %*% t(X))
draws2.cov <- cov(draws2)
draws2.cov
# [,1] [,2] [,3]
#[1,] 0.9765023 0.8030752 -0.3970233
#[2,] 0.8030752 1.9941052 0.3229827
#[3,] -0.3970233 0.3229827 3.1689348
A covariance matrix closely matching the original one is obtained and we didn't need to invert B in order to recover the original covariance matrix A.
A small simulation to check the validity of this approach:
set.seed(3)
niter <- 1000
m <- matrix(0, nrow=ncol(A), ncol=ncol(A))
for (i in seq_len(niter))
{
X <- matrix(rnorm(5000*ncol(A)), ncol=ncol(A))
draws2 <- t(e2$vectors %*% sqrt(diag(e2$values)) %*% t(X))
m <- m + cov(draws2)
}
m/niter
# average covariance matrix
# [,1] [,2] [,3]
#[1,] 1.0005129 0.7995872 -0.4005644
#[2,] 0.7995872 1.9993231 0.2990850
#[3,] -0.4005644 0.2990850 2.9957277
# original covariance matrix 'A'
# [,1] [,2] [,3]
#[1,] 1.0 0.8 -0.4
#[2,] 0.8 2.0 0.3
#[3,] -0.4 0.3 3.0
We can see that the covariance matrix of the draws are on average very close to the original covariance matrix A.
|
Can I get a Cholesky decomposition from the inverse of a matrix?
You can avoid inverting the matrix by generating draws by means of the eigendecomposition method. According to this method, the draws are generated by doing this product:
$$
(V D)^\top X^\top \,,
$$
w
|
42,765
|
Can I calculate this Bayesian line without needing to simulate every point?
|
As Kahneman & Tversky explain, and as you have accurately stated, the plot converts a probability $p$ (on the horizontal axis) to odds, multiplies that by an odds ratio $\alpha = 5.44$, then converts it back to a probability $q$ plotted on the vertical axis. It shows how Bayes' Rule works for a fixed odds ratio applied to a full range of prior probabilities $p$ to produce the posterior probability $q$.
Because the odds of a probability $p$ in the range $(0,1)$ is
$$y = \frac{p}{1-p},$$
simple algebra finds the probability in terms of odds,
$$p = \frac{y}{1+y}.\tag{1}$$
Applying $(1)$ to an odds of $\alpha y$ instead of $y$ gives
$$q = \frac{\alpha y}{1 + \alpha y} = \frac{\alpha p}{1-p + \alpha p}.$$
That is the equation of the graph. It is what your program should calculate for any $p$ between $0$ and $1$. (Evidently, $p=0$ should correspond to $q=0$ and $p=1$ to $q=1$ to make the plots continuous at their endpoints.)
To illustrate, here are plots for various odds ratios greater than $1$:
|
Can I calculate this Bayesian line without needing to simulate every point?
|
As Kahneman & Tversky explain, and as you have accurately stated, the plot converts a probability $p$ (on the horizontal axis) to odds, multiplies that by an odds ratio $\alpha = 5.44$, then converts
|
Can I calculate this Bayesian line without needing to simulate every point?
As Kahneman & Tversky explain, and as you have accurately stated, the plot converts a probability $p$ (on the horizontal axis) to odds, multiplies that by an odds ratio $\alpha = 5.44$, then converts it back to a probability $q$ plotted on the vertical axis. It shows how Bayes' Rule works for a fixed odds ratio applied to a full range of prior probabilities $p$ to produce the posterior probability $q$.
Because the odds of a probability $p$ in the range $(0,1)$ is
$$y = \frac{p}{1-p},$$
simple algebra finds the probability in terms of odds,
$$p = \frac{y}{1+y}.\tag{1}$$
Applying $(1)$ to an odds of $\alpha y$ instead of $y$ gives
$$q = \frac{\alpha y}{1 + \alpha y} = \frac{\alpha p}{1-p + \alpha p}.$$
That is the equation of the graph. It is what your program should calculate for any $p$ between $0$ and $1$. (Evidently, $p=0$ should correspond to $q=0$ and $p=1$ to $q=1$ to make the plots continuous at their endpoints.)
To illustrate, here are plots for various odds ratios greater than $1$:
|
Can I calculate this Bayesian line without needing to simulate every point?
As Kahneman & Tversky explain, and as you have accurately stated, the plot converts a probability $p$ (on the horizontal axis) to odds, multiplies that by an odds ratio $\alpha = 5.44$, then converts
|
42,766
|
Why do I end up with a highly correlated matrix when I multiply two strictly positive random matrices?
|
It helps to think about the underlying meaning of the scores that result from each approach. Denote the binary user-item scores as $X_{hi}$ for user $h=1,...,H$ on item $i=1,...,I$ and the item-attribute scores as $T_{ia}$ for item $i=1,...,I$ and attribute $a=1,...,A$.
First consider using the dot product (without normalization). The score on attribute $a$ for user $i$ is $\sum_{i=1}^I X_{hi} T_{ia}$, which is the sum of the scores on attribute $a$ for all items purchased by user $h$. The scores on the $A$ attributes will be correlated because they are driven in part by the number of items purchased by user $h$.
library(corrplot)
# randomly generate strictly positive matrices
item_attributes <- matrix(runif(100000, min=0, max=1),1000,10)
users_items <- matrix(sample(0:1, 10000*1000, rep=T, prob=c(0.95, 0.05)),10000,1000)
# dotproduct
mat_prod <- users_items %*% item_attributes
corrplot(cor(mat_prod), main='\ndot product')
Next consider taking the L1 norm of the user-item scores (but leaving the item-attribute scores as is):
item_attributes_l1 <- t(t(item_attributes)/abs(apply(item_attributes,2,sum)))
users_items_l1 <- users_items / abs(apply(users_items,1,sum))
mat_prod_l1 <- users_items_l1 %*% item_attributes_l1
# corrplot(cor(mat_prod_l1), main='\nl1 norm')
mat_prod_l1A <- users_items_l1 %*% item_attributes
corrplot(cor(mat_prod_l1A), main='\nl1 norm - items only')
The score on attribute $a$ for user $i$ would then be mean of the scores on attribute $a$ across all items purchased by user $h$: $\frac{1}{n_a} \sum_{i=1}^I X_{hi} T_{ia}$, where $n_a = \sum_{i=1}^I X_{hi}$ is the number of items purchased. Taking the mean rather than the sum removes the correlation driven by the number of items purchased.
Next consider taking the L2 norm of the user-item scores (again, leaving the item-attribute scores as is):
item_attributes_l2 <- t(t(item_attributes)/sqrt(apply(item_attributes^2,2,sum)))
users_items_l2 <- users_items/sqrt(apply(users_items^2,1,sum))
mat_prod_l2 <- users_items_l2 %*% item_attributes_l2
# corrplot(cor(mat_prod_l2), main='\nl2 norm')
mat_prod_l2A <- users_items_l2 %*% item_attributes
corrplot(cor(mat_prod_l2A), main='\nl2 norm - items only')
The L2 norm of a set of $i$ binary items is $\sqrt{\sum_{i=1}^I X_{hi}^2} = \sqrt{\sum_{i=1}^I X_{hi}} = \sqrt{n_a}$, and so the score on attribute $a$ for user $i$ would then be $\sqrt{n_a}$ times the mean of the scores on attribute $a$ across all items puchased by user $h$: $\frac{1}{\sqrt{n_a}} \sum_{i=1}^I X_{hi} T_{ia}$. The scores on the $A$ attributes will still be correlated because they are all driven in part by $\sqrt{n_a}$.
Of these three options, it seems to me that taking the L1 norm on items (i.e., averaging the item-attribute scores instead of summing them) produces the most interpretable results. If total number of items purchased is of interest, then you can always calculate this and include it as a further predictor.
How best to norm the item-attribute scores seems to me to be an entirely separate question. Note that taking the L1 norm of the item-attribute scores amounts to assigning each item a "portion" of the total amount of an attribute, which might or might not make sense depending on context. Rather than taking the L2 norm, it might make more intuitive sense to re-scale the item-attribute scores to have mean 0 and SD 1, i.e.,
item_attributes_Z <- apply(item_attributes, 2, scale)
apply(item_attributes_Z, 2, mean)
apply(item_attributes_Z, 2, sd)
|
Why do I end up with a highly correlated matrix when I multiply two strictly positive random matrice
|
It helps to think about the underlying meaning of the scores that result from each approach. Denote the binary user-item scores as $X_{hi}$ for user $h=1,...,H$ on item $i=1,...,I$ and the item-attrib
|
Why do I end up with a highly correlated matrix when I multiply two strictly positive random matrices?
It helps to think about the underlying meaning of the scores that result from each approach. Denote the binary user-item scores as $X_{hi}$ for user $h=1,...,H$ on item $i=1,...,I$ and the item-attribute scores as $T_{ia}$ for item $i=1,...,I$ and attribute $a=1,...,A$.
First consider using the dot product (without normalization). The score on attribute $a$ for user $i$ is $\sum_{i=1}^I X_{hi} T_{ia}$, which is the sum of the scores on attribute $a$ for all items purchased by user $h$. The scores on the $A$ attributes will be correlated because they are driven in part by the number of items purchased by user $h$.
library(corrplot)
# randomly generate strictly positive matrices
item_attributes <- matrix(runif(100000, min=0, max=1),1000,10)
users_items <- matrix(sample(0:1, 10000*1000, rep=T, prob=c(0.95, 0.05)),10000,1000)
# dotproduct
mat_prod <- users_items %*% item_attributes
corrplot(cor(mat_prod), main='\ndot product')
Next consider taking the L1 norm of the user-item scores (but leaving the item-attribute scores as is):
item_attributes_l1 <- t(t(item_attributes)/abs(apply(item_attributes,2,sum)))
users_items_l1 <- users_items / abs(apply(users_items,1,sum))
mat_prod_l1 <- users_items_l1 %*% item_attributes_l1
# corrplot(cor(mat_prod_l1), main='\nl1 norm')
mat_prod_l1A <- users_items_l1 %*% item_attributes
corrplot(cor(mat_prod_l1A), main='\nl1 norm - items only')
The score on attribute $a$ for user $i$ would then be mean of the scores on attribute $a$ across all items purchased by user $h$: $\frac{1}{n_a} \sum_{i=1}^I X_{hi} T_{ia}$, where $n_a = \sum_{i=1}^I X_{hi}$ is the number of items purchased. Taking the mean rather than the sum removes the correlation driven by the number of items purchased.
Next consider taking the L2 norm of the user-item scores (again, leaving the item-attribute scores as is):
item_attributes_l2 <- t(t(item_attributes)/sqrt(apply(item_attributes^2,2,sum)))
users_items_l2 <- users_items/sqrt(apply(users_items^2,1,sum))
mat_prod_l2 <- users_items_l2 %*% item_attributes_l2
# corrplot(cor(mat_prod_l2), main='\nl2 norm')
mat_prod_l2A <- users_items_l2 %*% item_attributes
corrplot(cor(mat_prod_l2A), main='\nl2 norm - items only')
The L2 norm of a set of $i$ binary items is $\sqrt{\sum_{i=1}^I X_{hi}^2} = \sqrt{\sum_{i=1}^I X_{hi}} = \sqrt{n_a}$, and so the score on attribute $a$ for user $i$ would then be $\sqrt{n_a}$ times the mean of the scores on attribute $a$ across all items puchased by user $h$: $\frac{1}{\sqrt{n_a}} \sum_{i=1}^I X_{hi} T_{ia}$. The scores on the $A$ attributes will still be correlated because they are all driven in part by $\sqrt{n_a}$.
Of these three options, it seems to me that taking the L1 norm on items (i.e., averaging the item-attribute scores instead of summing them) produces the most interpretable results. If total number of items purchased is of interest, then you can always calculate this and include it as a further predictor.
How best to norm the item-attribute scores seems to me to be an entirely separate question. Note that taking the L1 norm of the item-attribute scores amounts to assigning each item a "portion" of the total amount of an attribute, which might or might not make sense depending on context. Rather than taking the L2 norm, it might make more intuitive sense to re-scale the item-attribute scores to have mean 0 and SD 1, i.e.,
item_attributes_Z <- apply(item_attributes, 2, scale)
apply(item_attributes_Z, 2, mean)
apply(item_attributes_Z, 2, sd)
|
Why do I end up with a highly correlated matrix when I multiply two strictly positive random matrice
It helps to think about the underlying meaning of the scores that result from each approach. Denote the binary user-item scores as $X_{hi}$ for user $h=1,...,H$ on item $i=1,...,I$ and the item-attrib
|
42,767
|
Magic Urn Problem
|
What am I missing?
How can it be that even though the equations that I used to solve the problem (and remember I didn't know the answer was going to be 3R/3B at that point) yield the correct answer even with the inclusion of an impossible scenario (2 pairs of red)?
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)= \frac{{n-2\choose 2}}{{2n-2\choose2}} + \frac{{n\choose 2}}{{2n-2\choose2}}$$
holds only for $n-2 \geq 2$ because $n\choose r$ is a non zero for $n \geq r$, so the solution $n=3$ to this equation is bounded by this constraint: $n \geq4$, which implies there is no solution.
Solution
P1, P2 represent the two pairs drawn.
Scenario1: {P1: RR, P2: BB}
Scenario2: {P1: RR, P2: RR}
Scenario3: {P1: BB, P2: RR}
Scenario4: {P1: BB, P2: BB}
$$0.5 = P(P2=BB|P1=RR) + P(P2=RR|P1=RR) + P(P2=RR|P1=BB) + P(P2=BB|P1=BB)$$
$\implies$
$$ 0.5 = 2*\big(P(P2=BB|P1=RR) + P(P2=RR|P1=RR) \big)$$
$\implies$
$$ \frac{1}{4} = \frac{n\choose 2}{{2n-2}\choose 2} + \frac{{n-2}\choose 2}{{2n-2}\choose 2}$$
$\implies$
$ 2n^2-7n+9 =0$
I get no solution for $n$
|
Magic Urn Problem
|
What am I missing?
How can it be that even though the equations that I used to solve the problem (and remember I didn't know the answer was going to be 3R/3B at that point) yield the correct answer
|
Magic Urn Problem
What am I missing?
How can it be that even though the equations that I used to solve the problem (and remember I didn't know the answer was going to be 3R/3B at that point) yield the correct answer even with the inclusion of an impossible scenario (2 pairs of red)?
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)= \frac{{n-2\choose 2}}{{2n-2\choose2}} + \frac{{n\choose 2}}{{2n-2\choose2}}$$
holds only for $n-2 \geq 2$ because $n\choose r$ is a non zero for $n \geq r$, so the solution $n=3$ to this equation is bounded by this constraint: $n \geq4$, which implies there is no solution.
Solution
P1, P2 represent the two pairs drawn.
Scenario1: {P1: RR, P2: BB}
Scenario2: {P1: RR, P2: RR}
Scenario3: {P1: BB, P2: RR}
Scenario4: {P1: BB, P2: BB}
$$0.5 = P(P2=BB|P1=RR) + P(P2=RR|P1=RR) + P(P2=RR|P1=BB) + P(P2=BB|P1=BB)$$
$\implies$
$$ 0.5 = 2*\big(P(P2=BB|P1=RR) + P(P2=RR|P1=RR) \big)$$
$\implies$
$$ \frac{1}{4} = \frac{n\choose 2}{{2n-2}\choose 2} + \frac{{n-2}\choose 2}{{2n-2}\choose 2}$$
$\implies$
$ 2n^2-7n+9 =0$
I get no solution for $n$
|
Magic Urn Problem
What am I missing?
How can it be that even though the equations that I used to solve the problem (and remember I didn't know the answer was going to be 3R/3B at that point) yield the correct answer
|
42,768
|
Magic Urn Problem
|
You miss that for n<4 this:
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)= \frac{{n-2\choose 2}}{{2n-2\choose2}} + \frac{{n\choose 2}}{{2n-2\choose2}}$$
does not hold.
First, for $n=1$ the problem makes no sense, because you cannot take 2 balls and then 2 more balls.
For $n=2$ or $n=3$, $p\,(2\,R\,|after\,Red\,pair)=0$ rather than $\frac{{n-2\choose 2}}{{2n-2\choose2}}$, so your formula should be
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)=\frac{{n\choose 2}}{{2n-2\choose2}}$$
which holds for n=3 but not for n=2.
|
Magic Urn Problem
|
You miss that for n<4 this:
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)= \frac{{n-2\choose 2}}{{2n-2\choose2}} + \frac{{n\choose 2}}{{2n-2\choose2}}$$
does not hold.
First, for $
|
Magic Urn Problem
You miss that for n<4 this:
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)= \frac{{n-2\choose 2}}{{2n-2\choose2}} + \frac{{n\choose 2}}{{2n-2\choose2}}$$
does not hold.
First, for $n=1$ the problem makes no sense, because you cannot take 2 balls and then 2 more balls.
For $n=2$ or $n=3$, $p\,(2\,R\,|after\,Red\,pair)=0$ rather than $\frac{{n-2\choose 2}}{{2n-2\choose2}}$, so your formula should be
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)=\frac{{n\choose 2}}{{2n-2\choose2}}$$
which holds for n=3 but not for n=2.
|
Magic Urn Problem
You miss that for n<4 this:
$$0.5 = p\,(2\,R\,|after\,Red\,pair)+p\,(2\,B\,|after\,Red\,pair)= \frac{{n-2\choose 2}}{{2n-2\choose2}} + \frac{{n\choose 2}}{{2n-2\choose2}}$$
does not hold.
First, for $
|
42,769
|
Magic Urn Problem
|
This may not be formal but I figured:
\begin{align}
\frac{(n-2)(n-3)}{(2n-2)(2n-3)} + \frac{(n)(n-1)}{(2n-2)(2n-3)} &= .50 \\[10pt]
\frac{(n-2)(n-3)+(n)(n-1)}{(2n-2)(2n-3)} &= .50
\end{align}
Solving for $n$, QED $n=3$.
So it starts with 3 of each color, i.e., 6 balls total.
|
Magic Urn Problem
|
This may not be formal but I figured:
\begin{align}
\frac{(n-2)(n-3)}{(2n-2)(2n-3)} + \frac{(n)(n-1)}{(2n-2)(2n-3)} &= .50 \\[10pt]
\frac{(n-2)(n-3)+(n)(n-1)}{(2n-2)(2n-3)} &= .50
\end{align}
Solving
|
Magic Urn Problem
This may not be formal but I figured:
\begin{align}
\frac{(n-2)(n-3)}{(2n-2)(2n-3)} + \frac{(n)(n-1)}{(2n-2)(2n-3)} &= .50 \\[10pt]
\frac{(n-2)(n-3)+(n)(n-1)}{(2n-2)(2n-3)} &= .50
\end{align}
Solving for $n$, QED $n=3$.
So it starts with 3 of each color, i.e., 6 balls total.
|
Magic Urn Problem
This may not be formal but I figured:
\begin{align}
\frac{(n-2)(n-3)}{(2n-2)(2n-3)} + \frac{(n)(n-1)}{(2n-2)(2n-3)} &= .50 \\[10pt]
\frac{(n-2)(n-3)+(n)(n-1)}{(2n-2)(2n-3)} &= .50
\end{align}
Solving
|
42,770
|
Magic Urn Problem
|
Let $n$ be the number of balls. Then solve:
$$
\left[\frac{\frac n 2 }{n-2} \right] \left[\frac{\frac n 2 - 1}{n-3} \right] = \frac 1 2
$$
|
Magic Urn Problem
|
Let $n$ be the number of balls. Then solve:
$$
\left[\frac{\frac n 2 }{n-2} \right] \left[\frac{\frac n 2 - 1}{n-3} \right] = \frac 1 2
$$
|
Magic Urn Problem
Let $n$ be the number of balls. Then solve:
$$
\left[\frac{\frac n 2 }{n-2} \right] \left[\frac{\frac n 2 - 1}{n-3} \right] = \frac 1 2
$$
|
Magic Urn Problem
Let $n$ be the number of balls. Then solve:
$$
\left[\frac{\frac n 2 }{n-2} \right] \left[\frac{\frac n 2 - 1}{n-3} \right] = \frac 1 2
$$
|
42,771
|
Comparing magnitude of coefficients in a logistic regression
|
The marginal effects from a logistic regression is the following:
The partial derivative essentially tells you the effect of a unit change in some variable x
The first part of the equation,, is always positive and would look like the curve below:
First thing to notice is that the marginal effect will depend on X. So normally we would evaluate the marginal effects at the mean. Having said that, regardless of where you evaluate the marginal effects
c > b implies that the balance has a higher effect on the probability of event than the age. (bcos the first part of that marginal effects equation is always positive)
|
Comparing magnitude of coefficients in a logistic regression
|
The marginal effects from a logistic regression is the following:
The partial derivative essentially tells you the effect of a unit change in some variable x
The first part of the equation,, is alwa
|
Comparing magnitude of coefficients in a logistic regression
The marginal effects from a logistic regression is the following:
The partial derivative essentially tells you the effect of a unit change in some variable x
The first part of the equation,, is always positive and would look like the curve below:
First thing to notice is that the marginal effect will depend on X. So normally we would evaluate the marginal effects at the mean. Having said that, regardless of where you evaluate the marginal effects
c > b implies that the balance has a higher effect on the probability of event than the age. (bcos the first part of that marginal effects equation is always positive)
|
Comparing magnitude of coefficients in a logistic regression
The marginal effects from a logistic regression is the following:
The partial derivative essentially tells you the effect of a unit change in some variable x
The first part of the equation,, is alwa
|
42,772
|
Comparing magnitude of coefficients in a logistic regression
|
I think you cannot. For a continuous variable such as Age, you can make the coefficient as big or small as you want, if you change your measurement unit(such as from second to 1000 years). For multiple regression you only can study the relation of one predictor variable with your outcome variable at one time and hold all other variable constant. I think you can compare the effect of variable on goodness of fit such as $R^2$, but I don't think you can compare coefficient directly.
|
Comparing magnitude of coefficients in a logistic regression
|
I think you cannot. For a continuous variable such as Age, you can make the coefficient as big or small as you want, if you change your measurement unit(such as from second to 1000 years). For mul
|
Comparing magnitude of coefficients in a logistic regression
I think you cannot. For a continuous variable such as Age, you can make the coefficient as big or small as you want, if you change your measurement unit(such as from second to 1000 years). For multiple regression you only can study the relation of one predictor variable with your outcome variable at one time and hold all other variable constant. I think you can compare the effect of variable on goodness of fit such as $R^2$, but I don't think you can compare coefficient directly.
|
Comparing magnitude of coefficients in a logistic regression
I think you cannot. For a continuous variable such as Age, you can make the coefficient as big or small as you want, if you change your measurement unit(such as from second to 1000 years). For mul
|
42,773
|
Approximating the distribution of a linear combination of beta-distributed independent random variables
|
If the skewness of the beta components are all low, then the absolute third moments should also be low*, and the normal approximation should tend to come in quite quickly (see the Berry-Esseen theorem for non-i.i.d. variates).
* I don't mean this comment as a general one, just in respect of beta variates. For example, if the skewness $\gamma_1$ of a beta variate is small the kurtosis is bounded above and below by $1 +$ a multiple of $\gamma_1^2$ (where both multiples are small), and I believe the absolute third moment of a standardized variate should be smaller than the fourth moment. Those two things together suggest a small third moment implies a small absolute third moment.
However, what we're dealing with "closeness" of in the theorem is cdfs, but bounding the difference in cdfs doesn't necessarily make whatever other properties you want like that for a normal; it may make more sense to identify what properties you're after and investigate those.
On the other hand, if the skewness is high, we would not expect a very rapid approach to normality; indeed, simulation easily establishes that skewness can remain in the standardized mean. For example, here's a histogram for 10000 simulations of standardized means of 20 beta(100,1) variates:
Anyway, these points may help you figure out better when you might just decide to work with normal approximation rather than the more complicated formulas.
|
Approximating the distribution of a linear combination of beta-distributed independent random variab
|
If the skewness of the beta components are all low, then the absolute third moments should also be low*, and the normal approximation should tend to come in quite quickly (see the Berry-Esseen theorem
|
Approximating the distribution of a linear combination of beta-distributed independent random variables
If the skewness of the beta components are all low, then the absolute third moments should also be low*, and the normal approximation should tend to come in quite quickly (see the Berry-Esseen theorem for non-i.i.d. variates).
* I don't mean this comment as a general one, just in respect of beta variates. For example, if the skewness $\gamma_1$ of a beta variate is small the kurtosis is bounded above and below by $1 +$ a multiple of $\gamma_1^2$ (where both multiples are small), and I believe the absolute third moment of a standardized variate should be smaller than the fourth moment. Those two things together suggest a small third moment implies a small absolute third moment.
However, what we're dealing with "closeness" of in the theorem is cdfs, but bounding the difference in cdfs doesn't necessarily make whatever other properties you want like that for a normal; it may make more sense to identify what properties you're after and investigate those.
On the other hand, if the skewness is high, we would not expect a very rapid approach to normality; indeed, simulation easily establishes that skewness can remain in the standardized mean. For example, here's a histogram for 10000 simulations of standardized means of 20 beta(100,1) variates:
Anyway, these points may help you figure out better when you might just decide to work with normal approximation rather than the more complicated formulas.
|
Approximating the distribution of a linear combination of beta-distributed independent random variab
If the skewness of the beta components are all low, then the absolute third moments should also be low*, and the normal approximation should tend to come in quite quickly (see the Berry-Esseen theorem
|
42,774
|
Berry-Esseen bound for binomial distribution
|
Please don't shoot me if this doesn't work (well) or addresses a different problem than you want.
If your goal is to get the best asymptotic approximation of the Binomial, as opposed to getting the best Berry Esseen bound for its own sake, then consider using an Edgeworth Expansion http://projecteuclid.org/download/pdf_1/euclid.lnms/1215468238 . You may find a Computer Algebra System such as MAPLE to be of value in series manipulation.
|
Berry-Esseen bound for binomial distribution
|
Please don't shoot me if this doesn't work (well) or addresses a different problem than you want.
If your goal is to get the best asymptotic approximation of the Binomial, as opposed to getting the be
|
Berry-Esseen bound for binomial distribution
Please don't shoot me if this doesn't work (well) or addresses a different problem than you want.
If your goal is to get the best asymptotic approximation of the Binomial, as opposed to getting the best Berry Esseen bound for its own sake, then consider using an Edgeworth Expansion http://projecteuclid.org/download/pdf_1/euclid.lnms/1215468238 . You may find a Computer Algebra System such as MAPLE to be of value in series manipulation.
|
Berry-Esseen bound for binomial distribution
Please don't shoot me if this doesn't work (well) or addresses a different problem than you want.
If your goal is to get the best asymptotic approximation of the Binomial, as opposed to getting the be
|
42,775
|
testing contrast in two-way ANOVA using multcomp
|
This can be solved by using the ingenious combination of afex with lsmeans (and also multcomp if one desires so, but this is usually not necessary). Furthermore, thanks to afex functionality to aggregate automatically, dplyr is not needed.
library(afex)
require(lsmeans)
require(multcomp)
data(obk.long)
# Step 1: set up the model using afex
# but use return = "aov" to obtain an object lsmeans can handle.
fit <- aov.car(value~treatment*gender + Error(id),data=obk.long, return = "aov")
# Step 2: set up reference grid on which we
# we can test any type of tests using lsmeans functionality:
(ref1 <- lsmeans(fit, c("treatment", "gender")))
## treatment gender lsmean SE df lower.CL upper.CL
## control F 4.333333 0.8718860 10 2.390650 6.276016
## A F 4.500000 0.8718860 10 2.557317 6.442683
## B F 5.833333 0.6165165 10 4.459649 7.207018
## control M 4.111111 0.7118919 10 2.524917 5.697305
## A M 8.000000 0.8718860 10 6.057317 9.942683
## B M 6.222222 0.7118919 10 4.636028 7.808416
##
## Confidence level used: 0.95
# we simply define the contrasts as a list on the reference grid:
c_list <- list(c1 = c(0, -1, 1, 0, 0, 0),
c2 = c(0, -0.5, 0.5, 0, -0.5, 0.5))
# because we want to control for Type I errors we test this using
# the Bonferroni-Holm correction
summary(contrast(ref1, c_list), adjust = "holm")
## contrast estimate SE df t.ratio p.value
## c1 1.3333333 1.0678379 10 1.249 0.4805
## c2 -0.2222222 0.7757662 10 -0.286 0.7804
##
## P value adjustment: holm method for 2 tests
# alternatively, we can pass it to multcomp for even cooler corrections:
summary(as.glht(contrast(ref1, c_list)), test = adjusted("free"))
## Note: df set to 10
##
## Simultaneous Tests for General Linear Hypotheses
##
## Linear Hypotheses:
## Estimate Std. Error t value Pr(>|t|)
## c1 == 0 1.3333 1.0678 1.249 0.359
## c2 == 0 -0.2222 0.7758 -0.286 0.780
## (Adjusted p values reported -- free method)
Note that the first contrast (c1: A and B when gender = F) correspond to your first result while the latter one does not. You must have made an error.
The second contrast you wish can also be obtained easier (simply ignore the other two rows):
pairs(lsmeans(fit, "treatment"), adjust = "none")
## NOTE: Results may be misleading due to involvement in interactions
## contrast estimate SE df t.ratio p.value
## control - A -2.0277778 0.8347673 10 -2.429 0.0355
## control - B -1.8055556 0.7338014 10 -2.461 0.0336
## A - B 0.2222222 0.7757662 10 0.286 0.7804
##
## Results are averaged over the levels of: gender
|
testing contrast in two-way ANOVA using multcomp
|
This can be solved by using the ingenious combination of afex with lsmeans (and also multcomp if one desires so, but this is usually not necessary). Furthermore, thanks to afex functionality to aggreg
|
testing contrast in two-way ANOVA using multcomp
This can be solved by using the ingenious combination of afex with lsmeans (and also multcomp if one desires so, but this is usually not necessary). Furthermore, thanks to afex functionality to aggregate automatically, dplyr is not needed.
library(afex)
require(lsmeans)
require(multcomp)
data(obk.long)
# Step 1: set up the model using afex
# but use return = "aov" to obtain an object lsmeans can handle.
fit <- aov.car(value~treatment*gender + Error(id),data=obk.long, return = "aov")
# Step 2: set up reference grid on which we
# we can test any type of tests using lsmeans functionality:
(ref1 <- lsmeans(fit, c("treatment", "gender")))
## treatment gender lsmean SE df lower.CL upper.CL
## control F 4.333333 0.8718860 10 2.390650 6.276016
## A F 4.500000 0.8718860 10 2.557317 6.442683
## B F 5.833333 0.6165165 10 4.459649 7.207018
## control M 4.111111 0.7118919 10 2.524917 5.697305
## A M 8.000000 0.8718860 10 6.057317 9.942683
## B M 6.222222 0.7118919 10 4.636028 7.808416
##
## Confidence level used: 0.95
# we simply define the contrasts as a list on the reference grid:
c_list <- list(c1 = c(0, -1, 1, 0, 0, 0),
c2 = c(0, -0.5, 0.5, 0, -0.5, 0.5))
# because we want to control for Type I errors we test this using
# the Bonferroni-Holm correction
summary(contrast(ref1, c_list), adjust = "holm")
## contrast estimate SE df t.ratio p.value
## c1 1.3333333 1.0678379 10 1.249 0.4805
## c2 -0.2222222 0.7757662 10 -0.286 0.7804
##
## P value adjustment: holm method for 2 tests
# alternatively, we can pass it to multcomp for even cooler corrections:
summary(as.glht(contrast(ref1, c_list)), test = adjusted("free"))
## Note: df set to 10
##
## Simultaneous Tests for General Linear Hypotheses
##
## Linear Hypotheses:
## Estimate Std. Error t value Pr(>|t|)
## c1 == 0 1.3333 1.0678 1.249 0.359
## c2 == 0 -0.2222 0.7758 -0.286 0.780
## (Adjusted p values reported -- free method)
Note that the first contrast (c1: A and B when gender = F) correspond to your first result while the latter one does not. You must have made an error.
The second contrast you wish can also be obtained easier (simply ignore the other two rows):
pairs(lsmeans(fit, "treatment"), adjust = "none")
## NOTE: Results may be misleading due to involvement in interactions
## contrast estimate SE df t.ratio p.value
## control - A -2.0277778 0.8347673 10 -2.429 0.0355
## control - B -1.8055556 0.7338014 10 -2.461 0.0336
## A - B 0.2222222 0.7757662 10 0.286 0.7804
##
## Results are averaged over the levels of: gender
|
testing contrast in two-way ANOVA using multcomp
This can be solved by using the ingenious combination of afex with lsmeans (and also multcomp if one desires so, but this is usually not necessary). Furthermore, thanks to afex functionality to aggreg
|
42,776
|
Visualizing SVM results
|
Usually a dimension reduction technique is employed to visualize fit on many variables.
Usually again SVD is used to reduce dimensions and keep 2 components, and visualize.
Here's how it might look like -
Note that the x and y axes are the top 2 components of the SVD decomposition.
I haven't used R much lately, so I used python for creating the picture above.
from sklearn.decomposition import TruncatedSVD
from sklearn.svm import SVC
from sklearn.datasets import load_iris
# To visualize the actual data in top 2 dimensions
iris=load_iris()
x,y=iris.data,iris.target
model=SVC().fit(x,y)
predicted=model.predict(x)
svd=TruncatedSVD().fit_transform(x)
from matplotlib import pyplot as plt
plt.figure(figsize=(16,6))
plt.subplot(1,2,0)
plt.title('Actual data, with errors highlighted')
colors=['r','g','b']
for t in [0,1,2]:
plt.plot(svd[y==t][:,0],svd[y==t][:,1],colors[t]+'+')
errX,errY=svd[predicted!=y],y[predicted!=y]
for t in [0,1,2]:
plt.plot(errX[errY==t][:,0],errX[errY==t][:,1],colors[t]+'o')
# To visualize the SVM classifier across
import numpy as np
density=15
domain=[np.linspace(min(x[:,i]),max(x[:,i]),num=density*4 if i==2 else density) for i in range(4)]
from itertools import product
allxs=list(product(*domain))
allys=model.predict(allxs)
allxs_svd=TruncatedSVD().fit_transform(allxs)
plt.subplot(1,2,1)
plt.title('Prediction space reduced to top two SVD\'s')
plt.ylim(-3,3)
for t in [0,1,2]:
plt.scatter(allxs_svd[allys==t][:,0],allxs_svd[allys==t][:,1],color=colors[t],alpha=0.2/density,edgecolor='None')
|
Visualizing SVM results
|
Usually a dimension reduction technique is employed to visualize fit on many variables.
Usually again SVD is used to reduce dimensions and keep 2 components, and visualize.
Here's how it might look li
|
Visualizing SVM results
Usually a dimension reduction technique is employed to visualize fit on many variables.
Usually again SVD is used to reduce dimensions and keep 2 components, and visualize.
Here's how it might look like -
Note that the x and y axes are the top 2 components of the SVD decomposition.
I haven't used R much lately, so I used python for creating the picture above.
from sklearn.decomposition import TruncatedSVD
from sklearn.svm import SVC
from sklearn.datasets import load_iris
# To visualize the actual data in top 2 dimensions
iris=load_iris()
x,y=iris.data,iris.target
model=SVC().fit(x,y)
predicted=model.predict(x)
svd=TruncatedSVD().fit_transform(x)
from matplotlib import pyplot as plt
plt.figure(figsize=(16,6))
plt.subplot(1,2,0)
plt.title('Actual data, with errors highlighted')
colors=['r','g','b']
for t in [0,1,2]:
plt.plot(svd[y==t][:,0],svd[y==t][:,1],colors[t]+'+')
errX,errY=svd[predicted!=y],y[predicted!=y]
for t in [0,1,2]:
plt.plot(errX[errY==t][:,0],errX[errY==t][:,1],colors[t]+'o')
# To visualize the SVM classifier across
import numpy as np
density=15
domain=[np.linspace(min(x[:,i]),max(x[:,i]),num=density*4 if i==2 else density) for i in range(4)]
from itertools import product
allxs=list(product(*domain))
allys=model.predict(allxs)
allxs_svd=TruncatedSVD().fit_transform(allxs)
plt.subplot(1,2,1)
plt.title('Prediction space reduced to top two SVD\'s')
plt.ylim(-3,3)
for t in [0,1,2]:
plt.scatter(allxs_svd[allys==t][:,0],allxs_svd[allys==t][:,1],color=colors[t],alpha=0.2/density,edgecolor='None')
|
Visualizing SVM results
Usually a dimension reduction technique is employed to visualize fit on many variables.
Usually again SVD is used to reduce dimensions and keep 2 components, and visualize.
Here's how it might look li
|
42,777
|
Mixed effects - how to model random scaling of observations?
|
There is an identifiability issue. Suppose $\beta$ and $u$ work. Then, $\beta/2$ and $2u$ will work as well.
The basic solution is to build standard curves for your sensors and run them with your experiments. Then, your raw measurements would be transformed into measurements on the same scale.
Failing that, you will need to let one sensor be the "reference sensor". The other sensors will have variability as a scale factor relative to the reference sensor.
Then, your model is nonlinear. Without linearizing it somehow you probably should not try to fit it using linear model methods. Instead, you should use some sort of nonlinear model method.
Here is an example using nonlinear least squares. In this example, I'm using continuous variates, though the same approach is useful for factors by using effects coding. It is just easier to demonstrate using continuous variates.
# Gin up some data.
set.seed(838383)
Sensor <- data.frame(
X1 = rnorm(150),
X2 = rnorm(150),
X3 = rnorm(150),
U1 = c(rep(1, 50), rep(0, 50), rep(0, 50)),
U2 = c(rep(0, 50), rep(1, 50), rep(0, 50)),
U3 = c(rep(0, 50), rep(0, 50), rep(1, 50))
)
# Set some sensor gains and beta values. Note
# that the first sensor is the reference sensor.
g <- c(1, 2, 4)
b <- c(-1, 1, 3)
# Simulate a simple version. Careful of factors
# with numeric values.
Y <- with(
Sensor,
(b[1]*X1 + b[2]*X2 + b[3]*X3) * (g[1]*U1 + g[2]*U2 + g[3]*U3)
)
e <- rnorm(150)
Sensor$Y <- Y + e
This duplicates the model you show above, with an additive error after the nonlinear transformation. Note this also assumes a zero intercept.
In this example, the first sensor is the reference sensor. The second and third sensors produce measurements that differ by a scale factor of 2 and 4 respectively from the measurement that the first sensor would produce.
# Fit a model using nonlinear least squares.
library(nlme)
f <- function(b1, b2, b3, X1, X2, X3, g2, g3, U1, U2, U3) {
(b1*X1 + b2*X2 + b3*X3) * (1*U1 + g2*U2 + g3*U3)
}
fit <- nls(
formula = Y ~ f(b1, b2, b3, X1, X2, X3, g2, g3, U1, U2, U3),
start= c(b1=1, b2=2.4, b3=7, g2=2, g3=3),
data = Sensor
)
summary(fit)
#Formula: Y ~ f(b1, b2, b3, X1, X2, X3, g2, g3, U1, U2, U3)
#
#Parameters:
# Estimate Std. Error t value Pr(>|t|)
#b1 -1.02810 0.06005 -17.12 <2e-16 ***
#b2 1.01436 0.06237 16.26 <2e-16 ***
#b3 3.12400 0.15062 20.74 <2e-16 ***
#g2 1.85447 0.09965 18.61 <2e-16 ***
#g3 3.86931 0.19169 20.18 <2e-16 ***
#---
#Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#Residual standard error: 1.106 on 145 degrees of freedom
#
#Number of iterations to convergence: 5
#Achieved convergence tolerance: 1.782e-07
Pretty good agreement all around with the $\beta$ coefficients, the sensor scale factors, and the error variance.
|
Mixed effects - how to model random scaling of observations?
|
There is an identifiability issue. Suppose $\beta$ and $u$ work. Then, $\beta/2$ and $2u$ will work as well.
The basic solution is to build standard curves for your sensors and run them with your e
|
Mixed effects - how to model random scaling of observations?
There is an identifiability issue. Suppose $\beta$ and $u$ work. Then, $\beta/2$ and $2u$ will work as well.
The basic solution is to build standard curves for your sensors and run them with your experiments. Then, your raw measurements would be transformed into measurements on the same scale.
Failing that, you will need to let one sensor be the "reference sensor". The other sensors will have variability as a scale factor relative to the reference sensor.
Then, your model is nonlinear. Without linearizing it somehow you probably should not try to fit it using linear model methods. Instead, you should use some sort of nonlinear model method.
Here is an example using nonlinear least squares. In this example, I'm using continuous variates, though the same approach is useful for factors by using effects coding. It is just easier to demonstrate using continuous variates.
# Gin up some data.
set.seed(838383)
Sensor <- data.frame(
X1 = rnorm(150),
X2 = rnorm(150),
X3 = rnorm(150),
U1 = c(rep(1, 50), rep(0, 50), rep(0, 50)),
U2 = c(rep(0, 50), rep(1, 50), rep(0, 50)),
U3 = c(rep(0, 50), rep(0, 50), rep(1, 50))
)
# Set some sensor gains and beta values. Note
# that the first sensor is the reference sensor.
g <- c(1, 2, 4)
b <- c(-1, 1, 3)
# Simulate a simple version. Careful of factors
# with numeric values.
Y <- with(
Sensor,
(b[1]*X1 + b[2]*X2 + b[3]*X3) * (g[1]*U1 + g[2]*U2 + g[3]*U3)
)
e <- rnorm(150)
Sensor$Y <- Y + e
This duplicates the model you show above, with an additive error after the nonlinear transformation. Note this also assumes a zero intercept.
In this example, the first sensor is the reference sensor. The second and third sensors produce measurements that differ by a scale factor of 2 and 4 respectively from the measurement that the first sensor would produce.
# Fit a model using nonlinear least squares.
library(nlme)
f <- function(b1, b2, b3, X1, X2, X3, g2, g3, U1, U2, U3) {
(b1*X1 + b2*X2 + b3*X3) * (1*U1 + g2*U2 + g3*U3)
}
fit <- nls(
formula = Y ~ f(b1, b2, b3, X1, X2, X3, g2, g3, U1, U2, U3),
start= c(b1=1, b2=2.4, b3=7, g2=2, g3=3),
data = Sensor
)
summary(fit)
#Formula: Y ~ f(b1, b2, b3, X1, X2, X3, g2, g3, U1, U2, U3)
#
#Parameters:
# Estimate Std. Error t value Pr(>|t|)
#b1 -1.02810 0.06005 -17.12 <2e-16 ***
#b2 1.01436 0.06237 16.26 <2e-16 ***
#b3 3.12400 0.15062 20.74 <2e-16 ***
#g2 1.85447 0.09965 18.61 <2e-16 ***
#g3 3.86931 0.19169 20.18 <2e-16 ***
#---
#Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#Residual standard error: 1.106 on 145 degrees of freedom
#
#Number of iterations to convergence: 5
#Achieved convergence tolerance: 1.782e-07
Pretty good agreement all around with the $\beta$ coefficients, the sensor scale factors, and the error variance.
|
Mixed effects - how to model random scaling of observations?
There is an identifiability issue. Suppose $\beta$ and $u$ work. Then, $\beta/2$ and $2u$ will work as well.
The basic solution is to build standard curves for your sensors and run them with your e
|
42,778
|
split-split plot design with unbalanced repeated measures in lme4 or nlme (SAS translation)
|
The one practical thing I can tell you is that the denominator degrees-of-freedom business is available for lme4 models, using the pbkrtest package or various wrappers for it: see the ?pvalues man page from recent versions of lme4.
library("lme4")
options(contrasts=c("contr.sum","contr.poly"))
m1 <- lmer(output~0+mainplot*subplot*time +
(time|mainplot:subplot:subsubplot),
data=mockset)
library("car")
Anova(m1,type="3",test="F")
For the rest, I pretty much just have to agree with you. I'm a bit surprised by your colleague's specification -- I independently reconstructed your R-style syntax before I saw yours, and it doesn't make much sense to me to treat terms involving subsubplot (bottle) as fixed, or to treat mainplot*subplot as random (for both philosophical and practical, i.e. insufficient-replication, reasons). Perhaps she could chime in?
|
split-split plot design with unbalanced repeated measures in lme4 or nlme (SAS translation)
|
The one practical thing I can tell you is that the denominator degrees-of-freedom business is available for lme4 models, using the pbkrtest package or various wrappers for it: see the ?pvalues man pag
|
split-split plot design with unbalanced repeated measures in lme4 or nlme (SAS translation)
The one practical thing I can tell you is that the denominator degrees-of-freedom business is available for lme4 models, using the pbkrtest package or various wrappers for it: see the ?pvalues man page from recent versions of lme4.
library("lme4")
options(contrasts=c("contr.sum","contr.poly"))
m1 <- lmer(output~0+mainplot*subplot*time +
(time|mainplot:subplot:subsubplot),
data=mockset)
library("car")
Anova(m1,type="3",test="F")
For the rest, I pretty much just have to agree with you. I'm a bit surprised by your colleague's specification -- I independently reconstructed your R-style syntax before I saw yours, and it doesn't make much sense to me to treat terms involving subsubplot (bottle) as fixed, or to treat mainplot*subplot as random (for both philosophical and practical, i.e. insufficient-replication, reasons). Perhaps she could chime in?
|
split-split plot design with unbalanced repeated measures in lme4 or nlme (SAS translation)
The one practical thing I can tell you is that the denominator degrees-of-freedom business is available for lme4 models, using the pbkrtest package or various wrappers for it: see the ?pvalues man pag
|
42,779
|
Which samples are used in random forests for calculating variable importance?
|
After each tree is grown, the values of a given predictor are randomly permuted in the out-of-bag sample (the one third of unique observations that are not part of the bootstrap sample) and the prediction error of the tree on the modified OOB sample is compared with the prediction error of the tree on the untouched OOB sample.
This process is repeated for all input variables, and averaged over all trees. Finally, variables are given scores proportional to the overall decrease in accuracy that their permutation induced.
The most important variables are the ones leading to the greatest losses in accuracy when “noised-up” (see Breiman 2001).
In short, you do have independent samples at the tree level. The importance of a given variable is first computed at the tree level, and the scores are aggregated over all trees to obtain the final, global importance score for the variable.
|
Which samples are used in random forests for calculating variable importance?
|
After each tree is grown, the values of a given predictor are randomly permuted in the out-of-bag sample (the one third of unique observations that are not part of the bootstrap sample) and the predic
|
Which samples are used in random forests for calculating variable importance?
After each tree is grown, the values of a given predictor are randomly permuted in the out-of-bag sample (the one third of unique observations that are not part of the bootstrap sample) and the prediction error of the tree on the modified OOB sample is compared with the prediction error of the tree on the untouched OOB sample.
This process is repeated for all input variables, and averaged over all trees. Finally, variables are given scores proportional to the overall decrease in accuracy that their permutation induced.
The most important variables are the ones leading to the greatest losses in accuracy when “noised-up” (see Breiman 2001).
In short, you do have independent samples at the tree level. The importance of a given variable is first computed at the tree level, and the scores are aggregated over all trees to obtain the final, global importance score for the variable.
|
Which samples are used in random forests for calculating variable importance?
After each tree is grown, the values of a given predictor are randomly permuted in the out-of-bag sample (the one third of unique observations that are not part of the bootstrap sample) and the predic
|
42,780
|
Does linear regression assume all variables (predictors and response) to be multivariate normal? [duplicate]
|
As a general assertation this is just plain wrong, I agree complexly with @Glen_b. For a review of the classical linear model assumptions see this
But essentially normality of the error term ensures, that the distribution of the $\hat{\beta}_k$ is exactly normal. Instead of just being approximated by the t distribution. Note the comment below, about the distribution when the standard error is estimated.
I have no idea why the webpage, would say, what is says. To say why normality is not needed, you could just derive the estimator your self (or look it up online). OLS is (must typically) derived by methods of moments - normality enters no where in those equations.
Perhaps it is a misunderstanding of the maximum likehood method, at least the OLS MLE assumes normality. However, it is not needed since the estimates are entirely robust to this assumption (quasi-MLE).
|
Does linear regression assume all variables (predictors and response) to be multivariate normal? [du
|
As a general assertation this is just plain wrong, I agree complexly with @Glen_b. For a review of the classical linear model assumptions see this
But essentially normality of the error term ensures,
|
Does linear regression assume all variables (predictors and response) to be multivariate normal? [duplicate]
As a general assertation this is just plain wrong, I agree complexly with @Glen_b. For a review of the classical linear model assumptions see this
But essentially normality of the error term ensures, that the distribution of the $\hat{\beta}_k$ is exactly normal. Instead of just being approximated by the t distribution. Note the comment below, about the distribution when the standard error is estimated.
I have no idea why the webpage, would say, what is says. To say why normality is not needed, you could just derive the estimator your self (or look it up online). OLS is (must typically) derived by methods of moments - normality enters no where in those equations.
Perhaps it is a misunderstanding of the maximum likehood method, at least the OLS MLE assumes normality. However, it is not needed since the estimates are entirely robust to this assumption (quasi-MLE).
|
Does linear regression assume all variables (predictors and response) to be multivariate normal? [du
As a general assertation this is just plain wrong, I agree complexly with @Glen_b. For a review of the classical linear model assumptions see this
But essentially normality of the error term ensures,
|
42,781
|
Testing significant difference of correlation matrices
|
I'm looking at the same issue - I just came across the functions cortest.normal and cortest.jennrich, in the excellent psych package for R by William Revelle (see http://www.personality-project.org/r/html/cortest.mat.html). That page also contains references to articles on these tests. In you (our) case, the Jennrich test seems most appropriate (a quick scan of the Steiger paper (see http://ww.w.statpower.net/Steiger%20Biblio/Steiger80b.pdf) gives me the impression that that test, cortest.normal, also tests whether all correlations are zero - but I haven't looked into it more thoroughly yet).
|
Testing significant difference of correlation matrices
|
I'm looking at the same issue - I just came across the functions cortest.normal and cortest.jennrich, in the excellent psych package for R by William Revelle (see http://www.personality-project.org/r/
|
Testing significant difference of correlation matrices
I'm looking at the same issue - I just came across the functions cortest.normal and cortest.jennrich, in the excellent psych package for R by William Revelle (see http://www.personality-project.org/r/html/cortest.mat.html). That page also contains references to articles on these tests. In you (our) case, the Jennrich test seems most appropriate (a quick scan of the Steiger paper (see http://ww.w.statpower.net/Steiger%20Biblio/Steiger80b.pdf) gives me the impression that that test, cortest.normal, also tests whether all correlations are zero - but I haven't looked into it more thoroughly yet).
|
Testing significant difference of correlation matrices
I'm looking at the same issue - I just came across the functions cortest.normal and cortest.jennrich, in the excellent psych package for R by William Revelle (see http://www.personality-project.org/r/
|
42,782
|
Berry-Esseen Theorem with Continuity Correction
|
Well, if $S_n$ is discrete, then we have $F_n(x)=F_n(x+\frac12)$ for $x\in \mathbb Z$, in which case we recover the same Berry-Esseen bound for the continuity correction as without:
$$\left| F_n(x)-\Phi\left(\frac{x+\frac12}{\sqrt n}\right)\right| = \left| F_n\left(x+\frac12\right)-\Phi\left(\frac{x+\frac12}{\sqrt n}\right)\right| \leq .56\sum_{i=1}^n \rho_i$$
Is this what you were looking for? Or were you wanting to show that the continuity correction allows for a strict improvement of the Berry-Esseen inequality?
|
Berry-Esseen Theorem with Continuity Correction
|
Well, if $S_n$ is discrete, then we have $F_n(x)=F_n(x+\frac12)$ for $x\in \mathbb Z$, in which case we recover the same Berry-Esseen bound for the continuity correction as without:
$$\left| F_n(x)-\P
|
Berry-Esseen Theorem with Continuity Correction
Well, if $S_n$ is discrete, then we have $F_n(x)=F_n(x+\frac12)$ for $x\in \mathbb Z$, in which case we recover the same Berry-Esseen bound for the continuity correction as without:
$$\left| F_n(x)-\Phi\left(\frac{x+\frac12}{\sqrt n}\right)\right| = \left| F_n\left(x+\frac12\right)-\Phi\left(\frac{x+\frac12}{\sqrt n}\right)\right| \leq .56\sum_{i=1}^n \rho_i$$
Is this what you were looking for? Or were you wanting to show that the continuity correction allows for a strict improvement of the Berry-Esseen inequality?
|
Berry-Esseen Theorem with Continuity Correction
Well, if $S_n$ is discrete, then we have $F_n(x)=F_n(x+\frac12)$ for $x\in \mathbb Z$, in which case we recover the same Berry-Esseen bound for the continuity correction as without:
$$\left| F_n(x)-\P
|
42,783
|
Cholesky factorization and forward substitution less accurate than inversion?
|
For most cases Cholesky factorization should be a faster and more numerically stable method for solving a linear system of equation such as $Ax=b$ given that $A$ is describing a positive definite matrix. The standard workhorse behind the solution of linear systems is the QR decomposition; it does need the system $A$ to be positive definite or even square.
Some difference in performance might be found in relative small matrices as direct analytical solutions might be employed but this usually is not the case for systems larger than $3\times3$ or $4\times4$.
In general in terms of performance Cholesky decomposition is approximatelly twice as fast as LU decomposition, LU decomposition is approximatelly twice as fast as QR decomposition and QR decomposition is approximatelly twice as fast as SVD decomposition. All them have different conditions that need to be so they are applicable but all them can be used to solve a linear system.
Given you are using MATLAB, MATLAB's mldivide operator will automatically make certain checks and compute the solution given the optimal decomposition from the ones described above (and some additional too, eg. check if you have a Hessenberg matrix and use a banded solver) . Powering a matrix (^-1) is a rather inefficient way to solve a linear system of equations. It will most probably resort to do the singular value decomposition of the matrix. This is stable numerically but very slow.
|
Cholesky factorization and forward substitution less accurate than inversion?
|
For most cases Cholesky factorization should be a faster and more numerically stable method for solving a linear system of equation such as $Ax=b$ given that $A$ is describing a positive definite matr
|
Cholesky factorization and forward substitution less accurate than inversion?
For most cases Cholesky factorization should be a faster and more numerically stable method for solving a linear system of equation such as $Ax=b$ given that $A$ is describing a positive definite matrix. The standard workhorse behind the solution of linear systems is the QR decomposition; it does need the system $A$ to be positive definite or even square.
Some difference in performance might be found in relative small matrices as direct analytical solutions might be employed but this usually is not the case for systems larger than $3\times3$ or $4\times4$.
In general in terms of performance Cholesky decomposition is approximatelly twice as fast as LU decomposition, LU decomposition is approximatelly twice as fast as QR decomposition and QR decomposition is approximatelly twice as fast as SVD decomposition. All them have different conditions that need to be so they are applicable but all them can be used to solve a linear system.
Given you are using MATLAB, MATLAB's mldivide operator will automatically make certain checks and compute the solution given the optimal decomposition from the ones described above (and some additional too, eg. check if you have a Hessenberg matrix and use a banded solver) . Powering a matrix (^-1) is a rather inefficient way to solve a linear system of equations. It will most probably resort to do the singular value decomposition of the matrix. This is stable numerically but very slow.
|
Cholesky factorization and forward substitution less accurate than inversion?
For most cases Cholesky factorization should be a faster and more numerically stable method for solving a linear system of equation such as $Ax=b$ given that $A$ is describing a positive definite matr
|
42,784
|
How does the presence of factors affect the interpretation of the other coefficients in a regression?
|
Does this imply that the coefficient colourWhite:age = -0.0373729 is strictly limited to describing only the interaction between colour and age for people who are unemployed, non-citizen and arrested in 1997?
Yes, that is exactly what it means. If you want to investigate this interaction for the other years, you would fit the 3-way interaction colour:age:year.
|
How does the presence of factors affect the interpretation of the other coefficients in a regression
|
Does this imply that the coefficient colourWhite:age = -0.0373729 is strictly limited to describing only the interaction between colour and age for people who are unemployed, non-citizen and arrested
|
How does the presence of factors affect the interpretation of the other coefficients in a regression?
Does this imply that the coefficient colourWhite:age = -0.0373729 is strictly limited to describing only the interaction between colour and age for people who are unemployed, non-citizen and arrested in 1997?
Yes, that is exactly what it means. If you want to investigate this interaction for the other years, you would fit the 3-way interaction colour:age:year.
|
How does the presence of factors affect the interpretation of the other coefficients in a regression
Does this imply that the coefficient colourWhite:age = -0.0373729 is strictly limited to describing only the interaction between colour and age for people who are unemployed, non-citizen and arrested
|
42,785
|
How do v-structures in graphical models reflect real world data?
|
You understand v-structures, but let's recall formally what they mean. What that v-structure (applied to your example) encodes is: A: Student IQ and C: Test difficulty are independent, i.e. $$I(A,C), \ i.e. \ P(A|C) = P(A)$$ but they are dependent given B: Test score. I.e. $$D(A,C|B), \ i.e. \ P(A|C,B) \neq P(A|C)$$
How do they relate to the real world multivariate data?
Student IQ and Test difficulty are independent, that is clear. Now let's suppose you know the test score, i.e. $B$, of a student. Let's also suppose it is very high, e.g. the maximum grade. Now I ask you the following question:
If you knew that the Test difficulty, $C$, was very high, Wouldn't you think that the student should have a higher probability of being very smart (higher Student IQ, $A$)? There you have it, now $P(A|C,B) \neq P(A|C)$, because knowing $B$ and $C$ has changed the probability of the event $A$.
How does the multivariate distribution in this dataset reflect the
v-structure?
You can think of a toy dataset that explains this... (For the sake of simplicity I will use binary variables with states $+$ (high), $-$(low), and $=$ (medium), the last one only for $B$)
A C B
+ + =
+ - +
- + -
- - =
- - =
- + -
+ + -
+ + =
+ - +
+ - +
Look at the dataset. Hopefully you see $I(A,C)$. Now, if you know $B="="$, then knowing $C="+"$ doesn't tell you anything about $A$?
Note, response to the question above: You estimate *
real probabilities using the dataset, if we assume probabilities are estimated directly from the dataset (Maximum Likelihood, no need to worry about this, just being formal), you would estimate $P(A = "+" | \ B = "=", C = "+") = 1 $, because all students who obtained $B="="$ (medium score) when $C="+"$ (the exam was hard) were $A = "+"$ (smart, i.e. high IQ).
|
How do v-structures in graphical models reflect real world data?
|
You understand v-structures, but let's recall formally what they mean. What that v-structure (applied to your example) encodes is: A: Student IQ and C: Test difficulty are independent, i.e. $$I(A,C),
|
How do v-structures in graphical models reflect real world data?
You understand v-structures, but let's recall formally what they mean. What that v-structure (applied to your example) encodes is: A: Student IQ and C: Test difficulty are independent, i.e. $$I(A,C), \ i.e. \ P(A|C) = P(A)$$ but they are dependent given B: Test score. I.e. $$D(A,C|B), \ i.e. \ P(A|C,B) \neq P(A|C)$$
How do they relate to the real world multivariate data?
Student IQ and Test difficulty are independent, that is clear. Now let's suppose you know the test score, i.e. $B$, of a student. Let's also suppose it is very high, e.g. the maximum grade. Now I ask you the following question:
If you knew that the Test difficulty, $C$, was very high, Wouldn't you think that the student should have a higher probability of being very smart (higher Student IQ, $A$)? There you have it, now $P(A|C,B) \neq P(A|C)$, because knowing $B$ and $C$ has changed the probability of the event $A$.
How does the multivariate distribution in this dataset reflect the
v-structure?
You can think of a toy dataset that explains this... (For the sake of simplicity I will use binary variables with states $+$ (high), $-$(low), and $=$ (medium), the last one only for $B$)
A C B
+ + =
+ - +
- + -
- - =
- - =
- + -
+ + -
+ + =
+ - +
+ - +
Look at the dataset. Hopefully you see $I(A,C)$. Now, if you know $B="="$, then knowing $C="+"$ doesn't tell you anything about $A$?
Note, response to the question above: You estimate *
real probabilities using the dataset, if we assume probabilities are estimated directly from the dataset (Maximum Likelihood, no need to worry about this, just being formal), you would estimate $P(A = "+" | \ B = "=", C = "+") = 1 $, because all students who obtained $B="="$ (medium score) when $C="+"$ (the exam was hard) were $A = "+"$ (smart, i.e. high IQ).
|
How do v-structures in graphical models reflect real world data?
You understand v-structures, but let's recall formally what they mean. What that v-structure (applied to your example) encodes is: A: Student IQ and C: Test difficulty are independent, i.e. $$I(A,C),
|
42,786
|
k-means and other non-parametric methods for clustering 1 dimensional data
|
K-means finds partitions in a single vector based on any heterogeneity in that vector. It won't automatically find two clusters unless you tell it to find two clusters out of the n possible clusters where n is the finite number of observations in your sample. It's only by generating up to n clusters and then using some sort of decision rule for cluster selection that you could arrive at two clusters.
There are literally dozens of unsupervised classification or clustering algorithms that would work with your example: hierarchical approaches, disjoint solutions, etc., should be at the top of the list. These methods are strewn throughout the literature but good inventories of the many nuances in approaching cluster analysis can be found in the big stat package documentation, e.g., the SPSS or SAS online manuals. That said, there are algorithms that definitely will not work, such as knn or any distance-based, similarity or dissimilarity technique which relies on a p dimensional space to define the solution.
If you have a target enabling a supervised approach, CART would be a good method for partitioning based on a single predictor.
|
k-means and other non-parametric methods for clustering 1 dimensional data
|
K-means finds partitions in a single vector based on any heterogeneity in that vector. It won't automatically find two clusters unless you tell it to find two clusters out of the n possible clusters w
|
k-means and other non-parametric methods for clustering 1 dimensional data
K-means finds partitions in a single vector based on any heterogeneity in that vector. It won't automatically find two clusters unless you tell it to find two clusters out of the n possible clusters where n is the finite number of observations in your sample. It's only by generating up to n clusters and then using some sort of decision rule for cluster selection that you could arrive at two clusters.
There are literally dozens of unsupervised classification or clustering algorithms that would work with your example: hierarchical approaches, disjoint solutions, etc., should be at the top of the list. These methods are strewn throughout the literature but good inventories of the many nuances in approaching cluster analysis can be found in the big stat package documentation, e.g., the SPSS or SAS online manuals. That said, there are algorithms that definitely will not work, such as knn or any distance-based, similarity or dissimilarity technique which relies on a p dimensional space to define the solution.
If you have a target enabling a supervised approach, CART would be a good method for partitioning based on a single predictor.
|
k-means and other non-parametric methods for clustering 1 dimensional data
K-means finds partitions in a single vector based on any heterogeneity in that vector. It won't automatically find two clusters unless you tell it to find two clusters out of the n possible clusters w
|
42,787
|
k-means and other non-parametric methods for clustering 1 dimensional data
|
K-means assigns objects to the nearest mean.
This makes sense mathematically as it minimizes the squared errors.
But if you look at your data set, the right gaussian has a larger variance than the left. Since k-means does not take this into account, the result will be suboptimal. GMM should work better on this particular data set, but so does manually choosing the threshold, or density estimation...
Why don't you just run k-means and visualize the results?
|
k-means and other non-parametric methods for clustering 1 dimensional data
|
K-means assigns objects to the nearest mean.
This makes sense mathematically as it minimizes the squared errors.
But if you look at your data set, the right gaussian has a larger variance than the lef
|
k-means and other non-parametric methods for clustering 1 dimensional data
K-means assigns objects to the nearest mean.
This makes sense mathematically as it minimizes the squared errors.
But if you look at your data set, the right gaussian has a larger variance than the left. Since k-means does not take this into account, the result will be suboptimal. GMM should work better on this particular data set, but so does manually choosing the threshold, or density estimation...
Why don't you just run k-means and visualize the results?
|
k-means and other non-parametric methods for clustering 1 dimensional data
K-means assigns objects to the nearest mean.
This makes sense mathematically as it minimizes the squared errors.
But if you look at your data set, the right gaussian has a larger variance than the lef
|
42,788
|
Difference between Kaplan Meier Estimator and the Empirical CDF
|
As I understand from a comment, the OP didn't realize that the Kaplan-Meier estimate is nothing but the empirical estimate of the survival function in case when there is no censoring.
Let me tell a word about that. Consider two independent random variables $X$ and $Y$ with continuous distributions, and independent replicated observations $x_i$ and $y_i$, $i=1, \ldots, n$. In the context of the Kaplan-Meier estimate, $Y$ is considered as the censoring variable and one observes the minima $t_i=\min(x_i,y_i)$ together with the indicators $\delta_i={\boldsymbol 1}_{x_i \leq y_i}$, independent replicated observations of $T=\min(X,Y)$ and $\Delta={\boldsymbol 1}_{X \leq Y}$ respectively.
Note that $\Pr(T >t)=\Pr(X>t)\Pr(Y>t)$, that is to say $\boxed{S^T(t)=S^X(t)S^Y(t)}$ by denoting $S^T$, $S^X$ and $S^Y$ the survival functions of $T$, $X$ and $Y$ respectively.
The usual empirical survival function $\hat{S}^T$ of $T$ is available from the data. When seeking estimates $\hat{S}^X$ and $\hat{S}^Y$ of $S^X$ and $S^Y$, it is natural to require the empirical analogous of the previous boxed formula, that is to say $\boxed{\hat{S}^T(t)=\hat{S}^X(t)\hat{S}^Y(t)}$.
Then remember that:
The Kaplan-Meier estimates of $S^X$ and $S^Y$ satisfy this relation (at least when there are no ties, I don't know and I have not checked when there are ties). The case when $Y=+\infty$ corresponds to the absence of censoring, in this case $T=X$, $S^Y\equiv 1$, $\hat{S}^Y\equiv 1$ and one gets $\hat{S}^T(t)=\hat{S}^X(t)$: the Kaplan-Meier estimate is nothing but the empirical estimate of the survival function.
In fact (at least when there are no ties), the Kaplan-meier estimates can even be derived from the required relation $\boxed{\hat{S}^T(t)=\hat{S}^X(t)\hat{S}^Y(t)}$, after requiring in addition that $\hat{S}^X$ and $\hat{S}^Y$ are step functions jumping at the observations of $x_i$ ($t_i$ when $\delta_i=1$) and $y_i$ ($t_i$ when $\delta_i=0$) respectively.
|
Difference between Kaplan Meier Estimator and the Empirical CDF
|
As I understand from a comment, the OP didn't realize that the Kaplan-Meier estimate is nothing but the empirical estimate of the survival function in case when there is no censoring.
Let me tell a wo
|
Difference between Kaplan Meier Estimator and the Empirical CDF
As I understand from a comment, the OP didn't realize that the Kaplan-Meier estimate is nothing but the empirical estimate of the survival function in case when there is no censoring.
Let me tell a word about that. Consider two independent random variables $X$ and $Y$ with continuous distributions, and independent replicated observations $x_i$ and $y_i$, $i=1, \ldots, n$. In the context of the Kaplan-Meier estimate, $Y$ is considered as the censoring variable and one observes the minima $t_i=\min(x_i,y_i)$ together with the indicators $\delta_i={\boldsymbol 1}_{x_i \leq y_i}$, independent replicated observations of $T=\min(X,Y)$ and $\Delta={\boldsymbol 1}_{X \leq Y}$ respectively.
Note that $\Pr(T >t)=\Pr(X>t)\Pr(Y>t)$, that is to say $\boxed{S^T(t)=S^X(t)S^Y(t)}$ by denoting $S^T$, $S^X$ and $S^Y$ the survival functions of $T$, $X$ and $Y$ respectively.
The usual empirical survival function $\hat{S}^T$ of $T$ is available from the data. When seeking estimates $\hat{S}^X$ and $\hat{S}^Y$ of $S^X$ and $S^Y$, it is natural to require the empirical analogous of the previous boxed formula, that is to say $\boxed{\hat{S}^T(t)=\hat{S}^X(t)\hat{S}^Y(t)}$.
Then remember that:
The Kaplan-Meier estimates of $S^X$ and $S^Y$ satisfy this relation (at least when there are no ties, I don't know and I have not checked when there are ties). The case when $Y=+\infty$ corresponds to the absence of censoring, in this case $T=X$, $S^Y\equiv 1$, $\hat{S}^Y\equiv 1$ and one gets $\hat{S}^T(t)=\hat{S}^X(t)$: the Kaplan-Meier estimate is nothing but the empirical estimate of the survival function.
In fact (at least when there are no ties), the Kaplan-meier estimates can even be derived from the required relation $\boxed{\hat{S}^T(t)=\hat{S}^X(t)\hat{S}^Y(t)}$, after requiring in addition that $\hat{S}^X$ and $\hat{S}^Y$ are step functions jumping at the observations of $x_i$ ($t_i$ when $\delta_i=1$) and $y_i$ ($t_i$ when $\delta_i=0$) respectively.
|
Difference between Kaplan Meier Estimator and the Empirical CDF
As I understand from a comment, the OP didn't realize that the Kaplan-Meier estimate is nothing but the empirical estimate of the survival function in case when there is no censoring.
Let me tell a wo
|
42,789
|
How high is too high with Cronbach's alpha?
|
When I have ran into this kind of error, I had made a mistake during the coding process (I'm using SPSS). I usually use numbers like 99 or 999 to mark missing values. Once I forgot to specify the missing values to be excluded at the variable view, and I begun the scale analysis. I got very high C-alphas, around 0.95, just like you.
|
How high is too high with Cronbach's alpha?
|
When I have ran into this kind of error, I had made a mistake during the coding process (I'm using SPSS). I usually use numbers like 99 or 999 to mark missing values. Once I forgot to specify the miss
|
How high is too high with Cronbach's alpha?
When I have ran into this kind of error, I had made a mistake during the coding process (I'm using SPSS). I usually use numbers like 99 or 999 to mark missing values. Once I forgot to specify the missing values to be excluded at the variable view, and I begun the scale analysis. I got very high C-alphas, around 0.95, just like you.
|
How high is too high with Cronbach's alpha?
When I have ran into this kind of error, I had made a mistake during the coding process (I'm using SPSS). I usually use numbers like 99 or 999 to mark missing values. Once I forgot to specify the miss
|
42,790
|
why the non-seasonal and seasonal parts are multiplied in ARIMA models?
|
why are they multiplied from the first place?
To produce a model where the seasonal component enters multiplicatively? It makes a kind of intuitive sense that it might work that way, and often seems to work okay in practice. Indeed, you so often see it (at least approximately) in the diagnostic plots (ACF and PACF) that trying this seems uncontroversial.
More prosaically, an ARIMA model is already conceived of as a product of terms:
$y_t = (1+\theta(B))(1-B)^{-\delta}(1-\phi(B))^{-1} \varepsilon_t$
So adding products in for seasonality keeps that nice structure - and with seasonal differencing, it stays in that same framework. In a sense this allows us to conceive of and model the seasonality and the "ordinary" ARIMA separately in a way we couldn't do so readily if the model were additive.
is there an additive model which can be applied here?
Sure, an AR model with lags at 1 and 60 is one such example
One with lags at 1, 60 and 61 is even more like the seasonal model and would include the multiplicative model as a special case.
if there is, why is it not used?
What makes you say it's not? Distributed lag models can be used on data with seasonality
|
why the non-seasonal and seasonal parts are multiplied in ARIMA models?
|
why are they multiplied from the first place?
To produce a model where the seasonal component enters multiplicatively? It makes a kind of intuitive sense that it might work that way, and often seems
|
why the non-seasonal and seasonal parts are multiplied in ARIMA models?
why are they multiplied from the first place?
To produce a model where the seasonal component enters multiplicatively? It makes a kind of intuitive sense that it might work that way, and often seems to work okay in practice. Indeed, you so often see it (at least approximately) in the diagnostic plots (ACF and PACF) that trying this seems uncontroversial.
More prosaically, an ARIMA model is already conceived of as a product of terms:
$y_t = (1+\theta(B))(1-B)^{-\delta}(1-\phi(B))^{-1} \varepsilon_t$
So adding products in for seasonality keeps that nice structure - and with seasonal differencing, it stays in that same framework. In a sense this allows us to conceive of and model the seasonality and the "ordinary" ARIMA separately in a way we couldn't do so readily if the model were additive.
is there an additive model which can be applied here?
Sure, an AR model with lags at 1 and 60 is one such example
One with lags at 1, 60 and 61 is even more like the seasonal model and would include the multiplicative model as a special case.
if there is, why is it not used?
What makes you say it's not? Distributed lag models can be used on data with seasonality
|
why the non-seasonal and seasonal parts are multiplied in ARIMA models?
why are they multiplied from the first place?
To produce a model where the seasonal component enters multiplicatively? It makes a kind of intuitive sense that it might work that way, and often seems
|
42,791
|
Understanding the background to chi-square test for tables
|
From a memorable, intuitive perspective, your account is fine. The considerations of degrees of freedom rest on the understanding that each standardized residual,
$$Z_i = \frac{O_i-E_i}{\sqrt{E_i}},$$
is close enough to having a standard Normal distribution that the sum of their squares
$$X^2 = \sum Z_i^2 = \sum_i^n \frac{(O_i-E_i)^2}{E_i}$$
has a distribution close to that of the sum of $n$ standard Normal variables. (For convenience I have written $n=rc$ and index the residuals from $i=1$ to $i=rc$, rather than following the double-indexing that is usually used in two-way tables.)
The problem, as every textbook at every level points out, is that the $Z_i$ are not independent. In fact, they satisfy a lot of linear relations. Across each row, for instance, the sum of the $O_i$ (counts of observations) equals the sum of the $E_i$ (their expectations, constructed to give the same sum), whence the sum of the $Z_i$ across each row is zero. Similar, the column sums of the $Z_i$ are zero. But many more sums than that are zero: any linear combination of such sums will also be zero.
The best solution is to consider this geometrically. The vector $\mathbf{Z}=(Z_1, \ldots, Z_n)$ can be located anywhere in $\mathbb{R}^n$. (Visualize this in $n=3$ dimensions.) If the $Z_i$ truly were independent, they would have a rotationally-invariant distribution around the origin. The only variation in their probability density would be radial. Indeed, $X^2$ is precisely the squared length of $\mathbf{Z}$.
Any single sum-to-zero constraint defines a hyperplane in this space. (Visualize a plane in $\mathbb{R}^3$, such as the $xy$ plane.) The constraint restricts the vector $\mathbf{Z}$ to lie within that hyperplane. Nevertheless, because any rotation in that hyperplane can be extended to a rotation of the entire space--just fix the perpendicular direction--the distribution of $\mathbf{Z}$ remains rotationally invariant in this hyperplane. It therefore is identical to the distribution of independent standard Normal variables within the hyperplane itself, which has one less dimension, $n-1$.
(In the running example, $\mathbf{Z}=(Z_1,Z_2,Z_3)$ when restricted to the $xy$ plane in $\mathbb{R}^3$ is just $(Z_1,Z_2)$. Therefore its squared length is just $Z_1^2 + Z_2^2$, which by definition has a $\chi^2(2)$ distribution. Due to the rotational invariance of $\mathbf{Z}$, the distribution of $|\mathbf{Z}|^2$ in any plane through the origin in $\mathbb{R}^3$ will be the same as this one: namely, $\chi^2(2)$, not $\chi^2(3)$.)
In this fashion each additional hyperplane thereby reduces the number of independent standard Normal variables in the description, provided it truly reduces the dimension of the space in which $\mathbf{Z}$ may lie. The actual mathematical content of the $\nu = (r-1)(c-1)$ equation is to assert that (a) the $r+c$ obvious sum-to-zero constraints in the $r\times c$ table amount only to $r+c-1$ independent constraints--there is one degree of redundancy--and (b) there are no other constraints independent of them. Proving these facts is a matter of linear algebra: that is, of solving systems of equations and counting dimensions.
(It is easy to see there are at most $r+c-1$ independent constraints, because the fact that all $n$ $Z_i$ sum to zero follows by adding either all the row sums or all the column sums, showing there is at least this degree of redundancy among the row-sum and column-sum constraints.)
Consequently, we should visualize the situation as one of looking at the distribution of $rc$ independent standard Normal variables within a linear subspace that is determined by the intersection of $r + c - 1 $ independent hyperplanes. Within that subspace, the sum of squares of those variables still gives the distance to the origin. That distance, however, lies within a space of dimension only
$$\nu = rc - (r + c - 1) = (r-1)(c-1).$$
Thus, the distribution of the sum of squares is the same as the distribution of the sum of squares of $(r-1)(c-1)$ independent standard Normal variables.
The answers at How to understand degrees of freedom? provide additional explanations, many from similar viewpoints but at varying levels of sophistication and rigor.
|
Understanding the background to chi-square test for tables
|
From a memorable, intuitive perspective, your account is fine. The considerations of degrees of freedom rest on the understanding that each standardized residual,
$$Z_i = \frac{O_i-E_i}{\sqrt{E_i}},$
|
Understanding the background to chi-square test for tables
From a memorable, intuitive perspective, your account is fine. The considerations of degrees of freedom rest on the understanding that each standardized residual,
$$Z_i = \frac{O_i-E_i}{\sqrt{E_i}},$$
is close enough to having a standard Normal distribution that the sum of their squares
$$X^2 = \sum Z_i^2 = \sum_i^n \frac{(O_i-E_i)^2}{E_i}$$
has a distribution close to that of the sum of $n$ standard Normal variables. (For convenience I have written $n=rc$ and index the residuals from $i=1$ to $i=rc$, rather than following the double-indexing that is usually used in two-way tables.)
The problem, as every textbook at every level points out, is that the $Z_i$ are not independent. In fact, they satisfy a lot of linear relations. Across each row, for instance, the sum of the $O_i$ (counts of observations) equals the sum of the $E_i$ (their expectations, constructed to give the same sum), whence the sum of the $Z_i$ across each row is zero. Similar, the column sums of the $Z_i$ are zero. But many more sums than that are zero: any linear combination of such sums will also be zero.
The best solution is to consider this geometrically. The vector $\mathbf{Z}=(Z_1, \ldots, Z_n)$ can be located anywhere in $\mathbb{R}^n$. (Visualize this in $n=3$ dimensions.) If the $Z_i$ truly were independent, they would have a rotationally-invariant distribution around the origin. The only variation in their probability density would be radial. Indeed, $X^2$ is precisely the squared length of $\mathbf{Z}$.
Any single sum-to-zero constraint defines a hyperplane in this space. (Visualize a plane in $\mathbb{R}^3$, such as the $xy$ plane.) The constraint restricts the vector $\mathbf{Z}$ to lie within that hyperplane. Nevertheless, because any rotation in that hyperplane can be extended to a rotation of the entire space--just fix the perpendicular direction--the distribution of $\mathbf{Z}$ remains rotationally invariant in this hyperplane. It therefore is identical to the distribution of independent standard Normal variables within the hyperplane itself, which has one less dimension, $n-1$.
(In the running example, $\mathbf{Z}=(Z_1,Z_2,Z_3)$ when restricted to the $xy$ plane in $\mathbb{R}^3$ is just $(Z_1,Z_2)$. Therefore its squared length is just $Z_1^2 + Z_2^2$, which by definition has a $\chi^2(2)$ distribution. Due to the rotational invariance of $\mathbf{Z}$, the distribution of $|\mathbf{Z}|^2$ in any plane through the origin in $\mathbb{R}^3$ will be the same as this one: namely, $\chi^2(2)$, not $\chi^2(3)$.)
In this fashion each additional hyperplane thereby reduces the number of independent standard Normal variables in the description, provided it truly reduces the dimension of the space in which $\mathbf{Z}$ may lie. The actual mathematical content of the $\nu = (r-1)(c-1)$ equation is to assert that (a) the $r+c$ obvious sum-to-zero constraints in the $r\times c$ table amount only to $r+c-1$ independent constraints--there is one degree of redundancy--and (b) there are no other constraints independent of them. Proving these facts is a matter of linear algebra: that is, of solving systems of equations and counting dimensions.
(It is easy to see there are at most $r+c-1$ independent constraints, because the fact that all $n$ $Z_i$ sum to zero follows by adding either all the row sums or all the column sums, showing there is at least this degree of redundancy among the row-sum and column-sum constraints.)
Consequently, we should visualize the situation as one of looking at the distribution of $rc$ independent standard Normal variables within a linear subspace that is determined by the intersection of $r + c - 1 $ independent hyperplanes. Within that subspace, the sum of squares of those variables still gives the distance to the origin. That distance, however, lies within a space of dimension only
$$\nu = rc - (r + c - 1) = (r-1)(c-1).$$
Thus, the distribution of the sum of squares is the same as the distribution of the sum of squares of $(r-1)(c-1)$ independent standard Normal variables.
The answers at How to understand degrees of freedom? provide additional explanations, many from similar viewpoints but at varying levels of sophistication and rigor.
|
Understanding the background to chi-square test for tables
From a memorable, intuitive perspective, your account is fine. The considerations of degrees of freedom rest on the understanding that each standardized residual,
$$Z_i = \frac{O_i-E_i}{\sqrt{E_i}},$
|
42,792
|
How to differentiate with respect to a matrix?
|
Matrix calculus is used in such cases. Your equation looks like it's from OLS (least squares) theory. In those you differentiate by vector $x$ some quadratic forms like $\frac{\partial (x'A'Ax)}{\partial x}$. Look up relevant formulae in my link above.
If you really are up to differentiating by matrices not vectors, you'll end up with tensors. Tensors are fun, but so far I haven't seem them used a lot in statistics. They're ubiquitous in physics, btw. Again, follow the link I gave.
|
How to differentiate with respect to a matrix?
|
Matrix calculus is used in such cases. Your equation looks like it's from OLS (least squares) theory. In those you differentiate by vector $x$ some quadratic forms like $\frac{\partial (x'A'Ax)}{\part
|
How to differentiate with respect to a matrix?
Matrix calculus is used in such cases. Your equation looks like it's from OLS (least squares) theory. In those you differentiate by vector $x$ some quadratic forms like $\frac{\partial (x'A'Ax)}{\partial x}$. Look up relevant formulae in my link above.
If you really are up to differentiating by matrices not vectors, you'll end up with tensors. Tensors are fun, but so far I haven't seem them used a lot in statistics. They're ubiquitous in physics, btw. Again, follow the link I gave.
|
How to differentiate with respect to a matrix?
Matrix calculus is used in such cases. Your equation looks like it's from OLS (least squares) theory. In those you differentiate by vector $x$ some quadratic forms like $\frac{\partial (x'A'Ax)}{\part
|
42,793
|
How to select the best ARIMA order with low MAPE in R
|
This was the first that came to mind, and is just an example but it is slow and it should be done once per integration order you wish to consider. Looping through the 10 first AR and MA orders (again only example), saving the MAPE accuracy measures in a matrix "x". Then identifying the smallest value in the matrix afterwards. Is it something like this you had in mind?
set.seed(1)
tsdata <- ts(rnorm(50), start = c(1980,1), frequency = 12)
myts <- tsdata
x <- matrix(data = NA, nrow=10, ncol=10)
for(i in 0:9){
for(j in 0:9){
fit <- arima(myts, order=c(i,1,j))
acc <- accuracy(fit)
x[i+1,j+1] <- acc[[5]] # Number 5 indicates the position of MAPE in the accuracy list
print(i);print(j)
}
}
which(x==min(x), arr.ind=T)
row col
[1,] 3 1
edit: deleted unnecessary code.
|
How to select the best ARIMA order with low MAPE in R
|
This was the first that came to mind, and is just an example but it is slow and it should be done once per integration order you wish to consider. Looping through the 10 first AR and MA orders (again
|
How to select the best ARIMA order with low MAPE in R
This was the first that came to mind, and is just an example but it is slow and it should be done once per integration order you wish to consider. Looping through the 10 first AR and MA orders (again only example), saving the MAPE accuracy measures in a matrix "x". Then identifying the smallest value in the matrix afterwards. Is it something like this you had in mind?
set.seed(1)
tsdata <- ts(rnorm(50), start = c(1980,1), frequency = 12)
myts <- tsdata
x <- matrix(data = NA, nrow=10, ncol=10)
for(i in 0:9){
for(j in 0:9){
fit <- arima(myts, order=c(i,1,j))
acc <- accuracy(fit)
x[i+1,j+1] <- acc[[5]] # Number 5 indicates the position of MAPE in the accuracy list
print(i);print(j)
}
}
which(x==min(x), arr.ind=T)
row col
[1,] 3 1
edit: deleted unnecessary code.
|
How to select the best ARIMA order with low MAPE in R
This was the first that came to mind, and is just an example but it is slow and it should be done once per integration order you wish to consider. Looping through the 10 first AR and MA orders (again
|
42,794
|
Computing VaR with AR-GARCH
|
This is best done through simulation. See my MATLAB code example and explanation below:
%% Get S&P 500 price series
d=fetch(yahoo,'^GSPC','Adj Close','1-jan-2014','30-dec-2014');
n = 1; % # of shares
p = d(end:-1:1,2); % share price, the dates are backwards
PV0 = n*p(end); % portfolio value today
%%
r=price2ret(p,[],'Continuous'); % get the continous compounding returns
Mdl = arima('ARLags',1,'Variance',garch(1,1),'Constant',0);
fit = estimate(Mdl,r) % fit the AR(1)-GARCH(1,1)
fit.Variance
[E0,V0] = infer(fit,r); % get the estimated errors and variances
%% Simulate periods ahead
[Y] = simulate(fit,2,'Y0',r,'E0',E0,'V0',V0, 'NumPaths',1e5);
ret = sum(Y); % compund the return
histfit(PV0*(exp(ret)-1),100,'normal')
title 'P&L distribution'
ret2d = prctile(ret,0.01); % get the 99% lowest return
VaR = PV0*(exp(ret2d)-1);
fprintf('Today portfolio value: %f\n2-days ahead 99%% VaR: %f\n',PV0,VaR);
Output:
ARIMA(1,0,0) Model:
--------------------
Conditional Probability Distribution: Gaussian
Standard t
Parameter Value Error Statistic
----------- ----------- ------------ -----------
Constant 0 Fixed Fixed
AR{1} -0.020272 0.0697731 -0.290541
GARCH(1,1) Conditional Variance Model:
----------------------------------------
Conditional Probability Distribution: Gaussian
Standard t
Parameter Value Error Statistic
----------- ----------- ------------ -----------
Constant 7.43521e-06 2.14546e-06 3.46556
GARCH{1} 0.653488 0.126818 5.15295
ARCH{1} 0.206016 0.0881823 2.33626
fit =
ARIMA(1,0,0) Model:
--------------------
Distribution: Name = 'Gaussian'
P: 1
D: 0
Q: 0
Constant: 0
AR: {-0.020272} at Lags [1]
SAR: {}
MA: {}
SMA: {}
Variance: [GARCH(1,1) Model]
ans =
GARCH(1,1) Conditional Variance Model:
--------------------------------------
Distribution: Name = 'Gaussian'
P: 1
Q: 1
Constant: 7.43521e-06
GARCH: {0.653488} at Lags [1]
ARCH: {0.206016} at Lags [1]
Today portfolio value: 2090.570000
2-days ahead 99% VaR: -79.986280
For a portfolio consisting of one share of S&P 500 index, I got the current value of \$2091, and 2-day VaR at 99% is \$80.
I also plotted the P&L distribution with Normal fit, so you can see that the normal distribution is not a very good fit. That's why you have to simulate when using GARCH.
You can also look at MATLAB's own GARCH example here.
The idea is that you fit AR(1)-GARCH(1,1) to the returns. Then you Monte-Carlo simulate the returns two days ahead. Then you compound two days of returns in each path, and find 0.01 percentile. This is how much or more you'll lose at 99% confidence in terms of returns, and in terms of dollars it's a simple arithmetic using the current portfolio value.
You can find worked out examples in this book: Carol Alexander, Market Risk Analysis, Volume IV, Value at Risk Models, February 2009
|
Computing VaR with AR-GARCH
|
This is best done through simulation. See my MATLAB code example and explanation below:
%% Get S&P 500 price series
d=fetch(yahoo,'^GSPC','Adj Close','1-jan-2014','30-dec-2014');
n = 1; % # of shares
|
Computing VaR with AR-GARCH
This is best done through simulation. See my MATLAB code example and explanation below:
%% Get S&P 500 price series
d=fetch(yahoo,'^GSPC','Adj Close','1-jan-2014','30-dec-2014');
n = 1; % # of shares
p = d(end:-1:1,2); % share price, the dates are backwards
PV0 = n*p(end); % portfolio value today
%%
r=price2ret(p,[],'Continuous'); % get the continous compounding returns
Mdl = arima('ARLags',1,'Variance',garch(1,1),'Constant',0);
fit = estimate(Mdl,r) % fit the AR(1)-GARCH(1,1)
fit.Variance
[E0,V0] = infer(fit,r); % get the estimated errors and variances
%% Simulate periods ahead
[Y] = simulate(fit,2,'Y0',r,'E0',E0,'V0',V0, 'NumPaths',1e5);
ret = sum(Y); % compund the return
histfit(PV0*(exp(ret)-1),100,'normal')
title 'P&L distribution'
ret2d = prctile(ret,0.01); % get the 99% lowest return
VaR = PV0*(exp(ret2d)-1);
fprintf('Today portfolio value: %f\n2-days ahead 99%% VaR: %f\n',PV0,VaR);
Output:
ARIMA(1,0,0) Model:
--------------------
Conditional Probability Distribution: Gaussian
Standard t
Parameter Value Error Statistic
----------- ----------- ------------ -----------
Constant 0 Fixed Fixed
AR{1} -0.020272 0.0697731 -0.290541
GARCH(1,1) Conditional Variance Model:
----------------------------------------
Conditional Probability Distribution: Gaussian
Standard t
Parameter Value Error Statistic
----------- ----------- ------------ -----------
Constant 7.43521e-06 2.14546e-06 3.46556
GARCH{1} 0.653488 0.126818 5.15295
ARCH{1} 0.206016 0.0881823 2.33626
fit =
ARIMA(1,0,0) Model:
--------------------
Distribution: Name = 'Gaussian'
P: 1
D: 0
Q: 0
Constant: 0
AR: {-0.020272} at Lags [1]
SAR: {}
MA: {}
SMA: {}
Variance: [GARCH(1,1) Model]
ans =
GARCH(1,1) Conditional Variance Model:
--------------------------------------
Distribution: Name = 'Gaussian'
P: 1
Q: 1
Constant: 7.43521e-06
GARCH: {0.653488} at Lags [1]
ARCH: {0.206016} at Lags [1]
Today portfolio value: 2090.570000
2-days ahead 99% VaR: -79.986280
For a portfolio consisting of one share of S&P 500 index, I got the current value of \$2091, and 2-day VaR at 99% is \$80.
I also plotted the P&L distribution with Normal fit, so you can see that the normal distribution is not a very good fit. That's why you have to simulate when using GARCH.
You can also look at MATLAB's own GARCH example here.
The idea is that you fit AR(1)-GARCH(1,1) to the returns. Then you Monte-Carlo simulate the returns two days ahead. Then you compound two days of returns in each path, and find 0.01 percentile. This is how much or more you'll lose at 99% confidence in terms of returns, and in terms of dollars it's a simple arithmetic using the current portfolio value.
You can find worked out examples in this book: Carol Alexander, Market Risk Analysis, Volume IV, Value at Risk Models, February 2009
|
Computing VaR with AR-GARCH
This is best done through simulation. See my MATLAB code example and explanation below:
%% Get S&P 500 price series
d=fetch(yahoo,'^GSPC','Adj Close','1-jan-2014','30-dec-2014');
n = 1; % # of shares
|
42,795
|
Understanding confidence intervals in Firth penalized logistic regression
|
The fact that firth=FALSE doesn't give similar results to glm is puzzling to me -- hopefully someone else can answer. As far as pl goes, though, you're almost always better off with profile confidence intervals. The Wald confidence intervals assume that the (implicit) log-likelihood surface is locally quadratic, which is often a bad approximation. Except that they're more computationally intensive, profile confidence intervals are always (? I would welcome counterexamples ?) more accurate. The "improved" p values you get from the Wald estimates are likely overoptimistic.
Generate data:
dd <- data.frame(X=rep(c("yes","no"),c(22,363)),
Y=rep(c("no","yes","no"),c(22,7,356)))
with(dd,table(X,Y))
Replicate:
m_glm <-glm(Y~X,family=binomial,data=dd)
library("logistf")
m_fp <-logistf(Y~X,data=dd,pl=TRUE,firth=TRUE)
m_mp <- logistf(Y~X,data=dd,pl=TRUE,firth=FALSE)
m_fw <-logistf(Y~X,data=dd,pl=FALSE,firth=TRUE)
m_mw <-logistf(Y~X,data=dd,pl=FALSE,firth=FALSE)
Compare Wald (confint.default) with profile CIs for glm (in this case the profile intervals are actually narrower).
confint.default(m_glm) ## {-2740, 2710}
confint(m_glm) ## {NA, 118}
Comparing with the glm2 package (just to make sure that glm isn't doing something wonky).
library("glm2")
glm2(Y~X,family=binomial,data=dd)
## similar results to glm(...)
|
Understanding confidence intervals in Firth penalized logistic regression
|
The fact that firth=FALSE doesn't give similar results to glm is puzzling to me -- hopefully someone else can answer. As far as pl goes, though, you're almost always better off with profile confidenc
|
Understanding confidence intervals in Firth penalized logistic regression
The fact that firth=FALSE doesn't give similar results to glm is puzzling to me -- hopefully someone else can answer. As far as pl goes, though, you're almost always better off with profile confidence intervals. The Wald confidence intervals assume that the (implicit) log-likelihood surface is locally quadratic, which is often a bad approximation. Except that they're more computationally intensive, profile confidence intervals are always (? I would welcome counterexamples ?) more accurate. The "improved" p values you get from the Wald estimates are likely overoptimistic.
Generate data:
dd <- data.frame(X=rep(c("yes","no"),c(22,363)),
Y=rep(c("no","yes","no"),c(22,7,356)))
with(dd,table(X,Y))
Replicate:
m_glm <-glm(Y~X,family=binomial,data=dd)
library("logistf")
m_fp <-logistf(Y~X,data=dd,pl=TRUE,firth=TRUE)
m_mp <- logistf(Y~X,data=dd,pl=TRUE,firth=FALSE)
m_fw <-logistf(Y~X,data=dd,pl=FALSE,firth=TRUE)
m_mw <-logistf(Y~X,data=dd,pl=FALSE,firth=FALSE)
Compare Wald (confint.default) with profile CIs for glm (in this case the profile intervals are actually narrower).
confint.default(m_glm) ## {-2740, 2710}
confint(m_glm) ## {NA, 118}
Comparing with the glm2 package (just to make sure that glm isn't doing something wonky).
library("glm2")
glm2(Y~X,family=binomial,data=dd)
## similar results to glm(...)
|
Understanding confidence intervals in Firth penalized logistic regression
The fact that firth=FALSE doesn't give similar results to glm is puzzling to me -- hopefully someone else can answer. As far as pl goes, though, you're almost always better off with profile confidenc
|
42,796
|
Determining probability mass function (PMF) using Bayesian approach
|
The posterior probability over the set of true media (A,B,C) is a true probability distribution, conditional on the observed medium, A in your case. You only have to apply Bayes' theorem $$P(A\text{ true}|A\text{ observed})=P(A\text{ observed}|A\text{ true})P(A\text{ true})/P(A\text{ observed})$$ The first term on the left $P(A\text{ observed}|A\text{ true})$ comes from the second table, i.e.,
$$P(A\text{ observed}|A\text{ true})=0.2$$ the second $P(A\text{ true})$ from the first table, i.e. $$P(A\text{ true})=0.2$$ and the last one $P(A\text{ observed})$ is the normalisation that makes the whole thing sums up to one, i.e.
$$P(A\text{ observed})=P(A\text{ observed}|A\text{ true})P(A\text{ true})+P(A\text{ observed}|B\text{ true})P(B\text{ true})+P(A\text{ observed}|C\text{ true})P(C\text{ true})=0.2\times0.2+0.5\times0.5+0\times0.3=0.29\,.$$ Therefore
$$P(A\text{ true}|A\text{ observed})=0.04/0.29=0.14\,.$$
|
Determining probability mass function (PMF) using Bayesian approach
|
The posterior probability over the set of true media (A,B,C) is a true probability distribution, conditional on the observed medium, A in your case. You only have to apply Bayes' theorem $$P(A\text{ t
|
Determining probability mass function (PMF) using Bayesian approach
The posterior probability over the set of true media (A,B,C) is a true probability distribution, conditional on the observed medium, A in your case. You only have to apply Bayes' theorem $$P(A\text{ true}|A\text{ observed})=P(A\text{ observed}|A\text{ true})P(A\text{ true})/P(A\text{ observed})$$ The first term on the left $P(A\text{ observed}|A\text{ true})$ comes from the second table, i.e.,
$$P(A\text{ observed}|A\text{ true})=0.2$$ the second $P(A\text{ true})$ from the first table, i.e. $$P(A\text{ true})=0.2$$ and the last one $P(A\text{ observed})$ is the normalisation that makes the whole thing sums up to one, i.e.
$$P(A\text{ observed})=P(A\text{ observed}|A\text{ true})P(A\text{ true})+P(A\text{ observed}|B\text{ true})P(B\text{ true})+P(A\text{ observed}|C\text{ true})P(C\text{ true})=0.2\times0.2+0.5\times0.5+0\times0.3=0.29\,.$$ Therefore
$$P(A\text{ true}|A\text{ observed})=0.04/0.29=0.14\,.$$
|
Determining probability mass function (PMF) using Bayesian approach
The posterior probability over the set of true media (A,B,C) is a true probability distribution, conditional on the observed medium, A in your case. You only have to apply Bayes' theorem $$P(A\text{ t
|
42,797
|
Confidence interval before the first event in a Kaplan–Meier curve
|
Various ways to estimate Kaplan-Meier (KM) confidence intervals (CI) in difficult situations like this--before the first event time, with heavy censoring, or at late times when few are still at risk--have been discussed by Fay et al., "Pointwise confidence intervals for a survival distribution with small samples or heavy censoring," Biostatistics (2013), vol. 14, no. 4, pp. 723–736. Such estimates are possible with some CI methods, they just aren't provided by the default method in the survival package. For example, in the absence of censoring the binomial Clopper-Pearson exact interval for observing no events out of the total number of events, essentially as described in the question and in another answer, could be used.
With censoring, as frequently occurs in survival analysis, things become more complicated. Fay et al. compare 10 KM CI methods against the "beta product confidence procedure (BPCP)" method they propose. BPCP is based on quantiles of a product of beta random variables that is defined in terms of the numbers at risk at each event time up to the survival time of interest. They show that their method provides correct CI coverage for the above types of difficult situations, under some assumptions. They argue for its superiority over other methods if censoring times are simply independent of failure times, and (in a supplement) document its asymptotic equivalence to the Nelson-Aalen and Greenwood CI estimates.
There is an implementation in the R bpcp package. This implementation includes some extensions made since the paper cited above, including two-sample comparisons and handling of discrete-time data.
|
Confidence interval before the first event in a Kaplan–Meier curve
|
Various ways to estimate Kaplan-Meier (KM) confidence intervals (CI) in difficult situations like this--before the first event time, with heavy censoring, or at late times when few are still at risk--
|
Confidence interval before the first event in a Kaplan–Meier curve
Various ways to estimate Kaplan-Meier (KM) confidence intervals (CI) in difficult situations like this--before the first event time, with heavy censoring, or at late times when few are still at risk--have been discussed by Fay et al., "Pointwise confidence intervals for a survival distribution with small samples or heavy censoring," Biostatistics (2013), vol. 14, no. 4, pp. 723–736. Such estimates are possible with some CI methods, they just aren't provided by the default method in the survival package. For example, in the absence of censoring the binomial Clopper-Pearson exact interval for observing no events out of the total number of events, essentially as described in the question and in another answer, could be used.
With censoring, as frequently occurs in survival analysis, things become more complicated. Fay et al. compare 10 KM CI methods against the "beta product confidence procedure (BPCP)" method they propose. BPCP is based on quantiles of a product of beta random variables that is defined in terms of the numbers at risk at each event time up to the survival time of interest. They show that their method provides correct CI coverage for the above types of difficult situations, under some assumptions. They argue for its superiority over other methods if censoring times are simply independent of failure times, and (in a supplement) document its asymptotic equivalence to the Nelson-Aalen and Greenwood CI estimates.
There is an implementation in the R bpcp package. This implementation includes some extensions made since the paper cited above, including two-sample comparisons and handling of discrete-time data.
|
Confidence interval before the first event in a Kaplan–Meier curve
Various ways to estimate Kaplan-Meier (KM) confidence intervals (CI) in difficult situations like this--before the first event time, with heavy censoring, or at late times when few are still at risk--
|
42,798
|
Confidence interval before the first event in a Kaplan–Meier curve
|
seems to me that there should be a way to compute confidence interval on survival prior to the first failure using likelihood concept
the likelihood of seeing $k=0$ zero failures from $n$ units is given by binomial probability probability mass function $B(n,p)$ https://en.wikipedia.org/wiki/Binomial_distribution
if $\alpha$ is 1-tailed confidence level, the corresponding pre-fails survival probability $S_\alpha$ lower confidence bound should be $\alpha^{\frac{1}{n+1}}$for population of size $n$
for example 60% confidence bound for 30 units would be 0.6^(1/31) = 0.984
|
Confidence interval before the first event in a Kaplan–Meier curve
|
seems to me that there should be a way to compute confidence interval on survival prior to the first failure using likelihood concept
the likelihood of seeing $k=0$ zero failures from $n$ units is giv
|
Confidence interval before the first event in a Kaplan–Meier curve
seems to me that there should be a way to compute confidence interval on survival prior to the first failure using likelihood concept
the likelihood of seeing $k=0$ zero failures from $n$ units is given by binomial probability probability mass function $B(n,p)$ https://en.wikipedia.org/wiki/Binomial_distribution
if $\alpha$ is 1-tailed confidence level, the corresponding pre-fails survival probability $S_\alpha$ lower confidence bound should be $\alpha^{\frac{1}{n+1}}$for population of size $n$
for example 60% confidence bound for 30 units would be 0.6^(1/31) = 0.984
|
Confidence interval before the first event in a Kaplan–Meier curve
seems to me that there should be a way to compute confidence interval on survival prior to the first failure using likelihood concept
the likelihood of seeing $k=0$ zero failures from $n$ units is giv
|
42,799
|
What is "fitted function" in the context of boosted regression tree?
|
Your fitted model is best viewed as a function that consumes data points and returns predictions, this is the fitted function in its greatest generality. For example, in linear regression, the fitted model can be expressed as a vector of estimated model coefficients $(\beta_0, \beta_1, \ldots, \beta_n)$, and the fitted function is
$$ f(x) = \beta_0 + \beta_1 x_1 + \cdots + \beta_n x_n $$
For a boosted tree model, the fitted function is
$$ f(x) = g\left( \sum_i T_i(x) \right) $$
where $T_i$ are the individual weak learners (trees in most implementations), and $g$ is a link function. In your example, $g$ converts the predictions from a log-odd to a probability.
Usually in an R package you can evaluate the fitted function by calling predict.
You can evaluate the fitted function on your training data points, these are the fitted values in your second plot.
Your first plots are commonly called partial dependency plots. Generally, the full form of the fitted function is very high dimensional, and cannot be completely visualized by the human imagination. To alleviate this dimensionality problem, partial dependency plots average out the effects of all the variables in the model except one, and plots the average fitted value with respect to the one variable that is left over. It is also possible to make two-dimensional partial dependency plots, which look like a surface, you can see an example here.
|
What is "fitted function" in the context of boosted regression tree?
|
Your fitted model is best viewed as a function that consumes data points and returns predictions, this is the fitted function in its greatest generality. For example, in linear regression, the fitted
|
What is "fitted function" in the context of boosted regression tree?
Your fitted model is best viewed as a function that consumes data points and returns predictions, this is the fitted function in its greatest generality. For example, in linear regression, the fitted model can be expressed as a vector of estimated model coefficients $(\beta_0, \beta_1, \ldots, \beta_n)$, and the fitted function is
$$ f(x) = \beta_0 + \beta_1 x_1 + \cdots + \beta_n x_n $$
For a boosted tree model, the fitted function is
$$ f(x) = g\left( \sum_i T_i(x) \right) $$
where $T_i$ are the individual weak learners (trees in most implementations), and $g$ is a link function. In your example, $g$ converts the predictions from a log-odd to a probability.
Usually in an R package you can evaluate the fitted function by calling predict.
You can evaluate the fitted function on your training data points, these are the fitted values in your second plot.
Your first plots are commonly called partial dependency plots. Generally, the full form of the fitted function is very high dimensional, and cannot be completely visualized by the human imagination. To alleviate this dimensionality problem, partial dependency plots average out the effects of all the variables in the model except one, and plots the average fitted value with respect to the one variable that is left over. It is also possible to make two-dimensional partial dependency plots, which look like a surface, you can see an example here.
|
What is "fitted function" in the context of boosted regression tree?
Your fitted model is best viewed as a function that consumes data points and returns predictions, this is the fitted function in its greatest generality. For example, in linear regression, the fitted
|
42,800
|
Tests of equal variances- am I doing this right?
|
Variance alone isn't suitable, since you're trying to compare closeness to a particular location on the circle. You could have small variance but be nowhere near 0.
If you compare absolute deviation from target, you'd have two sets of values on $[0,\pi]$ (or $[0,180]$ if you prefer to work in degrees), for which you're interested in some general sense of 'closeness' that's not exactly a test for change in location or scale.
Presumably under the null the distributions of deviations from target would be identically distributed, in which case you might consider something like a Wilcoxon-Mann-Whitney.
The original data are of course circular, and you could assume some parametric distribution such the von Mises for each distribution, and construct some parametric comparison of deviation from zero under that assumption (which would have contributions due to deviation in $\mu$ from $0$ and also due to changes in $\kappa$).
You could also do some general test of a difference in distribution (a two-sample goodness of fit test on the circle), and then try to identify whether that's a change in "spread" vs a change in "location" vs some more general difference.
|
Tests of equal variances- am I doing this right?
|
Variance alone isn't suitable, since you're trying to compare closeness to a particular location on the circle. You could have small variance but be nowhere near 0.
If you compare absolute deviation f
|
Tests of equal variances- am I doing this right?
Variance alone isn't suitable, since you're trying to compare closeness to a particular location on the circle. You could have small variance but be nowhere near 0.
If you compare absolute deviation from target, you'd have two sets of values on $[0,\pi]$ (or $[0,180]$ if you prefer to work in degrees), for which you're interested in some general sense of 'closeness' that's not exactly a test for change in location or scale.
Presumably under the null the distributions of deviations from target would be identically distributed, in which case you might consider something like a Wilcoxon-Mann-Whitney.
The original data are of course circular, and you could assume some parametric distribution such the von Mises for each distribution, and construct some parametric comparison of deviation from zero under that assumption (which would have contributions due to deviation in $\mu$ from $0$ and also due to changes in $\kappa$).
You could also do some general test of a difference in distribution (a two-sample goodness of fit test on the circle), and then try to identify whether that's a change in "spread" vs a change in "location" vs some more general difference.
|
Tests of equal variances- am I doing this right?
Variance alone isn't suitable, since you're trying to compare closeness to a particular location on the circle. You could have small variance but be nowhere near 0.
If you compare absolute deviation f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.