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
|
|---|---|---|---|---|---|---|
9,101
|
Introduction to structural equation modeling
|
Jarrett Byrnes (jebyrnes here) also has his weeklong SEM intro course materials posted here: http://byrneslab.net/teaching/sem/
The course is intended for researchers applying SEMs to biological and ecological data but covers general introductions to SEM concepts, R code, and examples so is likely to be helpful to others. I found the material very helpful in starting with almost no knowledge of the approach.
|
Introduction to structural equation modeling
|
Jarrett Byrnes (jebyrnes here) also has his weeklong SEM intro course materials posted here: http://byrneslab.net/teaching/sem/
The course is intended for researchers applying SEMs to biological and e
|
Introduction to structural equation modeling
Jarrett Byrnes (jebyrnes here) also has his weeklong SEM intro course materials posted here: http://byrneslab.net/teaching/sem/
The course is intended for researchers applying SEMs to biological and ecological data but covers general introductions to SEM concepts, R code, and examples so is likely to be helpful to others. I found the material very helpful in starting with almost no knowledge of the approach.
|
Introduction to structural equation modeling
Jarrett Byrnes (jebyrnes here) also has his weeklong SEM intro course materials posted here: http://byrneslab.net/teaching/sem/
The course is intended for researchers applying SEMs to biological and e
|
9,102
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
There's only one Mr Tripletoddletrouble. In fact, unless he has
a son to pass his surname down to, he'll be the last
Mr Tripletoddletrouble. Social mores of his time and place sadly
disallow even such an exquisite surname to survive by passing through the
female line.
Mr Tripletoddletrouble has a rare and mathematically convenient
genetic condition, which any future generations of
Tripletoddletroubles will inherit: if he fathers any sons at all,
and there's a 50% chance he will, it will be one set of triplets.
So at every step of the family tree we see, equally likely, either three sons or none.
The bad news for
onomatologists is
this leaves a 50% chance of a wonderful name becoming extinct among the
next generation. The good news is that every Mr
Tripletoddletrouble has, on average, 1.5 sons — since this is
safely above one, the expected population of Tripletoddletroubles enjoys
exponential growth, and there is a positive probability their surname
will survive forever.
What's the probability that the Tripletoddletrouble surname will, eventually, become extinct?
Here's a quick R simulation.
set.seed(123)
nsims <- 1e5
ngens <- 20
simulate_extinction <- function(ngens) {
nsurvivors <- c(1, rep(NA, ngens - 1))
for (gen in seq_len(ngens - 1)) {
nsurvivors[gen + 1] <- 3 * rbinom(1, nsurvivors[gen], 0.5)
}
extinct <- (!is.na(nsurvivors) & nsurvivors == 0) # rbinom gives NA if population huge
return(extinct)
}
pextinct <- rowMeans(replicate(n = nsims, simulate_extinction(ngens)))
plot(pextinct, xlab = "Generation number", ylab = "Probability of extinction")
abline(h = (sqrt(5) - 1)/2, col = "red")
sprintf("Estimated probability of extinction = %f", pextinct[ngens])
The red line in the plot is at
$$\varphi - 1 = \varphi^{-1} = \frac{\sqrt{5} - 1}{2} \approx 0.618034 $$
[1] "Estimated probability of extinction = 0.618150"
This is a question about branching processes. Indeed, one of the earliest investigations into their stochastic behaviour originated in Victorian concerns about the extinction of unusual surnames. The resulting Galton-Watson process paper is available online:
Galton, F., & Watson, H. W. (1875). "On the probability of the extinction of families". Journal of the Royal Anthropological Institute, 4, 138–144.
"Either 3 or 0 offspring, equally likely" is arguably the simplest branching process with non-trivial probability of extinction. We need at least two outcomes if chance is to play a role, including zero offspring for extinction to be possible. "Either 1 or 0 offspring" is clearly doomed: with no branches budding off, the family line becomes extinct the first time there are no sons. "Either 2 or 0 offspring, equally likely" gives a mean of exactly one offspring to replace each individual. When fate balances on this knife-edge, it turns out extinction is certain in the long run, even if the family tree successfully buds a few times. We could tweak the offspring distribution to produce a range of desired extinction probabilities, but only by introducing unequal probabilities or more than two outcomes. This set-up doesn't feel artificially "tuned" to shoe-horn in the golden ratio.
Let's find the probability of ultimate extinction, $\theta$, algebraically. Intuitively, this probability splits into two parts: either the original Mr Tripletoddletrouble has no sons and his line becomes extinct immediately, or he successfully has three sons, but each of their three lines eventually becomes extinct. Since a son is in the same position as the original Mr Tripletoddletrouble, their lines also each have extinction probability $\theta$. Since we are concerned only with direct male descendants, each line's fate is independent of the others. Given that there are three sons, the probability the surname becomes extinct is therefore $\theta^3$.
From the tree diagram, we see the probability of extinction $\theta$ must obey the equation
$$\theta = \frac{1}{2} + \frac{1}{2}\theta^3 \tag{1}$$
which we can solve (and will, shortly). First let's tie this into some wider theory of branching processes. The number of offspring of any individual is a random variable with probability distribution $p_0 = p_3 = 0.5$ and $p_n = 0$ otherwise, so its probability generating function is:
$$\Pi(s) = \sum_n p_n s^n = \frac{1}{2} + \frac{1}{2} s^3 $$
Looks familiar? No coincidence. More later. By evaluating the derivative of the pgf at $s=1$, we get the mean number of offspring. This number $R_0 = \Pi'(1)$ is important in population ecology and human demography, where it's called the net reproduction rate (it's usually defined as the mean number of daughters produced by each female, rather than sons by each male — maternity is easier to track than paternity, and in many species females can reproduce by parthenogenesis), while in epidemiology it's the basic reproduction number (mean number of infections directly generated by one infected individual, in a fully susceptible population). If $\Pi'(1) \leq 1$ then ultimate extinction is certain. If $\Pi'(1) \gt 1$ the probability of extinction is below one. We have
$$\Pi'(s) = \frac{3s^2}{2} \implies \Pi'(1) = 1.5 > 1$$
so the surname has positive probability of survival. How many Tripletoddletroubles survive in each generation? Take one individual as "generation zero", and let $Z_n$ be the number of descendants after $n$ generations. $Z_n$ is a random variable whose probability distribution can be read off from the coefficients of its pgf $\Pi_{n}(s)$, which we find by iteratively applying $\Pi$, the offspring pgf, $n$ times:
$$\Pi_{n}(s) = \Pi(\dots\Pi(\Pi(s))\dots) $$
Why? $Z_{n}$ is the sum of the offspring of the $Z_{n-1}$ survivors in the previous generation. The numbers of offspring from each survivor are independent, identically distributed (iid) random variables with pgf $\Pi$, and the number of them we are adding up has pgf $\Pi_{n-1}$, so by the rule for the pgf of the sum of a random number of iid variables (proof in this answer), $Z_n$ has pgf $\Pi_{n}(s) = \Pi_{n-1}(\Pi(s))$. For example, after two generations
$$\Pi_2(s) = \Pi(\Pi(s)) = \frac{1}{2} + \frac{1}{2} \left(\frac{1}{2} + \frac{s^3}{2} \right)^3 = \frac{9}{16} + \frac{3s^3}{16} + \frac{3s^6}{16} + \frac{s^9}{16} $$
so there's a $\frac{1}{16}$ chance of nine descendants but $\Pi_2(0) = \frac{9}{16}$ chance that extinction has already occurred. $\mathbb{E}(Z_2)$, the expected number of descendants after two generations, is found by $\Pi'_2(1) = 2.25$. It's no coincidence this equals $1.5^2$.
The mean and variance of the number of offspring from a single individual are $\mu = \Pi'(1)$ and $\sigma^2 = \Pi''(1) + \mu - \mu^2$. You can prove by induction that $\mathbb{E}(Z_n) = \mu^n$. Now it's obvious why ultimate extinction is certain when $\mu < 1$. With $\mu = 1.5$ we see exponential growth on average, despite our high chance of early extinction. Essentially, chains of surname transmission tend to either fizzle out or blow up, and $\mu = 1.5$ guarantees enough chance of blowing up that extinction is not inevitable. Good news for the Tripletoddletroubles; bad news if we switch context from surnames to infectious diseases with $R_0 > 1$. The way chains of infection can randomly either "go big or go home", rather than follow a deterministic rule like "each case infects exactly two susceptibles", relates to the epidemiological idea of overdispersion due to clustering or super-spreading events. The variance of the number of descendants after $n$ generations can be considerable, as $Z_n$ might be enormous or zero. Again by induction, we find:
$$\operatorname{Var}(Z_n) =
\begin{cases}
\frac{\mu^{n-1} \sigma^2 \left(\mu^n - 1\right)}{\mu - 1}, & \mu \neq 1 \\[2ex]
n \sigma^2, & \mu = 1
\end{cases}$$
In general, the probability of ultimate extinction is the smallest positive solution, $\theta^{*}$, of the equation $\theta = \Pi(\theta)$. That's exactly equation $(1)$ we derived above! But how did we know which solution to take? The probability of extinction by generation $n$ is $\Pi_n(0)$, since that's the constant or $s^0$ term of the pgf of $Z_n$, hence represents $\Pr(Z_n = 0)$. The probability of ultimate extinction must be $\lim_{n \to \infty} \Pi_n(0)$ which we can find using a cobweb plot of $y=\Pi(x)$ and $y=x$ for $0 \le x \le 1$. Since $\Pi(0) = p_0$, the probability an individual has no offspring, we can assume the y-intercept is between $0 \lt \Pi(0) \le 1$ (if $p_0 = 0$ then extinction is clearly impossible). So $y = \Pi(x)$ starts above $y=x$, and the first time it intersects $y=x$ must be from above. Since $\Pi(x)$ and its derivatives have only non-negative coefficients, its graph is increasing and convex on $0 \le x \le 1$. This means it can intersect $y=x$ at most twice in this interval: once from above, then again from below. $\Pi(1) = \sum p_n = 1$ so the graphs certainly intersect at $(1,1)$.
This intersection's nature depends on the slope $\Pi'(1)$, which represents the mean number of offspring $\mu$ (biologically, $R_0$). If $\Pi'(1) > 1$ it must be steeper than $y=x$ so $y = \Pi(x)$ is hitting the line from below, in which case there must have been an earlier intersection in $0 \lt x \lt 1$. If $\Pi'(1) < 1$ it's shallower so hitting from above, and there's no earlier root. If $\Pi'(1) = 1$ the two curves just touch at $(1,1)$, but $y = \Pi(x)$ must have been shallower before (its average slope over $0 \le x \le 1$ is $1 - p_0$ so below one), hence approaches the line from above and there can be no earlier root. This is why if $\mu=1$ but $p_0 > 0$, ultimate extinction has probability one.
To find $\lim_{n \to \infty} \Pi_n(0)$ graphically, read off horizontally from the y-intercept at $y = \Pi(0)$ to the $y=x$ line, where now $x = \Pi(0)$. Then read off vertically to the $y = \Pi(x)$ graph, where now $y = \Pi(\Pi(x)) = \Pi_2(x)$. Read off horizontally to the line so $x = \Pi_2(x)$. Read off vertically to the curve so $y = \Pi(\Pi_2(x)) = \Pi_3(x)$. Note that all horizontal readings are rightwards and vertical readings are upwards, since $y = \Pi(x)$ is increasing so each vertical positions is above the previous one. This procedure must converge to the first (i.e. smallest positive $x$) intersection point $x = \Pi(x)$, where $y = \Pi(x)$ hits $y = x$ from above. We illustrate the three cases $\mu = 1.5$ ($p_0 = p_3 = \frac{1}{2}$), $\mu = 1$ ($p_0 = \frac{2}{3}, p_3 = \frac{1}{3}$) and $\mu = 0.5$ ($p_0 = \frac{5}{6}, p_3 = \frac{1}{6}$). The dotted blue line is the tangent to $y = \Pi(x)$ at $(1, 1)$, and shows the role of its slope $\Pi'(1) = \mu$ in determining whether there was an earlier intersection.
We need the smallest positive solution $\theta*$ of $(1)$. Moving $\theta$ to the right-hand side and doubling to clear out the fractions, we obtain:
$$0 = \theta^3 - 2 \theta + 1 = (\theta - 1)(\theta^2 + \theta - 1)$$
The solutions are $-\varphi < \varphi^{-1} < 1$ so the smallest positive solution is $\theta^{*} = \varphi^{-1}$.
Time to reveal the "fiddle". This link to the golden ratio isn't a result
I recall seeing before,
but I reverse-engineered it by thinking about the required factorisation of
the final equation. Since
$\Pi(1) = \sum p_n = 1$, we always have $\theta = 1$ as a root of
$\theta = \Pi(\theta)$, so $(\theta - 1)$ must appear as a factor once we
set one side to zero. I also knew what quadratic I wanted to see.
After that I worked back to try to form a valid pgf. Negative
coefficients are disallowed; positive coefficients just
needed normalising so they sum to unity. I hoped
that the resulting probability distribution for the offspring would be
a "nice" one — which I think it is!
R code for cobweb plot
ngens <- 100
par(mfrow=c(1, 3), pty = "s", xaxs = "i", yaxs = "i")
for(p0 in c(1/2, 2/3, 5/6)) {
pgf <- function(x) {p0 + (1-p0)*x^3}
mu <- p0*0 + (1-p0)*3
plot(pgf, xlim = c(0,1), ylim = c(0,1), xlab = "", ylab = "",
main = paste0("Mean offspring = ", mu))
segments(0, 0, 1, 1)
abline(1 - mu, mu, col = "blue", lty = "dotted")
pextinct <- c(0, rep(NA, ngens))
for (n in seq_len(ngens)) {
pextinct[n + 1] <- pgf(pextinct[n])
segments(pextinct[n], pextinct[n], pextinct[n], pextinct[n + 1], col = "red")
segments(pextinct[n], pextinct[n + 1], pextinct[n + 1], pextinct[n + 1], col = "red")
}
print(pextinct)
}
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
There's only one Mr Tripletoddletrouble. In fact, unless he has
a son to pass his surname down to, he'll be the last
Mr Tripletoddletrouble. Social mores of his time and place sadly
disallow even such
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
There's only one Mr Tripletoddletrouble. In fact, unless he has
a son to pass his surname down to, he'll be the last
Mr Tripletoddletrouble. Social mores of his time and place sadly
disallow even such an exquisite surname to survive by passing through the
female line.
Mr Tripletoddletrouble has a rare and mathematically convenient
genetic condition, which any future generations of
Tripletoddletroubles will inherit: if he fathers any sons at all,
and there's a 50% chance he will, it will be one set of triplets.
So at every step of the family tree we see, equally likely, either three sons or none.
The bad news for
onomatologists is
this leaves a 50% chance of a wonderful name becoming extinct among the
next generation. The good news is that every Mr
Tripletoddletrouble has, on average, 1.5 sons — since this is
safely above one, the expected population of Tripletoddletroubles enjoys
exponential growth, and there is a positive probability their surname
will survive forever.
What's the probability that the Tripletoddletrouble surname will, eventually, become extinct?
Here's a quick R simulation.
set.seed(123)
nsims <- 1e5
ngens <- 20
simulate_extinction <- function(ngens) {
nsurvivors <- c(1, rep(NA, ngens - 1))
for (gen in seq_len(ngens - 1)) {
nsurvivors[gen + 1] <- 3 * rbinom(1, nsurvivors[gen], 0.5)
}
extinct <- (!is.na(nsurvivors) & nsurvivors == 0) # rbinom gives NA if population huge
return(extinct)
}
pextinct <- rowMeans(replicate(n = nsims, simulate_extinction(ngens)))
plot(pextinct, xlab = "Generation number", ylab = "Probability of extinction")
abline(h = (sqrt(5) - 1)/2, col = "red")
sprintf("Estimated probability of extinction = %f", pextinct[ngens])
The red line in the plot is at
$$\varphi - 1 = \varphi^{-1} = \frac{\sqrt{5} - 1}{2} \approx 0.618034 $$
[1] "Estimated probability of extinction = 0.618150"
This is a question about branching processes. Indeed, one of the earliest investigations into their stochastic behaviour originated in Victorian concerns about the extinction of unusual surnames. The resulting Galton-Watson process paper is available online:
Galton, F., & Watson, H. W. (1875). "On the probability of the extinction of families". Journal of the Royal Anthropological Institute, 4, 138–144.
"Either 3 or 0 offspring, equally likely" is arguably the simplest branching process with non-trivial probability of extinction. We need at least two outcomes if chance is to play a role, including zero offspring for extinction to be possible. "Either 1 or 0 offspring" is clearly doomed: with no branches budding off, the family line becomes extinct the first time there are no sons. "Either 2 or 0 offspring, equally likely" gives a mean of exactly one offspring to replace each individual. When fate balances on this knife-edge, it turns out extinction is certain in the long run, even if the family tree successfully buds a few times. We could tweak the offspring distribution to produce a range of desired extinction probabilities, but only by introducing unequal probabilities or more than two outcomes. This set-up doesn't feel artificially "tuned" to shoe-horn in the golden ratio.
Let's find the probability of ultimate extinction, $\theta$, algebraically. Intuitively, this probability splits into two parts: either the original Mr Tripletoddletrouble has no sons and his line becomes extinct immediately, or he successfully has three sons, but each of their three lines eventually becomes extinct. Since a son is in the same position as the original Mr Tripletoddletrouble, their lines also each have extinction probability $\theta$. Since we are concerned only with direct male descendants, each line's fate is independent of the others. Given that there are three sons, the probability the surname becomes extinct is therefore $\theta^3$.
From the tree diagram, we see the probability of extinction $\theta$ must obey the equation
$$\theta = \frac{1}{2} + \frac{1}{2}\theta^3 \tag{1}$$
which we can solve (and will, shortly). First let's tie this into some wider theory of branching processes. The number of offspring of any individual is a random variable with probability distribution $p_0 = p_3 = 0.5$ and $p_n = 0$ otherwise, so its probability generating function is:
$$\Pi(s) = \sum_n p_n s^n = \frac{1}{2} + \frac{1}{2} s^3 $$
Looks familiar? No coincidence. More later. By evaluating the derivative of the pgf at $s=1$, we get the mean number of offspring. This number $R_0 = \Pi'(1)$ is important in population ecology and human demography, where it's called the net reproduction rate (it's usually defined as the mean number of daughters produced by each female, rather than sons by each male — maternity is easier to track than paternity, and in many species females can reproduce by parthenogenesis), while in epidemiology it's the basic reproduction number (mean number of infections directly generated by one infected individual, in a fully susceptible population). If $\Pi'(1) \leq 1$ then ultimate extinction is certain. If $\Pi'(1) \gt 1$ the probability of extinction is below one. We have
$$\Pi'(s) = \frac{3s^2}{2} \implies \Pi'(1) = 1.5 > 1$$
so the surname has positive probability of survival. How many Tripletoddletroubles survive in each generation? Take one individual as "generation zero", and let $Z_n$ be the number of descendants after $n$ generations. $Z_n$ is a random variable whose probability distribution can be read off from the coefficients of its pgf $\Pi_{n}(s)$, which we find by iteratively applying $\Pi$, the offspring pgf, $n$ times:
$$\Pi_{n}(s) = \Pi(\dots\Pi(\Pi(s))\dots) $$
Why? $Z_{n}$ is the sum of the offspring of the $Z_{n-1}$ survivors in the previous generation. The numbers of offspring from each survivor are independent, identically distributed (iid) random variables with pgf $\Pi$, and the number of them we are adding up has pgf $\Pi_{n-1}$, so by the rule for the pgf of the sum of a random number of iid variables (proof in this answer), $Z_n$ has pgf $\Pi_{n}(s) = \Pi_{n-1}(\Pi(s))$. For example, after two generations
$$\Pi_2(s) = \Pi(\Pi(s)) = \frac{1}{2} + \frac{1}{2} \left(\frac{1}{2} + \frac{s^3}{2} \right)^3 = \frac{9}{16} + \frac{3s^3}{16} + \frac{3s^6}{16} + \frac{s^9}{16} $$
so there's a $\frac{1}{16}$ chance of nine descendants but $\Pi_2(0) = \frac{9}{16}$ chance that extinction has already occurred. $\mathbb{E}(Z_2)$, the expected number of descendants after two generations, is found by $\Pi'_2(1) = 2.25$. It's no coincidence this equals $1.5^2$.
The mean and variance of the number of offspring from a single individual are $\mu = \Pi'(1)$ and $\sigma^2 = \Pi''(1) + \mu - \mu^2$. You can prove by induction that $\mathbb{E}(Z_n) = \mu^n$. Now it's obvious why ultimate extinction is certain when $\mu < 1$. With $\mu = 1.5$ we see exponential growth on average, despite our high chance of early extinction. Essentially, chains of surname transmission tend to either fizzle out or blow up, and $\mu = 1.5$ guarantees enough chance of blowing up that extinction is not inevitable. Good news for the Tripletoddletroubles; bad news if we switch context from surnames to infectious diseases with $R_0 > 1$. The way chains of infection can randomly either "go big or go home", rather than follow a deterministic rule like "each case infects exactly two susceptibles", relates to the epidemiological idea of overdispersion due to clustering or super-spreading events. The variance of the number of descendants after $n$ generations can be considerable, as $Z_n$ might be enormous or zero. Again by induction, we find:
$$\operatorname{Var}(Z_n) =
\begin{cases}
\frac{\mu^{n-1} \sigma^2 \left(\mu^n - 1\right)}{\mu - 1}, & \mu \neq 1 \\[2ex]
n \sigma^2, & \mu = 1
\end{cases}$$
In general, the probability of ultimate extinction is the smallest positive solution, $\theta^{*}$, of the equation $\theta = \Pi(\theta)$. That's exactly equation $(1)$ we derived above! But how did we know which solution to take? The probability of extinction by generation $n$ is $\Pi_n(0)$, since that's the constant or $s^0$ term of the pgf of $Z_n$, hence represents $\Pr(Z_n = 0)$. The probability of ultimate extinction must be $\lim_{n \to \infty} \Pi_n(0)$ which we can find using a cobweb plot of $y=\Pi(x)$ and $y=x$ for $0 \le x \le 1$. Since $\Pi(0) = p_0$, the probability an individual has no offspring, we can assume the y-intercept is between $0 \lt \Pi(0) \le 1$ (if $p_0 = 0$ then extinction is clearly impossible). So $y = \Pi(x)$ starts above $y=x$, and the first time it intersects $y=x$ must be from above. Since $\Pi(x)$ and its derivatives have only non-negative coefficients, its graph is increasing and convex on $0 \le x \le 1$. This means it can intersect $y=x$ at most twice in this interval: once from above, then again from below. $\Pi(1) = \sum p_n = 1$ so the graphs certainly intersect at $(1,1)$.
This intersection's nature depends on the slope $\Pi'(1)$, which represents the mean number of offspring $\mu$ (biologically, $R_0$). If $\Pi'(1) > 1$ it must be steeper than $y=x$ so $y = \Pi(x)$ is hitting the line from below, in which case there must have been an earlier intersection in $0 \lt x \lt 1$. If $\Pi'(1) < 1$ it's shallower so hitting from above, and there's no earlier root. If $\Pi'(1) = 1$ the two curves just touch at $(1,1)$, but $y = \Pi(x)$ must have been shallower before (its average slope over $0 \le x \le 1$ is $1 - p_0$ so below one), hence approaches the line from above and there can be no earlier root. This is why if $\mu=1$ but $p_0 > 0$, ultimate extinction has probability one.
To find $\lim_{n \to \infty} \Pi_n(0)$ graphically, read off horizontally from the y-intercept at $y = \Pi(0)$ to the $y=x$ line, where now $x = \Pi(0)$. Then read off vertically to the $y = \Pi(x)$ graph, where now $y = \Pi(\Pi(x)) = \Pi_2(x)$. Read off horizontally to the line so $x = \Pi_2(x)$. Read off vertically to the curve so $y = \Pi(\Pi_2(x)) = \Pi_3(x)$. Note that all horizontal readings are rightwards and vertical readings are upwards, since $y = \Pi(x)$ is increasing so each vertical positions is above the previous one. This procedure must converge to the first (i.e. smallest positive $x$) intersection point $x = \Pi(x)$, where $y = \Pi(x)$ hits $y = x$ from above. We illustrate the three cases $\mu = 1.5$ ($p_0 = p_3 = \frac{1}{2}$), $\mu = 1$ ($p_0 = \frac{2}{3}, p_3 = \frac{1}{3}$) and $\mu = 0.5$ ($p_0 = \frac{5}{6}, p_3 = \frac{1}{6}$). The dotted blue line is the tangent to $y = \Pi(x)$ at $(1, 1)$, and shows the role of its slope $\Pi'(1) = \mu$ in determining whether there was an earlier intersection.
We need the smallest positive solution $\theta*$ of $(1)$. Moving $\theta$ to the right-hand side and doubling to clear out the fractions, we obtain:
$$0 = \theta^3 - 2 \theta + 1 = (\theta - 1)(\theta^2 + \theta - 1)$$
The solutions are $-\varphi < \varphi^{-1} < 1$ so the smallest positive solution is $\theta^{*} = \varphi^{-1}$.
Time to reveal the "fiddle". This link to the golden ratio isn't a result
I recall seeing before,
but I reverse-engineered it by thinking about the required factorisation of
the final equation. Since
$\Pi(1) = \sum p_n = 1$, we always have $\theta = 1$ as a root of
$\theta = \Pi(\theta)$, so $(\theta - 1)$ must appear as a factor once we
set one side to zero. I also knew what quadratic I wanted to see.
After that I worked back to try to form a valid pgf. Negative
coefficients are disallowed; positive coefficients just
needed normalising so they sum to unity. I hoped
that the resulting probability distribution for the offspring would be
a "nice" one — which I think it is!
R code for cobweb plot
ngens <- 100
par(mfrow=c(1, 3), pty = "s", xaxs = "i", yaxs = "i")
for(p0 in c(1/2, 2/3, 5/6)) {
pgf <- function(x) {p0 + (1-p0)*x^3}
mu <- p0*0 + (1-p0)*3
plot(pgf, xlim = c(0,1), ylim = c(0,1), xlab = "", ylab = "",
main = paste0("Mean offspring = ", mu))
segments(0, 0, 1, 1)
abline(1 - mu, mu, col = "blue", lty = "dotted")
pextinct <- c(0, rep(NA, ngens))
for (n in seq_len(ngens)) {
pextinct[n + 1] <- pgf(pextinct[n])
segments(pextinct[n], pextinct[n], pextinct[n], pextinct[n + 1], col = "red")
segments(pextinct[n], pextinct[n + 1], pextinct[n + 1], pextinct[n + 1], col = "red")
}
print(pextinct)
}
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
There's only one Mr Tripletoddletrouble. In fact, unless he has
a son to pass his surname down to, he'll be the last
Mr Tripletoddletrouble. Social mores of his time and place sadly
disallow even such
|
9,103
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
Because you are looking for "unexpected" solutions, permit me to offer one before explaining it.
This is working R code to estimate $\varphi=(1+\sqrt{5})/2$ from iid uniform values and relatively simple (algebraic) calculations:
u <- runif(1e6)
v <- runif(length(u))
median((v/u)[u^2 + v^2 <= 1 & u <= 2*v])
1.61998
This procedure, which was inspired by the geometric nature of Buffon's needle experiment, can likewise be illustrated geometrically. It samples the blue portion of the unit square lying above the line of slope 1/2, u <= 2*v, enclosed within the unit circle u^2 + v^2 <= 1. The median slope of the sampled points estimates $\varphi,$ as simple trigonometric calculations will affirm. Thus, you throw darts at the square dartboard and after you're tired of that, sweep counterclockwise through the points landing in the blue sector until you have encountered half of them: the slope you have attained estimates $\varphi.$ Since approximately $7\pi/40 \approx 55\%$ of the points will fall in the blue sector, this rejection sampling method is reasonably efficient.
There are many equivalent ways to run this experiment, some of which are a little more efficient, such as
z <- qt(runif(1e6, 1/2, pt(2,1)), 1)
p <- median(z)
(1 + p + 1/(7*p)) * 7/8
1.61731
This method generates the slopes directly from a Cauchy (Student t) distribution and uses the relationship $\varphi = 1/\varphi$ to generate two inversely related estimates; a suitably weighted linear combination of them has lower variance (and therefore greater precision) than either estimate alone. (The weights are approximate, chosen empirically.)
Finally, I confess there is a "tuning parameter" in this setup (as there must be): by varying the magic value $x=2$ in the condition u <= 2*v you can estimate the quadratic number $(1 + \sqrt{1 + x^2})/x.$ A quick demonstration is based on a half-angle formula for the tangent. Let $0\lt \theta\lt \pi/2$ be the angular measure of the blue sector. With $x=\tan\theta,$
$$x = \tan\theta= \frac{2 \tan(\theta/2)}{\tan^2(\theta/2) - 1}.$$
Geometrically, this sampling procedure estimates the reciprocal slope of half the sector's angle, $1/\phi = \cot(\theta/2)$ (or, reversing the roles of u, and v, it estimates $\phi = \tan(\theta/2)$). Thus, in algebraic terms it finds a solution of the equation
$$x = \frac{2\phi}{\phi^2-1}$$
which is equivalent to
$$\phi^2 + \frac{2}{x}\phi - 1 = 0$$
and the claim follows from the Quadratic Formula.
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
Because you are looking for "unexpected" solutions, permit me to offer one before explaining it.
This is working R code to estimate $\varphi=(1+\sqrt{5})/2$ from iid uniform values and relatively simp
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
Because you are looking for "unexpected" solutions, permit me to offer one before explaining it.
This is working R code to estimate $\varphi=(1+\sqrt{5})/2$ from iid uniform values and relatively simple (algebraic) calculations:
u <- runif(1e6)
v <- runif(length(u))
median((v/u)[u^2 + v^2 <= 1 & u <= 2*v])
1.61998
This procedure, which was inspired by the geometric nature of Buffon's needle experiment, can likewise be illustrated geometrically. It samples the blue portion of the unit square lying above the line of slope 1/2, u <= 2*v, enclosed within the unit circle u^2 + v^2 <= 1. The median slope of the sampled points estimates $\varphi,$ as simple trigonometric calculations will affirm. Thus, you throw darts at the square dartboard and after you're tired of that, sweep counterclockwise through the points landing in the blue sector until you have encountered half of them: the slope you have attained estimates $\varphi.$ Since approximately $7\pi/40 \approx 55\%$ of the points will fall in the blue sector, this rejection sampling method is reasonably efficient.
There are many equivalent ways to run this experiment, some of which are a little more efficient, such as
z <- qt(runif(1e6, 1/2, pt(2,1)), 1)
p <- median(z)
(1 + p + 1/(7*p)) * 7/8
1.61731
This method generates the slopes directly from a Cauchy (Student t) distribution and uses the relationship $\varphi = 1/\varphi$ to generate two inversely related estimates; a suitably weighted linear combination of them has lower variance (and therefore greater precision) than either estimate alone. (The weights are approximate, chosen empirically.)
Finally, I confess there is a "tuning parameter" in this setup (as there must be): by varying the magic value $x=2$ in the condition u <= 2*v you can estimate the quadratic number $(1 + \sqrt{1 + x^2})/x.$ A quick demonstration is based on a half-angle formula for the tangent. Let $0\lt \theta\lt \pi/2$ be the angular measure of the blue sector. With $x=\tan\theta,$
$$x = \tan\theta= \frac{2 \tan(\theta/2)}{\tan^2(\theta/2) - 1}.$$
Geometrically, this sampling procedure estimates the reciprocal slope of half the sector's angle, $1/\phi = \cot(\theta/2)$ (or, reversing the roles of u, and v, it estimates $\phi = \tan(\theta/2)$). Thus, in algebraic terms it finds a solution of the equation
$$x = \frac{2\phi}{\phi^2-1}$$
which is equivalent to
$$\phi^2 + \frac{2}{x}\phi - 1 = 0$$
and the claim follows from the Quadratic Formula.
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
Because you are looking for "unexpected" solutions, permit me to offer one before explaining it.
This is working R code to estimate $\varphi=(1+\sqrt{5})/2$ from iid uniform values and relatively simp
|
9,104
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
There is a recursive algorithm that succeeds (outputs heads) with probability $1/\Phi$. It takes advantage of the fact that the continued fraction representation of $\Phi$ has all ones.
The algorithm follows:
Procedure OnePhi(): Returns 1 with probability $1/\Phi.$
Do the following steps repeatedly, until the algorithm returns a number:
Set C = RandomBit() (the flip of a fair coin that shows 1 or 0 with equal probability).
If C = 1, return 1 and stop.
Set D = OnePhi().
If D = 1, return 0 and stop.
The expected number of flips used by the algorithm, $\mathbb{E}[N]$, is $2\Phi$ as shown below, taking note that all the flips are independent:
Each iteration stops the algorithm with probability $p = \frac{1}{2} + (1-\frac{1}{2}) * (1/\Phi)$ (1/2 for step 2 and $1/\Phi$ for step 4).
Thus, the expected number of iterations is $\mathbb{E}[T] = 1/p$ by a well-known rejection sampling argument, since the algorithm doesn't depend on iteration counts.
Each iteration has $1 * \frac{1}{2} + (1 + \mathbb{E}[N]) * \frac{1}{2}$ coin flips on average, so the whole algorithm has $\mathbb{E}[N] = (1 * \frac{1}{2} + (1 + \mathbb{E}[N]) * \frac{1}{2}) * \mathbb{E}[T]$ coin flips on average. This equation has the solution $\mathbb{E}[N] = 1 + \sqrt{5} = 2\Phi$.
And on average, because the coin is fair, half of these flips ($\Phi$) show 1 and half show 0.
The following Python code shows this:
import random
def onephi(flips):
# Flips stores counts on the number of times
# the coin was flipped and the number of tails.
# Flips is not essential to the algorithm and
# can be omitted.
done=-1
while done==-1:
flips[0]+=1
if random.random()<0.5:
done=1
else:
flips[1]+=1
if onephi(flips)==1: done=0
return done
flips=[0,0]
c=0
runs=10000000
for _ in range(runs):
c+=onephi(flips)
print("Expected coin flips: %f" % (flips[0]/runs))
print("Expected coin flips showing heads: %f" % (flips[1]/runs))
print("Estimated probability: %f" % (c/runs))
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
There is a recursive algorithm that succeeds (outputs heads) with probability $1/\Phi$. It takes advantage of the fact that the continued fraction representation of $\Phi$ has all ones.
The algorithm
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
There is a recursive algorithm that succeeds (outputs heads) with probability $1/\Phi$. It takes advantage of the fact that the continued fraction representation of $\Phi$ has all ones.
The algorithm follows:
Procedure OnePhi(): Returns 1 with probability $1/\Phi.$
Do the following steps repeatedly, until the algorithm returns a number:
Set C = RandomBit() (the flip of a fair coin that shows 1 or 0 with equal probability).
If C = 1, return 1 and stop.
Set D = OnePhi().
If D = 1, return 0 and stop.
The expected number of flips used by the algorithm, $\mathbb{E}[N]$, is $2\Phi$ as shown below, taking note that all the flips are independent:
Each iteration stops the algorithm with probability $p = \frac{1}{2} + (1-\frac{1}{2}) * (1/\Phi)$ (1/2 for step 2 and $1/\Phi$ for step 4).
Thus, the expected number of iterations is $\mathbb{E}[T] = 1/p$ by a well-known rejection sampling argument, since the algorithm doesn't depend on iteration counts.
Each iteration has $1 * \frac{1}{2} + (1 + \mathbb{E}[N]) * \frac{1}{2}$ coin flips on average, so the whole algorithm has $\mathbb{E}[N] = (1 * \frac{1}{2} + (1 + \mathbb{E}[N]) * \frac{1}{2}) * \mathbb{E}[T]$ coin flips on average. This equation has the solution $\mathbb{E}[N] = 1 + \sqrt{5} = 2\Phi$.
And on average, because the coin is fair, half of these flips ($\Phi$) show 1 and half show 0.
The following Python code shows this:
import random
def onephi(flips):
# Flips stores counts on the number of times
# the coin was flipped and the number of tails.
# Flips is not essential to the algorithm and
# can be omitted.
done=-1
while done==-1:
flips[0]+=1
if random.random()<0.5:
done=1
else:
flips[1]+=1
if onephi(flips)==1: done=0
return done
flips=[0,0]
c=0
runs=10000000
for _ in range(runs):
c+=onephi(flips)
print("Expected coin flips: %f" % (flips[0]/runs))
print("Expected coin flips showing heads: %f" % (flips[1]/runs))
print("Estimated probability: %f" % (c/runs))
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
There is a recursive algorithm that succeeds (outputs heads) with probability $1/\Phi$. It takes advantage of the fact that the continued fraction representation of $\Phi$ has all ones.
The algorithm
|
9,105
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
Here's a quick one. It's related to the branching process from Silverfish's answer.
Run a random walk, starting from height 0, say. At each step, either move up by 2 or move down by 1, with probability 1/2 each.
Count the times at which the current height is below the maximum height so far.
The proportion of such times converges to $\phi$.
import random
t=0; height=0; max=0; nonRecords=0
N=10**7
while(t<N):
height+=random.choice([-1,2])
# increment by -1 or 2 with probability 1/2 each
if height<max: nonRecords+=1
if height>max: max=height
t+=1;
print(nonRecords/t)
print((5**(0.5)-1)/2)
0.6182664
0.6180339887498949
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
Here's a quick one. It's related to the branching process from Silverfish's answer.
Run a random walk, starting from height 0, say. At each step, either move up by 2 or move down by 1, with probabilit
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
Here's a quick one. It's related to the branching process from Silverfish's answer.
Run a random walk, starting from height 0, say. At each step, either move up by 2 or move down by 1, with probability 1/2 each.
Count the times at which the current height is below the maximum height so far.
The proportion of such times converges to $\phi$.
import random
t=0; height=0; max=0; nonRecords=0
N=10**7
while(t<N):
height+=random.choice([-1,2])
# increment by -1 or 2 with probability 1/2 each
if height<max: nonRecords+=1
if height>max: max=height
t+=1;
print(nonRecords/t)
print((5**(0.5)-1)/2)
0.6182664
0.6180339887498949
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
Here's a quick one. It's related to the branching process from Silverfish's answer.
Run a random walk, starting from height 0, say. At each step, either move up by 2 or move down by 1, with probabilit
|
9,106
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
Fibonacci numbers and Markov chains
I remember a question in which the Fibonacci numbers occurred. While computing the waiting time for the probability of flipping '1-0-0' the probabilities of the state '1' and the state '1-0' are Fibonacci numbers (divided by some power of 2).
We can simulate this in several ways
Example 1
Generate random binary numbers of length $n$
Eliminate the numbers with double 1's
Count the fraction of the numbers with a single '1' at the end among the remaining ones
Example code
library(binaryLogic)
set.seed(1)
### string length
n <- 20
### simulation
n_sim <- 10^4
### Step 1 generate random binary numbers (including zero)
x_dec <- sample(0:(2^n-1),n_sim,replace=TRUE)
x_bin <- as.binary(x_dec)
### Step 2 find subselection without double one's
sel <- sapply(x_bin, FUN = function(bx) sum(shiftLeft(as.binary(bx),1) & as.binary(bx))<1)
### Step 3 compute the ratio of odd and even numbers
sum(x_dec[sel] %% 2 == 0)/sum(sel)
### returns 0.6045198
Example 2
This example shows a bit better the similarity with a Markov Chain. Ratio's like these may occur a lot in practice.
Requirements:
1 vase/urn
1 fair coin
a lot of red and blue marbles (or any other tokens to express a binary option)
Algorithm:
Start with some marbles in the vase.
Draw a marble and remove it
Flip twice a coin. For each tails: put a marble of the opposite colour into the vase (opposite to the colour of the removed marble. For each heads: if the removed marble was red, then put a red marble into the vase.
Repeat 2 and 3 untill you are fed up with it.
Count the ratio of red and blue marbles
Example code
### initiate
### we start with some red and blue marbles
set.seed(1)
red <- 5
blue <- 5
### perform step 2 and 3 a lot of times
for (i in 1:10^4) {
### sample from the vase
x <- sample(c("red","blue"),1, prob = c(red,blue))
### coin flips
coinflips <- rbinom(2,1,0.5)
### add and remove marbles
if (x == "blue") {
blue <- blue - 1
red <- red + sum(coinflips)
}
if (x == "red") {
blue <- blue + sum(coinflips)
red <- red - 1 + sum(coinflips == 0)
}
}
### returns 0.6057246
blue/red
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
|
Fibonacci numbers and Markov chains
I remember a question in which the Fibonacci numbers occurred. While computing the waiting time for the probability of flipping '1-0-0' the probabilities of the sta
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
Fibonacci numbers and Markov chains
I remember a question in which the Fibonacci numbers occurred. While computing the waiting time for the probability of flipping '1-0-0' the probabilities of the state '1' and the state '1-0' are Fibonacci numbers (divided by some power of 2).
We can simulate this in several ways
Example 1
Generate random binary numbers of length $n$
Eliminate the numbers with double 1's
Count the fraction of the numbers with a single '1' at the end among the remaining ones
Example code
library(binaryLogic)
set.seed(1)
### string length
n <- 20
### simulation
n_sim <- 10^4
### Step 1 generate random binary numbers (including zero)
x_dec <- sample(0:(2^n-1),n_sim,replace=TRUE)
x_bin <- as.binary(x_dec)
### Step 2 find subselection without double one's
sel <- sapply(x_bin, FUN = function(bx) sum(shiftLeft(as.binary(bx),1) & as.binary(bx))<1)
### Step 3 compute the ratio of odd and even numbers
sum(x_dec[sel] %% 2 == 0)/sum(sel)
### returns 0.6045198
Example 2
This example shows a bit better the similarity with a Markov Chain. Ratio's like these may occur a lot in practice.
Requirements:
1 vase/urn
1 fair coin
a lot of red and blue marbles (or any other tokens to express a binary option)
Algorithm:
Start with some marbles in the vase.
Draw a marble and remove it
Flip twice a coin. For each tails: put a marble of the opposite colour into the vase (opposite to the colour of the removed marble. For each heads: if the removed marble was red, then put a red marble into the vase.
Repeat 2 and 3 untill you are fed up with it.
Count the ratio of red and blue marbles
Example code
### initiate
### we start with some red and blue marbles
set.seed(1)
red <- 5
blue <- 5
### perform step 2 and 3 a lot of times
for (i in 1:10^4) {
### sample from the vase
x <- sample(c("red","blue"),1, prob = c(red,blue))
### coin flips
coinflips <- rbinom(2,1,0.5)
### add and remove marbles
if (x == "blue") {
blue <- blue - 1
red <- red + sum(coinflips)
}
if (x == "red") {
blue <- blue + sum(coinflips)
red <- red - 1 + sum(coinflips == 0)
}
}
### returns 0.6057246
blue/red
|
What are examples of statistical experiments that allow the calculation of the golden ratio?
Fibonacci numbers and Markov chains
I remember a question in which the Fibonacci numbers occurred. While computing the waiting time for the probability of flipping '1-0-0' the probabilities of the sta
|
9,107
|
Does correlation assume stationarity of data?
|
The correlation measures linear relationship. In informal context relationship means something stable. When we calculate the sample correlation for stationary variables and increase the number of available data points this sample correlation tends to true correlation.
It can be shown that for prices, which usually are random walks, the sample correlation tends to random variable. This means that no matter how much data we have, the result will always be different.
Note I tried expressing mathematical intuition without the mathematics. From mathematical point of view the explanation is very clear: Sample moments of stationary processes converge in probability to constants. Sample moments of random walks converge to integrals of brownian motion which are random variables. Since relationship is usually expressed as a number and not a random variable, the reason for not calculating the correlation for non-stationary variables becomes evident.
Update Since we are interested in correlation between two variables assume first that they come from stationary process $Z_t=(X_t,Y_t)$. Stationarity implies that $EZ_t$ and $cov(Z_t,Z_{t-h})$ do not depend on $t$. So correlation
$$corr(X_t,Y_t)=\frac{cov(X_t,Y_t)}{\sqrt{DX_tDY_t}}$$
also does not depend on $t$, since all the quantities in the formula come from matrix $cov(Z_t)$, which does not depend on $t$. So the calculation of sample correlation
$$\hat{\rho}=\frac{\frac{1}{T}\sum_{t=1}^T(X_t-\bar{X})(Y_t-\bar{Y})}{\sqrt{\frac{1}{T^2}\sum_{t=1}^T(X_t-\bar{X})^2\sum_{t=1}^T(Y_t-\bar{Y})^2}}$$
makes sense, since we may have reasonable hope that sample correlation will estimate $\rho=corr(X_t,Y_t)$. It turns out that this hope is not unfounded, since for stationary processes satisfying certain conditions we have that $\hat{\rho}\to\rho$, as $T\to\infty$ in probability. Furthermore $\sqrt{T}(\hat{\rho}-\rho)\to N(0,\sigma_{\rho}^2)$ in distribution, so we can test the hypotheses about $\rho$.
Now suppose that $Z_t$ is not stationary. Then $corr(X_t,Y_t)$ may depend on $t$. So when we observe a sample of size $T$ we potentialy need to estimate $T$ different correlations $\rho_t$. This is of course infeasible, so in best case scenario we only can estimate some functional of $\rho_t$ such as mean or variance. But the result may not have sensible interpretation.
Now let us examine what happens with correlation of probably most studied non-stationary process random walk. We call process $Z_t=(X_t,Y_t)$ a random walk if $Z_t=\sum_{s=1}^t(U_t,V_t)$, where $C_t=(U_t,V_t)$ is a stationary process. For simplicity assume that $EC_t=0$. Then
\begin{align}
corr(X_tY_t)=\frac{EX_tY_t}{\sqrt{DX_tDY_t}}=\frac{E\sum_{s=1}^tU_t\sum_{s=1}^tV_t}{\sqrt{D\sum_{s=1}^tU_tD\sum_{s=1}^tV_t}}
\end{align}
To simplify matters further, assume that $C_t=(U_t,V_t)$ is a white noise. This means that all correlations $E(C_tC_{t+h})$ are zero for $h>0$. Note that this does not restrict $corr(U_t,V_t)$ to zero.
Then
\begin{align}
corr(X_t,Y_t)=\frac{tEU_tV_t}{\sqrt{t^2DU_tDV_t}}=corr(U_0,V_0).
\end{align}
So far so good, though the process is not stationary, correlation makes sense, although we had to make same restrictive assumptions.
Now to see what happens to sample correlation we will need to use the following fact about random walks, called functional central limit theorem:
\begin{align}
\frac{1}{\sqrt{T}}Z_{[Ts]}=\frac{1}{\sqrt{T}}\sum_{t=1}^{[Ts]}C_t\to (cov(C_0))^{-1/2}W_s,
\end{align}
in distribution, where $s\in[0,1]$ and $W_s=(W_{1s},W_{2s})$ is bivariate Brownian motion (two-dimensional Wiener process). For convenience introduce definition $M_s=(M_{1s},M_{2s})=(cov(C_0))^{-1/2}W_s$.
Again for simplicity let us define sample correlation as
\begin{align}
\hat{\rho}=\frac{\frac{1}{T}\sum_{t=1}^TX_{t}Y_t}{\sqrt{\frac{1}{T}\sum_{t=1}^TX_t^2\frac{1}{T}\sum_{t=1}^TY_t^2}}
\end{align}
Let us start with the variances. We have
\begin{align}
E\frac{1}{T}\sum_{t=1}^TX_t^2=\frac{1}{T}E\sum_{t=1}^T\left(\sum_{s=1}^tU_t\right)^2=\frac{1}{T}\sum_{t=1}^Tt\sigma_U^2=\sigma_U\frac{T+1}{2}.
\end{align}
This goes to infinity as $T$ increases, so we hit the first problem, sample variance does not converge. On the other hand continuous mapping theorem in conjunction with functional central limit theorem gives us
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TX_t^2=\sum_{t=1}^T\frac{1}{T}\left(\frac{1}{\sqrt{T}}\sum_{s=1}^tU_t\right)^2\to \int_0^1M_{1s}^2ds
\end{align}
where convergence is convergence in distribution, as $T\to \infty$.
Similarly we get
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TY_t^2\to \int_0^1M_{2s}^2ds
\end{align}
and
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TX_tY_t\to \int_0^1M_{1s}M_{2s}ds
\end{align}
So finally for sample correlation of our random walk we get
\begin{align}
\hat{\rho}\to \frac{\int_0^1M_{1s}M_{2s}ds}{\sqrt{\int_0^1M_{1s}^2ds\int_0^1M_{2s}^2ds}}
\end{align}
in distribution as $T\to \infty$.
So although correlation is well defined, sample correlation does not converge towards it, as in stationary process case. Instead it converges to a certain random variable.
|
Does correlation assume stationarity of data?
|
The correlation measures linear relationship. In informal context relationship means something stable. When we calculate the sample correlation for stationary variables and increase the number of ava
|
Does correlation assume stationarity of data?
The correlation measures linear relationship. In informal context relationship means something stable. When we calculate the sample correlation for stationary variables and increase the number of available data points this sample correlation tends to true correlation.
It can be shown that for prices, which usually are random walks, the sample correlation tends to random variable. This means that no matter how much data we have, the result will always be different.
Note I tried expressing mathematical intuition without the mathematics. From mathematical point of view the explanation is very clear: Sample moments of stationary processes converge in probability to constants. Sample moments of random walks converge to integrals of brownian motion which are random variables. Since relationship is usually expressed as a number and not a random variable, the reason for not calculating the correlation for non-stationary variables becomes evident.
Update Since we are interested in correlation between two variables assume first that they come from stationary process $Z_t=(X_t,Y_t)$. Stationarity implies that $EZ_t$ and $cov(Z_t,Z_{t-h})$ do not depend on $t$. So correlation
$$corr(X_t,Y_t)=\frac{cov(X_t,Y_t)}{\sqrt{DX_tDY_t}}$$
also does not depend on $t$, since all the quantities in the formula come from matrix $cov(Z_t)$, which does not depend on $t$. So the calculation of sample correlation
$$\hat{\rho}=\frac{\frac{1}{T}\sum_{t=1}^T(X_t-\bar{X})(Y_t-\bar{Y})}{\sqrt{\frac{1}{T^2}\sum_{t=1}^T(X_t-\bar{X})^2\sum_{t=1}^T(Y_t-\bar{Y})^2}}$$
makes sense, since we may have reasonable hope that sample correlation will estimate $\rho=corr(X_t,Y_t)$. It turns out that this hope is not unfounded, since for stationary processes satisfying certain conditions we have that $\hat{\rho}\to\rho$, as $T\to\infty$ in probability. Furthermore $\sqrt{T}(\hat{\rho}-\rho)\to N(0,\sigma_{\rho}^2)$ in distribution, so we can test the hypotheses about $\rho$.
Now suppose that $Z_t$ is not stationary. Then $corr(X_t,Y_t)$ may depend on $t$. So when we observe a sample of size $T$ we potentialy need to estimate $T$ different correlations $\rho_t$. This is of course infeasible, so in best case scenario we only can estimate some functional of $\rho_t$ such as mean or variance. But the result may not have sensible interpretation.
Now let us examine what happens with correlation of probably most studied non-stationary process random walk. We call process $Z_t=(X_t,Y_t)$ a random walk if $Z_t=\sum_{s=1}^t(U_t,V_t)$, where $C_t=(U_t,V_t)$ is a stationary process. For simplicity assume that $EC_t=0$. Then
\begin{align}
corr(X_tY_t)=\frac{EX_tY_t}{\sqrt{DX_tDY_t}}=\frac{E\sum_{s=1}^tU_t\sum_{s=1}^tV_t}{\sqrt{D\sum_{s=1}^tU_tD\sum_{s=1}^tV_t}}
\end{align}
To simplify matters further, assume that $C_t=(U_t,V_t)$ is a white noise. This means that all correlations $E(C_tC_{t+h})$ are zero for $h>0$. Note that this does not restrict $corr(U_t,V_t)$ to zero.
Then
\begin{align}
corr(X_t,Y_t)=\frac{tEU_tV_t}{\sqrt{t^2DU_tDV_t}}=corr(U_0,V_0).
\end{align}
So far so good, though the process is not stationary, correlation makes sense, although we had to make same restrictive assumptions.
Now to see what happens to sample correlation we will need to use the following fact about random walks, called functional central limit theorem:
\begin{align}
\frac{1}{\sqrt{T}}Z_{[Ts]}=\frac{1}{\sqrt{T}}\sum_{t=1}^{[Ts]}C_t\to (cov(C_0))^{-1/2}W_s,
\end{align}
in distribution, where $s\in[0,1]$ and $W_s=(W_{1s},W_{2s})$ is bivariate Brownian motion (two-dimensional Wiener process). For convenience introduce definition $M_s=(M_{1s},M_{2s})=(cov(C_0))^{-1/2}W_s$.
Again for simplicity let us define sample correlation as
\begin{align}
\hat{\rho}=\frac{\frac{1}{T}\sum_{t=1}^TX_{t}Y_t}{\sqrt{\frac{1}{T}\sum_{t=1}^TX_t^2\frac{1}{T}\sum_{t=1}^TY_t^2}}
\end{align}
Let us start with the variances. We have
\begin{align}
E\frac{1}{T}\sum_{t=1}^TX_t^2=\frac{1}{T}E\sum_{t=1}^T\left(\sum_{s=1}^tU_t\right)^2=\frac{1}{T}\sum_{t=1}^Tt\sigma_U^2=\sigma_U\frac{T+1}{2}.
\end{align}
This goes to infinity as $T$ increases, so we hit the first problem, sample variance does not converge. On the other hand continuous mapping theorem in conjunction with functional central limit theorem gives us
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TX_t^2=\sum_{t=1}^T\frac{1}{T}\left(\frac{1}{\sqrt{T}}\sum_{s=1}^tU_t\right)^2\to \int_0^1M_{1s}^2ds
\end{align}
where convergence is convergence in distribution, as $T\to \infty$.
Similarly we get
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TY_t^2\to \int_0^1M_{2s}^2ds
\end{align}
and
\begin{align}
\frac{1}{T^2}\sum_{t=1}^TX_tY_t\to \int_0^1M_{1s}M_{2s}ds
\end{align}
So finally for sample correlation of our random walk we get
\begin{align}
\hat{\rho}\to \frac{\int_0^1M_{1s}M_{2s}ds}{\sqrt{\int_0^1M_{1s}^2ds\int_0^1M_{2s}^2ds}}
\end{align}
in distribution as $T\to \infty$.
So although correlation is well defined, sample correlation does not converge towards it, as in stationary process case. Instead it converges to a certain random variable.
|
Does correlation assume stationarity of data?
The correlation measures linear relationship. In informal context relationship means something stable. When we calculate the sample correlation for stationary variables and increase the number of ava
|
9,108
|
Does correlation assume stationarity of data?
|
...is the computation of correlation whose data is non-stationary even a valid statistical calculation?
Let $W$ be a discrete random walk. Pick a positive number $h$. Define the processes $P$ and $V$ by $P(0) = 1$, $P(t+1) = -P(t)$ if $V(t) > h$, and otherwise $P(t+1) = P(t)$; and $V(t) = P(t)W(t)$. In other words, $V$ starts out identical to $W$ but every time $V$ rises above $h$, it switches signs (otherwise emulating $W$ in all respects).
(In this figure (for $h=5$) $W$ is blue and $V$ is red. There are four switches in sign.)
In effect, over short periods of time $V$ tends to be either perfectly correlated with $W$ or perfectly anticorrelated with it; however, using a correlation function to describe the relationship between $V$ and $W$ wouldn't be useful (a word that perhaps more aptly captures the problem than "unreliable" or "nonsense").
Mathematica code to produce the figure:
With[{h=5},
pv[{p_, v_}, w_] := With[{q=If[v > h, -p, p]}, {q, q w}];
w = Accumulate[RandomInteger[{-1,1}, 25 h^2]];
{p,v} = FoldList[pv, {1,0}, w] // Transpose;
ListPlot[{w,v}, Joined->True]]
|
Does correlation assume stationarity of data?
|
...is the computation of correlation whose data is non-stationary even a valid statistical calculation?
Let $W$ be a discrete random walk. Pick a positive number $h$. Define the processes $P$ and $
|
Does correlation assume stationarity of data?
...is the computation of correlation whose data is non-stationary even a valid statistical calculation?
Let $W$ be a discrete random walk. Pick a positive number $h$. Define the processes $P$ and $V$ by $P(0) = 1$, $P(t+1) = -P(t)$ if $V(t) > h$, and otherwise $P(t+1) = P(t)$; and $V(t) = P(t)W(t)$. In other words, $V$ starts out identical to $W$ but every time $V$ rises above $h$, it switches signs (otherwise emulating $W$ in all respects).
(In this figure (for $h=5$) $W$ is blue and $V$ is red. There are four switches in sign.)
In effect, over short periods of time $V$ tends to be either perfectly correlated with $W$ or perfectly anticorrelated with it; however, using a correlation function to describe the relationship between $V$ and $W$ wouldn't be useful (a word that perhaps more aptly captures the problem than "unreliable" or "nonsense").
Mathematica code to produce the figure:
With[{h=5},
pv[{p_, v_}, w_] := With[{q=If[v > h, -p, p]}, {q, q w}];
w = Accumulate[RandomInteger[{-1,1}, 25 h^2]];
{p,v} = FoldList[pv, {1,0}, w] // Transpose;
ListPlot[{w,v}, Joined->True]]
|
Does correlation assume stationarity of data?
...is the computation of correlation whose data is non-stationary even a valid statistical calculation?
Let $W$ be a discrete random walk. Pick a positive number $h$. Define the processes $P$ and $
|
9,109
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Update I've updated the code with maximum likelihood estimator as per @whuber suggestion. Minimizing sum of squares of differences between log theoretical probabilities and log frequencies though gives an answer would be a statistical procedure if it could be shown that it is some kind of M-estimator. Unfortunately I could not think of any which could give the same results.
Here is my attempt. I calculate logarithms of the frequencies and try to fit them to logarithms of theoretical probabilities given by this formula. The final result seems reasonable. Here is my code in R.
fr <- c(26486, 12053, 5052, 3033, 2536, 2391, 1444, 1220, 1152, 1039)
p <- fr/sum(fr)
lzipf <- function(s,N) -s*log(1:N)-log(sum(1/(1:N)^s))
opt.f <- function(s) sum((log(p)-lzipf(s,length(p)))^2)
opt <- optimize(opt.f,c(0.5,10))
> opt
$minimum
[1] 1.463946
$objective
[1] 0.1346248
The best quadratic fit then is $s=1.47$.
The maximum likelihood in R can be performed with mle function (from stats4 package), which helpfully calculates standard errors (if correct negative maximum likelihood function is supplied):
ll <- function(s) sum(fr*(s*log(1:10)+log(sum(1/(1:10)^s))))
fit <- mle(ll,start=list(s=1))
> summary(fit)
Maximum likelihood estimation
Call:
mle(minuslogl = ll, start = list(s = 1))
Coefficients:
Estimate Std. Error
s 1.451385 0.005715046
-2 log L: 188093.4
Here is the graph of the fit in log-log scale (again as @whuber suggested):
s.sq <- opt$minimum
s.ll <- coef(fit)
plot(1:10,p,log="xy")
lines(1:10,exp(lzipf(s.sq,10)),col=2)
lines(1:10,exp(lzipf(s.ll,10)),col=3)
Red line is sum of squares fit, green line is maximum-likelihood fit.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Update I've updated the code with maximum likelihood estimator as per @whuber suggestion. Minimizing sum of squares of differences between log theoretical probabilities and log frequencies though give
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Update I've updated the code with maximum likelihood estimator as per @whuber suggestion. Minimizing sum of squares of differences between log theoretical probabilities and log frequencies though gives an answer would be a statistical procedure if it could be shown that it is some kind of M-estimator. Unfortunately I could not think of any which could give the same results.
Here is my attempt. I calculate logarithms of the frequencies and try to fit them to logarithms of theoretical probabilities given by this formula. The final result seems reasonable. Here is my code in R.
fr <- c(26486, 12053, 5052, 3033, 2536, 2391, 1444, 1220, 1152, 1039)
p <- fr/sum(fr)
lzipf <- function(s,N) -s*log(1:N)-log(sum(1/(1:N)^s))
opt.f <- function(s) sum((log(p)-lzipf(s,length(p)))^2)
opt <- optimize(opt.f,c(0.5,10))
> opt
$minimum
[1] 1.463946
$objective
[1] 0.1346248
The best quadratic fit then is $s=1.47$.
The maximum likelihood in R can be performed with mle function (from stats4 package), which helpfully calculates standard errors (if correct negative maximum likelihood function is supplied):
ll <- function(s) sum(fr*(s*log(1:10)+log(sum(1/(1:10)^s))))
fit <- mle(ll,start=list(s=1))
> summary(fit)
Maximum likelihood estimation
Call:
mle(minuslogl = ll, start = list(s = 1))
Coefficients:
Estimate Std. Error
s 1.451385 0.005715046
-2 log L: 188093.4
Here is the graph of the fit in log-log scale (again as @whuber suggested):
s.sq <- opt$minimum
s.ll <- coef(fit)
plot(1:10,p,log="xy")
lines(1:10,exp(lzipf(s.sq,10)),col=2)
lines(1:10,exp(lzipf(s.ll,10)),col=3)
Red line is sum of squares fit, green line is maximum-likelihood fit.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Update I've updated the code with maximum likelihood estimator as per @whuber suggestion. Minimizing sum of squares of differences between log theoretical probabilities and log frequencies though give
|
9,110
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
There are several issues before us in any estimation problem:
Estimate the parameter.
Assess the quality of that estimate.
Explore the data.
Evaluate the fit.
For those who would use statistical methods for understanding and communication, the first should never be done without the others.
For estimation it is convenient to use maximimum likelihood (ML). The frequencies are so large we can expect the well-known asymptotic properties to hold. ML uses the assumed probability distribution of the data. Zipf's Law supposes the probabilities for $i=1,2,\ldots,n$ are proportional to $i^{-s}$ for some constant power $s$ (usually $s\gt 0$). Because these probabilities must sum to unity, the constant of proportionality is the reciprocal of the sum
$$H_s(n)=\frac{1}{1^s} + \frac{1}{2^s} + \cdots + \frac{1}{n^s}.$$
Consequently, the logarithm of the probability for any outcome $i$ between $1$ and $n$ is
$$\log(\Pr(i)) = \log\left(\frac{i^{-s}}{H_s(n)}\right) = -s\log(i) - \log(H_s(n)).$$
For independent data summarized by their frequencies $f_i, i=1,2,\ldots, n$, the probability is the product of the individual probabilities,
$$\Pr(f_1,f_2,\ldots,f_n) = \Pr(1)^{f_1}\Pr(2)^{f_2}\cdots\Pr(n)^{f_n}.$$
Thus the log probability for the data is
$$\Lambda(s) = -s \sum_{i=1}^n{f_i \log(i)} - \left(\sum_{i=1}^n{f_i}\right) \log\left(H_s(n)\right).$$
Considering the data as fixed, and expressing this explicitly as a function of $s$, makes it the log Likelihood.
Numerical minimization of the log Likelihood with the data given in the question yields $\hat{s} = 1.45041$ and $\Lambda(\hat{s}) = -94046.7$. This is significantly better (but just barely so) than the least squares solution (based on log frequencies) of $\hat{s}_{ls} = 1.463946$ with $\Lambda(\hat{s}_{ls}) = -94049.5$. (The optimization can be done with a minor change to the elegant, clear R code provided by mpiktas.)
ML will also estimate confidence limits for $s$ in the usual ways. The chi-square approximation gives $[1.43922, 1.46162]$ (if I did the calculations correctly :-).
Given the nature of Zipf's law, the right way to graph this fit is on a log-log plot, where the fit will be linear (by definition):
To evaluate the goodness of fit and explore the data, look at the residuals (data/fit, log-log axes again):
This is not too great: although there's no evident serial correlation or heteroscedasticity in the residuals, they typically are around 10% (away from 1.0). With frequencies in the thousands, we wouldn't expect deviations by more than a few percent. The goodness of fit is readily tested with chi square. We obtain $\chi^2 = 656.476$ with 10 - 1 = 9 degrees of freedom; this is highly significant evidence of departures from Zipf's Law.
Because the residuals appear random, in some applications we might be content to accept Zipf's Law (and our estimate of the parameter) as an acceptable albeit rough description of the frequencies. This analysis shows, though, that it would be a mistake to suppose this estimate has any explanatory or predictive value for the dataset examined here.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
There are several issues before us in any estimation problem:
Estimate the parameter.
Assess the quality of that estimate.
Explore the data.
Evaluate the fit.
For those who would use statistical met
|
How to calculate Zipf's law coefficient from a set of top frequencies?
There are several issues before us in any estimation problem:
Estimate the parameter.
Assess the quality of that estimate.
Explore the data.
Evaluate the fit.
For those who would use statistical methods for understanding and communication, the first should never be done without the others.
For estimation it is convenient to use maximimum likelihood (ML). The frequencies are so large we can expect the well-known asymptotic properties to hold. ML uses the assumed probability distribution of the data. Zipf's Law supposes the probabilities for $i=1,2,\ldots,n$ are proportional to $i^{-s}$ for some constant power $s$ (usually $s\gt 0$). Because these probabilities must sum to unity, the constant of proportionality is the reciprocal of the sum
$$H_s(n)=\frac{1}{1^s} + \frac{1}{2^s} + \cdots + \frac{1}{n^s}.$$
Consequently, the logarithm of the probability for any outcome $i$ between $1$ and $n$ is
$$\log(\Pr(i)) = \log\left(\frac{i^{-s}}{H_s(n)}\right) = -s\log(i) - \log(H_s(n)).$$
For independent data summarized by their frequencies $f_i, i=1,2,\ldots, n$, the probability is the product of the individual probabilities,
$$\Pr(f_1,f_2,\ldots,f_n) = \Pr(1)^{f_1}\Pr(2)^{f_2}\cdots\Pr(n)^{f_n}.$$
Thus the log probability for the data is
$$\Lambda(s) = -s \sum_{i=1}^n{f_i \log(i)} - \left(\sum_{i=1}^n{f_i}\right) \log\left(H_s(n)\right).$$
Considering the data as fixed, and expressing this explicitly as a function of $s$, makes it the log Likelihood.
Numerical minimization of the log Likelihood with the data given in the question yields $\hat{s} = 1.45041$ and $\Lambda(\hat{s}) = -94046.7$. This is significantly better (but just barely so) than the least squares solution (based on log frequencies) of $\hat{s}_{ls} = 1.463946$ with $\Lambda(\hat{s}_{ls}) = -94049.5$. (The optimization can be done with a minor change to the elegant, clear R code provided by mpiktas.)
ML will also estimate confidence limits for $s$ in the usual ways. The chi-square approximation gives $[1.43922, 1.46162]$ (if I did the calculations correctly :-).
Given the nature of Zipf's law, the right way to graph this fit is on a log-log plot, where the fit will be linear (by definition):
To evaluate the goodness of fit and explore the data, look at the residuals (data/fit, log-log axes again):
This is not too great: although there's no evident serial correlation or heteroscedasticity in the residuals, they typically are around 10% (away from 1.0). With frequencies in the thousands, we wouldn't expect deviations by more than a few percent. The goodness of fit is readily tested with chi square. We obtain $\chi^2 = 656.476$ with 10 - 1 = 9 degrees of freedom; this is highly significant evidence of departures from Zipf's Law.
Because the residuals appear random, in some applications we might be content to accept Zipf's Law (and our estimate of the parameter) as an acceptable albeit rough description of the frequencies. This analysis shows, though, that it would be a mistake to suppose this estimate has any explanatory or predictive value for the dataset examined here.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
There are several issues before us in any estimation problem:
Estimate the parameter.
Assess the quality of that estimate.
Explore the data.
Evaluate the fit.
For those who would use statistical met
|
9,111
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
The Maximum Likelihood estimates are only point estimates of the parameter $s$. Extra effort is needed to find also the confidence interval of the estimate. The problem is that this interval is not probabilistic. One cannot say "the parameter value s=... is with probability of 95% in the range [...]".
One of the probabilistic programming languages such as PyMC3 make this estimation relatively straightforward. Other languages include Stan which has great features and supportive community.
Here is my Python implementation of the model fitted on the OPs data (also on Github):
import theano.tensor as tt
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
data = np.array( [26486, 12053, 5052, 3033, 2536, 2391, 1444, 1220, 1152, 1039] )
N = len( data )
print( "Number of data points: %d" % N )
def build_model():
with pm.Model() as model:
# unsure about the prior...
#s = pm.Normal( 's', mu=0.0, sd=100 )
#s = pm.HalfNormal( 's', sd=10 )
s = pm.Gamma('s', alpha=1, beta=10)
def logp( f ):
r = tt.arange( 1, N+1 )
return -s * tt.sum( f * tt.log(r) ) - tt.sum( f ) * tt.log( tt.sum(tt.power(1.0/r,s)) )
pm.DensityDist( 'obs', logp=logp, observed={'f': data} )
return model
def run( n_samples=10000 ):
model = build_model()
with model:
start = pm.find_MAP()
step = pm.NUTS( scaling=start )
trace = pm.sample( n_samples, step=step, start=start )
pm.summary( trace )
pm.traceplot( trace )
pm.plot_posterior( trace, kde_plot=True )
plt.show()
if __name__ == '__main__':
run()
Here are the estimates of the parameter $s$ in distribution form. Notice how compact is the estimate! With probability of 95% the true value of parameter $s$ is in the range [1.439,1.461]; the mean is about 1.45, which is very close to MLE estimates.
To provide some basic sampling diagnostics, we can see that the sampling was "mixing well" as we don't see any structure in the trace:
To run the code, one needs Python with Theano and PyMC3 packages installed.
Thanks to @w-huber for his great answer and comments!
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
The Maximum Likelihood estimates are only point estimates of the parameter $s$. Extra effort is needed to find also the confidence interval of the estimate. The problem is that this interval is not pr
|
How to calculate Zipf's law coefficient from a set of top frequencies?
The Maximum Likelihood estimates are only point estimates of the parameter $s$. Extra effort is needed to find also the confidence interval of the estimate. The problem is that this interval is not probabilistic. One cannot say "the parameter value s=... is with probability of 95% in the range [...]".
One of the probabilistic programming languages such as PyMC3 make this estimation relatively straightforward. Other languages include Stan which has great features and supportive community.
Here is my Python implementation of the model fitted on the OPs data (also on Github):
import theano.tensor as tt
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
data = np.array( [26486, 12053, 5052, 3033, 2536, 2391, 1444, 1220, 1152, 1039] )
N = len( data )
print( "Number of data points: %d" % N )
def build_model():
with pm.Model() as model:
# unsure about the prior...
#s = pm.Normal( 's', mu=0.0, sd=100 )
#s = pm.HalfNormal( 's', sd=10 )
s = pm.Gamma('s', alpha=1, beta=10)
def logp( f ):
r = tt.arange( 1, N+1 )
return -s * tt.sum( f * tt.log(r) ) - tt.sum( f ) * tt.log( tt.sum(tt.power(1.0/r,s)) )
pm.DensityDist( 'obs', logp=logp, observed={'f': data} )
return model
def run( n_samples=10000 ):
model = build_model()
with model:
start = pm.find_MAP()
step = pm.NUTS( scaling=start )
trace = pm.sample( n_samples, step=step, start=start )
pm.summary( trace )
pm.traceplot( trace )
pm.plot_posterior( trace, kde_plot=True )
plt.show()
if __name__ == '__main__':
run()
Here are the estimates of the parameter $s$ in distribution form. Notice how compact is the estimate! With probability of 95% the true value of parameter $s$ is in the range [1.439,1.461]; the mean is about 1.45, which is very close to MLE estimates.
To provide some basic sampling diagnostics, we can see that the sampling was "mixing well" as we don't see any structure in the trace:
To run the code, one needs Python with Theano and PyMC3 packages installed.
Thanks to @w-huber for his great answer and comments!
|
How to calculate Zipf's law coefficient from a set of top frequencies?
The Maximum Likelihood estimates are only point estimates of the parameter $s$. Extra effort is needed to find also the confidence interval of the estimate. The problem is that this interval is not pr
|
9,112
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Here is my attempt to fit the data, evaluate and explore the results using VGAM:
require("VGAM")
freq <- dzipf(1:100, N = 100, s = 1)*1000 #randomizing values
freq <- freq + abs(rnorm(n=1,m=0, sd=100)) #adding noize
zdata <- data.frame(y = rank(-freq, ties.method = "first") , ofreq = freq)
fit = vglm(y ~ 1, zipf, zdata, trace = TRUE,weight = ofreq,crit = "coef")
summary(fit)
s <- (shat <- Coef(fit)) # the coefficient we've found
probs <- dzipf(zdata$y, N = length(freq), s = s) # expected values
chisq.test(zdata$ofreq, p = probs)
plot(zdata$y,(zdata$ofreq),log="xy") #log log graph
lines(zdata$y, (probs)*sum(zdata$ofreq), col="red") # red line, num of predicted frequency
Chi-squared test for given probabilities
data: zdata$ofreq
X-squared = 99.756, df = 99, p-value = 0.4598
In our case Chi square's null hypotheses is that the data is distributed according to zipf's law, hence larger p-values support the claim that the data is distributed according to it. Note that even very large p-values are not a proof, just a an indicator.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Here is my attempt to fit the data, evaluate and explore the results using VGAM:
require("VGAM")
freq <- dzipf(1:100, N = 100, s = 1)*1000 #randomizing values
freq <- freq + abs(rnorm(n=1,m=0, sd=10
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Here is my attempt to fit the data, evaluate and explore the results using VGAM:
require("VGAM")
freq <- dzipf(1:100, N = 100, s = 1)*1000 #randomizing values
freq <- freq + abs(rnorm(n=1,m=0, sd=100)) #adding noize
zdata <- data.frame(y = rank(-freq, ties.method = "first") , ofreq = freq)
fit = vglm(y ~ 1, zipf, zdata, trace = TRUE,weight = ofreq,crit = "coef")
summary(fit)
s <- (shat <- Coef(fit)) # the coefficient we've found
probs <- dzipf(zdata$y, N = length(freq), s = s) # expected values
chisq.test(zdata$ofreq, p = probs)
plot(zdata$y,(zdata$ofreq),log="xy") #log log graph
lines(zdata$y, (probs)*sum(zdata$ofreq), col="red") # red line, num of predicted frequency
Chi-squared test for given probabilities
data: zdata$ofreq
X-squared = 99.756, df = 99, p-value = 0.4598
In our case Chi square's null hypotheses is that the data is distributed according to zipf's law, hence larger p-values support the claim that the data is distributed according to it. Note that even very large p-values are not a proof, just a an indicator.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Here is my attempt to fit the data, evaluate and explore the results using VGAM:
require("VGAM")
freq <- dzipf(1:100, N = 100, s = 1)*1000 #randomizing values
freq <- freq + abs(rnorm(n=1,m=0, sd=10
|
9,113
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Just for fun, this is another instance where the UWSE can provide a closed form solution using only the top most frequency - though at a cost of accuracy. The probability on $ x = 1$ is unique across parameter values. If $ \hat{w_{x=1}} $ denotes the corresponding relative frequency then,
$$ \hat{s_{UWSE}} = H_{10}^{-1}(\frac{1}{\hat{w_{x=1}}}) $$
In this case, since $\hat{w_{x=1}} = 0.4695599775 $, we get:
$$ \hat{s_{UWSE}} = 1.4$$
Again, the UWSE only provides a consistent estimate - no confidence intervals, and we can see some trade-off in accuracy. mpiktas' solution above is also an application of the UWSE - though programming is required. For a full explanation of the estimator see:https://paradsp.wordpress.com/ - all the way at the bottom.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Just for fun, this is another instance where the UWSE can provide a closed form solution using only the top most frequency - though at a cost of accuracy. The probability on $ x = 1$ is unique across
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Just for fun, this is another instance where the UWSE can provide a closed form solution using only the top most frequency - though at a cost of accuracy. The probability on $ x = 1$ is unique across parameter values. If $ \hat{w_{x=1}} $ denotes the corresponding relative frequency then,
$$ \hat{s_{UWSE}} = H_{10}^{-1}(\frac{1}{\hat{w_{x=1}}}) $$
In this case, since $\hat{w_{x=1}} = 0.4695599775 $, we get:
$$ \hat{s_{UWSE}} = 1.4$$
Again, the UWSE only provides a consistent estimate - no confidence intervals, and we can see some trade-off in accuracy. mpiktas' solution above is also an application of the UWSE - though programming is required. For a full explanation of the estimator see:https://paradsp.wordpress.com/ - all the way at the bottom.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Just for fun, this is another instance where the UWSE can provide a closed form solution using only the top most frequency - though at a cost of accuracy. The probability on $ x = 1$ is unique across
|
9,114
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Here is a simple example using the text Ulysses.
I'll use a simple bash script to acquire the type frequencies:
cat ulysses.txt | tr 'A-Z' 'a-z' | tr -dc 'a-z ' | tr ' ' '\n' | sort | uniq -c | sort -k1,1nr | awk '{print $1}' > ulysses_freq.txt
And then use R to fit model using mle.
The normalized frequency of the element of rank k, $f(k;s,N)$, is defined as
$$
f(k;s,N)=\frac{1/k^s}{\sum\limits_{n=1}^N (1/n^s)} = \frac{1/k^s}{H_{N,s}}
$$
where $N$ is the vocabulary size and $s$ the exponent characterizing the distribution.
In a given sample, if we have $M$ tokens, the logarithm of the likelihood function will be given by:
$$
\ln L(s|k_1,\cdots,k_M,N) = -M \ln H_{N,s} - s \sum_{m=1}^{M} \ln k_m .
$$
The R code to load the data, fit the model and plot is presented below:
library('stats4')
library('ggplot2')
freq <- as.numeric(readLines('ulysses_freq.txt'))
zipf.ll <- function(s) {
N <- length(freq)
M <- sum(freq)
idx=1:length(freq)
return( M * log( sum((1:N)^(-s)) ) + s*sum(freq[idx] * log(idx)) )
}
m.fit <- mle(minuslogl=zipf.ll, start=list(s=1), lower=c(0.5), upper=c(2), nobs=as.integer(sum(freq)))
summary(m.fit)
s <- coef(m.fit)
N <- length(freq)
f <- ((1:N)^(-s))/(sum((1:N)^(-s)))
ggplot() + geom_point(aes(x=1:N,y=freq/sum(freq))) + geom_line(aes(x=1:N,y=f),colour='blue') + scale_x_continuous(trans='log10') + scale_y_continuous(trans='log10') + xlab('k') + ylab('f(k|s,N)') + theme_minimal()
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
Here is a simple example using the text Ulysses.
I'll use a simple bash script to acquire the type frequencies:
cat ulysses.txt | tr 'A-Z' 'a-z' | tr -dc 'a-z ' | tr ' ' '\n' | sort | uniq -c | sort -
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Here is a simple example using the text Ulysses.
I'll use a simple bash script to acquire the type frequencies:
cat ulysses.txt | tr 'A-Z' 'a-z' | tr -dc 'a-z ' | tr ' ' '\n' | sort | uniq -c | sort -k1,1nr | awk '{print $1}' > ulysses_freq.txt
And then use R to fit model using mle.
The normalized frequency of the element of rank k, $f(k;s,N)$, is defined as
$$
f(k;s,N)=\frac{1/k^s}{\sum\limits_{n=1}^N (1/n^s)} = \frac{1/k^s}{H_{N,s}}
$$
where $N$ is the vocabulary size and $s$ the exponent characterizing the distribution.
In a given sample, if we have $M$ tokens, the logarithm of the likelihood function will be given by:
$$
\ln L(s|k_1,\cdots,k_M,N) = -M \ln H_{N,s} - s \sum_{m=1}^{M} \ln k_m .
$$
The R code to load the data, fit the model and plot is presented below:
library('stats4')
library('ggplot2')
freq <- as.numeric(readLines('ulysses_freq.txt'))
zipf.ll <- function(s) {
N <- length(freq)
M <- sum(freq)
idx=1:length(freq)
return( M * log( sum((1:N)^(-s)) ) + s*sum(freq[idx] * log(idx)) )
}
m.fit <- mle(minuslogl=zipf.ll, start=list(s=1), lower=c(0.5), upper=c(2), nobs=as.integer(sum(freq)))
summary(m.fit)
s <- coef(m.fit)
N <- length(freq)
f <- ((1:N)^(-s))/(sum((1:N)^(-s)))
ggplot() + geom_point(aes(x=1:N,y=freq/sum(freq))) + geom_line(aes(x=1:N,y=f),colour='blue') + scale_x_continuous(trans='log10') + scale_y_continuous(trans='log10') + xlab('k') + ylab('f(k|s,N)') + theme_minimal()
|
How to calculate Zipf's law coefficient from a set of top frequencies?
Here is a simple example using the text Ulysses.
I'll use a simple bash script to acquire the type frequencies:
cat ulysses.txt | tr 'A-Z' 'a-z' | tr -dc 'a-z ' | tr ' ' '\n' | sort | uniq -c | sort -
|
9,115
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
My solution try to be complementary to the answers provided by mpiktas and whuber doing an implementation in Python. Our frequencies and ranges x are:
freqs = np.asarray([26486, 12053, 5052, 3033, 2536, 2391, 1444, 1220, 1152, 1039])
x = np.asarray([1, 2, 3, 4, 5 ,6 ,7 ,8 ,9, 10])
As our function is not defined in all range, we need to check that we are normalising each time we compute it. In the discrete case, a simple approximation is to divide by the sum of all y(x). In this way we can compare different parameters.
f,ax = plt.subplots()
ax.plot(x, f1, 'o')
ax.set_xscale("log")
ax.set_yscale("log")
def loglik(b):
# Power law function
Probabilities = x**(-b)
# Normalized
Probabilities = Probabilities/Probabilities.sum()
# Log Likelihoood
Lvector = np.log(Probabilities)
# Multiply the vector by frequencies
Lvector = np.log(Probabilities) * freqs
# LL is the sum
L = Lvector.sum()
# We want to maximize LogLikelihood or minimize (-1)*LogLikelihood
return(-L)
s_best = minimize(loglik, [2])
print(s_best)
ax.plot(x, freqs[0]*x**-s_best.x)
The result gives us a slope of 1.450408 as in previous answers.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
|
My solution try to be complementary to the answers provided by mpiktas and whuber doing an implementation in Python. Our frequencies and ranges x are:
freqs = np.asarray([26486, 12053, 5052, 3033, 253
|
How to calculate Zipf's law coefficient from a set of top frequencies?
My solution try to be complementary to the answers provided by mpiktas and whuber doing an implementation in Python. Our frequencies and ranges x are:
freqs = np.asarray([26486, 12053, 5052, 3033, 2536, 2391, 1444, 1220, 1152, 1039])
x = np.asarray([1, 2, 3, 4, 5 ,6 ,7 ,8 ,9, 10])
As our function is not defined in all range, we need to check that we are normalising each time we compute it. In the discrete case, a simple approximation is to divide by the sum of all y(x). In this way we can compare different parameters.
f,ax = plt.subplots()
ax.plot(x, f1, 'o')
ax.set_xscale("log")
ax.set_yscale("log")
def loglik(b):
# Power law function
Probabilities = x**(-b)
# Normalized
Probabilities = Probabilities/Probabilities.sum()
# Log Likelihoood
Lvector = np.log(Probabilities)
# Multiply the vector by frequencies
Lvector = np.log(Probabilities) * freqs
# LL is the sum
L = Lvector.sum()
# We want to maximize LogLikelihood or minimize (-1)*LogLikelihood
return(-L)
s_best = minimize(loglik, [2])
print(s_best)
ax.plot(x, freqs[0]*x**-s_best.x)
The result gives us a slope of 1.450408 as in previous answers.
|
How to calculate Zipf's law coefficient from a set of top frequencies?
My solution try to be complementary to the answers provided by mpiktas and whuber doing an implementation in Python. Our frequencies and ranges x are:
freqs = np.asarray([26486, 12053, 5052, 3033, 253
|
9,116
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
Variable importance might generally be computed based on the corresponding reduction of predictive accuracy when the predictor of interest is removed (with a permutation technique, like in Random Forest) or some measure of decrease of node impurity, but see (1) for an overview of available methods. An obvious alternative to CART is RF of course (randomForest, but see also party). With RF, the Gini importance index is defined as the averaged Gini decrease in node impurities over all trees in the forest (it follows from the fact that the Gini impurity index for a given parent node is larger than the value of that measure for its two daughter nodes, see e.g. (2)).
I know that Carolin Strobl and coll. have contributed a lot of simulation and experimental studies on (conditional) variable importance in RFs and CARTs (e.g., (3-4), but there are many other ones, or her thesis, Statistical Issues in Machine Learning – Towards Reliable Split Selection and Variable Importance Measures).
To my knowledge, the caret package (5) only considers a loss function for the regression case (i.e., mean squared error). Maybe it will be added in the near future (anyway, an example with a classification case by k-NN is available in the on-line help for dotPlot).
However, Noel M O'Boyle seems to have some R code for Variable importance in CART.
References
Sandri and Zuccolotto. A bias correction algorithm for the Gini variable importance measure in classification trees. 2008
Izenman. Modern Multivariate Statistical Techniques. Springer 2008
Strobl, Hothorn, and Zeilis. Party on!. R Journal 2009 1/2
Strobl, Boulesteix, Kneib, Augustin, and Zeilis. Conditional variable importance for random forests. BMC Bioinformatics 2008, 9:307
Kuhn. Building Predictive Models in R Using the caret Package. JSS 2008 28(5)
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
Variable importance might generally be computed based on the corresponding reduction of predictive accuracy when the predictor of interest is removed (with a permutation technique, like in Random Fore
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
Variable importance might generally be computed based on the corresponding reduction of predictive accuracy when the predictor of interest is removed (with a permutation technique, like in Random Forest) or some measure of decrease of node impurity, but see (1) for an overview of available methods. An obvious alternative to CART is RF of course (randomForest, but see also party). With RF, the Gini importance index is defined as the averaged Gini decrease in node impurities over all trees in the forest (it follows from the fact that the Gini impurity index for a given parent node is larger than the value of that measure for its two daughter nodes, see e.g. (2)).
I know that Carolin Strobl and coll. have contributed a lot of simulation and experimental studies on (conditional) variable importance in RFs and CARTs (e.g., (3-4), but there are many other ones, or her thesis, Statistical Issues in Machine Learning – Towards Reliable Split Selection and Variable Importance Measures).
To my knowledge, the caret package (5) only considers a loss function for the regression case (i.e., mean squared error). Maybe it will be added in the near future (anyway, an example with a classification case by k-NN is available in the on-line help for dotPlot).
However, Noel M O'Boyle seems to have some R code for Variable importance in CART.
References
Sandri and Zuccolotto. A bias correction algorithm for the Gini variable importance measure in classification trees. 2008
Izenman. Modern Multivariate Statistical Techniques. Springer 2008
Strobl, Hothorn, and Zeilis. Party on!. R Journal 2009 1/2
Strobl, Boulesteix, Kneib, Augustin, and Zeilis. Conditional variable importance for random forests. BMC Bioinformatics 2008, 9:307
Kuhn. Building Predictive Models in R Using the caret Package. JSS 2008 28(5)
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
Variable importance might generally be computed based on the corresponding reduction of predictive accuracy when the predictor of interest is removed (with a permutation technique, like in Random Fore
|
9,117
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
The following function(from Caret package) can be used for evaluating variable importance in rpart trees. I corrected a bug in the Caret function when this only root node in the tree.
varImp <- function(object, surrogates = FALSE, competes = TRUE, ...)
{
tmp <- rownames(object$splits)
allVars <- colnames(attributes(object$terms)$factors)
if(is.null(tmp))
{
out<-NULL
zeros <- data.frame(x = rep(0, length(allVars)),
Variable = allVars)
out <- rbind(out, zeros)
}
else {
rownames(object$splits) <- 1:nrow(object$splits)
splits <- data.frame(object$splits)
splits$var <- tmp
splits$type <- ""
frame <- as.data.frame(object$frame)
index <- 0
for(i in 1:nrow(frame))
{
if(frame$var[i] != "<leaf>")
{
index <- index + 1
splits$type[index] <- "primary"
if(frame$ncompete[i] > 0)
{
for(j in 1:frame$ncompete[i])
{
index <- index + 1
splits$type[index] <- "competing"
}
}
if(frame$nsurrogate[i] > 0)
{
for(j in 1:frame$nsurrogate[i])
{
index <- index + 1
splits$type[index] <- "surrogate"
}
}
}
}
splits$var <- factor(as.character(splits$var))
if(!surrogates) splits <- subset(splits, type != "surrogate")
if(!competes) splits <- subset(splits, type != "competing")
out <- aggregate(splits$improve,
list(Variable = splits$var),
sum,
na.rm = TRUE)
allVars <- colnames(attributes(object$terms)$factors)
if(!all(allVars %in% out$Variable))
{
missingVars <- allVars[!(allVars %in% out$Variable)]
zeros <- data.frame(x = rep(0, length(missingVars)),
Variable = missingVars)
out <- rbind(out, zeros)
}
}
out2 <- data.frame(Overall = out$x)
rownames(out2) <- out$Variable
out2
}
The following r code will produce importance scores for a rpart tree "fit"
varImp(fit)
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
The following function(from Caret package) can be used for evaluating variable importance in rpart trees. I corrected a bug in the Caret function when this only root node in the tree.
varImp <- functi
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
The following function(from Caret package) can be used for evaluating variable importance in rpart trees. I corrected a bug in the Caret function when this only root node in the tree.
varImp <- function(object, surrogates = FALSE, competes = TRUE, ...)
{
tmp <- rownames(object$splits)
allVars <- colnames(attributes(object$terms)$factors)
if(is.null(tmp))
{
out<-NULL
zeros <- data.frame(x = rep(0, length(allVars)),
Variable = allVars)
out <- rbind(out, zeros)
}
else {
rownames(object$splits) <- 1:nrow(object$splits)
splits <- data.frame(object$splits)
splits$var <- tmp
splits$type <- ""
frame <- as.data.frame(object$frame)
index <- 0
for(i in 1:nrow(frame))
{
if(frame$var[i] != "<leaf>")
{
index <- index + 1
splits$type[index] <- "primary"
if(frame$ncompete[i] > 0)
{
for(j in 1:frame$ncompete[i])
{
index <- index + 1
splits$type[index] <- "competing"
}
}
if(frame$nsurrogate[i] > 0)
{
for(j in 1:frame$nsurrogate[i])
{
index <- index + 1
splits$type[index] <- "surrogate"
}
}
}
}
splits$var <- factor(as.character(splits$var))
if(!surrogates) splits <- subset(splits, type != "surrogate")
if(!competes) splits <- subset(splits, type != "competing")
out <- aggregate(splits$improve,
list(Variable = splits$var),
sum,
na.rm = TRUE)
allVars <- colnames(attributes(object$terms)$factors)
if(!all(allVars %in% out$Variable))
{
missingVars <- allVars[!(allVars %in% out$Variable)]
zeros <- data.frame(x = rep(0, length(missingVars)),
Variable = missingVars)
out <- rbind(out, zeros)
}
}
out2 <- data.frame(Overall = out$x)
rownames(out2) <- out$Variable
out2
}
The following r code will produce importance scores for a rpart tree "fit"
varImp(fit)
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
The following function(from Caret package) can be used for evaluating variable importance in rpart trees. I corrected a bug in the Caret function when this only root node in the tree.
varImp <- functi
|
9,118
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
I think chl has pretty much answered the first part:
What common measures exists for ranking/measuring variable importance of participating variables in a CART model?
With respect to the second part of your question:
And how can this be computed using R (for example, when using the rpart package)
You can find the variable importance using rpart by using summary(fit). This outputs the variable importance among several other things. You can read more about it here: https://cran.r-project.org/web/packages/rpart/rpart.pdf. Refer page 25.
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
I think chl has pretty much answered the first part:
What common measures exists for ranking/measuring variable importance of participating variables in a CART model?
With respect to the second par
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
I think chl has pretty much answered the first part:
What common measures exists for ranking/measuring variable importance of participating variables in a CART model?
With respect to the second part of your question:
And how can this be computed using R (for example, when using the rpart package)
You can find the variable importance using rpart by using summary(fit). This outputs the variable importance among several other things. You can read more about it here: https://cran.r-project.org/web/packages/rpart/rpart.pdf. Refer page 25.
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
I think chl has pretty much answered the first part:
What common measures exists for ranking/measuring variable importance of participating variables in a CART model?
With respect to the second par
|
9,119
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
names(result) shows variable.importance
result$variable.importance should help?
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
names(result) shows variable.importance
result$variable.importance should help?
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
names(result) shows variable.importance
result$variable.importance should help?
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
names(result) shows variable.importance
result$variable.importance should help?
|
9,120
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
The caret package and the rpart package each have ways to list the variables and rank their importance, but generate different results from each other when calculating variable importance.
fit$variable.importance
## shows different results than
caret::varImp(fit)
The list of variables used is the same, but the scale is different, and even the order of importance is different for the dataset I'm using.
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
|
The caret package and the rpart package each have ways to list the variables and rank their importance, but generate different results from each other when calculating variable importance.
fit$variabl
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
The caret package and the rpart package each have ways to list the variables and rank their importance, but generate different results from each other when calculating variable importance.
fit$variable.importance
## shows different results than
caret::varImp(fit)
The list of variables used is the same, but the scale is different, and even the order of importance is different for the dataset I'm using.
|
How to measure/rank "variable importance" when using CART? (specifically using {rpart} from R)
The caret package and the rpart package each have ways to list the variables and rank their importance, but generate different results from each other when calculating variable importance.
fit$variabl
|
9,121
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
|
Automatically finding good starting values for a nonlinear model is an art. (It's relatively easy for one-off datasets when you can just plot the data and make some good guesses visually.) One approach is to linearize the model and use least squares estimates.
In this case, the model has the form
$$\mathbb{E}(Y) = a \exp(b x) + c$$
for unknown parameters $a,b,c$. The presence of the exponential encourages us to use logarithms--but the addition of $c$ makes it difficult to do that. Notice, though, that if $a$ is positive then $c$ will be less than the smallest expected value of $Y$--and therefore might be a little less than the smallest observed value of $Y$. (If $a$ could be negative you will also have to consider a value of $c$ that is a little greater than the largest observed value of $Y$.)
Let us, then, take care of $c$ by using as initial estimate $c_0$ something like half the minimum of the observations $y_i$. The model can now be rewritten without that thorny additive term as
$$\mathbb{E}(Y) - c_0 \approx a \exp(b x).$$
That we can take the log of:
$$\log(\mathbb{E}(Y) - c_0) \approx \log(a) + b x.$$
That is a linear approximation to the model. Both $\log(a)$ and $b$ can be estimated with least squares.
Here is the revised code:
c.0 <- min(q24$cost.per.car) * 0.5
model.0 <- lm(log(cost.per.car - c.0) ~ reductions, data=q24)
start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
model <- nls(cost.per.car ~ a * exp(b * reductions) + c, data = q24, start = start)
Its output (for the example data) is
Nonlinear regression model
model: cost.per.car ~ a * exp(b * reductions) + c
data: q24
a b c
0.003289 0.126805 48.487386
residual sum-of-squares: 2243
Number of iterations to convergence: 38
Achieved convergence tolerance: 1.374e-06
The convergence looks good. Let's plot it:
plot(q24)
p <- coef(model)
curve(p["a"] * exp(p["b"] * x) + p["c"], lwd=2, col="Red", add=TRUE)
It worked well!
When automating this, you might perform some quick analyses of the residuals, such as comparing their extremes to the spread in the ($y$) data. You might also need analogous code to deal with the possibility $a\lt 0$; I leave that as an exercise.
Another method to estimate initial values relies on understanding what they mean, which can be based on experience, physical theory, etc. An extended example of a (moderately difficult) nonlinear fit whose initial values can be determined in this way is described in my answer at https://stats.stackexchange.com/a/15769.
Visual analysis of a scatterplot (to determine initial parameter estimates) is described and illustrated at https://stats.stackexchange.com/a/32832.
In some circumstances, a sequence of nonlinear fits is made where you can expect the solutions to change slowly. In that case it's often convenient (and fast) to use the previous solutions as initial estimates for the next ones. I recall using this technique (without comment) at https://stats.stackexchange.com/a/63169.
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
|
Automatically finding good starting values for a nonlinear model is an art. (It's relatively easy for one-off datasets when you can just plot the data and make some good guesses visually.) One appro
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
Automatically finding good starting values for a nonlinear model is an art. (It's relatively easy for one-off datasets when you can just plot the data and make some good guesses visually.) One approach is to linearize the model and use least squares estimates.
In this case, the model has the form
$$\mathbb{E}(Y) = a \exp(b x) + c$$
for unknown parameters $a,b,c$. The presence of the exponential encourages us to use logarithms--but the addition of $c$ makes it difficult to do that. Notice, though, that if $a$ is positive then $c$ will be less than the smallest expected value of $Y$--and therefore might be a little less than the smallest observed value of $Y$. (If $a$ could be negative you will also have to consider a value of $c$ that is a little greater than the largest observed value of $Y$.)
Let us, then, take care of $c$ by using as initial estimate $c_0$ something like half the minimum of the observations $y_i$. The model can now be rewritten without that thorny additive term as
$$\mathbb{E}(Y) - c_0 \approx a \exp(b x).$$
That we can take the log of:
$$\log(\mathbb{E}(Y) - c_0) \approx \log(a) + b x.$$
That is a linear approximation to the model. Both $\log(a)$ and $b$ can be estimated with least squares.
Here is the revised code:
c.0 <- min(q24$cost.per.car) * 0.5
model.0 <- lm(log(cost.per.car - c.0) ~ reductions, data=q24)
start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
model <- nls(cost.per.car ~ a * exp(b * reductions) + c, data = q24, start = start)
Its output (for the example data) is
Nonlinear regression model
model: cost.per.car ~ a * exp(b * reductions) + c
data: q24
a b c
0.003289 0.126805 48.487386
residual sum-of-squares: 2243
Number of iterations to convergence: 38
Achieved convergence tolerance: 1.374e-06
The convergence looks good. Let's plot it:
plot(q24)
p <- coef(model)
curve(p["a"] * exp(p["b"] * x) + p["c"], lwd=2, col="Red", add=TRUE)
It worked well!
When automating this, you might perform some quick analyses of the residuals, such as comparing their extremes to the spread in the ($y$) data. You might also need analogous code to deal with the possibility $a\lt 0$; I leave that as an exercise.
Another method to estimate initial values relies on understanding what they mean, which can be based on experience, physical theory, etc. An extended example of a (moderately difficult) nonlinear fit whose initial values can be determined in this way is described in my answer at https://stats.stackexchange.com/a/15769.
Visual analysis of a scatterplot (to determine initial parameter estimates) is described and illustrated at https://stats.stackexchange.com/a/32832.
In some circumstances, a sequence of nonlinear fits is made where you can expect the solutions to change slowly. In that case it's often convenient (and fast) to use the previous solutions as initial estimates for the next ones. I recall using this technique (without comment) at https://stats.stackexchange.com/a/63169.
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
Automatically finding good starting values for a nonlinear model is an art. (It's relatively easy for one-off datasets when you can just plot the data and make some good guesses visually.) One appro
|
9,122
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
|
This library was able to resolve my problem with nls's singular gradient:
http://www.r-bloggers.com/a-better-nls/
An example:
library(minpack.lm)
nlsLM(function, start=list(variable=2,variable2=12))
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
|
This library was able to resolve my problem with nls's singular gradient:
http://www.r-bloggers.com/a-better-nls/
An example:
library(minpack.lm)
nlsLM(function, start=list(variable=2,variable2=12))
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
This library was able to resolve my problem with nls's singular gradient:
http://www.r-bloggers.com/a-better-nls/
An example:
library(minpack.lm)
nlsLM(function, start=list(variable=2,variable2=12))
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
This library was able to resolve my problem with nls's singular gradient:
http://www.r-bloggers.com/a-better-nls/
An example:
library(minpack.lm)
nlsLM(function, start=list(variable=2,variable2=12))
|
9,123
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
|
So ... I think I mis-read this as an exponential function. All I needed was poly()
model <- lm(cost.per.car ~ poly(reductions, 3), data=q24)
new.data <- data.frame(reductions = c(91,92,93,94))
predict(model, new.data)
plot(q24)
lines(q24$reductions, predict(model, list(reductions = q24$reductions)))
Or, using lattice:
xyplot(cost.per.car ~ reductions, data = q24,
panel = function(x, y) {
panel.xyplot(x, y)
panel.lines(x, predict(model,list(reductions = x) ))
},
xlab = "Reductions",
ylab = "Cost per car")
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
|
So ... I think I mis-read this as an exponential function. All I needed was poly()
model <- lm(cost.per.car ~ poly(reductions, 3), data=q24)
new.data <- data.frame(reductions = c(91,92,93,94))
predict
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
So ... I think I mis-read this as an exponential function. All I needed was poly()
model <- lm(cost.per.car ~ poly(reductions, 3), data=q24)
new.data <- data.frame(reductions = c(91,92,93,94))
predict(model, new.data)
plot(q24)
lines(q24$reductions, predict(model, list(reductions = q24$reductions)))
Or, using lattice:
xyplot(cost.per.car ~ reductions, data = q24,
panel = function(x, y) {
panel.xyplot(x, y)
panel.lines(x, predict(model,list(reductions = x) ))
},
xlab = "Reductions",
ylab = "Cost per car")
|
Why is nls() giving me "singular gradient matrix at initial parameter estimates" errors?
So ... I think I mis-read this as an exponential function. All I needed was poly()
model <- lm(cost.per.car ~ poly(reductions, 3), data=q24)
new.data <- data.frame(reductions = c(91,92,93,94))
predict
|
9,124
|
Why should I be Bayesian when my dataset is large?
|
Being Bayesian is not only about information fed through the prior. But even then: Where the prior is zero, no amount of data will turn that over.
Having a full Bayesian posterior distribution to draw from opens loads and loads of ways to make inference from.
It is easy to explain a credible interval to any audience whilst you know that most audiences have a very vague understanding of what a confidence interval is.
Andrew Gelman said in one of his youtube videos, that $p$ is always slightly lower then $0.05$ because if it wasn't smaller then we would not read about it and if it was much smaller they'd examine subgroups. While that is not an absolute truth, indeed when you have large data you will be tempted to investigate defined subgroups ("is it still true when we only investigate caucasian single women under 30?") and that tends to shrink even large data quite a lot.
$p$-values tend to get worthless with large data as in real life no null hypthesis holds true in large data sets. It is part of the tradition about $p$ values that we keep the acceptable alpha error at $.05$ even in huge datasets where there is absolutely no need for such a large margin of error. Baysian analysis is not limited to point hyptheses and can find that the data is in a region of practical equivalence to a null hypotheses, a Baysian factor can grow your believe in some sort of null hypothesis equivalent where a $p$ value can only accumulate evidence against it. Could you find ways to emulate that via confidence intervals and other Frequentist methods? Probably yes, but Bayes comes with that approach as the standard.
"But for large enough data, wouldn't the posterior just collapse to the MLE" - what if a posterior was bimodal or if two predictors are correlated so you could have different combinations of e.g. $\beta_8$ and $\beta_9$ - a posterior can represent these different combinations, an MLE point estimator does not.
|
Why should I be Bayesian when my dataset is large?
|
Being Bayesian is not only about information fed through the prior. But even then: Where the prior is zero, no amount of data will turn that over.
Having a full Bayesian posterior distribution to dra
|
Why should I be Bayesian when my dataset is large?
Being Bayesian is not only about information fed through the prior. But even then: Where the prior is zero, no amount of data will turn that over.
Having a full Bayesian posterior distribution to draw from opens loads and loads of ways to make inference from.
It is easy to explain a credible interval to any audience whilst you know that most audiences have a very vague understanding of what a confidence interval is.
Andrew Gelman said in one of his youtube videos, that $p$ is always slightly lower then $0.05$ because if it wasn't smaller then we would not read about it and if it was much smaller they'd examine subgroups. While that is not an absolute truth, indeed when you have large data you will be tempted to investigate defined subgroups ("is it still true when we only investigate caucasian single women under 30?") and that tends to shrink even large data quite a lot.
$p$-values tend to get worthless with large data as in real life no null hypthesis holds true in large data sets. It is part of the tradition about $p$ values that we keep the acceptable alpha error at $.05$ even in huge datasets where there is absolutely no need for such a large margin of error. Baysian analysis is not limited to point hyptheses and can find that the data is in a region of practical equivalence to a null hypotheses, a Baysian factor can grow your believe in some sort of null hypothesis equivalent where a $p$ value can only accumulate evidence against it. Could you find ways to emulate that via confidence intervals and other Frequentist methods? Probably yes, but Bayes comes with that approach as the standard.
"But for large enough data, wouldn't the posterior just collapse to the MLE" - what if a posterior was bimodal or if two predictors are correlated so you could have different combinations of e.g. $\beta_8$ and $\beta_9$ - a posterior can represent these different combinations, an MLE point estimator does not.
|
Why should I be Bayesian when my dataset is large?
Being Bayesian is not only about information fed through the prior. But even then: Where the prior is zero, no amount of data will turn that over.
Having a full Bayesian posterior distribution to dra
|
9,125
|
Why should I be Bayesian when my dataset is large?
|
I'd like to echo some of the points in the other answer with slightly different emphasis.
To me the most important issue is that the Bayesian view of uncertainty/probability/randomness is the one that directly answers the questions we probably care about, whereas the Frequentist view of uncertainty directly answers other questions that are often somewhat besides the point. Bayesian inferences try to tell us what we (or an algorithm, machine, etc.) should believe given the data we have seen, or in other words "what can I learn about the world from this data?" Frequentist inferences try to tell us how different our results would be if the data that we actually saw were "re-generated" or "repeatedly sampled" an infinite number of times. Personally I sometimes find Frequentist questions interesting, but I can't think of a scenario where the Bayesian questions aren't what matter most (since at the end of the day I want to make a decision about what to believe or do now that I've seen new data). It's worth noting that often people (statisticians included) incorrectly interpret Frequentist analyses as answering Bayesian questions, probably betraying their actual interests. And while people get worried about the subjectivity inherent in Bayesian methods, I think of the Tukey line, "Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise." For what it's worth, Frequentist methods are also subjective, and arguably in ways that are less obvious and convenient to critique.
Getting off my Bayesian high horse, you're right that answers to Frequentist questions (especially MLE) sometimes coincide closely (and in rare cases, exactly) with answers to Bayesian questions.
However, large data is a vague notion in a few senses that can make Bayesian and Frequentist (MLE) answers remain different:
Most results about large data are asymptotic as the sample size goes to infinity, meaning that they don't tell us when our sample size is actually large enough for the asymptotic result to be accurate enough (up to some known level of error). If you go through the trouble to do both Bayesian and Frequentist analyses of your data and find they're numerically similar then it doesn't matter so much.
Often with "large" data (e.g. many observations) we also have a large number of questions or parameters of interest. This is basically Bernhard's point #4.
A lot of large data sets are not perfectly designed and relate to our interests indirectly because of issues like measurement error or sampling bias. Treated honestly, these complications may not go away even asymptotically, meaning that the models that realistically relate the data to what we care about have non-identifiable sensitivity parameters that are most natural to deal with using priors and the Bayesian machinery.
Of course, the flip-side of this question is "Why should I be Frequentist when my dataset is large?"
|
Why should I be Bayesian when my dataset is large?
|
I'd like to echo some of the points in the other answer with slightly different emphasis.
To me the most important issue is that the Bayesian view of uncertainty/probability/randomness is the one that
|
Why should I be Bayesian when my dataset is large?
I'd like to echo some of the points in the other answer with slightly different emphasis.
To me the most important issue is that the Bayesian view of uncertainty/probability/randomness is the one that directly answers the questions we probably care about, whereas the Frequentist view of uncertainty directly answers other questions that are often somewhat besides the point. Bayesian inferences try to tell us what we (or an algorithm, machine, etc.) should believe given the data we have seen, or in other words "what can I learn about the world from this data?" Frequentist inferences try to tell us how different our results would be if the data that we actually saw were "re-generated" or "repeatedly sampled" an infinite number of times. Personally I sometimes find Frequentist questions interesting, but I can't think of a scenario where the Bayesian questions aren't what matter most (since at the end of the day I want to make a decision about what to believe or do now that I've seen new data). It's worth noting that often people (statisticians included) incorrectly interpret Frequentist analyses as answering Bayesian questions, probably betraying their actual interests. And while people get worried about the subjectivity inherent in Bayesian methods, I think of the Tukey line, "Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise." For what it's worth, Frequentist methods are also subjective, and arguably in ways that are less obvious and convenient to critique.
Getting off my Bayesian high horse, you're right that answers to Frequentist questions (especially MLE) sometimes coincide closely (and in rare cases, exactly) with answers to Bayesian questions.
However, large data is a vague notion in a few senses that can make Bayesian and Frequentist (MLE) answers remain different:
Most results about large data are asymptotic as the sample size goes to infinity, meaning that they don't tell us when our sample size is actually large enough for the asymptotic result to be accurate enough (up to some known level of error). If you go through the trouble to do both Bayesian and Frequentist analyses of your data and find they're numerically similar then it doesn't matter so much.
Often with "large" data (e.g. many observations) we also have a large number of questions or parameters of interest. This is basically Bernhard's point #4.
A lot of large data sets are not perfectly designed and relate to our interests indirectly because of issues like measurement error or sampling bias. Treated honestly, these complications may not go away even asymptotically, meaning that the models that realistically relate the data to what we care about have non-identifiable sensitivity parameters that are most natural to deal with using priors and the Bayesian machinery.
Of course, the flip-side of this question is "Why should I be Frequentist when my dataset is large?"
|
Why should I be Bayesian when my dataset is large?
I'd like to echo some of the points in the other answer with slightly different emphasis.
To me the most important issue is that the Bayesian view of uncertainty/probability/randomness is the one that
|
9,126
|
Why should I be Bayesian when my dataset is large?
|
The other answers address what's probably your actual question. But just to add a more concrete viewpoint: if you're already a Bayesian (for small/medium datasets) and you get a large data, why not use the methodology you're familiar with? It will be relatively slow but you are familiar with the steps so you're less likely to make mistakes and you're more likely to spot problems. And a Bayesian workflow includes things like posterior predictive checks, etc, which are useful for understanding your model.
|
Why should I be Bayesian when my dataset is large?
|
The other answers address what's probably your actual question. But just to add a more concrete viewpoint: if you're already a Bayesian (for small/medium datasets) and you get a large data, why not us
|
Why should I be Bayesian when my dataset is large?
The other answers address what's probably your actual question. But just to add a more concrete viewpoint: if you're already a Bayesian (for small/medium datasets) and you get a large data, why not use the methodology you're familiar with? It will be relatively slow but you are familiar with the steps so you're less likely to make mistakes and you're more likely to spot problems. And a Bayesian workflow includes things like posterior predictive checks, etc, which are useful for understanding your model.
|
Why should I be Bayesian when my dataset is large?
The other answers address what's probably your actual question. But just to add a more concrete viewpoint: if you're already a Bayesian (for small/medium datasets) and you get a large data, why not us
|
9,127
|
Why should I be Bayesian when my dataset is large?
|
One place where Bayesian approach meets large datasets is Bayesian deep learning. When using Bayesian approach to neural networks people usually use rather simplistic priors (Gaussians, centered at zero), this is mostly for computational reasons, but also because there is not much prior knowledge (neural network parameters are black-boxish). The reason why Bayesian approach is used, is because out-of-the-box it gives us uncertainty estimates.
|
Why should I be Bayesian when my dataset is large?
|
One place where Bayesian approach meets large datasets is Bayesian deep learning. When using Bayesian approach to neural networks people usually use rather simplistic priors (Gaussians, centered at ze
|
Why should I be Bayesian when my dataset is large?
One place where Bayesian approach meets large datasets is Bayesian deep learning. When using Bayesian approach to neural networks people usually use rather simplistic priors (Gaussians, centered at zero), this is mostly for computational reasons, but also because there is not much prior knowledge (neural network parameters are black-boxish). The reason why Bayesian approach is used, is because out-of-the-box it gives us uncertainty estimates.
|
Why should I be Bayesian when my dataset is large?
One place where Bayesian approach meets large datasets is Bayesian deep learning. When using Bayesian approach to neural networks people usually use rather simplistic priors (Gaussians, centered at ze
|
9,128
|
Simulate a uniform distribution on a disc
|
You want the proportion of points to be uniformly proportional to area rather than distance to the origin. Since area is proportional to the squared distance, generate uniform random areas and take their square roots; scale the results as desired. Combine that with a uniform polar angle.
This is quick and simple to code, efficient in execution (especially on a parallel platform), and generates exactly the prescribed number of points.
Example
This is working R code to illustrate the algorithm.
n <- 1e4
rho <- sqrt(runif(n))
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(theta)
plot(x, y, pch=19, cex=0.6, col="#00000020")
|
Simulate a uniform distribution on a disc
|
You want the proportion of points to be uniformly proportional to area rather than distance to the origin. Since area is proportional to the squared distance, generate uniform random areas and take t
|
Simulate a uniform distribution on a disc
You want the proportion of points to be uniformly proportional to area rather than distance to the origin. Since area is proportional to the squared distance, generate uniform random areas and take their square roots; scale the results as desired. Combine that with a uniform polar angle.
This is quick and simple to code, efficient in execution (especially on a parallel platform), and generates exactly the prescribed number of points.
Example
This is working R code to illustrate the algorithm.
n <- 1e4
rho <- sqrt(runif(n))
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(theta)
plot(x, y, pch=19, cex=0.6, col="#00000020")
|
Simulate a uniform distribution on a disc
You want the proportion of points to be uniformly proportional to area rather than distance to the origin. Since area is proportional to the squared distance, generate uniform random areas and take t
|
9,129
|
Simulate a uniform distribution on a disc
|
Rejection Sampling can be used. This means we can sample from 2D uniform distribution, and select samples that satisfy the disc condition.
Here is an example.
x=runif(1e4,-1,1)
y=runif(1e4,-1,1)
d=data.frame(x=x,y=y)
disc_sample=d[d$x^2+d$y^2<1,]
plot(disc_sample)
|
Simulate a uniform distribution on a disc
|
Rejection Sampling can be used. This means we can sample from 2D uniform distribution, and select samples that satisfy the disc condition.
Here is an example.
x=runif(1e4,-1,1)
y=runif(1e4,-1,1)
d=d
|
Simulate a uniform distribution on a disc
Rejection Sampling can be used. This means we can sample from 2D uniform distribution, and select samples that satisfy the disc condition.
Here is an example.
x=runif(1e4,-1,1)
y=runif(1e4,-1,1)
d=data.frame(x=x,y=y)
disc_sample=d[d$x^2+d$y^2<1,]
plot(disc_sample)
|
Simulate a uniform distribution on a disc
Rejection Sampling can be used. This means we can sample from 2D uniform distribution, and select samples that satisfy the disc condition.
Here is an example.
x=runif(1e4,-1,1)
y=runif(1e4,-1,1)
d=d
|
9,130
|
Simulate a uniform distribution on a disc
|
I'll give you a general n-dimensional answer that works for two-dimensional case too, of course. In three dimensions an analog of a disk is a volume of a solid ball (sphere).
There are two approaches I'm going to discuss. One of them I would call "precise", and you'll get a complete solution with it in R. The second one I call heuristic, and it's only the idea, no complete solution is provided.
"Precise" solution
My solution is based on Marsaglia and Muller's works. Basically, it happens so that the Gaussian vector normalized to its norm would give you the uniformly distributed points on a d-dimensional hypersphere:
It's the same as uniformely distributed points on a circle in two dimensions. To extend this to the entire surface of a disk, you need to further scale them by radius. The square of a radius is from uniform distribution in two dimensions, or raised to power $d$ in d-dimensions. So, you raise to power $1/d$ a uniform random number to get the properly distributed radius. Here's a complete code in R for two dimensions, which you can easily extend to any number of dimensions:
n <- 1e4
rho <- sqrt(runif(n))
# d - # of dimensions of hyperdisk
d = 2
r = matrix(rnorm(n*d),nrow=n,ncol=d)
x = r/rep(sqrt(rowSums(r^2))/rho,1)
plot(x[,1], x[,2], pch=19, cex=0.6, col="#00000020")
Here's a code snippet for 3d case, i.e. a solid ball:
library(scatterplot3d)
n <- 1e3
# d - # of dimensions of hyperdisk
d=3
rho <- (runif(n))^(1/d)
r = matrix(rnorm(n*d),nrow=n,ncol=d)
x = r/rep(sqrt(rowSums(r^2))/rho,1)
scatterplot3d(x[,1], x[,2], x[,3])
Heuristic approach
This approach is based on a not so obvious fact that the ration of the volume of the unit hypersphere over the volume of a unit hypercube that encloses it shrinks to zero when the number of dimensions increases to infinity. This can easily be seen from the expression for a volume of a hypersphere:
$$V_n(R) = \frac{\pi^\frac{n}{2}}{\Gamma\left(\frac{n}{2} + 1\right)}R^n$$
Here, you can see how the coefficient in front of $R^n$ quickly decreases to zero. This is another manifestation of the phenomenon that is linked to what's known as a dimensionality curse in machine learning.
Why is this relevant to our problem at hand? Suppose, you want to generate d random uniform numbers, these would the random points inside d-dimensional hypercube. Next, you apply rejection sampling to pick the points inside the hypersphere (aka n-ball): $\sum_{i=1}^d x_i^2<R^2$. The problem is that for high number of dimensions d, almost all points will be outside the sphere! You'll end up throwing out vast majority of your samples.
The solution I propose is to use the rejection sampling with oversampling the points near the center. It turns out that if you were watching one of the cartesian coordinates of the random uniform sample from inside the ball, its distribution would be converging to a Gaussian with variance $\frac 1 {\sqrt{d+2}}$. So, instead of picking points uniformly from the cube, we be sampling the cartesian coordinate using the Gaussian, then apply rejection sampling on them. This way we would not be wasting as many generated random variates. This would be a form of importance sampling technique.
|
Simulate a uniform distribution on a disc
|
I'll give you a general n-dimensional answer that works for two-dimensional case too, of course. In three dimensions an analog of a disk is a volume of a solid ball (sphere).
There are two approaches
|
Simulate a uniform distribution on a disc
I'll give you a general n-dimensional answer that works for two-dimensional case too, of course. In three dimensions an analog of a disk is a volume of a solid ball (sphere).
There are two approaches I'm going to discuss. One of them I would call "precise", and you'll get a complete solution with it in R. The second one I call heuristic, and it's only the idea, no complete solution is provided.
"Precise" solution
My solution is based on Marsaglia and Muller's works. Basically, it happens so that the Gaussian vector normalized to its norm would give you the uniformly distributed points on a d-dimensional hypersphere:
It's the same as uniformely distributed points on a circle in two dimensions. To extend this to the entire surface of a disk, you need to further scale them by radius. The square of a radius is from uniform distribution in two dimensions, or raised to power $d$ in d-dimensions. So, you raise to power $1/d$ a uniform random number to get the properly distributed radius. Here's a complete code in R for two dimensions, which you can easily extend to any number of dimensions:
n <- 1e4
rho <- sqrt(runif(n))
# d - # of dimensions of hyperdisk
d = 2
r = matrix(rnorm(n*d),nrow=n,ncol=d)
x = r/rep(sqrt(rowSums(r^2))/rho,1)
plot(x[,1], x[,2], pch=19, cex=0.6, col="#00000020")
Here's a code snippet for 3d case, i.e. a solid ball:
library(scatterplot3d)
n <- 1e3
# d - # of dimensions of hyperdisk
d=3
rho <- (runif(n))^(1/d)
r = matrix(rnorm(n*d),nrow=n,ncol=d)
x = r/rep(sqrt(rowSums(r^2))/rho,1)
scatterplot3d(x[,1], x[,2], x[,3])
Heuristic approach
This approach is based on a not so obvious fact that the ration of the volume of the unit hypersphere over the volume of a unit hypercube that encloses it shrinks to zero when the number of dimensions increases to infinity. This can easily be seen from the expression for a volume of a hypersphere:
$$V_n(R) = \frac{\pi^\frac{n}{2}}{\Gamma\left(\frac{n}{2} + 1\right)}R^n$$
Here, you can see how the coefficient in front of $R^n$ quickly decreases to zero. This is another manifestation of the phenomenon that is linked to what's known as a dimensionality curse in machine learning.
Why is this relevant to our problem at hand? Suppose, you want to generate d random uniform numbers, these would the random points inside d-dimensional hypercube. Next, you apply rejection sampling to pick the points inside the hypersphere (aka n-ball): $\sum_{i=1}^d x_i^2<R^2$. The problem is that for high number of dimensions d, almost all points will be outside the sphere! You'll end up throwing out vast majority of your samples.
The solution I propose is to use the rejection sampling with oversampling the points near the center. It turns out that if you were watching one of the cartesian coordinates of the random uniform sample from inside the ball, its distribution would be converging to a Gaussian with variance $\frac 1 {\sqrt{d+2}}$. So, instead of picking points uniformly from the cube, we be sampling the cartesian coordinate using the Gaussian, then apply rejection sampling on them. This way we would not be wasting as many generated random variates. This would be a form of importance sampling technique.
|
Simulate a uniform distribution on a disc
I'll give you a general n-dimensional answer that works for two-dimensional case too, of course. In three dimensions an analog of a disk is a volume of a solid ball (sphere).
There are two approaches
|
9,131
|
Simulate a uniform distribution on a disc
|
Here is an alternative solution in R:
n <- 1e4
## r <- seq(0, 1, by=1/1000)
r <- runif(n)
rho <- sample(r, size=n, replace=T, prob=r)
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(theta)
plot(x, y, pch=19, cex=0.6, col="#00000020")
|
Simulate a uniform distribution on a disc
|
Here is an alternative solution in R:
n <- 1e4
## r <- seq(0, 1, by=1/1000)
r <- runif(n)
rho <- sample(r, size=n, replace=T, prob=r)
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(th
|
Simulate a uniform distribution on a disc
Here is an alternative solution in R:
n <- 1e4
## r <- seq(0, 1, by=1/1000)
r <- runif(n)
rho <- sample(r, size=n, replace=T, prob=r)
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(theta)
plot(x, y, pch=19, cex=0.6, col="#00000020")
|
Simulate a uniform distribution on a disc
Here is an alternative solution in R:
n <- 1e4
## r <- seq(0, 1, by=1/1000)
r <- runif(n)
rho <- sample(r, size=n, replace=T, prob=r)
theta <- runif(n, 0, 2*pi)
x <- rho * cos(theta)
y <- rho * sin(th
|
9,132
|
An adaptation of the Kullback-Leibler distance?
|
You might look at Chapter 3 of Devroye, Gyorfi, and Lugosi, A Probabilistic Theory of Pattern Recognition, Springer, 1996. See, in particular, the section on $f$-divergences.
$f$-Divergences can be viewed as a generalization of Kullback--Leibler (or, alternatively, KL can be viewed as a special case of an $f$-Divergence).
The general form is
$$
D_f(p, q) = \int q(x) f\left(\frac{p(x)}{q(x)}\right) \, \lambda(dx) ,
$$
where $\lambda$ is a measure that dominates the measures associated with $p$ and $q$ and $f(\cdot)$ is a convex function satisfying $f(1) = 0$. (If $p(x)$ and $q(x)$ are densities with respect to Lebesgue measure, just substitute the notation $dx$ for $\lambda(dx)$ and you're good to go.)
We recover KL by taking $f(x) = x \log x$. We can get the Hellinger difference via $f(x) = (1 - \sqrt{x})^2$ and we get the total-variation or $L_1$ distance by taking $f(x) = \frac{1}{2} |x - 1|$. The latter gives
$$
D_{\mathrm{TV}}(p, q) = \frac{1}{2} \int |p(x) - q(x)| \, dx
$$
Note that this last one at least gives you a finite answer.
In another little book entitled Density Estimation: The $L_1$ View, Devroye argues strongly for the use of this latter distance due to its many nice invariance properties (among others). This latter book is probably a little harder to get a hold of than the former and, as the title suggests, a bit more specialized.
Addendum: Via this question, I became aware that it appears that the measure that @Didier proposes is (up to a constant) known as the Jensen-Shannon Divergence. If you follow the link to the answer provided in that question, you'll see that it turns out that the square-root of this quantity is actually a metric and was previously recognized in the literature to be a special case of an $f$-divergence. I found it interesting that we seem to have collectively "reinvented" the wheel (rather quickly) via the discussion of this question. The interpretation I gave to it in the comment below @Didier's response was also previously recognized. All around, kind of neat, actually.
|
An adaptation of the Kullback-Leibler distance?
|
You might look at Chapter 3 of Devroye, Gyorfi, and Lugosi, A Probabilistic Theory of Pattern Recognition, Springer, 1996. See, in particular, the section on $f$-divergences.
$f$-Divergences can be vi
|
An adaptation of the Kullback-Leibler distance?
You might look at Chapter 3 of Devroye, Gyorfi, and Lugosi, A Probabilistic Theory of Pattern Recognition, Springer, 1996. See, in particular, the section on $f$-divergences.
$f$-Divergences can be viewed as a generalization of Kullback--Leibler (or, alternatively, KL can be viewed as a special case of an $f$-Divergence).
The general form is
$$
D_f(p, q) = \int q(x) f\left(\frac{p(x)}{q(x)}\right) \, \lambda(dx) ,
$$
where $\lambda$ is a measure that dominates the measures associated with $p$ and $q$ and $f(\cdot)$ is a convex function satisfying $f(1) = 0$. (If $p(x)$ and $q(x)$ are densities with respect to Lebesgue measure, just substitute the notation $dx$ for $\lambda(dx)$ and you're good to go.)
We recover KL by taking $f(x) = x \log x$. We can get the Hellinger difference via $f(x) = (1 - \sqrt{x})^2$ and we get the total-variation or $L_1$ distance by taking $f(x) = \frac{1}{2} |x - 1|$. The latter gives
$$
D_{\mathrm{TV}}(p, q) = \frac{1}{2} \int |p(x) - q(x)| \, dx
$$
Note that this last one at least gives you a finite answer.
In another little book entitled Density Estimation: The $L_1$ View, Devroye argues strongly for the use of this latter distance due to its many nice invariance properties (among others). This latter book is probably a little harder to get a hold of than the former and, as the title suggests, a bit more specialized.
Addendum: Via this question, I became aware that it appears that the measure that @Didier proposes is (up to a constant) known as the Jensen-Shannon Divergence. If you follow the link to the answer provided in that question, you'll see that it turns out that the square-root of this quantity is actually a metric and was previously recognized in the literature to be a special case of an $f$-divergence. I found it interesting that we seem to have collectively "reinvented" the wheel (rather quickly) via the discussion of this question. The interpretation I gave to it in the comment below @Didier's response was also previously recognized. All around, kind of neat, actually.
|
An adaptation of the Kullback-Leibler distance?
You might look at Chapter 3 of Devroye, Gyorfi, and Lugosi, A Probabilistic Theory of Pattern Recognition, Springer, 1996. See, in particular, the section on $f$-divergences.
$f$-Divergences can be vi
|
9,133
|
An adaptation of the Kullback-Leibler distance?
|
The Kullback-Leibler divergence $\kappa(P|Q)$ of $P$ with respect to $Q$ is infinite when $P$ is not absolutely continuous with respect to $Q$, that is, when there exists a measurable set $A$ such that $Q(A)=0$ and $P(A)\ne0$. Furthermore the KL divergence is not symmetric, in the sense that in general $\kappa(P\mid Q)\ne\kappa(Q\mid P)$. Recall that
$$
\kappa(P\mid Q)=\int P\log\left(\frac{P}{Q}\right).
$$
A way out of both these drawbacks, still based on KL divergence, is to introduce the midpoint
$$R=\tfrac12(P+Q).
$$
Thus $R$ is a probability measure, and $P$ and $Q$ are always absolutely continuous with respect to $R$. Hence one can consider a "distance" between $P$ and $Q$, still based on KL divergence but using $R$, defined as
$$
\eta(P,Q)=\kappa(P\mid R)+\kappa(Q\mid R).
$$
Then $\eta(P,Q)$ is nonnegative and finite for every $P$ and $Q$, $\eta$ is symmetric in the sense that $\eta(P,Q)=\eta(Q,P)$ for every $P$ and $Q$, and $\eta(P,Q)=0$ iff $P=Q$.
An equivalent formulation is
$$
\eta(P,Q)=2\log(2)+\int \left(P\log(P)+Q\log(Q)-(P+Q)\log(P+Q)\right).
$$
Addendum 1 The introduction of the midpoint of $P$ and $Q$ is not arbitrary in the sense that
$$
\eta(P,Q)=\min [\kappa(P\mid \cdot)+\kappa(Q\mid \cdot)],
$$
where the minimum is over the set of probability measures.
Addendum 2 @cardinal remarks that $\eta$ is also an $f$-divergence, for the convex function
$$
f(x)=x\log(x)ŌłÆ(1+x)\log(1+x)+(1+x)\log(2).
$$
|
An adaptation of the Kullback-Leibler distance?
|
The Kullback-Leibler divergence $\kappa(P|Q)$ of $P$ with respect to $Q$ is infinite when $P$ is not absolutely continuous with respect to $Q$, that is, when there exists a measurable set $A$ such tha
|
An adaptation of the Kullback-Leibler distance?
The Kullback-Leibler divergence $\kappa(P|Q)$ of $P$ with respect to $Q$ is infinite when $P$ is not absolutely continuous with respect to $Q$, that is, when there exists a measurable set $A$ such that $Q(A)=0$ and $P(A)\ne0$. Furthermore the KL divergence is not symmetric, in the sense that in general $\kappa(P\mid Q)\ne\kappa(Q\mid P)$. Recall that
$$
\kappa(P\mid Q)=\int P\log\left(\frac{P}{Q}\right).
$$
A way out of both these drawbacks, still based on KL divergence, is to introduce the midpoint
$$R=\tfrac12(P+Q).
$$
Thus $R$ is a probability measure, and $P$ and $Q$ are always absolutely continuous with respect to $R$. Hence one can consider a "distance" between $P$ and $Q$, still based on KL divergence but using $R$, defined as
$$
\eta(P,Q)=\kappa(P\mid R)+\kappa(Q\mid R).
$$
Then $\eta(P,Q)$ is nonnegative and finite for every $P$ and $Q$, $\eta$ is symmetric in the sense that $\eta(P,Q)=\eta(Q,P)$ for every $P$ and $Q$, and $\eta(P,Q)=0$ iff $P=Q$.
An equivalent formulation is
$$
\eta(P,Q)=2\log(2)+\int \left(P\log(P)+Q\log(Q)-(P+Q)\log(P+Q)\right).
$$
Addendum 1 The introduction of the midpoint of $P$ and $Q$ is not arbitrary in the sense that
$$
\eta(P,Q)=\min [\kappa(P\mid \cdot)+\kappa(Q\mid \cdot)],
$$
where the minimum is over the set of probability measures.
Addendum 2 @cardinal remarks that $\eta$ is also an $f$-divergence, for the convex function
$$
f(x)=x\log(x)ŌłÆ(1+x)\log(1+x)+(1+x)\log(2).
$$
|
An adaptation of the Kullback-Leibler distance?
The Kullback-Leibler divergence $\kappa(P|Q)$ of $P$ with respect to $Q$ is infinite when $P$ is not absolutely continuous with respect to $Q$, that is, when there exists a measurable set $A$ such tha
|
9,134
|
An adaptation of the Kullback-Leibler distance?
|
The Kolmogorov distance between two distributions $P$ and $Q$ is the sup norm of their CDFs. (This is the largest vertical discrepancy between the two graphs of the CDFs.) It is used in distributional testing where $P$ is an hypothesized distribution and $Q$ is the empirical distribution function of a dataset.
It is hard to characterize this as an "adaptation" of the KL distance, but it does meet the other requirements of being "natural" and finite.
Incidentally, because the KL divergence is not a true "distance," we don't have to worry about preserving all the axiomatic properties of a distance. We can maintain the non-negativity property while making the values finite by applying any monotonic transformation $\mathbb{R_+} \to [0,C]$ for some finite value $C$. The inverse tangent will do fine, for instance.
|
An adaptation of the Kullback-Leibler distance?
|
The Kolmogorov distance between two distributions $P$ and $Q$ is the sup norm of their CDFs. (This is the largest vertical discrepancy between the two graphs of the CDFs.) It is used in distribution
|
An adaptation of the Kullback-Leibler distance?
The Kolmogorov distance between two distributions $P$ and $Q$ is the sup norm of their CDFs. (This is the largest vertical discrepancy between the two graphs of the CDFs.) It is used in distributional testing where $P$ is an hypothesized distribution and $Q$ is the empirical distribution function of a dataset.
It is hard to characterize this as an "adaptation" of the KL distance, but it does meet the other requirements of being "natural" and finite.
Incidentally, because the KL divergence is not a true "distance," we don't have to worry about preserving all the axiomatic properties of a distance. We can maintain the non-negativity property while making the values finite by applying any monotonic transformation $\mathbb{R_+} \to [0,C]$ for some finite value $C$. The inverse tangent will do fine, for instance.
|
An adaptation of the Kullback-Leibler distance?
The Kolmogorov distance between two distributions $P$ and $Q$ is the sup norm of their CDFs. (This is the largest vertical discrepancy between the two graphs of the CDFs.) It is used in distribution
|
9,135
|
An adaptation of the Kullback-Leibler distance?
|
Yes there does, Bernardo and Reuda defined something called the "intrinsic discrepancy" which for all purposes is a "symmetrised" version of the KL-divergence. Taking the KL divergence from $P$ to $Q$ to be $\kappa(P \mid Q)$ The intrinsic discrepancy is given by:
$$\delta(P,Q)\equiv \min \big[\kappa(P \mid Q),\kappa(Q \mid P)\big]$$
Searching intrinsic discrepancy (or bayesian reference criterion) will give you some articles on this measure.
In your case, you would just take the KL-divergence which is finite.
Another alternative measure to KL is Hellinger distance
EDIT: clarification, some comments raised suggested that the intrinsic discrepancy will not be finite when one density 0 when the other is not. This is not true if the operation of evaluating the zero density is carried out as a limit $Q\rightarrow 0$ or $P\rightarrow 0$ . The limit is well defined, and it is equal to $0$ for one of the KL divergences, while the other one will diverge. To see this note:
$$\delta(P,Q)\equiv \min \Big[\int P \,\log \big(\frac{P}{Q}\big),\int Q \log \big(\frac{Q}{P}\big)\Big]$$
Taking limit as $P\rightarrow 0$ over a region of the integral, the second integral diverges, and the first integral converges to $0$ over this region (assuming the conditions are such that one can interchange limits and integration). This is because $\lim_{z\rightarrow 0} z \log(z) =0$. Because of the symmetry in $P$ and $Q$ the result also holds for $Q$.
|
An adaptation of the Kullback-Leibler distance?
|
Yes there does, Bernardo and Reuda defined something called the "intrinsic discrepancy" which for all purposes is a "symmetrised" version of the KL-divergence. Taking the KL divergence from $P$ to $Q
|
An adaptation of the Kullback-Leibler distance?
Yes there does, Bernardo and Reuda defined something called the "intrinsic discrepancy" which for all purposes is a "symmetrised" version of the KL-divergence. Taking the KL divergence from $P$ to $Q$ to be $\kappa(P \mid Q)$ The intrinsic discrepancy is given by:
$$\delta(P,Q)\equiv \min \big[\kappa(P \mid Q),\kappa(Q \mid P)\big]$$
Searching intrinsic discrepancy (or bayesian reference criterion) will give you some articles on this measure.
In your case, you would just take the KL-divergence which is finite.
Another alternative measure to KL is Hellinger distance
EDIT: clarification, some comments raised suggested that the intrinsic discrepancy will not be finite when one density 0 when the other is not. This is not true if the operation of evaluating the zero density is carried out as a limit $Q\rightarrow 0$ or $P\rightarrow 0$ . The limit is well defined, and it is equal to $0$ for one of the KL divergences, while the other one will diverge. To see this note:
$$\delta(P,Q)\equiv \min \Big[\int P \,\log \big(\frac{P}{Q}\big),\int Q \log \big(\frac{Q}{P}\big)\Big]$$
Taking limit as $P\rightarrow 0$ over a region of the integral, the second integral diverges, and the first integral converges to $0$ over this region (assuming the conditions are such that one can interchange limits and integration). This is because $\lim_{z\rightarrow 0} z \log(z) =0$. Because of the symmetry in $P$ and $Q$ the result also holds for $Q$.
|
An adaptation of the Kullback-Leibler distance?
Yes there does, Bernardo and Reuda defined something called the "intrinsic discrepancy" which for all purposes is a "symmetrised" version of the KL-divergence. Taking the KL divergence from $P$ to $Q
|
9,136
|
Intuitive explanation for periodicity in Markov chains
|
First of all, your definition is not entirely correct. Here is the correct definition from wikipedia, as suggested by Cyan.
Periodicity (source: wikipedia)
A state i has period k if any return to state i must occur in multiples of k time steps. Formally, the period of a state is defined as
k = $gcd\{ n: \Pr(X_n = i | X_0 = i) > 0\}$
(where "gcd" is the greatest common divisor). Note that even though a state has period k, it may not be possible to reach the state in k steps. For example, suppose it is possible to return to the state in {6, 8, 10, 12, ...} time steps; k would be 2, even though 2 does not appear in this list.
If k = 1, then the state is said to be aperiodic: returns to state i can occur at irregular times. In other words, a state i is aperiodic if there exists n such that for all n' ≥ n,
$Pr(X_{n'} = i | X_0 = i) > 0.$
Otherwise (k > 1), the state is said to be periodic with period k. A Markov chain is aperiodic if every state is aperiodic.
My Explanation
The term periodicity describes whether something (an event, or here: the visit of a particular state) is happening at a regular time interval. Here time is measured in the number of states you visit.
First Example:
Now imagine that the clock represents a markov chain and every hour mark a state, so we got 12 states. Every state is visted by the hour hand every 12 hours (states) with probability=1, so the greatest common divisor is also 12.
So every (hour-)state is periodic with period 12.
Second example:
Imagine a graph describing a sequence of coin tosses, starting at state $start$ and state $heads$ and $tails$ representing the outcome of the last coin toss.
The transition probability is 0.5 for every pair of states (i,j), except $heads$ -> $start$ and $tails$ -> $start$ where it is 0.
Now imagine you are in state $heads$. The number of states you have to visit before you visit $heads$ again could be 1,2,3 etc.. It will happen, so the probability is greater 0, but it is not exactly predictable when. So the greatest common divisior of all possible number of visits which could occur before you visit $heads$ again is 1. This means that $heads$ is aperiodic.
The same applies for $tails$. Since it does not apply for $start$, the whole graph is not aperiodic. If we remove $start$, it would be.
|
Intuitive explanation for periodicity in Markov chains
|
First of all, your definition is not entirely correct. Here is the correct definition from wikipedia, as suggested by Cyan.
Periodicity (source: wikipedia)
A state i has period k if any return to sta
|
Intuitive explanation for periodicity in Markov chains
First of all, your definition is not entirely correct. Here is the correct definition from wikipedia, as suggested by Cyan.
Periodicity (source: wikipedia)
A state i has period k if any return to state i must occur in multiples of k time steps. Formally, the period of a state is defined as
k = $gcd\{ n: \Pr(X_n = i | X_0 = i) > 0\}$
(where "gcd" is the greatest common divisor). Note that even though a state has period k, it may not be possible to reach the state in k steps. For example, suppose it is possible to return to the state in {6, 8, 10, 12, ...} time steps; k would be 2, even though 2 does not appear in this list.
If k = 1, then the state is said to be aperiodic: returns to state i can occur at irregular times. In other words, a state i is aperiodic if there exists n such that for all n' ≥ n,
$Pr(X_{n'} = i | X_0 = i) > 0.$
Otherwise (k > 1), the state is said to be periodic with period k. A Markov chain is aperiodic if every state is aperiodic.
My Explanation
The term periodicity describes whether something (an event, or here: the visit of a particular state) is happening at a regular time interval. Here time is measured in the number of states you visit.
First Example:
Now imagine that the clock represents a markov chain and every hour mark a state, so we got 12 states. Every state is visted by the hour hand every 12 hours (states) with probability=1, so the greatest common divisor is also 12.
So every (hour-)state is periodic with period 12.
Second example:
Imagine a graph describing a sequence of coin tosses, starting at state $start$ and state $heads$ and $tails$ representing the outcome of the last coin toss.
The transition probability is 0.5 for every pair of states (i,j), except $heads$ -> $start$ and $tails$ -> $start$ where it is 0.
Now imagine you are in state $heads$. The number of states you have to visit before you visit $heads$ again could be 1,2,3 etc.. It will happen, so the probability is greater 0, but it is not exactly predictable when. So the greatest common divisior of all possible number of visits which could occur before you visit $heads$ again is 1. This means that $heads$ is aperiodic.
The same applies for $tails$. Since it does not apply for $start$, the whole graph is not aperiodic. If we remove $start$, it would be.
|
Intuitive explanation for periodicity in Markov chains
First of all, your definition is not entirely correct. Here is the correct definition from wikipedia, as suggested by Cyan.
Periodicity (source: wikipedia)
A state i has period k if any return to sta
|
9,137
|
Intuitive explanation for periodicity in Markov chains
|
Let $x$ be a state in some Markov chain. Consider the set $T(x)$ of all possible return times, that is, numbers $t$ such that there is a non-zero probability of returning to $x$ in exactly $t$ steps, starting from $x$. Notice that this is a purely graph-theoretic, not probabilistic notion, in the sense that, if you draw the directed graph underlying the Markov chain (and don't draw any edges corresponding to zero-probability transitions), then $T(x)$ is just the set of all lengths of directed cycles starting at $x$.
The set $T(x)$ has a remarkable property, which is that it is eventually periodic. What I mean by this is that there is some number $P$ such that past a certain point, all members of $T(x)$ are multiples of $P$, and all multiples of $P$ are in $T(x)$. So if you visualize the set $T(x)$ as dots on a line, the dots eventually become perfectly evenly spaced. The number $P$ is known as the period of $x$. When $P=1$, this just means that past a certain point, all return times to $x$ are possible, and $x$ is said to be aperiodic.
The proof that this is the case comes from the fact that $T(x)$ is closed under addition (if $t,s\in T(x)$, then $t+s\in T(x)$), and it turns out any set of positive integers closed under addition has this property. That $T(x)$ is closed under addition should be obvious if you think about it (remember that when we talk about "returning to $x$ in $t$ steps", we don't require that we never visit $x$ in between time). That sets closed under addition have this periodicity property is related to Bézout's identity. The period of $x$, as it turns out, is also equal to the GCD of $T(x)$ (because taking the GCD of an infinite set of numbers makes perfect sense, if you think about it). However, simply defining the period to be the GCD is a terrible way of doing things, pedagogically, because unless you know about this periodicity property, there's no apparent reason why the GCD should be relevant to anything.
If two states communicate, meaning it's possible to go from the first to the second and from the second to the first in some number of steps, then the two have the same period. This is easy to see. Since $x$ and $y$ communicate, it's possible to get from $x$ to $y$ in, say, $r$ steps, and from $y$ to $x$ in $s$ steps. Therefore if $t\in T(y)$, $r+t+s=t+(r+s)\in T(x)$. So if you shift $T(y)$ to the right by $r+s$, you get a subset of $T(x)$. For the same reason, if you shift $T(x)$ to the right by $r+s$, you get a subset of $T(y)$. Given that we know both of those sets are eventually evenly spaced, you can work out that this means the spacing on the two of them must be equal. Because of this, you can take a whole equivalence class of communicating states, and talk about the period of the class, and if you have an irreducible Markov chain (meaning all states communicate), then you can talk about the period of the Markov chain.
The period of an irreducible Markov chain is important because it tells you about the long-term dynamics of the chain. Imagine millions of particles all individually running through the Markov chain independently. Picture a heat-map, where states are color coded according to the amount of particles in that state. What you're picturing is really just a visualization of $\mu_0 M^t$, where $M$ is the transition matrix and $\mu_0$ the initial distribution of particles, the probability distribution of your state at time $t$ given that your starting point was chosen according to distribution $\mu_0$. If the chain is irreducible, then it turns out that this heat map will eventually stabilize over time. It will stabilize in one of two ways:
If the chain is aperiodic, then the heat map eventually essentially stops changing. The distribution of the particles is at equilibrium.
If the chain has period $P$, then after a while the heat map will be seen to cycle between $P$ different distributions, in a kind of "dynamic" equilibrium. The distribution of the particles washes back and forth like a pendulum, in a fixed pattern, forever.
Note that in both cases, the particles are all still moving, and indeed each particle is still independently following the Markov chain and moving completely randomly. It's only the overall distribution of particles that becomes predictable.
Above is a periodic Markov chain, with the time-$t$ distribution visualized as a heatmap (red means high, blue means low - with apologies to any colorblind readers). You can see an animated version to watch the distribution fall into its periodic dynamic equilibrium, starting with all particles concentrated in one state:
Notice that you might naively think the period of the chain is $6$, given the way it looks, but in fact it contains cycles of length both $6$ and $10$, the GCD of which is $2$, so the period of the chain is $2$, as you will see if you watch the animation.
|
Intuitive explanation for periodicity in Markov chains
|
Let $x$ be a state in some Markov chain. Consider the set $T(x)$ of all possible return times, that is, numbers $t$ such that there is a non-zero probability of returning to $x$ in exactly $t$ steps,
|
Intuitive explanation for periodicity in Markov chains
Let $x$ be a state in some Markov chain. Consider the set $T(x)$ of all possible return times, that is, numbers $t$ such that there is a non-zero probability of returning to $x$ in exactly $t$ steps, starting from $x$. Notice that this is a purely graph-theoretic, not probabilistic notion, in the sense that, if you draw the directed graph underlying the Markov chain (and don't draw any edges corresponding to zero-probability transitions), then $T(x)$ is just the set of all lengths of directed cycles starting at $x$.
The set $T(x)$ has a remarkable property, which is that it is eventually periodic. What I mean by this is that there is some number $P$ such that past a certain point, all members of $T(x)$ are multiples of $P$, and all multiples of $P$ are in $T(x)$. So if you visualize the set $T(x)$ as dots on a line, the dots eventually become perfectly evenly spaced. The number $P$ is known as the period of $x$. When $P=1$, this just means that past a certain point, all return times to $x$ are possible, and $x$ is said to be aperiodic.
The proof that this is the case comes from the fact that $T(x)$ is closed under addition (if $t,s\in T(x)$, then $t+s\in T(x)$), and it turns out any set of positive integers closed under addition has this property. That $T(x)$ is closed under addition should be obvious if you think about it (remember that when we talk about "returning to $x$ in $t$ steps", we don't require that we never visit $x$ in between time). That sets closed under addition have this periodicity property is related to Bézout's identity. The period of $x$, as it turns out, is also equal to the GCD of $T(x)$ (because taking the GCD of an infinite set of numbers makes perfect sense, if you think about it). However, simply defining the period to be the GCD is a terrible way of doing things, pedagogically, because unless you know about this periodicity property, there's no apparent reason why the GCD should be relevant to anything.
If two states communicate, meaning it's possible to go from the first to the second and from the second to the first in some number of steps, then the two have the same period. This is easy to see. Since $x$ and $y$ communicate, it's possible to get from $x$ to $y$ in, say, $r$ steps, and from $y$ to $x$ in $s$ steps. Therefore if $t\in T(y)$, $r+t+s=t+(r+s)\in T(x)$. So if you shift $T(y)$ to the right by $r+s$, you get a subset of $T(x)$. For the same reason, if you shift $T(x)$ to the right by $r+s$, you get a subset of $T(y)$. Given that we know both of those sets are eventually evenly spaced, you can work out that this means the spacing on the two of them must be equal. Because of this, you can take a whole equivalence class of communicating states, and talk about the period of the class, and if you have an irreducible Markov chain (meaning all states communicate), then you can talk about the period of the Markov chain.
The period of an irreducible Markov chain is important because it tells you about the long-term dynamics of the chain. Imagine millions of particles all individually running through the Markov chain independently. Picture a heat-map, where states are color coded according to the amount of particles in that state. What you're picturing is really just a visualization of $\mu_0 M^t$, where $M$ is the transition matrix and $\mu_0$ the initial distribution of particles, the probability distribution of your state at time $t$ given that your starting point was chosen according to distribution $\mu_0$. If the chain is irreducible, then it turns out that this heat map will eventually stabilize over time. It will stabilize in one of two ways:
If the chain is aperiodic, then the heat map eventually essentially stops changing. The distribution of the particles is at equilibrium.
If the chain has period $P$, then after a while the heat map will be seen to cycle between $P$ different distributions, in a kind of "dynamic" equilibrium. The distribution of the particles washes back and forth like a pendulum, in a fixed pattern, forever.
Note that in both cases, the particles are all still moving, and indeed each particle is still independently following the Markov chain and moving completely randomly. It's only the overall distribution of particles that becomes predictable.
Above is a periodic Markov chain, with the time-$t$ distribution visualized as a heatmap (red means high, blue means low - with apologies to any colorblind readers). You can see an animated version to watch the distribution fall into its periodic dynamic equilibrium, starting with all particles concentrated in one state:
Notice that you might naively think the period of the chain is $6$, given the way it looks, but in fact it contains cycles of length both $6$ and $10$, the GCD of which is $2$, so the period of the chain is $2$, as you will see if you watch the animation.
|
Intuitive explanation for periodicity in Markov chains
Let $x$ be a state in some Markov chain. Consider the set $T(x)$ of all possible return times, that is, numbers $t$ such that there is a non-zero probability of returning to $x$ in exactly $t$ steps,
|
9,138
|
Intuitive explanation for periodicity in Markov chains
|
To be short, periodic is when you visit each state at uniform rate, aperiodic is when you visit each state at random rate.
|
Intuitive explanation for periodicity in Markov chains
|
To be short, periodic is when you visit each state at uniform rate, aperiodic is when you visit each state at random rate.
|
Intuitive explanation for periodicity in Markov chains
To be short, periodic is when you visit each state at uniform rate, aperiodic is when you visit each state at random rate.
|
Intuitive explanation for periodicity in Markov chains
To be short, periodic is when you visit each state at uniform rate, aperiodic is when you visit each state at random rate.
|
9,139
|
What is "feature space"?
|
Feature Space
Feature space refers to the $n$-dimensions where your variables live (not including a target variable, if it is present). The term is used often in ML literature because a task in ML is feature extraction, hence we view all variables as features. For example, consider the data set with:
Target
$Y \equiv$ Thickness of car tires after some testing period
Variables
$X_1 \equiv$ distance travelled in test
$X_2 \equiv$ time duration of test
$X_3 \equiv$ amount of chemical $C$ in tires
The feature space is $\mathbf{R}^3$, or more accurately, the positive quadrant in $\mathbf{R}^3$ as all the $X$ variables can only be positive quantities. Domain knowledge about tires might suggest that the speed the vehicle was moving at is important, hence we generate another variable, $X_4$ (this is the feature extraction part):
$X_4 =\frac{X_1}{X_2} \equiv$ the speed of the vehicle during testing.
This extends our old feature space into a new one, the positive part of $\mathbf{R}^4$.
Mappings
Furthermore, a mapping in our example is a function, $\phi$, from $\mathbf{R}^3$ to $\mathbf{R}^4$:
$$\phi(x_1,x_2,x_3) = (x_1, x_2, x_3, \frac{x_1}{x_2} )$$
|
What is "feature space"?
|
Feature Space
Feature space refers to the $n$-dimensions where your variables live (not including a target variable, if it is present). The term is used often in ML literature because a task in ML is
|
What is "feature space"?
Feature Space
Feature space refers to the $n$-dimensions where your variables live (not including a target variable, if it is present). The term is used often in ML literature because a task in ML is feature extraction, hence we view all variables as features. For example, consider the data set with:
Target
$Y \equiv$ Thickness of car tires after some testing period
Variables
$X_1 \equiv$ distance travelled in test
$X_2 \equiv$ time duration of test
$X_3 \equiv$ amount of chemical $C$ in tires
The feature space is $\mathbf{R}^3$, or more accurately, the positive quadrant in $\mathbf{R}^3$ as all the $X$ variables can only be positive quantities. Domain knowledge about tires might suggest that the speed the vehicle was moving at is important, hence we generate another variable, $X_4$ (this is the feature extraction part):
$X_4 =\frac{X_1}{X_2} \equiv$ the speed of the vehicle during testing.
This extends our old feature space into a new one, the positive part of $\mathbf{R}^4$.
Mappings
Furthermore, a mapping in our example is a function, $\phi$, from $\mathbf{R}^3$ to $\mathbf{R}^4$:
$$\phi(x_1,x_2,x_3) = (x_1, x_2, x_3, \frac{x_1}{x_2} )$$
|
What is "feature space"?
Feature Space
Feature space refers to the $n$-dimensions where your variables live (not including a target variable, if it is present). The term is used often in ML literature because a task in ML is
|
9,140
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
You can actually measure whether your sample size is "large enough". One symptom of small sample size being too small is instability.
Bootstrap or cross validate your PCA: these techniques disturb your data set by deleting/exchanging a small fraction of your sample and then build "surrogate models" for each of the disturbed data sets. If the surrogate models are similar enough (= stable), you are fine.
You'll probably need to take into account that the solution of the PCA is not unique: PCs can flip (multiply both a score and the respective principal component by $-1$). You may also want to use Procrustes rotation, to obtain PC models that are as similar as possible.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
You can actually measure whether your sample size is "large enough". One symptom of small sample size being too small is instability.
Bootstrap or cross validate your PCA: these techniques disturb you
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
You can actually measure whether your sample size is "large enough". One symptom of small sample size being too small is instability.
Bootstrap or cross validate your PCA: these techniques disturb your data set by deleting/exchanging a small fraction of your sample and then build "surrogate models" for each of the disturbed data sets. If the surrogate models are similar enough (= stable), you are fine.
You'll probably need to take into account that the solution of the PCA is not unique: PCs can flip (multiply both a score and the respective principal component by $-1$). You may also want to use Procrustes rotation, to obtain PC models that are as similar as possible.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
You can actually measure whether your sample size is "large enough". One symptom of small sample size being too small is instability.
Bootstrap or cross validate your PCA: these techniques disturb you
|
9,141
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
For factor analysis (not principal component analysis), there is quite a literature calling into question some of the old rules of thumb on the number of observations. Traditional recommendations – at least within psychometrics – would be to have at least $x$ observations per variable (with $x$ typically anywhere from $5$ to $20$) so in any case $n \gg p$.
A rather thorough overview with many references can be found at http://www.encorewiki.org/display/~nzhao/The+Minimum+Sample+Size+in+Factor+Analysis
However, the main take-away message from recent simulation studies would probably be that the quality of the results vary so much (depending on the communalities, on the number of factors or the factors-to-variables ratio, etc.) that considering the variables-to-observations ratio is not a good way to decide on the required number of observations. If the conditions are auspicious, you might be able to get away with a lot fewer observations than old guidelines would suggest but even the most conservative guidelines are too optimistic in some cases. For example, Preacher & MacCallum (2002) obtained good results with extremely small sample sizes and $p > n$ but Mundfrom, Shaw & Ke (2005) found some cases where a sample size of $n > 100 p$ was necessary. They also found that if the number of underlying factors stays the same, more variables (and not fewer, as implied by guidelines based on the observations-to-variables ratio) could lead to better results with small samples of observations.
Relevant references:
Mundfrom, D.J., Shaw, D.G., & Ke, T.L. (2005). Minimum sample size recommendations for conducting factor analyses. International Journal of Testing, 5 (2), 159-168.
Preacher, K.J., & MacCallum, R.C. (2002). Exploratory factor analysis in behavior genetics research: Factor recovery with small sample sizes. Behavior Genetics, 32 (2), 153-161.
de Winter, J.C.F., Dodou, D., & Wieringa, P.A. (2009). Exploratory factor analysis with small sample sizes. Multivariate Behavioral Research, 44 (2), 147-181.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
For factor analysis (not principal component analysis), there is quite a literature calling into question some of the old rules of thumb on the number of observations. Traditional recommendations – at
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
For factor analysis (not principal component analysis), there is quite a literature calling into question some of the old rules of thumb on the number of observations. Traditional recommendations – at least within psychometrics – would be to have at least $x$ observations per variable (with $x$ typically anywhere from $5$ to $20$) so in any case $n \gg p$.
A rather thorough overview with many references can be found at http://www.encorewiki.org/display/~nzhao/The+Minimum+Sample+Size+in+Factor+Analysis
However, the main take-away message from recent simulation studies would probably be that the quality of the results vary so much (depending on the communalities, on the number of factors or the factors-to-variables ratio, etc.) that considering the variables-to-observations ratio is not a good way to decide on the required number of observations. If the conditions are auspicious, you might be able to get away with a lot fewer observations than old guidelines would suggest but even the most conservative guidelines are too optimistic in some cases. For example, Preacher & MacCallum (2002) obtained good results with extremely small sample sizes and $p > n$ but Mundfrom, Shaw & Ke (2005) found some cases where a sample size of $n > 100 p$ was necessary. They also found that if the number of underlying factors stays the same, more variables (and not fewer, as implied by guidelines based on the observations-to-variables ratio) could lead to better results with small samples of observations.
Relevant references:
Mundfrom, D.J., Shaw, D.G., & Ke, T.L. (2005). Minimum sample size recommendations for conducting factor analyses. International Journal of Testing, 5 (2), 159-168.
Preacher, K.J., & MacCallum, R.C. (2002). Exploratory factor analysis in behavior genetics research: Factor recovery with small sample sizes. Behavior Genetics, 32 (2), 153-161.
de Winter, J.C.F., Dodou, D., & Wieringa, P.A. (2009). Exploratory factor analysis with small sample sizes. Multivariate Behavioral Research, 44 (2), 147-181.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
For factor analysis (not principal component analysis), there is quite a literature calling into question some of the old rules of thumb on the number of observations. Traditional recommendations – at
|
9,142
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
The idea behind the MVA inequalities is simple: PCA is equivalent to estimate the correlation matrix of the variables. You are trying to guess $p\frac{p-1}{2}$ (symetric matrix) coefficients from $np$ data. (That is why you should have n>>p.)
The equivalence can be seen this way: each PCA step is an optimization problem.
We are trying to find wich direction express the most variance. ie:
$$ max( a_{i}^{T} * \Sigma * a_{i} ) $$
Where $\sigma$ is the covariance matrix.
under the constraints:
$$ a_{i}^{T} * a_{i} = 1 $$ (normalization)
$$ a_{i}^{T} * a_{j} = 0 $$ (for $j<i$, orthogonality whith previous components)
The solution of these problems are clearly eigenvectors of $\Sigma $ associated to their eigenvalues. I have to admit that I don't remember the exact formulation, but eigenvenctors depends on the coefficients of $\sigma$. Modulo normalisation of the variables, covariance matrix and correlation matrix are the same thing.
Taking n = p is more or less equivalent to guess a value with only two datas... it's not reliable.
There's no rules of thumbs, just keep in mind that PCA is more or less the same thing as guessing a value from $2\frac{n}{p}$ values.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
The idea behind the MVA inequalities is simple: PCA is equivalent to estimate the correlation matrix of the variables. You are trying to guess $p\frac{p-1}{2}$ (symetric matrix) coefficients from $np$
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
The idea behind the MVA inequalities is simple: PCA is equivalent to estimate the correlation matrix of the variables. You are trying to guess $p\frac{p-1}{2}$ (symetric matrix) coefficients from $np$ data. (That is why you should have n>>p.)
The equivalence can be seen this way: each PCA step is an optimization problem.
We are trying to find wich direction express the most variance. ie:
$$ max( a_{i}^{T} * \Sigma * a_{i} ) $$
Where $\sigma$ is the covariance matrix.
under the constraints:
$$ a_{i}^{T} * a_{i} = 1 $$ (normalization)
$$ a_{i}^{T} * a_{j} = 0 $$ (for $j<i$, orthogonality whith previous components)
The solution of these problems are clearly eigenvectors of $\Sigma $ associated to their eigenvalues. I have to admit that I don't remember the exact formulation, but eigenvenctors depends on the coefficients of $\sigma$. Modulo normalisation of the variables, covariance matrix and correlation matrix are the same thing.
Taking n = p is more or less equivalent to guess a value with only two datas... it's not reliable.
There's no rules of thumbs, just keep in mind that PCA is more or less the same thing as guessing a value from $2\frac{n}{p}$ values.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
The idea behind the MVA inequalities is simple: PCA is equivalent to estimate the correlation matrix of the variables. You are trying to guess $p\frac{p-1}{2}$ (symetric matrix) coefficients from $np$
|
9,143
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
I hope this might be helpful:
for both FA and PCA
''The methods described in this chapter require large samples to derive stable solutions. What constitutes an adequate sample size is somewhat complicated. Until recently, analysts used rules of thumb like “factor analysis requires 5–10 times as many subjects as variables.” Recent studies suggest that the required sample size depends on the number of factors, the number of variables associated with each factor, and how well the set of factors explains the variance in the variables (Bandalos and Boehm-Kaufman, 2009). I’ll go out on a limb and say that if you have several hundred observations, you’re probably safe.''
Reference:
Bandalos, D. L., and M. R. Boehm-Kaufman. 2009. “Four Common Misconceptions in Exploratory Factor Analysis.” In Statistical and Methodological Myths and Urban Legends, edited by C. E. Lance and R. J. Vandenberg, 61–87. New York: Routledge.
from "R in Action" by Robert I. Kabacoff, very informative book with good advises covering almost all statistical tests.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
|
I hope this might be helpful:
for both FA and PCA
''The methods described in this chapter require large samples to derive stable solutions. What constitutes an adequate sample size is s
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
I hope this might be helpful:
for both FA and PCA
''The methods described in this chapter require large samples to derive stable solutions. What constitutes an adequate sample size is somewhat complicated. Until recently, analysts used rules of thumb like “factor analysis requires 5–10 times as many subjects as variables.” Recent studies suggest that the required sample size depends on the number of factors, the number of variables associated with each factor, and how well the set of factors explains the variance in the variables (Bandalos and Boehm-Kaufman, 2009). I’ll go out on a limb and say that if you have several hundred observations, you’re probably safe.''
Reference:
Bandalos, D. L., and M. R. Boehm-Kaufman. 2009. “Four Common Misconceptions in Exploratory Factor Analysis.” In Statistical and Methodological Myths and Urban Legends, edited by C. E. Lance and R. J. Vandenberg, 61–87. New York: Routledge.
from "R in Action" by Robert I. Kabacoff, very informative book with good advises covering almost all statistical tests.
|
Minimum sample size for PCA or FA when the main goal is to estimate only few components?
I hope this might be helpful:
for both FA and PCA
''The methods described in this chapter require large samples to derive stable solutions. What constitutes an adequate sample size is s
|
9,144
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
I like your question, but unfortunately my answer is NO, it doesn't prove $H_0$. The reason is very simple. How would do you know that the distribution of p-values is uniform? You would probably have to run a test for uniformity which will return you its own p-value, and you end up with the same kind of inference question that you were trying to avoid, only one step farther. Instead of looking at p-value of the original $H_0$, now you look at a p-value of another $H'_0$ about the uniformity of distribution of original p-values.
UPDATE
Here's the demonstration. I generate 100 samples of 100 observations from Gaussian and Poisson distribution, then obtain 100 p-values for normality test of each sample. So, the premise of the question is that if the p-values are from uniform distribution, then it proves that the null hypothesis is correct, which is a stronger statement than a usual "fails to reject" in statistical inference. The trouble is that "the p-values are from uniform" is a hypothesis itself, which you have to somehow test.
In the picture (first row) below I'm showing the histograms of p-values from a normality test for the Guassian and Poisson sample, and you can see that it's hard to say whether one is more uniform than the other. That was my main point.
The second row shows one of the samples from each distribution. The samples are relatively small, so you can't have too many bins indeed. Actually, this particular Gaussian sample doesn't look that much Gaussian at all on the histogram.
In the third row, I'm showing the combined samples of 10,000 observations for each distribution on a histogram. Here, you can have more bins, and the shapes are more obvious.
Finally, I run the same normality test and get p-values for the combined samples and it rejects normality for Poisson, while failing to reject for Gaussian. The p-values are: [0.45348631] [0.]
This is not a proof, of course, but the demonstration of the idea that you better run the same test on the combined sample, instead of trying to analyze the distribution of p-values from subsamples.
Here's Python code:
import numpy as np
from scipy import stats
from matplotlib import pyplot as plt
def pvs(x):
pn = x.shape[1]
pvals = np.zeros(pn)
for i in range(pn):
pvals[i] = stats.jarque_bera(x[:,i])[1]
return pvals
n = 100
pn = 100
mu, sigma = 1, 2
np.random.seed(0)
x = np.random.normal(mu, sigma, size=(n,pn))
x2 = np.random.poisson(15, size=(n,pn))
print(x[1,1])
pvals = pvs(x)
pvals2 = pvs(x2)
x_f = x.reshape((n*pn,1))
pvals_f = pvs(x_f)
x2_f = x2.reshape((n*pn,1))
pvals2_f = pvs(x2_f)
print(pvals_f,pvals2_f)
print(x_f.shape,x_f[:,0])
#print(pvals)
plt.figure(figsize=(9,9))
plt.subplot(3,2,1)
plt.hist(pvals)
plt.gca().set_title('True Normal')
plt.gca().set_ylabel('p-value')
plt.subplot(3,2,2)
plt.hist(pvals2)
plt.gca().set_title('Poisson')
plt.gca().set_ylabel('p-value')
plt.subplot(3,2,3)
plt.hist(x[:,0])
plt.gca().set_title('a small sample')
plt.gca().set_ylabel('x')
plt.subplot(3,2,4)
plt.hist(x2[:,0])
plt.gca().set_title('a small Sample')
plt.gca().set_ylabel('x')
plt.subplot(3,2,5)
plt.hist(x_f[:,0],100)
plt.gca().set_title('Full Sample')
plt.gca().set_ylabel('x')
plt.subplot(3,2,6)
plt.hist(x2_f[:,0],100)
plt.gca().set_title('Full Sample')
plt.gca().set_ylabel('x')
plt.show()
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
I like your question, but unfortunately my answer is NO, it doesn't prove $H_0$. The reason is very simple. How would do you know that the distribution of p-values is uniform? You would probably have
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
I like your question, but unfortunately my answer is NO, it doesn't prove $H_0$. The reason is very simple. How would do you know that the distribution of p-values is uniform? You would probably have to run a test for uniformity which will return you its own p-value, and you end up with the same kind of inference question that you were trying to avoid, only one step farther. Instead of looking at p-value of the original $H_0$, now you look at a p-value of another $H'_0$ about the uniformity of distribution of original p-values.
UPDATE
Here's the demonstration. I generate 100 samples of 100 observations from Gaussian and Poisson distribution, then obtain 100 p-values for normality test of each sample. So, the premise of the question is that if the p-values are from uniform distribution, then it proves that the null hypothesis is correct, which is a stronger statement than a usual "fails to reject" in statistical inference. The trouble is that "the p-values are from uniform" is a hypothesis itself, which you have to somehow test.
In the picture (first row) below I'm showing the histograms of p-values from a normality test for the Guassian and Poisson sample, and you can see that it's hard to say whether one is more uniform than the other. That was my main point.
The second row shows one of the samples from each distribution. The samples are relatively small, so you can't have too many bins indeed. Actually, this particular Gaussian sample doesn't look that much Gaussian at all on the histogram.
In the third row, I'm showing the combined samples of 10,000 observations for each distribution on a histogram. Here, you can have more bins, and the shapes are more obvious.
Finally, I run the same normality test and get p-values for the combined samples and it rejects normality for Poisson, while failing to reject for Gaussian. The p-values are: [0.45348631] [0.]
This is not a proof, of course, but the demonstration of the idea that you better run the same test on the combined sample, instead of trying to analyze the distribution of p-values from subsamples.
Here's Python code:
import numpy as np
from scipy import stats
from matplotlib import pyplot as plt
def pvs(x):
pn = x.shape[1]
pvals = np.zeros(pn)
for i in range(pn):
pvals[i] = stats.jarque_bera(x[:,i])[1]
return pvals
n = 100
pn = 100
mu, sigma = 1, 2
np.random.seed(0)
x = np.random.normal(mu, sigma, size=(n,pn))
x2 = np.random.poisson(15, size=(n,pn))
print(x[1,1])
pvals = pvs(x)
pvals2 = pvs(x2)
x_f = x.reshape((n*pn,1))
pvals_f = pvs(x_f)
x2_f = x2.reshape((n*pn,1))
pvals2_f = pvs(x2_f)
print(pvals_f,pvals2_f)
print(x_f.shape,x_f[:,0])
#print(pvals)
plt.figure(figsize=(9,9))
plt.subplot(3,2,1)
plt.hist(pvals)
plt.gca().set_title('True Normal')
plt.gca().set_ylabel('p-value')
plt.subplot(3,2,2)
plt.hist(pvals2)
plt.gca().set_title('Poisson')
plt.gca().set_ylabel('p-value')
plt.subplot(3,2,3)
plt.hist(x[:,0])
plt.gca().set_title('a small sample')
plt.gca().set_ylabel('x')
plt.subplot(3,2,4)
plt.hist(x2[:,0])
plt.gca().set_title('a small Sample')
plt.gca().set_ylabel('x')
plt.subplot(3,2,5)
plt.hist(x_f[:,0],100)
plt.gca().set_title('Full Sample')
plt.gca().set_ylabel('x')
plt.subplot(3,2,6)
plt.hist(x2_f[:,0],100)
plt.gca().set_title('Full Sample')
plt.gca().set_ylabel('x')
plt.show()
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
I like your question, but unfortunately my answer is NO, it doesn't prove $H_0$. The reason is very simple. How would do you know that the distribution of p-values is uniform? You would probably have
|
9,145
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
Your series of experiments can be viewed as a single experiment with far more data, and as we know, more data is advantageous (eg. typically standard errors decrease as $\sqrt{n}$ increases for independent data). But you ask, "Is this ... enough evidence to conclude that H0 is true?"
No. A basic problem is that another theory may produce similar patterns in data! As @Björn discusses in his answer, you will fail to reject a false $H_0$ if your experiment lacks power to distinguish $H_0$ from other possibilities. For centuries, we failed to reject Newton's theory of gravity because no one had conducted the types of tests where Newton's theory gives sufficiently different predictions than Einstein's theory of general relativity. Less extreme examples are commonplace.
David Hume and the problem of induction
Perhaps a rephrasing is, "If I obtain more and more data consistent with $H_0$ being true, can I ever conclude that $H_0$ is true?"
That question is deeply related to 18th century philosopher David Hume's problem of induction. If all observed instances of A have been B, can we say that the next instance of A will be B? Hume famously said no, that we cannot logically deduce that "all A are B" even from voluminous data. In more modern math, a finite set of observations cannot logically entail $\forall_{a \in A} \left[ a \in B \right]$ if A is not a finite set. Two notable examples as discussed by Magee and Passermore:
For centuries, every swan observed by Europeans was white. Then Europeans discovered Australia and saw black swans.
For centuries, Newton's law of gravity agreed with observation and was thought correct. It was overturned though by Einstein's theory of general relativity.
If Hume's conclusion is correct, proving $H_0$ true is unachievable. That we cannot make statements with certitude though is not equivalent to saying we know nothing at all. Experimental science and statistics have been successful in helping us understand and navigate the world.
An (incomplete) listing of ways forward:
Karl Popper and falsificationism
In Karl Popper's view, no scientific law is ever proven true. We only have scientific laws not yet proven false.
Popper argued that science proceeds forward by guessing hypotheses and subjecting them to rigorous scrutiny. It proceeds forward through deduction (observation proving theories false), not induction (repeated observation proving theories true). Much of frequentist statistics was constructed consistent with this philosophy.
Popper's view has been immensely influential, but as Kuhn and others have argued, it does not quite conform to the empirically observed practice of successful science.
Bayesian, subjective probability
Let's assume we're interested in a parameter $\theta$.
To the frequentist statistician, parameter $\theta$ is a scalar value, a number. If you instead take a subjective Bayesian viewpoint (such as in Leonard Jimmie Savage's Foundation of Statistics), you can model your own uncertainty over $\theta$ using the tools of probability. To the subjective Bayesian, $\theta$ is a random variable and you have some prior $P(\theta)$. You can then talk about the subjective probability $P(\theta \mid X)$ of different values of $\theta$ given the data $X$. How you behave in various situations has some correspondence to these subjective probabilities.
This is a logical way to model your own subjective beliefs, but it's not a magic way to produce probabilities that are true in terms of correspondence to reality. A tricky question for any Bayesian interpretation is where do priors come from? Also, what if the model is misspecified?
George P. Box
A famous aphorism of George E.P. Box is that "all models are false, but some are useful."
Newton's law may not be true, but it's still useful for many problems. Box's view is quite important in the modern big data context where studies are so overpowered that you can reject basically any meaningful proposition. Strictly true versus false is a bad question: what matters is whether a model helps you understand the data.
Additional comments
There's a world of difference in statistics between estimating a parameter $\theta \approx 0$ with a small standard error versus with a large standard error! Don't walk away thinking that because certitude is impossible, passing rigorous scrutiny is irrelevant.
Perhaps also of interest, statistically analyzing the results of multiple studies is called meta-analysis.
How far you can go beyond narrow statistical interpretations is a difficult question.
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
Your series of experiments can be viewed as a single experiment with far more data, and as we know, more data is advantageous (eg. typically standard errors decrease as $\sqrt{n}$ increases for indepe
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
Your series of experiments can be viewed as a single experiment with far more data, and as we know, more data is advantageous (eg. typically standard errors decrease as $\sqrt{n}$ increases for independent data). But you ask, "Is this ... enough evidence to conclude that H0 is true?"
No. A basic problem is that another theory may produce similar patterns in data! As @Björn discusses in his answer, you will fail to reject a false $H_0$ if your experiment lacks power to distinguish $H_0$ from other possibilities. For centuries, we failed to reject Newton's theory of gravity because no one had conducted the types of tests where Newton's theory gives sufficiently different predictions than Einstein's theory of general relativity. Less extreme examples are commonplace.
David Hume and the problem of induction
Perhaps a rephrasing is, "If I obtain more and more data consistent with $H_0$ being true, can I ever conclude that $H_0$ is true?"
That question is deeply related to 18th century philosopher David Hume's problem of induction. If all observed instances of A have been B, can we say that the next instance of A will be B? Hume famously said no, that we cannot logically deduce that "all A are B" even from voluminous data. In more modern math, a finite set of observations cannot logically entail $\forall_{a \in A} \left[ a \in B \right]$ if A is not a finite set. Two notable examples as discussed by Magee and Passermore:
For centuries, every swan observed by Europeans was white. Then Europeans discovered Australia and saw black swans.
For centuries, Newton's law of gravity agreed with observation and was thought correct. It was overturned though by Einstein's theory of general relativity.
If Hume's conclusion is correct, proving $H_0$ true is unachievable. That we cannot make statements with certitude though is not equivalent to saying we know nothing at all. Experimental science and statistics have been successful in helping us understand and navigate the world.
An (incomplete) listing of ways forward:
Karl Popper and falsificationism
In Karl Popper's view, no scientific law is ever proven true. We only have scientific laws not yet proven false.
Popper argued that science proceeds forward by guessing hypotheses and subjecting them to rigorous scrutiny. It proceeds forward through deduction (observation proving theories false), not induction (repeated observation proving theories true). Much of frequentist statistics was constructed consistent with this philosophy.
Popper's view has been immensely influential, but as Kuhn and others have argued, it does not quite conform to the empirically observed practice of successful science.
Bayesian, subjective probability
Let's assume we're interested in a parameter $\theta$.
To the frequentist statistician, parameter $\theta$ is a scalar value, a number. If you instead take a subjective Bayesian viewpoint (such as in Leonard Jimmie Savage's Foundation of Statistics), you can model your own uncertainty over $\theta$ using the tools of probability. To the subjective Bayesian, $\theta$ is a random variable and you have some prior $P(\theta)$. You can then talk about the subjective probability $P(\theta \mid X)$ of different values of $\theta$ given the data $X$. How you behave in various situations has some correspondence to these subjective probabilities.
This is a logical way to model your own subjective beliefs, but it's not a magic way to produce probabilities that are true in terms of correspondence to reality. A tricky question for any Bayesian interpretation is where do priors come from? Also, what if the model is misspecified?
George P. Box
A famous aphorism of George E.P. Box is that "all models are false, but some are useful."
Newton's law may not be true, but it's still useful for many problems. Box's view is quite important in the modern big data context where studies are so overpowered that you can reject basically any meaningful proposition. Strictly true versus false is a bad question: what matters is whether a model helps you understand the data.
Additional comments
There's a world of difference in statistics between estimating a parameter $\theta \approx 0$ with a small standard error versus with a large standard error! Don't walk away thinking that because certitude is impossible, passing rigorous scrutiny is irrelevant.
Perhaps also of interest, statistically analyzing the results of multiple studies is called meta-analysis.
How far you can go beyond narrow statistical interpretations is a difficult question.
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
Your series of experiments can be viewed as a single experiment with far more data, and as we know, more data is advantageous (eg. typically standard errors decrease as $\sqrt{n}$ increases for indepe
|
9,146
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
In a sense you are right (see the p-curve) with some small caveats:
you need the test to have some power under the alternative. Illustration of the potential problem: generating a p-value as a uniform distribution on 0 to 1 and rejecting when $p \leq \alpha$ is a (admittedly pretty useless) level $\alpha$ test for any null hypothesis, but you will get a uniform distribution of p-values whether $H_0$ is true or not.
You can only really show that you are quite close to $H_0$ being true (i.e. under the true parameter values three distribution might be close to uniform, even if $H_0$ is false.
With realistic applications, you tend to get additional issues. These mostly arise, because no one person/lab/study group can usually do all the necessary studies. As a result one tends to look at studies from lots of groups, at which point you have increased concerns (i.e. if you had done all relevant experiments yourself, at least you'd know) of underreporting, selective reporting of significant/surprising findings, p-hacking, multiple testing/multiple testing corrections and so on.
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
In a sense you are right (see the p-curve) with some small caveats:
you need the test to have some power under the alternative. Illustration of the potential problem: generating a p-value as a unifo
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
In a sense you are right (see the p-curve) with some small caveats:
you need the test to have some power under the alternative. Illustration of the potential problem: generating a p-value as a uniform distribution on 0 to 1 and rejecting when $p \leq \alpha$ is a (admittedly pretty useless) level $\alpha$ test for any null hypothesis, but you will get a uniform distribution of p-values whether $H_0$ is true or not.
You can only really show that you are quite close to $H_0$ being true (i.e. under the true parameter values three distribution might be close to uniform, even if $H_0$ is false.
With realistic applications, you tend to get additional issues. These mostly arise, because no one person/lab/study group can usually do all the necessary studies. As a result one tends to look at studies from lots of groups, at which point you have increased concerns (i.e. if you had done all relevant experiments yourself, at least you'd know) of underreporting, selective reporting of significant/surprising findings, p-hacking, multiple testing/multiple testing corrections and so on.
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
In a sense you are right (see the p-curve) with some small caveats:
you need the test to have some power under the alternative. Illustration of the potential problem: generating a p-value as a unifo
|
9,147
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
Null hypothesis (H0): Gravity causes everything in the universe to fall toward Earth's surface.
Alternate hypothesis (H1): Nothing ever falls.
Performed 1 million experiments with dozens of household objects, fail to reject H0 with $p < 0.01$ every time. Is H0 true?
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
|
Null hypothesis (H0): Gravity causes everything in the universe to fall toward Earth's surface.
Alternate hypothesis (H1): Nothing ever falls.
Performed 1 million experiments with dozens of household
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
Null hypothesis (H0): Gravity causes everything in the universe to fall toward Earth's surface.
Alternate hypothesis (H1): Nothing ever falls.
Performed 1 million experiments with dozens of household objects, fail to reject H0 with $p < 0.01$ every time. Is H0 true?
|
Does a uniform distribution of many p-values give statistical evidence that H0 is true?
Null hypothesis (H0): Gravity causes everything in the universe to fall toward Earth's surface.
Alternate hypothesis (H1): Nothing ever falls.
Performed 1 million experiments with dozens of household
|
9,148
|
Variable selection procedure for binary classification
|
A very popular approach is penalized logistic regression, in which one maximizes the sum of the log-likelihood and a penalization term consisting of the L1-norm ("lasso"), L2-norm ("ridge"), a combination of the two ("elastic"), or a penalty associated to groups of variables ("group lasso"). This approach has several advantages:
It has strong theoretical properties, e.g., see this paper by Candes & Plan and close connections to compressed sensing;
It has accessible expositions, e.g., in Elements of Statistical Learning by Friedman-Hastie-Tibshirani (available online);
It has readily available software to fit models. R has the glmnet package which is very fast and works well with pretty large datasets. Python has scikit-learn, which includes L1- and L2-penalized logistic regression;
It works very well in practice, as shown in many application papers in image recognition, signal processing, biometrics, and finance.
|
Variable selection procedure for binary classification
|
A very popular approach is penalized logistic regression, in which one maximizes the sum of the log-likelihood and a penalization term consisting of the L1-norm ("lasso"), L2-norm ("ridge"), a combina
|
Variable selection procedure for binary classification
A very popular approach is penalized logistic regression, in which one maximizes the sum of the log-likelihood and a penalization term consisting of the L1-norm ("lasso"), L2-norm ("ridge"), a combination of the two ("elastic"), or a penalty associated to groups of variables ("group lasso"). This approach has several advantages:
It has strong theoretical properties, e.g., see this paper by Candes & Plan and close connections to compressed sensing;
It has accessible expositions, e.g., in Elements of Statistical Learning by Friedman-Hastie-Tibshirani (available online);
It has readily available software to fit models. R has the glmnet package which is very fast and works well with pretty large datasets. Python has scikit-learn, which includes L1- and L2-penalized logistic regression;
It works very well in practice, as shown in many application papers in image recognition, signal processing, biometrics, and finance.
|
Variable selection procedure for binary classification
A very popular approach is penalized logistic regression, in which one maximizes the sum of the log-likelihood and a penalization term consisting of the L1-norm ("lasso"), L2-norm ("ridge"), a combina
|
9,149
|
Variable selection procedure for binary classification
|
I have a slight preference for Random Forests by Leo Breiman & Adele Cutleer for several reasons:
it allows to cope with categorical and continuous predictors, as well as unbalanced class sample size;
as an ensemble/embedded method, cross-validation is embedded and allows to estimate a generalization error;
it is relatively insensible to its tuning parameters (% of variables selected for growing a tree, # of trees built);
it provides an original measure of variable importance and is able to uncover complex interactions between variables (although this may lead to hard to read results).
Some authors argued that it performed as well as penalized SVM or Gradient Boosting Machines (see, e.g. Cutler et al., 2009, for the latter point).
A complete coverage of its applications or advantages may be off the topic, so I suggest the Elements of Statistical Learning from Hastie et al. (chap. 15) and Sayes et al. (2007) for further readings.
Last but not least, it has a nice implementation in R, with the randomForest package. Other R packages also extend or use it, e.g. party and caret.
References:
Cutler, A., Cutler, D.R., and Stevens, J.R. (2009). Tree-Based Methods, in High-Dimensional Data Analysis in Cancer Research, Li, X. and Xu, R. (eds.), pp. 83-101, Springer.
Saeys, Y., Inza, I., and Larrañaga, P. (2007). A review of feature selection techniques in bioinformatics. Bioinformatics, 23(19): 2507-2517.
|
Variable selection procedure for binary classification
|
I have a slight preference for Random Forests by Leo Breiman & Adele Cutleer for several reasons:
it allows to cope with categorical and continuous predictors, as well as unbalanced class sample size
|
Variable selection procedure for binary classification
I have a slight preference for Random Forests by Leo Breiman & Adele Cutleer for several reasons:
it allows to cope with categorical and continuous predictors, as well as unbalanced class sample size;
as an ensemble/embedded method, cross-validation is embedded and allows to estimate a generalization error;
it is relatively insensible to its tuning parameters (% of variables selected for growing a tree, # of trees built);
it provides an original measure of variable importance and is able to uncover complex interactions between variables (although this may lead to hard to read results).
Some authors argued that it performed as well as penalized SVM or Gradient Boosting Machines (see, e.g. Cutler et al., 2009, for the latter point).
A complete coverage of its applications or advantages may be off the topic, so I suggest the Elements of Statistical Learning from Hastie et al. (chap. 15) and Sayes et al. (2007) for further readings.
Last but not least, it has a nice implementation in R, with the randomForest package. Other R packages also extend or use it, e.g. party and caret.
References:
Cutler, A., Cutler, D.R., and Stevens, J.R. (2009). Tree-Based Methods, in High-Dimensional Data Analysis in Cancer Research, Li, X. and Xu, R. (eds.), pp. 83-101, Springer.
Saeys, Y., Inza, I., and Larrañaga, P. (2007). A review of feature selection techniques in bioinformatics. Bioinformatics, 23(19): 2507-2517.
|
Variable selection procedure for binary classification
I have a slight preference for Random Forests by Leo Breiman & Adele Cutleer for several reasons:
it allows to cope with categorical and continuous predictors, as well as unbalanced class sample size
|
9,150
|
Variable selection procedure for binary classification
|
Metropolis scanning / MCMC
Select few features randomly for a
start, train classifier only on them
and obtain the error.
Make some
random change to this working set --
either remove one feature, add
another at random or replace some
feature with one not being currently
used.
Train new classifier and get
its error; store in dE the difference
the error on the new set minus the error on the previous set.
With probability min(1;exp(-beta*dE)) accept this change, otherwise reject it and try another random change.
Repeat it for a long time and finally return the working set that has globally achieved the smallest error.
You may extend it with some wiser control of beta parameter. Simpler way is to use simulated annealing when you increase beta (lower the temperature in physical analogy) over the time to reduce fluctuations and drive the algorithm towards minimum. Harder is to use replica exchange.
|
Variable selection procedure for binary classification
|
Metropolis scanning / MCMC
Select few features randomly for a
start, train classifier only on them
and obtain the error.
Make some
random change to this working set --
either remove one feature, add
|
Variable selection procedure for binary classification
Metropolis scanning / MCMC
Select few features randomly for a
start, train classifier only on them
and obtain the error.
Make some
random change to this working set --
either remove one feature, add
another at random or replace some
feature with one not being currently
used.
Train new classifier and get
its error; store in dE the difference
the error on the new set minus the error on the previous set.
With probability min(1;exp(-beta*dE)) accept this change, otherwise reject it and try another random change.
Repeat it for a long time and finally return the working set that has globally achieved the smallest error.
You may extend it with some wiser control of beta parameter. Simpler way is to use simulated annealing when you increase beta (lower the temperature in physical analogy) over the time to reduce fluctuations and drive the algorithm towards minimum. Harder is to use replica exchange.
|
Variable selection procedure for binary classification
Metropolis scanning / MCMC
Select few features randomly for a
start, train classifier only on them
and obtain the error.
Make some
random change to this working set --
either remove one feature, add
|
9,151
|
Variable selection procedure for binary classification
|
If you are only interested in generalization performance, you are probably better off not performing any feature selection and using regularization instead (e.g. ridge regression). There have been several open challenges in the machine learning community on feature selection, and methods that rely on regularization rather than feature selection generally perform at least as well, if not better.
|
Variable selection procedure for binary classification
|
If you are only interested in generalization performance, you are probably better off not performing any feature selection and using regularization instead (e.g. ridge regression). There have been se
|
Variable selection procedure for binary classification
If you are only interested in generalization performance, you are probably better off not performing any feature selection and using regularization instead (e.g. ridge regression). There have been several open challenges in the machine learning community on feature selection, and methods that rely on regularization rather than feature selection generally perform at least as well, if not better.
|
Variable selection procedure for binary classification
If you are only interested in generalization performance, you are probably better off not performing any feature selection and using regularization instead (e.g. ridge regression). There have been se
|
9,152
|
Variable selection procedure for binary classification
|
Greedy forward selection.
The steps for this method are:
Make sure you have a train and validation set
Repeat the following
Train a classifier with each single feature separately that is not selected yet and with all the previously selected features
If the result improves, add the best performing feature, else stop procedure
|
Variable selection procedure for binary classification
|
Greedy forward selection.
The steps for this method are:
Make sure you have a train and validation set
Repeat the following
Train a classifier with each single feature separately that is not selecte
|
Variable selection procedure for binary classification
Greedy forward selection.
The steps for this method are:
Make sure you have a train and validation set
Repeat the following
Train a classifier with each single feature separately that is not selected yet and with all the previously selected features
If the result improves, add the best performing feature, else stop procedure
|
Variable selection procedure for binary classification
Greedy forward selection.
The steps for this method are:
Make sure you have a train and validation set
Repeat the following
Train a classifier with each single feature separately that is not selecte
|
9,153
|
Variable selection procedure for binary classification
|
Backward elimination.
Start with the full set, then iteratively train the classifier on the remaining features and remove the feature with the smallest importance, stop when the classifier error rapidly increases/becomes unacceptable high.
Importance can be even obtained by removing iteratively each feature and check the error increase or adapted from the classifier if it produces it (like in case of Random Forest).
|
Variable selection procedure for binary classification
|
Backward elimination.
Start with the full set, then iteratively train the classifier on the remaining features and remove the feature with the smallest importance, stop when the classifier error rapid
|
Variable selection procedure for binary classification
Backward elimination.
Start with the full set, then iteratively train the classifier on the remaining features and remove the feature with the smallest importance, stop when the classifier error rapidly increases/becomes unacceptable high.
Importance can be even obtained by removing iteratively each feature and check the error increase or adapted from the classifier if it produces it (like in case of Random Forest).
|
Variable selection procedure for binary classification
Backward elimination.
Start with the full set, then iteratively train the classifier on the remaining features and remove the feature with the smallest importance, stop when the classifier error rapid
|
9,154
|
Why does my bootstrap interval have terrible coverage?
|
Bootstrap diagnostics and remedies by Canto, Davison, Hinkley & Ventura (2006) seems to be a logical point of departure. They discuss multiple ways the bootstrap can break down and - more importantly here - offer diagnostics and possible remedies:
Outliers
Incorrect resampling model
Nonpivotality
Inconsistency of the bootstrap method
I don't see a problem with 1, 2 and 4 in this situation. Let's look at 3. As @Ben Ogorek notes (although I agree with @Glen_b that the normality discussion may be a red herring), the validity of the bootstrap depends on the pivotality of the statistic we are interested in.
Section 4 in Canty et al. suggests resampling-within-resamples to get a measure of bias and variance for the parameter estimate within each bootstrap resample. Here is code to replicate the formulas from p. 15 of the article:
library(boot)
m <- 10 # sample size
n.boot <- 1000
inner.boot <- 1000
set.seed(1)
samp.mean <- bias <- vars <- rep(NA,n.boot)
for ( ii in 1:n.boot ) {
samp <- exp(rnorm(m,0,2)) + 1
samp.mean[ii] <- mean(samp)
foo <- boot(samp,statistic=function(xx,index)mean(xx[index]),R=inner.boot)
bias[ii] <- mean(foo$t[,1])-foo$t0
vars[ii] <- var(foo$t[,1])
}
opar <- par(mfrow=c(1,2))
plot(samp.mean,bias,xlab="Sample means",ylab="Bias",
main="Bias against sample means",pch=19,log="x")
abline(h=0)
plot(samp.mean,vars,xlab="Sample means",ylab="Variance",
main="Variance against sample means",pch=19,log="xy")
par(opar)
Note the log scales - without logs, this is even more blatant. We see nicely how the variance of the bootstrap mean estimate goes up with the mean of the bootstrap sample. This to me looks like enough of a smoking gun to attach blame to nonpivotality as a culprit for the low confidence interval coverage.
However, I'll happily admit that one could follow up in lots of ways. For instance, we could look at how whether the confidence interval from a specific bootstrap replicate includes the true mean depends on the mean of the particular replicate.
As for remedies, Canty et al. discuss transformations, and logarithms come to mind here (e.g., bootstrap and build confidence intervals not for the mean, but for the mean of the logged data), but I couldn't really make it work.
Canty et al. continue to discuss how one can reduce both the number of inner bootstraps and the remaining noise by importance sampling and smoothing as well as add confidence bands to the pivot plots.
This might be a fun thesis project for a smart student. I'd appreciate any pointers to where I went wrong, as well as to any other literature. And I'll take the liberty of adding the diagnostic tag to this question.
|
Why does my bootstrap interval have terrible coverage?
|
Bootstrap diagnostics and remedies by Canto, Davison, Hinkley & Ventura (2006) seems to be a logical point of departure. They discuss multiple ways the bootstrap can break down and - more importantly
|
Why does my bootstrap interval have terrible coverage?
Bootstrap diagnostics and remedies by Canto, Davison, Hinkley & Ventura (2006) seems to be a logical point of departure. They discuss multiple ways the bootstrap can break down and - more importantly here - offer diagnostics and possible remedies:
Outliers
Incorrect resampling model
Nonpivotality
Inconsistency of the bootstrap method
I don't see a problem with 1, 2 and 4 in this situation. Let's look at 3. As @Ben Ogorek notes (although I agree with @Glen_b that the normality discussion may be a red herring), the validity of the bootstrap depends on the pivotality of the statistic we are interested in.
Section 4 in Canty et al. suggests resampling-within-resamples to get a measure of bias and variance for the parameter estimate within each bootstrap resample. Here is code to replicate the formulas from p. 15 of the article:
library(boot)
m <- 10 # sample size
n.boot <- 1000
inner.boot <- 1000
set.seed(1)
samp.mean <- bias <- vars <- rep(NA,n.boot)
for ( ii in 1:n.boot ) {
samp <- exp(rnorm(m,0,2)) + 1
samp.mean[ii] <- mean(samp)
foo <- boot(samp,statistic=function(xx,index)mean(xx[index]),R=inner.boot)
bias[ii] <- mean(foo$t[,1])-foo$t0
vars[ii] <- var(foo$t[,1])
}
opar <- par(mfrow=c(1,2))
plot(samp.mean,bias,xlab="Sample means",ylab="Bias",
main="Bias against sample means",pch=19,log="x")
abline(h=0)
plot(samp.mean,vars,xlab="Sample means",ylab="Variance",
main="Variance against sample means",pch=19,log="xy")
par(opar)
Note the log scales - without logs, this is even more blatant. We see nicely how the variance of the bootstrap mean estimate goes up with the mean of the bootstrap sample. This to me looks like enough of a smoking gun to attach blame to nonpivotality as a culprit for the low confidence interval coverage.
However, I'll happily admit that one could follow up in lots of ways. For instance, we could look at how whether the confidence interval from a specific bootstrap replicate includes the true mean depends on the mean of the particular replicate.
As for remedies, Canty et al. discuss transformations, and logarithms come to mind here (e.g., bootstrap and build confidence intervals not for the mean, but for the mean of the logged data), but I couldn't really make it work.
Canty et al. continue to discuss how one can reduce both the number of inner bootstraps and the remaining noise by importance sampling and smoothing as well as add confidence bands to the pivot plots.
This might be a fun thesis project for a smart student. I'd appreciate any pointers to where I went wrong, as well as to any other literature. And I'll take the liberty of adding the diagnostic tag to this question.
|
Why does my bootstrap interval have terrible coverage?
Bootstrap diagnostics and remedies by Canto, Davison, Hinkley & Ventura (2006) seems to be a logical point of departure. They discuss multiple ways the bootstrap can break down and - more importantly
|
9,155
|
Why does my bootstrap interval have terrible coverage?
|
While I agree with Stephan Kolassa's analysis and conclusion,
$$\hat{\mu} - \mu$$
with $\hat{\mu}$ the sample mean is definitely not an approximate pivot, let me make an additional remark. I investigated the use of the $t$-statistic
$$\sqrt{m} \frac{\hat{\mu} - \mu}{\hat{\sigma}}$$
together with bootstrapping. The result was a coverage of around 0.8. Not a complete solution, but an improvement.
Then I thought a little more about the whole setup. With only 10 observations and an extremely skewed distribution, is it then not basically impossible to nonparametrically estimate the mean let alone construct confidence intervals with the right coverage?
The log-normal distribution considered has mean $e^2 + 1 = 8.39$. Since $P(X \leq 2) = 0.84$ when $X \sim \mathcal{N}(0,4)$ the mean is the $0.84$-quantile of the distribution! It means that the probability that all 10 observations are smaller than the mean is $0.84^{10} = 0.178$. So in a little less than 18% of the cases, the largest observation is smaller than the mean. To get a coverage greater than 0.82 we need a construction of a confidence interval for the mean the extends beyond the largest observation. I have a hard time imagining how such a construction can be made (and justified) without prior assumptions that the distribution is extremely skewed. But I welcome any suggestions.
|
Why does my bootstrap interval have terrible coverage?
|
While I agree with Stephan Kolassa's analysis and conclusion,
$$\hat{\mu} - \mu$$
with $\hat{\mu}$ the sample mean is definitely not an approximate pivot, let me make an additional remark. I investiga
|
Why does my bootstrap interval have terrible coverage?
While I agree with Stephan Kolassa's analysis and conclusion,
$$\hat{\mu} - \mu$$
with $\hat{\mu}$ the sample mean is definitely not an approximate pivot, let me make an additional remark. I investigated the use of the $t$-statistic
$$\sqrt{m} \frac{\hat{\mu} - \mu}{\hat{\sigma}}$$
together with bootstrapping. The result was a coverage of around 0.8. Not a complete solution, but an improvement.
Then I thought a little more about the whole setup. With only 10 observations and an extremely skewed distribution, is it then not basically impossible to nonparametrically estimate the mean let alone construct confidence intervals with the right coverage?
The log-normal distribution considered has mean $e^2 + 1 = 8.39$. Since $P(X \leq 2) = 0.84$ when $X \sim \mathcal{N}(0,4)$ the mean is the $0.84$-quantile of the distribution! It means that the probability that all 10 observations are smaller than the mean is $0.84^{10} = 0.178$. So in a little less than 18% of the cases, the largest observation is smaller than the mean. To get a coverage greater than 0.82 we need a construction of a confidence interval for the mean the extends beyond the largest observation. I have a hard time imagining how such a construction can be made (and justified) without prior assumptions that the distribution is extremely skewed. But I welcome any suggestions.
|
Why does my bootstrap interval have terrible coverage?
While I agree with Stephan Kolassa's analysis and conclusion,
$$\hat{\mu} - \mu$$
with $\hat{\mu}$ the sample mean is definitely not an approximate pivot, let me make an additional remark. I investiga
|
9,156
|
Why does my bootstrap interval have terrible coverage?
|
The calculations were right, I cross-checked with the well-known package boot. Additionally I added the BCa-interval (by Efron), a bias-corrected version of the percentile bootstrap interval:
for (i in 1:1000) {
samp <- exp(rnorm(m, 0, 2)) + 1
boot.out <- boot(samp, function(d, i) sum(d[i]) / m, R=999)
ci <- boot.ci(boot.out, 0.95, type="all")
##tCI <- mean(samp) + c(1,-1)*qt(0.025,df=9)*sd(samp)/sqrt(10)
tCI <- ci$normal[2:3]
percCI <- ci$perc[4:5]
bcaCI <- ci$bca[4:5]
boottCI <- ci$student[4:5]
if (true.mean > min(tCI) && true.mean < max(tCI)) tCI.total <- tCI.total + 1
if (true.mean > min(percCI) && true.mean < max(percCI)) percCI.total <- percCI.total + 1
if (true.mean > min(bcaCI) && true.mean < max(bcaCI)) bcaCI.total <- bcaCI.total + 1
}
tCI.total/1000 # estimate of t interval coverage probability
0.53
percCI.total/1000 # estimate of percentile interval coverage probability
0.55
bcaCI.total/1000 # estimate of BCa interval coverage probability
0.61
I assume the intervals would be far better if the original sample size is larger then 10, say 20 or 50.
Furthermore the bootstrap-t method usually leads to better results for skewed statistics. However it needs a nested loop and therefore 20+ times more computational time.
For hypothesis testing it is also very important that the 1-sided coverages are good. So looking only at the 2-sided coverages can often be misleading.
|
Why does my bootstrap interval have terrible coverage?
|
The calculations were right, I cross-checked with the well-known package boot. Additionally I added the BCa-interval (by Efron), a bias-corrected version of the percentile bootstrap interval:
for (i i
|
Why does my bootstrap interval have terrible coverage?
The calculations were right, I cross-checked with the well-known package boot. Additionally I added the BCa-interval (by Efron), a bias-corrected version of the percentile bootstrap interval:
for (i in 1:1000) {
samp <- exp(rnorm(m, 0, 2)) + 1
boot.out <- boot(samp, function(d, i) sum(d[i]) / m, R=999)
ci <- boot.ci(boot.out, 0.95, type="all")
##tCI <- mean(samp) + c(1,-1)*qt(0.025,df=9)*sd(samp)/sqrt(10)
tCI <- ci$normal[2:3]
percCI <- ci$perc[4:5]
bcaCI <- ci$bca[4:5]
boottCI <- ci$student[4:5]
if (true.mean > min(tCI) && true.mean < max(tCI)) tCI.total <- tCI.total + 1
if (true.mean > min(percCI) && true.mean < max(percCI)) percCI.total <- percCI.total + 1
if (true.mean > min(bcaCI) && true.mean < max(bcaCI)) bcaCI.total <- bcaCI.total + 1
}
tCI.total/1000 # estimate of t interval coverage probability
0.53
percCI.total/1000 # estimate of percentile interval coverage probability
0.55
bcaCI.total/1000 # estimate of BCa interval coverage probability
0.61
I assume the intervals would be far better if the original sample size is larger then 10, say 20 or 50.
Furthermore the bootstrap-t method usually leads to better results for skewed statistics. However it needs a nested loop and therefore 20+ times more computational time.
For hypothesis testing it is also very important that the 1-sided coverages are good. So looking only at the 2-sided coverages can often be misleading.
|
Why does my bootstrap interval have terrible coverage?
The calculations were right, I cross-checked with the well-known package boot. Additionally I added the BCa-interval (by Efron), a bias-corrected version of the percentile bootstrap interval:
for (i i
|
9,157
|
Why does my bootstrap interval have terrible coverage?
|
I was confused about this too, and I spent a lot of time of on the 1996 DiCiccio and Efron paper Bootstrap Confidence Intervals, without much to show for it.
It actually led me to think less of the bootstrap as a general purpose method. I used to think of it as something that would pull you out of a jam when you were really stuck. But I've learned its dirty little secret: bootstrap confidence intervals are all based on normality in some way or another. Allow me to explain.
The bootstrap gives you an estimate of the sampling distribution of the estimator, which is all you could ever hope for, right? But recall that the classical link between the sampling distribution and the confidence interval is based on finding a pivotal quantity. For anyone who's rusty, consider the case where $$x \sim N(\mu, \sigma^2)$$ and $\sigma$ is known. Then the quantity $$z = \frac{x - \mu}{\sigma} \sim N(0,1)$$ is pivotal, i.e., its distribution doesn't depend on $\mu$. Therefore, $\Pr(-1.96 \le \frac{x - \mu}{\sigma} \le 1.96) = 0.95$ and the rest is history.
When you think about what justifies the percentiles of the normal distribution being related to confidence intervals, it is entirely based on this convenient pivotal quantity. For an arbitrary distribution, there is no theoretical link between the percentiles of the sampling distribution and confidence intervals, and taking raw proportions of the bootstrap sampling distribution doesn't cut it.
So Efron's BCa (bias corrected) intervals use transformations to get to approximate normality and bootstrap-t methods rely on the resulting t-statistics being approximately pivotal. Now the bootstrap can estimate the hell out of moments, and you can always assume normality and use the standard +/-2*SE. But considering all the work that went into going non-parametric with the bootstrap, it doesn't seem quite fair, does it?
|
Why does my bootstrap interval have terrible coverage?
|
I was confused about this too, and I spent a lot of time of on the 1996 DiCiccio and Efron paper Bootstrap Confidence Intervals, without much to show for it.
It actually led me to think less of the bo
|
Why does my bootstrap interval have terrible coverage?
I was confused about this too, and I spent a lot of time of on the 1996 DiCiccio and Efron paper Bootstrap Confidence Intervals, without much to show for it.
It actually led me to think less of the bootstrap as a general purpose method. I used to think of it as something that would pull you out of a jam when you were really stuck. But I've learned its dirty little secret: bootstrap confidence intervals are all based on normality in some way or another. Allow me to explain.
The bootstrap gives you an estimate of the sampling distribution of the estimator, which is all you could ever hope for, right? But recall that the classical link between the sampling distribution and the confidence interval is based on finding a pivotal quantity. For anyone who's rusty, consider the case where $$x \sim N(\mu, \sigma^2)$$ and $\sigma$ is known. Then the quantity $$z = \frac{x - \mu}{\sigma} \sim N(0,1)$$ is pivotal, i.e., its distribution doesn't depend on $\mu$. Therefore, $\Pr(-1.96 \le \frac{x - \mu}{\sigma} \le 1.96) = 0.95$ and the rest is history.
When you think about what justifies the percentiles of the normal distribution being related to confidence intervals, it is entirely based on this convenient pivotal quantity. For an arbitrary distribution, there is no theoretical link between the percentiles of the sampling distribution and confidence intervals, and taking raw proportions of the bootstrap sampling distribution doesn't cut it.
So Efron's BCa (bias corrected) intervals use transformations to get to approximate normality and bootstrap-t methods rely on the resulting t-statistics being approximately pivotal. Now the bootstrap can estimate the hell out of moments, and you can always assume normality and use the standard +/-2*SE. But considering all the work that went into going non-parametric with the bootstrap, it doesn't seem quite fair, does it?
|
Why does my bootstrap interval have terrible coverage?
I was confused about this too, and I spent a lot of time of on the 1996 DiCiccio and Efron paper Bootstrap Confidence Intervals, without much to show for it.
It actually led me to think less of the bo
|
9,158
|
Why does my bootstrap interval have terrible coverage?
|
Check out Tim Hesterberg's article in The American Statistician at http://www.timhesterberg.net/bootstrap#TOC-What-Teachers-Should-Know-about-the-Bootstrap:-Resampling-in-the-Undergraduate-Statistics-Curriculum.
Essentially, the bootstrap percentile interval does not have strong coverage probability for skewed data unless n is large.
|
Why does my bootstrap interval have terrible coverage?
|
Check out Tim Hesterberg's article in The American Statistician at http://www.timhesterberg.net/bootstrap#TOC-What-Teachers-Should-Know-about-the-Bootstrap:-Resampling-in-the-Undergraduate-Statistics-
|
Why does my bootstrap interval have terrible coverage?
Check out Tim Hesterberg's article in The American Statistician at http://www.timhesterberg.net/bootstrap#TOC-What-Teachers-Should-Know-about-the-Bootstrap:-Resampling-in-the-Undergraduate-Statistics-Curriculum.
Essentially, the bootstrap percentile interval does not have strong coverage probability for skewed data unless n is large.
|
Why does my bootstrap interval have terrible coverage?
Check out Tim Hesterberg's article in The American Statistician at http://www.timhesterberg.net/bootstrap#TOC-What-Teachers-Should-Know-about-the-Bootstrap:-Resampling-in-the-Undergraduate-Statistics-
|
9,159
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
|
We still care. However, a large part of statistics is now based on a data-driven approach where these concepts may not be essential or there are many other important concepts.
With computation power and lots of data, a large body of statistics is devoted to provide models that solve specific problems (such as forecasting or classification) that can be tested using the given data and cross-validation strategies. So, in these applications, the most important characteristics of models are that they have a good fit to the data and claimed ability to forecast out of sample.
Furthermore, some years ago, we were very interested in unbiased estimators. We still are. However, in that time, in rare situations one could consider to use an estimator that is not unbiased. In situations where we are interested in out of sample forecasts, we may accept an estimator that is clearly biased (such as Ridge Regression, LASSO and Elastic Net) if they are able to reduce the out of sample forecast error. Using these estimators actually we “pay” with bias to reduce the variance of the error or the possibility of overfitting.
This new focus of the literature has also brought new concepts such as sparsistency. In statistical learning theory we study lots of bounds to understand the ability of the generalization of a model (this is crucial). See for instance the beautiful book "Learning From Data" by Abu-Mostafa et al.
Related fields such as econometrics have also been suffering the impact of these changes. Since this field is strongly based on statistical inference and it is fundamental to work with unbiased estimators associated with models that come from the theory, the changes are slower. However, several attempts have been introduced and machine learning (statistical learning) is becoming essential to deal for instance high dimensional databases.
Why is that?
Because economists, in several situations, are interested in the coefficients and not in the predictable variable. For instance, imagine a work that tries to explain corruption-level using a regression model such as: $$\text{corruptionLevel} = \beta_0 + \beta_1 \text{yearsInPrison} + \beta_2 \text{numberConvicted} + \cdots$$
Note that the coefficients $\beta_1$ and $\beta_2$ provide information to guide the public policy. Depending on the values of the coefficients, different public policies will be carried out. So, they cannot be biased.
If the idea is that we should trust in the coefficients of the econometric regression model and we are working with high dimensional databases, maybe we may accept to pay with some bias to receive in return lower variance: “Bias-variance tradeoff holds not only for forecasts (which in the case of a linear model are simply linear combinatons of the estimated coefficients) but also for individual coefficients. One can estimate individual coefficients more accurately (in terms of expected squared error) by introducing bias so as to cut variance. So in that sense biased estimators can be desirable. Remember: we aim at finding the true value. Unbiasedness does not help if variance is large and our estimates lie far away from the true value on average across repeated samples.” - @Richard_Hardy
This idea has motivated researchers to look for solutions that sound good for economists as well. Recent literature has approached this problem by choosing focus variables that are not penalized. These focus variables are the ones that are important to guide public policy. In order to avoid the omitted variables bias, they also run a regression of this focus variables on all the other independent variables using a shrinking procedure (such as Lasso). The ones with coefficients different from zero are also included in the regression model as well. They ensure that asymptotics of this procedure is good. See here a paper of one of the leader of the field. See for instance this overview by leaders of the field.
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
|
We still care. However, a large part of statistics is now based on a data-driven approach where these concepts may not be essential or there are many other important concepts.
With computation power
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
We still care. However, a large part of statistics is now based on a data-driven approach where these concepts may not be essential or there are many other important concepts.
With computation power and lots of data, a large body of statistics is devoted to provide models that solve specific problems (such as forecasting or classification) that can be tested using the given data and cross-validation strategies. So, in these applications, the most important characteristics of models are that they have a good fit to the data and claimed ability to forecast out of sample.
Furthermore, some years ago, we were very interested in unbiased estimators. We still are. However, in that time, in rare situations one could consider to use an estimator that is not unbiased. In situations where we are interested in out of sample forecasts, we may accept an estimator that is clearly biased (such as Ridge Regression, LASSO and Elastic Net) if they are able to reduce the out of sample forecast error. Using these estimators actually we “pay” with bias to reduce the variance of the error or the possibility of overfitting.
This new focus of the literature has also brought new concepts such as sparsistency. In statistical learning theory we study lots of bounds to understand the ability of the generalization of a model (this is crucial). See for instance the beautiful book "Learning From Data" by Abu-Mostafa et al.
Related fields such as econometrics have also been suffering the impact of these changes. Since this field is strongly based on statistical inference and it is fundamental to work with unbiased estimators associated with models that come from the theory, the changes are slower. However, several attempts have been introduced and machine learning (statistical learning) is becoming essential to deal for instance high dimensional databases.
Why is that?
Because economists, in several situations, are interested in the coefficients and not in the predictable variable. For instance, imagine a work that tries to explain corruption-level using a regression model such as: $$\text{corruptionLevel} = \beta_0 + \beta_1 \text{yearsInPrison} + \beta_2 \text{numberConvicted} + \cdots$$
Note that the coefficients $\beta_1$ and $\beta_2$ provide information to guide the public policy. Depending on the values of the coefficients, different public policies will be carried out. So, they cannot be biased.
If the idea is that we should trust in the coefficients of the econometric regression model and we are working with high dimensional databases, maybe we may accept to pay with some bias to receive in return lower variance: “Bias-variance tradeoff holds not only for forecasts (which in the case of a linear model are simply linear combinatons of the estimated coefficients) but also for individual coefficients. One can estimate individual coefficients more accurately (in terms of expected squared error) by introducing bias so as to cut variance. So in that sense biased estimators can be desirable. Remember: we aim at finding the true value. Unbiasedness does not help if variance is large and our estimates lie far away from the true value on average across repeated samples.” - @Richard_Hardy
This idea has motivated researchers to look for solutions that sound good for economists as well. Recent literature has approached this problem by choosing focus variables that are not penalized. These focus variables are the ones that are important to guide public policy. In order to avoid the omitted variables bias, they also run a regression of this focus variables on all the other independent variables using a shrinking procedure (such as Lasso). The ones with coefficients different from zero are also included in the regression model as well. They ensure that asymptotics of this procedure is good. See here a paper of one of the leader of the field. See for instance this overview by leaders of the field.
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
We still care. However, a large part of statistics is now based on a data-driven approach where these concepts may not be essential or there are many other important concepts.
With computation power
|
9,160
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
|
We do care but usually either the issue is taken care of, or we're not making a specific distributional assumption with which we could apply those considerations.
Many of the usual estimators for commonly used parametric models are either fully efficient under the usual distributional assumptions for that model or asymptotically efficient under those model assumptions. Unless we're dealing with fairly small sample sizes, there's nothing to do.
Consider generalized linear models as an obvious example.
We often don't have a fully explicit parametric distributional model. We might use a robust procedure, or we might be looking at some convenient estimator along with a bootstrap for dealing with bias and estimating standard error.
Without an explicit distribution to even start looking at sufficiency or completeness for, there's nothing to do.
(Consider that there may be little point in finding an efficient estimator for a model you're sure will be wrong... what might make more sense would be finding one that does reasonably well in some kind of neighborhood of an approximate model. A good part of the theory for robustness takes a particular sense of the word "neighborhood" when considering a question like this.)
In the comments below Nick Cox points out that "deviations from the ideal -- are often perfectly tolerable"; this is certainly the case. Box wrote "Remember that all models are wrong; the practical question is how wrong do they have to be to not be useful." To me this is a pretty central issue, but I'd add "and in what particular ways" after "how wrong".
It's important to understand the behavior of the tools we use away from the situation they're best at; when do they perform quite well, when do they perform badly (and hopefully what else might do at least as well in a similar range of circumstances).
We need to keep in mind that statistical tools like tests, estimates and intervals all have several senses in which we expect them to 'perform' (e.g. significance level and power, bias and variance, interval width and coverage); for example, there's often a tendency to focus very hard on significance level on tests without paying attention to power.
These issues are less clean-cut than looking at completeness or sufficiency, and we don't have a nice array of "neat" theorems to use. In many cases we may need to use coarser but simpler tools - like simulation - to get much of a sense of what may happen. [In some situations it helps to understand something of the tools of robustness to have clues about what things it might make sense to simulate. It's good to have a sense of what it takes to make something go completely off the rails. I've seen people report that a test has "good robustness to skewness" while simulating nothing more extreme than an exponential distribution, for example, and only examining type I error rate.]
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
|
We do care but usually either the issue is taken care of, or we're not making a specific distributional assumption with which we could apply those considerations.
Many of the usual estimators for co
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
We do care but usually either the issue is taken care of, or we're not making a specific distributional assumption with which we could apply those considerations.
Many of the usual estimators for commonly used parametric models are either fully efficient under the usual distributional assumptions for that model or asymptotically efficient under those model assumptions. Unless we're dealing with fairly small sample sizes, there's nothing to do.
Consider generalized linear models as an obvious example.
We often don't have a fully explicit parametric distributional model. We might use a robust procedure, or we might be looking at some convenient estimator along with a bootstrap for dealing with bias and estimating standard error.
Without an explicit distribution to even start looking at sufficiency or completeness for, there's nothing to do.
(Consider that there may be little point in finding an efficient estimator for a model you're sure will be wrong... what might make more sense would be finding one that does reasonably well in some kind of neighborhood of an approximate model. A good part of the theory for robustness takes a particular sense of the word "neighborhood" when considering a question like this.)
In the comments below Nick Cox points out that "deviations from the ideal -- are often perfectly tolerable"; this is certainly the case. Box wrote "Remember that all models are wrong; the practical question is how wrong do they have to be to not be useful." To me this is a pretty central issue, but I'd add "and in what particular ways" after "how wrong".
It's important to understand the behavior of the tools we use away from the situation they're best at; when do they perform quite well, when do they perform badly (and hopefully what else might do at least as well in a similar range of circumstances).
We need to keep in mind that statistical tools like tests, estimates and intervals all have several senses in which we expect them to 'perform' (e.g. significance level and power, bias and variance, interval width and coverage); for example, there's often a tendency to focus very hard on significance level on tests without paying attention to power.
These issues are less clean-cut than looking at completeness or sufficiency, and we don't have a nice array of "neat" theorems to use. In many cases we may need to use coarser but simpler tools - like simulation - to get much of a sense of what may happen. [In some situations it helps to understand something of the tools of robustness to have clues about what things it might make sense to simulate. It's good to have a sense of what it takes to make something go completely off the rails. I've seen people report that a test has "good robustness to skewness" while simulating nothing more extreme than an exponential distribution, for example, and only examining type I error rate.]
|
Why do we not care about completeness, sufficiency of an estimator as much anymore?
We do care but usually either the issue is taken care of, or we're not making a specific distributional assumption with which we could apply those considerations.
Many of the usual estimators for co
|
9,161
|
How does the L-BFGS work?
|
Basically think of L-BFGS as a way of finding a (local) minimum of an objective function, making use of objective function values and the gradient of the objective function. That level of description covers many optimization methods in addition to L-BFGS though. You can read more about it in section 7.2 of Nocedal and Wright "Numerical Optimization, 2nd edition" http://www.springer.com/us/book/9780387303031 . A very cursory discussion of L-BFGS is provided at https://en.wikipedia.org/wiki/Limited-memory_BFGS .
First order method means gradients (first derivatives) (and maybe objective function values) are used, but not Hessian (second derivatives). Think of, for instance, gradient descent and steepest descent, among many others.
Second order method means gradients and Hessian are used (and maybe objective function values). Second order methods can be either based on
"Exact" Hessian matrix (or finite differences of gradients), in which case they are known as Newton methods or
Quasi-Newton methods, which approximate the Hessian based on differences of gradients over several iterations, by imposing a "secant" (Quasi-Newton) condition. There are many different Quasi-Newton methods, which estimate the Hessian in different ways. One of the most popular is BFGS. The BFGS Hessian approximation can either be based on the full history of gradients, in which case it is referred to as BFGS, or it can be based only on the most recent m gradients, in which case it is known as limited memory BFGS, abbreviated as L-BFGS. The advantage of L-BFGS is that is requires only retaining the most recent m gradients, where m is usually around 5 to 20, which is a much smaller storage requirement than n*(n+1)/2 elements required to store the full (triangle) of a Hessian estimate, as is required with BFGS, where n is the problem dimension. Unlike (full) BFGS, the estimate of the Hessian is never explicitly formed or stored in L-BFGS (although some implementations of BFGS only form and update the Choelsky factor of the Hessian approximation, rather than the Hessian approximation itself); rather, the calculations which would be required with the estimate of the Hessian are accomplished without explicitly forming it. L-BFGS is used instead of BFGS for very large problems (when n is very large), but might not perform as well as BFGS. Therefore, BFGS is preferred over L-BFGS when the memory requirements of BFGS can be met. On the other hand, L-BFGS may not be much worse in performance than BFGS.
Even at this level of description, there are many variants. For instance, the methods can be totally unsafeguarded, in which case anything goes, and they may not converge to anything, even on convex problems. Or they can be safeguarded. Safeguarded methods are usually based on trust regions or line search, and are meant to ensure convergence to something. Very importantly, just knowing that a method is L-BFGS does not by itself tell you what type of safeguarding, if any, is used. It's kind of like saying that a car is a 4-door sedan - but of course not all 4-door sedans are the same in performance or reliability. It is just one attribute of an optimization algorithm.
|
How does the L-BFGS work?
|
Basically think of L-BFGS as a way of finding a (local) minimum of an objective function, making use of objective function values and the gradient of the objective function. That level of description
|
How does the L-BFGS work?
Basically think of L-BFGS as a way of finding a (local) minimum of an objective function, making use of objective function values and the gradient of the objective function. That level of description covers many optimization methods in addition to L-BFGS though. You can read more about it in section 7.2 of Nocedal and Wright "Numerical Optimization, 2nd edition" http://www.springer.com/us/book/9780387303031 . A very cursory discussion of L-BFGS is provided at https://en.wikipedia.org/wiki/Limited-memory_BFGS .
First order method means gradients (first derivatives) (and maybe objective function values) are used, but not Hessian (second derivatives). Think of, for instance, gradient descent and steepest descent, among many others.
Second order method means gradients and Hessian are used (and maybe objective function values). Second order methods can be either based on
"Exact" Hessian matrix (or finite differences of gradients), in which case they are known as Newton methods or
Quasi-Newton methods, which approximate the Hessian based on differences of gradients over several iterations, by imposing a "secant" (Quasi-Newton) condition. There are many different Quasi-Newton methods, which estimate the Hessian in different ways. One of the most popular is BFGS. The BFGS Hessian approximation can either be based on the full history of gradients, in which case it is referred to as BFGS, or it can be based only on the most recent m gradients, in which case it is known as limited memory BFGS, abbreviated as L-BFGS. The advantage of L-BFGS is that is requires only retaining the most recent m gradients, where m is usually around 5 to 20, which is a much smaller storage requirement than n*(n+1)/2 elements required to store the full (triangle) of a Hessian estimate, as is required with BFGS, where n is the problem dimension. Unlike (full) BFGS, the estimate of the Hessian is never explicitly formed or stored in L-BFGS (although some implementations of BFGS only form and update the Choelsky factor of the Hessian approximation, rather than the Hessian approximation itself); rather, the calculations which would be required with the estimate of the Hessian are accomplished without explicitly forming it. L-BFGS is used instead of BFGS for very large problems (when n is very large), but might not perform as well as BFGS. Therefore, BFGS is preferred over L-BFGS when the memory requirements of BFGS can be met. On the other hand, L-BFGS may not be much worse in performance than BFGS.
Even at this level of description, there are many variants. For instance, the methods can be totally unsafeguarded, in which case anything goes, and they may not converge to anything, even on convex problems. Or they can be safeguarded. Safeguarded methods are usually based on trust regions or line search, and are meant to ensure convergence to something. Very importantly, just knowing that a method is L-BFGS does not by itself tell you what type of safeguarding, if any, is used. It's kind of like saying that a car is a 4-door sedan - but of course not all 4-door sedans are the same in performance or reliability. It is just one attribute of an optimization algorithm.
|
How does the L-BFGS work?
Basically think of L-BFGS as a way of finding a (local) minimum of an objective function, making use of objective function values and the gradient of the objective function. That level of description
|
9,162
|
Which is the best visualization for contingency tables?
|
There isn't going to be a one-size-fits-all solution here. If you have a very simple table (e.g., $2\times 2$), simply presenting the table is probably best. If you want an actual figure, mosaic plots (as @xan suggests) are probably a nice place to start. There are some other options that are analogous to mosaic plots, including sieve plots, association plots, and dynamic pressure plots (see my question here: Alternative to sieve / mosaic plots for contingency tables); Michael Friendly's book, Visualizing Categorical Data, would be a good (SAS-based) resource for this topic and the vcd package is a good resource for implementing those ideas in R.
As tables have larger numbers of rows and columns, however, these become harder to use, in my opinion. A different type of visualization option is to perform / plot a correspondence analysis. A correspondence analysis is analogous to running a principal components analysis on both the rows and the columns of the contingency table. Then both are plotted together with a biplot. Here is an R based example using the data from @xan's answer:
library(ca)
tab = as.table(rbind(c(28, 4, 0, 56),
c(38, 5, 9, 10),
c( 6, 6, 14, 13) ))
names(dimnames(tab)) = c("activity", "period")
rownames(tab) = c("feed", "social", "travel")
colnames(tab) = c("morning", "noon", "afternoon", "evening")
tab
# period
# activity morning noon afternoon evening
# feed 28 4 0 56
# social 38 5 9 10
# travel 6 6 14 13
plot(ca(tab))
To interpret this plot, the closer two points of the same type are, the more similar those two row / column profiles are. And the closer two points of different types are, the more of their probability mass is in the cell representing their intersection.
In R there is the ca package; this vignette (pdf) may be helpful as well.
|
Which is the best visualization for contingency tables?
|
There isn't going to be a one-size-fits-all solution here. If you have a very simple table (e.g., $2\times 2$), simply presenting the table is probably best. If you want an actual figure, mosaic plo
|
Which is the best visualization for contingency tables?
There isn't going to be a one-size-fits-all solution here. If you have a very simple table (e.g., $2\times 2$), simply presenting the table is probably best. If you want an actual figure, mosaic plots (as @xan suggests) are probably a nice place to start. There are some other options that are analogous to mosaic plots, including sieve plots, association plots, and dynamic pressure plots (see my question here: Alternative to sieve / mosaic plots for contingency tables); Michael Friendly's book, Visualizing Categorical Data, would be a good (SAS-based) resource for this topic and the vcd package is a good resource for implementing those ideas in R.
As tables have larger numbers of rows and columns, however, these become harder to use, in my opinion. A different type of visualization option is to perform / plot a correspondence analysis. A correspondence analysis is analogous to running a principal components analysis on both the rows and the columns of the contingency table. Then both are plotted together with a biplot. Here is an R based example using the data from @xan's answer:
library(ca)
tab = as.table(rbind(c(28, 4, 0, 56),
c(38, 5, 9, 10),
c( 6, 6, 14, 13) ))
names(dimnames(tab)) = c("activity", "period")
rownames(tab) = c("feed", "social", "travel")
colnames(tab) = c("morning", "noon", "afternoon", "evening")
tab
# period
# activity morning noon afternoon evening
# feed 28 4 0 56
# social 38 5 9 10
# travel 6 6 14 13
plot(ca(tab))
To interpret this plot, the closer two points of the same type are, the more similar those two row / column profiles are. And the closer two points of different types are, the more of their probability mass is in the cell representing their intersection.
In R there is the ca package; this vignette (pdf) may be helpful as well.
|
Which is the best visualization for contingency tables?
There isn't going to be a one-size-fits-all solution here. If you have a very simple table (e.g., $2\times 2$), simply presenting the table is probably best. If you want an actual figure, mosaic plo
|
9,163
|
Which is the best visualization for contingency tables?
|
Different visuals will be better at highlighting different features, but Mosaic plots work well for a general view (checking to see if anything stands out). Maybe that's what you meant by dodged bar plot. Like most options, they're not symmetric in that they represent relative frequencies better in one dimension than the other. A nice feature is that the marginal frequencies are also represented.
|
Which is the best visualization for contingency tables?
|
Different visuals will be better at highlighting different features, but Mosaic plots work well for a general view (checking to see if anything stands out). Maybe that's what you meant by dodged bar p
|
Which is the best visualization for contingency tables?
Different visuals will be better at highlighting different features, but Mosaic plots work well for a general view (checking to see if anything stands out). Maybe that's what you meant by dodged bar plot. Like most options, they're not symmetric in that they represent relative frequencies better in one dimension than the other. A nice feature is that the marginal frequencies are also represented.
|
Which is the best visualization for contingency tables?
Different visuals will be better at highlighting different features, but Mosaic plots work well for a general view (checking to see if anything stands out). Maybe that's what you meant by dodged bar p
|
9,164
|
Which is the best visualization for contingency tables?
|
I agree that the "best" plot doesn't exist independent of dataset, readership and purpose. For two measured variables, scatter plots are arguably the design that leaves all others in its wake, except for specific purposes, but no such market leader is evident for categorical data.
My aim here is just to mention a simple method, often re-discovered or re-invented, but nevertheless also often overlooked even in monographs or textbooks covering statistical graphics.
Example first, covering the same data as posted by xan:
If a name is wanted, as it often is, this is a twoway barchart (in this case). I will not catalogue other terms here, except that multiple barchart is one common alternative with similar flavour. (My small objection to "multiple barchart" is that "multiple" does not rule out the very common stacked or side-by-side bar charts, whereas "twoway" to me more clearly implies a row and column layout, although in turn it may take examples to make that clear.)
Pluses and minuses for this kind of plot are also simple, but I will spell some out. As I am fond of this design (which goes back at least to the 1930s), others may want to add sharper criticisms.
+1. The idea is easily understood, even by non-technical groups. Bar heights or bar lengths encode frequencies in this example. In other examples, they could encode percents calculated any way you like, residuals, etc.
+2. The row-and-column structure matches that of a table. You can add numerical values too. Very small amounts and even implicit zeros are clearly evident, which is not always the case with other designs (e.g. stacked bar charts, mosaic plots). Row and column labelling is usually more efficient than adding a key or legend, with the mental "back and forth" that that requires. Thus this design hybridizes graph and table ideas, which seemingly troubles some readers; conversely, I would argue that strong distinctions between Figures and Tables are just historical hang-overs, obsolete now that researchers can prepare their own documents and do not have to rely on designers, compositors and printers.
+3. Extensions to three-way and higher designs are easy in principle. Put two or more variables as composite variables on either or both axes, or give an array of such plots. Naturally, the more complicated the design, the more complicated the interpretation.
+4. The design clearly allows ordinal variables on either axis. Order can be expressed (e.g.) by appropriate shading as well as the order of categories on that axis. Category order on axes can be determined by their meaning, or better determined by frequencies; alphabetical order according to text labels may be a default, but should never be the only choice considered.
-1. By being general in design the plot can be less efficient in showing certain kinds of relationships. In particular, a mosaic plot can make departures from independence very clear. Conversely, when relationships between categorical variables are complicated or unclear, then typically no graph is good at showing more than that weak fact.
-2. In some ways the design is inefficient in use of space by leaving room for every cross-combination regardless of whether or how frequently it occurs. This is the vice of the same principle considered as a virtue. The particular design above spaces categories equally regardless of their frequency; sacrificing that often sacrifices readable marginal labels, which I value very highly. In this example, the text labels happen all to be very short, but that is far from typical.
Note: xan's data appear just to be invented, so I won't try an interpretation any more than is attempted in other answers. But some homespun wisdom deserves the last word here: the best design for you is one that best conveys to you and your readers the structure of some real data that you care about.
Other examples include
How can you visualize the relationship between 3 categorical variables?
Graph for relationship between two ordinal variables
EDIT The general idea, and a Stata implementation, are now written up in this paper.
|
Which is the best visualization for contingency tables?
|
I agree that the "best" plot doesn't exist independent of dataset, readership and purpose. For two measured variables, scatter plots are arguably the design that leaves all others in its wake, except
|
Which is the best visualization for contingency tables?
I agree that the "best" plot doesn't exist independent of dataset, readership and purpose. For two measured variables, scatter plots are arguably the design that leaves all others in its wake, except for specific purposes, but no such market leader is evident for categorical data.
My aim here is just to mention a simple method, often re-discovered or re-invented, but nevertheless also often overlooked even in monographs or textbooks covering statistical graphics.
Example first, covering the same data as posted by xan:
If a name is wanted, as it often is, this is a twoway barchart (in this case). I will not catalogue other terms here, except that multiple barchart is one common alternative with similar flavour. (My small objection to "multiple barchart" is that "multiple" does not rule out the very common stacked or side-by-side bar charts, whereas "twoway" to me more clearly implies a row and column layout, although in turn it may take examples to make that clear.)
Pluses and minuses for this kind of plot are also simple, but I will spell some out. As I am fond of this design (which goes back at least to the 1930s), others may want to add sharper criticisms.
+1. The idea is easily understood, even by non-technical groups. Bar heights or bar lengths encode frequencies in this example. In other examples, they could encode percents calculated any way you like, residuals, etc.
+2. The row-and-column structure matches that of a table. You can add numerical values too. Very small amounts and even implicit zeros are clearly evident, which is not always the case with other designs (e.g. stacked bar charts, mosaic plots). Row and column labelling is usually more efficient than adding a key or legend, with the mental "back and forth" that that requires. Thus this design hybridizes graph and table ideas, which seemingly troubles some readers; conversely, I would argue that strong distinctions between Figures and Tables are just historical hang-overs, obsolete now that researchers can prepare their own documents and do not have to rely on designers, compositors and printers.
+3. Extensions to three-way and higher designs are easy in principle. Put two or more variables as composite variables on either or both axes, or give an array of such plots. Naturally, the more complicated the design, the more complicated the interpretation.
+4. The design clearly allows ordinal variables on either axis. Order can be expressed (e.g.) by appropriate shading as well as the order of categories on that axis. Category order on axes can be determined by their meaning, or better determined by frequencies; alphabetical order according to text labels may be a default, but should never be the only choice considered.
-1. By being general in design the plot can be less efficient in showing certain kinds of relationships. In particular, a mosaic plot can make departures from independence very clear. Conversely, when relationships between categorical variables are complicated or unclear, then typically no graph is good at showing more than that weak fact.
-2. In some ways the design is inefficient in use of space by leaving room for every cross-combination regardless of whether or how frequently it occurs. This is the vice of the same principle considered as a virtue. The particular design above spaces categories equally regardless of their frequency; sacrificing that often sacrifices readable marginal labels, which I value very highly. In this example, the text labels happen all to be very short, but that is far from typical.
Note: xan's data appear just to be invented, so I won't try an interpretation any more than is attempted in other answers. But some homespun wisdom deserves the last word here: the best design for you is one that best conveys to you and your readers the structure of some real data that you care about.
Other examples include
How can you visualize the relationship between 3 categorical variables?
Graph for relationship between two ordinal variables
EDIT The general idea, and a Stata implementation, are now written up in this paper.
|
Which is the best visualization for contingency tables?
I agree that the "best" plot doesn't exist independent of dataset, readership and purpose. For two measured variables, scatter plots are arguably the design that leaves all others in its wake, except
|
9,165
|
Which is the best visualization for contingency tables?
|
To complement @gung's and @xan's answers, here's an example of mosaic and association plots using vcd in R.
> tab
period
activity morning noon afternoon evening
feed 28 4 0 56
social 38 5 9 10
travel 6 6 14 13
To obtain the plots:
require(vcd)
mosaic(tab, shade=T, legend=T)
assoc(tab, shade=T, legend=T)
Both intuitively present departures from expected frequencies... The default is the model of mutual independence, but it can be changed (e.g. to joint independence if there is a clear response variable) via the expected argument.
See also:
How to interpret a two-dimensional contingency table?
|
Which is the best visualization for contingency tables?
|
To complement @gung's and @xan's answers, here's an example of mosaic and association plots using vcd in R.
> tab
period
activity morning noon afternoon evening
feed 28 4
|
Which is the best visualization for contingency tables?
To complement @gung's and @xan's answers, here's an example of mosaic and association plots using vcd in R.
> tab
period
activity morning noon afternoon evening
feed 28 4 0 56
social 38 5 9 10
travel 6 6 14 13
To obtain the plots:
require(vcd)
mosaic(tab, shade=T, legend=T)
assoc(tab, shade=T, legend=T)
Both intuitively present departures from expected frequencies... The default is the model of mutual independence, but it can be changed (e.g. to joint independence if there is a clear response variable) via the expected argument.
See also:
How to interpret a two-dimensional contingency table?
|
Which is the best visualization for contingency tables?
To complement @gung's and @xan's answers, here's an example of mosaic and association plots using vcd in R.
> tab
period
activity morning noon afternoon evening
feed 28 4
|
9,166
|
Which is the best visualization for contingency tables?
|
One idea that is sometimes useful, especially for somewhat large tables, is to reorder rows/columns to make any structure clearer. One way to do the reordering is to use the sort order of the correspondence analysis row/column scores (on the first eigenvalue). I will show this by an example, in R:
library(FactoMineR)
data(hobbies)
htable <- matrix(as.numeric(NA), nrow=18, ncol=7,
dimnames=list( colnames(hobbies)[1:18],
names(with(hobbies, table(Profession)))))
### Then filling the tables with values:
for(hob in rownames(htable)) {
htable[hob, ] <- table(hobbies[, hob], hobbies[, "Profession"])[2,]
}
### This might be criticized, because it gives more weight to
### people with more hobbies
Then we do the simple correspondence analysis, reorder, and some simplification of names to allow the table to fit on a page:
hobb_ca <- MASS::corresp(htable)
RS <- hobb_ca$rscore
CS <- hobb_ca$cscore
### Reordered table:
htable_reordered <- htable[order(RS), order(CS)]
colnames(htable_reordered) <- abbreviate(colnames(htable_reordered))
round(prop.table(htable_reordered, 1), 2)
Mngm Frmn Othr Tchn Empl Mnll Unsw
Exhibition 0.28 0.15 0.03 0.06 0.33 0.10 0.04
Show 0.27 0.13 0.03 0.07 0.37 0.09 0.04
Volunteering 0.24 0.15 0.04 0.06 0.35 0.11 0.05
Playing music 0.25 0.13 0.04 0.07 0.37 0.09 0.06
Travelling 0.26 0.14 0.03 0.07 0.33 0.11 0.06
Computer 0.23 0.13 0.03 0.08 0.35 0.12 0.06
Sport 0.23 0.14 0.03 0.07 0.34 0.12 0.06
Cinema 0.23 0.13 0.03 0.06 0.37 0.11 0.07
TV 0.21 0.13 0.04 0.06 0.34 0.14 0.08
Reading 0.20 0.12 0.03 0.05 0.39 0.13 0.08
Walking 0.18 0.13 0.03 0.06 0.37 0.15 0.09
Listening music 0.17 0.11 0.03 0.06 0.38 0.15 0.10
Gardening 0.18 0.12 0.03 0.06 0.34 0.18 0.09
Mechanic 0.18 0.13 0.03 0.08 0.29 0.21 0.09
Collecting 0.16 0.11 0.02 0.07 0.38 0.17 0.09
Cooking 0.15 0.10 0.03 0.05 0.42 0.14 0.10
Knitting 0.10 0.09 0.04 0.03 0.54 0.08 0.12
Fishing 0.13 0.12 0.02 0.08 0.21 0.28 0.14
To help the reading, a table of names with abbreviated names:
"Unskilled worker" "Unsw"
"Manual labourer" "Mnll"
"Technician" "Tchn"
"Foreman" "Frmn"
"Management" "Mngm"
"Employee" "Empl"
"Other" "Othr"
The group "Other" seems strange, with uniformly lower interest in hobbies than all the others! And look at "Fishing", the groups with a high general interest in hobbies have a low interest, while it for "Manual labourer" and "Unskilled worker" scores the highest. Is this as easy to see in the original table?
|
Which is the best visualization for contingency tables?
|
One idea that is sometimes useful, especially for somewhat large tables, is to reorder rows/columns to make any structure clearer. One way to do the reordering is to use the sort order of the correspo
|
Which is the best visualization for contingency tables?
One idea that is sometimes useful, especially for somewhat large tables, is to reorder rows/columns to make any structure clearer. One way to do the reordering is to use the sort order of the correspondence analysis row/column scores (on the first eigenvalue). I will show this by an example, in R:
library(FactoMineR)
data(hobbies)
htable <- matrix(as.numeric(NA), nrow=18, ncol=7,
dimnames=list( colnames(hobbies)[1:18],
names(with(hobbies, table(Profession)))))
### Then filling the tables with values:
for(hob in rownames(htable)) {
htable[hob, ] <- table(hobbies[, hob], hobbies[, "Profession"])[2,]
}
### This might be criticized, because it gives more weight to
### people with more hobbies
Then we do the simple correspondence analysis, reorder, and some simplification of names to allow the table to fit on a page:
hobb_ca <- MASS::corresp(htable)
RS <- hobb_ca$rscore
CS <- hobb_ca$cscore
### Reordered table:
htable_reordered <- htable[order(RS), order(CS)]
colnames(htable_reordered) <- abbreviate(colnames(htable_reordered))
round(prop.table(htable_reordered, 1), 2)
Mngm Frmn Othr Tchn Empl Mnll Unsw
Exhibition 0.28 0.15 0.03 0.06 0.33 0.10 0.04
Show 0.27 0.13 0.03 0.07 0.37 0.09 0.04
Volunteering 0.24 0.15 0.04 0.06 0.35 0.11 0.05
Playing music 0.25 0.13 0.04 0.07 0.37 0.09 0.06
Travelling 0.26 0.14 0.03 0.07 0.33 0.11 0.06
Computer 0.23 0.13 0.03 0.08 0.35 0.12 0.06
Sport 0.23 0.14 0.03 0.07 0.34 0.12 0.06
Cinema 0.23 0.13 0.03 0.06 0.37 0.11 0.07
TV 0.21 0.13 0.04 0.06 0.34 0.14 0.08
Reading 0.20 0.12 0.03 0.05 0.39 0.13 0.08
Walking 0.18 0.13 0.03 0.06 0.37 0.15 0.09
Listening music 0.17 0.11 0.03 0.06 0.38 0.15 0.10
Gardening 0.18 0.12 0.03 0.06 0.34 0.18 0.09
Mechanic 0.18 0.13 0.03 0.08 0.29 0.21 0.09
Collecting 0.16 0.11 0.02 0.07 0.38 0.17 0.09
Cooking 0.15 0.10 0.03 0.05 0.42 0.14 0.10
Knitting 0.10 0.09 0.04 0.03 0.54 0.08 0.12
Fishing 0.13 0.12 0.02 0.08 0.21 0.28 0.14
To help the reading, a table of names with abbreviated names:
"Unskilled worker" "Unsw"
"Manual labourer" "Mnll"
"Technician" "Tchn"
"Foreman" "Frmn"
"Management" "Mngm"
"Employee" "Empl"
"Other" "Othr"
The group "Other" seems strange, with uniformly lower interest in hobbies than all the others! And look at "Fishing", the groups with a high general interest in hobbies have a low interest, while it for "Manual labourer" and "Unskilled worker" scores the highest. Is this as easy to see in the original table?
|
Which is the best visualization for contingency tables?
One idea that is sometimes useful, especially for somewhat large tables, is to reorder rows/columns to make any structure clearer. One way to do the reordering is to use the sort order of the correspo
|
9,167
|
Sum of exponential random variables follows Gamma, confused by the parameters
|
The sum of $n$ independent Gamma random variables $\sim \Gamma(t_i, \lambda)$ is a Gamma random variable $\sim \Gamma\left(\sum_i t_i, \lambda\right)$. It does not matter what the second parameter means (scale or inverse of scale) as long as all $n$ random variable have the same second parameter. This idea extends readily
to $\chi^2$ random variables which are a special case of Gamma random variables.
|
Sum of exponential random variables follows Gamma, confused by the parameters
|
The sum of $n$ independent Gamma random variables $\sim \Gamma(t_i, \lambda)$ is a Gamma random variable $\sim \Gamma\left(\sum_i t_i, \lambda\right)$. It does not matter what the second parameter mea
|
Sum of exponential random variables follows Gamma, confused by the parameters
The sum of $n$ independent Gamma random variables $\sim \Gamma(t_i, \lambda)$ is a Gamma random variable $\sim \Gamma\left(\sum_i t_i, \lambda\right)$. It does not matter what the second parameter means (scale or inverse of scale) as long as all $n$ random variable have the same second parameter. This idea extends readily
to $\chi^2$ random variables which are a special case of Gamma random variables.
|
Sum of exponential random variables follows Gamma, confused by the parameters
The sum of $n$ independent Gamma random variables $\sim \Gamma(t_i, \lambda)$ is a Gamma random variable $\sim \Gamma\left(\sum_i t_i, \lambda\right)$. It does not matter what the second parameter mea
|
9,168
|
Sum of exponential random variables follows Gamma, confused by the parameters
|
The sum of $n$ iid exponential distributions with scale $\theta$ (rate $\theta^{-1}$) is gamma-distributed with shape $n$ and scale $\theta$ (rate $\theta^{-1}$).
|
Sum of exponential random variables follows Gamma, confused by the parameters
|
The sum of $n$ iid exponential distributions with scale $\theta$ (rate $\theta^{-1}$) is gamma-distributed with shape $n$ and scale $\theta$ (rate $\theta^{-1}$).
|
Sum of exponential random variables follows Gamma, confused by the parameters
The sum of $n$ iid exponential distributions with scale $\theta$ (rate $\theta^{-1}$) is gamma-distributed with shape $n$ and scale $\theta$ (rate $\theta^{-1}$).
|
Sum of exponential random variables follows Gamma, confused by the parameters
The sum of $n$ iid exponential distributions with scale $\theta$ (rate $\theta^{-1}$) is gamma-distributed with shape $n$ and scale $\theta$ (rate $\theta^{-1}$).
|
9,169
|
Sum of exponential random variables follows Gamma, confused by the parameters
|
gamma distribution is made of exponential distribution that is exponential distribution is base for gamma distribution.
then if $f(x|\lambda)=\lambda e^{−\lambda x}$ we have $\sum_n x_i \sim \text{Gamma}(n,\lambda)$, as long as all $X_i$ are independent.
$$f(x|\alpha,\beta)=\frac{\beta^α}{\Gamma(\alpha)} \cdot x^{\alpha−1} \cdot e^{−x\beta} $$
|
Sum of exponential random variables follows Gamma, confused by the parameters
|
gamma distribution is made of exponential distribution that is exponential distribution is base for gamma distribution.
then if $f(x|\lambda)=\lambda e^{−\lambda x}$ we have $\sum_n x_i \sim \text{Gam
|
Sum of exponential random variables follows Gamma, confused by the parameters
gamma distribution is made of exponential distribution that is exponential distribution is base for gamma distribution.
then if $f(x|\lambda)=\lambda e^{−\lambda x}$ we have $\sum_n x_i \sim \text{Gamma}(n,\lambda)$, as long as all $X_i$ are independent.
$$f(x|\alpha,\beta)=\frac{\beta^α}{\Gamma(\alpha)} \cdot x^{\alpha−1} \cdot e^{−x\beta} $$
|
Sum of exponential random variables follows Gamma, confused by the parameters
gamma distribution is made of exponential distribution that is exponential distribution is base for gamma distribution.
then if $f(x|\lambda)=\lambda e^{−\lambda x}$ we have $\sum_n x_i \sim \text{Gam
|
9,170
|
Why are p-values misleading after performing a stepwise selection?
|
after performing a stepwise selection based on the AIC criterion, it is misleading to look at the p-values to test the null hypothesis that each true regression coefficient is zero.
Indeed, p-values represent the probability of seeing a test statistic at least as extreme as the one you have, when the null hypothesis is true. If $H_0$ is true, the p-value should have a uniform distribution.
But after stepwise selection (or indeed, after a variety of other approaches to model selection), the p-values of those terms that remain in the model don't have that property, even when we know that the null hypothesis is true.
This happens because we choose the variables that have or tend to have small p-values (depending on the precise criteria we used). This means that the p-values of the variables left in the model are typically much smaller than they would be if we'd fitted a single model. Note that selection will on average pick models that seem to fit even better than the true model, if the class of models includes the true model, or if the class of models is flexible enough to closely approximate the true model.
[In addition and for basically the same reason, the coefficients that remain are biased away from zero and their standard errors are biased low; this in turn impacts confidence intervals and predictions as well -- our prediction intervals will be too narrow for example.]
To see these effects, we can take multiple regression where some coefficients are 0 and some are not, perform a stepwise procedure and then for those models that contain variables that had zero coefficients, look at the p-values that result.
(In the same simulation, you can look at the estimates and the standard deviations for the coefficients and discover the ones that correspond to non-zero coefficients are also impacted.)
In short, it's not appropriate to consider the usual p-values as meaningful.
I heard that one should consider all the variables left in the model as significant instead.
As to whether all the values in the model after stepwise should be 'regarded as significant', I'm not sure the extent to which that's a useful way to look at it. What is "significance" intended to mean then?
Here's the result of running R's stepAIC with default settings on 1000 simulated samples with n=100, and ten candidate variables (none of which are related to the response). In each case the number of terms left in the model was counted:
Only 15.5% of the time was the correct model chosen; the rest of the time the model included terms that were not different from zero. If it's actually possible that there are zero-coefficient variables in the set of candidate variables, we are likely to have several terms where the true coefficient is zero in our model. As a result, it's not clear it's a good idea to regard all of them as non-zero.
|
Why are p-values misleading after performing a stepwise selection?
|
after performing a stepwise selection based on the AIC criterion, it is misleading to look at the p-values to test the null hypothesis that each true regression coefficient is zero.
Indeed, p-values
|
Why are p-values misleading after performing a stepwise selection?
after performing a stepwise selection based on the AIC criterion, it is misleading to look at the p-values to test the null hypothesis that each true regression coefficient is zero.
Indeed, p-values represent the probability of seeing a test statistic at least as extreme as the one you have, when the null hypothesis is true. If $H_0$ is true, the p-value should have a uniform distribution.
But after stepwise selection (or indeed, after a variety of other approaches to model selection), the p-values of those terms that remain in the model don't have that property, even when we know that the null hypothesis is true.
This happens because we choose the variables that have or tend to have small p-values (depending on the precise criteria we used). This means that the p-values of the variables left in the model are typically much smaller than they would be if we'd fitted a single model. Note that selection will on average pick models that seem to fit even better than the true model, if the class of models includes the true model, or if the class of models is flexible enough to closely approximate the true model.
[In addition and for basically the same reason, the coefficients that remain are biased away from zero and their standard errors are biased low; this in turn impacts confidence intervals and predictions as well -- our prediction intervals will be too narrow for example.]
To see these effects, we can take multiple regression where some coefficients are 0 and some are not, perform a stepwise procedure and then for those models that contain variables that had zero coefficients, look at the p-values that result.
(In the same simulation, you can look at the estimates and the standard deviations for the coefficients and discover the ones that correspond to non-zero coefficients are also impacted.)
In short, it's not appropriate to consider the usual p-values as meaningful.
I heard that one should consider all the variables left in the model as significant instead.
As to whether all the values in the model after stepwise should be 'regarded as significant', I'm not sure the extent to which that's a useful way to look at it. What is "significance" intended to mean then?
Here's the result of running R's stepAIC with default settings on 1000 simulated samples with n=100, and ten candidate variables (none of which are related to the response). In each case the number of terms left in the model was counted:
Only 15.5% of the time was the correct model chosen; the rest of the time the model included terms that were not different from zero. If it's actually possible that there are zero-coefficient variables in the set of candidate variables, we are likely to have several terms where the true coefficient is zero in our model. As a result, it's not clear it's a good idea to regard all of them as non-zero.
|
Why are p-values misleading after performing a stepwise selection?
after performing a stepwise selection based on the AIC criterion, it is misleading to look at the p-values to test the null hypothesis that each true regression coefficient is zero.
Indeed, p-values
|
9,171
|
Why are p-values misleading after performing a stepwise selection?
|
An analogy may help. Stepwise regression when the candidate variables are indicator (dummy) variables representing mutually exclusive categories (as in ANOVA) corresponds exactly to choosing which groups to combine by finding out which groups are minimally different by $t$-tests. If the original ANOVA was tested against $F_{p-1, n-p-1}$ but the final collapsed groups are tested against $F_{q-1, n-q-1}$ where $q < p$ the resulting statistic does not have an $F$ distribution and the false positive probability will be out of control.
|
Why are p-values misleading after performing a stepwise selection?
|
An analogy may help. Stepwise regression when the candidate variables are indicator (dummy) variables representing mutually exclusive categories (as in ANOVA) corresponds exactly to choosing which gr
|
Why are p-values misleading after performing a stepwise selection?
An analogy may help. Stepwise regression when the candidate variables are indicator (dummy) variables representing mutually exclusive categories (as in ANOVA) corresponds exactly to choosing which groups to combine by finding out which groups are minimally different by $t$-tests. If the original ANOVA was tested against $F_{p-1, n-p-1}$ but the final collapsed groups are tested against $F_{q-1, n-q-1}$ where $q < p$ the resulting statistic does not have an $F$ distribution and the false positive probability will be out of control.
|
Why are p-values misleading after performing a stepwise selection?
An analogy may help. Stepwise regression when the candidate variables are indicator (dummy) variables representing mutually exclusive categories (as in ANOVA) corresponds exactly to choosing which gr
|
9,172
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
Adding and subtracting gives
\begin{eqnarray*}
\sum_{i=1}^n (y_i-\bar y)^2&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y)^2\\
&=&\sum_{i=1}^n (y_i-\hat y_i)^2+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)+\sum_{i=1}^n(\hat y_i-\bar y)^2
\end{eqnarray*}
So we need to show that $\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=0$. Write
$$
\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=\sum_{i=1}^n(y_i-\hat y_i)\hat y_i-\bar y\sum_{i=1}^n(y_i-\hat y_i)
$$
So, (a) the residuals $e_i=y_i-\hat y_i$ need to be orthogonal to the fitted values, $\sum_{i=1}^n(y_i-\hat y_i)\hat y_i=0$, and (b) the sum of the fitted values needs to be equal to the sum of the dependent variable, $\sum_{i=1}^ny_i=\sum_{i=1}^n\hat y_i$.
Actually, I think (a) is easier to show in matrix notation for general multiple regression of which the single variable case is a special case:
\begin{eqnarray*}
e'X\hat\beta
&=&(y-X\hat\beta)'X\hat\beta\\
&=&(y-X(X'X)^{-1}X'y)'X\hat\beta\\
&=&y'(X-X(X'X)^{-1}X'X)\hat\beta\\
&=&y'(X-X)\hat\beta=0
\end{eqnarray*}
As for (b), the derivative of the OLS criterion function with respect to the constant (so you need one in the regression for this to be true!), aka the normal equation,
is
$$
\frac{\partial SSR}{\partial\hat\alpha}=-2\sum_i(y_i-\hat\alpha-\hat\beta x_i)=0,$$
which can be rearranged to
$$
\sum_i y_i=n\hat\alpha+\hat\beta\sum_ix_i
$$
The right hand side of this equation evidently also is $\sum_{i=1}^n\hat y_i$, as $\hat y_i=\hat\alpha+\hat\beta x_i$.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
Adding and subtracting gives
\begin{eqnarray*}
\sum_{i=1}^n (y_i-\bar y)^2&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y)^2\\
&=&\sum_{i=1}^n (y_i-\hat y_i)^2+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar
|
Why is $SST=SSE + SSR$? (One variable linear regression)
Adding and subtracting gives
\begin{eqnarray*}
\sum_{i=1}^n (y_i-\bar y)^2&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y)^2\\
&=&\sum_{i=1}^n (y_i-\hat y_i)^2+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)+\sum_{i=1}^n(\hat y_i-\bar y)^2
\end{eqnarray*}
So we need to show that $\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=0$. Write
$$
\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=\sum_{i=1}^n(y_i-\hat y_i)\hat y_i-\bar y\sum_{i=1}^n(y_i-\hat y_i)
$$
So, (a) the residuals $e_i=y_i-\hat y_i$ need to be orthogonal to the fitted values, $\sum_{i=1}^n(y_i-\hat y_i)\hat y_i=0$, and (b) the sum of the fitted values needs to be equal to the sum of the dependent variable, $\sum_{i=1}^ny_i=\sum_{i=1}^n\hat y_i$.
Actually, I think (a) is easier to show in matrix notation for general multiple regression of which the single variable case is a special case:
\begin{eqnarray*}
e'X\hat\beta
&=&(y-X\hat\beta)'X\hat\beta\\
&=&(y-X(X'X)^{-1}X'y)'X\hat\beta\\
&=&y'(X-X(X'X)^{-1}X'X)\hat\beta\\
&=&y'(X-X)\hat\beta=0
\end{eqnarray*}
As for (b), the derivative of the OLS criterion function with respect to the constant (so you need one in the regression for this to be true!), aka the normal equation,
is
$$
\frac{\partial SSR}{\partial\hat\alpha}=-2\sum_i(y_i-\hat\alpha-\hat\beta x_i)=0,$$
which can be rearranged to
$$
\sum_i y_i=n\hat\alpha+\hat\beta\sum_ix_i
$$
The right hand side of this equation evidently also is $\sum_{i=1}^n\hat y_i$, as $\hat y_i=\hat\alpha+\hat\beta x_i$.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
Adding and subtracting gives
\begin{eqnarray*}
\sum_{i=1}^n (y_i-\bar y)^2&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y)^2\\
&=&\sum_{i=1}^n (y_i-\hat y_i)^2+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar
|
9,173
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
This is just the Pythagorean theorem!
Hence,
$$Y'Y=(Y-X\hat{\beta})'(Y-X\hat{\beta})+(X\hat{\beta})'X\hat{\beta}$$
or
$$SST=SSE+SSR$$
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
This is just the Pythagorean theorem!
Hence,
$$Y'Y=(Y-X\hat{\beta})'(Y-X\hat{\beta})+(X\hat{\beta})'X\hat{\beta}$$
or
$$SST=SSE+SSR$$
|
Why is $SST=SSE + SSR$? (One variable linear regression)
This is just the Pythagorean theorem!
Hence,
$$Y'Y=(Y-X\hat{\beta})'(Y-X\hat{\beta})+(X\hat{\beta})'X\hat{\beta}$$
or
$$SST=SSE+SSR$$
|
Why is $SST=SSE + SSR$? (One variable linear regression)
This is just the Pythagorean theorem!
Hence,
$$Y'Y=(Y-X\hat{\beta})'(Y-X\hat{\beta})+(X\hat{\beta})'X\hat{\beta}$$
or
$$SST=SSE+SSR$$
|
9,174
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
(1) Intuition for why $SST = SSR + SSE$
When we try to explain the total variation in Y ($SST$) with one explanatory variable, X, then there are exactly two sources of variability. First, there is the variability captured by X (Sum Square Regression), and second, there is the variability not captured by X (Sum Square Error). Hence, $SST = SSR + SSE$ (exact equality).
(2) Geometric intuition
Please see the first few pictures here (especially the third): https://sites.google.com/site/modernprogramevaluation/variance-and-bias
Some of the total variation in the data (distance from datapoint to $\bar{Y}$) is captured by the regression line (the distance from the regression line to $\bar{Y}$) and error (distance from the point to the regression line). There's not room left for $SST$ to be greater than $SSE + SSR$.
(3) The problem with your illustration
You can't look at SSE and SSR in a pointwise fashion. For a particular point, the residual may be large, so that there is more error than explanatory power from X. However, for other points, the residual will be small, so that the regression line explains a lot of the variability. They will balance out and ultimately $SST = SSR + SSE$. Of course this is not rigorous, but you can find proofs like the above.
Also notice that regression will not be defined for one point: $b_1 = \frac{\sum(X_i -\bar{X})(Y_i-\bar{Y}) }{\sum (X_i -\bar{X})^2}$, and you can see that the denominator will be zero, making estimation undefined.
Hope this helps.
--Ryan M.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
(1) Intuition for why $SST = SSR + SSE$
When we try to explain the total variation in Y ($SST$) with one explanatory variable, X, then there are exactly two sources of variability. First, there is th
|
Why is $SST=SSE + SSR$? (One variable linear regression)
(1) Intuition for why $SST = SSR + SSE$
When we try to explain the total variation in Y ($SST$) with one explanatory variable, X, then there are exactly two sources of variability. First, there is the variability captured by X (Sum Square Regression), and second, there is the variability not captured by X (Sum Square Error). Hence, $SST = SSR + SSE$ (exact equality).
(2) Geometric intuition
Please see the first few pictures here (especially the third): https://sites.google.com/site/modernprogramevaluation/variance-and-bias
Some of the total variation in the data (distance from datapoint to $\bar{Y}$) is captured by the regression line (the distance from the regression line to $\bar{Y}$) and error (distance from the point to the regression line). There's not room left for $SST$ to be greater than $SSE + SSR$.
(3) The problem with your illustration
You can't look at SSE and SSR in a pointwise fashion. For a particular point, the residual may be large, so that there is more error than explanatory power from X. However, for other points, the residual will be small, so that the regression line explains a lot of the variability. They will balance out and ultimately $SST = SSR + SSE$. Of course this is not rigorous, but you can find proofs like the above.
Also notice that regression will not be defined for one point: $b_1 = \frac{\sum(X_i -\bar{X})(Y_i-\bar{Y}) }{\sum (X_i -\bar{X})^2}$, and you can see that the denominator will be zero, making estimation undefined.
Hope this helps.
--Ryan M.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
(1) Intuition for why $SST = SSR + SSE$
When we try to explain the total variation in Y ($SST$) with one explanatory variable, X, then there are exactly two sources of variability. First, there is th
|
9,175
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
When an intercept is included in linear regression(sum of residuals is zero), $SST=SSE+SSR$.
prove
$$
\begin{eqnarray*}
SST&=&\sum_{i=1}^n (y_i-\bar y)^2\\&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y)^2\\&=&\sum_{i=1}^n (y_i-\hat y_i)^2+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)+\sum_{i=1}^n(\hat y_i-\bar y)^2\\&=&SSE+SSR+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)
\end{eqnarray*}
$$
Just need to prove last part is equal to 0:
$$\begin{eqnarray*}
\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)&=&\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)(\beta_0+\beta_1x_i-\bar y)\\&=&(\beta_0-\bar y)\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)+\beta_1\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)x_i
\end{eqnarray*}
$$
In Least squares regression, the sum of the squares of the errors is minimized.
$$
SSE=\displaystyle\sum\limits_{i=1}^n \left(e_i \right)^2= \sum_{i=1}^n\left(y_i - \hat{y_i} \right)^2= \sum_{i=1}^n\left(y_i -\beta_0- \beta_1x_i\right)^2
$$
Take the partial derivative of SSE with respect to $\beta_0$ and setting it to zero.
$$
\frac{\partial{SSE}}{\partial{\beta_0}} = \sum_{i=1}^n 2\left(y_i - \beta_0 - \beta_1x_i\right)^1 = 0
$$
So
$$
\sum_{i=1}^n \left(y_i - \beta_0 - \beta_1x_i\right)^1 = 0
$$
Take the partial derivative of SSE with respect to $\beta_1$ and setting it to zero.
$$
\frac{\partial{SSE}}{\partial{\beta_1}} = \sum_{i=1}^n 2\left(y_i - \beta_0 - \beta_1x_i\right)^1 x_i = 0
$$
So
$$
\sum_{i=1}^n \left(y_i - \beta_0 - \beta_1x_i\right)^1 x_i = 0
$$
Hence,
$$
\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=(\beta_0-\bar y)\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)+\beta_1\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)x_i=0
$$
$$SST=SSE+SSR+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=SSE+SSR$$
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
When an intercept is included in linear regression(sum of residuals is zero), $SST=SSE+SSR$.
prove
$$
\begin{eqnarray*}
SST&=&\sum_{i=1}^n (y_i-\bar y)^2\\&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y
|
Why is $SST=SSE + SSR$? (One variable linear regression)
When an intercept is included in linear regression(sum of residuals is zero), $SST=SSE+SSR$.
prove
$$
\begin{eqnarray*}
SST&=&\sum_{i=1}^n (y_i-\bar y)^2\\&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y)^2\\&=&\sum_{i=1}^n (y_i-\hat y_i)^2+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)+\sum_{i=1}^n(\hat y_i-\bar y)^2\\&=&SSE+SSR+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)
\end{eqnarray*}
$$
Just need to prove last part is equal to 0:
$$\begin{eqnarray*}
\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)&=&\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)(\beta_0+\beta_1x_i-\bar y)\\&=&(\beta_0-\bar y)\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)+\beta_1\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)x_i
\end{eqnarray*}
$$
In Least squares regression, the sum of the squares of the errors is minimized.
$$
SSE=\displaystyle\sum\limits_{i=1}^n \left(e_i \right)^2= \sum_{i=1}^n\left(y_i - \hat{y_i} \right)^2= \sum_{i=1}^n\left(y_i -\beta_0- \beta_1x_i\right)^2
$$
Take the partial derivative of SSE with respect to $\beta_0$ and setting it to zero.
$$
\frac{\partial{SSE}}{\partial{\beta_0}} = \sum_{i=1}^n 2\left(y_i - \beta_0 - \beta_1x_i\right)^1 = 0
$$
So
$$
\sum_{i=1}^n \left(y_i - \beta_0 - \beta_1x_i\right)^1 = 0
$$
Take the partial derivative of SSE with respect to $\beta_1$ and setting it to zero.
$$
\frac{\partial{SSE}}{\partial{\beta_1}} = \sum_{i=1}^n 2\left(y_i - \beta_0 - \beta_1x_i\right)^1 x_i = 0
$$
So
$$
\sum_{i=1}^n \left(y_i - \beta_0 - \beta_1x_i\right)^1 x_i = 0
$$
Hence,
$$
\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=(\beta_0-\bar y)\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)+\beta_1\sum_{i=1}^n(y_i-\beta_0-\beta_1x_i)x_i=0
$$
$$SST=SSE+SSR+2\sum_{i=1}^n(y_i-\hat y_i)(\hat y_i-\bar y)=SSE+SSR$$
|
Why is $SST=SSE + SSR$? (One variable linear regression)
When an intercept is included in linear regression(sum of residuals is zero), $SST=SSE+SSR$.
prove
$$
\begin{eqnarray*}
SST&=&\sum_{i=1}^n (y_i-\bar y)^2\\&=&\sum_{i=1}^n (y_i-\hat y_i+\hat y_i-\bar y
|
9,176
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
Here is a great graphical representation of why SST = SSR + SSE.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
Here is a great graphical representation of why SST = SSR + SSE.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
Here is a great graphical representation of why SST = SSR + SSE.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
Here is a great graphical representation of why SST = SSR + SSE.
|
9,177
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
If a model predicts $3$ and the residual is $2$ because the actual value is $5$, it doesn't look like variance is decomposing, since $3^2 + 2^2 \neq 5^2$.
If you only have one data point, your model would fit it perfectly and the residual would be zero, so you can't get that case by itself. There have to be multiple data points.
With multiple data points, the residuals won't all be positive.
If the model predicts 3, a residual of $+2$ and $-2$ should be equally likely. The balance of increases and decreases gives a nice cancellation:
$$\frac{(3+2)^2 + (3-2)^2}{2} = \frac{25+1}{2} = 13 = 9 + 4 = 3^2 + 2^2 $$
This property, that $(a+b)^2 + (a-b)^2 = 2(a^2 + b^2)$, is what makes variance decomposition work, for uncorrelated components.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
|
If a model predicts $3$ and the residual is $2$ because the actual value is $5$, it doesn't look like variance is decomposing, since $3^2 + 2^2 \neq 5^2$.
If you only have one data point, your model w
|
Why is $SST=SSE + SSR$? (One variable linear regression)
If a model predicts $3$ and the residual is $2$ because the actual value is $5$, it doesn't look like variance is decomposing, since $3^2 + 2^2 \neq 5^2$.
If you only have one data point, your model would fit it perfectly and the residual would be zero, so you can't get that case by itself. There have to be multiple data points.
With multiple data points, the residuals won't all be positive.
If the model predicts 3, a residual of $+2$ and $-2$ should be equally likely. The balance of increases and decreases gives a nice cancellation:
$$\frac{(3+2)^2 + (3-2)^2}{2} = \frac{25+1}{2} = 13 = 9 + 4 = 3^2 + 2^2 $$
This property, that $(a+b)^2 + (a-b)^2 = 2(a^2 + b^2)$, is what makes variance decomposition work, for uncorrelated components.
|
Why is $SST=SSE + SSR$? (One variable linear regression)
If a model predicts $3$ and the residual is $2$ because the actual value is $5$, it doesn't look like variance is decomposing, since $3^2 + 2^2 \neq 5^2$.
If you only have one data point, your model w
|
9,178
|
How exactly is sparse PCA better than PCA?
|
Whether sparse PCA is easier to interpret than standard PCA or not, depends on the dataset you are investigating. Here is how I think about it: sometimes one is more interested in the PCA projections (low dimensional representation of the data), and sometimes -- in the principal axes; it is only in the latter case that sparse PCA can have any benefits for the interpretation. Let me give a couple of examples.
I am e.g. working with neural data (simultaneous recordings of many neurons) and am applying PCA and/or related dimensionality reduction techniques to get a low-dimensional representation of neural population activity. I might have 1000 neurons (i.e. my data live in 1000-dimensional space) and want to project it on the three leading principal axes. What these axes are, is totally irrelevant for me, and I have no intention of "interpreting" these axes in any way. What I am interested, is the 3D projection (as the activity depends on time, I get a trajectory in this 3D space). So I am fine if each axis has all 1000 non-zero coefficients.
On the other hand, somebody might be working with more "tangible" data, where individual dimensions have obvious meaning (unlike individual neurons above). E.g. a dataset of various cars, where dimensions are anything from weight to price. In this case one might actually be interested in the leading principal axes themselves, because one might want to say something: look, the 1st principal axis corresponds to the "fanciness" of the car (I am totally making this up now). If the projection is sparse, such interpretations would generally be easier to give, because many variables will have $0$ coefficients and so are obviously irrelevant for this particular axis. In the case of standard PCA, one usually gets non-zero coefficients for all variables.
You can find more examples and some discussion of the latter case in the 2006 Sparse PCA paper by Zou et al. The difference between the former and the latter case, however, I did not see explicitly discussed anywhere (even though it probably was).
|
How exactly is sparse PCA better than PCA?
|
Whether sparse PCA is easier to interpret than standard PCA or not, depends on the dataset you are investigating. Here is how I think about it: sometimes one is more interested in the PCA projections
|
How exactly is sparse PCA better than PCA?
Whether sparse PCA is easier to interpret than standard PCA or not, depends on the dataset you are investigating. Here is how I think about it: sometimes one is more interested in the PCA projections (low dimensional representation of the data), and sometimes -- in the principal axes; it is only in the latter case that sparse PCA can have any benefits for the interpretation. Let me give a couple of examples.
I am e.g. working with neural data (simultaneous recordings of many neurons) and am applying PCA and/or related dimensionality reduction techniques to get a low-dimensional representation of neural population activity. I might have 1000 neurons (i.e. my data live in 1000-dimensional space) and want to project it on the three leading principal axes. What these axes are, is totally irrelevant for me, and I have no intention of "interpreting" these axes in any way. What I am interested, is the 3D projection (as the activity depends on time, I get a trajectory in this 3D space). So I am fine if each axis has all 1000 non-zero coefficients.
On the other hand, somebody might be working with more "tangible" data, where individual dimensions have obvious meaning (unlike individual neurons above). E.g. a dataset of various cars, where dimensions are anything from weight to price. In this case one might actually be interested in the leading principal axes themselves, because one might want to say something: look, the 1st principal axis corresponds to the "fanciness" of the car (I am totally making this up now). If the projection is sparse, such interpretations would generally be easier to give, because many variables will have $0$ coefficients and so are obviously irrelevant for this particular axis. In the case of standard PCA, one usually gets non-zero coefficients for all variables.
You can find more examples and some discussion of the latter case in the 2006 Sparse PCA paper by Zou et al. The difference between the former and the latter case, however, I did not see explicitly discussed anywhere (even though it probably was).
|
How exactly is sparse PCA better than PCA?
Whether sparse PCA is easier to interpret than standard PCA or not, depends on the dataset you are investigating. Here is how I think about it: sometimes one is more interested in the PCA projections
|
9,179
|
How exactly is sparse PCA better than PCA?
|
To understand the advantages of sparsity in PCA, you need to make sure you know the difference between "loadings" and "variables" (to me these names are somewhat arbitrary, but that's not important).
Say you have an $n\times p$ data matrix $\textbf{X}$, where $n$ is the number of samples. The SVD of $\textbf{X}=\textbf{US}\textbf{V}^\top$, gives you three matrices. Combining the first two $\textbf{Z} = \textbf{US}$ gives you the matrix of Principal Components. Let's say your reduced rank is $k$, then $\textbf{Z}$ is $n\times k$. $\textbf{Z}$ is essentially your data matrix after dimension reduction. Historically,
The entries of your principal components (aka $\textbf{Z} = \textbf{US}$) are called variables.
On the other hand, $\textbf{V}$ (which is $p\times k$) contains the Principal Loading Vectors and its entries are called the principal loadings. Given the properties of PCA, it's easy to show that $\textbf{Z}=\textbf{XV}$. This means that:
The principal components are derived by using the principal loadings as coefficients in a linear combination of your data matrix $\textbf{X}$.
Now that these definitions are out of the way, we'll look at sparsity. Most papers (or at least most that I've encountered), enforce sparsity on the principal loadings (aka $\textbf{V}$). The advantage of sparsity is that
a sparse $\textbf{V}$ will tell us which variables (from the original $p$-dimensional feature space) are worth keeping. This is called interpretability.
There are also interpretations for enforcing sparsity on the entries of $\textbf{Z}$, which I've seen people call "sparse variable PCA"", but that's far less popular and to be honest I haven't thought about it that much.
|
How exactly is sparse PCA better than PCA?
|
To understand the advantages of sparsity in PCA, you need to make sure you know the difference between "loadings" and "variables" (to me these names are somewhat arbitrary, but that's not important).
|
How exactly is sparse PCA better than PCA?
To understand the advantages of sparsity in PCA, you need to make sure you know the difference between "loadings" and "variables" (to me these names are somewhat arbitrary, but that's not important).
Say you have an $n\times p$ data matrix $\textbf{X}$, where $n$ is the number of samples. The SVD of $\textbf{X}=\textbf{US}\textbf{V}^\top$, gives you three matrices. Combining the first two $\textbf{Z} = \textbf{US}$ gives you the matrix of Principal Components. Let's say your reduced rank is $k$, then $\textbf{Z}$ is $n\times k$. $\textbf{Z}$ is essentially your data matrix after dimension reduction. Historically,
The entries of your principal components (aka $\textbf{Z} = \textbf{US}$) are called variables.
On the other hand, $\textbf{V}$ (which is $p\times k$) contains the Principal Loading Vectors and its entries are called the principal loadings. Given the properties of PCA, it's easy to show that $\textbf{Z}=\textbf{XV}$. This means that:
The principal components are derived by using the principal loadings as coefficients in a linear combination of your data matrix $\textbf{X}$.
Now that these definitions are out of the way, we'll look at sparsity. Most papers (or at least most that I've encountered), enforce sparsity on the principal loadings (aka $\textbf{V}$). The advantage of sparsity is that
a sparse $\textbf{V}$ will tell us which variables (from the original $p$-dimensional feature space) are worth keeping. This is called interpretability.
There are also interpretations for enforcing sparsity on the entries of $\textbf{Z}$, which I've seen people call "sparse variable PCA"", but that's far less popular and to be honest I haven't thought about it that much.
|
How exactly is sparse PCA better than PCA?
To understand the advantages of sparsity in PCA, you need to make sure you know the difference between "loadings" and "variables" (to me these names are somewhat arbitrary, but that's not important).
|
9,180
|
How exactly is sparse PCA better than PCA?
|
So you can eliminate the last few principal components, as they will not cause a lot of loss of data, and you can compress the data. Right?
yes, you're right. And if there are $N$ variables $V_1, V_2, \cdots , V_N$, you then have $N$ Principal Component $PC_1, PC_2, \cdots , PC_N$, and every variable $V_i$ has an information (a contribution) in every PC $PC_i$.
In Sparse PCA there are $PC_i$ without information of some variables $V_j, V_l, \cdots$, the variables with coefficient zero.
Then, if in one plane $(PC_i, PC_{j})$, there are fewer variables than expected ($N$), it's easier to clear the linear relations between them in this plane.
|
How exactly is sparse PCA better than PCA?
|
So you can eliminate the last few principal components, as they will not cause a lot of loss of data, and you can compress the data. Right?
yes, you're right. And if there are $N$ variables $V_1, V_2
|
How exactly is sparse PCA better than PCA?
So you can eliminate the last few principal components, as they will not cause a lot of loss of data, and you can compress the data. Right?
yes, you're right. And if there are $N$ variables $V_1, V_2, \cdots , V_N$, you then have $N$ Principal Component $PC_1, PC_2, \cdots , PC_N$, and every variable $V_i$ has an information (a contribution) in every PC $PC_i$.
In Sparse PCA there are $PC_i$ without information of some variables $V_j, V_l, \cdots$, the variables with coefficient zero.
Then, if in one plane $(PC_i, PC_{j})$, there are fewer variables than expected ($N$), it's easier to clear the linear relations between them in this plane.
|
How exactly is sparse PCA better than PCA?
So you can eliminate the last few principal components, as they will not cause a lot of loss of data, and you can compress the data. Right?
yes, you're right. And if there are $N$ variables $V_1, V_2
|
9,181
|
How exactly is sparse PCA better than PCA?
|
Like all good things, it depends.
After applying PCA, you can again represent it in the same dimensional space, but, this time, the first principal component will contain the most variance, the second will contain the second most variance direction and so on. So you can eliminate the last few principal components, as they will not cause a lot of loss of data, and you can compress the data. Right?
Yes. Here's the thing: the same logic applies for the parameters of each principal components themselves. Just as many of the principal components can be eliminated without losing very much information, you can eliminate many parts of each principal component without losing very much information. Why should we be efficient in one dimension but not another? Eliminate all of the unnecessary parameters.
If you think about the total number of parameters needed to describe your data, sparse PCA is very often just more efficient PCA. Modern sparse PCA methods are a big reason modern video and image compression is so good and doesn't look like sh-t. Sparse PCA is also easier to interpret; each principal component can actually represent a descriptive factor of some kind (for example: personality traits in psychological studies). And finally, sparse PCA (like sparse regression) is more likely to generalize better out of sample. If I have some new data generated from the same source, sparse principal components are more likely to summarize the new data better (less is more when it comes to generalizing).
Of course, that depends on your measure of efficiency. If you're using PCA to visualize multi-dimensional data in two or three dimensions, sparse PCA would be less efficient (each principal component would describe less variance than simple PCA).
Tl;dr simple PCA = handful of complicated principal components, sparse PCA = slightly more simple principal components and less parameters in total.
|
How exactly is sparse PCA better than PCA?
|
Like all good things, it depends.
After applying PCA, you can again represent it in the same dimensional space, but, this time, the first principal component will contain the most variance, the secon
|
How exactly is sparse PCA better than PCA?
Like all good things, it depends.
After applying PCA, you can again represent it in the same dimensional space, but, this time, the first principal component will contain the most variance, the second will contain the second most variance direction and so on. So you can eliminate the last few principal components, as they will not cause a lot of loss of data, and you can compress the data. Right?
Yes. Here's the thing: the same logic applies for the parameters of each principal components themselves. Just as many of the principal components can be eliminated without losing very much information, you can eliminate many parts of each principal component without losing very much information. Why should we be efficient in one dimension but not another? Eliminate all of the unnecessary parameters.
If you think about the total number of parameters needed to describe your data, sparse PCA is very often just more efficient PCA. Modern sparse PCA methods are a big reason modern video and image compression is so good and doesn't look like sh-t. Sparse PCA is also easier to interpret; each principal component can actually represent a descriptive factor of some kind (for example: personality traits in psychological studies). And finally, sparse PCA (like sparse regression) is more likely to generalize better out of sample. If I have some new data generated from the same source, sparse principal components are more likely to summarize the new data better (less is more when it comes to generalizing).
Of course, that depends on your measure of efficiency. If you're using PCA to visualize multi-dimensional data in two or three dimensions, sparse PCA would be less efficient (each principal component would describe less variance than simple PCA).
Tl;dr simple PCA = handful of complicated principal components, sparse PCA = slightly more simple principal components and less parameters in total.
|
How exactly is sparse PCA better than PCA?
Like all good things, it depends.
After applying PCA, you can again represent it in the same dimensional space, but, this time, the first principal component will contain the most variance, the secon
|
9,182
|
Proof that moment generating functions uniquely determine probability distributions
|
The general proof of this can be found in Feller (An Introduction to Probability Theory and Its Applications, Vol. 2). It is an inversion problem involving Laplace transform theory. Did you notice that the mgf bears a striking resemblance to the Laplace transform?. For use of Laplace Transformation you can see Widder (Calcus Vol I) .
Proof of a special case:
Suppose that X and Y are random varaibles both taking only possible values in {$0, 1, 2,\dots, n$}.
Further, suppose that X and Y have the same mgf for all t:
$$\sum_{x=0}^ne^{tx}f_X(x)=\sum_{y=0}^ne^{ty}f_Y(y)$$
For simplicity, we will let $s = e^t$
and we will define $c_i = f_X(i) − f_Y (i)$ for $i = 0, 1,\dots,n$.
Now
$$\sum_{x=0}^ne^{tx}f_X(x)-\sum_{y=0}^ne^{ty}f_Y(y)=0$$
$$\Rightarrow \sum_{x=0}^ns^xf_X(x)-\sum_{y=0}^ns^yf_Y(y)=0$$
$$\Rightarrow \sum_{x=0}^ns^xf_X(x)-\sum_{x=0}^ns^xf_Y(x)=0$$
$$\Rightarrow\sum_{x=0}^ns^x[f_X(x)-f_Y(x)]=0$$
$$\Rightarrow \sum_{x=0}^ns^xc_x=0~∀s>0$$
The above is simply a polynomial in s with coefficients $c_0, c_1,\dots,c_n$. The only way it can be zero for all values of s is if $c_0=c_1=\cdots= c_n=0$.So, we have that $0=c_i=f_X(i)−f_Y(i)$ for $i=0, 1,\dots,n$.
Therefore, $f_X(i)=f_Y(i)$ for $i=0,1,\dots,n$.
In other words the density functions for $X$ and $Y$ are exactly the same. In other other words, $X$ and $Y$ have the same distributions.
|
Proof that moment generating functions uniquely determine probability distributions
|
The general proof of this can be found in Feller (An Introduction to Probability Theory and Its Applications, Vol. 2). It is an inversion problem involving Laplace transform theory. Did you notice tha
|
Proof that moment generating functions uniquely determine probability distributions
The general proof of this can be found in Feller (An Introduction to Probability Theory and Its Applications, Vol. 2). It is an inversion problem involving Laplace transform theory. Did you notice that the mgf bears a striking resemblance to the Laplace transform?. For use of Laplace Transformation you can see Widder (Calcus Vol I) .
Proof of a special case:
Suppose that X and Y are random varaibles both taking only possible values in {$0, 1, 2,\dots, n$}.
Further, suppose that X and Y have the same mgf for all t:
$$\sum_{x=0}^ne^{tx}f_X(x)=\sum_{y=0}^ne^{ty}f_Y(y)$$
For simplicity, we will let $s = e^t$
and we will define $c_i = f_X(i) − f_Y (i)$ for $i = 0, 1,\dots,n$.
Now
$$\sum_{x=0}^ne^{tx}f_X(x)-\sum_{y=0}^ne^{ty}f_Y(y)=0$$
$$\Rightarrow \sum_{x=0}^ns^xf_X(x)-\sum_{y=0}^ns^yf_Y(y)=0$$
$$\Rightarrow \sum_{x=0}^ns^xf_X(x)-\sum_{x=0}^ns^xf_Y(x)=0$$
$$\Rightarrow\sum_{x=0}^ns^x[f_X(x)-f_Y(x)]=0$$
$$\Rightarrow \sum_{x=0}^ns^xc_x=0~∀s>0$$
The above is simply a polynomial in s with coefficients $c_0, c_1,\dots,c_n$. The only way it can be zero for all values of s is if $c_0=c_1=\cdots= c_n=0$.So, we have that $0=c_i=f_X(i)−f_Y(i)$ for $i=0, 1,\dots,n$.
Therefore, $f_X(i)=f_Y(i)$ for $i=0,1,\dots,n$.
In other words the density functions for $X$ and $Y$ are exactly the same. In other other words, $X$ and $Y$ have the same distributions.
|
Proof that moment generating functions uniquely determine probability distributions
The general proof of this can be found in Feller (An Introduction to Probability Theory and Its Applications, Vol. 2). It is an inversion problem involving Laplace transform theory. Did you notice tha
|
9,183
|
Proof that moment generating functions uniquely determine probability distributions
|
The theorem you are discussing is a basic result in probability/measure theory. The proofs would more likely be found in books on probability or statistical theory. I found the analogous result for characteristic functions given in Hoel Port and Stone pp 205-208
Tucker pp 51-53
and Chung pp 151-155 This is the Third Edition. I have the second edition and am referring to the page numbers in the second edition published in 1974.
The proof for the mgf I found to be more difficult to find but you can find it in
Billingley's book "Probability and Measure" pp. 342-345. On page 342 Theorem 30.1 provides the theorem that answers the moment problem. On page 345 Billingsley states the result that if a probability measure has a moment generating function M(s) defined on an interval surrounding 0 then the hypothesis for Theorem 30.1 is satisfied and hence the measure is determined by its moments. But these moment s are determined by M(s). Hence the measure is determined by its moment generating function if M(s) exists in a neighborhood of 0. So this logic along with the proof he gives for Theorem30.1 proves the result. Billingsley also comment that the solution to exercise 26.7 on page 305 is an alternative proof of the uniqueness theorem for moment generating functions.
|
Proof that moment generating functions uniquely determine probability distributions
|
The theorem you are discussing is a basic result in probability/measure theory. The proofs would more likely be found in books on probability or statistical theory. I found the analogous result for
|
Proof that moment generating functions uniquely determine probability distributions
The theorem you are discussing is a basic result in probability/measure theory. The proofs would more likely be found in books on probability or statistical theory. I found the analogous result for characteristic functions given in Hoel Port and Stone pp 205-208
Tucker pp 51-53
and Chung pp 151-155 This is the Third Edition. I have the second edition and am referring to the page numbers in the second edition published in 1974.
The proof for the mgf I found to be more difficult to find but you can find it in
Billingley's book "Probability and Measure" pp. 342-345. On page 342 Theorem 30.1 provides the theorem that answers the moment problem. On page 345 Billingsley states the result that if a probability measure has a moment generating function M(s) defined on an interval surrounding 0 then the hypothesis for Theorem 30.1 is satisfied and hence the measure is determined by its moments. But these moment s are determined by M(s). Hence the measure is determined by its moment generating function if M(s) exists in a neighborhood of 0. So this logic along with the proof he gives for Theorem30.1 proves the result. Billingsley also comment that the solution to exercise 26.7 on page 305 is an alternative proof of the uniqueness theorem for moment generating functions.
|
Proof that moment generating functions uniquely determine probability distributions
The theorem you are discussing is a basic result in probability/measure theory. The proofs would more likely be found in books on probability or statistical theory. I found the analogous result for
|
9,184
|
Proof that moment generating functions uniquely determine probability distributions
|
Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$.
Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$, then $F_X(t) = F_Y(t)$ for all $t \in \mathbb{R}$.
To prove that the moment generating function determines the distribution, there are at least two approaches:
To show that finiteness of $M_X$ on $(-\delta,\delta)$ implies that the moments $X$ do not increase too fast, so that $F_X$ is determined by $(EX^k)_{k\in\mathbb{N}}$, which are in turn determined by $M_X$. This proof can be found in Section 30 of Billingsley, P. Probability and Measure.
To show that $M_X$ is analytic and can be extended to $(-\delta,\delta)\times i\mathbb{R} \subseteq \mathbb{C}$, so that $M_X(z)=Ee^{zX}$, so in particular $M_X(it)=\varphi_X(t)$ for all $t\in\mathbb{R}$, and then use the fact that $\varphi_X$ determines $F_X$. For this approach, see Curtiss, J. H. Ann. Math. Statistics 13:430-433 and references therein.
At undergraduate level, almost every textbook works with the moment generating function and states the above theorem without proving it. It makes sense, because the proof requires far more advanced mathematics than undergraduate level allows.
At the point when students have all the tools needed in the proof, they also have the maturity to work with the characteristic function $\varphi_X(t)=Ee^{itX}$ instead. Almost every graduate textbook takes this path, they prove that the characteristic function determines the distribution and basically ignore moment generating functions altogether.
|
Proof that moment generating functions uniquely determine probability distributions
|
Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$.
Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$, then $F_X(t) =
|
Proof that moment generating functions uniquely determine probability distributions
Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$.
Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$, then $F_X(t) = F_Y(t)$ for all $t \in \mathbb{R}$.
To prove that the moment generating function determines the distribution, there are at least two approaches:
To show that finiteness of $M_X$ on $(-\delta,\delta)$ implies that the moments $X$ do not increase too fast, so that $F_X$ is determined by $(EX^k)_{k\in\mathbb{N}}$, which are in turn determined by $M_X$. This proof can be found in Section 30 of Billingsley, P. Probability and Measure.
To show that $M_X$ is analytic and can be extended to $(-\delta,\delta)\times i\mathbb{R} \subseteq \mathbb{C}$, so that $M_X(z)=Ee^{zX}$, so in particular $M_X(it)=\varphi_X(t)$ for all $t\in\mathbb{R}$, and then use the fact that $\varphi_X$ determines $F_X$. For this approach, see Curtiss, J. H. Ann. Math. Statistics 13:430-433 and references therein.
At undergraduate level, almost every textbook works with the moment generating function and states the above theorem without proving it. It makes sense, because the proof requires far more advanced mathematics than undergraduate level allows.
At the point when students have all the tools needed in the proof, they also have the maturity to work with the characteristic function $\varphi_X(t)=Ee^{itX}$ instead. Almost every graduate textbook takes this path, they prove that the characteristic function determines the distribution and basically ignore moment generating functions altogether.
|
Proof that moment generating functions uniquely determine probability distributions
Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$.
Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$, then $F_X(t) =
|
9,185
|
Deep learning : How do I know which variables are important?
|
What you describe is indeed one standard way of quantifying the importance of neural-net inputs. Note that in order for this to work, however, the input variables must be normalized in some way. Otherwise weights corresponding to input variables that tend to have larger values will be proportionally smaller. There are different normalization schemes, such as for instance subtracting off a variable's mean and dividing by its standard deviation. If the variables weren't normalized in the first place, you could perform a correction on the weights themselves in the importance calculation, such as multiplying by the standard deviation of the variable.
$I_i = \sigma_i\sum\limits_{j = 1}^{n_\text{hidden}}\left|w_{ij}\right|$.
Here $\sigma_i$ is the standard deviation of the $i$th input, $I_i$ is the $i$th input's importance, $w_{ij}$ is the weight connecting the $i$th input to the $j$th hidden node in the first layer, and $n_\text{hidden}$ is the number of hidden nodes in the first layer.
Another technique is to use the derivative of the neural-net mapping with respect to the input in question, averaged over inputs.
$I_i = \sigma_i\left\langle\left|\frac{dy}{dx_i}\right|\right\rangle$
Here $x_i$ is the $i$th input, $y$ is the output, and the expectation value is taken with respect to the vector of inputs $\mathbf{x}$.
|
Deep learning : How do I know which variables are important?
|
What you describe is indeed one standard way of quantifying the importance of neural-net inputs. Note that in order for this to work, however, the input variables must be normalized in some way. Oth
|
Deep learning : How do I know which variables are important?
What you describe is indeed one standard way of quantifying the importance of neural-net inputs. Note that in order for this to work, however, the input variables must be normalized in some way. Otherwise weights corresponding to input variables that tend to have larger values will be proportionally smaller. There are different normalization schemes, such as for instance subtracting off a variable's mean and dividing by its standard deviation. If the variables weren't normalized in the first place, you could perform a correction on the weights themselves in the importance calculation, such as multiplying by the standard deviation of the variable.
$I_i = \sigma_i\sum\limits_{j = 1}^{n_\text{hidden}}\left|w_{ij}\right|$.
Here $\sigma_i$ is the standard deviation of the $i$th input, $I_i$ is the $i$th input's importance, $w_{ij}$ is the weight connecting the $i$th input to the $j$th hidden node in the first layer, and $n_\text{hidden}$ is the number of hidden nodes in the first layer.
Another technique is to use the derivative of the neural-net mapping with respect to the input in question, averaged over inputs.
$I_i = \sigma_i\left\langle\left|\frac{dy}{dx_i}\right|\right\rangle$
Here $x_i$ is the $i$th input, $y$ is the output, and the expectation value is taken with respect to the vector of inputs $\mathbf{x}$.
|
Deep learning : How do I know which variables are important?
What you describe is indeed one standard way of quantifying the importance of neural-net inputs. Note that in order for this to work, however, the input variables must be normalized in some way. Oth
|
9,186
|
Deep learning : How do I know which variables are important?
|
A somewhat brute force but effective solution:
Try 'droping' an input by using a constant for one of your input features. Then, train the network for each of the possible cases and see how your accuracy drops. Important inputs will provide the greatest benefit to overall accuracy.
|
Deep learning : How do I know which variables are important?
|
A somewhat brute force but effective solution:
Try 'droping' an input by using a constant for one of your input features. Then, train the network for each of the possible cases and see how your accura
|
Deep learning : How do I know which variables are important?
A somewhat brute force but effective solution:
Try 'droping' an input by using a constant for one of your input features. Then, train the network for each of the possible cases and see how your accuracy drops. Important inputs will provide the greatest benefit to overall accuracy.
|
Deep learning : How do I know which variables are important?
A somewhat brute force but effective solution:
Try 'droping' an input by using a constant for one of your input features. Then, train the network for each of the possible cases and see how your accura
|
9,187
|
Deep learning : How do I know which variables are important?
|
What you described is not "deep network", where you only have $10$ inputs and $5$ units in hidden layer. When people say deep learning, it usually means hundreds of thousands of hidden units.
For a shallow network, this gives an example of define the variable importance.
For a really deep network, people do not talk about variable importance too much. Because the inputs are raw level features, such as pixels in an image.
|
Deep learning : How do I know which variables are important?
|
What you described is not "deep network", where you only have $10$ inputs and $5$ units in hidden layer. When people say deep learning, it usually means hundreds of thousands of hidden units.
For a sh
|
Deep learning : How do I know which variables are important?
What you described is not "deep network", where you only have $10$ inputs and $5$ units in hidden layer. When people say deep learning, it usually means hundreds of thousands of hidden units.
For a shallow network, this gives an example of define the variable importance.
For a really deep network, people do not talk about variable importance too much. Because the inputs are raw level features, such as pixels in an image.
|
Deep learning : How do I know which variables are important?
What you described is not "deep network", where you only have $10$ inputs and $5$ units in hidden layer. When people say deep learning, it usually means hundreds of thousands of hidden units.
For a sh
|
9,188
|
Deep learning : How do I know which variables are important?
|
The most that ive found about this is elaborately listed on this site more specifically you can look at this. If you talk only about linear models then you have to normalize the weights to make them interpret-able but even this can be misleading more on this on the link mentioned . Some people tried making complex functions of weights to interpret importance's of inputs (Garson's , Gedeon's and Milne's ) but even this can be misleading you can find more about this once you scroll the first link i mentioned. In general i would advice to go ahead interpret the results with a grain of salt.
would agree with @rhadar's answer but would like to add that instead of using any constant try using the mean value for that input and don't forget to retrain the network.
PS: sorry could not post more links or comment here don't have much reputation.
|
Deep learning : How do I know which variables are important?
|
The most that ive found about this is elaborately listed on this site more specifically you can look at this. If you talk only about linear models then you have to normalize the weights to make them i
|
Deep learning : How do I know which variables are important?
The most that ive found about this is elaborately listed on this site more specifically you can look at this. If you talk only about linear models then you have to normalize the weights to make them interpret-able but even this can be misleading more on this on the link mentioned . Some people tried making complex functions of weights to interpret importance's of inputs (Garson's , Gedeon's and Milne's ) but even this can be misleading you can find more about this once you scroll the first link i mentioned. In general i would advice to go ahead interpret the results with a grain of salt.
would agree with @rhadar's answer but would like to add that instead of using any constant try using the mean value for that input and don't forget to retrain the network.
PS: sorry could not post more links or comment here don't have much reputation.
|
Deep learning : How do I know which variables are important?
The most that ive found about this is elaborately listed on this site more specifically you can look at this. If you talk only about linear models then you have to normalize the weights to make them i
|
9,189
|
Deep learning : How do I know which variables are important?
|
Given that you have:
A classification task
A trained model
Normalised features (between 0 and 1)
Has anyone tried:
Zeroing out the biases
Pass each time as features a one hot vector where all features are zero except one.
Examine the output.
In that case, I think the output would be a number designating the "importance" of the feature as this output would also represent the output of the path of this 1 signal inside the network.
It is like lighting only one lightbulb inside a labyrinth and measure the light coming out in the exit.
|
Deep learning : How do I know which variables are important?
|
Given that you have:
A classification task
A trained model
Normalised features (between 0 and 1)
Has anyone tried:
Zeroing out the biases
Pass each time as features a one hot vector where all fe
|
Deep learning : How do I know which variables are important?
Given that you have:
A classification task
A trained model
Normalised features (between 0 and 1)
Has anyone tried:
Zeroing out the biases
Pass each time as features a one hot vector where all features are zero except one.
Examine the output.
In that case, I think the output would be a number designating the "importance" of the feature as this output would also represent the output of the path of this 1 signal inside the network.
It is like lighting only one lightbulb inside a labyrinth and measure the light coming out in the exit.
|
Deep learning : How do I know which variables are important?
Given that you have:
A classification task
A trained model
Normalised features (between 0 and 1)
Has anyone tried:
Zeroing out the biases
Pass each time as features a one hot vector where all fe
|
9,190
|
Deep learning : How do I know which variables are important?
|
You can also compute permutation importance of the input variables:
https://scikit-learn.org/stable/modules/permutation_importance.html
It is model-agnostic and is applicable to measure importance of input variables for “black-box” models like neural networks.
|
Deep learning : How do I know which variables are important?
|
You can also compute permutation importance of the input variables:
https://scikit-learn.org/stable/modules/permutation_importance.html
It is model-agnostic and is applicable to measure importance of
|
Deep learning : How do I know which variables are important?
You can also compute permutation importance of the input variables:
https://scikit-learn.org/stable/modules/permutation_importance.html
It is model-agnostic and is applicable to measure importance of input variables for “black-box” models like neural networks.
|
Deep learning : How do I know which variables are important?
You can also compute permutation importance of the input variables:
https://scikit-learn.org/stable/modules/permutation_importance.html
It is model-agnostic and is applicable to measure importance of
|
9,191
|
Deep learning : How do I know which variables are important?
|
What you describe is IMHO a simple and effective way to determine what inputs your model is most sensitive to.
However, 'sensitive' is not necessarily the same as 'important'.
For example if your model is very prone to overfitting issues then such a metric could easily lead you in the wrong direction: Those 'highly sensitive inputs' could then actually just mean 'highly important for easy overfitting'.
|
Deep learning : How do I know which variables are important?
|
What you describe is IMHO a simple and effective way to determine what inputs your model is most sensitive to.
However, 'sensitive' is not necessarily the same as 'important'.
For example if your mode
|
Deep learning : How do I know which variables are important?
What you describe is IMHO a simple and effective way to determine what inputs your model is most sensitive to.
However, 'sensitive' is not necessarily the same as 'important'.
For example if your model is very prone to overfitting issues then such a metric could easily lead you in the wrong direction: Those 'highly sensitive inputs' could then actually just mean 'highly important for easy overfitting'.
|
Deep learning : How do I know which variables are important?
What you describe is IMHO a simple and effective way to determine what inputs your model is most sensitive to.
However, 'sensitive' is not necessarily the same as 'important'.
For example if your mode
|
9,192
|
The proof of shrinking coefficients using ridge regression through "spectral decomposition"
|
The question appears to ask for a demonstration that Ridge Regression shrinks coefficient estimates towards zero, using a spectral decomposition. The spectral decomposition can be understood as an easy consequence of the Singular Value Decomposition (SVD). Therefore, this post starts with SVD. It explains it in simple terms and then illustrates it with important applications. Then it provides the requested (algebraic) demonstration. (The algebra, of course, is identical to the geometric demonstration; it merely is couched in a different language.)
##What the SVD is
Any $n\times p$ matrix $X$, with $p \le n$, can be written $$X = UDV^\prime$$ where
$U$ is an $n\times p$ matrix.
The columns of $U$ have length $1$.
The columns of $U$ are mutually orthogonal.
They are called the principal components of $X$.
$V$ is a $p \times p$ matrix.
The columns of $V$ have length $1$.
The columns of $V$ are mutually orthogonal.
This makes $V$ a rotation of $\mathbb{R}^p$.
$D$ is a diagonal $p \times p$ matrix.
The diagonal elements $d_{11}, d_{22}, \ldots, d_{pp}$ are not negative. These are the singular values of $X$.
If we wish, we may order them from largest to smallest.
Criteria (1) and (2) assert that both $U$ and $V$ are orthonormal matrices. They can be neatly summarized by the conditions
$$U^\prime U = 1_p,\ V^\prime V = 1_p.$$
As a consequence (that $V$ represents a rotation), $VV^\prime = 1_p$ also. This will be used in the Ridge Regression derivation below.
##What it does for us
It can simplify formulas. This works both algebraically and conceptually. Here are some examples.
###The Normal Equations
Consider the regression $y = X\beta + \varepsilon$ where, as usual, the $\varepsilon$ are independent and identically distributed according to a law that has zero expectation and finite variance $\sigma^2$. The least squares solution via the Normal Equations is $$\hat\beta = (X^\prime X)^{-1} X^\prime y.$$ Applying the SVD and simplifying the resulting algebraic mess (which is easy) provides a nice insight:
$$(X^\prime X)^{-1} X^\prime = ((UDV^\prime)^\prime (UDV^\prime))^{-1} (UDV^\prime)^\prime \\= (VDU^\prime U D V^\prime)^{-1} (VDU^\prime) = VD^{-2}V^\prime VDU^\prime = VD^{-1}U^\prime.$$
The only difference between this and $X^\prime = VDU^\prime$ is that the reciprocals of the elements of $D$ are used! In other words, the "equation" $y=X\beta$ is solved by "inverting" $X$: this pseudo-inversion undoes the rotations $U$ and $V^\prime$ (merely by transposing them) and undoes the multiplication (represented by $D$) separately in each principal direction.
For future reference, notice that "rotated" estimates $V^\prime \hat\beta $ are linear combinations of "rotated" responses $U^\prime y$. The coefficients are inverses of the (positive) diagonal elements of $D$, equal to $d_{ii}^{-1}$.
###Covariance of the coefficient estimates
Recall that the covariance of the estimates is $$\text{Cov}(\hat\beta) = \sigma^2(X^\prime X)^{-1}.$$ Using the SVD, this becomes $$\sigma^2(V D^2 V^\prime)^{-1} = \sigma^2 V D^{-2} V^\prime.$$ In other words, the covariance acts like that of $k$ orthogonal variables, each with variances $d^2_{ii}$, that have been rotated in $\mathbb{R}^k$.
###The Hat matrix
The hat matrix is $$H = X(X^\prime X)^{-1} X^\prime.$$ By means of the preceding result we may rewrite it as $$H = (UDV^\prime)(VD^{-1}U^\prime) = UU^\prime.$$ Simple!
###Eigenanalysis (spectral decomposition)
Since $$X^\prime X = VDU^\prime U D V^\prime = VD^2V^\prime$$ and $$XX^\prime = UDV^\prime VDU^\prime = UD^2U^\prime,$$ it is immediate that
The eigenvalues of $X^\prime X$ and $XX^\prime$ are the squares of the singular values.
The columns of $V$ are the eigenvectors of $X^\prime X$.
The columns of $U$ are some of the eigenvectors of $X X^\prime$. (Other eigenvectors exist but correspond to zero eigenvalues.)
SVD can diagnose and solve collinearity problems.
###Approximating the regressors
When you replace the smallest singular values with zeros, you will change the product $UDV^\prime$ only slightly. Now, however, the zeros eliminate the corresponding columns of $U$, effectively reducing the number of variables. Provided those eliminated columns have little correlation with $y$, this can work effectively as a variable-reduction technique.
##Ridge Regression
Let the columns of $X$ be standardized, as well as $y$ itself. (This means we no longer need a constant column in $X$.) For $\lambda \gt 0$ the ridge estimator is $$\begin{aligned}\hat\beta_R &= (X^\prime X + \lambda)^{-1}X^\prime y \\
&= (VD^2V^\prime + \lambda\,1_p)^{-1}VDU^\prime y \\
&= (VD^2V^\prime + \lambda V V^\prime)^{-1}VDU^\prime y \\
&= (V(D^2 + \lambda)V^\prime)^{-1} VDU^\prime y \\
&= V(D^2+\lambda)^{-1}V^\prime V DU^\prime y \\
&= V(D^2 + \lambda)^{-1} D U^\prime y.\end{aligned}$$
The difference between this and $\hat\beta$ is the replacement of $D^{-1} = D^{-2}D$ by $(D^2+\lambda)^{-1}D$. In effect, this multiplies the original by the fraction $D^2/(D^2+\lambda)$. Because (when $\lambda \gt 0$) the denominator is obviously greater than the numerator, the parameter estimates "shrink towards zero."
This result has to be understood in the somewhat subtle sense alluded to previously: the rotated estimates $V^\prime\hat\beta_R$ are still linear combinations of the vectors $U^\prime y$, but each coefficient--which used to be $d_{ii}^{-1}$--has been multiplied by a factor of $d_{ii}^2/(d_{ii}^2 + \lambda)$. As such, the rotated coefficients must shrink, but it is possible, when $\lambda$ is sufficiently small, for some of the $\hat\beta_R$ themselves actually to increase in size.
To avoid distractions, the case of one of more zero singular values was excluded in this discussion. In such circumstances, if we conventionally take "$d_{ii}^{-1}$" to be zero, then everything still works. This is what is going on when generalized inverses are used to solve the Normal equations.
|
The proof of shrinking coefficients using ridge regression through "spectral decomposition"
|
The question appears to ask for a demonstration that Ridge Regression shrinks coefficient estimates towards zero, using a spectral decomposition. The spectral decomposition can be understood as an ea
|
The proof of shrinking coefficients using ridge regression through "spectral decomposition"
The question appears to ask for a demonstration that Ridge Regression shrinks coefficient estimates towards zero, using a spectral decomposition. The spectral decomposition can be understood as an easy consequence of the Singular Value Decomposition (SVD). Therefore, this post starts with SVD. It explains it in simple terms and then illustrates it with important applications. Then it provides the requested (algebraic) demonstration. (The algebra, of course, is identical to the geometric demonstration; it merely is couched in a different language.)
##What the SVD is
Any $n\times p$ matrix $X$, with $p \le n$, can be written $$X = UDV^\prime$$ where
$U$ is an $n\times p$ matrix.
The columns of $U$ have length $1$.
The columns of $U$ are mutually orthogonal.
They are called the principal components of $X$.
$V$ is a $p \times p$ matrix.
The columns of $V$ have length $1$.
The columns of $V$ are mutually orthogonal.
This makes $V$ a rotation of $\mathbb{R}^p$.
$D$ is a diagonal $p \times p$ matrix.
The diagonal elements $d_{11}, d_{22}, \ldots, d_{pp}$ are not negative. These are the singular values of $X$.
If we wish, we may order them from largest to smallest.
Criteria (1) and (2) assert that both $U$ and $V$ are orthonormal matrices. They can be neatly summarized by the conditions
$$U^\prime U = 1_p,\ V^\prime V = 1_p.$$
As a consequence (that $V$ represents a rotation), $VV^\prime = 1_p$ also. This will be used in the Ridge Regression derivation below.
##What it does for us
It can simplify formulas. This works both algebraically and conceptually. Here are some examples.
###The Normal Equations
Consider the regression $y = X\beta + \varepsilon$ where, as usual, the $\varepsilon$ are independent and identically distributed according to a law that has zero expectation and finite variance $\sigma^2$. The least squares solution via the Normal Equations is $$\hat\beta = (X^\prime X)^{-1} X^\prime y.$$ Applying the SVD and simplifying the resulting algebraic mess (which is easy) provides a nice insight:
$$(X^\prime X)^{-1} X^\prime = ((UDV^\prime)^\prime (UDV^\prime))^{-1} (UDV^\prime)^\prime \\= (VDU^\prime U D V^\prime)^{-1} (VDU^\prime) = VD^{-2}V^\prime VDU^\prime = VD^{-1}U^\prime.$$
The only difference between this and $X^\prime = VDU^\prime$ is that the reciprocals of the elements of $D$ are used! In other words, the "equation" $y=X\beta$ is solved by "inverting" $X$: this pseudo-inversion undoes the rotations $U$ and $V^\prime$ (merely by transposing them) and undoes the multiplication (represented by $D$) separately in each principal direction.
For future reference, notice that "rotated" estimates $V^\prime \hat\beta $ are linear combinations of "rotated" responses $U^\prime y$. The coefficients are inverses of the (positive) diagonal elements of $D$, equal to $d_{ii}^{-1}$.
###Covariance of the coefficient estimates
Recall that the covariance of the estimates is $$\text{Cov}(\hat\beta) = \sigma^2(X^\prime X)^{-1}.$$ Using the SVD, this becomes $$\sigma^2(V D^2 V^\prime)^{-1} = \sigma^2 V D^{-2} V^\prime.$$ In other words, the covariance acts like that of $k$ orthogonal variables, each with variances $d^2_{ii}$, that have been rotated in $\mathbb{R}^k$.
###The Hat matrix
The hat matrix is $$H = X(X^\prime X)^{-1} X^\prime.$$ By means of the preceding result we may rewrite it as $$H = (UDV^\prime)(VD^{-1}U^\prime) = UU^\prime.$$ Simple!
###Eigenanalysis (spectral decomposition)
Since $$X^\prime X = VDU^\prime U D V^\prime = VD^2V^\prime$$ and $$XX^\prime = UDV^\prime VDU^\prime = UD^2U^\prime,$$ it is immediate that
The eigenvalues of $X^\prime X$ and $XX^\prime$ are the squares of the singular values.
The columns of $V$ are the eigenvectors of $X^\prime X$.
The columns of $U$ are some of the eigenvectors of $X X^\prime$. (Other eigenvectors exist but correspond to zero eigenvalues.)
SVD can diagnose and solve collinearity problems.
###Approximating the regressors
When you replace the smallest singular values with zeros, you will change the product $UDV^\prime$ only slightly. Now, however, the zeros eliminate the corresponding columns of $U$, effectively reducing the number of variables. Provided those eliminated columns have little correlation with $y$, this can work effectively as a variable-reduction technique.
##Ridge Regression
Let the columns of $X$ be standardized, as well as $y$ itself. (This means we no longer need a constant column in $X$.) For $\lambda \gt 0$ the ridge estimator is $$\begin{aligned}\hat\beta_R &= (X^\prime X + \lambda)^{-1}X^\prime y \\
&= (VD^2V^\prime + \lambda\,1_p)^{-1}VDU^\prime y \\
&= (VD^2V^\prime + \lambda V V^\prime)^{-1}VDU^\prime y \\
&= (V(D^2 + \lambda)V^\prime)^{-1} VDU^\prime y \\
&= V(D^2+\lambda)^{-1}V^\prime V DU^\prime y \\
&= V(D^2 + \lambda)^{-1} D U^\prime y.\end{aligned}$$
The difference between this and $\hat\beta$ is the replacement of $D^{-1} = D^{-2}D$ by $(D^2+\lambda)^{-1}D$. In effect, this multiplies the original by the fraction $D^2/(D^2+\lambda)$. Because (when $\lambda \gt 0$) the denominator is obviously greater than the numerator, the parameter estimates "shrink towards zero."
This result has to be understood in the somewhat subtle sense alluded to previously: the rotated estimates $V^\prime\hat\beta_R$ are still linear combinations of the vectors $U^\prime y$, but each coefficient--which used to be $d_{ii}^{-1}$--has been multiplied by a factor of $d_{ii}^2/(d_{ii}^2 + \lambda)$. As such, the rotated coefficients must shrink, but it is possible, when $\lambda$ is sufficiently small, for some of the $\hat\beta_R$ themselves actually to increase in size.
To avoid distractions, the case of one of more zero singular values was excluded in this discussion. In such circumstances, if we conventionally take "$d_{ii}^{-1}$" to be zero, then everything still works. This is what is going on when generalized inverses are used to solve the Normal equations.
|
The proof of shrinking coefficients using ridge regression through "spectral decomposition"
The question appears to ask for a demonstration that Ridge Regression shrinks coefficient estimates towards zero, using a spectral decomposition. The spectral decomposition can be understood as an ea
|
9,193
|
Advantages of doing "double lasso" or performing lasso twice?
|
Yes, the procedure you are asking (or thinking of) is called the relaxed lasso.
The general idea is that in the process of performing the LASSO for the first time you are probably including "noise variables"; performing the LASSO on a second set of variables (after the first LASSO) gives less competition between variables that are "real competitors" to being part of the model and not just "noise" variables. Technically, what this methods aims to is to overcome the (known) slow convergence of the LASSO in datasets with large number of variables.
You can read more about it on the original paper by Meinshausen (2007).
I also recommend section 3.8.5 on the Elements of Statistical Learning (Hastie, Tibshirani & Friedman, 2008), which gives an overview of other very interesting methods for performing variable selection using the LASSO.
|
Advantages of doing "double lasso" or performing lasso twice?
|
Yes, the procedure you are asking (or thinking of) is called the relaxed lasso.
The general idea is that in the process of performing the LASSO for the first time you are probably including "noise va
|
Advantages of doing "double lasso" or performing lasso twice?
Yes, the procedure you are asking (or thinking of) is called the relaxed lasso.
The general idea is that in the process of performing the LASSO for the first time you are probably including "noise variables"; performing the LASSO on a second set of variables (after the first LASSO) gives less competition between variables that are "real competitors" to being part of the model and not just "noise" variables. Technically, what this methods aims to is to overcome the (known) slow convergence of the LASSO in datasets with large number of variables.
You can read more about it on the original paper by Meinshausen (2007).
I also recommend section 3.8.5 on the Elements of Statistical Learning (Hastie, Tibshirani & Friedman, 2008), which gives an overview of other very interesting methods for performing variable selection using the LASSO.
|
Advantages of doing "double lasso" or performing lasso twice?
Yes, the procedure you are asking (or thinking of) is called the relaxed lasso.
The general idea is that in the process of performing the LASSO for the first time you are probably including "noise va
|
9,194
|
Advantages of doing "double lasso" or performing lasso twice?
|
The idea is to separate the two effects of lasso
Variable selection (i.e., many, even most, $\beta$s are zero)
Coefficient shrinkage (i.e., even non-zero $\beta$s are smaller, in absolute value, than in unpenalised regression). This is often a good thing even without selection because you avoid over-fitting.
If you have many variables ($p >\!\!> n$), and are running lasso, then you want to have a large penalty to select a small number of variables. However, this penalty might shrink the selected variables too much (you are under-fitting).
The idea of relaxed lasso is that you separate the two effects: you use a high penalty on the first pass to select variables; and a smaller penalty on the second pass to shrink them by a smaller amount.
The original paper (as linked by Néstor) gives more detail.
|
Advantages of doing "double lasso" or performing lasso twice?
|
The idea is to separate the two effects of lasso
Variable selection (i.e., many, even most, $\beta$s are zero)
Coefficient shrinkage (i.e., even non-zero $\beta$s are smaller, in absolute value, than
|
Advantages of doing "double lasso" or performing lasso twice?
The idea is to separate the two effects of lasso
Variable selection (i.e., many, even most, $\beta$s are zero)
Coefficient shrinkage (i.e., even non-zero $\beta$s are smaller, in absolute value, than in unpenalised regression). This is often a good thing even without selection because you avoid over-fitting.
If you have many variables ($p >\!\!> n$), and are running lasso, then you want to have a large penalty to select a small number of variables. However, this penalty might shrink the selected variables too much (you are under-fitting).
The idea of relaxed lasso is that you separate the two effects: you use a high penalty on the first pass to select variables; and a smaller penalty on the second pass to shrink them by a smaller amount.
The original paper (as linked by Néstor) gives more detail.
|
Advantages of doing "double lasso" or performing lasso twice?
The idea is to separate the two effects of lasso
Variable selection (i.e., many, even most, $\beta$s are zero)
Coefficient shrinkage (i.e., even non-zero $\beta$s are smaller, in absolute value, than
|
9,195
|
How to compute the confidence interval of the ratio of two normal means
|
Fieller's method does what you want -- compute a confidence interval for the quotient of two means, both assumed to be sampled from Gaussian distributions.
The original citation is: Fieller EC: The biological standardization of Insulin. Suppl to J R Statist Soc 1940, 7:1-64.
The Wikipedia article does a good job of summarizing.
I've created an online calculator that does the computation.
Here is a page summarizing the math from the first edition of my Intuitive Biostatistics
|
How to compute the confidence interval of the ratio of two normal means
|
Fieller's method does what you want -- compute a confidence interval for the quotient of two means, both assumed to be sampled from Gaussian distributions.
The original citation is: Fieller EC: The
|
How to compute the confidence interval of the ratio of two normal means
Fieller's method does what you want -- compute a confidence interval for the quotient of two means, both assumed to be sampled from Gaussian distributions.
The original citation is: Fieller EC: The biological standardization of Insulin. Suppl to J R Statist Soc 1940, 7:1-64.
The Wikipedia article does a good job of summarizing.
I've created an online calculator that does the computation.
Here is a page summarizing the math from the first edition of my Intuitive Biostatistics
|
How to compute the confidence interval of the ratio of two normal means
Fieller's method does what you want -- compute a confidence interval for the quotient of two means, both assumed to be sampled from Gaussian distributions.
The original citation is: Fieller EC: The
|
9,196
|
How to compute the confidence interval of the ratio of two normal means
|
R has the package mratios with the function t.test.ratio.
Gemechis Dilba Djira, Mario Hasler, Daniel Gerhard and Frank
Schaarschmidt (2011). mratios: Inferences for ratios of coefficients
in the general linear model. R package version 1.3.15.
http://CRAN.R-project.org/package=mratios
See also http://www.r-project.org/user-2006/Slides/DilbaEtAl.pdf
|
How to compute the confidence interval of the ratio of two normal means
|
R has the package mratios with the function t.test.ratio.
Gemechis Dilba Djira, Mario Hasler, Daniel Gerhard and Frank
Schaarschmidt (2011). mratios: Inferences for ratios of coefficients
in the
|
How to compute the confidence interval of the ratio of two normal means
R has the package mratios with the function t.test.ratio.
Gemechis Dilba Djira, Mario Hasler, Daniel Gerhard and Frank
Schaarschmidt (2011). mratios: Inferences for ratios of coefficients
in the general linear model. R package version 1.3.15.
http://CRAN.R-project.org/package=mratios
See also http://www.r-project.org/user-2006/Slides/DilbaEtAl.pdf
|
How to compute the confidence interval of the ratio of two normal means
R has the package mratios with the function t.test.ratio.
Gemechis Dilba Djira, Mario Hasler, Daniel Gerhard and Frank
Schaarschmidt (2011). mratios: Inferences for ratios of coefficients
in the
|
9,197
|
How to compute the confidence interval of the ratio of two normal means
|
Also if you want to compute Fieller's confidence interval not using mratios (typically because you don't want a simple lm fit but for example a glmer or glmer.nb fit), you can use the following FiellerRatioCI function, with model the output of the model, aname the name of the numerator parameter, bname the name of the denomiator parameter.
You can also use directly the FiellerRatioCI_basic function giving, a, b and the covariance matrix between a and b.
FiellerRatioCI <- function (x, ...) { # generic Biomass Equilibrium Level
UseMethod("FiellerRatioCI", x)
}
FiellerRatioCI_basic <- function(a,b,V,alpha=0.05){
theta <- a/b
v11 <- V[1,1]
v12 <- V[1,2]
v22 <- V[2,2]
z <- qnorm(1-alpha/2)
g <- (z^2)*v22/b^2
C <- sqrt(v11 - 2*theta*v12 + theta^2 * v22 - g*(v11-v12^2/v22))
minS <- (1/(1-g))*(theta- g*v12/v22 - z/b * C)
maxS <- (1/(1-g))*(theta- g*v12/v22 + z/b * C)
return(c(ratio=theta,min=minS,max=maxS))
}
FiellerRatioCI.glmerMod <- function(model,aname,bname){
V <- vcov(model)
a<-as.numeric(unique(coef(model)$culture[aname]))
b<-as.numeric(unique(coef(model)$culture[bname]))
return(FiellerRatioCI_basic(a,b,V[c(aname,bname),c(aname,bname)]))
}
FiellerRatioCI.glm <- function(model,aname,bname){
V <- vcov(model)
a <- coef(model)[aname]
b <- coef(model)[bname]
return(FiellerRatioCI_basic(a,b,V[c(aname,bname),c(aname,bname)]))
}
Example (based on standard glm basic example):
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
glm.D93 <- glm(counts ~ outcome + treatment, family = poisson())
FiellerRatioCI(glm.D93,"outcome2","outcome3")
ratio.outcome2 min max
1.550427 -2.226870 17.880574
|
How to compute the confidence interval of the ratio of two normal means
|
Also if you want to compute Fieller's confidence interval not using mratios (typically because you don't want a simple lm fit but for example a glmer or glmer.nb fit), you can use the following Fielle
|
How to compute the confidence interval of the ratio of two normal means
Also if you want to compute Fieller's confidence interval not using mratios (typically because you don't want a simple lm fit but for example a glmer or glmer.nb fit), you can use the following FiellerRatioCI function, with model the output of the model, aname the name of the numerator parameter, bname the name of the denomiator parameter.
You can also use directly the FiellerRatioCI_basic function giving, a, b and the covariance matrix between a and b.
FiellerRatioCI <- function (x, ...) { # generic Biomass Equilibrium Level
UseMethod("FiellerRatioCI", x)
}
FiellerRatioCI_basic <- function(a,b,V,alpha=0.05){
theta <- a/b
v11 <- V[1,1]
v12 <- V[1,2]
v22 <- V[2,2]
z <- qnorm(1-alpha/2)
g <- (z^2)*v22/b^2
C <- sqrt(v11 - 2*theta*v12 + theta^2 * v22 - g*(v11-v12^2/v22))
minS <- (1/(1-g))*(theta- g*v12/v22 - z/b * C)
maxS <- (1/(1-g))*(theta- g*v12/v22 + z/b * C)
return(c(ratio=theta,min=minS,max=maxS))
}
FiellerRatioCI.glmerMod <- function(model,aname,bname){
V <- vcov(model)
a<-as.numeric(unique(coef(model)$culture[aname]))
b<-as.numeric(unique(coef(model)$culture[bname]))
return(FiellerRatioCI_basic(a,b,V[c(aname,bname),c(aname,bname)]))
}
FiellerRatioCI.glm <- function(model,aname,bname){
V <- vcov(model)
a <- coef(model)[aname]
b <- coef(model)[bname]
return(FiellerRatioCI_basic(a,b,V[c(aname,bname),c(aname,bname)]))
}
Example (based on standard glm basic example):
counts <- c(18,17,15,20,10,20,25,13,12)
outcome <- gl(3,1,9)
treatment <- gl(3,3)
glm.D93 <- glm(counts ~ outcome + treatment, family = poisson())
FiellerRatioCI(glm.D93,"outcome2","outcome3")
ratio.outcome2 min max
1.550427 -2.226870 17.880574
|
How to compute the confidence interval of the ratio of two normal means
Also if you want to compute Fieller's confidence interval not using mratios (typically because you don't want a simple lm fit but for example a glmer or glmer.nb fit), you can use the following Fielle
|
9,198
|
How to compute the confidence interval of the ratio of two normal means
|
You can calculate it through:
Fieller's method
The Taylor method, also called Delta method: it's easier than Fieller's but will fail if the denominator approaches zero.
The Hwang–bootstrap method, a bootstrap technique that does not result in unbounded confidence limits.
Here you can find a thorough description and comparison of these methods.
|
How to compute the confidence interval of the ratio of two normal means
|
You can calculate it through:
Fieller's method
The Taylor method, also called Delta method: it's easier than Fieller's but will fail if the denominator approaches zero.
The Hwang–bootstrap method, a
|
How to compute the confidence interval of the ratio of two normal means
You can calculate it through:
Fieller's method
The Taylor method, also called Delta method: it's easier than Fieller's but will fail if the denominator approaches zero.
The Hwang–bootstrap method, a bootstrap technique that does not result in unbounded confidence limits.
Here you can find a thorough description and comparison of these methods.
|
How to compute the confidence interval of the ratio of two normal means
You can calculate it through:
Fieller's method
The Taylor method, also called Delta method: it's easier than Fieller's but will fail if the denominator approaches zero.
The Hwang–bootstrap method, a
|
9,199
|
Statistical podcasts
|
BBC's More or Less is often concerned with numeracy and statistical literacy issues. But it's not specifically about statistics. Their About page has some background.
More or Less is devoted to the powerful, sometimes beautiful, often abused but ever ubiquitous world of numbers.
The programme was an idea born of the sense that numbers were the principal language of public argument.
[...]
|
Statistical podcasts
|
BBC's More or Less is often concerned with numeracy and statistical literacy issues. But it's not specifically about statistics. Their About page has some background.
More or Less is devoted to the
|
Statistical podcasts
BBC's More or Less is often concerned with numeracy and statistical literacy issues. But it's not specifically about statistics. Their About page has some background.
More or Less is devoted to the powerful, sometimes beautiful, often abused but ever ubiquitous world of numbers.
The programme was an idea born of the sense that numbers were the principal language of public argument.
[...]
|
Statistical podcasts
BBC's More or Less is often concerned with numeracy and statistical literacy issues. But it's not specifically about statistics. Their About page has some background.
More or Less is devoted to the
|
9,200
|
Statistical podcasts
|
There is econtalk, it is mostly about economics, but delves very often to issues of research, science, and statistics.
|
Statistical podcasts
|
There is econtalk, it is mostly about economics, but delves very often to issues of research, science, and statistics.
|
Statistical podcasts
There is econtalk, it is mostly about economics, but delves very often to issues of research, science, and statistics.
|
Statistical podcasts
There is econtalk, it is mostly about economics, but delves very often to issues of research, science, and statistics.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.