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
|
|---|---|---|---|---|---|---|
40,301
|
What is the probability mass function of the scaled Poisson distribution?
|
To avoid confusion, use subscripts to denote the corresponding random variable.
Let $y\in\{0,c,2c,\ldots\}$ and observe that when $c\ne 0$,
$$p_Y(y) = p_X\left(\{x\mid cx=y\}\right) = p_X\left(\{y/c\}\right) = e^{-\lambda}\frac{\lambda^{y/c}}{(y/c)!}.$$
When $c=0$ the only possible value of $y$ is $0$ and
$$p_Y(0) = p_X\left(\{x\mid 0x=0\}\right) = p_X\left(\{0,1,2,\ldots\}\right) = 1.$$
The general rule applied here is that when $X$ is any random variable, $f:\mathbb{R}\to\mathbb{R}$ is a measurable function, and $Y=f(X)$, then for any Borel set $\mathcal{B}\subset\mathbb{R}$
$$\Pr(Y\in\mathcal{B}) = \Pr(f(X)\in\mathcal{B}) = \Pr(X\in f^{-1}(B))$$
where
$$f^{-1}(\mathcal B) = \left\{x\in\mathbb{R}\mid f(x)\in\mathcal{B}\right\}.$$
These aren't really facts about probabilities per se: you can see they are merely stating basic properties of functions.
In this particular case the map is $f(x)=cx$ and $\Pr$ is a Poisson distribution; but exactly the same approach works for any (measurable) $f$ and any distribution whatsoever.
|
What is the probability mass function of the scaled Poisson distribution?
|
To avoid confusion, use subscripts to denote the corresponding random variable.
Let $y\in\{0,c,2c,\ldots\}$ and observe that when $c\ne 0$,
$$p_Y(y) = p_X\left(\{x\mid cx=y\}\right) = p_X\left(\{y/c\
|
What is the probability mass function of the scaled Poisson distribution?
To avoid confusion, use subscripts to denote the corresponding random variable.
Let $y\in\{0,c,2c,\ldots\}$ and observe that when $c\ne 0$,
$$p_Y(y) = p_X\left(\{x\mid cx=y\}\right) = p_X\left(\{y/c\}\right) = e^{-\lambda}\frac{\lambda^{y/c}}{(y/c)!}.$$
When $c=0$ the only possible value of $y$ is $0$ and
$$p_Y(0) = p_X\left(\{x\mid 0x=0\}\right) = p_X\left(\{0,1,2,\ldots\}\right) = 1.$$
The general rule applied here is that when $X$ is any random variable, $f:\mathbb{R}\to\mathbb{R}$ is a measurable function, and $Y=f(X)$, then for any Borel set $\mathcal{B}\subset\mathbb{R}$
$$\Pr(Y\in\mathcal{B}) = \Pr(f(X)\in\mathcal{B}) = \Pr(X\in f^{-1}(B))$$
where
$$f^{-1}(\mathcal B) = \left\{x\in\mathbb{R}\mid f(x)\in\mathcal{B}\right\}.$$
These aren't really facts about probabilities per se: you can see they are merely stating basic properties of functions.
In this particular case the map is $f(x)=cx$ and $\Pr$ is a Poisson distribution; but exactly the same approach works for any (measurable) $f$ and any distribution whatsoever.
|
What is the probability mass function of the scaled Poisson distribution?
To avoid confusion, use subscripts to denote the corresponding random variable.
Let $y\in\{0,c,2c,\ldots\}$ and observe that when $c\ne 0$,
$$p_Y(y) = p_X\left(\{x\mid cx=y\}\right) = p_X\left(\{y/c\
|
40,302
|
Non-Parametric altervative to one sample t-test
|
The 4 doesn't pose any problem. Just subtract 4 from every observation and you can test $\mu=0$ on the shifted data.
There are two common nonparametric tests of location which might be relevant to you -- the Wilcoxon signed rank test and the sign test.
The signed rank test is a test for the pseudo-median. When accompanied by the assumption of symmetry (which the signed rank test needs for the permutations to be equally likely under the null), the population pseudo-median will equal the population median, and (by symmetry) will also equal the population mean when it is finite (which is hereafter assumed to save repeating it every time I mention the mean). Which is to say, under the usual assumptions the signed rank test is a suitable test for a mean as well as a median (keeping in mind that strictly that assumption is only required when the null is actually true).
The sign test doesn't require the assumption of symmetry to be a valid test but it's a test for the median rather than the mean, so you'll still need an assumption that would make the two equal (for which symmetry is sufficient but not necessary, since many asymmetric distributions can also have mean=median).
There's also the possibility of performing a permutation test based on the mean. This will be similar to the signed rank test but performed on the original observations rather than the ranks. In order that the signs can be permuted under the null, you would (again) assume symmetry.
Josh suggested the bootstrap as another possibility, and that should work quite well (though it will tend to have closer to the desired significance level if you have fairly large samples). It should not require any assumption of symmetry.
Another possibility is a different parametric assumption (one more suited to the situation you're sampling, which you haven't stated). For example you might assume that the data are drawn (say) from an exponential distribution, and test whether the mean is 4 against the alternative that it is different from 4.
Finally if the distribution is not very far from normal you might simply proceed with the t-test. [While the significance level might not be badly affected by the non-normality, the power can be if you're not at least reasonably close to normality. This is not an issue that goes away with larger samples.]
|
Non-Parametric altervative to one sample t-test
|
The 4 doesn't pose any problem. Just subtract 4 from every observation and you can test $\mu=0$ on the shifted data.
There are two common nonparametric tests of location which might be relevant to you
|
Non-Parametric altervative to one sample t-test
The 4 doesn't pose any problem. Just subtract 4 from every observation and you can test $\mu=0$ on the shifted data.
There are two common nonparametric tests of location which might be relevant to you -- the Wilcoxon signed rank test and the sign test.
The signed rank test is a test for the pseudo-median. When accompanied by the assumption of symmetry (which the signed rank test needs for the permutations to be equally likely under the null), the population pseudo-median will equal the population median, and (by symmetry) will also equal the population mean when it is finite (which is hereafter assumed to save repeating it every time I mention the mean). Which is to say, under the usual assumptions the signed rank test is a suitable test for a mean as well as a median (keeping in mind that strictly that assumption is only required when the null is actually true).
The sign test doesn't require the assumption of symmetry to be a valid test but it's a test for the median rather than the mean, so you'll still need an assumption that would make the two equal (for which symmetry is sufficient but not necessary, since many asymmetric distributions can also have mean=median).
There's also the possibility of performing a permutation test based on the mean. This will be similar to the signed rank test but performed on the original observations rather than the ranks. In order that the signs can be permuted under the null, you would (again) assume symmetry.
Josh suggested the bootstrap as another possibility, and that should work quite well (though it will tend to have closer to the desired significance level if you have fairly large samples). It should not require any assumption of symmetry.
Another possibility is a different parametric assumption (one more suited to the situation you're sampling, which you haven't stated). For example you might assume that the data are drawn (say) from an exponential distribution, and test whether the mean is 4 against the alternative that it is different from 4.
Finally if the distribution is not very far from normal you might simply proceed with the t-test. [While the significance level might not be badly affected by the non-normality, the power can be if you're not at least reasonably close to normality. This is not an issue that goes away with larger samples.]
|
Non-Parametric altervative to one sample t-test
The 4 doesn't pose any problem. Just subtract 4 from every observation and you can test $\mu=0$ on the shifted data.
There are two common nonparametric tests of location which might be relevant to you
|
40,303
|
Non-Parametric altervative to one sample t-test
|
How large is your sample? Normality of the data is not required for testing the sample mean if the sample size is large enough. A common cutoff given to students is $n=30$.
Alternatively, you could use the Wilcoxon Signed-Rank test, but for one sample that's actually testing the median.
Finally, the bootstrap might work well in this case.
|
Non-Parametric altervative to one sample t-test
|
How large is your sample? Normality of the data is not required for testing the sample mean if the sample size is large enough. A common cutoff given to students is $n=30$.
Alternatively, you could us
|
Non-Parametric altervative to one sample t-test
How large is your sample? Normality of the data is not required for testing the sample mean if the sample size is large enough. A common cutoff given to students is $n=30$.
Alternatively, you could use the Wilcoxon Signed-Rank test, but for one sample that's actually testing the median.
Finally, the bootstrap might work well in this case.
|
Non-Parametric altervative to one sample t-test
How large is your sample? Normality of the data is not required for testing the sample mean if the sample size is large enough. A common cutoff given to students is $n=30$.
Alternatively, you could us
|
40,304
|
Maximum of a probability vector distributed as a Dirichlet variate
|
I am not sure there is a closed-form solution for the distribution of
$p_{(k)}$ when
$(p_1,\ldots,p_k)\sim\text{Dir}(\alpha_1,\ldots,\alpha_k)$ and the
$\alpha_i$'s are different. At least, it seems to be the case when following the natural derivation of the density of $p_{(k)}$.
Indeed, if we start with the Gamma representation of $\text{Dir}(\alpha_1,\ldots,\alpha_k)$ random variables, namely that
$$p_i=\xi_i\Big/\sum_{i=1}^k \xi_i,$$where $$\xi_i\sim\text{Ga}(\alpha_i,1)\,,$$
the index of the maximum in $(p_1,\ldots,p_k)$ is the same as the index of the maximum in $(\xi_1,\ldots,\xi_k)$. Considering the distribution of the maximum of the $\xi_i$'s, namely
$$\xi_{(k)}=\arg\max\{\xi_1,\ldots,\xi_k\},$$ the same argument as the one used for order statistics leads to a marginal distribution with density
\begin{align*}f_k(\xi)&=\sum_{i=1}^k \left\{\prod_{j\ne i} F(\xi;\alpha_j)f(\xi;\alpha_i)\right\}\\
&=\left\{\prod_{i=1}^kF(\xi;\alpha_i)\right\}\sum_{i=1}^k\dfrac{f(\xi;\alpha_i)}{F(\xi;\alpha_i)}\end{align*}
where $f(\cdot;\alpha)$ and $F(\cdot;\alpha)$ are the Ga$(\alpha,1)$ pdf and cdf, respectively. (The later is not available in closed form.)
This means in particular that the probability that the maximum is associated with index $\iota$ is given by
$$\pi_\iota=\int_0^\infty \left\{\prod_{i\ne\iota}F(\xi;\alpha_i)\right\}f(\xi;\alpha_\iota)\,\text{d}\xi$$
(which does not seem to enjoy a closed-formed expression in the general case).
If we now move to the Dirichlet case, we have
$$p_{(k)}=\xi_{(k)}\Big/\sum_{i=1}^k \xi_i=\xi_{(k)}\Big/\{\xi_{(k)}+\sigma\}\,,$$where $\sigma$ denotes the sum of the remaining $\xi_i$'s. Conditional on $\xi_{(k)}$, those $\xi_i$'s are distributed as
$$\sum_{i=1}^k \pi_i \prod_{j\ne i} \left\{\dfrac{f(\xi_j;\alpha_j) }{F(\xi_{(k)};\alpha_j)}\mathbb{I}_{(0,\xi_{(k)})}(\xi_j)\right\}$$modulo a permutation that does not matter for the sum. Therefore the sum $\sigma$ is distributed from the convolution of this density, namely
$$g(\sigma|\xi_{(k)})=\int_{[0,\xi_{(k)}]^{k-2}} \sum_{i=1}^k \pi_i \left\{\prod_{j\ne i,i+1} \dfrac{f(\xi_j;\alpha_j)}{F(\xi_{(k)};\alpha_j)}\right\} \dfrac{f(\sigma_{-i+1};\alpha_{i+1})}{F(\xi_{(k)};\alpha_{i+1})}\,\mathbb{I}_{(0,\xi_{(k)})}(\sigma_{-i+1})\,\prod_{j\ne i,i+1}\text{d}\xi_j$$where
$$\sigma_{-i+1}=\sigma-\sum_{j\ne i,i+1}\xi_j$$denotes the remaining $\xi_{i+1}$ determined by the sum $\sigma$ and the other $\xi_j$, and where $i+1$ is understood modulo $k$, meaning that $k+1\equiv 1$. From there, we can derive the joint density of $(\sigma,\xi_{(k)})$ as $f_k(\xi_{(k)})g(\sigma|\xi_{(k)})$, hence the density of
$$\dfrac{\xi_{(k)}}{\sigma+\xi_{(k)}}$$but there is no hope (?) this approach leads to a closed-form density.
|
Maximum of a probability vector distributed as a Dirichlet variate
|
I am not sure there is a closed-form solution for the distribution of
$p_{(k)}$ when
$(p_1,\ldots,p_k)\sim\text{Dir}(\alpha_1,\ldots,\alpha_k)$ and the
$\alpha_i$'s are different. At least, it
|
Maximum of a probability vector distributed as a Dirichlet variate
I am not sure there is a closed-form solution for the distribution of
$p_{(k)}$ when
$(p_1,\ldots,p_k)\sim\text{Dir}(\alpha_1,\ldots,\alpha_k)$ and the
$\alpha_i$'s are different. At least, it seems to be the case when following the natural derivation of the density of $p_{(k)}$.
Indeed, if we start with the Gamma representation of $\text{Dir}(\alpha_1,\ldots,\alpha_k)$ random variables, namely that
$$p_i=\xi_i\Big/\sum_{i=1}^k \xi_i,$$where $$\xi_i\sim\text{Ga}(\alpha_i,1)\,,$$
the index of the maximum in $(p_1,\ldots,p_k)$ is the same as the index of the maximum in $(\xi_1,\ldots,\xi_k)$. Considering the distribution of the maximum of the $\xi_i$'s, namely
$$\xi_{(k)}=\arg\max\{\xi_1,\ldots,\xi_k\},$$ the same argument as the one used for order statistics leads to a marginal distribution with density
\begin{align*}f_k(\xi)&=\sum_{i=1}^k \left\{\prod_{j\ne i} F(\xi;\alpha_j)f(\xi;\alpha_i)\right\}\\
&=\left\{\prod_{i=1}^kF(\xi;\alpha_i)\right\}\sum_{i=1}^k\dfrac{f(\xi;\alpha_i)}{F(\xi;\alpha_i)}\end{align*}
where $f(\cdot;\alpha)$ and $F(\cdot;\alpha)$ are the Ga$(\alpha,1)$ pdf and cdf, respectively. (The later is not available in closed form.)
This means in particular that the probability that the maximum is associated with index $\iota$ is given by
$$\pi_\iota=\int_0^\infty \left\{\prod_{i\ne\iota}F(\xi;\alpha_i)\right\}f(\xi;\alpha_\iota)\,\text{d}\xi$$
(which does not seem to enjoy a closed-formed expression in the general case).
If we now move to the Dirichlet case, we have
$$p_{(k)}=\xi_{(k)}\Big/\sum_{i=1}^k \xi_i=\xi_{(k)}\Big/\{\xi_{(k)}+\sigma\}\,,$$where $\sigma$ denotes the sum of the remaining $\xi_i$'s. Conditional on $\xi_{(k)}$, those $\xi_i$'s are distributed as
$$\sum_{i=1}^k \pi_i \prod_{j\ne i} \left\{\dfrac{f(\xi_j;\alpha_j) }{F(\xi_{(k)};\alpha_j)}\mathbb{I}_{(0,\xi_{(k)})}(\xi_j)\right\}$$modulo a permutation that does not matter for the sum. Therefore the sum $\sigma$ is distributed from the convolution of this density, namely
$$g(\sigma|\xi_{(k)})=\int_{[0,\xi_{(k)}]^{k-2}} \sum_{i=1}^k \pi_i \left\{\prod_{j\ne i,i+1} \dfrac{f(\xi_j;\alpha_j)}{F(\xi_{(k)};\alpha_j)}\right\} \dfrac{f(\sigma_{-i+1};\alpha_{i+1})}{F(\xi_{(k)};\alpha_{i+1})}\,\mathbb{I}_{(0,\xi_{(k)})}(\sigma_{-i+1})\,\prod_{j\ne i,i+1}\text{d}\xi_j$$where
$$\sigma_{-i+1}=\sigma-\sum_{j\ne i,i+1}\xi_j$$denotes the remaining $\xi_{i+1}$ determined by the sum $\sigma$ and the other $\xi_j$, and where $i+1$ is understood modulo $k$, meaning that $k+1\equiv 1$. From there, we can derive the joint density of $(\sigma,\xi_{(k)})$ as $f_k(\xi_{(k)})g(\sigma|\xi_{(k)})$, hence the density of
$$\dfrac{\xi_{(k)}}{\sigma+\xi_{(k)}}$$but there is no hope (?) this approach leads to a closed-form density.
|
Maximum of a probability vector distributed as a Dirichlet variate
I am not sure there is a closed-form solution for the distribution of
$p_{(k)}$ when
$(p_1,\ldots,p_k)\sim\text{Dir}(\alpha_1,\ldots,\alpha_k)$ and the
$\alpha_i$'s are different. At least, it
|
40,305
|
Intuition behind regression sum of squares
|
Just a bit of a misunderstanding with the definitions, I believe:
\begin{align}
\text{SST}_{\text{otal}} &= \color{red}{\text{SSE}_{\text{xplained}}}+\color{blue}{\text{SSR}_{\text{esidual}}}\\
\end{align}
or, equivalently,
\begin{align}
\sum(y_i-\bar y)^2 &=\color{red}{\sum(\hat y_i-\bar y)^2}+\color{blue}{\sum(y_i-\hat y_i)^2}
\end{align}
and
$\large \text{R}^2 = 1 - \frac{\text{SSR}_{\text{esidual}}}{\text{SST}_{\text{otal}}}$
So if the model explained all the variation, $\text{SSR}_{\text{esidual}}=\sum(y_i-\hat y_i)^2=0$, and $\bf R^2=1.$
From Wikipedia:
Suppose $r = 0.7$ then $R^2 = 0.49$ and it implies that $49\%$ of the
variability between the two variables have been accounted for and the
remaining $51\%$ of the variability is still unaccounted for.
The sum of the squared distances between the mean ($\bar Y$) and the fitted values ($\hat Y$) (the SSExplained) is the part of the distance from the mean to the actual value ($ Y$) (TSS) that the model has been able to account for. The difference between these two calculations, is the unexplained part of the variation (the residuals). If you take TSS as a fixed value, the higher the SSExplained, the lower the SSResidual, and hence the closer to 1 R.Square will be.
Here is some intuition, at the risk of actually making clear waters murky. In OLS we minimize distances to the points in the data cloud in an overdetermined system, rendering a line that fulfills $\text{SST}>\text{SSE}$. The difference is the $\text{SSR}$ (residuals).
But let's imagine a data "cloud" of three points, all perfectly aligned. Now, let's play a game of actually doing the opposite of an OLS: we are going to increase the error by proposing a line different from the line that goes through all the points, using the mean as a fulcrum. Remember that the OLS goes through the mean values $({\bf \bar X, \bar Y})$, which is the blue point in the middle, through which we draw a horizontal line. In this case, opposite to the expected situation in OLS and just to illustrate the point, we can see how by moving the line from having zero $\text{SSR}$ (all the variance, $\text{SST}$ accounted by the model (the line), $\text{SSE}$) on the left "column" of the diagram, we introduce residual errors (in red, on the right part of the diagram):
Logically, by minimizing errors, and in the typical situation of an overdetermined system, the $\text{SST}> \text{SSE}$, and the difference will correspond to the $\text{SSR}$.
Here is a quick example with a widely available data set in R:
fit = lm(mpg ~ wt, mtcars)
summary(fit)$r.square
[1] 0.7528328
> sse = sum((fitted(fit) - mean(mtcars$mpg))^2)
> ssr = sum((fitted(fit) - mtcars$mpg)^2)
> 1 - (ssr/(sse + ssr))
[1] 0.7528328
|
Intuition behind regression sum of squares
|
Just a bit of a misunderstanding with the definitions, I believe:
\begin{align}
\text{SST}_{\text{otal}} &= \color{red}{\text{SSE}_{\text{xplained}}}+\color{blue}{\text{SSR}_{\text{esidual}}}\\
\end{a
|
Intuition behind regression sum of squares
Just a bit of a misunderstanding with the definitions, I believe:
\begin{align}
\text{SST}_{\text{otal}} &= \color{red}{\text{SSE}_{\text{xplained}}}+\color{blue}{\text{SSR}_{\text{esidual}}}\\
\end{align}
or, equivalently,
\begin{align}
\sum(y_i-\bar y)^2 &=\color{red}{\sum(\hat y_i-\bar y)^2}+\color{blue}{\sum(y_i-\hat y_i)^2}
\end{align}
and
$\large \text{R}^2 = 1 - \frac{\text{SSR}_{\text{esidual}}}{\text{SST}_{\text{otal}}}$
So if the model explained all the variation, $\text{SSR}_{\text{esidual}}=\sum(y_i-\hat y_i)^2=0$, and $\bf R^2=1.$
From Wikipedia:
Suppose $r = 0.7$ then $R^2 = 0.49$ and it implies that $49\%$ of the
variability between the two variables have been accounted for and the
remaining $51\%$ of the variability is still unaccounted for.
The sum of the squared distances between the mean ($\bar Y$) and the fitted values ($\hat Y$) (the SSExplained) is the part of the distance from the mean to the actual value ($ Y$) (TSS) that the model has been able to account for. The difference between these two calculations, is the unexplained part of the variation (the residuals). If you take TSS as a fixed value, the higher the SSExplained, the lower the SSResidual, and hence the closer to 1 R.Square will be.
Here is some intuition, at the risk of actually making clear waters murky. In OLS we minimize distances to the points in the data cloud in an overdetermined system, rendering a line that fulfills $\text{SST}>\text{SSE}$. The difference is the $\text{SSR}$ (residuals).
But let's imagine a data "cloud" of three points, all perfectly aligned. Now, let's play a game of actually doing the opposite of an OLS: we are going to increase the error by proposing a line different from the line that goes through all the points, using the mean as a fulcrum. Remember that the OLS goes through the mean values $({\bf \bar X, \bar Y})$, which is the blue point in the middle, through which we draw a horizontal line. In this case, opposite to the expected situation in OLS and just to illustrate the point, we can see how by moving the line from having zero $\text{SSR}$ (all the variance, $\text{SST}$ accounted by the model (the line), $\text{SSE}$) on the left "column" of the diagram, we introduce residual errors (in red, on the right part of the diagram):
Logically, by minimizing errors, and in the typical situation of an overdetermined system, the $\text{SST}> \text{SSE}$, and the difference will correspond to the $\text{SSR}$.
Here is a quick example with a widely available data set in R:
fit = lm(mpg ~ wt, mtcars)
summary(fit)$r.square
[1] 0.7528328
> sse = sum((fitted(fit) - mean(mtcars$mpg))^2)
> ssr = sum((fitted(fit) - mtcars$mpg)^2)
> 1 - (ssr/(sse + ssr))
[1] 0.7528328
|
Intuition behind regression sum of squares
Just a bit of a misunderstanding with the definitions, I believe:
\begin{align}
\text{SST}_{\text{otal}} &= \color{red}{\text{SSE}_{\text{xplained}}}+\color{blue}{\text{SSR}_{\text{esidual}}}\\
\end{a
|
40,306
|
Intuition behind regression sum of squares
|
why do we want a big difference between ŷ and ȳ?
maybe the graphs A, B, C, and D can be intuitively useful by visualizing the differences or distances between the
1. systolic blood pressure of each person from the mean systolic blood pressure(y-ȳ),
2. between the systolic blood pressure of each person from the regression line (y-ŷ),
3. and between the regression line and the mean systolic blood pressure (ŷ-ȳ).
the sum of squared differences of each sbp from the mean is the total sum of squares (tss) as shown in graph A.
if serum cholesterol is added or fitted as a predictor (x), a regression line can be placed on the graph. the sum of squared differences of each sbp value from the regression line is the regression sum of squares or explained sum of squares (rss or ess) as shown in graph B.
if the sum of squared differences of each sbp value from the regression line is smaller than the total sum of squares, then the regression line (serum cholesterol) has a better fit to the data than the mean sbp. the better the fit of the regression line the smaller the residual sum of squares( graph C).
if all the sbp fall perfectly on the regression line, then the residual sum of squares is zero and the regression sum of squares or explained sum of squares is equal to the total sum of squares (graph D). this means that all variation in sbp can be explained by variation in serum cholesterol.
to address the question: why do we want a big difference between ŷ and ȳ?
as the residual sum of squares approaches zero, the total sum of squares shrink until it is equal to the regression sum of squares when the y = ŷ. it this case, the mean of ŷ = ȳ.
|
Intuition behind regression sum of squares
|
why do we want a big difference between ŷ and ȳ?
maybe the graphs A, B, C, and D can be intuitively useful by visualizing the differences or distances between the
1. systolic blood pressure of each p
|
Intuition behind regression sum of squares
why do we want a big difference between ŷ and ȳ?
maybe the graphs A, B, C, and D can be intuitively useful by visualizing the differences or distances between the
1. systolic blood pressure of each person from the mean systolic blood pressure(y-ȳ),
2. between the systolic blood pressure of each person from the regression line (y-ŷ),
3. and between the regression line and the mean systolic blood pressure (ŷ-ȳ).
the sum of squared differences of each sbp from the mean is the total sum of squares (tss) as shown in graph A.
if serum cholesterol is added or fitted as a predictor (x), a regression line can be placed on the graph. the sum of squared differences of each sbp value from the regression line is the regression sum of squares or explained sum of squares (rss or ess) as shown in graph B.
if the sum of squared differences of each sbp value from the regression line is smaller than the total sum of squares, then the regression line (serum cholesterol) has a better fit to the data than the mean sbp. the better the fit of the regression line the smaller the residual sum of squares( graph C).
if all the sbp fall perfectly on the regression line, then the residual sum of squares is zero and the regression sum of squares or explained sum of squares is equal to the total sum of squares (graph D). this means that all variation in sbp can be explained by variation in serum cholesterol.
to address the question: why do we want a big difference between ŷ and ȳ?
as the residual sum of squares approaches zero, the total sum of squares shrink until it is equal to the regression sum of squares when the y = ŷ. it this case, the mean of ŷ = ȳ.
|
Intuition behind regression sum of squares
why do we want a big difference between ŷ and ȳ?
maybe the graphs A, B, C, and D can be intuitively useful by visualizing the differences or distances between the
1. systolic blood pressure of each p
|
40,307
|
Intuition behind regression sum of squares
|
This is the note I wrote for self studying purpose. I don't have much time to improve this due to lack of my English ability. But I guess this would be helpful. So I just paste this here. I will add some details later.
linear models
We can come up with several linear models with error $\vec \epsilon$
$\vec y=\vec \epsilon$ (It isn't model technically. There is no $\beta$s but I'd consider this as a linear model for explanation)
$\vec y=\beta_0 \vec 1+ \vec \epsilon$ (0th model)
$\vec y=\beta_0 \vec 1+ \beta_1 \vec x_1 +\vec \epsilon$ (1st model)
$\vec y=\beta_0 \vec 1 +\beta_1 \vec x_1 +...+\beta_n \vec x_n + \vec \epsilon$ (nth model)
$m$th model least square fit minimizing error $\vec \epsilon ' \vec \epsilon$
$\hat y_{(m)}=X_{(m)}\hat \beta_{(m)}$ (vector symbols omitted.)
$X_{(m)}=[\vec 1 \ \ \vec x_1 \ \ \vec x_2 \ \ ... \ \ \vec x_m ]$
$\hat \beta_{(m)}=(X_{(m)}'X_{(m)})^{-1}X_{(m)}' \vec y=(\hat \beta_0 \ \ \hat \beta_1 \ \ ...\ \ \hat \beta_m)'$
$SS_{residual}=\sum(\hat y^2_{i(m)}-y_i)^2$
$0$th model least square fit.
$\hat y_{(0)}=\vec 1(\vec 1' \vec 1)^{-1} \vec 1' \vec y=\bar y \vec 1$
What does regression really mean?
Let's consider this :$\sum y_i^2$.
If there's no model we there would be no regression so every $y_i$ can be treated as an error. (In other words, we can say the model is 0.) Then total error would be $\sum y_i^2$
Now let's adopt 0th model which is we don't consider any regressors ($x$s)
The error of 0th model is $\sum(\hat y_{i(0)}-y_i)^2=\sum(\bar y-y_i)^2$.
We can explain the error $\sum y_i^2-\sum(\bar y-y_i)^2=\sum \bar y^2$ and this is the regression of model 0th.
We can extend this in the same way to the nth model like below equation.
$$\sum y_i^2 = \sum \bar{y}^2_{(0)}+\sum(\bar{y}_{(0)}-\hat y_{i(1)})^2+\sum(\hat y_{i(1)}-\hat y_{i(2)})^2+...+\sum(\hat y_{i(n-1)}-\hat y_{i(n)})^2+\sum(\hat y_{i(n)}-y_i)^2$$
proof> First prove that $\sum (\hat y_{i(n-1)}-\hat y_{i(n)})(\hat y_{i(n)}-y_i) =0$
On the right hand, except the last term, is the regression of nth model.
Note this :
$\sum(\hat y_{i(n-1)}-\hat y_{i(n)})^2=(X_{(n-1)}\hat \beta_{(n-1)}-X_{(n)}\hat \beta_{(n)})'(X_{(n-1)}\hat \beta_{(n-1)}-X_{(n)}\hat \beta_{(n)})$
$=\vec y'X_{(n)}(X_{(n)}'X_{(n)})^{-1}X_{(n)}' \vec y-\vec y'X_{(n-1)}(X_{(n-1)}'X_{(n-1)})^{-1}X_{(n-1)}' \vec y$
$=\hat \beta_{(n)}'X_{(n)}'\vec y-\hat \beta_{(n-1)}'X_{(n-1)}'\vec y$
Using this we can reduce those terms.
Let the regression of nth model $SS_R(\hat \beta_{(n)})=\hat \beta_{(n)}'X_{(n)}'\vec y$. This is the regression sum of squares due to $\hat \beta_{(n)}$
$$\sum y_i^2 = SS_R(\hat \beta_{(n)})+\sum(\hat y_{i(n)}-y_i)^2$$
Now substract 0th model's regression from each side of the equation.
$SS_{total}=\sum (y_i-\bar y)^2 = SS_R(\hat \beta_{(n)} )-SS_R(\hat \beta_{(0)})+\sum(\hat y_{i(n)}-y_i)^2$
This is the equation we usually consider during ANOVA method.
Now we can see that $SS_R( ( \hat \beta_1 \ \ ...\ \ \hat \beta_n)')=SS_R(\hat \beta_{(n)} )-SS_R(\hat \beta_{(0)})$, extra sum of squares due to $( \hat \beta_1 \ \ ...\ \ \hat \beta_n)'$ given $\beta_{(0)}=\hat \beta_0 \vec 1 =\bar y \vec 1$
So I guess regression sum of squares is how more we can explain the data than 0th model.
Model with no intercept
Here we don't consider 0th model.
$\vec y=\beta_1 \vec x_1+ \vec \epsilon$
By minimizing $\vec \epsilon'\vec \epsilon$ we can get
$\sum y_i^2 =\sum(\hat y_{i(1)})^2+\sum(\hat y_{i(1)}-y_i)^2$
So in this case $SS_R=\sum(\hat y_{i(1)})^2$
|
Intuition behind regression sum of squares
|
This is the note I wrote for self studying purpose. I don't have much time to improve this due to lack of my English ability. But I guess this would be helpful. So I just paste this here. I will add s
|
Intuition behind regression sum of squares
This is the note I wrote for self studying purpose. I don't have much time to improve this due to lack of my English ability. But I guess this would be helpful. So I just paste this here. I will add some details later.
linear models
We can come up with several linear models with error $\vec \epsilon$
$\vec y=\vec \epsilon$ (It isn't model technically. There is no $\beta$s but I'd consider this as a linear model for explanation)
$\vec y=\beta_0 \vec 1+ \vec \epsilon$ (0th model)
$\vec y=\beta_0 \vec 1+ \beta_1 \vec x_1 +\vec \epsilon$ (1st model)
$\vec y=\beta_0 \vec 1 +\beta_1 \vec x_1 +...+\beta_n \vec x_n + \vec \epsilon$ (nth model)
$m$th model least square fit minimizing error $\vec \epsilon ' \vec \epsilon$
$\hat y_{(m)}=X_{(m)}\hat \beta_{(m)}$ (vector symbols omitted.)
$X_{(m)}=[\vec 1 \ \ \vec x_1 \ \ \vec x_2 \ \ ... \ \ \vec x_m ]$
$\hat \beta_{(m)}=(X_{(m)}'X_{(m)})^{-1}X_{(m)}' \vec y=(\hat \beta_0 \ \ \hat \beta_1 \ \ ...\ \ \hat \beta_m)'$
$SS_{residual}=\sum(\hat y^2_{i(m)}-y_i)^2$
$0$th model least square fit.
$\hat y_{(0)}=\vec 1(\vec 1' \vec 1)^{-1} \vec 1' \vec y=\bar y \vec 1$
What does regression really mean?
Let's consider this :$\sum y_i^2$.
If there's no model we there would be no regression so every $y_i$ can be treated as an error. (In other words, we can say the model is 0.) Then total error would be $\sum y_i^2$
Now let's adopt 0th model which is we don't consider any regressors ($x$s)
The error of 0th model is $\sum(\hat y_{i(0)}-y_i)^2=\sum(\bar y-y_i)^2$.
We can explain the error $\sum y_i^2-\sum(\bar y-y_i)^2=\sum \bar y^2$ and this is the regression of model 0th.
We can extend this in the same way to the nth model like below equation.
$$\sum y_i^2 = \sum \bar{y}^2_{(0)}+\sum(\bar{y}_{(0)}-\hat y_{i(1)})^2+\sum(\hat y_{i(1)}-\hat y_{i(2)})^2+...+\sum(\hat y_{i(n-1)}-\hat y_{i(n)})^2+\sum(\hat y_{i(n)}-y_i)^2$$
proof> First prove that $\sum (\hat y_{i(n-1)}-\hat y_{i(n)})(\hat y_{i(n)}-y_i) =0$
On the right hand, except the last term, is the regression of nth model.
Note this :
$\sum(\hat y_{i(n-1)}-\hat y_{i(n)})^2=(X_{(n-1)}\hat \beta_{(n-1)}-X_{(n)}\hat \beta_{(n)})'(X_{(n-1)}\hat \beta_{(n-1)}-X_{(n)}\hat \beta_{(n)})$
$=\vec y'X_{(n)}(X_{(n)}'X_{(n)})^{-1}X_{(n)}' \vec y-\vec y'X_{(n-1)}(X_{(n-1)}'X_{(n-1)})^{-1}X_{(n-1)}' \vec y$
$=\hat \beta_{(n)}'X_{(n)}'\vec y-\hat \beta_{(n-1)}'X_{(n-1)}'\vec y$
Using this we can reduce those terms.
Let the regression of nth model $SS_R(\hat \beta_{(n)})=\hat \beta_{(n)}'X_{(n)}'\vec y$. This is the regression sum of squares due to $\hat \beta_{(n)}$
$$\sum y_i^2 = SS_R(\hat \beta_{(n)})+\sum(\hat y_{i(n)}-y_i)^2$$
Now substract 0th model's regression from each side of the equation.
$SS_{total}=\sum (y_i-\bar y)^2 = SS_R(\hat \beta_{(n)} )-SS_R(\hat \beta_{(0)})+\sum(\hat y_{i(n)}-y_i)^2$
This is the equation we usually consider during ANOVA method.
Now we can see that $SS_R( ( \hat \beta_1 \ \ ...\ \ \hat \beta_n)')=SS_R(\hat \beta_{(n)} )-SS_R(\hat \beta_{(0)})$, extra sum of squares due to $( \hat \beta_1 \ \ ...\ \ \hat \beta_n)'$ given $\beta_{(0)}=\hat \beta_0 \vec 1 =\bar y \vec 1$
So I guess regression sum of squares is how more we can explain the data than 0th model.
Model with no intercept
Here we don't consider 0th model.
$\vec y=\beta_1 \vec x_1+ \vec \epsilon$
By minimizing $\vec \epsilon'\vec \epsilon$ we can get
$\sum y_i^2 =\sum(\hat y_{i(1)})^2+\sum(\hat y_{i(1)}-y_i)^2$
So in this case $SS_R=\sum(\hat y_{i(1)})^2$
|
Intuition behind regression sum of squares
This is the note I wrote for self studying purpose. I don't have much time to improve this due to lack of my English ability. But I guess this would be helpful. So I just paste this here. I will add s
|
40,308
|
How, in practice, are spatial covariances determined?
|
To expand on my comment, commonly "spatial covariance" is associated with Gaussian Processes, which are typically assumed to be stationary. Furthermore, in practice the spatial covariance function (kernel) is assumed to be non-negative and decay with distance. The standard setup is then to assume that your spatial (sample) domain is much larger than the correlation length, so that under the ergodic hypothesis, ensemble averages are well approximated by spatial averages. In this framework, empirical (auto-)correlation functions can be estimated using e.g. spectral methods. So a parametric fit of some particular model is not always required in practice.
Now, in my work I encounter a lot of geostatistics, where all of these assumptions are commonly taken for granted, even though they blatantly do not apply (simple parametric fits are also common). As this is a pet peeve of mine, I would like to take a moment here to contrast the standard geostatistics approach with a technique from computer vision, to demonstrate how one might relax the stationary assumption.
Consider the common geostatistics paradigm of a zero-mean stationary random field $z[\mathbf{x}]$ with variance $\sigma^2$. Typically geostatistics does not use the covariance function directly, but rather uses the variogram, defined for some lag $\mathbf{h}$ as
$$\gamma[\mathbf{h}]\equiv\langle (z[\mathbf{x}+\mathbf{h}]-z[\mathbf{x}])^2\rangle=2(\sigma^2-\kappa[\mathbf{h}])$$
where $\kappa[\mathbf{h}]$ is the (auto-)covariance function, and the last equality comes from expanding the terms in the average and invoking the stationary assumption.
A quite similar construction is commonly used in computer vision, but is derived somewhat differently. If we assume that $z$ is differentiable, then we can approximate the variogram as
$$\gamma[\mathbf{h}]\equiv\langle (z[\mathbf{x}+\mathbf{h}]-z[\mathbf{x}])^2\rangle\approx\langle (\mathbf{S}[\mathbf{x}]^T\mathbf{h})^2\rangle=\mathbf{h}^T\langle \mathbf{S}\mathbf{S}^T\rangle\mathbf{h}\equiv\mathbf{h}^T\mathbf{T}\mathbf{h}$$
where $\mathbf{S}$ is the gradient of $z$ and $\mathbf{T}$ is known as the structure tensor.
A key difference between the geostatistical variogram and the structure tensor is that the latter is not assumed to be stationary. Rather, $\mathbf{T}$ is used to describe the local texture in an image (or in 3D, e.g. seismic or medical imaging data). A simple Google image search will show numerous examples of non-stationary structure, which is perhaps the norm (i.e. the classical geostatistics assumptions are quite commonly invalid).
EDIT: This structure-tensor demo on "Lena" (from a Matlab toolbox by Gabriel Peyre) gives a nice illustration of the texture information the tensor field captures.
|
How, in practice, are spatial covariances determined?
|
To expand on my comment, commonly "spatial covariance" is associated with Gaussian Processes, which are typically assumed to be stationary. Furthermore, in practice the spatial covariance function (ke
|
How, in practice, are spatial covariances determined?
To expand on my comment, commonly "spatial covariance" is associated with Gaussian Processes, which are typically assumed to be stationary. Furthermore, in practice the spatial covariance function (kernel) is assumed to be non-negative and decay with distance. The standard setup is then to assume that your spatial (sample) domain is much larger than the correlation length, so that under the ergodic hypothesis, ensemble averages are well approximated by spatial averages. In this framework, empirical (auto-)correlation functions can be estimated using e.g. spectral methods. So a parametric fit of some particular model is not always required in practice.
Now, in my work I encounter a lot of geostatistics, where all of these assumptions are commonly taken for granted, even though they blatantly do not apply (simple parametric fits are also common). As this is a pet peeve of mine, I would like to take a moment here to contrast the standard geostatistics approach with a technique from computer vision, to demonstrate how one might relax the stationary assumption.
Consider the common geostatistics paradigm of a zero-mean stationary random field $z[\mathbf{x}]$ with variance $\sigma^2$. Typically geostatistics does not use the covariance function directly, but rather uses the variogram, defined for some lag $\mathbf{h}$ as
$$\gamma[\mathbf{h}]\equiv\langle (z[\mathbf{x}+\mathbf{h}]-z[\mathbf{x}])^2\rangle=2(\sigma^2-\kappa[\mathbf{h}])$$
where $\kappa[\mathbf{h}]$ is the (auto-)covariance function, and the last equality comes from expanding the terms in the average and invoking the stationary assumption.
A quite similar construction is commonly used in computer vision, but is derived somewhat differently. If we assume that $z$ is differentiable, then we can approximate the variogram as
$$\gamma[\mathbf{h}]\equiv\langle (z[\mathbf{x}+\mathbf{h}]-z[\mathbf{x}])^2\rangle\approx\langle (\mathbf{S}[\mathbf{x}]^T\mathbf{h})^2\rangle=\mathbf{h}^T\langle \mathbf{S}\mathbf{S}^T\rangle\mathbf{h}\equiv\mathbf{h}^T\mathbf{T}\mathbf{h}$$
where $\mathbf{S}$ is the gradient of $z$ and $\mathbf{T}$ is known as the structure tensor.
A key difference between the geostatistical variogram and the structure tensor is that the latter is not assumed to be stationary. Rather, $\mathbf{T}$ is used to describe the local texture in an image (or in 3D, e.g. seismic or medical imaging data). A simple Google image search will show numerous examples of non-stationary structure, which is perhaps the norm (i.e. the classical geostatistics assumptions are quite commonly invalid).
EDIT: This structure-tensor demo on "Lena" (from a Matlab toolbox by Gabriel Peyre) gives a nice illustration of the texture information the tensor field captures.
|
How, in practice, are spatial covariances determined?
To expand on my comment, commonly "spatial covariance" is associated with Gaussian Processes, which are typically assumed to be stationary. Furthermore, in practice the spatial covariance function (ke
|
40,309
|
How caret calculates R Squared
|
The code is here:
> R2
function(pred, obs, formula = "corr", na.rm = FALSE) {
n <- sum(complete.cases(pred))
switch(formula,
corr = cor(obs, pred, use = ifelse(na.rm, "complete.obs", "everything"))^2,
traditional = 1 - (sum((obs-pred)^2, na.rm = na.rm)/((n-1)*var(obs, na.rm = na.rm))))
}
It follows the idea of calculating R then squaring it. There are a lot of formulas for R^2 that can be used. See Kvalseth. Cautionary note about R^2. American Statistician (1985) vol. 39 (4) pp. 279-285. All of this is described at ?R2.
|
How caret calculates R Squared
|
The code is here:
> R2
function(pred, obs, formula = "corr", na.rm = FALSE) {
n <- sum(complete.cases(pred))
switch(formula,
corr = cor(obs, pred, use = ifelse(na.rm, "complete.obs
|
How caret calculates R Squared
The code is here:
> R2
function(pred, obs, formula = "corr", na.rm = FALSE) {
n <- sum(complete.cases(pred))
switch(formula,
corr = cor(obs, pred, use = ifelse(na.rm, "complete.obs", "everything"))^2,
traditional = 1 - (sum((obs-pred)^2, na.rm = na.rm)/((n-1)*var(obs, na.rm = na.rm))))
}
It follows the idea of calculating R then squaring it. There are a lot of formulas for R^2 that can be used. See Kvalseth. Cautionary note about R^2. American Statistician (1985) vol. 39 (4) pp. 279-285. All of this is described at ?R2.
|
How caret calculates R Squared
The code is here:
> R2
function(pred, obs, formula = "corr", na.rm = FALSE) {
n <- sum(complete.cases(pred))
switch(formula,
corr = cor(obs, pred, use = ifelse(na.rm, "complete.obs
|
40,310
|
How caret calculates R Squared
|
Update: The R2 function is deprecated.
You can get R2 by the postResample function now.
The code is here and shows in line 136 and 142 the formula:
resamplCor <- try(cor(pred, obs, use = "pairwise.complete.obs"), silent = TRUE
...
out <- c(sqrt(mse), resamplCor^2, mae)
So postResample uses the squared correlation to calculate R2.
|
How caret calculates R Squared
|
Update: The R2 function is deprecated.
You can get R2 by the postResample function now.
The code is here and shows in line 136 and 142 the formula:
resamplCor <- try(cor(pred, obs, use = "pairwise.co
|
How caret calculates R Squared
Update: The R2 function is deprecated.
You can get R2 by the postResample function now.
The code is here and shows in line 136 and 142 the formula:
resamplCor <- try(cor(pred, obs, use = "pairwise.complete.obs"), silent = TRUE
...
out <- c(sqrt(mse), resamplCor^2, mae)
So postResample uses the squared correlation to calculate R2.
|
How caret calculates R Squared
Update: The R2 function is deprecated.
You can get R2 by the postResample function now.
The code is here and shows in line 136 and 142 the formula:
resamplCor <- try(cor(pred, obs, use = "pairwise.co
|
40,311
|
Where does the number 12 come from and why is it the same 12 in Wilcoxon and Kruskal Wallis?
|
In both cases 12 appears when approximating the distribution of the test statistic with a normal and chi-square respectively because the statistic must first be written in a standardized form (if you were performing a permutation test these constants would be unnecessary). With continuous data, the ranks from $1$ to $n$ are used, and the variance of a randomly chosen value from $(1,2,3,...,n)$ is $(n^2-1)/12$.
[Consider that the expectation of a randomly chosen rank from $1$ to $n$ is $(n+1)/2$ and the expected value of the square of a randomly chosen rank is $n(n+1)(2n+1)/(6n)$; the variance of a randomly chosen rank is therefore $(n+1)(n-1)/12$. Similarly, the covariance of two randomly selected values (chosen without replacement) from $(1,2,3,...,n)$ is $-(n+1)/12$.]
As a result the variance of either the sum or the average of $m$ randomly chosen ranks from $(1,2,3,...,n)$ will have $12$ in it.
There's no "inversion" of the 12 differently in either formula - in both cases there's a denominator term involving a function of (something/12). If you divide by something/12 that's the same as multiplying by 12/something. So in the Kruskal-Wallis we see it simplified to be written that "12/something" way. In the Wilcoxon rank sum test when you're using the normal approximation you divide by the square root of the variance, so there's a $\sqrt{}$(something/12) in the denominator; it could as easily be written as $\times \sqrt{}$(12/something).
For similar reasons (at heart, because an expected squared rank involves $\sum_{i=1}^n i^2$), either 12 or 6 (or sometimes a 24) appears in formulas related to many other rank-based statistics.
|
Where does the number 12 come from and why is it the same 12 in Wilcoxon and Kruskal Wallis?
|
In both cases 12 appears when approximating the distribution of the test statistic with a normal and chi-square respectively because the statistic must first be written in a standardized form (if you
|
Where does the number 12 come from and why is it the same 12 in Wilcoxon and Kruskal Wallis?
In both cases 12 appears when approximating the distribution of the test statistic with a normal and chi-square respectively because the statistic must first be written in a standardized form (if you were performing a permutation test these constants would be unnecessary). With continuous data, the ranks from $1$ to $n$ are used, and the variance of a randomly chosen value from $(1,2,3,...,n)$ is $(n^2-1)/12$.
[Consider that the expectation of a randomly chosen rank from $1$ to $n$ is $(n+1)/2$ and the expected value of the square of a randomly chosen rank is $n(n+1)(2n+1)/(6n)$; the variance of a randomly chosen rank is therefore $(n+1)(n-1)/12$. Similarly, the covariance of two randomly selected values (chosen without replacement) from $(1,2,3,...,n)$ is $-(n+1)/12$.]
As a result the variance of either the sum or the average of $m$ randomly chosen ranks from $(1,2,3,...,n)$ will have $12$ in it.
There's no "inversion" of the 12 differently in either formula - in both cases there's a denominator term involving a function of (something/12). If you divide by something/12 that's the same as multiplying by 12/something. So in the Kruskal-Wallis we see it simplified to be written that "12/something" way. In the Wilcoxon rank sum test when you're using the normal approximation you divide by the square root of the variance, so there's a $\sqrt{}$(something/12) in the denominator; it could as easily be written as $\times \sqrt{}$(12/something).
For similar reasons (at heart, because an expected squared rank involves $\sum_{i=1}^n i^2$), either 12 or 6 (or sometimes a 24) appears in formulas related to many other rank-based statistics.
|
Where does the number 12 come from and why is it the same 12 in Wilcoxon and Kruskal Wallis?
In both cases 12 appears when approximating the distribution of the test statistic with a normal and chi-square respectively because the statistic must first be written in a standardized form (if you
|
40,312
|
multiple imputation and propensity scores
|
My understanding is that you should generate individual propensity score models for each data set, then match, then estimate outcomes, then combine the estimates into one.
1) Match() in Matching accepts a user's own propensity score (include it as the X parameter in the call to Match(). matchit() in MatchIt does the same. I also recommend you try propensity score weighting; the package twang allows users to enter their own propensity scores/weights and then assess balance. The twang vignette explains how to do this and estimate a treatment effect.
2) Typically for balance assessment reporting, you assess balance on each dataset individually and then report maximum imbalance for each covariate across the imputed data sets. Do not average your imputed data sets. If across the imputed datasets the maximum imbalance of each covariates is within an acceptable range (e.g., ASMD <.1), that should be good enough evidence that you have achieved balance and can move forward.
|
multiple imputation and propensity scores
|
My understanding is that you should generate individual propensity score models for each data set, then match, then estimate outcomes, then combine the estimates into one.
1) Match() in Matching accep
|
multiple imputation and propensity scores
My understanding is that you should generate individual propensity score models for each data set, then match, then estimate outcomes, then combine the estimates into one.
1) Match() in Matching accepts a user's own propensity score (include it as the X parameter in the call to Match(). matchit() in MatchIt does the same. I also recommend you try propensity score weighting; the package twang allows users to enter their own propensity scores/weights and then assess balance. The twang vignette explains how to do this and estimate a treatment effect.
2) Typically for balance assessment reporting, you assess balance on each dataset individually and then report maximum imbalance for each covariate across the imputed data sets. Do not average your imputed data sets. If across the imputed datasets the maximum imbalance of each covariates is within an acceptable range (e.g., ASMD <.1), that should be good enough evidence that you have achieved balance and can move forward.
|
multiple imputation and propensity scores
My understanding is that you should generate individual propensity score models for each data set, then match, then estimate outcomes, then combine the estimates into one.
1) Match() in Matching accep
|
40,313
|
multiple imputation and propensity scores
|
As I previously stated, instead of doing propensity matching it can be reasonable to use inverse probability of treatment weighting after missing data imputation.
Suitable Stata examples follow:
clear all
webuse mheart5
*dataset
replace smokes = . in 20/70
*creates missing values for smokes variable in observations 20 to 70
mi set mlong
mi register imputed age bmi smokes
set seed 29390
mi impute mvn age bmi smokes = attack hsgrad female, add(10)
*missing data imputation creating 10 imputed datasets
replace smokes=round(smokes,1)
replace smokes = 1 if smokes >=1
replace smokes = 0 if smokes <=0
*rounding to transform smokes variables into a binary one
set seed 54321
generate randomvar = runiform()
gsort randomvar
*random sorting of the data
psmatch2 smokes age bmi female hsgrad, noreplace logit
gen iptw = 1/(1-_pscore) if smokes == 0
replace iptw = 1/(_pscore) if smokes == 1
*generation of inverse probability of treatment weighting
mi estimate: glm attack smokes [pweight = iptw], family(binomial) link(identity) vce(robust)
*inverse probability of treatment weighting analysis for dichotomous endpoint after multiple imputation
*---
clear all
webuse stan3
*dataset
replace age = . in 20/70
replace transplant = . in 40/90
*creates missing values for age variable in observations 20 to 70 and transplant variable in observations 40 to 90
mi set mlong
mi register imputed age transplant
set seed 54321
mi impute mvn age transplant = year died stime surgery wait posttran, add(10)
*missing data imputation creating 10 imputed datasets
replace transplant=round(transplant,1)
replace transplant = 1 if transplant >=1
replace transplant = 0 if transplant <=0
*rounding to transform transplant variable into a binary one
set seed 54321
generate randomvar = runiform()
gsort randomvar
*random sorting of the data
psmatch2 surgery year age transplant wait posttran, noreplace logit
gen iptw = 1/(1-_pscore) if surgery == 0
replace iptw = 1/(_pscore) if surgery == 1
*generation of inverse probability of treatment weighting
mi stset stime [pweight = iptw], failure(died) scale(1)
mi estimate: stcox surgery
*inverse probability of treatment weighting analysis for censored endpoint after multiple imputation
mi estimate: glm stime surgery [pweight = iptw], family(gaussian) link(identity) vce(robust)
*inverse probability of treatment weighting analysis for continuous endpoint after multiple imputation
|
multiple imputation and propensity scores
|
As I previously stated, instead of doing propensity matching it can be reasonable to use inverse probability of treatment weighting after missing data imputation.
Suitable Stata examples follow:
clear
|
multiple imputation and propensity scores
As I previously stated, instead of doing propensity matching it can be reasonable to use inverse probability of treatment weighting after missing data imputation.
Suitable Stata examples follow:
clear all
webuse mheart5
*dataset
replace smokes = . in 20/70
*creates missing values for smokes variable in observations 20 to 70
mi set mlong
mi register imputed age bmi smokes
set seed 29390
mi impute mvn age bmi smokes = attack hsgrad female, add(10)
*missing data imputation creating 10 imputed datasets
replace smokes=round(smokes,1)
replace smokes = 1 if smokes >=1
replace smokes = 0 if smokes <=0
*rounding to transform smokes variables into a binary one
set seed 54321
generate randomvar = runiform()
gsort randomvar
*random sorting of the data
psmatch2 smokes age bmi female hsgrad, noreplace logit
gen iptw = 1/(1-_pscore) if smokes == 0
replace iptw = 1/(_pscore) if smokes == 1
*generation of inverse probability of treatment weighting
mi estimate: glm attack smokes [pweight = iptw], family(binomial) link(identity) vce(robust)
*inverse probability of treatment weighting analysis for dichotomous endpoint after multiple imputation
*---
clear all
webuse stan3
*dataset
replace age = . in 20/70
replace transplant = . in 40/90
*creates missing values for age variable in observations 20 to 70 and transplant variable in observations 40 to 90
mi set mlong
mi register imputed age transplant
set seed 54321
mi impute mvn age transplant = year died stime surgery wait posttran, add(10)
*missing data imputation creating 10 imputed datasets
replace transplant=round(transplant,1)
replace transplant = 1 if transplant >=1
replace transplant = 0 if transplant <=0
*rounding to transform transplant variable into a binary one
set seed 54321
generate randomvar = runiform()
gsort randomvar
*random sorting of the data
psmatch2 surgery year age transplant wait posttran, noreplace logit
gen iptw = 1/(1-_pscore) if surgery == 0
replace iptw = 1/(_pscore) if surgery == 1
*generation of inverse probability of treatment weighting
mi stset stime [pweight = iptw], failure(died) scale(1)
mi estimate: stcox surgery
*inverse probability of treatment weighting analysis for censored endpoint after multiple imputation
mi estimate: glm stime surgery [pweight = iptw], family(gaussian) link(identity) vce(robust)
*inverse probability of treatment weighting analysis for continuous endpoint after multiple imputation
|
multiple imputation and propensity scores
As I previously stated, instead of doing propensity matching it can be reasonable to use inverse probability of treatment weighting after missing data imputation.
Suitable Stata examples follow:
clear
|
40,314
|
Fourier terms to model seasonality in ARIMA models
|
It appears to me that this approach is sufficiently intuitive that many people must have looked at it, but I can't locate a useful reference in my bib file, either. Searching for "Fourier ARIMA" or similar at the International Journal of Forecasting (IJF) does not yield anything very useful. Ludlow & Enders (2000, IJF) do combine ARIMA and Fourier terms, but not as regressors in the way you envisage.
A similar search at Google Scholar turns up a couple thousand hits that you would need to refine. This older paper seems to use this approach (so it's been around for thirty years at least), but I'm not sure you want to cite it.
I'd say this approach is eminently useful. Rob Hyndman seems to agree: Forecasting with long seasonal periods and Forecasting weekly data. I see that you have to use ARIMA models (why?), but note that he writes that TBATS performs comparably well. Rob's recent update to the forecast package is also relevant.
(Don't disregard these because they are "just blog entries". Rob Hyndman is one of the forecasting gurus, highly active in the community, and the Chief Editor of the IJF. I'd trust anything he blogs more than much of what other people publish in journals.)
|
Fourier terms to model seasonality in ARIMA models
|
It appears to me that this approach is sufficiently intuitive that many people must have looked at it, but I can't locate a useful reference in my bib file, either. Searching for "Fourier ARIMA" or si
|
Fourier terms to model seasonality in ARIMA models
It appears to me that this approach is sufficiently intuitive that many people must have looked at it, but I can't locate a useful reference in my bib file, either. Searching for "Fourier ARIMA" or similar at the International Journal of Forecasting (IJF) does not yield anything very useful. Ludlow & Enders (2000, IJF) do combine ARIMA and Fourier terms, but not as regressors in the way you envisage.
A similar search at Google Scholar turns up a couple thousand hits that you would need to refine. This older paper seems to use this approach (so it's been around for thirty years at least), but I'm not sure you want to cite it.
I'd say this approach is eminently useful. Rob Hyndman seems to agree: Forecasting with long seasonal periods and Forecasting weekly data. I see that you have to use ARIMA models (why?), but note that he writes that TBATS performs comparably well. Rob's recent update to the forecast package is also relevant.
(Don't disregard these because they are "just blog entries". Rob Hyndman is one of the forecasting gurus, highly active in the community, and the Chief Editor of the IJF. I'd trust anything he blogs more than much of what other people publish in journals.)
|
Fourier terms to model seasonality in ARIMA models
It appears to me that this approach is sufficiently intuitive that many people must have looked at it, but I can't locate a useful reference in my bib file, either. Searching for "Fourier ARIMA" or si
|
40,315
|
Fourier terms to model seasonality in ARIMA models
|
Maybe you can look this https://medium.com/intive-developers/forecasting-time-series-with-multiple-seasonalities-using-tbats-in-python-398a00ac0e8a
This article compared tbats and SARIMAX with Fourier Terms .
The answer to your question :
SARIMAX with Fourier Terms One can apply a trick [4] to utilize
exogenous variables in SARIMAX to model additional seasonalities with
Fourier terms. We will keep modeling the weekly pattern with seasonal
part of SARIMA. For the yearly seasonal pattern we will use the
above-mentioned trick. I have compared multiple choices for the number
of Fourier terms and 2 provides the most accurate forecasts. Therefore
we shall use 2 Fourier terms as exogenous variables.
# prepare Fourier terms
exog = pd.DataFrame({'date': y.index})
exog = exog.set_index(pd.PeriodIndex(exog['date'], freq='D'))
exog['sin365'] = np.sin(2 * np.pi * exog.index.dayofyear / 365.25)
exog['cos365'] = np.cos(2 * np.pi * exog.index.dayofyear / 365.25)
exog['sin365_2'] = np.sin(4 * np.pi * exog.index.dayofyear / 365.25)
exog['cos365_2'] = np.cos(4 * np.pi * exog.index.dayofyear / 365.25)
exog = exog.drop(columns=['date'])
exog_to_train = exog.iloc[:(len(y)-365)]
exog_to_test = exog.iloc[(len(y)-365):]
# Fit model
arima_exog_model = auto_arima(y=y_to_train, exogenous=exog_to_train, seasonal=True, m=7)
# Forecast
y_arima_exog_forecast = arima_exog_model.predict(n_periods=365, exogenous=exog_to_test)
|
Fourier terms to model seasonality in ARIMA models
|
Maybe you can look this https://medium.com/intive-developers/forecasting-time-series-with-multiple-seasonalities-using-tbats-in-python-398a00ac0e8a
This article compared tbats and SARIMAX with Fourier
|
Fourier terms to model seasonality in ARIMA models
Maybe you can look this https://medium.com/intive-developers/forecasting-time-series-with-multiple-seasonalities-using-tbats-in-python-398a00ac0e8a
This article compared tbats and SARIMAX with Fourier Terms .
The answer to your question :
SARIMAX with Fourier Terms One can apply a trick [4] to utilize
exogenous variables in SARIMAX to model additional seasonalities with
Fourier terms. We will keep modeling the weekly pattern with seasonal
part of SARIMA. For the yearly seasonal pattern we will use the
above-mentioned trick. I have compared multiple choices for the number
of Fourier terms and 2 provides the most accurate forecasts. Therefore
we shall use 2 Fourier terms as exogenous variables.
# prepare Fourier terms
exog = pd.DataFrame({'date': y.index})
exog = exog.set_index(pd.PeriodIndex(exog['date'], freq='D'))
exog['sin365'] = np.sin(2 * np.pi * exog.index.dayofyear / 365.25)
exog['cos365'] = np.cos(2 * np.pi * exog.index.dayofyear / 365.25)
exog['sin365_2'] = np.sin(4 * np.pi * exog.index.dayofyear / 365.25)
exog['cos365_2'] = np.cos(4 * np.pi * exog.index.dayofyear / 365.25)
exog = exog.drop(columns=['date'])
exog_to_train = exog.iloc[:(len(y)-365)]
exog_to_test = exog.iloc[(len(y)-365):]
# Fit model
arima_exog_model = auto_arima(y=y_to_train, exogenous=exog_to_train, seasonal=True, m=7)
# Forecast
y_arima_exog_forecast = arima_exog_model.predict(n_periods=365, exogenous=exog_to_test)
|
Fourier terms to model seasonality in ARIMA models
Maybe you can look this https://medium.com/intive-developers/forecasting-time-series-with-multiple-seasonalities-using-tbats-in-python-398a00ac0e8a
This article compared tbats and SARIMAX with Fourier
|
40,316
|
Probabilistic classification and loss functions
|
The "probability loss" function has sometimes been called the "linear score" in the literature. Although it looks appealing, this loss function is improper, which means that it does not set the incentive to forecast the true probability that $y_i = 1$. For details, see p. 366 of Gneiting and Raftery ("Strictly Proper Scoring Rules, Prediction, and Estimation", Journal of the American Statistical Association, 2007).
In practice, impropriety means that a silly forecaster (who, for example, skews his probabilities towards the extremes of zero and one) may obtain a better probability loss than a reasonable forecaster.
The following example, based on R code, illustrates this point.
First, set a random seed (set.seed(1)) and fix a sample size (n <- 10000)
Simulate an arbitrary vector of true probabilities: p_true <- runif(n)
Now, draw a vector of binary observations which follow these probabilities: y <- runif(n) < p_true
Suppose Anne is an omniscient forecaster, and knows the true probabilities p_true. Her probability loss (on average over cases) can be computed as follows: loss_Anne <- (sum(p_true[y == FALSE]) + sum((1-p_true)[y == TRUE]))/n
By contrast, consider a second forecaster (Bob) who makes overconfident predictions, according to the following formula: p_wrong <- 0.5*(p_true + (p_true >= 0.5)). The formula means that Bob skews the "small" probabilities (less than 50 percent) towards zero, and the "large" probabilities (more than 50 percent) towards one. Bob's average loss is given by loss_Bob <- (sum(p_wrong[y == FALSE]) + sum((1-p_wrong)[y == TRUE]))/n
Running this code on my PC, I find that loss_Anne is about $0.33$, whereas loss_Bob is about $0.29$. Thus, a perfect forecaster (Anne) loses to an overconfident forecaster who deliberately skews his probabilities towards the extremes of zero and one.
Thus, the probability loss should not be used for model comparison, as it will generally not select the true model (even asymptotically). Instead, a strictly proper scoring function like the logarithmic loss or Brier score should be used. Again see the reference mentioned above.
|
Probabilistic classification and loss functions
|
The "probability loss" function has sometimes been called the "linear score" in the literature. Although it looks appealing, this loss function is improper, which means that it does not set the incent
|
Probabilistic classification and loss functions
The "probability loss" function has sometimes been called the "linear score" in the literature. Although it looks appealing, this loss function is improper, which means that it does not set the incentive to forecast the true probability that $y_i = 1$. For details, see p. 366 of Gneiting and Raftery ("Strictly Proper Scoring Rules, Prediction, and Estimation", Journal of the American Statistical Association, 2007).
In practice, impropriety means that a silly forecaster (who, for example, skews his probabilities towards the extremes of zero and one) may obtain a better probability loss than a reasonable forecaster.
The following example, based on R code, illustrates this point.
First, set a random seed (set.seed(1)) and fix a sample size (n <- 10000)
Simulate an arbitrary vector of true probabilities: p_true <- runif(n)
Now, draw a vector of binary observations which follow these probabilities: y <- runif(n) < p_true
Suppose Anne is an omniscient forecaster, and knows the true probabilities p_true. Her probability loss (on average over cases) can be computed as follows: loss_Anne <- (sum(p_true[y == FALSE]) + sum((1-p_true)[y == TRUE]))/n
By contrast, consider a second forecaster (Bob) who makes overconfident predictions, according to the following formula: p_wrong <- 0.5*(p_true + (p_true >= 0.5)). The formula means that Bob skews the "small" probabilities (less than 50 percent) towards zero, and the "large" probabilities (more than 50 percent) towards one. Bob's average loss is given by loss_Bob <- (sum(p_wrong[y == FALSE]) + sum((1-p_wrong)[y == TRUE]))/n
Running this code on my PC, I find that loss_Anne is about $0.33$, whereas loss_Bob is about $0.29$. Thus, a perfect forecaster (Anne) loses to an overconfident forecaster who deliberately skews his probabilities towards the extremes of zero and one.
Thus, the probability loss should not be used for model comparison, as it will generally not select the true model (even asymptotically). Instead, a strictly proper scoring function like the logarithmic loss or Brier score should be used. Again see the reference mentioned above.
|
Probabilistic classification and loss functions
The "probability loss" function has sometimes been called the "linear score" in the literature. Although it looks appealing, this loss function is improper, which means that it does not set the incent
|
40,317
|
Is AUC via CV a good procedure for selecting optimal model?
|
The concordance probability ($c$-index; ROC area) is not sensitive enough to be used to compare two models let alone a whole series of models. It rewards extreme predictions that are right too little because it uses only the ranks of the predictions, not their absolute values. Classification accuracy is even worse, being an arbitrary discontinuous improper accuracy score. For your purpose use a proper accuracy score such as deviance, pseudo $R^2$, or Brier score.
|
Is AUC via CV a good procedure for selecting optimal model?
|
The concordance probability ($c$-index; ROC area) is not sensitive enough to be used to compare two models let alone a whole series of models. It rewards extreme predictions that are right too little
|
Is AUC via CV a good procedure for selecting optimal model?
The concordance probability ($c$-index; ROC area) is not sensitive enough to be used to compare two models let alone a whole series of models. It rewards extreme predictions that are right too little because it uses only the ranks of the predictions, not their absolute values. Classification accuracy is even worse, being an arbitrary discontinuous improper accuracy score. For your purpose use a proper accuracy score such as deviance, pseudo $R^2$, or Brier score.
|
Is AUC via CV a good procedure for selecting optimal model?
The concordance probability ($c$-index; ROC area) is not sensitive enough to be used to compare two models let alone a whole series of models. It rewards extreme predictions that are right too little
|
40,318
|
Is there a method to plot the output of a random forest in R?
|
There are many packages that implement randomForest. Party is one of them that supports plotting
First build a forest:
library("party")
cf <- cforest(Species~., data=iris)
Then extract a tree and build a binary tree that can be plotted:
pt <- prettytree(cf@ensemble[[1]], names(cf@data@get("input")))
nt <- new("BinaryTree")
nt@tree <- pt
nt@data <- cf@data
nt@responses <- cf@responses
plot(nt, type="simple")
|
Is there a method to plot the output of a random forest in R?
|
There are many packages that implement randomForest. Party is one of them that supports plotting
First build a forest:
library("party")
cf <- cforest(Species~., data=iris)
Then extract a tree and bui
|
Is there a method to plot the output of a random forest in R?
There are many packages that implement randomForest. Party is one of them that supports plotting
First build a forest:
library("party")
cf <- cforest(Species~., data=iris)
Then extract a tree and build a binary tree that can be plotted:
pt <- prettytree(cf@ensemble[[1]], names(cf@data@get("input")))
nt <- new("BinaryTree")
nt@tree <- pt
nt@data <- cf@data
nt@responses <- cf@responses
plot(nt, type="simple")
|
Is there a method to plot the output of a random forest in R?
There are many packages that implement randomForest. Party is one of them that supports plotting
First build a forest:
library("party")
cf <- cforest(Species~., data=iris)
Then extract a tree and bui
|
40,319
|
Combining multiple variables into one "score"
|
Taking your example literally, I'd say the approach is problematic from the outset.
If the problem is assessing the total burden, then absolute numbers of deaths and people living with AIDS are key variables, but any PCA is likely to be dominated by a small number of countries with large populations. Even if you use correlation-based PCA, as you should when variables are in very different units, you will have some large outliers in there for most conceivable mixes of countries.
If the problem is assessing the total burden given population sizes, then the other variables are relevant.
It seems unlikely that mixing together different kinds of variables will help either purpose.
The biggest question of all is whether it's a good idea at all to seek a single scale in this way. The best that I can do is flag that statistically-minded people have very different views on this, many highly negative. My own view is that PCA of this sort will only be of interest to those capable of understanding and criticising the PCA and doing their own alternative analysis. A fallacy known under many different names, of which one is the fallacy of misplaced concreteness, is confusing a desire for a single measure with a demonstration that such a measure can be reliably and intelligibly identified from data. It's one thing to have a single name (creativity, intelligence, in this case burden) and another thing to have a single quantifiable dimension.
Turning to your results, what's most alarming, as you clearly flag, is that the loadings on the first PC don't even have the same sign. If there is one important shared dimension that justifies trying to quantify burden as a single measure, then it minimally requires all those variables to be positively correlated with each other (or for reversals of sign to be obvious consequences of some measures being direct and some inverse, which doesn't seem the case here). Without seeing the data, I can't interpret further, but I'd expect the variation in sign to be a side-effect of mushing together quite different variables that are also skewed in distribution and with outliers.
Plotting the data will help you understand why you got the results you did.
I don't have suggestions for a different way to collapse to a single score. I've seen too many applications in which such endeavours were not helpful to be positive there.
|
Combining multiple variables into one "score"
|
Taking your example literally, I'd say the approach is problematic from the outset.
If the problem is assessing the total burden, then absolute numbers of deaths and people living with AIDS are key
|
Combining multiple variables into one "score"
Taking your example literally, I'd say the approach is problematic from the outset.
If the problem is assessing the total burden, then absolute numbers of deaths and people living with AIDS are key variables, but any PCA is likely to be dominated by a small number of countries with large populations. Even if you use correlation-based PCA, as you should when variables are in very different units, you will have some large outliers in there for most conceivable mixes of countries.
If the problem is assessing the total burden given population sizes, then the other variables are relevant.
It seems unlikely that mixing together different kinds of variables will help either purpose.
The biggest question of all is whether it's a good idea at all to seek a single scale in this way. The best that I can do is flag that statistically-minded people have very different views on this, many highly negative. My own view is that PCA of this sort will only be of interest to those capable of understanding and criticising the PCA and doing their own alternative analysis. A fallacy known under many different names, of which one is the fallacy of misplaced concreteness, is confusing a desire for a single measure with a demonstration that such a measure can be reliably and intelligibly identified from data. It's one thing to have a single name (creativity, intelligence, in this case burden) and another thing to have a single quantifiable dimension.
Turning to your results, what's most alarming, as you clearly flag, is that the loadings on the first PC don't even have the same sign. If there is one important shared dimension that justifies trying to quantify burden as a single measure, then it minimally requires all those variables to be positively correlated with each other (or for reversals of sign to be obvious consequences of some measures being direct and some inverse, which doesn't seem the case here). Without seeing the data, I can't interpret further, but I'd expect the variation in sign to be a side-effect of mushing together quite different variables that are also skewed in distribution and with outliers.
Plotting the data will help you understand why you got the results you did.
I don't have suggestions for a different way to collapse to a single score. I've seen too many applications in which such endeavours were not helpful to be positive there.
|
Combining multiple variables into one "score"
Taking your example literally, I'd say the approach is problematic from the outset.
If the problem is assessing the total burden, then absolute numbers of deaths and people living with AIDS are key
|
40,320
|
Combining multiple variables into one "score"
|
Suggest an exploratory factor analysis. Rather than assume the dimensionality behind your HIV measures, take one half of the sample randomly, extract 4 factors, by almost any method, and plot the eigenvalues. Use the scree test or just use the "eigenvalues greater than one thumb rule": Rotate to simple structure via Varimax or Quartimax the number of factors by either of these tests. I'm guessing that a two factor solution will explain the dimensionality of your HIV measures. By studying the loadings, and thinking while taking a jog or hot shower, you will soon understand what these two dimensions actually are. Then do a confirmatory factor analysis with the other half of the sample.
|
Combining multiple variables into one "score"
|
Suggest an exploratory factor analysis. Rather than assume the dimensionality behind your HIV measures, take one half of the sample randomly, extract 4 factors, by almost any method, and plot the eig
|
Combining multiple variables into one "score"
Suggest an exploratory factor analysis. Rather than assume the dimensionality behind your HIV measures, take one half of the sample randomly, extract 4 factors, by almost any method, and plot the eigenvalues. Use the scree test or just use the "eigenvalues greater than one thumb rule": Rotate to simple structure via Varimax or Quartimax the number of factors by either of these tests. I'm guessing that a two factor solution will explain the dimensionality of your HIV measures. By studying the loadings, and thinking while taking a jog or hot shower, you will soon understand what these two dimensions actually are. Then do a confirmatory factor analysis with the other half of the sample.
|
Combining multiple variables into one "score"
Suggest an exploratory factor analysis. Rather than assume the dimensionality behind your HIV measures, take one half of the sample randomly, extract 4 factors, by almost any method, and plot the eig
|
40,321
|
Markov chain,transition matrix and jordan form
|
The result is easy to prove by induction once it has been shown to you, so let's focus on how to find these powers on your own. The point of the Jordan Normal Form of a square matrix is clearly revealed by its geometrical interpretation. Each of its blocks, of dimensions $k\times k$, corresponds to a subspace on which the matrix acts as an endomorphism. On each such subspace it is the sum of a homothety $\lambda \mathbb{I}_k$ and a nilpotent transformation $N$. Moreover, it is so arranged that a basis $(e_1, e_2, \ldots, e_k)$ can be found in which $$N:e_{j+1}\to e_j\tag{*}$$ for $j=1, 2, \ldots, k-1$ and $N(e_1)=0$. Because $\lambda\mathbb{I}_k$ commutes with $N$, this makes it easy to find powers of $D = \lambda\mathbb{I}_k + N$, since
Repeated application of $(*)$ immediately shows that for $i \ge 1$, $N^i(e_{j+i}) = e_j$ for $j=1, 2, \ldots, k-i$ and $N^i(e_j) = 0$ for $j \le i$ and
The Binomial Theorem asserts $$(\lambda \mathbb{I}_k + N)^n = \sum_{i=0}^n \binom{n}{i} \lambda^{n-i} N^i.$$
(1) guarantees that $N^k = N^{k+1} = \cdots = 0$: that's what it means to be nilpotent and it's the reason why this form is so convenient.
In the example $D$ has two blocks of dimensions $2$ and $1$. The $k=1$ block acts trivially. The $k=2$ block has $\lambda=1/2$. Its matrix in the basis $(e_1, e_2)$ therefore is $$D_2 = \pmatrix{\frac{1}{2} & 1 \\ 0 & \frac{1}{2}} = \frac{1}{2}\pmatrix{1 & 0 \\ 0 & 1} + \pmatrix{0 & 1 \\ 0 & 0} = \frac{1}{2}\mathbb{I}_2 + N.$$
Consequently $N^2 = 0$, whence for any positive integral power $n$,
$$D_2^n =\sum_{i=0}^n \binom{n}{i} \left(\frac{1}{2}\right)^{n-i} N^i = \left(\frac{1}{2}\right)^n + \binom{n}{1} \left(\frac{1}{2}\right)^{n-1} N + 0 + 0 + \cdots + 0.$$
In terms of the basis $(e_1, e_2)$ the matrix of $D_2^n$ therefore is
$$D_2^n = \frac{1}{2^n}\pmatrix{1 & 0 \\ 0 & 1} + \binom{n}{1}\frac{1}{2^{n-1}}\pmatrix{0 & 1 \\ 0 & 0} = \pmatrix{\frac{1}{2^n} & 0 \\ 0 & \frac{1}{2^n}} + \pmatrix{0 & n \frac{1}{2^{n-1}} \\ 0 & 0}.$$
That's algebraically equivalent to the formula in the question.
|
Markov chain,transition matrix and jordan form
|
The result is easy to prove by induction once it has been shown to you, so let's focus on how to find these powers on your own. The point of the Jordan Normal Form of a square matrix is clearly revea
|
Markov chain,transition matrix and jordan form
The result is easy to prove by induction once it has been shown to you, so let's focus on how to find these powers on your own. The point of the Jordan Normal Form of a square matrix is clearly revealed by its geometrical interpretation. Each of its blocks, of dimensions $k\times k$, corresponds to a subspace on which the matrix acts as an endomorphism. On each such subspace it is the sum of a homothety $\lambda \mathbb{I}_k$ and a nilpotent transformation $N$. Moreover, it is so arranged that a basis $(e_1, e_2, \ldots, e_k)$ can be found in which $$N:e_{j+1}\to e_j\tag{*}$$ for $j=1, 2, \ldots, k-1$ and $N(e_1)=0$. Because $\lambda\mathbb{I}_k$ commutes with $N$, this makes it easy to find powers of $D = \lambda\mathbb{I}_k + N$, since
Repeated application of $(*)$ immediately shows that for $i \ge 1$, $N^i(e_{j+i}) = e_j$ for $j=1, 2, \ldots, k-i$ and $N^i(e_j) = 0$ for $j \le i$ and
The Binomial Theorem asserts $$(\lambda \mathbb{I}_k + N)^n = \sum_{i=0}^n \binom{n}{i} \lambda^{n-i} N^i.$$
(1) guarantees that $N^k = N^{k+1} = \cdots = 0$: that's what it means to be nilpotent and it's the reason why this form is so convenient.
In the example $D$ has two blocks of dimensions $2$ and $1$. The $k=1$ block acts trivially. The $k=2$ block has $\lambda=1/2$. Its matrix in the basis $(e_1, e_2)$ therefore is $$D_2 = \pmatrix{\frac{1}{2} & 1 \\ 0 & \frac{1}{2}} = \frac{1}{2}\pmatrix{1 & 0 \\ 0 & 1} + \pmatrix{0 & 1 \\ 0 & 0} = \frac{1}{2}\mathbb{I}_2 + N.$$
Consequently $N^2 = 0$, whence for any positive integral power $n$,
$$D_2^n =\sum_{i=0}^n \binom{n}{i} \left(\frac{1}{2}\right)^{n-i} N^i = \left(\frac{1}{2}\right)^n + \binom{n}{1} \left(\frac{1}{2}\right)^{n-1} N + 0 + 0 + \cdots + 0.$$
In terms of the basis $(e_1, e_2)$ the matrix of $D_2^n$ therefore is
$$D_2^n = \frac{1}{2^n}\pmatrix{1 & 0 \\ 0 & 1} + \binom{n}{1}\frac{1}{2^{n-1}}\pmatrix{0 & 1 \\ 0 & 0} = \pmatrix{\frac{1}{2^n} & 0 \\ 0 & \frac{1}{2^n}} + \pmatrix{0 & n \frac{1}{2^{n-1}} \\ 0 & 0}.$$
That's algebraically equivalent to the formula in the question.
|
Markov chain,transition matrix and jordan form
The result is easy to prove by induction once it has been shown to you, so let's focus on how to find these powers on your own. The point of the Jordan Normal Form of a square matrix is clearly revea
|
40,322
|
Feature selection using RFE in SVM kernel (other than linear eg rbf, poly etc)
|
To use RFE, it is a must to have a supervised learning estimator which attribute coef_ is available, this is the case of the linear kernel. The error you are getting is because coef_ is not for SVM using kernels different from Linear. It is in RFE documentation
A walk-around solution is presented in Feature selection for support vector machines with RBF kernel by Quanzhong Liu et. al.
|
Feature selection using RFE in SVM kernel (other than linear eg rbf, poly etc)
|
To use RFE, it is a must to have a supervised learning estimator which attribute coef_ is available, this is the case of the linear kernel. The error you are getting is because coef_ is not for SVM us
|
Feature selection using RFE in SVM kernel (other than linear eg rbf, poly etc)
To use RFE, it is a must to have a supervised learning estimator which attribute coef_ is available, this is the case of the linear kernel. The error you are getting is because coef_ is not for SVM using kernels different from Linear. It is in RFE documentation
A walk-around solution is presented in Feature selection for support vector machines with RBF kernel by Quanzhong Liu et. al.
|
Feature selection using RFE in SVM kernel (other than linear eg rbf, poly etc)
To use RFE, it is a must to have a supervised learning estimator which attribute coef_ is available, this is the case of the linear kernel. The error you are getting is because coef_ is not for SVM us
|
40,323
|
Is this Simpson's Paradox on the Titanic data set?
|
Although Simpson's paradox (or Simpson's reversal) is more often referred in 3-way contingency tables than in correlation between continuous variables, it's the same phenomenon.
Here, the explanation in simple words seems clear: Although inside each class there is a slight tendency of decreasing fares with age, people in lower classes tend to be younger. That is, younger people tend to travel in lower classes and therefore younger people tends to pay lower fares.
About the fact that people is younger in the lower classes, you can see in the plot that there are a lot of children (age<18) in 3rd class, less of them in 2nd class (clearly less people in 0-20 than in 20-40), and very few children in 1st class. Comparing the 40-60 and 60-80 bands with the 20-40 band would also show that people tend to be younger in lower classes.
In summary: Yes, it is an occurrence of the Simpson's paradox. Younger people tend to travel in lower classes and therefore younger people tend to pays lower fares, even if they tend to pay a little more than older people in the same class.
And just a as a side comment: this one is not the only occurrence of Simpson's paradox in the Titanic dataset. In https://select-statistics.co.uk/blog/hidden-data-and-surviving-a-sinking-ship-simpsons-paradox/ or https://www2.stat.duke.edu/courses/Fall12/sta611/SimpsonsParadox.pdf another one is noticed.
|
Is this Simpson's Paradox on the Titanic data set?
|
Although Simpson's paradox (or Simpson's reversal) is more often referred in 3-way contingency tables than in correlation between continuous variables, it's the same phenomenon.
Here, the explanation
|
Is this Simpson's Paradox on the Titanic data set?
Although Simpson's paradox (or Simpson's reversal) is more often referred in 3-way contingency tables than in correlation between continuous variables, it's the same phenomenon.
Here, the explanation in simple words seems clear: Although inside each class there is a slight tendency of decreasing fares with age, people in lower classes tend to be younger. That is, younger people tend to travel in lower classes and therefore younger people tends to pay lower fares.
About the fact that people is younger in the lower classes, you can see in the plot that there are a lot of children (age<18) in 3rd class, less of them in 2nd class (clearly less people in 0-20 than in 20-40), and very few children in 1st class. Comparing the 40-60 and 60-80 bands with the 20-40 band would also show that people tend to be younger in lower classes.
In summary: Yes, it is an occurrence of the Simpson's paradox. Younger people tend to travel in lower classes and therefore younger people tend to pays lower fares, even if they tend to pay a little more than older people in the same class.
And just a as a side comment: this one is not the only occurrence of Simpson's paradox in the Titanic dataset. In https://select-statistics.co.uk/blog/hidden-data-and-surviving-a-sinking-ship-simpsons-paradox/ or https://www2.stat.duke.edu/courses/Fall12/sta611/SimpsonsParadox.pdf another one is noticed.
|
Is this Simpson's Paradox on the Titanic data set?
Although Simpson's paradox (or Simpson's reversal) is more often referred in 3-way contingency tables than in correlation between continuous variables, it's the same phenomenon.
Here, the explanation
|
40,324
|
Weak first stage in 2SLS
|
To test for weak instruments you would test the joint significance of your instruments' coefficients via an F-test. The typical rule of thumb is that an F-statistic of more than 10 is fine (see Stock and Yogo, 2002), however, this is not a theorem and people may still give you a hard time if your test statistic is close to 10.
In case you only have one instrument, this F-statistic is equivalent to the square of the t-statistic of your instrument's coefficient in the first stage.
Should you find that your instrument is weak, i.e. if you get an F-statistic of less than 10 (or close to it), then you can use alternative estimators which are somewhat more robust to this weak instruments problem. One of such estimators is limited information maximum likelihood (LIML), which is programmed in pre-canned packages in most of the available statistics softwares.
CITATION
Stock, James H., Jonathan H. Wright, and Motohiro Yogo. "A survey of weak instruments and weak identification in generalized method of moments." Journal of Business & Economic Statistics 20.4 (2002): 518-529.
|
Weak first stage in 2SLS
|
To test for weak instruments you would test the joint significance of your instruments' coefficients via an F-test. The typical rule of thumb is that an F-statistic of more than 10 is fine (see Stock
|
Weak first stage in 2SLS
To test for weak instruments you would test the joint significance of your instruments' coefficients via an F-test. The typical rule of thumb is that an F-statistic of more than 10 is fine (see Stock and Yogo, 2002), however, this is not a theorem and people may still give you a hard time if your test statistic is close to 10.
In case you only have one instrument, this F-statistic is equivalent to the square of the t-statistic of your instrument's coefficient in the first stage.
Should you find that your instrument is weak, i.e. if you get an F-statistic of less than 10 (or close to it), then you can use alternative estimators which are somewhat more robust to this weak instruments problem. One of such estimators is limited information maximum likelihood (LIML), which is programmed in pre-canned packages in most of the available statistics softwares.
CITATION
Stock, James H., Jonathan H. Wright, and Motohiro Yogo. "A survey of weak instruments and weak identification in generalized method of moments." Journal of Business & Economic Statistics 20.4 (2002): 518-529.
|
Weak first stage in 2SLS
To test for weak instruments you would test the joint significance of your instruments' coefficients via an F-test. The typical rule of thumb is that an F-statistic of more than 10 is fine (see Stock
|
40,325
|
Weak first stage in 2SLS
|
Since you have only one instrument and one treatment, you can use the Anderson-Rubin (AR) confidence interval by inverting the AR test.
The AR test is uniformly most powerful unbiased in this setting, and it has correct coverage rates regardless of the strength of the instrument. This review might be useful.
This and other "weak-instrument robust" methods are implemented int he ivmodel R package.
|
Weak first stage in 2SLS
|
Since you have only one instrument and one treatment, you can use the Anderson-Rubin (AR) confidence interval by inverting the AR test.
The AR test is uniformly most powerful unbiased in this setting
|
Weak first stage in 2SLS
Since you have only one instrument and one treatment, you can use the Anderson-Rubin (AR) confidence interval by inverting the AR test.
The AR test is uniformly most powerful unbiased in this setting, and it has correct coverage rates regardless of the strength of the instrument. This review might be useful.
This and other "weak-instrument robust" methods are implemented int he ivmodel R package.
|
Weak first stage in 2SLS
Since you have only one instrument and one treatment, you can use the Anderson-Rubin (AR) confidence interval by inverting the AR test.
The AR test is uniformly most powerful unbiased in this setting
|
40,326
|
Interpretation of correlogram
|
On the y axis is the autocorrelation. The x axis tells you the lag. So, if x=1 we are looking at the correlation of December with November, November with October, etc. If x=2, we have a lag of 2 and we are looking at the correlation of December with October, November with September, etc.
In the first graph, there are high positive correlations that only slowly decline with increasing lags. This indicates a lot of autocorrelation and you will need to take that into account in your modeling.
In the second graph, the correlations are very low (the y axis goes from +.10 to -.10) and don't seem to have a pattern.
The gray areas are confidence bands (e.g. tell you whether the correlation is statistically significant).
|
Interpretation of correlogram
|
On the y axis is the autocorrelation. The x axis tells you the lag. So, if x=1 we are looking at the correlation of December with November, November with October, etc. If x=2, we have a lag of 2 and
|
Interpretation of correlogram
On the y axis is the autocorrelation. The x axis tells you the lag. So, if x=1 we are looking at the correlation of December with November, November with October, etc. If x=2, we have a lag of 2 and we are looking at the correlation of December with October, November with September, etc.
In the first graph, there are high positive correlations that only slowly decline with increasing lags. This indicates a lot of autocorrelation and you will need to take that into account in your modeling.
In the second graph, the correlations are very low (the y axis goes from +.10 to -.10) and don't seem to have a pattern.
The gray areas are confidence bands (e.g. tell you whether the correlation is statistically significant).
|
Interpretation of correlogram
On the y axis is the autocorrelation. The x axis tells you the lag. So, if x=1 we are looking at the correlation of December with November, November with October, etc. If x=2, we have a lag of 2 and
|
40,327
|
Bernstein's inequality for heavy-tailed random variables
|
Yes, see Theorem 6.21 of [LT13], Michel Ledoux and Michel Talagrand. Probability in Banach Spaces: isoperimetry and processes, volume 23. Springer Science & Business Media, 2013.
For simplicity you may also look at section 8 of my paper.
http://arxiv.org/pdf/1507.06370v2.pdf
(I just summarized those theorems -- the purpose of the paper is completely different)
|
Bernstein's inequality for heavy-tailed random variables
|
Yes, see Theorem 6.21 of [LT13], Michel Ledoux and Michel Talagrand. Probability in Banach Spaces: isoperimetry and processes, volume 23. Springer Science & Business Media, 2013.
For simplicity you ma
|
Bernstein's inequality for heavy-tailed random variables
Yes, see Theorem 6.21 of [LT13], Michel Ledoux and Michel Talagrand. Probability in Banach Spaces: isoperimetry and processes, volume 23. Springer Science & Business Media, 2013.
For simplicity you may also look at section 8 of my paper.
http://arxiv.org/pdf/1507.06370v2.pdf
(I just summarized those theorems -- the purpose of the paper is completely different)
|
Bernstein's inequality for heavy-tailed random variables
Yes, see Theorem 6.21 of [LT13], Michel Ledoux and Michel Talagrand. Probability in Banach Spaces: isoperimetry and processes, volume 23. Springer Science & Business Media, 2013.
For simplicity you ma
|
40,328
|
What happens if I use Z-test instead of T test?
|
There is little to add to @Glen_b expert and eloquent discussion; rather, there is only room for making concepts less precise with the excuse or intention of appealing to intuition. That being said, here're a couple of plots that helped me come to terms with these concepts:
1. t-Student Distributions have "fatter" tails:
These tend towards the normal distribution as the sample size (or degrees of freedom) increase. Consequently, there are more points lying in the asymptotes, and to determine a certain risk alpha, the cut-off point of the test statistic would have to be slid towards the right (let's leave aside two-tail tests). The comparison is thus:
2. The farther away the cut-off, the lower the power:
So we slide the cutoff value to the right, and in doing so, we stay within the NULL a longer stretch before we reject it. Looking at it from the alternative there is a larger area of its corresponding curve sub-tending to the left of the cut-off value (beta), and a smaller slice to the right (the power). Just like this:
Notice the funny looking t-distribution under the alternative, which is a tentative approximation to a non-central t with a delta parameter of $2$. Under the NULL the distribution is central with $2\,df$. The cut-off value for a one-sided risk alpha of $0.5\,\%$ is shown as vertical straight lines on both the Z-test (above in blue) and the t-test (below in red).
|
What happens if I use Z-test instead of T test?
|
There is little to add to @Glen_b expert and eloquent discussion; rather, there is only room for making concepts less precise with the excuse or intention of appealing to intuition. That being said, h
|
What happens if I use Z-test instead of T test?
There is little to add to @Glen_b expert and eloquent discussion; rather, there is only room for making concepts less precise with the excuse or intention of appealing to intuition. That being said, here're a couple of plots that helped me come to terms with these concepts:
1. t-Student Distributions have "fatter" tails:
These tend towards the normal distribution as the sample size (or degrees of freedom) increase. Consequently, there are more points lying in the asymptotes, and to determine a certain risk alpha, the cut-off point of the test statistic would have to be slid towards the right (let's leave aside two-tail tests). The comparison is thus:
2. The farther away the cut-off, the lower the power:
So we slide the cutoff value to the right, and in doing so, we stay within the NULL a longer stretch before we reject it. Looking at it from the alternative there is a larger area of its corresponding curve sub-tending to the left of the cut-off value (beta), and a smaller slice to the right (the power). Just like this:
Notice the funny looking t-distribution under the alternative, which is a tentative approximation to a non-central t with a delta parameter of $2$. Under the NULL the distribution is central with $2\,df$. The cut-off value for a one-sided risk alpha of $0.5\,\%$ is shown as vertical straight lines on both the Z-test (above in blue) and the t-test (below in red).
|
What happens if I use Z-test instead of T test?
There is little to add to @Glen_b expert and eloquent discussion; rather, there is only room for making concepts less precise with the excuse or intention of appealing to intuition. That being said, h
|
40,329
|
What happens if I use Z-test instead of T test?
|
Because the critical values are smaller with the Z, the rejection region is larger.
So yes, significance level goes up, and consequently the rest of the power curve comes with it, as it does whenever you move the significance level.
|
What happens if I use Z-test instead of T test?
|
Because the critical values are smaller with the Z, the rejection region is larger.
So yes, significance level goes up, and consequently the rest of the power curve comes with it, as it does whenever
|
What happens if I use Z-test instead of T test?
Because the critical values are smaller with the Z, the rejection region is larger.
So yes, significance level goes up, and consequently the rest of the power curve comes with it, as it does whenever you move the significance level.
|
What happens if I use Z-test instead of T test?
Because the critical values are smaller with the Z, the rejection region is larger.
So yes, significance level goes up, and consequently the rest of the power curve comes with it, as it does whenever
|
40,330
|
Plotting the results of GLM in R
|
"I was told the R value was too low compared to the significance of the p value" -- sounds like nonsense to me.
On the other hand, some form of glm may be a good idea (but it looks to me like the spread may be increasing more than you might expect with a quasipoisson).
Note that nothing about the glm changes the spread of the data -- it only models changing spread (in a particular way). The data are still the data and if you plot them will still look as they do.
You can change the appearance of the data via a transformation. One that approximately stabilizes variance when the Poisson parameter is not very small is $\sqrt{y}$. If the Poisson parameter can take small values, you may like to try $\sqrt{y+\frac{3}{8}}$ or $\sqrt{y}+\sqrt{y+1}$ instead (it looks to me like that might well be the case that you have small values).
On the other hand, one that would linearize your fitted model would be a log (but that's only suitable if you don't have exact zeros).
--
Although it won't be satisfying to you, you can plot the fitted curve via
plot(temp,encno,xlim=c(0,60))
newdat <- data.frame(temp=seq(9,48,.5))
encnoglm1 <- glm(formula = encno ~ temp, family = quasipoisson(link = log),
data = encnotemp)
fit <- predict(encnoglm1,newdata=newdat,type="response")
lines(fit~temp,data=newdat,type="l",col=4)
Or if you want to look at what would be a nearly constant variance if the quasipoisson were suitable:
plot(temp,sqrt(encno+3/8),xlim=c(0,60))
lines(sqrt(fit+3/8)~temp,data=newdat,type="l",col=2)
|
Plotting the results of GLM in R
|
"I was told the R value was too low compared to the significance of the p value" -- sounds like nonsense to me.
On the other hand, some form of glm may be a good idea (but it looks to me like the spr
|
Plotting the results of GLM in R
"I was told the R value was too low compared to the significance of the p value" -- sounds like nonsense to me.
On the other hand, some form of glm may be a good idea (but it looks to me like the spread may be increasing more than you might expect with a quasipoisson).
Note that nothing about the glm changes the spread of the data -- it only models changing spread (in a particular way). The data are still the data and if you plot them will still look as they do.
You can change the appearance of the data via a transformation. One that approximately stabilizes variance when the Poisson parameter is not very small is $\sqrt{y}$. If the Poisson parameter can take small values, you may like to try $\sqrt{y+\frac{3}{8}}$ or $\sqrt{y}+\sqrt{y+1}$ instead (it looks to me like that might well be the case that you have small values).
On the other hand, one that would linearize your fitted model would be a log (but that's only suitable if you don't have exact zeros).
--
Although it won't be satisfying to you, you can plot the fitted curve via
plot(temp,encno,xlim=c(0,60))
newdat <- data.frame(temp=seq(9,48,.5))
encnoglm1 <- glm(formula = encno ~ temp, family = quasipoisson(link = log),
data = encnotemp)
fit <- predict(encnoglm1,newdata=newdat,type="response")
lines(fit~temp,data=newdat,type="l",col=4)
Or if you want to look at what would be a nearly constant variance if the quasipoisson were suitable:
plot(temp,sqrt(encno+3/8),xlim=c(0,60))
lines(sqrt(fit+3/8)~temp,data=newdat,type="l",col=2)
|
Plotting the results of GLM in R
"I was told the R value was too low compared to the significance of the p value" -- sounds like nonsense to me.
On the other hand, some form of glm may be a good idea (but it looks to me like the spr
|
40,331
|
Understanding Bagged Logistic Regression (and a Python Implementation)
|
Bagging is an ensemble method where you train model on independent samples of the training data and combine (average, vote, ...) their predictions. This generally produces more accurate predictions than the individual models. Technically bagging means that the samples are drawn with replacement and of the same size as the full data set. However the term is sometimes also applied to other sampling schemes.
Bagged Logistic Regression means bagging using logistic regression for the individual models, but it is bagging in the loose sense of the word.
They are really combining subsampling (ie sampling without replacement) with randomized subspaces (sampling the columns/features).
In the quote ps is the fraction of the rows/items included in each sample and pc is the fraction of columns/features. They just use a more statistics flavored terminology where observations are the rows and covariates are the columns.
This is close to what sklearn.linear_model.RandomizedLogisticRegression does internally. The main differences are that RandomizedLogisticRegression does not support column sampling and also it is not a predictive model. It is only used to select relevant features.
Bagging does not really offer anything extra for dealing with sequencing information. You can create features that encode the sequencing information as you would with any other machine learning method, but if that is the main thing you are interested in you should look into specialized methods.
|
Understanding Bagged Logistic Regression (and a Python Implementation)
|
Bagging is an ensemble method where you train model on independent samples of the training data and combine (average, vote, ...) their predictions. This generally produces more accurate predictions th
|
Understanding Bagged Logistic Regression (and a Python Implementation)
Bagging is an ensemble method where you train model on independent samples of the training data and combine (average, vote, ...) their predictions. This generally produces more accurate predictions than the individual models. Technically bagging means that the samples are drawn with replacement and of the same size as the full data set. However the term is sometimes also applied to other sampling schemes.
Bagged Logistic Regression means bagging using logistic regression for the individual models, but it is bagging in the loose sense of the word.
They are really combining subsampling (ie sampling without replacement) with randomized subspaces (sampling the columns/features).
In the quote ps is the fraction of the rows/items included in each sample and pc is the fraction of columns/features. They just use a more statistics flavored terminology where observations are the rows and covariates are the columns.
This is close to what sklearn.linear_model.RandomizedLogisticRegression does internally. The main differences are that RandomizedLogisticRegression does not support column sampling and also it is not a predictive model. It is only used to select relevant features.
Bagging does not really offer anything extra for dealing with sequencing information. You can create features that encode the sequencing information as you would with any other machine learning method, but if that is the main thing you are interested in you should look into specialized methods.
|
Understanding Bagged Logistic Regression (and a Python Implementation)
Bagging is an ensemble method where you train model on independent samples of the training data and combine (average, vote, ...) their predictions. This generally produces more accurate predictions th
|
40,332
|
Implement Fisher Scoring for linear regression
|
I have fixed the code according to the suggestions by @Randel. Now it works, except $\sigma^2$ takes a very long time to converge.
Here is the code:
fisher.scoring <- function(y, x, start = runif(ncol(x)+1)){
n <- nrow(x)
p <- ncol(x)
theta <- start
score <- rep(0, p+1)
for (i in 1:1000){
# betas
score[1:p] <- (1/theta[p+1]) * t((y - x%*%theta[1:p])) %*% x
# sigma
score[p+1] <- -(n/(2*theta[p+1])) +
(1/(2*theta[p+1]^2)) *
crossprod(y - x %*% theta[1:p])
# new
hessMat <- matrix(0,ncol=p+1,nrow = p+1)
for(j in 1:n)
{
# Estimate derivative of likelihood for each observation
estVec <- c((1/theta[p+1]) *
t((y[j] - x[j,]%*%theta[1:p])) %*% x[j,],
-(n/(2*theta[p+1])) + (1/(2*theta[p+1]^2)) *
crossprod(y[j] - x[j,] %*% theta[1:p]))
# Add them up as suggested to get an estimate of the Hessian.
hessMat <- hessMat + estVec%*%t(estVec)
}
theta <- theta + MASS::ginv(hessMat) %*% score
}
return(theta)
}
Now when I run the code I get the following:
> lm.fit(cbind(1,x), y)$coefficients
x1 x2 x3
2.0136134 0.9356782 2.9666921
> fisher.scoring(y, cbind(1,x))
[,1]
[1,] 2.0136126
[2,] 0.9356782
[3,] 2.9666917
[4,] 0.6534185
I ran it again with 5000 iterations instead of 1000 and then I get:
> fisher.scoring(y, cbind(1,x))
[,1]
[1,] 2.0136133
[2,] 0.9356782
[3,] 2.9666920
[4,] 0.8962295
Hope this helps! $\sigma^2$ seems to be converging very slowly, I do not know why, I guess that is material for another question!
EDIT: Here you can see the convergence of the parameters. The number of iterations is on a log-scale. The regression coefficients take 30-40 iterations to converge, although the $\beta_1$ parameter overshoots and then comes down again, (I was not expecting to see that). The $\sigma^2$ parameter is converging rather fast as the other ones are converging, and then the convergence slows down a lot. I have no idea at the moment why this happens.
EDIT2: There was an error in the update for $\sigma^2$. See Randel's answer for the correction.
|
Implement Fisher Scoring for linear regression
|
I have fixed the code according to the suggestions by @Randel. Now it works, except $\sigma^2$ takes a very long time to converge.
Here is the code:
fisher.scoring <- function(y, x, start = runif(ncol
|
Implement Fisher Scoring for linear regression
I have fixed the code according to the suggestions by @Randel. Now it works, except $\sigma^2$ takes a very long time to converge.
Here is the code:
fisher.scoring <- function(y, x, start = runif(ncol(x)+1)){
n <- nrow(x)
p <- ncol(x)
theta <- start
score <- rep(0, p+1)
for (i in 1:1000){
# betas
score[1:p] <- (1/theta[p+1]) * t((y - x%*%theta[1:p])) %*% x
# sigma
score[p+1] <- -(n/(2*theta[p+1])) +
(1/(2*theta[p+1]^2)) *
crossprod(y - x %*% theta[1:p])
# new
hessMat <- matrix(0,ncol=p+1,nrow = p+1)
for(j in 1:n)
{
# Estimate derivative of likelihood for each observation
estVec <- c((1/theta[p+1]) *
t((y[j] - x[j,]%*%theta[1:p])) %*% x[j,],
-(n/(2*theta[p+1])) + (1/(2*theta[p+1]^2)) *
crossprod(y[j] - x[j,] %*% theta[1:p]))
# Add them up as suggested to get an estimate of the Hessian.
hessMat <- hessMat + estVec%*%t(estVec)
}
theta <- theta + MASS::ginv(hessMat) %*% score
}
return(theta)
}
Now when I run the code I get the following:
> lm.fit(cbind(1,x), y)$coefficients
x1 x2 x3
2.0136134 0.9356782 2.9666921
> fisher.scoring(y, cbind(1,x))
[,1]
[1,] 2.0136126
[2,] 0.9356782
[3,] 2.9666917
[4,] 0.6534185
I ran it again with 5000 iterations instead of 1000 and then I get:
> fisher.scoring(y, cbind(1,x))
[,1]
[1,] 2.0136133
[2,] 0.9356782
[3,] 2.9666920
[4,] 0.8962295
Hope this helps! $\sigma^2$ seems to be converging very slowly, I do not know why, I guess that is material for another question!
EDIT: Here you can see the convergence of the parameters. The number of iterations is on a log-scale. The regression coefficients take 30-40 iterations to converge, although the $\beta_1$ parameter overshoots and then comes down again, (I was not expecting to see that). The $\sigma^2$ parameter is converging rather fast as the other ones are converging, and then the convergence slows down a lot. I have no idea at the moment why this happens.
EDIT2: There was an error in the update for $\sigma^2$. See Randel's answer for the correction.
|
Implement Fisher Scoring for linear regression
I have fixed the code according to the suggestions by @Randel. Now it works, except $\sigma^2$ takes a very long time to converge.
Here is the code:
fisher.scoring <- function(y, x, start = runif(ncol
|
40,333
|
Implement Fisher Scoring for linear regression
|
The short answer is that there is a bug in @guðmundur-einarsson's code.
For each observation, the score function for $\sigma^2$ is $$\frac{\partial L_i}{\partial \sigma^2} = -\frac{1}{2\sigma^{2}}+\frac{1}{2\sigma^{4}}(y_i-X_i\beta)^{'}(y_i-X_i\beta),$$ not $\frac{\partial L_i}{\partial \sigma^2} = -\frac{{\color{red}N}}{2\sigma^{2}}+\frac{1}{2\sigma^{4}}(y_i-X_i\beta)^{'}(y_i-X_i\beta)$. So just replace n in estVec with 1. Although it's not apparent, there're some clues.
The estimate of $\sigma^2$ weirdly does not change much through iterations, although it shows some trend when ylim is automatically set to be small. This small change is because each move is divided by about $N$.
As noted by @guðmundur-einarsson in the related question:
The convergence is rather fast in the beginning and then stagnates
and continues very slowly when the regression parameters converge.
When $\beta$ does not converge (at round 4 of the x-axis in the above figures) , $\sigma^2$ depends on $\beta$, so it's changing faster as compared to that after $\beta$ converges. The log scale of iteration times seems also produce some artificial effect.
The reason why $\beta$ can still converge with the bug can be explained by its closed-form solution does not depend on $\sigma^2$ at all.
The following figures are based on 100 iterations and the random seed is set as 1.
The lesson I learned from this is keeping debugging, although it's relatively easier in this small example.
|
Implement Fisher Scoring for linear regression
|
The short answer is that there is a bug in @guðmundur-einarsson's code.
For each observation, the score function for $\sigma^2$ is $$\frac{\partial L_i}{\partial \sigma^2} = -\frac{1}{2\sigma^{2}}+\f
|
Implement Fisher Scoring for linear regression
The short answer is that there is a bug in @guðmundur-einarsson's code.
For each observation, the score function for $\sigma^2$ is $$\frac{\partial L_i}{\partial \sigma^2} = -\frac{1}{2\sigma^{2}}+\frac{1}{2\sigma^{4}}(y_i-X_i\beta)^{'}(y_i-X_i\beta),$$ not $\frac{\partial L_i}{\partial \sigma^2} = -\frac{{\color{red}N}}{2\sigma^{2}}+\frac{1}{2\sigma^{4}}(y_i-X_i\beta)^{'}(y_i-X_i\beta)$. So just replace n in estVec with 1. Although it's not apparent, there're some clues.
The estimate of $\sigma^2$ weirdly does not change much through iterations, although it shows some trend when ylim is automatically set to be small. This small change is because each move is divided by about $N$.
As noted by @guðmundur-einarsson in the related question:
The convergence is rather fast in the beginning and then stagnates
and continues very slowly when the regression parameters converge.
When $\beta$ does not converge (at round 4 of the x-axis in the above figures) , $\sigma^2$ depends on $\beta$, so it's changing faster as compared to that after $\beta$ converges. The log scale of iteration times seems also produce some artificial effect.
The reason why $\beta$ can still converge with the bug can be explained by its closed-form solution does not depend on $\sigma^2$ at all.
The following figures are based on 100 iterations and the random seed is set as 1.
The lesson I learned from this is keeping debugging, although it's relatively easier in this small example.
|
Implement Fisher Scoring for linear regression
The short answer is that there is a bug in @guðmundur-einarsson's code.
For each observation, the score function for $\sigma^2$ is $$\frac{\partial L_i}{\partial \sigma^2} = -\frac{1}{2\sigma^{2}}+\f
|
40,334
|
SVM why do we maximize 2/||w||
|
I assume that you understand that the margin is given by the equation $\langle w,x\rangle+b=\pm k$ where the width of the margin is equal to $2k$ and one has to maximise the width $k$.
Notice that the equation represents a hyperplane with normal vector $w$. Furthermore, if $w$ is a normal vector, then $\lambda w$ is also a normal vector (where $\lambda$ is a scalar). So we can just as well write $\langle \lambda w, x \rangle + b = \pm k$ or $\langle w , x \rangle + \frac{b}{\lambda} = \pm \frac{k}{\lambda}$. So by ''re-scaling" the vector $w$ with a factor $\lambda$ we can reduce the equation to $\langle w, x \rangle + b = \pm 1$.
If you want to compute the distance of a point $x_0$ to a hyperplane (see my answer to Getting distance of points from decision boundary with linear SVM?) than you have to compute
$\frac{| \langle w, x_0 \rangle +b |}{\sqrt{ \langle w,w \rangle}}$. (note that ${\sqrt{ \langle w,w \rangle}}=||w||$). If I take $x_0$ a point on the margin, then is must fullfill the equation of the margin, so $\langle w, x_0 \rangle +b=\pm 1$ so for a point on the margin the distance is equal to $\frac{| \langle w, x_0 \rangle +b |}{\sqrt{\langle w,w \rangle}}=\frac{| \pm 1 |}{\sqrt{\langle w,w \rangle}}$
EDIT: you added the picture and asked an additional question:
For equation $x_1+5x_2=5$ we see that when $x_1=0$ then $x_2=1$ and for $x_2=0$ we have $x_1=5$, so the $x_1$ axis is vertical and $x_2$ horizontal (you see that when you look for these points on your graph).
The point $(x_1,x_2)=(5,0)$ is on the red line (note that your $x_1$ is vertical) , $w$ is the vector $(1,5)$ and your equation is $x_1+5x_2+0=0$, so you have to compute $\langle w, x \rangle + 0 = 1 \times 5 + 5 \times 0 + 0 = 5$ and divide this by the norm of $w$ which is $\sqrt{1 \times 1 + 5 \times 5} \approx 5.1$, so half the margin is $\frac{5}{5.1}$
EDIT: Added after the question in your comments
The reason for 'eliminating' the $k$ is technical: because of the fact that the normal vector is only known op to a constant, the problem has no unique solution. So either you have to fix the norm of w or you have to fix the k. You could see both cases as choosing a different unit for measuring distances.
|
SVM why do we maximize 2/||w||
|
I assume that you understand that the margin is given by the equation $\langle w,x\rangle+b=\pm k$ where the width of the margin is equal to $2k$ and one has to maximise the width $k$.
Notice that
|
SVM why do we maximize 2/||w||
I assume that you understand that the margin is given by the equation $\langle w,x\rangle+b=\pm k$ where the width of the margin is equal to $2k$ and one has to maximise the width $k$.
Notice that the equation represents a hyperplane with normal vector $w$. Furthermore, if $w$ is a normal vector, then $\lambda w$ is also a normal vector (where $\lambda$ is a scalar). So we can just as well write $\langle \lambda w, x \rangle + b = \pm k$ or $\langle w , x \rangle + \frac{b}{\lambda} = \pm \frac{k}{\lambda}$. So by ''re-scaling" the vector $w$ with a factor $\lambda$ we can reduce the equation to $\langle w, x \rangle + b = \pm 1$.
If you want to compute the distance of a point $x_0$ to a hyperplane (see my answer to Getting distance of points from decision boundary with linear SVM?) than you have to compute
$\frac{| \langle w, x_0 \rangle +b |}{\sqrt{ \langle w,w \rangle}}$. (note that ${\sqrt{ \langle w,w \rangle}}=||w||$). If I take $x_0$ a point on the margin, then is must fullfill the equation of the margin, so $\langle w, x_0 \rangle +b=\pm 1$ so for a point on the margin the distance is equal to $\frac{| \langle w, x_0 \rangle +b |}{\sqrt{\langle w,w \rangle}}=\frac{| \pm 1 |}{\sqrt{\langle w,w \rangle}}$
EDIT: you added the picture and asked an additional question:
For equation $x_1+5x_2=5$ we see that when $x_1=0$ then $x_2=1$ and for $x_2=0$ we have $x_1=5$, so the $x_1$ axis is vertical and $x_2$ horizontal (you see that when you look for these points on your graph).
The point $(x_1,x_2)=(5,0)$ is on the red line (note that your $x_1$ is vertical) , $w$ is the vector $(1,5)$ and your equation is $x_1+5x_2+0=0$, so you have to compute $\langle w, x \rangle + 0 = 1 \times 5 + 5 \times 0 + 0 = 5$ and divide this by the norm of $w$ which is $\sqrt{1 \times 1 + 5 \times 5} \approx 5.1$, so half the margin is $\frac{5}{5.1}$
EDIT: Added after the question in your comments
The reason for 'eliminating' the $k$ is technical: because of the fact that the normal vector is only known op to a constant, the problem has no unique solution. So either you have to fix the norm of w or you have to fix the k. You could see both cases as choosing a different unit for measuring distances.
|
SVM why do we maximize 2/||w||
I assume that you understand that the margin is given by the equation $\langle w,x\rangle+b=\pm k$ where the width of the margin is equal to $2k$ and one has to maximise the width $k$.
Notice that
|
40,335
|
Combining Linear Regression and Time Series
|
Previously I was thinking I would figure out what lags/ARIMA model I should be using (it’s looking like a (2,0,0)) and then apply the AR2 to the residuals (or even the whole of the dependent variable) to produce a new independent variable that I then use in the linear regression. But this doesn’t seem mathematically sound.
Instead of doing it in two steps, you can do it simultaneously, making it more "mathematically sound". That will be a regression with ARMA errors. Here is some discussion of that and related techniques. R implementation is also discussed.
In your case, denote the dependent variable $y$ and the independent variables $x_1, \dotsb, x_k$. Having loaded library "forecast", use auto.arima(y,xreg=cbind(x_1,...,x_k)) to automatically select a sensible order for the ARMA structure in the model errors.
|
Combining Linear Regression and Time Series
|
Previously I was thinking I would figure out what lags/ARIMA model I should be using (it’s looking like a (2,0,0)) and then apply the AR2 to the residuals (or even the whole of the dependent variable)
|
Combining Linear Regression and Time Series
Previously I was thinking I would figure out what lags/ARIMA model I should be using (it’s looking like a (2,0,0)) and then apply the AR2 to the residuals (or even the whole of the dependent variable) to produce a new independent variable that I then use in the linear regression. But this doesn’t seem mathematically sound.
Instead of doing it in two steps, you can do it simultaneously, making it more "mathematically sound". That will be a regression with ARMA errors. Here is some discussion of that and related techniques. R implementation is also discussed.
In your case, denote the dependent variable $y$ and the independent variables $x_1, \dotsb, x_k$. Having loaded library "forecast", use auto.arima(y,xreg=cbind(x_1,...,x_k)) to automatically select a sensible order for the ARMA structure in the model errors.
|
Combining Linear Regression and Time Series
Previously I was thinking I would figure out what lags/ARIMA model I should be using (it’s looking like a (2,0,0)) and then apply the AR2 to the residuals (or even the whole of the dependent variable)
|
40,336
|
Combining Linear Regression and Time Series
|
The combination is called Transfer Function modelling . See Cross correlation influenced by self auto correlation for my answer and a very good tutorial from Penn State on model identifviaction. Also look at http://www.autobox.com/cms/index.php/afs-university/intro-to-forecasting/doc_download/24-regression-vs-box-jenkins for a philosophical discussion of Regression vs Box-Jenkins
|
Combining Linear Regression and Time Series
|
The combination is called Transfer Function modelling . See Cross correlation influenced by self auto correlation for my answer and a very good tutorial from Penn State on model identifviaction. Also
|
Combining Linear Regression and Time Series
The combination is called Transfer Function modelling . See Cross correlation influenced by self auto correlation for my answer and a very good tutorial from Penn State on model identifviaction. Also look at http://www.autobox.com/cms/index.php/afs-university/intro-to-forecasting/doc_download/24-regression-vs-box-jenkins for a philosophical discussion of Regression vs Box-Jenkins
|
Combining Linear Regression and Time Series
The combination is called Transfer Function modelling . See Cross correlation influenced by self auto correlation for my answer and a very good tutorial from Penn State on model identifviaction. Also
|
40,337
|
How to calculate decision boundary from support vectors?
|
A binary SVM tries to separate subjects belonging to one of two classes based on some features, the class will be denoted as $y_i \in \{-1,+1\}$ and the features as $x_i$, note the $y_i$ is a single number while $x_i$ is a vector. The index $i$ identifies the subject.
The SVM solves a quadratic programming problem and finds, for each subject a lagrange multiplier $\alpha_i$, many of the $\alpha$'s are zero. Note that the $\alpha_i$ are numbers, so for each subject $i$ you have a number $y_i$, a feature vector $x_i$ and a lagrange multiplier $\alpha_i$ (a number).
You have also choosen a kernel $K(x,y)$ ($x$ and $y$ are vectors) for which you know the functional form and you have choosen a capacity parameter $C$.
The $x_i$ for which the corresponding $\alpha_i$ are non-zero are the support vectors.
To compute your decision boundary, I refer to this article. Formula (61) from the mentioned article learns that the decision boundary has the equation $f(x)=0$, where $f(x)=\sum_i \alpha_i y_i K(x_i, x) + b$ and as the $\alpha_i$ are only non-zero for the support vectors, this becomes (SV is the set of support vectors): $f(x)=\sum_{i \in SV} \alpha_i y_i K(s_i, x) + b$ (where I changed $x_i$ to $s_i$ as in formula (61) of the article, to indicate that only support vectors appear).
As you know all the support vectors, you know the (non-zero) $\alpha_i$, the corresponding (number) $y_i$ and the vectors $s_i$, you can compute this $f(x)$ if you know your kernel $K$ and the constant $b$.
So we still have to find $b$: The equations (55) and (56) of the article I referred to, learn that for an arbitrary $\alpha_i$ with $0 < \alpha_i < C$ (C is a parameter of your SVM) it holds that $y_i ( x_i \cdot w + b) = 1$ where $w$ is given by equation (46) of the article. So $b = \frac{1}{y_i} - x_i \cdot w=\frac{1}{y_i} - \sum_{k \in SV} \alpha_k y_k K(x_i, s_k)$. (the '$\cdot$' is the inner product that will later be replaced by the kernel, see article that I referred to).
The latter holds for any of the $\alpha_i, 0 < \alpha_i < C$, so if you choose one such an $\alpha_i$ that is smaller than $C$ and positive , then you can compute $b$ from the corresponding observation: take an $m$ for which $0 < \alpha_m < C$, with this $m$ there corresponds an $x_m$ and an $y_m$. On the other hand you know all the support vectors $s_k$ (which are the vectors $x_k$ whith non-zero $\alpha_k$ see above) with their corresponding $y_k$ and $\alpha_k$. With all these you can compute $f(x)$ and $f(x)=0$ identifies the decision boundary, the sign of $f(x)$ determines the class.
So to summarise:
Take the subjects $k$ that correspond to the support vectors, i.e. for which the Lagrange multiplier $\alpha_k$ is not zero, for each such subject you have the Lagrange multiplier $\alpha_k$, the class $y_k \in \{-1,+1\}$, and the feature vector $x_k$ (denoted as $s_k$ to make it clear that it are support vectors);
Take one subject for which the Lagrange multiplier is strictly smaller than $C$, and strictly positive, assume this is object $m$ and use it to compute $b$ as $b =\frac{1}{y_m} - \sum_{k \in SV} \alpha_k y_k K(x_m, s_k)$;
The equation that identifies the decision boundary is $f(x)=0$ where $f(x)=\sum_{k \in SV} \alpha_k y_k K(s_k, x) + b$
|
How to calculate decision boundary from support vectors?
|
A binary SVM tries to separate subjects belonging to one of two classes based on some features, the class will be denoted as $y_i \in \{-1,+1\}$ and the features as $x_i$, note the $y_i$ is a single n
|
How to calculate decision boundary from support vectors?
A binary SVM tries to separate subjects belonging to one of two classes based on some features, the class will be denoted as $y_i \in \{-1,+1\}$ and the features as $x_i$, note the $y_i$ is a single number while $x_i$ is a vector. The index $i$ identifies the subject.
The SVM solves a quadratic programming problem and finds, for each subject a lagrange multiplier $\alpha_i$, many of the $\alpha$'s are zero. Note that the $\alpha_i$ are numbers, so for each subject $i$ you have a number $y_i$, a feature vector $x_i$ and a lagrange multiplier $\alpha_i$ (a number).
You have also choosen a kernel $K(x,y)$ ($x$ and $y$ are vectors) for which you know the functional form and you have choosen a capacity parameter $C$.
The $x_i$ for which the corresponding $\alpha_i$ are non-zero are the support vectors.
To compute your decision boundary, I refer to this article. Formula (61) from the mentioned article learns that the decision boundary has the equation $f(x)=0$, where $f(x)=\sum_i \alpha_i y_i K(x_i, x) + b$ and as the $\alpha_i$ are only non-zero for the support vectors, this becomes (SV is the set of support vectors): $f(x)=\sum_{i \in SV} \alpha_i y_i K(s_i, x) + b$ (where I changed $x_i$ to $s_i$ as in formula (61) of the article, to indicate that only support vectors appear).
As you know all the support vectors, you know the (non-zero) $\alpha_i$, the corresponding (number) $y_i$ and the vectors $s_i$, you can compute this $f(x)$ if you know your kernel $K$ and the constant $b$.
So we still have to find $b$: The equations (55) and (56) of the article I referred to, learn that for an arbitrary $\alpha_i$ with $0 < \alpha_i < C$ (C is a parameter of your SVM) it holds that $y_i ( x_i \cdot w + b) = 1$ where $w$ is given by equation (46) of the article. So $b = \frac{1}{y_i} - x_i \cdot w=\frac{1}{y_i} - \sum_{k \in SV} \alpha_k y_k K(x_i, s_k)$. (the '$\cdot$' is the inner product that will later be replaced by the kernel, see article that I referred to).
The latter holds for any of the $\alpha_i, 0 < \alpha_i < C$, so if you choose one such an $\alpha_i$ that is smaller than $C$ and positive , then you can compute $b$ from the corresponding observation: take an $m$ for which $0 < \alpha_m < C$, with this $m$ there corresponds an $x_m$ and an $y_m$. On the other hand you know all the support vectors $s_k$ (which are the vectors $x_k$ whith non-zero $\alpha_k$ see above) with their corresponding $y_k$ and $\alpha_k$. With all these you can compute $f(x)$ and $f(x)=0$ identifies the decision boundary, the sign of $f(x)$ determines the class.
So to summarise:
Take the subjects $k$ that correspond to the support vectors, i.e. for which the Lagrange multiplier $\alpha_k$ is not zero, for each such subject you have the Lagrange multiplier $\alpha_k$, the class $y_k \in \{-1,+1\}$, and the feature vector $x_k$ (denoted as $s_k$ to make it clear that it are support vectors);
Take one subject for which the Lagrange multiplier is strictly smaller than $C$, and strictly positive, assume this is object $m$ and use it to compute $b$ as $b =\frac{1}{y_m} - \sum_{k \in SV} \alpha_k y_k K(x_m, s_k)$;
The equation that identifies the decision boundary is $f(x)=0$ where $f(x)=\sum_{k \in SV} \alpha_k y_k K(s_k, x) + b$
|
How to calculate decision boundary from support vectors?
A binary SVM tries to separate subjects belonging to one of two classes based on some features, the class will be denoted as $y_i \in \{-1,+1\}$ and the features as $x_i$, note the $y_i$ is a single n
|
40,338
|
How does linear SVMs function in multi dimensional feature space?
|
Linear SVM always works in the exact same way, even if you can't mentally wrap your head around the geometrics. Humans are generally bad at reasoning in more than three dimensions, so don't let that worry you.
Imagine linear SVM in one dimension. This would look something like this:
+ + + + + | - - - -
where | is your decision boundary. A hyperplane in one dimension is a cutoff value. In two dimensions, you get a line. In three dimensions, you get a plane, ...
With 4000 features in input space, you probably don't benefit enough by mapping to a higher dimensional feature space (= use a kernel) to make it worth the extra computational expense. Hence, use a linear kernel.
In fact, always use the linear kernel first and see if you get satisfactory results. Generally, you can try a nonlinear kernel if and only if you don't get good results with a linear kernel.
|
How does linear SVMs function in multi dimensional feature space?
|
Linear SVM always works in the exact same way, even if you can't mentally wrap your head around the geometrics. Humans are generally bad at reasoning in more than three dimensions, so don't let that w
|
How does linear SVMs function in multi dimensional feature space?
Linear SVM always works in the exact same way, even if you can't mentally wrap your head around the geometrics. Humans are generally bad at reasoning in more than three dimensions, so don't let that worry you.
Imagine linear SVM in one dimension. This would look something like this:
+ + + + + | - - - -
where | is your decision boundary. A hyperplane in one dimension is a cutoff value. In two dimensions, you get a line. In three dimensions, you get a plane, ...
With 4000 features in input space, you probably don't benefit enough by mapping to a higher dimensional feature space (= use a kernel) to make it worth the extra computational expense. Hence, use a linear kernel.
In fact, always use the linear kernel first and see if you get satisfactory results. Generally, you can try a nonlinear kernel if and only if you don't get good results with a linear kernel.
|
How does linear SVMs function in multi dimensional feature space?
Linear SVM always works in the exact same way, even if you can't mentally wrap your head around the geometrics. Humans are generally bad at reasoning in more than three dimensions, so don't let that w
|
40,339
|
How does linear SVMs function in multi dimensional feature space?
|
I was even stuck at same question for sometime, then I reffered some of the websites through which I was able yo get the intution.
If you are not able to visualise in mind consider this..
For 1 dimensional dataset a point will be suitable to discriminate between different classes.
Increase a dimension up for a 2 dimensional plane of data a single line may discriminate it with/without applying kernel.
Another increase will be analogous to having data in three dimensions but hyperplane or seperating plane in 2 dimension as we know a plane is 2d.
According to following Wikipedia article's starting lines you may develop the intution.
https://en.m.wikipedia.org/wiki/Hyperplane
The hyperplane is just one dimension less than data in order to separate the data points into multiple classes.
Then for 4000 feature space it will be nothing other than 3999 dimensional plane (plane in order to seperate) or simply collection of the points with 3999 dimensions in order to seperate the data points.
|
How does linear SVMs function in multi dimensional feature space?
|
I was even stuck at same question for sometime, then I reffered some of the websites through which I was able yo get the intution.
If you are not able to visualise in mind consider this..
For 1 dimen
|
How does linear SVMs function in multi dimensional feature space?
I was even stuck at same question for sometime, then I reffered some of the websites through which I was able yo get the intution.
If you are not able to visualise in mind consider this..
For 1 dimensional dataset a point will be suitable to discriminate between different classes.
Increase a dimension up for a 2 dimensional plane of data a single line may discriminate it with/without applying kernel.
Another increase will be analogous to having data in three dimensions but hyperplane or seperating plane in 2 dimension as we know a plane is 2d.
According to following Wikipedia article's starting lines you may develop the intution.
https://en.m.wikipedia.org/wiki/Hyperplane
The hyperplane is just one dimension less than data in order to separate the data points into multiple classes.
Then for 4000 feature space it will be nothing other than 3999 dimensional plane (plane in order to seperate) or simply collection of the points with 3999 dimensions in order to seperate the data points.
|
How does linear SVMs function in multi dimensional feature space?
I was even stuck at same question for sometime, then I reffered some of the websites through which I was able yo get the intution.
If you are not able to visualise in mind consider this..
For 1 dimen
|
40,340
|
Linear regression: Intercept isn't significant
|
It is not necessarily a problem that an intercept is not significant(ly different from zero) and indeed that may be scientifically or practically what you expect. But much more can be said.
The estimate of the intercept for any linear regression that includes one will be determined by all the data, especially including those furthest away from it! The estimation thus pays no attention to whatever is substantively meaningful or interpretable (physically, biologically, economically, and so forth). In many projects what happens at or near the origin to the position of the fit may be at least partly a side-effect of the leverage exerted by very large positive values, either of the response or of the predictors. (In principle, exactly the same leverage effect could be observed for large negative values, but that is less common in practice.) Intuition can be gained by looking at scatter plots in 2 or 3 dimensions and imagining how the fitted line or plane needs to move to satisfy a least squares criterion (unless, naturally, some other fitting method is used).
Nevertheless it is often a good idea to think about whether the intercept estimate is consistent with known or expected behaviour of the response or outcome variable as it changes with predictors. This is especially important whenever there are values close to zero for the predictors, but less important when no value is close to their origin, when the intercept is in effect just an extrapolation of the fitted line or plane away from the mass of the data. When doing this, drawing graphs never hurts and can be invaluable for understanding what is happening. (It is still extraordinarily common in my experience to encounter researchers who have fitted a regression and not plotted their data. This is most common, it seems, in certain social sciences marked by a primitive belief that testing every hypothesis in sight is not only necessary but also sufficient to elucidate what has been done.)
The example here of box office revenues is typical of many response variables which cannot be negative and in practice will usually be positive. Concern that a negative intercept might be produced can be linked to a deeper concern. A linear regression $y = Xb$ is often not a good idea for such responses any way as in principle it will predict negative values for some values of the predictors. Here using a generalised linear model with logarithmic link is often much better, and may capture curvature and heteroscedasticity in the data in a way that is consistent with the underlying science.
With a nod to completeness, note also that many people prefer to omit the intercept from a linear regression and force the fitted surface through the origin and/or to use other functional forms (power laws or power functions) that do something equivalent. There are costs as well as benefits to either strategy.
|
Linear regression: Intercept isn't significant
|
It is not necessarily a problem that an intercept is not significant(ly different from zero) and indeed that may be scientifically or practically what you expect. But much more can be said.
The estim
|
Linear regression: Intercept isn't significant
It is not necessarily a problem that an intercept is not significant(ly different from zero) and indeed that may be scientifically or practically what you expect. But much more can be said.
The estimate of the intercept for any linear regression that includes one will be determined by all the data, especially including those furthest away from it! The estimation thus pays no attention to whatever is substantively meaningful or interpretable (physically, biologically, economically, and so forth). In many projects what happens at or near the origin to the position of the fit may be at least partly a side-effect of the leverage exerted by very large positive values, either of the response or of the predictors. (In principle, exactly the same leverage effect could be observed for large negative values, but that is less common in practice.) Intuition can be gained by looking at scatter plots in 2 or 3 dimensions and imagining how the fitted line or plane needs to move to satisfy a least squares criterion (unless, naturally, some other fitting method is used).
Nevertheless it is often a good idea to think about whether the intercept estimate is consistent with known or expected behaviour of the response or outcome variable as it changes with predictors. This is especially important whenever there are values close to zero for the predictors, but less important when no value is close to their origin, when the intercept is in effect just an extrapolation of the fitted line or plane away from the mass of the data. When doing this, drawing graphs never hurts and can be invaluable for understanding what is happening. (It is still extraordinarily common in my experience to encounter researchers who have fitted a regression and not plotted their data. This is most common, it seems, in certain social sciences marked by a primitive belief that testing every hypothesis in sight is not only necessary but also sufficient to elucidate what has been done.)
The example here of box office revenues is typical of many response variables which cannot be negative and in practice will usually be positive. Concern that a negative intercept might be produced can be linked to a deeper concern. A linear regression $y = Xb$ is often not a good idea for such responses any way as in principle it will predict negative values for some values of the predictors. Here using a generalised linear model with logarithmic link is often much better, and may capture curvature and heteroscedasticity in the data in a way that is consistent with the underlying science.
With a nod to completeness, note also that many people prefer to omit the intercept from a linear regression and force the fitted surface through the origin and/or to use other functional forms (power laws or power functions) that do something equivalent. There are costs as well as benefits to either strategy.
|
Linear regression: Intercept isn't significant
It is not necessarily a problem that an intercept is not significant(ly different from zero) and indeed that may be scientifically or practically what you expect. But much more can be said.
The estim
|
40,341
|
Linear regression: Intercept isn't significant
|
I think you understand correctly :)
The intercept isn't significant because there isn't sufficient statistical evidence that it's different from zero. And as you say, it seems reasonable that a Movie not mentioned by anyone would make no money.
|
Linear regression: Intercept isn't significant
|
I think you understand correctly :)
The intercept isn't significant because there isn't sufficient statistical evidence that it's different from zero. And as you say, it seems reasonable that a Movie
|
Linear regression: Intercept isn't significant
I think you understand correctly :)
The intercept isn't significant because there isn't sufficient statistical evidence that it's different from zero. And as you say, it seems reasonable that a Movie not mentioned by anyone would make no money.
|
Linear regression: Intercept isn't significant
I think you understand correctly :)
The intercept isn't significant because there isn't sufficient statistical evidence that it's different from zero. And as you say, it seems reasonable that a Movie
|
40,342
|
$\chi^2$ tabulated value
|
The following say the same thing:
For a given "area to the right of the critical value," called $\alpha$ (Greek "alpha"), the critical value increases with the degrees of freedom, called $\nu$ (Greek "nu").
For a given critical value $c$, $\alpha$ increases with $\nu$.
For any given number $c$, the chance that a $\chi^2(\nu)$ variable $W$ exceeds $c$ increases as $\nu$ goes up.
This has a pretty graphical interpretation. Imagine filling in missing columns for other areas $\alpha$ like $\alpha=0.5$ or $\alpha=0.000001$. Each individual row--for each $\nu$--would express a relation between all those values of $\alpha$, as written in the top header, and the entries $c$. We may graph this relation. It's conventional to put $c$ on the horizontal axis and $\alpha$ on the vertical. Thus, for instance, the top row (for $\nu=21$) contains the ten points $(8.033653, 0.995),$ $(8.897198, 0.99),$ $\ldots, (41.401065, 0.005)$, as shown by the black dots in the left plot:
Of course the filled-in curve has to drop from the highest possible probability of $1$ to the lowest possible value of $0$, because as the critical value increases it becomes less and less likely that $W$ will exceed it.
The right hand plot shows all the values in the table, with the missing columns filled in with curves. Each curve--which is a completely filled-in row of the table--drops from left to right. Their shapes change a little, taking longer to drop the further to the right they go. Ordinarily, when you have a set of curves like this that are shifting and changing their shapes, any two of them will tend to cross each other somewhere. However, in this case if you fix any elevation $\alpha$ and watch what happens as $\nu$ increases, the points on the curves march off consistently to the right: that's what it means for the critical values to increase. The leftmost (green) plots must therefore correspond to the smaller values of $\nu$ near the top of the table and the right hand plots track what happens as $\nu$ grows and we move down through the table. The rightmost (gray) plot shows the values in the bottom row of the table.
In short, these complementary cumulative distribution functions never overlap: as $\nu$ increases, they shift to the right without ever crossing.
That's what is happening. But why?
Recall that a $\chi^2(\nu)$ distribution describes the sum of squares of $\nu$ independent standard Normal variables. Consider what happens to such a sum of squares
$$W = X_1^2 + X_2^2 + \cdots + X_\nu^2$$
when one more square, $X_{\nu+1}^2$, is added to it. Fix a critical value $c$ and suppose $W$ has a chance $\alpha$ of exceeding $c$. Formally,
$$\Pr(W \gt c) = \alpha.$$
Then, because $X_{\nu+1}^2$ is almost surely positive,
$$\Pr(W + X_{\nu+1}^2 \gt c) = \Pr(W \gt c) + \int_0^c \Pr(X_{\nu+1}^2 \gt \varepsilon) f_\nu(c-\varepsilon)d\varepsilon.$$
This expression breaks the situation where $W + X_{\nu+1}^2 \gt c$ into an (infinite) collection of mutually exclusive possibilities. Axioms of probability say that the total chance that $W + X_{\nu+1}^2$ exceeds $c$ must be the sum of all these separate probabilities. I have broken the sum into two parts:
The first term on the right is the chance that $W$ already exceeds $c$, in which case adding $X_{\nu+1}^2$ only makes the sum larger.
The second term on the right (an integral) contemplates all the possibilities where $W$ does not exceed $c$ but $X_{\nu+1}^2$ is large enough to still make $W+X_{\nu+1}^2$ greater than $c$. It uses "$f_\nu$" to represent the probability density function (PDF) of $W$. When $c \gt 0$, the second term is strictly positive (because it can be interpreted as the area under a curve of positive heights and positive horizontal extent going from $0$ to $c$).
Intuitively, this all says that adding another squared normal variate $X_{\nu+1}^2$ to $W$ can only make it more likely that the sum of squares exceeds $c$. That is statement (3), which is the same thing as (1), as asked in the question.
|
$\chi^2$ tabulated value
|
The following say the same thing:
For a given "area to the right of the critical value," called $\alpha$ (Greek "alpha"), the critical value increases with the degrees of freedom, called $\nu$ (Greek
|
$\chi^2$ tabulated value
The following say the same thing:
For a given "area to the right of the critical value," called $\alpha$ (Greek "alpha"), the critical value increases with the degrees of freedom, called $\nu$ (Greek "nu").
For a given critical value $c$, $\alpha$ increases with $\nu$.
For any given number $c$, the chance that a $\chi^2(\nu)$ variable $W$ exceeds $c$ increases as $\nu$ goes up.
This has a pretty graphical interpretation. Imagine filling in missing columns for other areas $\alpha$ like $\alpha=0.5$ or $\alpha=0.000001$. Each individual row--for each $\nu$--would express a relation between all those values of $\alpha$, as written in the top header, and the entries $c$. We may graph this relation. It's conventional to put $c$ on the horizontal axis and $\alpha$ on the vertical. Thus, for instance, the top row (for $\nu=21$) contains the ten points $(8.033653, 0.995),$ $(8.897198, 0.99),$ $\ldots, (41.401065, 0.005)$, as shown by the black dots in the left plot:
Of course the filled-in curve has to drop from the highest possible probability of $1$ to the lowest possible value of $0$, because as the critical value increases it becomes less and less likely that $W$ will exceed it.
The right hand plot shows all the values in the table, with the missing columns filled in with curves. Each curve--which is a completely filled-in row of the table--drops from left to right. Their shapes change a little, taking longer to drop the further to the right they go. Ordinarily, when you have a set of curves like this that are shifting and changing their shapes, any two of them will tend to cross each other somewhere. However, in this case if you fix any elevation $\alpha$ and watch what happens as $\nu$ increases, the points on the curves march off consistently to the right: that's what it means for the critical values to increase. The leftmost (green) plots must therefore correspond to the smaller values of $\nu$ near the top of the table and the right hand plots track what happens as $\nu$ grows and we move down through the table. The rightmost (gray) plot shows the values in the bottom row of the table.
In short, these complementary cumulative distribution functions never overlap: as $\nu$ increases, they shift to the right without ever crossing.
That's what is happening. But why?
Recall that a $\chi^2(\nu)$ distribution describes the sum of squares of $\nu$ independent standard Normal variables. Consider what happens to such a sum of squares
$$W = X_1^2 + X_2^2 + \cdots + X_\nu^2$$
when one more square, $X_{\nu+1}^2$, is added to it. Fix a critical value $c$ and suppose $W$ has a chance $\alpha$ of exceeding $c$. Formally,
$$\Pr(W \gt c) = \alpha.$$
Then, because $X_{\nu+1}^2$ is almost surely positive,
$$\Pr(W + X_{\nu+1}^2 \gt c) = \Pr(W \gt c) + \int_0^c \Pr(X_{\nu+1}^2 \gt \varepsilon) f_\nu(c-\varepsilon)d\varepsilon.$$
This expression breaks the situation where $W + X_{\nu+1}^2 \gt c$ into an (infinite) collection of mutually exclusive possibilities. Axioms of probability say that the total chance that $W + X_{\nu+1}^2$ exceeds $c$ must be the sum of all these separate probabilities. I have broken the sum into two parts:
The first term on the right is the chance that $W$ already exceeds $c$, in which case adding $X_{\nu+1}^2$ only makes the sum larger.
The second term on the right (an integral) contemplates all the possibilities where $W$ does not exceed $c$ but $X_{\nu+1}^2$ is large enough to still make $W+X_{\nu+1}^2$ greater than $c$. It uses "$f_\nu$" to represent the probability density function (PDF) of $W$. When $c \gt 0$, the second term is strictly positive (because it can be interpreted as the area under a curve of positive heights and positive horizontal extent going from $0$ to $c$).
Intuitively, this all says that adding another squared normal variate $X_{\nu+1}^2$ to $W$ can only make it more likely that the sum of squares exceeds $c$. That is statement (3), which is the same thing as (1), as asked in the question.
|
$\chi^2$ tabulated value
The following say the same thing:
For a given "area to the right of the critical value," called $\alpha$ (Greek "alpha"), the critical value increases with the degrees of freedom, called $\nu$ (Greek
|
40,343
|
$\chi^2$ tabulated value
|
Let's recall what a $p$-value is. It is the probability of getting a value as far or further away from a reference / null value as your observed value, if the null hypothesis is true. In your case, you are working with $\chi^2$, so it is the probability of getting an observed $\chi^2$ test statistic as far or further from the expected value if the null hypothesis is true. Moreover, the $\chi^2$ is essentially always a one-tailed test (see here), so we are only interested in the probability of finding a value that far over to the right or further to the right within the null distribution.
Given an observed $\chi^2$ value and the relevant degrees of freedom, you can calculate the $p$-value directly. But you wouldn't want to try it with pen and paper. Nowadays, you can get such $p$-values quite easily with a computer and statistical software (such as R), but tables like the ones you show were very convenient back in the days when computers were not widespread. The idea was that you could set $\alpha$ to any of the values listed along the top ($0.05$ is most common), and look up the critical value of $\chi^2$ according to your degrees of freedom. Then, if the $\chi^2$ value from your analysis was greater than that critical value, you knew that $p<\alpha$ (although you didn't actually know how much less / what the actual $p$-value was).
From the above, we can see that your question becomes: 'Why do we need a progressively higher observed $\chi^2$ value to be in the top $\alpha\%$ of the distribution as the degrees of freedom increases?'
The answer is that the null (more specifically the central) $\chi^2$ distribution changes when the degrees of freedom changes. You can see this in @Hamed's helpful plot: The quantile (observed $\chi^2$ value) that separates the top, say, $5\%$ of the distribution from the bottom $95\%$ is getting larger. Consider just the distributions with df = 2 and df = 9:
|
$\chi^2$ tabulated value
|
Let's recall what a $p$-value is. It is the probability of getting a value as far or further away from a reference / null value as your observed value, if the null hypothesis is true. In your case,
|
$\chi^2$ tabulated value
Let's recall what a $p$-value is. It is the probability of getting a value as far or further away from a reference / null value as your observed value, if the null hypothesis is true. In your case, you are working with $\chi^2$, so it is the probability of getting an observed $\chi^2$ test statistic as far or further from the expected value if the null hypothesis is true. Moreover, the $\chi^2$ is essentially always a one-tailed test (see here), so we are only interested in the probability of finding a value that far over to the right or further to the right within the null distribution.
Given an observed $\chi^2$ value and the relevant degrees of freedom, you can calculate the $p$-value directly. But you wouldn't want to try it with pen and paper. Nowadays, you can get such $p$-values quite easily with a computer and statistical software (such as R), but tables like the ones you show were very convenient back in the days when computers were not widespread. The idea was that you could set $\alpha$ to any of the values listed along the top ($0.05$ is most common), and look up the critical value of $\chi^2$ according to your degrees of freedom. Then, if the $\chi^2$ value from your analysis was greater than that critical value, you knew that $p<\alpha$ (although you didn't actually know how much less / what the actual $p$-value was).
From the above, we can see that your question becomes: 'Why do we need a progressively higher observed $\chi^2$ value to be in the top $\alpha\%$ of the distribution as the degrees of freedom increases?'
The answer is that the null (more specifically the central) $\chi^2$ distribution changes when the degrees of freedom changes. You can see this in @Hamed's helpful plot: The quantile (observed $\chi^2$ value) that separates the top, say, $5\%$ of the distribution from the bottom $95\%$ is getting larger. Consider just the distributions with df = 2 and df = 9:
|
$\chi^2$ tabulated value
Let's recall what a $p$-value is. It is the probability of getting a value as far or further away from a reference / null value as your observed value, if the null hypothesis is true. In your case,
|
40,344
|
$\chi^2$ tabulated value
|
The chi-squared distribution with $n$ degrees of freedom is the sum of the squares of $n$ independent (0,1)-normal distributions. Each summand has positive expected value, so the chi-squared distribution will have larger and larger mean as $n$ increases. In addition, the standard deviation also increases, and the critical values do as well.
Specifically, for large $n$ the mean of the chi-squared distribution is approximately $n$ and the standard deviation is approximately $\sqrt{2n}$.
|
$\chi^2$ tabulated value
|
The chi-squared distribution with $n$ degrees of freedom is the sum of the squares of $n$ independent (0,1)-normal distributions. Each summand has positive expected value, so the chi-squared distribut
|
$\chi^2$ tabulated value
The chi-squared distribution with $n$ degrees of freedom is the sum of the squares of $n$ independent (0,1)-normal distributions. Each summand has positive expected value, so the chi-squared distribution will have larger and larger mean as $n$ increases. In addition, the standard deviation also increases, and the critical values do as well.
Specifically, for large $n$ the mean of the chi-squared distribution is approximately $n$ and the standard deviation is approximately $\sqrt{2n}$.
|
$\chi^2$ tabulated value
The chi-squared distribution with $n$ degrees of freedom is the sum of the squares of $n$ independent (0,1)-normal distributions. Each summand has positive expected value, so the chi-squared distribut
|
40,345
|
$\chi^2$ tabulated value
|
I guess the best way of understanding is looking at density plot for different degrees of freedom.
If you run the R code below,
x = seq(0, 25, length.out=100)
plot(x, dchisq(x=x, df=2), type='l', col=2, ylab='density')
for(i in 3:9){
y = dchisq(x=x, df=i)
lines(x, y, col=i)
}
legend('topright', legend=paste('df = ', 2:9), col=2:9, fill=2:9)
you will get this nice plot:
It is clear that with increasing degree of freedom, the tails of the distribution get thicker and thicker. That shows that the $P(X<x)=a$ happens in larger value of $x$.
|
$\chi^2$ tabulated value
|
I guess the best way of understanding is looking at density plot for different degrees of freedom.
If you run the R code below,
x = seq(0, 25, length.out=100)
plot(x, dchisq(x=x, df=2), type='l', col
|
$\chi^2$ tabulated value
I guess the best way of understanding is looking at density plot for different degrees of freedom.
If you run the R code below,
x = seq(0, 25, length.out=100)
plot(x, dchisq(x=x, df=2), type='l', col=2, ylab='density')
for(i in 3:9){
y = dchisq(x=x, df=i)
lines(x, y, col=i)
}
legend('topright', legend=paste('df = ', 2:9), col=2:9, fill=2:9)
you will get this nice plot:
It is clear that with increasing degree of freedom, the tails of the distribution get thicker and thicker. That shows that the $P(X<x)=a$ happens in larger value of $x$.
|
$\chi^2$ tabulated value
I guess the best way of understanding is looking at density plot for different degrees of freedom.
If you run the R code below,
x = seq(0, 25, length.out=100)
plot(x, dchisq(x=x, df=2), type='l', col
|
40,346
|
How to interpret a two-dimensional contingency table?
|
In general, there isn't much to a 2-way contingency table, but you are trying to unpack this at such a level of detail that some confusions are arising. Typically, with a simple contingency table like this, people just want to know if the variables (sex and citizen) are independent. To assess that, you can run a chi-squared test:
chisq.test(tab.sex.citizen)
# Pearson's Chi-squared test with Yates' continuity correction
#
# data: tab.sex.citizen
# X-squared = 2.389, df = 1, p-value = 0.1222
You can perform a likelihood ratio version of this test (the chi-squared test above is a score test), by performing a nested model test of the Poisson GLM you ran against the full (saturated) model:
phd.mod.indep <- glm(Freq ~ sex + citizen, family=poisson, data=AMS2)
phd.mod.sat <- glm(Freq ~ sex * citizen, family=poisson, data=AMS2)
anova(phd.mod.indep, phd.mod.sat, test="LRT")
# Analysis of Deviance Table
#
# Model 1: Freq ~ sex + citizen
# Model 2: Freq ~ sex * citizen
# Resid. Df Resid. Dev Df Deviance Pr(>Chi)
# 1 1 2.5721
# 2 0 0.0000 1 2.5721 0.1088
deviance(phd.mod.indep) # [1] 2.572123
deviance(phd.mod.sat) # [1] 3.308465e-14
1-pchisq(deviance(phd.mod.indep)-deviance(phd.mod.sat), df=1) # [1] 0.1087617
You can also get the Wald test of the interaction term (which is the test of independence):
summary(phd.mod.sat)
# ...
# Coefficients:
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) 5.56068 0.06202 89.663 < 2e-16 ***
# sexMale 0.65592 0.07643 8.582 < 2e-16 ***
# citizenUS -0.25241 0.09379 -2.691 0.00712 **
# sexMale:citizenUS 0.18214 0.11373 1.602 0.10926
# ...
# Null deviance: 1.9148e+02 on 3 degrees of freedom
# Residual deviance: 3.3085e-14 on 0 degrees of freedom
# AIC: 38.586
# ...
(To read about score vs Wald vs likelihood ratio tests, see my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR?)
Note however, that the way you conducted your test of phd.mod.indep is incorrect (see here: Test GLM model using null and model deviances). The test of that model against the null model is the test of whether all cells have the same probability in the population. It would be implemented as follows:
1-pchisq(191.5-2.57, df=3-1) # [1] 0
Setting aside the test of whether all cell probabilities are equal (which I doubt is of much interest to you), if you believed that there was an association between sex and citizen, you would not interpret the model phd.mod.indep. That would be a misspecified model.
|
How to interpret a two-dimensional contingency table?
|
In general, there isn't much to a 2-way contingency table, but you are trying to unpack this at such a level of detail that some confusions are arising. Typically, with a simple contingency table lik
|
How to interpret a two-dimensional contingency table?
In general, there isn't much to a 2-way contingency table, but you are trying to unpack this at such a level of detail that some confusions are arising. Typically, with a simple contingency table like this, people just want to know if the variables (sex and citizen) are independent. To assess that, you can run a chi-squared test:
chisq.test(tab.sex.citizen)
# Pearson's Chi-squared test with Yates' continuity correction
#
# data: tab.sex.citizen
# X-squared = 2.389, df = 1, p-value = 0.1222
You can perform a likelihood ratio version of this test (the chi-squared test above is a score test), by performing a nested model test of the Poisson GLM you ran against the full (saturated) model:
phd.mod.indep <- glm(Freq ~ sex + citizen, family=poisson, data=AMS2)
phd.mod.sat <- glm(Freq ~ sex * citizen, family=poisson, data=AMS2)
anova(phd.mod.indep, phd.mod.sat, test="LRT")
# Analysis of Deviance Table
#
# Model 1: Freq ~ sex + citizen
# Model 2: Freq ~ sex * citizen
# Resid. Df Resid. Dev Df Deviance Pr(>Chi)
# 1 1 2.5721
# 2 0 0.0000 1 2.5721 0.1088
deviance(phd.mod.indep) # [1] 2.572123
deviance(phd.mod.sat) # [1] 3.308465e-14
1-pchisq(deviance(phd.mod.indep)-deviance(phd.mod.sat), df=1) # [1] 0.1087617
You can also get the Wald test of the interaction term (which is the test of independence):
summary(phd.mod.sat)
# ...
# Coefficients:
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) 5.56068 0.06202 89.663 < 2e-16 ***
# sexMale 0.65592 0.07643 8.582 < 2e-16 ***
# citizenUS -0.25241 0.09379 -2.691 0.00712 **
# sexMale:citizenUS 0.18214 0.11373 1.602 0.10926
# ...
# Null deviance: 1.9148e+02 on 3 degrees of freedom
# Residual deviance: 3.3085e-14 on 0 degrees of freedom
# AIC: 38.586
# ...
(To read about score vs Wald vs likelihood ratio tests, see my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR?)
Note however, that the way you conducted your test of phd.mod.indep is incorrect (see here: Test GLM model using null and model deviances). The test of that model against the null model is the test of whether all cells have the same probability in the population. It would be implemented as follows:
1-pchisq(191.5-2.57, df=3-1) # [1] 0
Setting aside the test of whether all cell probabilities are equal (which I doubt is of much interest to you), if you believed that there was an association between sex and citizen, you would not interpret the model phd.mod.indep. That would be a misspecified model.
|
How to interpret a two-dimensional contingency table?
In general, there isn't much to a 2-way contingency table, but you are trying to unpack this at such a level of detail that some confusions are arising. Typically, with a simple contingency table lik
|
40,347
|
How to interpret a two-dimensional contingency table?
|
In addition to @gung's answer, I discovered that mosaic plots are very useful in assessing the relative relationships with categorical data. Once we establish (actually, we assume here) departure from independence, one can use package vcd to graphically display such contingency tables.
A mosaic plot:
mosaic(tab.sex.citizen, shade=TRUE, legend=TRUE)
An association plot:
assoc(tab.sex.citizen, shade=TRUE, legend=TRUE)
From the second plot, it's clear that the proportion of women is bigger for non-citizens than for US citizens. Equivalently, the proportion of non-citizens is bigger for females than for males.
The graphs are clearer when the departure from independence is clear-cut, so here's an example on the Titanic data (see this tutorial).
data(Titanic)
sex.survived <- margin.table(Titanic, c(2,4))
ftable(sex.survived)
Yielding:
> ftable(sex.survived)
Survived No Yes
Sex
Male 1364 367
Female 126 344
Then the plots:
mosaic(sex.survived, shade=TRUE, legend=TRUE)
assoc(sex.survived, shade=TRUE, legend=TRUE)
From the Pearson residuals (a measure of the departure of the Observed Frequencies from the Expected Frequencies, or the bits in the data not explained by the loglinear model), it's clear that for males there is a disproportionately high number that haven't survived and a disproportionately low number that have survived. Equivalently, out of those that survived the number of females is unexpectedly high.
|
How to interpret a two-dimensional contingency table?
|
In addition to @gung's answer, I discovered that mosaic plots are very useful in assessing the relative relationships with categorical data. Once we establish (actually, we assume here) departure from
|
How to interpret a two-dimensional contingency table?
In addition to @gung's answer, I discovered that mosaic plots are very useful in assessing the relative relationships with categorical data. Once we establish (actually, we assume here) departure from independence, one can use package vcd to graphically display such contingency tables.
A mosaic plot:
mosaic(tab.sex.citizen, shade=TRUE, legend=TRUE)
An association plot:
assoc(tab.sex.citizen, shade=TRUE, legend=TRUE)
From the second plot, it's clear that the proportion of women is bigger for non-citizens than for US citizens. Equivalently, the proportion of non-citizens is bigger for females than for males.
The graphs are clearer when the departure from independence is clear-cut, so here's an example on the Titanic data (see this tutorial).
data(Titanic)
sex.survived <- margin.table(Titanic, c(2,4))
ftable(sex.survived)
Yielding:
> ftable(sex.survived)
Survived No Yes
Sex
Male 1364 367
Female 126 344
Then the plots:
mosaic(sex.survived, shade=TRUE, legend=TRUE)
assoc(sex.survived, shade=TRUE, legend=TRUE)
From the Pearson residuals (a measure of the departure of the Observed Frequencies from the Expected Frequencies, or the bits in the data not explained by the loglinear model), it's clear that for males there is a disproportionately high number that haven't survived and a disproportionately low number that have survived. Equivalently, out of those that survived the number of females is unexpectedly high.
|
How to interpret a two-dimensional contingency table?
In addition to @gung's answer, I discovered that mosaic plots are very useful in assessing the relative relationships with categorical data. Once we establish (actually, we assume here) departure from
|
40,348
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
|
There are many possibilities. One possibility is to take a pair of families to cover positive and negative excess kurtosis, and when matching the first four moments the obvious candidates are Pearson-family distributions.
The family of scaled t-distributions have parameters ($\sigma$ and $\nu$) that affect the variance and kurtosis. They can only have kurtosis above that of the normal, though.
That will have excess kurtosis $\frac{6}{\nu-4}$ (so if you want that to only go as high as 3, you'll want $\nu\geq 6$).
It has variance $\sigma^2 \frac{\nu}{\nu-2}$, so given $\nu$ you can choose $\sigma$ to yield the desired variance
The family of scaled shifted (to mean 0) beta distributions then would take care of the case where kurtosis was smaller than for the normal (both families include the normal as a limiting case). So take a $\text{Beta}(\alpha,\alpha)$ and shift it down by $\frac{1}{2}$ and then scale to the desired variance.
That is a $\text{Beta}(\alpha,\alpha)$ has excess kurtosis $-\frac{6}{ (2\alpha + 3)}$, and includes your desired uniform at $\alpha=1$.
Before scaling it has variance $\frac{1}{4(2\alpha+1)}$; the ratio of the desired variance to that unscaled variance will be the square of the required scale.
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
|
There are many possibilities. One possibility is to take a pair of families to cover positive and negative excess kurtosis, and when matching the first four moments the obvious candidates are Pearson-
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
There are many possibilities. One possibility is to take a pair of families to cover positive and negative excess kurtosis, and when matching the first four moments the obvious candidates are Pearson-family distributions.
The family of scaled t-distributions have parameters ($\sigma$ and $\nu$) that affect the variance and kurtosis. They can only have kurtosis above that of the normal, though.
That will have excess kurtosis $\frac{6}{\nu-4}$ (so if you want that to only go as high as 3, you'll want $\nu\geq 6$).
It has variance $\sigma^2 \frac{\nu}{\nu-2}$, so given $\nu$ you can choose $\sigma$ to yield the desired variance
The family of scaled shifted (to mean 0) beta distributions then would take care of the case where kurtosis was smaller than for the normal (both families include the normal as a limiting case). So take a $\text{Beta}(\alpha,\alpha)$ and shift it down by $\frac{1}{2}$ and then scale to the desired variance.
That is a $\text{Beta}(\alpha,\alpha)$ has excess kurtosis $-\frac{6}{ (2\alpha + 3)}$, and includes your desired uniform at $\alpha=1$.
Before scaling it has variance $\frac{1}{4(2\alpha+1)}$; the ratio of the desired variance to that unscaled variance will be the square of the required scale.
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
There are many possibilities. One possibility is to take a pair of families to cover positive and negative excess kurtosis, and when matching the first four moments the obvious candidates are Pearson-
|
40,349
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
|
Have a look at heavy tail Lambert W x F distributions (disclaimer: I am the author).
The random variable $Y \sim Lambert W \times F$ is a heavy-tail version of $X\sim F$, where you control the tails with tail parameter $\delta \geq 0$: for $\delta = 0$, $X = Y$ and thus Lambert W x F is the same as F; and for $\delta \rightarrow \infty$ you get more and more heavy tails in $Y$ (Tukey's h is a special case of Lambert W x F random variables for F = Gaussian and $\alpha = 1$).
Note that this works for any (non pathological) continuous distribution -- not just the Normal distribution.
For your particular request of mean = 0, symmetric, and variable variance and kurtosis you can set $\mu = 0$, $\delta_{\ell} = \delta_r = \delta$ (by default), and vary scale $\sigma$ and tail parameter $\delta$.
In R this is implemented in the LambertW package (use type = "h" and distname = "normal").
See also (my) related replies here:
Transformation to increase kurtosis and skewness of normal r.v: this shows some illustrations of how the densities vary when varying $\delta$.
What's the distribution of these data?: an application example of how to use this to estimate model parameters and Gaussianize your data.
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
|
Have a look at heavy tail Lambert W x F distributions (disclaimer: I am the author).
The random variable $Y \sim Lambert W \times F$ is a heavy-tail version of $X\sim F$, where you control the tails w
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
Have a look at heavy tail Lambert W x F distributions (disclaimer: I am the author).
The random variable $Y \sim Lambert W \times F$ is a heavy-tail version of $X\sim F$, where you control the tails with tail parameter $\delta \geq 0$: for $\delta = 0$, $X = Y$ and thus Lambert W x F is the same as F; and for $\delta \rightarrow \infty$ you get more and more heavy tails in $Y$ (Tukey's h is a special case of Lambert W x F random variables for F = Gaussian and $\alpha = 1$).
Note that this works for any (non pathological) continuous distribution -- not just the Normal distribution.
For your particular request of mean = 0, symmetric, and variable variance and kurtosis you can set $\mu = 0$, $\delta_{\ell} = \delta_r = \delta$ (by default), and vary scale $\sigma$ and tail parameter $\delta$.
In R this is implemented in the LambertW package (use type = "h" and distname = "normal").
See also (my) related replies here:
Transformation to increase kurtosis and skewness of normal r.v: this shows some illustrations of how the densities vary when varying $\delta$.
What's the distribution of these data?: an application example of how to use this to estimate model parameters and Gaussianize your data.
|
Looking for a distribution where: Mean=0, variance is variable, Skew=0 and kurtosis is variable
Have a look at heavy tail Lambert W x F distributions (disclaimer: I am the author).
The random variable $Y \sim Lambert W \times F$ is a heavy-tail version of $X\sim F$, where you control the tails w
|
40,350
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
|
An autoencoder attempts to reconstruct the input. During the process it could learn the identity function if the size of the hidden layers is greater than the number of inputs. However that is not desirable.
During learning, the autoencoder discovers the most common features in the input. For example if the input is a natural image, it discovers an edge because it is the most common feature in all natural images.
In the simplest case, the autoencoder is constructed with fewer hidden units than its input layer. As hidden units are added, it can enlist more features to represent the input. However, as the number of hidden units exceeds the number of input units, the features becomes more and more dependent. The autoencoder can discover those features when the hidden layers are densely activated.
Sparsity restricts the activation of the hidden units, which reduces the dependency between features. This allows us to increase the number of features, which is desirable.
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
|
An autoencoder attempts to reconstruct the input. During the process it could learn the identity function if the size of the hidden layers is greater than the number of inputs. However that is not des
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
An autoencoder attempts to reconstruct the input. During the process it could learn the identity function if the size of the hidden layers is greater than the number of inputs. However that is not desirable.
During learning, the autoencoder discovers the most common features in the input. For example if the input is a natural image, it discovers an edge because it is the most common feature in all natural images.
In the simplest case, the autoencoder is constructed with fewer hidden units than its input layer. As hidden units are added, it can enlist more features to represent the input. However, as the number of hidden units exceeds the number of input units, the features becomes more and more dependent. The autoencoder can discover those features when the hidden layers are densely activated.
Sparsity restricts the activation of the hidden units, which reduces the dependency between features. This allows us to increase the number of features, which is desirable.
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
An autoencoder attempts to reconstruct the input. During the process it could learn the identity function if the size of the hidden layers is greater than the number of inputs. However that is not des
|
40,351
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
|
Autoencoder is a NN-versioned POD
Sparsity results from the assumption "the law behind complexity is simple". And your job is to try to find the most simple one by changing your weights.
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
|
Autoencoder is a NN-versioned POD
Sparsity results from the assumption "the law behind complexity is simple". And your job is to try to find the most simple one by changing your weights.
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
Autoencoder is a NN-versioned POD
Sparsity results from the assumption "the law behind complexity is simple". And your job is to try to find the most simple one by changing your weights.
|
What is the intuition behind the sparsity parameter in sparse autoencoders?
Autoencoder is a NN-versioned POD
Sparsity results from the assumption "the law behind complexity is simple". And your job is to try to find the most simple one by changing your weights.
|
40,352
|
cv.glmnet - choose lambda to include specific number of variables
|
I don't think that your colleague had anything fancy in mind -- fit a glmnet model with cross-validation as you ordinarily would and then examine how many nonzero features you have at each value of $\lambda$. When you have 5 (or however many) nonzero features, that's the value of $\lambda$ to choose.
glmnet even keeps track of this automatically for you. If lassoFit is your cv.glmnet object, then lassoFit$nzero counts the number of nonzero entries at each value of lambda in the sequence. They occur in the order of the lambda sequence.
|
cv.glmnet - choose lambda to include specific number of variables
|
I don't think that your colleague had anything fancy in mind -- fit a glmnet model with cross-validation as you ordinarily would and then examine how many nonzero features you have at each value of $\
|
cv.glmnet - choose lambda to include specific number of variables
I don't think that your colleague had anything fancy in mind -- fit a glmnet model with cross-validation as you ordinarily would and then examine how many nonzero features you have at each value of $\lambda$. When you have 5 (or however many) nonzero features, that's the value of $\lambda$ to choose.
glmnet even keeps track of this automatically for you. If lassoFit is your cv.glmnet object, then lassoFit$nzero counts the number of nonzero entries at each value of lambda in the sequence. They occur in the order of the lambda sequence.
|
cv.glmnet - choose lambda to include specific number of variables
I don't think that your colleague had anything fancy in mind -- fit a glmnet model with cross-validation as you ordinarily would and then examine how many nonzero features you have at each value of $\
|
40,353
|
Word2Vec : Interpretation of Subtraction or addition of vectors
|
Yes, that's my understanding of their interpretation; that's the reasoning behind why you'd expect (as observed) that [man] - [woman] + [king] ≈ [queen], or [Paris] - [France] + [China] ≈ [Beijing].
The idea is perhaps that vectors are approximately sums of their semantic components, so that [king] includes a "male" component as well as "ruler", "person", and whatever else, and [queen] has basically the same set of components except it has "female" instead of "male". [man] - [woman] would then end up at ["male"] - ["female"], so adding it to [king] would just swap the "male" concept for "female".
I kind of doubt there's a more complete understanding of it than that, though I'm not familiar with all of the literature on the subject and someone may have studied it in more detail.
|
Word2Vec : Interpretation of Subtraction or addition of vectors
|
Yes, that's my understanding of their interpretation; that's the reasoning behind why you'd expect (as observed) that [man] - [woman] + [king] ≈ [queen], or [Paris] - [France] + [China] ≈ [Beijing].
T
|
Word2Vec : Interpretation of Subtraction or addition of vectors
Yes, that's my understanding of their interpretation; that's the reasoning behind why you'd expect (as observed) that [man] - [woman] + [king] ≈ [queen], or [Paris] - [France] + [China] ≈ [Beijing].
The idea is perhaps that vectors are approximately sums of their semantic components, so that [king] includes a "male" component as well as "ruler", "person", and whatever else, and [queen] has basically the same set of components except it has "female" instead of "male". [man] - [woman] would then end up at ["male"] - ["female"], so adding it to [king] would just swap the "male" concept for "female".
I kind of doubt there's a more complete understanding of it than that, though I'm not familiar with all of the literature on the subject and someone may have studied it in more detail.
|
Word2Vec : Interpretation of Subtraction or addition of vectors
Yes, that's my understanding of their interpretation; that's the reasoning behind why you'd expect (as observed) that [man] - [woman] + [king] ≈ [queen], or [Paris] - [France] + [China] ≈ [Beijing].
T
|
40,354
|
Word2Vec : Interpretation of Subtraction or addition of vectors
|
Actually there has been some recent theoretical advances in understanding how the addition/subtraction of vectors works. See here:
http://andyljones.tumblr.com/post/111299309808/why-word2vec-works
http://arxiv.org/abs/1502.03520
I would give a summary here - but I don't think I could do any better than Andy in his blog!
|
Word2Vec : Interpretation of Subtraction or addition of vectors
|
Actually there has been some recent theoretical advances in understanding how the addition/subtraction of vectors works. See here:
http://andyljones.tumblr.com/post/111299309808/why-word2vec-works
ht
|
Word2Vec : Interpretation of Subtraction or addition of vectors
Actually there has been some recent theoretical advances in understanding how the addition/subtraction of vectors works. See here:
http://andyljones.tumblr.com/post/111299309808/why-word2vec-works
http://arxiv.org/abs/1502.03520
I would give a summary here - but I don't think I could do any better than Andy in his blog!
|
Word2Vec : Interpretation of Subtraction or addition of vectors
Actually there has been some recent theoretical advances in understanding how the addition/subtraction of vectors works. See here:
http://andyljones.tumblr.com/post/111299309808/why-word2vec-works
ht
|
40,355
|
If $\operatorname{Var}\left(\epsilon_i\right) = h\left(X\right) \neq \sigma^2$, what can we know about $\operatorname{Var}\left(\hat{\beta}\right)$?
|
It's an easy derivation to show that the least squares estimator:
$$
\hat{\beta} = \left( \mathbf{X}^T\mathbf{X} \right)^{-1} \mathbf{X}^T Y
$$
has variance:
$$
\mbox{var} \left(\hat{\beta} \right)= \left( \mathbf{X}^T\mathbf{X} \right)^{-1} \mathbf{X}^T \mbox{var} \left(Y\right)\mathbf{X} \left( \mathbf{X}^T\mathbf{X} \right)^{-1}
$$
If $h(X)$ is known then the inverse variance weighted least squares estimator: $(X^T W X)^{-1} X^T W Y$ is unbiased and efficient where $W = diag(h(X)^{-1})$.
The variance of the WLS estimator becomes:
$$ \mbox{var} (\hat{\beta}_{wls}) = (X^T W X)^{-1}$$
It's easy to show that if the mean model is correctly specified the unweighted version of OLS is NOT BIASED. It's NOT BIASED. It's NOT BIASED. -- that always bears repeating as many people don't understand: weighting here only gives you better efficiency.
How much better?
The relative efficiency of the two estimators is not to hard to work out, but WLS is uniformly better. Seber and Lee would have more details if you're interested.
|
If $\operatorname{Var}\left(\epsilon_i\right) = h\left(X\right) \neq \sigma^2$, what can we know abo
|
It's an easy derivation to show that the least squares estimator:
$$
\hat{\beta} = \left( \mathbf{X}^T\mathbf{X} \right)^{-1} \mathbf{X}^T Y
$$
has variance:
$$
\mbox{var} \left(\hat{\beta} \right)=
|
If $\operatorname{Var}\left(\epsilon_i\right) = h\left(X\right) \neq \sigma^2$, what can we know about $\operatorname{Var}\left(\hat{\beta}\right)$?
It's an easy derivation to show that the least squares estimator:
$$
\hat{\beta} = \left( \mathbf{X}^T\mathbf{X} \right)^{-1} \mathbf{X}^T Y
$$
has variance:
$$
\mbox{var} \left(\hat{\beta} \right)= \left( \mathbf{X}^T\mathbf{X} \right)^{-1} \mathbf{X}^T \mbox{var} \left(Y\right)\mathbf{X} \left( \mathbf{X}^T\mathbf{X} \right)^{-1}
$$
If $h(X)$ is known then the inverse variance weighted least squares estimator: $(X^T W X)^{-1} X^T W Y$ is unbiased and efficient where $W = diag(h(X)^{-1})$.
The variance of the WLS estimator becomes:
$$ \mbox{var} (\hat{\beta}_{wls}) = (X^T W X)^{-1}$$
It's easy to show that if the mean model is correctly specified the unweighted version of OLS is NOT BIASED. It's NOT BIASED. It's NOT BIASED. -- that always bears repeating as many people don't understand: weighting here only gives you better efficiency.
How much better?
The relative efficiency of the two estimators is not to hard to work out, but WLS is uniformly better. Seber and Lee would have more details if you're interested.
|
If $\operatorname{Var}\left(\epsilon_i\right) = h\left(X\right) \neq \sigma^2$, what can we know abo
It's an easy derivation to show that the least squares estimator:
$$
\hat{\beta} = \left( \mathbf{X}^T\mathbf{X} \right)^{-1} \mathbf{X}^T Y
$$
has variance:
$$
\mbox{var} \left(\hat{\beta} \right)=
|
40,356
|
Encompassing Tests to compare models in R
|
If you have two competing linear models with different regressors, say:
m1 <- lm(y ~ x1 + x2, data = ...)
m2 <- lm(y ~ z1 + z2, data = ...)
then the encompassing model is
m12 <- lm(y ~ x1 + x2 + z1 + z2, data = ...)
and the encompassing test compares
anova(m1, m12)
anova(m2, m12)
The "hope" would be that one of the models (m1, m2) is significantly worse than the encompassing model m12 while the other is not. The one that is not significantly worse would be preferable then. However, it may happen that both models are significantly worse than m12 in which case neither model alone is entirely convincing.
If you want a convenience function to carry out this test in R, you can use the encomptest() function from the lmtest package:
encomptest(m1, m2)
The package also provides other tests for non-nested model comparisons, e.g., jtest() and coxtest().
|
Encompassing Tests to compare models in R
|
If you have two competing linear models with different regressors, say:
m1 <- lm(y ~ x1 + x2, data = ...)
m2 <- lm(y ~ z1 + z2, data = ...)
then the encompassing model is
m12 <- lm(y ~ x1 + x2 + z1 +
|
Encompassing Tests to compare models in R
If you have two competing linear models with different regressors, say:
m1 <- lm(y ~ x1 + x2, data = ...)
m2 <- lm(y ~ z1 + z2, data = ...)
then the encompassing model is
m12 <- lm(y ~ x1 + x2 + z1 + z2, data = ...)
and the encompassing test compares
anova(m1, m12)
anova(m2, m12)
The "hope" would be that one of the models (m1, m2) is significantly worse than the encompassing model m12 while the other is not. The one that is not significantly worse would be preferable then. However, it may happen that both models are significantly worse than m12 in which case neither model alone is entirely convincing.
If you want a convenience function to carry out this test in R, you can use the encomptest() function from the lmtest package:
encomptest(m1, m2)
The package also provides other tests for non-nested model comparisons, e.g., jtest() and coxtest().
|
Encompassing Tests to compare models in R
If you have two competing linear models with different regressors, say:
m1 <- lm(y ~ x1 + x2, data = ...)
m2 <- lm(y ~ z1 + z2, data = ...)
then the encompassing model is
m12 <- lm(y ~ x1 + x2 + z1 +
|
40,357
|
Encompassing Tests to compare models in R
|
There are different encompassing tests. I'll give you an example of forecast encompassing test from "A Companion to Economic Forecasting" edited by Michael P. Clements, David F. Hendry, see Eq (14.2) on p.302.
Let's say you have competing forecast $\hat y_{1,t+1}$ and $\hat y_{2,t+1}$, and the actual observations $y_{t+1}$. Run a regression:
$$y_{t+1}=\alpha_0+\alpha_1 \hat y_{1,t+1}+\alpha_2 \hat y_{2,t+1}+u_{t+1}$$
Under $H_0$: model 1 encompasses model 2, you have $\alpha_1=1$ and $\alpha_2=0$. This is a simple linear restriction test, that can easily be done in R or any other stat package.
Note, that you don't need to know anything about the models, their independent variables etc. All you need is their forecasts and actual observations.
|
Encompassing Tests to compare models in R
|
There are different encompassing tests. I'll give you an example of forecast encompassing test from "A Companion to Economic Forecasting" edited by Michael P. Clements, David F. Hendry, see Eq (14.2)
|
Encompassing Tests to compare models in R
There are different encompassing tests. I'll give you an example of forecast encompassing test from "A Companion to Economic Forecasting" edited by Michael P. Clements, David F. Hendry, see Eq (14.2) on p.302.
Let's say you have competing forecast $\hat y_{1,t+1}$ and $\hat y_{2,t+1}$, and the actual observations $y_{t+1}$. Run a regression:
$$y_{t+1}=\alpha_0+\alpha_1 \hat y_{1,t+1}+\alpha_2 \hat y_{2,t+1}+u_{t+1}$$
Under $H_0$: model 1 encompasses model 2, you have $\alpha_1=1$ and $\alpha_2=0$. This is a simple linear restriction test, that can easily be done in R or any other stat package.
Note, that you don't need to know anything about the models, their independent variables etc. All you need is their forecasts and actual observations.
|
Encompassing Tests to compare models in R
There are different encompassing tests. I'll give you an example of forecast encompassing test from "A Companion to Economic Forecasting" edited by Michael P. Clements, David F. Hendry, see Eq (14.2)
|
40,358
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-built estimator when software runs out of memory
|
Using QR decomposition (which ought to be available if you already have calculated the regression):
Let $X$ have $n$ rows and $p$ columns and be of full column rank.
$H=X(X'X)^{-1}X'$
$=QR(R'Q'QR)^{-1}R'Q'$
$=QR(R'R)^{-1}R'Q'$
But if $R_1$ is the first $p$ rows of $R$ then $R'R=R_1'R_1$
$=QR(R_1'R_1)^{-1}R'Q'$
Now let $Q=(Q_1,Q_2)$ where $Q_1$ is the first $p$ columns of $Q$. Then $QR=Q_1R_1$.
$=Q_1R_1R_1^{-1}(R_1')^{-1}R_1'Q_1'$
$=Q_1Q_1'$
Where $Q_1$ is $n\times p$.
So if you have the QR decomposition of $X$, then the hat matrix is fairly simple.
Note that some regression programs will give $Q_1$ automatically. [It's also possibly that a regression program will have performed pivoting. That shouldn't impact the calculation of the hat matrix though.]
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-buil
|
Using QR decomposition (which ought to be available if you already have calculated the regression):
Let $X$ have $n$ rows and $p$ columns and be of full column rank.
$H=X(X'X)^{-1}X'$
$=QR(R'Q'QR)^{-1
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-built estimator when software runs out of memory
Using QR decomposition (which ought to be available if you already have calculated the regression):
Let $X$ have $n$ rows and $p$ columns and be of full column rank.
$H=X(X'X)^{-1}X'$
$=QR(R'Q'QR)^{-1}R'Q'$
$=QR(R'R)^{-1}R'Q'$
But if $R_1$ is the first $p$ rows of $R$ then $R'R=R_1'R_1$
$=QR(R_1'R_1)^{-1}R'Q'$
Now let $Q=(Q_1,Q_2)$ where $Q_1$ is the first $p$ columns of $Q$. Then $QR=Q_1R_1$.
$=Q_1R_1R_1^{-1}(R_1')^{-1}R_1'Q_1'$
$=Q_1Q_1'$
Where $Q_1$ is $n\times p$.
So if you have the QR decomposition of $X$, then the hat matrix is fairly simple.
Note that some regression programs will give $Q_1$ automatically. [It's also possibly that a regression program will have performed pivoting. That shouldn't impact the calculation of the hat matrix though.]
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-buil
Using QR decomposition (which ought to be available if you already have calculated the regression):
Let $X$ have $n$ rows and $p$ columns and be of full column rank.
$H=X(X'X)^{-1}X'$
$=QR(R'Q'QR)^{-1
|
40,359
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-built estimator when software runs out of memory
|
Try using the SVD. E.g., since
$$
X = U\Sigma V^T,
$$
then
$$
(X^T X)^{-1} = (V\Sigma^2 V^T)^{-1} = V\Sigma^{-2} V^T,
$$
and thus
$$
X(X^T X)^{-1}X^T = U I_r U^T = U_r U_r^T,
$$
where $I_r$ is an $n\times n$ identity matrix with $r\leq n$ ones on the diagonal (upper part), and $n-r$ zeros on the lower diagonal, where $r$ is the rank of $X$.
This will likely speed up your computation.
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-buil
|
Try using the SVD. E.g., since
$$
X = U\Sigma V^T,
$$
then
$$
(X^T X)^{-1} = (V\Sigma^2 V^T)^{-1} = V\Sigma^{-2} V^T,
$$
and thus
$$
X(X^T X)^{-1}X^T = U I_r U^T = U_r U_r^T,
$$
where $I_r
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-built estimator when software runs out of memory
Try using the SVD. E.g., since
$$
X = U\Sigma V^T,
$$
then
$$
(X^T X)^{-1} = (V\Sigma^2 V^T)^{-1} = V\Sigma^{-2} V^T,
$$
and thus
$$
X(X^T X)^{-1}X^T = U I_r U^T = U_r U_r^T,
$$
where $I_r$ is an $n\times n$ identity matrix with $r\leq n$ ones on the diagonal (upper part), and $n-r$ zeros on the lower diagonal, where $r$ is the rank of $X$.
This will likely speed up your computation.
|
Speeding up hat matrices like $X(X'X)^{-1}X'$ (projection matrices) and other aspects of custom-buil
Try using the SVD. E.g., since
$$
X = U\Sigma V^T,
$$
then
$$
(X^T X)^{-1} = (V\Sigma^2 V^T)^{-1} = V\Sigma^{-2} V^T,
$$
and thus
$$
X(X^T X)^{-1}X^T = U I_r U^T = U_r U_r^T,
$$
where $I_r
|
40,360
|
Regression trees to model rates
|
One way would be to adopt a formal model-based tree. The glmtree() function in the partykit package implements the general MOB algorithm for model-based recursive partitioning (Zeileis et al. 2008, Journal of Computational and Graphical Statistics, 17(2), 492-514). This supports Poisson responses and also allows for the inclusion of offsets. Furthermore, additional regressors could be included in each of the terminal nodes.
Consider the following simple artificial example:
set.seed(1)
d <- data.frame(
x1 = runif(500),
x2 = runif(500),
exposure = runif(500, 1, 10)
)
d$claims <- rpois(500, lambda = exp(d$x1 > 0.5 & d$x2 > 0.5) * d$exposure)
This uses two simple partitioning variables (x1 and x2) and an exposure variable. The response is Poisson-distributed with offset log(exposure) and mean 1 = exp(0) except for the case when both x1 > 0.5 & x2 > 0.5 where the mean is exp(1)
Then glmtree() can fit a Poisson GLM-based tree for claims with offset(log(exposure)) and partitioning variables x1 + x2.
m <- glmtree(claims ~ offset(log(exposure)) | x1 + x2,
data = d, family = poisson)
plot(as.constparty(m))
This captures the true tree structure (which is admittedly easy to find here) and correctly estimates the intercepts (with the default log-link):
coef(m)
## 2 4 5
## -0.047934373 -0.005690107 1.050569309
You can also obtain more detailed information about each fitted GLM in the nodes of the tree, e.g., for the last node:
summary(m, node = 5)
## Call:
## glm(formula = claims ~ offset(log(exposure)))
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -3.13527 -0.66977 -0.04251 0.56984 2.13581
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 1.05057 0.02375 44.24 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for poisson family taken to be 1)
##
## Null deviance: 630.95 on 120 degrees of freedom
## Residual deviance: 113.36 on 120 degrees of freedom
## AIC: 635.89
##
## Number of Fisher Scoring iterations: 4
More details and references are provided in vignette("mob", package = "partykit").
|
Regression trees to model rates
|
One way would be to adopt a formal model-based tree. The glmtree() function in the partykit package implements the general MOB algorithm for model-based recursive partitioning (Zeileis et al. 2008, Jo
|
Regression trees to model rates
One way would be to adopt a formal model-based tree. The glmtree() function in the partykit package implements the general MOB algorithm for model-based recursive partitioning (Zeileis et al. 2008, Journal of Computational and Graphical Statistics, 17(2), 492-514). This supports Poisson responses and also allows for the inclusion of offsets. Furthermore, additional regressors could be included in each of the terminal nodes.
Consider the following simple artificial example:
set.seed(1)
d <- data.frame(
x1 = runif(500),
x2 = runif(500),
exposure = runif(500, 1, 10)
)
d$claims <- rpois(500, lambda = exp(d$x1 > 0.5 & d$x2 > 0.5) * d$exposure)
This uses two simple partitioning variables (x1 and x2) and an exposure variable. The response is Poisson-distributed with offset log(exposure) and mean 1 = exp(0) except for the case when both x1 > 0.5 & x2 > 0.5 where the mean is exp(1)
Then glmtree() can fit a Poisson GLM-based tree for claims with offset(log(exposure)) and partitioning variables x1 + x2.
m <- glmtree(claims ~ offset(log(exposure)) | x1 + x2,
data = d, family = poisson)
plot(as.constparty(m))
This captures the true tree structure (which is admittedly easy to find here) and correctly estimates the intercepts (with the default log-link):
coef(m)
## 2 4 5
## -0.047934373 -0.005690107 1.050569309
You can also obtain more detailed information about each fitted GLM in the nodes of the tree, e.g., for the last node:
summary(m, node = 5)
## Call:
## glm(formula = claims ~ offset(log(exposure)))
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -3.13527 -0.66977 -0.04251 0.56984 2.13581
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 1.05057 0.02375 44.24 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for poisson family taken to be 1)
##
## Null deviance: 630.95 on 120 degrees of freedom
## Residual deviance: 113.36 on 120 degrees of freedom
## AIC: 635.89
##
## Number of Fisher Scoring iterations: 4
More details and references are provided in vignette("mob", package = "partykit").
|
Regression trees to model rates
One way would be to adopt a formal model-based tree. The glmtree() function in the partykit package implements the general MOB algorithm for model-based recursive partitioning (Zeileis et al. 2008, Jo
|
40,361
|
can someone fix this cognitive dissonance I have about marginals?
|
This is one of the first results I give in my Bayesian Analysis class. You are confused by notations: using the same symbol $p$ all over is a reason for this confusion and hence let me introduce $\pi(\cdot)$ for the prior, $p_1(x_1|\theta)$ for the density of $X_1$, $p_{2|1}(x_2|\theta,x_1)$ for the conditional density of $X_2$ given $X_1=x_1$, and $p_{12}(x_1,x_2|\theta)$ for the joint density of $(X_1,X_2)$.
In a sequential update of the information on $\theta$,$$\pi(\theta|x_1)= \frac{\pi(\theta)p_1(x_1 | \theta)}{m_1(x_1)}$$and the second update on $\theta$ is\begin{align*}\pi_{x_1}(\theta|x_2) &= \frac{\pi(\theta|x_1)p_{21}(x_2|\theta,x_1)}{m_{2|1}(x_2|x_1)} \\ &=\frac{\pi(\theta)p_1(x_1 | \theta)}{m_1(x_1)}\frac{p_{2|1}(x_2|\theta,x_1)}{m_{2|1}(x_2|x_1)}\\ &= \frac{\pi(\theta)p_1(x_1 | \theta)}{m_1(x_1)}\frac{p_{2|1}(x_2|\theta,x_1)}{\int \frac{\pi(\theta)p_1(x_1|\theta)}{m_1(x_1)}p_{2|1}(x_2|\theta,x_1)\text{d}\theta} \\&= \frac{\pi(\theta)p_1(x_1 | \theta)p_{2|1}(x_2|\theta,x_1)}{\int \pi(\theta)p_1(x_1|\theta) p_{2|1}(x_2|\theta,x_1)\text{d}\theta}\end{align*}
In a joint update, the posterior of $\theta$ is
$$\pi(\theta|x_1,x_2)=\frac{\pi(\theta)p_{12}(x_1,x_2|\theta)}{\int \pi(\theta)p_{12}(x_1,x_2|\theta)\text{d}\theta}=\frac{\pi(\theta)p_1(x_1 | \theta)p_{2|1}(x_2|\theta,x_1)}{\int \pi(\theta)p_1(x_1|\theta) p_{2|1}(x_2|\theta,x_1)\text{d}\theta}$$
Therefore both expressions are the same with no assumption on the dependence between both variables. The side result is that
$$m_1(x_1)\times m_{2|1}(x_2|x_1)=m_{12}(x_1,x_2)$$
|
can someone fix this cognitive dissonance I have about marginals?
|
This is one of the first results I give in my Bayesian Analysis class. You are confused by notations: using the same symbol $p$ all over is a reason for this confusion and hence let me introduce $\pi(
|
can someone fix this cognitive dissonance I have about marginals?
This is one of the first results I give in my Bayesian Analysis class. You are confused by notations: using the same symbol $p$ all over is a reason for this confusion and hence let me introduce $\pi(\cdot)$ for the prior, $p_1(x_1|\theta)$ for the density of $X_1$, $p_{2|1}(x_2|\theta,x_1)$ for the conditional density of $X_2$ given $X_1=x_1$, and $p_{12}(x_1,x_2|\theta)$ for the joint density of $(X_1,X_2)$.
In a sequential update of the information on $\theta$,$$\pi(\theta|x_1)= \frac{\pi(\theta)p_1(x_1 | \theta)}{m_1(x_1)}$$and the second update on $\theta$ is\begin{align*}\pi_{x_1}(\theta|x_2) &= \frac{\pi(\theta|x_1)p_{21}(x_2|\theta,x_1)}{m_{2|1}(x_2|x_1)} \\ &=\frac{\pi(\theta)p_1(x_1 | \theta)}{m_1(x_1)}\frac{p_{2|1}(x_2|\theta,x_1)}{m_{2|1}(x_2|x_1)}\\ &= \frac{\pi(\theta)p_1(x_1 | \theta)}{m_1(x_1)}\frac{p_{2|1}(x_2|\theta,x_1)}{\int \frac{\pi(\theta)p_1(x_1|\theta)}{m_1(x_1)}p_{2|1}(x_2|\theta,x_1)\text{d}\theta} \\&= \frac{\pi(\theta)p_1(x_1 | \theta)p_{2|1}(x_2|\theta,x_1)}{\int \pi(\theta)p_1(x_1|\theta) p_{2|1}(x_2|\theta,x_1)\text{d}\theta}\end{align*}
In a joint update, the posterior of $\theta$ is
$$\pi(\theta|x_1,x_2)=\frac{\pi(\theta)p_{12}(x_1,x_2|\theta)}{\int \pi(\theta)p_{12}(x_1,x_2|\theta)\text{d}\theta}=\frac{\pi(\theta)p_1(x_1 | \theta)p_{2|1}(x_2|\theta,x_1)}{\int \pi(\theta)p_1(x_1|\theta) p_{2|1}(x_2|\theta,x_1)\text{d}\theta}$$
Therefore both expressions are the same with no assumption on the dependence between both variables. The side result is that
$$m_1(x_1)\times m_{2|1}(x_2|x_1)=m_{12}(x_1,x_2)$$
|
can someone fix this cognitive dissonance I have about marginals?
This is one of the first results I give in my Bayesian Analysis class. You are confused by notations: using the same symbol $p$ all over is a reason for this confusion and hence let me introduce $\pi(
|
40,362
|
Why is this random variable both continuous and discrete?
|
It's wrong because - as the answer explained - there are discrete atoms at 0 and 2.
By that cdf, you can wait exactly 0 time with positive probability (similarly with 2). Because of that, the waiting time is mixed, not continuous.
Presumably you've been given definitions of all three. How are continuous r.v.s defined?
If it's not immediately clear from the formula, it often helps to draw the cdf:
|
Why is this random variable both continuous and discrete?
|
It's wrong because - as the answer explained - there are discrete atoms at 0 and 2.
By that cdf, you can wait exactly 0 time with positive probability (similarly with 2). Because of that, the waiting
|
Why is this random variable both continuous and discrete?
It's wrong because - as the answer explained - there are discrete atoms at 0 and 2.
By that cdf, you can wait exactly 0 time with positive probability (similarly with 2). Because of that, the waiting time is mixed, not continuous.
Presumably you've been given definitions of all three. How are continuous r.v.s defined?
If it's not immediately clear from the formula, it often helps to draw the cdf:
|
Why is this random variable both continuous and discrete?
It's wrong because - as the answer explained - there are discrete atoms at 0 and 2.
By that cdf, you can wait exactly 0 time with positive probability (similarly with 2). Because of that, the waiting
|
40,363
|
SARIMA model equation
|
Excerpt from a comment clarifying the actual confusion:
I always found it a odd way to define the model. Consider the SARIMA(1,0,0)(1,0,0)24... isn't this the same as the much simpler rendering $y_t=\beta_0+\beta_1 y_{t-1}+\beta_2 y_{t-24}+\beta_3 y_{t-25}$? Why define it in that weird way?
Now
$$ y_t = \beta_0 + \beta_1 y_{t-1} + \beta_2 y_{t-24} + \beta_3 y_{t-25} + \varepsilon_t $$
is an ARIMA(25,0,0) model (with some coefficients set to zero). Is it the same as SARIMA(1,0,0)(1,0,0)24? Actually, no. They are the same up to a restriction on the coefficients. In SARIMA(1,0,0)(1,0,0)24, the following must hold:
$$ \beta_1 = \phi_1, \ \beta_{2} = \Phi_{24}, \ \beta_{3} = - \phi_{1}\Phi_{24}. $$
Hence, for a given pair $(\beta_1,\beta_{2})$, the remaining coefficient $\beta_{3}$ is fixed: $\beta_{3} = - \beta_1\beta_{2}$. If this restriction does not hold, you have an ARIMA(25,0,0) rather than SARIMA(1,0,0)(1,0,0)24.
This is also a testable hypothesis (although I am not sure how useful such a test is from the subject-matter perspective); you may estimate an ARIMA(25,0,0) with zero restrictions on all lags but 1, 24 and 25, and test for the hypothesis $\text{H}_0: \beta_{3} = - \beta_1\beta_{2}$. If you cannot reject it, you would go for SARIMA(1,0,0)(1,0,0)24; if you reject it, ARIMA(25,0,0) would be your choice.
|
SARIMA model equation
|
Excerpt from a comment clarifying the actual confusion:
I always found it a odd way to define the model. Consider the SARIMA(1,0,0)(1,0,0)24... isn't this the same as the much simpler rendering $y_t
|
SARIMA model equation
Excerpt from a comment clarifying the actual confusion:
I always found it a odd way to define the model. Consider the SARIMA(1,0,0)(1,0,0)24... isn't this the same as the much simpler rendering $y_t=\beta_0+\beta_1 y_{t-1}+\beta_2 y_{t-24}+\beta_3 y_{t-25}$? Why define it in that weird way?
Now
$$ y_t = \beta_0 + \beta_1 y_{t-1} + \beta_2 y_{t-24} + \beta_3 y_{t-25} + \varepsilon_t $$
is an ARIMA(25,0,0) model (with some coefficients set to zero). Is it the same as SARIMA(1,0,0)(1,0,0)24? Actually, no. They are the same up to a restriction on the coefficients. In SARIMA(1,0,0)(1,0,0)24, the following must hold:
$$ \beta_1 = \phi_1, \ \beta_{2} = \Phi_{24}, \ \beta_{3} = - \phi_{1}\Phi_{24}. $$
Hence, for a given pair $(\beta_1,\beta_{2})$, the remaining coefficient $\beta_{3}$ is fixed: $\beta_{3} = - \beta_1\beta_{2}$. If this restriction does not hold, you have an ARIMA(25,0,0) rather than SARIMA(1,0,0)(1,0,0)24.
This is also a testable hypothesis (although I am not sure how useful such a test is from the subject-matter perspective); you may estimate an ARIMA(25,0,0) with zero restrictions on all lags but 1, 24 and 25, and test for the hypothesis $\text{H}_0: \beta_{3} = - \beta_1\beta_{2}$. If you cannot reject it, you would go for SARIMA(1,0,0)(1,0,0)24; if you reject it, ARIMA(25,0,0) would be your choice.
|
SARIMA model equation
Excerpt from a comment clarifying the actual confusion:
I always found it a odd way to define the model. Consider the SARIMA(1,0,0)(1,0,0)24... isn't this the same as the much simpler rendering $y_t
|
40,364
|
SARIMA model equation
|
ARIMA model uses the historical information within the own variable to predict the future values and this model have two parts. On the one hand we have the AR structure and on the other hand we have the MA structure. The AR structure is very intuitive because we are multiplying one past variable's value by one estimated parameter, it's like a weight of this past in the prediction. However the MA structure it's less intuitive but it's the same intuition regarding AR. If you'd like to have a detailed explanation, tell me.
So, pay attention to the subindex "t" in your model because I think here is the key of your question. e_t is just the error that you will get with your forecasts: Tomorrow, we'll see X sales, but when tomorrow arrives the sales have been Y (approximated value to X but different), so when you carried out the forecast you had to introduce the error term to be consistent: Y_t=X+e_t, Y is the real value at t, X the estimated one and e the difference between the real and the estimated. Y_t and e_t is the information that you have today, the X value is based on the past (based on t-1, t-2,...t-n info) and it's your work with the ARIMA model.
|
SARIMA model equation
|
ARIMA model uses the historical information within the own variable to predict the future values and this model have two parts. On the one hand we have the AR structure and on the other hand we have t
|
SARIMA model equation
ARIMA model uses the historical information within the own variable to predict the future values and this model have two parts. On the one hand we have the AR structure and on the other hand we have the MA structure. The AR structure is very intuitive because we are multiplying one past variable's value by one estimated parameter, it's like a weight of this past in the prediction. However the MA structure it's less intuitive but it's the same intuition regarding AR. If you'd like to have a detailed explanation, tell me.
So, pay attention to the subindex "t" in your model because I think here is the key of your question. e_t is just the error that you will get with your forecasts: Tomorrow, we'll see X sales, but when tomorrow arrives the sales have been Y (approximated value to X but different), so when you carried out the forecast you had to introduce the error term to be consistent: Y_t=X+e_t, Y is the real value at t, X the estimated one and e the difference between the real and the estimated. Y_t and e_t is the information that you have today, the X value is based on the past (based on t-1, t-2,...t-n info) and it's your work with the ARIMA model.
|
SARIMA model equation
ARIMA model uses the historical information within the own variable to predict the future values and this model have two parts. On the one hand we have the AR structure and on the other hand we have t
|
40,365
|
SARIMA model equation
|
$Y(t)=α1*Y(t−1)+e(t)$
Since $Y(t-1)=B*Y(t)$ we get
$Y(t)=α1*B*Y(t)+e(t)$
Collecting like terms
$Y(t)-α1*B*Y(t)=e(t)$
or
$Y(t)[1-α1*B]=e(t)$
the forecast equation is $YPRED(t)=α1*Y(t−1)$ since the expected value of $e(t)=0.0$
|
SARIMA model equation
|
$Y(t)=α1*Y(t−1)+e(t)$
Since $Y(t-1)=B*Y(t)$ we get
$Y(t)=α1*B*Y(t)+e(t)$
Collecting like terms
$Y(t)-α1*B*Y(t)=e(t)$
or
$Y(t)[1-α1*B]=e(t)$
the forecast equation is $YPRED(t)=α1*Y(t−1)$ since the expe
|
SARIMA model equation
$Y(t)=α1*Y(t−1)+e(t)$
Since $Y(t-1)=B*Y(t)$ we get
$Y(t)=α1*B*Y(t)+e(t)$
Collecting like terms
$Y(t)-α1*B*Y(t)=e(t)$
or
$Y(t)[1-α1*B]=e(t)$
the forecast equation is $YPRED(t)=α1*Y(t−1)$ since the expected value of $e(t)=0.0$
|
SARIMA model equation
$Y(t)=α1*Y(t−1)+e(t)$
Since $Y(t-1)=B*Y(t)$ we get
$Y(t)=α1*B*Y(t)+e(t)$
Collecting like terms
$Y(t)-α1*B*Y(t)=e(t)$
or
$Y(t)[1-α1*B]=e(t)$
the forecast equation is $YPRED(t)=α1*Y(t−1)$ since the expe
|
40,366
|
Is 'indirect effect' the same as 'mediation'?
|
No, "mediation" and "indirect effect" are not synonymous. For example, when analyzing complex causal systems in which any variable in the system at time $t$ contributes causally to every variable in the system at times $>t$, the term "mediator" is largely meaningless, whereas indirect effects may or may not exist due both to the qualitative structure of the system, and due to the quantitative magnitude of direct causal effects withing that structure (see, for example, Levins, R. (1974). The qualitative analysis of partially specified systems. Annals of the New York Academy of Sciences, 231:123–138.)
gung's answer assumes a terminal causal model, where the analysis attempts to explain or predict a final causal outcome, typically in a limited set of variables. By contrast complex causal models attempt to explain system behaviors.
|
Is 'indirect effect' the same as 'mediation'?
|
No, "mediation" and "indirect effect" are not synonymous. For example, when analyzing complex causal systems in which any variable in the system at time $t$ contributes causally to every variable in t
|
Is 'indirect effect' the same as 'mediation'?
No, "mediation" and "indirect effect" are not synonymous. For example, when analyzing complex causal systems in which any variable in the system at time $t$ contributes causally to every variable in the system at times $>t$, the term "mediator" is largely meaningless, whereas indirect effects may or may not exist due both to the qualitative structure of the system, and due to the quantitative magnitude of direct causal effects withing that structure (see, for example, Levins, R. (1974). The qualitative analysis of partially specified systems. Annals of the New York Academy of Sciences, 231:123–138.)
gung's answer assumes a terminal causal model, where the analysis attempts to explain or predict a final causal outcome, typically in a limited set of variables. By contrast complex causal models attempt to explain system behaviors.
|
Is 'indirect effect' the same as 'mediation'?
No, "mediation" and "indirect effect" are not synonymous. For example, when analyzing complex causal systems in which any variable in the system at time $t$ contributes causally to every variable in t
|
40,367
|
Is 'indirect effect' the same as 'mediation'?
|
There seem to be two distinct aspects to this question:
Are the terms 'indirect effect' and 'mediation' synonymous?
I would say largely yes (edit: assuming--cf. @Alexis' answer--that you are referring to a terminal causal model). Bear in mind that you can have full or partial mediation. That is, the effect of A on C can flow only through B, or partly through B but also partly directly. It is less clear to me how one would use 'indirect effect' in the latter case. To my ear it sounds more like full mediation.
If we know a-priori that A causes B, and B in turn causes C, do we need a mediation test?
No. If you know that this is the case a-priori, then testing is silly and redundant. This has to do with the nature of statistical testing; there is nothing special about mediation here: We can also say that there is no need to do a $t$-test (for example), to determine if the mean of a variable differs by grouping after having done a median split.
|
Is 'indirect effect' the same as 'mediation'?
|
There seem to be two distinct aspects to this question:
Are the terms 'indirect effect' and 'mediation' synonymous?
I would say largely yes (edit: assuming--cf. @Alexis' answer--that you are referrin
|
Is 'indirect effect' the same as 'mediation'?
There seem to be two distinct aspects to this question:
Are the terms 'indirect effect' and 'mediation' synonymous?
I would say largely yes (edit: assuming--cf. @Alexis' answer--that you are referring to a terminal causal model). Bear in mind that you can have full or partial mediation. That is, the effect of A on C can flow only through B, or partly through B but also partly directly. It is less clear to me how one would use 'indirect effect' in the latter case. To my ear it sounds more like full mediation.
If we know a-priori that A causes B, and B in turn causes C, do we need a mediation test?
No. If you know that this is the case a-priori, then testing is silly and redundant. This has to do with the nature of statistical testing; there is nothing special about mediation here: We can also say that there is no need to do a $t$-test (for example), to determine if the mean of a variable differs by grouping after having done a median split.
|
Is 'indirect effect' the same as 'mediation'?
There seem to be two distinct aspects to this question:
Are the terms 'indirect effect' and 'mediation' synonymous?
I would say largely yes (edit: assuming--cf. @Alexis' answer--that you are referrin
|
40,368
|
Is 'indirect effect' the same as 'mediation'?
|
The word mediation is inappropriate when the influence from A to C is not significant. However, you can say that A influences C indirectly through B, i.e. indirect effect.
|
Is 'indirect effect' the same as 'mediation'?
|
The word mediation is inappropriate when the influence from A to C is not significant. However, you can say that A influences C indirectly through B, i.e. indirect effect.
|
Is 'indirect effect' the same as 'mediation'?
The word mediation is inappropriate when the influence from A to C is not significant. However, you can say that A influences C indirectly through B, i.e. indirect effect.
|
Is 'indirect effect' the same as 'mediation'?
The word mediation is inappropriate when the influence from A to C is not significant. However, you can say that A influences C indirectly through B, i.e. indirect effect.
|
40,369
|
Define the joint pmf of a particle moving randomly on a grid
|
I'm going to focus attention on some specifics of your example, but the arguments carry over to larger examples.
As you saw, there are 25 cells inside a 3-step radius of the origin:
.
. . .
. . . . .
. . . o . . .
. . . . .
. . .
.
The first thing to do is recognize that symmetry considerations reduce calculation to final cells whose center lie within an angle to the origin of $[0,\pi/4]$:
. ⁄
. . . ⁄
. . . + +
. . . + + + + ------
. . . . .
. . .
.
That cuts 25 cells that lie within a 3-step radius down to 6. In large problems it will reduce it to a bit over 1/8th of the total.
The second thing to see is that parity considerations reduce calculation still further, eliminating 3 of the 6 cells (e.g. if you move three steps, you can't end up back where you start). So you only need to work out three cells:
.
. . .
. . . . c
. . . . a . b
. . . . .
. . .
.
This step will reduce calculation by around half.
All other cells that have non-zero probability after 3 steps will equal one of the
three marked cells.
Now recognize that if you take those three cells, and add another cell:
.
. . c'
. . . . c
. . . . a . b
. . . . .
. . .
.
then by rotation, you cover all the positive-probability cells with the right probability. Hence if $n(.)$ is the number of ways of getting to cell $i$, $n(a)+n(b)+2n(c)=64/4=16$, and for probabilities, if $p_3(i)$ is the probability of getting to position $i$ at step $3$, $p_3(a)+p_3(b)+2p_3(c)=1/4$. This provides a useful check that we didn't miss any probability.
(More generally, you'd double any cell not on the x-axis or on an exact diagonal in
this calculation. And on even numbered steps, the origin counts only once, of course.)
So if you have a systematic method for getting those individual cell counts/probabilities, you only have to do those ones.
However as for working out the probabilities, I tend to look at doing it recursively, one step at a time, essentially convolving the single-step probabilities as a kernel with the outcome of the previous step.
Step 0. We start with all the probability at the center:
· · ·
· · · · ·
· · 1 · ·
· · · · ·
· · ·
Step 1. Consider the first, single step
· · · · · · · 1/4 · ·
↑
· · ← 1 → · · ===> · 1/4 0 1/4 ·
↓
· · · · · · · 1/4 · ·
This single-step result now can be treated treated as a kernel - on any future step, we take the probabilities at any given location at the previous step, convolve it with this bivariate kernel and to get the next step. In practice this means you take a given amount of probability, divide it by 4 and add it to the cell probabilities one step in each of the 4 directions, iterated over all cells (in really large problems you'd look at more efficient approaches, but this will do for the present problem). If you do that across all relevant cells, you've computed all the probabilities at one step in terms of the previous one.
But, usefully, we can flip this around. To work out the probability of a given cell, you average the 4 probabilities from the previous step that were one step in each of the 4 directions around it:
$p_{i,j}(t)=\frac{1}{4}[p_{i-1,j}(t-1)+p_{i,j-1}(t-1)+p_{i+1,j}(t-1)+p_{i,j+1}(t-1)]$
We can employ the previously mentioned symmetries, so we only need to keep track of cells within the 1/8-arc (including its boundary).
So revised Step 1:
· ·
· · ·
· · · ·
o q · · ·
Where $p_1(o)=0$ and $p_1(q)=\frac{1}{4}$ (I used $q$ to stand for "quarter").
And revised Step 2:
· ·
· · ·
w · · ·
o . x · ·
The point marked $w$ gets 1/4 of the probability from each side of it. But only 2 of those cells are non-zero:
0
↓
q → w ← 0
↑
q
so $p_2(w) = 2(1/4)^2 = 1/8$
Meanwhile, $x$ is only getting probability from its left, so $p_2(x) = (1/4)^2 = 1/16$
However, there's also point $o$, which can inherit probability from any side, so $p_2(o)=4(1/4)^2=1/4$.
Check: $p_2(o)+4(p_2(w)+p_2(x))=1/4 + 4/8 + 4/16 = 1$
You can continue in that fashion to
a revised Step 3:
· · · ·
· · · · · ·
w · · · ===> . c · ·
o . x · · . a . b ·
$p_3(a) = [p_2(o)+2p_2(w)+p_2(x)]/4 = [\frac{1}{4} + 2\frac{1}{8} + \frac{1}{16}]/4 =9/64$
$p_3(b) = p_2(x)/4 = (\frac{1}{16})/4 = 1/64$
$p_3(c) = [p_2(w)+p_2(x)]/4 = [\frac{1}{8} + \frac{1}{16}]/4 =3/64$
Check: $p_3(a)+p_3(b)+2p_3(c)=[9+1+2\times 3]/64=1/4$.
And so on for step 4, 5, etc.
Step 4 would go like:
· · · ·
· · · · · ·
· c · · ===> w · y ·
· a · b · o · x · z
This is easy to write code to iterate through.
|
Define the joint pmf of a particle moving randomly on a grid
|
I'm going to focus attention on some specifics of your example, but the arguments carry over to larger examples.
As you saw, there are 25 cells inside a 3-step radius of the origin:
.
|
Define the joint pmf of a particle moving randomly on a grid
I'm going to focus attention on some specifics of your example, but the arguments carry over to larger examples.
As you saw, there are 25 cells inside a 3-step radius of the origin:
.
. . .
. . . . .
. . . o . . .
. . . . .
. . .
.
The first thing to do is recognize that symmetry considerations reduce calculation to final cells whose center lie within an angle to the origin of $[0,\pi/4]$:
. ⁄
. . . ⁄
. . . + +
. . . + + + + ------
. . . . .
. . .
.
That cuts 25 cells that lie within a 3-step radius down to 6. In large problems it will reduce it to a bit over 1/8th of the total.
The second thing to see is that parity considerations reduce calculation still further, eliminating 3 of the 6 cells (e.g. if you move three steps, you can't end up back where you start). So you only need to work out three cells:
.
. . .
. . . . c
. . . . a . b
. . . . .
. . .
.
This step will reduce calculation by around half.
All other cells that have non-zero probability after 3 steps will equal one of the
three marked cells.
Now recognize that if you take those three cells, and add another cell:
.
. . c'
. . . . c
. . . . a . b
. . . . .
. . .
.
then by rotation, you cover all the positive-probability cells with the right probability. Hence if $n(.)$ is the number of ways of getting to cell $i$, $n(a)+n(b)+2n(c)=64/4=16$, and for probabilities, if $p_3(i)$ is the probability of getting to position $i$ at step $3$, $p_3(a)+p_3(b)+2p_3(c)=1/4$. This provides a useful check that we didn't miss any probability.
(More generally, you'd double any cell not on the x-axis or on an exact diagonal in
this calculation. And on even numbered steps, the origin counts only once, of course.)
So if you have a systematic method for getting those individual cell counts/probabilities, you only have to do those ones.
However as for working out the probabilities, I tend to look at doing it recursively, one step at a time, essentially convolving the single-step probabilities as a kernel with the outcome of the previous step.
Step 0. We start with all the probability at the center:
· · ·
· · · · ·
· · 1 · ·
· · · · ·
· · ·
Step 1. Consider the first, single step
· · · · · · · 1/4 · ·
↑
· · ← 1 → · · ===> · 1/4 0 1/4 ·
↓
· · · · · · · 1/4 · ·
This single-step result now can be treated treated as a kernel - on any future step, we take the probabilities at any given location at the previous step, convolve it with this bivariate kernel and to get the next step. In practice this means you take a given amount of probability, divide it by 4 and add it to the cell probabilities one step in each of the 4 directions, iterated over all cells (in really large problems you'd look at more efficient approaches, but this will do for the present problem). If you do that across all relevant cells, you've computed all the probabilities at one step in terms of the previous one.
But, usefully, we can flip this around. To work out the probability of a given cell, you average the 4 probabilities from the previous step that were one step in each of the 4 directions around it:
$p_{i,j}(t)=\frac{1}{4}[p_{i-1,j}(t-1)+p_{i,j-1}(t-1)+p_{i+1,j}(t-1)+p_{i,j+1}(t-1)]$
We can employ the previously mentioned symmetries, so we only need to keep track of cells within the 1/8-arc (including its boundary).
So revised Step 1:
· ·
· · ·
· · · ·
o q · · ·
Where $p_1(o)=0$ and $p_1(q)=\frac{1}{4}$ (I used $q$ to stand for "quarter").
And revised Step 2:
· ·
· · ·
w · · ·
o . x · ·
The point marked $w$ gets 1/4 of the probability from each side of it. But only 2 of those cells are non-zero:
0
↓
q → w ← 0
↑
q
so $p_2(w) = 2(1/4)^2 = 1/8$
Meanwhile, $x$ is only getting probability from its left, so $p_2(x) = (1/4)^2 = 1/16$
However, there's also point $o$, which can inherit probability from any side, so $p_2(o)=4(1/4)^2=1/4$.
Check: $p_2(o)+4(p_2(w)+p_2(x))=1/4 + 4/8 + 4/16 = 1$
You can continue in that fashion to
a revised Step 3:
· · · ·
· · · · · ·
w · · · ===> . c · ·
o . x · · . a . b ·
$p_3(a) = [p_2(o)+2p_2(w)+p_2(x)]/4 = [\frac{1}{4} + 2\frac{1}{8} + \frac{1}{16}]/4 =9/64$
$p_3(b) = p_2(x)/4 = (\frac{1}{16})/4 = 1/64$
$p_3(c) = [p_2(w)+p_2(x)]/4 = [\frac{1}{8} + \frac{1}{16}]/4 =3/64$
Check: $p_3(a)+p_3(b)+2p_3(c)=[9+1+2\times 3]/64=1/4$.
And so on for step 4, 5, etc.
Step 4 would go like:
· · · ·
· · · · · ·
· c · · ===> w · y ·
· a · b · o · x · z
This is easy to write code to iterate through.
|
Define the joint pmf of a particle moving randomly on a grid
I'm going to focus attention on some specifics of your example, but the arguments carry over to larger examples.
As you saw, there are 25 cells inside a 3-step radius of the origin:
.
|
40,370
|
Define the joint pmf of a particle moving randomly on a grid
|
Are you allowing the particle to move backwards?
Either way, I would model it in terms of a matrix $A$ giving the transition probabilities between each pairs of cells. You can then find the probabilities of all paths from i to j after k steps by calculating $A^K$. This representation may lead you to a set of equations that would be more concise.
|
Define the joint pmf of a particle moving randomly on a grid
|
Are you allowing the particle to move backwards?
Either way, I would model it in terms of a matrix $A$ giving the transition probabilities between each pairs of cells. You can then find the probabili
|
Define the joint pmf of a particle moving randomly on a grid
Are you allowing the particle to move backwards?
Either way, I would model it in terms of a matrix $A$ giving the transition probabilities between each pairs of cells. You can then find the probabilities of all paths from i to j after k steps by calculating $A^K$. This representation may lead you to a set of equations that would be more concise.
|
Define the joint pmf of a particle moving randomly on a grid
Are you allowing the particle to move backwards?
Either way, I would model it in terms of a matrix $A$ giving the transition probabilities between each pairs of cells. You can then find the probabili
|
40,371
|
Define the joint pmf of a particle moving randomly on a grid
|
Your approach would lead to the correct answer, but you have missed some ways to get into the squares marked with $4$ and $2$. For example, 'right-up-right', 'right-right-up' and 'up-right-right' are 3 ways to end up at the same square, which you have marked with $2$.
|
Define the joint pmf of a particle moving randomly on a grid
|
Your approach would lead to the correct answer, but you have missed some ways to get into the squares marked with $4$ and $2$. For example, 'right-up-right', 'right-right-up' and 'up-right-right' are
|
Define the joint pmf of a particle moving randomly on a grid
Your approach would lead to the correct answer, but you have missed some ways to get into the squares marked with $4$ and $2$. For example, 'right-up-right', 'right-right-up' and 'up-right-right' are 3 ways to end up at the same square, which you have marked with $2$.
|
Define the joint pmf of a particle moving randomly on a grid
Your approach would lead to the correct answer, but you have missed some ways to get into the squares marked with $4$ and $2$. For example, 'right-up-right', 'right-right-up' and 'up-right-right' are
|
40,372
|
Outer crossvalidation cycle in caret package (R)?
|
Inner and outer CV are used to perform classifier selection not to get a better prediction on the estimate. To get a better estimate, do a repeated cv. So to perform a 10-repeates 5-fold CV use
trainControl(method = "repeatedcv",number = 5,
## repeated ten times
repeats = 10)
But if what you really want is a nested CV, for example to select between a random forest or a svm) then as far as know you have to do the outer CV explicitly. What I did for an outer 5-fold, inner 10-fold was:
ntrain=length(ytrain)
train.ext=createFolds(ytrain,k=5,returnTrain=TRUE)
test.ext=lapply(train.ext,function(x) (1:ntrain)[-x])
for (i in 1:5){
model<-train(Class ~ ., data = training[train.ext[[i]]],
trControl=trainControl(method = "cv",number = 10),
...
...
}
|
Outer crossvalidation cycle in caret package (R)?
|
Inner and outer CV are used to perform classifier selection not to get a better prediction on the estimate. To get a better estimate, do a repeated cv. So to perform a 10-repeates 5-fold CV use
trainC
|
Outer crossvalidation cycle in caret package (R)?
Inner and outer CV are used to perform classifier selection not to get a better prediction on the estimate. To get a better estimate, do a repeated cv. So to perform a 10-repeates 5-fold CV use
trainControl(method = "repeatedcv",number = 5,
## repeated ten times
repeats = 10)
But if what you really want is a nested CV, for example to select between a random forest or a svm) then as far as know you have to do the outer CV explicitly. What I did for an outer 5-fold, inner 10-fold was:
ntrain=length(ytrain)
train.ext=createFolds(ytrain,k=5,returnTrain=TRUE)
test.ext=lapply(train.ext,function(x) (1:ntrain)[-x])
for (i in 1:5){
model<-train(Class ~ ., data = training[train.ext[[i]]],
trControl=trainControl(method = "cv",number = 10),
...
...
}
|
Outer crossvalidation cycle in caret package (R)?
Inner and outer CV are used to perform classifier selection not to get a better prediction on the estimate. To get a better estimate, do a repeated cv. So to perform a 10-repeates 5-fold CV use
trainC
|
40,373
|
Mixed effects model for power function data
|
(Disclaimer: answering my own question after fiddling around - I'm really not an expert on this so please read critically)
Step 1: create a power function, including the intercept, using the deriv function which adds the necessary properties to the object. You have to be somewhat verbose, specifying which parameters to estimate (namevec) and which parameters nlmer can play with (function.arg). In this case it's sort of trivial but this is handy if you have big and complicated stuff going on with lots of internal variables that really are of no interest to nlmer when finding the optimal fit. So:
power.f = deriv(~k + a*time^b, namevec=c('k', 'a', 'b'), function.arg=c('time','k', 'a','b'))
Step 2: fit the parameters of the nonlinear model using a dependent ~ non-linear ~ fixed + random syntax, where the non-linear part is objects of the sort we just created above.
fit.nlmer = nlmer(y ~ power.f(time, k, a, b) ~ k|id, start=list(nlpars=c(k=2, a=1, b=1)), data=D)
A few comments on step 2: The latter part is the stuff you may be used to from lmer but with the exception that it won't accept intercept-only stuff (for example 1|id). So here's why you didn't just make the power.f formula ~ a*time^b and put a random intercept in the fixed-random part. Instead you "put in" a random intercept (here k) into the nonlinear function - which in this case is equivalent to a linear intercept.
Also: the start values are just you helping nlmer to start in the vicinity of the correct solution since the likelihood landscape can be way more complex and contain more traps (plateaus, local minima etc.) than a linear one. But don't care too much about being spot-on (after all, you're doing inference for a reason). I just looked at the data and put in something that was not totally off.
To see why this mixed-model effort is fruitful compared to a common-intercept model like the nls one, consider the fit (observed y versus model-predicted y):
|
Mixed effects model for power function data
|
(Disclaimer: answering my own question after fiddling around - I'm really not an expert on this so please read critically)
Step 1: create a power function, including the intercept, using the deriv fun
|
Mixed effects model for power function data
(Disclaimer: answering my own question after fiddling around - I'm really not an expert on this so please read critically)
Step 1: create a power function, including the intercept, using the deriv function which adds the necessary properties to the object. You have to be somewhat verbose, specifying which parameters to estimate (namevec) and which parameters nlmer can play with (function.arg). In this case it's sort of trivial but this is handy if you have big and complicated stuff going on with lots of internal variables that really are of no interest to nlmer when finding the optimal fit. So:
power.f = deriv(~k + a*time^b, namevec=c('k', 'a', 'b'), function.arg=c('time','k', 'a','b'))
Step 2: fit the parameters of the nonlinear model using a dependent ~ non-linear ~ fixed + random syntax, where the non-linear part is objects of the sort we just created above.
fit.nlmer = nlmer(y ~ power.f(time, k, a, b) ~ k|id, start=list(nlpars=c(k=2, a=1, b=1)), data=D)
A few comments on step 2: The latter part is the stuff you may be used to from lmer but with the exception that it won't accept intercept-only stuff (for example 1|id). So here's why you didn't just make the power.f formula ~ a*time^b and put a random intercept in the fixed-random part. Instead you "put in" a random intercept (here k) into the nonlinear function - which in this case is equivalent to a linear intercept.
Also: the start values are just you helping nlmer to start in the vicinity of the correct solution since the likelihood landscape can be way more complex and contain more traps (plateaus, local minima etc.) than a linear one. But don't care too much about being spot-on (after all, you're doing inference for a reason). I just looked at the data and put in something that was not totally off.
To see why this mixed-model effort is fruitful compared to a common-intercept model like the nls one, consider the fit (observed y versus model-predicted y):
|
Mixed effects model for power function data
(Disclaimer: answering my own question after fiddling around - I'm really not an expert on this so please read critically)
Step 1: create a power function, including the intercept, using the deriv fun
|
40,374
|
What is the variance of a Polya Gamma distribution?
|
In equation (6), the paper obtains the Laplace transform of these distributions as
$$\phi(t) = \prod_{k=1}^\infty \left(1 + \frac{t}{d_k}
\right)^{-b};\ d_k = 2\left(k-\frac{1}{2}\right)^2 \pi^2 + c^2/2$$
where $b\gt 0$ and $c\in \mathbb R$ are the parameters. Taking logarithms yields
$$\psi(t) = \frac{d}{dt}\phi(t) = \sum_{k=1}^\infty -b \log\left(1 + \frac{t}{d_k}\right).$$
This is a cumulant generating function (for imaginary values of $t$, at any rate) whose Taylor series around $t=0$ begins
$$\psi(t) = -\mu_1^\prime t + \frac{1}{2!} \left( \mu_2^\prime - \mu_1^{\prime \,2} \right)t^2 + \cdots$$
with $\mu_j^\prime$ representing the raw moment of order $j$: thus, the negative of the coefficient of $t$ is the mean and twice ($=2!$) the coefficient of $t^2$ is the variance. The summation formula for $\psi$ can be expanded term-by-term and collected in common powers of $t$ to produce
$$\psi(t) = \sum_{k=1}^\infty -b \left(\frac{t}{d_k} + \frac{t^2}{2 d_k^2} + \cdots\right) = -b\sum_{k=1}^\infty \frac{1}{d_k} t - b\sum_{k=1}^\infty \frac{1}{2d_k^2} t^2 + \cdots.$$
Such sums, whose terms are the reciprocals of quadratic (and higher) functions of the integral index $k$, are straightforward to evaluate using the Weierstrass Factorization Theorem and yield
$$\mu_1^\prime = \frac{b }{2 c}\tanh \left(c/2\right);\ \mu_2^\prime - \mu_1^{\prime\,2} = \frac{b }{4 c^3}(\sinh (c) - c) \text{sech}^2\left(c/2\right).$$
The former agrees with the mean reported in the paper (adding some confidence to the overall correctness of this approach) while the latter answers the question: it is a closed form expression for the variance. (These series can be continued in higher powers of $t$ to develop closed formulas for any cumulants, from which higher moments can be extracted.)
Partial contour plots show that the signs of the results (at least) are correct.
Nothing is shown along the $b$ axis (where $c=0$) because these formulas are not defined for $c=0$. However, the plots make it clear that the formulas can be extended to continuous functions along that axis by taking the limits as $c\to 0$. They give $b/4$ for the mean and $b/24$ for the variance.
|
What is the variance of a Polya Gamma distribution?
|
In equation (6), the paper obtains the Laplace transform of these distributions as
$$\phi(t) = \prod_{k=1}^\infty \left(1 + \frac{t}{d_k}
\right)^{-b};\ d_k = 2\left(k-\frac{1}{2}\right)^2 \pi^2 + c^2
|
What is the variance of a Polya Gamma distribution?
In equation (6), the paper obtains the Laplace transform of these distributions as
$$\phi(t) = \prod_{k=1}^\infty \left(1 + \frac{t}{d_k}
\right)^{-b};\ d_k = 2\left(k-\frac{1}{2}\right)^2 \pi^2 + c^2/2$$
where $b\gt 0$ and $c\in \mathbb R$ are the parameters. Taking logarithms yields
$$\psi(t) = \frac{d}{dt}\phi(t) = \sum_{k=1}^\infty -b \log\left(1 + \frac{t}{d_k}\right).$$
This is a cumulant generating function (for imaginary values of $t$, at any rate) whose Taylor series around $t=0$ begins
$$\psi(t) = -\mu_1^\prime t + \frac{1}{2!} \left( \mu_2^\prime - \mu_1^{\prime \,2} \right)t^2 + \cdots$$
with $\mu_j^\prime$ representing the raw moment of order $j$: thus, the negative of the coefficient of $t$ is the mean and twice ($=2!$) the coefficient of $t^2$ is the variance. The summation formula for $\psi$ can be expanded term-by-term and collected in common powers of $t$ to produce
$$\psi(t) = \sum_{k=1}^\infty -b \left(\frac{t}{d_k} + \frac{t^2}{2 d_k^2} + \cdots\right) = -b\sum_{k=1}^\infty \frac{1}{d_k} t - b\sum_{k=1}^\infty \frac{1}{2d_k^2} t^2 + \cdots.$$
Such sums, whose terms are the reciprocals of quadratic (and higher) functions of the integral index $k$, are straightforward to evaluate using the Weierstrass Factorization Theorem and yield
$$\mu_1^\prime = \frac{b }{2 c}\tanh \left(c/2\right);\ \mu_2^\prime - \mu_1^{\prime\,2} = \frac{b }{4 c^3}(\sinh (c) - c) \text{sech}^2\left(c/2\right).$$
The former agrees with the mean reported in the paper (adding some confidence to the overall correctness of this approach) while the latter answers the question: it is a closed form expression for the variance. (These series can be continued in higher powers of $t$ to develop closed formulas for any cumulants, from which higher moments can be extracted.)
Partial contour plots show that the signs of the results (at least) are correct.
Nothing is shown along the $b$ axis (where $c=0$) because these formulas are not defined for $c=0$. However, the plots make it clear that the formulas can be extended to continuous functions along that axis by taking the limits as $c\to 0$. They give $b/4$ for the mean and $b/24$ for the variance.
|
What is the variance of a Polya Gamma distribution?
In equation (6), the paper obtains the Laplace transform of these distributions as
$$\phi(t) = \prod_{k=1}^\infty \left(1 + \frac{t}{d_k}
\right)^{-b};\ d_k = 2\left(k-\frac{1}{2}\right)^2 \pi^2 + c^2
|
40,375
|
Can we average over a Cauchy random variable?
|
I don't know of any results from integration theory that would give full description of such functions, but I can give a few observations that might be helpful.
0) If the function $g$ is always positive or always negative, then the integral exists, although it might by infinite.
1) The set of $g$ for which the integral is finite forms a linear space.
2) For any $g$ that is Lebesgue integrable the expectation exists and is finite, since: $$ |\int f(x) g(x) dx | \leq \int \frac{1}{\pi} |g(x)| dx < \infty $$
3) For any $g$ that is essentially bounded the integral is also finite since:
$$ |\int f(x) g(x) dx | \leq \int |f(x)| C dx = C$$
Where $C$ is such that $g(x) \leq C$ almost everywhere.
4) If there exists $\alpha <1 $ such that $\lim_{|x| \rightarrow \infty} \frac{g(x)}{|x|^{\alpha}} = 0$ and $\int_{-n}^{n} f(x) g(x) dx$ exists for any $n > 0$, then the integral exists.
Proof : From the first assumption about $g$, there exists $n$ such that for $|x| > n$ we have $\frac{g(x)}{\pi(x^2 + 1)} \leq \frac{1}{|x|^{2 - \alpha}}$. This imiples:
$$ \int f(x)g(x) dx \leq \int_{-\infty}^{-n} \frac{1}{|x|^{2 - \alpha}} dx + \int_{-n}^{n} f(x)g(x) dx + \int_{n}^{\infty} \frac{1}{|x|^{2 - \alpha}} dx < \infty$$
I suppose for most situations of interest, when the integral actually exists at least one of those criterions will work. Especially the 4th one should be quite sharp, although might not be very comfortable to check. Furthermore they are sufficient conditions for the existance of the integral, and neither of them is necessary.
|
Can we average over a Cauchy random variable?
|
I don't know of any results from integration theory that would give full description of such functions, but I can give a few observations that might be helpful.
0) If the function $g$ is always positi
|
Can we average over a Cauchy random variable?
I don't know of any results from integration theory that would give full description of such functions, but I can give a few observations that might be helpful.
0) If the function $g$ is always positive or always negative, then the integral exists, although it might by infinite.
1) The set of $g$ for which the integral is finite forms a linear space.
2) For any $g$ that is Lebesgue integrable the expectation exists and is finite, since: $$ |\int f(x) g(x) dx | \leq \int \frac{1}{\pi} |g(x)| dx < \infty $$
3) For any $g$ that is essentially bounded the integral is also finite since:
$$ |\int f(x) g(x) dx | \leq \int |f(x)| C dx = C$$
Where $C$ is such that $g(x) \leq C$ almost everywhere.
4) If there exists $\alpha <1 $ such that $\lim_{|x| \rightarrow \infty} \frac{g(x)}{|x|^{\alpha}} = 0$ and $\int_{-n}^{n} f(x) g(x) dx$ exists for any $n > 0$, then the integral exists.
Proof : From the first assumption about $g$, there exists $n$ such that for $|x| > n$ we have $\frac{g(x)}{\pi(x^2 + 1)} \leq \frac{1}{|x|^{2 - \alpha}}$. This imiples:
$$ \int f(x)g(x) dx \leq \int_{-\infty}^{-n} \frac{1}{|x|^{2 - \alpha}} dx + \int_{-n}^{n} f(x)g(x) dx + \int_{n}^{\infty} \frac{1}{|x|^{2 - \alpha}} dx < \infty$$
I suppose for most situations of interest, when the integral actually exists at least one of those criterions will work. Especially the 4th one should be quite sharp, although might not be very comfortable to check. Furthermore they are sufficient conditions for the existance of the integral, and neither of them is necessary.
|
Can we average over a Cauchy random variable?
I don't know of any results from integration theory that would give full description of such functions, but I can give a few observations that might be helpful.
0) If the function $g$ is always positi
|
40,376
|
Can we average over a Cauchy random variable?
|
This started out as a comment (just thinking out loud here), but I got further along than I thought. I haven't read any other answers yet so there's probably some overlap.
[This is clearly not anything like a definitive answer, since it doesn't characterize when such integrals converge in general. What it does after some initial rambling is explore one set of special cases of $g$, the first couple of which may be useful in practice.]
If $g$ is small enough in the tails (and doesn't shoot off to $\infty$ too fast anywhere in the middle), the limit for the integral would be finite; $g(x)=C$, for example, is fine, as is $g(x)=\phi(x)$ (or indeed any density). On the other hand, clearly you can't have $g(x)=x$, but you could have something like $g(x) = a+bF(x)$ for some cdf.
Since $f$ is so nice near 0, as long as $g(x)$ doesn't shoot off to $\infty$ at small $x$, the fun is at the big end, so one important aspect of the question seems to be 'how fast can $g$ grow?'.
Let's split up $∫^∞_{−∞}f(x)g(x)dx$ into three parts, a left part, a right part and a middle part, and try to identify a bound for the right part only. Because $f$ is symmetric, playing with the left part is very similar to the right, and because $f$ is bounded, the behavior in the middle is only an issue if your $g$ goes off to $∞$ in that part (when you'd have to worry about how it behaved then) - but I assume you'd have mentioned if $g$ might do that.
So I assume you mostly care to bound $∫^∞_c f(x)g(x)dx$ for some sufficiently large* positive $c$.
* In the sequence of functions I consider later, I'll also need a sequence of $c$'s to go with it. In effect, each $p_j$ will have some corresponding $c_j$.
Note that if $c>1$, $\frac{1}{1+x^2}<\frac{1}{x^2}<\frac{2}{1+x^2}<\frac{2}{x^2}$, so (taking $f^*(x)=x^{-2}$), if $∫^∞_c f^*(x).g(x)dx$ diverges or converges, so does $∫^∞_c f(x)g(x)dx$, and vice-versa (they share their convergence properties). So we only need to consider this simpler case.
To simplify further, let's call $f^*(x)g(x)$ "$p(x)$" and see what $p(x)$ can do in the extreme tail ... if we get some worthwhile limits on $p(x)$ in some particular cases, we can then back out bounds on $g(x)$ from that. (Excuse me, but I'm going to be overloading the symbol "$p$" here, so there's a sequence of functions $p_j(x)$ involving $x$, $log(x)$ and a scalar power, $p$. I could call $p_j(x)$ say $q_j(x)$ and denote the dependence on the power $p$ by say $q_j(x;p)$ but to me it was more intuitive in this case to overload $p$ to show that dependence. I don't know if that's just me, though.)
By bounding the right tail of the Cauchy between multiples of $f^*(x)=\frac{1}{x^2}$, we've simplified convergence considerations to cases that are easier to examine.
For example, if we examine the behavior of $p_0(x)=1/x^p$ then we're effectively considering what happens with $g(x)=1/x^{p-2}$.
Since $I_0=\int_1^\infty 1/x^p dx$ diverges for $p\leq 1$, the required integral diverges for $g(x) = x^k$ for $k\geq1$ (a fact we already knew, of course), so to get convergence you would need $g(x)/x$ to head toward zero at some rate. We'll explore how fast it needs to do that via the mechanism of examining some functions, $p(x)$ again.
Let's now consider $I_1=\int_c^\infty 1/(x.\log(x)^p) dx$ (i.e. $p_1=1/(x\log(x)^p)$) for some finite positive $c$ that's large enough we don't have to worry about the left hand end. Some $c>1$ would do to start but we can play with it if we need to. (Here we're effectively considering a connection to $g(x)$ that on the right side is bounded by $x/\log(x)^p$, but of course we'd need some other bound for values near 0)
When $p=1$ this integral also diverges. But if $p>1$, consider the substitution $y=\log(x)$, whereupon we get:
$I_1=\int_{\log{c}}^\infty 1/(x^p) dx$
So again, it looks like this will converge if $p>1$.
We can keep iterating this trick! Consider
$I_2=\int_c^\infty 1/(x.\log(x).\log(\log(x))^p) dx$
Let $y=\log(x)$
$I_2=\int_{\log{c}}^\infty 1/(y\log(y)^p) dy$
and so again, if $p>1$ (and $c$ is not too small), that integral will converge. Similarly we could make an $I_3$, $I_4$ and so on.
So there's an interesting sequence of functions in the right tail* where you have divergence when $p\leq 1$ and convergence for $p>1$.
* $p_0(x) = \frac{1}{x^p}$, $p_1=\frac{1}{x\log(x)^p}$, $p_2=\frac{1}{x\log(x)\log(\log(x))^p}$, $\ldots$
It seems that $g(x)$ can get really close to $x$ for large $x$, since as long as $g(x)\cdot(xp_j(x))$ is bounded and $p>1$ for some $j$, $\int_c^\infty f(x)g(x)dx$ for some sufficiently large $c$ should converge to some finite bound.
In effect, we have a corresponding sequence of $g_j(x)$:
* $g_0(x) = x^{2-p}$, $g_1=\frac{x}{\log(x)^p}$, $g_2=\frac{x}{\log(x)\log(\log(x))^p}$, $g_3=\frac{x}{\log(x)\log(\log(x))\log(\log(\log(x)))^p}$, $\ldots$
for which $\int^\infty_{c_j} \frac{1}{1+x^2}g(x)dx$ will converge if $p>1$ and diverge if $p\leq 1$.
[Of course if $g$ is not bounded at finite $x$ or does something weird at the left hand end, you still have to worry about the rest of the integral.]
I've got a strong feeling I've seen a sequence like this before, so I bet this is a very well-known result.
|
Can we average over a Cauchy random variable?
|
This started out as a comment (just thinking out loud here), but I got further along than I thought. I haven't read any other answers yet so there's probably some overlap.
[This is clearly not anythin
|
Can we average over a Cauchy random variable?
This started out as a comment (just thinking out loud here), but I got further along than I thought. I haven't read any other answers yet so there's probably some overlap.
[This is clearly not anything like a definitive answer, since it doesn't characterize when such integrals converge in general. What it does after some initial rambling is explore one set of special cases of $g$, the first couple of which may be useful in practice.]
If $g$ is small enough in the tails (and doesn't shoot off to $\infty$ too fast anywhere in the middle), the limit for the integral would be finite; $g(x)=C$, for example, is fine, as is $g(x)=\phi(x)$ (or indeed any density). On the other hand, clearly you can't have $g(x)=x$, but you could have something like $g(x) = a+bF(x)$ for some cdf.
Since $f$ is so nice near 0, as long as $g(x)$ doesn't shoot off to $\infty$ at small $x$, the fun is at the big end, so one important aspect of the question seems to be 'how fast can $g$ grow?'.
Let's split up $∫^∞_{−∞}f(x)g(x)dx$ into three parts, a left part, a right part and a middle part, and try to identify a bound for the right part only. Because $f$ is symmetric, playing with the left part is very similar to the right, and because $f$ is bounded, the behavior in the middle is only an issue if your $g$ goes off to $∞$ in that part (when you'd have to worry about how it behaved then) - but I assume you'd have mentioned if $g$ might do that.
So I assume you mostly care to bound $∫^∞_c f(x)g(x)dx$ for some sufficiently large* positive $c$.
* In the sequence of functions I consider later, I'll also need a sequence of $c$'s to go with it. In effect, each $p_j$ will have some corresponding $c_j$.
Note that if $c>1$, $\frac{1}{1+x^2}<\frac{1}{x^2}<\frac{2}{1+x^2}<\frac{2}{x^2}$, so (taking $f^*(x)=x^{-2}$), if $∫^∞_c f^*(x).g(x)dx$ diverges or converges, so does $∫^∞_c f(x)g(x)dx$, and vice-versa (they share their convergence properties). So we only need to consider this simpler case.
To simplify further, let's call $f^*(x)g(x)$ "$p(x)$" and see what $p(x)$ can do in the extreme tail ... if we get some worthwhile limits on $p(x)$ in some particular cases, we can then back out bounds on $g(x)$ from that. (Excuse me, but I'm going to be overloading the symbol "$p$" here, so there's a sequence of functions $p_j(x)$ involving $x$, $log(x)$ and a scalar power, $p$. I could call $p_j(x)$ say $q_j(x)$ and denote the dependence on the power $p$ by say $q_j(x;p)$ but to me it was more intuitive in this case to overload $p$ to show that dependence. I don't know if that's just me, though.)
By bounding the right tail of the Cauchy between multiples of $f^*(x)=\frac{1}{x^2}$, we've simplified convergence considerations to cases that are easier to examine.
For example, if we examine the behavior of $p_0(x)=1/x^p$ then we're effectively considering what happens with $g(x)=1/x^{p-2}$.
Since $I_0=\int_1^\infty 1/x^p dx$ diverges for $p\leq 1$, the required integral diverges for $g(x) = x^k$ for $k\geq1$ (a fact we already knew, of course), so to get convergence you would need $g(x)/x$ to head toward zero at some rate. We'll explore how fast it needs to do that via the mechanism of examining some functions, $p(x)$ again.
Let's now consider $I_1=\int_c^\infty 1/(x.\log(x)^p) dx$ (i.e. $p_1=1/(x\log(x)^p)$) for some finite positive $c$ that's large enough we don't have to worry about the left hand end. Some $c>1$ would do to start but we can play with it if we need to. (Here we're effectively considering a connection to $g(x)$ that on the right side is bounded by $x/\log(x)^p$, but of course we'd need some other bound for values near 0)
When $p=1$ this integral also diverges. But if $p>1$, consider the substitution $y=\log(x)$, whereupon we get:
$I_1=\int_{\log{c}}^\infty 1/(x^p) dx$
So again, it looks like this will converge if $p>1$.
We can keep iterating this trick! Consider
$I_2=\int_c^\infty 1/(x.\log(x).\log(\log(x))^p) dx$
Let $y=\log(x)$
$I_2=\int_{\log{c}}^\infty 1/(y\log(y)^p) dy$
and so again, if $p>1$ (and $c$ is not too small), that integral will converge. Similarly we could make an $I_3$, $I_4$ and so on.
So there's an interesting sequence of functions in the right tail* where you have divergence when $p\leq 1$ and convergence for $p>1$.
* $p_0(x) = \frac{1}{x^p}$, $p_1=\frac{1}{x\log(x)^p}$, $p_2=\frac{1}{x\log(x)\log(\log(x))^p}$, $\ldots$
It seems that $g(x)$ can get really close to $x$ for large $x$, since as long as $g(x)\cdot(xp_j(x))$ is bounded and $p>1$ for some $j$, $\int_c^\infty f(x)g(x)dx$ for some sufficiently large $c$ should converge to some finite bound.
In effect, we have a corresponding sequence of $g_j(x)$:
* $g_0(x) = x^{2-p}$, $g_1=\frac{x}{\log(x)^p}$, $g_2=\frac{x}{\log(x)\log(\log(x))^p}$, $g_3=\frac{x}{\log(x)\log(\log(x))\log(\log(\log(x)))^p}$, $\ldots$
for which $\int^\infty_{c_j} \frac{1}{1+x^2}g(x)dx$ will converge if $p>1$ and diverge if $p\leq 1$.
[Of course if $g$ is not bounded at finite $x$ or does something weird at the left hand end, you still have to worry about the rest of the integral.]
I've got a strong feeling I've seen a sequence like this before, so I bet this is a very well-known result.
|
Can we average over a Cauchy random variable?
This started out as a comment (just thinking out loud here), but I got further along than I thought. I haven't read any other answers yet so there's probably some overlap.
[This is clearly not anythin
|
40,377
|
Can anyone provide a peer reviewed reference for the calculation of least squares means as implemented in the R package lsmeans?
|
The history of the least squares mean, its appearance in SAS, and its interpretation is discussed in Searle, Milliken, and Speed (1979).
Some discussion of the concepts around least squares means (population marginal means) is found in Searle, Speed, and Milliken (1980). Earliest mention of the concept that they note is Damon et al (1959). They provide some other references, but I do not have access to the full article.
The initial implementations of the calculation seem to have been worked out explicitly in Harvey (1960) and some subsequent publications, including but probably not limited to Harvey (1977), Goodnight (1979), Harvey (1982), and Goodnight and Harvey (1997).
It looks like the computation routines were first developed as LSML 76 and LSML GP before the user-contributed PROC HARVEY.
References
J.H. Goodnight (1979) A tutorial on the SWEEP operator. The American Statistician 33 (3): 149-159.
J.H. Goodnight and W.R. Harvey (1997) Least squares means in the fixed effects general model. SAS Technical Report R-103. SAS Institute Inc.
W.R. Harvey (1960) Least-squares analysis of data with unequal subclass numbers. USDA National Agricultural Library ARS-20-8.
Harvey, W.R (1977) User's guide for LSML 76. Mixed model least-squares and maximum likelihood computer program. Ohio State Univ., Colarubus (Mimeo).
W.R. Harvey (1982) Mixed model capabilities of LSML76. Journal of Animal Science 54:1279-1285.
S.R. Searle, F.M. Speed, and G.A. Milliken (1980) Population marginal means in the linear model: An alternative to least squares means. The American Statistician 34 (4):216-221.
Searle, S. R., Milliken, G. A., and Speed, F. M. (1979). Expected Marginal Means in the Linear Model. Cornell University Biometrics Unit Technical Reports: Number BU-672-M.
|
Can anyone provide a peer reviewed reference for the calculation of least squares means as implement
|
The history of the least squares mean, its appearance in SAS, and its interpretation is discussed in Searle, Milliken, and Speed (1979).
Some discussion of the concepts around least squares means (pop
|
Can anyone provide a peer reviewed reference for the calculation of least squares means as implemented in the R package lsmeans?
The history of the least squares mean, its appearance in SAS, and its interpretation is discussed in Searle, Milliken, and Speed (1979).
Some discussion of the concepts around least squares means (population marginal means) is found in Searle, Speed, and Milliken (1980). Earliest mention of the concept that they note is Damon et al (1959). They provide some other references, but I do not have access to the full article.
The initial implementations of the calculation seem to have been worked out explicitly in Harvey (1960) and some subsequent publications, including but probably not limited to Harvey (1977), Goodnight (1979), Harvey (1982), and Goodnight and Harvey (1997).
It looks like the computation routines were first developed as LSML 76 and LSML GP before the user-contributed PROC HARVEY.
References
J.H. Goodnight (1979) A tutorial on the SWEEP operator. The American Statistician 33 (3): 149-159.
J.H. Goodnight and W.R. Harvey (1997) Least squares means in the fixed effects general model. SAS Technical Report R-103. SAS Institute Inc.
W.R. Harvey (1960) Least-squares analysis of data with unequal subclass numbers. USDA National Agricultural Library ARS-20-8.
Harvey, W.R (1977) User's guide for LSML 76. Mixed model least-squares and maximum likelihood computer program. Ohio State Univ., Colarubus (Mimeo).
W.R. Harvey (1982) Mixed model capabilities of LSML76. Journal of Animal Science 54:1279-1285.
S.R. Searle, F.M. Speed, and G.A. Milliken (1980) Population marginal means in the linear model: An alternative to least squares means. The American Statistician 34 (4):216-221.
Searle, S. R., Milliken, G. A., and Speed, F. M. (1979). Expected Marginal Means in the Linear Model. Cornell University Biometrics Unit Technical Reports: Number BU-672-M.
|
Can anyone provide a peer reviewed reference for the calculation of least squares means as implement
The history of the least squares mean, its appearance in SAS, and its interpretation is discussed in Searle, Milliken, and Speed (1979).
Some discussion of the concepts around least squares means (pop
|
40,378
|
Sum of truncated normal with two normal distributions
|
I think this is a very nice problem. If I may change notation slightly ...
The Problem
Let $\quad W \sim N(\mu_0, \sigma_0^2), \quad X_1 \sim N(\mu_1, \sigma_1^2), \quad X_2 \sim N(\mu_2, \sigma_2^2)$
denote independent random variables, and let $c$ denote a constant.
Find the pdf of $Z$, where:
$$ Z = \begin{cases}W + X_1 & \text{if } W \leq c \\ W + X_2 & \text{if } W > c \end{cases}$$
Solution
To solve this, we need to solve 2 problems.
Find $h_1(z)$: the pdf of $(W + X_1) \, \big| \, (W \leq c) \quad $ (i.e. truncated-above Normal + Normal)
Find $h_2(z)$: the pdf of $(W + X_2) \, \big| \, (W > c) \quad $ (i.e. truncated-below Normal + Normal)
Then the pdf of $Z$, say $h(z)$, is the component mix:
$$h(z) \, = \, P(W \leq c) * h_1(z) \quad + \quad P(W>c) * h_2(z)$$
Solution: Part 1
$\rightarrow$ The pdf of the sum of a truncated-above Normal and a Normal
If $W$ is truncated ABOVE at $c$, ... then the joint pdf of $(W \big|(W \leq c),X_1)$, say $f_1(w,x_1;c)$, is, by independence, simply the product of the respective individual pdf's ... that is, $f_1(w,x_1;c) = \frac{f_w(w)}{P(W<c)} * f_{x_1}(x_1)$:
Next, transform $(W,X_1) \rightarrow (Z=W+X_1, V=X_1)$. Here is the joint pdf of $(Z, V)$, say $g_1(z,v)$:
where:
I am using the Transform function in the mathStatica package for Mathematica to do the nitty-gritties.
Note that the transformation equation $(Z=W+X_1, V=X_1)$ induces dependency between $Z$ and $V$. In particular, since $Z=V+W$ and $W < c$, it follows that $Z < V + c$. This important constraint is entered using the Boole[ blah ] statement above.
Erf[.] denotes the error function
We seek the marginal pdf of $Z = W + X_1$, say $h_1(z)$, which is:
... defined on the real line. This concludes Part 1.
Solution: Part 2
$\rightarrow$ The pdf of the sum of a truncated-below Normal and a Normal
If $W$ is truncated BELOW at $c$, ... then the joint pdf of $(W \big|(W > c),X_2)$, say $f_2(w,x_2;c)$, is, by independence, simply the product of the respective individual pdf's ... that is, $f_2(w,x_2;c) = \frac{f_w(w)}{P(W>c)} * f_{x_2}(x_2)$:
Next, transform $(W,X_2) \rightarrow (Z=W+X_2, V=X_2)$. Here is the joint pdf of $(Z, V)$, say $g_2(z,v)$:
Note that the transformation equation $(Z=W+X_2, V=X_2)$ induces dependency between $Z$ and $V$. In particular, since $Z=V+W$ and $W > c$, it follows that $Z > V + c$. This important constraint is entered using the Boole[ blah ] statement above.
We seek the marginal pdf of $Z = W + X_2$, say $h_2(z)$, which is:
...defined on the real line. This concludes Part 2.
The Component Mix
All the necessary pieces to the puzzle are now in place. To make this explicit, if $W \sim N(\mu_0, \sigma_0^2)$ with pdf $f(w)$:
... then $P(W<c)$ is:
Recall that the pdf of $Z$ is:
$$h(z) \, = \, P(W \leq c) * h_1(z) \quad + \quad P(W>c) * h_2(z)$$
... which is explicitly:
where $Z$ is defined on the real line. All done.
Monte Carlo check
It is always a good idea to check symbolic work using alternative methods. Here is a quick Monte Carlo check when:
$\text{params}=\left\{\mu _0\to 16,\mu _1\to 3,\mu _2\to 2,\sigma _0\to 6,\sigma _1\to 0.1,\sigma _2\to 2,c\to 12\right\}$
The following plot compares:
a Monte Carlo simulation of the pdf of $Z$ (squiggly BLUE curve) to the
theoretical solution derived above (dashed RED curve)
Looks fine :) Different parameter choices can, of course, yield very different shaped outcomes.
Mean of $Z$
Paulius Šarka asks: "Does the mean of Z have an analytical form"
Yes - it is easiest to derive this from:
$$ Z = \begin{cases}W + X_1 & \text{if } W \leq c \\ W + X_2 & \text{if } W >c\end{cases}$$
... it follows that:
$$E[Z] = P(W \leq c) \big(E[W \big | W \leq c] + \mu_1 \big) \quad + \quad P(W>c)\big(E[W \big | W > c] + \mu_2 \big)$$
which yields the closed-form solution:
$$E[Z] \quad = \quad \mu_0 \, + \, P(W \leq c) \mu_1 \, + \, P(W > c) \mu_2$$
|
Sum of truncated normal with two normal distributions
|
I think this is a very nice problem. If I may change notation slightly ...
The Problem
Let $\quad W \sim N(\mu_0, \sigma_0^2), \quad X_1 \sim N(\mu_1, \sigma_1^2), \quad X_2 \sim N(\mu_2, \sigma_2^2)
|
Sum of truncated normal with two normal distributions
I think this is a very nice problem. If I may change notation slightly ...
The Problem
Let $\quad W \sim N(\mu_0, \sigma_0^2), \quad X_1 \sim N(\mu_1, \sigma_1^2), \quad X_2 \sim N(\mu_2, \sigma_2^2)$
denote independent random variables, and let $c$ denote a constant.
Find the pdf of $Z$, where:
$$ Z = \begin{cases}W + X_1 & \text{if } W \leq c \\ W + X_2 & \text{if } W > c \end{cases}$$
Solution
To solve this, we need to solve 2 problems.
Find $h_1(z)$: the pdf of $(W + X_1) \, \big| \, (W \leq c) \quad $ (i.e. truncated-above Normal + Normal)
Find $h_2(z)$: the pdf of $(W + X_2) \, \big| \, (W > c) \quad $ (i.e. truncated-below Normal + Normal)
Then the pdf of $Z$, say $h(z)$, is the component mix:
$$h(z) \, = \, P(W \leq c) * h_1(z) \quad + \quad P(W>c) * h_2(z)$$
Solution: Part 1
$\rightarrow$ The pdf of the sum of a truncated-above Normal and a Normal
If $W$ is truncated ABOVE at $c$, ... then the joint pdf of $(W \big|(W \leq c),X_1)$, say $f_1(w,x_1;c)$, is, by independence, simply the product of the respective individual pdf's ... that is, $f_1(w,x_1;c) = \frac{f_w(w)}{P(W<c)} * f_{x_1}(x_1)$:
Next, transform $(W,X_1) \rightarrow (Z=W+X_1, V=X_1)$. Here is the joint pdf of $(Z, V)$, say $g_1(z,v)$:
where:
I am using the Transform function in the mathStatica package for Mathematica to do the nitty-gritties.
Note that the transformation equation $(Z=W+X_1, V=X_1)$ induces dependency between $Z$ and $V$. In particular, since $Z=V+W$ and $W < c$, it follows that $Z < V + c$. This important constraint is entered using the Boole[ blah ] statement above.
Erf[.] denotes the error function
We seek the marginal pdf of $Z = W + X_1$, say $h_1(z)$, which is:
... defined on the real line. This concludes Part 1.
Solution: Part 2
$\rightarrow$ The pdf of the sum of a truncated-below Normal and a Normal
If $W$ is truncated BELOW at $c$, ... then the joint pdf of $(W \big|(W > c),X_2)$, say $f_2(w,x_2;c)$, is, by independence, simply the product of the respective individual pdf's ... that is, $f_2(w,x_2;c) = \frac{f_w(w)}{P(W>c)} * f_{x_2}(x_2)$:
Next, transform $(W,X_2) \rightarrow (Z=W+X_2, V=X_2)$. Here is the joint pdf of $(Z, V)$, say $g_2(z,v)$:
Note that the transformation equation $(Z=W+X_2, V=X_2)$ induces dependency between $Z$ and $V$. In particular, since $Z=V+W$ and $W > c$, it follows that $Z > V + c$. This important constraint is entered using the Boole[ blah ] statement above.
We seek the marginal pdf of $Z = W + X_2$, say $h_2(z)$, which is:
...defined on the real line. This concludes Part 2.
The Component Mix
All the necessary pieces to the puzzle are now in place. To make this explicit, if $W \sim N(\mu_0, \sigma_0^2)$ with pdf $f(w)$:
... then $P(W<c)$ is:
Recall that the pdf of $Z$ is:
$$h(z) \, = \, P(W \leq c) * h_1(z) \quad + \quad P(W>c) * h_2(z)$$
... which is explicitly:
where $Z$ is defined on the real line. All done.
Monte Carlo check
It is always a good idea to check symbolic work using alternative methods. Here is a quick Monte Carlo check when:
$\text{params}=\left\{\mu _0\to 16,\mu _1\to 3,\mu _2\to 2,\sigma _0\to 6,\sigma _1\to 0.1,\sigma _2\to 2,c\to 12\right\}$
The following plot compares:
a Monte Carlo simulation of the pdf of $Z$ (squiggly BLUE curve) to the
theoretical solution derived above (dashed RED curve)
Looks fine :) Different parameter choices can, of course, yield very different shaped outcomes.
Mean of $Z$
Paulius Šarka asks: "Does the mean of Z have an analytical form"
Yes - it is easiest to derive this from:
$$ Z = \begin{cases}W + X_1 & \text{if } W \leq c \\ W + X_2 & \text{if } W >c\end{cases}$$
... it follows that:
$$E[Z] = P(W \leq c) \big(E[W \big | W \leq c] + \mu_1 \big) \quad + \quad P(W>c)\big(E[W \big | W > c] + \mu_2 \big)$$
which yields the closed-form solution:
$$E[Z] \quad = \quad \mu_0 \, + \, P(W \leq c) \mu_1 \, + \, P(W > c) \mu_2$$
|
Sum of truncated normal with two normal distributions
I think this is a very nice problem. If I may change notation slightly ...
The Problem
Let $\quad W \sim N(\mu_0, \sigma_0^2), \quad X_1 \sim N(\mu_1, \sigma_1^2), \quad X_2 \sim N(\mu_2, \sigma_2^2)
|
40,379
|
Conditional Expectation Constant
|
Regarding the second part, the answer is yes
$$
E(Z)=E(E(Z|X))=E(k)=k
$$
|
Conditional Expectation Constant
|
Regarding the second part, the answer is yes
$$
E(Z)=E(E(Z|X))=E(k)=k
$$
|
Conditional Expectation Constant
Regarding the second part, the answer is yes
$$
E(Z)=E(E(Z|X))=E(k)=k
$$
|
Conditional Expectation Constant
Regarding the second part, the answer is yes
$$
E(Z)=E(E(Z|X))=E(k)=k
$$
|
40,380
|
If I divide my data by its mean, does it still have a unit?
|
Since the series and the mean are measured in the same units, the ratio is unit-free.
Adding or subtracting two things in the same units leaves you with the sum or difference in the same units again. But ratios are in the ratio of the units.
If the numerator is in dollars and the denominator is in weeks, you have the ratio in units of dollars per week.
Imagine the units in your series were dollars, or people, or nanometers. The mean is in the same units, so the units of the ratio would be dollars per dollar, or people per person or nanometers per nanometer, any of which cancel out - the result is unit-free.
Similarly when dividing by a standard deviation, mean deviation, interquartile range, median absolute deviation from the median, which are all in the original units ... ratios of anything measured in the same units will cancel out to give a unitless result. So coefficient of variation (sd/mean) for example, is dimensionless, as is moment-based skewness (it's a ratio of cubed-units: third central moment / sd^3).
See the wikipedia article relating to dimensionless quantities:
Dimensionless quantities are often defined as products or ratios of quantities that are not dimensionless, but whose dimensions cancel out
Several sub-sections of the Wikipedia article on dimensional analysis are also relevant.
|
If I divide my data by its mean, does it still have a unit?
|
Since the series and the mean are measured in the same units, the ratio is unit-free.
Adding or subtracting two things in the same units leaves you with the sum or difference in the same units again.
|
If I divide my data by its mean, does it still have a unit?
Since the series and the mean are measured in the same units, the ratio is unit-free.
Adding or subtracting two things in the same units leaves you with the sum or difference in the same units again. But ratios are in the ratio of the units.
If the numerator is in dollars and the denominator is in weeks, you have the ratio in units of dollars per week.
Imagine the units in your series were dollars, or people, or nanometers. The mean is in the same units, so the units of the ratio would be dollars per dollar, or people per person or nanometers per nanometer, any of which cancel out - the result is unit-free.
Similarly when dividing by a standard deviation, mean deviation, interquartile range, median absolute deviation from the median, which are all in the original units ... ratios of anything measured in the same units will cancel out to give a unitless result. So coefficient of variation (sd/mean) for example, is dimensionless, as is moment-based skewness (it's a ratio of cubed-units: third central moment / sd^3).
See the wikipedia article relating to dimensionless quantities:
Dimensionless quantities are often defined as products or ratios of quantities that are not dimensionless, but whose dimensions cancel out
Several sub-sections of the Wikipedia article on dimensional analysis are also relevant.
|
If I divide my data by its mean, does it still have a unit?
Since the series and the mean are measured in the same units, the ratio is unit-free.
Adding or subtracting two things in the same units leaves you with the sum or difference in the same units again.
|
40,381
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
|
Although coldmoon's answer is perfectly valid, I would like to propose a slightly different approach:
General gradient expression
First, let's simply restrict our model to be of the form $P_{model}(X) = \frac{f(x; \Theta)}{Z(\Theta)}$ with $f$ a positive parametric function and $Z$ a partition function (=normalizing coefficient).
Main approach (where the likelihood comes from)
The objective is to learn the underlying data distribution. In practice, we
minimize the distance between the model and data distributions according to
the Kullback-Leibler divergence.
Let $\chi$ be the space in which samples lie (eg: ${\{0,1 \}}^{h
\times w}$ for binary images), ${\bf X} \in \chi^N$ a set of N training
samples:
$$
D_{KL}(P_{data}, P_{model})
= \int_{x \in \chi} P_{data}(x) log\left(\frac{P_{data}(x)}{P_{model}(x)}\right) dx
$$
Since the underlying distribution ruling the dataset is unknown,
$P_{data}(x)$ is only known through the samples and cannot be summed
over $\chi$. However, this expression is also the expectation of
$\log\left(\frac{P_{data}(x)}{P_{model}(x)}\right)$, so we approximate
it by an empirical expectation over ${\bf X}$:
$$\begin{align}
D_{KL} (P_{data}, P_{model})
&= \frac{1}{N} \sum_{x \in {\bf X}} \log\left(\frac{P_{data}(x)}{P_{model}(x)}\right) \\
&= \sum_{x \in {\bf X}} \frac{1}{N} \log (\frac{1}{N}) - \sum_{x \in {\bf X}} \frac{1}{N} \log(P_{model} (x)) \quad (\text{iid samples} \rightarrow P_{data}(x) = \frac{1}{N}) \\
&= -\log(N) - \frac{1}{N} \sum_{x \in {\bf X}} \log\left(\frac{f(x, \Theta)}{Z(f,\Theta)}\right) \\
&= -\log(N) + \log(Z(f, \Theta)) - \frac{1}{N} \sum_{x \in {\bf X}} \log(f(x; \Theta)) \end{align}
$$
Gradient for the fitting process
We want to minimize:
$$
D_{KL} (P_{data}, P_{model}) =
-\log(N) + \log(Z(f, \Theta))
- \frac{1}{N} \sum_{x \in {\bf X}} \log(f(x; \Theta))
$$
The derivative of the sum with respect to the model parameters identifies as an
empirical expectation over the training dataset:
$$
\frac{1}{N} \sum_{x \in {\bf X}} \frac{\partial \log(f(x; \Theta))}{\partial \Theta}
= \left< \frac{\partial \log(f(x; \Theta))}{\partial \Theta} \right>_{x \in {\bf X} }
$$
Rewriting the first term's derivative brings another expectation term:
$$\begin{align}
\frac{\partial \log(Z(f; \Theta))}{\partial \Theta}
& = \frac{1}{Z(f, \Theta)}
\frac{\partial Z(f, \Theta)}{\partial \Theta} \\
& = \frac{1}{Z(f, \Theta)}
\frac{\partial }{\partial \Theta} \int_{x \in \chi} f(x,\Theta) dx \\
& = \int_{x \in \chi} \frac{1}{Z(f, \Theta)}
\frac{\partial f(x,\Theta)}{\partial \Theta} dx \\
\end{align}$$
Since $\frac{\partial f}{\partial \Theta} = f \times \frac{\partial
\log(f)}{\partial\Theta}$, it comes that:
$$
\frac{\partial \log(Z(X; \Theta))}{\partial \Theta}
= \int_{x \in \chi} p(x; \Theta)
\frac{\partial \log(f(x;\Theta))}{\partial \Theta} dx
$$
which is a formal expectation on the underlying model distribution usually
written as:
$$
\left<
\frac{\partial \log(f(x; \Theta))}{\partial \Theta}
\right>_{x \sim p(x;\Theta)}
$$
Hence the whole gradient expression:
$$
\Delta\Theta = \left<
\frac{\partial \log(f(x; \Theta))}{\partial \Theta}
\right>_{x \sim p(x;\Theta)}
- \left<
\frac{\partial \log(f(x; \Theta))}{\partial \Theta}
\right>_{x \in {\bf X} }
$$
Application to RBM with binary units
Since the objective is to fit the distribution of the visible units from the RBM, the model distribution $f$ is given by:
$$
p({\bf v}) = \sum_{{\bf \tilde{h}} \in \chi_h} p({\bf v},{\bf \tilde{h}})
= \frac{\sum_{{\bf \tilde{h}} \in \chi_h} f({\bf v},{\bf \tilde{h}},W)}
{Z(f, \Theta)}
$$
By definition, $f({\bf v}, {\bf h}, W) = exp(\sum_{(i,j) \in V} v_i w_{ij} h_j)$. Using the general expression of the gradient above, we now need to
compute:
$$\begin{align}
\frac{\partial \log \left(
\sum_{{\bf \tilde{h}} \in \chi_h}
f({\bf v},{\bf \tilde{h}},W)
\right)}
{\partial w_{ij}}
&= \frac{1}{ \sum_{{\bf \tilde{h}} \in \chi_h} f({\bf v},{\bf \tilde{h}},W) }
\sum_{{\bf \tilde{h}} \in \chi_h}
\frac{\partial f({\bf v},{\bf \tilde{h}}, W)}
{\partial w_{ij}}
\end{align}$$
for the sake of readability, I now abbreviate the sum indexes:
$$\begin{align}
&= \frac{1}{ Z \times p({\bf v}) }
\sum_{{\bf \tilde{h}}}
\frac{\partial}{\partial w_{ij}}
exp(\sum_{(i,j) \in V} v_i w_{ij} \tilde{h}_j)\\
&= \frac{1}{ Z \times p({\bf v}) }
\sum_{{\bf \tilde{h}}} f({\bf v},{\bf \tilde{h}},W) v_i \tilde{h}_j
= \frac{v_i}{p({\bf v})}
\sum_{{\bf \tilde{h}}} p({\bf v}, {\bf \tilde{h}}) \tilde{h}_j\\
&= \frac{v_i}{p({\bf v})}
\sum_{{\bf \tilde{h}}} \tilde{h}_j p({\bf v}, \tilde{h}_j) p({\bf \tilde{h}}^{-j} | {\bf v}, \tilde{h}_j)
\end{align}$$
Using a proper decomposition of the sum, it is possible to factor and cancel
the states of hidden units other than $h_j$, which I designate by
${\bf \tilde{h}}^{-j}$:
$$\begin{align}
&= \frac{v_i}{p({\bf v})}
\sum_{\tilde{h_j}} \tilde{h}_jp({\bf v}, h_j)
\sum_{{\bf \tilde{h}}^{-j}} p({\bf \tilde{h}}^{-j} | {\bf v}, \tilde{h}_j) \\
&= \frac{v_i}{p({\bf v})}
\sum_{\tilde{h_j}} \tilde{h}_jp(\tilde{h}_j| {\bf v}) p({\bf v})
= \sum_{\tilde{h_j}} v_i \tilde{h}_j p(\tilde{h}_j| {\bf v}) \\
&= v_i E_{{\bf v}}[h_j]
\end{align}$$
Consequently, the model expectation is given by (hang on :-) ):
$$\begin{align}
\left< v_i E_{{\bf v}}\left[h_j\right]) \right>_{{\bf v} \sim p({\bf v})}
&= \sum_{{\bf v}} p({\bf v}) \sum_{\tilde{h_j}} v_i \tilde{h}_j p(\tilde{h}_j| {\bf v}) \\
&= \sum_{{\bf v}} \sum_{\tilde{h_j}} v_i \tilde{h}_j p(\tilde{h}_j, {\bf v}) \\
&= \sum_{v_i} \sum_{\tilde{h_j}} v_i \tilde{h}_j \sum_{{\bf v}^{-i}}p(\tilde{h}_j, v_i, {\bf v^{-i}}) \\
&= \left< v_i h_j \right>_{v_i, h_j \sim p({\bf v}, {\bf h})}
\end{align}$$
And finally, the whole gradient comes as:
$$
\Delta W_{ij}
= \left< v_i h_j \right>_{v_i, h_j \sim p({\bf v}, {\bf h})}
- \left< v_i E_{{\bf v}}\left[h_j\right] \right>_{{\bf v} \in X}
\qquad \forall (i,j) \in V
$$
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
|
Although coldmoon's answer is perfectly valid, I would like to propose a slightly different approach:
General gradient expression
First, let's simply restrict our model to be of the form $P_{model}(X)
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
Although coldmoon's answer is perfectly valid, I would like to propose a slightly different approach:
General gradient expression
First, let's simply restrict our model to be of the form $P_{model}(X) = \frac{f(x; \Theta)}{Z(\Theta)}$ with $f$ a positive parametric function and $Z$ a partition function (=normalizing coefficient).
Main approach (where the likelihood comes from)
The objective is to learn the underlying data distribution. In practice, we
minimize the distance between the model and data distributions according to
the Kullback-Leibler divergence.
Let $\chi$ be the space in which samples lie (eg: ${\{0,1 \}}^{h
\times w}$ for binary images), ${\bf X} \in \chi^N$ a set of N training
samples:
$$
D_{KL}(P_{data}, P_{model})
= \int_{x \in \chi} P_{data}(x) log\left(\frac{P_{data}(x)}{P_{model}(x)}\right) dx
$$
Since the underlying distribution ruling the dataset is unknown,
$P_{data}(x)$ is only known through the samples and cannot be summed
over $\chi$. However, this expression is also the expectation of
$\log\left(\frac{P_{data}(x)}{P_{model}(x)}\right)$, so we approximate
it by an empirical expectation over ${\bf X}$:
$$\begin{align}
D_{KL} (P_{data}, P_{model})
&= \frac{1}{N} \sum_{x \in {\bf X}} \log\left(\frac{P_{data}(x)}{P_{model}(x)}\right) \\
&= \sum_{x \in {\bf X}} \frac{1}{N} \log (\frac{1}{N}) - \sum_{x \in {\bf X}} \frac{1}{N} \log(P_{model} (x)) \quad (\text{iid samples} \rightarrow P_{data}(x) = \frac{1}{N}) \\
&= -\log(N) - \frac{1}{N} \sum_{x \in {\bf X}} \log\left(\frac{f(x, \Theta)}{Z(f,\Theta)}\right) \\
&= -\log(N) + \log(Z(f, \Theta)) - \frac{1}{N} \sum_{x \in {\bf X}} \log(f(x; \Theta)) \end{align}
$$
Gradient for the fitting process
We want to minimize:
$$
D_{KL} (P_{data}, P_{model}) =
-\log(N) + \log(Z(f, \Theta))
- \frac{1}{N} \sum_{x \in {\bf X}} \log(f(x; \Theta))
$$
The derivative of the sum with respect to the model parameters identifies as an
empirical expectation over the training dataset:
$$
\frac{1}{N} \sum_{x \in {\bf X}} \frac{\partial \log(f(x; \Theta))}{\partial \Theta}
= \left< \frac{\partial \log(f(x; \Theta))}{\partial \Theta} \right>_{x \in {\bf X} }
$$
Rewriting the first term's derivative brings another expectation term:
$$\begin{align}
\frac{\partial \log(Z(f; \Theta))}{\partial \Theta}
& = \frac{1}{Z(f, \Theta)}
\frac{\partial Z(f, \Theta)}{\partial \Theta} \\
& = \frac{1}{Z(f, \Theta)}
\frac{\partial }{\partial \Theta} \int_{x \in \chi} f(x,\Theta) dx \\
& = \int_{x \in \chi} \frac{1}{Z(f, \Theta)}
\frac{\partial f(x,\Theta)}{\partial \Theta} dx \\
\end{align}$$
Since $\frac{\partial f}{\partial \Theta} = f \times \frac{\partial
\log(f)}{\partial\Theta}$, it comes that:
$$
\frac{\partial \log(Z(X; \Theta))}{\partial \Theta}
= \int_{x \in \chi} p(x; \Theta)
\frac{\partial \log(f(x;\Theta))}{\partial \Theta} dx
$$
which is a formal expectation on the underlying model distribution usually
written as:
$$
\left<
\frac{\partial \log(f(x; \Theta))}{\partial \Theta}
\right>_{x \sim p(x;\Theta)}
$$
Hence the whole gradient expression:
$$
\Delta\Theta = \left<
\frac{\partial \log(f(x; \Theta))}{\partial \Theta}
\right>_{x \sim p(x;\Theta)}
- \left<
\frac{\partial \log(f(x; \Theta))}{\partial \Theta}
\right>_{x \in {\bf X} }
$$
Application to RBM with binary units
Since the objective is to fit the distribution of the visible units from the RBM, the model distribution $f$ is given by:
$$
p({\bf v}) = \sum_{{\bf \tilde{h}} \in \chi_h} p({\bf v},{\bf \tilde{h}})
= \frac{\sum_{{\bf \tilde{h}} \in \chi_h} f({\bf v},{\bf \tilde{h}},W)}
{Z(f, \Theta)}
$$
By definition, $f({\bf v}, {\bf h}, W) = exp(\sum_{(i,j) \in V} v_i w_{ij} h_j)$. Using the general expression of the gradient above, we now need to
compute:
$$\begin{align}
\frac{\partial \log \left(
\sum_{{\bf \tilde{h}} \in \chi_h}
f({\bf v},{\bf \tilde{h}},W)
\right)}
{\partial w_{ij}}
&= \frac{1}{ \sum_{{\bf \tilde{h}} \in \chi_h} f({\bf v},{\bf \tilde{h}},W) }
\sum_{{\bf \tilde{h}} \in \chi_h}
\frac{\partial f({\bf v},{\bf \tilde{h}}, W)}
{\partial w_{ij}}
\end{align}$$
for the sake of readability, I now abbreviate the sum indexes:
$$\begin{align}
&= \frac{1}{ Z \times p({\bf v}) }
\sum_{{\bf \tilde{h}}}
\frac{\partial}{\partial w_{ij}}
exp(\sum_{(i,j) \in V} v_i w_{ij} \tilde{h}_j)\\
&= \frac{1}{ Z \times p({\bf v}) }
\sum_{{\bf \tilde{h}}} f({\bf v},{\bf \tilde{h}},W) v_i \tilde{h}_j
= \frac{v_i}{p({\bf v})}
\sum_{{\bf \tilde{h}}} p({\bf v}, {\bf \tilde{h}}) \tilde{h}_j\\
&= \frac{v_i}{p({\bf v})}
\sum_{{\bf \tilde{h}}} \tilde{h}_j p({\bf v}, \tilde{h}_j) p({\bf \tilde{h}}^{-j} | {\bf v}, \tilde{h}_j)
\end{align}$$
Using a proper decomposition of the sum, it is possible to factor and cancel
the states of hidden units other than $h_j$, which I designate by
${\bf \tilde{h}}^{-j}$:
$$\begin{align}
&= \frac{v_i}{p({\bf v})}
\sum_{\tilde{h_j}} \tilde{h}_jp({\bf v}, h_j)
\sum_{{\bf \tilde{h}}^{-j}} p({\bf \tilde{h}}^{-j} | {\bf v}, \tilde{h}_j) \\
&= \frac{v_i}{p({\bf v})}
\sum_{\tilde{h_j}} \tilde{h}_jp(\tilde{h}_j| {\bf v}) p({\bf v})
= \sum_{\tilde{h_j}} v_i \tilde{h}_j p(\tilde{h}_j| {\bf v}) \\
&= v_i E_{{\bf v}}[h_j]
\end{align}$$
Consequently, the model expectation is given by (hang on :-) ):
$$\begin{align}
\left< v_i E_{{\bf v}}\left[h_j\right]) \right>_{{\bf v} \sim p({\bf v})}
&= \sum_{{\bf v}} p({\bf v}) \sum_{\tilde{h_j}} v_i \tilde{h}_j p(\tilde{h}_j| {\bf v}) \\
&= \sum_{{\bf v}} \sum_{\tilde{h_j}} v_i \tilde{h}_j p(\tilde{h}_j, {\bf v}) \\
&= \sum_{v_i} \sum_{\tilde{h_j}} v_i \tilde{h}_j \sum_{{\bf v}^{-i}}p(\tilde{h}_j, v_i, {\bf v^{-i}}) \\
&= \left< v_i h_j \right>_{v_i, h_j \sim p({\bf v}, {\bf h})}
\end{align}$$
And finally, the whole gradient comes as:
$$
\Delta W_{ij}
= \left< v_i h_j \right>_{v_i, h_j \sim p({\bf v}, {\bf h})}
- \left< v_i E_{{\bf v}}\left[h_j\right] \right>_{{\bf v} \in X}
\qquad \forall (i,j) \in V
$$
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
Although coldmoon's answer is perfectly valid, I would like to propose a slightly different approach:
General gradient expression
First, let's simply restrict our model to be of the form $P_{model}(X)
|
40,382
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
|
S represents all of samples you collect. Suppose that we consider only one sample and the red "v" represents the sample:
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
|
S represents all of samples you collect. Suppose that we consider only one sample and the red "v" represents the sample:
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
S represents all of samples you collect. Suppose that we consider only one sample and the red "v" represents the sample:
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
S represents all of samples you collect. Suppose that we consider only one sample and the red "v" represents the sample:
|
40,383
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I have the same problem. Refer to this book page 567 and problem 11.8
Simon Haykin. 1998. Neural Networks: A Comprehensive Foundation (2nd ed.). Prentice Hall PTR, Upper Saddle River, NJ, USA.
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
|
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
I have the same problem. Refer to this book page 567 and problem 11.8
Simon Haykin. 1998. Neural Networks: A Comprehensive Foundation (2nd ed.). Prentice Hall PTR, Upper Saddle River, NJ, USA.
|
How to derive the gradient formula for the Maximum Likelihood in RBM?
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
|
40,384
|
Can neural net extrapolate output value
|
More generally an output neuron of a feed-forward neural net is defined as $f(\sum \Theta_i a_i)$, where $f$ is the link function of the output neuron (which was the identity function in your question) and the other notations are as in your question. The activation values of the neurons of the previous layer $a_i$ depend on the choice of their own link function (say $g$) and of the activation values of the layer before that.
You are right when you say that if all the link functions $g$ in the previous layer are bounded, then the network's output values will be bounded too, even if $f$ is identity. (There was a small confusion however, the logistic link is bounded in $(0,1)$, the hyperbolic tangent is bounded in $(-1,1)$.)
Setting all link functions ($g$ and $f$) of the network to the identity function might seem like a good idea in order to allow extrapolation outside the observed response values in the training set, but that special case of feedforward neural networks is in fact just a linear regression model, in which case you don't need the neural net framework at all!
A better solution would be to use unbounded but non-linear link functions for g, like a rectifier $g(x)= max(0, x)$. This keeps the nice "universal approximation" property of the neural net, but with unbounded outputs.
Beware, however, prediction will be less good in regions of the data that were not present in the training data. You should probably use regularization to prevent over-fitting and (hopefully) improve extrapolating prediction power.
|
Can neural net extrapolate output value
|
More generally an output neuron of a feed-forward neural net is defined as $f(\sum \Theta_i a_i)$, where $f$ is the link function of the output neuron (which was the identity function in your question
|
Can neural net extrapolate output value
More generally an output neuron of a feed-forward neural net is defined as $f(\sum \Theta_i a_i)$, where $f$ is the link function of the output neuron (which was the identity function in your question) and the other notations are as in your question. The activation values of the neurons of the previous layer $a_i$ depend on the choice of their own link function (say $g$) and of the activation values of the layer before that.
You are right when you say that if all the link functions $g$ in the previous layer are bounded, then the network's output values will be bounded too, even if $f$ is identity. (There was a small confusion however, the logistic link is bounded in $(0,1)$, the hyperbolic tangent is bounded in $(-1,1)$.)
Setting all link functions ($g$ and $f$) of the network to the identity function might seem like a good idea in order to allow extrapolation outside the observed response values in the training set, but that special case of feedforward neural networks is in fact just a linear regression model, in which case you don't need the neural net framework at all!
A better solution would be to use unbounded but non-linear link functions for g, like a rectifier $g(x)= max(0, x)$. This keeps the nice "universal approximation" property of the neural net, but with unbounded outputs.
Beware, however, prediction will be less good in regions of the data that were not present in the training data. You should probably use regularization to prevent over-fitting and (hopefully) improve extrapolating prediction power.
|
Can neural net extrapolate output value
More generally an output neuron of a feed-forward neural net is defined as $f(\sum \Theta_i a_i)$, where $f$ is the link function of the output neuron (which was the identity function in your question
|
40,385
|
Logistic regression and error terms
|
There are many kinds of residuals. This is true of linear regression (e.g., raw, studentized, standardized, etc.), but is even more true of logistic regression. R has options available for retrieving 5 different types of residuals from a logistic regression fit (see ?residuals.glm: type = c("deviance", "pearson", "working", "response", "partial").
You are right that the response variable in a logistic regression can take on only $0$ and $1$, and that logistic regression's predicted values $\hat Y$ can take on any real value within $(0, 1)$. However, that implies that raw residuals, $\hat y_i - y_i$, will take on real values within the interval $(0, 1)$ as well. Moreover, they can take on many different values unless the $X$ values are limited to a few discrete levels and/or the response is completely unrelated to $X$, not only in the population, but in your sample.
These facts pertain to raw residuals, though, which are basically not used by anyone.
The most common residuals to examine in logistic regression are deviance residuals. Their calculation is very hard to understand (it is listed in the link @whuber gave), but they can be roughly normally distributed with sufficient variability in $X$. Below, I do a simple demonstration in R to show the deviance residuals from an experimental situation with two groups and an observational situation where $X$ is uniformly distributed.
lo.2.p = function(lo){ # this function will convert log odds to
o = exp(lo) # probabilities
p = o/(o+1)
return(p)
}
set.seed(9044) # this makes the example exactly reproducible
x.e = rep(c(0, 20), each=20) # in the experimental case, there are 2 groups
x.o = runif(40, min=-20, max=20) # for observational, X is uniform
p.e = lo.2.p(-.2 + .3*x.e) # on the log odds scale, the intercept is -.2,
p.o = lo.2.p(-.2 + .3*x.o) # & the slope is .3
y.e = rbinom(40, size=1, prob=p.e) # this generates the response data
y.o = rbinom(40, size=1, prob=p.o)
mod.e = glm(y.e~x.e) # here I fit the 2 models
mod.o = glm(y.o~x.o)
|
Logistic regression and error terms
|
There are many kinds of residuals. This is true of linear regression (e.g., raw, studentized, standardized, etc.), but is even more true of logistic regression. R has options available for retrievin
|
Logistic regression and error terms
There are many kinds of residuals. This is true of linear regression (e.g., raw, studentized, standardized, etc.), but is even more true of logistic regression. R has options available for retrieving 5 different types of residuals from a logistic regression fit (see ?residuals.glm: type = c("deviance", "pearson", "working", "response", "partial").
You are right that the response variable in a logistic regression can take on only $0$ and $1$, and that logistic regression's predicted values $\hat Y$ can take on any real value within $(0, 1)$. However, that implies that raw residuals, $\hat y_i - y_i$, will take on real values within the interval $(0, 1)$ as well. Moreover, they can take on many different values unless the $X$ values are limited to a few discrete levels and/or the response is completely unrelated to $X$, not only in the population, but in your sample.
These facts pertain to raw residuals, though, which are basically not used by anyone.
The most common residuals to examine in logistic regression are deviance residuals. Their calculation is very hard to understand (it is listed in the link @whuber gave), but they can be roughly normally distributed with sufficient variability in $X$. Below, I do a simple demonstration in R to show the deviance residuals from an experimental situation with two groups and an observational situation where $X$ is uniformly distributed.
lo.2.p = function(lo){ # this function will convert log odds to
o = exp(lo) # probabilities
p = o/(o+1)
return(p)
}
set.seed(9044) # this makes the example exactly reproducible
x.e = rep(c(0, 20), each=20) # in the experimental case, there are 2 groups
x.o = runif(40, min=-20, max=20) # for observational, X is uniform
p.e = lo.2.p(-.2 + .3*x.e) # on the log odds scale, the intercept is -.2,
p.o = lo.2.p(-.2 + .3*x.o) # & the slope is .3
y.e = rbinom(40, size=1, prob=p.e) # this generates the response data
y.o = rbinom(40, size=1, prob=p.o)
mod.e = glm(y.e~x.e) # here I fit the 2 models
mod.o = glm(y.o~x.o)
|
Logistic regression and error terms
There are many kinds of residuals. This is true of linear regression (e.g., raw, studentized, standardized, etc.), but is even more true of logistic regression. R has options available for retrievin
|
40,386
|
Logistic regression and error terms
|
There are no error terms in logistic regression. And in my opinion the only residuals that are useful are partial residuals useful for checking departures from the assumed shape of regression effects. But even that can be dealt with more directly using regression splines in the first place. There are no intrinsic residuals for the model.
|
Logistic regression and error terms
|
There are no error terms in logistic regression. And in my opinion the only residuals that are useful are partial residuals useful for checking departures from the assumed shape of regression effects
|
Logistic regression and error terms
There are no error terms in logistic regression. And in my opinion the only residuals that are useful are partial residuals useful for checking departures from the assumed shape of regression effects. But even that can be dealt with more directly using regression splines in the first place. There are no intrinsic residuals for the model.
|
Logistic regression and error terms
There are no error terms in logistic regression. And in my opinion the only residuals that are useful are partial residuals useful for checking departures from the assumed shape of regression effects
|
40,387
|
Faith in an extrapolated result
|
Answering your edited question.
Take the simplest regression possible:
$\text{Netflow} \sim\alpha + \epsilon$
Intercept only. The $\alpha$ will be your average daily netflow.
Now, let's say that you want to know when will the data storage fill up? Simulate. Data storage will follow this formula:
$Y_{t+1} \sim Y_t + \alpha + \epsilon_t$
You can simulate a path that your data storage will follow by sampling a bunch of $\epsilon$ (either assuming they are normal or resampling bootstrap-like from the residuals).
Simulate a 1000 paths. Each of them will have a simulated day of when the storage is full. Use this distribution of days to manage the overfilling risk. You can also update this distibution daily by redoing regression and simulation as more data comes up.
|
Faith in an extrapolated result
|
Answering your edited question.
Take the simplest regression possible:
$\text{Netflow} \sim\alpha + \epsilon$
Intercept only. The $\alpha$ will be your average daily netflow.
Now, let's say that you w
|
Faith in an extrapolated result
Answering your edited question.
Take the simplest regression possible:
$\text{Netflow} \sim\alpha + \epsilon$
Intercept only. The $\alpha$ will be your average daily netflow.
Now, let's say that you want to know when will the data storage fill up? Simulate. Data storage will follow this formula:
$Y_{t+1} \sim Y_t + \alpha + \epsilon_t$
You can simulate a path that your data storage will follow by sampling a bunch of $\epsilon$ (either assuming they are normal or resampling bootstrap-like from the residuals).
Simulate a 1000 paths. Each of them will have a simulated day of when the storage is full. Use this distribution of days to manage the overfilling risk. You can also update this distibution daily by redoing regression and simulation as more data comes up.
|
Faith in an extrapolated result
Answering your edited question.
Take the simplest regression possible:
$\text{Netflow} \sim\alpha + \epsilon$
Intercept only. The $\alpha$ will be your average daily netflow.
Now, let's say that you w
|
40,388
|
Faith in an extrapolated result
|
To expand on my comments, a typical simple "level of dam" or "level of tank" type model might produce results that look vaguely something like this, say:
It's not really appropriate to fit a linear regression to this kind of process, for a variety of reasons (not least, dependence and barrier effects). You need a model that more reasonably describes the process, and will measure the uncertanties appropriately.
I wouldn't have much faith in the predictions of a model that really doesn't describe what's going on. With a good model, you can at least use simulation to get some idea of when the tank may be full or unlikely to be full.
Stochastic models of this kind are included under stochastic fluid models, what used to be called 'dam models', but they're also used in computing-related applications and ruin theory in insurance. The books on ruin theory that don't necessarily make much reference to the other literature. In ruin theory the process is "flipped" relative to a dam-type model - increases are continuous and close to linear over time (premiums), and the decreases are jumps (claims); for dam models the jumps are increases and decreases more continuous.
There are more than 40 references at the wikipedia page linked above.
Books on stochastic processes (of which there are many) often have some basic models of this type.
More sophisticated models take into account more of the details, like dependence in increases and decreases and variation over time; the more complex models aren't usually nice algebraically and generally have to be simulated.
|
Faith in an extrapolated result
|
To expand on my comments, a typical simple "level of dam" or "level of tank" type model might produce results that look vaguely something like this, say:
It's not really appropriate to fit a linear r
|
Faith in an extrapolated result
To expand on my comments, a typical simple "level of dam" or "level of tank" type model might produce results that look vaguely something like this, say:
It's not really appropriate to fit a linear regression to this kind of process, for a variety of reasons (not least, dependence and barrier effects). You need a model that more reasonably describes the process, and will measure the uncertanties appropriately.
I wouldn't have much faith in the predictions of a model that really doesn't describe what's going on. With a good model, you can at least use simulation to get some idea of when the tank may be full or unlikely to be full.
Stochastic models of this kind are included under stochastic fluid models, what used to be called 'dam models', but they're also used in computing-related applications and ruin theory in insurance. The books on ruin theory that don't necessarily make much reference to the other literature. In ruin theory the process is "flipped" relative to a dam-type model - increases are continuous and close to linear over time (premiums), and the decreases are jumps (claims); for dam models the jumps are increases and decreases more continuous.
There are more than 40 references at the wikipedia page linked above.
Books on stochastic processes (of which there are many) often have some basic models of this type.
More sophisticated models take into account more of the details, like dependence in increases and decreases and variation over time; the more complex models aren't usually nice algebraically and generally have to be simulated.
|
Faith in an extrapolated result
To expand on my comments, a typical simple "level of dam" or "level of tank" type model might produce results that look vaguely something like this, say:
It's not really appropriate to fit a linear r
|
40,389
|
Residual plot for nonlinear regression
|
Are the residuals from a nonlinear regression model supposed to be randomly distributed too (as in linear regression)?
Yes. The error term is the same and the residuals represent estimated errors. The fitting of the model will induce some structure among the residuals, and that won't be identical in form for a nonlinear model as it is for a linear model but taking a Taylor approximation to first order, the nonlinear model is approximated by a linear model, so as long as a first order Taylor approximation is reasonable, even that structure will tend to be similar to that of a linear model near the optimum.
2. I am comparing two nonlinear regression models (non-nested). What model performance indicators can I use for the purpose? My understanding was to compare RSS, RSE, residual plots, autocorrelation and residual normality plots.
You can compare two different models fitted to the same data using those things, but what you should look at depends on what kind of performance matters for your present purpose.
Note that when you compare RSS, more parameters will tend to make the RSS smaller; you can't really compare them for models with different degrees of freedom. Similarly with MSE or RMSE. (You might better compare AIC or BIC instead, but I wouldn't use them as the basis for model selection - you need to properly account for out of sample error or you'll end up with the usual problems from doing model selection using the same data you measure model performance on)
3. The models have different Y axis.
If the response variable isn't the same, you can't really compare the models.
So I tried standardizing variables and then re-estimated RSS, RSE. Is that the right approach?
The right approach to achieve what exactly?
|
Residual plot for nonlinear regression
|
Are the residuals from a nonlinear regression model supposed to be randomly distributed too (as in linear regression)?
Yes. The error term is the same and the residuals represent estimated errors.
|
Residual plot for nonlinear regression
Are the residuals from a nonlinear regression model supposed to be randomly distributed too (as in linear regression)?
Yes. The error term is the same and the residuals represent estimated errors. The fitting of the model will induce some structure among the residuals, and that won't be identical in form for a nonlinear model as it is for a linear model but taking a Taylor approximation to first order, the nonlinear model is approximated by a linear model, so as long as a first order Taylor approximation is reasonable, even that structure will tend to be similar to that of a linear model near the optimum.
2. I am comparing two nonlinear regression models (non-nested). What model performance indicators can I use for the purpose? My understanding was to compare RSS, RSE, residual plots, autocorrelation and residual normality plots.
You can compare two different models fitted to the same data using those things, but what you should look at depends on what kind of performance matters for your present purpose.
Note that when you compare RSS, more parameters will tend to make the RSS smaller; you can't really compare them for models with different degrees of freedom. Similarly with MSE or RMSE. (You might better compare AIC or BIC instead, but I wouldn't use them as the basis for model selection - you need to properly account for out of sample error or you'll end up with the usual problems from doing model selection using the same data you measure model performance on)
3. The models have different Y axis.
If the response variable isn't the same, you can't really compare the models.
So I tried standardizing variables and then re-estimated RSS, RSE. Is that the right approach?
The right approach to achieve what exactly?
|
Residual plot for nonlinear regression
Are the residuals from a nonlinear regression model supposed to be randomly distributed too (as in linear regression)?
Yes. The error term is the same and the residuals represent estimated errors.
|
40,390
|
Bayesian alternative or complement to the Student t-test
|
Two come to mind.
Morey and Rouder present "Bayesian t tests for accepting and rejecting the null hypothesis". The reference paper is here, there is a handy web interface, and an R package. There are also equivalent programs for ANOVA and correlation.
John Kruschke claims that "Bayesian estimation supersedes the t test" ("BEST"). The reference paper is here, a web app by Rasmus Bååth here, and of course an R package. For more, see the web page, including a Python implementation. Rasmus Bååth has implemented a range of further tests in this tradition, but also provides a very readable explanation of BEST.
The primary difference between the two, BEST and Rouder/Morey's test, is that Morey and Rouder present their approach explicitly in the tradition of hypothesis testing, whereas BEST is parameter estimation. Under the hood, the two are not too dissimilar - default priors, MCMC sampling - but the outpood is quite different; the first gives you the Bayes Factors for or against your hypothesis, the other focuses the graphical presentation on the credible interval for the estimated parameter.
|
Bayesian alternative or complement to the Student t-test
|
Two come to mind.
Morey and Rouder present "Bayesian t tests for accepting and rejecting the null hypothesis". The reference paper is here, there is a handy web interface, and an R package. There are
|
Bayesian alternative or complement to the Student t-test
Two come to mind.
Morey and Rouder present "Bayesian t tests for accepting and rejecting the null hypothesis". The reference paper is here, there is a handy web interface, and an R package. There are also equivalent programs for ANOVA and correlation.
John Kruschke claims that "Bayesian estimation supersedes the t test" ("BEST"). The reference paper is here, a web app by Rasmus Bååth here, and of course an R package. For more, see the web page, including a Python implementation. Rasmus Bååth has implemented a range of further tests in this tradition, but also provides a very readable explanation of BEST.
The primary difference between the two, BEST and Rouder/Morey's test, is that Morey and Rouder present their approach explicitly in the tradition of hypothesis testing, whereas BEST is parameter estimation. Under the hood, the two are not too dissimilar - default priors, MCMC sampling - but the outpood is quite different; the first gives you the Bayes Factors for or against your hypothesis, the other focuses the graphical presentation on the credible interval for the estimated parameter.
|
Bayesian alternative or complement to the Student t-test
Two come to mind.
Morey and Rouder present "Bayesian t tests for accepting and rejecting the null hypothesis". The reference paper is here, there is a handy web interface, and an R package. There are
|
40,391
|
Entropy and information content
|
Based on your phrasing, it seems you are equating thermodynamic entropy with information entropy. The concepts are related, but you have to be careful because they are used differently in the two fields.
Shannon entropy measures unpredictability. You are correct that entropy is maximum when the outcome is the most uncertain. An unbiased coin has maximum entropy (among coins), while a coin that comes up Heads with probability 0.9 has less entropy. Contrary to your next statement, however, max entropy = maximum information content.
Suppose we flip a coin 20 times. If the coin is unbiased, the sequence might look like this:
TTHTHHTTHHTHHTHTHTTH
If the coin comes up Heads with probability 0.9, it might look more like this:
HHHHHHHHHHTHHHHHHTHH
The second signal contains less information. Suppose we encode it using run length encoding, like this:
10T6T2
which we interpret as "10 heads, then 1 tail, then 6 heads, then a tail, then 2 heads". Compare this to the same encoding method applied to the first signal:
TT1T2TT2T2T1T1TT1
We can't compress the signal from the maximum entropy coin as much, because it contains more information.
As for your specific questions:
A thermodynamic system in equilibrium has maximum entropy in the sense that its microstate is maximally uncertain given its macrostate (e.g. its temperature, pressure, etc). From our perspective as observers, this means that our knowledge of its microstate is less certain than when it was not in equilibrium. But the system in equilibrium contains more information because its microstate is maximally unpredictable. The quantity that has decreased is the mutual information between the macrostate and the microstate. This is the sense in which we "lose (mutual) information" when entropy increases. The loss is relative to the observer.
As long as the process is random, each new symbol adds information to the sequence. The symbols are random variables, so each one has a distribution for which we can calculate entropy. The information content of the sequence is measured with joint entropy.
|
Entropy and information content
|
Based on your phrasing, it seems you are equating thermodynamic entropy with information entropy. The concepts are related, but you have to be careful because they are used differently in the two fiel
|
Entropy and information content
Based on your phrasing, it seems you are equating thermodynamic entropy with information entropy. The concepts are related, but you have to be careful because they are used differently in the two fields.
Shannon entropy measures unpredictability. You are correct that entropy is maximum when the outcome is the most uncertain. An unbiased coin has maximum entropy (among coins), while a coin that comes up Heads with probability 0.9 has less entropy. Contrary to your next statement, however, max entropy = maximum information content.
Suppose we flip a coin 20 times. If the coin is unbiased, the sequence might look like this:
TTHTHHTTHHTHHTHTHTTH
If the coin comes up Heads with probability 0.9, it might look more like this:
HHHHHHHHHHTHHHHHHTHH
The second signal contains less information. Suppose we encode it using run length encoding, like this:
10T6T2
which we interpret as "10 heads, then 1 tail, then 6 heads, then a tail, then 2 heads". Compare this to the same encoding method applied to the first signal:
TT1T2TT2T2T1T1TT1
We can't compress the signal from the maximum entropy coin as much, because it contains more information.
As for your specific questions:
A thermodynamic system in equilibrium has maximum entropy in the sense that its microstate is maximally uncertain given its macrostate (e.g. its temperature, pressure, etc). From our perspective as observers, this means that our knowledge of its microstate is less certain than when it was not in equilibrium. But the system in equilibrium contains more information because its microstate is maximally unpredictable. The quantity that has decreased is the mutual information between the macrostate and the microstate. This is the sense in which we "lose (mutual) information" when entropy increases. The loss is relative to the observer.
As long as the process is random, each new symbol adds information to the sequence. The symbols are random variables, so each one has a distribution for which we can calculate entropy. The information content of the sequence is measured with joint entropy.
|
Entropy and information content
Based on your phrasing, it seems you are equating thermodynamic entropy with information entropy. The concepts are related, but you have to be careful because they are used differently in the two fiel
|
40,392
|
Entropy and information content
|
So, would this imply that Max Entropy = minimum information?
No, max entropy means the event you have observed conveys the max information. If an event happens with equal probability of each possibility you have no any idear what to expect, then the outcome of an event tells you the most information. But when you are very certain for something the outcome if it can only contain very limited information. And the average information you get from all the events is what the entropy measures.
|
Entropy and information content
|
So, would this imply that Max Entropy = minimum information?
No, max entropy means the event you have observed conveys the max information. If an event happens with equal probability of each possibil
|
Entropy and information content
So, would this imply that Max Entropy = minimum information?
No, max entropy means the event you have observed conveys the max information. If an event happens with equal probability of each possibility you have no any idear what to expect, then the outcome of an event tells you the most information. But when you are very certain for something the outcome if it can only contain very limited information. And the average information you get from all the events is what the entropy measures.
|
Entropy and information content
So, would this imply that Max Entropy = minimum information?
No, max entropy means the event you have observed conveys the max information. If an event happens with equal probability of each possibil
|
40,393
|
Conjugate mixture of beta distributions - weights
|
Assuming you meant a binomial likelihood,
$$
\begin{eqnarray*}
\text{Posterior}(\theta) & \propto & \text{Likelihood}(\theta) \times \text{Prior}(\theta) \\ \\
& = & \text{Binomial}(20 \mid 30, \theta) \times \bigg[ \lambda \times \text{Beta}(\theta \mid 20,10) + (1-\lambda) \times \text{Beta}(\theta \mid 20, 20) \bigg] \\ \\
& = & \lambda \times \text{Binomial}(20 \mid 30, \theta) \times \text{Beta}(\theta \mid 20,10) \\[8pt]
&&+ (1 - \lambda) \times \text{Binomial}(20 \mid 30, \theta) \times \text{Beta}(\theta \mid 20,20) \\ \\
& = & \lambda { 30 \choose 20} \frac{1}{\text{B}(20, 10)} \theta^{40 - 1} (1-\theta)^{20-1} \\[8pt]
&&+ (1-\lambda) {30 \choose 20} \frac{1}{\text{B}(20,20)} \theta^{40-1} (1-\theta)^{30-1} \\ \\
& = & \lambda { 30 \choose 20} \frac{\text{B}(40,20) \text{B}(40,30)}{\text{B}(20, 10) \text{B}(40,20) \text{B}(40,30)} \theta^{40 - 1} (1-\theta)^{20-1} \\[8pt]
&&+ (1-\lambda) {30 \choose 20} \frac{\text{B}(40,20) \text{B}(40,30)}{\text{B}(20,20) \text{B}(40,20) \text{B}(40,30)} \theta^{40-1} (1-\theta)^{30-1} \\ \\
& = & \lambda { 30 \choose 20} \frac{ \text{B}(40,20)}{\text{B}(20, 10)} \text{Beta}(\theta \mid 40,20) \\[8pt]
&&+ (1- \lambda) { 30 \choose 20} \frac{\text{B}(40,30)}{\text{B}(20, 20)} \text{Beta}(\theta \mid 40,30) \\ \\
& \propto & \lambda \frac{ \text{B}(40,20)}{\text{B}(20, 10)} \text{Beta}(\theta \mid 40,20) \\[8pt]
&&+ (1- \lambda) \frac{\text{B}(40,30)}{\text{B}(20, 20)} \text{Beta}(\theta \mid 40,30).
\end{eqnarray*}
$$
Thus, the new weights $\omega_1, \omega_2$ are
$$
\begin{eqnarray*}
\omega_1 & = & \left( \lambda \frac{ \text{B}(40,20)}{\text{B}(20, 10)} \right) \left( \lambda \frac{ \text{B}(40,20)}{\text{B}(20, 10)} + (1- \lambda) \frac{\text{B}(40,30)}{\text{B}(20, 20)} \right)^{-1} \\
\omega_2 & = & 1 - \omega_1,
\end{eqnarray*}
$$
and
$$
\text{Posterior}(\theta) = \omega_1 \times \text{Beta}(\theta \mid 40,20) + \omega_2 \times \text{Beta}(\theta \mid 40,30).
$$
|
Conjugate mixture of beta distributions - weights
|
Assuming you meant a binomial likelihood,
$$
\begin{eqnarray*}
\text{Posterior}(\theta) & \propto & \text{Likelihood}(\theta) \times \text{Prior}(\theta) \\ \\
& = & \text{Binomial}(20 \mid 30, \thet
|
Conjugate mixture of beta distributions - weights
Assuming you meant a binomial likelihood,
$$
\begin{eqnarray*}
\text{Posterior}(\theta) & \propto & \text{Likelihood}(\theta) \times \text{Prior}(\theta) \\ \\
& = & \text{Binomial}(20 \mid 30, \theta) \times \bigg[ \lambda \times \text{Beta}(\theta \mid 20,10) + (1-\lambda) \times \text{Beta}(\theta \mid 20, 20) \bigg] \\ \\
& = & \lambda \times \text{Binomial}(20 \mid 30, \theta) \times \text{Beta}(\theta \mid 20,10) \\[8pt]
&&+ (1 - \lambda) \times \text{Binomial}(20 \mid 30, \theta) \times \text{Beta}(\theta \mid 20,20) \\ \\
& = & \lambda { 30 \choose 20} \frac{1}{\text{B}(20, 10)} \theta^{40 - 1} (1-\theta)^{20-1} \\[8pt]
&&+ (1-\lambda) {30 \choose 20} \frac{1}{\text{B}(20,20)} \theta^{40-1} (1-\theta)^{30-1} \\ \\
& = & \lambda { 30 \choose 20} \frac{\text{B}(40,20) \text{B}(40,30)}{\text{B}(20, 10) \text{B}(40,20) \text{B}(40,30)} \theta^{40 - 1} (1-\theta)^{20-1} \\[8pt]
&&+ (1-\lambda) {30 \choose 20} \frac{\text{B}(40,20) \text{B}(40,30)}{\text{B}(20,20) \text{B}(40,20) \text{B}(40,30)} \theta^{40-1} (1-\theta)^{30-1} \\ \\
& = & \lambda { 30 \choose 20} \frac{ \text{B}(40,20)}{\text{B}(20, 10)} \text{Beta}(\theta \mid 40,20) \\[8pt]
&&+ (1- \lambda) { 30 \choose 20} \frac{\text{B}(40,30)}{\text{B}(20, 20)} \text{Beta}(\theta \mid 40,30) \\ \\
& \propto & \lambda \frac{ \text{B}(40,20)}{\text{B}(20, 10)} \text{Beta}(\theta \mid 40,20) \\[8pt]
&&+ (1- \lambda) \frac{\text{B}(40,30)}{\text{B}(20, 20)} \text{Beta}(\theta \mid 40,30).
\end{eqnarray*}
$$
Thus, the new weights $\omega_1, \omega_2$ are
$$
\begin{eqnarray*}
\omega_1 & = & \left( \lambda \frac{ \text{B}(40,20)}{\text{B}(20, 10)} \right) \left( \lambda \frac{ \text{B}(40,20)}{\text{B}(20, 10)} + (1- \lambda) \frac{\text{B}(40,30)}{\text{B}(20, 20)} \right)^{-1} \\
\omega_2 & = & 1 - \omega_1,
\end{eqnarray*}
$$
and
$$
\text{Posterior}(\theta) = \omega_1 \times \text{Beta}(\theta \mid 40,20) + \omega_2 \times \text{Beta}(\theta \mid 40,30).
$$
|
Conjugate mixture of beta distributions - weights
Assuming you meant a binomial likelihood,
$$
\begin{eqnarray*}
\text{Posterior}(\theta) & \propto & \text{Likelihood}(\theta) \times \text{Prior}(\theta) \\ \\
& = & \text{Binomial}(20 \mid 30, \thet
|
40,394
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
|
An alternative interpretation of AUC is that it gives the probability that a randomly selected positive is ranked above a randomly selected negative (see, e.g., Wikipedia). Thus, AUC is 1 if and only if all positives are ranked above all negatives. However, it is still possible to obtain sensitivity or specificity under 1 by selecting a suboptimal cutoff.
For example, let us consider a test case with 4 subjects and an algorithm predicting probabilities (of being positive) as follows:
\begin{equation}
\begin{array}{c|c}
\textrm{Truth} & \textrm{Probability} \\ \hline
\textrm{P} & 0.9 \\
\textrm{P} & 0.4 \\
\textrm{N} & 0.2 \\
\textrm{N} & 0.1
\end{array}
\end{equation}
All positives are ranked above all negatives, thus the AUC is 1. However, if the cutoff probability is set as $0.5$, one of the positives is classified as negative, and thus the sensitivity is only $50\%$. Indeed, depending on the cutoff, the sensitivities and false positive rates ($1-$ specifities) will be as follows.
\begin{equation}
\begin{array}{c|c|c}
\textrm{Cutoff in range} & \textrm{Sensitivity} & 1-\textrm{ Specificity} \\ \hline
(-\infty,0.1] & 1 & 1 \\
(0.1,0.2] & 1 & 0.5 \\
(0.2,0.4] & 1 & 0 \\
(0.4,0.9] & 0.5 & 0 \\
(0.9,\infty) & 0 & 0
\end{array}
\end{equation}
This is illustrated in the following figure. The possible (Sensitivity, $1-$ Specificity) combinations are drawn as red circles and the (interpolated) ROC curve as green line. The entire unit square is under the curve, and thus the area under the curve is 1.
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
|
An alternative interpretation of AUC is that it gives the probability that a randomly selected positive is ranked above a randomly selected negative (see, e.g., Wikipedia). Thus, AUC is 1 if and only
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
An alternative interpretation of AUC is that it gives the probability that a randomly selected positive is ranked above a randomly selected negative (see, e.g., Wikipedia). Thus, AUC is 1 if and only if all positives are ranked above all negatives. However, it is still possible to obtain sensitivity or specificity under 1 by selecting a suboptimal cutoff.
For example, let us consider a test case with 4 subjects and an algorithm predicting probabilities (of being positive) as follows:
\begin{equation}
\begin{array}{c|c}
\textrm{Truth} & \textrm{Probability} \\ \hline
\textrm{P} & 0.9 \\
\textrm{P} & 0.4 \\
\textrm{N} & 0.2 \\
\textrm{N} & 0.1
\end{array}
\end{equation}
All positives are ranked above all negatives, thus the AUC is 1. However, if the cutoff probability is set as $0.5$, one of the positives is classified as negative, and thus the sensitivity is only $50\%$. Indeed, depending on the cutoff, the sensitivities and false positive rates ($1-$ specifities) will be as follows.
\begin{equation}
\begin{array}{c|c|c}
\textrm{Cutoff in range} & \textrm{Sensitivity} & 1-\textrm{ Specificity} \\ \hline
(-\infty,0.1] & 1 & 1 \\
(0.1,0.2] & 1 & 0.5 \\
(0.2,0.4] & 1 & 0 \\
(0.4,0.9] & 0.5 & 0 \\
(0.9,\infty) & 0 & 0
\end{array}
\end{equation}
This is illustrated in the following figure. The possible (Sensitivity, $1-$ Specificity) combinations are drawn as red circles and the (interpolated) ROC curve as green line. The entire unit square is under the curve, and thus the area under the curve is 1.
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
An alternative interpretation of AUC is that it gives the probability that a randomly selected positive is ranked above a randomly selected negative (see, e.g., Wikipedia). Thus, AUC is 1 if and only
|
40,395
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
|
AUC=1 means for all specificities in [0,1] the sensitivity is 1. It is IMPOSSIBLE to get a sensitivity of 95%. So that paper is reporting a fundamental error. Hope this helps.
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
|
AUC=1 means for all specificities in [0,1] the sensitivity is 1. It is IMPOSSIBLE to get a sensitivity of 95%. So that paper is reporting a fundamental error. Hope this helps.
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
AUC=1 means for all specificities in [0,1] the sensitivity is 1. It is IMPOSSIBLE to get a sensitivity of 95%. So that paper is reporting a fundamental error. Hope this helps.
|
Confused about sensitivity, specificity and area under ROC curve (AUC)
AUC=1 means for all specificities in [0,1] the sensitivity is 1. It is IMPOSSIBLE to get a sensitivity of 95%. So that paper is reporting a fundamental error. Hope this helps.
|
40,396
|
Probability Interval for Gamma Distribution
|
Your algebra sounds like it's all fine.
You don't give enough information to guess how you decided "according to $\text{R}$, $P(W<c_1)=1$, instead of the desired $0.025$".
This is a common issue with the gamma distribution - there are two different common parameterizations, both reasonably widespread, and if we're not careful, we can think we're dealing with one when we're actually doing the other. (Actually, there's a third paramaterization that comes up a lot when dealing with gamma GLMs, the shape-mean parameterization, but that one is usually more obvious when it occurs.)
Wikipedia (permalink to today's version) gives both forms, see the column on the right. Confusingly, it swaps the role of what I see as the more conventional parameter names (to my mind $\beta$ is more often the scale, $\theta$ is more often the rate).
[While it comes up a lot when dealing with software, it's not simply a software issue, because the issue often happens between humans as well.]
As it happens, R is a particular culprit with this kind of issue, the help for the collection of gamma distribution functions seemingly going out of its way to muddy the water (I'm using 3.0.2 at the time of writing, but the issue has been there for ages).
My guess is you might be calling the pgamma function in R with unnamed arguments, but supplying shape and scale arguments, like so ...
pgamma(16.791*3/2,15,3)
[1] 1
... when R defaults to shape and rate arguments.
When in doubt, draw. Here's what you want to be calculating with:
As you see, the proportion of that to the left of $\frac{3}{2}16.791$ (around 25) looks roughly right.
Here's the actual density I suspect you're calculating with:
plot(x,dgamma(x,15,3),col=3,type="l")
Here the proportion of that to the left of $\frac{3}{2}16.791$ will be very close to 1.
The R help is, unfortunately, less than clear -- even actively misleading. The sentence under "Description" implies that the supplied parameters are shape and scale -- and the description of rate under "Arguments" confirms the impression(!) -- but the argument list in the function itself isn't ambiguous, if non-obvious to a novice user:
pgamma(q, shape, rate = 1, scale = 1/rate, lower.tail = TRUE, log.p = FALSE)
Do you see how the scale defaults to a function of whatever is specified for the rate? If you just supply two unnamed arguments after the q, they are the shape and the rate, and then scale is obtained by taking reciprocals.
Which is to say, you need to use a named argument to get what you want:
pgamma(16.791*3/2,15,scale=3)
[1] 0.02500255
When there is any potential for doubt, you should probably name your arguments anyway, to make them explicit to human readers.
|
Probability Interval for Gamma Distribution
|
Your algebra sounds like it's all fine.
You don't give enough information to guess how you decided "according to $\text{R}$, $P(W<c_1)=1$, instead of the desired $0.025$".
This is a common issue with
|
Probability Interval for Gamma Distribution
Your algebra sounds like it's all fine.
You don't give enough information to guess how you decided "according to $\text{R}$, $P(W<c_1)=1$, instead of the desired $0.025$".
This is a common issue with the gamma distribution - there are two different common parameterizations, both reasonably widespread, and if we're not careful, we can think we're dealing with one when we're actually doing the other. (Actually, there's a third paramaterization that comes up a lot when dealing with gamma GLMs, the shape-mean parameterization, but that one is usually more obvious when it occurs.)
Wikipedia (permalink to today's version) gives both forms, see the column on the right. Confusingly, it swaps the role of what I see as the more conventional parameter names (to my mind $\beta$ is more often the scale, $\theta$ is more often the rate).
[While it comes up a lot when dealing with software, it's not simply a software issue, because the issue often happens between humans as well.]
As it happens, R is a particular culprit with this kind of issue, the help for the collection of gamma distribution functions seemingly going out of its way to muddy the water (I'm using 3.0.2 at the time of writing, but the issue has been there for ages).
My guess is you might be calling the pgamma function in R with unnamed arguments, but supplying shape and scale arguments, like so ...
pgamma(16.791*3/2,15,3)
[1] 1
... when R defaults to shape and rate arguments.
When in doubt, draw. Here's what you want to be calculating with:
As you see, the proportion of that to the left of $\frac{3}{2}16.791$ (around 25) looks roughly right.
Here's the actual density I suspect you're calculating with:
plot(x,dgamma(x,15,3),col=3,type="l")
Here the proportion of that to the left of $\frac{3}{2}16.791$ will be very close to 1.
The R help is, unfortunately, less than clear -- even actively misleading. The sentence under "Description" implies that the supplied parameters are shape and scale -- and the description of rate under "Arguments" confirms the impression(!) -- but the argument list in the function itself isn't ambiguous, if non-obvious to a novice user:
pgamma(q, shape, rate = 1, scale = 1/rate, lower.tail = TRUE, log.p = FALSE)
Do you see how the scale defaults to a function of whatever is specified for the rate? If you just supply two unnamed arguments after the q, they are the shape and the rate, and then scale is obtained by taking reciprocals.
Which is to say, you need to use a named argument to get what you want:
pgamma(16.791*3/2,15,scale=3)
[1] 0.02500255
When there is any potential for doubt, you should probably name your arguments anyway, to make them explicit to human readers.
|
Probability Interval for Gamma Distribution
Your algebra sounds like it's all fine.
You don't give enough information to guess how you decided "according to $\text{R}$, $P(W<c_1)=1$, instead of the desired $0.025$".
This is a common issue with
|
40,397
|
Hamiltonian Monte Carlo: why is reparameterizing needed?
|
Hamiltonian Monte Carlo is often quoted as being rotation invariant, but what does that actually mean?
In theory Hamiltonian Monte Carlo (HMC) is independent of the coordinates chosen to represent your distribution, which actually means it is both rotation and scale invariant. The problem is that, in practice, we can't run HMC exactly and must instead use numerical integrators for approximation. It is the numerical integrators that introduce a sensitivity to correlations and scales -- the more isotropic the target distribution the better-behaved the integrator.
That said, the reparameterizations recommended for hierarchical models are actually a bit more subtle. The issue isn't correlations in the classical sense but rather correlations in the hierarchical sense. These introduce different but equally challenging problems for HMC which can be mediated by non-centered parameterizations that cleverly shift the correlations around. For details check out our recent preprint, http://arxiv.org/abs/1312.0906.
|
Hamiltonian Monte Carlo: why is reparameterizing needed?
|
Hamiltonian Monte Carlo is often quoted as being rotation invariant, but what does that actually mean?
In theory Hamiltonian Monte Carlo (HMC) is independent of the coordinates chosen to represent you
|
Hamiltonian Monte Carlo: why is reparameterizing needed?
Hamiltonian Monte Carlo is often quoted as being rotation invariant, but what does that actually mean?
In theory Hamiltonian Monte Carlo (HMC) is independent of the coordinates chosen to represent your distribution, which actually means it is both rotation and scale invariant. The problem is that, in practice, we can't run HMC exactly and must instead use numerical integrators for approximation. It is the numerical integrators that introduce a sensitivity to correlations and scales -- the more isotropic the target distribution the better-behaved the integrator.
That said, the reparameterizations recommended for hierarchical models are actually a bit more subtle. The issue isn't correlations in the classical sense but rather correlations in the hierarchical sense. These introduce different but equally challenging problems for HMC which can be mediated by non-centered parameterizations that cleverly shift the correlations around. For details check out our recent preprint, http://arxiv.org/abs/1312.0906.
|
Hamiltonian Monte Carlo: why is reparameterizing needed?
Hamiltonian Monte Carlo is often quoted as being rotation invariant, but what does that actually mean?
In theory Hamiltonian Monte Carlo (HMC) is independent of the coordinates chosen to represent you
|
40,398
|
How to identify the distribution of data?
|
Although your question is very general, the rule is that there isn't a standard way of fitting a distribution to a vector of observations and several methods exist for it. You can start by creating a histogram of your data. In this way, you can immediately see if the shape of the histogram resembles any of the widely known and used statistical distributions (e.g. Gaussian).
As a next step, have a look at http://www.r-bloggers.com/fitting-distributions-with-r/. It contains several information that will help you deal with your data, a diagram that can help you identify a distribution based on data characteristics and a link to a nice tutorial on fitting distributions with R. More help would be possible as soon as you identify the basic shape of your data's distribution (e.g. histogram).
|
How to identify the distribution of data?
|
Although your question is very general, the rule is that there isn't a standard way of fitting a distribution to a vector of observations and several methods exist for it. You can start by creating a
|
How to identify the distribution of data?
Although your question is very general, the rule is that there isn't a standard way of fitting a distribution to a vector of observations and several methods exist for it. You can start by creating a histogram of your data. In this way, you can immediately see if the shape of the histogram resembles any of the widely known and used statistical distributions (e.g. Gaussian).
As a next step, have a look at http://www.r-bloggers.com/fitting-distributions-with-r/. It contains several information that will help you deal with your data, a diagram that can help you identify a distribution based on data characteristics and a link to a nice tutorial on fitting distributions with R. More help would be possible as soon as you identify the basic shape of your data's distribution (e.g. histogram).
|
How to identify the distribution of data?
Although your question is very general, the rule is that there isn't a standard way of fitting a distribution to a vector of observations and several methods exist for it. You can start by creating a
|
40,399
|
How are partial regression slopes calculated in multiple regression?
|
if I wanted to plot Y against X1 so that I could visualise how strongly the two were related while also controlling for any confounding with X2, would I plot [Y]~[residuals of X1~X2], or [residuals of Y~X2] ~ [residuals of X1~X2]?
The second one. You want to plot $ e(Y|X_2) \sim e(X_1|X_2)$ to obtain the added variable plot for $X_1$ for the model already containing $X_2$. Intuitively think of it this way: the presence of $X_2$ in the model you already have is reducing the variance of the residuals (which is relative to the response). You want to determine if adding $X_1$ will reduce this variance further, so you want to consider $e(Y|X_2)$, which contains the variance remaining in the residuals after taking the predictor $X_2$ into consideration.
As you put it: you want to "partial out" the effects of the predictor(s) currently in your model on both the predictor(s) you are considering adding as wells as the response.
|
How are partial regression slopes calculated in multiple regression?
|
if I wanted to plot Y against X1 so that I could visualise how strongly the two were related while also controlling for any confounding with X2, would I plot [Y]~[residuals of X1~X2], or [residuals of
|
How are partial regression slopes calculated in multiple regression?
if I wanted to plot Y against X1 so that I could visualise how strongly the two were related while also controlling for any confounding with X2, would I plot [Y]~[residuals of X1~X2], or [residuals of Y~X2] ~ [residuals of X1~X2]?
The second one. You want to plot $ e(Y|X_2) \sim e(X_1|X_2)$ to obtain the added variable plot for $X_1$ for the model already containing $X_2$. Intuitively think of it this way: the presence of $X_2$ in the model you already have is reducing the variance of the residuals (which is relative to the response). You want to determine if adding $X_1$ will reduce this variance further, so you want to consider $e(Y|X_2)$, which contains the variance remaining in the residuals after taking the predictor $X_2$ into consideration.
As you put it: you want to "partial out" the effects of the predictor(s) currently in your model on both the predictor(s) you are considering adding as wells as the response.
|
How are partial regression slopes calculated in multiple regression?
if I wanted to plot Y against X1 so that I could visualise how strongly the two were related while also controlling for any confounding with X2, would I plot [Y]~[residuals of X1~X2], or [residuals of
|
40,400
|
How are partial regression slopes calculated in multiple regression?
|
To avoid blackening the place, I will not use bold symbols -but the answer will be carried out in matrix form. Vectors are column vectors, a prime will denote the transpose.
Let a linear regression model
$$y = X_1b_1 + X_2b_2 + u_A \qquad [A]$$
The normal equations for the OLS estimator are
$$\begin{align}
\left(X_1'X_1\right)b_1+\left(X_1'X_2\right)b_2=& X_1'y \qquad [1]\\
\\
\left(X_2'X_1\right)b_1+\left(X_2'X_2\right)b_2=& X_2'y \qquad [2]\\
\end{align}$$
Solving $[2]$ for $b_2$ we have
$$[2]\rightarrow b_2= \left(X_2'X_2\right)^{-1}X_2'y-\left(X_2'X_2\right)^{-1}\left(X_2'X_1\right)b_1$$
Inserting this into $[1]$ we obtain
$$\left(X_1'X_1\right)b_1+\left(X_1'X_2\right)\left(X_2'X_2\right)^{-1}X_2'y-\left(X_1'X_2\right)\left(X_2'X_2\right)^{-1}\left(X_2'X_1\right)b_1= X_1'y $$
Collecting terms w.r.t $b_1$ and $y$,
$$X_1'\left[I-X_2\left(X_2'X_2\right)^{-1}X_2'\right]X_1b_1= X_1'\left[I-X_2\left(X_2'X_2\right)^{-1}X_2'\right]y$$
$$\Rightarrow X_1'M_2X_1b_1 = X_1'M_2y \qquad [3]$$
where $M_2$ is the "annihilator" or "residual maker"matrix related to $X_2$, namely the matrix that produces the residuals when a variable is regressed on $X_2$, by pre-multiplying this variable. This matrix is symmetric and idempotent, $M_2=M_2',\; M_2= M_2M_2$. So we can write
$$(M_2X_1)'(M_2X_1)b_1 = (M_2X_1)'y$$
$$\Rightarrow R_{1\sim2}'R_{1\sim2}b_1=R_{1\sim2}'y \Rightarrow \hat b_1 = \left(R_{1\sim2}'R_{1\sim2}\right)^{-1}R_{1\sim2}'y\qquad [4]$$
where $R_{1\sim2}$ denotes the residual vector from regressing $X_1$ on $X_2$.
This last formula is exactly the OLS formula from the regression model
$$y= R_{1\sim2}d_1+u_B \qquad [B]$$
So eq. $[4]$ tells us that the coefficient estimate for $X_1$ that we will obtain in a multiple regression setting, will be exactly the same with what we will obtain if we regress the dependent variable on the residuals from the regression of $X_1$ on $X_2$.
Now consider the second case, regressing the residuals on the residuals. This is the model
$$R_{y\sim2} = R_{1\sim2}c_1+u_C \Rightarrow (M_2y)= (M_2X_1)c_1 +u_C \qquad [C]$$
The OLS estimator of $c$ is
$$\hat c_1 = \left[(M_2X_1)'(M_2X_1)\right]^{-1}(M_2X_1)'(M_2y) \qquad [5]$$
By the properties of $M_2$ we have
$$(M_2X_1)'(M_2y) = X_1'M_2'M_2y=X_1'M_2M_2y=X_1'M_2y=X_1'M_2'y=(M_2X_1)'y$$
Noting that $M_2X_1 = R_{1\sim2}$ eq. $[5]$ becomes
$$\hat c_1= \left(R_{1\sim2}'R_{1\sim2}\right)^{-1}R_{1\sim2}'y \qquad [6]$$
which is identical to eq. $[4]$, and so $ \hat c_1 = \hat d_1 =\hat b_1$. In other words the three models give mathematically identical results.
Let's now consider the issue of the estimator variance.
Models $[B]$ and $[C]$ have the same regressor matrix so the question is what happens with the estimated error variances, $\sigma^2_B$ and $\sigma^2_C$. We will denote $M(r)_{1\sim2}$ the annihilator matrix of the regressor $R_{1\sim2}$. It has analogous properties as $M_2$
For model $[B]$ we have
$$u'_Bu_B = \left(M(r)_{1\sim2}y\right)'\left(M(r)_{1\sim2}y\right) = y'M(r)_{1\sim2}y \qquad [7]$$
while for model $[C]$ we have
$$u'_Cu_C = \left(M(r)_{1\sim2}(M_2y)\right)'\left(M(r)_{1\sim2}(M_2y)\right) = y'M_2M(r)_{1\sim2}M_2y \qquad [8]$$
Are the RHS of eq. $[7]$ and $[8]$ equal? I 'll leave that to the reader.
|
How are partial regression slopes calculated in multiple regression?
|
To avoid blackening the place, I will not use bold symbols -but the answer will be carried out in matrix form. Vectors are column vectors, a prime will denote the transpose.
Let a linear regression mo
|
How are partial regression slopes calculated in multiple regression?
To avoid blackening the place, I will not use bold symbols -but the answer will be carried out in matrix form. Vectors are column vectors, a prime will denote the transpose.
Let a linear regression model
$$y = X_1b_1 + X_2b_2 + u_A \qquad [A]$$
The normal equations for the OLS estimator are
$$\begin{align}
\left(X_1'X_1\right)b_1+\left(X_1'X_2\right)b_2=& X_1'y \qquad [1]\\
\\
\left(X_2'X_1\right)b_1+\left(X_2'X_2\right)b_2=& X_2'y \qquad [2]\\
\end{align}$$
Solving $[2]$ for $b_2$ we have
$$[2]\rightarrow b_2= \left(X_2'X_2\right)^{-1}X_2'y-\left(X_2'X_2\right)^{-1}\left(X_2'X_1\right)b_1$$
Inserting this into $[1]$ we obtain
$$\left(X_1'X_1\right)b_1+\left(X_1'X_2\right)\left(X_2'X_2\right)^{-1}X_2'y-\left(X_1'X_2\right)\left(X_2'X_2\right)^{-1}\left(X_2'X_1\right)b_1= X_1'y $$
Collecting terms w.r.t $b_1$ and $y$,
$$X_1'\left[I-X_2\left(X_2'X_2\right)^{-1}X_2'\right]X_1b_1= X_1'\left[I-X_2\left(X_2'X_2\right)^{-1}X_2'\right]y$$
$$\Rightarrow X_1'M_2X_1b_1 = X_1'M_2y \qquad [3]$$
where $M_2$ is the "annihilator" or "residual maker"matrix related to $X_2$, namely the matrix that produces the residuals when a variable is regressed on $X_2$, by pre-multiplying this variable. This matrix is symmetric and idempotent, $M_2=M_2',\; M_2= M_2M_2$. So we can write
$$(M_2X_1)'(M_2X_1)b_1 = (M_2X_1)'y$$
$$\Rightarrow R_{1\sim2}'R_{1\sim2}b_1=R_{1\sim2}'y \Rightarrow \hat b_1 = \left(R_{1\sim2}'R_{1\sim2}\right)^{-1}R_{1\sim2}'y\qquad [4]$$
where $R_{1\sim2}$ denotes the residual vector from regressing $X_1$ on $X_2$.
This last formula is exactly the OLS formula from the regression model
$$y= R_{1\sim2}d_1+u_B \qquad [B]$$
So eq. $[4]$ tells us that the coefficient estimate for $X_1$ that we will obtain in a multiple regression setting, will be exactly the same with what we will obtain if we regress the dependent variable on the residuals from the regression of $X_1$ on $X_2$.
Now consider the second case, regressing the residuals on the residuals. This is the model
$$R_{y\sim2} = R_{1\sim2}c_1+u_C \Rightarrow (M_2y)= (M_2X_1)c_1 +u_C \qquad [C]$$
The OLS estimator of $c$ is
$$\hat c_1 = \left[(M_2X_1)'(M_2X_1)\right]^{-1}(M_2X_1)'(M_2y) \qquad [5]$$
By the properties of $M_2$ we have
$$(M_2X_1)'(M_2y) = X_1'M_2'M_2y=X_1'M_2M_2y=X_1'M_2y=X_1'M_2'y=(M_2X_1)'y$$
Noting that $M_2X_1 = R_{1\sim2}$ eq. $[5]$ becomes
$$\hat c_1= \left(R_{1\sim2}'R_{1\sim2}\right)^{-1}R_{1\sim2}'y \qquad [6]$$
which is identical to eq. $[4]$, and so $ \hat c_1 = \hat d_1 =\hat b_1$. In other words the three models give mathematically identical results.
Let's now consider the issue of the estimator variance.
Models $[B]$ and $[C]$ have the same regressor matrix so the question is what happens with the estimated error variances, $\sigma^2_B$ and $\sigma^2_C$. We will denote $M(r)_{1\sim2}$ the annihilator matrix of the regressor $R_{1\sim2}$. It has analogous properties as $M_2$
For model $[B]$ we have
$$u'_Bu_B = \left(M(r)_{1\sim2}y\right)'\left(M(r)_{1\sim2}y\right) = y'M(r)_{1\sim2}y \qquad [7]$$
while for model $[C]$ we have
$$u'_Cu_C = \left(M(r)_{1\sim2}(M_2y)\right)'\left(M(r)_{1\sim2}(M_2y)\right) = y'M_2M(r)_{1\sim2}M_2y \qquad [8]$$
Are the RHS of eq. $[7]$ and $[8]$ equal? I 'll leave that to the reader.
|
How are partial regression slopes calculated in multiple regression?
To avoid blackening the place, I will not use bold symbols -but the answer will be carried out in matrix form. Vectors are column vectors, a prime will denote the transpose.
Let a linear regression mo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.