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
|
|---|---|---|---|---|---|---|
6,501
|
Random walk on the edges of a cube
|
Let $x^*$ be the number of expected steps. Let $x_1$ be the number of expected steps from any corner adjacent to the origin of the spider and $x_0$ ditto for the ant.
Then $x^* = 1 + x_1$ and $x_0 = 1 + \frac{2}{3}x_1$. Since
$$x_1 = 1 + \frac{2}{3}x_0 + \frac{1}{3}x^*= 1 + \frac{2}{3}x_0 + \frac{1}{3} + \frac{1}{3}x_1$$
we get that $x_1 = x_0 + 2$. So $x_0 = 1 + \frac{2}{3}x_0 + \frac{4}{3}$ implying that $x_0=7$ and $x_1=9$.
We get our answer as $x^*=10$.
Edit:
If we draw the cube with coordinates $(x, y, z)$ then $111$ is the starting position of the spider and $000$ the position of the ant.
The spider can move to either $011$, $101$ or $110$.
By the symmetry of the cube these must have the same number of expected steps to the ant, denoted by $x_1$. From $x_1$, we can either return to the origin (with probability $1/3$) or (with probability $2/3$) we can go to one of the points $001$, $100$, $010$ depending on which state we are in.
Again, by symmetry, these points will have the same number of expected steps which we call $x_0$. From these positions we can reach the goal in one step with probability $1/3$ or go back to one of the $x_1$-positions with probability $2/3$. This means that
$x_0 = \frac{1}{3}1 + \frac{2}{3}(1 + x_1) = 1 + \frac{2}{3}x_1$.
|
Random walk on the edges of a cube
|
Let $x^*$ be the number of expected steps. Let $x_1$ be the number of expected steps from any corner adjacent to the origin of the spider and $x_0$ ditto for the ant.
Then $x^* = 1 + x_1$ and $x_0 = 1
|
Random walk on the edges of a cube
Let $x^*$ be the number of expected steps. Let $x_1$ be the number of expected steps from any corner adjacent to the origin of the spider and $x_0$ ditto for the ant.
Then $x^* = 1 + x_1$ and $x_0 = 1 + \frac{2}{3}x_1$. Since
$$x_1 = 1 + \frac{2}{3}x_0 + \frac{1}{3}x^*= 1 + \frac{2}{3}x_0 + \frac{1}{3} + \frac{1}{3}x_1$$
we get that $x_1 = x_0 + 2$. So $x_0 = 1 + \frac{2}{3}x_0 + \frac{4}{3}$ implying that $x_0=7$ and $x_1=9$.
We get our answer as $x^*=10$.
Edit:
If we draw the cube with coordinates $(x, y, z)$ then $111$ is the starting position of the spider and $000$ the position of the ant.
The spider can move to either $011$, $101$ or $110$.
By the symmetry of the cube these must have the same number of expected steps to the ant, denoted by $x_1$. From $x_1$, we can either return to the origin (with probability $1/3$) or (with probability $2/3$) we can go to one of the points $001$, $100$, $010$ depending on which state we are in.
Again, by symmetry, these points will have the same number of expected steps which we call $x_0$. From these positions we can reach the goal in one step with probability $1/3$ or go back to one of the $x_1$-positions with probability $2/3$. This means that
$x_0 = \frac{1}{3}1 + \frac{2}{3}(1 + x_1) = 1 + \frac{2}{3}x_1$.
|
Random walk on the edges of a cube
Let $x^*$ be the number of expected steps. Let $x_1$ be the number of expected steps from any corner adjacent to the origin of the spider and $x_0$ ditto for the ant.
Then $x^* = 1 + x_1$ and $x_0 = 1
|
6,502
|
Random walk on the edges of a cube
|
One nice abstraction to think of it is this:
Think of the Position of the Ant as $(0,0,0)$ and Spider $(1,1,1)$, now each move the spider can make will essentially switch exactly one of the three components from $1\to0$ or $0\to1$. So the question becomes:
If I randomly switch bits in (1,1,1) after how many steps in average do I get 0,0,0
We see the shortest way is 3 switches. Since it doesn't matter with which bit I start the probability of that happening is 1 * 2/3 * 1/3 = 2/9. If we make 1 mistake (switch one bit back to 1) we will need 5 steps. And the chances of making a mistake are 7/9 - if we want to make only one mistake, we have to get from there back and do everything right again - so the chance of making exactly 1 mistake resulting in 5 steps is 7/9 * 2/9 and the chance of making 2 mistakes aka 7 steps is (7/9)² * 2/9 and so on.
So the formula for the expected average number of steps is:
$$\mathbb E(\mathrm{steps}) = \sum_{n=0}^{\infty} (3 + 2n) \cdot \frac{2}{9} \cdot \left ( \frac{7}{9} \right ) ^{n} = 10$$
|
Random walk on the edges of a cube
|
One nice abstraction to think of it is this:
Think of the Position of the Ant as $(0,0,0)$ and Spider $(1,1,1)$, now each move the spider can make will essentially switch exactly one of the three comp
|
Random walk on the edges of a cube
One nice abstraction to think of it is this:
Think of the Position of the Ant as $(0,0,0)$ and Spider $(1,1,1)$, now each move the spider can make will essentially switch exactly one of the three components from $1\to0$ or $0\to1$. So the question becomes:
If I randomly switch bits in (1,1,1) after how many steps in average do I get 0,0,0
We see the shortest way is 3 switches. Since it doesn't matter with which bit I start the probability of that happening is 1 * 2/3 * 1/3 = 2/9. If we make 1 mistake (switch one bit back to 1) we will need 5 steps. And the chances of making a mistake are 7/9 - if we want to make only one mistake, we have to get from there back and do everything right again - so the chance of making exactly 1 mistake resulting in 5 steps is 7/9 * 2/9 and the chance of making 2 mistakes aka 7 steps is (7/9)² * 2/9 and so on.
So the formula for the expected average number of steps is:
$$\mathbb E(\mathrm{steps}) = \sum_{n=0}^{\infty} (3 + 2n) \cdot \frac{2}{9} \cdot \left ( \frac{7}{9} \right ) ^{n} = 10$$
|
Random walk on the edges of a cube
One nice abstraction to think of it is this:
Think of the Position of the Ant as $(0,0,0)$ and Spider $(1,1,1)$, now each move the spider can make will essentially switch exactly one of the three comp
|
6,503
|
Random walk on the edges of a cube
|
Just to compliment tiagotvv's answer:
I don't naturally think of these kinds of problems as matrices (even though they are). I have to draw it out, which I've done below. You can see that there are 3 places to move from S, all of which are As. From any A, you can either return to the S, or move to one of two Bs. From any B, you can move to the E, or to one of two As. This all translates to the transition matrix given by tiagotvv, which can also be drawn in graph form.
Because I am terrible at math, I would just try to simulate your problem. You can do this with the markovchain package in R.
library(markovchain)
library(ggplot2)
# Create a markovchain object, given the states and their transition matrix
mcCube <- new("markovchain",
states = c("S", "A", "B", "E"),
transitionMatrix = matrix(data = c(0, 1, 0, 0,
1/3, 0, 2/3, 0,
0, 2/3, 0, 1/3,
0, 0, 0, 1),
byrow = T, nrow = 4),
name = "cube")
# The following code calcuates the probability of landing on E after taking
# between 1 and 100 steps from the start, given the above set of transition
# probabilities.
start <- c(1, 0, 0, 0)
list <- list()
for (i in 1:100){
list[[i]] <- (start * mcCube^i)[4]
}
a <- do.call(rbind, list)
data <- data.frame(propE = a,
steps = c(1:100))
ggplot(data, aes(x = steps, y = propE)) +
geom_line(size = 1) +
ylab("Probability you reached the spider") +
xlab("Number of steps taken") +
theme_bw() +
theme(panel.grid.minor = element_blank())
# This code simulates 1000 different applications of the markov chain where you
# take 1000 steps, and records the step at which you landed on E
list <- list()
for (i in 1:1000) {
b <- rmarkovchain(n = 1000, object = mcCube, t0 = "S", include.t0 = T)
list[[i]] <- 1001 - length(b[b == "E"])
}
data <- as.data.frame(do.call(rbind, list))
ggplot(data, aes(x = V1)) +
geom_density(fill = "grey50", alpha = 0.5) +
geom_vline(aes(xintercept = mean(V1))) +
ylab("Density") +
xlab("Number of steps to reach E") +
theme_bw() +
theme(panel.grid.minor = element_blank())
mean(data$V1) # ~10 is the average number of steps to reach E in this set of
# simulations
tiagotvv's answer can be calcuated in R as:
q = matrix(c(0, 1, 0,
1/3, 0, 2/3,
0, 2/3, 0), byrow = T, nrow = 3)
(solve(diag(3) - q) %*% c(1, 1, 1))[1] # = 10
|
Random walk on the edges of a cube
|
Just to compliment tiagotvv's answer:
I don't naturally think of these kinds of problems as matrices (even though they are). I have to draw it out, which I've done below. You can see that there are 3
|
Random walk on the edges of a cube
Just to compliment tiagotvv's answer:
I don't naturally think of these kinds of problems as matrices (even though they are). I have to draw it out, which I've done below. You can see that there are 3 places to move from S, all of which are As. From any A, you can either return to the S, or move to one of two Bs. From any B, you can move to the E, or to one of two As. This all translates to the transition matrix given by tiagotvv, which can also be drawn in graph form.
Because I am terrible at math, I would just try to simulate your problem. You can do this with the markovchain package in R.
library(markovchain)
library(ggplot2)
# Create a markovchain object, given the states and their transition matrix
mcCube <- new("markovchain",
states = c("S", "A", "B", "E"),
transitionMatrix = matrix(data = c(0, 1, 0, 0,
1/3, 0, 2/3, 0,
0, 2/3, 0, 1/3,
0, 0, 0, 1),
byrow = T, nrow = 4),
name = "cube")
# The following code calcuates the probability of landing on E after taking
# between 1 and 100 steps from the start, given the above set of transition
# probabilities.
start <- c(1, 0, 0, 0)
list <- list()
for (i in 1:100){
list[[i]] <- (start * mcCube^i)[4]
}
a <- do.call(rbind, list)
data <- data.frame(propE = a,
steps = c(1:100))
ggplot(data, aes(x = steps, y = propE)) +
geom_line(size = 1) +
ylab("Probability you reached the spider") +
xlab("Number of steps taken") +
theme_bw() +
theme(panel.grid.minor = element_blank())
# This code simulates 1000 different applications of the markov chain where you
# take 1000 steps, and records the step at which you landed on E
list <- list()
for (i in 1:1000) {
b <- rmarkovchain(n = 1000, object = mcCube, t0 = "S", include.t0 = T)
list[[i]] <- 1001 - length(b[b == "E"])
}
data <- as.data.frame(do.call(rbind, list))
ggplot(data, aes(x = V1)) +
geom_density(fill = "grey50", alpha = 0.5) +
geom_vline(aes(xintercept = mean(V1))) +
ylab("Density") +
xlab("Number of steps to reach E") +
theme_bw() +
theme(panel.grid.minor = element_blank())
mean(data$V1) # ~10 is the average number of steps to reach E in this set of
# simulations
tiagotvv's answer can be calcuated in R as:
q = matrix(c(0, 1, 0,
1/3, 0, 2/3,
0, 2/3, 0), byrow = T, nrow = 3)
(solve(diag(3) - q) %*% c(1, 1, 1))[1] # = 10
|
Random walk on the edges of a cube
Just to compliment tiagotvv's answer:
I don't naturally think of these kinds of problems as matrices (even though they are). I have to draw it out, which I've done below. You can see that there are 3
|
6,504
|
Random walk on the edges of a cube
|
Parity considerations give a very clean solution, using surprisingly simple machinery: no Markov chains, no iterated expectations, and only high school level summations. The basic idea is that if the spider has moved an even number of times in the $x$ direction, it has returned to its original $x$ coordinate so can't be at the ant's position. If it has moved an odd number of times in the $x$ direction, then its $x$ coordinate matches the ant's. Only if it has moved an odd number of times in all three directions will it match the $x$, $y$ and $z$ coordinates of the ant.
Initially the spider has made zero moves in any of the three directions, so the parity for each direction is even. All three parities need to be flipped to reach the ant.
After the spider's first move (let's label that direction $x$), exactly one direction has odd parity and the other two ($y$ and $z$) are even. To catch the ant, only those two parities need to be reversed. Since that can't be achieved in an odd number of subsequent moves, from now on we consider pairs of moves. There are nine possible combinations for the first paired move:
$$(x,x), \,(x,y), \,(x,z), \,(y,x), \,(y,y), \,(y,z), \,(z,x), \,(z,y), \text{or} \,(z,z)$$
We need to move in the $y$ and $z$ directions to reach the ant after one paired move, and two out of nine combinations will achieve this: $(y,z)$ and $(z,y)$ would ensure all three parities are odd.
The other seven combinations leave one odd and two even parities. The three repeated moves, $(x,x)$, $(y,y)$ or $(z,z)$, leave all parities unchanged so we still require one $y$ and one $z$ movement to reach the ant. The other pairs contain two distinct moves, including one in the $x$ direction. This switches the parity of $x$ and one of the other parities (either $y$ or $z$) so we are still left with one odd and two even parities. For instance the pair $(x,z)$ leaves us needing one more $x$ and one more $y$ to reach the ant: an equivalent situation (after relabelling of axes) to where we were before. We can then analyse the next paired move in the same way.
In general paired moves start with one odd and two even parities, and will either end with three odd parities (with probability $\frac{2}{9}$) and the immediate capture of the ant, or with one odd and two even parities (with probability $\frac{7}{9}$) which returns us to the same situation.
Let $M$ be the number of paired moves required to reach the ant. Clearly $M$ follows the geometric distribution on the support $\{1, 2, 3, \dots\}$ with probability of success $p = \frac{2}{9}$ so has mean $\mathbb{E}(M) = p^{-1} = \frac{9}{2} = 4.5$. Let $N$ be the total number of moves required, including the initial move and the $M$ subsequent paired moves. Then $N = 2M + 1$ so, applying linearity of expectations, $\mathbb{E}(N) = 2\mathbb{E}(M) + 1 = 2 \times 4.5 + 1 = 10$.
Alternatively you might note $P(M \geq m) = (\frac{7}{9})^{m-1}$ and apply the well-known formula for the mean of a discrete distribution taking only non-negative integer values, $\mathbb{E}(M)=\sum_{m=1}^\infty P(M\geq m)$. This gives $\mathbb{E}(M)=\sum_{m=1}^\infty (\frac{7}{9})^{m-1}$ which is a geometric series with first term $a=1$ and common ratio $r=\frac{7}{9}$ so has sum $\frac{a}{1-r} = \frac{1}{1-7/9}=\frac{1}{2/9}=\frac{9}{2}$. We can then take $\mathbb{E}(N)$ as before.
Comparison to Markov chain solutions
How might I have spotted this from the Markov chain transition matrix? Using @DLDahly's notation, the states in the transition matrix correspond to my description of the number of the number of directions with odd parity.
The one-step transition matrix is
\begin{equation}
\mathbf{P} = \left[\begin{array}{cccc}
P_{S \to S} & P_{S \to A}& P_{S \to B} & P_{S \to E} \\
P_{A \to S} & P_{A \to A}& P_{A \to B} & P_{A \to E} \\
P_{B \to S} & P_{B \to A}& P_{B \to B} & P_{B \to E} \\
P_{E \to S} & P_{E \to A} & P_{E \to B}& P_{E \to E} \\
\end{array}\right] = \left[\begin{array}{cccc}
0 & 1 & 0 & 0 \\
1/3 & 0 & 2/3 & 0 \\
0 & 2/3 & 0 & 1/3 \\
0 & 0 & 0 & 1 \\
\end{array}\right]
\end{equation}
The first row show us that after one movement, the spider is guaranteed to be in state A (one odd and two even parities). The two-step transition matrix is:
\begin{equation}
\mathbf{P}^{(2)} = \mathbf{P}^{2} = \left[\begin{array}{cccc}
1/3 & 0 & 2/3 & 0 \\
0 & 7/9 & 0 & 2/9 \\
2/9 & 0 & 4/9 & 1/3 \\
0 & 0 & 0 & 1 \\
\end{array}\right]
\end{equation}
The second row shows us that once the spider has entered state A, in two moves time it has either returned to state A with probability $7/9$ or has reached state E (all odd parities) and captured the ant, with probabilty $2/9$. So having reached state A, we see from the two-step transition matrix that the number of two-step moves required can be analysed using the geometric distribution as above. This isn't how I found my solution, but it is sometimes worth calculating the first few powers of the transition matrix to see if a useful pattern like this can be exploited. I have occasionally found this to give simpler solutions than having to invert a matrix or perform an eigendecomposition by hand - admittedly something that is only really relevant in an exam or interview situation.
|
Random walk on the edges of a cube
|
Parity considerations give a very clean solution, using surprisingly simple machinery: no Markov chains, no iterated expectations, and only high school level summations. The basic idea is that if the
|
Random walk on the edges of a cube
Parity considerations give a very clean solution, using surprisingly simple machinery: no Markov chains, no iterated expectations, and only high school level summations. The basic idea is that if the spider has moved an even number of times in the $x$ direction, it has returned to its original $x$ coordinate so can't be at the ant's position. If it has moved an odd number of times in the $x$ direction, then its $x$ coordinate matches the ant's. Only if it has moved an odd number of times in all three directions will it match the $x$, $y$ and $z$ coordinates of the ant.
Initially the spider has made zero moves in any of the three directions, so the parity for each direction is even. All three parities need to be flipped to reach the ant.
After the spider's first move (let's label that direction $x$), exactly one direction has odd parity and the other two ($y$ and $z$) are even. To catch the ant, only those two parities need to be reversed. Since that can't be achieved in an odd number of subsequent moves, from now on we consider pairs of moves. There are nine possible combinations for the first paired move:
$$(x,x), \,(x,y), \,(x,z), \,(y,x), \,(y,y), \,(y,z), \,(z,x), \,(z,y), \text{or} \,(z,z)$$
We need to move in the $y$ and $z$ directions to reach the ant after one paired move, and two out of nine combinations will achieve this: $(y,z)$ and $(z,y)$ would ensure all three parities are odd.
The other seven combinations leave one odd and two even parities. The three repeated moves, $(x,x)$, $(y,y)$ or $(z,z)$, leave all parities unchanged so we still require one $y$ and one $z$ movement to reach the ant. The other pairs contain two distinct moves, including one in the $x$ direction. This switches the parity of $x$ and one of the other parities (either $y$ or $z$) so we are still left with one odd and two even parities. For instance the pair $(x,z)$ leaves us needing one more $x$ and one more $y$ to reach the ant: an equivalent situation (after relabelling of axes) to where we were before. We can then analyse the next paired move in the same way.
In general paired moves start with one odd and two even parities, and will either end with three odd parities (with probability $\frac{2}{9}$) and the immediate capture of the ant, or with one odd and two even parities (with probability $\frac{7}{9}$) which returns us to the same situation.
Let $M$ be the number of paired moves required to reach the ant. Clearly $M$ follows the geometric distribution on the support $\{1, 2, 3, \dots\}$ with probability of success $p = \frac{2}{9}$ so has mean $\mathbb{E}(M) = p^{-1} = \frac{9}{2} = 4.5$. Let $N$ be the total number of moves required, including the initial move and the $M$ subsequent paired moves. Then $N = 2M + 1$ so, applying linearity of expectations, $\mathbb{E}(N) = 2\mathbb{E}(M) + 1 = 2 \times 4.5 + 1 = 10$.
Alternatively you might note $P(M \geq m) = (\frac{7}{9})^{m-1}$ and apply the well-known formula for the mean of a discrete distribution taking only non-negative integer values, $\mathbb{E}(M)=\sum_{m=1}^\infty P(M\geq m)$. This gives $\mathbb{E}(M)=\sum_{m=1}^\infty (\frac{7}{9})^{m-1}$ which is a geometric series with first term $a=1$ and common ratio $r=\frac{7}{9}$ so has sum $\frac{a}{1-r} = \frac{1}{1-7/9}=\frac{1}{2/9}=\frac{9}{2}$. We can then take $\mathbb{E}(N)$ as before.
Comparison to Markov chain solutions
How might I have spotted this from the Markov chain transition matrix? Using @DLDahly's notation, the states in the transition matrix correspond to my description of the number of the number of directions with odd parity.
The one-step transition matrix is
\begin{equation}
\mathbf{P} = \left[\begin{array}{cccc}
P_{S \to S} & P_{S \to A}& P_{S \to B} & P_{S \to E} \\
P_{A \to S} & P_{A \to A}& P_{A \to B} & P_{A \to E} \\
P_{B \to S} & P_{B \to A}& P_{B \to B} & P_{B \to E} \\
P_{E \to S} & P_{E \to A} & P_{E \to B}& P_{E \to E} \\
\end{array}\right] = \left[\begin{array}{cccc}
0 & 1 & 0 & 0 \\
1/3 & 0 & 2/3 & 0 \\
0 & 2/3 & 0 & 1/3 \\
0 & 0 & 0 & 1 \\
\end{array}\right]
\end{equation}
The first row show us that after one movement, the spider is guaranteed to be in state A (one odd and two even parities). The two-step transition matrix is:
\begin{equation}
\mathbf{P}^{(2)} = \mathbf{P}^{2} = \left[\begin{array}{cccc}
1/3 & 0 & 2/3 & 0 \\
0 & 7/9 & 0 & 2/9 \\
2/9 & 0 & 4/9 & 1/3 \\
0 & 0 & 0 & 1 \\
\end{array}\right]
\end{equation}
The second row shows us that once the spider has entered state A, in two moves time it has either returned to state A with probability $7/9$ or has reached state E (all odd parities) and captured the ant, with probabilty $2/9$. So having reached state A, we see from the two-step transition matrix that the number of two-step moves required can be analysed using the geometric distribution as above. This isn't how I found my solution, but it is sometimes worth calculating the first few powers of the transition matrix to see if a useful pattern like this can be exploited. I have occasionally found this to give simpler solutions than having to invert a matrix or perform an eigendecomposition by hand - admittedly something that is only really relevant in an exam or interview situation.
|
Random walk on the edges of a cube
Parity considerations give a very clean solution, using surprisingly simple machinery: no Markov chains, no iterated expectations, and only high school level summations. The basic idea is that if the
|
6,505
|
Random walk on the edges of a cube
|
I have written a short Java program to answer your question numerically. The traversing of the spider is truly random, meaning that it can also traverse in cycles before getting to the ant.
However, you did not defined the term "opposite corner", so I have two different scenarios. Opposite as in across the same plane or as across the cube. In the first scenario, the shortest path is 2 steps, and 3 steps in the second scenario.
I hava used 100 million repeats and the results are the following:
-- First scenario --
Steps sum: 900019866
Repeats: 100000000
Avg. step count: 9.00019866
-- Second scenario --
Steps sum: 1000000836
Repeats: 100000000
Avg. step count: 10.00000836
Source code:
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class ProbabilityQuizSpider {
// Edges of the cube
private static final int[][] EDGES = new int[][] {
{1, 3, 7}, // corner 0
{0, 2, 4}, // corner 1
{1, 3, 5}, // corner 2
{0, 2, 6}, // corner 3
{1, 5, 7}, // corner 4
{2, 4, 6}, // corner 5
{3, 5, 7}, // corner 6
{0, 4, 6} // corner 7
};
private static final int START = 0; // Spider
private static final int FINISH = 5; // Ant
private static final int REPEATS = (int) Math.pow(10, 8);
public static void main(String[] args) {
final Random r = new Random();
final AtomicLong stepsSum = new AtomicLong();
IntStream.range(0, REPEATS).parallel().forEach(i -> {
int currentPoint = START;
int steps = 0;
do {
// Randomly traverse to next point
currentPoint = EDGES[currentPoint][r.nextInt(3)];
// Increase number of steps
steps++;
} while(currentPoint != FINISH);
stepsSum.addAndGet(steps);
});
// Results
System.out.println("Steps sum: " + stepsSum.get());
System.out.println("Repeats: " + REPEATS);
System.out.println("Avg. step count: " + (((double) stepsSum.get()) / ((double) REPEATS)));
}
}
EDIT: fixed a typo in the script (and also updated the results)
|
Random walk on the edges of a cube
|
I have written a short Java program to answer your question numerically. The traversing of the spider is truly random, meaning that it can also traverse in cycles before getting to the ant.
However, y
|
Random walk on the edges of a cube
I have written a short Java program to answer your question numerically. The traversing of the spider is truly random, meaning that it can also traverse in cycles before getting to the ant.
However, you did not defined the term "opposite corner", so I have two different scenarios. Opposite as in across the same plane or as across the cube. In the first scenario, the shortest path is 2 steps, and 3 steps in the second scenario.
I hava used 100 million repeats and the results are the following:
-- First scenario --
Steps sum: 900019866
Repeats: 100000000
Avg. step count: 9.00019866
-- Second scenario --
Steps sum: 1000000836
Repeats: 100000000
Avg. step count: 10.00000836
Source code:
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;
public class ProbabilityQuizSpider {
// Edges of the cube
private static final int[][] EDGES = new int[][] {
{1, 3, 7}, // corner 0
{0, 2, 4}, // corner 1
{1, 3, 5}, // corner 2
{0, 2, 6}, // corner 3
{1, 5, 7}, // corner 4
{2, 4, 6}, // corner 5
{3, 5, 7}, // corner 6
{0, 4, 6} // corner 7
};
private static final int START = 0; // Spider
private static final int FINISH = 5; // Ant
private static final int REPEATS = (int) Math.pow(10, 8);
public static void main(String[] args) {
final Random r = new Random();
final AtomicLong stepsSum = new AtomicLong();
IntStream.range(0, REPEATS).parallel().forEach(i -> {
int currentPoint = START;
int steps = 0;
do {
// Randomly traverse to next point
currentPoint = EDGES[currentPoint][r.nextInt(3)];
// Increase number of steps
steps++;
} while(currentPoint != FINISH);
stepsSum.addAndGet(steps);
});
// Results
System.out.println("Steps sum: " + stepsSum.get());
System.out.println("Repeats: " + REPEATS);
System.out.println("Avg. step count: " + (((double) stepsSum.get()) / ((double) REPEATS)));
}
}
EDIT: fixed a typo in the script (and also updated the results)
|
Random walk on the edges of a cube
I have written a short Java program to answer your question numerically. The traversing of the spider is truly random, meaning that it can also traverse in cycles before getting to the ant.
However, y
|
6,506
|
Random walk on the edges of a cube
|
I solved your conundrum via Monte Carlo simulations ($n = 10^4$) and obtained $\mathtt{mean(steps)} \approx 10$.
Here is the R code I used:
ant = c(0,0,0) # ant's coordinates
sim = 1e4 # number of MC simulations
steps = numeric() # initialize array of steps
for (i in 1:sim)
{
spider = c(1,1,1) # spider's coordinates
count = 0 # initialize step counter
# while ant's coordinates == spider's coordinates
while (!isTRUE(all.equal(ant, spider)))
{
# random walk in one of three dimensions
xyz = trunc(runif(1,1,4))
# let the spider move
if (spider[xyz] == 1)
{
spider[xyz] = 0
} else if (spider[xyz] == 0)
{
spider[xyz] = 1
}
# add one step
count = count + 1
}
# add the number of step occurred in the ith iteration
steps = c(steps, count)
# print i and number of steps occurred
cat("\n", i, " ::: ", count)
}
# print the mean of steps
(mean(steps))
|
Random walk on the edges of a cube
|
I solved your conundrum via Monte Carlo simulations ($n = 10^4$) and obtained $\mathtt{mean(steps)} \approx 10$.
Here is the R code I used:
ant = c(0,0,0) # ant's coordinates
sim = 1e4 # number of
|
Random walk on the edges of a cube
I solved your conundrum via Monte Carlo simulations ($n = 10^4$) and obtained $\mathtt{mean(steps)} \approx 10$.
Here is the R code I used:
ant = c(0,0,0) # ant's coordinates
sim = 1e4 # number of MC simulations
steps = numeric() # initialize array of steps
for (i in 1:sim)
{
spider = c(1,1,1) # spider's coordinates
count = 0 # initialize step counter
# while ant's coordinates == spider's coordinates
while (!isTRUE(all.equal(ant, spider)))
{
# random walk in one of three dimensions
xyz = trunc(runif(1,1,4))
# let the spider move
if (spider[xyz] == 1)
{
spider[xyz] = 0
} else if (spider[xyz] == 0)
{
spider[xyz] = 1
}
# add one step
count = count + 1
}
# add the number of step occurred in the ith iteration
steps = c(steps, count)
# print i and number of steps occurred
cat("\n", i, " ::: ", count)
}
# print the mean of steps
(mean(steps))
|
Random walk on the edges of a cube
I solved your conundrum via Monte Carlo simulations ($n = 10^4$) and obtained $\mathtt{mean(steps)} \approx 10$.
Here is the R code I used:
ant = c(0,0,0) # ant's coordinates
sim = 1e4 # number of
|
6,507
|
Random walk on the edges of a cube
|
I believe alesc is on the right track when mentioning "However, you did not defined the term "opposite corner"
Unless I am missing something in the question, there is no correct answer, just answers based on assumptions.
The cube size is not defined I.E. 10 cubic ft, 1000 cubic ft etc.
Ant size is not defined I.E. small garden, carpenter, giant red etc,
Spider type is not defined (to determine step size) I.E small garden, Tarantula etc.
IF you combine all "not defined" variables. the answer could be 0 steps or an undetermined/infinite number of steps.
|
Random walk on the edges of a cube
|
I believe alesc is on the right track when mentioning "However, you did not defined the term "opposite corner"
Unless I am missing something in the question, there is no correct answer, just answers b
|
Random walk on the edges of a cube
I believe alesc is on the right track when mentioning "However, you did not defined the term "opposite corner"
Unless I am missing something in the question, there is no correct answer, just answers based on assumptions.
The cube size is not defined I.E. 10 cubic ft, 1000 cubic ft etc.
Ant size is not defined I.E. small garden, carpenter, giant red etc,
Spider type is not defined (to determine step size) I.E small garden, Tarantula etc.
IF you combine all "not defined" variables. the answer could be 0 steps or an undetermined/infinite number of steps.
|
Random walk on the edges of a cube
I believe alesc is on the right track when mentioning "However, you did not defined the term "opposite corner"
Unless I am missing something in the question, there is no correct answer, just answers b
|
6,508
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
|
It is very unfortunate that McNemar's test is so difficult for people to understand. I even notice that at the top of its Wikipedia page it states that the explanation on the page is difficult for people to understand. The typical short explanation for McNemar's test is either that it is: 'a within-subjects chi-squared test', or that it is 'a test of the marginal homogeneity of a contingency table'. I find neither of these to be very helpful. First, it is not clear what is meant by 'within-subjects chi-squared', because you are always measuring your subjects twice (once on each variable) and trying to determine the relationship between those variables. In addition, 'marginal homogeneity' is barely intelligible (I know what this means and I have a hard time moving from the words to the meaning). (Tragically, even this answer may be confusing. If it is, it may help to read my second attempt below.)
Let's see if we can work through a process of reasoning about your top example to see if we can understand whether (and if so, why) McNemar's test is appropriate. You have put:
This is a contingency table, so it connotes a chi-squared analysis. Moreover, you want to understand the relationship between ${\rm Before}$ and ${\rm After}$, and the chi-squared test checks for a relationship between the variables, so at first glance it seems like the chi-squared test must be the analysis that answers your question.
However, it is worth pointing out that we can also present these data like so:
When you look at the data this way, you might think you could do a regular old $t$-test. But a $t$-test isn't quite right. There are two issues: First, because each row lists data measured from the same subject, we wouldn't want to do a between-subjects $t$-test, we would want to do a within-subjects $t$-test. Second, since these data are distributed as a binomial, the variance is a function of the mean. This means that there is no additional uncertainty to worry about once the sample mean has been estimated (i.e., you don't have to subsequently estimate the variance), so you don't have to refer to the $t$ distribution, you can use the $z$ distribution. (For more on this, it may help to read my answer here: The $z$-test vs. the $\chi^2$ test.) Thus, we would need a within-subjects $z$-test. That is, we need a within-subjects test of equality of proportions.
We have seen that there are two different ways of thinking about and analyzing these data (prompted by two different ways of looking at the data). So we need to decide which way we should use. The chi-squared test assesses whether ${\rm Before}$ and ${\rm After}$ are independent. That is, are people who were sick beforehand more likely to be sick afterwards than people who have never been sick. It is extremely difficult to see how that wouldn't be the case given that these measurements are assessed on the same subjects. If you did get a non-significant result (as you almost do) that would simply be a type II error. Instead of whether ${\rm Before}$ and ${\rm After}$ are independent, you almost certainly want to know if the treatment works (a question chi-squared does not answer). This is very similar to any number of treatment vs. control studies where you want to see if the means are equal, except that in this case your measurements are yes/no and they are within-subjects. Consider a more typical $t$-test situation with blood pressure measured before and after some treatment. Those whose bp was above your sample average beforehand will almost certainly tend to be among the higher bps afterwards, but you don't want to know about the consistency of the rankings, you want to know if the treatment led to a change in mean bp. Your situation here is directly analogous. Specifically, you want to run a within-subjects $z$-test of equality of proportions. That is what McNemar's test is.
So, having realized that we want to conduct McNemar's test, how does it work? Running a between-subjects $z$-test is easy, but how do we run a within-subjects version? The key to understanding how to do a within-subjects test of proportions is to examine the contingency table, which decomposes the proportions:
\begin{array}{rrrrrr}
& &{\rm After} & & & \\
& &{\rm No} &{\rm Yes} & &{\rm total} \\
{\rm Before}&{\rm No} &1157 &35 & &1192 \\
&{\rm Yes} &220 &13 & &233 \\
& & & & & \\
&{\rm total} &1377 &48 & &1425 \\
\end{array}
Obviously the ${\rm Before}$ proportions are the row totals divided by the overall total, and the ${\rm After}$ proportions are the column totals divided by overall total. When we look at the contingency table we can see that those are, for example:
$$
\text{Before proportion yes} = \frac{220 + 13}{1425},\quad\quad
\text{After proportion yes} = \frac{35 + 13}{1425}
$$
What is interesting to note here is that $13$ observations were yes both before and after. They end up as part of both proportions, but as a result of being in both calculations they add no distinct information about the change in the proportion of yeses. Moreover they are counted twice, which is invalid. Likewise, the overall total ends up in both calculations and adds no distinct information. By decomposing the proportions we are able to recognize that the only distinct information about the before and after proportions of yeses exists in the $220$ and $35$, so those are the numbers we need to analyze. This was McNemar's insight. In addition, he realized that under the null, this is a binomial test of $220/(220 + 35)$ against a null proportion of $.5$. (There is an equivalent formulation that is distributed as a chi-squared, which is what R outputs.)
There is another discussion of McNemar's test, with extensions to contingency tables larger than 2x2, here.
Here is an R demo with your data:
mat = as.table(rbind(c(1157, 35),
c( 220, 13) ))
colnames(mat) <- rownames(mat) <- c("No", "Yes")
names(dimnames(mat)) = c("Before", "After")
mat
margin.table(mat, 1)
margin.table(mat, 2)
sum(mat)
mcnemar.test(mat, correct=FALSE)
# McNemar's Chi-squared test
#
# data: mat
# McNemar's chi-squared = 134.2157, df = 1, p-value < 2.2e-16
binom.test(c(220, 35), p=0.5)
# Exact binomial test
#
# data: c(220, 35)
# number of successes = 220, number of trials = 255, p-value < 2.2e-16
# alternative hypothesis: true probability of success is not equal to 0.5
# 95 percent confidence interval:
# 0.8143138 0.9024996
# sample estimates:
# probability of success
# 0.8627451
If we didn't take the within-subjects nature of your data into account, we would have a slightly less powerful test of the equality of proportions:
prop.test(rbind(margin.table(mat, 1), margin.table(mat, 2)), correct=FALSE)
# 2-sample test for equality of proportions without continuity
# correction
#
# data: rbind(margin.table(mat, 1), margin.table(mat, 2))
# X-squared = 135.1195, df = 1, p-value < 2.2e-16
# alternative hypothesis: two.sided
# 95 percent confidence interval:
# 0.1084598 0.1511894
# sample estimates:
# prop 1 prop 2
# 0.9663158 0.8364912
That is, X-squared = 133.6627 instead of chi-squared = 134.2157. In this case, these differ very little, because you have a lot of data and only $13$ cases are overlapping as discussed above. (Another, and more important, problem here is that this counts your data twice, i.e., $N = 2850$, instead of $N = 1425$.)
Here are the answers to your concrete questions:
The correct analysis is McNemar's test (as discussed extensively above).
This version is trickier, and the phrasing "does higher proportions of one infections relate to higher proportions of Y" is ambiguous. There are two possible questions:
It is perfectly reasonable to want to know if the patients who get one of the infections tend to get the other, in which case you would use the chi-squared test of independence. This question is asking whether susceptibility to the two different infections is independent (perhaps because they are contracted via different physiological pathways) or not (perhaps they are contracted due to a generally weakened immune system).
It is also perfectly reasonable to what to know if the same proportion of patients tend to get both infections, in which case you would use McNemar's test. The question here is about whether the infections are equally virulent.
Since this is once again the same infection, of course they will be related. I gather that this version is not before and after a treatment, but just at some later point in time. Thus, you are asking if the background infection rates are changing organically, which is again a perfectly reasonable question. At any rate, the correct analysis is McNemar's test.
Edit: It would seem I misinterpreted your third question, perhaps due to a typo. I now interpret it as two different infections at two separate timepoints. Under this interpretation, the chi-squared test would be appropriate.
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
|
It is very unfortunate that McNemar's test is so difficult for people to understand. I even notice that at the top of its Wikipedia page it states that the explanation on the page is difficult for pe
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
It is very unfortunate that McNemar's test is so difficult for people to understand. I even notice that at the top of its Wikipedia page it states that the explanation on the page is difficult for people to understand. The typical short explanation for McNemar's test is either that it is: 'a within-subjects chi-squared test', or that it is 'a test of the marginal homogeneity of a contingency table'. I find neither of these to be very helpful. First, it is not clear what is meant by 'within-subjects chi-squared', because you are always measuring your subjects twice (once on each variable) and trying to determine the relationship between those variables. In addition, 'marginal homogeneity' is barely intelligible (I know what this means and I have a hard time moving from the words to the meaning). (Tragically, even this answer may be confusing. If it is, it may help to read my second attempt below.)
Let's see if we can work through a process of reasoning about your top example to see if we can understand whether (and if so, why) McNemar's test is appropriate. You have put:
This is a contingency table, so it connotes a chi-squared analysis. Moreover, you want to understand the relationship between ${\rm Before}$ and ${\rm After}$, and the chi-squared test checks for a relationship between the variables, so at first glance it seems like the chi-squared test must be the analysis that answers your question.
However, it is worth pointing out that we can also present these data like so:
When you look at the data this way, you might think you could do a regular old $t$-test. But a $t$-test isn't quite right. There are two issues: First, because each row lists data measured from the same subject, we wouldn't want to do a between-subjects $t$-test, we would want to do a within-subjects $t$-test. Second, since these data are distributed as a binomial, the variance is a function of the mean. This means that there is no additional uncertainty to worry about once the sample mean has been estimated (i.e., you don't have to subsequently estimate the variance), so you don't have to refer to the $t$ distribution, you can use the $z$ distribution. (For more on this, it may help to read my answer here: The $z$-test vs. the $\chi^2$ test.) Thus, we would need a within-subjects $z$-test. That is, we need a within-subjects test of equality of proportions.
We have seen that there are two different ways of thinking about and analyzing these data (prompted by two different ways of looking at the data). So we need to decide which way we should use. The chi-squared test assesses whether ${\rm Before}$ and ${\rm After}$ are independent. That is, are people who were sick beforehand more likely to be sick afterwards than people who have never been sick. It is extremely difficult to see how that wouldn't be the case given that these measurements are assessed on the same subjects. If you did get a non-significant result (as you almost do) that would simply be a type II error. Instead of whether ${\rm Before}$ and ${\rm After}$ are independent, you almost certainly want to know if the treatment works (a question chi-squared does not answer). This is very similar to any number of treatment vs. control studies where you want to see if the means are equal, except that in this case your measurements are yes/no and they are within-subjects. Consider a more typical $t$-test situation with blood pressure measured before and after some treatment. Those whose bp was above your sample average beforehand will almost certainly tend to be among the higher bps afterwards, but you don't want to know about the consistency of the rankings, you want to know if the treatment led to a change in mean bp. Your situation here is directly analogous. Specifically, you want to run a within-subjects $z$-test of equality of proportions. That is what McNemar's test is.
So, having realized that we want to conduct McNemar's test, how does it work? Running a between-subjects $z$-test is easy, but how do we run a within-subjects version? The key to understanding how to do a within-subjects test of proportions is to examine the contingency table, which decomposes the proportions:
\begin{array}{rrrrrr}
& &{\rm After} & & & \\
& &{\rm No} &{\rm Yes} & &{\rm total} \\
{\rm Before}&{\rm No} &1157 &35 & &1192 \\
&{\rm Yes} &220 &13 & &233 \\
& & & & & \\
&{\rm total} &1377 &48 & &1425 \\
\end{array}
Obviously the ${\rm Before}$ proportions are the row totals divided by the overall total, and the ${\rm After}$ proportions are the column totals divided by overall total. When we look at the contingency table we can see that those are, for example:
$$
\text{Before proportion yes} = \frac{220 + 13}{1425},\quad\quad
\text{After proportion yes} = \frac{35 + 13}{1425}
$$
What is interesting to note here is that $13$ observations were yes both before and after. They end up as part of both proportions, but as a result of being in both calculations they add no distinct information about the change in the proportion of yeses. Moreover they are counted twice, which is invalid. Likewise, the overall total ends up in both calculations and adds no distinct information. By decomposing the proportions we are able to recognize that the only distinct information about the before and after proportions of yeses exists in the $220$ and $35$, so those are the numbers we need to analyze. This was McNemar's insight. In addition, he realized that under the null, this is a binomial test of $220/(220 + 35)$ against a null proportion of $.5$. (There is an equivalent formulation that is distributed as a chi-squared, which is what R outputs.)
There is another discussion of McNemar's test, with extensions to contingency tables larger than 2x2, here.
Here is an R demo with your data:
mat = as.table(rbind(c(1157, 35),
c( 220, 13) ))
colnames(mat) <- rownames(mat) <- c("No", "Yes")
names(dimnames(mat)) = c("Before", "After")
mat
margin.table(mat, 1)
margin.table(mat, 2)
sum(mat)
mcnemar.test(mat, correct=FALSE)
# McNemar's Chi-squared test
#
# data: mat
# McNemar's chi-squared = 134.2157, df = 1, p-value < 2.2e-16
binom.test(c(220, 35), p=0.5)
# Exact binomial test
#
# data: c(220, 35)
# number of successes = 220, number of trials = 255, p-value < 2.2e-16
# alternative hypothesis: true probability of success is not equal to 0.5
# 95 percent confidence interval:
# 0.8143138 0.9024996
# sample estimates:
# probability of success
# 0.8627451
If we didn't take the within-subjects nature of your data into account, we would have a slightly less powerful test of the equality of proportions:
prop.test(rbind(margin.table(mat, 1), margin.table(mat, 2)), correct=FALSE)
# 2-sample test for equality of proportions without continuity
# correction
#
# data: rbind(margin.table(mat, 1), margin.table(mat, 2))
# X-squared = 135.1195, df = 1, p-value < 2.2e-16
# alternative hypothesis: two.sided
# 95 percent confidence interval:
# 0.1084598 0.1511894
# sample estimates:
# prop 1 prop 2
# 0.9663158 0.8364912
That is, X-squared = 133.6627 instead of chi-squared = 134.2157. In this case, these differ very little, because you have a lot of data and only $13$ cases are overlapping as discussed above. (Another, and more important, problem here is that this counts your data twice, i.e., $N = 2850$, instead of $N = 1425$.)
Here are the answers to your concrete questions:
The correct analysis is McNemar's test (as discussed extensively above).
This version is trickier, and the phrasing "does higher proportions of one infections relate to higher proportions of Y" is ambiguous. There are two possible questions:
It is perfectly reasonable to want to know if the patients who get one of the infections tend to get the other, in which case you would use the chi-squared test of independence. This question is asking whether susceptibility to the two different infections is independent (perhaps because they are contracted via different physiological pathways) or not (perhaps they are contracted due to a generally weakened immune system).
It is also perfectly reasonable to what to know if the same proportion of patients tend to get both infections, in which case you would use McNemar's test. The question here is about whether the infections are equally virulent.
Since this is once again the same infection, of course they will be related. I gather that this version is not before and after a treatment, but just at some later point in time. Thus, you are asking if the background infection rates are changing organically, which is again a perfectly reasonable question. At any rate, the correct analysis is McNemar's test.
Edit: It would seem I misinterpreted your third question, perhaps due to a typo. I now interpret it as two different infections at two separate timepoints. Under this interpretation, the chi-squared test would be appropriate.
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
It is very unfortunate that McNemar's test is so difficult for people to understand. I even notice that at the top of its Wikipedia page it states that the explanation on the page is difficult for pe
|
6,509
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
|
Well, it seems I've made a hash of this. Let me try to explain this again, in a different way and we'll see if it might help clear things up.
The traditional way to explain McNemar's test vs. the chi-squared test is to ask if the data are "paired" and to recommend McNemar's test if the data are paired and the chi-squared test if the data are "unpaired". I have found that this leads to a lot of confusion (this thread being an example!). In place of this, I have found that it is most helpful to focus on the question you are trying to ask, and to use the test that matches your question. To make this more concrete, let's look at a made-up scenario:
You walk around a statistics conference and for each statistician you meet, you record whether they are from the US or the UK. You also record whether they have high blood pressure or normal blood pressure.
Here are the data:
mat = as.table(rbind(c(195, 5),
c( 5, 195) ))
colnames(mat) = c("US", "UK")
rownames(mat) = c("Hi", "Normal")
names(dimnames(mat)) = c("BP", "Nationality")
mat
# Nationality
# BP US UK
# Hi 195 5
# Normal 5 195
At this point, it is important to figure out what question we want to ask of our data. There are three different questions we could ask here:
We might want to know if the categorical variables BP and Nationality are associated or independent;
We might wonder if high blood pressure is more common amongst US statisticians than it is amongst UK statisticians;
Finally, we might wonder if the proportion of statisticians with high blood pressure is equal to the proportion of US statisticians that we talked to. This refers to the marginal proportions of the table. These are not printed by default in R, but we can get them thusly (notice that, in this case, they are exactly the same):
margin.table(mat, 1)/sum(mat)
# BP
# Hi Normal
# 0.5 0.5
margin.table(mat, 2)/sum(mat)
# Nationality
# US UK
# 0.5 0.5
As I said, the traditional approach, discussed in many textbooks, is to determine which test to use based on whether the data are "paired" or not. But this is very confusing, is this contingency table "paired"? If we compare the proportion with high blood pressure between US and UK statisticians, you are comparing two proportions (albeit of the same variable) measured on different sets of people. On the other hand, if you want to compare the proportion with high blood pressure to the proportion US, you are comparing two proportions (albeit of different variables) measured on the same set of people. These data are both "paired" and "unpaired" at the same time (albeit with respect to different aspects of the data). This leads to confusion. To try to avoid this confusion, I argue that you should think in terms of which question you are asking. Specifically, if you want to know:
If the variables are independent: use the chi-squared test.
If the proportion with high blood pressure differs by nationality: use the z-test for difference of proportions.
If the marginal proportions are the same: use McNemar's test.
Someone might disagree with me here, arguing that because the contingency table is not "paired", McNemar's test cannot be used to test the equality of the marginal proportions and that the chi-squared test should be used instead. Since this is the point of contention, let's try both to see if the results make sense:
chisq.test(mat)
# Pearson's Chi-squared test with Yates' continuity correction
#
# data: mat
# X-squared = 357.21, df = 1, p-value < 2.2e-16
mcnemar.test(mat)
# McNemar's Chi-squared test
#
# data: mat
# McNemar's chi-squared = 0, df = 1, p-value = 1
The chi-squared test yields a p-value of approximately 0. That is, it says that the probability of getting data as far or further from equal marginal proportions, if the marginal proportions actually were equal is essentially 0. But the marginal proportions are exactly the same, $50\%=50\%$, as we saw above! The results of the chi-squared test just don't make any sense in light of the data. On the other hand, McNemar's test yields a p-value of 1. That is, it says that you will have a 100% chance of finding marginal proportions this close to equality or further from equality, if the true marginal proportions are equal. Since the observed marginal proportions cannot be closer to equal than they are, this result makes sense.
Let's try another example:
mat2 = as.table(rbind(c(195, 195),
c( 5, 5) ))
colnames(mat2) = c("US", "UK")
rownames(mat2) = c("Hi", "Normal")
names(dimnames(mat2)) = c("BP", "Nationality")
mat2
# Nationality
# BP US UK
# Hi 195 195
# Normal 5 5
margin.table(mat2, 1)/sum(mat2)
# BP
# Hi Normal
# 0.975 0.025
margin.table(mat2, 2)/sum(mat2)
# Nationality
# US UK
# 0.5 0.5
In this case, the marginal proportions are very different, $97.5\%\gg 50\%$. Let's try the two tests again to see how their results compare to the observed large difference in marginal proportions:
chisq.test(mat2)
# Pearson's Chi-squared test
#
# data: mat2
# X-squared = 0, df = 1, p-value = 1
mcnemar.test(mat2)
# McNemar's Chi-squared test with continuity correction
#
# data: mat2
# McNemar's chi-squared = 178.605, df = 1, p-value < 2.2e-16
This time, the chi-squared test gives a p-value of 1, meaning that the marginal proportions are as equal as they can be. But we saw that the marginal proportions are very obviously not equal, so this result doesn't make any sense in light of our data. On the other hand, McNemar's test yields a p-value of approximately 0. In other words, it is extremely unlikely to get data with marginal proportions as far from equality as these, if they truly are equal in the population. Since our observed marginal proportions are far from equal, this result makes sense.
The fact that the chi-squared test yields results that make no sense given our data suggests there is something wrong with using the chi-squared test here. Of course, the fact that McNemar's test provided sensible results doesn't prove that it is valid, it may just have been a coincidence, but the chi-squared test is clearly wrong.
Let's see if we can work through the argument for why McNemar's test might be the right one. I will use a third dataset:
mat3 = as.table(rbind(c(190, 15),
c( 60, 135) ))
colnames(mat3) = c("US", "UK")
rownames(mat3) = c("Hi", "Normal")
names(dimnames(mat3)) = c("BP", "Nationality")
mat3
# Nationality
# BP US UK
# Hi 190 15
# Normal 60 135
margin.table(mat3, 1)/sum(mat3)
# BP
# Hi Normal
# 0.5125 0.4875
margin.table(mat3, 2)/sum(mat3)
# Nationality
# US UK
# 0.625 0.375
This time we want to compare $51.25\%$ to $62.5\%$ and wonder if in the population the true marginal proportions might have been the same. Because we are comparing two proportions, the most intuitive option would be to use a z-test for the equality of two proportions. We can try that here:
prop.test(x=c(205, 250), n=c(400, 400))
# 2-sample test for equality of proportions with continuity correction
#
# data: c(205, 250) out of c(400, 400)
# X-squared = 9.8665, df = 1, p-value = 0.001683
# alternative hypothesis: two.sided
# 95 percent confidence interval:
# -0.18319286 -0.04180714
# sample estimates:
# prop 1 prop 2
# 0.5125 0.6250
(To use prop.test() to test the marginal proportions, I had to enter the numbers of 'successes' and the total number of 'trials' manually, but you can see from the last line of the output that the proportions are correct.) This suggests that it is unlikely to get marginal proportions this far from equality if they were actually equal, given the amount of data we have.
Is this test valid? There are two problems here: The test believes we have 800 data, when we actually have only 400. This test also does not take into account that these two proportions are not independent, in the sense that they were measured on the same people.
Let's see if we can take this apart and find another way. From the contingency table, we can see that the marginal proportions are:
$$
\text{% high BP: }\frac{190 + 15}{400} \qquad\qquad\qquad \text{% US: }\frac{190 + 60}{400}
$$
What we see here is that the $190$ US statisticians with high blood pressure show up in both marginal proportions. They are both being counted twice and contributing no information about the differences in the marginal proportions. Moreover, the $400$ total shows up in both denominators as well. All of the unique and distinctive information is in the two off-diagonal cell counts ($15$ and $60$). Whether the marginal proportions are the same or different is due only to them. Whether an observation is equally likely to fall into either of those two cells is distributed as a binomial with probability $\pi = .5$ under the null. That was McNemar's insight. In fact, McNemar's test is essentially just a binomial test of whether observations are equally likely to fall into those two cells:
binom.test(x=15, n=(15+60))
# Exact binomial test
#
# data: 15 and (15 + 60)
# number of successes = 15, number of trials = 75, p-value = 1.588e-07
# alternative hypothesis: true probability of success is not equal to 0.5
# 95 percent confidence interval:
# 0.1164821 0.3083261
# sample estimates:
# probability of success
# 0.2
In this version, only the informative observations are used and they are not counted twice. The p-value here is much smaller, 0.0000001588, which is often the case when the dependency in the data is taken into account. That is, this test is more powerful than the z-test of difference of proportions. We can further see that the above version is essentially the same as McNemar's test:
mcnemar.test(mat3, correct=FALSE)
# McNemar's Chi-squared test
#
# data: mat3
# McNemar's chi-squared = 27, df = 1, p-value = 2.035e-07
If the non-identicallity is confusing, McNemar's test typically, and in R, squares the result and compares it to the chi-squared distribution, which is not an exact test like the binomial above:
(15-60)^2/(15+60)
# [1] 27
1-pchisq(27, df=1)
# [1] 2.034555e-07
Thus, when you want to check the marginal proportions of a contingency table are equal, McNemar's test (or the exact binomial test computed manually) is correct. It uses only the relevant information without illegally using any data twice. It does not just 'happen' to yield results that make sense of the data.
I continue to believe that trying to figure out whether a contingency table is "paired" is unhelpful. I suggest using the test that matches the question you are asking of the data.
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
|
Well, it seems I've made a hash of this. Let me try to explain this again, in a different way and we'll see if it might help clear things up.
The traditional way to explain McNemar's test vs. the c
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
Well, it seems I've made a hash of this. Let me try to explain this again, in a different way and we'll see if it might help clear things up.
The traditional way to explain McNemar's test vs. the chi-squared test is to ask if the data are "paired" and to recommend McNemar's test if the data are paired and the chi-squared test if the data are "unpaired". I have found that this leads to a lot of confusion (this thread being an example!). In place of this, I have found that it is most helpful to focus on the question you are trying to ask, and to use the test that matches your question. To make this more concrete, let's look at a made-up scenario:
You walk around a statistics conference and for each statistician you meet, you record whether they are from the US or the UK. You also record whether they have high blood pressure or normal blood pressure.
Here are the data:
mat = as.table(rbind(c(195, 5),
c( 5, 195) ))
colnames(mat) = c("US", "UK")
rownames(mat) = c("Hi", "Normal")
names(dimnames(mat)) = c("BP", "Nationality")
mat
# Nationality
# BP US UK
# Hi 195 5
# Normal 5 195
At this point, it is important to figure out what question we want to ask of our data. There are three different questions we could ask here:
We might want to know if the categorical variables BP and Nationality are associated or independent;
We might wonder if high blood pressure is more common amongst US statisticians than it is amongst UK statisticians;
Finally, we might wonder if the proportion of statisticians with high blood pressure is equal to the proportion of US statisticians that we talked to. This refers to the marginal proportions of the table. These are not printed by default in R, but we can get them thusly (notice that, in this case, they are exactly the same):
margin.table(mat, 1)/sum(mat)
# BP
# Hi Normal
# 0.5 0.5
margin.table(mat, 2)/sum(mat)
# Nationality
# US UK
# 0.5 0.5
As I said, the traditional approach, discussed in many textbooks, is to determine which test to use based on whether the data are "paired" or not. But this is very confusing, is this contingency table "paired"? If we compare the proportion with high blood pressure between US and UK statisticians, you are comparing two proportions (albeit of the same variable) measured on different sets of people. On the other hand, if you want to compare the proportion with high blood pressure to the proportion US, you are comparing two proportions (albeit of different variables) measured on the same set of people. These data are both "paired" and "unpaired" at the same time (albeit with respect to different aspects of the data). This leads to confusion. To try to avoid this confusion, I argue that you should think in terms of which question you are asking. Specifically, if you want to know:
If the variables are independent: use the chi-squared test.
If the proportion with high blood pressure differs by nationality: use the z-test for difference of proportions.
If the marginal proportions are the same: use McNemar's test.
Someone might disagree with me here, arguing that because the contingency table is not "paired", McNemar's test cannot be used to test the equality of the marginal proportions and that the chi-squared test should be used instead. Since this is the point of contention, let's try both to see if the results make sense:
chisq.test(mat)
# Pearson's Chi-squared test with Yates' continuity correction
#
# data: mat
# X-squared = 357.21, df = 1, p-value < 2.2e-16
mcnemar.test(mat)
# McNemar's Chi-squared test
#
# data: mat
# McNemar's chi-squared = 0, df = 1, p-value = 1
The chi-squared test yields a p-value of approximately 0. That is, it says that the probability of getting data as far or further from equal marginal proportions, if the marginal proportions actually were equal is essentially 0. But the marginal proportions are exactly the same, $50\%=50\%$, as we saw above! The results of the chi-squared test just don't make any sense in light of the data. On the other hand, McNemar's test yields a p-value of 1. That is, it says that you will have a 100% chance of finding marginal proportions this close to equality or further from equality, if the true marginal proportions are equal. Since the observed marginal proportions cannot be closer to equal than they are, this result makes sense.
Let's try another example:
mat2 = as.table(rbind(c(195, 195),
c( 5, 5) ))
colnames(mat2) = c("US", "UK")
rownames(mat2) = c("Hi", "Normal")
names(dimnames(mat2)) = c("BP", "Nationality")
mat2
# Nationality
# BP US UK
# Hi 195 195
# Normal 5 5
margin.table(mat2, 1)/sum(mat2)
# BP
# Hi Normal
# 0.975 0.025
margin.table(mat2, 2)/sum(mat2)
# Nationality
# US UK
# 0.5 0.5
In this case, the marginal proportions are very different, $97.5\%\gg 50\%$. Let's try the two tests again to see how their results compare to the observed large difference in marginal proportions:
chisq.test(mat2)
# Pearson's Chi-squared test
#
# data: mat2
# X-squared = 0, df = 1, p-value = 1
mcnemar.test(mat2)
# McNemar's Chi-squared test with continuity correction
#
# data: mat2
# McNemar's chi-squared = 178.605, df = 1, p-value < 2.2e-16
This time, the chi-squared test gives a p-value of 1, meaning that the marginal proportions are as equal as they can be. But we saw that the marginal proportions are very obviously not equal, so this result doesn't make any sense in light of our data. On the other hand, McNemar's test yields a p-value of approximately 0. In other words, it is extremely unlikely to get data with marginal proportions as far from equality as these, if they truly are equal in the population. Since our observed marginal proportions are far from equal, this result makes sense.
The fact that the chi-squared test yields results that make no sense given our data suggests there is something wrong with using the chi-squared test here. Of course, the fact that McNemar's test provided sensible results doesn't prove that it is valid, it may just have been a coincidence, but the chi-squared test is clearly wrong.
Let's see if we can work through the argument for why McNemar's test might be the right one. I will use a third dataset:
mat3 = as.table(rbind(c(190, 15),
c( 60, 135) ))
colnames(mat3) = c("US", "UK")
rownames(mat3) = c("Hi", "Normal")
names(dimnames(mat3)) = c("BP", "Nationality")
mat3
# Nationality
# BP US UK
# Hi 190 15
# Normal 60 135
margin.table(mat3, 1)/sum(mat3)
# BP
# Hi Normal
# 0.5125 0.4875
margin.table(mat3, 2)/sum(mat3)
# Nationality
# US UK
# 0.625 0.375
This time we want to compare $51.25\%$ to $62.5\%$ and wonder if in the population the true marginal proportions might have been the same. Because we are comparing two proportions, the most intuitive option would be to use a z-test for the equality of two proportions. We can try that here:
prop.test(x=c(205, 250), n=c(400, 400))
# 2-sample test for equality of proportions with continuity correction
#
# data: c(205, 250) out of c(400, 400)
# X-squared = 9.8665, df = 1, p-value = 0.001683
# alternative hypothesis: two.sided
# 95 percent confidence interval:
# -0.18319286 -0.04180714
# sample estimates:
# prop 1 prop 2
# 0.5125 0.6250
(To use prop.test() to test the marginal proportions, I had to enter the numbers of 'successes' and the total number of 'trials' manually, but you can see from the last line of the output that the proportions are correct.) This suggests that it is unlikely to get marginal proportions this far from equality if they were actually equal, given the amount of data we have.
Is this test valid? There are two problems here: The test believes we have 800 data, when we actually have only 400. This test also does not take into account that these two proportions are not independent, in the sense that they were measured on the same people.
Let's see if we can take this apart and find another way. From the contingency table, we can see that the marginal proportions are:
$$
\text{% high BP: }\frac{190 + 15}{400} \qquad\qquad\qquad \text{% US: }\frac{190 + 60}{400}
$$
What we see here is that the $190$ US statisticians with high blood pressure show up in both marginal proportions. They are both being counted twice and contributing no information about the differences in the marginal proportions. Moreover, the $400$ total shows up in both denominators as well. All of the unique and distinctive information is in the two off-diagonal cell counts ($15$ and $60$). Whether the marginal proportions are the same or different is due only to them. Whether an observation is equally likely to fall into either of those two cells is distributed as a binomial with probability $\pi = .5$ under the null. That was McNemar's insight. In fact, McNemar's test is essentially just a binomial test of whether observations are equally likely to fall into those two cells:
binom.test(x=15, n=(15+60))
# Exact binomial test
#
# data: 15 and (15 + 60)
# number of successes = 15, number of trials = 75, p-value = 1.588e-07
# alternative hypothesis: true probability of success is not equal to 0.5
# 95 percent confidence interval:
# 0.1164821 0.3083261
# sample estimates:
# probability of success
# 0.2
In this version, only the informative observations are used and they are not counted twice. The p-value here is much smaller, 0.0000001588, which is often the case when the dependency in the data is taken into account. That is, this test is more powerful than the z-test of difference of proportions. We can further see that the above version is essentially the same as McNemar's test:
mcnemar.test(mat3, correct=FALSE)
# McNemar's Chi-squared test
#
# data: mat3
# McNemar's chi-squared = 27, df = 1, p-value = 2.035e-07
If the non-identicallity is confusing, McNemar's test typically, and in R, squares the result and compares it to the chi-squared distribution, which is not an exact test like the binomial above:
(15-60)^2/(15+60)
# [1] 27
1-pchisq(27, df=1)
# [1] 2.034555e-07
Thus, when you want to check the marginal proportions of a contingency table are equal, McNemar's test (or the exact binomial test computed manually) is correct. It uses only the relevant information without illegally using any data twice. It does not just 'happen' to yield results that make sense of the data.
I continue to believe that trying to figure out whether a contingency table is "paired" is unhelpful. I suggest using the test that matches the question you are asking of the data.
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
Well, it seems I've made a hash of this. Let me try to explain this again, in a different way and we'll see if it might help clear things up.
The traditional way to explain McNemar's test vs. the c
|
6,510
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
|
The question of which test to use, contingency table $\chi^{2}$ versus McNemar's $\chi^{2}$ of a null hypothesis of no association between two binary variables is simply a question of whether your data are paired/dependent, or unpaired/independent:
Binary Data in Two Independent Samples
In this case, you would use a contingency table $\chi^{2}$ test.
For example, you might have a sample of 20 statisticians from the USA, and a separate independent sample of 37 statisticians from the UK, and have a measure of whether these statisticians are hypertensive or normotensive. Your null hypothesis is that both UK and US statisticians have the same underlying probability of being hypertensive (i.e. that knowing whether one is from the USA or from the UK tells one nothing about the probability of hypertension). Of course it is possible that you could have the same sample size in each group, but that does not change the fact of the samples being independent (i.e. unpaired).
Binary Data in Paired Samples
In this case you would use McNemar's $\chi^{2}$ test.
For example, you might have individually-matched case-control study data sampled from an international statistician conference, where 30 statisticians with hypertension (cases) and 30 statisticians without hypertension (controls; who are individually matched by age, sex, BMI & smoking status to particular cases), are retrospectively assessed for professional residency in the UK versus residency elsewhere. The null is that the probability of residing in the UK among cases is the same as the probability of residing in the UK as controls (i.e. that knowing about one's hypertensive status tells one nothing about one's UK residence history).
In fact, McNemar's test analyzes pairs of data. Specifically, it analyzes discordant pairs. So the $r$ and $s$ from $\chi^{2}=\frac{[(r−s)−1]^{2}}{(r+s)}$ are counts of discordant pairs.
Anto, in your example, your data are paired (same variable measured twice in same subject) and therefore McNemar's test is the appropriate choice of test for association.
[gung and I disagreed for a time about an earlier answer.]
Quoted References
"Assuming that we are still interested in comparing proportions, what can we do if our data are paired, rather than independent?... In this situation, we use McNemar's test."–Pagano and Gauvreau, Principles of Biostatistics, 2nd edition, page 349. [Emphasis added]
"The expression is better known as the McNemar matched-pair test statistic (McNemar, 1949), and has been a mainstay of matched-pair analysis."—Rothman, Greenland, & Lash. Modern Epidemiology, page 286. [Emphasis added]
"The paired t test and repeated measures of analysis of variance can be used to analyze experiments in which the variable being studied can be measured on an interval scale (and satisfies other assumptions required of parametric methods). What about experiments, analogous to the ones in Chapter 5, where the outcome is measured on a nominal scale? This problem often arises when asking whether or not a an individual responded to a treatment or when comparing the results of two different diagnostic tests that are classified positive or negative in the same individuals. We will develop a procedure to analyze such experiments, Mcnemar's test for changes, in the context of one such study."—Glanz, Primer of Biostatistics, 7th edition, page 200. [Emphasis added. Glanz works through an example of a misapplication the contingency table $\chi^{2}$ test to paired data on page 201.]
"For matched case-control data with one control per case, the resultant analysis is simple, and the appropriate statistical test is McNemar's chi-squared test... note that for the calculation of both the odds ratio and the statistic, the only contributors are the pairs which are disparate in exposure, that is the pairs where the case was exposed but the control was not, and those where the control was exposed but the case was not."—Elwood. Critical Appraisal of Epidemiological Studies and Clinical Trials, 1st edition, pages 189–190. [Emphasis added]
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
|
The question of which test to use, contingency table $\chi^{2}$ versus McNemar's $\chi^{2}$ of a null hypothesis of no association between two binary variables is simply a question of whether your dat
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
The question of which test to use, contingency table $\chi^{2}$ versus McNemar's $\chi^{2}$ of a null hypothesis of no association between two binary variables is simply a question of whether your data are paired/dependent, or unpaired/independent:
Binary Data in Two Independent Samples
In this case, you would use a contingency table $\chi^{2}$ test.
For example, you might have a sample of 20 statisticians from the USA, and a separate independent sample of 37 statisticians from the UK, and have a measure of whether these statisticians are hypertensive or normotensive. Your null hypothesis is that both UK and US statisticians have the same underlying probability of being hypertensive (i.e. that knowing whether one is from the USA or from the UK tells one nothing about the probability of hypertension). Of course it is possible that you could have the same sample size in each group, but that does not change the fact of the samples being independent (i.e. unpaired).
Binary Data in Paired Samples
In this case you would use McNemar's $\chi^{2}$ test.
For example, you might have individually-matched case-control study data sampled from an international statistician conference, where 30 statisticians with hypertension (cases) and 30 statisticians without hypertension (controls; who are individually matched by age, sex, BMI & smoking status to particular cases), are retrospectively assessed for professional residency in the UK versus residency elsewhere. The null is that the probability of residing in the UK among cases is the same as the probability of residing in the UK as controls (i.e. that knowing about one's hypertensive status tells one nothing about one's UK residence history).
In fact, McNemar's test analyzes pairs of data. Specifically, it analyzes discordant pairs. So the $r$ and $s$ from $\chi^{2}=\frac{[(r−s)−1]^{2}}{(r+s)}$ are counts of discordant pairs.
Anto, in your example, your data are paired (same variable measured twice in same subject) and therefore McNemar's test is the appropriate choice of test for association.
[gung and I disagreed for a time about an earlier answer.]
Quoted References
"Assuming that we are still interested in comparing proportions, what can we do if our data are paired, rather than independent?... In this situation, we use McNemar's test."–Pagano and Gauvreau, Principles of Biostatistics, 2nd edition, page 349. [Emphasis added]
"The expression is better known as the McNemar matched-pair test statistic (McNemar, 1949), and has been a mainstay of matched-pair analysis."—Rothman, Greenland, & Lash. Modern Epidemiology, page 286. [Emphasis added]
"The paired t test and repeated measures of analysis of variance can be used to analyze experiments in which the variable being studied can be measured on an interval scale (and satisfies other assumptions required of parametric methods). What about experiments, analogous to the ones in Chapter 5, where the outcome is measured on a nominal scale? This problem often arises when asking whether or not a an individual responded to a treatment or when comparing the results of two different diagnostic tests that are classified positive or negative in the same individuals. We will develop a procedure to analyze such experiments, Mcnemar's test for changes, in the context of one such study."—Glanz, Primer of Biostatistics, 7th edition, page 200. [Emphasis added. Glanz works through an example of a misapplication the contingency table $\chi^{2}$ test to paired data on page 201.]
"For matched case-control data with one control per case, the resultant analysis is simple, and the appropriate statistical test is McNemar's chi-squared test... note that for the calculation of both the odds ratio and the statistic, the only contributors are the pairs which are disparate in exposure, that is the pairs where the case was exposed but the control was not, and those where the control was exposed but the case was not."—Elwood. Critical Appraisal of Epidemiological Studies and Clinical Trials, 1st edition, pages 189–190. [Emphasis added]
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
The question of which test to use, contingency table $\chi^{2}$ versus McNemar's $\chi^{2}$ of a null hypothesis of no association between two binary variables is simply a question of whether your dat
|
6,511
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
|
My understanding of McNemar's test is as follows: It is used to see whether an intervention has made a significant difference to a binary outcome. In your example, a group of subjects are checked for infection and the response is recorded as yes or no. All subjects are then given some intervention, say an antibiotic drug. They are then checked again for infection and response is recorded as yes/no again. The (pairs of) responses can be put in the contigency table:
After
|no |yes|
Before|No |1157|35 |
|Yes |220 |13 |
And McNemar's test would be appropriate for this.
It is clear from the table that many more have converted from 'yes' to 'no' (220/(220+13) or 94.4%) than from 'no' to 'yes' (35/(1157+35) or 2.9%). Considering these proportions, McNemar's P value (4.901e-31) appears more correct than chi-square P value (0.04082 ).
If contigency table represents 2 different infections (question 2), then Chi-square would be more appropriate.
Your 3rd question is ambiguous: you first state relating Y at t2 with Y at t1 but in the table you write 'X' at t1 vs Y at t2. Y at t2 vs Y at t1 is same as your first question and hence McNemar's test is needed, while X at t1 and Y at t2 indicates different events are being compared and hence Chi-square will be more appropriate.
Edit:
As mentioned by Alexis in the comment, matched case-control data are also analyzed by McNemar's test. For example, 1425 cancer patients are recruited for a study and for each patient a matched control is also recruited. All these (1425*2) are checked for infection. The results of each pair can be shown by similar table:
Normal
|no |yes|
Cancer|No |1157|35 |
|Yes |220 |13 |
More clearly:
Normal:
No infection Infection
Cancer patient: No infection 1157 35
Infection 220 13
It shows that it is much more often that cancer patient had infection and control did not, rather than the reverse. Its significance can be tested by McNemar's test.
If these patients and controls were not matched and independent, one can only make following table and do a chisquare test:
Infection
No Yes
Cancer No 1377 48
Yes 1192 233
More clearly:
No infection Infection
No cancer 1377 48
Cancer 1192 233
Note that these numbers are same as margins of the first table:
> addmargins(mat)
After
Before No Yes Sum
No 1157 35 1192
Yes 220 13 233
Sum 1377 48 1425
That must be the reason for use of terms like 'marginal frequencies' and 'marginal homogeneity' in McNemar's test.
Interestingly, the addmargins function can also help decide which test to use. If the grand-total is half the number of subjects observed (indicating pairing has been done), then McNemar's test is applicable, else chisquare test is appropriate:
> addmargins(mat)
Normal
Cancer No Yes Sum
No 1157 35 1192
Yes 220 13 233
Sum 1377 48 1425
>
> addmargins(mat3)
Infection
Cancer No Yes Sum
No 1377 48 1425
Yes 1192 233 1425
Sum 2569 281 2850
The R codes for above tables are as from answers above:
mat = as.table(rbind(c(1157, 35),
c( 220, 13) ))
colnames(mat) <- rownames(mat) <- c("No", "Yes")
names(dimnames(mat)) = c("Cancer", "Normal")
mat3 = as.table(rbind(c(1377, 48),
c(1192, 233) ))
colnames(mat3) <- rownames(mat3) <- c("No", "Yes")
names(dimnames(mat3)) = c("Cancer", "Infection")
Following pseudocode may also help knowing the difference:
subject_id result_first_observation result_second_observation
1 no yes
2 yes no
...
mcnemar.test(table(result_first_observation, result_second_observation))
pair_id result_case_subject result_control_subject
1 no yes
2 yes no
...
mcnemar.test(table(result_case_subject, result_control_subject))
subject_id result_first_test result_second_test
1 yes no
2 no yes
..
chisq.test(table(result_first_test, result_second_test))
Edit:
mid-p variation of peforming McNemar test ( https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3716987/ ) is interesting. It compares b and c of contingency table, i.e. number who changed from yes to no versus number who changed from no to yes (ignoring number of those who remained yes or no through the study). It can be performed using binomial test in python, as shown at https://gist.github.com/kylebgorman/c8b3fb31c1552ecbaafb
It could be equivalent to binom.test(b, b+c, 0.5) since in a random change, one would expect b to be equal to c.
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
|
My understanding of McNemar's test is as follows: It is used to see whether an intervention has made a significant difference to a binary outcome. In your example, a group of subjects are checked for
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to use each?
My understanding of McNemar's test is as follows: It is used to see whether an intervention has made a significant difference to a binary outcome. In your example, a group of subjects are checked for infection and the response is recorded as yes or no. All subjects are then given some intervention, say an antibiotic drug. They are then checked again for infection and response is recorded as yes/no again. The (pairs of) responses can be put in the contigency table:
After
|no |yes|
Before|No |1157|35 |
|Yes |220 |13 |
And McNemar's test would be appropriate for this.
It is clear from the table that many more have converted from 'yes' to 'no' (220/(220+13) or 94.4%) than from 'no' to 'yes' (35/(1157+35) or 2.9%). Considering these proportions, McNemar's P value (4.901e-31) appears more correct than chi-square P value (0.04082 ).
If contigency table represents 2 different infections (question 2), then Chi-square would be more appropriate.
Your 3rd question is ambiguous: you first state relating Y at t2 with Y at t1 but in the table you write 'X' at t1 vs Y at t2. Y at t2 vs Y at t1 is same as your first question and hence McNemar's test is needed, while X at t1 and Y at t2 indicates different events are being compared and hence Chi-square will be more appropriate.
Edit:
As mentioned by Alexis in the comment, matched case-control data are also analyzed by McNemar's test. For example, 1425 cancer patients are recruited for a study and for each patient a matched control is also recruited. All these (1425*2) are checked for infection. The results of each pair can be shown by similar table:
Normal
|no |yes|
Cancer|No |1157|35 |
|Yes |220 |13 |
More clearly:
Normal:
No infection Infection
Cancer patient: No infection 1157 35
Infection 220 13
It shows that it is much more often that cancer patient had infection and control did not, rather than the reverse. Its significance can be tested by McNemar's test.
If these patients and controls were not matched and independent, one can only make following table and do a chisquare test:
Infection
No Yes
Cancer No 1377 48
Yes 1192 233
More clearly:
No infection Infection
No cancer 1377 48
Cancer 1192 233
Note that these numbers are same as margins of the first table:
> addmargins(mat)
After
Before No Yes Sum
No 1157 35 1192
Yes 220 13 233
Sum 1377 48 1425
That must be the reason for use of terms like 'marginal frequencies' and 'marginal homogeneity' in McNemar's test.
Interestingly, the addmargins function can also help decide which test to use. If the grand-total is half the number of subjects observed (indicating pairing has been done), then McNemar's test is applicable, else chisquare test is appropriate:
> addmargins(mat)
Normal
Cancer No Yes Sum
No 1157 35 1192
Yes 220 13 233
Sum 1377 48 1425
>
> addmargins(mat3)
Infection
Cancer No Yes Sum
No 1377 48 1425
Yes 1192 233 1425
Sum 2569 281 2850
The R codes for above tables are as from answers above:
mat = as.table(rbind(c(1157, 35),
c( 220, 13) ))
colnames(mat) <- rownames(mat) <- c("No", "Yes")
names(dimnames(mat)) = c("Cancer", "Normal")
mat3 = as.table(rbind(c(1377, 48),
c(1192, 233) ))
colnames(mat3) <- rownames(mat3) <- c("No", "Yes")
names(dimnames(mat3)) = c("Cancer", "Infection")
Following pseudocode may also help knowing the difference:
subject_id result_first_observation result_second_observation
1 no yes
2 yes no
...
mcnemar.test(table(result_first_observation, result_second_observation))
pair_id result_case_subject result_control_subject
1 no yes
2 yes no
...
mcnemar.test(table(result_case_subject, result_control_subject))
subject_id result_first_test result_second_test
1 yes no
2 no yes
..
chisq.test(table(result_first_test, result_second_test))
Edit:
mid-p variation of peforming McNemar test ( https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3716987/ ) is interesting. It compares b and c of contingency table, i.e. number who changed from yes to no versus number who changed from no to yes (ignoring number of those who remained yes or no through the study). It can be performed using binomial test in python, as shown at https://gist.github.com/kylebgorman/c8b3fb31c1552ecbaafb
It could be equivalent to binom.test(b, b+c, 0.5) since in a random change, one would expect b to be equal to c.
|
What is the difference between McNemar's test and the chi-squared test, and how do you know when to
My understanding of McNemar's test is as follows: It is used to see whether an intervention has made a significant difference to a binary outcome. In your example, a group of subjects are checked for
|
6,512
|
How to create an arbitrary covariance matrix
|
Create an $n\times n$ matrix $A$ with arbitrary values
and then use $\Sigma = A^T A$ as your covariance matrix.
For example
n <- 4
A <- matrix(runif(n^2)*2-1, ncol=n)
Sigma <- t(A) %*% A
|
How to create an arbitrary covariance matrix
|
Create an $n\times n$ matrix $A$ with arbitrary values
and then use $\Sigma = A^T A$ as your covariance matrix.
For example
n <- 4
A <- matrix(runif(n^2)*2-1, ncol=n)
Sigma <- t(A) %*% A
|
How to create an arbitrary covariance matrix
Create an $n\times n$ matrix $A$ with arbitrary values
and then use $\Sigma = A^T A$ as your covariance matrix.
For example
n <- 4
A <- matrix(runif(n^2)*2-1, ncol=n)
Sigma <- t(A) %*% A
|
How to create an arbitrary covariance matrix
Create an $n\times n$ matrix $A$ with arbitrary values
and then use $\Sigma = A^T A$ as your covariance matrix.
For example
n <- 4
A <- matrix(runif(n^2)*2-1, ncol=n)
Sigma <- t(A) %*% A
|
6,513
|
How to create an arbitrary covariance matrix
|
I like to have control over the objects I create, even when they might be arbitrary.
Consider, then, that all possible $n\times n$ covariance matrices $\Sigma$ can be expressed in the form
$$\Sigma= P^\prime\ \text{Diagonal}(\sigma_1,\sigma_2,\ldots, \sigma_n)\ P$$
where $P$ is an orthogonal matrix and $\sigma_1 \ge \sigma_2 \ge \cdots \ge \sigma_n \ge 0$.
Geometrically this describes a covariance structure with a range of principal components of sizes $\sigma_i$. These components point in the directions of the rows of $P$. See the figures at Making sense of principal component analysis, eigenvectors & eigenvalues for examples with $n=3$. Setting the $\sigma_i$ will set the magnitudes of the covariances and their relative sizes, thereby determining any desired ellipsoidal shape. The rows of $P$ orient the axes of the shape as you prefer.
One algebraic and computing benefit of this approach is that when $\sigma_n \gt 0$, $\Sigma$ is readily inverted (which is a common operation on covariance matrices):
$$\Sigma^{-1} = P^\prime\ \text{Diagonal}(1/\sigma_1, 1/\sigma_2, \ldots, 1/\sigma_n)\ P.$$
Don't care about the directions, but only about the ranges of sizes of the the $\sigma_i$? That's fine: you can easily generate a random orthogonal matrix. Just wrap $n^2$ iid standard Normal values into a square matrix and then orthogonalize it. It will almost surely work (provided $n$ isn't huge). The QR decomposition will do that, as in this code
n <- 5
p <- qr.Q(qr(matrix(rnorm(n^2), n)))
This works because the $n$-variate multinormal distribution so generated is "elliptical": it is invariant under all rotations and reflections (through the origin). Thus, all orthogonal matrices are generated uniformly, as argued at How to generate uniformly distributed points on the surface of the 3-d unit sphere?.
A quick way to obtain $\Sigma$ from $P$ and the $\sigma_i$, once you have specified or created them, uses crossprod and exploits R's re-use of arrays in arithmetic operations, as in this example with $\sigma=(\sigma_1, \ldots, \sigma_5) = (5,4,3,2,1)$:
Sigma <- crossprod(p, p*(5:1))
As a check, the Singular Value decomposition should return both $\sigma$ and $P^\prime$. You may inspect it with the command
svd(Sigma)
The inverse of Sigma of course is obtained merely by changing the multiplication by $\sigma$ into a division:
Tau <- crossprod(p, p/(5:1))
You may verify this by viewing zapsmall(Sigma %*% Tau), which should be the $n\times n$ identity matrix. A generalized inverse (essential for regression calculations) is obtained by replacing any $\sigma_i \ne 0$ by $1/\sigma_i$, exactly as above, but keeping any zeros among the $\sigma_i$ as they were.
|
How to create an arbitrary covariance matrix
|
I like to have control over the objects I create, even when they might be arbitrary.
Consider, then, that all possible $n\times n$ covariance matrices $\Sigma$ can be expressed in the form
$$\Sigma= P
|
How to create an arbitrary covariance matrix
I like to have control over the objects I create, even when they might be arbitrary.
Consider, then, that all possible $n\times n$ covariance matrices $\Sigma$ can be expressed in the form
$$\Sigma= P^\prime\ \text{Diagonal}(\sigma_1,\sigma_2,\ldots, \sigma_n)\ P$$
where $P$ is an orthogonal matrix and $\sigma_1 \ge \sigma_2 \ge \cdots \ge \sigma_n \ge 0$.
Geometrically this describes a covariance structure with a range of principal components of sizes $\sigma_i$. These components point in the directions of the rows of $P$. See the figures at Making sense of principal component analysis, eigenvectors & eigenvalues for examples with $n=3$. Setting the $\sigma_i$ will set the magnitudes of the covariances and their relative sizes, thereby determining any desired ellipsoidal shape. The rows of $P$ orient the axes of the shape as you prefer.
One algebraic and computing benefit of this approach is that when $\sigma_n \gt 0$, $\Sigma$ is readily inverted (which is a common operation on covariance matrices):
$$\Sigma^{-1} = P^\prime\ \text{Diagonal}(1/\sigma_1, 1/\sigma_2, \ldots, 1/\sigma_n)\ P.$$
Don't care about the directions, but only about the ranges of sizes of the the $\sigma_i$? That's fine: you can easily generate a random orthogonal matrix. Just wrap $n^2$ iid standard Normal values into a square matrix and then orthogonalize it. It will almost surely work (provided $n$ isn't huge). The QR decomposition will do that, as in this code
n <- 5
p <- qr.Q(qr(matrix(rnorm(n^2), n)))
This works because the $n$-variate multinormal distribution so generated is "elliptical": it is invariant under all rotations and reflections (through the origin). Thus, all orthogonal matrices are generated uniformly, as argued at How to generate uniformly distributed points on the surface of the 3-d unit sphere?.
A quick way to obtain $\Sigma$ from $P$ and the $\sigma_i$, once you have specified or created them, uses crossprod and exploits R's re-use of arrays in arithmetic operations, as in this example with $\sigma=(\sigma_1, \ldots, \sigma_5) = (5,4,3,2,1)$:
Sigma <- crossprod(p, p*(5:1))
As a check, the Singular Value decomposition should return both $\sigma$ and $P^\prime$. You may inspect it with the command
svd(Sigma)
The inverse of Sigma of course is obtained merely by changing the multiplication by $\sigma$ into a division:
Tau <- crossprod(p, p/(5:1))
You may verify this by viewing zapsmall(Sigma %*% Tau), which should be the $n\times n$ identity matrix. A generalized inverse (essential for regression calculations) is obtained by replacing any $\sigma_i \ne 0$ by $1/\sigma_i$, exactly as above, but keeping any zeros among the $\sigma_i$ as they were.
|
How to create an arbitrary covariance matrix
I like to have control over the objects I create, even when they might be arbitrary.
Consider, then, that all possible $n\times n$ covariance matrices $\Sigma$ can be expressed in the form
$$\Sigma= P
|
6,514
|
How to create an arbitrary covariance matrix
|
You can simulate random positive definite matrices from the Wishart distribution using the function "rWishart" from stats (included in base)
n <- 4
rWishart(1,n,diag(n))
From the documentation for rWishart:
Usage should be:
rWishart(n, df, Sigma)
where,
n: the number of samples.
df: the degrees of freedom, i.e. the number of dimensions of the matrix.
Sigma: a positive definite scaling matrix.
|
How to create an arbitrary covariance matrix
|
You can simulate random positive definite matrices from the Wishart distribution using the function "rWishart" from stats (included in base)
n <- 4
rWishart(1,n,diag(n))
From the documentation for rW
|
How to create an arbitrary covariance matrix
You can simulate random positive definite matrices from the Wishart distribution using the function "rWishart" from stats (included in base)
n <- 4
rWishart(1,n,diag(n))
From the documentation for rWishart:
Usage should be:
rWishart(n, df, Sigma)
where,
n: the number of samples.
df: the degrees of freedom, i.e. the number of dimensions of the matrix.
Sigma: a positive definite scaling matrix.
|
How to create an arbitrary covariance matrix
You can simulate random positive definite matrices from the Wishart distribution using the function "rWishart" from stats (included in base)
n <- 4
rWishart(1,n,diag(n))
From the documentation for rW
|
6,515
|
How to create an arbitrary covariance matrix
|
There is a package specifically for that, clusterGeneration (written among other by Harry Joe, a big name in that field).
There are two main functions:
genPositiveDefMat generate a covariance matrix, 4 different methods
rcorrmatrix : generate a correlation matrix
Quick example:
library(clusterGeneration)
#> Loading required package: MASS
genPositiveDefMat("unifcorrmat",dim=3)
#> $egvalues
#> [1] 15.408962 5.673916 1.228842
#>
#> $Sigma
#> [,1] [,2] [,3]
#> [1,] 6.714871 1.643449 6.530493
#> [2,] 1.643449 6.568033 2.312455
#> [3,] 6.530493 2.312455 9.028815
genPositiveDefMat("eigen",dim=3)
#> $egvalues
#> [1] 8.409136 4.076442 2.256715
#>
#> $Sigma
#> [,1] [,2] [,3]
#> [1,] 2.3217300 -0.1467812 0.5220522
#> [2,] -0.1467812 4.1126757 0.5049819
#> [3,] 0.5220522 0.5049819 8.3078880
Created on 2019-10-27 by the reprex package (v0.3.0)
Finally, note that an alternative approach is to do a first try from scratch, then use Matrix::nearPD() to make your matrix positive-definite.
|
How to create an arbitrary covariance matrix
|
There is a package specifically for that, clusterGeneration (written among other by Harry Joe, a big name in that field).
There are two main functions:
genPositiveDefMat generate a covariance matrix
|
How to create an arbitrary covariance matrix
There is a package specifically for that, clusterGeneration (written among other by Harry Joe, a big name in that field).
There are two main functions:
genPositiveDefMat generate a covariance matrix, 4 different methods
rcorrmatrix : generate a correlation matrix
Quick example:
library(clusterGeneration)
#> Loading required package: MASS
genPositiveDefMat("unifcorrmat",dim=3)
#> $egvalues
#> [1] 15.408962 5.673916 1.228842
#>
#> $Sigma
#> [,1] [,2] [,3]
#> [1,] 6.714871 1.643449 6.530493
#> [2,] 1.643449 6.568033 2.312455
#> [3,] 6.530493 2.312455 9.028815
genPositiveDefMat("eigen",dim=3)
#> $egvalues
#> [1] 8.409136 4.076442 2.256715
#>
#> $Sigma
#> [,1] [,2] [,3]
#> [1,] 2.3217300 -0.1467812 0.5220522
#> [2,] -0.1467812 4.1126757 0.5049819
#> [3,] 0.5220522 0.5049819 8.3078880
Created on 2019-10-27 by the reprex package (v0.3.0)
Finally, note that an alternative approach is to do a first try from scratch, then use Matrix::nearPD() to make your matrix positive-definite.
|
How to create an arbitrary covariance matrix
There is a package specifically for that, clusterGeneration (written among other by Harry Joe, a big name in that field).
There are two main functions:
genPositiveDefMat generate a covariance matrix
|
6,516
|
How to create an arbitrary covariance matrix
|
In my case I still want the eigenvalues to be randomly drawn so, to control the condition number of the covariance matrix does not exceed, say, $\kappa > 1$, one can generate $\sigma_k = 1 + (\kappa - 1) \cdot \mathcal{U}_k$ where $\mathcal{U}_k$ is uniformly sampled in $[0,1]$ for all $k=1,\dots,n$.
Following @whuber (very comprehensive) algorithm, here is a code snippet in Python with all kinds of assertions and data reshaping.
import numpy as np
d = 5
sigmas = np.arange(1, 6).reshape(-1, 1) # [1, 2, 3, 4, 5]
# or sigmas = (1 + (kappa - 1) * np.random.uniform(size = d)).reshape(-1, 1)
Q, R = np.linalg.qr(np.random.normal(size = d**2).reshape(d, d))
S = Q.T @ (sigmas * Q)
# Check that S is psd
assert np.all(np.linalg.eigvals(S) > 0)
# Check that S is symmetric
assert np.allclose(S.T, S)
S
_, sigmas_, Q_ = np.linalg.svd(S)
# Check SVD retrieves original parameters
assert np.allclose(np.abs(Q), np.abs(Q_[::-1])) # up to sign
assert np.allclose(sigmas.reshape(-1), sigmas_[::-1])
|
How to create an arbitrary covariance matrix
|
In my case I still want the eigenvalues to be randomly drawn so, to control the condition number of the covariance matrix does not exceed, say, $\kappa > 1$, one can generate $\sigma_k = 1 + (\kappa -
|
How to create an arbitrary covariance matrix
In my case I still want the eigenvalues to be randomly drawn so, to control the condition number of the covariance matrix does not exceed, say, $\kappa > 1$, one can generate $\sigma_k = 1 + (\kappa - 1) \cdot \mathcal{U}_k$ where $\mathcal{U}_k$ is uniformly sampled in $[0,1]$ for all $k=1,\dots,n$.
Following @whuber (very comprehensive) algorithm, here is a code snippet in Python with all kinds of assertions and data reshaping.
import numpy as np
d = 5
sigmas = np.arange(1, 6).reshape(-1, 1) # [1, 2, 3, 4, 5]
# or sigmas = (1 + (kappa - 1) * np.random.uniform(size = d)).reshape(-1, 1)
Q, R = np.linalg.qr(np.random.normal(size = d**2).reshape(d, d))
S = Q.T @ (sigmas * Q)
# Check that S is psd
assert np.all(np.linalg.eigvals(S) > 0)
# Check that S is symmetric
assert np.allclose(S.T, S)
S
_, sigmas_, Q_ = np.linalg.svd(S)
# Check SVD retrieves original parameters
assert np.allclose(np.abs(Q), np.abs(Q_[::-1])) # up to sign
assert np.allclose(sigmas.reshape(-1), sigmas_[::-1])
|
How to create an arbitrary covariance matrix
In my case I still want the eigenvalues to be randomly drawn so, to control the condition number of the covariance matrix does not exceed, say, $\kappa > 1$, one can generate $\sigma_k = 1 + (\kappa -
|
6,517
|
How to prove that the radial basis function is a kernel?
|
Zen used method 1. Here is method 2: Map $x$ to a spherically symmetric Gaussian distribution centered at $x$ in the Hilbert space $L^2$. The standard deviation and a constant factor have to be tweaked for this to work exactly. For example, in one dimension,
$$ \int_{-\infty}^\infty \frac{\exp[-(x-z)^2/(2\sigma^2)]}{\sqrt{2 \pi} \sigma} \frac{\exp[-(y-z)^2/(2 \sigma^2)}{\sqrt{2 \pi} \sigma} dz = \frac{\exp [-(x-y)^2/(4 \sigma^2)]}{2 \sqrt \pi \sigma}. $$
So, use a standard deviation of $\sigma/\sqrt 2$ and scale the Gaussian distribution to get $k(x,y) = \langle \Phi(x), \Phi(y)\rangle$. This last rescaling occurs because the $L^2$ norm of a normal distribution is not $1$ in general.
|
How to prove that the radial basis function is a kernel?
|
Zen used method 1. Here is method 2: Map $x$ to a spherically symmetric Gaussian distribution centered at $x$ in the Hilbert space $L^2$. The standard deviation and a constant factor have to be tweake
|
How to prove that the radial basis function is a kernel?
Zen used method 1. Here is method 2: Map $x$ to a spherically symmetric Gaussian distribution centered at $x$ in the Hilbert space $L^2$. The standard deviation and a constant factor have to be tweaked for this to work exactly. For example, in one dimension,
$$ \int_{-\infty}^\infty \frac{\exp[-(x-z)^2/(2\sigma^2)]}{\sqrt{2 \pi} \sigma} \frac{\exp[-(y-z)^2/(2 \sigma^2)}{\sqrt{2 \pi} \sigma} dz = \frac{\exp [-(x-y)^2/(4 \sigma^2)]}{2 \sqrt \pi \sigma}. $$
So, use a standard deviation of $\sigma/\sqrt 2$ and scale the Gaussian distribution to get $k(x,y) = \langle \Phi(x), \Phi(y)\rangle$. This last rescaling occurs because the $L^2$ norm of a normal distribution is not $1$ in general.
|
How to prove that the radial basis function is a kernel?
Zen used method 1. Here is method 2: Map $x$ to a spherically symmetric Gaussian distribution centered at $x$ in the Hilbert space $L^2$. The standard deviation and a constant factor have to be tweake
|
6,518
|
How to prove that the radial basis function is a kernel?
|
I'll add a third method, just for variety: building up the kernel from a sequence of general steps known to create pd kernels. Let $\mathcal X$ denote the domain of the kernels below and $\varphi$ the feature maps.
Scalings:
If $\kappa$ is a pd kernel, so is $\gamma \kappa$ for any constant $\gamma > 0$.
Proof: if $\varphi$ is the feature map for $\kappa$, $\sqrt\gamma \varphi$ is a valid feature map for $\gamma \kappa$.
Sums:
If $\kappa_1$ and $\kappa_2$ are pd kernels, so is $\kappa_1 + \kappa_2$.
Proof: Concatenate the feature maps $\varphi_1$ and $\varphi_2$, to get $x \mapsto \begin{bmatrix}\varphi_1(x) \\ \varphi_2(x)\end{bmatrix}$.
Limits:
If $\kappa_1, \kappa_2, \dots$ are pd kernels, and $\kappa(x, y) := \lim_{n \to \infty} \kappa_n(x, y)$ exists for all $x, y$, then $\kappa$ is pd.
Proof: For each $m, n \ge 1$ and every $\{ (x_i, c_i) \}_{i=1}^m \subseteq \mathcal{X} \times \mathbb R$ we have that $\sum_{i=1}^m c_i \kappa_n(x_i, x_j) c_j \ge 0$. Taking the limit as $n \to \infty$ gives the same property for $\kappa$.
Products:
If $\kappa_1$ and $\kappa_2$ are pd kernels, so is $g(x, y) = \kappa_1(x, y) \, \kappa_2(x, y)$.
Proof: It follows immediately from the Schur product theorem, but Schölkopf and Smola (2002) give the following nice, elementary proof.
Let
$$
(V_1, \dots, V_m) \sim \mathcal{N}\left( 0, \left[ \kappa_1(x_i, x_j) \right]_{ij} \right)
\\
(W_1, \dots, W_m) \sim \mathcal{N}\left( 0, \left[ \kappa_2(x_i, x_j) \right]_{ij} \right)
$$
be independent.
Thus
$$\mathrm{Cov}(V_i W_i, V_j W_j) = \mathrm{Cov}(V_i, V_j) \,\mathrm{Cov}(W_i, W_j) = \kappa_1(x_i, x_j) \kappa_2(x_i, x_j).$$
Covariance matrices must be psd,
so considering the covariance matrix of $(V_1 W_1, \dots, V_n W_n)$ proves it.
Powers:
If $\kappa$ is a pd kernel, so is $\kappa^n(x, y) := \kappa(x, y)^n$ for any positive integer $n$.
Proof: immediate from the "products" property.
Exponents:
If $\kappa$ is a pd kernel, so is $e^\kappa(x, y) := \exp(\kappa(x, y))$.
Proof: We have
$e^\kappa(x, y) = \lim_{N \to \infty} \sum_{n=0}^N \frac{1}{n!} \kappa(x, y)^n$; use the "powers", "scalings", "sums", and "limits" properties.
Functions:
If $\kappa$ is a pd kernel and $f : \mathcal X \to \mathbb R$, $g(x, y) := f(x) \kappa(x, y) f(y)$ is as well.
Proof: Use the feature map $x \mapsto f(x) \varphi(x)$.
Now, note that
\begin{align*}
k(x, y)
&= \exp\left( - \tfrac{1}{2 \sigma^2} \lVert x - y \rVert^2 \right)
\\&= \exp\left( - \tfrac{1}{2 \sigma^2} \lVert x \rVert^2 \right)
\exp\left( \tfrac{1}{\sigma^2} x^T y \right)
\exp\left( - \tfrac{1}{2 \sigma^2} \lVert y \rVert^2 \right)
.\end{align*}
Start with the linear kernel $\kappa(x, y) = x^T y$,
apply "scalings" with $\frac{1}{\sigma^2}$,
apply "exponents",
and apply "functions" with $x \mapsto \exp\left( - \tfrac{1}{2 \sigma^2} \lVert x \rVert^2 \right)$.
|
How to prove that the radial basis function is a kernel?
|
I'll add a third method, just for variety: building up the kernel from a sequence of general steps known to create pd kernels. Let $\mathcal X$ denote the domain of the kernels below and $\varphi$ the
|
How to prove that the radial basis function is a kernel?
I'll add a third method, just for variety: building up the kernel from a sequence of general steps known to create pd kernels. Let $\mathcal X$ denote the domain of the kernels below and $\varphi$ the feature maps.
Scalings:
If $\kappa$ is a pd kernel, so is $\gamma \kappa$ for any constant $\gamma > 0$.
Proof: if $\varphi$ is the feature map for $\kappa$, $\sqrt\gamma \varphi$ is a valid feature map for $\gamma \kappa$.
Sums:
If $\kappa_1$ and $\kappa_2$ are pd kernels, so is $\kappa_1 + \kappa_2$.
Proof: Concatenate the feature maps $\varphi_1$ and $\varphi_2$, to get $x \mapsto \begin{bmatrix}\varphi_1(x) \\ \varphi_2(x)\end{bmatrix}$.
Limits:
If $\kappa_1, \kappa_2, \dots$ are pd kernels, and $\kappa(x, y) := \lim_{n \to \infty} \kappa_n(x, y)$ exists for all $x, y$, then $\kappa$ is pd.
Proof: For each $m, n \ge 1$ and every $\{ (x_i, c_i) \}_{i=1}^m \subseteq \mathcal{X} \times \mathbb R$ we have that $\sum_{i=1}^m c_i \kappa_n(x_i, x_j) c_j \ge 0$. Taking the limit as $n \to \infty$ gives the same property for $\kappa$.
Products:
If $\kappa_1$ and $\kappa_2$ are pd kernels, so is $g(x, y) = \kappa_1(x, y) \, \kappa_2(x, y)$.
Proof: It follows immediately from the Schur product theorem, but Schölkopf and Smola (2002) give the following nice, elementary proof.
Let
$$
(V_1, \dots, V_m) \sim \mathcal{N}\left( 0, \left[ \kappa_1(x_i, x_j) \right]_{ij} \right)
\\
(W_1, \dots, W_m) \sim \mathcal{N}\left( 0, \left[ \kappa_2(x_i, x_j) \right]_{ij} \right)
$$
be independent.
Thus
$$\mathrm{Cov}(V_i W_i, V_j W_j) = \mathrm{Cov}(V_i, V_j) \,\mathrm{Cov}(W_i, W_j) = \kappa_1(x_i, x_j) \kappa_2(x_i, x_j).$$
Covariance matrices must be psd,
so considering the covariance matrix of $(V_1 W_1, \dots, V_n W_n)$ proves it.
Powers:
If $\kappa$ is a pd kernel, so is $\kappa^n(x, y) := \kappa(x, y)^n$ for any positive integer $n$.
Proof: immediate from the "products" property.
Exponents:
If $\kappa$ is a pd kernel, so is $e^\kappa(x, y) := \exp(\kappa(x, y))$.
Proof: We have
$e^\kappa(x, y) = \lim_{N \to \infty} \sum_{n=0}^N \frac{1}{n!} \kappa(x, y)^n$; use the "powers", "scalings", "sums", and "limits" properties.
Functions:
If $\kappa$ is a pd kernel and $f : \mathcal X \to \mathbb R$, $g(x, y) := f(x) \kappa(x, y) f(y)$ is as well.
Proof: Use the feature map $x \mapsto f(x) \varphi(x)$.
Now, note that
\begin{align*}
k(x, y)
&= \exp\left( - \tfrac{1}{2 \sigma^2} \lVert x - y \rVert^2 \right)
\\&= \exp\left( - \tfrac{1}{2 \sigma^2} \lVert x \rVert^2 \right)
\exp\left( \tfrac{1}{\sigma^2} x^T y \right)
\exp\left( - \tfrac{1}{2 \sigma^2} \lVert y \rVert^2 \right)
.\end{align*}
Start with the linear kernel $\kappa(x, y) = x^T y$,
apply "scalings" with $\frac{1}{\sigma^2}$,
apply "exponents",
and apply "functions" with $x \mapsto \exp\left( - \tfrac{1}{2 \sigma^2} \lVert x \rVert^2 \right)$.
|
How to prove that the radial basis function is a kernel?
I'll add a third method, just for variety: building up the kernel from a sequence of general steps known to create pd kernels. Let $\mathcal X$ denote the domain of the kernels below and $\varphi$ the
|
6,519
|
How to prove that the radial basis function is a kernel?
|
I will use method 1. Check Douglas Zare's answer for a proof using method 2.
I will prove the case when $x,y$ are real numbers, so $k(x,y)=\exp(-(x-y)^2/2\sigma^2)$. The general case follows mutatis mutandis from the same argument, and is worth doing.
Without loss of generality, suppose that $\sigma^2=1$.
Write $k(x,y)=h(x-y)$, where $$h(t)=\exp\left(-\frac{t^2}{2}\right)=\mathrm{E}\left[e^{itZ}\right] $$ is the characteristic function of a random variable $Z$ with $N(0,1)$ distribution.
For real numbers $x_1,\dots,x_n$ and $a_1,\dots,a_n$, we have
$$
\sum_{j,k=1}^n a_j\,a_k\,h(x_j-x_k) = \sum_{j,k=1}^n a_j\,a_k\,\mathrm{E} \left[ e^{i(x_j-x_k)Z}\right] = \mathrm{E} \left[ \sum_{j,k=1}^n a_j\,e^{i x_j Z}\,a_k\,e^{-i x_k Z}\right]
= \mathrm{E}\left[ \left| \sum_{j=1}^n a_j\,e^{i x_j Z}\right|^2\right] \geq 0 \, ,
$$
which entails that $k$ is a positive semidefinite function, aka a kernel.
To understand this result in greater generality, check out Bochner's Theorem: http://en.wikipedia.org/wiki/Positive-definite_function
|
How to prove that the radial basis function is a kernel?
|
I will use method 1. Check Douglas Zare's answer for a proof using method 2.
I will prove the case when $x,y$ are real numbers, so $k(x,y)=\exp(-(x-y)^2/2\sigma^2)$. The general case follows mutatis m
|
How to prove that the radial basis function is a kernel?
I will use method 1. Check Douglas Zare's answer for a proof using method 2.
I will prove the case when $x,y$ are real numbers, so $k(x,y)=\exp(-(x-y)^2/2\sigma^2)$. The general case follows mutatis mutandis from the same argument, and is worth doing.
Without loss of generality, suppose that $\sigma^2=1$.
Write $k(x,y)=h(x-y)$, where $$h(t)=\exp\left(-\frac{t^2}{2}\right)=\mathrm{E}\left[e^{itZ}\right] $$ is the characteristic function of a random variable $Z$ with $N(0,1)$ distribution.
For real numbers $x_1,\dots,x_n$ and $a_1,\dots,a_n$, we have
$$
\sum_{j,k=1}^n a_j\,a_k\,h(x_j-x_k) = \sum_{j,k=1}^n a_j\,a_k\,\mathrm{E} \left[ e^{i(x_j-x_k)Z}\right] = \mathrm{E} \left[ \sum_{j,k=1}^n a_j\,e^{i x_j Z}\,a_k\,e^{-i x_k Z}\right]
= \mathrm{E}\left[ \left| \sum_{j=1}^n a_j\,e^{i x_j Z}\right|^2\right] \geq 0 \, ,
$$
which entails that $k$ is a positive semidefinite function, aka a kernel.
To understand this result in greater generality, check out Bochner's Theorem: http://en.wikipedia.org/wiki/Positive-definite_function
|
How to prove that the radial basis function is a kernel?
I will use method 1. Check Douglas Zare's answer for a proof using method 2.
I will prove the case when $x,y$ are real numbers, so $k(x,y)=\exp(-(x-y)^2/2\sigma^2)$. The general case follows mutatis m
|
6,520
|
Why use colormap viridis over jet?
|
See this video. You could also google it because there are a lot of (reasonable) jet-bashing everywhere.
Jet is very pleasing because it is flashy, colorful, and it does not require you to think about your color scale: even if you have just a few outliers, you still get "all the features" in your plot. You said it yourself: jet almost never lacks contrast.
However this comes at a very high price: jet literally shows things that do not exist. It creates contrast out of nowhere: just change your color scale a little bit in jet and you should see that the picture is change dramatically. Do the same thing in viridis, and you would merely have the impression that you are putting more or less light on the exact same thing.
If you don't like viridis, use the other colormaps that were discussed in the video above: they have the same nice properties, and they won't make your data lie. Also change the color scale: starting at 0, even if it is logical from a scientific point of view, may not be a good idea to represent these specific data (but change your colorbar to reflect that, e.g. "<25").
But again, see the video, there are a lot of examples in there as well as complete explanations.
|
Why use colormap viridis over jet?
|
See this video. You could also google it because there are a lot of (reasonable) jet-bashing everywhere.
Jet is very pleasing because it is flashy, colorful, and it does not require you to think about
|
Why use colormap viridis over jet?
See this video. You could also google it because there are a lot of (reasonable) jet-bashing everywhere.
Jet is very pleasing because it is flashy, colorful, and it does not require you to think about your color scale: even if you have just a few outliers, you still get "all the features" in your plot. You said it yourself: jet almost never lacks contrast.
However this comes at a very high price: jet literally shows things that do not exist. It creates contrast out of nowhere: just change your color scale a little bit in jet and you should see that the picture is change dramatically. Do the same thing in viridis, and you would merely have the impression that you are putting more or less light on the exact same thing.
If you don't like viridis, use the other colormaps that were discussed in the video above: they have the same nice properties, and they won't make your data lie. Also change the color scale: starting at 0, even if it is logical from a scientific point of view, may not be a good idea to represent these specific data (but change your colorbar to reflect that, e.g. "<25").
But again, see the video, there are a lot of examples in there as well as complete explanations.
|
Why use colormap viridis over jet?
See this video. You could also google it because there are a lot of (reasonable) jet-bashing everywhere.
Jet is very pleasing because it is flashy, colorful, and it does not require you to think about
|
6,521
|
Why use colormap viridis over jet?
|
You need the plot because you need to show data and you need a colormap because you know that the color you show will not be seen equally by all persons: any color is an interpretation through our visual perception.
Indeed, colors are subjective in the sense that they are interpreted by the brain (in the sense that a spectrum is transformed into a neural activity) into different levels of valence (or value) as a function of the colorbar given next to it. Your eyes will make a constant set of saccades to match the plot with the bar.
JET is to be banned because it is perceptually ambiguous. One first feature of colors in visual perception is its value, that is the total brightness, that acts as the most direct feature. However, this value is non-monotonic in JET, such that ONE value in brightness may induce different values in perception. This is in particular true for the blueiash - yellowish tone (and that most of the time those that correspond to zero values) which artificially "pop up" from an image. Check such curves on :
Viridis (among other alternatives) is made to avoid that problem. You may read this full description for this choice, and how to adapt your colormap to the category of data to plot.
This should convince your supervisor.
|
Why use colormap viridis over jet?
|
You need the plot because you need to show data and you need a colormap because you know that the color you show will not be seen equally by all persons: any color is an interpretation through our vis
|
Why use colormap viridis over jet?
You need the plot because you need to show data and you need a colormap because you know that the color you show will not be seen equally by all persons: any color is an interpretation through our visual perception.
Indeed, colors are subjective in the sense that they are interpreted by the brain (in the sense that a spectrum is transformed into a neural activity) into different levels of valence (or value) as a function of the colorbar given next to it. Your eyes will make a constant set of saccades to match the plot with the bar.
JET is to be banned because it is perceptually ambiguous. One first feature of colors in visual perception is its value, that is the total brightness, that acts as the most direct feature. However, this value is non-monotonic in JET, such that ONE value in brightness may induce different values in perception. This is in particular true for the blueiash - yellowish tone (and that most of the time those that correspond to zero values) which artificially "pop up" from an image. Check such curves on :
Viridis (among other alternatives) is made to avoid that problem. You may read this full description for this choice, and how to adapt your colormap to the category of data to plot.
This should convince your supervisor.
|
Why use colormap viridis over jet?
You need the plot because you need to show data and you need a colormap because you know that the color you show will not be seen equally by all persons: any color is an interpretation through our vis
|
6,522
|
Why use colormap viridis over jet?
|
There's several nice answers here already, but I think it's still pertinent to add another viewpoint, from the excellent paper
Good Colour Maps: How to Design Them. Peter Kovesi. arXiv:1509.03700 (2015). Software available here.
which lays out in a very clear fashion the principles of colour-map design, and provides a really nice tool to analyze them for perceptual uniformity:
This 'washboard' plot has a steady ramp from zero to one going left to right along the bottom, and the top of the plot has a sinusoidal modulation of uniform amplitude. For a properly-designed color map, all of the fringes at the top should show identical, or at least similar, contrast. However, when you put jet to the test, it is immediately obvious that this is not the case:
In other words, there are a ton of fringes, in the red and particularly the green stretches of jet, that get completely nuked out and become completely invisible, because the colour map simply does not have any contrast there. When you apply this to your data, the contrast in those regions will go the same way as the fringes. Similarly, the sharp contrasts along the bottom, on what should be a smooth linear scale, represent places where the map is introducing features that are not really present in the data.
|
Why use colormap viridis over jet?
|
There's several nice answers here already, but I think it's still pertinent to add another viewpoint, from the excellent paper
Good Colour Maps: How to Design Them. Peter Kovesi. arXiv:1509.03700 (20
|
Why use colormap viridis over jet?
There's several nice answers here already, but I think it's still pertinent to add another viewpoint, from the excellent paper
Good Colour Maps: How to Design Them. Peter Kovesi. arXiv:1509.03700 (2015). Software available here.
which lays out in a very clear fashion the principles of colour-map design, and provides a really nice tool to analyze them for perceptual uniformity:
This 'washboard' plot has a steady ramp from zero to one going left to right along the bottom, and the top of the plot has a sinusoidal modulation of uniform amplitude. For a properly-designed color map, all of the fringes at the top should show identical, or at least similar, contrast. However, when you put jet to the test, it is immediately obvious that this is not the case:
In other words, there are a ton of fringes, in the red and particularly the green stretches of jet, that get completely nuked out and become completely invisible, because the colour map simply does not have any contrast there. When you apply this to your data, the contrast in those regions will go the same way as the fringes. Similarly, the sharp contrasts along the bottom, on what should be a smooth linear scale, represent places where the map is introducing features that are not really present in the data.
|
Why use colormap viridis over jet?
There's several nice answers here already, but I think it's still pertinent to add another viewpoint, from the excellent paper
Good Colour Maps: How to Design Them. Peter Kovesi. arXiv:1509.03700 (20
|
6,523
|
Why use colormap viridis over jet?
|
The issue with using any kind of color scale to visually represent ordinal data is that of luminance monotonicity: that is to say, if you have data that satisfy some kind of ordering relationship, that relationship should be reflected not just by changes in hue, but by luminance. The problem with the "jet" color mapping is that the highest point in the mapping (corresponding to larger values) is given a red color, the middle range is given a yellow-green color, and the lowest is blue--but if we look at the perceived "brightness" (i.e., luminance) of those colors, it is clear that this mapping is not monotone. The other color mapping in your question fixes this defect.
The reason for this property should be obvious, not the least of which is the fact that if such figures are reproduced in grayscale, interpretability is not lost.
|
Why use colormap viridis over jet?
|
The issue with using any kind of color scale to visually represent ordinal data is that of luminance monotonicity: that is to say, if you have data that satisfy some kind of ordering relationship, th
|
Why use colormap viridis over jet?
The issue with using any kind of color scale to visually represent ordinal data is that of luminance monotonicity: that is to say, if you have data that satisfy some kind of ordering relationship, that relationship should be reflected not just by changes in hue, but by luminance. The problem with the "jet" color mapping is that the highest point in the mapping (corresponding to larger values) is given a red color, the middle range is given a yellow-green color, and the lowest is blue--but if we look at the perceived "brightness" (i.e., luminance) of those colors, it is clear that this mapping is not monotone. The other color mapping in your question fixes this defect.
The reason for this property should be obvious, not the least of which is the fact that if such figures are reproduced in grayscale, interpretability is not lost.
|
Why use colormap viridis over jet?
The issue with using any kind of color scale to visually represent ordinal data is that of luminance monotonicity: that is to say, if you have data that satisfy some kind of ordering relationship, th
|
6,524
|
Does statistical independence mean lack of causation?
|
So if that's the case, does statistical independence automatically
mean lack of causation?
No, and here's a simple counter example with a multivariate normal,
set.seed(100)
n <- 1e6
a <- 0.2
b <- 0.1
c <- 0.5
z <- rnorm(n)
x <- a*z + sqrt(1-a^2)*rnorm(n)
y <- b*x - c*z + sqrt(1- b^2 - c^2 +2*a*b*c)*rnorm(n)
cor(x, y)
With corresponding graph,
Here we have that $x$ and $y$ are marginally independent (in the multivariate normal case, zero correlation implies independence). This happens because the backdoor path via $z$ exactly cancels out the direct path from $x$ to $y$, that is, $cov(x,y) = b - a*c = 0.1 - 0.1 = 0$. Thus $E[Y|X =x] =E[Y] =0$. Yet, $x$ directly causes $y$, and we have that $E[Y|do(X= x)] = bx$, which is different from $E[Y]=0$.
Associations, interventions and counterfactuals
I think it's important to make some clarifications here regarding associations, interventions and counterfactuals.
Causal models entail statements about the behavior of the system: (i) under passive observations, (ii) under interventions, as well as (iii) counterfactuals. And independence on one level does not necessarily translate to the other.
As the example above shows, we can have no association between $X$ and $Y$, that is, $P(Y|X) = P(Y)$, and still be the case that manipulations on $X$ changes the distribution of $Y$, that is, $P(Y|do(x)) \neq P(Y)$.
Now, we can go one step further. We can have causal models where intervening on $X$ does not change the population distribution of $Y$, but that does not mean lack of counterfactual causation! That is, even though $P(Y|do(x)) = P(Y)$, for every individual their outcome $Y$ would have been different had you changed his $X$. This is precisely the case described by user20160, as well as in my previous answer here.
These three levels make a hierarchy of causal inference tasks, in terms of the information needed to answer queries on each of them.
|
Does statistical independence mean lack of causation?
|
So if that's the case, does statistical independence automatically
mean lack of causation?
No, and here's a simple counter example with a multivariate normal,
set.seed(100)
n <- 1e6
a <- 0.2
b <- 0
|
Does statistical independence mean lack of causation?
So if that's the case, does statistical independence automatically
mean lack of causation?
No, and here's a simple counter example with a multivariate normal,
set.seed(100)
n <- 1e6
a <- 0.2
b <- 0.1
c <- 0.5
z <- rnorm(n)
x <- a*z + sqrt(1-a^2)*rnorm(n)
y <- b*x - c*z + sqrt(1- b^2 - c^2 +2*a*b*c)*rnorm(n)
cor(x, y)
With corresponding graph,
Here we have that $x$ and $y$ are marginally independent (in the multivariate normal case, zero correlation implies independence). This happens because the backdoor path via $z$ exactly cancels out the direct path from $x$ to $y$, that is, $cov(x,y) = b - a*c = 0.1 - 0.1 = 0$. Thus $E[Y|X =x] =E[Y] =0$. Yet, $x$ directly causes $y$, and we have that $E[Y|do(X= x)] = bx$, which is different from $E[Y]=0$.
Associations, interventions and counterfactuals
I think it's important to make some clarifications here regarding associations, interventions and counterfactuals.
Causal models entail statements about the behavior of the system: (i) under passive observations, (ii) under interventions, as well as (iii) counterfactuals. And independence on one level does not necessarily translate to the other.
As the example above shows, we can have no association between $X$ and $Y$, that is, $P(Y|X) = P(Y)$, and still be the case that manipulations on $X$ changes the distribution of $Y$, that is, $P(Y|do(x)) \neq P(Y)$.
Now, we can go one step further. We can have causal models where intervening on $X$ does not change the population distribution of $Y$, but that does not mean lack of counterfactual causation! That is, even though $P(Y|do(x)) = P(Y)$, for every individual their outcome $Y$ would have been different had you changed his $X$. This is precisely the case described by user20160, as well as in my previous answer here.
These three levels make a hierarchy of causal inference tasks, in terms of the information needed to answer queries on each of them.
|
Does statistical independence mean lack of causation?
So if that's the case, does statistical independence automatically
mean lack of causation?
No, and here's a simple counter example with a multivariate normal,
set.seed(100)
n <- 1e6
a <- 0.2
b <- 0
|
6,525
|
Does statistical independence mean lack of causation?
|
Suppose we have a lightbulb controlled by two switches. Let $S_1$ and $S_2$ denote the state of the switches, which can be either 0 or 1. Let $L$ denote the state of the lighbulb, which can be either 0 (off) or 1 (on). We set up the circuit such that the lighbulb is on when the two switches are in different states, and off when they're in the same state. So, the circuit implements the exclusive or function: $L = \text{XOR}(S_1, S_2)$.
By construction, $L$ is causally related to $S_1$ and $S_2$. Given any configuration of the system, if we flip one switch, the state of the lightbulb will change.
Now, suppose both switches are actuated independently according to a Bernoulli process, where the probability of being in state 1 is 0.5. So, $p(S_1=1) = p(S_2=1) = 0.5$, and $S_1$ and $S_2$ are independent. In this case, we know from the design of the circuit that $P(L=1) = 0.5$ and, furthermore, $p(L \mid S_1) = p(L \mid S_2) = p(L)$. That is, knowing the state of one switch doesn't tell us anything about whether the lighbulb will be on or off. So $L$ and $S_1$ are independent, as are $L$ and $S_2$.
But, as above, $L$ is causally related to $S_1$ and $S_2$. So, statistical independence does not imply lack of causation.
|
Does statistical independence mean lack of causation?
|
Suppose we have a lightbulb controlled by two switches. Let $S_1$ and $S_2$ denote the state of the switches, which can be either 0 or 1. Let $L$ denote the state of the lighbulb, which can be either
|
Does statistical independence mean lack of causation?
Suppose we have a lightbulb controlled by two switches. Let $S_1$ and $S_2$ denote the state of the switches, which can be either 0 or 1. Let $L$ denote the state of the lighbulb, which can be either 0 (off) or 1 (on). We set up the circuit such that the lighbulb is on when the two switches are in different states, and off when they're in the same state. So, the circuit implements the exclusive or function: $L = \text{XOR}(S_1, S_2)$.
By construction, $L$ is causally related to $S_1$ and $S_2$. Given any configuration of the system, if we flip one switch, the state of the lightbulb will change.
Now, suppose both switches are actuated independently according to a Bernoulli process, where the probability of being in state 1 is 0.5. So, $p(S_1=1) = p(S_2=1) = 0.5$, and $S_1$ and $S_2$ are independent. In this case, we know from the design of the circuit that $P(L=1) = 0.5$ and, furthermore, $p(L \mid S_1) = p(L \mid S_2) = p(L)$. That is, knowing the state of one switch doesn't tell us anything about whether the lighbulb will be on or off. So $L$ and $S_1$ are independent, as are $L$ and $S_2$.
But, as above, $L$ is causally related to $S_1$ and $S_2$. So, statistical independence does not imply lack of causation.
|
Does statistical independence mean lack of causation?
Suppose we have a lightbulb controlled by two switches. Let $S_1$ and $S_2$ denote the state of the switches, which can be either 0 or 1. Let $L$ denote the state of the lighbulb, which can be either
|
6,526
|
Does statistical independence mean lack of causation?
|
Based on your question, you can think like this:
$ P(A B) = P(A) P(B)$ when $A$ and $B$ are independent. You can similarly imply
$P(AB)/P(A) = P(B|A) = P(B)$. Also,
$P(AB)/P(B) = P(A|B) = P(A)$.
In this regards, I believe that independence means a lack of causation. However, dependence doesn't necessarily imply causation.
|
Does statistical independence mean lack of causation?
|
Based on your question, you can think like this:
$ P(A B) = P(A) P(B)$ when $A$ and $B$ are independent. You can similarly imply
$P(AB)/P(A) = P(B|A) = P(B)$. Also,
$P(AB)/P(B) = P(A|B) = P(A)$.
In th
|
Does statistical independence mean lack of causation?
Based on your question, you can think like this:
$ P(A B) = P(A) P(B)$ when $A$ and $B$ are independent. You can similarly imply
$P(AB)/P(A) = P(B|A) = P(B)$. Also,
$P(AB)/P(B) = P(A|B) = P(A)$.
In this regards, I believe that independence means a lack of causation. However, dependence doesn't necessarily imply causation.
|
Does statistical independence mean lack of causation?
Based on your question, you can think like this:
$ P(A B) = P(A) P(B)$ when $A$ and $B$ are independent. You can similarly imply
$P(AB)/P(A) = P(B|A) = P(B)$. Also,
$P(AB)/P(B) = P(A|B) = P(A)$.
In th
|
6,527
|
Difference between generalized linear models & generalized linear mixed models
|
The advent of generalized linear models has allowed us to build regression-type models of data when the distribution of the response variable is non-normal--for example, when your DV is binary. (If you would like to know a little more about GLiMs, I wrote a fairly extensive answer here, which may be useful although the context differs.) However, a GLiM, e.g. a logistic regression model, assumes that your data are independent. For instance, imagine a study that looks at whether a child has developed asthma. Each child contributes one data point to the study--they either have asthma or they don't. Sometimes data are not independent, though. Consider another study that looks at whether a child has a cold at various points during the school year. In this case, each child contributes many data points. At one time a child might have a cold, later they might not, and still later they might have another cold. These data are not independent because they came from the same child. In order to appropriately analyze these data, we need to somehow take this non-independence into account. There are two ways: One way is to use the generalized estimating equations (which you don't mention, so we'll skip). The other way is to use a generalized linear mixed model. GLiMMs can account for the non-independence by adding random effects (as @MichaelChernick notes). Thus, the answer is that your second option is for non-normal repeated measures (or otherwise non-independent) data. (I should mention, in keeping with @Macro's comment, that general-ized linear mixed models include linear models as a special case and thus can be used with normally distributed data. However, in typical usage the term connotes non-normal data.)
Update: (The OP has asked about GEE as well, so I will write a little about how all three relate to each other.)
Here's a basic overview:
a typical GLiM (I'll use logistic regression as the prototypical case) lets you model an independent binary response as a function of covariates
a GLMM lets you model a non-independent (or clustered) binary response conditional on the attributes of each individual cluster as a function of covariates
the GEE lets you model the population mean response of non-independent binary data as a function of covariates
Since you have multiple trials per participant, your data are not independent; as you correctly note, "[t]rials within one participant are likely to be more similar than as compared to the whole group". Therefore, you should use either a GLMM or the GEE.
The issue, then, is how to choose whether GLMM or GEE would be more appropriate for your situation. The answer to this question depends on the subject of your research--specifically, the target of the inferences you hope to make. As I stated above, with a GLMM, the betas are telling you about the effect of a one unit change in your covariates on a particular participant, given their individual characteristics. On the other hand with the GEE, the betas are telling you about the effect of a one unit change in your covariates on the average of the responses of the entire population in question. This is a difficult distinction to grasp, especially because there is no such distinction with linear models (in which case the two are the same thing).
One way to try to wrap your head around this is to imagine averaging over your population on both sides of the equals sign in your model. For example, this might be a model:
$$
\text{logit}(p_i)=\beta_{0}+\beta_{1}X_1+b_i
$$
where:
$$
\text{logit}(p)=\ln\left(\frac{p}{1-p}\right),~~~~~\&~~~~~~b\sim\mathcal N(0,\sigma^2_b)
$$
There is a parameter that governs the response distribution ($p$, the probability, with binary data) on the left side for each participant. On the right hand side, there are coefficients for the effect of the covariate[s] and the baseline level when the covariate[s] equals 0. The first thing to notice is that the actual intercept for any specific individual is not $\beta_0$, but rather $(\beta_0+b_i)$. But so what? If we are assuming that the $b_i$'s (the random effect) are normally distributed with a mean of 0 (as we've done), certainly we can average over these without difficulty (it would just be $\beta_0$). Moreover, in this case we don't have a corresponding random effect for the slopes and thus their average is just $\beta_1$. So the average of the intercepts plus the average of the slopes must be equal to the logit transformation of the average of the $p_i$'s on the left, mustn't it? Unfortunately, no. The problem is that in between those two is the $\text{logit}$, which is a non-linear transformation. (If the transformation were linear, they would be equivalent, which is why this problem doesn't occur for linear models.) The following plot makes this clear:
Imagine that this plot represents the underlying data generating process for the probability that a small class of students will be able to pass a test on some subject with a given number of hours of instruction on that topic. Each of the grey curves represents the probability of passing the test with varying amounts of instruction for one of the students. The bold curve is the average over the whole class. In this case, the effect of an additional hour of teaching conditional on the student's attributes is $\beta_1$--the same for each student (that is, there is not a random slope). Note, though, that the students baseline ability differs amongst them--probably due to differences in things like IQ (that is, there is a random intercept). The average probability for the class as a whole, however, follows a different profile than the students. The strikingly counter-intuitive result is this: an additional hour of instruction can have a sizable effect on the probability of each student passing the test, but have relatively little effect on the probable total proportion of students who pass. This is because some students might already have had a large chance of passing while others might still have little chance.
The question of whether you should use a GLMM or the GEE is the question of which of these functions you want to estimate. If you wanted to know about the probability of a given student passing (if, say, you were the student, or the student's parent), you want to use a GLMM. On the other hand, if you want to know about the effect on the population (if, for example, you were the teacher, or the principal), you would want to use the GEE.
For another, more mathematically detailed, discussion of this material, see this answer by @Macro.
|
Difference between generalized linear models & generalized linear mixed models
|
The advent of generalized linear models has allowed us to build regression-type models of data when the distribution of the response variable is non-normal--for example, when your DV is binary. (If y
|
Difference between generalized linear models & generalized linear mixed models
The advent of generalized linear models has allowed us to build regression-type models of data when the distribution of the response variable is non-normal--for example, when your DV is binary. (If you would like to know a little more about GLiMs, I wrote a fairly extensive answer here, which may be useful although the context differs.) However, a GLiM, e.g. a logistic regression model, assumes that your data are independent. For instance, imagine a study that looks at whether a child has developed asthma. Each child contributes one data point to the study--they either have asthma or they don't. Sometimes data are not independent, though. Consider another study that looks at whether a child has a cold at various points during the school year. In this case, each child contributes many data points. At one time a child might have a cold, later they might not, and still later they might have another cold. These data are not independent because they came from the same child. In order to appropriately analyze these data, we need to somehow take this non-independence into account. There are two ways: One way is to use the generalized estimating equations (which you don't mention, so we'll skip). The other way is to use a generalized linear mixed model. GLiMMs can account for the non-independence by adding random effects (as @MichaelChernick notes). Thus, the answer is that your second option is for non-normal repeated measures (or otherwise non-independent) data. (I should mention, in keeping with @Macro's comment, that general-ized linear mixed models include linear models as a special case and thus can be used with normally distributed data. However, in typical usage the term connotes non-normal data.)
Update: (The OP has asked about GEE as well, so I will write a little about how all three relate to each other.)
Here's a basic overview:
a typical GLiM (I'll use logistic regression as the prototypical case) lets you model an independent binary response as a function of covariates
a GLMM lets you model a non-independent (or clustered) binary response conditional on the attributes of each individual cluster as a function of covariates
the GEE lets you model the population mean response of non-independent binary data as a function of covariates
Since you have multiple trials per participant, your data are not independent; as you correctly note, "[t]rials within one participant are likely to be more similar than as compared to the whole group". Therefore, you should use either a GLMM or the GEE.
The issue, then, is how to choose whether GLMM or GEE would be more appropriate for your situation. The answer to this question depends on the subject of your research--specifically, the target of the inferences you hope to make. As I stated above, with a GLMM, the betas are telling you about the effect of a one unit change in your covariates on a particular participant, given their individual characteristics. On the other hand with the GEE, the betas are telling you about the effect of a one unit change in your covariates on the average of the responses of the entire population in question. This is a difficult distinction to grasp, especially because there is no such distinction with linear models (in which case the two are the same thing).
One way to try to wrap your head around this is to imagine averaging over your population on both sides of the equals sign in your model. For example, this might be a model:
$$
\text{logit}(p_i)=\beta_{0}+\beta_{1}X_1+b_i
$$
where:
$$
\text{logit}(p)=\ln\left(\frac{p}{1-p}\right),~~~~~\&~~~~~~b\sim\mathcal N(0,\sigma^2_b)
$$
There is a parameter that governs the response distribution ($p$, the probability, with binary data) on the left side for each participant. On the right hand side, there are coefficients for the effect of the covariate[s] and the baseline level when the covariate[s] equals 0. The first thing to notice is that the actual intercept for any specific individual is not $\beta_0$, but rather $(\beta_0+b_i)$. But so what? If we are assuming that the $b_i$'s (the random effect) are normally distributed with a mean of 0 (as we've done), certainly we can average over these without difficulty (it would just be $\beta_0$). Moreover, in this case we don't have a corresponding random effect for the slopes and thus their average is just $\beta_1$. So the average of the intercepts plus the average of the slopes must be equal to the logit transformation of the average of the $p_i$'s on the left, mustn't it? Unfortunately, no. The problem is that in between those two is the $\text{logit}$, which is a non-linear transformation. (If the transformation were linear, they would be equivalent, which is why this problem doesn't occur for linear models.) The following plot makes this clear:
Imagine that this plot represents the underlying data generating process for the probability that a small class of students will be able to pass a test on some subject with a given number of hours of instruction on that topic. Each of the grey curves represents the probability of passing the test with varying amounts of instruction for one of the students. The bold curve is the average over the whole class. In this case, the effect of an additional hour of teaching conditional on the student's attributes is $\beta_1$--the same for each student (that is, there is not a random slope). Note, though, that the students baseline ability differs amongst them--probably due to differences in things like IQ (that is, there is a random intercept). The average probability for the class as a whole, however, follows a different profile than the students. The strikingly counter-intuitive result is this: an additional hour of instruction can have a sizable effect on the probability of each student passing the test, but have relatively little effect on the probable total proportion of students who pass. This is because some students might already have had a large chance of passing while others might still have little chance.
The question of whether you should use a GLMM or the GEE is the question of which of these functions you want to estimate. If you wanted to know about the probability of a given student passing (if, say, you were the student, or the student's parent), you want to use a GLMM. On the other hand, if you want to know about the effect on the population (if, for example, you were the teacher, or the principal), you would want to use the GEE.
For another, more mathematically detailed, discussion of this material, see this answer by @Macro.
|
Difference between generalized linear models & generalized linear mixed models
The advent of generalized linear models has allowed us to build regression-type models of data when the distribution of the response variable is non-normal--for example, when your DV is binary. (If y
|
6,528
|
Difference between generalized linear models & generalized linear mixed models
|
The key is the introduction of random effects. Gung's link mentions it. But I think it should have been mentioned directly. That is the main difference.
|
Difference between generalized linear models & generalized linear mixed models
|
The key is the introduction of random effects. Gung's link mentions it. But I think it should have been mentioned directly. That is the main difference.
|
Difference between generalized linear models & generalized linear mixed models
The key is the introduction of random effects. Gung's link mentions it. But I think it should have been mentioned directly. That is the main difference.
|
Difference between generalized linear models & generalized linear mixed models
The key is the introduction of random effects. Gung's link mentions it. But I think it should have been mentioned directly. That is the main difference.
|
6,529
|
Difference between generalized linear models & generalized linear mixed models
|
I suggest you also examine answers of a question I asked some time ago:
General Linear Model vs. Generalized Linear Model (with an identity link function?)
|
Difference between generalized linear models & generalized linear mixed models
|
I suggest you also examine answers of a question I asked some time ago:
General Linear Model vs. Generalized Linear Model (with an identity link function?)
|
Difference between generalized linear models & generalized linear mixed models
I suggest you also examine answers of a question I asked some time ago:
General Linear Model vs. Generalized Linear Model (with an identity link function?)
|
Difference between generalized linear models & generalized linear mixed models
I suggest you also examine answers of a question I asked some time ago:
General Linear Model vs. Generalized Linear Model (with an identity link function?)
|
6,530
|
Recall and precision in classification
|
Whether a classifier is “good” really depends on
What else is available for your particular problem. Obviously, you want a classifier to be better than random or naive guesses (e.g. classifying everything as belonging to the most common category) but some things are easier to classify than others.
The cost of different mistakes (false alarm vs. false negatives) and the base rate. It's very important to distinguish the two and work out the consequences as it's possible to have a classifier with a very high accuracy (correct classifications on some test sample) that is completely useless in practice (say you are trying to detect a rare disease or some uncommon mischievous behavior and plan to launch some action upon detection; Large-scale testing costs something and the remedial action/treatment also typically involve significant risks/costs so considering that most hits are going to be false positives, from a cost/benefit perspective it might be better to do nothing).
To understand the link between recall/precision on the one hand and sensitivity/specificity on the other hand, it's useful to come back to a confusion matrix:
Condition: A Not A
Test says “A” True positive (TP) | False positive (FP)
----------------------------------
Test says “Not A” False negative (FN) | True negative (TN)
Recall is TP/(TP + FN) whereas precision is TP/(TP+FP). This reflects the nature of the problem: In information retrieval, you want to identify as many relevant documents as you can (that's recall) and avoid having to sort through junk (that's precision).
Using the same table, traditional classification metrics are (1) sensitivity defined as TP/(TP + FN) and (2) specificity defined as TN/(FP + TN). So recall and sensitivity are simply synonymous but precision and specificity are defined differently (like recall and sensitivity, specificity is defined with respect to the column total whereas precision refers to the row total). Precision is also sometimes called the “positive predictive value” or, rarely, the “false positive rate” (but see my answer to Relation between true positive, false positive, false negative and true negative regarding the confusion surrounding this definition of the false positive rate).
Interestingly, information retrieval metrics do not involve the “true negative” count. This makes sense: In information retrieval, you don't care about correctly classifying negative instances per se, you just don't want too many of them polluting your results (see also Why doesn't recall take into account true negatives?).
Because of this difference, it's not possible to go from specificity to precision or the other way around without additional information, namely the number of true negatives or, alternatively, the overall proportion of positive and negative cases. However, for the same corpus/test set, higher specificity always means better precision so they are closely related.
In an information retrieval context, the goal is typically to identify a small number of matches from a large number of documents. Because of this asymmetry, it is in fact much more difficult to get a good precision than a good specificity while keeping the sensitivity/recall constant. Since most documents are irrelevant, you have many more occasions for false alarms than true positives and these false alarms can swamp the correct results even if the classifier has impressive accuracy on a balanced test set (this is in fact what's going on in the scenarios I mentioned in my point 2 above). Consequently, you really need to optimize precision and not merely to ensure decent specificity because even impressive-looking rates like 99% or more are sometimes not enough to avoid numerous false alarms.
There is usually a trade-off between sensitivity and specificity (or recall and precision). Intuitively, if you cast a wider net, you will detect more relevant documents/positive cases (higher sensitivity/recall) but you will also get more false alarms (lower specificity and lower precision). If you classify everything in the positive category, you have 100% recall/sensitivity, a bad precision and a mostly useless classifier (“mostly” because if you don't have any other information, it is perfectly reasonable to assume it's not going to rain in a desert and to act accordingly so maybe the output is not useless after all; of course, you don't need a sophisticated model for that).
Considering all this, 60% precision and 95% recall does not sound too bad but, again, this really depends on the domain and what you intend to do with this classifier.
Some additional information regarding the latest comments/edits:
Again, the performance you can expect depends on the specifics (in this context this would be things like the exact set of emotions present in the training set, quality of the picture/video, luminosity, occlusion, head movements, acted or spontaneous videos, person-dependent or person-independent model, etc.) but F1 over .7 sounds good for this type of applications even if the very best models can do better on some data sets [see Valstar, M.F., Mehu, M., Jiang, B., Pantic, M., & Scherer, K. (2012). Meta-analysis of the first facial expression recognition challenge. IEEE Transactions on Systems, Man, and Cybernetics, Part B: Cybernetics, 42 (4), 966-979.]
Whether such a model is useful in practice is a completely different question and obviously depends on the application. Note that facial “expression” is itself a complex topic and going from a typical training set (posed expressions) to any real-life situation is not easy. This is rather off-topic on this forum but it will have serious consequences for any practical application you might contemplate.
Finally, head-to-head comparison between models is yet another question. My take on the numbers you presented is that there isn't any dramatic difference between the models (if you refer to the paper I cited above, the range of F1 scores for well-known models in this area is much broader). In practice, technical aspects (simplicity/availability of standard libraries, speed of the different techniques, etc.) would likely decide which model is implemented, except perhaps if the cost/benefits and overall rate make you strongly favor either precision or recall.
|
Recall and precision in classification
|
Whether a classifier is “good” really depends on
What else is available for your particular problem. Obviously, you want a classifier to be better than random or naive guesses (e.g. classifying ever
|
Recall and precision in classification
Whether a classifier is “good” really depends on
What else is available for your particular problem. Obviously, you want a classifier to be better than random or naive guesses (e.g. classifying everything as belonging to the most common category) but some things are easier to classify than others.
The cost of different mistakes (false alarm vs. false negatives) and the base rate. It's very important to distinguish the two and work out the consequences as it's possible to have a classifier with a very high accuracy (correct classifications on some test sample) that is completely useless in practice (say you are trying to detect a rare disease or some uncommon mischievous behavior and plan to launch some action upon detection; Large-scale testing costs something and the remedial action/treatment also typically involve significant risks/costs so considering that most hits are going to be false positives, from a cost/benefit perspective it might be better to do nothing).
To understand the link between recall/precision on the one hand and sensitivity/specificity on the other hand, it's useful to come back to a confusion matrix:
Condition: A Not A
Test says “A” True positive (TP) | False positive (FP)
----------------------------------
Test says “Not A” False negative (FN) | True negative (TN)
Recall is TP/(TP + FN) whereas precision is TP/(TP+FP). This reflects the nature of the problem: In information retrieval, you want to identify as many relevant documents as you can (that's recall) and avoid having to sort through junk (that's precision).
Using the same table, traditional classification metrics are (1) sensitivity defined as TP/(TP + FN) and (2) specificity defined as TN/(FP + TN). So recall and sensitivity are simply synonymous but precision and specificity are defined differently (like recall and sensitivity, specificity is defined with respect to the column total whereas precision refers to the row total). Precision is also sometimes called the “positive predictive value” or, rarely, the “false positive rate” (but see my answer to Relation between true positive, false positive, false negative and true negative regarding the confusion surrounding this definition of the false positive rate).
Interestingly, information retrieval metrics do not involve the “true negative” count. This makes sense: In information retrieval, you don't care about correctly classifying negative instances per se, you just don't want too many of them polluting your results (see also Why doesn't recall take into account true negatives?).
Because of this difference, it's not possible to go from specificity to precision or the other way around without additional information, namely the number of true negatives or, alternatively, the overall proportion of positive and negative cases. However, for the same corpus/test set, higher specificity always means better precision so they are closely related.
In an information retrieval context, the goal is typically to identify a small number of matches from a large number of documents. Because of this asymmetry, it is in fact much more difficult to get a good precision than a good specificity while keeping the sensitivity/recall constant. Since most documents are irrelevant, you have many more occasions for false alarms than true positives and these false alarms can swamp the correct results even if the classifier has impressive accuracy on a balanced test set (this is in fact what's going on in the scenarios I mentioned in my point 2 above). Consequently, you really need to optimize precision and not merely to ensure decent specificity because even impressive-looking rates like 99% or more are sometimes not enough to avoid numerous false alarms.
There is usually a trade-off between sensitivity and specificity (or recall and precision). Intuitively, if you cast a wider net, you will detect more relevant documents/positive cases (higher sensitivity/recall) but you will also get more false alarms (lower specificity and lower precision). If you classify everything in the positive category, you have 100% recall/sensitivity, a bad precision and a mostly useless classifier (“mostly” because if you don't have any other information, it is perfectly reasonable to assume it's not going to rain in a desert and to act accordingly so maybe the output is not useless after all; of course, you don't need a sophisticated model for that).
Considering all this, 60% precision and 95% recall does not sound too bad but, again, this really depends on the domain and what you intend to do with this classifier.
Some additional information regarding the latest comments/edits:
Again, the performance you can expect depends on the specifics (in this context this would be things like the exact set of emotions present in the training set, quality of the picture/video, luminosity, occlusion, head movements, acted or spontaneous videos, person-dependent or person-independent model, etc.) but F1 over .7 sounds good for this type of applications even if the very best models can do better on some data sets [see Valstar, M.F., Mehu, M., Jiang, B., Pantic, M., & Scherer, K. (2012). Meta-analysis of the first facial expression recognition challenge. IEEE Transactions on Systems, Man, and Cybernetics, Part B: Cybernetics, 42 (4), 966-979.]
Whether such a model is useful in practice is a completely different question and obviously depends on the application. Note that facial “expression” is itself a complex topic and going from a typical training set (posed expressions) to any real-life situation is not easy. This is rather off-topic on this forum but it will have serious consequences for any practical application you might contemplate.
Finally, head-to-head comparison between models is yet another question. My take on the numbers you presented is that there isn't any dramatic difference between the models (if you refer to the paper I cited above, the range of F1 scores for well-known models in this area is much broader). In practice, technical aspects (simplicity/availability of standard libraries, speed of the different techniques, etc.) would likely decide which model is implemented, except perhaps if the cost/benefits and overall rate make you strongly favor either precision or recall.
|
Recall and precision in classification
Whether a classifier is “good” really depends on
What else is available for your particular problem. Obviously, you want a classifier to be better than random or naive guesses (e.g. classifying ever
|
6,531
|
Recall and precision in classification
|
In the context of binary classification, examples are either positive or negative.
The recall addresses the question: "Given a positive example, will the classifier detect it ?"
The precision addresses the question: "Given a positive prediction from the classifier, how likely is it to be correct ?"
So it depends if the focus is on positive examples or on positive predictions.
One could say "at a recall at least 90%, the classifier with the highest precision is 4." But if what matters is the quality of the predictions, among the classifiers with a precision of at least 70%, the one that achieves highest recall is 6.
|
Recall and precision in classification
|
In the context of binary classification, examples are either positive or negative.
The recall addresses the question: "Given a positive example, will the classifier detect it ?"
The precision address
|
Recall and precision in classification
In the context of binary classification, examples are either positive or negative.
The recall addresses the question: "Given a positive example, will the classifier detect it ?"
The precision addresses the question: "Given a positive prediction from the classifier, how likely is it to be correct ?"
So it depends if the focus is on positive examples or on positive predictions.
One could say "at a recall at least 90%, the classifier with the highest precision is 4." But if what matters is the quality of the predictions, among the classifiers with a precision of at least 70%, the one that achieves highest recall is 6.
|
Recall and precision in classification
In the context of binary classification, examples are either positive or negative.
The recall addresses the question: "Given a positive example, will the classifier detect it ?"
The precision address
|
6,532
|
Recall and precision in classification
|
Moving from continuous predictions, as used in computing ROC area (concordance probability; c-index) to a discontinuous improper scoring rule (forced-choice classification accuracy) results in all kinds of anomalies and will mislead the analyst to choose the wrong predictors and/or the wrong model. It is much better to make decisions on the basis of proper scoring rules (e.g., log-likelihood/deviance/logarithmic probability scoring rule; Brier score (quadratic probability accuracy score)). Among the many advantages of such an approach is the identification of observations for which classification is hazardous to your health due to uncertainty caused by mid-range probabilities.
|
Recall and precision in classification
|
Moving from continuous predictions, as used in computing ROC area (concordance probability; c-index) to a discontinuous improper scoring rule (forced-choice classification accuracy) results in all kin
|
Recall and precision in classification
Moving from continuous predictions, as used in computing ROC area (concordance probability; c-index) to a discontinuous improper scoring rule (forced-choice classification accuracy) results in all kinds of anomalies and will mislead the analyst to choose the wrong predictors and/or the wrong model. It is much better to make decisions on the basis of proper scoring rules (e.g., log-likelihood/deviance/logarithmic probability scoring rule; Brier score (quadratic probability accuracy score)). Among the many advantages of such an approach is the identification of observations for which classification is hazardous to your health due to uncertainty caused by mid-range probabilities.
|
Recall and precision in classification
Moving from continuous predictions, as used in computing ROC area (concordance probability; c-index) to a discontinuous improper scoring rule (forced-choice classification accuracy) results in all kin
|
6,533
|
Recall and precision in classification
|
Neither precision nor recall tell the full story, and it is hard to compare a predictor with, say, 90% recall and 60% precision to a predictor with, say, 85% precision and 65% recall - unless, of course, you have cost/benefit associated with each of the 4 cells (tp/fp/tn/fn) in the confusion matrix.
An interesting way to get a single number (proficiency, aka uncertainty coefficient) describing the classifier performance is to use information theory:
proficiency = I(predicted,actual) / H(actual)
i.e., it tells you what fraction of the information present in the actual data was recovered by the classifier. It is 0 if either precision or recall is 0 and it is 100% if (and only if) both precision and recall are 100%. In that it is similar to F1 score, but proficiency has a clear information-theoretical meaning while F1 is just a harmonic average of two numbers with a meaning.
You can find paper, presentation and code (Python) to compute the Proficiency metric here: https://github.com/Magnetic/proficiency-metric
|
Recall and precision in classification
|
Neither precision nor recall tell the full story, and it is hard to compare a predictor with, say, 90% recall and 60% precision to a predictor with, say, 85% precision and 65% recall - unless, of cour
|
Recall and precision in classification
Neither precision nor recall tell the full story, and it is hard to compare a predictor with, say, 90% recall and 60% precision to a predictor with, say, 85% precision and 65% recall - unless, of course, you have cost/benefit associated with each of the 4 cells (tp/fp/tn/fn) in the confusion matrix.
An interesting way to get a single number (proficiency, aka uncertainty coefficient) describing the classifier performance is to use information theory:
proficiency = I(predicted,actual) / H(actual)
i.e., it tells you what fraction of the information present in the actual data was recovered by the classifier. It is 0 if either precision or recall is 0 and it is 100% if (and only if) both precision and recall are 100%. In that it is similar to F1 score, but proficiency has a clear information-theoretical meaning while F1 is just a harmonic average of two numbers with a meaning.
You can find paper, presentation and code (Python) to compute the Proficiency metric here: https://github.com/Magnetic/proficiency-metric
|
Recall and precision in classification
Neither precision nor recall tell the full story, and it is hard to compare a predictor with, say, 90% recall and 60% precision to a predictor with, say, 85% precision and 65% recall - unless, of cour
|
6,534
|
Effect size as the hypothesis for significance testing
|
As far as significance testing goes (or anything else that does essentially the same thing as significance testing), I have long thought that the best approach in most situations is likely to be estimating a standardized effect size, with a 95% confidence interval about that effect size. There's nothing really new there--mathematically you can shuffle back and forth between them--if the p-value for a 'nil' null is <.05, then 0 will lie outside of a 95% CI, and vise versa. The advantage of this, in my opinion, is psychological; that is, it makes salient information that exists but that people can't see when only p-values are reported. For example, it is easy to see that an effect is wildly 'significant', but ridiculously small; or 'non-significant', but only because the error bars are huge whereas the estimated effect is more or less what you expected. These can be paired with raw values and their CI's.
Now, in many fields the raw values are intrinsically meaningful, and I recognize that raises the question of whether it's still worthwhile to compute effect size measures given that we already have values like means and slopes. An example might be looking at stunted growth; we know what it means for a 20 year old, white male to be 6 +/- 2 inches shorter (i.e. 15 +/- 5 cm), than they would otherwise, so why mention $d=-1.6\pm.5$? I tend to think that there can still be value in reporting both, and functions can be written to compute these so that it's very little extra work, but I recognize that opinions will vary. At any rate, I argue that point estimates with confidence intervals replace p-values as the first part of my response.
On the other hand, I think a bigger question is 'is the thing that significance testing does what we really want?' I think the real problem is that for most people analyzing data (i.e., practitioners not statisticians), significance testing can become the entirety of data analysis. It seems to me that the most important thing is to have a principled way to think about what is going on with our data, and null hypothesis significance testing is, at best, a very small part of that. Let me give an imaginary example (I acknowledge that this is a caricature, but unfortunately, I fear it is somewhat plausible):
Bob conducts a study, gathering data on something-or-other. He
expects the data will be normally distributed, clustering tightly
around some value, and intends to conduct a one-sample t-test to see
if his data are 'significantly different' from some pre-specified
value. After collecting his sample, he checks to see if his data are
normally distributed, and finds that they are not. Instead, they do
not have a pronounced lump in the center but are relatively high over a given
interval and then trail off with a long left tail. Bob worries about
what he should do to ensure that his test is valid. He ends up doing
something (e.g., a transformation, a non-parametric test, etc.), and
then reports a test statistic and a p-value.
I hope this doesn't come off as nasty. I don't mean to mock anyone, but I think something like this does happen occasionally. Should this scenario occur, we can all agree that it is poor data analysis. However, the problem isn't that the test statistic or the p-value is wrong; we can posit that the data were handled properly in that respect. I would argue that the problem is Bob is engaged in what Cleveland called "rote data analysis". He appears to believe that the only point is to get the right p-value, and thinks very little about his data outside of pursuing that goal. He even could have switched over to my suggestion above and reported a standardized effect size with a 95% confidence interval, and it wouldn't have changed what I see as the larger problem (this is what I meant by doing "essentially the same thing" by a different means). In this specific case, the fact that the data didn't look the way he expected (i.e., weren't normal) is real information, it's interesting, and very possibly important, but that information is essentially just thrown away. Bob doesn't recognize this, because of the focus on significance testing. To my mind, that is the real problem with significance testing.
Let me address a few other perspectives that have been mentioned, and I want to be very clear that I am not criticizing anyone.
It is often mentioned that many people don't really understand
p-values (e.g., thinking they're the probability the null is
true), etc. It is sometimes argued that, if only people would use
the Bayesian approach, these problems would go away. I believe that people
can approach Bayesian data analysis in a manner that is just as
incurious and mechanical. However, I think that misunderstanding the meaning of p-values would be less harmful if no one thought getting a p-value was the goal.
The existence of 'big data' is generally unrelated to this issue. Big data only make it obvious that organizing data analysis around 'significance' is not a helpful approach.
I do not believe the problem is with the hypothesis being tested. If people only wanted to see if the estimated value is outside of an interval, rather than if it's equal to a point value, many of the same issues could arise. (Again, I want to be clear I know you are not 'Bob'.)
For the record, I want to mention that my own suggestion from the first paragraph, does not address the issue, as I tried to point out.
For me, this is the core issue: What we really want is a principled way to think about what happened. What that means in any given situation is not cut and dried. How to impart that to students in a methods class is neither clear nor easy. Significance testing has a lot of inertia and tradition behind it. In a stats class, it's clear what needs to be taught and how. For students and practitioners it becomes possible to develop a conceptual schema for understanding the material, and a checklist / flowchart (I've seen some!) for conducting analysis. Significance testing can naturally evolve into rote data analysis without anyone being dumb or lazy or bad. That is the problem.
|
Effect size as the hypothesis for significance testing
|
As far as significance testing goes (or anything else that does essentially the same thing as significance testing), I have long thought that the best approach in most situations is likely to be estim
|
Effect size as the hypothesis for significance testing
As far as significance testing goes (or anything else that does essentially the same thing as significance testing), I have long thought that the best approach in most situations is likely to be estimating a standardized effect size, with a 95% confidence interval about that effect size. There's nothing really new there--mathematically you can shuffle back and forth between them--if the p-value for a 'nil' null is <.05, then 0 will lie outside of a 95% CI, and vise versa. The advantage of this, in my opinion, is psychological; that is, it makes salient information that exists but that people can't see when only p-values are reported. For example, it is easy to see that an effect is wildly 'significant', but ridiculously small; or 'non-significant', but only because the error bars are huge whereas the estimated effect is more or less what you expected. These can be paired with raw values and their CI's.
Now, in many fields the raw values are intrinsically meaningful, and I recognize that raises the question of whether it's still worthwhile to compute effect size measures given that we already have values like means and slopes. An example might be looking at stunted growth; we know what it means for a 20 year old, white male to be 6 +/- 2 inches shorter (i.e. 15 +/- 5 cm), than they would otherwise, so why mention $d=-1.6\pm.5$? I tend to think that there can still be value in reporting both, and functions can be written to compute these so that it's very little extra work, but I recognize that opinions will vary. At any rate, I argue that point estimates with confidence intervals replace p-values as the first part of my response.
On the other hand, I think a bigger question is 'is the thing that significance testing does what we really want?' I think the real problem is that for most people analyzing data (i.e., practitioners not statisticians), significance testing can become the entirety of data analysis. It seems to me that the most important thing is to have a principled way to think about what is going on with our data, and null hypothesis significance testing is, at best, a very small part of that. Let me give an imaginary example (I acknowledge that this is a caricature, but unfortunately, I fear it is somewhat plausible):
Bob conducts a study, gathering data on something-or-other. He
expects the data will be normally distributed, clustering tightly
around some value, and intends to conduct a one-sample t-test to see
if his data are 'significantly different' from some pre-specified
value. After collecting his sample, he checks to see if his data are
normally distributed, and finds that they are not. Instead, they do
not have a pronounced lump in the center but are relatively high over a given
interval and then trail off with a long left tail. Bob worries about
what he should do to ensure that his test is valid. He ends up doing
something (e.g., a transformation, a non-parametric test, etc.), and
then reports a test statistic and a p-value.
I hope this doesn't come off as nasty. I don't mean to mock anyone, but I think something like this does happen occasionally. Should this scenario occur, we can all agree that it is poor data analysis. However, the problem isn't that the test statistic or the p-value is wrong; we can posit that the data were handled properly in that respect. I would argue that the problem is Bob is engaged in what Cleveland called "rote data analysis". He appears to believe that the only point is to get the right p-value, and thinks very little about his data outside of pursuing that goal. He even could have switched over to my suggestion above and reported a standardized effect size with a 95% confidence interval, and it wouldn't have changed what I see as the larger problem (this is what I meant by doing "essentially the same thing" by a different means). In this specific case, the fact that the data didn't look the way he expected (i.e., weren't normal) is real information, it's interesting, and very possibly important, but that information is essentially just thrown away. Bob doesn't recognize this, because of the focus on significance testing. To my mind, that is the real problem with significance testing.
Let me address a few other perspectives that have been mentioned, and I want to be very clear that I am not criticizing anyone.
It is often mentioned that many people don't really understand
p-values (e.g., thinking they're the probability the null is
true), etc. It is sometimes argued that, if only people would use
the Bayesian approach, these problems would go away. I believe that people
can approach Bayesian data analysis in a manner that is just as
incurious and mechanical. However, I think that misunderstanding the meaning of p-values would be less harmful if no one thought getting a p-value was the goal.
The existence of 'big data' is generally unrelated to this issue. Big data only make it obvious that organizing data analysis around 'significance' is not a helpful approach.
I do not believe the problem is with the hypothesis being tested. If people only wanted to see if the estimated value is outside of an interval, rather than if it's equal to a point value, many of the same issues could arise. (Again, I want to be clear I know you are not 'Bob'.)
For the record, I want to mention that my own suggestion from the first paragraph, does not address the issue, as I tried to point out.
For me, this is the core issue: What we really want is a principled way to think about what happened. What that means in any given situation is not cut and dried. How to impart that to students in a methods class is neither clear nor easy. Significance testing has a lot of inertia and tradition behind it. In a stats class, it's clear what needs to be taught and how. For students and practitioners it becomes possible to develop a conceptual schema for understanding the material, and a checklist / flowchart (I've seen some!) for conducting analysis. Significance testing can naturally evolve into rote data analysis without anyone being dumb or lazy or bad. That is the problem.
|
Effect size as the hypothesis for significance testing
As far as significance testing goes (or anything else that does essentially the same thing as significance testing), I have long thought that the best approach in most situations is likely to be estim
|
6,535
|
Effect size as the hypothesis for significance testing
|
Why do we insist on any form of hypothesis test in statistics?
In the wonderful book Statistics as Principled Argument Robert Abelson argues that statistical analysis is part of a principled argument about the subject in question. He says that, rather than be evaluated as hypotheses to be rejected or not rejected (or even accepted!?!) we should evaluate them based on what he calls the MAGIC criteria:
Magnitude - how big is it?
Articulation - Is it full of exceptions? Is it clear?
Generality - How generally does it apply?
Interestingness - Do we care about the result?
Credibility - Can we believe it?
My review of the book on my blog
|
Effect size as the hypothesis for significance testing
|
Why do we insist on any form of hypothesis test in statistics?
In the wonderful book Statistics as Principled Argument Robert Abelson argues that statistical analysis is part of a principled argument
|
Effect size as the hypothesis for significance testing
Why do we insist on any form of hypothesis test in statistics?
In the wonderful book Statistics as Principled Argument Robert Abelson argues that statistical analysis is part of a principled argument about the subject in question. He says that, rather than be evaluated as hypotheses to be rejected or not rejected (or even accepted!?!) we should evaluate them based on what he calls the MAGIC criteria:
Magnitude - how big is it?
Articulation - Is it full of exceptions? Is it clear?
Generality - How generally does it apply?
Interestingness - Do we care about the result?
Credibility - Can we believe it?
My review of the book on my blog
|
Effect size as the hypothesis for significance testing
Why do we insist on any form of hypothesis test in statistics?
In the wonderful book Statistics as Principled Argument Robert Abelson argues that statistical analysis is part of a principled argument
|
6,536
|
Effect size as the hypothesis for significance testing
|
Your last question not only makes sense: nowadays sensible industrial statisticians do not test for significant difference but for significant equivalence, that is, testing a null hypothesis of the form $H_0\colon \{|\mu_1-\mu_2|>\epsilon\}$ where $\epsilon$ is set by the user and is indeed related to the notion of "effect size". The most common equivalence test is the so-called TOST.
Nevertheless the TOST strategy aims to prove that two means $\mu_1$ and $\mu_2$ are significantly $\epsilon$-close, for example $\mu_1$ is the mean value for some measurement method and $\mu_2$ for another measurement method, and in many situations it is more sensible to assess the equivalence between the observations rather than the means. To do so we could perform hypothesis testing on quantities such that $\Pr(|X_1-X_2|>\epsilon)$, and such hypothesis testing relates to tolerance intervals.
|
Effect size as the hypothesis for significance testing
|
Your last question not only makes sense: nowadays sensible industrial statisticians do not test for significant difference but for significant equivalence, that is, testing a null hypothesis of the fo
|
Effect size as the hypothesis for significance testing
Your last question not only makes sense: nowadays sensible industrial statisticians do not test for significant difference but for significant equivalence, that is, testing a null hypothesis of the form $H_0\colon \{|\mu_1-\mu_2|>\epsilon\}$ where $\epsilon$ is set by the user and is indeed related to the notion of "effect size". The most common equivalence test is the so-called TOST.
Nevertheless the TOST strategy aims to prove that two means $\mu_1$ and $\mu_2$ are significantly $\epsilon$-close, for example $\mu_1$ is the mean value for some measurement method and $\mu_2$ for another measurement method, and in many situations it is more sensible to assess the equivalence between the observations rather than the means. To do so we could perform hypothesis testing on quantities such that $\Pr(|X_1-X_2|>\epsilon)$, and such hypothesis testing relates to tolerance intervals.
|
Effect size as the hypothesis for significance testing
Your last question not only makes sense: nowadays sensible industrial statisticians do not test for significant difference but for significant equivalence, that is, testing a null hypothesis of the fo
|
6,537
|
Effect size as the hypothesis for significance testing
|
Traditional hypothesis tests tell you whether there is statistically significant evidence for the existence of an effect, whereas what we often want to know about is the existence of evidence of a practically significant effect.
It is certainly possible to form Bayesian "hypothesis tests" with a minimum effect size (IIRC there is an example of this in David MacKay's book on "Information Theory, Inference and Learning Algorithms", I'll look it up when I have a moment.
Normality testing is another good example, we usually know that the data are not really normally distributed, we are just testing to see if there is evidence that this is isn't a reasonable approximation. Or testing for the bias of a coin, we know it is unlikely to be completely biased as it is assymetric.
|
Effect size as the hypothesis for significance testing
|
Traditional hypothesis tests tell you whether there is statistically significant evidence for the existence of an effect, whereas what we often want to know about is the existence of evidence of a pr
|
Effect size as the hypothesis for significance testing
Traditional hypothesis tests tell you whether there is statistically significant evidence for the existence of an effect, whereas what we often want to know about is the existence of evidence of a practically significant effect.
It is certainly possible to form Bayesian "hypothesis tests" with a minimum effect size (IIRC there is an example of this in David MacKay's book on "Information Theory, Inference and Learning Algorithms", I'll look it up when I have a moment.
Normality testing is another good example, we usually know that the data are not really normally distributed, we are just testing to see if there is evidence that this is isn't a reasonable approximation. Or testing for the bias of a coin, we know it is unlikely to be completely biased as it is assymetric.
|
Effect size as the hypothesis for significance testing
Traditional hypothesis tests tell you whether there is statistically significant evidence for the existence of an effect, whereas what we often want to know about is the existence of evidence of a pr
|
6,538
|
Effect size as the hypothesis for significance testing
|
A lot of this comes down to what question you are actually asking, how you design your study, and even what you mean by equal.
I ran accros an interesting little insert in the British Medical Journal once that talked about what people interpreted certain phases to mean. It turns out that "always" can mean that something happens as low as 91% of the time (BMJ VOLUME 333 26 AUGUST 2006 page 445). So maybe equal and equivalent (or within X% for some value of X) could be thought to mean the same thing. And lets ask the computer a simple equality, using R:
> (1e+5 + 1e-50) == (1e+5 - 1e-50)
[1] TRUE
Now a pure mathematician using infinite precision might say that those 2 values are not equal, but R says they are and for most practical cases they would be (If you offered to give me $\$$(1e+5 + 1e-50), but the amount ended up being $\$$(1e+5 - 1e-50) I would not refuse the money because it differed from what was promised).
Further if our alternative hypothesis is $H_a: \mu > \mu_0$ we often write the null as $H_0: \mu=\mu_0$ even though technically the real null is $H_0: \mu \le \mu_0$, but we work with the equality as null since if we can show that $\mu$ is bigger than $\mu_0$ then we also know that it is bigger than all the values less than $\mu_0$. And isn't a two-tailed test really just 2 one-tailed tests? After all, would you really say that $\mu \ne \mu_0$ but refuse to say which side of $\mu_0$ $\mu$ is on? This is partly why there is a trend towards using confidence intervals in place of p-values when possible, if my confidence interval for $\mu$ includes $\mu_0$ then while I may not be willing to believe that $\mu$ is exactly equal to $\mu_0$, I cannot say for certain which side of $\mu_0$ $\mu$ lies on, which means they might as well be equal for practical purposes.
A lot of this comes down to asking the right question and designing the right study for that question. If you end up with enough data to show that a practically meaningless difference is statistically significant, then you have wasted resources getting that much data. It would have been better to decide what a meaningful difference would be and designed the study to give you enough power to detect that difference but not smaller.
And if we really want to split hairs, how do we define what parts of the lamb are on the right and which are on the left? If we define it by a line that by definition has equal number of hairs on each side then the answer to the above question becomes "Of Course it is".
|
Effect size as the hypothesis for significance testing
|
A lot of this comes down to what question you are actually asking, how you design your study, and even what you mean by equal.
I ran accros an interesting little insert in the British Medical Journal
|
Effect size as the hypothesis for significance testing
A lot of this comes down to what question you are actually asking, how you design your study, and even what you mean by equal.
I ran accros an interesting little insert in the British Medical Journal once that talked about what people interpreted certain phases to mean. It turns out that "always" can mean that something happens as low as 91% of the time (BMJ VOLUME 333 26 AUGUST 2006 page 445). So maybe equal and equivalent (or within X% for some value of X) could be thought to mean the same thing. And lets ask the computer a simple equality, using R:
> (1e+5 + 1e-50) == (1e+5 - 1e-50)
[1] TRUE
Now a pure mathematician using infinite precision might say that those 2 values are not equal, but R says they are and for most practical cases they would be (If you offered to give me $\$$(1e+5 + 1e-50), but the amount ended up being $\$$(1e+5 - 1e-50) I would not refuse the money because it differed from what was promised).
Further if our alternative hypothesis is $H_a: \mu > \mu_0$ we often write the null as $H_0: \mu=\mu_0$ even though technically the real null is $H_0: \mu \le \mu_0$, but we work with the equality as null since if we can show that $\mu$ is bigger than $\mu_0$ then we also know that it is bigger than all the values less than $\mu_0$. And isn't a two-tailed test really just 2 one-tailed tests? After all, would you really say that $\mu \ne \mu_0$ but refuse to say which side of $\mu_0$ $\mu$ is on? This is partly why there is a trend towards using confidence intervals in place of p-values when possible, if my confidence interval for $\mu$ includes $\mu_0$ then while I may not be willing to believe that $\mu$ is exactly equal to $\mu_0$, I cannot say for certain which side of $\mu_0$ $\mu$ lies on, which means they might as well be equal for practical purposes.
A lot of this comes down to asking the right question and designing the right study for that question. If you end up with enough data to show that a practically meaningless difference is statistically significant, then you have wasted resources getting that much data. It would have been better to decide what a meaningful difference would be and designed the study to give you enough power to detect that difference but not smaller.
And if we really want to split hairs, how do we define what parts of the lamb are on the right and which are on the left? If we define it by a line that by definition has equal number of hairs on each side then the answer to the above question becomes "Of Course it is".
|
Effect size as the hypothesis for significance testing
A lot of this comes down to what question you are actually asking, how you design your study, and even what you mean by equal.
I ran accros an interesting little insert in the British Medical Journal
|
6,539
|
Effect size as the hypothesis for significance testing
|
From an organisational perspective, be it government with policy options or a company looking to roll out a new process/product, the use of a simple cost-benefit analysis can help too. I have argued in the past that (ignoring political reasons) given the known cost of a new initiative, what is the break even point for numbers of people who must be affected positively by that initiative? For example, if the new initiative is to get more unemployed people into work, and the initiative costs $100,000, does it achieve a reduction in unemployment transfers of at least $100,000? If not, then the effect of the initiative is not practically significant.
For health outcomes, the value of a statistical life takes on importance. This is because health benefits are accrued over a lifetime (and therefore the benefits are adjusted downwards in value based on a discount rate). So then instead of statistical significance, one gets arguments over how to estimate the value of a statistical life, and what discount rate should apply.
|
Effect size as the hypothesis for significance testing
|
From an organisational perspective, be it government with policy options or a company looking to roll out a new process/product, the use of a simple cost-benefit analysis can help too. I have argued i
|
Effect size as the hypothesis for significance testing
From an organisational perspective, be it government with policy options or a company looking to roll out a new process/product, the use of a simple cost-benefit analysis can help too. I have argued in the past that (ignoring political reasons) given the known cost of a new initiative, what is the break even point for numbers of people who must be affected positively by that initiative? For example, if the new initiative is to get more unemployed people into work, and the initiative costs $100,000, does it achieve a reduction in unemployment transfers of at least $100,000? If not, then the effect of the initiative is not practically significant.
For health outcomes, the value of a statistical life takes on importance. This is because health benefits are accrued over a lifetime (and therefore the benefits are adjusted downwards in value based on a discount rate). So then instead of statistical significance, one gets arguments over how to estimate the value of a statistical life, and what discount rate should apply.
|
Effect size as the hypothesis for significance testing
From an organisational perspective, be it government with policy options or a company looking to roll out a new process/product, the use of a simple cost-benefit analysis can help too. I have argued i
|
6,540
|
What is the intuition behind the formula for conditional probability?
|
A good intuition is that we are now in the universe in which B occurred, the full circle. Of that circle, how much is also A?
This intuitive explanation was offered in a class by Marc Herman
https://people.math.rochester.edu/faculty/herman/
|
What is the intuition behind the formula for conditional probability?
|
A good intuition is that we are now in the universe in which B occurred, the full circle. Of that circle, how much is also A?
This intuitive explanation was offered in a class by Marc Herman
https:/
|
What is the intuition behind the formula for conditional probability?
A good intuition is that we are now in the universe in which B occurred, the full circle. Of that circle, how much is also A?
This intuitive explanation was offered in a class by Marc Herman
https://people.math.rochester.edu/faculty/herman/
|
What is the intuition behind the formula for conditional probability?
A good intuition is that we are now in the universe in which B occurred, the full circle. Of that circle, how much is also A?
This intuitive explanation was offered in a class by Marc Herman
https:/
|
6,541
|
What is the intuition behind the formula for conditional probability?
|
I would think of it like this:
I take for granted that you understand the intuition until:
Given that B has occurred, the only way for A to occur is for the even to fall in the intersection of A & B.
and I am going to comment the second image you posted:
Imagine that the entire white rectangle is your sample space $\Omega$.
Assigning a probability to a set means that you are measuring in some sense that set. It is the same as if you measured the area of the rectangle but the probability is a different kind of measure that has specific properties (I won't say anything more about this).
You know that $P(\Omega) = 1$ and this is interpreted like this:
$\Omega$ represents all the events that could happen and something has to happen so we have 100% probability that something happens.
Analogously the set $A$ has a probability $P(A)$ that is proportional to the probability of the sample space $\Omega$. Graphically speaking you see that $A \subset \Omega$ hence the measure of $A$ (its probability $P(A)$) has to be lesser than $P(\Omega)$. The same reasoning is valid for the set $A \cap B$. This set can be measured and its measure is $P(A \cap B)$.
If now you are told that $B$ has happened you have to think as if $B$ were your "new" $\Omega$. If $B$ is your "new" $\Omega$ then you can be 100% sure that everything happens in the set $B$.
And what does that mean? It means that now, in the "new" contest $P(B \mid
B) =1$, and you have to rescale all the probability measures, taking into account that they have to be expressed in terms of the "new" sample space $B$. It is a simple proportion.
Your intuition is almost right when you say that:
the probability of P(A | B) would simply be equal to the probability of A intersection B
and the "almost" is due to the fact that now your sample space has changed (it is $B$ now) and you want to rescale $P(A \cap B)$ accordingly.
$P(A \mid B)$ is your $P(A \cap B)$ in the new world where the sample space is now $B$. In words you would say it like this (and please try to visualize it on the image with the sets):
In the new world the ratio between the measure of $B$ and the measure of $A\cap B$ must be the the same as the ratio between the measure of $\Omega$ and the measure of $A \mid B$
Lastly translate this in mathematical language (a simple proportion):
$$P(B):P(A \cap B) = P(\Omega):P(A \mid B)$$
and since $P(\Omega)=1$ it follows that:
$$P(A \mid B)= P(A \cap B):P(B)$$
|
What is the intuition behind the formula for conditional probability?
|
I would think of it like this:
I take for granted that you understand the intuition until:
Given that B has occurred, the only way for A to occur is for the even to fall in the intersection of A & B.
|
What is the intuition behind the formula for conditional probability?
I would think of it like this:
I take for granted that you understand the intuition until:
Given that B has occurred, the only way for A to occur is for the even to fall in the intersection of A & B.
and I am going to comment the second image you posted:
Imagine that the entire white rectangle is your sample space $\Omega$.
Assigning a probability to a set means that you are measuring in some sense that set. It is the same as if you measured the area of the rectangle but the probability is a different kind of measure that has specific properties (I won't say anything more about this).
You know that $P(\Omega) = 1$ and this is interpreted like this:
$\Omega$ represents all the events that could happen and something has to happen so we have 100% probability that something happens.
Analogously the set $A$ has a probability $P(A)$ that is proportional to the probability of the sample space $\Omega$. Graphically speaking you see that $A \subset \Omega$ hence the measure of $A$ (its probability $P(A)$) has to be lesser than $P(\Omega)$. The same reasoning is valid for the set $A \cap B$. This set can be measured and its measure is $P(A \cap B)$.
If now you are told that $B$ has happened you have to think as if $B$ were your "new" $\Omega$. If $B$ is your "new" $\Omega$ then you can be 100% sure that everything happens in the set $B$.
And what does that mean? It means that now, in the "new" contest $P(B \mid
B) =1$, and you have to rescale all the probability measures, taking into account that they have to be expressed in terms of the "new" sample space $B$. It is a simple proportion.
Your intuition is almost right when you say that:
the probability of P(A | B) would simply be equal to the probability of A intersection B
and the "almost" is due to the fact that now your sample space has changed (it is $B$ now) and you want to rescale $P(A \cap B)$ accordingly.
$P(A \mid B)$ is your $P(A \cap B)$ in the new world where the sample space is now $B$. In words you would say it like this (and please try to visualize it on the image with the sets):
In the new world the ratio between the measure of $B$ and the measure of $A\cap B$ must be the the same as the ratio between the measure of $\Omega$ and the measure of $A \mid B$
Lastly translate this in mathematical language (a simple proportion):
$$P(B):P(A \cap B) = P(\Omega):P(A \mid B)$$
and since $P(\Omega)=1$ it follows that:
$$P(A \mid B)= P(A \cap B):P(B)$$
|
What is the intuition behind the formula for conditional probability?
I would think of it like this:
I take for granted that you understand the intuition until:
Given that B has occurred, the only way for A to occur is for the even to fall in the intersection of A & B.
|
6,542
|
What is the intuition behind the formula for conditional probability?
|
You'll see intuition easily thinking about the following problem.
Suppose, you have 10 balls: 6 Black and 4 red. Of Black balls 3 are Awesome and of red balls only 1 is Awesome. How likely it is that a Black ball is also Awesome?
The answer is very easy: it's 50%, because we have 3 Awesome Black balls out of total 6 Black balls.
This is how you map probabilities to our problem:
3 balls that are Black AND Awesome correspond to $P(A \cap B)$
6 balls that are Black correspond to $P(B)$
probability that a ball is Awesome when we KNOW that it is Black: $P(A\mid B)$
|
What is the intuition behind the formula for conditional probability?
|
You'll see intuition easily thinking about the following problem.
Suppose, you have 10 balls: 6 Black and 4 red. Of Black balls 3 are Awesome and of red balls only 1 is Awesome. How likely it is that
|
What is the intuition behind the formula for conditional probability?
You'll see intuition easily thinking about the following problem.
Suppose, you have 10 balls: 6 Black and 4 red. Of Black balls 3 are Awesome and of red balls only 1 is Awesome. How likely it is that a Black ball is also Awesome?
The answer is very easy: it's 50%, because we have 3 Awesome Black balls out of total 6 Black balls.
This is how you map probabilities to our problem:
3 balls that are Black AND Awesome correspond to $P(A \cap B)$
6 balls that are Black correspond to $P(B)$
probability that a ball is Awesome when we KNOW that it is Black: $P(A\mid B)$
|
What is the intuition behind the formula for conditional probability?
You'll see intuition easily thinking about the following problem.
Suppose, you have 10 balls: 6 Black and 4 red. Of Black balls 3 are Awesome and of red balls only 1 is Awesome. How likely it is that
|
6,543
|
What is the intuition behind the formula for conditional probability?
|
For a basic intuition of the conditional probability formula, I always like using a two way table. Let's say there are 150 students in a yeargroup, of whom 80 are female and 70 male, each of whom must study exactly one language course. The two-way table of students taking different courses is:
| French German Italian | Total
-------- --------------------------- -------
Male | 30 20 20 | 70
Female | 25 15 40 | 80
-------- --------------------------- -------
Total | 55 35 60 | 150
Given that a student takes the Italian course, what is the probability they are female? Well the Italian course has 60 students, of whom 40 are females studying Italian, so the probability must be:
$$P(\text{F|Italian})=\frac{n(\text{F} \cap \text{Italian})}{n(\text{Italian})}=\frac{40}{60}=\frac{2}{3}$$
where $n(A)$ is the cardinality of the set $A$, i.e. the number of items it contains. Note that we needed to use $n(\text{F} \cap \text{Italian})$ in the numerator and not just $n(\text{F})$, because the latter would have included all 80 females, including the other 40 who do not study Italian.
But if the question were flipped around, what is the probability that a student takes the Italian course, given that they are female? Then 40 of the 80 female students take the Italian course, so we have:
$$P(\text{Italian|F})=\frac{n(\text{Italian} \cap \text{F})}{n(\text{F})}=\frac{40}{80}=\frac{1}{2}$$
I hope this provides intuition for why
$$P(A|B)=\frac{n(A \cap B)}{n(B)}$$
Understanding why the fraction can be written with probabilities instead of cardinalities is a matter of equivalent fractions. For example, let us return to the probability a student is female given that they are studying Italian. There are 150 students in total, so the probability that a student is female and studies Italian is 40/150 (this is a "joint" probability) and the probability a student studies Italian is 60/150 (this is a "marginal" probability). Note that dividing the joint probability by the marginal probability gives:
$$\frac{P(\text{F} \cap \text{Italian})}{P(\text{Italian})}=\frac{40/150}{60/150}=\frac{40}{60}=\frac{n(\text{F} \cap \text{Italian})}{n(\text{Italian})}=P(\text{F|Italian})$$
(To see that the fractions are equivalent, multiplying numerator and denominator by 150 removes the "/150" in each.)
More generally, if your sampling space $\Omega$ has cardinality $n(\Omega)$ — in this example the cardinality was 150 — we find that
$$P(A|B)=\frac{n(A \cap B)}{n(B)}=\frac{n(A \cap B)/n(\Omega)}{n(B)/n(\Omega)}=\frac{P(A \cap B)}{P(B)}$$
|
What is the intuition behind the formula for conditional probability?
|
For a basic intuition of the conditional probability formula, I always like using a two way table. Let's say there are 150 students in a yeargroup, of whom 80 are female and 70 male, each of whom must
|
What is the intuition behind the formula for conditional probability?
For a basic intuition of the conditional probability formula, I always like using a two way table. Let's say there are 150 students in a yeargroup, of whom 80 are female and 70 male, each of whom must study exactly one language course. The two-way table of students taking different courses is:
| French German Italian | Total
-------- --------------------------- -------
Male | 30 20 20 | 70
Female | 25 15 40 | 80
-------- --------------------------- -------
Total | 55 35 60 | 150
Given that a student takes the Italian course, what is the probability they are female? Well the Italian course has 60 students, of whom 40 are females studying Italian, so the probability must be:
$$P(\text{F|Italian})=\frac{n(\text{F} \cap \text{Italian})}{n(\text{Italian})}=\frac{40}{60}=\frac{2}{3}$$
where $n(A)$ is the cardinality of the set $A$, i.e. the number of items it contains. Note that we needed to use $n(\text{F} \cap \text{Italian})$ in the numerator and not just $n(\text{F})$, because the latter would have included all 80 females, including the other 40 who do not study Italian.
But if the question were flipped around, what is the probability that a student takes the Italian course, given that they are female? Then 40 of the 80 female students take the Italian course, so we have:
$$P(\text{Italian|F})=\frac{n(\text{Italian} \cap \text{F})}{n(\text{F})}=\frac{40}{80}=\frac{1}{2}$$
I hope this provides intuition for why
$$P(A|B)=\frac{n(A \cap B)}{n(B)}$$
Understanding why the fraction can be written with probabilities instead of cardinalities is a matter of equivalent fractions. For example, let us return to the probability a student is female given that they are studying Italian. There are 150 students in total, so the probability that a student is female and studies Italian is 40/150 (this is a "joint" probability) and the probability a student studies Italian is 60/150 (this is a "marginal" probability). Note that dividing the joint probability by the marginal probability gives:
$$\frac{P(\text{F} \cap \text{Italian})}{P(\text{Italian})}=\frac{40/150}{60/150}=\frac{40}{60}=\frac{n(\text{F} \cap \text{Italian})}{n(\text{Italian})}=P(\text{F|Italian})$$
(To see that the fractions are equivalent, multiplying numerator and denominator by 150 removes the "/150" in each.)
More generally, if your sampling space $\Omega$ has cardinality $n(\Omega)$ — in this example the cardinality was 150 — we find that
$$P(A|B)=\frac{n(A \cap B)}{n(B)}=\frac{n(A \cap B)/n(\Omega)}{n(B)/n(\Omega)}=\frac{P(A \cap B)}{P(B)}$$
|
What is the intuition behind the formula for conditional probability?
For a basic intuition of the conditional probability formula, I always like using a two way table. Let's say there are 150 students in a yeargroup, of whom 80 are female and 70 male, each of whom must
|
6,544
|
What is the intuition behind the formula for conditional probability?
|
I would reverse the logic. The probability that both $A$ and $B$ is either:
The probability $B$ happened, and that given that $A$ happened.
Same but reverse roles for $A$ and $B$
This will give you
$p(A\cap B)=p(B)p(A\mid B)$
If you're looking for a negative to your suggestion, it's while it's true the probability of $A$ given $B$ is contained in the probability of the product, the space you're rolling the dice in is smaller than your original probability space - you know for sure you're "in" $B$, hence you divide by the size of the new space.
|
What is the intuition behind the formula for conditional probability?
|
I would reverse the logic. The probability that both $A$ and $B$ is either:
The probability $B$ happened, and that given that $A$ happened.
Same but reverse roles for $A$ and $B$
This will give y
|
What is the intuition behind the formula for conditional probability?
I would reverse the logic. The probability that both $A$ and $B$ is either:
The probability $B$ happened, and that given that $A$ happened.
Same but reverse roles for $A$ and $B$
This will give you
$p(A\cap B)=p(B)p(A\mid B)$
If you're looking for a negative to your suggestion, it's while it's true the probability of $A$ given $B$ is contained in the probability of the product, the space you're rolling the dice in is smaller than your original probability space - you know for sure you're "in" $B$, hence you divide by the size of the new space.
|
What is the intuition behind the formula for conditional probability?
I would reverse the logic. The probability that both $A$ and $B$ is either:
The probability $B$ happened, and that given that $A$ happened.
Same but reverse roles for $A$ and $B$
This will give y
|
6,545
|
What is the intuition behind the formula for conditional probability?
|
The Venn diagram doesn't represent probability, it represents the measure of subsets of the event space. A probability is the ratio between two measures; the probability of X is the size of "everything that constitutes X" divided the size of "all the events being considered". Any time you're calculating a probability, you need both a "success space" and a "population space". You can't calculated a probability based just on "how big" the success space is. For instance, the probability of rolling a seven with two dice is the number of ways of rolling a seven divided by the total number of ways of rolling two dice. Just knowing the number of ways of rolling a seven is not enough to calculate the probability. P(A|B) is the ratio of the measure of the "both A and B happen" space and the measure of the "B happens" space. That's what the "|" means: it means "make what comes after this the population space".
|
What is the intuition behind the formula for conditional probability?
|
The Venn diagram doesn't represent probability, it represents the measure of subsets of the event space. A probability is the ratio between two measures; the probability of X is the size of "everythin
|
What is the intuition behind the formula for conditional probability?
The Venn diagram doesn't represent probability, it represents the measure of subsets of the event space. A probability is the ratio between two measures; the probability of X is the size of "everything that constitutes X" divided the size of "all the events being considered". Any time you're calculating a probability, you need both a "success space" and a "population space". You can't calculated a probability based just on "how big" the success space is. For instance, the probability of rolling a seven with two dice is the number of ways of rolling a seven divided by the total number of ways of rolling two dice. Just knowing the number of ways of rolling a seven is not enough to calculate the probability. P(A|B) is the ratio of the measure of the "both A and B happen" space and the measure of the "B happens" space. That's what the "|" means: it means "make what comes after this the population space".
|
What is the intuition behind the formula for conditional probability?
The Venn diagram doesn't represent probability, it represents the measure of subsets of the event space. A probability is the ratio between two measures; the probability of X is the size of "everythin
|
6,546
|
What is the intuition behind the formula for conditional probability?
|
I think the best way to think about this is drawing step-by-step paths.
Let's describe Event B as rolling a $4$ on a fair die - this can be easily shown to have probability $\frac{1}{6}$.
Now let's describe Event A as drawing an Ace from a standard 52-card deck of cards - this can be easily shown to have probability $\frac{1}{13}$.
Let's now run an experiment where we roll a die and then pick a card. So $P\left(A \middle| B\right)$ would be the probability that we draw an Ace, given that we have already rolled a $4$. If you look at the image, this would be the $\frac{1}{6}$ path (go up) and then the $\frac{1}{13}$ path (go up again).
Intuitively, the total probability space is what we have already been given: rolling the $4$. We can ignore the $\frac{1}{13}$ and $\frac{12}{13}$ the initial down path leads to, since it was GIVEN that we rolled a $4$. By law of multiplication, our total space is then $\left(\frac{1}{6}{\times}\frac{1}{13}\right) + \left(\frac{1}{6}{\times}\frac{12}{13}\right)$.
Now what's the probability we drew an Ace, GIVEN that we rolled a $4$? The answer by using the path is $\left(\frac{1}{6} {\times} \frac{1}{13} \right)$, which we then need to divide by the total space. So we get$$
P\left(A \middle| B\right) = \frac{\frac{1}{6} {\times} \frac{1}{13}}{\left(\frac{1}{6} {\times} \frac{1}{13}\right) + \left(\frac{1}{6} {\times} \frac{12}{13}\right)}.
$$
|
What is the intuition behind the formula for conditional probability?
|
I think the best way to think about this is drawing step-by-step paths.
Let's describe Event B as rolling a $4$ on a fair die - this can be easily shown to have probability $\frac{1}{6}$.
Now let's de
|
What is the intuition behind the formula for conditional probability?
I think the best way to think about this is drawing step-by-step paths.
Let's describe Event B as rolling a $4$ on a fair die - this can be easily shown to have probability $\frac{1}{6}$.
Now let's describe Event A as drawing an Ace from a standard 52-card deck of cards - this can be easily shown to have probability $\frac{1}{13}$.
Let's now run an experiment where we roll a die and then pick a card. So $P\left(A \middle| B\right)$ would be the probability that we draw an Ace, given that we have already rolled a $4$. If you look at the image, this would be the $\frac{1}{6}$ path (go up) and then the $\frac{1}{13}$ path (go up again).
Intuitively, the total probability space is what we have already been given: rolling the $4$. We can ignore the $\frac{1}{13}$ and $\frac{12}{13}$ the initial down path leads to, since it was GIVEN that we rolled a $4$. By law of multiplication, our total space is then $\left(\frac{1}{6}{\times}\frac{1}{13}\right) + \left(\frac{1}{6}{\times}\frac{12}{13}\right)$.
Now what's the probability we drew an Ace, GIVEN that we rolled a $4$? The answer by using the path is $\left(\frac{1}{6} {\times} \frac{1}{13} \right)$, which we then need to divide by the total space. So we get$$
P\left(A \middle| B\right) = \frac{\frac{1}{6} {\times} \frac{1}{13}}{\left(\frac{1}{6} {\times} \frac{1}{13}\right) + \left(\frac{1}{6} {\times} \frac{12}{13}\right)}.
$$
|
What is the intuition behind the formula for conditional probability?
I think the best way to think about this is drawing step-by-step paths.
Let's describe Event B as rolling a $4$ on a fair die - this can be easily shown to have probability $\frac{1}{6}$.
Now let's de
|
6,547
|
What is the intuition behind the formula for conditional probability?
|
Think of it on terms of counts. Marginal probability is how many times A occurred divided by sample size. Joint probability of A and B is how many times A occurred together with B divided by sample size. Conditional probability of A given B is how many times A occurred together with B divided by how many times B occurred, i.e. only the A's "within" B's.
You can find nice visual illustration on this blog, that shows it using Lego blocks.
|
What is the intuition behind the formula for conditional probability?
|
Think of it on terms of counts. Marginal probability is how many times A occurred divided by sample size. Joint probability of A and B is how many times A occurred together with B divided by sample si
|
What is the intuition behind the formula for conditional probability?
Think of it on terms of counts. Marginal probability is how many times A occurred divided by sample size. Joint probability of A and B is how many times A occurred together with B divided by sample size. Conditional probability of A given B is how many times A occurred together with B divided by how many times B occurred, i.e. only the A's "within" B's.
You can find nice visual illustration on this blog, that shows it using Lego blocks.
|
What is the intuition behind the formula for conditional probability?
Think of it on terms of counts. Marginal probability is how many times A occurred divided by sample size. Joint probability of A and B is how many times A occurred together with B divided by sample si
|
6,548
|
What is the intuition behind the formula for conditional probability?
|
At the time of writing there is about 10 answers which seem to all miss the most important point: you are essentially right.
In that case, wouldn't the probability of P(A | B) simply be equal to the probability of A intersection B, since that's the only way the event could happen?
This is definitely true. This explains why the quantity we to define $P(A\vert B)$ is actually $P(A \cap B)$ rescaled.
What am I missing?
You are missing that the probability of B being satisfied given that B is satisfied should be 1 since this is quite a certain event, and not $P(B\cap B) = P(B)$ which can well be less than 1. Dividing by $P(B)$ makes the conditional probability of B given B equal to 1, as expected. Actually this is even better and makes the map $A \mapsto P(A\vert B)$ a probability – so a conditional probability is actually a probability.
|
What is the intuition behind the formula for conditional probability?
|
At the time of writing there is about 10 answers which seem to all miss the most important point: you are essentially right.
In that case, wouldn't the probability of P(A | B) simply be equal to the
|
What is the intuition behind the formula for conditional probability?
At the time of writing there is about 10 answers which seem to all miss the most important point: you are essentially right.
In that case, wouldn't the probability of P(A | B) simply be equal to the probability of A intersection B, since that's the only way the event could happen?
This is definitely true. This explains why the quantity we to define $P(A\vert B)$ is actually $P(A \cap B)$ rescaled.
What am I missing?
You are missing that the probability of B being satisfied given that B is satisfied should be 1 since this is quite a certain event, and not $P(B\cap B) = P(B)$ which can well be less than 1. Dividing by $P(B)$ makes the conditional probability of B given B equal to 1, as expected. Actually this is even better and makes the map $A \mapsto P(A\vert B)$ a probability – so a conditional probability is actually a probability.
|
What is the intuition behind the formula for conditional probability?
At the time of writing there is about 10 answers which seem to all miss the most important point: you are essentially right.
In that case, wouldn't the probability of P(A | B) simply be equal to the
|
6,549
|
What is the intuition behind the formula for conditional probability?
|
I feel it is more intuitive when we have a concrete data to estimate the probabilities.
Let's use mtcars data as an example, the data looks like this (we only use number of cylinders and transmission type.)
> mtcars[,c("am","cyl")]
am cyl
Mazda RX4 1 6
Mazda RX4 Wag 1 6
Datsun 710 1 4
Hornet 4 Drive 0 6
...
...
Ford Pantera L 1 8
Ferrari Dino 1 6
Maserati Bora 1 8
Volvo 142E 1 4
We can calculate the joint distribution on two variables by doing a cross table:
> prop.table(table(mtcars$cyl,mtcars$am))
0 1
4 0.09375 0.25000
6 0.12500 0.09375
8 0.37500 0.06250
The joint probability means we want to consider two variables at the same time. For example, we will ask how many cars are 4 cylinder and manual transmission.
Now, we come to conditional probability. I found the most intuitive way to explain conditional probability is using the term filtering on data.
Suppose we want to get $P(am=1|cyl=4)$, we will do following estimations:
> cyl_4_cars=subset(mtcars, cyl==4)
> prop.table(table(cyl_4_cars$am))
0 1
0.2727273 0.7272727
This means, we only care cars have 4 cylinder. So we filter data on that. After filtering, we check how many of them are manual transmission.
You can compare conditional this with joint I mentioned earlier to feel the differences.
|
What is the intuition behind the formula for conditional probability?
|
I feel it is more intuitive when we have a concrete data to estimate the probabilities.
Let's use mtcars data as an example, the data looks like this (we only use number of cylinders and transmission
|
What is the intuition behind the formula for conditional probability?
I feel it is more intuitive when we have a concrete data to estimate the probabilities.
Let's use mtcars data as an example, the data looks like this (we only use number of cylinders and transmission type.)
> mtcars[,c("am","cyl")]
am cyl
Mazda RX4 1 6
Mazda RX4 Wag 1 6
Datsun 710 1 4
Hornet 4 Drive 0 6
...
...
Ford Pantera L 1 8
Ferrari Dino 1 6
Maserati Bora 1 8
Volvo 142E 1 4
We can calculate the joint distribution on two variables by doing a cross table:
> prop.table(table(mtcars$cyl,mtcars$am))
0 1
4 0.09375 0.25000
6 0.12500 0.09375
8 0.37500 0.06250
The joint probability means we want to consider two variables at the same time. For example, we will ask how many cars are 4 cylinder and manual transmission.
Now, we come to conditional probability. I found the most intuitive way to explain conditional probability is using the term filtering on data.
Suppose we want to get $P(am=1|cyl=4)$, we will do following estimations:
> cyl_4_cars=subset(mtcars, cyl==4)
> prop.table(table(cyl_4_cars$am))
0 1
0.2727273 0.7272727
This means, we only care cars have 4 cylinder. So we filter data on that. After filtering, we check how many of them are manual transmission.
You can compare conditional this with joint I mentioned earlier to feel the differences.
|
What is the intuition behind the formula for conditional probability?
I feel it is more intuitive when we have a concrete data to estimate the probabilities.
Let's use mtcars data as an example, the data looks like this (we only use number of cylinders and transmission
|
6,550
|
What is the intuition behind the formula for conditional probability?
|
If A were a superset of B the probability that A happens is always 1 given that B happened, i.e. P(A|B) = 1. However, B itself may have a probability much smaller than 1.
Consider the following example:
given x is a natural number in 1..100,
A is 'x is an even number'
B is 'x is divisible by 10'
we then have:
P(A) is 0.5
P(B) is 0.1
If we know that x is divisible by 10 (i.e.x is in B) we know that it is also an even number (i.e. x is in A) so P(A|B) = 1.
From Bayes' rule we have:
$$
P(A|B) = \dfrac{P(A \cap B)}{P(B)}
$$
note that in our (special) case $P(A \cap B)$, i.e. the probability that x is both an even number and a number divisible by 10 is equal to the probability that x is a number divisible by 10. Therefore we have $P(A \cap B) = P(B)$ and plugging this back into Bayes' rule we get $P(A|B) = P(B) / P(B) = 1$.
For a non-degenerate example consider e.g. A is 'x is divisible by 7' and B is 'x is divisible by 3'. Then P(A|B) is equivalent to 'given that we know that x is divisible by 3 what is the probability that it is (also) divisible by 7 ?'. Or equivalently 'What fraction of the numbers 3, 6, ..., 99 are divisible by 7' ?
|
What is the intuition behind the formula for conditional probability?
|
If A were a superset of B the probability that A happens is always 1 given that B happened, i.e. P(A|B) = 1. However, B itself may have a probability much smaller than 1.
Consider the following exam
|
What is the intuition behind the formula for conditional probability?
If A were a superset of B the probability that A happens is always 1 given that B happened, i.e. P(A|B) = 1. However, B itself may have a probability much smaller than 1.
Consider the following example:
given x is a natural number in 1..100,
A is 'x is an even number'
B is 'x is divisible by 10'
we then have:
P(A) is 0.5
P(B) is 0.1
If we know that x is divisible by 10 (i.e.x is in B) we know that it is also an even number (i.e. x is in A) so P(A|B) = 1.
From Bayes' rule we have:
$$
P(A|B) = \dfrac{P(A \cap B)}{P(B)}
$$
note that in our (special) case $P(A \cap B)$, i.e. the probability that x is both an even number and a number divisible by 10 is equal to the probability that x is a number divisible by 10. Therefore we have $P(A \cap B) = P(B)$ and plugging this back into Bayes' rule we get $P(A|B) = P(B) / P(B) = 1$.
For a non-degenerate example consider e.g. A is 'x is divisible by 7' and B is 'x is divisible by 3'. Then P(A|B) is equivalent to 'given that we know that x is divisible by 3 what is the probability that it is (also) divisible by 7 ?'. Or equivalently 'What fraction of the numbers 3, 6, ..., 99 are divisible by 7' ?
|
What is the intuition behind the formula for conditional probability?
If A were a superset of B the probability that A happens is always 1 given that B happened, i.e. P(A|B) = 1. However, B itself may have a probability much smaller than 1.
Consider the following exam
|
6,551
|
What is the intuition behind the formula for conditional probability?
|
I think your initial statement may be a misunderstanding.
You wrote:
The formula for conditional probability of A happening, once B has happened is:
From your phrasing, it may sound as if there are 2 events "First B happened, and then we want to calculate the probability that A will happen".
This is not the case. (The following is valid whether there was a misunderstanding or not).
We have just 1 event, which is described by one of 4 possibilities:
neither $\text{A}$ nor $\text{B}$;
just $\text{A}$, not $\text{B}$;
just $\text{B}$, not $\text{A}$;
both $\text{A}$ and $\text{B}$.
Putting some example numbers on it, let's say$$
\begin{array}{ccccccc}
P\left(\text{A}\right) = 0.5, & &
P\left(\text{B}\right) = 0.5, & &
\text{and} & &
\text{A and B are independent}.
\end{array}
$$
It follows that$$
\begin{array}{ccccc}
P\left(\text{A and B}\right)=0.25 & & \text{and} & & P\left(\text{neither A nor B}\right)=0.25.
\end{array}
$$
Initially (with no knowledge of the event), we knew $P\left(\text{AB}\right) = 0.25$.
But once we know that $\text{B}$ has happened, we are in a different space. $P\left(\text{AB}\right)$ is half of $P\left(\text{B}\right)$ so the probability of $\text{A}$ given $\text{B}$, $P\left(\text{A} \middle| \text{B}\right)$, is $0.5$. It is not $0.25$, knowing that $\text{B}$ has happened.
|
What is the intuition behind the formula for conditional probability?
|
I think your initial statement may be a misunderstanding.
You wrote:
The formula for conditional probability of A happening, once B has happened is:
From your phrasing, it may sound as if there are
|
What is the intuition behind the formula for conditional probability?
I think your initial statement may be a misunderstanding.
You wrote:
The formula for conditional probability of A happening, once B has happened is:
From your phrasing, it may sound as if there are 2 events "First B happened, and then we want to calculate the probability that A will happen".
This is not the case. (The following is valid whether there was a misunderstanding or not).
We have just 1 event, which is described by one of 4 possibilities:
neither $\text{A}$ nor $\text{B}$;
just $\text{A}$, not $\text{B}$;
just $\text{B}$, not $\text{A}$;
both $\text{A}$ and $\text{B}$.
Putting some example numbers on it, let's say$$
\begin{array}{ccccccc}
P\left(\text{A}\right) = 0.5, & &
P\left(\text{B}\right) = 0.5, & &
\text{and} & &
\text{A and B are independent}.
\end{array}
$$
It follows that$$
\begin{array}{ccccc}
P\left(\text{A and B}\right)=0.25 & & \text{and} & & P\left(\text{neither A nor B}\right)=0.25.
\end{array}
$$
Initially (with no knowledge of the event), we knew $P\left(\text{AB}\right) = 0.25$.
But once we know that $\text{B}$ has happened, we are in a different space. $P\left(\text{AB}\right)$ is half of $P\left(\text{B}\right)$ so the probability of $\text{A}$ given $\text{B}$, $P\left(\text{A} \middle| \text{B}\right)$, is $0.5$. It is not $0.25$, knowing that $\text{B}$ has happened.
|
What is the intuition behind the formula for conditional probability?
I think your initial statement may be a misunderstanding.
You wrote:
The formula for conditional probability of A happening, once B has happened is:
From your phrasing, it may sound as if there are
|
6,552
|
What is the intuition behind the formula for conditional probability?
|
The conditioning probability is NOT equal to the probability of intersection. Here is an intuitive answer:
1) $P(B \mid A)$: "We know that $A$ happened. What is the probability that $B$ will happen?"
2: $P(A \cap B)$ : "We don't know if $A$ or $B$ did happen. What is the probability that both will happen?
The difference is that in the first one, we have extra information (we know that $A$ occurs first). In the second one we do not know anything.
Starting out with the probability of the second one, we can deduce the probability of the first one.
The event that both $A$ and $B$ will occur can happen in two ways:
1) The probability of $A$ AND the probability of $B$ given that $A$ happened.
2) The probability of $B$ AND the probability of $A$ given that $B$ happened.
It turns out that both situations are equally like to happen. (I cannot myself find out the intuitive reason). Thus we have to weight both scenarios with $0.5$
$P(A \cap B) = 1/2 * P(A \cap (B \mid A)) + 1/2*P(B \cap (A \mid B))$
Now use that $A$ and $B \mid A$ are independent and remember that both scenarios are equally likely to happen.
$P(A \cap B) = P(A) * P(B \mid A)$
Tadaaa... now isolate the probability of the conditioning!
btw. I would love if someone could explain why scenario 1 and 2 are equal. The key lies in there imo.
|
What is the intuition behind the formula for conditional probability?
|
The conditioning probability is NOT equal to the probability of intersection. Here is an intuitive answer:
1) $P(B \mid A)$: "We know that $A$ happened. What is the probability that $B$ will happen?"
|
What is the intuition behind the formula for conditional probability?
The conditioning probability is NOT equal to the probability of intersection. Here is an intuitive answer:
1) $P(B \mid A)$: "We know that $A$ happened. What is the probability that $B$ will happen?"
2: $P(A \cap B)$ : "We don't know if $A$ or $B$ did happen. What is the probability that both will happen?
The difference is that in the first one, we have extra information (we know that $A$ occurs first). In the second one we do not know anything.
Starting out with the probability of the second one, we can deduce the probability of the first one.
The event that both $A$ and $B$ will occur can happen in two ways:
1) The probability of $A$ AND the probability of $B$ given that $A$ happened.
2) The probability of $B$ AND the probability of $A$ given that $B$ happened.
It turns out that both situations are equally like to happen. (I cannot myself find out the intuitive reason). Thus we have to weight both scenarios with $0.5$
$P(A \cap B) = 1/2 * P(A \cap (B \mid A)) + 1/2*P(B \cap (A \mid B))$
Now use that $A$ and $B \mid A$ are independent and remember that both scenarios are equally likely to happen.
$P(A \cap B) = P(A) * P(B \mid A)$
Tadaaa... now isolate the probability of the conditioning!
btw. I would love if someone could explain why scenario 1 and 2 are equal. The key lies in there imo.
|
What is the intuition behind the formula for conditional probability?
The conditioning probability is NOT equal to the probability of intersection. Here is an intuitive answer:
1) $P(B \mid A)$: "We know that $A$ happened. What is the probability that $B$ will happen?"
|
6,553
|
What is the intuition behind the formula for conditional probability?
|
You could see P(A∩B)/P(B) as P(A∩B)/(1/x) where x is the average amount for event B, then simplify to x • P(A∩B), which means on average it will skip over events that aren’t B
|
What is the intuition behind the formula for conditional probability?
|
You could see P(A∩B)/P(B) as P(A∩B)/(1/x) where x is the average amount for event B, then simplify to x • P(A∩B), which means on average it will skip over events that aren’t B
|
What is the intuition behind the formula for conditional probability?
You could see P(A∩B)/P(B) as P(A∩B)/(1/x) where x is the average amount for event B, then simplify to x • P(A∩B), which means on average it will skip over events that aren’t B
|
What is the intuition behind the formula for conditional probability?
You could see P(A∩B)/P(B) as P(A∩B)/(1/x) where x is the average amount for event B, then simplify to x • P(A∩B), which means on average it will skip over events that aren’t B
|
6,554
|
What is the intuition behind the formula for conditional probability?
|
The way I think about it is this:
$$P(A|B)=\frac{P(A \cap B)}{P(B)}$$
The key is to understand what each term means and what division by $P(B)$ means in this case (it's a little more confusing because we are dividing by a number which is $\le 1$Also, Do not think about this using a Venn diagram. As far as I know, this formula has no clear meaning that can be visualized with a Venn Diagram, and as another answer mentioned, Venn diagrams are mostly used to describe sets and intersections, not probabilities.
Let's start with the numerator.
$$P(A\cap B)$$
At first I was also confused as to why this is not the entire formula for conditional probability because both $P(A|B)$ and $P(A \cap B)$ describe probabilities in which both $A$ and $B$ occur. But things become clear when you consider more events(i.e. C, D, E etc). Now when you say $P(A \cap B)$, you consider the entire sample space when what you need is $A$ with some relation to only $B$, disregarding other events! What we need from conditional probability is to help us establish a "What is the likeliness of $A$ considering $B$ has occured." relation between two events. This leads us to the role of the denominator.
To me, $P(B)$ was the confusing part about the formula, so let's consider the $P(B)$ in the formula as a seperate term $\frac{1}{P(B)}$. If we consider $P(B)$ to be the chance obtaining 1 from a six-sided die, then $$P(B)=\frac{1}{6}\implies \frac{1}{P(B)}=6$$This is the same as the average number of die rolls that we need to roll a one. In other words, to "probabilistically guarantee" an event $B$, we repeat the experiment $\frac{1}{P(B)}$ times ($P(B)\cdot \frac{1}{P(B)}=1$).
Therefore,
$$P(A \cap B)\cdot \frac{1}{P(B)}$$ Is the same as saying give me the probability of both $A$ and $B$ occuring assuming $B$ is guaranteed.
NOTE: I am an undergrad student currently taking an Introduction to Probability course. If I commit a Math or Statistics crime, please forgive me. Also disregard the fact that I am answering this question 5 years later.
|
What is the intuition behind the formula for conditional probability?
|
The way I think about it is this:
$$P(A|B)=\frac{P(A \cap B)}{P(B)}$$
The key is to understand what each term means and what division by $P(B)$ means in this case (it's a little more confusing because
|
What is the intuition behind the formula for conditional probability?
The way I think about it is this:
$$P(A|B)=\frac{P(A \cap B)}{P(B)}$$
The key is to understand what each term means and what division by $P(B)$ means in this case (it's a little more confusing because we are dividing by a number which is $\le 1$Also, Do not think about this using a Venn diagram. As far as I know, this formula has no clear meaning that can be visualized with a Venn Diagram, and as another answer mentioned, Venn diagrams are mostly used to describe sets and intersections, not probabilities.
Let's start with the numerator.
$$P(A\cap B)$$
At first I was also confused as to why this is not the entire formula for conditional probability because both $P(A|B)$ and $P(A \cap B)$ describe probabilities in which both $A$ and $B$ occur. But things become clear when you consider more events(i.e. C, D, E etc). Now when you say $P(A \cap B)$, you consider the entire sample space when what you need is $A$ with some relation to only $B$, disregarding other events! What we need from conditional probability is to help us establish a "What is the likeliness of $A$ considering $B$ has occured." relation between two events. This leads us to the role of the denominator.
To me, $P(B)$ was the confusing part about the formula, so let's consider the $P(B)$ in the formula as a seperate term $\frac{1}{P(B)}$. If we consider $P(B)$ to be the chance obtaining 1 from a six-sided die, then $$P(B)=\frac{1}{6}\implies \frac{1}{P(B)}=6$$This is the same as the average number of die rolls that we need to roll a one. In other words, to "probabilistically guarantee" an event $B$, we repeat the experiment $\frac{1}{P(B)}$ times ($P(B)\cdot \frac{1}{P(B)}=1$).
Therefore,
$$P(A \cap B)\cdot \frac{1}{P(B)}$$ Is the same as saying give me the probability of both $A$ and $B$ occuring assuming $B$ is guaranteed.
NOTE: I am an undergrad student currently taking an Introduction to Probability course. If I commit a Math or Statistics crime, please forgive me. Also disregard the fact that I am answering this question 5 years later.
|
What is the intuition behind the formula for conditional probability?
The way I think about it is this:
$$P(A|B)=\frac{P(A \cap B)}{P(B)}$$
The key is to understand what each term means and what division by $P(B)$ means in this case (it's a little more confusing because
|
6,555
|
What is the intuition behind the formula for conditional probability?
|
Let add a bit of philosophy and heuristic.
The question ends at : wouldn't the probability of P(A|B) simply be equal to the probability of A intersection B.
In line with proof by contradiction;
Let say Answer to your question is YES.
Then, how should we calculate p(A|B).
Is this equal to n(A|B) / n(B) ---- (1)
Wait,
From the diagram without loss of generality,
the entity (A|B) can be considered as disjoint set,
(especially when the interest is to calculate the probability of (A|B) entity only).
Then can we say p(A|B) = n(A|B) / n(A + B- A∩B) ---- (2)
Or even p(A|B) = n(A|B) / n(Rectangle) ---- (3)
Or even p(A|B) = n(A|B) / n(Rectangle + anything other than Rectangle) ----(4)
So among (1), (2), (3), and (4) which one is correct?
Possibly an anchor for the denominator is missing here in the whole argument.
So intuitively that denominator is justified when we anchor it to n(B).
A better substitute for the denominator could be Set B intuitively which will act as an anchor.
And the inclusion of set B only fix the calculation pf p(A|B) by dividing p(B) with p(A∩B).
|
What is the intuition behind the formula for conditional probability?
|
Let add a bit of philosophy and heuristic.
The question ends at : wouldn't the probability of P(A|B) simply be equal to the probability of A intersection B.
In line with proof by contradiction;
Let
|
What is the intuition behind the formula for conditional probability?
Let add a bit of philosophy and heuristic.
The question ends at : wouldn't the probability of P(A|B) simply be equal to the probability of A intersection B.
In line with proof by contradiction;
Let say Answer to your question is YES.
Then, how should we calculate p(A|B).
Is this equal to n(A|B) / n(B) ---- (1)
Wait,
From the diagram without loss of generality,
the entity (A|B) can be considered as disjoint set,
(especially when the interest is to calculate the probability of (A|B) entity only).
Then can we say p(A|B) = n(A|B) / n(A + B- A∩B) ---- (2)
Or even p(A|B) = n(A|B) / n(Rectangle) ---- (3)
Or even p(A|B) = n(A|B) / n(Rectangle + anything other than Rectangle) ----(4)
So among (1), (2), (3), and (4) which one is correct?
Possibly an anchor for the denominator is missing here in the whole argument.
So intuitively that denominator is justified when we anchor it to n(B).
A better substitute for the denominator could be Set B intuitively which will act as an anchor.
And the inclusion of set B only fix the calculation pf p(A|B) by dividing p(B) with p(A∩B).
|
What is the intuition behind the formula for conditional probability?
Let add a bit of philosophy and heuristic.
The question ends at : wouldn't the probability of P(A|B) simply be equal to the probability of A intersection B.
In line with proof by contradiction;
Let
|
6,556
|
How is the cost function from Logistic Regression differentiated
|
Adapted from the notes in the course, which I don't see available (including this derivation) outside the notes contributed by students within the page of Andrew Ng's Coursera Machine Learning course.
In what follows, the superscript $(i)$ denotes individual measurements or training "examples."
$\small
\frac{\partial J(\theta)}{\partial \theta_j} =
\frac{\partial}{\partial \theta_j} \,\frac{-1}{m}\sum_{i=1}^m
\left[ y^{(i)}\log\left(h_\theta \left(x^{(i)}\right)\right) +
(1 -y^{(i)})\log\left(1-h_\theta \left(x^{(i)}\right)\right)\right]
\\[2ex]\small\underset{\text{linearity}}= \,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{\partial}{\partial \theta_j}\log\left(h_\theta \left(x^{(i)}\right)\right) +
(1 -y^{(i)})\frac{\partial}{\partial \theta_j}\log\left(1-h_\theta \left(x^{(i)}\right)\right)
\right]
\\[2ex]\Tiny\underset{\text{chain rule}}= \,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{\frac{\partial}{\partial \theta_j}h_\theta \left(x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} +
(1 -y^{(i)})\frac{\frac{\partial}{\partial \theta_j}\left(1-h_\theta \left(x^{(i)}\right)\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\small\underset{h_\theta(x)=\sigma\left(\theta^\top x\right)}=\,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{\frac{\partial}{\partial \theta_j}\sigma\left(\theta^\top x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} +
(1 -y^{(i)})\frac{\frac{\partial}{\partial \theta_j}\left(1-\sigma\left(\theta^\top x^{(i)}\right)\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\Tiny\underset{\sigma'}=\frac{-1}{m}\,\sum_{i=1}^m
\left[ y^{(i)}\,
\frac{\sigma\left(\theta^\top x^{(i)}\right)\left(1-\sigma\left(\theta^\top x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} -
(1 -y^{(i)})\,\frac{\sigma\left(\theta^\top x^{(i)}\right)\left(1-\sigma\left(\theta^\top x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\small\underset{\sigma\left(\theta^\top x\right)=h_\theta(x)}= \,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{h_\theta\left( x^{(i)}\right)\left(1-h_\theta\left( x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} -
(1 -y^{(i)})\frac{h_\theta\left( x^{(i)}\right)\left(1-h_\theta\left(x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left( \theta^\top x^{(i)}\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\small\underset{\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)=x_j^{(i)}}=\,\frac{-1}{m}\,\sum_{i=1}^m \left[y^{(i)}\left(1-h_\theta\left(x^{(i)}\right)\right)x_j^{(i)}-
\left(1-y^{i}\right)\,h_\theta\left(x^{(i)}\right)x_j^{(i)}
\right]
\\[2ex]\small\underset{\text{distribute}}=\,\frac{-1}{m}\,\sum_{i=1}^m \left[y^{i}-y^{i}h_\theta\left(x^{(i)}\right)-
h_\theta\left(x^{(i)}\right)+y^{(i)}h_\theta\left(x^{(i)}\right)
\right]\,x_j^{(i)}
\\[2ex]\small\underset{\text{cancel}}=\,\frac{-1}{m}\,\sum_{i=1}^m \left[y^{(i)}-h_\theta\left(x^{(i)}\right)\right]\,x_j^{(i)} \\[2ex]\small=\frac{1}{m}\sum_{i=1}^m\left[h_\theta\left(x^{(i)}\right)-y^{(i)}\right]\,x_j^{(i)}
$
The derivative of the sigmoid function is
$\Tiny\begin{align}\frac{d}{dx}\sigma(x)&=\frac{d}{dx}\left(\frac{1}{1+e^{-x}}\right)\\[2ex]
&=\frac{-(1+e^{-x})'}{(1+e^{-x})^2}\\[2ex]
&=\frac{e^{-x}}{(1+e^{-x})^2}\\[2ex]
&=\left(\frac{1}{1+e^{-x}}\right)\left(\frac{e^{-x}}{1+e^{-x}}\right)\\[2ex]
&=\left(\frac{1}{1+e^{-x}}\right)\,\left(\frac{1+e^{-x}}{1+e^{-x}}-\frac{1}{1+e^{-x}}\right)\\[2ex]
&=\sigma(x)\,\left(\frac{1+e^{-x}}{1+e^{-x}}-\sigma(x)\right)\\[2ex]
&=\sigma(x)\,(1-\sigma(x))
\end{align}$
|
How is the cost function from Logistic Regression differentiated
|
Adapted from the notes in the course, which I don't see available (including this derivation) outside the notes contributed by students within the page of Andrew Ng's Coursera Machine Learning course.
|
How is the cost function from Logistic Regression differentiated
Adapted from the notes in the course, which I don't see available (including this derivation) outside the notes contributed by students within the page of Andrew Ng's Coursera Machine Learning course.
In what follows, the superscript $(i)$ denotes individual measurements or training "examples."
$\small
\frac{\partial J(\theta)}{\partial \theta_j} =
\frac{\partial}{\partial \theta_j} \,\frac{-1}{m}\sum_{i=1}^m
\left[ y^{(i)}\log\left(h_\theta \left(x^{(i)}\right)\right) +
(1 -y^{(i)})\log\left(1-h_\theta \left(x^{(i)}\right)\right)\right]
\\[2ex]\small\underset{\text{linearity}}= \,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{\partial}{\partial \theta_j}\log\left(h_\theta \left(x^{(i)}\right)\right) +
(1 -y^{(i)})\frac{\partial}{\partial \theta_j}\log\left(1-h_\theta \left(x^{(i)}\right)\right)
\right]
\\[2ex]\Tiny\underset{\text{chain rule}}= \,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{\frac{\partial}{\partial \theta_j}h_\theta \left(x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} +
(1 -y^{(i)})\frac{\frac{\partial}{\partial \theta_j}\left(1-h_\theta \left(x^{(i)}\right)\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\small\underset{h_\theta(x)=\sigma\left(\theta^\top x\right)}=\,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{\frac{\partial}{\partial \theta_j}\sigma\left(\theta^\top x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} +
(1 -y^{(i)})\frac{\frac{\partial}{\partial \theta_j}\left(1-\sigma\left(\theta^\top x^{(i)}\right)\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\Tiny\underset{\sigma'}=\frac{-1}{m}\,\sum_{i=1}^m
\left[ y^{(i)}\,
\frac{\sigma\left(\theta^\top x^{(i)}\right)\left(1-\sigma\left(\theta^\top x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} -
(1 -y^{(i)})\,\frac{\sigma\left(\theta^\top x^{(i)}\right)\left(1-\sigma\left(\theta^\top x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\small\underset{\sigma\left(\theta^\top x\right)=h_\theta(x)}= \,\frac{-1}{m}\,\sum_{i=1}^m
\left[
y^{(i)}\frac{h_\theta\left( x^{(i)}\right)\left(1-h_\theta\left( x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)}{h_\theta\left(x^{(i)}\right)} -
(1 -y^{(i)})\frac{h_\theta\left( x^{(i)}\right)\left(1-h_\theta\left(x^{(i)}\right)\right)\frac{\partial}{\partial \theta_j}\left( \theta^\top x^{(i)}\right)}{1-h_\theta\left(x^{(i)}\right)}
\right]
\\[2ex]\small\underset{\frac{\partial}{\partial \theta_j}\left(\theta^\top x^{(i)}\right)=x_j^{(i)}}=\,\frac{-1}{m}\,\sum_{i=1}^m \left[y^{(i)}\left(1-h_\theta\left(x^{(i)}\right)\right)x_j^{(i)}-
\left(1-y^{i}\right)\,h_\theta\left(x^{(i)}\right)x_j^{(i)}
\right]
\\[2ex]\small\underset{\text{distribute}}=\,\frac{-1}{m}\,\sum_{i=1}^m \left[y^{i}-y^{i}h_\theta\left(x^{(i)}\right)-
h_\theta\left(x^{(i)}\right)+y^{(i)}h_\theta\left(x^{(i)}\right)
\right]\,x_j^{(i)}
\\[2ex]\small\underset{\text{cancel}}=\,\frac{-1}{m}\,\sum_{i=1}^m \left[y^{(i)}-h_\theta\left(x^{(i)}\right)\right]\,x_j^{(i)} \\[2ex]\small=\frac{1}{m}\sum_{i=1}^m\left[h_\theta\left(x^{(i)}\right)-y^{(i)}\right]\,x_j^{(i)}
$
The derivative of the sigmoid function is
$\Tiny\begin{align}\frac{d}{dx}\sigma(x)&=\frac{d}{dx}\left(\frac{1}{1+e^{-x}}\right)\\[2ex]
&=\frac{-(1+e^{-x})'}{(1+e^{-x})^2}\\[2ex]
&=\frac{e^{-x}}{(1+e^{-x})^2}\\[2ex]
&=\left(\frac{1}{1+e^{-x}}\right)\left(\frac{e^{-x}}{1+e^{-x}}\right)\\[2ex]
&=\left(\frac{1}{1+e^{-x}}\right)\,\left(\frac{1+e^{-x}}{1+e^{-x}}-\frac{1}{1+e^{-x}}\right)\\[2ex]
&=\sigma(x)\,\left(\frac{1+e^{-x}}{1+e^{-x}}-\sigma(x)\right)\\[2ex]
&=\sigma(x)\,(1-\sigma(x))
\end{align}$
|
How is the cost function from Logistic Regression differentiated
Adapted from the notes in the course, which I don't see available (including this derivation) outside the notes contributed by students within the page of Andrew Ng's Coursera Machine Learning course.
|
6,557
|
How is the cost function from Logistic Regression differentiated
|
To avoid impression of excessive complexity of the matter, let us just see the structure of solution.
With simplification and some abuse of notation, let $G(\theta)$ be a term in sum of $J(\theta)$, and $h = 1/(1+e^{-z})$ is a function of $z(\theta)= x \theta $:
$$ G = y \cdot \log(h)+(1-y)\cdot \log(1-h) $$
We may use chain rule:
$\frac{d G}{d \theta}=\frac{d G}{d h}\frac{d h}{d z}\frac{d z}{d \theta}$ and solve it one by one ($x$ and $y$ are constants).
$$\frac{d G}{\partial h} = \frac{y} {h} - \frac{1-y}{1-h} = \frac{y - h}{h(1-h)} $$
For sigmoid $\frac{d h}{d z} = h (1-h) $ holds,
which is just a denominator of the previous statement.
Finally, $\frac{d z}{d \theta} = x $.
Combining results all together gives sought-for expression:
$$\frac{d G}{d \theta} = (y-h)x $$
Hope that helps.
|
How is the cost function from Logistic Regression differentiated
|
To avoid impression of excessive complexity of the matter, let us just see the structure of solution.
With simplification and some abuse of notation, let $G(\theta)$ be a term in sum of $J(\theta)$, a
|
How is the cost function from Logistic Regression differentiated
To avoid impression of excessive complexity of the matter, let us just see the structure of solution.
With simplification and some abuse of notation, let $G(\theta)$ be a term in sum of $J(\theta)$, and $h = 1/(1+e^{-z})$ is a function of $z(\theta)= x \theta $:
$$ G = y \cdot \log(h)+(1-y)\cdot \log(1-h) $$
We may use chain rule:
$\frac{d G}{d \theta}=\frac{d G}{d h}\frac{d h}{d z}\frac{d z}{d \theta}$ and solve it one by one ($x$ and $y$ are constants).
$$\frac{d G}{\partial h} = \frac{y} {h} - \frac{1-y}{1-h} = \frac{y - h}{h(1-h)} $$
For sigmoid $\frac{d h}{d z} = h (1-h) $ holds,
which is just a denominator of the previous statement.
Finally, $\frac{d z}{d \theta} = x $.
Combining results all together gives sought-for expression:
$$\frac{d G}{d \theta} = (y-h)x $$
Hope that helps.
|
How is the cost function from Logistic Regression differentiated
To avoid impression of excessive complexity of the matter, let us just see the structure of solution.
With simplification and some abuse of notation, let $G(\theta)$ be a term in sum of $J(\theta)$, a
|
6,558
|
How is the cost function from Logistic Regression differentiated
|
For those of us who are not so strong at calculus, but would like to play around with adjusting the cost function and need to find a way to calculate derivatives... a short cut to re-learning calculus is this online tool to automatically provide the derivation, with step by step explanations of the rule.
https://www.derivative-calculator.net
|
How is the cost function from Logistic Regression differentiated
|
For those of us who are not so strong at calculus, but would like to play around with adjusting the cost function and need to find a way to calculate derivatives... a short cut to re-learning calculus
|
How is the cost function from Logistic Regression differentiated
For those of us who are not so strong at calculus, but would like to play around with adjusting the cost function and need to find a way to calculate derivatives... a short cut to re-learning calculus is this online tool to automatically provide the derivation, with step by step explanations of the rule.
https://www.derivative-calculator.net
|
How is the cost function from Logistic Regression differentiated
For those of us who are not so strong at calculus, but would like to play around with adjusting the cost function and need to find a way to calculate derivatives... a short cut to re-learning calculus
|
6,559
|
How is the cost function from Logistic Regression differentiated
|
The credit for this answer goes to Antoni Parellada from the comments, which I think deserves a more prominent place on this page (as it helped me out when many other answers did not). Also, this is not a full derivation but more of a clear statement of $\frac{\partial J(\theta)}{\partial \theta}$. (For full derivation, see the other answers).
$$\frac{\partial J(\theta)}{\partial \theta} = \frac{1}{m} \cdot X^T\big(\sigma(X\theta)-y\big)$$
where
\begin{equation}
\begin{aligned}
X \in \mathbb{R}^{m\times n} &= \text{Training example matrix} \\
\sigma(z) &= \frac{1}{1+e^{-z}} = \text{sigmoid function} = \text{logistic function} \\
\theta \in \mathbb{R}^{n} &= \text{weight row vector} \\
y &= \text{class/category/label corresponding to rows in X}
\end{aligned}
\end{equation}
Also, a Python implementation for those wanting to calculate the gradient of $J$ with respect to $\theta$.
import numpy
def sig(z):
return 1/(1+np.e**-(z))
def compute_grad(X, y, w):
"""
Compute gradient of cross entropy function with sigmoidal probabilities
Args:
X (numpy.ndarray): examples. Individuals in rows, features in columns
y (numpy.ndarray): labels. Vector corresponding to rows in X
w (numpy.ndarray): weight vector
Returns:
numpy.ndarray
"""
m = X.shape[0]
Z = w.dot(X.T)
A = sig(Z)
return (-1/ m) * (X.T * (A - y)).sum(axis=1)
|
How is the cost function from Logistic Regression differentiated
|
The credit for this answer goes to Antoni Parellada from the comments, which I think deserves a more prominent place on this page (as it helped me out when many other answers did not). Also, this is n
|
How is the cost function from Logistic Regression differentiated
The credit for this answer goes to Antoni Parellada from the comments, which I think deserves a more prominent place on this page (as it helped me out when many other answers did not). Also, this is not a full derivation but more of a clear statement of $\frac{\partial J(\theta)}{\partial \theta}$. (For full derivation, see the other answers).
$$\frac{\partial J(\theta)}{\partial \theta} = \frac{1}{m} \cdot X^T\big(\sigma(X\theta)-y\big)$$
where
\begin{equation}
\begin{aligned}
X \in \mathbb{R}^{m\times n} &= \text{Training example matrix} \\
\sigma(z) &= \frac{1}{1+e^{-z}} = \text{sigmoid function} = \text{logistic function} \\
\theta \in \mathbb{R}^{n} &= \text{weight row vector} \\
y &= \text{class/category/label corresponding to rows in X}
\end{aligned}
\end{equation}
Also, a Python implementation for those wanting to calculate the gradient of $J$ with respect to $\theta$.
import numpy
def sig(z):
return 1/(1+np.e**-(z))
def compute_grad(X, y, w):
"""
Compute gradient of cross entropy function with sigmoidal probabilities
Args:
X (numpy.ndarray): examples. Individuals in rows, features in columns
y (numpy.ndarray): labels. Vector corresponding to rows in X
w (numpy.ndarray): weight vector
Returns:
numpy.ndarray
"""
m = X.shape[0]
Z = w.dot(X.T)
A = sig(Z)
return (-1/ m) * (X.T * (A - y)).sum(axis=1)
|
How is the cost function from Logistic Regression differentiated
The credit for this answer goes to Antoni Parellada from the comments, which I think deserves a more prominent place on this page (as it helped me out when many other answers did not). Also, this is n
|
6,560
|
How is the cost function from Logistic Regression differentiated
|
Another presentation, with matrix notation.
Preparation: $\sigma(t)=\frac{1}{1+e^{-t}}$ has $\frac{d \ln \sigma(t)}{dt}=\sigma(-t)=1-\sigma(t)$ hence $\frac{d \sigma}{dt}=\sigma(1-\sigma)$
and hence $\frac{d \ln (1- \sigma)}{dt}=\sigma$.
We use the convention in which all vectors are column vectors. Let $X$ be the data matrix whose rows are the data points $x_i^T$. Using the convention that a scalar function applying to a vector is applied entry-wise, we have
$$mJ(\theta)=\sum_i -y_i \ln \sigma(x_i^T\theta)-(1-y_i) \ln (1-\sigma(x_i^T\theta))=-y^T \ln \sigma (X\theta)-(1^T-y^T)\ln(1-\sigma)(X\theta).$$
Now the derivative (Jacobian, row vector) of $J$ with respect to $ \theta$ is obtained by using chain rule and noting that for matrix $M$, column vector $v$ and $f$ acting entry-wise we have $D_v f(Mv)=\text{diag}(f'(Mv))M$. The computation is as follows:
$$m D_\theta J= -y^T [\text{diag}((1-\sigma)(X\theta))] X-(1^T-y^T) [\text{diag}(-\sigma(X\theta))]X=$$
$$=-y^TX+1^T[\text{diag}(\sigma(X\theta))]X=-y^TX+(\sigma(X\theta))^TX.$$
Finally, the gradient is
$$\nabla_\theta J=(D_\theta J)^T=\frac{1}{m}X^T(\sigma(X\theta)-y)$$
|
How is the cost function from Logistic Regression differentiated
|
Another presentation, with matrix notation.
Preparation: $\sigma(t)=\frac{1}{1+e^{-t}}$ has $\frac{d \ln \sigma(t)}{dt}=\sigma(-t)=1-\sigma(t)$ hence $\frac{d \sigma}{dt}=\sigma(1-\sigma)$
and hence $
|
How is the cost function from Logistic Regression differentiated
Another presentation, with matrix notation.
Preparation: $\sigma(t)=\frac{1}{1+e^{-t}}$ has $\frac{d \ln \sigma(t)}{dt}=\sigma(-t)=1-\sigma(t)$ hence $\frac{d \sigma}{dt}=\sigma(1-\sigma)$
and hence $\frac{d \ln (1- \sigma)}{dt}=\sigma$.
We use the convention in which all vectors are column vectors. Let $X$ be the data matrix whose rows are the data points $x_i^T$. Using the convention that a scalar function applying to a vector is applied entry-wise, we have
$$mJ(\theta)=\sum_i -y_i \ln \sigma(x_i^T\theta)-(1-y_i) \ln (1-\sigma(x_i^T\theta))=-y^T \ln \sigma (X\theta)-(1^T-y^T)\ln(1-\sigma)(X\theta).$$
Now the derivative (Jacobian, row vector) of $J$ with respect to $ \theta$ is obtained by using chain rule and noting that for matrix $M$, column vector $v$ and $f$ acting entry-wise we have $D_v f(Mv)=\text{diag}(f'(Mv))M$. The computation is as follows:
$$m D_\theta J= -y^T [\text{diag}((1-\sigma)(X\theta))] X-(1^T-y^T) [\text{diag}(-\sigma(X\theta))]X=$$
$$=-y^TX+1^T[\text{diag}(\sigma(X\theta))]X=-y^TX+(\sigma(X\theta))^TX.$$
Finally, the gradient is
$$\nabla_\theta J=(D_\theta J)^T=\frac{1}{m}X^T(\sigma(X\theta)-y)$$
|
How is the cost function from Logistic Regression differentiated
Another presentation, with matrix notation.
Preparation: $\sigma(t)=\frac{1}{1+e^{-t}}$ has $\frac{d \ln \sigma(t)}{dt}=\sigma(-t)=1-\sigma(t)$ hence $\frac{d \sigma}{dt}=\sigma(1-\sigma)$
and hence $
|
6,561
|
Under what conditions should one use multilevel/hierarchical analysis?
|
When the structure of your data is naturally hierarchical or nested, multilevel modeling is a good candidate. More generally, it's one method to model interactions.
A natural example is when your data is from an organized structure such as country, state, districts, where you want to examine effects at those levels. Another example where you can fit such a structure is is longitudinal analysis, where you have repeated measurements from many subjects over time (e.g. some biological response to a drug dose). One level of your model assumes a group mean response for all subjects over time. Another level of your model then allows for perturbations (random effects) from the group mean, to model individual differences.
A popular and good book to start with is Gelman's Data Analysis Using Regression and Multilevel/Hierachical Models.
|
Under what conditions should one use multilevel/hierarchical analysis?
|
When the structure of your data is naturally hierarchical or nested, multilevel modeling is a good candidate. More generally, it's one method to model interactions.
A natural example is when your dat
|
Under what conditions should one use multilevel/hierarchical analysis?
When the structure of your data is naturally hierarchical or nested, multilevel modeling is a good candidate. More generally, it's one method to model interactions.
A natural example is when your data is from an organized structure such as country, state, districts, where you want to examine effects at those levels. Another example where you can fit such a structure is is longitudinal analysis, where you have repeated measurements from many subjects over time (e.g. some biological response to a drug dose). One level of your model assumes a group mean response for all subjects over time. Another level of your model then allows for perturbations (random effects) from the group mean, to model individual differences.
A popular and good book to start with is Gelman's Data Analysis Using Regression and Multilevel/Hierachical Models.
|
Under what conditions should one use multilevel/hierarchical analysis?
When the structure of your data is naturally hierarchical or nested, multilevel modeling is a good candidate. More generally, it's one method to model interactions.
A natural example is when your dat
|
6,562
|
Under what conditions should one use multilevel/hierarchical analysis?
|
The Centre for Multilevel Modelling has some good free online tutorials for multi-level modeling, and they have software tutorials for fitting models in both their MLwiN software and STATA.
Take this as heresy, because I have not read more than a chapter in the book, but Hierarchical linear models: applications and data analysis methods By Stephen W. Raudenbush, Anthony S. Bryk comes highly recommended. I also swore there was a book on multi level modeling using R software in the Springer Use R! series, but I can't seem to find it at the moment (I thought it was written by the same people who wrote the A Beginner’s Guide to R book).
edit: The book on using R for multi-level models is Mixed Effects Models and Extensions in Ecology with R by Zuur, A.F., Ieno, E.N., Walker, N., Saveliev, A.A., Smith, G.M.
good luck
|
Under what conditions should one use multilevel/hierarchical analysis?
|
The Centre for Multilevel Modelling has some good free online tutorials for multi-level modeling, and they have software tutorials for fitting models in both their MLwiN software and STATA.
Take this
|
Under what conditions should one use multilevel/hierarchical analysis?
The Centre for Multilevel Modelling has some good free online tutorials for multi-level modeling, and they have software tutorials for fitting models in both their MLwiN software and STATA.
Take this as heresy, because I have not read more than a chapter in the book, but Hierarchical linear models: applications and data analysis methods By Stephen W. Raudenbush, Anthony S. Bryk comes highly recommended. I also swore there was a book on multi level modeling using R software in the Springer Use R! series, but I can't seem to find it at the moment (I thought it was written by the same people who wrote the A Beginner’s Guide to R book).
edit: The book on using R for multi-level models is Mixed Effects Models and Extensions in Ecology with R by Zuur, A.F., Ieno, E.N., Walker, N., Saveliev, A.A., Smith, G.M.
good luck
|
Under what conditions should one use multilevel/hierarchical analysis?
The Centre for Multilevel Modelling has some good free online tutorials for multi-level modeling, and they have software tutorials for fitting models in both their MLwiN software and STATA.
Take this
|
6,563
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Here's another perspective on using multilevel vs. regression models: In an interesting paper by Afshartous and de Leeuw, they show that if the purpose of the modeling is predictive (that is, to predict new observations), the choice of model is different from when the goal is inference (where you try to match the model with the data structure). The paper that I am referring to is
Afshartous, D., de Leeuw, J. (2005). Prediction in multilevel models. J. Educat. Behav. Statist. 30(2):109–139.
I just found another related paper by these authors here: http://moya.bus.miami.edu/~dafshartous/Afshartous_CIS.pdf
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Here's another perspective on using multilevel vs. regression models: In an interesting paper by Afshartous and de Leeuw, they show that if the purpose of the modeling is predictive (that is, to predi
|
Under what conditions should one use multilevel/hierarchical analysis?
Here's another perspective on using multilevel vs. regression models: In an interesting paper by Afshartous and de Leeuw, they show that if the purpose of the modeling is predictive (that is, to predict new observations), the choice of model is different from when the goal is inference (where you try to match the model with the data structure). The paper that I am referring to is
Afshartous, D., de Leeuw, J. (2005). Prediction in multilevel models. J. Educat. Behav. Statist. 30(2):109–139.
I just found another related paper by these authors here: http://moya.bus.miami.edu/~dafshartous/Afshartous_CIS.pdf
|
Under what conditions should one use multilevel/hierarchical analysis?
Here's another perspective on using multilevel vs. regression models: In an interesting paper by Afshartous and de Leeuw, they show that if the purpose of the modeling is predictive (that is, to predi
|
6,564
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Here's an example where a multilevel model might be "essential." Suppose you want to rate the "quality" of the education provided by a set of schools using students' test scores. One way to define school quality is in terms of average test performance after taking student characteristics into account. You could conceptualized this as,
$$y_{is} = \alpha_s + X_{is}'\beta_s + \epsilon_{is},$$
where $y_{is}$ is the continuous test score for student $i$ in school $s$, $X_{is}$ are student attributes centered at school means, $\beta_s$ is a school-specific coefficient on these attributes, $\alpha_s$ is a "school effect" that measures school quality, and $\epsilon_{is}$ are student level idiosyncrasies in test taking performance. Interest here focuses on estimating the $\alpha_s$'s, which measure the "added value" that the school provides to students once their attributes are accounted-for. You want to take student attributes into account, because you don't want to punish a good school that has to deal with students with certain disadvantages, therefore depressing average test scores despited the high "added value" that the school provides to its students.
With the model in hand, the issue becomes one of estimation. If you have lots of schools and lots of data for each school, the nice properties of OLS (see Angrist and Pischke, Mostly Harmless..., for a current review) suggest that you would want to use that, with suitable adjustments to standard errors to account for dependencies, and using dummy variables and interactions to get at school level effects and school specific intercepts. OLS may be inefficient, but it's so transparent that it might be easier to convince skeptical audiences if you use that. But if your data are sparse in certain ways---particularly if you have few observations for some schools---you may want to impose more "structure" on the problem. You may want to "borrow strength" from the larger-sample schools to improve the noisy estimates that you would get in the small-sample schools if the estimation were done with no structure. Then, you might turn to a random effects model estimated via FGLS, or maybe an approximation to direct likelihood given a certain parametric model, or even Bayes on a parametric model.
In this example, the use of a multilevel model (however we decide to fit it, ultimately) is motivated by the direct interest in the school-level intercepts. Of course, in other situations, these group level parameters may be nothing more than nuisance. Whether or not you need to adjust for them (and, therefore, still work with some kind of multilevel model) depends on whether certain conditional exogeneity assumptions hold. On that, I would recommend consulting the econometric literature on panel data methods; most insights from there carry over to general grouped data contexts.
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Here's an example where a multilevel model might be "essential." Suppose you want to rate the "quality" of the education provided by a set of schools using students' test scores. One way to define sc
|
Under what conditions should one use multilevel/hierarchical analysis?
Here's an example where a multilevel model might be "essential." Suppose you want to rate the "quality" of the education provided by a set of schools using students' test scores. One way to define school quality is in terms of average test performance after taking student characteristics into account. You could conceptualized this as,
$$y_{is} = \alpha_s + X_{is}'\beta_s + \epsilon_{is},$$
where $y_{is}$ is the continuous test score for student $i$ in school $s$, $X_{is}$ are student attributes centered at school means, $\beta_s$ is a school-specific coefficient on these attributes, $\alpha_s$ is a "school effect" that measures school quality, and $\epsilon_{is}$ are student level idiosyncrasies in test taking performance. Interest here focuses on estimating the $\alpha_s$'s, which measure the "added value" that the school provides to students once their attributes are accounted-for. You want to take student attributes into account, because you don't want to punish a good school that has to deal with students with certain disadvantages, therefore depressing average test scores despited the high "added value" that the school provides to its students.
With the model in hand, the issue becomes one of estimation. If you have lots of schools and lots of data for each school, the nice properties of OLS (see Angrist and Pischke, Mostly Harmless..., for a current review) suggest that you would want to use that, with suitable adjustments to standard errors to account for dependencies, and using dummy variables and interactions to get at school level effects and school specific intercepts. OLS may be inefficient, but it's so transparent that it might be easier to convince skeptical audiences if you use that. But if your data are sparse in certain ways---particularly if you have few observations for some schools---you may want to impose more "structure" on the problem. You may want to "borrow strength" from the larger-sample schools to improve the noisy estimates that you would get in the small-sample schools if the estimation were done with no structure. Then, you might turn to a random effects model estimated via FGLS, or maybe an approximation to direct likelihood given a certain parametric model, or even Bayes on a parametric model.
In this example, the use of a multilevel model (however we decide to fit it, ultimately) is motivated by the direct interest in the school-level intercepts. Of course, in other situations, these group level parameters may be nothing more than nuisance. Whether or not you need to adjust for them (and, therefore, still work with some kind of multilevel model) depends on whether certain conditional exogeneity assumptions hold. On that, I would recommend consulting the econometric literature on panel data methods; most insights from there carry over to general grouped data contexts.
|
Under what conditions should one use multilevel/hierarchical analysis?
Here's an example where a multilevel model might be "essential." Suppose you want to rate the "quality" of the education provided by a set of schools using students' test scores. One way to define sc
|
6,565
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Multi-level modelling is appropriate, as the name suggests, when your data have influences occurring at different levels (individual, over time, over domains, etc). Single level modeling assumes everything is occurring at the lowest level. Another thing that a multi-level model does is to introduce correlations among nested units. So level-1 units within the same level-2 unit will be correlated.
In some sense you can think of multi-level modelling as finding the middle ground between the "individualist fallacy" and the "ecological fallacy". Individualist fallacy is when "community effects" are ignored such as the compatibility of a teacher's style with a student's learning style, for example (the effect is assumed to come from the individual alone, so just do regression at level 1). whereas "ecological fallacy" is the opposite, and would be like supposing the best teacher had the students with the best grades (and so that the level-1 is not needed, just do regression entirely at level 2). In most settings, neither is appropriate (the student-teacher is a "classical" example).
Note that in the school example, there was a "natural" clustering or structure in the data. But this is not an essential feature of multi-level/hierachical modeling. However, the natural clustering makes the mathematics and computations easier. The key ingredient is the prior information which says that there are processes happening at different levels. In fact you can devise clustering algorithms by imposing a multi-level structure on your data with uncertainty about which unit is in which higher level. So you have $y_{ij}$ with the subscript $j$ being unknown.
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Multi-level modelling is appropriate, as the name suggests, when your data have influences occurring at different levels (individual, over time, over domains, etc). Single level modeling assumes ever
|
Under what conditions should one use multilevel/hierarchical analysis?
Multi-level modelling is appropriate, as the name suggests, when your data have influences occurring at different levels (individual, over time, over domains, etc). Single level modeling assumes everything is occurring at the lowest level. Another thing that a multi-level model does is to introduce correlations among nested units. So level-1 units within the same level-2 unit will be correlated.
In some sense you can think of multi-level modelling as finding the middle ground between the "individualist fallacy" and the "ecological fallacy". Individualist fallacy is when "community effects" are ignored such as the compatibility of a teacher's style with a student's learning style, for example (the effect is assumed to come from the individual alone, so just do regression at level 1). whereas "ecological fallacy" is the opposite, and would be like supposing the best teacher had the students with the best grades (and so that the level-1 is not needed, just do regression entirely at level 2). In most settings, neither is appropriate (the student-teacher is a "classical" example).
Note that in the school example, there was a "natural" clustering or structure in the data. But this is not an essential feature of multi-level/hierachical modeling. However, the natural clustering makes the mathematics and computations easier. The key ingredient is the prior information which says that there are processes happening at different levels. In fact you can devise clustering algorithms by imposing a multi-level structure on your data with uncertainty about which unit is in which higher level. So you have $y_{ij}$ with the subscript $j$ being unknown.
|
Under what conditions should one use multilevel/hierarchical analysis?
Multi-level modelling is appropriate, as the name suggests, when your data have influences occurring at different levels (individual, over time, over domains, etc). Single level modeling assumes ever
|
6,566
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Generally, speaking a hierarchical bayesian (HB) analysis will lead to efficient and stable individual level estimates unless your data is such that individual level effects are completely homogeneous (an unrealistic scenario). The efficiency and stable parameter estimates of HB models becomes really important when you have sparse data (e.g., less no of obs than the no of parameters at the individual level) and when you want to estimate individual level estimates.
However, HB models are not always easy to estimate. Therefore, while HB analysis usually trumps non-HB analysis you have to weigh the relative costs vs benefits based on your past experience and your current priorities in terms of time and cost.
Having said that if you are not interested in individual level estimates then you can simply estimate an aggregate level model but even in these contexts estimating aggregating models via HB using individual level estimates may make a lot of sense.
In summary, fitting HB models is the recommended approach as long as you have the time and the patience to fit them. You can then use aggregate models as a benchmark to assess the performance of your HB model.
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Generally, speaking a hierarchical bayesian (HB) analysis will lead to efficient and stable individual level estimates unless your data is such that individual level effects are completely homogeneous
|
Under what conditions should one use multilevel/hierarchical analysis?
Generally, speaking a hierarchical bayesian (HB) analysis will lead to efficient and stable individual level estimates unless your data is such that individual level effects are completely homogeneous (an unrealistic scenario). The efficiency and stable parameter estimates of HB models becomes really important when you have sparse data (e.g., less no of obs than the no of parameters at the individual level) and when you want to estimate individual level estimates.
However, HB models are not always easy to estimate. Therefore, while HB analysis usually trumps non-HB analysis you have to weigh the relative costs vs benefits based on your past experience and your current priorities in terms of time and cost.
Having said that if you are not interested in individual level estimates then you can simply estimate an aggregate level model but even in these contexts estimating aggregating models via HB using individual level estimates may make a lot of sense.
In summary, fitting HB models is the recommended approach as long as you have the time and the patience to fit them. You can then use aggregate models as a benchmark to assess the performance of your HB model.
|
Under what conditions should one use multilevel/hierarchical analysis?
Generally, speaking a hierarchical bayesian (HB) analysis will lead to efficient and stable individual level estimates unless your data is such that individual level effects are completely homogeneous
|
6,567
|
Under what conditions should one use multilevel/hierarchical analysis?
|
I learned from Snijders and Bosker, Multilevel Analysis: An introduction to basic and advanced multilevel modeling. It is very well pitched at the beginner I think, it must be because I am a thicko where these things are concerned and it made sense to me.
I second the Gelman and Hill as well, a truly brilliant book.
|
Under what conditions should one use multilevel/hierarchical analysis?
|
I learned from Snijders and Bosker, Multilevel Analysis: An introduction to basic and advanced multilevel modeling. It is very well pitched at the beginner I think, it must be because I am a thicko wh
|
Under what conditions should one use multilevel/hierarchical analysis?
I learned from Snijders and Bosker, Multilevel Analysis: An introduction to basic and advanced multilevel modeling. It is very well pitched at the beginner I think, it must be because I am a thicko where these things are concerned and it made sense to me.
I second the Gelman and Hill as well, a truly brilliant book.
|
Under what conditions should one use multilevel/hierarchical analysis?
I learned from Snijders and Bosker, Multilevel Analysis: An introduction to basic and advanced multilevel modeling. It is very well pitched at the beginner I think, it must be because I am a thicko wh
|
6,568
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Multi-level models should be employed when the data are nested in a hierarchical structure, particularly when there are significant differences between higher level units in the dependent variable (e.g., student achievement orientation varies between students, and also between the classes with which the students are nested). In these circumstances, observations are clustered rather than independent. Failure to take the clustering into account leads to underestimation of the errors of parameter estimates, biased significance testing, and a tendency to reject the null when it should be retained. The rationale for using multi level models, as well as thorough explanations of how to carry out the analyses, is provided by
Raudenbush, S. W. Bryk, A. S. (2002). Hierarchical linear models: Applications and data analysis methods. 2nd edition. Newbury Park , CA : Sage.
The R & B book is also well integrated with the authors' HLM software package, which helps a great deal in learning the package. An explanation of why multi-level models are necessary and preferable to some alternatives (like dummy coding the higher level units) is provided in a classic paper
Hoffman, D.A. (1997). An overview of the logic and rationale of Hierachical Linear Models. Journal of Management, 23, 723-744.
The Hoffman paper can be downloaded for free if you Google "Hoffman 1997 HLM" and access the pdf online.
|
Under what conditions should one use multilevel/hierarchical analysis?
|
Multi-level models should be employed when the data are nested in a hierarchical structure, particularly when there are significant differences between higher level units in the dependent variable (e.
|
Under what conditions should one use multilevel/hierarchical analysis?
Multi-level models should be employed when the data are nested in a hierarchical structure, particularly when there are significant differences between higher level units in the dependent variable (e.g., student achievement orientation varies between students, and also between the classes with which the students are nested). In these circumstances, observations are clustered rather than independent. Failure to take the clustering into account leads to underestimation of the errors of parameter estimates, biased significance testing, and a tendency to reject the null when it should be retained. The rationale for using multi level models, as well as thorough explanations of how to carry out the analyses, is provided by
Raudenbush, S. W. Bryk, A. S. (2002). Hierarchical linear models: Applications and data analysis methods. 2nd edition. Newbury Park , CA : Sage.
The R & B book is also well integrated with the authors' HLM software package, which helps a great deal in learning the package. An explanation of why multi-level models are necessary and preferable to some alternatives (like dummy coding the higher level units) is provided in a classic paper
Hoffman, D.A. (1997). An overview of the logic and rationale of Hierachical Linear Models. Journal of Management, 23, 723-744.
The Hoffman paper can be downloaded for free if you Google "Hoffman 1997 HLM" and access the pdf online.
|
Under what conditions should one use multilevel/hierarchical analysis?
Multi-level models should be employed when the data are nested in a hierarchical structure, particularly when there are significant differences between higher level units in the dependent variable (e.
|
6,569
|
What is the difference between censoring and truncation?
|
Definitions vary, and the two terms are sometimes used interchangeably. I'll try to explain the most common uses using the following data set:
$$ 1\qquad 1.25\qquad 2\qquad 4 \qquad 5$$
Censoring: some observations will be censored, meaning that we only know that they are below (or above) some bound. This can for instance occur if we measure the concentration of a chemical in a water sample. If the concentration is too low, the laboratory equipment cannot detect the presence of the chemical. It may still be present though, so we only know that the concentration is below the laboratory's detection limit.
If the detection limit is 1.5, so that observations that fall below this limit is censored, our example data set would become:
$$ <1.5\qquad <1.5\qquad 2\qquad 4 \qquad 5,$$
that is, we don't know the actual values of the first two observations, but only that they are smaller than 1.5.
Truncation: the process generating the data is such that it only is possible to observe outcomes above (or below) the truncation limit. This can for instance occur if measurements are taken using a detector which only is activated if the signals it detects are above a certain limit. There may be lots of weak incoming signals, but we can never tell using this detector.
If the truncation limit is 1.5, our example data set would become
$$2\qquad 4 \qquad 5$$
and we would not know that there in fact were two signals which were not recorded.
|
What is the difference between censoring and truncation?
|
Definitions vary, and the two terms are sometimes used interchangeably. I'll try to explain the most common uses using the following data set:
$$ 1\qquad 1.25\qquad 2\qquad 4 \qquad 5$$
Censoring: som
|
What is the difference between censoring and truncation?
Definitions vary, and the two terms are sometimes used interchangeably. I'll try to explain the most common uses using the following data set:
$$ 1\qquad 1.25\qquad 2\qquad 4 \qquad 5$$
Censoring: some observations will be censored, meaning that we only know that they are below (or above) some bound. This can for instance occur if we measure the concentration of a chemical in a water sample. If the concentration is too low, the laboratory equipment cannot detect the presence of the chemical. It may still be present though, so we only know that the concentration is below the laboratory's detection limit.
If the detection limit is 1.5, so that observations that fall below this limit is censored, our example data set would become:
$$ <1.5\qquad <1.5\qquad 2\qquad 4 \qquad 5,$$
that is, we don't know the actual values of the first two observations, but only that they are smaller than 1.5.
Truncation: the process generating the data is such that it only is possible to observe outcomes above (or below) the truncation limit. This can for instance occur if measurements are taken using a detector which only is activated if the signals it detects are above a certain limit. There may be lots of weak incoming signals, but we can never tell using this detector.
If the truncation limit is 1.5, our example data set would become
$$2\qquad 4 \qquad 5$$
and we would not know that there in fact were two signals which were not recorded.
|
What is the difference between censoring and truncation?
Definitions vary, and the two terms are sometimes used interchangeably. I'll try to explain the most common uses using the following data set:
$$ 1\qquad 1.25\qquad 2\qquad 4 \qquad 5$$
Censoring: som
|
6,570
|
What is the difference between censoring and truncation?
|
Just as a perspective from another field (programming), censoring and truncating are two distinct operations.
When working with a sensitive dataset, for example social security numbers and telephone numbers, I might censor it or have it censored prior to access being granted:
123-12-1234 => 999-99-9999
567-56-5678 => 999-99-9999
(906) 123-4567 => (000) 000-0000
This allows the rest of the application to operate as it normally would, with similar data structures, but with no real informational content or dissemination of private information.
Truncation, by contrast, is typically just cutting off remaining values after a certain point. To work on an application, I don't need hundreds of thousands of records, perhaps I only need ~50 of each which makes the data access much faster and the data sets smaller.
A similar variant of truncation is when inserting a value into a column or datatype of limited length or precision:
abcdefghijklmnopqrstuv => abcdef
10.23412421345 => 10.23
10.92455311 => 10
|
What is the difference between censoring and truncation?
|
Just as a perspective from another field (programming), censoring and truncating are two distinct operations.
When working with a sensitive dataset, for example social security numbers and telephone n
|
What is the difference between censoring and truncation?
Just as a perspective from another field (programming), censoring and truncating are two distinct operations.
When working with a sensitive dataset, for example social security numbers and telephone numbers, I might censor it or have it censored prior to access being granted:
123-12-1234 => 999-99-9999
567-56-5678 => 999-99-9999
(906) 123-4567 => (000) 000-0000
This allows the rest of the application to operate as it normally would, with similar data structures, but with no real informational content or dissemination of private information.
Truncation, by contrast, is typically just cutting off remaining values after a certain point. To work on an application, I don't need hundreds of thousands of records, perhaps I only need ~50 of each which makes the data access much faster and the data sets smaller.
A similar variant of truncation is when inserting a value into a column or datatype of limited length or precision:
abcdefghijklmnopqrstuv => abcdef
10.23412421345 => 10.23
10.92455311 => 10
|
What is the difference between censoring and truncation?
Just as a perspective from another field (programming), censoring and truncating are two distinct operations.
When working with a sensitive dataset, for example social security numbers and telephone n
|
6,571
|
Examples of PCA where PCs with low variance are "useful"
|
Here's a cool excerpt from Jolliffe (1982) that I didn't include in my previous answer to the very similar question, "Low variance components in PCA, are they really just noise? Is there any way to test for it?" I find it pretty intuitive.
$\quad$Suppose that it is required to predict the height of the cloud-base, $H$, an important problem at airports. Various climatic variables are measured including surface temperature $T_s$, and surface dewpoint, $T_d$. Here, $T_d$ is the temperature at which the surface air would be saturated with water vapour, and the difference $T_s-T_d$, is a measure of surface humidity. Now $T_s,T_d$ are generally positively correlated, so a principal component analysis of the climatic variables will have a high-variance component which is highly correlated with $T_s+T_d$,and a low-variance component which is similarly correlated with $T_s-T_d$. But $H$ is related to humidity and hence to $T_s-T_d$, i.e. to a low-variance rather than a high-variance component, so a strategy which rejects low-variance components will give poor predictions for $H$.
$\quad$The discussion of this example is necessarily vague because of the unknown effects of any other climatic variables which are also measured and included in the analysis. However, it shows a physically plausible case where a dependent variable will be related to a low-variance component, confirming the three empirical examples from the literature.
$\quad$Furthermore, the cloud-base example has been tested on data from Cardiff (Wales) Airport for the period 1966–73 with one extra climatic variable, sea-surface temperature, also included.
Results were essentially as predicted above. The last principal component was approximately
$T_s-T_d$, and it accounted for only 0·4 per cent of the total variation. However, in a principal component regression it was easily the most important predictor for $H$. [Emphasis added]
The three examples from literature referred to in the last sentence of the second paragraph were the three I mentioned in my answer to the linked question.
Reference
Jolliffe, I. T. (1982). Note on the use of principal components in regression. Applied Statistics, 31(3), 300–303. Retrieved from http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2082.pdf.
|
Examples of PCA where PCs with low variance are "useful"
|
Here's a cool excerpt from Jolliffe (1982) that I didn't include in my previous answer to the very similar question, "Low variance components in PCA, are they really just noise? Is there any way to te
|
Examples of PCA where PCs with low variance are "useful"
Here's a cool excerpt from Jolliffe (1982) that I didn't include in my previous answer to the very similar question, "Low variance components in PCA, are they really just noise? Is there any way to test for it?" I find it pretty intuitive.
$\quad$Suppose that it is required to predict the height of the cloud-base, $H$, an important problem at airports. Various climatic variables are measured including surface temperature $T_s$, and surface dewpoint, $T_d$. Here, $T_d$ is the temperature at which the surface air would be saturated with water vapour, and the difference $T_s-T_d$, is a measure of surface humidity. Now $T_s,T_d$ are generally positively correlated, so a principal component analysis of the climatic variables will have a high-variance component which is highly correlated with $T_s+T_d$,and a low-variance component which is similarly correlated with $T_s-T_d$. But $H$ is related to humidity and hence to $T_s-T_d$, i.e. to a low-variance rather than a high-variance component, so a strategy which rejects low-variance components will give poor predictions for $H$.
$\quad$The discussion of this example is necessarily vague because of the unknown effects of any other climatic variables which are also measured and included in the analysis. However, it shows a physically plausible case where a dependent variable will be related to a low-variance component, confirming the three empirical examples from the literature.
$\quad$Furthermore, the cloud-base example has been tested on data from Cardiff (Wales) Airport for the period 1966–73 with one extra climatic variable, sea-surface temperature, also included.
Results were essentially as predicted above. The last principal component was approximately
$T_s-T_d$, and it accounted for only 0·4 per cent of the total variation. However, in a principal component regression it was easily the most important predictor for $H$. [Emphasis added]
The three examples from literature referred to in the last sentence of the second paragraph were the three I mentioned in my answer to the linked question.
Reference
Jolliffe, I. T. (1982). Note on the use of principal components in regression. Applied Statistics, 31(3), 300–303. Retrieved from http://automatica.dei.unipd.it/public/Schenato/PSC/2010_2011/gruppo4-Building_termo_identification/IdentificazioneTermodinamica20072008/Biblio/Articoli/PCR%20vecchio%2082.pdf.
|
Examples of PCA where PCs with low variance are "useful"
Here's a cool excerpt from Jolliffe (1982) that I didn't include in my previous answer to the very similar question, "Low variance components in PCA, are they really just noise? Is there any way to te
|
6,572
|
Examples of PCA where PCs with low variance are "useful"
|
If you have R, there is a good example in the crabs data in the MASS package.
> library(MASS)
> data(crabs)
> head(crabs)
sp sex index FL RW CL CW BD
1 B M 1 8.1 6.7 16.1 19.0 7.0
2 B M 2 8.8 7.7 18.1 20.8 7.4
3 B M 3 9.2 7.8 19.0 22.4 7.7
4 B M 4 9.6 7.9 20.1 23.1 8.2
5 B M 5 9.8 8.0 20.3 23.0 8.2
6 B M 6 10.8 9.0 23.0 26.5 9.8
> crabs.n <- crabs[,4:8]
> pr1 <- prcomp(crabs.n, center=T, scale=T)
> cumsum(pr1$sdev^2)/sum(pr1$sdev^2)
[1] 0.9577670 0.9881040 0.9974306 0.9996577 1.0000000
Over 98% of the variance is "explained" by the first two PCs, but in fact if you had actually collected these measurements and were studying them, the third PC is very interesting, because it is closely related to the crab's species. But it is swamped by PC1 (which seems to correspond to the size of the crab) and PC2 (which seems to correspond to the sex of the crab.)
|
Examples of PCA where PCs with low variance are "useful"
|
If you have R, there is a good example in the crabs data in the MASS package.
> library(MASS)
> data(crabs)
> head(crabs)
sp sex index FL RW CL CW BD
1 B M 1 8.1 6.7 16.1 19.0 7.0
|
Examples of PCA where PCs with low variance are "useful"
If you have R, there is a good example in the crabs data in the MASS package.
> library(MASS)
> data(crabs)
> head(crabs)
sp sex index FL RW CL CW BD
1 B M 1 8.1 6.7 16.1 19.0 7.0
2 B M 2 8.8 7.7 18.1 20.8 7.4
3 B M 3 9.2 7.8 19.0 22.4 7.7
4 B M 4 9.6 7.9 20.1 23.1 8.2
5 B M 5 9.8 8.0 20.3 23.0 8.2
6 B M 6 10.8 9.0 23.0 26.5 9.8
> crabs.n <- crabs[,4:8]
> pr1 <- prcomp(crabs.n, center=T, scale=T)
> cumsum(pr1$sdev^2)/sum(pr1$sdev^2)
[1] 0.9577670 0.9881040 0.9974306 0.9996577 1.0000000
Over 98% of the variance is "explained" by the first two PCs, but in fact if you had actually collected these measurements and were studying them, the third PC is very interesting, because it is closely related to the crab's species. But it is swamped by PC1 (which seems to correspond to the size of the crab) and PC2 (which seems to correspond to the sex of the crab.)
|
Examples of PCA where PCs with low variance are "useful"
If you have R, there is a good example in the crabs data in the MASS package.
> library(MASS)
> data(crabs)
> head(crabs)
sp sex index FL RW CL CW BD
1 B M 1 8.1 6.7 16.1 19.0 7.0
|
6,573
|
Examples of PCA where PCs with low variance are "useful"
|
Here are two examples from my experience (chemometrics, optical/vibrational/Raman spectroscopy):
I recently had optical spectroscopy data, where > 99% of the total variance of the raw data was due to changes in the background light (spotlight more or less intense on the measured point, fluorescent lamps switched on/off, more or less clouds before the sun). After background correction with the optical spectra of known influencing factors (extracted by PCA on the raw data; extra measurements taken in order to cover those variations), the effect we were interested in showed up in PCs 4 and 5.
PCs 1 and 3 where due to other effects in the measured sample, and PC 2 correlates with the instrument tip heating up during the measurements.
In another measurement, a lens without color correction for the measured spectral range was used. The chromatic aberration lead to distortions in the spectra that accounted for ca. 90 % of total variance of the pre-processed data (captured mostly in PC 1).
For this data it took us quite a while to realize what exactly had happened, but switching to a better objective solved the problem for later experiments.
(I cannot show details as these studies are still unpublished)
|
Examples of PCA where PCs with low variance are "useful"
|
Here are two examples from my experience (chemometrics, optical/vibrational/Raman spectroscopy):
I recently had optical spectroscopy data, where > 99% of the total variance of the raw data was due to
|
Examples of PCA where PCs with low variance are "useful"
Here are two examples from my experience (chemometrics, optical/vibrational/Raman spectroscopy):
I recently had optical spectroscopy data, where > 99% of the total variance of the raw data was due to changes in the background light (spotlight more or less intense on the measured point, fluorescent lamps switched on/off, more or less clouds before the sun). After background correction with the optical spectra of known influencing factors (extracted by PCA on the raw data; extra measurements taken in order to cover those variations), the effect we were interested in showed up in PCs 4 and 5.
PCs 1 and 3 where due to other effects in the measured sample, and PC 2 correlates with the instrument tip heating up during the measurements.
In another measurement, a lens without color correction for the measured spectral range was used. The chromatic aberration lead to distortions in the spectra that accounted for ca. 90 % of total variance of the pre-processed data (captured mostly in PC 1).
For this data it took us quite a while to realize what exactly had happened, but switching to a better objective solved the problem for later experiments.
(I cannot show details as these studies are still unpublished)
|
Examples of PCA where PCs with low variance are "useful"
Here are two examples from my experience (chemometrics, optical/vibrational/Raman spectroscopy):
I recently had optical spectroscopy data, where > 99% of the total variance of the raw data was due to
|
6,574
|
Examples of PCA where PCs with low variance are "useful"
|
I have noticed that PCs with low variance are most helpful when performing a PCA on a covariance matrix where the underlying data are clustered or grouped in some way. If one of the groups has a substantially lower average variance than the other groups, then the smallest PCs would be dominated by that group. However, you might have some reason to not want to throw away the results from that group.
In finance, stock returns have about 15-25% annual standard deviation. Changes in bond yields are historically much lower standard deviation. If you perform PCA on the covariance matrix of stock returns and changes in bond yields, then the top PCs will all reflect variance of the stocks and the smallest ones will reflect the variances of the bonds. If you throw away the PCs that explain the bonds, then you might be in for some trouble. For instance, the bonds might have very different distributional characteristics than stocks (thinner tails, different time-varying variance properties, different mean reversion, cointegration, etc). These might be very important to model, depending on the circumstances.
If you perform PCA on the correlation matrix, then you might see more of the PCs explaining bonds near the top.
|
Examples of PCA where PCs with low variance are "useful"
|
I have noticed that PCs with low variance are most helpful when performing a PCA on a covariance matrix where the underlying data are clustered or grouped in some way. If one of the groups has a subst
|
Examples of PCA where PCs with low variance are "useful"
I have noticed that PCs with low variance are most helpful when performing a PCA on a covariance matrix where the underlying data are clustered or grouped in some way. If one of the groups has a substantially lower average variance than the other groups, then the smallest PCs would be dominated by that group. However, you might have some reason to not want to throw away the results from that group.
In finance, stock returns have about 15-25% annual standard deviation. Changes in bond yields are historically much lower standard deviation. If you perform PCA on the covariance matrix of stock returns and changes in bond yields, then the top PCs will all reflect variance of the stocks and the smallest ones will reflect the variances of the bonds. If you throw away the PCs that explain the bonds, then you might be in for some trouble. For instance, the bonds might have very different distributional characteristics than stocks (thinner tails, different time-varying variance properties, different mean reversion, cointegration, etc). These might be very important to model, depending on the circumstances.
If you perform PCA on the correlation matrix, then you might see more of the PCs explaining bonds near the top.
|
Examples of PCA where PCs with low variance are "useful"
I have noticed that PCs with low variance are most helpful when performing a PCA on a covariance matrix where the underlying data are clustered or grouped in some way. If one of the groups has a subst
|
6,575
|
Examples of PCA where PCs with low variance are "useful"
|
In this talk (slides) the presenters discuss their use of PCA to discriminate between high variability and low variability features.
They actually prefer the low variability features for anomaly detection, since a significant shift in a low variability dimension is a strong indicator of anomalous behavior. The motivating example they provide is as follows:
Assume a user always logs in from a Mac. The "operating system" dimension of their activity would be very low variance. But if we saw a login event from that same user where the "operating system" was Windows, that would be very interesting, and something we'd like to catch.
|
Examples of PCA where PCs with low variance are "useful"
|
In this talk (slides) the presenters discuss their use of PCA to discriminate between high variability and low variability features.
They actually prefer the low variability features for anomaly detec
|
Examples of PCA where PCs with low variance are "useful"
In this talk (slides) the presenters discuss their use of PCA to discriminate between high variability and low variability features.
They actually prefer the low variability features for anomaly detection, since a significant shift in a low variability dimension is a strong indicator of anomalous behavior. The motivating example they provide is as follows:
Assume a user always logs in from a Mac. The "operating system" dimension of their activity would be very low variance. But if we saw a login event from that same user where the "operating system" was Windows, that would be very interesting, and something we'd like to catch.
|
Examples of PCA where PCs with low variance are "useful"
In this talk (slides) the presenters discuss their use of PCA to discriminate between high variability and low variability features.
They actually prefer the low variability features for anomaly detec
|
6,576
|
Open Source statistical textbooks?
|
Try IPSUR, Introduction to Probability and Statistics Using R by G. Jay Kerns. It's "free, in the GNU sense of the word".
http://ipsur.r-forge.r-project.org/book/
It's definitely open source - on the download page you can download the LaTeX source or the lyx source used to generate this.
|
Open Source statistical textbooks?
|
Try IPSUR, Introduction to Probability and Statistics Using R by G. Jay Kerns. It's "free, in the GNU sense of the word".
http://ipsur.r-forge.r-project.org/book/
It's definitely open source - on the
|
Open Source statistical textbooks?
Try IPSUR, Introduction to Probability and Statistics Using R by G. Jay Kerns. It's "free, in the GNU sense of the word".
http://ipsur.r-forge.r-project.org/book/
It's definitely open source - on the download page you can download the LaTeX source or the lyx source used to generate this.
|
Open Source statistical textbooks?
Try IPSUR, Introduction to Probability and Statistics Using R by G. Jay Kerns. It's "free, in the GNU sense of the word".
http://ipsur.r-forge.r-project.org/book/
It's definitely open source - on the
|
6,577
|
Open Source statistical textbooks?
|
Michael Lavine: Introduction to Statistical Thought, licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
|
Open Source statistical textbooks?
|
Michael Lavine: Introduction to Statistical Thought, licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
|
Open Source statistical textbooks?
Michael Lavine: Introduction to Statistical Thought, licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
|
Open Source statistical textbooks?
Michael Lavine: Introduction to Statistical Thought, licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
|
6,578
|
Open Source statistical textbooks?
|
Multivariate statistics with R
|
Open Source statistical textbooks?
|
Multivariate statistics with R
|
Open Source statistical textbooks?
Multivariate statistics with R
|
Open Source statistical textbooks?
Multivariate statistics with R
|
6,579
|
Open Source statistical textbooks?
|
The "Statistics" book on wikibooks
|
Open Source statistical textbooks?
|
The "Statistics" book on wikibooks
|
Open Source statistical textbooks?
The "Statistics" book on wikibooks
|
Open Source statistical textbooks?
The "Statistics" book on wikibooks
|
6,580
|
Open Source statistical textbooks?
|
OpenIntro Statistics is available via CC BY-SA. The LaTeX source code plus the R code to generate every figure in the textbook is also readily available in a single download.
OpenIntro's website also highlights several other freely available statistics textbooks at the beginner, intermediate, and advanced levels.
|
Open Source statistical textbooks?
|
OpenIntro Statistics is available via CC BY-SA. The LaTeX source code plus the R code to generate every figure in the textbook is also readily available in a single download.
OpenIntro's website also
|
Open Source statistical textbooks?
OpenIntro Statistics is available via CC BY-SA. The LaTeX source code plus the R code to generate every figure in the textbook is also readily available in a single download.
OpenIntro's website also highlights several other freely available statistics textbooks at the beginner, intermediate, and advanced levels.
|
Open Source statistical textbooks?
OpenIntro Statistics is available via CC BY-SA. The LaTeX source code plus the R code to generate every figure in the textbook is also readily available in a single download.
OpenIntro's website also
|
6,581
|
Open Source statistical textbooks?
|
Statistical Analysis with the General Linear Model
It covers basic linear models (ANOVA, ANCOVA, multiple regression). I can tell by personal experience that it is really really good book to get into the general framework of linear models, which are very useful in many advanced approaches (e.g., hierarchical modeling).
|
Open Source statistical textbooks?
|
Statistical Analysis with the General Linear Model
It covers basic linear models (ANOVA, ANCOVA, multiple regression). I can tell by personal experience that it is really really good book to get into
|
Open Source statistical textbooks?
Statistical Analysis with the General Linear Model
It covers basic linear models (ANOVA, ANCOVA, multiple regression). I can tell by personal experience that it is really really good book to get into the general framework of linear models, which are very useful in many advanced approaches (e.g., hierarchical modeling).
|
Open Source statistical textbooks?
Statistical Analysis with the General Linear Model
It covers basic linear models (ANOVA, ANCOVA, multiple regression). I can tell by personal experience that it is really really good book to get into
|
6,582
|
Open Source statistical textbooks?
|
Street-Fighting Mathematics. The Art of Educated Guessing and Opportunistic Problem Solving by Sanjoy Mahajan from MIT. Available under a Creative Commons Noncommercial Share Alike license.
Available as a free download on the MIT Press website (but not from the author's website).
|
Open Source statistical textbooks?
|
Street-Fighting Mathematics. The Art of Educated Guessing and Opportunistic Problem Solving by Sanjoy Mahajan from MIT. Available under a Creative Commons Noncommercial Share Alike license.
Available
|
Open Source statistical textbooks?
Street-Fighting Mathematics. The Art of Educated Guessing and Opportunistic Problem Solving by Sanjoy Mahajan from MIT. Available under a Creative Commons Noncommercial Share Alike license.
Available as a free download on the MIT Press website (but not from the author's website).
|
Open Source statistical textbooks?
Street-Fighting Mathematics. The Art of Educated Guessing and Opportunistic Problem Solving by Sanjoy Mahajan from MIT. Available under a Creative Commons Noncommercial Share Alike license.
Available
|
6,583
|
Open Source statistical textbooks?
|
R programming wiki book
|
Open Source statistical textbooks?
|
R programming wiki book
|
Open Source statistical textbooks?
R programming wiki book
|
Open Source statistical textbooks?
R programming wiki book
|
6,584
|
Open Source statistical textbooks?
|
Collaborative Statistics is CC BY: http://cnx.org/content/col10522/latest/
|
Open Source statistical textbooks?
|
Collaborative Statistics is CC BY: http://cnx.org/content/col10522/latest/
|
Open Source statistical textbooks?
Collaborative Statistics is CC BY: http://cnx.org/content/col10522/latest/
|
Open Source statistical textbooks?
Collaborative Statistics is CC BY: http://cnx.org/content/col10522/latest/
|
6,585
|
Open Source statistical textbooks?
|
Some googling found Statistics & Probability on CollegeOpenTextbooks.org. Still, be aware that most of CC-ed material is share-aliked (so you must also publish your work on CC) or at least attributed (so you must add info that certain part was copied and from whom). The same works with GFDL (both SA & A), it is even worse since in principle you should print it along with the document.
|
Open Source statistical textbooks?
|
Some googling found Statistics & Probability on CollegeOpenTextbooks.org. Still, be aware that most of CC-ed material is share-aliked (so you must also publish your work on CC) or at least attributed
|
Open Source statistical textbooks?
Some googling found Statistics & Probability on CollegeOpenTextbooks.org. Still, be aware that most of CC-ed material is share-aliked (so you must also publish your work on CC) or at least attributed (so you must add info that certain part was copied and from whom). The same works with GFDL (both SA & A), it is even worse since in principle you should print it along with the document.
|
Open Source statistical textbooks?
Some googling found Statistics & Probability on CollegeOpenTextbooks.org. Still, be aware that most of CC-ed material is share-aliked (so you must also publish your work on CC) or at least attributed
|
6,586
|
Open Source statistical textbooks?
|
Look at Statistics Topics ebook on Amazon by Mehta, and his free web log Statistics Ideas that has lecture slides. Nearly free and better in some pedagogical topics, than the ones you cite on your list of resources.
|
Open Source statistical textbooks?
|
Look at Statistics Topics ebook on Amazon by Mehta, and his free web log Statistics Ideas that has lecture slides. Nearly free and better in some pedagogical topics, than the ones you cite on your li
|
Open Source statistical textbooks?
Look at Statistics Topics ebook on Amazon by Mehta, and his free web log Statistics Ideas that has lecture slides. Nearly free and better in some pedagogical topics, than the ones you cite on your list of resources.
|
Open Source statistical textbooks?
Look at Statistics Topics ebook on Amazon by Mehta, and his free web log Statistics Ideas that has lecture slides. Nearly free and better in some pedagogical topics, than the ones you cite on your li
|
6,587
|
How to translate the results from lm() to an equation?
|
Consider this example:
set.seed(5) # this line will allow you to run these commands on your
# own computer & get *exactly* the same output
x = rnorm(50)
y = rnorm(50)
fit = lm(y~x)
summary(fit)
# Call:
# lm(formula = y ~ x)
#
# Residuals:
# Min 1Q Median 3Q Max
# -2.04003 -0.43414 -0.04609 0.50807 2.48728
#
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) -0.00761 0.11554 -0.066 0.948
# x 0.09156 0.10901 0.840 0.405
#
# Residual standard error: 0.8155 on 48 degrees of freedom
# Multiple R-squared: 0.01449, Adjusted R-squared: -0.006046
# F-statistic: 0.7055 on 1 and 48 DF, p-value: 0.4051
The question, I'm guessing, is how to figure out the regression equation from R's summary output. Algebraically, the equation for a simple regression model is:
$$
\hat y_i = \hat\beta_0 + \hat\beta_1 x_i + \hat\varepsilon_i \\
\text{where } \varepsilon\sim\mathcal N(0,~\hat\sigma^2)
$$
We just need to map the summary.lm() output to these terms. To wit:
$\hat\beta_0$ is the Estimate value in the (Intercept) row (specifically, -0.00761)
$\hat\beta_1$ is the Estimate value in the x row (specifically, 0.09156)
$\hat\sigma$ is the Residual standard error (specifically, 0.8155)
Plugging these in above yields:
$$
\hat y_i = -0.00761~+~0.09156 x_i~+~\hat\varepsilon_i \\
\text{where } \varepsilon\sim\mathcal N(0,~0.8155^2)
$$
For a more thorough overview, you may want to read this thread: Interpretation of R's lm() output.
|
How to translate the results from lm() to an equation?
|
Consider this example:
set.seed(5) # this line will allow you to run these commands on your
# own computer & get *exactly* the same output
x = rnorm(50)
y = rnorm(5
|
How to translate the results from lm() to an equation?
Consider this example:
set.seed(5) # this line will allow you to run these commands on your
# own computer & get *exactly* the same output
x = rnorm(50)
y = rnorm(50)
fit = lm(y~x)
summary(fit)
# Call:
# lm(formula = y ~ x)
#
# Residuals:
# Min 1Q Median 3Q Max
# -2.04003 -0.43414 -0.04609 0.50807 2.48728
#
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) -0.00761 0.11554 -0.066 0.948
# x 0.09156 0.10901 0.840 0.405
#
# Residual standard error: 0.8155 on 48 degrees of freedom
# Multiple R-squared: 0.01449, Adjusted R-squared: -0.006046
# F-statistic: 0.7055 on 1 and 48 DF, p-value: 0.4051
The question, I'm guessing, is how to figure out the regression equation from R's summary output. Algebraically, the equation for a simple regression model is:
$$
\hat y_i = \hat\beta_0 + \hat\beta_1 x_i + \hat\varepsilon_i \\
\text{where } \varepsilon\sim\mathcal N(0,~\hat\sigma^2)
$$
We just need to map the summary.lm() output to these terms. To wit:
$\hat\beta_0$ is the Estimate value in the (Intercept) row (specifically, -0.00761)
$\hat\beta_1$ is the Estimate value in the x row (specifically, 0.09156)
$\hat\sigma$ is the Residual standard error (specifically, 0.8155)
Plugging these in above yields:
$$
\hat y_i = -0.00761~+~0.09156 x_i~+~\hat\varepsilon_i \\
\text{where } \varepsilon\sim\mathcal N(0,~0.8155^2)
$$
For a more thorough overview, you may want to read this thread: Interpretation of R's lm() output.
|
How to translate the results from lm() to an equation?
Consider this example:
set.seed(5) # this line will allow you to run these commands on your
# own computer & get *exactly* the same output
x = rnorm(50)
y = rnorm(5
|
6,588
|
How to translate the results from lm() to an equation?
|
If what you want is to predict scores using your resulting regression equation, you can construct the equation by hand by typing summary(fit) (if your regression analysis is stored in a variable called fit, for example), and looking at the estimates for each coefficient included in your model.
For example, if you have a simple regression of the type $y=\beta_0+\beta_1x+\epsilon$, and you get an estimate of the intercept ($\beta_0$) of +0.5 and an estimate of the effect of x on y ($\beta_1$) of +1.6, you would predict an individual's y score from their x score by computing: $\hat{y}=0.5+1.6x$.
However, this is the hard route. R has a built-in function, predict(), which you can use to automatically compute predicted values given a model for any dataset. For example: predict(fit, newdata=data), if the x scores you want to use to predict y scores are stored in the variable data. (Note that in order to see the predicted scores for the sample on which your regression was performed, you can simply type fit$fitted or fitted(fit); these will give you the predicted, a.k.a. fitted, values.)
|
How to translate the results from lm() to an equation?
|
If what you want is to predict scores using your resulting regression equation, you can construct the equation by hand by typing summary(fit) (if your regression analysis is stored in a variable calle
|
How to translate the results from lm() to an equation?
If what you want is to predict scores using your resulting regression equation, you can construct the equation by hand by typing summary(fit) (if your regression analysis is stored in a variable called fit, for example), and looking at the estimates for each coefficient included in your model.
For example, if you have a simple regression of the type $y=\beta_0+\beta_1x+\epsilon$, and you get an estimate of the intercept ($\beta_0$) of +0.5 and an estimate of the effect of x on y ($\beta_1$) of +1.6, you would predict an individual's y score from their x score by computing: $\hat{y}=0.5+1.6x$.
However, this is the hard route. R has a built-in function, predict(), which you can use to automatically compute predicted values given a model for any dataset. For example: predict(fit, newdata=data), if the x scores you want to use to predict y scores are stored in the variable data. (Note that in order to see the predicted scores for the sample on which your regression was performed, you can simply type fit$fitted or fitted(fit); these will give you the predicted, a.k.a. fitted, values.)
|
How to translate the results from lm() to an equation?
If what you want is to predict scores using your resulting regression equation, you can construct the equation by hand by typing summary(fit) (if your regression analysis is stored in a variable calle
|
6,589
|
How to translate the results from lm() to an equation?
|
Building on @keithpjolley's answer, this replaces the '+' signs used in the separator with the actual sign of the co-efficient and replaces the 'y' with whatever the model's dependent variable actually is.
The function accepts arguments to 'format', such as 'digits' and 'trim'.
library(dplyr)
model_equation <- function(model, ...) {
format_args <- list(...)
model_coeff <- model$coefficients
format_args$x <- abs(model$coefficients)
model_coeff_sign <- sign(model_coeff)
model_coeff_prefix <- case_when(model_coeff_sign == -1 ~ " - ",
model_coeff_sign == 1 ~ " + ",
model_coeff_sign == 0 ~ " + ")
model_eqn <- paste(strsplit(as.character(model$call$formula), "~")[[2]], # 'y'
"=",
paste(if_else(model_coeff[1]<0, "- ", ""),
do.call(format, format_args)[1],
paste(model_coeff_prefix[-1],
do.call(format, format_args)[-1],
" * ",
names(model_coeff[-1]),
sep = "", collapse = ""),
sep = ""))
return(model_eqn)
}
library(MASS)
modelcrime <- lm(y ~ ., data = UScrime)
model_equation(modelcrime, digits = 3, trim = TRUE)
produces the result
[1] "y = - 5984.288 + 8.783 * M - 3.803 * So + 18.832 * Ed + 19.280 * Po1 - 10.942 * Po2 - 0.664 * LF + 1.741 * M.F - 0.733 * Pop + 0.420 * NW - 5.827 * U1 + 16.780 * U2 + 0.962 * GDP + 7.067 * Ineq - 4855.266 * Prob - 3.479 * Time"
and
library(car)
state.x77=as.data.frame(state.x77)
model.x77 <- lm(Murder ~ ., data = state.x77)
model_equation(model.x77, digits = 2)
produces
[1] "Murder = 1.2e+02 + 1.9e-04 * Population - 1.6e-04 * Income + 1.4e+00 * Illiteracy - 1.7e+00 * Life.Exp + 3.2e-02 * HS.Grad - 1.3e-02 * Frost + 6.0e-06 * Area"
*** Edit
made explicit the requirement for 'dplyr'
functionalized the code
incorporated improvements found in rvezy's answer - 'flexible' y argument, use of 'format' arguments
|
How to translate the results from lm() to an equation?
|
Building on @keithpjolley's answer, this replaces the '+' signs used in the separator with the actual sign of the co-efficient and replaces the 'y' with whatever the model's dependent variable actuall
|
How to translate the results from lm() to an equation?
Building on @keithpjolley's answer, this replaces the '+' signs used in the separator with the actual sign of the co-efficient and replaces the 'y' with whatever the model's dependent variable actually is.
The function accepts arguments to 'format', such as 'digits' and 'trim'.
library(dplyr)
model_equation <- function(model, ...) {
format_args <- list(...)
model_coeff <- model$coefficients
format_args$x <- abs(model$coefficients)
model_coeff_sign <- sign(model_coeff)
model_coeff_prefix <- case_when(model_coeff_sign == -1 ~ " - ",
model_coeff_sign == 1 ~ " + ",
model_coeff_sign == 0 ~ " + ")
model_eqn <- paste(strsplit(as.character(model$call$formula), "~")[[2]], # 'y'
"=",
paste(if_else(model_coeff[1]<0, "- ", ""),
do.call(format, format_args)[1],
paste(model_coeff_prefix[-1],
do.call(format, format_args)[-1],
" * ",
names(model_coeff[-1]),
sep = "", collapse = ""),
sep = ""))
return(model_eqn)
}
library(MASS)
modelcrime <- lm(y ~ ., data = UScrime)
model_equation(modelcrime, digits = 3, trim = TRUE)
produces the result
[1] "y = - 5984.288 + 8.783 * M - 3.803 * So + 18.832 * Ed + 19.280 * Po1 - 10.942 * Po2 - 0.664 * LF + 1.741 * M.F - 0.733 * Pop + 0.420 * NW - 5.827 * U1 + 16.780 * U2 + 0.962 * GDP + 7.067 * Ineq - 4855.266 * Prob - 3.479 * Time"
and
library(car)
state.x77=as.data.frame(state.x77)
model.x77 <- lm(Murder ~ ., data = state.x77)
model_equation(model.x77, digits = 2)
produces
[1] "Murder = 1.2e+02 + 1.9e-04 * Population - 1.6e-04 * Income + 1.4e+00 * Illiteracy - 1.7e+00 * Life.Exp + 3.2e-02 * HS.Grad - 1.3e-02 * Frost + 6.0e-06 * Area"
*** Edit
made explicit the requirement for 'dplyr'
functionalized the code
incorporated improvements found in rvezy's answer - 'flexible' y argument, use of 'format' arguments
|
How to translate the results from lm() to an equation?
Building on @keithpjolley's answer, this replaces the '+' signs used in the separator with the actual sign of the co-efficient and replaces the 'y' with whatever the model's dependent variable actuall
|
6,590
|
How to translate the results from lm() to an equation?
|
If you want to show the equation, like to cut/paste into a doc, but don't want to fuss with putting the entire equation together:
R> library(MASS)
R> crime.lm <- lm(y~., UScrime)
R> cc <- crime.lm$coefficients
R> (eqn <- paste("Y =", paste(round(cc[1],2), paste(round(cc[-1],2), names(cc[-1]), sep=" * ", collapse=" + "), sep=" + "), "+ e"))
[1] "Y = -5984.29 + 8.78 * M + -3.8 * So + 18.83 * Ed + 19.28 * Po1 + -10.94 * Po2 + -0.66 * LF + 1.74 * M.F + -0.73 * Pop + 0.42 * NW + -5.83 * U1 + 16.78 * U2 + 0.96 * GDP + 7.07 * Ineq + -4855.27 * Prob + -3.48 * Time + e"
Edit for if the spaces and signs bother:
R> (eqn <- gsub('\\+ -', '- ', gsub(' \\* ', '*', eqn)))
[1] "Y = -5984.29 + 8.78*M - 3.8*So + 18.83*Ed + 19.28*Po1 - 10.94*Po2 - 0.66*LF + 1.74*M.F - 0.73*Pop + 0.42*NW - 5.83*U1 + 16.78*U2 + 0.96*GDP + 7.07*Ineq - 4855.27*Prob - 3.48*Time + e"
|
How to translate the results from lm() to an equation?
|
If you want to show the equation, like to cut/paste into a doc, but don't want to fuss with putting the entire equation together:
R> library(MASS)
R> crime.lm <- lm(y~., UScrime)
R> cc <- crime.lm$coe
|
How to translate the results from lm() to an equation?
If you want to show the equation, like to cut/paste into a doc, but don't want to fuss with putting the entire equation together:
R> library(MASS)
R> crime.lm <- lm(y~., UScrime)
R> cc <- crime.lm$coefficients
R> (eqn <- paste("Y =", paste(round(cc[1],2), paste(round(cc[-1],2), names(cc[-1]), sep=" * ", collapse=" + "), sep=" + "), "+ e"))
[1] "Y = -5984.29 + 8.78 * M + -3.8 * So + 18.83 * Ed + 19.28 * Po1 + -10.94 * Po2 + -0.66 * LF + 1.74 * M.F + -0.73 * Pop + 0.42 * NW + -5.83 * U1 + 16.78 * U2 + 0.96 * GDP + 7.07 * Ineq + -4855.27 * Prob + -3.48 * Time + e"
Edit for if the spaces and signs bother:
R> (eqn <- gsub('\\+ -', '- ', gsub(' \\* ', '*', eqn)))
[1] "Y = -5984.29 + 8.78*M - 3.8*So + 18.83*Ed + 19.28*Po1 - 10.94*Po2 - 0.66*LF + 1.74*M.F - 0.73*Pop + 0.42*NW - 5.83*U1 + 16.78*U2 + 0.96*GDP + 7.07*Ineq - 4855.27*Prob - 3.48*Time + e"
|
How to translate the results from lm() to an equation?
If you want to show the equation, like to cut/paste into a doc, but don't want to fuss with putting the entire equation together:
R> library(MASS)
R> crime.lm <- lm(y~., UScrime)
R> cc <- crime.lm$coe
|
6,591
|
How to translate the results from lm() to an equation?
|
You can use the equatiomatic package to solve many challenges with extracting and reporting equations. https://github.com/datalorax/equatiomatic
Basic Example
Inserting Model Coefficients
You can also include the coefficients.
|
How to translate the results from lm() to an equation?
|
You can use the equatiomatic package to solve many challenges with extracting and reporting equations. https://github.com/datalorax/equatiomatic
Basic Example
Inserting Model Coefficients
You can als
|
How to translate the results from lm() to an equation?
You can use the equatiomatic package to solve many challenges with extracting and reporting equations. https://github.com/datalorax/equatiomatic
Basic Example
Inserting Model Coefficients
You can also include the coefficients.
|
How to translate the results from lm() to an equation?
You can use the equatiomatic package to solve many challenges with extracting and reporting equations. https://github.com/datalorax/equatiomatic
Basic Example
Inserting Model Coefficients
You can als
|
6,592
|
What is the difference between a stationary test and a unit root test?
|
I don't know how those tests work in detail, but one difference is that ADF test uses null hypothesis that a series contains a unit root, while KPSS test uses null hypothesis that the series is stationary.
Here is wikipedia passage that might be useful:
In econometrics, Kwiatkowski–Phillips–Schmidt–Shin (KPSS) tests are
used for testing a null hypothesis that an observable time series is
stationary around a deterministic trend. Such models were proposed in
1982 by Alok Bhargava in his Ph.D. thesis where several John von
Neumann or Durbin–Watson type finite sample tests for unit roots were
developed (see Bhargava, 1986). Later, Denis Kwiatkowski, Peter C.B.
Phillips, Peter Schmidt and Yongcheol Shin (1992) proposed a test of
the null hypothesis that an observable series is trend stationary
(stationary around a deterministic trend). The series is expressed as
the sum of deterministic trend, random walk, and stationary error, and
the test is the Lagrange multiplier test of the hypothesis that the
random walk has zero variance. KPSS type tests are intended to
complement unit root tests, such as the Dickey–Fuller tests. By
testing both the unit root hypothesis and the stationarity hypothesis,
one can distinguish series that appear to be stationary, series that
appear to have a unit root, and series for which the data (or the
tests) are not sufficiently informative to be sure whether they are
stationary or integrated.
KPSS test
|
What is the difference between a stationary test and a unit root test?
|
I don't know how those tests work in detail, but one difference is that ADF test uses null hypothesis that a series contains a unit root, while KPSS test uses null hypothesis that the series is statio
|
What is the difference between a stationary test and a unit root test?
I don't know how those tests work in detail, but one difference is that ADF test uses null hypothesis that a series contains a unit root, while KPSS test uses null hypothesis that the series is stationary.
Here is wikipedia passage that might be useful:
In econometrics, Kwiatkowski–Phillips–Schmidt–Shin (KPSS) tests are
used for testing a null hypothesis that an observable time series is
stationary around a deterministic trend. Such models were proposed in
1982 by Alok Bhargava in his Ph.D. thesis where several John von
Neumann or Durbin–Watson type finite sample tests for unit roots were
developed (see Bhargava, 1986). Later, Denis Kwiatkowski, Peter C.B.
Phillips, Peter Schmidt and Yongcheol Shin (1992) proposed a test of
the null hypothesis that an observable series is trend stationary
(stationary around a deterministic trend). The series is expressed as
the sum of deterministic trend, random walk, and stationary error, and
the test is the Lagrange multiplier test of the hypothesis that the
random walk has zero variance. KPSS type tests are intended to
complement unit root tests, such as the Dickey–Fuller tests. By
testing both the unit root hypothesis and the stationarity hypothesis,
one can distinguish series that appear to be stationary, series that
appear to have a unit root, and series for which the data (or the
tests) are not sufficiently informative to be sure whether they are
stationary or integrated.
KPSS test
|
What is the difference between a stationary test and a unit root test?
I don't know how those tests work in detail, but one difference is that ADF test uses null hypothesis that a series contains a unit root, while KPSS test uses null hypothesis that the series is statio
|
6,593
|
What is the difference between a stationary test and a unit root test?
|
The Concepts and examples of Unit-root tests and stationarity tests
Concept of Unit-root tests:
Null hypothesis: Unit-root
Alternative hypothesis: Process has root outside the unit circle, which is usually equivalent to stationarity or trend stationarity
Concept of Stationarity tests
Null hypothesis: (Trend) Stationarity
Alternative hypothesis: There is a unit root.
There are many different Unit-root tests and many Stationarity tests.
Some Unit root tests:
Dickey-Fuller test
Augmented Dickey Fuller test
Phillipps-Perron test
Zivot-Andrews test
ADF-GLS test
The most simple test is the DF-test. The ADF and the PP test are similar to the Dickey-Fuller test, but they correct for lags. The ADF does so by including them the PP test does so by adjusting the test statistics.
Some Stationarity tests:
KPSS
Leybourne-McCabe
In practice KPSS test is used far more often. The main difference of both tests is that KPSS is a non-parametric test and Leybourne-McCabe is a parametric test.
How unit-root test and stationarity-test complement each other
If you have a time series data set how it usually appears in econometric time series I propose you should apply both a Unit root test: (Augmented) Dickey Fuller or Phillips-Perron depending on the structure of the underlying data and a KPSS test.
Case 1 Unit root test: you can’t reject $H_0$; KPSS test: reject $H_0$. Both imply that series has unit root.
Case 2 Unit root test: Reject $H_0$. KPSS test: don't reject $H_0$. Both imply that series is stationary.
Case 3 If we can’t reject both test: data give not enough observations.
Case 4 Reject unit root, reject stationarity: both hypotheses are component
hypotheses – heteroskedasticity in a series may make a big difference; if
there is structural break it will affect inference.
Power problem: if there is small random walk component (small
variance $\sigma^{2}_{\mu}$), we can’t reject unit root and can’t reject stationarity.
Economics: if the series is highly persistent we can’t reject $H_0$ (unit
root) – highly persistent may be even without unit root, but it also means
we shouldn’t treat/take data in levels. Whether a time series is "highly persistent" can be measured with the p-value of a unit-root test. For a more detailed discussion what "persistence" means in time-series see: Persistence in time series
General rule about statistical testing You cannot proove a null hypothesis, you can only affirm it. However, if you reject a null hypothesis then you can be very sure that the null hypothesis is really not true. Thus alternative hypothesis is always a stronger hypothesis than the null hypothesis.
Variance ratio tests:
If we want to quantify how important the unit root is, we should use a
variance ratio test.
In contrast to unit root and stationarity tests, variance ratio tests can also detect the strength of the unit root. The outcomes of a variance ratio test can be divided into roughly 5 different groups.
Bigger than 1 After the shock the value of the variable explodes even more in the direction of the shock.
(Close to) 1 You get this value in the "classical case of a unit root"
Between 0 and 1 After the shock the value approaches a level between the value before the shock and the value after the shock.
(Close to) 0 The series is (close to) stationary
Negative After the shock the value goes into the opposite direction, i.e. if the value before the shock is 20 and the value after the shock is 10 over the long haul the variable will take on values greater than 20.
|
What is the difference between a stationary test and a unit root test?
|
The Concepts and examples of Unit-root tests and stationarity tests
Concept of Unit-root tests:
Null hypothesis: Unit-root
Alternative hypothesis: Process has root outside the unit circle, which is u
|
What is the difference between a stationary test and a unit root test?
The Concepts and examples of Unit-root tests and stationarity tests
Concept of Unit-root tests:
Null hypothesis: Unit-root
Alternative hypothesis: Process has root outside the unit circle, which is usually equivalent to stationarity or trend stationarity
Concept of Stationarity tests
Null hypothesis: (Trend) Stationarity
Alternative hypothesis: There is a unit root.
There are many different Unit-root tests and many Stationarity tests.
Some Unit root tests:
Dickey-Fuller test
Augmented Dickey Fuller test
Phillipps-Perron test
Zivot-Andrews test
ADF-GLS test
The most simple test is the DF-test. The ADF and the PP test are similar to the Dickey-Fuller test, but they correct for lags. The ADF does so by including them the PP test does so by adjusting the test statistics.
Some Stationarity tests:
KPSS
Leybourne-McCabe
In practice KPSS test is used far more often. The main difference of both tests is that KPSS is a non-parametric test and Leybourne-McCabe is a parametric test.
How unit-root test and stationarity-test complement each other
If you have a time series data set how it usually appears in econometric time series I propose you should apply both a Unit root test: (Augmented) Dickey Fuller or Phillips-Perron depending on the structure of the underlying data and a KPSS test.
Case 1 Unit root test: you can’t reject $H_0$; KPSS test: reject $H_0$. Both imply that series has unit root.
Case 2 Unit root test: Reject $H_0$. KPSS test: don't reject $H_0$. Both imply that series is stationary.
Case 3 If we can’t reject both test: data give not enough observations.
Case 4 Reject unit root, reject stationarity: both hypotheses are component
hypotheses – heteroskedasticity in a series may make a big difference; if
there is structural break it will affect inference.
Power problem: if there is small random walk component (small
variance $\sigma^{2}_{\mu}$), we can’t reject unit root and can’t reject stationarity.
Economics: if the series is highly persistent we can’t reject $H_0$ (unit
root) – highly persistent may be even without unit root, but it also means
we shouldn’t treat/take data in levels. Whether a time series is "highly persistent" can be measured with the p-value of a unit-root test. For a more detailed discussion what "persistence" means in time-series see: Persistence in time series
General rule about statistical testing You cannot proove a null hypothesis, you can only affirm it. However, if you reject a null hypothesis then you can be very sure that the null hypothesis is really not true. Thus alternative hypothesis is always a stronger hypothesis than the null hypothesis.
Variance ratio tests:
If we want to quantify how important the unit root is, we should use a
variance ratio test.
In contrast to unit root and stationarity tests, variance ratio tests can also detect the strength of the unit root. The outcomes of a variance ratio test can be divided into roughly 5 different groups.
Bigger than 1 After the shock the value of the variable explodes even more in the direction of the shock.
(Close to) 1 You get this value in the "classical case of a unit root"
Between 0 and 1 After the shock the value approaches a level between the value before the shock and the value after the shock.
(Close to) 0 The series is (close to) stationary
Negative After the shock the value goes into the opposite direction, i.e. if the value before the shock is 20 and the value after the shock is 10 over the long haul the variable will take on values greater than 20.
|
What is the difference between a stationary test and a unit root test?
The Concepts and examples of Unit-root tests and stationarity tests
Concept of Unit-root tests:
Null hypothesis: Unit-root
Alternative hypothesis: Process has root outside the unit circle, which is u
|
6,594
|
What is the difference between a stationary test and a unit root test?
|
I don't totally agree with the accepted answer: the null hypothesis of the KPSS test is not stationarity, but trend stationarity, which is quite a different concept.
To summarize:
KPSS test:
Null Hypothesis: the process is trend-stationary
Alternative Hypothesis: the process has a unit root (this is how the authors of the test defined the alternative in their original 1992 paper)
ADF test:
Null Hypothesis: the process has a unit-root ("difference stationary")
Alternative Hypothesis: the process has no unit root. It can mean either that the process is stationary, or trend stationary, depending on which version of the ADF test is used.
If the "deterministic time trend alternative hypothesis" version of the ADF test is used, then both tests are similar, except that ones defines the null hypothesis as the unit-root while the other defines it as the alternative.
|
What is the difference between a stationary test and a unit root test?
|
I don't totally agree with the accepted answer: the null hypothesis of the KPSS test is not stationarity, but trend stationarity, which is quite a different concept.
To summarize:
KPSS test:
Null Hyp
|
What is the difference between a stationary test and a unit root test?
I don't totally agree with the accepted answer: the null hypothesis of the KPSS test is not stationarity, but trend stationarity, which is quite a different concept.
To summarize:
KPSS test:
Null Hypothesis: the process is trend-stationary
Alternative Hypothesis: the process has a unit root (this is how the authors of the test defined the alternative in their original 1992 paper)
ADF test:
Null Hypothesis: the process has a unit-root ("difference stationary")
Alternative Hypothesis: the process has no unit root. It can mean either that the process is stationary, or trend stationary, depending on which version of the ADF test is used.
If the "deterministic time trend alternative hypothesis" version of the ADF test is used, then both tests are similar, except that ones defines the null hypothesis as the unit-root while the other defines it as the alternative.
|
What is the difference between a stationary test and a unit root test?
I don't totally agree with the accepted answer: the null hypothesis of the KPSS test is not stationarity, but trend stationarity, which is quite a different concept.
To summarize:
KPSS test:
Null Hyp
|
6,595
|
What is the difference between a stationary test and a unit root test?
|
I don't know the specifics of the two tests you mentioned but I can address the general question posed in the title of your question and maybe that applies to these specific tests. Stationarity is a property of stochastic processes (or time series in particular) where the joint distribution of any k consecutive observations does not change with a time shift. There can be many ways to test for this, or its weaker form covariance stationary, where only the mean and the second moments remain constant with time changes. If the time series specifically follows an autoregressive process there is a characteristic polynomial corresponding to the model. For autoregressive time series, the series is covariance stationary if and only if all the roots of the characteristic polynomial are outside the unit circle in the complex plane. So testing for unit roots is a test for a specific type of non-stationarity for a specific type of time series models. Other tests can test for other forms of nonstationarity and deal with more general forms of time series.
|
What is the difference between a stationary test and a unit root test?
|
I don't know the specifics of the two tests you mentioned but I can address the general question posed in the title of your question and maybe that applies to these specific tests. Stationarity is a
|
What is the difference between a stationary test and a unit root test?
I don't know the specifics of the two tests you mentioned but I can address the general question posed in the title of your question and maybe that applies to these specific tests. Stationarity is a property of stochastic processes (or time series in particular) where the joint distribution of any k consecutive observations does not change with a time shift. There can be many ways to test for this, or its weaker form covariance stationary, where only the mean and the second moments remain constant with time changes. If the time series specifically follows an autoregressive process there is a characteristic polynomial corresponding to the model. For autoregressive time series, the series is covariance stationary if and only if all the roots of the characteristic polynomial are outside the unit circle in the complex plane. So testing for unit roots is a test for a specific type of non-stationarity for a specific type of time series models. Other tests can test for other forms of nonstationarity and deal with more general forms of time series.
|
What is the difference between a stationary test and a unit root test?
I don't know the specifics of the two tests you mentioned but I can address the general question posed in the title of your question and maybe that applies to these specific tests. Stationarity is a
|
6,596
|
What exactly is a seed in a random number generator?
|
Most pseudo-random number generators (PRNGs) are build on algorithms involving some kind of recursive method starting from a base value that is determined by an input called the "seed". The default PRNG in most statistical software (R, Python, Stata, etc.) is the Mersenne Twister algorithm MT19937, which is set out in Matsumoto and Nishimura (1998). This is a complicated algorithm, so it would be best to read the paper on it if you want to know how it works in detail. In this particular algorithm, there is a recurrence relation of degree $n$, and your input seed is an initial set of vectors $\mathbf{x}_0, \mathbf{x}_1, ..., \mathbf{x}_{n-1}$. The algorithm uses a linear recurrence relation that generates:
$$\mathbf{x}_{n+k} = f(\mathbf{x}_k, \mathbf{x}_{k+1}, \mathbf{x}_{k+m}, r, \mathbf{A}),$$
where $1 \leqslant m \leqslant n$ and $r$ and $\mathbf{A}$ are objects that can be specified as parameters in the algorithm. Since the seed gives the initial set of vectors (and given other fixed parameters for the algorithm), the series of pseudo-random numbers generated by the algorithm is fixed. If you change the seed then you change the initial vectors, which changes the pseudo-random numbers generated by the algorithm. This is, of course, the function of the seed.
Now, it is important to note that this is just one example, using the MT19937 algorithm. There are many PRNGs that can be used in statistical software, and they each involve different recursive methods, and so the seed means a different thing (in technical terms) in each of them. You can find a library of PRNGs for R in this documentation, which lists the available algorithms and the papers that describe these algorithms.
The purpose of the seed is to allow the user to "lock" the pseudo-random number generator, to allow replicable analysis. Some analysts like to set the seed using a true random-number generator (TRNG) which uses hardware inputs to generate an initial seed number, and then report this as a locked number. If the seed is set and reported by the original user then an auditor can repeat the analysis and obtain the same sequence of pseudo-random numbers as the original user. If the seed is not set then the algorithm will usually use some kind of default seed (e.g., from the system clock), and it will generally not be possible to replicate the randomisation.
|
What exactly is a seed in a random number generator?
|
Most pseudo-random number generators (PRNGs) are build on algorithms involving some kind of recursive method starting from a base value that is determined by an input called the "seed". The default P
|
What exactly is a seed in a random number generator?
Most pseudo-random number generators (PRNGs) are build on algorithms involving some kind of recursive method starting from a base value that is determined by an input called the "seed". The default PRNG in most statistical software (R, Python, Stata, etc.) is the Mersenne Twister algorithm MT19937, which is set out in Matsumoto and Nishimura (1998). This is a complicated algorithm, so it would be best to read the paper on it if you want to know how it works in detail. In this particular algorithm, there is a recurrence relation of degree $n$, and your input seed is an initial set of vectors $\mathbf{x}_0, \mathbf{x}_1, ..., \mathbf{x}_{n-1}$. The algorithm uses a linear recurrence relation that generates:
$$\mathbf{x}_{n+k} = f(\mathbf{x}_k, \mathbf{x}_{k+1}, \mathbf{x}_{k+m}, r, \mathbf{A}),$$
where $1 \leqslant m \leqslant n$ and $r$ and $\mathbf{A}$ are objects that can be specified as parameters in the algorithm. Since the seed gives the initial set of vectors (and given other fixed parameters for the algorithm), the series of pseudo-random numbers generated by the algorithm is fixed. If you change the seed then you change the initial vectors, which changes the pseudo-random numbers generated by the algorithm. This is, of course, the function of the seed.
Now, it is important to note that this is just one example, using the MT19937 algorithm. There are many PRNGs that can be used in statistical software, and they each involve different recursive methods, and so the seed means a different thing (in technical terms) in each of them. You can find a library of PRNGs for R in this documentation, which lists the available algorithms and the papers that describe these algorithms.
The purpose of the seed is to allow the user to "lock" the pseudo-random number generator, to allow replicable analysis. Some analysts like to set the seed using a true random-number generator (TRNG) which uses hardware inputs to generate an initial seed number, and then report this as a locked number. If the seed is set and reported by the original user then an auditor can repeat the analysis and obtain the same sequence of pseudo-random numbers as the original user. If the seed is not set then the algorithm will usually use some kind of default seed (e.g., from the system clock), and it will generally not be possible to replicate the randomisation.
|
What exactly is a seed in a random number generator?
Most pseudo-random number generators (PRNGs) are build on algorithms involving some kind of recursive method starting from a base value that is determined by an input called the "seed". The default P
|
6,597
|
What exactly is a seed in a random number generator?
|
First, there is no true randomness in today's computer-generated "random numbers." All pseudorandom generators use
deterministic methods. (Possibly, quantum computers will change that.)
The difficult task is to contrive algorithms
that produce output that cannot meaningfully be distinguished from
data coming from a truly random source.
You are right that setting a seed starts you at a particular known
starting point in a long list of pseudorandom numbers. For the generators implemented
in R, Python, and so on, the list is hugely long. Long enough that
not even the largest feasible simulation project will exceed the 'period'
of the generator so that values begin to re-cycle.
In many ordinary applications, people do not set a seed. Then an unpredictable
seed is picked automatically (for example, from the microseconds on the
operating system clock). Pseudorandom generators in general use have been
subjected to batteries of tests, largely consisting of problems that have
proved to be difficult to simulate with earlier unsatisfactory generators.
Usually, the output of a generator consists of values that are not, for
practical purposes, distinguishable from numbers chosen truly at random
form the uniform distribution on $(0,1).$ Then those pseudorandom numbers
are manipulated to match what one would get sampling at random from other
distributions such as binomial, Poisson, normal, exponential, etc.
One test of a generator is to see if its successive pairs in 'observations' simulated as
$\mathsf{Unif}(0,1)$ actually look like they are filling the unit square
at random. (Done twice below.) The slightly marbled look is a result of inherent variability.
It would be very suspicious to get a plot that looked perfectly uniformly
grey. [At some resolutions, there may be a regular moire pattern; please
change the magnification up or down to get rid of that bogus effect if it occurs.]
set.seed(1776); m = 50000
par(mfrow=c(1,2))
u = runif(m); plot(u[1:(m-1)], u[2:m], pch=".")
u = runif(m); plot(u[1:(m-1)], u[2:m], pch=".")
par(mfrow=c(1,1))
It is sometimes useful to set a seed. Some such uses are as
follows:
When programming and debugging it is convenient to have predictable output.
So many programmers put a set.seed statement at the start of a program
until writing and debugging are done.
When teaching about simulation. If I want to show students that
I can simulate rolls of a fair die using the sample function in R, I could
cheat, running many simulations, and picking the one that comes closest to
a target theoretical value. But that would give an unrealistic impression of how simulation really works.
If I set a seed at the start, the simulation
will get the same result every time. Students can proofread their copy of
my program to make sure it gives the intended results. Then they can run
their own simulations, either with their own seeds or by letting the program
pick its own starting place.
For example, the probability of getting the total 10 when rolling two fair dice is $$3/36 = 1/12 = 0.08333333.$$ With a million 2-dice experiments I should get about two or three-place accuracy. The 95% margin of simulation error is about $$2\sqrt{(1/12)(11/12)/10^6} = 0.00055.$$
set.seed(703); m = 10^6
s = replicate( m, sum(sample(1:6, 2, rep=T)) )
mean(s == 10)
[1] 0.083456 # aprx 1/12 = 0.0833
2*sd(s == 10)/sqrt(m)
[1] 0.0005531408 # aprx 95% marg of sim err.
When sharing statistical analyses that involve simulation.
Nowadays many statistical analyses involve some simulation, for example a permutation test or a Gibbs sampler. By showing the seed, you enable
people who read the analysis to replicate the results exactly, if they wish.
When writing academic articles involving randomization. Academic articles usually go through multiple rounds of peer review. A plot may use, e.g., randomly jittered points to reduce overplotting. If the analyses need to be slightly changed in response to reviewer comments, it is good if a particular unrelated jittering does not change between review rounds, which might be disconcerting to particularly nitpicky reviewers, so you set a seed before jittering.
|
What exactly is a seed in a random number generator?
|
First, there is no true randomness in today's computer-generated "random numbers." All pseudorandom generators use
deterministic methods. (Possibly, quantum computers will change that.)
The difficult
|
What exactly is a seed in a random number generator?
First, there is no true randomness in today's computer-generated "random numbers." All pseudorandom generators use
deterministic methods. (Possibly, quantum computers will change that.)
The difficult task is to contrive algorithms
that produce output that cannot meaningfully be distinguished from
data coming from a truly random source.
You are right that setting a seed starts you at a particular known
starting point in a long list of pseudorandom numbers. For the generators implemented
in R, Python, and so on, the list is hugely long. Long enough that
not even the largest feasible simulation project will exceed the 'period'
of the generator so that values begin to re-cycle.
In many ordinary applications, people do not set a seed. Then an unpredictable
seed is picked automatically (for example, from the microseconds on the
operating system clock). Pseudorandom generators in general use have been
subjected to batteries of tests, largely consisting of problems that have
proved to be difficult to simulate with earlier unsatisfactory generators.
Usually, the output of a generator consists of values that are not, for
practical purposes, distinguishable from numbers chosen truly at random
form the uniform distribution on $(0,1).$ Then those pseudorandom numbers
are manipulated to match what one would get sampling at random from other
distributions such as binomial, Poisson, normal, exponential, etc.
One test of a generator is to see if its successive pairs in 'observations' simulated as
$\mathsf{Unif}(0,1)$ actually look like they are filling the unit square
at random. (Done twice below.) The slightly marbled look is a result of inherent variability.
It would be very suspicious to get a plot that looked perfectly uniformly
grey. [At some resolutions, there may be a regular moire pattern; please
change the magnification up or down to get rid of that bogus effect if it occurs.]
set.seed(1776); m = 50000
par(mfrow=c(1,2))
u = runif(m); plot(u[1:(m-1)], u[2:m], pch=".")
u = runif(m); plot(u[1:(m-1)], u[2:m], pch=".")
par(mfrow=c(1,1))
It is sometimes useful to set a seed. Some such uses are as
follows:
When programming and debugging it is convenient to have predictable output.
So many programmers put a set.seed statement at the start of a program
until writing and debugging are done.
When teaching about simulation. If I want to show students that
I can simulate rolls of a fair die using the sample function in R, I could
cheat, running many simulations, and picking the one that comes closest to
a target theoretical value. But that would give an unrealistic impression of how simulation really works.
If I set a seed at the start, the simulation
will get the same result every time. Students can proofread their copy of
my program to make sure it gives the intended results. Then they can run
their own simulations, either with their own seeds or by letting the program
pick its own starting place.
For example, the probability of getting the total 10 when rolling two fair dice is $$3/36 = 1/12 = 0.08333333.$$ With a million 2-dice experiments I should get about two or three-place accuracy. The 95% margin of simulation error is about $$2\sqrt{(1/12)(11/12)/10^6} = 0.00055.$$
set.seed(703); m = 10^6
s = replicate( m, sum(sample(1:6, 2, rep=T)) )
mean(s == 10)
[1] 0.083456 # aprx 1/12 = 0.0833
2*sd(s == 10)/sqrt(m)
[1] 0.0005531408 # aprx 95% marg of sim err.
When sharing statistical analyses that involve simulation.
Nowadays many statistical analyses involve some simulation, for example a permutation test or a Gibbs sampler. By showing the seed, you enable
people who read the analysis to replicate the results exactly, if they wish.
When writing academic articles involving randomization. Academic articles usually go through multiple rounds of peer review. A plot may use, e.g., randomly jittered points to reduce overplotting. If the analyses need to be slightly changed in response to reviewer comments, it is good if a particular unrelated jittering does not change between review rounds, which might be disconcerting to particularly nitpicky reviewers, so you set a seed before jittering.
|
What exactly is a seed in a random number generator?
First, there is no true randomness in today's computer-generated "random numbers." All pseudorandom generators use
deterministic methods. (Possibly, quantum computers will change that.)
The difficult
|
6,598
|
What exactly is a seed in a random number generator?
|
TL;DR;
A seed usually enables you to reproduce the sequence of random numbers. In that sense they are not true random numbers but "pseudo random numbers", hence a PNR Generator (PNRG). These are a real help in real life!
A bit more detail:
Virtually all "random" number generators implemented in computer languages are pseudo random number generators. This is because given a starting value (===> the seed) they will always provide the same sequence of pseudo random results. A good generator will produce a sequence that can not be distinguished - in statistical terms - from a true random sequence (throw a true die, true coin, etc).
In many simulation cases you want to have a true "random" experience. However, you also want to be able to reproduce your results. Why? Well, at least regulators are interested in that peculiar thing.
There's a lot to dive in to. People even do analysis into the "best" random seed. In my opinion this invalidates their model as they can't handle "true" random behavior - or their PRNG is not fit for their implementation. Most of the time they just don't do enough simulations - but they take time.
Now imagine a "true" RNG. One could implement this based on a kind of randomness in the machine. If you only take a random seed (e.g. time now) you create kind of a random starting point but the randomness of the sequence still depends on the algorithm to determine the next numbers. This is more important than the starting point in most cases as the distribution of results determines the actual "result". If your sequence should be truly random, how would you implement this? Clock ticks of a computer can be said to be deterministic and otherwise probably will show a lot of auto-correlation. So what can you do?
The best bet so-far is to implement a solid PNRG.
Quantum Computing? I'm not sure that will fix it.
|
What exactly is a seed in a random number generator?
|
TL;DR;
A seed usually enables you to reproduce the sequence of random numbers. In that sense they are not true random numbers but "pseudo random numbers", hence a PNR Generator (PNRG). These are a rea
|
What exactly is a seed in a random number generator?
TL;DR;
A seed usually enables you to reproduce the sequence of random numbers. In that sense they are not true random numbers but "pseudo random numbers", hence a PNR Generator (PNRG). These are a real help in real life!
A bit more detail:
Virtually all "random" number generators implemented in computer languages are pseudo random number generators. This is because given a starting value (===> the seed) they will always provide the same sequence of pseudo random results. A good generator will produce a sequence that can not be distinguished - in statistical terms - from a true random sequence (throw a true die, true coin, etc).
In many simulation cases you want to have a true "random" experience. However, you also want to be able to reproduce your results. Why? Well, at least regulators are interested in that peculiar thing.
There's a lot to dive in to. People even do analysis into the "best" random seed. In my opinion this invalidates their model as they can't handle "true" random behavior - or their PRNG is not fit for their implementation. Most of the time they just don't do enough simulations - but they take time.
Now imagine a "true" RNG. One could implement this based on a kind of randomness in the machine. If you only take a random seed (e.g. time now) you create kind of a random starting point but the randomness of the sequence still depends on the algorithm to determine the next numbers. This is more important than the starting point in most cases as the distribution of results determines the actual "result". If your sequence should be truly random, how would you implement this? Clock ticks of a computer can be said to be deterministic and otherwise probably will show a lot of auto-correlation. So what can you do?
The best bet so-far is to implement a solid PNRG.
Quantum Computing? I'm not sure that will fix it.
|
What exactly is a seed in a random number generator?
TL;DR;
A seed usually enables you to reproduce the sequence of random numbers. In that sense they are not true random numbers but "pseudo random numbers", hence a PNR Generator (PNRG). These are a rea
|
6,599
|
Why is the mean function in Gaussian Process uninteresting?
|
I think I know what the speaker was getting at. Personally I don't completely agree with her/him, and there's a lot of people who don't. But to be fair, there are also many who do :) First of all, note that specifying the covariance function (kernel) implies specifying a prior distribution over functions. Just by changing the kernel, the realizations of the Gaussian Process change drastically, from the very smooth, infinitely differentiable, functions generated by the Squared Exponential kernel
to the "spiky", nondifferentiable functions corresponding to an Exponential kernel (or Matern kernel with $\nu=1/2$)
Another way to see it is to write the predictive mean (the mean of the Gaussian Process predictions, obtained by conditioning the GP on the training points) in a test point $x^*$, in the simplest case of a zero mean function:
$$y^*=\mathbf{k}^{*T}(K+\sigma^{2}I)^{-1}\mathbf{y}$$
where $\mathbf{k}^*$ is the vector of covariances between the test point $x^*$ and the training points $x_1,\ldots,x_n$, $K$ is the covariance matrix of the training points, $\sigma$ is the noise term (just set $\sigma=0$ if your lecture concerned noise-free predictions, i.e., Gaussian Process interpolation), and $\mathbf{y}=(y_1,\ldots,y_n)$ is the vector of observations in the training set. As you can see, even if the mean of the GP prior is zero, the predictive mean is not zero at all, and depending on the kernel and on the number of training points, it can be a very flexible model, able to learn extremely complex patterns.
More generally, it's the kernel which defines the generalization properties of the GP. Some kernels have the universal approximation property, i.e., they are in principle capable to approximate any continuous function on a compact subset, to any prespecified maximum tolerance, given enough training points.
Then, why should you care at all about the mean function? First of all, a simple mean function (a linear or orthogonal polynomial one) makes the model much more interpretable, and this advantage must not be underestimated for model as flexible (thus, complicated) as the GP. Secondly, in some way the zero mean (or, for what's worth, also the constant mean) GP kind of sucks at prediction far away from the training data. Many stationary kernels (except the periodic kernels) are such that $k(x_i-x^*) \to 0 $ for $\operatorname{dist}(x_i,x^*)\to\infty$. This convergence to 0 can happen surprisingly quickly, expecially with the Squared Exponential kernel, and particularly when a short correlation length is necessary to fit the training set well. Thus a GP with zero mean function will invariably predict $y^*\approx 0$ as soon as you get away from the training set.
Now, this could make sense in your application: after all, it is often a bad idea to use a data-driven model to perform predictions away from the set of data points used to train the model. See here for many interesting and fun examples of why this can be a bad idea. In this respect, the zero mean GP, which always converges to 0 away from the training set, is safer than a model (such as for example an high degree multivariate orthogonal polynomial model), which will happily shoot out insanely large predictions as soon as you get away from the training data.
In other cases, however, you may want your model to have a certain asympotic behavior, which is not to converge to a constant. Maybe physical consideration tell you that for $x^*$ sufficiently large, your model must become linear. In that case you want a linear mean function. In general, when the global properties of the model are of interest for your application, then you have to pay attention to the choice of the mean function. When you are interested only in the local (close to the training points) behavior of your model, then a zero or constant mean GP may be more than enough.
|
Why is the mean function in Gaussian Process uninteresting?
|
I think I know what the speaker was getting at. Personally I don't completely agree with her/him, and there's a lot of people who don't. But to be fair, there are also many who do :) First of all, not
|
Why is the mean function in Gaussian Process uninteresting?
I think I know what the speaker was getting at. Personally I don't completely agree with her/him, and there's a lot of people who don't. But to be fair, there are also many who do :) First of all, note that specifying the covariance function (kernel) implies specifying a prior distribution over functions. Just by changing the kernel, the realizations of the Gaussian Process change drastically, from the very smooth, infinitely differentiable, functions generated by the Squared Exponential kernel
to the "spiky", nondifferentiable functions corresponding to an Exponential kernel (or Matern kernel with $\nu=1/2$)
Another way to see it is to write the predictive mean (the mean of the Gaussian Process predictions, obtained by conditioning the GP on the training points) in a test point $x^*$, in the simplest case of a zero mean function:
$$y^*=\mathbf{k}^{*T}(K+\sigma^{2}I)^{-1}\mathbf{y}$$
where $\mathbf{k}^*$ is the vector of covariances between the test point $x^*$ and the training points $x_1,\ldots,x_n$, $K$ is the covariance matrix of the training points, $\sigma$ is the noise term (just set $\sigma=0$ if your lecture concerned noise-free predictions, i.e., Gaussian Process interpolation), and $\mathbf{y}=(y_1,\ldots,y_n)$ is the vector of observations in the training set. As you can see, even if the mean of the GP prior is zero, the predictive mean is not zero at all, and depending on the kernel and on the number of training points, it can be a very flexible model, able to learn extremely complex patterns.
More generally, it's the kernel which defines the generalization properties of the GP. Some kernels have the universal approximation property, i.e., they are in principle capable to approximate any continuous function on a compact subset, to any prespecified maximum tolerance, given enough training points.
Then, why should you care at all about the mean function? First of all, a simple mean function (a linear or orthogonal polynomial one) makes the model much more interpretable, and this advantage must not be underestimated for model as flexible (thus, complicated) as the GP. Secondly, in some way the zero mean (or, for what's worth, also the constant mean) GP kind of sucks at prediction far away from the training data. Many stationary kernels (except the periodic kernels) are such that $k(x_i-x^*) \to 0 $ for $\operatorname{dist}(x_i,x^*)\to\infty$. This convergence to 0 can happen surprisingly quickly, expecially with the Squared Exponential kernel, and particularly when a short correlation length is necessary to fit the training set well. Thus a GP with zero mean function will invariably predict $y^*\approx 0$ as soon as you get away from the training set.
Now, this could make sense in your application: after all, it is often a bad idea to use a data-driven model to perform predictions away from the set of data points used to train the model. See here for many interesting and fun examples of why this can be a bad idea. In this respect, the zero mean GP, which always converges to 0 away from the training set, is safer than a model (such as for example an high degree multivariate orthogonal polynomial model), which will happily shoot out insanely large predictions as soon as you get away from the training data.
In other cases, however, you may want your model to have a certain asympotic behavior, which is not to converge to a constant. Maybe physical consideration tell you that for $x^*$ sufficiently large, your model must become linear. In that case you want a linear mean function. In general, when the global properties of the model are of interest for your application, then you have to pay attention to the choice of the mean function. When you are interested only in the local (close to the training points) behavior of your model, then a zero or constant mean GP may be more than enough.
|
Why is the mean function in Gaussian Process uninteresting?
I think I know what the speaker was getting at. Personally I don't completely agree with her/him, and there's a lot of people who don't. But to be fair, there are also many who do :) First of all, not
|
6,600
|
Why is the mean function in Gaussian Process uninteresting?
|
Well one very good reason is that the mean function may not live in the the space of functions you wish to model. each input point, $x_i$, may have a corresponding posterior mean, $\mu(x_i)$. However, these posterior mean points are the expectation before you see any other data. So there are many cases where no situation where the future data observed will create that mean function.
Simple example: Imagine fitting a sine function with unknown offset but known period and amplitude one. The prior mean is zero for all $x$ but a constant line does not live in the space of sine functions we described. The covariance function gives us that additional structural information.
|
Why is the mean function in Gaussian Process uninteresting?
|
Well one very good reason is that the mean function may not live in the the space of functions you wish to model. each input point, $x_i$, may have a corresponding posterior mean, $\mu(x_i)$. However,
|
Why is the mean function in Gaussian Process uninteresting?
Well one very good reason is that the mean function may not live in the the space of functions you wish to model. each input point, $x_i$, may have a corresponding posterior mean, $\mu(x_i)$. However, these posterior mean points are the expectation before you see any other data. So there are many cases where no situation where the future data observed will create that mean function.
Simple example: Imagine fitting a sine function with unknown offset but known period and amplitude one. The prior mean is zero for all $x$ but a constant line does not live in the space of sine functions we described. The covariance function gives us that additional structural information.
|
Why is the mean function in Gaussian Process uninteresting?
Well one very good reason is that the mean function may not live in the the space of functions you wish to model. each input point, $x_i$, may have a corresponding posterior mean, $\mu(x_i)$. However,
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.