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 |
|---|---|---|---|---|---|---|
20,501 | Best way to put two histograms on same scale? | Another approach would be to plot the different distributions on the same plot and use something like the alpha parameter in ggplot2 to address the overplotting issues. The utility of this method will be dependent on the differences or similarities in your distribution as they will be plotted with the same bins. Another alternative would be to display smoothed density curves for each distribution. Here's an example of these options and the other options discussed in the thread:
library(ggplot2)
df <- melt(
data.frame(
x = rnorm(1000)
, y = rnorm(1000, 0, 2)
)
)
ggplot(data = df) +
# geom_bar(aes(x = value, fill = variable), alpha = 1/2)
# geom_bar(aes(x = value)) + facet_grid(variable ~ .)
# geom_density(aes(x = value, colour = variable))
# stat_qq(aes(sample = value, colour = variable)) | Best way to put two histograms on same scale? | Another approach would be to plot the different distributions on the same plot and use something like the alpha parameter in ggplot2 to address the overplotting issues. The utility of this method will | Best way to put two histograms on same scale?
Another approach would be to plot the different distributions on the same plot and use something like the alpha parameter in ggplot2 to address the overplotting issues. The utility of this method will be dependent on the differences or similarities in your distribution as they will be plotted with the same bins. Another alternative would be to display smoothed density curves for each distribution. Here's an example of these options and the other options discussed in the thread:
library(ggplot2)
df <- melt(
data.frame(
x = rnorm(1000)
, y = rnorm(1000, 0, 2)
)
)
ggplot(data = df) +
# geom_bar(aes(x = value, fill = variable), alpha = 1/2)
# geom_bar(aes(x = value)) + facet_grid(variable ~ .)
# geom_density(aes(x = value, colour = variable))
# stat_qq(aes(sample = value, colour = variable)) | Best way to put two histograms on same scale?
Another approach would be to plot the different distributions on the same plot and use something like the alpha parameter in ggplot2 to address the overplotting issues. The utility of this method will |
20,502 | Best way to put two histograms on same scale? | So it's a question of maintaining the same bin size or maintaining the same number of bins? I can see arguments for both sides. A work-around would be to standardize the values first. Then you could maintain both. | Best way to put two histograms on same scale? | So it's a question of maintaining the same bin size or maintaining the same number of bins? I can see arguments for both sides. A work-around would be to standardize the values first. Then you could m | Best way to put two histograms on same scale?
So it's a question of maintaining the same bin size or maintaining the same number of bins? I can see arguments for both sides. A work-around would be to standardize the values first. Then you could maintain both. | Best way to put two histograms on same scale?
So it's a question of maintaining the same bin size or maintaining the same number of bins? I can see arguments for both sides. A work-around would be to standardize the values first. Then you could m |
20,503 | How to determine the distribution of a parameter fit by nonlinear regression | This answer does not (yet) answer the question but should at least help to clarify what the question really is:
"fit by nonlinear regression" sounds like you are using the following model:
$\mathcal{Y}\sim \mathcal{N}(\mu=\frac{X}{X+K_m}, \sigma^2)$
(this assumes that there is no error in measuring the substrate concentration X; If this nevertheless a good model is another question)
The corresponding likelihood function given a sample $Y^N$ is:
$p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N) = \prod_{i=1}^Np_{\mathcal{N}}(Y^N|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$,
where $p_\mathcal{N}$ is the density of the normal.
and sounds like you are using maximum-likelihood to estimate $K_m$ (and $\sigma^2$).
(if this is a good approach is yet another question)
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N)$
You then seem to sample $\mathcal{Y^N}$ for some fixed $X^N$, $K_m$ and $\sigma$
(Where $X^N$ might be your data while $K_m$ and $\sigma$ might be the estimate you obtained for your data with above ML approach)
and then apply above ML estimator ( let's call it ), thus sampling a random variable $\mathcal{\hat{K_m}}$ whose distribution you are asking about (and which you are plotting). There are legit reasons to desire an explicit form of this distribution; for example, to construct confidence intervals for your estimation of $K_m$.
However since this distribution is not (symmetric and uni-modal) it's yet another question which is the best way to construct a confidence interval given this distribution
Note, however, that this distribution is NOT the posterior distribution of nor a likelihood function for $K_m$ and thus probably not what you desired when you said "the distribution of a parameter".
the likelihood function is trivial to obtain (look at logLik for your model in R) while the posterior requires you to choose a prior (the empirical distribution of $K_m$ values in databases might be a good choice)
Anyway, let's see how far we get. Let's start by expressing it as compound distribution using the the distribution of $Y^N$ that we know:
$p_{\mathcal{\hat{K_m}}} (\hat{K_M})=\int_{ \{Y^N|\hat{K_M}=ML_{\hat{K_m}}(X^N,Y^N)\}} p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
This contains $ML_{\hat{K_m}}(X^N,Y^N)$ for which we might be able to find and algebraic expression for:
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \prod_{i=1}^Np_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(p_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2))$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(\frac{1}{\sqrt{2\pi\sigma^2}}) - \frac{\left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2}{2\sigma^2}$
$ = \operatorname*{argmin}\limits_{K_m} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2$
$ 0 = \left.\frac{\mathrm{d}}{\mathrm{d} K_m} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2\right|_\hat{K_m}$
$ = \sum_{i=1}^N \left.\frac{\mathrm{d}}{\mathrm{d} K_m} \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2\right|_\hat{K_m}$
$ = \sum_{i=1}^N \frac{X^N_i(\hat{K_m}Y^N_i+X^N_i(Y^N_i-1))}{(\hat{K_m}+X^N_i)^3}$
From where I don't know how to continue.
I'm still in the progress of refining this answer please find below a current draft to decide if it's worth your bounty:
In this answer I assume $V_{max}$ is known to be (without loss of generality) 1. As confirmed in the comments you are using the following model:
$\mathcal{Y}\sim \mathcal{N}(\mu=\frac{X}{X+K_m}, \sigma^2)$
The corresponding likelihood function is
$L(K_m, \sigma) = p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N) = \prod_{i=1}^Np_{\mathcal{N}}(Y^N|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$,
where $p_\mathcal{N}$ is the density of the normal distribution.
Now, you would like to know the distribution of a random variable $\mathcal{\hat{K_m}}$ that is the maximum likelihood estimate,
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N)$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \prod_{i=1}^Np_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(p_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2))$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(\frac{1}{\sqrt{2\pi\sigma^2}}) - \frac{\left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2}{2\sigma^2}$
$ = \operatorname*{argmin}\limits_{K_m} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2$,
obtained for draws of draws of size $N$ from $\mathcal{Y}$, $\mathcal{Y^N}$, for any $N$, $X^N$, $\sigma$.
You then sampled $K_m$ for some fixed $K$, $X^N$, $K_m$ and $\sigma$ by first sampling $\mathcal{Y^N}$ accordingly and then applying above ML estimator.
Based on this, you think that $\mathcal{K_m}$ follows a log normal distribution.
It is known that, for any differentiable function $f: \mathbb{R}^N \to \mathbb{R}$ and $\mathcal{Y} = f(\mathcal{X})$,
$p_\mathcal{Y}(y) = \int_x \delta(f(x)-y) p_\mathcal{X}(x)\mathrm{d}x$ , where $\delta$ is the Dirac delta.
And that for any monotonic function $g: \mathbb{R} \to \mathbb{R}$ and $\mathcal{Y} = f(\mathcal{X})$,
$p_\mathcal{Y}(y) = p_\mathcal{X}(g^{-1}(y)) \left|\frac{\mathrm{d}}{\mathrm{d}y} g^{-1}(y) \right|$
We can use this to try to derive a closed form for the density of the distribution of $\mathcal{\hat{K_m}}$:
$p_{\mathcal{\hat{K_m}}}(\hat{K_m})=\int \delta (\hat{K_m}-ML_{\hat{K_m}}(X^N,Y^N)) p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
$\overset{\tiny{\text{if i'm lucky}}}{=}\int \delta(\frac{\mathrm{d}}{\mathrm{d} \hat{K_m}} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+\hat{K_m}}\right)^2) p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
$=\int \delta(\sum_{i=1}^N \frac{X^N_i(\hat{K_m}Y^N_i+X^N_i(Y^N_i-1))}{(\hat{K_m}+X^N_i)^3}) p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
But I don't how to find a simpler form for that.
For $N=1$ this is a bit simpler:
$p_{\mathcal{\hat{K_m}}}(\hat{K_m})=p_\mathcal{Y}(g^{-1}(\hat{K_m})) \left|\frac{\mathrm{d}}{\mathrm{d}\hat{K_m}} g^{-1}(\hat{K_m}) \right| = p_\mathcal{Y}(\frac{X}{X+\hat{K_m}}) \left|\frac{\mathrm{d}}{\mathrm{d}\hat{K_m}} \frac{X}{X+\hat{K_m}} \right|= p_\mathcal{Y}(\frac{X}{X+\hat{K_m}}) \left|- \frac{X}{(X+\hat{K_m})^2} \right|= p_{\mathcal{N}}(\frac{X}{X+\hat{K_m}}|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2) \frac{X}{(X+\hat{K_m})^2} $
Where I used:
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmin}\limits_{K_m}\left(y-\frac{x}{x+K_m}\right)^2 \Leftrightarrow 0 =\frac{x(\hat{K_m}y+x(y-1))}{(\hat{K_m}+x)^3} \land (\text{further conditions})$ which solves $\hat{K_m}=x(\frac{1}{y}-1)$.
For $N=2$ the explicit form of $ML_{K_m}$ has quite a few more terms
In any case, this shows that $p_{\mathcal{\hat{K_m}}}(\hat{K_m})$ is not log normal (but might converge to it (before converging to normal)). | How to determine the distribution of a parameter fit by nonlinear regression | This answer does not (yet) answer the question but should at least help to clarify what the question really is:
"fit by nonlinear regression" sounds like you are using the following model:
$\mathcal{ | How to determine the distribution of a parameter fit by nonlinear regression
This answer does not (yet) answer the question but should at least help to clarify what the question really is:
"fit by nonlinear regression" sounds like you are using the following model:
$\mathcal{Y}\sim \mathcal{N}(\mu=\frac{X}{X+K_m}, \sigma^2)$
(this assumes that there is no error in measuring the substrate concentration X; If this nevertheless a good model is another question)
The corresponding likelihood function given a sample $Y^N$ is:
$p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N) = \prod_{i=1}^Np_{\mathcal{N}}(Y^N|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$,
where $p_\mathcal{N}$ is the density of the normal.
and sounds like you are using maximum-likelihood to estimate $K_m$ (and $\sigma^2$).
(if this is a good approach is yet another question)
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N)$
You then seem to sample $\mathcal{Y^N}$ for some fixed $X^N$, $K_m$ and $\sigma$
(Where $X^N$ might be your data while $K_m$ and $\sigma$ might be the estimate you obtained for your data with above ML approach)
and then apply above ML estimator ( let's call it ), thus sampling a random variable $\mathcal{\hat{K_m}}$ whose distribution you are asking about (and which you are plotting). There are legit reasons to desire an explicit form of this distribution; for example, to construct confidence intervals for your estimation of $K_m$.
However since this distribution is not (symmetric and uni-modal) it's yet another question which is the best way to construct a confidence interval given this distribution
Note, however, that this distribution is NOT the posterior distribution of nor a likelihood function for $K_m$ and thus probably not what you desired when you said "the distribution of a parameter".
the likelihood function is trivial to obtain (look at logLik for your model in R) while the posterior requires you to choose a prior (the empirical distribution of $K_m$ values in databases might be a good choice)
Anyway, let's see how far we get. Let's start by expressing it as compound distribution using the the distribution of $Y^N$ that we know:
$p_{\mathcal{\hat{K_m}}} (\hat{K_M})=\int_{ \{Y^N|\hat{K_M}=ML_{\hat{K_m}}(X^N,Y^N)\}} p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
This contains $ML_{\hat{K_m}}(X^N,Y^N)$ for which we might be able to find and algebraic expression for:
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \prod_{i=1}^Np_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(p_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2))$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(\frac{1}{\sqrt{2\pi\sigma^2}}) - \frac{\left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2}{2\sigma^2}$
$ = \operatorname*{argmin}\limits_{K_m} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2$
$ 0 = \left.\frac{\mathrm{d}}{\mathrm{d} K_m} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2\right|_\hat{K_m}$
$ = \sum_{i=1}^N \left.\frac{\mathrm{d}}{\mathrm{d} K_m} \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2\right|_\hat{K_m}$
$ = \sum_{i=1}^N \frac{X^N_i(\hat{K_m}Y^N_i+X^N_i(Y^N_i-1))}{(\hat{K_m}+X^N_i)^3}$
From where I don't know how to continue.
I'm still in the progress of refining this answer please find below a current draft to decide if it's worth your bounty:
In this answer I assume $V_{max}$ is known to be (without loss of generality) 1. As confirmed in the comments you are using the following model:
$\mathcal{Y}\sim \mathcal{N}(\mu=\frac{X}{X+K_m}, \sigma^2)$
The corresponding likelihood function is
$L(K_m, \sigma) = p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N) = \prod_{i=1}^Np_{\mathcal{N}}(Y^N|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$,
where $p_\mathcal{N}$ is the density of the normal distribution.
Now, you would like to know the distribution of a random variable $\mathcal{\hat{K_m}}$ that is the maximum likelihood estimate,
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} p_{\mathcal{Y^N}}(Y^N|K_m, \sigma, X^N)$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \prod_{i=1}^Np_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2)$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(p_{\mathcal{N}}(Y^N_i|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2))$
$ = \operatorname*{argmax}\limits_{K_m} \operatorname*{max}\limits_{\sigma} \sum_{i=1}^N\log(\frac{1}{\sqrt{2\pi\sigma^2}}) - \frac{\left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2}{2\sigma^2}$
$ = \operatorname*{argmin}\limits_{K_m} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+K_m}\right)^2$,
obtained for draws of draws of size $N$ from $\mathcal{Y}$, $\mathcal{Y^N}$, for any $N$, $X^N$, $\sigma$.
You then sampled $K_m$ for some fixed $K$, $X^N$, $K_m$ and $\sigma$ by first sampling $\mathcal{Y^N}$ accordingly and then applying above ML estimator.
Based on this, you think that $\mathcal{K_m}$ follows a log normal distribution.
It is known that, for any differentiable function $f: \mathbb{R}^N \to \mathbb{R}$ and $\mathcal{Y} = f(\mathcal{X})$,
$p_\mathcal{Y}(y) = \int_x \delta(f(x)-y) p_\mathcal{X}(x)\mathrm{d}x$ , where $\delta$ is the Dirac delta.
And that for any monotonic function $g: \mathbb{R} \to \mathbb{R}$ and $\mathcal{Y} = f(\mathcal{X})$,
$p_\mathcal{Y}(y) = p_\mathcal{X}(g^{-1}(y)) \left|\frac{\mathrm{d}}{\mathrm{d}y} g^{-1}(y) \right|$
We can use this to try to derive a closed form for the density of the distribution of $\mathcal{\hat{K_m}}$:
$p_{\mathcal{\hat{K_m}}}(\hat{K_m})=\int \delta (\hat{K_m}-ML_{\hat{K_m}}(X^N,Y^N)) p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
$\overset{\tiny{\text{if i'm lucky}}}{=}\int \delta(\frac{\mathrm{d}}{\mathrm{d} \hat{K_m}} \sum_{i=1}^N \left(Y^N_i-\frac{X^N_i}{X^N_i+\hat{K_m}}\right)^2) p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
$=\int \delta(\sum_{i=1}^N \frac{X^N_i(\hat{K_m}Y^N_i+X^N_i(Y^N_i-1))}{(\hat{K_m}+X^N_i)^3}) p_{\mathcal{Y^N}}(Y^N) \mathrm{d} Y^N$
But I don't how to find a simpler form for that.
For $N=1$ this is a bit simpler:
$p_{\mathcal{\hat{K_m}}}(\hat{K_m})=p_\mathcal{Y}(g^{-1}(\hat{K_m})) \left|\frac{\mathrm{d}}{\mathrm{d}\hat{K_m}} g^{-1}(\hat{K_m}) \right| = p_\mathcal{Y}(\frac{X}{X+\hat{K_m}}) \left|\frac{\mathrm{d}}{\mathrm{d}\hat{K_m}} \frac{X}{X+\hat{K_m}} \right|= p_\mathcal{Y}(\frac{X}{X+\hat{K_m}}) \left|- \frac{X}{(X+\hat{K_m})^2} \right|= p_{\mathcal{N}}(\frac{X}{X+\hat{K_m}}|\mu=\frac{X^N_i}{X^N_i+K_m}, \sigma^2) \frac{X}{(X+\hat{K_m})^2} $
Where I used:
$ML_{\hat{K_m}}(X^N,Y^N) = \operatorname*{argmin}\limits_{K_m}\left(y-\frac{x}{x+K_m}\right)^2 \Leftrightarrow 0 =\frac{x(\hat{K_m}y+x(y-1))}{(\hat{K_m}+x)^3} \land (\text{further conditions})$ which solves $\hat{K_m}=x(\frac{1}{y}-1)$.
For $N=2$ the explicit form of $ML_{K_m}$ has quite a few more terms
In any case, this shows that $p_{\mathcal{\hat{K_m}}}(\hat{K_m})$ is not log normal (but might converge to it (before converging to normal)). | How to determine the distribution of a parameter fit by nonlinear regression
This answer does not (yet) answer the question but should at least help to clarify what the question really is:
"fit by nonlinear regression" sounds like you are using the following model:
$\mathcal{ |
20,504 | How to determine the distribution of a parameter fit by nonlinear regression | My questions are:
For this example, can algebra and/or calculus prove that the distribution of Km values is lognormal (or prove it has some other distribution)?
More generally, what method can be used to derive the distribution of any parameter fit by nonlinear regression?
The Km values can not be exactly lognormal. This is because in your problem formulation negative values can occur as the maximum likelihood estimate (yes the negative values do not make sense, but neither do normal distributed errors, which can cause the negative Km values). Of course, the lognormal might still be a reasonable approximation.
A more rigorous 'proof' that the distribution can not be exactly lognormal is given below in the special case with measurements in two points. For that case it is possible/easy to compute the estimates explicitly and express the sample distribution of the estimates.
Below I describe a method that derives an approximate distribution by not performing a normal approximation to the $K_m$ parameter directly, but instead on two other parameters from which a different approximate sample distribution for $K_m$ is derived.
The second part in the following, improving it even more, is very experimental. It shows a very reasonable fit, but I do not have a proof for it. I have to look into that further. But I thought it was interesting to share.
1 Different parameterization
I can re-express the Michaelis-Menten equation as a generalized linear model (using the normal family with inverse as link function):
$$y \sim N\left( \frac{1}{\beta_0+\beta_1 z},\sigma^2 \right)$$
Where
$z = 1/x$ the inverse of your variable $x$ for the substrate concentrate
$\beta_0 = 1/V_{max}$ the inverse of your enzyme velocity parameter
$\beta_1 = K_m/V_{max}$ the ratio of your half-maximal and velocity parameters
The parameters $\beta_i$ will be approximately multivariate normal distributed. Then the distribution of $K_m = \beta_1/\beta_0$ is the ratio of two correlated normal variables.
When we compute this then we get a slightly more reasonable fit
set.seed(1)
### parameters
a = 10
b = 5
n <- 10^5
### two arrays of sample distribution of parameters
am <- rep(0,n)
bm <- rep(0,n)
### perform n times a computation to view te sample distribution
for (i in 1:n) {
x <-seq(0,40,5)
y <- a*x/(x+b)+rnorm(length(x),0,1)
mod <- nls(y ~ ae * x/(x+be), start = list(ae=a,be=b))
am[i] <- coef(mod)[1]
bm[i] <- coef(mod)[2]
}
### histogram
hist(bm, breaks = seq(-2,30,0.3), freq = 0 , xlim = c(0,20), ylim = c(0,0.20),
main = "histogram compared with \n two normal approximations",
xlab = "Km", cex.main = 1)
### fit with normal approximation
s <- seq(0,22,0.01)
lines(s,dnorm(s,mean(bm),var(bm)^0.5))
### fit with ratio of normal approximation
w <- fw(s,mean(bm/am),mean(1/am),var(bm/am)^0.5,var(1/am)^0.5,cor(1/am,bm/am))
lines(s,w,col=2)
legend(20,0.20,
c("normal approximation",
"normal ratio approximation"),
xjust = 1, cex = 0.7, col = c(1,2), lty = 1 )
Here we used the following function to compute the ratio of two correlated normal distributions (see also here). It is based on: Hinkley D.V., 1969, On the Ratio of Two Correlated Normal Random Variables, Biometrica vol. 56 no. 3.
## X1/X2
fw <- function(w,mu1,mu2,sig1,sig2,rho) {
#several parameters
aw <- sqrt(w^2/sig1^2 - 2*rho*w/(sig1*sig2) + 1/sig2^2)
bw <- w*mu1/sig1^2 - rho*(mu1+mu2*w)/(sig1*sig2)+ mu2/sig2^2
c <- mu1^2/sig1^2 - 2 * rho * mu1 * mu2 / (sig1*sig2) + mu2^2/sig2^2
dw <- exp((bw^2 - c*aw^2)/(2*(1-rho^2)*aw^2))
# output from Hinkley's density formula
out <- (bw*dw / ( sqrt(2*pi) * sig1 * sig2 * aw^3)) * (pnorm(bw/aw/sqrt(1-rho^2),0,1) - pnorm(-bw/aw/sqrt(1-rho^2),0,1)) +
sqrt(1-rho^2)/(pi*sig1*sig2*aw^2) * exp(-c/(2*(1-rho^2)))
out
}
fw <- Vectorize(fw)
In the above computation, we estimated the covariance matrix for the sample distribution of the parameters $\beta_0$ and $\beta_1$ by simulating many samples. In practice, when you only have a single sample, you could be using an estimate of the variance based on the observed information matrix (for instance when you use in R the glm function, then you can obtain estimates for the covariance, based on the observed information matrix by using the vcov function) .
2 Improving normal approximation for parameter $\beta_1$
The above result, using $K_m = \beta_1/\beta_0$ is still not great because the normal approximation for the parameter $\beta_1$ is not perfect. However, with some trial and error, I found that a scaled noncentral t-distribution is a very good fit (I have some intuitive idea about it but I can not yet explain so well why, let alone proof it).
h <- hist(bm/am, breaks = seq(-2,3,0.02), freq = 0 , xlim = c(-0.2,1.3), ylim = c(0,3),
main = "histogram compared with normal and t-distribution",
xlab = expression(beta[1]), cex.main = 1)
### fitting a normal distribution
s <- seq(0,22,0.001)
lines(s,dnorm(s,mean(bm/am),var(bm/am)^0.5))
### fitting a t-distribution to the histogram
xw <- h$mids
yw <- h$density
wfit <- nls(yw ~ dt(xw*a, df, ncp)*a, start = list(a=2,df=1, ncp = 0.5),
control = nls.control(tol = 10^-5, maxiter = 10^5),
algorithm = 'port',
lower = c(0.1,0.1,0.1))
wfit
lines(xw,predict(wfit),col = 2)
legend(1.3,3,
c("normal approximation",
"t-distribution approximation"),
xjust = 1, cex = 0.7, col = c(1,2), lty = 1 )
Special case with measurements in two points
If you measure in only two points $x=s$ and $x = t$, then you could reparameterize the curve in terms of the values in those two points $y(s)$ and $y(t)$. The parameter $K_m$ will be
$$K_m = \frac{y(t)-y(s)}{y(s)/s-y(t)/t}$$
Since estimates of $y(t)$ and $y(s)$ will be independent and normally distributed the sample distribution of the estimate of $K_m$ will be the ratio of two correlated normal distributions.
The computation below illustrates this with a perfect match.
The fit with a lognormal distribution is actually not so bad either (and I needed to use some extreme parameters to make the difference clearly visible). There might be a connection between a product/ratio distribution and the lognormal distribution. It is similar to this question/answer where you have a variable that is a product of several terms. This is the same as the exponent of the sum of the log of those terms. That sum might be approximately normal distributed if either you have a lot of terms or when you have a few terms that are already approximately normal distributed.
$$K_m = e^{\log(K_m/V_{max}) - \log(1/V_{max})}$$
set.seed(1)
### parameters
a = 50
b = 5
n <- 10^5
t = 2
s = 4
### two arrays of sample distribution of parameters
am <- rep(0,n)
bm <- rep(0,n)
### perform n times a computation to view the sample distribution
x <- c(t,s)
for (i in 1:n) {
y <- a*x/(x+b)+rnorm(length(x),0,1)
mod <- lm(1/y ~ 1+I(1/x))
am[i] <- 1/coef(mod)[1]
bm[i] <- coef(mod)[2]/coef(mod)[1]
}
### histogram
h <- hist(bm, breaks = c(-10^5,seq(-100,100,0.2),10^5), freq = 0 , xlim = c(0,15), ylim = c(0,0.30),
main = "special case of measurement in two points",
xlab = "Km", cex.main = 1)
### plotting fit with lognormal distribution
xw <- h$mids
yw <- h$density
wfit <- nls(yw ~ dlnorm(xw, mu, sd), start = list(mu = log(5), sd = 0.5),
control = nls.control(tol = 10^-5, maxiter = 10^5),
algorithm = 'port',
lower = c(0.1,0.1))
wfit
lines(xw,predict(wfit),col = 1)
### plotting ratio distribution
### means, sigma and distribution
y1 = a*s/(b+s)
y2 = a*t/(b+t)
cc = -(1/s + 1/t)/sqrt(1+1)/sqrt(1/t^2+1/s^2)
lines(ts,fw(ts, mu1 = y2-y1 ,
mu2 = y1/s-y2/t,
sig1 = sqrt(1+1),
sig2 = sqrt(1/t^2+1/s^2),
rho = cc ),
col = 2)
legend(15,0.3,
c("ratio distribution", "fit with lognormal"),
xjust = 1, cex = 0.7, col = c(2,1), lty = 1 ) | How to determine the distribution of a parameter fit by nonlinear regression | My questions are:
For this example, can algebra and/or calculus prove that the distribution of Km values is lognormal (or prove it has some other distribution)?
More generally, what method can be use | How to determine the distribution of a parameter fit by nonlinear regression
My questions are:
For this example, can algebra and/or calculus prove that the distribution of Km values is lognormal (or prove it has some other distribution)?
More generally, what method can be used to derive the distribution of any parameter fit by nonlinear regression?
The Km values can not be exactly lognormal. This is because in your problem formulation negative values can occur as the maximum likelihood estimate (yes the negative values do not make sense, but neither do normal distributed errors, which can cause the negative Km values). Of course, the lognormal might still be a reasonable approximation.
A more rigorous 'proof' that the distribution can not be exactly lognormal is given below in the special case with measurements in two points. For that case it is possible/easy to compute the estimates explicitly and express the sample distribution of the estimates.
Below I describe a method that derives an approximate distribution by not performing a normal approximation to the $K_m$ parameter directly, but instead on two other parameters from which a different approximate sample distribution for $K_m$ is derived.
The second part in the following, improving it even more, is very experimental. It shows a very reasonable fit, but I do not have a proof for it. I have to look into that further. But I thought it was interesting to share.
1 Different parameterization
I can re-express the Michaelis-Menten equation as a generalized linear model (using the normal family with inverse as link function):
$$y \sim N\left( \frac{1}{\beta_0+\beta_1 z},\sigma^2 \right)$$
Where
$z = 1/x$ the inverse of your variable $x$ for the substrate concentrate
$\beta_0 = 1/V_{max}$ the inverse of your enzyme velocity parameter
$\beta_1 = K_m/V_{max}$ the ratio of your half-maximal and velocity parameters
The parameters $\beta_i$ will be approximately multivariate normal distributed. Then the distribution of $K_m = \beta_1/\beta_0$ is the ratio of two correlated normal variables.
When we compute this then we get a slightly more reasonable fit
set.seed(1)
### parameters
a = 10
b = 5
n <- 10^5
### two arrays of sample distribution of parameters
am <- rep(0,n)
bm <- rep(0,n)
### perform n times a computation to view te sample distribution
for (i in 1:n) {
x <-seq(0,40,5)
y <- a*x/(x+b)+rnorm(length(x),0,1)
mod <- nls(y ~ ae * x/(x+be), start = list(ae=a,be=b))
am[i] <- coef(mod)[1]
bm[i] <- coef(mod)[2]
}
### histogram
hist(bm, breaks = seq(-2,30,0.3), freq = 0 , xlim = c(0,20), ylim = c(0,0.20),
main = "histogram compared with \n two normal approximations",
xlab = "Km", cex.main = 1)
### fit with normal approximation
s <- seq(0,22,0.01)
lines(s,dnorm(s,mean(bm),var(bm)^0.5))
### fit with ratio of normal approximation
w <- fw(s,mean(bm/am),mean(1/am),var(bm/am)^0.5,var(1/am)^0.5,cor(1/am,bm/am))
lines(s,w,col=2)
legend(20,0.20,
c("normal approximation",
"normal ratio approximation"),
xjust = 1, cex = 0.7, col = c(1,2), lty = 1 )
Here we used the following function to compute the ratio of two correlated normal distributions (see also here). It is based on: Hinkley D.V., 1969, On the Ratio of Two Correlated Normal Random Variables, Biometrica vol. 56 no. 3.
## X1/X2
fw <- function(w,mu1,mu2,sig1,sig2,rho) {
#several parameters
aw <- sqrt(w^2/sig1^2 - 2*rho*w/(sig1*sig2) + 1/sig2^2)
bw <- w*mu1/sig1^2 - rho*(mu1+mu2*w)/(sig1*sig2)+ mu2/sig2^2
c <- mu1^2/sig1^2 - 2 * rho * mu1 * mu2 / (sig1*sig2) + mu2^2/sig2^2
dw <- exp((bw^2 - c*aw^2)/(2*(1-rho^2)*aw^2))
# output from Hinkley's density formula
out <- (bw*dw / ( sqrt(2*pi) * sig1 * sig2 * aw^3)) * (pnorm(bw/aw/sqrt(1-rho^2),0,1) - pnorm(-bw/aw/sqrt(1-rho^2),0,1)) +
sqrt(1-rho^2)/(pi*sig1*sig2*aw^2) * exp(-c/(2*(1-rho^2)))
out
}
fw <- Vectorize(fw)
In the above computation, we estimated the covariance matrix for the sample distribution of the parameters $\beta_0$ and $\beta_1$ by simulating many samples. In practice, when you only have a single sample, you could be using an estimate of the variance based on the observed information matrix (for instance when you use in R the glm function, then you can obtain estimates for the covariance, based on the observed information matrix by using the vcov function) .
2 Improving normal approximation for parameter $\beta_1$
The above result, using $K_m = \beta_1/\beta_0$ is still not great because the normal approximation for the parameter $\beta_1$ is not perfect. However, with some trial and error, I found that a scaled noncentral t-distribution is a very good fit (I have some intuitive idea about it but I can not yet explain so well why, let alone proof it).
h <- hist(bm/am, breaks = seq(-2,3,0.02), freq = 0 , xlim = c(-0.2,1.3), ylim = c(0,3),
main = "histogram compared with normal and t-distribution",
xlab = expression(beta[1]), cex.main = 1)
### fitting a normal distribution
s <- seq(0,22,0.001)
lines(s,dnorm(s,mean(bm/am),var(bm/am)^0.5))
### fitting a t-distribution to the histogram
xw <- h$mids
yw <- h$density
wfit <- nls(yw ~ dt(xw*a, df, ncp)*a, start = list(a=2,df=1, ncp = 0.5),
control = nls.control(tol = 10^-5, maxiter = 10^5),
algorithm = 'port',
lower = c(0.1,0.1,0.1))
wfit
lines(xw,predict(wfit),col = 2)
legend(1.3,3,
c("normal approximation",
"t-distribution approximation"),
xjust = 1, cex = 0.7, col = c(1,2), lty = 1 )
Special case with measurements in two points
If you measure in only two points $x=s$ and $x = t$, then you could reparameterize the curve in terms of the values in those two points $y(s)$ and $y(t)$. The parameter $K_m$ will be
$$K_m = \frac{y(t)-y(s)}{y(s)/s-y(t)/t}$$
Since estimates of $y(t)$ and $y(s)$ will be independent and normally distributed the sample distribution of the estimate of $K_m$ will be the ratio of two correlated normal distributions.
The computation below illustrates this with a perfect match.
The fit with a lognormal distribution is actually not so bad either (and I needed to use some extreme parameters to make the difference clearly visible). There might be a connection between a product/ratio distribution and the lognormal distribution. It is similar to this question/answer where you have a variable that is a product of several terms. This is the same as the exponent of the sum of the log of those terms. That sum might be approximately normal distributed if either you have a lot of terms or when you have a few terms that are already approximately normal distributed.
$$K_m = e^{\log(K_m/V_{max}) - \log(1/V_{max})}$$
set.seed(1)
### parameters
a = 50
b = 5
n <- 10^5
t = 2
s = 4
### two arrays of sample distribution of parameters
am <- rep(0,n)
bm <- rep(0,n)
### perform n times a computation to view the sample distribution
x <- c(t,s)
for (i in 1:n) {
y <- a*x/(x+b)+rnorm(length(x),0,1)
mod <- lm(1/y ~ 1+I(1/x))
am[i] <- 1/coef(mod)[1]
bm[i] <- coef(mod)[2]/coef(mod)[1]
}
### histogram
h <- hist(bm, breaks = c(-10^5,seq(-100,100,0.2),10^5), freq = 0 , xlim = c(0,15), ylim = c(0,0.30),
main = "special case of measurement in two points",
xlab = "Km", cex.main = 1)
### plotting fit with lognormal distribution
xw <- h$mids
yw <- h$density
wfit <- nls(yw ~ dlnorm(xw, mu, sd), start = list(mu = log(5), sd = 0.5),
control = nls.control(tol = 10^-5, maxiter = 10^5),
algorithm = 'port',
lower = c(0.1,0.1))
wfit
lines(xw,predict(wfit),col = 1)
### plotting ratio distribution
### means, sigma and distribution
y1 = a*s/(b+s)
y2 = a*t/(b+t)
cc = -(1/s + 1/t)/sqrt(1+1)/sqrt(1/t^2+1/s^2)
lines(ts,fw(ts, mu1 = y2-y1 ,
mu2 = y1/s-y2/t,
sig1 = sqrt(1+1),
sig2 = sqrt(1/t^2+1/s^2),
rho = cc ),
col = 2)
legend(15,0.3,
c("ratio distribution", "fit with lognormal"),
xjust = 1, cex = 0.7, col = c(2,1), lty = 1 ) | How to determine the distribution of a parameter fit by nonlinear regression
My questions are:
For this example, can algebra and/or calculus prove that the distribution of Km values is lognormal (or prove it has some other distribution)?
More generally, what method can be use |
20,505 | Why doesn't deep learning work as well in regression as in classification? | In my opinion, the following might be one -but not the only- reason for the relatively low popularity of Deep Learning in regression problems:
Much of the success of modern Neural Networks comes from their ability to exploit the compositional nature of the world. This is, in perception problems such as image or audio analysis, features have an order (spatial or temporal) and local patterns aggregate to form higher level concepts and objects (e.g, a picture of a car is made of wheels and other parts, which are made of lower level visual features, which are made of basic shapes like edges, circles and lines, etc.). Modern Neural Networks such as Convolutional Neural Networks take advantage of this by learning increasingly abstract features in the deeper layers. These ideas are explained in more detail in these slides by Hinton et al. [1]
Conversely, classical regression problems consist of a number of non-ordered features, and the target value can be predicted fairly well with a shallow linear/nonlinear model of the input features. In some sense, this compositional property present in problems such as image classification or speech recognition is not present in problems such as "Predict the income of an individual based on their sex, age, nationality, academic degree, family size...".
This might explain why some of the regression problems where Deep Learning is more popular are those based on images (e.g., Age prediction based on face photography).
Of course, these are only some intuitive ideas, and a more formal analysis of this problem is certainly a nice research topic. Deep Learning is certainly a field where more theoretical guarantees and insights are needed.
[1] https://www.iro.umontreal.ca/~bengioy/talks/DL-Tutorial-NIPS2015.pdf | Why doesn't deep learning work as well in regression as in classification? | In my opinion, the following might be one -but not the only- reason for the relatively low popularity of Deep Learning in regression problems:
Much of the success of modern Neural Networks comes from | Why doesn't deep learning work as well in regression as in classification?
In my opinion, the following might be one -but not the only- reason for the relatively low popularity of Deep Learning in regression problems:
Much of the success of modern Neural Networks comes from their ability to exploit the compositional nature of the world. This is, in perception problems such as image or audio analysis, features have an order (spatial or temporal) and local patterns aggregate to form higher level concepts and objects (e.g, a picture of a car is made of wheels and other parts, which are made of lower level visual features, which are made of basic shapes like edges, circles and lines, etc.). Modern Neural Networks such as Convolutional Neural Networks take advantage of this by learning increasingly abstract features in the deeper layers. These ideas are explained in more detail in these slides by Hinton et al. [1]
Conversely, classical regression problems consist of a number of non-ordered features, and the target value can be predicted fairly well with a shallow linear/nonlinear model of the input features. In some sense, this compositional property present in problems such as image classification or speech recognition is not present in problems such as "Predict the income of an individual based on their sex, age, nationality, academic degree, family size...".
This might explain why some of the regression problems where Deep Learning is more popular are those based on images (e.g., Age prediction based on face photography).
Of course, these are only some intuitive ideas, and a more formal analysis of this problem is certainly a nice research topic. Deep Learning is certainly a field where more theoretical guarantees and insights are needed.
[1] https://www.iro.umontreal.ca/~bengioy/talks/DL-Tutorial-NIPS2015.pdf | Why doesn't deep learning work as well in regression as in classification?
In my opinion, the following might be one -but not the only- reason for the relatively low popularity of Deep Learning in regression problems:
Much of the success of modern Neural Networks comes from |
20,506 | Why doesn't deep learning work as well in regression as in classification? | My experience with deep neural networks (DNN) on regression convinced myself that it does not work well if the number of features are high and the accuracy requirement is also high. The probable reason is that the DNN is a only a function approximator. When the original function is complicated and # of features are high, it is very difficult to have “right” model for DNN, the training seems to alternate between underfitting and overfitting if you change the size of DNN and/or size of training data. | Why doesn't deep learning work as well in regression as in classification? | My experience with deep neural networks (DNN) on regression convinced myself that it does not work well if the number of features are high and the accuracy requirement is also high. The probable reaso | Why doesn't deep learning work as well in regression as in classification?
My experience with deep neural networks (DNN) on regression convinced myself that it does not work well if the number of features are high and the accuracy requirement is also high. The probable reason is that the DNN is a only a function approximator. When the original function is complicated and # of features are high, it is very difficult to have “right” model for DNN, the training seems to alternate between underfitting and overfitting if you change the size of DNN and/or size of training data. | Why doesn't deep learning work as well in regression as in classification?
My experience with deep neural networks (DNN) on regression convinced myself that it does not work well if the number of features are high and the accuracy requirement is also high. The probable reaso |
20,507 | Why doesn't deep learning work as well in regression as in classification? | You can "use" deep learning for regression. You have to consider the following:
You can use a fully connected neural network for regression, just don't use any activation unit in the end (i.e. take out the RELU, sigmoid) and just let the input parameter flow-out (y=x). Consider that a NN with one neuron without activation unit is basically a simple linear regression.
More generally this is not what you want, you will be using a very complicated structure of chained linear regressions that can tend to overfitting. Ridge regressions, Lasso, SVR and Bayesian predictors would do a better job at it and you would have better control about what you want to do. | Why doesn't deep learning work as well in regression as in classification? | You can "use" deep learning for regression. You have to consider the following:
You can use a fully connected neural network for regression, just don't use any activation unit in the end (i.e. take o | Why doesn't deep learning work as well in regression as in classification?
You can "use" deep learning for regression. You have to consider the following:
You can use a fully connected neural network for regression, just don't use any activation unit in the end (i.e. take out the RELU, sigmoid) and just let the input parameter flow-out (y=x). Consider that a NN with one neuron without activation unit is basically a simple linear regression.
More generally this is not what you want, you will be using a very complicated structure of chained linear regressions that can tend to overfitting. Ridge regressions, Lasso, SVR and Bayesian predictors would do a better job at it and you would have better control about what you want to do. | Why doesn't deep learning work as well in regression as in classification?
You can "use" deep learning for regression. You have to consider the following:
You can use a fully connected neural network for regression, just don't use any activation unit in the end (i.e. take o |
20,508 | Variational Inference, KL divergence requires true $p$ | I have a feeling that you treat $p$ as a completely unknown object. I do not think this is the case. This is probably what you missed.
Say we observe $Y = \{y_i\}_{i=1}^n$ (i.i.d.) and we want to infer $p(x|Y)$ where we assume that $p(y|x)$ and $p(x)$ for $x\in\mathbb{R}^d$ are specified by the model. By Bayes' rule,
$$p(x|Y) = \frac{p(x)}{p(Y)}p(Y|x)
= \frac{p(x)}{p(Y)}\prod_{i=1}^n p(y_i|x).$$
The first observation is that we know something about the posterior distribution $p(x|Y)$. It is given as above. Typically, we just do not know its normalizer $p(Y)$. If the likelihood $p(y|x)$ is very complicated, then we end up having some complicated distribution $p(x|Y)$.
The second thing that makes it possible to do variational inference is that there is a constraint on the form that $q$ can take. Without any constraint, $\arg \min_q KL(p||q)$ would be $p$ which is usually intractable. Typically, $q$ is assumed to live in a chosen subset of the exponential family. For example, this might be the family of fully factorized Gaussian distributions i.e., $q \in \mathcal{Q} = \{\prod_{i=1}^d q_i(x_i) \mid \text{each } q_i \text{ is a one-dimensional Gaussian}\}$. It turns out that if this is your constraint set, then each component of $q$ is given by
$$q_i \propto \exp( \mathbb{E}_{\prod_{j\neq i} q_j} \log p(x, Y) ), $$
where $p(x, Y) = p(x) \prod_{i=1}^n p(y_i|x).$ The exact formula does not matter much. The point is the approximate $q$ can be found by relying on the knowledge of the true $p$, and the assumption on the form that the approximate $q$ should take.
Update
The following is to answer the updated part in the question. I just realized that I have been thinking about $KL(q||p(x|Y))$. I will always use $p$ for the true quantity, and $q$ for an approximate one. In variational inference or variational Bayes, $q$ is given by
$$q = \arg \min_{q \in \mathcal{Q}} KL(q\, ||\, p(x|Y)).$$
With the constraint set $\mathcal{Q}$ as above, the solution is the one given previously. Now if you are thinking about
$$q = \arg \min_{q \in \mathcal{Q}} KL( p(x|Y) \, || \, q),$$
for $\mathcal{Q}$ defined to be a subset of the exponential family, then this inference is called expectation propagation (EP). The solution for $q$ in this case is the one such that its moments match that of $p(x|Y)$.
Either way, you are right in saying that essentially you try to approximate the true posterior distribution in the KL sense by a distribution $q$ constrained to take some form. | Variational Inference, KL divergence requires true $p$ | I have a feeling that you treat $p$ as a completely unknown object. I do not think this is the case. This is probably what you missed.
Say we observe $Y = \{y_i\}_{i=1}^n$ (i.i.d.) and we want to infe | Variational Inference, KL divergence requires true $p$
I have a feeling that you treat $p$ as a completely unknown object. I do not think this is the case. This is probably what you missed.
Say we observe $Y = \{y_i\}_{i=1}^n$ (i.i.d.) and we want to infer $p(x|Y)$ where we assume that $p(y|x)$ and $p(x)$ for $x\in\mathbb{R}^d$ are specified by the model. By Bayes' rule,
$$p(x|Y) = \frac{p(x)}{p(Y)}p(Y|x)
= \frac{p(x)}{p(Y)}\prod_{i=1}^n p(y_i|x).$$
The first observation is that we know something about the posterior distribution $p(x|Y)$. It is given as above. Typically, we just do not know its normalizer $p(Y)$. If the likelihood $p(y|x)$ is very complicated, then we end up having some complicated distribution $p(x|Y)$.
The second thing that makes it possible to do variational inference is that there is a constraint on the form that $q$ can take. Without any constraint, $\arg \min_q KL(p||q)$ would be $p$ which is usually intractable. Typically, $q$ is assumed to live in a chosen subset of the exponential family. For example, this might be the family of fully factorized Gaussian distributions i.e., $q \in \mathcal{Q} = \{\prod_{i=1}^d q_i(x_i) \mid \text{each } q_i \text{ is a one-dimensional Gaussian}\}$. It turns out that if this is your constraint set, then each component of $q$ is given by
$$q_i \propto \exp( \mathbb{E}_{\prod_{j\neq i} q_j} \log p(x, Y) ), $$
where $p(x, Y) = p(x) \prod_{i=1}^n p(y_i|x).$ The exact formula does not matter much. The point is the approximate $q$ can be found by relying on the knowledge of the true $p$, and the assumption on the form that the approximate $q$ should take.
Update
The following is to answer the updated part in the question. I just realized that I have been thinking about $KL(q||p(x|Y))$. I will always use $p$ for the true quantity, and $q$ for an approximate one. In variational inference or variational Bayes, $q$ is given by
$$q = \arg \min_{q \in \mathcal{Q}} KL(q\, ||\, p(x|Y)).$$
With the constraint set $\mathcal{Q}$ as above, the solution is the one given previously. Now if you are thinking about
$$q = \arg \min_{q \in \mathcal{Q}} KL( p(x|Y) \, || \, q),$$
for $\mathcal{Q}$ defined to be a subset of the exponential family, then this inference is called expectation propagation (EP). The solution for $q$ in this case is the one such that its moments match that of $p(x|Y)$.
Either way, you are right in saying that essentially you try to approximate the true posterior distribution in the KL sense by a distribution $q$ constrained to take some form. | Variational Inference, KL divergence requires true $p$
I have a feeling that you treat $p$ as a completely unknown object. I do not think this is the case. This is probably what you missed.
Say we observe $Y = \{y_i\}_{i=1}^n$ (i.i.d.) and we want to infe |
20,509 | What classification algorithm should one use after seeing that t-SNE separates classes well? | First a brief answer, and then a longer comment:
Answer
SNE techniques compute an N ×N similarity matrix in both the original data space and in the low-dimensional embedding space in such a way that the similarities
form a probability distribution over pairs of objects. Specifically, the probabilities are generally given by a normalized Gaussian kernel computed from the input data or from the embedding. In terms of classification, this immediately brings to mind instance-based learning methods. You have listed one of them: SVM's with RBF, and @amoeba has listed kNN. There are also radial basis function networks, which I am not an expert on.
Comment
Having said that, I would be doubly careful about making inferences on a dataset just looking at t-SNE plots. t-SNE does not necessarily focus on the local structure. However, you can adjust it to do so by tuning the perplexity parameter, which regulates (loosely) how to balance attention between local and global aspects of your data.
In this context, perplexity itself is a stab in the dark on how many close neighbours each observation may have and is user-provided. The original paper states: “The performance of t-SNE is fairly robust to changes in the perplexity, and typical values are between 5 and 50.” However, my experience is that getting the most from t-SNE may mean analyzing multiple plots with different perplexities.
In other words, tuning learning rate and perplexity, it is possible to obtain very different looking 2-d plots for the same number of training steps and using the same data.
This Distill paper How to Use t-SNE Effectively gives a great summary of the common pitfalls of t-SNE analysis. The summary points are:
Those hyperparameters (e.g. learning rate, perplexity) really matter
Cluster sizes in a t-SNE plot mean nothing
Distances between clusters might not mean anything
Random noise doesn’t always look random.
You can see some shapes, sometimes
For topology, you may need more than one plot
Specifically from points 2, 3, and 6 above, I would think twice about making inferences about the separability of the data by looking at individual t-SNE plots. There are many cases where you can 'manufacture' plots that show clear clusters using the right parameters. | What classification algorithm should one use after seeing that t-SNE separates classes well? | First a brief answer, and then a longer comment:
Answer
SNE techniques compute an N ×N similarity matrix in both the original data space and in the low-dimensional embedding space in such a way that t | What classification algorithm should one use after seeing that t-SNE separates classes well?
First a brief answer, and then a longer comment:
Answer
SNE techniques compute an N ×N similarity matrix in both the original data space and in the low-dimensional embedding space in such a way that the similarities
form a probability distribution over pairs of objects. Specifically, the probabilities are generally given by a normalized Gaussian kernel computed from the input data or from the embedding. In terms of classification, this immediately brings to mind instance-based learning methods. You have listed one of them: SVM's with RBF, and @amoeba has listed kNN. There are also radial basis function networks, which I am not an expert on.
Comment
Having said that, I would be doubly careful about making inferences on a dataset just looking at t-SNE plots. t-SNE does not necessarily focus on the local structure. However, you can adjust it to do so by tuning the perplexity parameter, which regulates (loosely) how to balance attention between local and global aspects of your data.
In this context, perplexity itself is a stab in the dark on how many close neighbours each observation may have and is user-provided. The original paper states: “The performance of t-SNE is fairly robust to changes in the perplexity, and typical values are between 5 and 50.” However, my experience is that getting the most from t-SNE may mean analyzing multiple plots with different perplexities.
In other words, tuning learning rate and perplexity, it is possible to obtain very different looking 2-d plots for the same number of training steps and using the same data.
This Distill paper How to Use t-SNE Effectively gives a great summary of the common pitfalls of t-SNE analysis. The summary points are:
Those hyperparameters (e.g. learning rate, perplexity) really matter
Cluster sizes in a t-SNE plot mean nothing
Distances between clusters might not mean anything
Random noise doesn’t always look random.
You can see some shapes, sometimes
For topology, you may need more than one plot
Specifically from points 2, 3, and 6 above, I would think twice about making inferences about the separability of the data by looking at individual t-SNE plots. There are many cases where you can 'manufacture' plots that show clear clusters using the right parameters. | What classification algorithm should one use after seeing that t-SNE separates classes well?
First a brief answer, and then a longer comment:
Answer
SNE techniques compute an N ×N similarity matrix in both the original data space and in the low-dimensional embedding space in such a way that t |
20,510 | When to use GLM instead of LM? | A GLM is a more general version of a linear model: the linear model is a special case of a Gaussian GLM with the identity link. So the question is then: why do we use other link functions or other mean-variance relationships? We fit GLMs because they answer a specific question that we are interested in.
There is, for instance, nothing inherently wrong with fitting a binary response in a linear regression model if you are interested in the association between these variables. Indeed if a higher proportion of negative outcomes tends to be observed in the lower 50th percentile of an exposure and a higher proportion of positive outcomes is observed in the upper 50th percentile, this will yield a positively sloped line which correctly describes a positive association between these two variables.
Alternately, you might be interested in modeling the aforementioned association using an S shaped curve. The slope and the intercept of such a curve account for a tendency of extreme risk to tend toward 0/1 probability. Also the slope of a logit curve is interpreted as a log-odds ratio. That motivates use of a logit link function. Similarly, fitted probabilities very close to 1 or 0 may tend to be less variable under replications of study design, and so could be accounted for by a binomial mean-variance relationship saying that $se(\hat{Y}) = \hat{Y}(1-\hat{Y})$ which motivates logistic regression. Along those lines, a more modern approach to this problem would suggest fitting a relative risk model which utilizes a log link, such that the slope of the exponential trend line is interpreted as a log-relative risk, a more practical value than a log-odds-ratio. | When to use GLM instead of LM? | A GLM is a more general version of a linear model: the linear model is a special case of a Gaussian GLM with the identity link. So the question is then: why do we use other link functions or other mea | When to use GLM instead of LM?
A GLM is a more general version of a linear model: the linear model is a special case of a Gaussian GLM with the identity link. So the question is then: why do we use other link functions or other mean-variance relationships? We fit GLMs because they answer a specific question that we are interested in.
There is, for instance, nothing inherently wrong with fitting a binary response in a linear regression model if you are interested in the association between these variables. Indeed if a higher proportion of negative outcomes tends to be observed in the lower 50th percentile of an exposure and a higher proportion of positive outcomes is observed in the upper 50th percentile, this will yield a positively sloped line which correctly describes a positive association between these two variables.
Alternately, you might be interested in modeling the aforementioned association using an S shaped curve. The slope and the intercept of such a curve account for a tendency of extreme risk to tend toward 0/1 probability. Also the slope of a logit curve is interpreted as a log-odds ratio. That motivates use of a logit link function. Similarly, fitted probabilities very close to 1 or 0 may tend to be less variable under replications of study design, and so could be accounted for by a binomial mean-variance relationship saying that $se(\hat{Y}) = \hat{Y}(1-\hat{Y})$ which motivates logistic regression. Along those lines, a more modern approach to this problem would suggest fitting a relative risk model which utilizes a log link, such that the slope of the exponential trend line is interpreted as a log-relative risk, a more practical value than a log-odds-ratio. | When to use GLM instead of LM?
A GLM is a more general version of a linear model: the linear model is a special case of a Gaussian GLM with the identity link. So the question is then: why do we use other link functions or other mea |
20,511 | When to use GLM instead of LM? | Well, there are plenty of reasons to choose a different error distribution. But I believe that you aren't aware on why we have distributions for variables in the first place. If this is obvious to, I believe my answer is useless to you, sorry.
Why distributions are important
See, having distributions allows us to consider a model in a probabilistic, meaning we can quantify uncertainties about our model. When in stat 101 we learn that the sampling distribution of the sample mean $\bar{X} \dot{\sim} \mathcal{N}(\mu,\sigma)$ (asymptotically), we can, in a probabilistic framework, tell a lot of stuff about that estimate, like testing hypothesis, constructing confidence intervals.
Probabilistic Distributions in linear and generalized linear models
When in a linear model framework, we can basically do the same, if we know the the distribution of the error term. Why? This a result of linear combination of random variables (see this answer). But the point is, when this probabilistic structure is present in the model, we can again do sorts of stuff. Most notably, besides hypothesis testing and constructing C.I, we can build predictions with quantified uncertainty, model selection, goodness of fit testes and a bunch of other stuff.
Now why do we need GLMs specifically? Firstly, the probabilistic framework of a linear model can't handle different types of that, such as counts or binary data. Those types of data are intrinsically different them a regular continuous data, meaning its possible to have a height of 1.83 meters, but its senseless to have 4.5 electrical lights not working.
Therefore the motivation for GLMs starts with handling different types of data, primarily by the use of link functions or/and by cleverly manipulating the intended model to a linear known "framework". These needs and ideas are connected directly to how the errors are modeled by the "framework" being used. | When to use GLM instead of LM? | Well, there are plenty of reasons to choose a different error distribution. But I believe that you aren't aware on why we have distributions for variables in the first place. If this is obvious to, I | When to use GLM instead of LM?
Well, there are plenty of reasons to choose a different error distribution. But I believe that you aren't aware on why we have distributions for variables in the first place. If this is obvious to, I believe my answer is useless to you, sorry.
Why distributions are important
See, having distributions allows us to consider a model in a probabilistic, meaning we can quantify uncertainties about our model. When in stat 101 we learn that the sampling distribution of the sample mean $\bar{X} \dot{\sim} \mathcal{N}(\mu,\sigma)$ (asymptotically), we can, in a probabilistic framework, tell a lot of stuff about that estimate, like testing hypothesis, constructing confidence intervals.
Probabilistic Distributions in linear and generalized linear models
When in a linear model framework, we can basically do the same, if we know the the distribution of the error term. Why? This a result of linear combination of random variables (see this answer). But the point is, when this probabilistic structure is present in the model, we can again do sorts of stuff. Most notably, besides hypothesis testing and constructing C.I, we can build predictions with quantified uncertainty, model selection, goodness of fit testes and a bunch of other stuff.
Now why do we need GLMs specifically? Firstly, the probabilistic framework of a linear model can't handle different types of that, such as counts or binary data. Those types of data are intrinsically different them a regular continuous data, meaning its possible to have a height of 1.83 meters, but its senseless to have 4.5 electrical lights not working.
Therefore the motivation for GLMs starts with handling different types of data, primarily by the use of link functions or/and by cleverly manipulating the intended model to a linear known "framework". These needs and ideas are connected directly to how the errors are modeled by the "framework" being used. | When to use GLM instead of LM?
Well, there are plenty of reasons to choose a different error distribution. But I believe that you aren't aware on why we have distributions for variables in the first place. If this is obvious to, I |
20,512 | When to use GLM instead of LM? | There are two things we should care about,
consistency,
efficiency.
If we don't have 1, screw 2. But if we have 1, we would like to get 2 if possible.
If you run OLS, then it is consistent under very general assumptions about the error distribution (you just need exogeneity). However, GLS can be more efficient. This is particularly nice if you have a small sample. | When to use GLM instead of LM? | There are two things we should care about,
consistency,
efficiency.
If we don't have 1, screw 2. But if we have 1, we would like to get 2 if possible.
If you run OLS, then it is consistent under | When to use GLM instead of LM?
There are two things we should care about,
consistency,
efficiency.
If we don't have 1, screw 2. But if we have 1, we would like to get 2 if possible.
If you run OLS, then it is consistent under very general assumptions about the error distribution (you just need exogeneity). However, GLS can be more efficient. This is particularly nice if you have a small sample. | When to use GLM instead of LM?
There are two things we should care about,
consistency,
efficiency.
If we don't have 1, screw 2. But if we have 1, we would like to get 2 if possible.
If you run OLS, then it is consistent under |
20,513 | difference between sample_weight and class_weight RandomForest Classifier | You are using the sample_weights wrong. What you want to use is the
class_weights. Sample weights are used to increase the importance of a
single data-point (let's say, some of your data is more trustworthy,
then they receive a higher weight). So: The sample weights exist to
change the importance of data-points whereas the class weights change
the weights to correct class imbalance. They can be used together with
their purpose in mind. In your example, using class weights has no
effect whatsoever, because you abused the sample weights to do the job
of the class weights. | difference between sample_weight and class_weight RandomForest Classifier | You are using the sample_weights wrong. What you want to use is the
class_weights. Sample weights are used to increase the importance of a
single data-point (let's say, some of your data is more t | difference between sample_weight and class_weight RandomForest Classifier
You are using the sample_weights wrong. What you want to use is the
class_weights. Sample weights are used to increase the importance of a
single data-point (let's say, some of your data is more trustworthy,
then they receive a higher weight). So: The sample weights exist to
change the importance of data-points whereas the class weights change
the weights to correct class imbalance. They can be used together with
their purpose in mind. In your example, using class weights has no
effect whatsoever, because you abused the sample weights to do the job
of the class weights. | difference between sample_weight and class_weight RandomForest Classifier
You are using the sample_weights wrong. What you want to use is the
class_weights. Sample weights are used to increase the importance of a
single data-point (let's say, some of your data is more t |
20,514 | difference between sample_weight and class_weight RandomForest Classifier | Q&A
Should sample_weight and class_weight be used together simultaneously
If your goal is to weight your classes because they are imbalanced, you can use either. Using class_weight="balanced is the same as sample_weight=[n_samples].
I tested it with an unbalanced set in kaggle. I estimated the "sample_weight" based on what was given in the sklearn docs: n_samples / (n_classes * np.bincount(y))
Note: "A guide as to what weights to give is to make them inversely proportional to the class populations"--- People at Berkeley
between class_weights = "balanced" and class_weights = balanced_subsamples which is supposed to give a better performance of the classifier
You can easily test it for your dataset. It's hard for me to say. For me, recall was higher (9%) and precision was lower by 9% (on the minority) dataset.
is sample_weight supposed to be adjusted always according to ratio of imbalance in the samples?
Depends on what you care about. If you want the prediction error (1-recall) of all classes to be the same, then you can look at the different recalls, change your weights and until they balance out. Note: This WILL reduce your overall prediction error.
This is suggested by "some people" at Uni of Berkeley. However, I was not able to balance out my 1-recall despite increasing my minority class weight by a lot (1000 from 26).
Here is a comparison table for one of the kaggle contests I am working on:
tr recall
vd recall
tr prec
vd prec
baseline
37.4
26.9
94.8
79.6
balanced (1,26)
67.6 (80%)
30.2 (12%)
88.7 (-6.5%)
75.3 (-5.5%)
subsample balanced
67.5 (80%)
32.9 (22%)
88.0 (-7.2%)
70.9 (-11.7%)
overweighting (1,1000)
65.3 (80%)
25.1 (-7%)
84.5 (-10.9%)
84.0 (5%)
class_weights = balanced_subsamples and sample_weight give an execution error when used simultaneously. why?
Not sure. | difference between sample_weight and class_weight RandomForest Classifier | Q&A
Should sample_weight and class_weight be used together simultaneously
If your goal is to weight your classes because they are imbalanced, you can use either. Using class_weight="balanced is the | difference between sample_weight and class_weight RandomForest Classifier
Q&A
Should sample_weight and class_weight be used together simultaneously
If your goal is to weight your classes because they are imbalanced, you can use either. Using class_weight="balanced is the same as sample_weight=[n_samples].
I tested it with an unbalanced set in kaggle. I estimated the "sample_weight" based on what was given in the sklearn docs: n_samples / (n_classes * np.bincount(y))
Note: "A guide as to what weights to give is to make them inversely proportional to the class populations"--- People at Berkeley
between class_weights = "balanced" and class_weights = balanced_subsamples which is supposed to give a better performance of the classifier
You can easily test it for your dataset. It's hard for me to say. For me, recall was higher (9%) and precision was lower by 9% (on the minority) dataset.
is sample_weight supposed to be adjusted always according to ratio of imbalance in the samples?
Depends on what you care about. If you want the prediction error (1-recall) of all classes to be the same, then you can look at the different recalls, change your weights and until they balance out. Note: This WILL reduce your overall prediction error.
This is suggested by "some people" at Uni of Berkeley. However, I was not able to balance out my 1-recall despite increasing my minority class weight by a lot (1000 from 26).
Here is a comparison table for one of the kaggle contests I am working on:
tr recall
vd recall
tr prec
vd prec
baseline
37.4
26.9
94.8
79.6
balanced (1,26)
67.6 (80%)
30.2 (12%)
88.7 (-6.5%)
75.3 (-5.5%)
subsample balanced
67.5 (80%)
32.9 (22%)
88.0 (-7.2%)
70.9 (-11.7%)
overweighting (1,1000)
65.3 (80%)
25.1 (-7%)
84.5 (-10.9%)
84.0 (5%)
class_weights = balanced_subsamples and sample_weight give an execution error when used simultaneously. why?
Not sure. | difference between sample_weight and class_weight RandomForest Classifier
Q&A
Should sample_weight and class_weight be used together simultaneously
If your goal is to weight your classes because they are imbalanced, you can use either. Using class_weight="balanced is the |
20,515 | What is the difference between beta regression and quasi glm with variance = $\mu(1-\mu)$? | You're correct that the mean and variance functions are of the same form.
This suggests that in very large samples, as long as you don't have observations really close to 1 or 0 they should tend to give quite similar answers because in that situation observations will have similar relative weights.
But in smaller samples where some of the continuous proportions approach the bounds, the differences can grow larger because the relative weights given by the two approaches will differ; if the points that get different weights are also relatively influential (more extreme in x-space), the differences may in some cases become substantial.
In beta-regression you'd be estimating via ML, and in the case of a quasibinomial model - at least one estimated in R, note this comment in the help:
The quasibinomial and quasipoisson families differ from the binomial and poisson families only in that the dispersion parameter is not fixed at one, so they can model over-dispersion. For the binomial case see McCullagh and Nelder (1989, pp. 124–8). Although they show that there is (under some restrictions) a model with variance proportional to mean as in the quasi-binomial model, note that glm does not compute maximum-likelihood estimates in that model. The behaviour of S is closer to the quasi- variants.
I think in betareg you can get $h_{ii}$ values, and you can as well for GLMs, so at the two fitted models you can compare an approximation of each observation's relative influence (/"weight") on its own fitted value (since the other components of the ratio of influences should cancel, or nearly so). This should give a quick sense of which observations are looked at most differently by the two approaches. [One might do it more exactly by actually tweaking the observations one by one and seeing the change in fit per unit change in value]
Note that the betareg vignette gives some discussion of the connection between these models at the end of section 2. | What is the difference between beta regression and quasi glm with variance = $\mu(1-\mu)$? | You're correct that the mean and variance functions are of the same form.
This suggests that in very large samples, as long as you don't have observations really close to 1 or 0 they should tend to gi | What is the difference between beta regression and quasi glm with variance = $\mu(1-\mu)$?
You're correct that the mean and variance functions are of the same form.
This suggests that in very large samples, as long as you don't have observations really close to 1 or 0 they should tend to give quite similar answers because in that situation observations will have similar relative weights.
But in smaller samples where some of the continuous proportions approach the bounds, the differences can grow larger because the relative weights given by the two approaches will differ; if the points that get different weights are also relatively influential (more extreme in x-space), the differences may in some cases become substantial.
In beta-regression you'd be estimating via ML, and in the case of a quasibinomial model - at least one estimated in R, note this comment in the help:
The quasibinomial and quasipoisson families differ from the binomial and poisson families only in that the dispersion parameter is not fixed at one, so they can model over-dispersion. For the binomial case see McCullagh and Nelder (1989, pp. 124–8). Although they show that there is (under some restrictions) a model with variance proportional to mean as in the quasi-binomial model, note that glm does not compute maximum-likelihood estimates in that model. The behaviour of S is closer to the quasi- variants.
I think in betareg you can get $h_{ii}$ values, and you can as well for GLMs, so at the two fitted models you can compare an approximation of each observation's relative influence (/"weight") on its own fitted value (since the other components of the ratio of influences should cancel, or nearly so). This should give a quick sense of which observations are looked at most differently by the two approaches. [One might do it more exactly by actually tweaking the observations one by one and seeing the change in fit per unit change in value]
Note that the betareg vignette gives some discussion of the connection between these models at the end of section 2. | What is the difference between beta regression and quasi glm with variance = $\mu(1-\mu)$?
You're correct that the mean and variance functions are of the same form.
This suggests that in very large samples, as long as you don't have observations really close to 1 or 0 they should tend to gi |
20,516 | Derivation of the standard error for Pearson's correlation coefficient | After looking for a long time for an answer to this same question, I found a couple interesting links:
$\bullet$ The Standard Deviation of the Correlation Coefficient, where we can only see the first page but that's where the derivation is. The "standard deviation by dr Sheppard" is given by something called the Asymptotic distribution of moments, of which you can see a bit in the following source.
$\bullet$ A History of Parametric Statistical Inference from Bernoulli to Fisher, 1713-1935.
The reason for the "n-2" instead of "n" in the root, is that your formula assumes a t-distribution with n-2 degrees of freedom, while the one in the links assumes a normal distribution. | Derivation of the standard error for Pearson's correlation coefficient | After looking for a long time for an answer to this same question, I found a couple interesting links:
$\bullet$ The Standard Deviation of the Correlation Coefficient, where we can only see the first | Derivation of the standard error for Pearson's correlation coefficient
After looking for a long time for an answer to this same question, I found a couple interesting links:
$\bullet$ The Standard Deviation of the Correlation Coefficient, where we can only see the first page but that's where the derivation is. The "standard deviation by dr Sheppard" is given by something called the Asymptotic distribution of moments, of which you can see a bit in the following source.
$\bullet$ A History of Parametric Statistical Inference from Bernoulli to Fisher, 1713-1935.
The reason for the "n-2" instead of "n" in the root, is that your formula assumes a t-distribution with n-2 degrees of freedom, while the one in the links assumes a normal distribution. | Derivation of the standard error for Pearson's correlation coefficient
After looking for a long time for an answer to this same question, I found a couple interesting links:
$\bullet$ The Standard Deviation of the Correlation Coefficient, where we can only see the first |
20,517 | Derivation of the standard error for Pearson's correlation coefficient | There are two equations here for computing the statistical significance of the correlation coefficient. The first is the variance of the true correlation coefficient $\rho$ of two bivariate normal random variables:\begin{equation}\text{var}\left(r\right)=\frac{\left(1-\rho^2\right)^2}{n},\end{equation} and the second is a t-statistic associated with the hypothesis that in the linear regression of $Y$ on $X$, the main effect of $X$ is zero:\begin{equation}t=r\sqrt{\frac{n-2}{1-r^2}}.\end{equation}Whence the standard error of $r$ mentioned by the OP: $\text{se}\left(r\right)=\sqrt{\frac{1-r^2}{n-2}}$.
Both of these expression can derived from the principle of maximum-likelihood. That is, if we assume a parameter $\theta$ should be distributed normally,\begin{equation}\mathcal{L}\left(\theta\right)\sim\exp{\left(-\frac{\theta^2}{2\sigma^2_{\theta}}\right)},\end{equation}then the standard error of the parameter can be estimated from the curvature of the log-likelihood $\ell=\log{\mathcal{L}}$, function via\begin{equation}\sigma^2_{\theta}=\frac{-1}{\frac{\partial^2\ell}{\partial\theta^2}\bigr|_{\theta=\hat{\theta}}},\end{equation}where $\hat{\theta}$ is the maximum-likelihood estimate of $\theta$, got from the condition\begin{equation}\frac{\partial\ell}{\partial\theta}\bigr|_{\theta=\hat{\theta}}=0.\end{equation}
Now, Pearson derived the first expression \begin{equation}\text{var}\left(r\right)=\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}\end{equation} in VII. Mathematical contributions to the theory of evolution.-III. Regression, heredity, and panmixia and https://royalsocietypublishing.org/doi/10.1098/rspl.1897.0091 by expanding the joint distribution of $n$ pairs of bivariate normal variables about the true value of $\rho$. We can summarize his method here. If we let $f$ be the bivariate normal density of two zero-mean random variables, i.e.,\begin{equation}f\left(X,Y\right)=\frac{1}{2\pi\sqrt{1-\rho^2}\sigma_X\sigma_Y}\exp{\left(-\frac{X^2}{2\sigma_X^2\left(1-\rho^2\right)}+-\frac{\rho XY}{2\sigma_X\sigma_Y\left(1-\rho^2\right)}-\frac{Y^2}{2\sigma_Y^2\left(1-\rho^2\right)}\right)},\end{equation}then we can get the variance $\sigma^2_{\rho}$ of the correlation coefficient by evaluating $\frac{-\partial^2\log{f}}{\partial \rho^2}\bigr|_{\rho=\hat{\rho}}$. The first derivative of $\log{f}$ is\begin{align}\frac{\partial\log{f}}{\partial \rho}&=\frac{\rho}{1-\rho^2}+\frac{2\rho}{1-\rho^2}\cdot\frac{-X^2}{2\left(1-\rho^2\right)\sigma_X^2}+\left(\frac{1}{1-\rho^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}\right)\frac{XY}{\sigma_X\sigma_Y}+\frac{2\rho}{1-\rho^2}\cdot\frac{-X^2}{2\left(1-\rho^2\right)\sigma_Y^2}\nonumber\\&=\frac{\rho}{1-\rho^2}+\left(\frac{2\rho}{1-\rho^2}\right)\left(\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right)+\frac{1}{1-\rho^2}\frac{XY}{\sigma_X\sigma_Y},\end{align}where at the maximum-likelihood solution $\hat{\rho}=\frac{\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y}$ the middle term becomes\begin{equation}\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}=-\frac{\mathbb{E}\left(X^2\right)}{\sigma_X^2\left(1-\rho^2\right)}+\frac{\rho\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y\left(1-\rho^2\right)}-\frac{\mathbb{E}\left(Y^2\right)}{\sigma_X^2\left(1-\rho^2\right)}=-1.\end{equation}Whence upon taking the second derivative and evaluating at $\rho=\hat{\rho}$, we get\begin{align}\frac{\partial^2\log{f}}{\partial\rho^2}\bigr|_{\rho=\hat{\rho^2}}&=\left(\frac{1}{1-\rho^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}\right)+\frac{2\rho}{\left(1-\rho^2\right)^2}\frac{\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y}+\left(\frac{2}{1-\rho^2}+{4\rho^2}{\left(1-\rho^2\right)}\right)\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}+\frac{2\rho}{1-\rho^2}\frac{\partial}{\partial\rho}\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}\nonumber\\&=\frac{1+\rho^2}{\left(1-\rho^2\right)^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}-2\left(\frac{1+\rho^2}{\left(1-\rho^2\right)^2}\right)-\frac{2\rho^2}{\left(1-\rho\right)^2},\end{align}so that\begin{equation}\sigma^2_{\rho}=\frac{-1}{\frac{\partial^2\log{f}}{\partial\rho^2}\bigr|_{\rho=\hat{\rho}}}=\frac{\left(1-\rho^2\right)^2}{1+\rho^2}.\end{equation}Then by the central limit theorem, the sampling variance of $\rho$ is $\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}$.
For the second form of the statistic, let's drop the assumption of bivariate normality and consider the regression of $Y$ on $X$ with normally-distributed error $\varepsilon$: if\begin{equation}Y=\alpha+\beta X+\varepsilon\end{equation}and\begin{equation}\sigma^2_Y=\beta^2\sigma^2_X+\sigma^2,\end{equation} then according to the relationship $\beta=\rho\frac{\sigma_Y}{\sigma_X}$, it must be the case that error variance is $\sigma^2=\left(1-\rho^2\right)\sigma^2_Y$. Then the distribution of $\varepsilon$ is:\begin{equation}\mathcal{L}\left(\varepsilon\right)\sim\Pi_i\exp{\left(-\frac{\left(Y_i-\alpha-\beta X_i\right)^2}{2\sigma^2}\right)},\end{equation}so that the log-likelihood is\begin{equation}\ell=-\sum_i\frac{\left(Y_i-\alpha-\beta X_i\right)^2}{2\left(1-\rho^2\right)\sigma_Y^2}.\end{equation}The first two derivatives are\begin{equation}\frac{\partial\ell}{\partial \beta}=\sum_i\frac{\left(Y_i-\overline{Y}-\beta\left(X_i-\overline{X}\right)\right)\left(X_i-\overline{X}\right)}{\left(1-\rho^2\right)\sigma_Y^2}\end{equation}and\begin{equation}\frac{\partial^2\ell}{\partial\beta^2}=-\sum_i\frac{\left(X_i-\overline{X}\right)^2}{\left(1-\rho^2\right)\sigma_Y^2}.\end{equation}Now, making the substitution $\beta=\rho\frac{\sigma_Y}{\sigma_X}$ and evaluating at $\rho=\hat{\rho}=r$ gives\begin{equation}\frac{-1}{\frac{\partial^2\ell}{\partial\beta^2}\bigr|_{\beta=\hat{\beta}}}=\frac{-1}{\frac{\partial^2\ell}{\partial\rho^2}\bigr|_{\rho=\hat{\rho}}}\frac{\sigma^2_Y}{\sigma^2_X}=\frac{\sigma^2_Y\left(1-r^2\right)}{\sigma^2_X\left(n-2\right)},\end{equation}whence the sampling variance of the measured correlation coefficient $\hat{\rho}=r$ is\begin{equation}\sigma^2_r=\frac{1-r^2}{n-2},\end{equation} in which we lose two degrees of freedom from the estimation of two parameters $\alpha$ and $\beta$. Finally, we can form a t-statistic to test the hypothesis that $r=0$ using \begin{equation}t=\frac{r}{\sigma_r}=r\sqrt{\frac{n-2}{1-r^2}}.\end{equation}For an alternate derivation, see The Analysis of Physical Measurements, pp. 193-199, by Pugh and Winslow cited in A brief note on the standard error of the Pearson correlation.
A comparison of the two formulas shows\begin{equation}\frac{\sigma^2_{\rho}}{n}=\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}<\frac{1-r^2}{n-2}=\sigma^2_r.\end{equation}In other words, there is less variance of the true parameter $\rho$ than in the value estimated from linear regression. It should also be pointed out that Pearson's formula is only true for bivariate normal variables, while the standard error of $r$ is valid for any linear regression. However, we see that the test of whether $r=0$ is equivalent to the test of whether $\beta=0$ and does not really tell us anything new. | Derivation of the standard error for Pearson's correlation coefficient | There are two equations here for computing the statistical significance of the correlation coefficient. The first is the variance of the true correlation coefficient $\rho$ of two bivariate normal ra | Derivation of the standard error for Pearson's correlation coefficient
There are two equations here for computing the statistical significance of the correlation coefficient. The first is the variance of the true correlation coefficient $\rho$ of two bivariate normal random variables:\begin{equation}\text{var}\left(r\right)=\frac{\left(1-\rho^2\right)^2}{n},\end{equation} and the second is a t-statistic associated with the hypothesis that in the linear regression of $Y$ on $X$, the main effect of $X$ is zero:\begin{equation}t=r\sqrt{\frac{n-2}{1-r^2}}.\end{equation}Whence the standard error of $r$ mentioned by the OP: $\text{se}\left(r\right)=\sqrt{\frac{1-r^2}{n-2}}$.
Both of these expression can derived from the principle of maximum-likelihood. That is, if we assume a parameter $\theta$ should be distributed normally,\begin{equation}\mathcal{L}\left(\theta\right)\sim\exp{\left(-\frac{\theta^2}{2\sigma^2_{\theta}}\right)},\end{equation}then the standard error of the parameter can be estimated from the curvature of the log-likelihood $\ell=\log{\mathcal{L}}$, function via\begin{equation}\sigma^2_{\theta}=\frac{-1}{\frac{\partial^2\ell}{\partial\theta^2}\bigr|_{\theta=\hat{\theta}}},\end{equation}where $\hat{\theta}$ is the maximum-likelihood estimate of $\theta$, got from the condition\begin{equation}\frac{\partial\ell}{\partial\theta}\bigr|_{\theta=\hat{\theta}}=0.\end{equation}
Now, Pearson derived the first expression \begin{equation}\text{var}\left(r\right)=\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}\end{equation} in VII. Mathematical contributions to the theory of evolution.-III. Regression, heredity, and panmixia and https://royalsocietypublishing.org/doi/10.1098/rspl.1897.0091 by expanding the joint distribution of $n$ pairs of bivariate normal variables about the true value of $\rho$. We can summarize his method here. If we let $f$ be the bivariate normal density of two zero-mean random variables, i.e.,\begin{equation}f\left(X,Y\right)=\frac{1}{2\pi\sqrt{1-\rho^2}\sigma_X\sigma_Y}\exp{\left(-\frac{X^2}{2\sigma_X^2\left(1-\rho^2\right)}+-\frac{\rho XY}{2\sigma_X\sigma_Y\left(1-\rho^2\right)}-\frac{Y^2}{2\sigma_Y^2\left(1-\rho^2\right)}\right)},\end{equation}then we can get the variance $\sigma^2_{\rho}$ of the correlation coefficient by evaluating $\frac{-\partial^2\log{f}}{\partial \rho^2}\bigr|_{\rho=\hat{\rho}}$. The first derivative of $\log{f}$ is\begin{align}\frac{\partial\log{f}}{\partial \rho}&=\frac{\rho}{1-\rho^2}+\frac{2\rho}{1-\rho^2}\cdot\frac{-X^2}{2\left(1-\rho^2\right)\sigma_X^2}+\left(\frac{1}{1-\rho^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}\right)\frac{XY}{\sigma_X\sigma_Y}+\frac{2\rho}{1-\rho^2}\cdot\frac{-X^2}{2\left(1-\rho^2\right)\sigma_Y^2}\nonumber\\&=\frac{\rho}{1-\rho^2}+\left(\frac{2\rho}{1-\rho^2}\right)\left(\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right)+\frac{1}{1-\rho^2}\frac{XY}{\sigma_X\sigma_Y},\end{align}where at the maximum-likelihood solution $\hat{\rho}=\frac{\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y}$ the middle term becomes\begin{equation}\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}=-\frac{\mathbb{E}\left(X^2\right)}{\sigma_X^2\left(1-\rho^2\right)}+\frac{\rho\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y\left(1-\rho^2\right)}-\frac{\mathbb{E}\left(Y^2\right)}{\sigma_X^2\left(1-\rho^2\right)}=-1.\end{equation}Whence upon taking the second derivative and evaluating at $\rho=\hat{\rho}$, we get\begin{align}\frac{\partial^2\log{f}}{\partial\rho^2}\bigr|_{\rho=\hat{\rho^2}}&=\left(\frac{1}{1-\rho^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}\right)+\frac{2\rho}{\left(1-\rho^2\right)^2}\frac{\mathbb{E}\left(XY\right)}{\sigma_X\sigma_Y}+\left(\frac{2}{1-\rho^2}+{4\rho^2}{\left(1-\rho^2\right)}\right)\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}+\frac{2\rho}{1-\rho^2}\frac{\partial}{\partial\rho}\left[\log{f}-\log{\frac{1}{2\pi\sigma_X\sigma_Y\sqrt{1-\rho^2}}}\right]\bigr|_{\rho=\hat{\rho}}\nonumber\\&=\frac{1+\rho^2}{\left(1-\rho^2\right)^2}+\frac{2\rho^2}{\left(1-\rho^2\right)^2}-2\left(\frac{1+\rho^2}{\left(1-\rho^2\right)^2}\right)-\frac{2\rho^2}{\left(1-\rho\right)^2},\end{align}so that\begin{equation}\sigma^2_{\rho}=\frac{-1}{\frac{\partial^2\log{f}}{\partial\rho^2}\bigr|_{\rho=\hat{\rho}}}=\frac{\left(1-\rho^2\right)^2}{1+\rho^2}.\end{equation}Then by the central limit theorem, the sampling variance of $\rho$ is $\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}$.
For the second form of the statistic, let's drop the assumption of bivariate normality and consider the regression of $Y$ on $X$ with normally-distributed error $\varepsilon$: if\begin{equation}Y=\alpha+\beta X+\varepsilon\end{equation}and\begin{equation}\sigma^2_Y=\beta^2\sigma^2_X+\sigma^2,\end{equation} then according to the relationship $\beta=\rho\frac{\sigma_Y}{\sigma_X}$, it must be the case that error variance is $\sigma^2=\left(1-\rho^2\right)\sigma^2_Y$. Then the distribution of $\varepsilon$ is:\begin{equation}\mathcal{L}\left(\varepsilon\right)\sim\Pi_i\exp{\left(-\frac{\left(Y_i-\alpha-\beta X_i\right)^2}{2\sigma^2}\right)},\end{equation}so that the log-likelihood is\begin{equation}\ell=-\sum_i\frac{\left(Y_i-\alpha-\beta X_i\right)^2}{2\left(1-\rho^2\right)\sigma_Y^2}.\end{equation}The first two derivatives are\begin{equation}\frac{\partial\ell}{\partial \beta}=\sum_i\frac{\left(Y_i-\overline{Y}-\beta\left(X_i-\overline{X}\right)\right)\left(X_i-\overline{X}\right)}{\left(1-\rho^2\right)\sigma_Y^2}\end{equation}and\begin{equation}\frac{\partial^2\ell}{\partial\beta^2}=-\sum_i\frac{\left(X_i-\overline{X}\right)^2}{\left(1-\rho^2\right)\sigma_Y^2}.\end{equation}Now, making the substitution $\beta=\rho\frac{\sigma_Y}{\sigma_X}$ and evaluating at $\rho=\hat{\rho}=r$ gives\begin{equation}\frac{-1}{\frac{\partial^2\ell}{\partial\beta^2}\bigr|_{\beta=\hat{\beta}}}=\frac{-1}{\frac{\partial^2\ell}{\partial\rho^2}\bigr|_{\rho=\hat{\rho}}}\frac{\sigma^2_Y}{\sigma^2_X}=\frac{\sigma^2_Y\left(1-r^2\right)}{\sigma^2_X\left(n-2\right)},\end{equation}whence the sampling variance of the measured correlation coefficient $\hat{\rho}=r$ is\begin{equation}\sigma^2_r=\frac{1-r^2}{n-2},\end{equation} in which we lose two degrees of freedom from the estimation of two parameters $\alpha$ and $\beta$. Finally, we can form a t-statistic to test the hypothesis that $r=0$ using \begin{equation}t=\frac{r}{\sigma_r}=r\sqrt{\frac{n-2}{1-r^2}}.\end{equation}For an alternate derivation, see The Analysis of Physical Measurements, pp. 193-199, by Pugh and Winslow cited in A brief note on the standard error of the Pearson correlation.
A comparison of the two formulas shows\begin{equation}\frac{\sigma^2_{\rho}}{n}=\frac{\left(1-\rho^2\right)^2}{n\left(1+\rho^2\right)}<\frac{1-r^2}{n-2}=\sigma^2_r.\end{equation}In other words, there is less variance of the true parameter $\rho$ than in the value estimated from linear regression. It should also be pointed out that Pearson's formula is only true for bivariate normal variables, while the standard error of $r$ is valid for any linear regression. However, we see that the test of whether $r=0$ is equivalent to the test of whether $\beta=0$ and does not really tell us anything new. | Derivation of the standard error for Pearson's correlation coefficient
There are two equations here for computing the statistical significance of the correlation coefficient. The first is the variance of the true correlation coefficient $\rho$ of two bivariate normal ra |
20,518 | Derivation of the standard error for Pearson's correlation coefficient | I do not have the answer, but for me there is an error in the formula of the question.
It is: $$SE_r =\frac{1-r^2}{\sqrt{n-2}}$$ and
$$\newcommand{\Var}{\operatorname{Var}} \Var(r)=\frac{(1-r^2)^2}{n-2}$$
I will try to check this by simulation:
library(MASS)
N = 100000
r = 0.8
n = 100
Sigma = matrix(c(1, r, r, 1), nrow=2)
r_obs = replicate(N, cor(mvrnorm(n, c(0,0), Sigma))[2,1])
> mean(r_obs)
[1] 0.7984783
> sd(r_obs)
[1] 0.03690896
So the standard error for r=0.8 with n=100 is approximately 0.037.
If I use the formula of the question I get:
> sqrt((1-r^2)/(n-2))
[1] 0.06060915
And with the formula I gave:
> (1-r^2)/sqrt((n-2))
[1] 0.03636549
The second formula seems to be much closer to the true value than the first.
Edit:
To try to explain why there are two different formulas for the standard error which are circulating, I found that it depends on how you compute it.
In my first simulation, I used Pearson formula to compute the correlation, but one can also use the least square regression coefficient. I can confirm that the latter method has the standard error proposed in the question:
r_obs <- replicate(N, {
M<-mvrnorm(n, c(0,0), Sigma)
c(pearson=cor(M, method="pearson")[2,1],
regression=lm(M[,2]~M[,1])$coef[[2]])
})
> apply(r_obs, 1, mean)
pearson regression
0.7981580 0.7998433
> apply(r_obs, 1, sd)
pearson regression
0.03707184 0.06094964
These are two estimators of the correlation which do not have the same variance.
Edit 2:
That try to reconcile the two formulas did not work, because I forgot to normalize the regression coefficient. The formula to compute the correlation from the regression coefficient is:
$$r=\frac{SD(x)}{SD(y)}b$$ with $$E(y|x)=a+b\cdot x$$
By redoing the correct computation, I obtain in fact the same result:
r_obs <- replicate(N, {
M<-mvrnorm(n, c(0,0), Sigma)
c(pearson=cor(M, method="pearson")[2,1],
regression=lm(M[,2]~M[,1])$coef[[2]]*sd(M[,1])/sd(M[,2]))
})
> apply(r_obs, 1, sd)
pearson regression
0.03676248 0.03676248
> apply(r_obs, 1, mean)
pearson regression
0.7992615 0.7992615
Which is reassuring in some way. So I maintain that the standard error formula in the question is incorrect, but maybe I explained where does the error come from. | Derivation of the standard error for Pearson's correlation coefficient | I do not have the answer, but for me there is an error in the formula of the question.
It is: $$SE_r =\frac{1-r^2}{\sqrt{n-2}}$$ and
$$\newcommand{\Var}{\operatorname{Var}} \Var(r)=\frac{(1-r^2)^2}{n | Derivation of the standard error for Pearson's correlation coefficient
I do not have the answer, but for me there is an error in the formula of the question.
It is: $$SE_r =\frac{1-r^2}{\sqrt{n-2}}$$ and
$$\newcommand{\Var}{\operatorname{Var}} \Var(r)=\frac{(1-r^2)^2}{n-2}$$
I will try to check this by simulation:
library(MASS)
N = 100000
r = 0.8
n = 100
Sigma = matrix(c(1, r, r, 1), nrow=2)
r_obs = replicate(N, cor(mvrnorm(n, c(0,0), Sigma))[2,1])
> mean(r_obs)
[1] 0.7984783
> sd(r_obs)
[1] 0.03690896
So the standard error for r=0.8 with n=100 is approximately 0.037.
If I use the formula of the question I get:
> sqrt((1-r^2)/(n-2))
[1] 0.06060915
And with the formula I gave:
> (1-r^2)/sqrt((n-2))
[1] 0.03636549
The second formula seems to be much closer to the true value than the first.
Edit:
To try to explain why there are two different formulas for the standard error which are circulating, I found that it depends on how you compute it.
In my first simulation, I used Pearson formula to compute the correlation, but one can also use the least square regression coefficient. I can confirm that the latter method has the standard error proposed in the question:
r_obs <- replicate(N, {
M<-mvrnorm(n, c(0,0), Sigma)
c(pearson=cor(M, method="pearson")[2,1],
regression=lm(M[,2]~M[,1])$coef[[2]])
})
> apply(r_obs, 1, mean)
pearson regression
0.7981580 0.7998433
> apply(r_obs, 1, sd)
pearson regression
0.03707184 0.06094964
These are two estimators of the correlation which do not have the same variance.
Edit 2:
That try to reconcile the two formulas did not work, because I forgot to normalize the regression coefficient. The formula to compute the correlation from the regression coefficient is:
$$r=\frac{SD(x)}{SD(y)}b$$ with $$E(y|x)=a+b\cdot x$$
By redoing the correct computation, I obtain in fact the same result:
r_obs <- replicate(N, {
M<-mvrnorm(n, c(0,0), Sigma)
c(pearson=cor(M, method="pearson")[2,1],
regression=lm(M[,2]~M[,1])$coef[[2]]*sd(M[,1])/sd(M[,2]))
})
> apply(r_obs, 1, sd)
pearson regression
0.03676248 0.03676248
> apply(r_obs, 1, mean)
pearson regression
0.7992615 0.7992615
Which is reassuring in some way. So I maintain that the standard error formula in the question is incorrect, but maybe I explained where does the error come from. | Derivation of the standard error for Pearson's correlation coefficient
I do not have the answer, but for me there is an error in the formula of the question.
It is: $$SE_r =\frac{1-r^2}{\sqrt{n-2}}$$ and
$$\newcommand{\Var}{\operatorname{Var}} \Var(r)=\frac{(1-r^2)^2}{n |
20,519 | Intuition for the degrees of freedom of the LASSO | Assume we are given a set of $n$ $p$-dimensional observations, $x_i \in \mathbb{R}^p$, $i = 1, \dotsc, n$. Assume a model of the form:
\begin{align}
Y_i = \langle \beta, x_i\rangle + \epsilon
\end{align}
where $\epsilon \sim N(0, \sigma^2)$, $\beta \in \mathbb{R}^p$, and $\langle \cdot, \cdot \rangle$ denoting the inner product. Let $\hat{\beta} = \delta(\{Y_i\}_{i=1}^n)$ be an estimate of $\beta$ using fitting method $\delta$ (either OLS or LASSO for our purposes). The formula for degrees of freedom given in the article (equation 1.2) is:
\begin{align}
\text{df}(\hat{\beta}) = \sum_{i=1}^n \frac{\text{Cov}(\langle\hat{\beta}, x_i\rangle, Y_i)}{\sigma^2}.
\end{align}
By inspecting this formula we can surmise that, in accordance with your intuition, the true DOF for the LASSO will indeed be less than the true DOF of OLS; the coefficient-shrinkage effected by the LASSO should tend to decrease the covariances.
Now, to answer your question, the reason that the DOF for the LASSO is the same as the DOF for OLS in your example is just that there you are dealing with estimates (albeit unbiased ones), obtained from a particular dataset sampled from the model, of the true DOF values. For any particular dataset, such an estimate will not be equal to the true value (especially since the estimate is required to be an integer while the true value is a real number in general).
However, when such estimates are averaged over many datasets sampled from the model, by unbiasedness and the law of large numbers such an average will converge to the true DOF. In the case of the LASSO, some of those datasets will result in an estimator wherein the coefficient is actually 0 (though such datasets might be rare if $\lambda$ is small). In the case of OLS, the estimate of the DOF is always the number of coefficients, not the number of non-zero coefficients, and so the average for the OLS case will not contain these zeros. This shows how the estimators differ, and how the average estimator for the LASSO DOF can converge to something smaller than the average estimator for the OLS DOF. | Intuition for the degrees of freedom of the LASSO | Assume we are given a set of $n$ $p$-dimensional observations, $x_i \in \mathbb{R}^p$, $i = 1, \dotsc, n$. Assume a model of the form:
\begin{align}
Y_i = \langle \beta, x_i\rangle + \epsilon
\end{ali | Intuition for the degrees of freedom of the LASSO
Assume we are given a set of $n$ $p$-dimensional observations, $x_i \in \mathbb{R}^p$, $i = 1, \dotsc, n$. Assume a model of the form:
\begin{align}
Y_i = \langle \beta, x_i\rangle + \epsilon
\end{align}
where $\epsilon \sim N(0, \sigma^2)$, $\beta \in \mathbb{R}^p$, and $\langle \cdot, \cdot \rangle$ denoting the inner product. Let $\hat{\beta} = \delta(\{Y_i\}_{i=1}^n)$ be an estimate of $\beta$ using fitting method $\delta$ (either OLS or LASSO for our purposes). The formula for degrees of freedom given in the article (equation 1.2) is:
\begin{align}
\text{df}(\hat{\beta}) = \sum_{i=1}^n \frac{\text{Cov}(\langle\hat{\beta}, x_i\rangle, Y_i)}{\sigma^2}.
\end{align}
By inspecting this formula we can surmise that, in accordance with your intuition, the true DOF for the LASSO will indeed be less than the true DOF of OLS; the coefficient-shrinkage effected by the LASSO should tend to decrease the covariances.
Now, to answer your question, the reason that the DOF for the LASSO is the same as the DOF for OLS in your example is just that there you are dealing with estimates (albeit unbiased ones), obtained from a particular dataset sampled from the model, of the true DOF values. For any particular dataset, such an estimate will not be equal to the true value (especially since the estimate is required to be an integer while the true value is a real number in general).
However, when such estimates are averaged over many datasets sampled from the model, by unbiasedness and the law of large numbers such an average will converge to the true DOF. In the case of the LASSO, some of those datasets will result in an estimator wherein the coefficient is actually 0 (though such datasets might be rare if $\lambda$ is small). In the case of OLS, the estimate of the DOF is always the number of coefficients, not the number of non-zero coefficients, and so the average for the OLS case will not contain these zeros. This shows how the estimators differ, and how the average estimator for the LASSO DOF can converge to something smaller than the average estimator for the OLS DOF. | Intuition for the degrees of freedom of the LASSO
Assume we are given a set of $n$ $p$-dimensional observations, $x_i \in \mathbb{R}^p$, $i = 1, \dotsc, n$. Assume a model of the form:
\begin{align}
Y_i = \langle \beta, x_i\rangle + \epsilon
\end{ali |
20,520 | Difference between ElasticNet in scikit-learn Python and Glmnet in R | Finally I got the same values with the following code :
Python
# normalize function that gives the same with R
def mystandardize(D):
S = np.std(D, axis=0, ddof=1)
M = np.mean(D, axis = 0)
D_norm = (D-M)/S
return [D_norm, M, S]
Y_norm_train = pd.DataFrame(mystandardize(Y_train)[0])
glmnet_regr = linear_model.ElasticNet(alpha=1, l1_ratio = 0.01,
fit_intercept = True, normalize = False, tol=0.0000001, max_iter = 100000)
glmnet_regr.fit(X_train, Y_norm_train)
R
y_norm_train <- scale(y[train_idx])
glmnet_obj_norm <- glmnet(x_train, y_norm_train, alpha=0.01, lambda = 1,
thresh = 1e-07, standardize = FALSE, intercept=TRUE, standardize.response = FALSE)
print_coef(glmnet_obj_norm) | Difference between ElasticNet in scikit-learn Python and Glmnet in R | Finally I got the same values with the following code :
Python
# normalize function that gives the same with R
def mystandardize(D):
S = np.std(D, axis=0, ddof=1)
M = np.mean(D, axis = 0)
D_n | Difference between ElasticNet in scikit-learn Python and Glmnet in R
Finally I got the same values with the following code :
Python
# normalize function that gives the same with R
def mystandardize(D):
S = np.std(D, axis=0, ddof=1)
M = np.mean(D, axis = 0)
D_norm = (D-M)/S
return [D_norm, M, S]
Y_norm_train = pd.DataFrame(mystandardize(Y_train)[0])
glmnet_regr = linear_model.ElasticNet(alpha=1, l1_ratio = 0.01,
fit_intercept = True, normalize = False, tol=0.0000001, max_iter = 100000)
glmnet_regr.fit(X_train, Y_norm_train)
R
y_norm_train <- scale(y[train_idx])
glmnet_obj_norm <- glmnet(x_train, y_norm_train, alpha=0.01, lambda = 1,
thresh = 1e-07, standardize = FALSE, intercept=TRUE, standardize.response = FALSE)
print_coef(glmnet_obj_norm) | Difference between ElasticNet in scikit-learn Python and Glmnet in R
Finally I got the same values with the following code :
Python
# normalize function that gives the same with R
def mystandardize(D):
S = np.std(D, axis=0, ddof=1)
M = np.mean(D, axis = 0)
D_n |
20,521 | Comparing mixed-effects and fixed-effects models (testing significance of random effects) | Technically, you can get it working by just switching the order of the parameters:
> anova(fit.me, fit.fe)
Will work just fine. If you pass an object generated by lmer first, the anova.merMod will be called instead of anova.lm (which does not know how to handle lmer objects). See:
?anova.merMod
Although, choosing a mixed model or a fixed model is a modeling choice which needs to take into account the experimental design, not a model selection problem. See @BenBolker's https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html#testing-significance-of-random-effects for more details:
Consider not testing the significance of random effects. | Comparing mixed-effects and fixed-effects models (testing significance of random effects) | Technically, you can get it working by just switching the order of the parameters:
> anova(fit.me, fit.fe)
Will work just fine. If you pass an object generated by lmer first, the anova.merMod will b | Comparing mixed-effects and fixed-effects models (testing significance of random effects)
Technically, you can get it working by just switching the order of the parameters:
> anova(fit.me, fit.fe)
Will work just fine. If you pass an object generated by lmer first, the anova.merMod will be called instead of anova.lm (which does not know how to handle lmer objects). See:
?anova.merMod
Although, choosing a mixed model or a fixed model is a modeling choice which needs to take into account the experimental design, not a model selection problem. See @BenBolker's https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html#testing-significance-of-random-effects for more details:
Consider not testing the significance of random effects. | Comparing mixed-effects and fixed-effects models (testing significance of random effects)
Technically, you can get it working by just switching the order of the parameters:
> anova(fit.me, fit.fe)
Will work just fine. If you pass an object generated by lmer first, the anova.merMod will b |
20,522 | Why should we remove seasonality from a time series? | Burman, J. Peter (1980), “Seasonal Adjustment by Signal Extraction,” Journal of the Royal Statistical Society, Series A, 143, p.321
The reasons according to Burman:
The most common is to provide an estimate of the current trend so
that judgemental short-term forecasts can be made. Alternatively, it
may be applied to a large number of series which enter an economic
model, as it has been found impracticable to use unadjusted data with
seasonal dummies in all but the smallest models: this is often called
the historical mode of seasonal adjustment
Shiskin, Julius (1957), “Electronic Computers and Business Indicators", Journal of Business, 30, 219-267.
A principal purpose of studying economic indicators is to determine
the stage of the business cycle at which the economy stands. Such
knowledge helps in forecasting subsequent cyclical movements and
provides a factual basis for taking steps to moderate the amplitude
and scope of the business cycle. . . . In using indicators, however,
analysts are perennially troubled by the difficulty of separating
cyclical from other types of fluctuations, particularly seasonal
fluctuations.
If you want my 2 kopeks, then I'd summarize it like this:
Convenience: If you deal with multiple economic series, each of them will have its own seasonality. It becomes impractical to deal with seasonality of each series in multivariate models. So, it's easier to de-seasonalize all economic series before adding them to multivariate models, or analyzing them together.
Trend extraction: many economic series are inherently seasonal, e.g. house prices are higher in summer. Hence, when house price index suddenly goes down, it is not always because it signals something important in economy, but it could simply be the seasonal drop, which has no significant information. Hence, we want to deseasonalize the series to understand where we are. | Why should we remove seasonality from a time series? | Burman, J. Peter (1980), “Seasonal Adjustment by Signal Extraction,” Journal of the Royal Statistical Society, Series A, 143, p.321
The reasons according to Burman:
The most common is to provide an | Why should we remove seasonality from a time series?
Burman, J. Peter (1980), “Seasonal Adjustment by Signal Extraction,” Journal of the Royal Statistical Society, Series A, 143, p.321
The reasons according to Burman:
The most common is to provide an estimate of the current trend so
that judgemental short-term forecasts can be made. Alternatively, it
may be applied to a large number of series which enter an economic
model, as it has been found impracticable to use unadjusted data with
seasonal dummies in all but the smallest models: this is often called
the historical mode of seasonal adjustment
Shiskin, Julius (1957), “Electronic Computers and Business Indicators", Journal of Business, 30, 219-267.
A principal purpose of studying economic indicators is to determine
the stage of the business cycle at which the economy stands. Such
knowledge helps in forecasting subsequent cyclical movements and
provides a factual basis for taking steps to moderate the amplitude
and scope of the business cycle. . . . In using indicators, however,
analysts are perennially troubled by the difficulty of separating
cyclical from other types of fluctuations, particularly seasonal
fluctuations.
If you want my 2 kopeks, then I'd summarize it like this:
Convenience: If you deal with multiple economic series, each of them will have its own seasonality. It becomes impractical to deal with seasonality of each series in multivariate models. So, it's easier to de-seasonalize all economic series before adding them to multivariate models, or analyzing them together.
Trend extraction: many economic series are inherently seasonal, e.g. house prices are higher in summer. Hence, when house price index suddenly goes down, it is not always because it signals something important in economy, but it could simply be the seasonal drop, which has no significant information. Hence, we want to deseasonalize the series to understand where we are. | Why should we remove seasonality from a time series?
Burman, J. Peter (1980), “Seasonal Adjustment by Signal Extraction,” Journal of the Royal Statistical Society, Series A, 143, p.321
The reasons according to Burman:
The most common is to provide an |
20,523 | Why should we remove seasonality from a time series? | When looking at relationships between two variables which are time series, seasonality will reduce the degrees of freedom because the data will not be independent. This "serial" correlation will result in spurious correlations. Thus the seasonality is removed with the goal of increasing the degrees of freedom. | Why should we remove seasonality from a time series? | When looking at relationships between two variables which are time series, seasonality will reduce the degrees of freedom because the data will not be independent. This "serial" correlation will resul | Why should we remove seasonality from a time series?
When looking at relationships between two variables which are time series, seasonality will reduce the degrees of freedom because the data will not be independent. This "serial" correlation will result in spurious correlations. Thus the seasonality is removed with the goal of increasing the degrees of freedom. | Why should we remove seasonality from a time series?
When looking at relationships between two variables which are time series, seasonality will reduce the degrees of freedom because the data will not be independent. This "serial" correlation will resul |
20,524 | Logistic Regression with regression splines in R | It is very hard to interpret your results when you have not pre-specified the model but have engaged in significant testing and resulting model modifications. And I don't recommend the global goodness of fit test you used because it has a degenerate distribution and not a $\chi^2$ distribution.
Two recommended ways to assess model fit are:
Bootstrap overfitting-corrected smooth nonparametric (e.g., *loess) calibration curve to check absolute accuracy of predictions
Examine various generalizations of the model, testing whether more flexible model specification works better. For example, do likelihood ratio or Wald $\chi^2$ tests of extra nonlinear or interaction terms.
There are some advantages of regression splines over fractional polynomials, including:
The predictor can have values $\leq 0$; you can't take logs of such values as required by FPs
You needn't worry about a predictor's origin. FPs assume that zero is a "magic" origin for predictors, whereas regression splines are invariant to shifting a predictor by a constant.
For more about regression splines and linearity and additivity assessment see my handouts at http://biostat.mc.vanderbilt.edu/CourseBios330 as well as the R rms package rcs function. For bootstrap calibration curves penalized for overfitting see the rms calibrate function. | Logistic Regression with regression splines in R | It is very hard to interpret your results when you have not pre-specified the model but have engaged in significant testing and resulting model modifications. And I don't recommend the global goodnes | Logistic Regression with regression splines in R
It is very hard to interpret your results when you have not pre-specified the model but have engaged in significant testing and resulting model modifications. And I don't recommend the global goodness of fit test you used because it has a degenerate distribution and not a $\chi^2$ distribution.
Two recommended ways to assess model fit are:
Bootstrap overfitting-corrected smooth nonparametric (e.g., *loess) calibration curve to check absolute accuracy of predictions
Examine various generalizations of the model, testing whether more flexible model specification works better. For example, do likelihood ratio or Wald $\chi^2$ tests of extra nonlinear or interaction terms.
There are some advantages of regression splines over fractional polynomials, including:
The predictor can have values $\leq 0$; you can't take logs of such values as required by FPs
You needn't worry about a predictor's origin. FPs assume that zero is a "magic" origin for predictors, whereas regression splines are invariant to shifting a predictor by a constant.
For more about regression splines and linearity and additivity assessment see my handouts at http://biostat.mc.vanderbilt.edu/CourseBios330 as well as the R rms package rcs function. For bootstrap calibration curves penalized for overfitting see the rms calibrate function. | Logistic Regression with regression splines in R
It is very hard to interpret your results when you have not pre-specified the model but have engaged in significant testing and resulting model modifications. And I don't recommend the global goodnes |
20,525 | R: test normality of residuals of linear model - which residuals to use | Grew too long for a comment.
For an ordinary regression model (such as would be fitted by lm), there's no distinction between the first two residual types you consider; type="pearson" is relevant for non-Gaussian GLMs, but is the same as response for gaussian models.
The observations you apply your tests to (some form of residuals) aren't independent, so the usual statistics don't have the correct distribution. Further, strictly speaking, none of the residuals you consider will be exactly normal, since your data will never be exactly normal. [Formal testing answers the wrong question - a more relevant question would be 'how much will this non-normality impact my inference?', a question not answered by the usual goodness of fit hypothesis testing.]
Even if your data were to be exactly normal, neither the third nor the fourth kind of residual would be exactly normal. Nevertheless it's much more common for people to examine those (say by QQ plots) than the raw residuals.
You could overcome some of the issues in 2. and 3. (dependence in residuals as well as non-normality in standardized residuals) by simulation conditional on your design matrix ($\mathbf{X}$), meaning you could use whichever residuals you like (however you can't deal with the "answering an unhelpful question you already know the answer to" problem that way). | R: test normality of residuals of linear model - which residuals to use | Grew too long for a comment.
For an ordinary regression model (such as would be fitted by lm), there's no distinction between the first two residual types you consider; type="pearson" is relevant for | R: test normality of residuals of linear model - which residuals to use
Grew too long for a comment.
For an ordinary regression model (such as would be fitted by lm), there's no distinction between the first two residual types you consider; type="pearson" is relevant for non-Gaussian GLMs, but is the same as response for gaussian models.
The observations you apply your tests to (some form of residuals) aren't independent, so the usual statistics don't have the correct distribution. Further, strictly speaking, none of the residuals you consider will be exactly normal, since your data will never be exactly normal. [Formal testing answers the wrong question - a more relevant question would be 'how much will this non-normality impact my inference?', a question not answered by the usual goodness of fit hypothesis testing.]
Even if your data were to be exactly normal, neither the third nor the fourth kind of residual would be exactly normal. Nevertheless it's much more common for people to examine those (say by QQ plots) than the raw residuals.
You could overcome some of the issues in 2. and 3. (dependence in residuals as well as non-normality in standardized residuals) by simulation conditional on your design matrix ($\mathbf{X}$), meaning you could use whichever residuals you like (however you can't deal with the "answering an unhelpful question you already know the answer to" problem that way). | R: test normality of residuals of linear model - which residuals to use
Grew too long for a comment.
For an ordinary regression model (such as would be fitted by lm), there's no distinction between the first two residual types you consider; type="pearson" is relevant for |
20,526 | Calculating ICC for random-effects logistic regression | You can use the icc()-function from the sjstats-package.
In the help-file ?sjstats::icc you find a reference to the formula for mixed models with binary response:
Wu S, Crespi CM, Wong WK. 2012. Comparison of methods for estimating
the intraclass correlation coefficient for binary responses in cancer
prevention cluster randomized trials. Contempory Clinical Trials 33:
869-880 (doi: 10.1016/j.cct.2012.05.004)
The residual deviance in logistic regression is fixed to (pi ^ 2) / 3. | Calculating ICC for random-effects logistic regression | You can use the icc()-function from the sjstats-package.
In the help-file ?sjstats::icc you find a reference to the formula for mixed models with binary response:
Wu S, Crespi CM, Wong WK. 2012. Co | Calculating ICC for random-effects logistic regression
You can use the icc()-function from the sjstats-package.
In the help-file ?sjstats::icc you find a reference to the formula for mixed models with binary response:
Wu S, Crespi CM, Wong WK. 2012. Comparison of methods for estimating
the intraclass correlation coefficient for binary responses in cancer
prevention cluster randomized trials. Contempory Clinical Trials 33:
869-880 (doi: 10.1016/j.cct.2012.05.004)
The residual deviance in logistic regression is fixed to (pi ^ 2) / 3. | Calculating ICC for random-effects logistic regression
You can use the icc()-function from the sjstats-package.
In the help-file ?sjstats::icc you find a reference to the formula for mixed models with binary response:
Wu S, Crespi CM, Wong WK. 2012. Co |
20,527 | Structural equations: how to specify interaction effects in R lavaan package | There isn't currently a method implemented at the model level, but you can create a new variable that is just attitude1*group, or you can just use multigroup analysis, which may be more appropriate in this case. | Structural equations: how to specify interaction effects in R lavaan package | There isn't currently a method implemented at the model level, but you can create a new variable that is just attitude1*group, or you can just use multigroup analysis, which may be more appropriate in | Structural equations: how to specify interaction effects in R lavaan package
There isn't currently a method implemented at the model level, but you can create a new variable that is just attitude1*group, or you can just use multigroup analysis, which may be more appropriate in this case. | Structural equations: how to specify interaction effects in R lavaan package
There isn't currently a method implemented at the model level, but you can create a new variable that is just attitude1*group, or you can just use multigroup analysis, which may be more appropriate in |
20,528 | Can you compare AIC values as long as the models are based on the same dataset? | The two models treat initial values differently. For example, after differencing, an ARIMA model is computed on fewer observations, whereas an ETS model is always computed on the full set of data. Even when the models are equivalent (e.g., an ARIMA(0,1,1) and an ETS(A,N,N)), the AIC values will be different.
Effectively, the likelihood of an ETS model is conditional on the initial state vector, whereas the likelihood of a non-stationary ARIMA model is conditional on the first few observations, even when a diffuse prior is used for the nonstationary components. | Can you compare AIC values as long as the models are based on the same dataset? | The two models treat initial values differently. For example, after differencing, an ARIMA model is computed on fewer observations, whereas an ETS model is always computed on the full set of data. Eve | Can you compare AIC values as long as the models are based on the same dataset?
The two models treat initial values differently. For example, after differencing, an ARIMA model is computed on fewer observations, whereas an ETS model is always computed on the full set of data. Even when the models are equivalent (e.g., an ARIMA(0,1,1) and an ETS(A,N,N)), the AIC values will be different.
Effectively, the likelihood of an ETS model is conditional on the initial state vector, whereas the likelihood of a non-stationary ARIMA model is conditional on the first few observations, even when a diffuse prior is used for the nonstationary components. | Can you compare AIC values as long as the models are based on the same dataset?
The two models treat initial values differently. For example, after differencing, an ARIMA model is computed on fewer observations, whereas an ETS model is always computed on the full set of data. Eve |
20,529 | Deseasonalizing count data | There is no inherent problem with using stl() to deseasonalize count data. One issue to be aware of however is that count data generally has an increasing variance as the mean increases. This is often seen in both the seasonal and random elements of the decomposition. Using stl() on the raw data will not take this into account, and hence it may be best to first take the logarithm (edit - or square root) of your data.
It doesn't matter that the trend values are not integers any more. They can be thought of in a similar way to the parameter in a Poisson distribution. Although a Poisson distributed variable must be an integer, the mean doesn't need to be.
However, this doesn't necessarily mean you can use lm() to model the trend component. There are many pitfalls in modelling trends in time series, as spurious correlations will be very difficult to avoid. More commonly people first detrend the series and then model the residual part. | Deseasonalizing count data | There is no inherent problem with using stl() to deseasonalize count data. One issue to be aware of however is that count data generally has an increasing variance as the mean increases. This is oft | Deseasonalizing count data
There is no inherent problem with using stl() to deseasonalize count data. One issue to be aware of however is that count data generally has an increasing variance as the mean increases. This is often seen in both the seasonal and random elements of the decomposition. Using stl() on the raw data will not take this into account, and hence it may be best to first take the logarithm (edit - or square root) of your data.
It doesn't matter that the trend values are not integers any more. They can be thought of in a similar way to the parameter in a Poisson distribution. Although a Poisson distributed variable must be an integer, the mean doesn't need to be.
However, this doesn't necessarily mean you can use lm() to model the trend component. There are many pitfalls in modelling trends in time series, as spurious correlations will be very difficult to avoid. More commonly people first detrend the series and then model the residual part. | Deseasonalizing count data
There is no inherent problem with using stl() to deseasonalize count data. One issue to be aware of however is that count data generally has an increasing variance as the mean increases. This is oft |
20,530 | What do the arrows in a PCA biplot mean? | Well it appears Kevin Wright should be given most of the credit to try to help explain the confusion (from R-help mail list);
The arrows are not pointing in the most-varying direction of the data.
The principal components are pointing in the most-varying direction of
the data. But you are not plotting the data on the original scale,
you are plotting the data on the rotated scale, and thus the
horizontal axis is the most-varying direction of the data.
The arrows are pointing in the direction of the variables, as
projected into the 2-d plane of the biplot.
There is no bug.
Kevin Wright
Michael Greenacre has a very excellent free online book about biplots, Biplots in Practice, and simply reading the first chapter should help motivate where the coordinates of the arrows are taken from. There are also several other questions on the site that are similar and you may be interested in, see Interpretation of biplots in principal components analysis in R and Interpretation of MDS factor plot for two examples. Also look through the questions with biplot in search on the site, as there are a few more of potential interest (it appears maybe even making a biplot tag would be useful at this point given the number of questions it has come up in). | What do the arrows in a PCA biplot mean? | Well it appears Kevin Wright should be given most of the credit to try to help explain the confusion (from R-help mail list);
The arrows are not pointing in the most-varying direction of the data.
| What do the arrows in a PCA biplot mean?
Well it appears Kevin Wright should be given most of the credit to try to help explain the confusion (from R-help mail list);
The arrows are not pointing in the most-varying direction of the data.
The principal components are pointing in the most-varying direction of
the data. But you are not plotting the data on the original scale,
you are plotting the data on the rotated scale, and thus the
horizontal axis is the most-varying direction of the data.
The arrows are pointing in the direction of the variables, as
projected into the 2-d plane of the biplot.
There is no bug.
Kevin Wright
Michael Greenacre has a very excellent free online book about biplots, Biplots in Practice, and simply reading the first chapter should help motivate where the coordinates of the arrows are taken from. There are also several other questions on the site that are similar and you may be interested in, see Interpretation of biplots in principal components analysis in R and Interpretation of MDS factor plot for two examples. Also look through the questions with biplot in search on the site, as there are a few more of potential interest (it appears maybe even making a biplot tag would be useful at this point given the number of questions it has come up in). | What do the arrows in a PCA biplot mean?
Well it appears Kevin Wright should be given most of the credit to try to help explain the confusion (from R-help mail list);
The arrows are not pointing in the most-varying direction of the data.
|
20,531 | When over/under-sampling unbalanced classes, does maximizing accuracy differ from minimizing misclassification costs? | It's a good question. Personally, my answer would be that it never makes sense to throw data away (unless it is for computational reasons), as the more data you have, the better your model of the world can be. Therefore, I would suggest that modifying the cost function in appropriate way for your task should be sufficient. For example, if you are interested in one particular rare class, you can make misclassifications of this class only more expensive; if you are interested in a balanced measure, something like Balanced Error Rate (the average of the errors on each class) or the Matthews Correlation Coefficient is appropriate; if you are interested only in overall classification error, the traditional 0-1 loss.
A modern approach to the problem is to use Active Learning. For example, Hospedales et al (2011) "Finding Rare Classes: Active Learning with Generative and Discriminative Models, IEEE Transactions on Knowledge and Data Engineering, (TKDE 2011). However I believe the these approaches are still relatively less mature. | When over/under-sampling unbalanced classes, does maximizing accuracy differ from minimizing misclas | It's a good question. Personally, my answer would be that it never makes sense to throw data away (unless it is for computational reasons), as the more data you have, the better your model of the worl | When over/under-sampling unbalanced classes, does maximizing accuracy differ from minimizing misclassification costs?
It's a good question. Personally, my answer would be that it never makes sense to throw data away (unless it is for computational reasons), as the more data you have, the better your model of the world can be. Therefore, I would suggest that modifying the cost function in appropriate way for your task should be sufficient. For example, if you are interested in one particular rare class, you can make misclassifications of this class only more expensive; if you are interested in a balanced measure, something like Balanced Error Rate (the average of the errors on each class) or the Matthews Correlation Coefficient is appropriate; if you are interested only in overall classification error, the traditional 0-1 loss.
A modern approach to the problem is to use Active Learning. For example, Hospedales et al (2011) "Finding Rare Classes: Active Learning with Generative and Discriminative Models, IEEE Transactions on Knowledge and Data Engineering, (TKDE 2011). However I believe the these approaches are still relatively less mature. | When over/under-sampling unbalanced classes, does maximizing accuracy differ from minimizing misclas
It's a good question. Personally, my answer would be that it never makes sense to throw data away (unless it is for computational reasons), as the more data you have, the better your model of the worl |
20,532 | Learning weights in a Boltzmann machine | Intuitively, you can think of visible units as "what the model sees" and hidden units as "model's state of mind". When you set all visible units to some values, you "show the data to the model". Then, when you activate hidden units, the model adjusts it's state of mind to what it sees.
Next you let the model go free and fantasize. It will become shut-in and literally see some things it's mind generates, and generate new states of mind based on those images.
What we do by adjusting the weights (and biases) is making the model believe more in the data and less in it's own fantasies. This way after some training it will believe in some (hopefully) pretty good model of data, and we can for example ask "do you believe in this pair (X,Y)? How likely do you find it? What's your opinion mr. Boltzmann Machine?"
Finally here is a brief description of Energy Based Models, which should give you some intuition where do Clamped and Free phases come from and how we want to run them.
http://deeplearning.net/tutorial/rbm.html#energy-based-models-ebm
It is funny to see that the intuitively clear update rules come out form derivation of log-likelihood of generating data by the model.
With these intuitions in mind it's now easier to answer your questions:
We have to reset the visible units to some data we would like the model to believe in. If we use the values from the end of free phase it will just continue fantasizing, end enforce it's own misguided beliefs.
It's better to do updates after the end of the phase. Especially if it's the clamped phase, it's better to give the model some time to "focus" on the data. Earlier updates will slow down convergence, as they enforce the connections when the model hasn't adjusted it's state of mind to reality yet. Updating the weight's after each equilibrium step while fantasizing should be less harmful, although I have no experience with that.
If you want to improve your intuition on EBM, BM, and RBM I'd advise watching some of Geoffrey Hinton's lectures on the subject, he has some good analogies. | Learning weights in a Boltzmann machine | Intuitively, you can think of visible units as "what the model sees" and hidden units as "model's state of mind". When you set all visible units to some values, you "show the data to the model". Then, | Learning weights in a Boltzmann machine
Intuitively, you can think of visible units as "what the model sees" and hidden units as "model's state of mind". When you set all visible units to some values, you "show the data to the model". Then, when you activate hidden units, the model adjusts it's state of mind to what it sees.
Next you let the model go free and fantasize. It will become shut-in and literally see some things it's mind generates, and generate new states of mind based on those images.
What we do by adjusting the weights (and biases) is making the model believe more in the data and less in it's own fantasies. This way after some training it will believe in some (hopefully) pretty good model of data, and we can for example ask "do you believe in this pair (X,Y)? How likely do you find it? What's your opinion mr. Boltzmann Machine?"
Finally here is a brief description of Energy Based Models, which should give you some intuition where do Clamped and Free phases come from and how we want to run them.
http://deeplearning.net/tutorial/rbm.html#energy-based-models-ebm
It is funny to see that the intuitively clear update rules come out form derivation of log-likelihood of generating data by the model.
With these intuitions in mind it's now easier to answer your questions:
We have to reset the visible units to some data we would like the model to believe in. If we use the values from the end of free phase it will just continue fantasizing, end enforce it's own misguided beliefs.
It's better to do updates after the end of the phase. Especially if it's the clamped phase, it's better to give the model some time to "focus" on the data. Earlier updates will slow down convergence, as they enforce the connections when the model hasn't adjusted it's state of mind to reality yet. Updating the weight's after each equilibrium step while fantasizing should be less harmful, although I have no experience with that.
If you want to improve your intuition on EBM, BM, and RBM I'd advise watching some of Geoffrey Hinton's lectures on the subject, he has some good analogies. | Learning weights in a Boltzmann machine
Intuitively, you can think of visible units as "what the model sees" and hidden units as "model's state of mind". When you set all visible units to some values, you "show the data to the model". Then, |
20,533 | Learning weights in a Boltzmann machine | Yes, "we reset (clamp) the visible units to one of the patterns we want to learn (with some frequency that represents the importance of that pattern)."
Yes, "we do a batch update of the weights at the end of each phase." I don't think that updating "the weights at each equilibrium step in the phase" will lead to fast convergence because the network "gets distracted" by instantaneous errors — I have implemented Boltzmann machines that way, and I remember it not working very well until I changed it to a batch update. | Learning weights in a Boltzmann machine | Yes, "we reset (clamp) the visible units to one of the patterns we want to learn (with some frequency that represents the importance of that pattern)."
Yes, "we do a batch update of the weights at the | Learning weights in a Boltzmann machine
Yes, "we reset (clamp) the visible units to one of the patterns we want to learn (with some frequency that represents the importance of that pattern)."
Yes, "we do a batch update of the weights at the end of each phase." I don't think that updating "the weights at each equilibrium step in the phase" will lead to fast convergence because the network "gets distracted" by instantaneous errors — I have implemented Boltzmann machines that way, and I remember it not working very well until I changed it to a batch update. | Learning weights in a Boltzmann machine
Yes, "we reset (clamp) the visible units to one of the patterns we want to learn (with some frequency that represents the importance of that pattern)."
Yes, "we do a batch update of the weights at the |
20,534 | Learning weights in a Boltzmann machine | Here is sample Python code for Boltzmann Machines based on Paul Ivanov's code from
http://redwood.berkeley.edu/wiki/VS265:_Homework_assignments
import numpy as np
def extract_patches(im,SZ,n):
imsize,imsize=im.shape;
X=np.zeros((n,SZ**2),dtype=np.int8);
startsx= np.random.randint(imsize-SZ,size=n)
startsy=np.random.randint(imsize-SZ,size=n)
for i,stx,sty in zip(xrange(n), startsx,startsy):
P=im[sty:sty+SZ, stx:stx+SZ];
X[i]=2*P.flat[:]-1;
return X.T
def sample(T,b,n,num_init_samples):
"""
sample.m - sample states from model distribution
function S = sample(T,b,n, num_init_samples)
T: weight matrix
b: bias
n: number of samples
num_init_samples: number of initial Gibbs sweeps
"""
N=T.shape[0]
# initialize state vector for sampling
s=2*(np.random.rand(N)<sigmoid(b))-1
for k in xrange(num_init_samples):
s=draw(s,T,b)
# sample states
S=np.zeros((N,n))
S[:,0]=s
for i in xrange(1,n):
S[:,i]=draw(S[:,i-1],T,b)
return S
def sigmoid(u):
"""
sigmoid.m - sigmoid function
function s = sigmoid(u)
"""
return 1./(1.+np.exp(-u));
def draw(Sin,T,b):
"""
draw.m - perform single Gibbs sweep to draw a sample from distribution
function S = draw(Sin,T,b)
Sin: initial state
T: weight matrix
b: bias
"""
N=Sin.shape[0]
S=Sin.copy()
rand = np.random.rand(N,1)
for i in xrange(N):
h=np.dot(T[i,:],S)+b[i];
S[i]=2*(rand[i]<sigmoid(h))-1;
return S
def run(im, T=None, b=None, display=True,N=4,num_trials=100,batch_size=100,num_init_samples=10,eta=0.1):
SZ=np.sqrt(N);
if T is None: T=np.zeros((N,N)); # weight matrix
if b is None: b=np.zeros(N); # bias
for t in xrange(num_trials):
print t, num_trials
# data statistics (clamped)
X=extract_patches(im,SZ,batch_size).astype(np.float);
R_data=np.dot(X,X.T)/batch_size;
mu_data=X.mean(1);
# prior statistics (unclamped)
S=sample(T,b,batch_size,num_init_samples);
R_prior=np.dot(S,S.T)/batch_size;
mu_prior=S.mean(1);
# update params
deltaT=eta*(R_data - R_prior);
T=T+deltaT;
deltab=eta*(mu_data - mu_prior);
b=b+deltab;
return T, b
if __name__ == "__main__":
A = np.array([\
[0.,1.,1.,0],
[1.,1.,0, 0],
[1.,1.,1.,0],
[0, 1.,1.,1.],
[0, 0, 1.,0]
])
T,b = run(A,display=False)
print T
print b
It works by creating patches of data, but this can be modified so the code works on all data all the time. | Learning weights in a Boltzmann machine | Here is sample Python code for Boltzmann Machines based on Paul Ivanov's code from
http://redwood.berkeley.edu/wiki/VS265:_Homework_assignments
import numpy as np
def extract_patches(im,SZ,n):
i | Learning weights in a Boltzmann machine
Here is sample Python code for Boltzmann Machines based on Paul Ivanov's code from
http://redwood.berkeley.edu/wiki/VS265:_Homework_assignments
import numpy as np
def extract_patches(im,SZ,n):
imsize,imsize=im.shape;
X=np.zeros((n,SZ**2),dtype=np.int8);
startsx= np.random.randint(imsize-SZ,size=n)
startsy=np.random.randint(imsize-SZ,size=n)
for i,stx,sty in zip(xrange(n), startsx,startsy):
P=im[sty:sty+SZ, stx:stx+SZ];
X[i]=2*P.flat[:]-1;
return X.T
def sample(T,b,n,num_init_samples):
"""
sample.m - sample states from model distribution
function S = sample(T,b,n, num_init_samples)
T: weight matrix
b: bias
n: number of samples
num_init_samples: number of initial Gibbs sweeps
"""
N=T.shape[0]
# initialize state vector for sampling
s=2*(np.random.rand(N)<sigmoid(b))-1
for k in xrange(num_init_samples):
s=draw(s,T,b)
# sample states
S=np.zeros((N,n))
S[:,0]=s
for i in xrange(1,n):
S[:,i]=draw(S[:,i-1],T,b)
return S
def sigmoid(u):
"""
sigmoid.m - sigmoid function
function s = sigmoid(u)
"""
return 1./(1.+np.exp(-u));
def draw(Sin,T,b):
"""
draw.m - perform single Gibbs sweep to draw a sample from distribution
function S = draw(Sin,T,b)
Sin: initial state
T: weight matrix
b: bias
"""
N=Sin.shape[0]
S=Sin.copy()
rand = np.random.rand(N,1)
for i in xrange(N):
h=np.dot(T[i,:],S)+b[i];
S[i]=2*(rand[i]<sigmoid(h))-1;
return S
def run(im, T=None, b=None, display=True,N=4,num_trials=100,batch_size=100,num_init_samples=10,eta=0.1):
SZ=np.sqrt(N);
if T is None: T=np.zeros((N,N)); # weight matrix
if b is None: b=np.zeros(N); # bias
for t in xrange(num_trials):
print t, num_trials
# data statistics (clamped)
X=extract_patches(im,SZ,batch_size).astype(np.float);
R_data=np.dot(X,X.T)/batch_size;
mu_data=X.mean(1);
# prior statistics (unclamped)
S=sample(T,b,batch_size,num_init_samples);
R_prior=np.dot(S,S.T)/batch_size;
mu_prior=S.mean(1);
# update params
deltaT=eta*(R_data - R_prior);
T=T+deltaT;
deltab=eta*(mu_data - mu_prior);
b=b+deltab;
return T, b
if __name__ == "__main__":
A = np.array([\
[0.,1.,1.,0],
[1.,1.,0, 0],
[1.,1.,1.,0],
[0, 1.,1.,1.],
[0, 0, 1.,0]
])
T,b = run(A,display=False)
print T
print b
It works by creating patches of data, but this can be modified so the code works on all data all the time. | Learning weights in a Boltzmann machine
Here is sample Python code for Boltzmann Machines based on Paul Ivanov's code from
http://redwood.berkeley.edu/wiki/VS265:_Homework_assignments
import numpy as np
def extract_patches(im,SZ,n):
i |
20,535 | Intuition for higher moments in circular statistics | The moments are the Fourier coefficients of the probability measure $P^Z$. Suppose (for the sake of intuition) that $Z$ has a density. Then the argument (angle from $1$ in the complex plane) of $Z$ has a density on $[0,2\pi)$, and the moments are the coefficients when that density is expanded in a Fourier series. Thus the usual intuition about Fourier series applies -- these measure the strengths of frequencies in that density.
As for your second question, I think you already gave the answer: "complex multiplication is essentially addition of angles in this case". | Intuition for higher moments in circular statistics | The moments are the Fourier coefficients of the probability measure $P^Z$. Suppose (for the sake of intuition) that $Z$ has a density. Then the argument (angle from $1$ in the complex plane) of $Z$ | Intuition for higher moments in circular statistics
The moments are the Fourier coefficients of the probability measure $P^Z$. Suppose (for the sake of intuition) that $Z$ has a density. Then the argument (angle from $1$ in the complex plane) of $Z$ has a density on $[0,2\pi)$, and the moments are the coefficients when that density is expanded in a Fourier series. Thus the usual intuition about Fourier series applies -- these measure the strengths of frequencies in that density.
As for your second question, I think you already gave the answer: "complex multiplication is essentially addition of angles in this case". | Intuition for higher moments in circular statistics
The moments are the Fourier coefficients of the probability measure $P^Z$. Suppose (for the sake of intuition) that $Z$ has a density. Then the argument (angle from $1$ in the complex plane) of $Z$ |
20,536 | Is $\frac1{n+1}\sum_{i=1}^n(X_i-\overline X)^2$ an admissible estimator for $\sigma^2$? | Assume that $X_i \sim \mathcal{N}(\mu, \sigma^2)$ are i.i.d. with unknown $\mu$ and $\sigma^2$ and that the loss function is $\left(\delta(\mathbf{X}) - \sigma^2 \right)^2$. Consider the reference estimator $\delta_0(\mathbf{X}) = \sum_{i=1}^n (X_i-\bar{X})^2/(n+1)$.
Stein (1964) found an estimator $\delta_{(\nu)}$ which dominates $\delta_0$ for any fixed choice $\nu$. The estimator is $$\delta_{(\nu)}(\mathbf{X}) = \min\left\{ \delta_0(\mathbf{X}), \frac{1}{n+2} \sum_{i=1}^n (X_i - \nu)^2\right\}.$$ At a high level, this estimator chooses between an estimator with unknown mean (estimated with the sample mean) and an estimator which commits to the fixed $\nu$ as being the true mean and thus has one more df. Stein writes that ``It is interesting to observe that the estimator [$\delta_{(\nu)}$] may be obtained by first testing the hypothesis $\mu=\nu$ at an appropriate significance level and using the estimate [$\frac{1}{n+2} \sum_{i=1}^n (X_i - \nu)^2$] if the hypothesis is accepted and the estimate [$\delta_0(\mathbf{X})$] if the hypothesis is rejected.''
From my perspective, the estimator $\delta_{(\nu)}$ bets on $\nu$ being the true mean and is allowed to ``shirk'' out of the bet. This is a kind of post selection inference which is common in modern high dimensional statistics, but here there's no need to control for the selection.
Note, I was initially surprised to see this from Stein since in my experience, estimators for covariances are (sensibly) compared with scale invariant loss functions. On this point, in the linked article, Stein writes "I find it hard to take the problem of estimating a [variance] with quadratic loss function very seriously" and goes on to elaborate and conclude that "unlike the results of the present paper, the main results in [another paper which uses a squared error loss but for location estimation] can be seriously recommended to the practical statistician".
In the case that the true mean $\mu$ is known, the estimator with division by $n+2$ is admissible under squared error. This is reviewed in the above article from Stein and credited to Hodges and Lehmann (1951). | Is $\frac1{n+1}\sum_{i=1}^n(X_i-\overline X)^2$ an admissible estimator for $\sigma^2$? | Assume that $X_i \sim \mathcal{N}(\mu, \sigma^2)$ are i.i.d. with unknown $\mu$ and $\sigma^2$ and that the loss function is $\left(\delta(\mathbf{X}) - \sigma^2 \right)^2$. Consider the reference est | Is $\frac1{n+1}\sum_{i=1}^n(X_i-\overline X)^2$ an admissible estimator for $\sigma^2$?
Assume that $X_i \sim \mathcal{N}(\mu, \sigma^2)$ are i.i.d. with unknown $\mu$ and $\sigma^2$ and that the loss function is $\left(\delta(\mathbf{X}) - \sigma^2 \right)^2$. Consider the reference estimator $\delta_0(\mathbf{X}) = \sum_{i=1}^n (X_i-\bar{X})^2/(n+1)$.
Stein (1964) found an estimator $\delta_{(\nu)}$ which dominates $\delta_0$ for any fixed choice $\nu$. The estimator is $$\delta_{(\nu)}(\mathbf{X}) = \min\left\{ \delta_0(\mathbf{X}), \frac{1}{n+2} \sum_{i=1}^n (X_i - \nu)^2\right\}.$$ At a high level, this estimator chooses between an estimator with unknown mean (estimated with the sample mean) and an estimator which commits to the fixed $\nu$ as being the true mean and thus has one more df. Stein writes that ``It is interesting to observe that the estimator [$\delta_{(\nu)}$] may be obtained by first testing the hypothesis $\mu=\nu$ at an appropriate significance level and using the estimate [$\frac{1}{n+2} \sum_{i=1}^n (X_i - \nu)^2$] if the hypothesis is accepted and the estimate [$\delta_0(\mathbf{X})$] if the hypothesis is rejected.''
From my perspective, the estimator $\delta_{(\nu)}$ bets on $\nu$ being the true mean and is allowed to ``shirk'' out of the bet. This is a kind of post selection inference which is common in modern high dimensional statistics, but here there's no need to control for the selection.
Note, I was initially surprised to see this from Stein since in my experience, estimators for covariances are (sensibly) compared with scale invariant loss functions. On this point, in the linked article, Stein writes "I find it hard to take the problem of estimating a [variance] with quadratic loss function very seriously" and goes on to elaborate and conclude that "unlike the results of the present paper, the main results in [another paper which uses a squared error loss but for location estimation] can be seriously recommended to the practical statistician".
In the case that the true mean $\mu$ is known, the estimator with division by $n+2$ is admissible under squared error. This is reviewed in the above article from Stein and credited to Hodges and Lehmann (1951). | Is $\frac1{n+1}\sum_{i=1}^n(X_i-\overline X)^2$ an admissible estimator for $\sigma^2$?
Assume that $X_i \sim \mathcal{N}(\mu, \sigma^2)$ are i.i.d. with unknown $\mu$ and $\sigma^2$ and that the loss function is $\left(\delta(\mathbf{X}) - \sigma^2 \right)^2$. Consider the reference est |
20,537 | What is the Frequentist definition of fixed effects? | First of all, the 'random effects' can be viewed in different ways and the approaches to them and associated definitions may seem conflicting but it is just a different viewpoint.
The 'random effect' term in a model can be seen as both a term in the deterministic part of the model as a term in the random part of the model.
Basically, in general, the difference between fixed effect and random effect is whether a parameter is considered fixed within the experiment or not. From that point you get all kinds of different practical applications, and the many varying answers (opinions) to the question "When to use random effects?". It might actually be more a linguistic problem (when something is called random effect or not) than something with a problem with modelling (where we all understand the mathematics in the same way).
The Bayesian and Frequentist frameworks look in the same way at a statistical model, say: observations $Y_{ij}$ where $j$ is the observation number and $i$ indicates a grouping
$$Y_{ij} = \underbrace{ \alpha + \beta}_{\substack{\llap{\text{mod}}\rlap{\text{el}} \\ \llap{\text{parame}}\rlap{\text{ters}} }}\overbrace{X_{ij}}^{\substack{\llap{\text{indep}}\rlap{\text{endent}} \\ \text{variables}}} +\overbrace{Z_{i}}^{\substack{\llap{\text{ran}}\rlap{\text{dom}} \\ \text{group}\\ \text{term}}} + \overbrace{\epsilon_{j}}^{\substack{\llap{\text{ran}}\rlap{\text{dom}} \\ \text{individual}\\ \text{term}}}$$
The observations $Y_{ij}$ will depend on some model parameters $\alpha$ and $\beta$, which can be seen as the 'effects' which describe how the $Y_{ij}$ depends on the variable $X_{ij}$.
But the observations will not be deterministic and only depend on $X_{ij}$, there will also be random terms such that the observation conditional on the independent variables $Y_{ij} \vert X_{ij}$ will follow some random distribution. The terms $Z_{i}$ and $\epsilon_j$ are the nondeterministic part of the model.
This is the same for the Bayesian and Frequentist approach, which in principle do not differ in their way to describe a probability for the observations $Y_{ij}$ conditional on the model parameters $\alpha$ and $\beta$ and independent variables $X_{ij}$, where $Z_i$ and $\epsilon_j$ describe a non-deterministic part.
The difference is in the approach to 'inference'.
The Bayesian approach uses reverse probability and describes a probability distribution of the (fixed effect) parameters $\alpha$ and $\beta$. This implies an interpretation of those parameters as random variables. With a Bayesian approach the outcome is a statement about the probability distribution for the fixed effect parameters $\alpha$ and $\beta$.
A Frequentist method does not consider a distribution of the fixed effect parameters $\alpha$ and $\beta$ and avoids making statements that imply such distribution (but it is not explicitly rejected). The probability/frequency statements in a frequentist approach do not relate to a frequency/probability statement about the parameters but to a frequency/probability statement about the success rate of the estimation procedure.
So if you like, you could say that a frequentist definition of a fixed effect is: 'a model parameter that describes the deterministic part in a statistical model'. (ie. parameters that describe how dependent variables depend on independent variables).
And more specifically in most contexts this relates only to the parameters for the deterministic model that describe $E[Y_{ij} \vert X_{ij}]$. For instance, with a frequentist model one can estimate both the mean and variance, but only the parameters that relate to the mean are considered 'effects'. And even more specifically, the effects are most often used in the context of a 'linear' model. E.g. a for a nonlinear model like $E[y] \sim a e^{-bt}$ the parameters $a$ and $b$ are not really called 'effects'.
In a Bayesian framework all effects are sort of random and not deterministic (so the difference between random effect and fixed effect is not so obvious). The model parameters $\alpha$ and $\beta$ are random variables.
How I interpret the question's description/definition of the difference in random effect and fixed effect in the Bayesian framework is more as something pragmatic than as some principle.
the fixed effects $\alpha$ and $\beta$ are considered to be like "where we estimate each parameter ... independently" (the $\alpha$ and $\beta$ are randomly drawn from a distribution, but they are the same for all $i$ and $j$ within the analysis, e.g. the mean of a species is a model parameter that is considered the same for each species)
and the random effects are like "for a random effect the parameters for each level are modeled as being drawn from a distribution" (for each observation category $i$ a different random effect is 'drawn' from the distribution, e.g. the mean of a species is a model parameter that is considered different for each species)
In a frequentist framework the fixed effect model parameters are not considered as random parameters, or at least it doesn't matter for the inference whether the parameters are a random parameter or not and it is left out the analysis. However, the random effect term is explicitly considered as a random variable (that is, as a nondeterministic component of the model) and this will influence the analysis (e.g. as in a mixed effects model the imposed structure of the random error term). | What is the Frequentist definition of fixed effects? | First of all, the 'random effects' can be viewed in different ways and the approaches to them and associated definitions may seem conflicting but it is just a different viewpoint.
The 'random effect' | What is the Frequentist definition of fixed effects?
First of all, the 'random effects' can be viewed in different ways and the approaches to them and associated definitions may seem conflicting but it is just a different viewpoint.
The 'random effect' term in a model can be seen as both a term in the deterministic part of the model as a term in the random part of the model.
Basically, in general, the difference between fixed effect and random effect is whether a parameter is considered fixed within the experiment or not. From that point you get all kinds of different practical applications, and the many varying answers (opinions) to the question "When to use random effects?". It might actually be more a linguistic problem (when something is called random effect or not) than something with a problem with modelling (where we all understand the mathematics in the same way).
The Bayesian and Frequentist frameworks look in the same way at a statistical model, say: observations $Y_{ij}$ where $j$ is the observation number and $i$ indicates a grouping
$$Y_{ij} = \underbrace{ \alpha + \beta}_{\substack{\llap{\text{mod}}\rlap{\text{el}} \\ \llap{\text{parame}}\rlap{\text{ters}} }}\overbrace{X_{ij}}^{\substack{\llap{\text{indep}}\rlap{\text{endent}} \\ \text{variables}}} +\overbrace{Z_{i}}^{\substack{\llap{\text{ran}}\rlap{\text{dom}} \\ \text{group}\\ \text{term}}} + \overbrace{\epsilon_{j}}^{\substack{\llap{\text{ran}}\rlap{\text{dom}} \\ \text{individual}\\ \text{term}}}$$
The observations $Y_{ij}$ will depend on some model parameters $\alpha$ and $\beta$, which can be seen as the 'effects' which describe how the $Y_{ij}$ depends on the variable $X_{ij}$.
But the observations will not be deterministic and only depend on $X_{ij}$, there will also be random terms such that the observation conditional on the independent variables $Y_{ij} \vert X_{ij}$ will follow some random distribution. The terms $Z_{i}$ and $\epsilon_j$ are the nondeterministic part of the model.
This is the same for the Bayesian and Frequentist approach, which in principle do not differ in their way to describe a probability for the observations $Y_{ij}$ conditional on the model parameters $\alpha$ and $\beta$ and independent variables $X_{ij}$, where $Z_i$ and $\epsilon_j$ describe a non-deterministic part.
The difference is in the approach to 'inference'.
The Bayesian approach uses reverse probability and describes a probability distribution of the (fixed effect) parameters $\alpha$ and $\beta$. This implies an interpretation of those parameters as random variables. With a Bayesian approach the outcome is a statement about the probability distribution for the fixed effect parameters $\alpha$ and $\beta$.
A Frequentist method does not consider a distribution of the fixed effect parameters $\alpha$ and $\beta$ and avoids making statements that imply such distribution (but it is not explicitly rejected). The probability/frequency statements in a frequentist approach do not relate to a frequency/probability statement about the parameters but to a frequency/probability statement about the success rate of the estimation procedure.
So if you like, you could say that a frequentist definition of a fixed effect is: 'a model parameter that describes the deterministic part in a statistical model'. (ie. parameters that describe how dependent variables depend on independent variables).
And more specifically in most contexts this relates only to the parameters for the deterministic model that describe $E[Y_{ij} \vert X_{ij}]$. For instance, with a frequentist model one can estimate both the mean and variance, but only the parameters that relate to the mean are considered 'effects'. And even more specifically, the effects are most often used in the context of a 'linear' model. E.g. a for a nonlinear model like $E[y] \sim a e^{-bt}$ the parameters $a$ and $b$ are not really called 'effects'.
In a Bayesian framework all effects are sort of random and not deterministic (so the difference between random effect and fixed effect is not so obvious). The model parameters $\alpha$ and $\beta$ are random variables.
How I interpret the question's description/definition of the difference in random effect and fixed effect in the Bayesian framework is more as something pragmatic than as some principle.
the fixed effects $\alpha$ and $\beta$ are considered to be like "where we estimate each parameter ... independently" (the $\alpha$ and $\beta$ are randomly drawn from a distribution, but they are the same for all $i$ and $j$ within the analysis, e.g. the mean of a species is a model parameter that is considered the same for each species)
and the random effects are like "for a random effect the parameters for each level are modeled as being drawn from a distribution" (for each observation category $i$ a different random effect is 'drawn' from the distribution, e.g. the mean of a species is a model parameter that is considered different for each species)
In a frequentist framework the fixed effect model parameters are not considered as random parameters, or at least it doesn't matter for the inference whether the parameters are a random parameter or not and it is left out the analysis. However, the random effect term is explicitly considered as a random variable (that is, as a nondeterministic component of the model) and this will influence the analysis (e.g. as in a mixed effects model the imposed structure of the random error term). | What is the Frequentist definition of fixed effects?
First of all, the 'random effects' can be viewed in different ways and the approaches to them and associated definitions may seem conflicting but it is just a different viewpoint.
The 'random effect' |
20,538 | What is the Frequentist definition of fixed effects? | Trying to find single "authoritative" definition is always tempting in cases like this, but the variety of different definitions shows that this term simply is not used in consistent manner. Andrew Gelman seems to have reached same conclusions, you can look as his blog posts here and here, or into his handbook Data Analysis Using Regression and Multilevel/Hierarchical Models written together with Jennifer Hill, where they write (p. 254-255):
The term fixed effects is used in contrast to random effects—but not
in a consistent way! Fixed effects are usually defined as varying
coefficients that are not themselves modeled. For example, a classical
regression including $J − 1 = 19$ city indicators as regression
predictors is sometimes called a “fixed-effects model” or a model with
“fixed effects for cities.” Confusingly, however, “fixed-effects
models” sometimes refer to regressions in which coefficients do not
vary by group (so that they are fixed, not random).
A question that commonly arises is when to use fixed effects (in the
sense of varying coefficients that are unmodeled) and when to use
random effects. The statistical literature is full of confusing and
contradictory advice. Some say that fixed effects are appropriate if
group-level coefficients are of interest, and random effects are
appropriate if interest lies in the underlying population. Others
recommend fixed effects when the groups in the data represent all
possible groups, and random effects when the population includes
groups not in the data. These two recommendations (and others) can be
unhelpful. For example, in the child support example, we are
interested in these particular cities and also the country as a whole.
The cities are only a sample of cities in the United States—but if we
were suddenly given data from all the other cities, we would not want
then to change our model.
Our advice (elaborated upon in the rest of this book) is to always
use multilevel modeling (“random effects”). Because of the conflicting
definitions and advice, we avoid the terms “fixed” and “random”
entirely, and focus on the description of the model itself (for
example, varying intercepts and constant slopes), with the
understanding that batches of coefficients (for example, $\alpha_1,
\alpha_2, \dots, \alpha_J$) will themselves be modeled.
This is a good advice. | What is the Frequentist definition of fixed effects? | Trying to find single "authoritative" definition is always tempting in cases like this, but the variety of different definitions shows that this term simply is not used in consistent manner. Andrew Ge | What is the Frequentist definition of fixed effects?
Trying to find single "authoritative" definition is always tempting in cases like this, but the variety of different definitions shows that this term simply is not used in consistent manner. Andrew Gelman seems to have reached same conclusions, you can look as his blog posts here and here, or into his handbook Data Analysis Using Regression and Multilevel/Hierarchical Models written together with Jennifer Hill, where they write (p. 254-255):
The term fixed effects is used in contrast to random effects—but not
in a consistent way! Fixed effects are usually defined as varying
coefficients that are not themselves modeled. For example, a classical
regression including $J − 1 = 19$ city indicators as regression
predictors is sometimes called a “fixed-effects model” or a model with
“fixed effects for cities.” Confusingly, however, “fixed-effects
models” sometimes refer to regressions in which coefficients do not
vary by group (so that they are fixed, not random).
A question that commonly arises is when to use fixed effects (in the
sense of varying coefficients that are unmodeled) and when to use
random effects. The statistical literature is full of confusing and
contradictory advice. Some say that fixed effects are appropriate if
group-level coefficients are of interest, and random effects are
appropriate if interest lies in the underlying population. Others
recommend fixed effects when the groups in the data represent all
possible groups, and random effects when the population includes
groups not in the data. These two recommendations (and others) can be
unhelpful. For example, in the child support example, we are
interested in these particular cities and also the country as a whole.
The cities are only a sample of cities in the United States—but if we
were suddenly given data from all the other cities, we would not want
then to change our model.
Our advice (elaborated upon in the rest of this book) is to always
use multilevel modeling (“random effects”). Because of the conflicting
definitions and advice, we avoid the terms “fixed” and “random”
entirely, and focus on the description of the model itself (for
example, varying intercepts and constant slopes), with the
understanding that batches of coefficients (for example, $\alpha_1,
\alpha_2, \dots, \alpha_J$) will themselves be modeled.
This is a good advice. | What is the Frequentist definition of fixed effects?
Trying to find single "authoritative" definition is always tempting in cases like this, but the variety of different definitions shows that this term simply is not used in consistent manner. Andrew Ge |
20,539 | How is `tol` used in scikit-learn's `Lasso` and `ElasticNet`? | I am going to explain the case of Lasso, you can apply the same logic to ElasticNet.
How is the duality gap defined in the case of Lasso (/ElasticNet)?
The duality gap is the difference between a solution of the primal problem and a solution of the dual problem as said here.
The primal problem is the following:
$$ \min_{w \in \mathbb{R}^{n}} \frac{1}{2} ||Xw - y||_{2}^{2} + \alpha ||w||_{1}$$
Where $n$ is the number of features that your dataset has. $X$ is your samples, $w$ is the weights and $\alpha$ is the tradeoff between accuracy and sparsity of the weights. I don't think there is a real interest in looking at the dual formulation but if you want, you can have a look here.
However, it is more interesting to know that the dual gap is always positive. In case of strong duality, the dual gap is equal to zero. The lasso problem is convex (and has an interior point) so there is strong duality. This is why reducing the dual gap tells us that we are getting closer to an optimal solution.
Why the displayed tolerance in the example above is 5.712111291830755 whereas it was set as 0.0001 (default value) in the model?
The reason is that the algorithm has not converged yet after max_iter updates of weight coordinate. That is why they ask you to increase the number of iterations. The last update of a weight coordinate changed the value of this coordinate by 5.71, which is greater than 0.0001. In the meantime, with the weights that you have, the primal problem minus the dual problem is equal to 8.058.
In pratice, what does the optimization code checks the dual gap for optimality and continues until it is smaller than tol. mean?
In order for your algorithm to converge, there has to be an update of a weight coordinate lower than tol. Then, sklearn will check the dual gap and it will stop only if the value is lower than tol. | How is `tol` used in scikit-learn's `Lasso` and `ElasticNet`? | I am going to explain the case of Lasso, you can apply the same logic to ElasticNet.
How is the duality gap defined in the case of Lasso (/ElasticNet)?
The duality gap is the difference between a | How is `tol` used in scikit-learn's `Lasso` and `ElasticNet`?
I am going to explain the case of Lasso, you can apply the same logic to ElasticNet.
How is the duality gap defined in the case of Lasso (/ElasticNet)?
The duality gap is the difference between a solution of the primal problem and a solution of the dual problem as said here.
The primal problem is the following:
$$ \min_{w \in \mathbb{R}^{n}} \frac{1}{2} ||Xw - y||_{2}^{2} + \alpha ||w||_{1}$$
Where $n$ is the number of features that your dataset has. $X$ is your samples, $w$ is the weights and $\alpha$ is the tradeoff between accuracy and sparsity of the weights. I don't think there is a real interest in looking at the dual formulation but if you want, you can have a look here.
However, it is more interesting to know that the dual gap is always positive. In case of strong duality, the dual gap is equal to zero. The lasso problem is convex (and has an interior point) so there is strong duality. This is why reducing the dual gap tells us that we are getting closer to an optimal solution.
Why the displayed tolerance in the example above is 5.712111291830755 whereas it was set as 0.0001 (default value) in the model?
The reason is that the algorithm has not converged yet after max_iter updates of weight coordinate. That is why they ask you to increase the number of iterations. The last update of a weight coordinate changed the value of this coordinate by 5.71, which is greater than 0.0001. In the meantime, with the weights that you have, the primal problem minus the dual problem is equal to 8.058.
In pratice, what does the optimization code checks the dual gap for optimality and continues until it is smaller than tol. mean?
In order for your algorithm to converge, there has to be an update of a weight coordinate lower than tol. Then, sklearn will check the dual gap and it will stop only if the value is lower than tol. | How is `tol` used in scikit-learn's `Lasso` and `ElasticNet`?
I am going to explain the case of Lasso, you can apply the same logic to ElasticNet.
How is the duality gap defined in the case of Lasso (/ElasticNet)?
The duality gap is the difference between a |
20,540 | Generate uniform noise from a p-norm ball ($||x||_p \leq r$) | I found the full solution in a paper as suggested by kjetil b halvorsen (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=758215). I honestly have trouble understanding the math behind it, but the eventual algorithm is fairly simple. if we have $n$ dimensions, a radius $r$ and norm $p$ than:
1) generate $n$ independent random real scalars $\varepsilon_i = \bar{G}(1/p, p)$, where $\bar{G}(\mu, \sigma^2)$ is the Generalized Gaussian distribution (with a different power in the exponent $e^{−|x|^p}$ instead of just $p=2$)
2) construct the vector $x$ of components $s_i * \varepsilon_i$, where $s_i$ are independent random signs
3) Generate $z = w^{1/n}$, where $w$ is a random variable uniformly distributed in the interval [0, 1].
4) return $y = r z \frac{x}{||x||_p}$ | Generate uniform noise from a p-norm ball ($||x||_p \leq r$) | I found the full solution in a paper as suggested by kjetil b halvorsen (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=758215). I honestly have trouble understanding the math behind it, but the | Generate uniform noise from a p-norm ball ($||x||_p \leq r$)
I found the full solution in a paper as suggested by kjetil b halvorsen (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=758215). I honestly have trouble understanding the math behind it, but the eventual algorithm is fairly simple. if we have $n$ dimensions, a radius $r$ and norm $p$ than:
1) generate $n$ independent random real scalars $\varepsilon_i = \bar{G}(1/p, p)$, where $\bar{G}(\mu, \sigma^2)$ is the Generalized Gaussian distribution (with a different power in the exponent $e^{−|x|^p}$ instead of just $p=2$)
2) construct the vector $x$ of components $s_i * \varepsilon_i$, where $s_i$ are independent random signs
3) Generate $z = w^{1/n}$, where $w$ is a random variable uniformly distributed in the interval [0, 1].
4) return $y = r z \frac{x}{||x||_p}$ | Generate uniform noise from a p-norm ball ($||x||_p \leq r$)
I found the full solution in a paper as suggested by kjetil b halvorsen (https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=758215). I honestly have trouble understanding the math behind it, but the |
20,541 | Generate uniform noise from a p-norm ball ($||x||_p \leq r$) | Using homogeneously distributed multivariate variables
Taeke provides a link to an article which the text below makes more intuitive by explaining specifically 2-norm and 1-norm cases.
2-norm $\Vert x \Vert_2 \leq r$
sample direction
You can use this result http://mathworld.wolfram.com/HyperspherePointPicking.html
A multivariate Gaussian distributed variable $X$ (with identity covariance matrix) depends only on the distance, or sum of squares.
$$f(X_1,X_2,...,X_n) = \prod_{1\leq i \leq n} \frac{1}{\sqrt{2\pi}}e^{\frac{1}{2}x_i^2} = \frac{1}{\sqrt{2\pi}}e^{\frac{1}{2}\sum_{1 \leq i \leq n} x_i^2} $$
Thus $\frac{X}{\Vert X \Vert_2}$ is uniformly distributed on the surface of the n-dimensional-hypersphere.
sample distance
To complete you only need to sample the distance, to change the homogeneous distribution on the sphere to a homogeneous distribution in a ball. (which is more or less similar as your linked example for disk point picking)
If you would simply sample $r$ as a uniform distribution then you would have a relatively higher density near the center (the volume scales as $r^n$ so a fraction $r$ of the points would end up in a volume $r^n$, which is more dense near the center and would not mean a uniform distribution)
If instead you use the $n$-th root of a variable sampled from a uniform distribution, then you get an even distribution.
1-norm $\Vert x \Vert_1 \leq r$
direction
In this case you sample $X$ from the Laplace distribution instead of the Gaussian distribution and divide by the 1-norm. The $\frac{X}{\vert X \vert_1}$ is uniformly distributed on the n-dimensional 1-norm sphere.
I have no formal proof, just intuition
(since the pdf is independent from position, you will expect for any infinitesimal area/volume with the same 1-norm to have the same probability $f(x) dV$ and when you collapse this to the unit surface the same $f(x) dA$)
but testing with simulations looks good.
library(rmutil)
x <- abs(rlaplace(20000))
y <- abs(rlaplace(20000))
z <- abs(rlaplace(20000))
rn <- abs(x)+abs(y)+abs(z)
xi <- (x/rn)
yi <- (y/rn)
zi <- (z/rn)
plot(sqrt(0.5)*(xi-yi),
sqrt((0.5-0.5*(xi+yi))^2+zi^2),
pc=21,bg=rgb(0,0,0,0.02), col=rgb(0,0,0,0),cex=1)
distance
The distance goes similar as with the 2-norm case (the volume still scales as $r^n$).
p-norm $\Vert x \Vert_p \leq r$
In this case, if you wish to follow the same principle, you would need to sample from distributions with $f(x) \propto e^{\vert x \vert^p}$ (I hypothesize). These are generalized normal distributions and probably relate to the distribution $G()$ mentioned by Taeke. | Generate uniform noise from a p-norm ball ($||x||_p \leq r$) | Using homogeneously distributed multivariate variables
Taeke provides a link to an article which the text below makes more intuitive by explaining specifically 2-norm and 1-norm cases.
2-norm $\Vert x | Generate uniform noise from a p-norm ball ($||x||_p \leq r$)
Using homogeneously distributed multivariate variables
Taeke provides a link to an article which the text below makes more intuitive by explaining specifically 2-norm and 1-norm cases.
2-norm $\Vert x \Vert_2 \leq r$
sample direction
You can use this result http://mathworld.wolfram.com/HyperspherePointPicking.html
A multivariate Gaussian distributed variable $X$ (with identity covariance matrix) depends only on the distance, or sum of squares.
$$f(X_1,X_2,...,X_n) = \prod_{1\leq i \leq n} \frac{1}{\sqrt{2\pi}}e^{\frac{1}{2}x_i^2} = \frac{1}{\sqrt{2\pi}}e^{\frac{1}{2}\sum_{1 \leq i \leq n} x_i^2} $$
Thus $\frac{X}{\Vert X \Vert_2}$ is uniformly distributed on the surface of the n-dimensional-hypersphere.
sample distance
To complete you only need to sample the distance, to change the homogeneous distribution on the sphere to a homogeneous distribution in a ball. (which is more or less similar as your linked example for disk point picking)
If you would simply sample $r$ as a uniform distribution then you would have a relatively higher density near the center (the volume scales as $r^n$ so a fraction $r$ of the points would end up in a volume $r^n$, which is more dense near the center and would not mean a uniform distribution)
If instead you use the $n$-th root of a variable sampled from a uniform distribution, then you get an even distribution.
1-norm $\Vert x \Vert_1 \leq r$
direction
In this case you sample $X$ from the Laplace distribution instead of the Gaussian distribution and divide by the 1-norm. The $\frac{X}{\vert X \vert_1}$ is uniformly distributed on the n-dimensional 1-norm sphere.
I have no formal proof, just intuition
(since the pdf is independent from position, you will expect for any infinitesimal area/volume with the same 1-norm to have the same probability $f(x) dV$ and when you collapse this to the unit surface the same $f(x) dA$)
but testing with simulations looks good.
library(rmutil)
x <- abs(rlaplace(20000))
y <- abs(rlaplace(20000))
z <- abs(rlaplace(20000))
rn <- abs(x)+abs(y)+abs(z)
xi <- (x/rn)
yi <- (y/rn)
zi <- (z/rn)
plot(sqrt(0.5)*(xi-yi),
sqrt((0.5-0.5*(xi+yi))^2+zi^2),
pc=21,bg=rgb(0,0,0,0.02), col=rgb(0,0,0,0),cex=1)
distance
The distance goes similar as with the 2-norm case (the volume still scales as $r^n$).
p-norm $\Vert x \Vert_p \leq r$
In this case, if you wish to follow the same principle, you would need to sample from distributions with $f(x) \propto e^{\vert x \vert^p}$ (I hypothesize). These are generalized normal distributions and probably relate to the distribution $G()$ mentioned by Taeke. | Generate uniform noise from a p-norm ball ($||x||_p \leq r$)
Using homogeneously distributed multivariate variables
Taeke provides a link to an article which the text below makes more intuitive by explaining specifically 2-norm and 1-norm cases.
2-norm $\Vert x |
20,542 | Intuitive understanding of the Halmos-Savage theorem | A Technical Lemma
I'm not sure how intuitive this is, but the main technical result underlying your statement of the Halmos-Savage Theorem is the following:
Lemma.
Let $\mu$ be a $\sigma$-finite measure on $(S, \mathcal{A})$.
Suppose that $\aleph$ is a collection of measures on $(S, \mathcal{A})$ such that for every $\nu \in \aleph$, $\nu \ll \mu$.
Then there exists a sequence of nonnegative numbers $\{c_i\}_{i=1}^\infty$ and a sequence of elements of $\aleph$, $\{\nu_i\}_{i=1}^\infty$ such that $\sum_{i=1}^\infty c_i = 1$ and $\nu \ll \sum_{i=1}^\infty c_i \nu_i$ for every $\nu \in \aleph$.
This is taken verbatim from Theorem A.78 in Schervish's Theory of Statistics (1995).
Therein he attributes it to Lehmann's Testing Statistical Hypotheses (1986) (link to the third edition), where the result is attributed to Halmos and Savage themselves (see Lemma 7).
Another good reference is Shao's Mathematical Statistics (second edition, 2003), where the relevant results are Lemma 2.1 and Theorem 2.2.
The lemma above states that if you start with a family of measures dominated by a $\sigma$-finite measure, then in fact you can replace the dominating measure by a countable convex combination of measures from within the family.
Schervish writes before stating Theorem A.78,
"In statistical applications, we will often have a class of measures, each of which
is absolutely continuous with respect to a single $\sigma$-finite measure. It would be
nice if the single dominating measure were in the original class or could be constructed
from the class. The following theorem addresses this problem."
A Concrete Example
Suppose we take a measurement of a quantity $X$ which we believe to be distributed uniformly on the interval $[0, \theta]$ for some unknown $\theta > 0$.
In this statistical problem, we are implicitly considering the set $\mathcal{P}$ of Borel probability measures on $\mathbb{R}$ consisting of the uniform distributions on all intervals of the form $[0, \theta]$.
That is, if $\lambda$ denotes Lebesgue measure and, for $\theta > 0$, $P_\theta$ denotes the $\operatorname{Uniform}([0, \theta])$ distribution (i.e.,
$$
P_\theta(A)
= \frac{1}{\theta} \lambda(A \cap [0, \theta])
= \int_A \frac{1}{\theta} \mathbf{1}_{[0, \theta]}(x) \, dx
$$
for every Borel $A \subseteq \mathbb{R}$), then we simply have
$$
\mathcal{P} = \{P_\theta : \theta > 0\}.
$$
This is the set of candidate distributions for our measurement $X$.
The family $\mathcal{P}$ is clearly dominated by Lebesgue measure $\lambda$ (which is $\sigma$-finite), so the lemma above (with $\aleph = \mathcal{P}$) guarantees the existence of a sequence $\{c_i\}_{i=1}^\infty$ of nonnegative numbers summing to $1$ and a sequence $\{Q_i\}_{i=1}^\infty$ of uniform distributions in $\mathcal{P}$ such that
$$
P_\theta \ll \sum_{i=1}^\infty c_i Q_i
$$
for each $\theta > 0$.
In this example, we can construct such sequences explicitly!
First, let $(\theta_i)_{i=1}^\infty$ be an enumeration of the positive rational numbers (this can be done explicitly), and let $Q_i = P_{\theta_i}$ for each $i$.
Next, let $c_i = 2^{-i}$, so that $\sum_{i=1}^\infty c_i = 1$.
I claim that this combination of $\{c_i\}_{i=1}^\infty$ and $\{Q_i\}_{i=1}^\infty$ works.
To see this, fix $\theta > 0$ and let $A$ be a Borel subset of $\mathbb{R}$ such that $\sum_{i=1}^\infty c_i Q_i(A) = 0$.
We need to show that $P_\theta(A) = 0$.
Since $\sum_{i=1}^\infty c_i Q_i(A) = 0$ and each summand is non-negative, it follows that $c_i Q_i(A) = 0$ for each $i$.
Moreover, since each $c_i$ is positive, it follows that $Q_i(A) = 0$ for each $i$.
That is, for all $i$ we have
$$
Q_i(A)
= P_{\theta_i}(A)
= \frac{1}{\theta_i} \lambda(A \cap [0, \theta_i])
= 0.
$$
Since each $\theta_i$ is positive, it follows that $\lambda(A \cap [0, \theta_i]) = 0$ for each $i$.
Now choose a subsequence $\{\theta_{i_k}\}_{k=1}^\infty$ of $\{\theta_i\}_{i=1}^\infty$ which converges to $\theta$ from above (this can be done since $\mathbb{Q}$ is dense in $\mathbb{R}$).
Then $A \cap [0, \theta_{\theta_{i_k}}] \downarrow A \cap [0, \theta]$ as $k \to \infty$, so by continuity of measure we conclude that
$$
\lambda(A \cap [0, \theta])
= \lim_{k \to \infty} \lambda(A \cap [0, \theta_{i_k}])
= 0,
$$
and so $P_\theta(A) = 0$.
This proves the claim.
Thus, in this example we were able to explicitly construct a countable convex combination of probability measures from our dominated family which still dominates the entire family.
The Lemma above guarantees that this can be done for any dominated family (at least as long as the dominating measure is $\sigma$-finite).
The Halmos-Savage Theorem
So now on to the Halmos-Savage Theorem (for which I will use slightly different notation than in the question due to personal preference).
Given the Halmos-Savage Theorem, the Fisher-Neyman factorization theorem is just one application of the Doob-Dynkin lemma and the chain rule for Radon-Nikodym derivatives away!
Halmos-Savage Theorem.
Let $(\mathcal{X}, \mathcal{B}, \mathcal{P})$ be a dominated statistical model (meaning that $\mathcal{P}$ is a set of probability measures on $\mathcal{B}$ and there is a $\sigma$-finite measure $\mu$ on $\mathcal{B}$ such that $P \ll \mu$ for all $P \in \mathcal{P}$).
Let $T : (\mathcal{X}, \mathcal{B}) \to (\mathcal{T}, \mathcal{C})$ be a measurable function, where $(T, \mathcal{C})$ is a standard Borel space.
Then the following are equivalent:
$T$ is sufficient for $\mathcal{P}$ (meaning that there is a probability kernel $r : \mathcal{B} \times \mathcal{T} \to [0, 1]$ such that $r(B, T)$ is a version of $P(B \mid T)$ for all $B \in \mathcal{B}$ and $P \in \mathcal{P}$).
There exists a sequence $\{c_i\}_{i=1}^\infty$ of nonnegative numbers such that $\sum_{i=1}^\infty c_i = 1$ and a sequence $\{P_i\}_{i=1}^\infty$ of probability measures in $\mathcal{P}$ such that $P \ll P^*$ for all $P \in \mathcal{P}$, where $P^* = \sum_{i=1}^\infty c_i P_i$, and for each $P \in \mathcal{P}$ there exists a $T$-measurable version of $dP/dP^*$.
Proof.
By the lemma above, we may immediately replace $\mu$ by $P^* = \sum_{i=1}^\infty c_i P_i$ for some sequence $\{c_i\}_{i=1}^\infty$ of nonnegative numbers such that $\sum_{i=1}^\infty c_i = 1$ and a sequence $\{P_i\}_{i=1}^\infty$ of probability measures in $\mathcal{P}$.
(1. implies 2.)
Suppose $T$ is sufficient.
Then we must show that there are $T$-measurable versions of $dP/dP^*$ for all $P \in \mathcal{P}$.
Let $r$ be the probability kernel in the statement of the theorem.
For each $A \in \sigma(T)$ and $B \in \mathcal{B}$ we have
$$
\begin{aligned}
P^*(A \cap B)
&= \sum_{i=1}^\infty c_i P_i(A \cap B) \\
&= \sum_{i=1}^\infty c_i \int_A P_i(B \mid T) \, dP_i \\
&= \sum_{i=1}^\infty c_i \int_A r(B, T) \, dP_i \\
&= \int_A r(B, T) \, dP^*.
\end{aligned}
$$
Thus $r(B, T)$ is a version of $P^*(B \mid T)$ for all $B \in \mathcal{B}$.
For each $P \in \mathcal{P}$, let $f_P$ denote a version of the Radon-Nikodym derivative $dP/dP^*$ on the measurable space $(\mathcal{X}, \sigma(T))$ (so in particular $f_P$ is $T$-measurable).
Then for all $B \in \mathcal{B}$ and $P \in \mathcal{P}$ we have
$$
\begin{aligned}
P(B)
&= \int_{\mathcal{X}} P(B \mid T) \, dP \\
&= \int_{\mathcal{X}} r(B, T) \, dP \\
&= \int_{\mathcal{X}} r(B, T) f_P \, dP^* \\
&= \int_{\mathcal{X}} P^*(B \mid T) f_P \, dP^* \\
&= \int_{\mathcal{X}} E_{P^*}[\mathbf{1}_B f_P \mid T] \, dP^* \\
&= \int_B f_P \, dP^*.
\end{aligned}
$$
Thus in fact $f_P$ is a $T$-measurable version of $dP/dP^*$ on $(\mathcal{X}, \mathcal{B})$.
This proves that the first condition of the theorem implies the second.
(2. implies 1.)
Suppose one can choose a $T$-measurable version $f_P$ of $dP/dP^*$ for each $P \in \mathcal{P}$.
For each $B \in \mathcal{B}$, let $r(B, t)$ denote a particular version of $P^*(B \mid T = t)$ (e.g., $r(B, t)$ is a function such that $r(B, T)$ is a version of $P^*(B \mid T)$).
Since $(T, \mathcal{C})$ is a standard Borel space, we may choose $r$ in a way that makes it a probability kernel (see, e.g., Theorem B.32 in Schervish's Theory of Statistics (1995)).
We will show that $r(B, T)$ is a version of $P(B \mid T)$ for any $P \in \mathcal{P}$ and any $B \in \mathcal{B}$.
Thus, let $A \in \sigma(T)$ and $B \in \mathcal{B}$ be given.
Then for all $P \in \mathcal{P}$ we have
$$
\begin{aligned}
P(A \cap B)
&= \int_A \mathbf{1}_B f_P \, dP^* \\
&= \int_A E_{P^*}[\mathbf{1}_B f_P \mid T] \, dP^* \\
&= \int_A P^*(B \mid T) f_P \, dP^* \\
&= \int_A r(B, T) f_P \, dP^* \\
&= \int_A r(B, T) \, dP.
\end{aligned}
$$
This shows that $r(B, T)$ is a version of $P(B \mid T)$ for any $P \in \mathcal{P}$ and any $B \in \mathcal{B}$, and the proof is done.
Summary.
The important technical result underlying the Halmos-Savage theorem as presented here is the fact that a dominated family of probability measures is actually dominated by a countable convex combination of probability measures from that family.
Given that result, the rest of the Halmos-Savage theorem is mostly just manipulations with basic properties of Radon-Nikodym derivatives and conditional expectations. | Intuitive understanding of the Halmos-Savage theorem | A Technical Lemma
I'm not sure how intuitive this is, but the main technical result underlying your statement of the Halmos-Savage Theorem is the following:
Lemma.
Let $\mu$ be a $\sigma$-finite me | Intuitive understanding of the Halmos-Savage theorem
A Technical Lemma
I'm not sure how intuitive this is, but the main technical result underlying your statement of the Halmos-Savage Theorem is the following:
Lemma.
Let $\mu$ be a $\sigma$-finite measure on $(S, \mathcal{A})$.
Suppose that $\aleph$ is a collection of measures on $(S, \mathcal{A})$ such that for every $\nu \in \aleph$, $\nu \ll \mu$.
Then there exists a sequence of nonnegative numbers $\{c_i\}_{i=1}^\infty$ and a sequence of elements of $\aleph$, $\{\nu_i\}_{i=1}^\infty$ such that $\sum_{i=1}^\infty c_i = 1$ and $\nu \ll \sum_{i=1}^\infty c_i \nu_i$ for every $\nu \in \aleph$.
This is taken verbatim from Theorem A.78 in Schervish's Theory of Statistics (1995).
Therein he attributes it to Lehmann's Testing Statistical Hypotheses (1986) (link to the third edition), where the result is attributed to Halmos and Savage themselves (see Lemma 7).
Another good reference is Shao's Mathematical Statistics (second edition, 2003), where the relevant results are Lemma 2.1 and Theorem 2.2.
The lemma above states that if you start with a family of measures dominated by a $\sigma$-finite measure, then in fact you can replace the dominating measure by a countable convex combination of measures from within the family.
Schervish writes before stating Theorem A.78,
"In statistical applications, we will often have a class of measures, each of which
is absolutely continuous with respect to a single $\sigma$-finite measure. It would be
nice if the single dominating measure were in the original class or could be constructed
from the class. The following theorem addresses this problem."
A Concrete Example
Suppose we take a measurement of a quantity $X$ which we believe to be distributed uniformly on the interval $[0, \theta]$ for some unknown $\theta > 0$.
In this statistical problem, we are implicitly considering the set $\mathcal{P}$ of Borel probability measures on $\mathbb{R}$ consisting of the uniform distributions on all intervals of the form $[0, \theta]$.
That is, if $\lambda$ denotes Lebesgue measure and, for $\theta > 0$, $P_\theta$ denotes the $\operatorname{Uniform}([0, \theta])$ distribution (i.e.,
$$
P_\theta(A)
= \frac{1}{\theta} \lambda(A \cap [0, \theta])
= \int_A \frac{1}{\theta} \mathbf{1}_{[0, \theta]}(x) \, dx
$$
for every Borel $A \subseteq \mathbb{R}$), then we simply have
$$
\mathcal{P} = \{P_\theta : \theta > 0\}.
$$
This is the set of candidate distributions for our measurement $X$.
The family $\mathcal{P}$ is clearly dominated by Lebesgue measure $\lambda$ (which is $\sigma$-finite), so the lemma above (with $\aleph = \mathcal{P}$) guarantees the existence of a sequence $\{c_i\}_{i=1}^\infty$ of nonnegative numbers summing to $1$ and a sequence $\{Q_i\}_{i=1}^\infty$ of uniform distributions in $\mathcal{P}$ such that
$$
P_\theta \ll \sum_{i=1}^\infty c_i Q_i
$$
for each $\theta > 0$.
In this example, we can construct such sequences explicitly!
First, let $(\theta_i)_{i=1}^\infty$ be an enumeration of the positive rational numbers (this can be done explicitly), and let $Q_i = P_{\theta_i}$ for each $i$.
Next, let $c_i = 2^{-i}$, so that $\sum_{i=1}^\infty c_i = 1$.
I claim that this combination of $\{c_i\}_{i=1}^\infty$ and $\{Q_i\}_{i=1}^\infty$ works.
To see this, fix $\theta > 0$ and let $A$ be a Borel subset of $\mathbb{R}$ such that $\sum_{i=1}^\infty c_i Q_i(A) = 0$.
We need to show that $P_\theta(A) = 0$.
Since $\sum_{i=1}^\infty c_i Q_i(A) = 0$ and each summand is non-negative, it follows that $c_i Q_i(A) = 0$ for each $i$.
Moreover, since each $c_i$ is positive, it follows that $Q_i(A) = 0$ for each $i$.
That is, for all $i$ we have
$$
Q_i(A)
= P_{\theta_i}(A)
= \frac{1}{\theta_i} \lambda(A \cap [0, \theta_i])
= 0.
$$
Since each $\theta_i$ is positive, it follows that $\lambda(A \cap [0, \theta_i]) = 0$ for each $i$.
Now choose a subsequence $\{\theta_{i_k}\}_{k=1}^\infty$ of $\{\theta_i\}_{i=1}^\infty$ which converges to $\theta$ from above (this can be done since $\mathbb{Q}$ is dense in $\mathbb{R}$).
Then $A \cap [0, \theta_{\theta_{i_k}}] \downarrow A \cap [0, \theta]$ as $k \to \infty$, so by continuity of measure we conclude that
$$
\lambda(A \cap [0, \theta])
= \lim_{k \to \infty} \lambda(A \cap [0, \theta_{i_k}])
= 0,
$$
and so $P_\theta(A) = 0$.
This proves the claim.
Thus, in this example we were able to explicitly construct a countable convex combination of probability measures from our dominated family which still dominates the entire family.
The Lemma above guarantees that this can be done for any dominated family (at least as long as the dominating measure is $\sigma$-finite).
The Halmos-Savage Theorem
So now on to the Halmos-Savage Theorem (for which I will use slightly different notation than in the question due to personal preference).
Given the Halmos-Savage Theorem, the Fisher-Neyman factorization theorem is just one application of the Doob-Dynkin lemma and the chain rule for Radon-Nikodym derivatives away!
Halmos-Savage Theorem.
Let $(\mathcal{X}, \mathcal{B}, \mathcal{P})$ be a dominated statistical model (meaning that $\mathcal{P}$ is a set of probability measures on $\mathcal{B}$ and there is a $\sigma$-finite measure $\mu$ on $\mathcal{B}$ such that $P \ll \mu$ for all $P \in \mathcal{P}$).
Let $T : (\mathcal{X}, \mathcal{B}) \to (\mathcal{T}, \mathcal{C})$ be a measurable function, where $(T, \mathcal{C})$ is a standard Borel space.
Then the following are equivalent:
$T$ is sufficient for $\mathcal{P}$ (meaning that there is a probability kernel $r : \mathcal{B} \times \mathcal{T} \to [0, 1]$ such that $r(B, T)$ is a version of $P(B \mid T)$ for all $B \in \mathcal{B}$ and $P \in \mathcal{P}$).
There exists a sequence $\{c_i\}_{i=1}^\infty$ of nonnegative numbers such that $\sum_{i=1}^\infty c_i = 1$ and a sequence $\{P_i\}_{i=1}^\infty$ of probability measures in $\mathcal{P}$ such that $P \ll P^*$ for all $P \in \mathcal{P}$, where $P^* = \sum_{i=1}^\infty c_i P_i$, and for each $P \in \mathcal{P}$ there exists a $T$-measurable version of $dP/dP^*$.
Proof.
By the lemma above, we may immediately replace $\mu$ by $P^* = \sum_{i=1}^\infty c_i P_i$ for some sequence $\{c_i\}_{i=1}^\infty$ of nonnegative numbers such that $\sum_{i=1}^\infty c_i = 1$ and a sequence $\{P_i\}_{i=1}^\infty$ of probability measures in $\mathcal{P}$.
(1. implies 2.)
Suppose $T$ is sufficient.
Then we must show that there are $T$-measurable versions of $dP/dP^*$ for all $P \in \mathcal{P}$.
Let $r$ be the probability kernel in the statement of the theorem.
For each $A \in \sigma(T)$ and $B \in \mathcal{B}$ we have
$$
\begin{aligned}
P^*(A \cap B)
&= \sum_{i=1}^\infty c_i P_i(A \cap B) \\
&= \sum_{i=1}^\infty c_i \int_A P_i(B \mid T) \, dP_i \\
&= \sum_{i=1}^\infty c_i \int_A r(B, T) \, dP_i \\
&= \int_A r(B, T) \, dP^*.
\end{aligned}
$$
Thus $r(B, T)$ is a version of $P^*(B \mid T)$ for all $B \in \mathcal{B}$.
For each $P \in \mathcal{P}$, let $f_P$ denote a version of the Radon-Nikodym derivative $dP/dP^*$ on the measurable space $(\mathcal{X}, \sigma(T))$ (so in particular $f_P$ is $T$-measurable).
Then for all $B \in \mathcal{B}$ and $P \in \mathcal{P}$ we have
$$
\begin{aligned}
P(B)
&= \int_{\mathcal{X}} P(B \mid T) \, dP \\
&= \int_{\mathcal{X}} r(B, T) \, dP \\
&= \int_{\mathcal{X}} r(B, T) f_P \, dP^* \\
&= \int_{\mathcal{X}} P^*(B \mid T) f_P \, dP^* \\
&= \int_{\mathcal{X}} E_{P^*}[\mathbf{1}_B f_P \mid T] \, dP^* \\
&= \int_B f_P \, dP^*.
\end{aligned}
$$
Thus in fact $f_P$ is a $T$-measurable version of $dP/dP^*$ on $(\mathcal{X}, \mathcal{B})$.
This proves that the first condition of the theorem implies the second.
(2. implies 1.)
Suppose one can choose a $T$-measurable version $f_P$ of $dP/dP^*$ for each $P \in \mathcal{P}$.
For each $B \in \mathcal{B}$, let $r(B, t)$ denote a particular version of $P^*(B \mid T = t)$ (e.g., $r(B, t)$ is a function such that $r(B, T)$ is a version of $P^*(B \mid T)$).
Since $(T, \mathcal{C})$ is a standard Borel space, we may choose $r$ in a way that makes it a probability kernel (see, e.g., Theorem B.32 in Schervish's Theory of Statistics (1995)).
We will show that $r(B, T)$ is a version of $P(B \mid T)$ for any $P \in \mathcal{P}$ and any $B \in \mathcal{B}$.
Thus, let $A \in \sigma(T)$ and $B \in \mathcal{B}$ be given.
Then for all $P \in \mathcal{P}$ we have
$$
\begin{aligned}
P(A \cap B)
&= \int_A \mathbf{1}_B f_P \, dP^* \\
&= \int_A E_{P^*}[\mathbf{1}_B f_P \mid T] \, dP^* \\
&= \int_A P^*(B \mid T) f_P \, dP^* \\
&= \int_A r(B, T) f_P \, dP^* \\
&= \int_A r(B, T) \, dP.
\end{aligned}
$$
This shows that $r(B, T)$ is a version of $P(B \mid T)$ for any $P \in \mathcal{P}$ and any $B \in \mathcal{B}$, and the proof is done.
Summary.
The important technical result underlying the Halmos-Savage theorem as presented here is the fact that a dominated family of probability measures is actually dominated by a countable convex combination of probability measures from that family.
Given that result, the rest of the Halmos-Savage theorem is mostly just manipulations with basic properties of Radon-Nikodym derivatives and conditional expectations. | Intuitive understanding of the Halmos-Savage theorem
A Technical Lemma
I'm not sure how intuitive this is, but the main technical result underlying your statement of the Halmos-Savage Theorem is the following:
Lemma.
Let $\mu$ be a $\sigma$-finite me |
20,543 | Why do we use residuals to test the assumptions on errors in regression? | The residuals are our estimates of the error terms
The short answer to this question is relatively simple: the assumptions in a regression model are assumptions about the behaviour of the error terms, and the residuals are our estimates of the error terms. Ipso facto, examination of the behaviour of the observed residuals tells us whether or not the assumptions about the error terms are plausible.
To understand this general line of reasoning in more detail, it helps to examine in detail the behaviour of the residuals in a standard regression model. Under a standard multiple linear regression with independent homoskedastic normal error terms, the distribution of the residual vector is known, which allows you to test the underlying distributional assumptions in the regression model. The basic idea is that you figure out the distribution of the residual vector under the regression assumptions, and then check if the residual values plausibly match this theoretical distribution. Deviations from the theoretical residual distribution show that the underlying assumed distribution of the error terms is wrong in some respect, and fortunately it is possible to diagnose any flawed assumption from different kinds of departures from the theoretical distribution.
If you use the underlying error distribution $\epsilon_i \sim \text{IID N}(0, \sigma^2)$ for a standard regression model and you use OLS estimation for the coefficients, then the distribution of the residuals can be shown to be the multivariate normal distribution:
$$\boldsymbol{r} = (\boldsymbol{I} - \boldsymbol{h}) \boldsymbol{\epsilon} \sim \text{N}(\boldsymbol{0}, \sigma^2 (\boldsymbol{I} - \boldsymbol{h})),$$
where $\boldsymbol{h} = \boldsymbol{x} (\boldsymbol{x}^{\text{T}} \boldsymbol{x})^{-1} \boldsymbol{x}^{\text{T}}$ is the hat matrix for the regression. The residual vector mimics the error vector, but the variance matrix has the additional multiplicative term $\boldsymbol{I} - \boldsymbol{h}$. To test the regression assumptions we use the studentised residuals, which have marginal T-distribution:
$$s_i \equiv \frac{r_i}{\hat{\sigma}_{\text{Ext}} \cdot (1-l_i)} \sim \text{T}(\text{df}_{\text{Res}}-1).$$
(This formula is for the externally studentised residuals, where the variance estimator excludes the variable under consideration. The values $l_i = h_{i,i}$ are the leverage values, which are the diagonal values in the hat matrix. The studentised residuals are not independent, but if $n$ is large, they are close to independent. This means that the marginal distribution is a simple known distribution but the joint distribution is complicated.) Now, if the limit $\lim_{n \rightarrow \infty} (\boldsymbol{x}^{\text{T}} \boldsymbol{x}) / n = \Delta$ exists, then it can be shown that the coefficient estimators are consistent estimators of the true regression coefficients, and the residuals are consistent estimators of the true error terms.
Essentially, this means that you test the underlying distributional assumptions for the error terms by comparing the studentised residuals to the T-distribution. Each of the underlying properties of the error distribution (linearity, homoskedasticity, uncorrelated errors, normality) can be tested by using the analogous properties of the distribuion of the studentised residuals. If the model is correctly specified, then for large $n$ the residuals should be close to the true error terms, and they have a similar distributional form.
Omission of an explanatory variable from the regression model leads to omitted variable bias in the coefficient estimators and this affects the residual distribution. Both the mean and variance of the residual vector are affected by the omitted variable. If the omitted terms in the regression are $\boldsymbol{Z} \boldsymbol{\delta}$ then the residual vector becomes $\boldsymbol{r} = (\boldsymbol{I} - \boldsymbol{h}) (\boldsymbol{Z \delta} + \boldsymbol{\epsilon})$. If the data vectors in the omitted matrix $\boldsymbol{Z}$ are IID normal vectors and independent of the error terms then $\boldsymbol{Z \delta} + \boldsymbol{\epsilon} \sim \text{N} (\mu \boldsymbol{1}, \sigma_*^2 \boldsymbol{I})$ so that the residual distribution becomes:
$$\boldsymbol{r} = (\boldsymbol{I} - \boldsymbol{h}) (\boldsymbol{Z \delta} + \boldsymbol{\epsilon}) \sim \text{N} \Big( \mu (\boldsymbol{I} - \boldsymbol{h}) \boldsymbol{1}, \sigma_*^2 (\boldsymbol{I} - \boldsymbol{h}) \Big).$$
If there is already an intercept term in the model (i.e., if the unit vector $\boldsymbol{1}$ is in the design matrix) then $(\boldsymbol{I} - \boldsymbol{h}) \boldsymbol{1} = \boldsymbol{0}$, which means that the standard distributional form of the residuals is preserved. If there is no intercept term in the model then the omitted variable may give a non-zero mean for the residuals. Alternatively, if the omitted variable is not IID normal then it can lead to other deviations from the standard residual distribution. In this latter case, the residual tests are unlikely to detect anything resulting from the presence of an omitted variable; it is not usually possible to determine whether deviations from the theoretical residual distribution occurs as a result of an omitted variable, or merely because of an ill-posed relationship with the included variables (and arguably these are the same thing in any case). | Why do we use residuals to test the assumptions on errors in regression? | The residuals are our estimates of the error terms
The short answer to this question is relatively simple: the assumptions in a regression model are assumptions about the behaviour of the error terms, | Why do we use residuals to test the assumptions on errors in regression?
The residuals are our estimates of the error terms
The short answer to this question is relatively simple: the assumptions in a regression model are assumptions about the behaviour of the error terms, and the residuals are our estimates of the error terms. Ipso facto, examination of the behaviour of the observed residuals tells us whether or not the assumptions about the error terms are plausible.
To understand this general line of reasoning in more detail, it helps to examine in detail the behaviour of the residuals in a standard regression model. Under a standard multiple linear regression with independent homoskedastic normal error terms, the distribution of the residual vector is known, which allows you to test the underlying distributional assumptions in the regression model. The basic idea is that you figure out the distribution of the residual vector under the regression assumptions, and then check if the residual values plausibly match this theoretical distribution. Deviations from the theoretical residual distribution show that the underlying assumed distribution of the error terms is wrong in some respect, and fortunately it is possible to diagnose any flawed assumption from different kinds of departures from the theoretical distribution.
If you use the underlying error distribution $\epsilon_i \sim \text{IID N}(0, \sigma^2)$ for a standard regression model and you use OLS estimation for the coefficients, then the distribution of the residuals can be shown to be the multivariate normal distribution:
$$\boldsymbol{r} = (\boldsymbol{I} - \boldsymbol{h}) \boldsymbol{\epsilon} \sim \text{N}(\boldsymbol{0}, \sigma^2 (\boldsymbol{I} - \boldsymbol{h})),$$
where $\boldsymbol{h} = \boldsymbol{x} (\boldsymbol{x}^{\text{T}} \boldsymbol{x})^{-1} \boldsymbol{x}^{\text{T}}$ is the hat matrix for the regression. The residual vector mimics the error vector, but the variance matrix has the additional multiplicative term $\boldsymbol{I} - \boldsymbol{h}$. To test the regression assumptions we use the studentised residuals, which have marginal T-distribution:
$$s_i \equiv \frac{r_i}{\hat{\sigma}_{\text{Ext}} \cdot (1-l_i)} \sim \text{T}(\text{df}_{\text{Res}}-1).$$
(This formula is for the externally studentised residuals, where the variance estimator excludes the variable under consideration. The values $l_i = h_{i,i}$ are the leverage values, which are the diagonal values in the hat matrix. The studentised residuals are not independent, but if $n$ is large, they are close to independent. This means that the marginal distribution is a simple known distribution but the joint distribution is complicated.) Now, if the limit $\lim_{n \rightarrow \infty} (\boldsymbol{x}^{\text{T}} \boldsymbol{x}) / n = \Delta$ exists, then it can be shown that the coefficient estimators are consistent estimators of the true regression coefficients, and the residuals are consistent estimators of the true error terms.
Essentially, this means that you test the underlying distributional assumptions for the error terms by comparing the studentised residuals to the T-distribution. Each of the underlying properties of the error distribution (linearity, homoskedasticity, uncorrelated errors, normality) can be tested by using the analogous properties of the distribuion of the studentised residuals. If the model is correctly specified, then for large $n$ the residuals should be close to the true error terms, and they have a similar distributional form.
Omission of an explanatory variable from the regression model leads to omitted variable bias in the coefficient estimators and this affects the residual distribution. Both the mean and variance of the residual vector are affected by the omitted variable. If the omitted terms in the regression are $\boldsymbol{Z} \boldsymbol{\delta}$ then the residual vector becomes $\boldsymbol{r} = (\boldsymbol{I} - \boldsymbol{h}) (\boldsymbol{Z \delta} + \boldsymbol{\epsilon})$. If the data vectors in the omitted matrix $\boldsymbol{Z}$ are IID normal vectors and independent of the error terms then $\boldsymbol{Z \delta} + \boldsymbol{\epsilon} \sim \text{N} (\mu \boldsymbol{1}, \sigma_*^2 \boldsymbol{I})$ so that the residual distribution becomes:
$$\boldsymbol{r} = (\boldsymbol{I} - \boldsymbol{h}) (\boldsymbol{Z \delta} + \boldsymbol{\epsilon}) \sim \text{N} \Big( \mu (\boldsymbol{I} - \boldsymbol{h}) \boldsymbol{1}, \sigma_*^2 (\boldsymbol{I} - \boldsymbol{h}) \Big).$$
If there is already an intercept term in the model (i.e., if the unit vector $\boldsymbol{1}$ is in the design matrix) then $(\boldsymbol{I} - \boldsymbol{h}) \boldsymbol{1} = \boldsymbol{0}$, which means that the standard distributional form of the residuals is preserved. If there is no intercept term in the model then the omitted variable may give a non-zero mean for the residuals. Alternatively, if the omitted variable is not IID normal then it can lead to other deviations from the standard residual distribution. In this latter case, the residual tests are unlikely to detect anything resulting from the presence of an omitted variable; it is not usually possible to determine whether deviations from the theoretical residual distribution occurs as a result of an omitted variable, or merely because of an ill-posed relationship with the included variables (and arguably these are the same thing in any case). | Why do we use residuals to test the assumptions on errors in regression?
The residuals are our estimates of the error terms
The short answer to this question is relatively simple: the assumptions in a regression model are assumptions about the behaviour of the error terms, |
20,544 | Why do we use residuals to test the assumptions on errors in regression? | Usually, the terms residuals and errors mean the same thing. If your model has no predictors, E(Y) is indeed the mean of Y. With predictors (as in your model), E(Y) is the value of Y predicted from each X. So the residuals are the difference between each observed and predicted Y. | Why do we use residuals to test the assumptions on errors in regression? | Usually, the terms residuals and errors mean the same thing. If your model has no predictors, E(Y) is indeed the mean of Y. With predictors (as in your model), E(Y) is the value of Y predicted from ea | Why do we use residuals to test the assumptions on errors in regression?
Usually, the terms residuals and errors mean the same thing. If your model has no predictors, E(Y) is indeed the mean of Y. With predictors (as in your model), E(Y) is the value of Y predicted from each X. So the residuals are the difference between each observed and predicted Y. | Why do we use residuals to test the assumptions on errors in regression?
Usually, the terms residuals and errors mean the same thing. If your model has no predictors, E(Y) is indeed the mean of Y. With predictors (as in your model), E(Y) is the value of Y predicted from ea |
20,545 | More predictors than observations? | I think that the confusion comes from the way the word "observation" is sometimes used. Say that you wanted to know how the expression of 20,000 genes was related to some continuous biological variable like blood pressure. You have data both on expression of 20,000 genes and on blood pressure for 10,000 individuals. You might think that this involves 10,000 * 20,001 = 200,010,000 observations. There certainly are that many individual data points. But when people say there are "more predictors than observations" in this case, they only count each individual person as an "observation"; an "observation" is then a vector of all data points collected on a single individual. It might be less confusing to say "cases" rather than "observations," but usage in practice often has hidden assumptions like this.
The problem with more predictors than cases (usually indicated as "$p>n$") is that there is then no unique solution to a standard linear regression problem. If rows of the matrix of data points represent cases and columns represent predictors, there are necessarily linear dependences among the columns of the matrix. So once you've found coefficients for $n$ of the predictors, the coefficients for the other $(p-n)$ predictors can be expressed as arbitrary linear combinations of those first $n$ predictors. Other approaches like LASSO or ridge regression, or a variety of other machine-learning approaches, provide ways to proceed in such cases. | More predictors than observations? | I think that the confusion comes from the way the word "observation" is sometimes used. Say that you wanted to know how the expression of 20,000 genes was related to some continuous biological variabl | More predictors than observations?
I think that the confusion comes from the way the word "observation" is sometimes used. Say that you wanted to know how the expression of 20,000 genes was related to some continuous biological variable like blood pressure. You have data both on expression of 20,000 genes and on blood pressure for 10,000 individuals. You might think that this involves 10,000 * 20,001 = 200,010,000 observations. There certainly are that many individual data points. But when people say there are "more predictors than observations" in this case, they only count each individual person as an "observation"; an "observation" is then a vector of all data points collected on a single individual. It might be less confusing to say "cases" rather than "observations," but usage in practice often has hidden assumptions like this.
The problem with more predictors than cases (usually indicated as "$p>n$") is that there is then no unique solution to a standard linear regression problem. If rows of the matrix of data points represent cases and columns represent predictors, there are necessarily linear dependences among the columns of the matrix. So once you've found coefficients for $n$ of the predictors, the coefficients for the other $(p-n)$ predictors can be expressed as arbitrary linear combinations of those first $n$ predictors. Other approaches like LASSO or ridge regression, or a variety of other machine-learning approaches, provide ways to proceed in such cases. | More predictors than observations?
I think that the confusion comes from the way the word "observation" is sometimes used. Say that you wanted to know how the expression of 20,000 genes was related to some continuous biological variabl |
20,546 | More predictors than observations? | How could that even be possible?
More than possible, that's becoming more and more common as machine learning problems require unstructured features such as Natural Language Process (NLP), pictures, audios and videos.
NLP example: If a feature generation process takes one ore more text features and generate n-grams for each word found in each observation, the bigger the sample size, the much bigger will be the n-gram feature vector, although inherently an sparse matrix. | More predictors than observations? | How could that even be possible?
More than possible, that's becoming more and more common as machine learning problems require unstructured features such as Natural Language Process (NLP), pictures, | More predictors than observations?
How could that even be possible?
More than possible, that's becoming more and more common as machine learning problems require unstructured features such as Natural Language Process (NLP), pictures, audios and videos.
NLP example: If a feature generation process takes one ore more text features and generate n-grams for each word found in each observation, the bigger the sample size, the much bigger will be the n-gram feature vector, although inherently an sparse matrix. | More predictors than observations?
How could that even be possible?
More than possible, that's becoming more and more common as machine learning problems require unstructured features such as Natural Language Process (NLP), pictures, |
20,547 | Random Forest regression for time series prediction | How is this different from utilizing 'later' data in the time series
as testing?
The approach you quote is called "rolling origin" forecasting: the origin from which we forecast out is "rolled forward", and the training data is updated with the newly available information. The simpler approach is "single origin forecasting", where we pick a single origin.
The advantage of rolling origin forecasting is that it simulates a forecasting system over time. In single origin forecasting, we might by chance pick an origin where our system works very well (or very badly), which might give us an incorrect idea of our system's performance.
One disadvantage of rolling origin forecasting is its higher data requirement. If we want to forecast out 10 steps with at least 50 historical observations, then we can do this single-origin with 60 data points overall. But if we want to do 10 overlapping rolling origins, then we need 70 data points.
The other disadvantage is of course its higher complexity.
Needless to say, you should not use "later" data in rolling origin forecasting, either, but only use data prior to the origin you are using in each iteration.
Should I be validating my RF regression model with this
approach as well as on the testing data set?
If you have enough data, a rolling origin evaluation will always inspire more confidence in me than a single origin evaluation, because it will hopefully average out the impact of the origin.
Furthermore, is this sort
of 'autoregressive' approach to random forest regression valid for
time series, and do I even need to create this many lagged variables
if I'm interested in a prediction 10 minutes in the future?
Yes, rolling vs. single origin forecasting is valid for any predictive exercise. It doesn't depend on whether you use random forests or ARIMA or anything else.
Whether you need your lagged variables is something we can't counsel you on. It might be best to talk to a subject matter expert, who might also suggest other inputs. Just try your RF with the lagged inputs vs. without. And also compare to standard benchmarks like ARIMA or ETS or even simpler methods, which can be surprisingly hard to beat. | Random Forest regression for time series prediction | How is this different from utilizing 'later' data in the time series
as testing?
The approach you quote is called "rolling origin" forecasting: the origin from which we forecast out is "rolled forw | Random Forest regression for time series prediction
How is this different from utilizing 'later' data in the time series
as testing?
The approach you quote is called "rolling origin" forecasting: the origin from which we forecast out is "rolled forward", and the training data is updated with the newly available information. The simpler approach is "single origin forecasting", where we pick a single origin.
The advantage of rolling origin forecasting is that it simulates a forecasting system over time. In single origin forecasting, we might by chance pick an origin where our system works very well (or very badly), which might give us an incorrect idea of our system's performance.
One disadvantage of rolling origin forecasting is its higher data requirement. If we want to forecast out 10 steps with at least 50 historical observations, then we can do this single-origin with 60 data points overall. But if we want to do 10 overlapping rolling origins, then we need 70 data points.
The other disadvantage is of course its higher complexity.
Needless to say, you should not use "later" data in rolling origin forecasting, either, but only use data prior to the origin you are using in each iteration.
Should I be validating my RF regression model with this
approach as well as on the testing data set?
If you have enough data, a rolling origin evaluation will always inspire more confidence in me than a single origin evaluation, because it will hopefully average out the impact of the origin.
Furthermore, is this sort
of 'autoregressive' approach to random forest regression valid for
time series, and do I even need to create this many lagged variables
if I'm interested in a prediction 10 minutes in the future?
Yes, rolling vs. single origin forecasting is valid for any predictive exercise. It doesn't depend on whether you use random forests or ARIMA or anything else.
Whether you need your lagged variables is something we can't counsel you on. It might be best to talk to a subject matter expert, who might also suggest other inputs. Just try your RF with the lagged inputs vs. without. And also compare to standard benchmarks like ARIMA or ETS or even simpler methods, which can be surprisingly hard to beat. | Random Forest regression for time series prediction
How is this different from utilizing 'later' data in the time series
as testing?
The approach you quote is called "rolling origin" forecasting: the origin from which we forecast out is "rolled forw |
20,548 | What is the difference between linear perceptron regression and LS linear regression? | scikit-learn's Perceptron class (equivalent to SGDClassifier(loss="perceptron", penalty=None, learning_rate="constant", eta0=1)) uses the following objective function:
$$\frac{1}{N} \sum_{i=1}^N \max(0, - y_i w^T x_i).$$
In this case, $y_i \in \{-1, 1\}$. If $w^T x_i$ has the right sign, it doesn't incur any loss; otherwise, it gives linear loss. The perceptron in particular uses a fixed learning rate which can lead to some optimization weirdness as well.
Least squares regression, by contrast, uses
$$\frac{1}{N} \sum_{i=1}^N (y_i - w^T x_i)^2.$$
Here $y_i$ can be any real; you can give it classification targets in $\{-1, 1\}$ if you want, but it's not going to give you a very good model.
You can optimize this with SGDRegressor(loss="squared_loss", penalty=None) if you'd like.
The two define fundamentally different models: the perceptron predicts a binary class label with $\mathrm{sign}(w^T x_i)$, whereas linear regression predicts a real value with $w^T x_i$. This answer talks some about why trying to solve a classification problem with a regression algorithm can be problematic. | What is the difference between linear perceptron regression and LS linear regression? | scikit-learn's Perceptron class (equivalent to SGDClassifier(loss="perceptron", penalty=None, learning_rate="constant", eta0=1)) uses the following objective function:
$$\frac{1}{N} \sum_{i=1}^N \max( | What is the difference between linear perceptron regression and LS linear regression?
scikit-learn's Perceptron class (equivalent to SGDClassifier(loss="perceptron", penalty=None, learning_rate="constant", eta0=1)) uses the following objective function:
$$\frac{1}{N} \sum_{i=1}^N \max(0, - y_i w^T x_i).$$
In this case, $y_i \in \{-1, 1\}$. If $w^T x_i$ has the right sign, it doesn't incur any loss; otherwise, it gives linear loss. The perceptron in particular uses a fixed learning rate which can lead to some optimization weirdness as well.
Least squares regression, by contrast, uses
$$\frac{1}{N} \sum_{i=1}^N (y_i - w^T x_i)^2.$$
Here $y_i$ can be any real; you can give it classification targets in $\{-1, 1\}$ if you want, but it's not going to give you a very good model.
You can optimize this with SGDRegressor(loss="squared_loss", penalty=None) if you'd like.
The two define fundamentally different models: the perceptron predicts a binary class label with $\mathrm{sign}(w^T x_i)$, whereas linear regression predicts a real value with $w^T x_i$. This answer talks some about why trying to solve a classification problem with a regression algorithm can be problematic. | What is the difference between linear perceptron regression and LS linear regression?
scikit-learn's Perceptron class (equivalent to SGDClassifier(loss="perceptron", penalty=None, learning_rate="constant", eta0=1)) uses the following objective function:
$$\frac{1}{N} \sum_{i=1}^N \max( |
20,549 | Why use the parametric bootstrap? | Yes. You are right. But Parametric bootstrap shields better results when the assumptions hold. Think of it this way:
We have a random sample $X_1, \ldots, X_n$ from a distribution $F$. We estimate a parameter of interest $\theta$ as a function of the sample, $\hat{\theta} = h (X_1, \ldots, X_n)$. This estimate is a random variable, so it has a distribution we call $G$. This distribution is fully determined by $h$ and $F$ meaning $G=G(h,F)$. When doing any kind of bootstrap (parametric, non-parametric, re-sampling) what we are doing is to estimate $F$ with $\hat{F}$ in order to get an estimate of $G$, $\hat G = G(h,\hat{F})$. From $\hat G$ we estimate the properties of $\hat \theta$. What changes fom differents types of bootstrap is how we get $\hat{F}$.
If you can analytically calculate $\hat{G} = G(h,\hat{F})$ you should go for it, but in general, it is a rather hard thing to do. The magic of bootstrap is that we can generate samples with distribution $\hat G$.
To do this, we generate random samples $X^b_1, \ldots, X^b_n$ with distribution $\hat F$ and calculate $\hat {\theta}^b = h(X^b_1, \ldots, X^b_n)$ which will follow the $\hat G$ distribution.
Once you think of it this way, the advantages of parametric bootstrap are obvious. $\hat{F}$ would be a better approximation of $F$, then $\hat{G}$ would be closer to $G$ and finally the estimations of $\hat{\theta}$'s properties would be better. | Why use the parametric bootstrap? | Yes. You are right. But Parametric bootstrap shields better results when the assumptions hold. Think of it this way:
We have a random sample $X_1, \ldots, X_n$ from a distribution $F$. We estimate a | Why use the parametric bootstrap?
Yes. You are right. But Parametric bootstrap shields better results when the assumptions hold. Think of it this way:
We have a random sample $X_1, \ldots, X_n$ from a distribution $F$. We estimate a parameter of interest $\theta$ as a function of the sample, $\hat{\theta} = h (X_1, \ldots, X_n)$. This estimate is a random variable, so it has a distribution we call $G$. This distribution is fully determined by $h$ and $F$ meaning $G=G(h,F)$. When doing any kind of bootstrap (parametric, non-parametric, re-sampling) what we are doing is to estimate $F$ with $\hat{F}$ in order to get an estimate of $G$, $\hat G = G(h,\hat{F})$. From $\hat G$ we estimate the properties of $\hat \theta$. What changes fom differents types of bootstrap is how we get $\hat{F}$.
If you can analytically calculate $\hat{G} = G(h,\hat{F})$ you should go for it, but in general, it is a rather hard thing to do. The magic of bootstrap is that we can generate samples with distribution $\hat G$.
To do this, we generate random samples $X^b_1, \ldots, X^b_n$ with distribution $\hat F$ and calculate $\hat {\theta}^b = h(X^b_1, \ldots, X^b_n)$ which will follow the $\hat G$ distribution.
Once you think of it this way, the advantages of parametric bootstrap are obvious. $\hat{F}$ would be a better approximation of $F$, then $\hat{G}$ would be closer to $G$ and finally the estimations of $\hat{\theta}$'s properties would be better. | Why use the parametric bootstrap?
Yes. You are right. But Parametric bootstrap shields better results when the assumptions hold. Think of it this way:
We have a random sample $X_1, \ldots, X_n$ from a distribution $F$. We estimate a |
20,550 | Back-transformed confidence intervals | Why are you doing back transformations at all? That's critical to answering your question because in some cases the naive transform is the right answer. In fact, I think I'll argue that, if the naive back transform isn't the right answer then you shouldn't back transform at all.
I find the general issue of back transformation highly problematic and often filled with muddled thinking. Looking at the article you cited, what makes them think that it's a reasonable question that the back transformed CI doesn't capture the original mean? It's a mistaken interpretation of back transformed values. They think that the coverage should be for direct analysis in the back transformed space. And then they create a back transform to fix that mistake instead of their interpretation.
If you do your analyses on log values then your estimates and inferences apply to those log values. As long as you consider any back transform a representation of how that log analysis looks in the exponential space, and only as that, then you're fine with the naive approach. In fact, it's accurate. That's true of any transform.
Doing what they're doing solves the problem of trying to make the CI into something that it's not, a CI of the transformed values. This is fraught with problems. Consider the bind you're in now, the two possible CI's, one in transformed space where you do your analyses, and one back transformed, make very different statements about where the likely mu is in the other space. The recommended back transform creates more problems than it solves.
The best thing to take out of that paper is that when you decide to transform the data it has deeper impacts than expected on the meaning of your estimates and inferences. | Back-transformed confidence intervals | Why are you doing back transformations at all? That's critical to answering your question because in some cases the naive transform is the right answer. In fact, I think I'll argue that, if the naive | Back-transformed confidence intervals
Why are you doing back transformations at all? That's critical to answering your question because in some cases the naive transform is the right answer. In fact, I think I'll argue that, if the naive back transform isn't the right answer then you shouldn't back transform at all.
I find the general issue of back transformation highly problematic and often filled with muddled thinking. Looking at the article you cited, what makes them think that it's a reasonable question that the back transformed CI doesn't capture the original mean? It's a mistaken interpretation of back transformed values. They think that the coverage should be for direct analysis in the back transformed space. And then they create a back transform to fix that mistake instead of their interpretation.
If you do your analyses on log values then your estimates and inferences apply to those log values. As long as you consider any back transform a representation of how that log analysis looks in the exponential space, and only as that, then you're fine with the naive approach. In fact, it's accurate. That's true of any transform.
Doing what they're doing solves the problem of trying to make the CI into something that it's not, a CI of the transformed values. This is fraught with problems. Consider the bind you're in now, the two possible CI's, one in transformed space where you do your analyses, and one back transformed, make very different statements about where the likely mu is in the other space. The recommended back transform creates more problems than it solves.
The best thing to take out of that paper is that when you decide to transform the data it has deeper impacts than expected on the meaning of your estimates and inferences. | Back-transformed confidence intervals
Why are you doing back transformations at all? That's critical to answering your question because in some cases the naive transform is the right answer. In fact, I think I'll argue that, if the naive |
20,551 | Is there a problem with multicollinearity and for splines regression? | The multicollinearity can lead to numerical problems when estimating such a function. This is why some use B-splines (or variations on that theme) instead of restricted cubic splines. So, I tend to see restricted cubic splines as one potentially usefull tool in a larger toolbox. | Is there a problem with multicollinearity and for splines regression? | The multicollinearity can lead to numerical problems when estimating such a function. This is why some use B-splines (or variations on that theme) instead of restricted cubic splines. So, I tend to se | Is there a problem with multicollinearity and for splines regression?
The multicollinearity can lead to numerical problems when estimating such a function. This is why some use B-splines (or variations on that theme) instead of restricted cubic splines. So, I tend to see restricted cubic splines as one potentially usefull tool in a larger toolbox. | Is there a problem with multicollinearity and for splines regression?
The multicollinearity can lead to numerical problems when estimating such a function. This is why some use B-splines (or variations on that theme) instead of restricted cubic splines. So, I tend to se |
20,552 | A practical example for MCMC | A good example of a distribution that is hard to sample from is the Hard-Core model, see this page for an overview:
http://www.mathematik.uni-ulm.de/stochastik/lehre/ss06/markov/skript_engl/node34.html
This model defines a distribution over $n \times n$ grids for some fixed $n$, where at each point in the grid you can have a value of either one or zero. In order for a grid to be admissible under the hard-core model, no two adjacent points on the grid can both have a value of 1.
The image below shows an example admissible configuration for an $8 \times 8$ grid under the hard-core model. In this image ones are shown as black dots, and zeros as white. Note that not two black dots are adjacent.
I believe the inspiration for this model comes from physics, you can think of each position in the grid being a particle, and the value at that position representing electric charge, or spin.
We want to sample uniformly from the population of admissible grids, that is if $E$ is the set of admissible grids, we want to sample $e \in E$ such that
$
p(e) = \frac{1}{|E|}
$
where $|E|$ is the number of all possible admissible configurations.
Already this presents a challenge, given that we are considering $n \times n$ grids, how can we determine $|E|$ the number of admissible grids?
One of the nice things about MCMC, is that it allows you to sample from distributions where the normalizing constant is difficult or impossible to evaluate.
I'll let you read the paper on the details of of how to implement MCMC for this problem, but it is relatively straightforward. | A practical example for MCMC | A good example of a distribution that is hard to sample from is the Hard-Core model, see this page for an overview:
http://www.mathematik.uni-ulm.de/stochastik/lehre/ss06/markov/skript_engl/node34.htm | A practical example for MCMC
A good example of a distribution that is hard to sample from is the Hard-Core model, see this page for an overview:
http://www.mathematik.uni-ulm.de/stochastik/lehre/ss06/markov/skript_engl/node34.html
This model defines a distribution over $n \times n$ grids for some fixed $n$, where at each point in the grid you can have a value of either one or zero. In order for a grid to be admissible under the hard-core model, no two adjacent points on the grid can both have a value of 1.
The image below shows an example admissible configuration for an $8 \times 8$ grid under the hard-core model. In this image ones are shown as black dots, and zeros as white. Note that not two black dots are adjacent.
I believe the inspiration for this model comes from physics, you can think of each position in the grid being a particle, and the value at that position representing electric charge, or spin.
We want to sample uniformly from the population of admissible grids, that is if $E$ is the set of admissible grids, we want to sample $e \in E$ such that
$
p(e) = \frac{1}{|E|}
$
where $|E|$ is the number of all possible admissible configurations.
Already this presents a challenge, given that we are considering $n \times n$ grids, how can we determine $|E|$ the number of admissible grids?
One of the nice things about MCMC, is that it allows you to sample from distributions where the normalizing constant is difficult or impossible to evaluate.
I'll let you read the paper on the details of of how to implement MCMC for this problem, but it is relatively straightforward. | A practical example for MCMC
A good example of a distribution that is hard to sample from is the Hard-Core model, see this page for an overview:
http://www.mathematik.uni-ulm.de/stochastik/lehre/ss06/markov/skript_engl/node34.htm |
20,553 | A practical example for MCMC | I think the best example I can give you is this:
A Markov Chain Monte Carlo example by Murali Haran
Which includes some useful code in R.
I think that I could reproduce the article here, but it makes no sense. | A practical example for MCMC | I think the best example I can give you is this:
A Markov Chain Monte Carlo example by Murali Haran
Which includes some useful code in R.
I think that I could reproduce the article here, but it makes | A practical example for MCMC
I think the best example I can give you is this:
A Markov Chain Monte Carlo example by Murali Haran
Which includes some useful code in R.
I think that I could reproduce the article here, but it makes no sense. | A practical example for MCMC
I think the best example I can give you is this:
A Markov Chain Monte Carlo example by Murali Haran
Which includes some useful code in R.
I think that I could reproduce the article here, but it makes |
20,554 | A practical example for MCMC | Another daunting issue in statistics. The question is old, but the introductory examples on-line are hard to come by. So let me simplify two great examples just in case someone following the Markov random walk of PageRank lands here befuddled by MCMC, and full of anticipation for an easy to follow answer. How likely? That could be a follow-up question.
FIRST EXAMPLE:
The post recreates a standard normal distribution $N(0,1)$ using the Metropolis - Hastings algorithm. Far from a challenging case but a good one to dissect. I have collected the code from the post here for convenience and for annotations.
The difficulty is in realizing that after going through all the mechanical steps, there is just one magical trick: the binary decision of accepting or rejecting a proposed value.
It's good to keep in mind that what we want is to generate a bunch of values ($x$) that when plotted on a histogram look like a bell curve, centered (mean) at $0$ and with a standard deviation (sd) of $~ 1$. The problem is that we don't have predetermined parameters; that would be too easy, simply running something along the lines of rnorm(10000).
We do so by taking tiny (or larger, it won't change the results too much) random stochastic steps through the use of pseudorandom number generators. In the example, the magnitude of the step is set by eps, which determines the $\epsilon$, or size of the step to the left or to the right from the previous accepted value ($x_i$). This will be the starting line in the process that generates a new proposed value to fill in the next "link" of the "chain", $x_{i+1}$. OK, I'm talking about generating runif(1, - eps, eps) to either subtract or add to $x_i$.
Every proposed value would thus differ from the prior value in a random fashion, and within the boundaries of [- eps,+ eps].
Enter the Markov kernel. We need to assess the probability of transitioning to the new proposed value somehow, much like in a transition Markov matrix on a given state at time $i$ tells about the probability of the new state at time $i + 1$. If in doubt go here, or ask the grandma who's been paying attention to all the "How would you explain quantum physics to your nanna?" type of questions (don't the matrices look nice? ;-) ).
To get this probability of acceptance into the bouquet of culled values, we simply compare the height of the $N(0,1)$ density at the proposed new value ($x_{i+1}$) to the previous (already accepted value), ($x_{i}$), just like this:
And we take the ratio of both values: min(1, dnorm(candidate_value)/dnorm(x)). Since we want a probability, the resultant calculation cannot go over $1$, which occurs whenever the $N(0,1)$ $pdf$ at $x_{i+1}$ (candidate value) is greater than at $x_i$, amounting to automatic acceptance of the proposed value, and explaining the min(1, ...) part of the code. Otherwise, the closer the dnorm value of the proposed value is to the previous value, the higher the odds of it being accepted.
So we do have a probability of acceptance, but we need to make a binary decision (accept the new proposed value, or reject it). And here comes the magic trick: if the probability calculated as min(1, dnorm(candidate_value)/dnorm(x)) is greater than a runif(1) uniform draw from $0$ to $1$ (as close as it gets to a coin toss for a continuous value), we accept, and fill in the x[i+1] entry of the chain with the proposed value; otherwise, we fill it in with a repeat of the previous value, x[i]... The idea would be, better two of the same than one too far away into the tails.
We do this thousands of times and we collect all these values (only the accepted and repeated values), and when we plot the histogram, we get a nice normal curve with a sd close to $1$, and centered at $0$.
Just one final point: Where do we start? Probably not to relevant, but in the simulation, we fill in the first value as $0$, x = 0; vec[1] = x before looping through all the rest of iterations, and let the process follow its course.
SECOND EXAMPLE:
This is more exciting, and makes reference to estimating the parameters of a linear regression curve by calculating log likelihoods for random parameters given a dataset. However, the exegesis of the code lines is built in the condensed simulation saved here, following very similar steps to the first example. | A practical example for MCMC | Another daunting issue in statistics. The question is old, but the introductory examples on-line are hard to come by. So let me simplify two great examples just in case someone following the Markov ra | A practical example for MCMC
Another daunting issue in statistics. The question is old, but the introductory examples on-line are hard to come by. So let me simplify two great examples just in case someone following the Markov random walk of PageRank lands here befuddled by MCMC, and full of anticipation for an easy to follow answer. How likely? That could be a follow-up question.
FIRST EXAMPLE:
The post recreates a standard normal distribution $N(0,1)$ using the Metropolis - Hastings algorithm. Far from a challenging case but a good one to dissect. I have collected the code from the post here for convenience and for annotations.
The difficulty is in realizing that after going through all the mechanical steps, there is just one magical trick: the binary decision of accepting or rejecting a proposed value.
It's good to keep in mind that what we want is to generate a bunch of values ($x$) that when plotted on a histogram look like a bell curve, centered (mean) at $0$ and with a standard deviation (sd) of $~ 1$. The problem is that we don't have predetermined parameters; that would be too easy, simply running something along the lines of rnorm(10000).
We do so by taking tiny (or larger, it won't change the results too much) random stochastic steps through the use of pseudorandom number generators. In the example, the magnitude of the step is set by eps, which determines the $\epsilon$, or size of the step to the left or to the right from the previous accepted value ($x_i$). This will be the starting line in the process that generates a new proposed value to fill in the next "link" of the "chain", $x_{i+1}$. OK, I'm talking about generating runif(1, - eps, eps) to either subtract or add to $x_i$.
Every proposed value would thus differ from the prior value in a random fashion, and within the boundaries of [- eps,+ eps].
Enter the Markov kernel. We need to assess the probability of transitioning to the new proposed value somehow, much like in a transition Markov matrix on a given state at time $i$ tells about the probability of the new state at time $i + 1$. If in doubt go here, or ask the grandma who's been paying attention to all the "How would you explain quantum physics to your nanna?" type of questions (don't the matrices look nice? ;-) ).
To get this probability of acceptance into the bouquet of culled values, we simply compare the height of the $N(0,1)$ density at the proposed new value ($x_{i+1}$) to the previous (already accepted value), ($x_{i}$), just like this:
And we take the ratio of both values: min(1, dnorm(candidate_value)/dnorm(x)). Since we want a probability, the resultant calculation cannot go over $1$, which occurs whenever the $N(0,1)$ $pdf$ at $x_{i+1}$ (candidate value) is greater than at $x_i$, amounting to automatic acceptance of the proposed value, and explaining the min(1, ...) part of the code. Otherwise, the closer the dnorm value of the proposed value is to the previous value, the higher the odds of it being accepted.
So we do have a probability of acceptance, but we need to make a binary decision (accept the new proposed value, or reject it). And here comes the magic trick: if the probability calculated as min(1, dnorm(candidate_value)/dnorm(x)) is greater than a runif(1) uniform draw from $0$ to $1$ (as close as it gets to a coin toss for a continuous value), we accept, and fill in the x[i+1] entry of the chain with the proposed value; otherwise, we fill it in with a repeat of the previous value, x[i]... The idea would be, better two of the same than one too far away into the tails.
We do this thousands of times and we collect all these values (only the accepted and repeated values), and when we plot the histogram, we get a nice normal curve with a sd close to $1$, and centered at $0$.
Just one final point: Where do we start? Probably not to relevant, but in the simulation, we fill in the first value as $0$, x = 0; vec[1] = x before looping through all the rest of iterations, and let the process follow its course.
SECOND EXAMPLE:
This is more exciting, and makes reference to estimating the parameters of a linear regression curve by calculating log likelihoods for random parameters given a dataset. However, the exegesis of the code lines is built in the condensed simulation saved here, following very similar steps to the first example. | A practical example for MCMC
Another daunting issue in statistics. The question is old, but the introductory examples on-line are hard to come by. So let me simplify two great examples just in case someone following the Markov ra |
20,555 | A practical example for MCMC | This Youtube video is a really nice visualization of a simple problem that's solved using MCMC.
The distribution of interest is the posterior distribution over possible slopes and intercepts in a linear regression (upper-right panel). Some combinations of slopes and intercepts are very probable (i.e. they have a high likelihood of producing the observed data points and are consistent with our a priori expectations), so they should be sampled frequently. Other combinations are improbable (e.g. if they correspond to a blue line that doesn't go through the cloud of data points), and should be sampled less often.
The big panel in the lower-left shows the path taken by the Markov chain through a two-dimensional space of slopes and intercepts. The histograms show one-dimensional summaries of the chain's progress so far. Once the chain has run long enough, we have very good estimates of the distributions for possible values of the slope and intercept.
In this case, MCMC is overkill, but there are some problems where a solution is hard to write down and it makes a lot of sense to explore the possibilities with a Markov chain rather than trying to solve it directly. | A practical example for MCMC | This Youtube video is a really nice visualization of a simple problem that's solved using MCMC.
The distribution of interest is the posterior distribution over possible slopes and intercepts in a line | A practical example for MCMC
This Youtube video is a really nice visualization of a simple problem that's solved using MCMC.
The distribution of interest is the posterior distribution over possible slopes and intercepts in a linear regression (upper-right panel). Some combinations of slopes and intercepts are very probable (i.e. they have a high likelihood of producing the observed data points and are consistent with our a priori expectations), so they should be sampled frequently. Other combinations are improbable (e.g. if they correspond to a blue line that doesn't go through the cloud of data points), and should be sampled less often.
The big panel in the lower-left shows the path taken by the Markov chain through a two-dimensional space of slopes and intercepts. The histograms show one-dimensional summaries of the chain's progress so far. Once the chain has run long enough, we have very good estimates of the distributions for possible values of the slope and intercept.
In this case, MCMC is overkill, but there are some problems where a solution is hard to write down and it makes a lot of sense to explore the possibilities with a Markov chain rather than trying to solve it directly. | A practical example for MCMC
This Youtube video is a really nice visualization of a simple problem that's solved using MCMC.
The distribution of interest is the posterior distribution over possible slopes and intercepts in a line |
20,556 | Conditions for the existence of a Fisher information matrix | I do not have access to all the references, but I would like to point out a few remarks on some of your points:
Borovkov, Mathematical Statistics (1998). p. 140 presents another assumption, Condition (R), which is quite strong. This condition assumes that $E[(\partial\log f(x;\theta)/\partial\theta)^2]<\infty$. Then, the author basically assumes that each entry of the Fisher information matrix (FIM) is well-defined.
The double differentiability and exchangeability of the integral and differential operators assumptions are employed to deduce the equality $E[(\partial\log f(x;\theta)/\partial\theta)^2]=-E[\partial^2\log f(x;\theta)/\partial\theta^2]$. This equality is often helpful, but not strictly necessary.
It is difficult to establish general conditions for the existence of the FIM without discarding some models for which the FIM actually exists. For instance, differentiability condition is not a necessary condition for the existence of the FIM. An example of this is the double exponential or Laplace model. The corresponding FIM is well defined, but the density is not doubly differentiable at the mode. Some other models which are doubly differentiable have bad-behaved FIM and require some additional conditions (see this paper).
It is possible to come up with very general sufficient conditions, but they might be too strict. Necessary conditions for the existence of the FIM have not been fully studied. Then, the answer to your first question may not be simple. | Conditions for the existence of a Fisher information matrix | I do not have access to all the references, but I would like to point out a few remarks on some of your points:
Borovkov, Mathematical Statistics (1998). p. 140 presents another assumption, Condition | Conditions for the existence of a Fisher information matrix
I do not have access to all the references, but I would like to point out a few remarks on some of your points:
Borovkov, Mathematical Statistics (1998). p. 140 presents another assumption, Condition (R), which is quite strong. This condition assumes that $E[(\partial\log f(x;\theta)/\partial\theta)^2]<\infty$. Then, the author basically assumes that each entry of the Fisher information matrix (FIM) is well-defined.
The double differentiability and exchangeability of the integral and differential operators assumptions are employed to deduce the equality $E[(\partial\log f(x;\theta)/\partial\theta)^2]=-E[\partial^2\log f(x;\theta)/\partial\theta^2]$. This equality is often helpful, but not strictly necessary.
It is difficult to establish general conditions for the existence of the FIM without discarding some models for which the FIM actually exists. For instance, differentiability condition is not a necessary condition for the existence of the FIM. An example of this is the double exponential or Laplace model. The corresponding FIM is well defined, but the density is not doubly differentiable at the mode. Some other models which are doubly differentiable have bad-behaved FIM and require some additional conditions (see this paper).
It is possible to come up with very general sufficient conditions, but they might be too strict. Necessary conditions for the existence of the FIM have not been fully studied. Then, the answer to your first question may not be simple. | Conditions for the existence of a Fisher information matrix
I do not have access to all the references, but I would like to point out a few remarks on some of your points:
Borovkov, Mathematical Statistics (1998). p. 140 presents another assumption, Condition |
20,557 | How can a vector of variables represent a hyperplane? | Let $N$ be the number of observations and $K$ the number of explanatory variables.
$X$ is actually a $N\!\times\!K$ matrix. Only when we look at a single observation, we denote each observation usually as $x_i^T$ - a row vector of explanatory variables of one particular observation scalar multiplied with the $K\!\times\!1$ column vector $\beta$. Furthermore, $Y$ is a $N\!\times\!1$ column vector, holding all observations $Y_n$.
Now, a two dimensional hyperplane would span between the vector $Y$ and one(!) column vector of $X$. Remember that $X$ is a $N\!\times\!K$ matrix, so each explanatory variable is represented by exactly one column vector of the matrix $X$. If we have only one explanatory variable, no intercept and $Y$, all data points are situated along the 2 dimensional plane spanned by $Y$ and $X$.
For a multiple regression, how many dimensions in total does the hyperplane between $Y$ and the matrix $X$ have? Answer: Since we have $K$ column vectors of explanatory variables in $X$, we must have a $K\!+\!1$ dimensional hyperplane.
Usually, in a matrix setting, the regression requires a constant intercept to be unbiased for a reasonable analysis of the slope coefficient. To accommodate for this trick, we force one column of the matrix $X$ to be only consisting of "$1$s". In this case, the estimator $\beta_1$ stands alone multiplied with a constant for each observation instead of a random explanatory variable. The coefficient $\beta_1$ represents the therefore the expected value of $Y$ given that $x_{1i}$ is held fixed with value 1 and all other variables are zero. Therefore the $K\!+\!1$-dimensional hyperplane is reduced by one dimension to a $K$-dimensional subspace, and $\beta_1$ corresponds to the "intercept" of this $K$-dimensional plane.
In matrix settings its always advisable to have a look at the simple case of two dimensions, to see if we can find an intuition for our results. Here, the easiest way is to think of the simple regression with two explanatory variables:
$$
y_i=\beta_1x_{1i} + \beta_2x_{2i} +u_i
$$
or alternatively expressed in Matrix algebra: $Y=X\beta +u$ where $X$ is a $N\!\times\!2$ matrix.
$<Y,X>$ spans a 3-dimensional hyperplane.
Now if we force all $x_1$ to be all $1$, we obtain:
$$
y_i=\beta_{1i} + \beta_2x_{2i} + u_i
$$
which is our usual simple regression that can be represented in a two dimensional $X,\ Y$ plot. Note that $<Y,X>$ is now reduced to a two dimensional line - a subset of the originally 3 dimensional hyperplane. The coefficient $\beta_1$ corresponds to the intercept of the line cutting at $x_{2i}=0$.
It can be further shown that it also passes through $<0,\beta_1>$ for when the constant is included. If we leave out the constant, the regression hyperplane always passes trivially through $<0,0>$ - no doubt. This generalizes to multiple dimensions, as it will be seen later for when deriving $\beta$:
$$
(X'X)\beta=X'y \implies (X'X)\beta-X'y=0 \implies X'(y-X\beta)=0.
$$
Since $X$ has full rank per definition, $y-X\beta=0$, and so the regression passes through the origin if we leave out the intercept.
(Edit: I just realized that for your second question this is exactly the opposite of you have written regading inclusion or exclusion of the constant. However, I have already devised the solution here and I stand corrected if I am wrong on that one.)
I know the matrix representation of a regression can be quite confusing at the beginning but eventually it simplifies a lot when deriving more complex algebra. Hope this helps a bit. | How can a vector of variables represent a hyperplane? | Let $N$ be the number of observations and $K$ the number of explanatory variables.
$X$ is actually a $N\!\times\!K$ matrix. Only when we look at a single observation, we denote each observation usuall | How can a vector of variables represent a hyperplane?
Let $N$ be the number of observations and $K$ the number of explanatory variables.
$X$ is actually a $N\!\times\!K$ matrix. Only when we look at a single observation, we denote each observation usually as $x_i^T$ - a row vector of explanatory variables of one particular observation scalar multiplied with the $K\!\times\!1$ column vector $\beta$. Furthermore, $Y$ is a $N\!\times\!1$ column vector, holding all observations $Y_n$.
Now, a two dimensional hyperplane would span between the vector $Y$ and one(!) column vector of $X$. Remember that $X$ is a $N\!\times\!K$ matrix, so each explanatory variable is represented by exactly one column vector of the matrix $X$. If we have only one explanatory variable, no intercept and $Y$, all data points are situated along the 2 dimensional plane spanned by $Y$ and $X$.
For a multiple regression, how many dimensions in total does the hyperplane between $Y$ and the matrix $X$ have? Answer: Since we have $K$ column vectors of explanatory variables in $X$, we must have a $K\!+\!1$ dimensional hyperplane.
Usually, in a matrix setting, the regression requires a constant intercept to be unbiased for a reasonable analysis of the slope coefficient. To accommodate for this trick, we force one column of the matrix $X$ to be only consisting of "$1$s". In this case, the estimator $\beta_1$ stands alone multiplied with a constant for each observation instead of a random explanatory variable. The coefficient $\beta_1$ represents the therefore the expected value of $Y$ given that $x_{1i}$ is held fixed with value 1 and all other variables are zero. Therefore the $K\!+\!1$-dimensional hyperplane is reduced by one dimension to a $K$-dimensional subspace, and $\beta_1$ corresponds to the "intercept" of this $K$-dimensional plane.
In matrix settings its always advisable to have a look at the simple case of two dimensions, to see if we can find an intuition for our results. Here, the easiest way is to think of the simple regression with two explanatory variables:
$$
y_i=\beta_1x_{1i} + \beta_2x_{2i} +u_i
$$
or alternatively expressed in Matrix algebra: $Y=X\beta +u$ where $X$ is a $N\!\times\!2$ matrix.
$<Y,X>$ spans a 3-dimensional hyperplane.
Now if we force all $x_1$ to be all $1$, we obtain:
$$
y_i=\beta_{1i} + \beta_2x_{2i} + u_i
$$
which is our usual simple regression that can be represented in a two dimensional $X,\ Y$ plot. Note that $<Y,X>$ is now reduced to a two dimensional line - a subset of the originally 3 dimensional hyperplane. The coefficient $\beta_1$ corresponds to the intercept of the line cutting at $x_{2i}=0$.
It can be further shown that it also passes through $<0,\beta_1>$ for when the constant is included. If we leave out the constant, the regression hyperplane always passes trivially through $<0,0>$ - no doubt. This generalizes to multiple dimensions, as it will be seen later for when deriving $\beta$:
$$
(X'X)\beta=X'y \implies (X'X)\beta-X'y=0 \implies X'(y-X\beta)=0.
$$
Since $X$ has full rank per definition, $y-X\beta=0$, and so the regression passes through the origin if we leave out the intercept.
(Edit: I just realized that for your second question this is exactly the opposite of you have written regading inclusion or exclusion of the constant. However, I have already devised the solution here and I stand corrected if I am wrong on that one.)
I know the matrix representation of a regression can be quite confusing at the beginning but eventually it simplifies a lot when deriving more complex algebra. Hope this helps a bit. | How can a vector of variables represent a hyperplane?
Let $N$ be the number of observations and $K$ the number of explanatory variables.
$X$ is actually a $N\!\times\!K$ matrix. Only when we look at a single observation, we denote each observation usuall |
20,558 | How can a vector of variables represent a hyperplane? | Clearly @whuber's comment is correct: "The book is wrong". If you omit the intercept term then the hyperplane does pass through the origin. If you include it, then the hyperplane intersects each of the axis at the point where all the other axes are zero and the axis under consideration is value of that single component of the intercept entry.
I think the way to think of it is to rearrange that equation:
$$\widehat{Y} - X^{T} \widehat{\beta} = 0$$
The only way you will get that linear equation to include the origin is to make the predicted $\widehat{Y}$ equal to the intercept. And the way to estimate that value is to include an intercept term in the regression model. | How can a vector of variables represent a hyperplane? | Clearly @whuber's comment is correct: "The book is wrong". If you omit the intercept term then the hyperplane does pass through the origin. If you include it, then the hyperplane intersects each of t | How can a vector of variables represent a hyperplane?
Clearly @whuber's comment is correct: "The book is wrong". If you omit the intercept term then the hyperplane does pass through the origin. If you include it, then the hyperplane intersects each of the axis at the point where all the other axes are zero and the axis under consideration is value of that single component of the intercept entry.
I think the way to think of it is to rearrange that equation:
$$\widehat{Y} - X^{T} \widehat{\beta} = 0$$
The only way you will get that linear equation to include the origin is to make the predicted $\widehat{Y}$ equal to the intercept. And the way to estimate that value is to include an intercept term in the regression model. | How can a vector of variables represent a hyperplane?
Clearly @whuber's comment is correct: "The book is wrong". If you omit the intercept term then the hyperplane does pass through the origin. If you include it, then the hyperplane intersects each of t |
20,559 | Techniques for analyzing ratios | I wouldn't call observed correlations spurious, but rather false causal inferences drawn from those correlations. Problems with ratios are of a kind with other types of confounding.
If you define random variables $U=\frac{X}{Q}$ & $V=\frac{Y}{Q}$, where $X$, $Y$, & $Q$ are independent, then $U$ & $V$ are correlated. This could mislead you into thinking there's a causal relationship from $X$ to $Y$ or vice versa, or from something other than $Q$ to both of them. It's no use however simply deciding to eschew the use of ratios. Observations aren't essentially ratios, & if $U$, $V$, & $Q$ are independent you will introduce "spurious" correlations by using the ratios $X=\frac{U}{1/Q}$ & $Y=\frac{V}{1/Q}$. Including $Q$ in your analysis—& it's important to note that 'scaling' by $Q$ is not the same thing†—protects you whichever you use; but not from other confounders $R,S,T,\ldots$
Aldrich (1995), ""Correlations Genuine and Spurious in Pearson and Yule", Statistical Science, 10, 4 provides an intesting historical perspective.
† See Including the interaction but not the main effects in a model. | Techniques for analyzing ratios | I wouldn't call observed correlations spurious, but rather false causal inferences drawn from those correlations. Problems with ratios are of a kind with other types of confounding.
If you define rand | Techniques for analyzing ratios
I wouldn't call observed correlations spurious, but rather false causal inferences drawn from those correlations. Problems with ratios are of a kind with other types of confounding.
If you define random variables $U=\frac{X}{Q}$ & $V=\frac{Y}{Q}$, where $X$, $Y$, & $Q$ are independent, then $U$ & $V$ are correlated. This could mislead you into thinking there's a causal relationship from $X$ to $Y$ or vice versa, or from something other than $Q$ to both of them. It's no use however simply deciding to eschew the use of ratios. Observations aren't essentially ratios, & if $U$, $V$, & $Q$ are independent you will introduce "spurious" correlations by using the ratios $X=\frac{U}{1/Q}$ & $Y=\frac{V}{1/Q}$. Including $Q$ in your analysis—& it's important to note that 'scaling' by $Q$ is not the same thing†—protects you whichever you use; but not from other confounders $R,S,T,\ldots$
Aldrich (1995), ""Correlations Genuine and Spurious in Pearson and Yule", Statistical Science, 10, 4 provides an intesting historical perspective.
† See Including the interaction but not the main effects in a model. | Techniques for analyzing ratios
I wouldn't call observed correlations spurious, but rather false causal inferences drawn from those correlations. Problems with ratios are of a kind with other types of confounding.
If you define rand |
20,560 | poisson vs logistic regression | One solution to this problem is to assume that the number of events (like flare-ups) is proportional to time. If you denote the individual level of exposure (length of follow-up in your case) by $t$, then $\frac{E[y \vert x]}{t}=\exp\{x'\beta\}.$ Here a follow-up that is twice as long would double the expected count, all else equal. This can be algebraically equivalent to a model where $E[y \vert x]=\exp\{x'\beta+\log{t}\},$ which is just the Poisson model with the coefficient on $\log t$ constrained to $1$. You can also test the proportionality assumption by relaxing the constraint and testing the hypothesis that $\beta_{log(t)}=1$.
However, it does not sound like you observe the number of events, since your outcome is binary (or maybe it's not meaningful given your disease). This leads me to believe a logistic model with an logarithmic offset would be more appropriate here. | poisson vs logistic regression | One solution to this problem is to assume that the number of events (like flare-ups) is proportional to time. If you denote the individual level of exposure (length of follow-up in your case) by $t$, | poisson vs logistic regression
One solution to this problem is to assume that the number of events (like flare-ups) is proportional to time. If you denote the individual level of exposure (length of follow-up in your case) by $t$, then $\frac{E[y \vert x]}{t}=\exp\{x'\beta\}.$ Here a follow-up that is twice as long would double the expected count, all else equal. This can be algebraically equivalent to a model where $E[y \vert x]=\exp\{x'\beta+\log{t}\},$ which is just the Poisson model with the coefficient on $\log t$ constrained to $1$. You can also test the proportionality assumption by relaxing the constraint and testing the hypothesis that $\beta_{log(t)}=1$.
However, it does not sound like you observe the number of events, since your outcome is binary (or maybe it's not meaningful given your disease). This leads me to believe a logistic model with an logarithmic offset would be more appropriate here. | poisson vs logistic regression
One solution to this problem is to assume that the number of events (like flare-ups) is proportional to time. If you denote the individual level of exposure (length of follow-up in your case) by $t$, |
20,561 | poisson vs logistic regression | This dataset sounds like a person-years dataset, the outcome being an event (is this correct?) and uneven follow-up until the event. In that case, this is sounds like a cohort study of some sort (assuming I understood what is being researched), and thus, either poisson regression OR a survival analysis may be warranted (kaplan-meier & cox-proportional hazards regression). | poisson vs logistic regression | This dataset sounds like a person-years dataset, the outcome being an event (is this correct?) and uneven follow-up until the event. In that case, this is sounds like a cohort study of some sort (assu | poisson vs logistic regression
This dataset sounds like a person-years dataset, the outcome being an event (is this correct?) and uneven follow-up until the event. In that case, this is sounds like a cohort study of some sort (assuming I understood what is being researched), and thus, either poisson regression OR a survival analysis may be warranted (kaplan-meier & cox-proportional hazards regression). | poisson vs logistic regression
This dataset sounds like a person-years dataset, the outcome being an event (is this correct?) and uneven follow-up until the event. In that case, this is sounds like a cohort study of some sort (assu |
20,562 | lme4 or other open source R package code equivalent to asreml-R | You can fit this model with AD Model Builder. AD Model Builder is free software for building general nonlinear models including general nonlinear random effects
models. So for example you could fit a negative binomial spatial model where
both the mean and over dispersion had an ar(1) x ar(1) structure.
I built the code for this example and fit it to the data.
If anyone is interested it is probably better to discuss this on the list at
http://admb-project.org
Note: There is an R version of ADMB, but the features available in the R package are a subset of the standalone ADMB software.
For this example it is easier to create an ASCII file with the data,
read it into the ADMB program, run the program, and then read the parameter
estimates etc back into R for whatever you want to do.
You should understand that ADMB is not a collection of packages, but rather
a language for writing nonlinear parameter estimation software. As I said before it is better to discuss this on the ADMB list where everyone knows about the software. After it is done and you understand the model you can post the results here. However here is a link to the ML and REML codes I put together
for the wheat data.
http://lists.admb-project.org/pipermail/users/attachments/20111124/448923c8/attachment.zip | lme4 or other open source R package code equivalent to asreml-R | You can fit this model with AD Model Builder. AD Model Builder is free software for building general nonlinear models including general nonlinear random effects
models. So for example you could fit a | lme4 or other open source R package code equivalent to asreml-R
You can fit this model with AD Model Builder. AD Model Builder is free software for building general nonlinear models including general nonlinear random effects
models. So for example you could fit a negative binomial spatial model where
both the mean and over dispersion had an ar(1) x ar(1) structure.
I built the code for this example and fit it to the data.
If anyone is interested it is probably better to discuss this on the list at
http://admb-project.org
Note: There is an R version of ADMB, but the features available in the R package are a subset of the standalone ADMB software.
For this example it is easier to create an ASCII file with the data,
read it into the ADMB program, run the program, and then read the parameter
estimates etc back into R for whatever you want to do.
You should understand that ADMB is not a collection of packages, but rather
a language for writing nonlinear parameter estimation software. As I said before it is better to discuss this on the ADMB list where everyone knows about the software. After it is done and you understand the model you can post the results here. However here is a link to the ML and REML codes I put together
for the wheat data.
http://lists.admb-project.org/pipermail/users/attachments/20111124/448923c8/attachment.zip | lme4 or other open source R package code equivalent to asreml-R
You can fit this model with AD Model Builder. AD Model Builder is free software for building general nonlinear models including general nonlinear random effects
models. So for example you could fit a |
20,563 | lme4 or other open source R package code equivalent to asreml-R | Model 0
ASReml-R
rcb0.asr <- asreml(yield~Variety, random=~Rep, data=nin89, na.method.X="include")
summary(rcb0.asr)
$call
asreml(fixed = yield ~ Variety, random = ~Rep, data = nin89,
na.method.X = "include")
$loglik
[1] -454.4691
$nedf
[1] 168
$sigma
[1] 7.041475
$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 0.1993231 9.882911 8.792829 1.123974 Positive
R!variance 1.0000000 49.582368 5.458839 9.082951 Positive
attr(,"class")
[1] "summary.asreml"
summary(rcb0.asr)$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 0.1993231 9.882911 8.792829 1.123974 Positive
R!variance 1.0000000 49.582368 5.458839 9.082951 Positive
> anova(rcb0.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 12001.6 242.054 <2e-16 ***
Variety 55 2387.5 48.152 0.7317
residual (MS) 49.6
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(rcb0.asr)$fixed
effect
Variety_ARAPAHOE 0.0000
Variety_BRULE -3.3625
Variety_BUCKSKIN -3.8750
Variety_CENTURA -7.7875
Variety_CENTURK78 0.8625
Variety_CHEYENNE -1.3750
Variety_CODY -8.2250
Variety_COLT -2.4375
Variety_GAGE -4.9250
Variety_HOMESTEAD -1.8000
Variety_KS831374 -5.3125
Variety_LANCER -0.8750
Variety_LANCOTA -2.8875
Variety_NE83404 -2.0500
Variety_NE83406 -5.1625
Variety_NE83407 -6.7500
Variety_NE83432 -9.7125
Variety_NE83498 0.6875
Variety_NE83T12 -7.8750
Variety_NE84557 -8.9125
Variety_NE85556 -3.0500
Variety_NE85623 -7.7125
Variety_NE86482 -5.1500
Variety_NE86501 1.5000
Variety_NE86503 3.2125
Variety_NE86507 -5.6500
Variety_NE86509 -2.5875
Variety_NE86527 -7.4250
Variety_NE86582 -4.9000
Variety_NE86606 0.3250
Variety_NE86607 -0.1125
Variety_NE86T666 -7.9000
Variety_NE87403 -4.3125
Variety_NE87408 -3.1375
Variety_NE87409 -8.0625
Variety_NE87446 -1.7625
Variety_NE87451 -4.8250
Variety_NE87457 -5.5250
Variety_NE87463 -3.5250
Variety_NE87499 -9.0250
Variety_NE87512 -6.1875
Variety_NE87513 -2.6250
Variety_NE87522 -4.4375
Variety_NE87612 -7.6375
Variety_NE87613 -0.0375
Variety_NE87615 -3.7500
Variety_NE87619 1.8250
Variety_NE87627 -6.2125
Variety_NORKAN -5.0250
Variety_REDLAND 1.0625
Variety_ROUGHRIDER -8.2500
Variety_SCOUT66 -1.9125
Variety_SIOUXLAND 0.6750
Variety_TAM107 -1.0375
Variety_TAM200 -8.2000
Variety_VONA -5.8375
(Intercept) 29.4375
> coef(rcb0.asr)$random
effect
Rep_1 1.8795997
Rep_2 2.8432659
Rep_3 -0.8712739
Rep_4 -3.8515918
lme4
> rcb0.lmer <- lmer(yield~Variety+(1|Rep), data=nin89)
> print(rcb0.lmer, corr=FALSE)
Linear mixed model fit by REML
Formula: yield ~ Variety + (1 | Rep)
Data: nin89
AIC BIC logLik deviance REMLdev
1334 1532 -608.9 1456 1218
Random effects:
Groups Name Variance Std.Dev.
Rep (Intercept) 9.8829 3.1437
Residual 49.5824 7.0415
Number of obs: 224, groups: Rep, 4
Fixed effects:
Estimate Std. Error t value
(Intercept) 29.4375 3.8556 7.635
VarietyBRULE -3.3625 4.9791 -0.675
VarietyBUCKSKIN -3.8750 4.9791 -0.778
VarietyCENTURA -7.7875 4.9791 -1.564
VarietyCENTURK78 0.8625 4.9791 0.173
VarietyCHEYENNE -1.3750 4.9791 -0.276
VarietyCODY -8.2250 4.9791 -1.652
VarietyCOLT -2.4375 4.9791 -0.490
VarietyGAGE -4.9250 4.9791 -0.989
VarietyHOMESTEAD -1.8000 4.9791 -0.362
VarietyKS831374 -5.3125 4.9791 -1.067
VarietyLANCER -0.8750 4.9791 -0.176
VarietyLANCOTA -2.8875 4.9791 -0.580
VarietyNE83404 -2.0500 4.9791 -0.412
VarietyNE83406 -5.1625 4.9791 -1.037
VarietyNE83407 -6.7500 4.9791 -1.356
VarietyNE83432 -9.7125 4.9791 -1.951
VarietyNE83498 0.6875 4.9791 0.138
VarietyNE83T12 -7.8750 4.9791 -1.582
VarietyNE84557 -8.9125 4.9791 -1.790
VarietyNE85556 -3.0500 4.9791 -0.613
VarietyNE85623 -7.7125 4.9791 -1.549
VarietyNE86482 -5.1500 4.9791 -1.034
VarietyNE86501 1.5000 4.9791 0.301
VarietyNE86503 3.2125 4.9791 0.645
VarietyNE86507 -5.6500 4.9791 -1.135
VarietyNE86509 -2.5875 4.9791 -0.520
VarietyNE86527 -7.4250 4.9791 -1.491
VarietyNE86582 -4.9000 4.9791 -0.984
VarietyNE86606 0.3250 4.9791 0.065
VarietyNE86607 -0.1125 4.9791 -0.023
VarietyNE86T666 -7.9000 4.9791 -1.587
VarietyNE87403 -4.3125 4.9791 -0.866
VarietyNE87408 -3.1375 4.9791 -0.630
VarietyNE87409 -8.0625 4.9791 -1.619
VarietyNE87446 -1.7625 4.9791 -0.354
VarietyNE87451 -4.8250 4.9791 -0.969
VarietyNE87457 -5.5250 4.9791 -1.110
VarietyNE87463 -3.5250 4.9791 -0.708
VarietyNE87499 -9.0250 4.9791 -1.813
VarietyNE87512 -6.1875 4.9791 -1.243
VarietyNE87513 -2.6250 4.9791 -0.527
VarietyNE87522 -4.4375 4.9791 -0.891
VarietyNE87612 -7.6375 4.9791 -1.534
VarietyNE87613 -0.0375 4.9791 -0.008
VarietyNE87615 -3.7500 4.9791 -0.753
VarietyNE87619 1.8250 4.9791 0.367
VarietyNE87627 -6.2125 4.9791 -1.248
VarietyNORKAN -5.0250 4.9791 -1.009
VarietyREDLAND 1.0625 4.9791 0.213
VarietyROUGHRIDER -8.2500 4.9791 -1.657
VarietySCOUT66 -1.9125 4.9791 -0.384
VarietySIOUXLAND 0.6750 4.9791 0.136
VarietyTAM107 -1.0375 4.9791 -0.208
VarietyTAM200 -8.2000 4.9791 -1.647
VarietyVONA -5.8375 4.9791 -1.172
> anova(rcb0.lmer)
Analysis of Variance Table
Df Sum Sq Mean Sq F value
Variety 55 2387.5 43.409 0.8755
> fixef(rcb0.lmer)
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
> ranef(rcb0.lmer)
$Rep
(Intercept)
1 1.8798700
2 2.8436747
3 -0.8713991
4 -3.8521455
nlme
> rcb0.lme <- lme(yield~Variety, random=~1|Rep, data=na.omit(nin89))
> print(rcb0.lme, corr=FALSE)
Linear mixed-effects model fit by REML
Data: na.omit(nin89)
Log-restricted-likelihood: -608.8508
Fixed: yield ~ Variety
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
Random effects:
Formula: ~1 | Rep
(Intercept) Residual
StdDev: 3.14371 7.041475
Number of Observations: 224
Number of Groups: 4
> anova(rcb0.lme)
numDF denDF F-value p-value
(Intercept) 1 165 242.05402 <.0001
Variety 55 165 0.87549 0.7119
> fixef(rcb0.lme)
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
> ranef(rcb0.lme)
(Intercept)
1 1.8795997
2 2.8432659
3 -0.8712739
4 -3.8515918 | lme4 or other open source R package code equivalent to asreml-R | Model 0
ASReml-R
rcb0.asr <- asreml(yield~Variety, random=~Rep, data=nin89, na.method.X="include")
summary(rcb0.asr)
$call
asreml(fixed = yield ~ Variety, random = ~Rep, data = nin89,
na.method.X | lme4 or other open source R package code equivalent to asreml-R
Model 0
ASReml-R
rcb0.asr <- asreml(yield~Variety, random=~Rep, data=nin89, na.method.X="include")
summary(rcb0.asr)
$call
asreml(fixed = yield ~ Variety, random = ~Rep, data = nin89,
na.method.X = "include")
$loglik
[1] -454.4691
$nedf
[1] 168
$sigma
[1] 7.041475
$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 0.1993231 9.882911 8.792829 1.123974 Positive
R!variance 1.0000000 49.582368 5.458839 9.082951 Positive
attr(,"class")
[1] "summary.asreml"
summary(rcb0.asr)$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 0.1993231 9.882911 8.792829 1.123974 Positive
R!variance 1.0000000 49.582368 5.458839 9.082951 Positive
> anova(rcb0.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 12001.6 242.054 <2e-16 ***
Variety 55 2387.5 48.152 0.7317
residual (MS) 49.6
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(rcb0.asr)$fixed
effect
Variety_ARAPAHOE 0.0000
Variety_BRULE -3.3625
Variety_BUCKSKIN -3.8750
Variety_CENTURA -7.7875
Variety_CENTURK78 0.8625
Variety_CHEYENNE -1.3750
Variety_CODY -8.2250
Variety_COLT -2.4375
Variety_GAGE -4.9250
Variety_HOMESTEAD -1.8000
Variety_KS831374 -5.3125
Variety_LANCER -0.8750
Variety_LANCOTA -2.8875
Variety_NE83404 -2.0500
Variety_NE83406 -5.1625
Variety_NE83407 -6.7500
Variety_NE83432 -9.7125
Variety_NE83498 0.6875
Variety_NE83T12 -7.8750
Variety_NE84557 -8.9125
Variety_NE85556 -3.0500
Variety_NE85623 -7.7125
Variety_NE86482 -5.1500
Variety_NE86501 1.5000
Variety_NE86503 3.2125
Variety_NE86507 -5.6500
Variety_NE86509 -2.5875
Variety_NE86527 -7.4250
Variety_NE86582 -4.9000
Variety_NE86606 0.3250
Variety_NE86607 -0.1125
Variety_NE86T666 -7.9000
Variety_NE87403 -4.3125
Variety_NE87408 -3.1375
Variety_NE87409 -8.0625
Variety_NE87446 -1.7625
Variety_NE87451 -4.8250
Variety_NE87457 -5.5250
Variety_NE87463 -3.5250
Variety_NE87499 -9.0250
Variety_NE87512 -6.1875
Variety_NE87513 -2.6250
Variety_NE87522 -4.4375
Variety_NE87612 -7.6375
Variety_NE87613 -0.0375
Variety_NE87615 -3.7500
Variety_NE87619 1.8250
Variety_NE87627 -6.2125
Variety_NORKAN -5.0250
Variety_REDLAND 1.0625
Variety_ROUGHRIDER -8.2500
Variety_SCOUT66 -1.9125
Variety_SIOUXLAND 0.6750
Variety_TAM107 -1.0375
Variety_TAM200 -8.2000
Variety_VONA -5.8375
(Intercept) 29.4375
> coef(rcb0.asr)$random
effect
Rep_1 1.8795997
Rep_2 2.8432659
Rep_3 -0.8712739
Rep_4 -3.8515918
lme4
> rcb0.lmer <- lmer(yield~Variety+(1|Rep), data=nin89)
> print(rcb0.lmer, corr=FALSE)
Linear mixed model fit by REML
Formula: yield ~ Variety + (1 | Rep)
Data: nin89
AIC BIC logLik deviance REMLdev
1334 1532 -608.9 1456 1218
Random effects:
Groups Name Variance Std.Dev.
Rep (Intercept) 9.8829 3.1437
Residual 49.5824 7.0415
Number of obs: 224, groups: Rep, 4
Fixed effects:
Estimate Std. Error t value
(Intercept) 29.4375 3.8556 7.635
VarietyBRULE -3.3625 4.9791 -0.675
VarietyBUCKSKIN -3.8750 4.9791 -0.778
VarietyCENTURA -7.7875 4.9791 -1.564
VarietyCENTURK78 0.8625 4.9791 0.173
VarietyCHEYENNE -1.3750 4.9791 -0.276
VarietyCODY -8.2250 4.9791 -1.652
VarietyCOLT -2.4375 4.9791 -0.490
VarietyGAGE -4.9250 4.9791 -0.989
VarietyHOMESTEAD -1.8000 4.9791 -0.362
VarietyKS831374 -5.3125 4.9791 -1.067
VarietyLANCER -0.8750 4.9791 -0.176
VarietyLANCOTA -2.8875 4.9791 -0.580
VarietyNE83404 -2.0500 4.9791 -0.412
VarietyNE83406 -5.1625 4.9791 -1.037
VarietyNE83407 -6.7500 4.9791 -1.356
VarietyNE83432 -9.7125 4.9791 -1.951
VarietyNE83498 0.6875 4.9791 0.138
VarietyNE83T12 -7.8750 4.9791 -1.582
VarietyNE84557 -8.9125 4.9791 -1.790
VarietyNE85556 -3.0500 4.9791 -0.613
VarietyNE85623 -7.7125 4.9791 -1.549
VarietyNE86482 -5.1500 4.9791 -1.034
VarietyNE86501 1.5000 4.9791 0.301
VarietyNE86503 3.2125 4.9791 0.645
VarietyNE86507 -5.6500 4.9791 -1.135
VarietyNE86509 -2.5875 4.9791 -0.520
VarietyNE86527 -7.4250 4.9791 -1.491
VarietyNE86582 -4.9000 4.9791 -0.984
VarietyNE86606 0.3250 4.9791 0.065
VarietyNE86607 -0.1125 4.9791 -0.023
VarietyNE86T666 -7.9000 4.9791 -1.587
VarietyNE87403 -4.3125 4.9791 -0.866
VarietyNE87408 -3.1375 4.9791 -0.630
VarietyNE87409 -8.0625 4.9791 -1.619
VarietyNE87446 -1.7625 4.9791 -0.354
VarietyNE87451 -4.8250 4.9791 -0.969
VarietyNE87457 -5.5250 4.9791 -1.110
VarietyNE87463 -3.5250 4.9791 -0.708
VarietyNE87499 -9.0250 4.9791 -1.813
VarietyNE87512 -6.1875 4.9791 -1.243
VarietyNE87513 -2.6250 4.9791 -0.527
VarietyNE87522 -4.4375 4.9791 -0.891
VarietyNE87612 -7.6375 4.9791 -1.534
VarietyNE87613 -0.0375 4.9791 -0.008
VarietyNE87615 -3.7500 4.9791 -0.753
VarietyNE87619 1.8250 4.9791 0.367
VarietyNE87627 -6.2125 4.9791 -1.248
VarietyNORKAN -5.0250 4.9791 -1.009
VarietyREDLAND 1.0625 4.9791 0.213
VarietyROUGHRIDER -8.2500 4.9791 -1.657
VarietySCOUT66 -1.9125 4.9791 -0.384
VarietySIOUXLAND 0.6750 4.9791 0.136
VarietyTAM107 -1.0375 4.9791 -0.208
VarietyTAM200 -8.2000 4.9791 -1.647
VarietyVONA -5.8375 4.9791 -1.172
> anova(rcb0.lmer)
Analysis of Variance Table
Df Sum Sq Mean Sq F value
Variety 55 2387.5 43.409 0.8755
> fixef(rcb0.lmer)
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
> ranef(rcb0.lmer)
$Rep
(Intercept)
1 1.8798700
2 2.8436747
3 -0.8713991
4 -3.8521455
nlme
> rcb0.lme <- lme(yield~Variety, random=~1|Rep, data=na.omit(nin89))
> print(rcb0.lme, corr=FALSE)
Linear mixed-effects model fit by REML
Data: na.omit(nin89)
Log-restricted-likelihood: -608.8508
Fixed: yield ~ Variety
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
Random effects:
Formula: ~1 | Rep
(Intercept) Residual
StdDev: 3.14371 7.041475
Number of Observations: 224
Number of Groups: 4
> anova(rcb0.lme)
numDF denDF F-value p-value
(Intercept) 1 165 242.05402 <.0001
Variety 55 165 0.87549 0.7119
> fixef(rcb0.lme)
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
> ranef(rcb0.lme)
(Intercept)
1 1.8795997
2 2.8432659
3 -0.8712739
4 -3.8515918 | lme4 or other open source R package code equivalent to asreml-R
Model 0
ASReml-R
rcb0.asr <- asreml(yield~Variety, random=~Rep, data=nin89, na.method.X="include")
summary(rcb0.asr)
$call
asreml(fixed = yield ~ Variety, random = ~Rep, data = nin89,
na.method.X |
20,564 | lme4 or other open source R package code equivalent to asreml-R | Model 1
ASReml-R
> rcb.asr <- asreml(yield~Variety, random=~idv(Rep), rcov=~idv(units), data=nin89, na.method.X="include")
> summary(rcb.asr)
$call
asreml(fixed = yield ~ Variety, random = ~idv(Rep), rcov = ~idv(units),
data = nin89, na.method.X = "include")
$loglik
[1] -454.4691
$nedf
[1] 168
$sigma
[1] 1
$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 9.882911 9.882911 8.792823 1.123975 Positive
R!variance 1.000000 1.000000 NA NA Fixed
R!units.var 49.582368 49.582368 5.458839 9.082951 Positive
attr(,"class")
[1] "summary.asreml"
> summary(rcb0.asr)$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 0.1993231 9.882911 8.792829 1.123974 Positive
R!variance 1.0000000 49.582368 5.458839 9.082951 Positive
> anova(rcb.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 242.054 242.054 <2e-16 ***
Variety 55 48.152 48.152 0.7317
residual (MS) 1.000
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(rcb.asr)$fixed
effect
Variety_ARAPAHOE 0.0000
Variety_BRULE -3.3625
Variety_BUCKSKIN -3.8750
Variety_CENTURA -7.7875
Variety_CENTURK78 0.8625
Variety_CHEYENNE -1.3750
Variety_CODY -8.2250
Variety_COLT -2.4375
Variety_GAGE -4.9250
Variety_HOMESTEAD -1.8000
Variety_KS831374 -5.3125
Variety_LANCER -0.8750
Variety_LANCOTA -2.8875
Variety_NE83404 -2.0500
Variety_NE83406 -5.1625
Variety_NE83407 -6.7500
Variety_NE83432 -9.7125
Variety_NE83498 0.6875
Variety_NE83T12 -7.8750
Variety_NE84557 -8.9125
Variety_NE85556 -3.0500
Variety_NE85623 -7.7125
Variety_NE86482 -5.1500
Variety_NE86501 1.5000
Variety_NE86503 3.2125
Variety_NE86507 -5.6500
Variety_NE86509 -2.5875
Variety_NE86527 -7.4250
Variety_NE86582 -4.9000
Variety_NE86606 0.3250
Variety_NE86607 -0.1125
Variety_NE86T666 -7.9000
Variety_NE87403 -4.3125
Variety_NE87408 -3.1375
Variety_NE87409 -8.0625
Variety_NE87446 -1.7625
Variety_NE87451 -4.8250
Variety_NE87457 -5.5250
Variety_NE87463 -3.5250
Variety_NE87499 -9.0250
Variety_NE87512 -6.1875
Variety_NE87513 -2.6250
Variety_NE87522 -4.4375
Variety_NE87612 -7.6375
Variety_NE87613 -0.0375
Variety_NE87615 -3.7500
Variety_NE87619 1.8250
Variety_NE87627 -6.2125
Variety_NORKAN -5.0250
Variety_REDLAND 1.0625
Variety_ROUGHRIDER -8.2500
Variety_SCOUT66 -1.9125
Variety_SIOUXLAND 0.6750
Variety_TAM107 -1.0375
Variety_TAM200 -8.2000
Variety_VONA -5.8375
(Intercept) 29.4375
> coef(rcb.asr)$random
effect
Rep_1 1.8795997
Rep_2 2.8432658
Rep_3 -0.8712738
Rep_4 -3.8515916
nlme
See the trick
> nin89$Int <- 1
> rcb.lme <- lme(yield~Variety, random=list(Int=pdIdent(~Rep-1)), data=na.omit(nin89))
> print(rcb.lme, corr=FALSE)
Linear mixed-effects model fit by REML
Data: na.omit(nin89)
Log-restricted-likelihood: -608.8508
Fixed: yield ~ Variety
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
Random effects:
Formula: ~Rep - 1 | Int
Structure: Multiple of an Identity
Rep1 Rep2 Rep3 Rep4 Residual
StdDev: 3.14371 3.14371 3.14371 3.14371 7.041475
Number of Observations: 224
Number of Groups: 1
> anova(rcb.lme)
numDF denDF F-value p-value
(Intercept) 1 168 242.05402 <.0001
Variety 55 168 0.87549 0.7121
> fixef(rcb.lme)
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
> ranef(rcb.lme)
Rep1 Rep2 Rep3 Rep4
1 1.8796 2.843266 -0.8712739 -3.851592 | lme4 or other open source R package code equivalent to asreml-R | Model 1
ASReml-R
> rcb.asr <- asreml(yield~Variety, random=~idv(Rep), rcov=~idv(units), data=nin89, na.method.X="include")
> summary(rcb.asr)
$call
asreml(fixed = yield ~ Variety, random = ~idv(Rep), | lme4 or other open source R package code equivalent to asreml-R
Model 1
ASReml-R
> rcb.asr <- asreml(yield~Variety, random=~idv(Rep), rcov=~idv(units), data=nin89, na.method.X="include")
> summary(rcb.asr)
$call
asreml(fixed = yield ~ Variety, random = ~idv(Rep), rcov = ~idv(units),
data = nin89, na.method.X = "include")
$loglik
[1] -454.4691
$nedf
[1] 168
$sigma
[1] 1
$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 9.882911 9.882911 8.792823 1.123975 Positive
R!variance 1.000000 1.000000 NA NA Fixed
R!units.var 49.582368 49.582368 5.458839 9.082951 Positive
attr(,"class")
[1] "summary.asreml"
> summary(rcb0.asr)$varcomp
gamma component std.error z.ratio constraint
Rep!Rep.var 0.1993231 9.882911 8.792829 1.123974 Positive
R!variance 1.0000000 49.582368 5.458839 9.082951 Positive
> anova(rcb.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 242.054 242.054 <2e-16 ***
Variety 55 48.152 48.152 0.7317
residual (MS) 1.000
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(rcb.asr)$fixed
effect
Variety_ARAPAHOE 0.0000
Variety_BRULE -3.3625
Variety_BUCKSKIN -3.8750
Variety_CENTURA -7.7875
Variety_CENTURK78 0.8625
Variety_CHEYENNE -1.3750
Variety_CODY -8.2250
Variety_COLT -2.4375
Variety_GAGE -4.9250
Variety_HOMESTEAD -1.8000
Variety_KS831374 -5.3125
Variety_LANCER -0.8750
Variety_LANCOTA -2.8875
Variety_NE83404 -2.0500
Variety_NE83406 -5.1625
Variety_NE83407 -6.7500
Variety_NE83432 -9.7125
Variety_NE83498 0.6875
Variety_NE83T12 -7.8750
Variety_NE84557 -8.9125
Variety_NE85556 -3.0500
Variety_NE85623 -7.7125
Variety_NE86482 -5.1500
Variety_NE86501 1.5000
Variety_NE86503 3.2125
Variety_NE86507 -5.6500
Variety_NE86509 -2.5875
Variety_NE86527 -7.4250
Variety_NE86582 -4.9000
Variety_NE86606 0.3250
Variety_NE86607 -0.1125
Variety_NE86T666 -7.9000
Variety_NE87403 -4.3125
Variety_NE87408 -3.1375
Variety_NE87409 -8.0625
Variety_NE87446 -1.7625
Variety_NE87451 -4.8250
Variety_NE87457 -5.5250
Variety_NE87463 -3.5250
Variety_NE87499 -9.0250
Variety_NE87512 -6.1875
Variety_NE87513 -2.6250
Variety_NE87522 -4.4375
Variety_NE87612 -7.6375
Variety_NE87613 -0.0375
Variety_NE87615 -3.7500
Variety_NE87619 1.8250
Variety_NE87627 -6.2125
Variety_NORKAN -5.0250
Variety_REDLAND 1.0625
Variety_ROUGHRIDER -8.2500
Variety_SCOUT66 -1.9125
Variety_SIOUXLAND 0.6750
Variety_TAM107 -1.0375
Variety_TAM200 -8.2000
Variety_VONA -5.8375
(Intercept) 29.4375
> coef(rcb.asr)$random
effect
Rep_1 1.8795997
Rep_2 2.8432658
Rep_3 -0.8712738
Rep_4 -3.8515916
nlme
See the trick
> nin89$Int <- 1
> rcb.lme <- lme(yield~Variety, random=list(Int=pdIdent(~Rep-1)), data=na.omit(nin89))
> print(rcb.lme, corr=FALSE)
Linear mixed-effects model fit by REML
Data: na.omit(nin89)
Log-restricted-likelihood: -608.8508
Fixed: yield ~ Variety
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
Random effects:
Formula: ~Rep - 1 | Int
Structure: Multiple of an Identity
Rep1 Rep2 Rep3 Rep4 Residual
StdDev: 3.14371 3.14371 3.14371 3.14371 7.041475
Number of Observations: 224
Number of Groups: 1
> anova(rcb.lme)
numDF denDF F-value p-value
(Intercept) 1 168 242.05402 <.0001
Variety 55 168 0.87549 0.7121
> fixef(rcb.lme)
(Intercept) VarietyBRULE VarietyBUCKSKIN VarietyCENTURA
29.4375 -3.3625 -3.8750 -7.7875
VarietyCENTURK78 VarietyCHEYENNE VarietyCODY VarietyCOLT
0.8625 -1.3750 -8.2250 -2.4375
VarietyGAGE VarietyHOMESTEAD VarietyKS831374 VarietyLANCER
-4.9250 -1.8000 -5.3125 -0.8750
VarietyLANCOTA VarietyNE83404 VarietyNE83406 VarietyNE83407
-2.8875 -2.0500 -5.1625 -6.7500
VarietyNE83432 VarietyNE83498 VarietyNE83T12 VarietyNE84557
-9.7125 0.6875 -7.8750 -8.9125
VarietyNE85556 VarietyNE85623 VarietyNE86482 VarietyNE86501
-3.0500 -7.7125 -5.1500 1.5000
VarietyNE86503 VarietyNE86507 VarietyNE86509 VarietyNE86527
3.2125 -5.6500 -2.5875 -7.4250
VarietyNE86582 VarietyNE86606 VarietyNE86607 VarietyNE86T666
-4.9000 0.3250 -0.1125 -7.9000
VarietyNE87403 VarietyNE87408 VarietyNE87409 VarietyNE87446
-4.3125 -3.1375 -8.0625 -1.7625
VarietyNE87451 VarietyNE87457 VarietyNE87463 VarietyNE87499
-4.8250 -5.5250 -3.5250 -9.0250
VarietyNE87512 VarietyNE87513 VarietyNE87522 VarietyNE87612
-6.1875 -2.6250 -4.4375 -7.6375
VarietyNE87613 VarietyNE87615 VarietyNE87619 VarietyNE87627
-0.0375 -3.7500 1.8250 -6.2125
VarietyNORKAN VarietyREDLAND VarietyROUGHRIDER VarietySCOUT66
-5.0250 1.0625 -8.2500 -1.9125
VarietySIOUXLAND VarietyTAM107 VarietyTAM200 VarietyVONA
0.6750 -1.0375 -8.2000 -5.8375
> ranef(rcb.lme)
Rep1 Rep2 Rep3 Rep4
1 1.8796 2.843266 -0.8712739 -3.851592 | lme4 or other open source R package code equivalent to asreml-R
Model 1
ASReml-R
> rcb.asr <- asreml(yield~Variety, random=~idv(Rep), rcov=~idv(units), data=nin89, na.method.X="include")
> summary(rcb.asr)
$call
asreml(fixed = yield ~ Variety, random = ~idv(Rep), |
20,565 | lme4 or other open source R package code equivalent to asreml-R | Model 2
ASReml-R
sp1.asr <- asreml(yield~Variety, rcov=~Column:ar1(Row), data=nin89, na.method.X="include")
> summary(sp1.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~Column:ar1(Row), data = nin89,
na.method.X = "include")
$loglik
[1] -408.1412
$nedf
[1] 168
$sigma
[1] 7.975127
$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 63.6026561 11.3182328 5.619486 Positive
R!Row.cor 0.7795799 0.7795799 0.0406026 19.200245 Unconstrained
attr(,"class")
[1] "summary.asreml"
> summary(sp1.asr)$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 63.6026561 11.3182328 5.619486 Positive
R!Row.cor 0.7795799 0.7795799 0.0406026 19.200245 Unconstrained
> anova(sp1.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 24604.3 386.84 < 2.2e-16 ***
Variety 55 7974.4 125.38 2.048e-07 ***
residual (MS) 63.6
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(sp1.asr)$fixed
effect
Variety_ARAPAHOE 0.0000000
Variety_BRULE -2.4048816
Variety_BUCKSKIN 7.8064972
Variety_CENTURA -1.6997427
Variety_CENTURK78 -1.3829446
Variety_CHEYENNE -1.1113084
Variety_CODY -6.7461911
Variety_COLT -1.7963394
Variety_GAGE -3.4539524
Variety_HOMESTEAD -5.5877510
Variety_KS831374 -0.8589476
Variety_LANCER -2.8418476
Variety_LANCOTA -5.9394801
Variety_NE83404 -3.4112613
Variety_NE83406 -1.9057358
Variety_NE83407 -3.2563922
Variety_NE83432 -5.4594311
Variety_NE83498 0.6446010
Variety_NE83T12 -4.0071361
Variety_NE84557 -4.2005181
Variety_NE85556 1.4836395
Variety_NE85623 -2.7617129
Variety_NE86482 -1.4309381
Variety_NE86501 -2.2287462
Variety_NE86503 -0.4557866
Variety_NE86507 -0.6983418
Variety_NE86509 -3.9215624
Variety_NE86527 0.5294386
Variety_NE86582 -5.4653632
Variety_NE86606 -0.7291575
Variety_NE86607 -0.1265536
Variety_NE86T666 -12.1437291
Variety_NE87403 -7.4623631
Variety_NE87408 -3.3586380
Variety_NE87409 -1.0360336
Variety_NE87446 -4.9030958
Variety_NE87451 -3.2836149
Variety_NE87457 -3.5244583
Variety_NE87463 -3.8427658
Variety_NE87499 -4.6298393
Variety_NE87512 -5.3760809
Variety_NE87513 -5.5656241
Variety_NE87522 -7.6500899
Variety_NE87612 -2.7225851
Variety_NE87613 -0.8793319
Variety_NE87615 -4.0089291
Variety_NE87619 0.7975626
Variety_NE87627 -10.1315147
Variety_NORKAN -7.1804945
Variety_REDLAND 0.6753066
Variety_ROUGHRIDER -0.9637487
Variety_SCOUT66 0.7088916
Variety_SIOUXLAND -1.1998807
Variety_TAM107 -3.7160351
Variety_TAM200 -9.0340942
Variety_VONA -2.7970689
(Intercept) 28.3487457
nlme
Working on, yet not figured out. Could be something like this. Still could not figure out how to do rcov=~Column:ar1(Row) with nlme
nin89$Int <- 1
sp1.lme <- lme(yield~Variety, random=~1|Int, data=na.omit(nin89)) | lme4 or other open source R package code equivalent to asreml-R | Model 2
ASReml-R
sp1.asr <- asreml(yield~Variety, rcov=~Column:ar1(Row), data=nin89, na.method.X="include")
> summary(sp1.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~Column:ar1(Row), data = ni | lme4 or other open source R package code equivalent to asreml-R
Model 2
ASReml-R
sp1.asr <- asreml(yield~Variety, rcov=~Column:ar1(Row), data=nin89, na.method.X="include")
> summary(sp1.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~Column:ar1(Row), data = nin89,
na.method.X = "include")
$loglik
[1] -408.1412
$nedf
[1] 168
$sigma
[1] 7.975127
$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 63.6026561 11.3182328 5.619486 Positive
R!Row.cor 0.7795799 0.7795799 0.0406026 19.200245 Unconstrained
attr(,"class")
[1] "summary.asreml"
> summary(sp1.asr)$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 63.6026561 11.3182328 5.619486 Positive
R!Row.cor 0.7795799 0.7795799 0.0406026 19.200245 Unconstrained
> anova(sp1.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 24604.3 386.84 < 2.2e-16 ***
Variety 55 7974.4 125.38 2.048e-07 ***
residual (MS) 63.6
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(sp1.asr)$fixed
effect
Variety_ARAPAHOE 0.0000000
Variety_BRULE -2.4048816
Variety_BUCKSKIN 7.8064972
Variety_CENTURA -1.6997427
Variety_CENTURK78 -1.3829446
Variety_CHEYENNE -1.1113084
Variety_CODY -6.7461911
Variety_COLT -1.7963394
Variety_GAGE -3.4539524
Variety_HOMESTEAD -5.5877510
Variety_KS831374 -0.8589476
Variety_LANCER -2.8418476
Variety_LANCOTA -5.9394801
Variety_NE83404 -3.4112613
Variety_NE83406 -1.9057358
Variety_NE83407 -3.2563922
Variety_NE83432 -5.4594311
Variety_NE83498 0.6446010
Variety_NE83T12 -4.0071361
Variety_NE84557 -4.2005181
Variety_NE85556 1.4836395
Variety_NE85623 -2.7617129
Variety_NE86482 -1.4309381
Variety_NE86501 -2.2287462
Variety_NE86503 -0.4557866
Variety_NE86507 -0.6983418
Variety_NE86509 -3.9215624
Variety_NE86527 0.5294386
Variety_NE86582 -5.4653632
Variety_NE86606 -0.7291575
Variety_NE86607 -0.1265536
Variety_NE86T666 -12.1437291
Variety_NE87403 -7.4623631
Variety_NE87408 -3.3586380
Variety_NE87409 -1.0360336
Variety_NE87446 -4.9030958
Variety_NE87451 -3.2836149
Variety_NE87457 -3.5244583
Variety_NE87463 -3.8427658
Variety_NE87499 -4.6298393
Variety_NE87512 -5.3760809
Variety_NE87513 -5.5656241
Variety_NE87522 -7.6500899
Variety_NE87612 -2.7225851
Variety_NE87613 -0.8793319
Variety_NE87615 -4.0089291
Variety_NE87619 0.7975626
Variety_NE87627 -10.1315147
Variety_NORKAN -7.1804945
Variety_REDLAND 0.6753066
Variety_ROUGHRIDER -0.9637487
Variety_SCOUT66 0.7088916
Variety_SIOUXLAND -1.1998807
Variety_TAM107 -3.7160351
Variety_TAM200 -9.0340942
Variety_VONA -2.7970689
(Intercept) 28.3487457
nlme
Working on, yet not figured out. Could be something like this. Still could not figure out how to do rcov=~Column:ar1(Row) with nlme
nin89$Int <- 1
sp1.lme <- lme(yield~Variety, random=~1|Int, data=na.omit(nin89)) | lme4 or other open source R package code equivalent to asreml-R
Model 2
ASReml-R
sp1.asr <- asreml(yield~Variety, rcov=~Column:ar1(Row), data=nin89, na.method.X="include")
> summary(sp1.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~Column:ar1(Row), data = ni |
20,566 | lme4 or other open source R package code equivalent to asreml-R | Model 3
ASReml-R
sp2.asr <- asreml(yield~Variety, rcov=~ar1(Column):ar1(Row), data=nin89, na.method.X="include")
> summary(sp2.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~ar1(Column):ar1(Row),
data = nin89, na.method.X = "include")
$loglik
[1] -399.3238
$nedf
[1] 168
$sigma
[1] 6.978728
$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 48.7026395 7.15527571 6.806536 Positive
R!Column.cor 0.4375045 0.4375045 0.08060227 5.427943 Unconstrained
R!Row.cor 0.6554798 0.6554798 0.05637709 11.626704 Unconstrained
attr(,"class")
[1] "summary.asreml"
> summary(sp2.asr)$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 48.7026395 7.15527571 6.806536 Positive
R!Column.cor 0.4375045 0.4375045 0.08060227 5.427943 Unconstrained
R!Row.cor 0.6554798 0.6554798 0.05637709 11.626704 Unconstrained
> anova(sp2.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 16165.6 331.93 < 2.2e-16 ***
Variety 55 5961.7 122.41 4.866e-07 ***
residual (MS) 48.7
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(sp2.asr)$fixed
effect
Variety_ARAPAHOE 0.00000000
Variety_BRULE 0.03029321
Variety_BUCKSKIN 8.89207227
Variety_CENTURA -0.68979639
Variety_CENTURK78 0.16461970
Variety_CHEYENNE 0.50267820
Variety_CODY -3.26960093
Variety_COLT -0.51826695
Variety_GAGE -0.95824999
Variety_HOMESTEAD -4.57873078
Variety_KS831374 0.27843476
Variety_LANCER -2.95379384
Variety_LANCOTA -4.67006598
Variety_NE83404 -1.32290865
Variety_NE83406 -1.66351994
Variety_NE83407 -2.64471830
Variety_NE83432 -4.42828427
Variety_NE83498 1.80418738
Variety_NE83T12 -2.11789109
Variety_NE84557 -2.34685080
Variety_NE85556 2.78001120
Variety_NE85623 -1.42164134
Variety_NE86482 -1.63334029
Variety_NE86501 -2.94339063
Variety_NE86503 -0.95747374
Variety_NE86507 0.46223383
Variety_NE86509 -3.27166458
Variety_NE86527 1.86588098
Variety_NE86582 -3.87940069
Variety_NE86606 0.22753741
Variety_NE86607 0.60702026
Variety_NE86T666 -10.27005825
Variety_NE87403 -7.43945904
Variety_NE87408 -3.10433009
Variety_NE87409 1.29746980
Variety_NE87446 -4.15943316
Variety_NE87451 -1.85324718
Variety_NE87457 -2.31156727
Variety_NE87463 -4.47086114
Variety_NE87499 -1.85909637
Variety_NE87512 -4.06473578
Variety_NE87513 -3.99604937
Variety_NE87522 -5.52109215
Variety_NE87612 -1.95543098
Variety_NE87613 -0.83160454
Variety_NE87615 -1.92104271
Variety_NE87619 2.98322047
Variety_NE87627 -7.33205188
Variety_NORKAN -5.78418023
Variety_REDLAND 1.75249392
Variety_ROUGHRIDER -0.97736288
Variety_SCOUT66 2.13126094
Variety_SIOUXLAND -2.54195346
Variety_TAM107 -1.59083563
Variety_TAM200 -6.54229161
Variety_VONA -1.52728371
(Intercept) 27.04285175
nlme
Working on, yet not figured out. Could be something like this. Still could not figure out how to do rcov=~ar1(Column):ar1(Row) with nlme
nin89$Int <- 1
sp1.lme <- lme(yield~Variety, random=~1|Int, data=na.omit(nin89))
I could not figured out how to fit Model 2 and 3 with nlme. I'm working on it and will update the answer when get it done. But I've included the output from ASReml-R for Model 2 and 3 for comparison purposes. Kevin has good experience of analyzing such models and Ben Bolker has wonderful authority on Mixed Models. I hope they can help us on Models 2 and 3. | lme4 or other open source R package code equivalent to asreml-R | Model 3
ASReml-R
sp2.asr <- asreml(yield~Variety, rcov=~ar1(Column):ar1(Row), data=nin89, na.method.X="include")
> summary(sp2.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~ar1(Column):ar1(Row), | lme4 or other open source R package code equivalent to asreml-R
Model 3
ASReml-R
sp2.asr <- asreml(yield~Variety, rcov=~ar1(Column):ar1(Row), data=nin89, na.method.X="include")
> summary(sp2.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~ar1(Column):ar1(Row),
data = nin89, na.method.X = "include")
$loglik
[1] -399.3238
$nedf
[1] 168
$sigma
[1] 6.978728
$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 48.7026395 7.15527571 6.806536 Positive
R!Column.cor 0.4375045 0.4375045 0.08060227 5.427943 Unconstrained
R!Row.cor 0.6554798 0.6554798 0.05637709 11.626704 Unconstrained
attr(,"class")
[1] "summary.asreml"
> summary(sp2.asr)$varcomp
gamma component std.error z.ratio constraint
R!variance 1.0000000 48.7026395 7.15527571 6.806536 Positive
R!Column.cor 0.4375045 0.4375045 0.08060227 5.427943 Unconstrained
R!Row.cor 0.6554798 0.6554798 0.05637709 11.626704 Unconstrained
> anova(sp2.asr)
Wald tests for fixed effects
Response: yield
Terms added sequentially; adjusted for those above
Df Sum of Sq Wald statistic Pr(Chisq)
(Intercept) 1 16165.6 331.93 < 2.2e-16 ***
Variety 55 5961.7 122.41 4.866e-07 ***
residual (MS) 48.7
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> coef(sp2.asr)$fixed
effect
Variety_ARAPAHOE 0.00000000
Variety_BRULE 0.03029321
Variety_BUCKSKIN 8.89207227
Variety_CENTURA -0.68979639
Variety_CENTURK78 0.16461970
Variety_CHEYENNE 0.50267820
Variety_CODY -3.26960093
Variety_COLT -0.51826695
Variety_GAGE -0.95824999
Variety_HOMESTEAD -4.57873078
Variety_KS831374 0.27843476
Variety_LANCER -2.95379384
Variety_LANCOTA -4.67006598
Variety_NE83404 -1.32290865
Variety_NE83406 -1.66351994
Variety_NE83407 -2.64471830
Variety_NE83432 -4.42828427
Variety_NE83498 1.80418738
Variety_NE83T12 -2.11789109
Variety_NE84557 -2.34685080
Variety_NE85556 2.78001120
Variety_NE85623 -1.42164134
Variety_NE86482 -1.63334029
Variety_NE86501 -2.94339063
Variety_NE86503 -0.95747374
Variety_NE86507 0.46223383
Variety_NE86509 -3.27166458
Variety_NE86527 1.86588098
Variety_NE86582 -3.87940069
Variety_NE86606 0.22753741
Variety_NE86607 0.60702026
Variety_NE86T666 -10.27005825
Variety_NE87403 -7.43945904
Variety_NE87408 -3.10433009
Variety_NE87409 1.29746980
Variety_NE87446 -4.15943316
Variety_NE87451 -1.85324718
Variety_NE87457 -2.31156727
Variety_NE87463 -4.47086114
Variety_NE87499 -1.85909637
Variety_NE87512 -4.06473578
Variety_NE87513 -3.99604937
Variety_NE87522 -5.52109215
Variety_NE87612 -1.95543098
Variety_NE87613 -0.83160454
Variety_NE87615 -1.92104271
Variety_NE87619 2.98322047
Variety_NE87627 -7.33205188
Variety_NORKAN -5.78418023
Variety_REDLAND 1.75249392
Variety_ROUGHRIDER -0.97736288
Variety_SCOUT66 2.13126094
Variety_SIOUXLAND -2.54195346
Variety_TAM107 -1.59083563
Variety_TAM200 -6.54229161
Variety_VONA -1.52728371
(Intercept) 27.04285175
nlme
Working on, yet not figured out. Could be something like this. Still could not figure out how to do rcov=~ar1(Column):ar1(Row) with nlme
nin89$Int <- 1
sp1.lme <- lme(yield~Variety, random=~1|Int, data=na.omit(nin89))
I could not figured out how to fit Model 2 and 3 with nlme. I'm working on it and will update the answer when get it done. But I've included the output from ASReml-R for Model 2 and 3 for comparison purposes. Kevin has good experience of analyzing such models and Ben Bolker has wonderful authority on Mixed Models. I hope they can help us on Models 2 and 3. | lme4 or other open source R package code equivalent to asreml-R
Model 3
ASReml-R
sp2.asr <- asreml(yield~Variety, rcov=~ar1(Column):ar1(Row), data=nin89, na.method.X="include")
> summary(sp2.asr)
$call
asreml(fixed = yield ~ Variety, rcov = ~ar1(Column):ar1(Row), |
20,567 | Testing simultaneous and lagged effects in longitudinal mixed models with time-varying covariates | I know this is probably too late for your benefit, but perhaps for others I will provide an answer.
You can include time-varying covariates in a longitudinal random-effects models (see Applied Longitudinal Analysis by Fitzmaurice, Laird and Ware, 2011 and http://www.ats.ucla.edu/stat/r/examples/alda/ specifically for R – use lme). Interpretation of trends depends on if you code time as categorical or continuous and your interaction terms. So for instance, if time is continuous and your covariates x1 and x2 are binary (0 and 1) and time-dependent, the fixed model is:
$$yij = \beta_0 + \beta_1x_{1ij} + \beta_2x_{2ij} + \beta_3time_{ij} + \beta_4 \times (x_{1ij} * time_{ij}) + \beta_5 \times (x_{2ij} * time_{ij})$$
i is for ith person,
j is for jth occasion
$\beta_4$ and $\beta_5$ capture the difference in trends between levels of $x_1$ and $x_2$ while accounting for change over time in $x_1$ and $x_2$. Unless you specify $x_1$ and $x_2$ as random effects, correlations between the repeated measures will not be taken into account (but this needs to be based on theory and can get messy if you have too many random effects - i.e., model won’t converge). There is also some discussion about centering time-dependent covariates to remove bias, although I have not done this (Raudenbush & Bryk, 2002). Interpretation, in general, is also more difficult if you have a continuous time-dependent covariate.
$\beta_1$ and $\beta_2$ capture the cross-sectional association between $x_1$ and $y$ and $x_2$ and $y$ at the intercept ($\beta_0$). The intercept is where time is zero (baseline or wherever you centered your time variable). This interpretation could also be changed if you have a higher order model (e.g., quadratic).
You would code this in R as something like:
model<- lme(y ~ time*x1 + time*x2, data, random= ~time|subject, method="")
Singer and Willet appear to use ML for “method” but I have always been taught to use REML in SAS for overall results but compare the fit of different models using ML. I would imagine you could use REML in R too.
You can also model the correlation structure for y by adding to the previous code:
correlation = [you’ll have to look up the options]
I am not sure I understand your reasoning for only being able to test lagged effects. I am not familiar with modeling lagged effects so I can’t really speak to that here. Perhaps I am wrong, but I would imagine that modeling lagged effects would undermine the usefulness of mixed models (e.g., being able to include subjects with missing time-dependent data) | Testing simultaneous and lagged effects in longitudinal mixed models with time-varying covariates | I know this is probably too late for your benefit, but perhaps for others I will provide an answer.
You can include time-varying covariates in a longitudinal random-effects models (see Applied Longitu | Testing simultaneous and lagged effects in longitudinal mixed models with time-varying covariates
I know this is probably too late for your benefit, but perhaps for others I will provide an answer.
You can include time-varying covariates in a longitudinal random-effects models (see Applied Longitudinal Analysis by Fitzmaurice, Laird and Ware, 2011 and http://www.ats.ucla.edu/stat/r/examples/alda/ specifically for R – use lme). Interpretation of trends depends on if you code time as categorical or continuous and your interaction terms. So for instance, if time is continuous and your covariates x1 and x2 are binary (0 and 1) and time-dependent, the fixed model is:
$$yij = \beta_0 + \beta_1x_{1ij} + \beta_2x_{2ij} + \beta_3time_{ij} + \beta_4 \times (x_{1ij} * time_{ij}) + \beta_5 \times (x_{2ij} * time_{ij})$$
i is for ith person,
j is for jth occasion
$\beta_4$ and $\beta_5$ capture the difference in trends between levels of $x_1$ and $x_2$ while accounting for change over time in $x_1$ and $x_2$. Unless you specify $x_1$ and $x_2$ as random effects, correlations between the repeated measures will not be taken into account (but this needs to be based on theory and can get messy if you have too many random effects - i.e., model won’t converge). There is also some discussion about centering time-dependent covariates to remove bias, although I have not done this (Raudenbush & Bryk, 2002). Interpretation, in general, is also more difficult if you have a continuous time-dependent covariate.
$\beta_1$ and $\beta_2$ capture the cross-sectional association between $x_1$ and $y$ and $x_2$ and $y$ at the intercept ($\beta_0$). The intercept is where time is zero (baseline or wherever you centered your time variable). This interpretation could also be changed if you have a higher order model (e.g., quadratic).
You would code this in R as something like:
model<- lme(y ~ time*x1 + time*x2, data, random= ~time|subject, method="")
Singer and Willet appear to use ML for “method” but I have always been taught to use REML in SAS for overall results but compare the fit of different models using ML. I would imagine you could use REML in R too.
You can also model the correlation structure for y by adding to the previous code:
correlation = [you’ll have to look up the options]
I am not sure I understand your reasoning for only being able to test lagged effects. I am not familiar with modeling lagged effects so I can’t really speak to that here. Perhaps I am wrong, but I would imagine that modeling lagged effects would undermine the usefulness of mixed models (e.g., being able to include subjects with missing time-dependent data) | Testing simultaneous and lagged effects in longitudinal mixed models with time-varying covariates
I know this is probably too late for your benefit, but perhaps for others I will provide an answer.
You can include time-varying covariates in a longitudinal random-effects models (see Applied Longitu |
20,568 | Logistic regression with directional data as IV | I would suggest applying a transform which deals with periodicity. i.e. $\lim_{x \to 360} f(x) = f(0)$. An easy option is to take the sin and cos, and put them both as covariates in the model. | Logistic regression with directional data as IV | I would suggest applying a transform which deals with periodicity. i.e. $\lim_{x \to 360} f(x) = f(0)$. An easy option is to take the sin and cos, and put them both as covariates in the model. | Logistic regression with directional data as IV
I would suggest applying a transform which deals with periodicity. i.e. $\lim_{x \to 360} f(x) = f(0)$. An easy option is to take the sin and cos, and put them both as covariates in the model. | Logistic regression with directional data as IV
I would suggest applying a transform which deals with periodicity. i.e. $\lim_{x \to 360} f(x) = f(0)$. An easy option is to take the sin and cos, and put them both as covariates in the model. |
20,569 | What would a confidence interval around a predicted value from a mixed effects model mean? | It has the same meaning as any other confidence interval: under the assumption that the model is correct, if the experiment and procedure is repeated over and over, 95% of the time the true value of the quantity of interest will lie within the interval. In this case, the quantity of interest is the expected value of the response variable.
It is probably easiest to explain this in the context of a linear model (mixed models are just an extension of this, so the same ideas apply):
The usual assumption is that:
$y_i = X_{i1} \beta_1 + X_{i2} \beta_2 + \ldots X_{ip} \beta_p + \epsilon $
where $y_i$ is the response, $X_{ij}$'s are the covariates, $\beta_j$'s are the parameters, and $\epsilon$ is the error term which has mean zero. The quantity of interest is then:
$E[y_i] = X_{i1} \beta_1 + X_{i2} \beta_2 + \ldots X_{ip} \beta_p $
which is a linear function of the (unknown) parameters, since the covariates are known (and fixed). Since we know the sampling distribution of the parameter vector, we can easily calculate the sampling distribution (and hence the confidence interval) of this quantity.
So why would you want to know it? I guess if you're doing out-of-sample prediction, it could tell you how good your forecast is expected to be (though you'd need to take into account model uncertainty). | What would a confidence interval around a predicted value from a mixed effects model mean? | It has the same meaning as any other confidence interval: under the assumption that the model is correct, if the experiment and procedure is repeated over and over, 95% of the time the true value of t | What would a confidence interval around a predicted value from a mixed effects model mean?
It has the same meaning as any other confidence interval: under the assumption that the model is correct, if the experiment and procedure is repeated over and over, 95% of the time the true value of the quantity of interest will lie within the interval. In this case, the quantity of interest is the expected value of the response variable.
It is probably easiest to explain this in the context of a linear model (mixed models are just an extension of this, so the same ideas apply):
The usual assumption is that:
$y_i = X_{i1} \beta_1 + X_{i2} \beta_2 + \ldots X_{ip} \beta_p + \epsilon $
where $y_i$ is the response, $X_{ij}$'s are the covariates, $\beta_j$'s are the parameters, and $\epsilon$ is the error term which has mean zero. The quantity of interest is then:
$E[y_i] = X_{i1} \beta_1 + X_{i2} \beta_2 + \ldots X_{ip} \beta_p $
which is a linear function of the (unknown) parameters, since the covariates are known (and fixed). Since we know the sampling distribution of the parameter vector, we can easily calculate the sampling distribution (and hence the confidence interval) of this quantity.
So why would you want to know it? I guess if you're doing out-of-sample prediction, it could tell you how good your forecast is expected to be (though you'd need to take into account model uncertainty). | What would a confidence interval around a predicted value from a mixed effects model mean?
It has the same meaning as any other confidence interval: under the assumption that the model is correct, if the experiment and procedure is repeated over and over, 95% of the time the true value of t |
20,570 | What would a confidence interval around a predicted value from a mixed effects model mean? | Maybe this makes sense in the Bayesian framework. Consider for instance the one-way random effect ANOVA model : $$(y_{ij} | \mu_i) \sim {\cal N}(\mu_i, \sigma^2_w), \quad \mu_i \sim {\cal N}(\mu, \sigma_b^2),$$
and a prior distribution on the overall mean $\mu$ and the variance components $\sigma^2_w$ and $\sigma^2_b$. Then each $\mu_i$ has a posterior distribution, and a $95\%$ dispersion interval of this distribution could play the role of a $95\%$ "confidence" interval. | What would a confidence interval around a predicted value from a mixed effects model mean? | Maybe this makes sense in the Bayesian framework. Consider for instance the one-way random effect ANOVA model : $$(y_{ij} | \mu_i) \sim {\cal N}(\mu_i, \sigma^2_w), \quad \mu_i \sim {\cal N}(\mu, \sig | What would a confidence interval around a predicted value from a mixed effects model mean?
Maybe this makes sense in the Bayesian framework. Consider for instance the one-way random effect ANOVA model : $$(y_{ij} | \mu_i) \sim {\cal N}(\mu_i, \sigma^2_w), \quad \mu_i \sim {\cal N}(\mu, \sigma_b^2),$$
and a prior distribution on the overall mean $\mu$ and the variance components $\sigma^2_w$ and $\sigma^2_b$. Then each $\mu_i$ has a posterior distribution, and a $95\%$ dispersion interval of this distribution could play the role of a $95\%$ "confidence" interval. | What would a confidence interval around a predicted value from a mixed effects model mean?
Maybe this makes sense in the Bayesian framework. Consider for instance the one-way random effect ANOVA model : $$(y_{ij} | \mu_i) \sim {\cal N}(\mu_i, \sigma^2_w), \quad \mu_i \sim {\cal N}(\mu, \sig |
20,571 | Fitting a model to a variable with many zeros and few but large values in right tail [duplicate] | If the number of counts where Count $\neq$0 is small then you can just handle this as a classification problem. Otherwise you can firstly separate the data based on the target variable into two groups:
1- Count ==0
2-Count $\neq$0
You can use a classification method (for example a logistic regression) to model each of the above outcomes. Then in the group where Count $\neq$0 you can fit a regression model.
why this would help:
Balancing the data: If you fit a regression model with least square it would be heavily biased towards 0, as most of your data is located at count==0. When you separate your data into two groups then all the data with Count $\neq$0 are put into one bin and they will have more weight against Count $\neq$0.
Based on distribution count==0 seems to be a case completely distinct from other counts. Hence it can help if you treat is differently by first separating the data where count==0. | Fitting a model to a variable with many zeros and few but large values in right tail [duplicate] | If the number of counts where Count $\neq$0 is small then you can just handle this as a classification problem. Otherwise you can firstly separate the data based on the target variable into two groups | Fitting a model to a variable with many zeros and few but large values in right tail [duplicate]
If the number of counts where Count $\neq$0 is small then you can just handle this as a classification problem. Otherwise you can firstly separate the data based on the target variable into two groups:
1- Count ==0
2-Count $\neq$0
You can use a classification method (for example a logistic regression) to model each of the above outcomes. Then in the group where Count $\neq$0 you can fit a regression model.
why this would help:
Balancing the data: If you fit a regression model with least square it would be heavily biased towards 0, as most of your data is located at count==0. When you separate your data into two groups then all the data with Count $\neq$0 are put into one bin and they will have more weight against Count $\neq$0.
Based on distribution count==0 seems to be a case completely distinct from other counts. Hence it can help if you treat is differently by first separating the data where count==0. | Fitting a model to a variable with many zeros and few but large values in right tail [duplicate]
If the number of counts where Count $\neq$0 is small then you can just handle this as a classification problem. Otherwise you can firstly separate the data based on the target variable into two groups |
20,572 | What is the good use for t-SNE, apart from data visualization? | The answer to this question suggests that t-SNE should be used only for visualization and that we should not use it for clustering. Then what is the good use for t-SNE?
I don't agree with this conclusion. There is no reason to assume that t-SNE is any worse universally than any other clustering algorithm. Every clustering algorithm makes assumptions about the structure of the data, and they can be expected to perform differently depending on the underlying distribution and end use of the reduced dimensionality.
t-SNE like many unsupervised learning algorithms often provide a means to an end, e.g. obtaining early insight on whether or not the data is separable, testing that it has some identifiable structure, and inspecting the nature of this structure. One does not need visualization of the t-SNE output to start answering some of these questions. Other applications of lower dimensional embeddings include building features for classification or getting rid of multi-collinearity to improve the performance of prediction methods. | What is the good use for t-SNE, apart from data visualization? | The answer to this question suggests that t-SNE should be used only for visualization and that we should not use it for clustering. Then what is the good use for t-SNE?
I don't agree with this conclu | What is the good use for t-SNE, apart from data visualization?
The answer to this question suggests that t-SNE should be used only for visualization and that we should not use it for clustering. Then what is the good use for t-SNE?
I don't agree with this conclusion. There is no reason to assume that t-SNE is any worse universally than any other clustering algorithm. Every clustering algorithm makes assumptions about the structure of the data, and they can be expected to perform differently depending on the underlying distribution and end use of the reduced dimensionality.
t-SNE like many unsupervised learning algorithms often provide a means to an end, e.g. obtaining early insight on whether or not the data is separable, testing that it has some identifiable structure, and inspecting the nature of this structure. One does not need visualization of the t-SNE output to start answering some of these questions. Other applications of lower dimensional embeddings include building features for classification or getting rid of multi-collinearity to improve the performance of prediction methods. | What is the good use for t-SNE, apart from data visualization?
The answer to this question suggests that t-SNE should be used only for visualization and that we should not use it for clustering. Then what is the good use for t-SNE?
I don't agree with this conclu |
20,573 | Deep Learning: Why does increase batch_size cause overfitting and how does one reduce it? | Chapter 6 of Goodfellow's book:
Small batches can offer a regularizing effect (Wilson and Martinez, 2003), perhaps due to the noise they add to the learning process. Generalization error is often best for a batch size of 1. Training with such a small batch size might require a small learning rate to maintain stability because of the high variance in the estimate of the gradient. The total runtime can be very high as a result of the need to make more steps, both because of the reduced learning rate and because it takes more steps to observe the entire training set. | Deep Learning: Why does increase batch_size cause overfitting and how does one reduce it? | Chapter 6 of Goodfellow's book:
Small batches can offer a regularizing effect (Wilson and Martinez, 2003), perhaps due to the noise they add to the learning process. Generalization error is often best | Deep Learning: Why does increase batch_size cause overfitting and how does one reduce it?
Chapter 6 of Goodfellow's book:
Small batches can offer a regularizing effect (Wilson and Martinez, 2003), perhaps due to the noise they add to the learning process. Generalization error is often best for a batch size of 1. Training with such a small batch size might require a small learning rate to maintain stability because of the high variance in the estimate of the gradient. The total runtime can be very high as a result of the need to make more steps, both because of the reduced learning rate and because it takes more steps to observe the entire training set. | Deep Learning: Why does increase batch_size cause overfitting and how does one reduce it?
Chapter 6 of Goodfellow's book:
Small batches can offer a regularizing effect (Wilson and Martinez, 2003), perhaps due to the noise they add to the learning process. Generalization error is often best |
20,574 | What is the difference between RRMSE and RMSRE? | RMSE is stated in the same units of the original measurement, so if you are comparing distance measuring techniques, you might have an RMSE of 0.29 meters. If you're measuring mountain height or river distances then this is a tiny amount of inaccuracy, perhaps 0.005%. If you're measuring people's height, then you're about 17% off. That percentage variation in accuracy is RRMSE.
RRMSE can also be used to hide inaccuracy. If you're comparing different techniques of measuring large magnitude items, say distances of 10,000 m, one may be established and very accurate, measuring within .05 m accuracy, while the proposed new technique is much less precise, measuring within 200 m accuracy. Those are scary big differences, but when presented as percentages, 2% error sounds pretty good, and the <0.1% error is only slightly better, but in reality it's 4,000x more accurate. | What is the difference between RRMSE and RMSRE? | RMSE is stated in the same units of the original measurement, so if you are comparing distance measuring techniques, you might have an RMSE of 0.29 meters. If you're measuring mountain height or river | What is the difference between RRMSE and RMSRE?
RMSE is stated in the same units of the original measurement, so if you are comparing distance measuring techniques, you might have an RMSE of 0.29 meters. If you're measuring mountain height or river distances then this is a tiny amount of inaccuracy, perhaps 0.005%. If you're measuring people's height, then you're about 17% off. That percentage variation in accuracy is RRMSE.
RRMSE can also be used to hide inaccuracy. If you're comparing different techniques of measuring large magnitude items, say distances of 10,000 m, one may be established and very accurate, measuring within .05 m accuracy, while the proposed new technique is much less precise, measuring within 200 m accuracy. Those are scary big differences, but when presented as percentages, 2% error sounds pretty good, and the <0.1% error is only slightly better, but in reality it's 4,000x more accurate. | What is the difference between RRMSE and RMSRE?
RMSE is stated in the same units of the original measurement, so if you are comparing distance measuring techniques, you might have an RMSE of 0.29 meters. If you're measuring mountain height or river |
20,575 | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | Use a gradient descent optimizer. This is a very good overview.
Regarding the code, have a look at this tutorial. This and this are some examples.
Personally, I suggest to use either ADAM or RMSprop. There are still some hyperparameters to set, but there are some "standard" ones that work 99% of the time. For ADAM you can look at its paper and for RMSprop at this slides.
EDIT
Ok, you already use a gradient optimizer. Then you can perform some hyperparameters optimization to select the best learning rate. Recently, an automated approach has been proposed. Also, there is a lot of promising work by Frank Hutter regarding automated hyperparameters tuning.
More in general, have a look at the AutoML Challenge, where you can also find source code by the teams. In this challenge, the goal is to automate machine learning, including hyperparameters tuning.
Finally, this paper by LeCun and this very recent tutorial by DeepMin (check Chapter 8) give some insights that might be useful for your question.
Anyway, keep in mind that (especially for easy problems), it's normal that the learning rate doesn't affect much the learning when using a gradient descent optimizer. Usually, these optimizers are very reliable and work with different parameters. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | Use a gradient descent optimizer. This is a very good overview.
Regarding the code, have a look at this tutorial. This and this are some examples.
Personally, I suggest to use either ADAM or RMSprop. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
Use a gradient descent optimizer. This is a very good overview.
Regarding the code, have a look at this tutorial. This and this are some examples.
Personally, I suggest to use either ADAM or RMSprop. There are still some hyperparameters to set, but there are some "standard" ones that work 99% of the time. For ADAM you can look at its paper and for RMSprop at this slides.
EDIT
Ok, you already use a gradient optimizer. Then you can perform some hyperparameters optimization to select the best learning rate. Recently, an automated approach has been proposed. Also, there is a lot of promising work by Frank Hutter regarding automated hyperparameters tuning.
More in general, have a look at the AutoML Challenge, where you can also find source code by the teams. In this challenge, the goal is to automate machine learning, including hyperparameters tuning.
Finally, this paper by LeCun and this very recent tutorial by DeepMin (check Chapter 8) give some insights that might be useful for your question.
Anyway, keep in mind that (especially for easy problems), it's normal that the learning rate doesn't affect much the learning when using a gradient descent optimizer. Usually, these optimizers are very reliable and work with different parameters. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
Use a gradient descent optimizer. This is a very good overview.
Regarding the code, have a look at this tutorial. This and this are some examples.
Personally, I suggest to use either ADAM or RMSprop. |
20,576 | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | You can automate the tuning of hyper-parameters in a lot of machine learning algorithms themselves, or just the hyperparameters for Gradient Descent optimizer i.e learning rate.
One library that has been popular for doing this is spearmint.
https://github.com/JasperSnoek/spearmint | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | You can automate the tuning of hyper-parameters in a lot of machine learning algorithms themselves, or just the hyperparameters for Gradient Descent optimizer i.e learning rate.
One library that has | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
You can automate the tuning of hyper-parameters in a lot of machine learning algorithms themselves, or just the hyperparameters for Gradient Descent optimizer i.e learning rate.
One library that has been popular for doing this is spearmint.
https://github.com/JasperSnoek/spearmint | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
You can automate the tuning of hyper-parameters in a lot of machine learning algorithms themselves, or just the hyperparameters for Gradient Descent optimizer i.e learning rate.
One library that has |
20,577 | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | A very recent automatic learning-rate tuner is given in Online Learning Rate Adaptation with Hypergradient Descent
This method is very straightforward to implement, the core result for SGD is given as:
$\alpha_{t} = \alpha_{t-1} + \beta \nabla f(\theta_{t-1})^T\nabla f(\theta_{t-2}) $
where $\beta$ is a (hyper) hyperparameter. The method also applies to other gradient-based updates ($\textit{e.g.}$ momentum-based methods). No validation set is needed: it only requires storing the previous gradient, $\nabla f(\theta_{t-2})$. The idea is to use the partial derivative of the objective function w.r.t. the learning rate ($\alpha$), to derive an update rule for alpha.
Anecdotally, I implemented this on top of my existing problem, and observed much better results. I did not tune $\beta$ or $\alpha_0$, but picked from the suggested ranges from the paper. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | A very recent automatic learning-rate tuner is given in Online Learning Rate Adaptation with Hypergradient Descent
This method is very straightforward to implement, the core result for SGD is given as | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
A very recent automatic learning-rate tuner is given in Online Learning Rate Adaptation with Hypergradient Descent
This method is very straightforward to implement, the core result for SGD is given as:
$\alpha_{t} = \alpha_{t-1} + \beta \nabla f(\theta_{t-1})^T\nabla f(\theta_{t-2}) $
where $\beta$ is a (hyper) hyperparameter. The method also applies to other gradient-based updates ($\textit{e.g.}$ momentum-based methods). No validation set is needed: it only requires storing the previous gradient, $\nabla f(\theta_{t-2})$. The idea is to use the partial derivative of the objective function w.r.t. the learning rate ($\alpha$), to derive an update rule for alpha.
Anecdotally, I implemented this on top of my existing problem, and observed much better results. I did not tune $\beta$ or $\alpha_0$, but picked from the suggested ranges from the paper. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
A very recent automatic learning-rate tuner is given in Online Learning Rate Adaptation with Hypergradient Descent
This method is very straightforward to implement, the core result for SGD is given as |
20,578 | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | To tune hyperparameters (whether it is learning rate, decay rate, regularization, or anything else), you need to establish a heldout dataset; this dataset is disjoint from your training dataset. After tuning several models with different configurations (where a configuration = a particular choice of each hyperparameter), you choose the configuration by selecting the one that maximizes heldout accuracy. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer? | To tune hyperparameters (whether it is learning rate, decay rate, regularization, or anything else), you need to establish a heldout dataset; this dataset is disjoint from your training dataset. After | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
To tune hyperparameters (whether it is learning rate, decay rate, regularization, or anything else), you need to establish a heldout dataset; this dataset is disjoint from your training dataset. After tuning several models with different configurations (where a configuration = a particular choice of each hyperparameter), you choose the configuration by selecting the one that maximizes heldout accuracy. | How to (systematically) tune learning rate having Gradient Descent as the Optimizer?
To tune hyperparameters (whether it is learning rate, decay rate, regularization, or anything else), you need to establish a heldout dataset; this dataset is disjoint from your training dataset. After |
20,579 | How does Word2Vec's skip-gram model generate the output vectors? | I had the same problem understanding it. It seems that the output score vector will be the same for all C terms. But the difference in error with each one-hot represented vectors will be different. Thus the error vectors are used in back-propagation to update the weights.
Please correct me, if I'm wrong.
source : https://iksinc.wordpress.com/tag/skip-gram-model/ | How does Word2Vec's skip-gram model generate the output vectors? | I had the same problem understanding it. It seems that the output score vector will be the same for all C terms. But the difference in error with each one-hot represented vectors will be different. Th | How does Word2Vec's skip-gram model generate the output vectors?
I had the same problem understanding it. It seems that the output score vector will be the same for all C terms. But the difference in error with each one-hot represented vectors will be different. Thus the error vectors are used in back-propagation to update the weights.
Please correct me, if I'm wrong.
source : https://iksinc.wordpress.com/tag/skip-gram-model/ | How does Word2Vec's skip-gram model generate the output vectors?
I had the same problem understanding it. It seems that the output score vector will be the same for all C terms. But the difference in error with each one-hot represented vectors will be different. Th |
20,580 | How does Word2Vec's skip-gram model generate the output vectors? | In both of the models output score depends on the score function that you use. There can be two score functions softmax or negative sampling. So you use a softmax score function. You will get a score function size of N*D. Here D is the dimension of a word vector. N is the number of examples. Each word is like a class in neural net architecture. | How does Word2Vec's skip-gram model generate the output vectors? | In both of the models output score depends on the score function that you use. There can be two score functions softmax or negative sampling. So you use a softmax score function. You will get a score | How does Word2Vec's skip-gram model generate the output vectors?
In both of the models output score depends on the score function that you use. There can be two score functions softmax or negative sampling. So you use a softmax score function. You will get a score function size of N*D. Here D is the dimension of a word vector. N is the number of examples. Each word is like a class in neural net architecture. | How does Word2Vec's skip-gram model generate the output vectors?
In both of the models output score depends on the score function that you use. There can be two score functions softmax or negative sampling. So you use a softmax score function. You will get a score |
20,581 | How does Word2Vec's skip-gram model generate the output vectors? | In the skip-gram model a one-hot encoded word is fed to two-layer shallow neural net. Since the input is one-hot encoded, the hidden layer contains only one row of the input hidden weight matrix (let's say $k_{th}$ row because the $k_{th}$ row of input vector is one).
The scores for each word is computed by the following equation.
$u = \mathcal{W'}^Th$
where h is a vector in the hidden layer and $\mathcal{W'}$ is the hidden output weight matrix. After computing $u$ $\mathcal{C}$ multinomial distributions are computed where $\mathcal{C}$ is windows size. The distributions are computed by the following equation.
$p(w_{c,j} = w_{O,c}|w_I)=\frac{\exp{u_{c,j}}}{\sum_{j'=1}^V\exp{u_{j'}}}$
As you can see all of the $\mathcal{C}$ distributions are different. (For more information: https://arxiv.org/pdf/1411.2738.pdf). In fact, this would be more clear if they would use something like the following figure.
In summary, there is only one source vector $u$. However, $\mathcal{C}$ different distributions are computed using softmax function.
$\textbf{References:}$
Xin Rong, Word2Vec Parameter Learning Explained | How does Word2Vec's skip-gram model generate the output vectors? | In the skip-gram model a one-hot encoded word is fed to two-layer shallow neural net. Since the input is one-hot encoded, the hidden layer contains only one row of the input hidden weight matrix (let' | How does Word2Vec's skip-gram model generate the output vectors?
In the skip-gram model a one-hot encoded word is fed to two-layer shallow neural net. Since the input is one-hot encoded, the hidden layer contains only one row of the input hidden weight matrix (let's say $k_{th}$ row because the $k_{th}$ row of input vector is one).
The scores for each word is computed by the following equation.
$u = \mathcal{W'}^Th$
where h is a vector in the hidden layer and $\mathcal{W'}$ is the hidden output weight matrix. After computing $u$ $\mathcal{C}$ multinomial distributions are computed where $\mathcal{C}$ is windows size. The distributions are computed by the following equation.
$p(w_{c,j} = w_{O,c}|w_I)=\frac{\exp{u_{c,j}}}{\sum_{j'=1}^V\exp{u_{j'}}}$
As you can see all of the $\mathcal{C}$ distributions are different. (For more information: https://arxiv.org/pdf/1411.2738.pdf). In fact, this would be more clear if they would use something like the following figure.
In summary, there is only one source vector $u$. However, $\mathcal{C}$ different distributions are computed using softmax function.
$\textbf{References:}$
Xin Rong, Word2Vec Parameter Learning Explained | How does Word2Vec's skip-gram model generate the output vectors?
In the skip-gram model a one-hot encoded word is fed to two-layer shallow neural net. Since the input is one-hot encoded, the hidden layer contains only one row of the input hidden weight matrix (let' |
20,582 | How to reduce number of false positives? | I am not an expert when it comes to random forests, I read them quite recently. But from how it looks to me you are overfitting the random forest. What I would do is to use the technique where you use the Out-Of-Bag observations to make predictions. You can find the procedure on these slides: https://lagunita.stanford.edu/c4x/HumanitiesScience/StatLearning/asset/trees.pdf
One other thing I would suggest is also mentioned in these slides called the gradient boosting machine(GBM) also mentioned in this section. I feel that GBM is more intuitive than random forest.
Edit1:
I checked it again and it seems bootstrapping is the very first step of GBM. Also, I do not have problems with bootstrapping per se, it is nice and good. The only problem with it is that it can be used very badly. | How to reduce number of false positives? | I am not an expert when it comes to random forests, I read them quite recently. But from how it looks to me you are overfitting the random forest. What I would do is to use the technique where you use | How to reduce number of false positives?
I am not an expert when it comes to random forests, I read them quite recently. But from how it looks to me you are overfitting the random forest. What I would do is to use the technique where you use the Out-Of-Bag observations to make predictions. You can find the procedure on these slides: https://lagunita.stanford.edu/c4x/HumanitiesScience/StatLearning/asset/trees.pdf
One other thing I would suggest is also mentioned in these slides called the gradient boosting machine(GBM) also mentioned in this section. I feel that GBM is more intuitive than random forest.
Edit1:
I checked it again and it seems bootstrapping is the very first step of GBM. Also, I do not have problems with bootstrapping per se, it is nice and good. The only problem with it is that it can be used very badly. | How to reduce number of false positives?
I am not an expert when it comes to random forests, I read them quite recently. But from how it looks to me you are overfitting the random forest. What I would do is to use the technique where you use |
20,583 | What does my ACF graph tell me about my data? | If your primary concern is to use the ACF and PACF plots to guide a good ARMA fit then http://people.duke.edu/~rnau/411arim3.htm is a good resource. In general, AR orders will tend to present themselves by a sharp cutoff in the PACF plot and a slow trending or sinusoidal degradation in the ACF plot. The opposite is usually true for MA orders...the link provided above discusses this in more detail.
The ACF plot you provided may suggest an MA(2). I would guess that you have some significant AR orders just looking at the sinusoidal decay in auto-correlation. But all this is extremely speculative since the coefficients become insignificant very quickly as lag increases. Seeing the PACF would be very helpful.
Another important thing you want to watch for is significance in the 4th lag on the PACF. Since you have quarterly data, significance in the 4th lag is a sign of seasonality. For example if your investment is a gift store, returns may higher during the holidays (Q4) and lower during the beginning of the year (Q1), causing correlation between identical quarters.
The significant coefficients for smaller lags in the ACF plot should stay the same as your data size increases assuming nothing changes with the investment. Higher lags are estimated with less data points then are lower lags (i.e every lag looses a data point), so you can use the sample size in the estimation of each lag to guide your judgment as to which will stay the same and which are less reliable.
Using the ACF plot to make deeper insights about your data (beyond just an ARMA fit) would require a deeper understanding of what type of investment this is. I have commented on this already.
For deeper insight...
With financial assets, practitioners often log then difference price to obtain stationary. The log
difference is analogous to a continually compacted returns (i.e. growth) so it
has a very nice interpretation and there is a lot of financial literature available
on studying/modeling series of asset returns. I assume your stationary data was obtained in this manner.
In the most general sense, I would say the auto-correlation means that returns on the investment are somewhat predictable. You could use an ARMA fit to forecast future returns or comment on the investment's performance when compared to a benchmark such as the S&P 500.
Looking at the variance in residual terms of the fit also gives you a measure of risk in the investment. This is extremely important. In finance you want an optimal risk to return trade off
and you can decide if this investment is worth the money by comparing to other market benchmarks. For example, if these returns have a low mean
and are hard to predict (i.e risky) when compared to other investment options, you would know its a bad investment. Some good places to start are
http://en.wikipedia.org/wiki/Efficient_frontier and http://en.wikipedia.org/wiki/Modern_portfolio_theory.
Hopefully that helps! | What does my ACF graph tell me about my data? | If your primary concern is to use the ACF and PACF plots to guide a good ARMA fit then http://people.duke.edu/~rnau/411arim3.htm is a good resource. In general, AR orders will tend to present themsel | What does my ACF graph tell me about my data?
If your primary concern is to use the ACF and PACF plots to guide a good ARMA fit then http://people.duke.edu/~rnau/411arim3.htm is a good resource. In general, AR orders will tend to present themselves by a sharp cutoff in the PACF plot and a slow trending or sinusoidal degradation in the ACF plot. The opposite is usually true for MA orders...the link provided above discusses this in more detail.
The ACF plot you provided may suggest an MA(2). I would guess that you have some significant AR orders just looking at the sinusoidal decay in auto-correlation. But all this is extremely speculative since the coefficients become insignificant very quickly as lag increases. Seeing the PACF would be very helpful.
Another important thing you want to watch for is significance in the 4th lag on the PACF. Since you have quarterly data, significance in the 4th lag is a sign of seasonality. For example if your investment is a gift store, returns may higher during the holidays (Q4) and lower during the beginning of the year (Q1), causing correlation between identical quarters.
The significant coefficients for smaller lags in the ACF plot should stay the same as your data size increases assuming nothing changes with the investment. Higher lags are estimated with less data points then are lower lags (i.e every lag looses a data point), so you can use the sample size in the estimation of each lag to guide your judgment as to which will stay the same and which are less reliable.
Using the ACF plot to make deeper insights about your data (beyond just an ARMA fit) would require a deeper understanding of what type of investment this is. I have commented on this already.
For deeper insight...
With financial assets, practitioners often log then difference price to obtain stationary. The log
difference is analogous to a continually compacted returns (i.e. growth) so it
has a very nice interpretation and there is a lot of financial literature available
on studying/modeling series of asset returns. I assume your stationary data was obtained in this manner.
In the most general sense, I would say the auto-correlation means that returns on the investment are somewhat predictable. You could use an ARMA fit to forecast future returns or comment on the investment's performance when compared to a benchmark such as the S&P 500.
Looking at the variance in residual terms of the fit also gives you a measure of risk in the investment. This is extremely important. In finance you want an optimal risk to return trade off
and you can decide if this investment is worth the money by comparing to other market benchmarks. For example, if these returns have a low mean
and are hard to predict (i.e risky) when compared to other investment options, you would know its a bad investment. Some good places to start are
http://en.wikipedia.org/wiki/Efficient_frontier and http://en.wikipedia.org/wiki/Modern_portfolio_theory.
Hopefully that helps! | What does my ACF graph tell me about my data?
If your primary concern is to use the ACF and PACF plots to guide a good ARMA fit then http://people.duke.edu/~rnau/411arim3.htm is a good resource. In general, AR orders will tend to present themsel |
20,584 | regression for angular/circular data | I suggest you to take a look at the book "Topics in circular statistics" of Jammalamadaka if you are interested in circular variable.
Suppose that your data come from a circular distribution $F()$, and you want to model the (circular) mean of the circular variable:
what is generally used is:
$$
E(\theta) = 2\arctan(\boldsymbol{\beta}\mathbf{z}_i)
$$
$\theta$ is the circular variable, $\boldsymbol{\beta}$ is the vector of regression coefficients and $\mathbf{z}_i$ are the linear covariates.
If you want a parallelism with the usual linear regression you can assume that $\theta_i \sim WN(\mu_i,\sigma^2)$, where $WN()$ indicates the wrapped normal distribution that is in some sense the Normal distribution on a circle. Then
$$
\mu_i = 2\arctan(\boldsymbol{\beta}\mathbf{z}_i)
$$
or equivalently
$$
\theta_i = 2\arctan(\boldsymbol{\beta}\mathbf{z}_i) + \epsilon_i
$$
where $\epsilon_i \sim WN(0, \sigma^2)$
This type of regression is implemented in the package $circular$ that the user Scortchi suggests | regression for angular/circular data | I suggest you to take a look at the book "Topics in circular statistics" of Jammalamadaka if you are interested in circular variable.
Suppose that your data come from a circular distribution $F()$, an | regression for angular/circular data
I suggest you to take a look at the book "Topics in circular statistics" of Jammalamadaka if you are interested in circular variable.
Suppose that your data come from a circular distribution $F()$, and you want to model the (circular) mean of the circular variable:
what is generally used is:
$$
E(\theta) = 2\arctan(\boldsymbol{\beta}\mathbf{z}_i)
$$
$\theta$ is the circular variable, $\boldsymbol{\beta}$ is the vector of regression coefficients and $\mathbf{z}_i$ are the linear covariates.
If you want a parallelism with the usual linear regression you can assume that $\theta_i \sim WN(\mu_i,\sigma^2)$, where $WN()$ indicates the wrapped normal distribution that is in some sense the Normal distribution on a circle. Then
$$
\mu_i = 2\arctan(\boldsymbol{\beta}\mathbf{z}_i)
$$
or equivalently
$$
\theta_i = 2\arctan(\boldsymbol{\beta}\mathbf{z}_i) + \epsilon_i
$$
where $\epsilon_i \sim WN(0, \sigma^2)$
This type of regression is implemented in the package $circular$ that the user Scortchi suggests | regression for angular/circular data
I suggest you to take a look at the book "Topics in circular statistics" of Jammalamadaka if you are interested in circular variable.
Suppose that your data come from a circular distribution $F()$, an |
20,585 | Additive vs Multiplicative decomposition | In addition to what @whuber has recommended, I would refer you to https://www.otexts.org/fpp/6/1 which explains why you would choose additive vs. multiplicative decomposition.
In specifically looking at your data, because the seasonality varies, i.e., seasonality at the beginning is large and as it seasonality is almost not present in the later years, this would suggest a multiplicative decomposition. According to the text referenced above, an alternative would be to do an appropriate transformation and apply additive decomposition.
There is a level shift in the data some time around mod 1972 which also needs to be treated when decomposing.
There is another decomposition based method called unobserved components model which takes most of the guess work out of decomposition and provides you with some good statistics to make sound decision such as stochastic vs. deterministic trends/seasonality etc.
Hope this helps. | Additive vs Multiplicative decomposition | In addition to what @whuber has recommended, I would refer you to https://www.otexts.org/fpp/6/1 which explains why you would choose additive vs. multiplicative decomposition.
In specifically looking | Additive vs Multiplicative decomposition
In addition to what @whuber has recommended, I would refer you to https://www.otexts.org/fpp/6/1 which explains why you would choose additive vs. multiplicative decomposition.
In specifically looking at your data, because the seasonality varies, i.e., seasonality at the beginning is large and as it seasonality is almost not present in the later years, this would suggest a multiplicative decomposition. According to the text referenced above, an alternative would be to do an appropriate transformation and apply additive decomposition.
There is a level shift in the data some time around mod 1972 which also needs to be treated when decomposing.
There is another decomposition based method called unobserved components model which takes most of the guess work out of decomposition and provides you with some good statistics to make sound decision such as stochastic vs. deterministic trends/seasonality etc.
Hope this helps. | Additive vs Multiplicative decomposition
In addition to what @whuber has recommended, I would refer you to https://www.otexts.org/fpp/6/1 which explains why you would choose additive vs. multiplicative decomposition.
In specifically looking |
20,586 | Why does independence test use the chi-squared distribution? | It's about the Poisson distribution. If $X$ is Poisson with mean $\lambda$, then the variance of $X$ is $\lambda$ also. This means that $$\frac{(X-\lambda)^2}{\lambda}$$ is a $z^2$ like entity. By the CLT, the Poisson tends to normality as the mean gets large, which is where the chi-squared comes in. Yes, it is an asymptotic test.
The degrees of freedom come from Cochran's theorem. Basically, Cochran explains how the Chi-squared is transformed (or remains unchanged) subject to a linear transformation in the $z^2$ scores.
$$\sum_i z_i^2=Z' I Z$$
in matrix notation. If instead of computing the usual sum of squares, you compute $$Z' Q Z$$ for some matrix Q, then you still get a quantity with a a chi-squared distribution, but the degrees of freedom are now the rank of $Q$. There are more conditions on the matrix Q, but this is the gist of it.
If you play around with some matrix notation, you can express $$\sum_i (z_i-\bar{z})^2$$ as a quadratic form. Cochran assumes independence of the original normal variates, which is why the columns of your table of counts must be independent as well. | Why does independence test use the chi-squared distribution? | It's about the Poisson distribution. If $X$ is Poisson with mean $\lambda$, then the variance of $X$ is $\lambda$ also. This means that $$\frac{(X-\lambda)^2}{\lambda}$$ is a $z^2$ like entity. By the | Why does independence test use the chi-squared distribution?
It's about the Poisson distribution. If $X$ is Poisson with mean $\lambda$, then the variance of $X$ is $\lambda$ also. This means that $$\frac{(X-\lambda)^2}{\lambda}$$ is a $z^2$ like entity. By the CLT, the Poisson tends to normality as the mean gets large, which is where the chi-squared comes in. Yes, it is an asymptotic test.
The degrees of freedom come from Cochran's theorem. Basically, Cochran explains how the Chi-squared is transformed (or remains unchanged) subject to a linear transformation in the $z^2$ scores.
$$\sum_i z_i^2=Z' I Z$$
in matrix notation. If instead of computing the usual sum of squares, you compute $$Z' Q Z$$ for some matrix Q, then you still get a quantity with a a chi-squared distribution, but the degrees of freedom are now the rank of $Q$. There are more conditions on the matrix Q, but this is the gist of it.
If you play around with some matrix notation, you can express $$\sum_i (z_i-\bar{z})^2$$ as a quadratic form. Cochran assumes independence of the original normal variates, which is why the columns of your table of counts must be independent as well. | Why does independence test use the chi-squared distribution?
It's about the Poisson distribution. If $X$ is Poisson with mean $\lambda$, then the variance of $X$ is $\lambda$ also. This means that $$\frac{(X-\lambda)^2}{\lambda}$$ is a $z^2$ like entity. By the |
20,587 | Why does independence test use the chi-squared distribution? | According to the textbook "Introductory Statistics with Randomization and Simulation", section 3.3.2 (textbook freely available at OpenIntro), the $\chi^2$ test statistic is trying to accumulate the deviations of the observed from the expected. And the deviations are indeed expressed through the term
$$Z_i = \frac{O_i - E_i}{\sqrt{E_i}}$$
which actually originates from $$\frac{O_i - E_i}{(Standard Error Of The Observed)}$$.
The textbook goes on to say that the $(StandardErrorOfTheObserved)$ is better estimated by $\sqrt{E_i}$, so the term becomes $Z_i = \frac{O_i - E_i}{\sqrt{E_i}}$. The textbook doesn't actually explain why this substitution is acceptable, and I'd also like to find out.
Anyway, you could create a test statistic of the form
$$Z = |Z_1| + |Z_2| + |Z_3| + ...$$
but it's better to square all the terms, because you get positive values immediately and the higher values stand out more after squaring. So you get the following:
$$\chi^2 = Z_1^2 + Z_2^2 + Z_3^2 +...$$
But I don't know either why should this sum follow the $\chi^2$ distribution, or what's the connection to the definition of the $\chi^2$ distribution (sum of squares of standard normal independent variables).
EDIT: I'm still learning statistics, and I still don't think I understand the $\chi^2$ test properly. I hope others can enlighten me too. | Why does independence test use the chi-squared distribution? | According to the textbook "Introductory Statistics with Randomization and Simulation", section 3.3.2 (textbook freely available at OpenIntro), the $\chi^2$ test statistic is trying to accumulate the d | Why does independence test use the chi-squared distribution?
According to the textbook "Introductory Statistics with Randomization and Simulation", section 3.3.2 (textbook freely available at OpenIntro), the $\chi^2$ test statistic is trying to accumulate the deviations of the observed from the expected. And the deviations are indeed expressed through the term
$$Z_i = \frac{O_i - E_i}{\sqrt{E_i}}$$
which actually originates from $$\frac{O_i - E_i}{(Standard Error Of The Observed)}$$.
The textbook goes on to say that the $(StandardErrorOfTheObserved)$ is better estimated by $\sqrt{E_i}$, so the term becomes $Z_i = \frac{O_i - E_i}{\sqrt{E_i}}$. The textbook doesn't actually explain why this substitution is acceptable, and I'd also like to find out.
Anyway, you could create a test statistic of the form
$$Z = |Z_1| + |Z_2| + |Z_3| + ...$$
but it's better to square all the terms, because you get positive values immediately and the higher values stand out more after squaring. So you get the following:
$$\chi^2 = Z_1^2 + Z_2^2 + Z_3^2 +...$$
But I don't know either why should this sum follow the $\chi^2$ distribution, or what's the connection to the definition of the $\chi^2$ distribution (sum of squares of standard normal independent variables).
EDIT: I'm still learning statistics, and I still don't think I understand the $\chi^2$ test properly. I hope others can enlighten me too. | Why does independence test use the chi-squared distribution?
According to the textbook "Introductory Statistics with Randomization and Simulation", section 3.3.2 (textbook freely available at OpenIntro), the $\chi^2$ test statistic is trying to accumulate the d |
20,588 | Repeated measures over time with small $n$ | I have re-think your problem and found Friedman's test which is a non-parametric version of a one way ANOVA with repeated measures.
I hope you have some basic skills with R.
# Creating a source data.frame
my.data<-data.frame(value=c(2,7,7,3,6,3,2,4,4,3,14,167,200,45,132,NA,
245,199,177,134,298,111,75,43,23,98,87,NA,300,NA,118,202,156,23,34,98,
112,NA,200,NA,156,54,18,NA),
post.no=rep(c("baseline","post1","post2","post3"), each=11),
ID=rep(c(1:11), times=4))
# you must install this library
library(pgirmess)
Perform test Friedman's test...
friedman.test(my.data$value,my.data$post.no,my.data$ID)
Friedman rank sum test
data: my.data$value, my.data$post.no and my.data$ID
Friedman chi-squared = 14.6, df = 3, p-value = 0.002192
and then find between which groups the difference exist by non-parametric post-hoc test.
Here you have all possible comparisons.
friedmanmc(my.data$value,my.data$post.no,my.data$ID)
Multiple comparisons between groups after Friedman test
p.value: 0.05
Comparisons
obs.dif critical.dif difference
baseline-post1 25 15.97544 TRUE
baseline-post2 21 15.97544 TRUE
baseline-post3 20 15.97544 TRUE
post1-post2 4 15.97544 FALSE
post1-post3 5 15.97544 FALSE
post2-post3 1 15.97544 FALSE
As you can see only baseline (first time point) is statistically different from others.
I hope this will help you. | Repeated measures over time with small $n$ | I have re-think your problem and found Friedman's test which is a non-parametric version of a one way ANOVA with repeated measures.
I hope you have some basic skills with R.
# Creating a source data.f | Repeated measures over time with small $n$
I have re-think your problem and found Friedman's test which is a non-parametric version of a one way ANOVA with repeated measures.
I hope you have some basic skills with R.
# Creating a source data.frame
my.data<-data.frame(value=c(2,7,7,3,6,3,2,4,4,3,14,167,200,45,132,NA,
245,199,177,134,298,111,75,43,23,98,87,NA,300,NA,118,202,156,23,34,98,
112,NA,200,NA,156,54,18,NA),
post.no=rep(c("baseline","post1","post2","post3"), each=11),
ID=rep(c(1:11), times=4))
# you must install this library
library(pgirmess)
Perform test Friedman's test...
friedman.test(my.data$value,my.data$post.no,my.data$ID)
Friedman rank sum test
data: my.data$value, my.data$post.no and my.data$ID
Friedman chi-squared = 14.6, df = 3, p-value = 0.002192
and then find between which groups the difference exist by non-parametric post-hoc test.
Here you have all possible comparisons.
friedmanmc(my.data$value,my.data$post.no,my.data$ID)
Multiple comparisons between groups after Friedman test
p.value: 0.05
Comparisons
obs.dif critical.dif difference
baseline-post1 25 15.97544 TRUE
baseline-post2 21 15.97544 TRUE
baseline-post3 20 15.97544 TRUE
post1-post2 4 15.97544 FALSE
post1-post3 5 15.97544 FALSE
post2-post3 1 15.97544 FALSE
As you can see only baseline (first time point) is statistically different from others.
I hope this will help you. | Repeated measures over time with small $n$
I have re-think your problem and found Friedman's test which is a non-parametric version of a one way ANOVA with repeated measures.
I hope you have some basic skills with R.
# Creating a source data.f |
20,589 | Repeated measures over time with small $n$ | If you don't know the distribution of individual changes over time, you cannot approximate it with distribution of between-patient differences. For example, if you have 10 patient with respective iron levels (510,520,...,600) before treatment and (520,530,...,610) after treatment, the Kruskal-Wallis ANOVA (or any other similar algorithm) would claim that there is no significant change of iron levels.
IMHO, without the control group, the best you can do is to count how many patients increased their iron level and how many decreased it, and test the significance of this.
That said, if the KW ANOVA tells you that there is a significant iron level, it is (no false positives). | Repeated measures over time with small $n$ | If you don't know the distribution of individual changes over time, you cannot approximate it with distribution of between-patient differences. For example, if you have 10 patient with respective iro | Repeated measures over time with small $n$
If you don't know the distribution of individual changes over time, you cannot approximate it with distribution of between-patient differences. For example, if you have 10 patient with respective iron levels (510,520,...,600) before treatment and (520,530,...,610) after treatment, the Kruskal-Wallis ANOVA (or any other similar algorithm) would claim that there is no significant change of iron levels.
IMHO, without the control group, the best you can do is to count how many patients increased their iron level and how many decreased it, and test the significance of this.
That said, if the KW ANOVA tells you that there is a significant iron level, it is (no false positives). | Repeated measures over time with small $n$
If you don't know the distribution of individual changes over time, you cannot approximate it with distribution of between-patient differences. For example, if you have 10 patient with respective iro |
20,590 | Does stepwise regression provide a biased estimate of population r-square? | Referenced in my book, there is a literature showing that to get a nearly unbiased estimate of $R^2$ when doing variable selection, one needs to insert into the formula for adjusted $R^2$ the number of candidate predictors, not the number of "selected" predictors. Therefore, biases caused by variable selection are substantial. Perhaps more importantly, variable selection results in worse real $R^2$ and an inability to actually find the "right" variables. | Does stepwise regression provide a biased estimate of population r-square? | Referenced in my book, there is a literature showing that to get a nearly unbiased estimate of $R^2$ when doing variable selection, one needs to insert into the formula for adjusted $R^2$ the number o | Does stepwise regression provide a biased estimate of population r-square?
Referenced in my book, there is a literature showing that to get a nearly unbiased estimate of $R^2$ when doing variable selection, one needs to insert into the formula for adjusted $R^2$ the number of candidate predictors, not the number of "selected" predictors. Therefore, biases caused by variable selection are substantial. Perhaps more importantly, variable selection results in worse real $R^2$ and an inability to actually find the "right" variables. | Does stepwise regression provide a biased estimate of population r-square?
Referenced in my book, there is a literature showing that to get a nearly unbiased estimate of $R^2$ when doing variable selection, one needs to insert into the formula for adjusted $R^2$ the number o |
20,591 | Does stepwise regression provide a biased estimate of population r-square? | Overview
Many researchers have discussed the many problems with stepwise regression (e.g., @FrankHarrell (2001) in section 4.3). In particular Harrell notes that "it yields $R^2$ values that are biased high" (p.56). There are several possible interpretations of this statement, based on what you assume is the estimand. If you assume the estimate is some form of $\rho^2$, then the following can be said: While this is true for some combinations of data generating process, sample size, set of predictors and p-value criterion of predictor entry, it is not true in all cases.
Specifically, $R^2$ from stepwise regression is not inherently biased in a particular direction when estimating $\rho^2$. The p-value criterion for entry of predictors in the stepwise regression can be used to modulate the expected value of stepwise $R^2$ (i.e., the estimator of $\rho^2$). Specifically, as the p-value of entry approaches zero, then the probability of any predictor being included in the final model approaches zero, and the expected value of stepwise $R^2$ will approach zero. With a p-value of entry of one, all predictors will be retained, and stepwise $R^2$ will display the same bias that $R^2$ shows with all predictors. The bias is monotonically related to the p-value of entry. Thus, there will be a p-value of entry which results in an unbiased estimate of $\rho^2$.
I've run a few simulations under different conditions. The p-value of predictor entry which yielded an approximately unbiased estimate often ranged between .05 and .0001. However, I haven't yet read any simulations which explicitly explore this or provide advice on what kind of bias to expect from published stepwise $R^2$ values using a given p-value of entry and given the features of the data.
That said, for practical purposes, adjusted $R^2$ is specifically designed to estimate $\rho^2$. Thus, it is more suited to estimating $\rho^2$ than merely hoping that the p-value of entry in a stepwise regression happens to be correct in order to result in an approximately unbiased estimate.
Simulation
The following simulation has four uncorrelated predictors where population r-square is 40%. Two of the predictors explain 20% each, and the other two predictors explain 0%.
The simulation generates a 1000 datasets and estimates stepwise regression r-square as a percentage for each dataset.
# source("http://bioconductor.org/biocLite.R")
# biocLite("maSigPro") # provides stepwise regression function two.ways.stepfor
library(maSigPro)
get_data <- function(n=100) {
x1 <- rnorm(n, 0, 1)
x2 <- rnorm(n, 0, 1)
x3 <- rnorm(n, 0, 1)
x4 <- rnorm(n, 0, 1)
e <- rnorm(n, 0, 1)
y <- 1 * x1 + 1 * x2 + sqrt(3) * e
data <- data.frame(y, x1, x2, x3, x4)
data
}
get_rsquare <- function(x, alpha=.05) {
fit <- two.ways.stepfor(x$y, subset(x, select=-y), alfa=alpha)
class(fit) <-'lm'
summary.lm(fit)$r.square * 100
}
The following code returns the r-square with an alpha for entry of .01, .001, .0001, and .00001.
set.seed(1234)
simulations <- 1000
datasets <- lapply(seq(simulations), function(X) get_data(n=100))
rsquares01 <- sapply(datasets, function(X) get_rsquare(X, alpha=.01))
rsquares001 <- sapply(datasets, function(X) get_rsquare(X, alpha=.001))
rsquares0001 <- sapply(datasets, function(X) get_rsquare(X, alpha=.0001))
rsquares00001 <- sapply(datasets, function(X) get_rsquare(X, alpha=.00001))
The following results indicate the bias for each of the five alpha of entries. Note that I've multiplied r-square by 100 to make it easier to see the differences.
mean(rsquares01) - 40
mean(rsquares001) - 40
mean(rsquares0001) - 40
mean(rsquares00001) - 40
sd(rsquares01)/sqrt(simulations) # approximate standard error in estimate of bias
The results suggest that alpha of entries of .01 and .001 result in positive bias and alpha of entries of .0001 and .00001 result in negative bias. So presumably an alpha of entry around .0005 would result in an unbiased stepwise regression.
> mean(rsquares01) - 40
[1] 1.128996
> mean(rsquares001) - 40
[1] 0.8238992
> mean(rsquares0001) - 40
[1] -0.9681992
> mean(rsquares00001) - 40
[1] -5.126225
> sd(rsquares01)/sqrt(simulations) # approximate standard error in estimate of bias
[1] 0.2329339
The main conclusion I take from this is that stepwise regression is not inherently biased in a particular direction. That said, it will be at least somewhat biased for all but one p-value of predictor entry. I take @Peter Flom's point that in the real world we don't know the data generating process. However, I imagine a more detailed exploration of how this bias varies over, n, alpha of entry, data generating processes, and stepwise regression procedure (e.g., including backwards pass) could substantially inform an understanding of such bias.
References
Harrell, F. E. (2001). Regression modeling strategies: with applications to linear models, logistic regression, and survival analysis. Springer. | Does stepwise regression provide a biased estimate of population r-square? | Overview
Many researchers have discussed the many problems with stepwise regression (e.g., @FrankHarrell (2001) in section 4.3). In particular Harrell notes that "it yields $R^2$ values that are bia | Does stepwise regression provide a biased estimate of population r-square?
Overview
Many researchers have discussed the many problems with stepwise regression (e.g., @FrankHarrell (2001) in section 4.3). In particular Harrell notes that "it yields $R^2$ values that are biased high" (p.56). There are several possible interpretations of this statement, based on what you assume is the estimand. If you assume the estimate is some form of $\rho^2$, then the following can be said: While this is true for some combinations of data generating process, sample size, set of predictors and p-value criterion of predictor entry, it is not true in all cases.
Specifically, $R^2$ from stepwise regression is not inherently biased in a particular direction when estimating $\rho^2$. The p-value criterion for entry of predictors in the stepwise regression can be used to modulate the expected value of stepwise $R^2$ (i.e., the estimator of $\rho^2$). Specifically, as the p-value of entry approaches zero, then the probability of any predictor being included in the final model approaches zero, and the expected value of stepwise $R^2$ will approach zero. With a p-value of entry of one, all predictors will be retained, and stepwise $R^2$ will display the same bias that $R^2$ shows with all predictors. The bias is monotonically related to the p-value of entry. Thus, there will be a p-value of entry which results in an unbiased estimate of $\rho^2$.
I've run a few simulations under different conditions. The p-value of predictor entry which yielded an approximately unbiased estimate often ranged between .05 and .0001. However, I haven't yet read any simulations which explicitly explore this or provide advice on what kind of bias to expect from published stepwise $R^2$ values using a given p-value of entry and given the features of the data.
That said, for practical purposes, adjusted $R^2$ is specifically designed to estimate $\rho^2$. Thus, it is more suited to estimating $\rho^2$ than merely hoping that the p-value of entry in a stepwise regression happens to be correct in order to result in an approximately unbiased estimate.
Simulation
The following simulation has four uncorrelated predictors where population r-square is 40%. Two of the predictors explain 20% each, and the other two predictors explain 0%.
The simulation generates a 1000 datasets and estimates stepwise regression r-square as a percentage for each dataset.
# source("http://bioconductor.org/biocLite.R")
# biocLite("maSigPro") # provides stepwise regression function two.ways.stepfor
library(maSigPro)
get_data <- function(n=100) {
x1 <- rnorm(n, 0, 1)
x2 <- rnorm(n, 0, 1)
x3 <- rnorm(n, 0, 1)
x4 <- rnorm(n, 0, 1)
e <- rnorm(n, 0, 1)
y <- 1 * x1 + 1 * x2 + sqrt(3) * e
data <- data.frame(y, x1, x2, x3, x4)
data
}
get_rsquare <- function(x, alpha=.05) {
fit <- two.ways.stepfor(x$y, subset(x, select=-y), alfa=alpha)
class(fit) <-'lm'
summary.lm(fit)$r.square * 100
}
The following code returns the r-square with an alpha for entry of .01, .001, .0001, and .00001.
set.seed(1234)
simulations <- 1000
datasets <- lapply(seq(simulations), function(X) get_data(n=100))
rsquares01 <- sapply(datasets, function(X) get_rsquare(X, alpha=.01))
rsquares001 <- sapply(datasets, function(X) get_rsquare(X, alpha=.001))
rsquares0001 <- sapply(datasets, function(X) get_rsquare(X, alpha=.0001))
rsquares00001 <- sapply(datasets, function(X) get_rsquare(X, alpha=.00001))
The following results indicate the bias for each of the five alpha of entries. Note that I've multiplied r-square by 100 to make it easier to see the differences.
mean(rsquares01) - 40
mean(rsquares001) - 40
mean(rsquares0001) - 40
mean(rsquares00001) - 40
sd(rsquares01)/sqrt(simulations) # approximate standard error in estimate of bias
The results suggest that alpha of entries of .01 and .001 result in positive bias and alpha of entries of .0001 and .00001 result in negative bias. So presumably an alpha of entry around .0005 would result in an unbiased stepwise regression.
> mean(rsquares01) - 40
[1] 1.128996
> mean(rsquares001) - 40
[1] 0.8238992
> mean(rsquares0001) - 40
[1] -0.9681992
> mean(rsquares00001) - 40
[1] -5.126225
> sd(rsquares01)/sqrt(simulations) # approximate standard error in estimate of bias
[1] 0.2329339
The main conclusion I take from this is that stepwise regression is not inherently biased in a particular direction. That said, it will be at least somewhat biased for all but one p-value of predictor entry. I take @Peter Flom's point that in the real world we don't know the data generating process. However, I imagine a more detailed exploration of how this bias varies over, n, alpha of entry, data generating processes, and stepwise regression procedure (e.g., including backwards pass) could substantially inform an understanding of such bias.
References
Harrell, F. E. (2001). Regression modeling strategies: with applications to linear models, logistic regression, and survival analysis. Springer. | Does stepwise regression provide a biased estimate of population r-square?
Overview
Many researchers have discussed the many problems with stepwise regression (e.g., @FrankHarrell (2001) in section 4.3). In particular Harrell notes that "it yields $R^2$ values that are bia |
20,592 | Bayesian variable selection -- does it really work? | In the BUGS code, mean[i]<-inprod(X[i,],beta) should be mean[i]<-inprod(X[i,],beta[]).
Your priors on tau and taubeta are too informative.
You need a non-informative prior on betaifincluded, use e.g. a gamma(0.1,0.1) on taubeta. This may explain why you get tiny regression coefficients. | Bayesian variable selection -- does it really work? | In the BUGS code, mean[i]<-inprod(X[i,],beta) should be mean[i]<-inprod(X[i,],beta[]).
Your priors on tau and taubeta are too informative.
You need a non-informative prior on betaifincluded, use e.g. | Bayesian variable selection -- does it really work?
In the BUGS code, mean[i]<-inprod(X[i,],beta) should be mean[i]<-inprod(X[i,],beta[]).
Your priors on tau and taubeta are too informative.
You need a non-informative prior on betaifincluded, use e.g. a gamma(0.1,0.1) on taubeta. This may explain why you get tiny regression coefficients. | Bayesian variable selection -- does it really work?
In the BUGS code, mean[i]<-inprod(X[i,],beta) should be mean[i]<-inprod(X[i,],beta[]).
Your priors on tau and taubeta are too informative.
You need a non-informative prior on betaifincluded, use e.g. |
20,593 | Bayesian variable selection -- does it really work? | It does work, but you gave all the variable inclusion indicators the same underlying distribution.
model {
for (i in 1:n) {
mean[i]<-inprod(X[i,],beta)
y[i]~dnorm(mean[i],tau)
}
for (j in 1:p) {
indicator[j]~dbern(probindicator[j])
probindicator[j]~dbeta(2,8)
betaifincluded[j]~dnorm(0,taubeta)
beta[j] <- indicator[j]*betaifincluded[j]
}
tau~dgamma(1,0.01)
taubeta~dgamma(1,0.01)
}
might work better with a limited number of variables. | Bayesian variable selection -- does it really work? | It does work, but you gave all the variable inclusion indicators the same underlying distribution.
model {
for (i in 1:n) {
mean[i]<-inprod(X[i,],beta)
y[i]~dnorm(mean[i],tau)
}
| Bayesian variable selection -- does it really work?
It does work, but you gave all the variable inclusion indicators the same underlying distribution.
model {
for (i in 1:n) {
mean[i]<-inprod(X[i,],beta)
y[i]~dnorm(mean[i],tau)
}
for (j in 1:p) {
indicator[j]~dbern(probindicator[j])
probindicator[j]~dbeta(2,8)
betaifincluded[j]~dnorm(0,taubeta)
beta[j] <- indicator[j]*betaifincluded[j]
}
tau~dgamma(1,0.01)
taubeta~dgamma(1,0.01)
}
might work better with a limited number of variables. | Bayesian variable selection -- does it really work?
It does work, but you gave all the variable inclusion indicators the same underlying distribution.
model {
for (i in 1:n) {
mean[i]<-inprod(X[i,],beta)
y[i]~dnorm(mean[i],tau)
}
|
20,594 | Bayesian variable selection -- does it really work? | If you used log returns, then you made a slightly biasing error but if you used future value divided by present value then your likelihood is wrong. Actually, your likelihood is wrong in either case. It is wrong enough to matter.
Consider that a statistic is any function of the data. Returns are not data, they are transformations of data. They are a future value divided by a present value. Prices are data. Prices must have a distribution function, but the distribution function for returns must depend solely on the nature of the prices.
For securities in a double auction, there is no "winner's curse." The rational behavior is to bid your expectation. With many buyers and many sellers, the limit book should converge to the normal distribution as it is a distribution of expectations. So $p_t$ should be normally distributed. Also $p_{t+1}$ should be normally distributed. Therefore returns should be the ratio of $$\frac{p_{t+1}}{p_t}-1.$$
The likelihood function for your regression should have been $$\frac{1}{\pi}\frac{\sigma}{\sigma^2+(y-\beta_1x_1-\beta_2x_2\dots-\beta_nx_n-\alpha)^2}.$$
OLS forces a best fit to the observed data even if it is the wrong solution. Bayesian methods attempt to find the data generating function through the likelihood. You had the likelihood wrong, so it could not find it.
I have a paper out on this if you need additional information.
EDIT
I think you have misunderstood. If you would convert the likelihood to a density function and take the expectation, you would find that it has none. By proof by Augustin Cauchy in 1852 or maybe 1851, any form of least squares solution is perfectly imprecise. It will always fail. It isn't that you should use standard regression because the Bayesian is sensitive to the likelihood, it is that Bayes is the only available solution that is admissible, with some special exceptions for some unusual special cases.
In doing the empirical testing on this, and before I had read enough of the math, I naively thought that the Bayesian and the Frequentist solution should match. There is, approximately, a theorem that says that as the sample becomes large enough, the two will converge. I used all end of day trades in the CRSP universe from 1925-2013 to test it. That isn't what the theorem says though. I was misunderstanding the rules.
I also tried the problem in logs, and it still did not match. So I realized something, all distributions are shapes, and so I constructed a geometric solution to determine which solution was correct. I treated it as a pure geometry problem to determine which algebraic answer matched the data.
The Bayesian one matched. This lead me down a very mathematical path because I couldn't figure out why the unbiased estimator was so wrong. Just for the record, using disaggregated returns over the period 1925-2013 and removing shell companies, closed-end funds and so forth, the discrepancy between the center of location is 2% and the measure of risk is understated by 4% for annual returns. This discrepancy holds under log transformation, but for a different reason. It may be different for individual indices or subsets of the data.
The reason for the discrepancy is two-fold. The first is that the distributions involved lack a sufficient statistic. For certain types of problems, this doesn't matter. For projective purposes, such as prediction or allocation, however, they matter quite a bit. The second reason is that the unbiased estimator is always a version of the mean, but the distribution has no mean.
The density above is not a member of the exponential family as the normal or the gamma distribution is. By the Pitman–Koopman–Darmois theorem, no sufficient point statistic exists for the parameters. This implies that any attempt to create a point estimator must throw away information. This is not a problem for Bayesian solutions because the posterior is an entire density and if you did need a point estimate, you could find the predictive density and minimize a cost function over it to reduce it to a single point. The Bayesian likelihood is always minimally sufficient.
The minimum variance unbiased estimator for the above function is to keep the central 24.6% of the data, find its trimmed mean, and to discard the rest of the data. That means over 75% of the data is dropped, and the information is lost. Just a note, it might be 24.8%, as I am working from memory. You can find Rothenberg's paper at:
Rothenberg, T. J. and F. M. Fisher, and C. B. Tilanus, A Note on Estimation from a Cauchy Sample, Journal of the American Statistical Association, 1964, vol 59(306), pp. 460-463
The second issue was surprising to me. Until I worked through the geometry, I didn't realize what the cause was. Returns are bound on the bottom at -100%. This shifts the median by 2% and the interquartile range is shifted by 4% although the half-mass is still at the same points. The half-mass is the proper measure of scale, but the half-width is not. If there were no truncation, then the half-width and the half-mass would be at the same points. Likewise, the median and the mode would remain at the same point. The median is the return for the mean actor or at least the mean trade. As such, it is always the location of the MVUE and the log mean.
The correct understanding of the theorem is that all Bayesian estimators are admissible estimators. Frequentist estimators are admissible estimators if one of two conditions obtain. The first is that in every sample, the Frequentist and the Bayesian solution are identical. The second is that if the limiting solution of the Bayesian method matched the Frequentist solution, then the Frequentist solution is admissible.
All admissible estimators converge to the same solution once the sample size is large enough. The Frequentist estimator presumes that its model is the true model and the data is random. The Bayesian assumes the data is true, but the model is random. If you had an infinite amount of data, then the subjective model must converge to reality. If you had an infinite amount of data, but the wrong model, then the Frequentist model will converge to reality with probability zero.
In this case, the Bayesian solution, under reasonable priors, will always stochastically dominate any Frequentist estimator because of the truncation and the loss of information to create the estimator.
In logs, the likelihood function is the hyperbolic secant distribution. It has a finite variance, but no covariance. The covariance matrix found using OLS is an artifact of the data and does not point to a parameter that exists in the underlying data. As with the raw form, nothing in the log form covaries, but nothing is independent either. Instead, a far more complex relationship exists that violates the definition of covariance, but in which they can comove.
Markowitz and Usman almost found it in their work on distributions, but the hyperbolic secant distribution isn't in a Pearson family and they misinterpreted the data by not noticing that when you change a distribution from raw data to log data you also change its statistical properties. They basically found this out but missed it because they had no reason to look for it and they didn't realize the unintended consequences of using logs.
I don't have the Markowitz and Usman cite with me where I am at, but they did one of the few very good jobs at estimating the distribution that are out there.
In any case, I don't use JAGS. I have no idea how to do it. I code all my MCMC work by hand.
I have a paper that is far more complete and accurate on this topic at:
Harris, D.E. (2017) The Distribution of Returns. Journal of Mathematical Finance, 7, 769-804.
It will provide you with a method to construct distributions for any asset or liability class, also accounting ratios.
I was wordy, but I could see you were misunderstanding the relationship between Bayes and the Pearson-Neyman methods. You had them reversed. Bayes always works, but you are trapped with a prior density that will perturb your solution. With a proper prior you are guaranteed a biased estimator and for this type of likelihood function, I believe you must use a proper prior to guarantee integrability to unity. Frequentist methods are fast and usually work. They are unbiased, but may not be valid. | Bayesian variable selection -- does it really work? | If you used log returns, then you made a slightly biasing error but if you used future value divided by present value then your likelihood is wrong. Actually, your likelihood is wrong in either case. | Bayesian variable selection -- does it really work?
If you used log returns, then you made a slightly biasing error but if you used future value divided by present value then your likelihood is wrong. Actually, your likelihood is wrong in either case. It is wrong enough to matter.
Consider that a statistic is any function of the data. Returns are not data, they are transformations of data. They are a future value divided by a present value. Prices are data. Prices must have a distribution function, but the distribution function for returns must depend solely on the nature of the prices.
For securities in a double auction, there is no "winner's curse." The rational behavior is to bid your expectation. With many buyers and many sellers, the limit book should converge to the normal distribution as it is a distribution of expectations. So $p_t$ should be normally distributed. Also $p_{t+1}$ should be normally distributed. Therefore returns should be the ratio of $$\frac{p_{t+1}}{p_t}-1.$$
The likelihood function for your regression should have been $$\frac{1}{\pi}\frac{\sigma}{\sigma^2+(y-\beta_1x_1-\beta_2x_2\dots-\beta_nx_n-\alpha)^2}.$$
OLS forces a best fit to the observed data even if it is the wrong solution. Bayesian methods attempt to find the data generating function through the likelihood. You had the likelihood wrong, so it could not find it.
I have a paper out on this if you need additional information.
EDIT
I think you have misunderstood. If you would convert the likelihood to a density function and take the expectation, you would find that it has none. By proof by Augustin Cauchy in 1852 or maybe 1851, any form of least squares solution is perfectly imprecise. It will always fail. It isn't that you should use standard regression because the Bayesian is sensitive to the likelihood, it is that Bayes is the only available solution that is admissible, with some special exceptions for some unusual special cases.
In doing the empirical testing on this, and before I had read enough of the math, I naively thought that the Bayesian and the Frequentist solution should match. There is, approximately, a theorem that says that as the sample becomes large enough, the two will converge. I used all end of day trades in the CRSP universe from 1925-2013 to test it. That isn't what the theorem says though. I was misunderstanding the rules.
I also tried the problem in logs, and it still did not match. So I realized something, all distributions are shapes, and so I constructed a geometric solution to determine which solution was correct. I treated it as a pure geometry problem to determine which algebraic answer matched the data.
The Bayesian one matched. This lead me down a very mathematical path because I couldn't figure out why the unbiased estimator was so wrong. Just for the record, using disaggregated returns over the period 1925-2013 and removing shell companies, closed-end funds and so forth, the discrepancy between the center of location is 2% and the measure of risk is understated by 4% for annual returns. This discrepancy holds under log transformation, but for a different reason. It may be different for individual indices or subsets of the data.
The reason for the discrepancy is two-fold. The first is that the distributions involved lack a sufficient statistic. For certain types of problems, this doesn't matter. For projective purposes, such as prediction or allocation, however, they matter quite a bit. The second reason is that the unbiased estimator is always a version of the mean, but the distribution has no mean.
The density above is not a member of the exponential family as the normal or the gamma distribution is. By the Pitman–Koopman–Darmois theorem, no sufficient point statistic exists for the parameters. This implies that any attempt to create a point estimator must throw away information. This is not a problem for Bayesian solutions because the posterior is an entire density and if you did need a point estimate, you could find the predictive density and minimize a cost function over it to reduce it to a single point. The Bayesian likelihood is always minimally sufficient.
The minimum variance unbiased estimator for the above function is to keep the central 24.6% of the data, find its trimmed mean, and to discard the rest of the data. That means over 75% of the data is dropped, and the information is lost. Just a note, it might be 24.8%, as I am working from memory. You can find Rothenberg's paper at:
Rothenberg, T. J. and F. M. Fisher, and C. B. Tilanus, A Note on Estimation from a Cauchy Sample, Journal of the American Statistical Association, 1964, vol 59(306), pp. 460-463
The second issue was surprising to me. Until I worked through the geometry, I didn't realize what the cause was. Returns are bound on the bottom at -100%. This shifts the median by 2% and the interquartile range is shifted by 4% although the half-mass is still at the same points. The half-mass is the proper measure of scale, but the half-width is not. If there were no truncation, then the half-width and the half-mass would be at the same points. Likewise, the median and the mode would remain at the same point. The median is the return for the mean actor or at least the mean trade. As such, it is always the location of the MVUE and the log mean.
The correct understanding of the theorem is that all Bayesian estimators are admissible estimators. Frequentist estimators are admissible estimators if one of two conditions obtain. The first is that in every sample, the Frequentist and the Bayesian solution are identical. The second is that if the limiting solution of the Bayesian method matched the Frequentist solution, then the Frequentist solution is admissible.
All admissible estimators converge to the same solution once the sample size is large enough. The Frequentist estimator presumes that its model is the true model and the data is random. The Bayesian assumes the data is true, but the model is random. If you had an infinite amount of data, then the subjective model must converge to reality. If you had an infinite amount of data, but the wrong model, then the Frequentist model will converge to reality with probability zero.
In this case, the Bayesian solution, under reasonable priors, will always stochastically dominate any Frequentist estimator because of the truncation and the loss of information to create the estimator.
In logs, the likelihood function is the hyperbolic secant distribution. It has a finite variance, but no covariance. The covariance matrix found using OLS is an artifact of the data and does not point to a parameter that exists in the underlying data. As with the raw form, nothing in the log form covaries, but nothing is independent either. Instead, a far more complex relationship exists that violates the definition of covariance, but in which they can comove.
Markowitz and Usman almost found it in their work on distributions, but the hyperbolic secant distribution isn't in a Pearson family and they misinterpreted the data by not noticing that when you change a distribution from raw data to log data you also change its statistical properties. They basically found this out but missed it because they had no reason to look for it and they didn't realize the unintended consequences of using logs.
I don't have the Markowitz and Usman cite with me where I am at, but they did one of the few very good jobs at estimating the distribution that are out there.
In any case, I don't use JAGS. I have no idea how to do it. I code all my MCMC work by hand.
I have a paper that is far more complete and accurate on this topic at:
Harris, D.E. (2017) The Distribution of Returns. Journal of Mathematical Finance, 7, 769-804.
It will provide you with a method to construct distributions for any asset or liability class, also accounting ratios.
I was wordy, but I could see you were misunderstanding the relationship between Bayes and the Pearson-Neyman methods. You had them reversed. Bayes always works, but you are trapped with a prior density that will perturb your solution. With a proper prior you are guaranteed a biased estimator and for this type of likelihood function, I believe you must use a proper prior to guarantee integrability to unity. Frequentist methods are fast and usually work. They are unbiased, but may not be valid. | Bayesian variable selection -- does it really work?
If you used log returns, then you made a slightly biasing error but if you used future value divided by present value then your likelihood is wrong. Actually, your likelihood is wrong in either case. |
20,595 | Is it OK to mix categorical and continuous data for SVM (Support Vector Machines)? | Yes! But maybe not in the way you mean.
In my research I frequently create categorical features from continuously-valued ones using an algorithm like recursive partitioning. I usually use this approach with the SVMLight implementation of support vector machines, but I've used it with LibSVM as well. You'll need to be sure you assign your partitioned categorical features to a specific place in your feature vector during training and classification, otherwise your model is going to end up jumbly.
Edit: That is to say, when I've done this, I assign the first n elements of the vector to the binary values associated with the output of recursive partitioning. In binary feature modeling, you just have a giant vector of 0's and 1's, so everything looks the same to the model, unless you explicitly indicate where different features are. This is probably overly specific, as I imagine most SVM implementations will do this on their own, but, if you like to program your own, it might be something to think about! | Is it OK to mix categorical and continuous data for SVM (Support Vector Machines)? | Yes! But maybe not in the way you mean.
In my research I frequently create categorical features from continuously-valued ones using an algorithm like recursive partitioning. I usually use this approac | Is it OK to mix categorical and continuous data for SVM (Support Vector Machines)?
Yes! But maybe not in the way you mean.
In my research I frequently create categorical features from continuously-valued ones using an algorithm like recursive partitioning. I usually use this approach with the SVMLight implementation of support vector machines, but I've used it with LibSVM as well. You'll need to be sure you assign your partitioned categorical features to a specific place in your feature vector during training and classification, otherwise your model is going to end up jumbly.
Edit: That is to say, when I've done this, I assign the first n elements of the vector to the binary values associated with the output of recursive partitioning. In binary feature modeling, you just have a giant vector of 0's and 1's, so everything looks the same to the model, unless you explicitly indicate where different features are. This is probably overly specific, as I imagine most SVM implementations will do this on their own, but, if you like to program your own, it might be something to think about! | Is it OK to mix categorical and continuous data for SVM (Support Vector Machines)?
Yes! But maybe not in the way you mean.
In my research I frequently create categorical features from continuously-valued ones using an algorithm like recursive partitioning. I usually use this approac |
20,596 | Question about logistic regression | This is actually an extremely sophisticated problem and a tough ask from your lecturer!
In terms of how you organise your data, a 1070 x 10 rectangle is fine. For example, in R:
> conflict.data <- data.frame(
+ confl = sample(0:1, 1070, replace=T),
+ country = factor(rep(1:107,10)),
+ period = factor(rep(1:10, rep(107,10))),
+ landdeg = sample(c("Type1", "Type2"), 1070, replace=T),
+ popincrease = sample(0:1, 1070, replace=T),
+ liveli =sample(0:1, 1070, replace=T),
+ popden = sample(c("Low", "Med", "High"), 1070, replace=T),
+ NDVI = rnorm(1070,100,10),
+ NDVIdecl1 = sample(0:1, 1070, replace=T),
+ NDVIdecl2 = sample(0:1, 1070, replace=T))
> head(conflict.data)
confl country period landdeg popincrease liveli popden NDVI NDVIdecl1 NDVIdecl2
1 1 1 1 Type1 1 0 Low 113.4744 0 1
2 1 2 1 Type2 1 1 High 103.2979 0 0
3 0 3 1 Type2 1 1 Med 109.1200 1 1
4 1 4 1 Type2 0 1 Low 112.1574 1 0
5 0 5 1 Type1 0 0 High 109.9875 0 1
6 1 6 1 Type1 1 0 Low 109.2785 0 0
> summary(conflict.data)
confl country period landdeg popincrease liveli popden NDVI NDVIdecl1 NDVIdecl2
Min. :0.0000 1 : 10 1 :107 Type1:535 Min. :0.0000 Min. :0.0000 High:361 Min. : 68.71 Min. :0.0000 Min. :0.0000
1st Qu.:0.0000 2 : 10 2 :107 Type2:535 1st Qu.:0.0000 1st Qu.:0.0000 Low :340 1st Qu.: 93.25 1st Qu.:0.0000 1st Qu.:0.0000
Median :1.0000 3 : 10 3 :107 Median :1.0000 Median :1.0000 Med :369 Median : 99.65 Median :1.0000 Median :0.0000
Mean :0.5009 4 : 10 4 :107 Mean :0.5028 Mean :0.5056 Mean : 99.84 Mean :0.5121 Mean :0.4888
3rd Qu.:1.0000 5 : 10 5 :107 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.:106.99 3rd Qu.:1.0000 3rd Qu.:1.0000
Max. :1.0000 6 : 10 6 :107 Max. :1.0000 Max. :1.0000 Max. :130.13 Max. :1.0000 Max. :1.0000
(Other):1010 (Other):428
> dim(conflict.data)
[1] 1070 10
For fitting a model, the glm() function as @gui11aume suggests will do the basics...
mod <- glm(confl~., family="binomial", data=conflict.data)
anova(mod)
... but this has the problem that it treats "country" (I'm assuming you have country as your 107 units) as a fixed effect, whereas a random effect is more appropriate. It also treats period as a simple factor, no autocorrelation allowed.
You can address the first problem with a generalized linear mixed effects model as in eg Bates et al's lme4 package in R. There's a nice introduction to some aspects of this here. Something like
library(lme4)
mod2 <- lmer(confl ~ landdeg + popincrease + liveli + popden +
NDVI + NDVIdecl1 + NDVIdecl2 + (1|country) +(1|period), family=binomial,
data=conflict.data)
summary(mod2)
would be a step forward.
Now your last remaining problem is autocorrelation across your 10 periods. Basically, your 10 data points on each country aren't worth as much as if they were 10 randomly chosen independent and identicall distributed points. I'm not aware of a widely available software solution to autocorrelation in the residuals of a multilevel model with a non-Normal response. Certainly it isn't implemented in lme4. Others may know more than me. | Question about logistic regression | This is actually an extremely sophisticated problem and a tough ask from your lecturer!
In terms of how you organise your data, a 1070 x 10 rectangle is fine. For example, in R:
> conflict.data <- da | Question about logistic regression
This is actually an extremely sophisticated problem and a tough ask from your lecturer!
In terms of how you organise your data, a 1070 x 10 rectangle is fine. For example, in R:
> conflict.data <- data.frame(
+ confl = sample(0:1, 1070, replace=T),
+ country = factor(rep(1:107,10)),
+ period = factor(rep(1:10, rep(107,10))),
+ landdeg = sample(c("Type1", "Type2"), 1070, replace=T),
+ popincrease = sample(0:1, 1070, replace=T),
+ liveli =sample(0:1, 1070, replace=T),
+ popden = sample(c("Low", "Med", "High"), 1070, replace=T),
+ NDVI = rnorm(1070,100,10),
+ NDVIdecl1 = sample(0:1, 1070, replace=T),
+ NDVIdecl2 = sample(0:1, 1070, replace=T))
> head(conflict.data)
confl country period landdeg popincrease liveli popden NDVI NDVIdecl1 NDVIdecl2
1 1 1 1 Type1 1 0 Low 113.4744 0 1
2 1 2 1 Type2 1 1 High 103.2979 0 0
3 0 3 1 Type2 1 1 Med 109.1200 1 1
4 1 4 1 Type2 0 1 Low 112.1574 1 0
5 0 5 1 Type1 0 0 High 109.9875 0 1
6 1 6 1 Type1 1 0 Low 109.2785 0 0
> summary(conflict.data)
confl country period landdeg popincrease liveli popden NDVI NDVIdecl1 NDVIdecl2
Min. :0.0000 1 : 10 1 :107 Type1:535 Min. :0.0000 Min. :0.0000 High:361 Min. : 68.71 Min. :0.0000 Min. :0.0000
1st Qu.:0.0000 2 : 10 2 :107 Type2:535 1st Qu.:0.0000 1st Qu.:0.0000 Low :340 1st Qu.: 93.25 1st Qu.:0.0000 1st Qu.:0.0000
Median :1.0000 3 : 10 3 :107 Median :1.0000 Median :1.0000 Med :369 Median : 99.65 Median :1.0000 Median :0.0000
Mean :0.5009 4 : 10 4 :107 Mean :0.5028 Mean :0.5056 Mean : 99.84 Mean :0.5121 Mean :0.4888
3rd Qu.:1.0000 5 : 10 5 :107 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.:106.99 3rd Qu.:1.0000 3rd Qu.:1.0000
Max. :1.0000 6 : 10 6 :107 Max. :1.0000 Max. :1.0000 Max. :130.13 Max. :1.0000 Max. :1.0000
(Other):1010 (Other):428
> dim(conflict.data)
[1] 1070 10
For fitting a model, the glm() function as @gui11aume suggests will do the basics...
mod <- glm(confl~., family="binomial", data=conflict.data)
anova(mod)
... but this has the problem that it treats "country" (I'm assuming you have country as your 107 units) as a fixed effect, whereas a random effect is more appropriate. It also treats period as a simple factor, no autocorrelation allowed.
You can address the first problem with a generalized linear mixed effects model as in eg Bates et al's lme4 package in R. There's a nice introduction to some aspects of this here. Something like
library(lme4)
mod2 <- lmer(confl ~ landdeg + popincrease + liveli + popden +
NDVI + NDVIdecl1 + NDVIdecl2 + (1|country) +(1|period), family=binomial,
data=conflict.data)
summary(mod2)
would be a step forward.
Now your last remaining problem is autocorrelation across your 10 periods. Basically, your 10 data points on each country aren't worth as much as if they were 10 randomly chosen independent and identicall distributed points. I'm not aware of a widely available software solution to autocorrelation in the residuals of a multilevel model with a non-Normal response. Certainly it isn't implemented in lme4. Others may know more than me. | Question about logistic regression
This is actually an extremely sophisticated problem and a tough ask from your lecturer!
In terms of how you organise your data, a 1070 x 10 rectangle is fine. For example, in R:
> conflict.data <- da |
20,597 | Question about logistic regression | This tutorial is comprehensive.
In R, you need to prepare your data, say variable data in a data.frame, the first column of which is your 0-1 variable (conflict) and the other columns are the predictors. For categorical variables, you must make sure that they are of type factor. To make sure that column 3, say, has this property, you can enforce by data[,3] <- as.factor(data[,3]).
Then it is only a matter of
glm(data, family="binomial")
This implicitly assumes that you have an additive model and gives you the estimated values. To get a more comprehensive output, with test for individual parameters, you can do
summary(glm(data, family="binomial")) | Question about logistic regression | This tutorial is comprehensive.
In R, you need to prepare your data, say variable data in a data.frame, the first column of which is your 0-1 variable (conflict) and the other columns are the predicto | Question about logistic regression
This tutorial is comprehensive.
In R, you need to prepare your data, say variable data in a data.frame, the first column of which is your 0-1 variable (conflict) and the other columns are the predictors. For categorical variables, you must make sure that they are of type factor. To make sure that column 3, say, has this property, you can enforce by data[,3] <- as.factor(data[,3]).
Then it is only a matter of
glm(data, family="binomial")
This implicitly assumes that you have an additive model and gives you the estimated values. To get a more comprehensive output, with test for individual parameters, you can do
summary(glm(data, family="binomial")) | Question about logistic regression
This tutorial is comprehensive.
In R, you need to prepare your data, say variable data in a data.frame, the first column of which is your 0-1 variable (conflict) and the other columns are the predicto |
20,598 | Cross Validation for mixed models? | Fang (2011) has demonstrated asymptotic equivalence between AIC applied to mixed models and leave-one-cluster-out cross validation. Possibly this would satisfy your reviewer, permitting you to simply compute AIC as an easier-to-compute approximation to what they requested? | Cross Validation for mixed models? | Fang (2011) has demonstrated asymptotic equivalence between AIC applied to mixed models and leave-one-cluster-out cross validation. Possibly this would satisfy your reviewer, permitting you to simply | Cross Validation for mixed models?
Fang (2011) has demonstrated asymptotic equivalence between AIC applied to mixed models and leave-one-cluster-out cross validation. Possibly this would satisfy your reviewer, permitting you to simply compute AIC as an easier-to-compute approximation to what they requested? | Cross Validation for mixed models?
Fang (2011) has demonstrated asymptotic equivalence between AIC applied to mixed models and leave-one-cluster-out cross validation. Possibly this would satisfy your reviewer, permitting you to simply |
20,599 | Cross Validation for mixed models? | Colby and Bair (2013) had developed a cross-validation approach that can be applied to nonlinear mixed effects models. You can visit this link to learn more. | Cross Validation for mixed models? | Colby and Bair (2013) had developed a cross-validation approach that can be applied to nonlinear mixed effects models. You can visit this link to learn more. | Cross Validation for mixed models?
Colby and Bair (2013) had developed a cross-validation approach that can be applied to nonlinear mixed effects models. You can visit this link to learn more. | Cross Validation for mixed models?
Colby and Bair (2013) had developed a cross-validation approach that can be applied to nonlinear mixed effects models. You can visit this link to learn more. |
20,600 | Methods for fitting a "simple" measurement error model | There are a range of possibilities described by J.W. Gillard in An Historical Overview
of Linear Regression with Errors in both Variables
If you are not interested in details or reasons for choosing one method over another, just go with the simplest, which is to draw the line through the centroid $(\bar{x},\bar{y})$ with slope $\hat{\beta}=s_y/s_x$, i.e. the ratio of the observed standard deviations (making the sign of the slope the same as the sign of the covariance of $x$ and $y$); as you can probably work out, this gives an intercept on the $y$-axis of $\hat{\alpha}=\bar{y}-\hat{\beta}\bar{x}.$
The merits of this particular approach are
it gives the same line comparing $x$ against $y$ as $y$ against $x$,
it is scale-invariant so you do not need to worry about units,
it lies between the two ordinary linear regression lines
it crosses them where they cross each other at the centroid of the observations, and
it is very easy to calculate.
The slope is the geometric mean of the slopes of the two ordinary linear regression slopes. It is also what you would get if you standardised the $x$ and $y$ observations, drew a line at 45° (or 135° if there is negative correlation) and then de-standardised the line. It could also be seen as equivalent to making an implicit assumption that the variances of the two sets of errors are proportional to the variances of the two sets of observations; as far as I can tell, you claim not to know which way this is wrong.
Here is some R code to illustrate: the red line in the chart is OLS regression of $Y$ on $X$, the blue line is OLS regression of $X$ on $Y$, and the green line is this simple method. Note that the slope should be about 5.
X0 <- 1600:3600
Y0 <- 5*X0 + 700
X1 <- X0 + 400*rnorm(2001)
Y1 <- Y0 + 2000*rnorm(2001)
slopeOLSXY <- lm(Y1 ~ X1)$coefficients[2] #OLS slope of Y on X
slopeOLSYX <- 1/lm(X1 ~ Y1)$coefficients[2] #Inverse of OLS slope of X on Y
slopesimple <- sd(Y1)/sd(X1) *sign(cov(X1,Y1)) #Simple slope
c(slopeOLSXY, slopeOLSYX, slopesimple) #Show the three slopes
plot(Y1~X1)
abline(mean(Y1) - slopeOLSXY * mean(X1), slopeOLSXY, col="red")
abline(mean(Y1) - slopeOLSYX * mean(X1), slopeOLSYX, col="blue")
abline(mean(Y1) - slopesimple * mean(X1), slopesimple, col="green") | Methods for fitting a "simple" measurement error model | There are a range of possibilities described by J.W. Gillard in An Historical Overview
of Linear Regression with Errors in both Variables
If you are not interested in details or reasons for choosing | Methods for fitting a "simple" measurement error model
There are a range of possibilities described by J.W. Gillard in An Historical Overview
of Linear Regression with Errors in both Variables
If you are not interested in details or reasons for choosing one method over another, just go with the simplest, which is to draw the line through the centroid $(\bar{x},\bar{y})$ with slope $\hat{\beta}=s_y/s_x$, i.e. the ratio of the observed standard deviations (making the sign of the slope the same as the sign of the covariance of $x$ and $y$); as you can probably work out, this gives an intercept on the $y$-axis of $\hat{\alpha}=\bar{y}-\hat{\beta}\bar{x}.$
The merits of this particular approach are
it gives the same line comparing $x$ against $y$ as $y$ against $x$,
it is scale-invariant so you do not need to worry about units,
it lies between the two ordinary linear regression lines
it crosses them where they cross each other at the centroid of the observations, and
it is very easy to calculate.
The slope is the geometric mean of the slopes of the two ordinary linear regression slopes. It is also what you would get if you standardised the $x$ and $y$ observations, drew a line at 45° (or 135° if there is negative correlation) and then de-standardised the line. It could also be seen as equivalent to making an implicit assumption that the variances of the two sets of errors are proportional to the variances of the two sets of observations; as far as I can tell, you claim not to know which way this is wrong.
Here is some R code to illustrate: the red line in the chart is OLS regression of $Y$ on $X$, the blue line is OLS regression of $X$ on $Y$, and the green line is this simple method. Note that the slope should be about 5.
X0 <- 1600:3600
Y0 <- 5*X0 + 700
X1 <- X0 + 400*rnorm(2001)
Y1 <- Y0 + 2000*rnorm(2001)
slopeOLSXY <- lm(Y1 ~ X1)$coefficients[2] #OLS slope of Y on X
slopeOLSYX <- 1/lm(X1 ~ Y1)$coefficients[2] #Inverse of OLS slope of X on Y
slopesimple <- sd(Y1)/sd(X1) *sign(cov(X1,Y1)) #Simple slope
c(slopeOLSXY, slopeOLSYX, slopesimple) #Show the three slopes
plot(Y1~X1)
abline(mean(Y1) - slopeOLSXY * mean(X1), slopeOLSXY, col="red")
abline(mean(Y1) - slopeOLSYX * mean(X1), slopeOLSYX, col="blue")
abline(mean(Y1) - slopesimple * mean(X1), slopesimple, col="green") | Methods for fitting a "simple" measurement error model
There are a range of possibilities described by J.W. Gillard in An Historical Overview
of Linear Regression with Errors in both Variables
If you are not interested in details or reasons for choosing |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.