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
|
|---|---|---|---|---|---|---|
10,201
|
How to easily determine the results distribution for multiple dice?
|
Characteristic functions can make computations involving the sums and differences of random variables really easy. Mathematica has lots of functions to work with statistical distributions, including a builtin to transform a distribution into its characteristic function.
I'd like to illustrate this with two concrete examples: (1) Suppose you wanted to determine the results of rolling a collection of dice with differing numbers of sides, e.g., roll two six-sided dice plus one eight-sided die (i.e., 2d6+d8)? Or (2) suppose you wanted to find the difference of two dice rolls (e.g., d6-d6)?
An easy way to do this would be to use the characteristic functions of the underlying discrete uniform distributions. If a random variable $X$ has a probability mass function $f$, then its characteristic function $\varphi_X(t)$ is just the discrete Fourier Transform of $f$, i.e., $\varphi_X(t) = \mathcal{F}\{f\}(t) = E[e^{i t X}]$. A theorem tells us:
If the independent random variables $X$ and $Y$ have corresponding probability mass functions $f$ and $g$, then the pmf $h$ of the sum $X + Y$ of these RVs is the convolution of their pmfs $h(n) = (f \ast g)(n) = \sum_{m=-\infty}^\infty f(m) g(n-m)$.
We can use the convolution property of Fourier Transforms to restate this more simply in terms of characteristic functions:
The characteristic function $\varphi_{X+Y}(t)$ of the sum of independent random variables $X$ and $Y$ equals the product of their characteristic functions $\varphi_{X}(t) \varphi_{Y}(t)$.
This Mathematica function will make the characteristic function for an s-sided die:
MakeCf[s_] :=
Module[{Cf},
Cf := CharacteristicFunction[DiscreteUniformDistribution[{1, s}],
t];
Cf]
The pmf of a distribution can be recovered from its characteristic function, because Fourier Transforms are invertible. Here is the Mathematica code to do it:
RecoverPmf[Cf_] :=
Module[{F},
F[y_] := SeriesCoefficient[Cf /. t -> -I*Log[x], {x, 0, y}];
F]
Continuing our example, let F be the pmf that results from 2d6+d8.
F := RecoverPmf[MakeCf[6]^2 MakeCf[8]]
There are $6^2 \cdot 8 = 288$ outcomes. The domain of support of F is $S=\{3,\ldots,20\}$. Three is the min because you're rolling three dice. And twenty is the max because $20 = 2 \cdot 6 + 8$. If you want to see the image of F, compute
In:= F /@ Range[3, 20]
Out= {1/288, 1/96, 1/48, 5/144, 5/96, 7/96, 13/144, 5/48, 1/9, 1/9, \
5/48, 13/144, 7/96, 5/96, 5/144, 1/48, 1/96, 1/288}
If you want to know the number of outcomes that sum to 10, compute
In:= 6^2 8 F[10]
Out= 30
If the independent random variables $X$ and $Y$ have corresponding probability mass functions $f$ and $g$, then the pmf $h$ of the difference $X - Y$ of these RVs is the cross-correlation of their pmfs $h(n) = (f \star g)(n) = \sum_{m=-\infty}^\infty f(m) g(n+m)$.
We can use the cross-correlation property of Fourier Transforms to restate this more simply in terms of characteristic functions:
The characteristic function $\varphi_{X-Y}(t)$ of the difference of two independent random variables ${X,Y}$ equals the product of the characteristic function $\varphi_{X}(t)$ and $\varphi_{Y}(-t)$ (N.B. the negative sign in front of the variable t in the second characteristic function).
So, using Mathematica to find the pmf G of d6-d6:
G := RecoverPmf[MakeCf[6] (MakeCf[6] /. t -> -t)]
There are $6^2 = 36$ outcomes. The domain of support of G is $S=\{-5,\ldots,5\}$. -5 is the min because $-5=1-6$. And 5 is the max because $6-1=5$. If you want to see the image of G, compute
In:= G /@ Range[-5, 5]
Out= {1/36, 1/18, 1/12, 1/9, 5/36, 1/6, 5/36, 1/9, 1/12, 1/18, 1/36}
|
How to easily determine the results distribution for multiple dice?
|
Characteristic functions can make computations involving the sums and differences of random variables really easy. Mathematica has lots of functions to work with statistical distributions, including a
|
How to easily determine the results distribution for multiple dice?
Characteristic functions can make computations involving the sums and differences of random variables really easy. Mathematica has lots of functions to work with statistical distributions, including a builtin to transform a distribution into its characteristic function.
I'd like to illustrate this with two concrete examples: (1) Suppose you wanted to determine the results of rolling a collection of dice with differing numbers of sides, e.g., roll two six-sided dice plus one eight-sided die (i.e., 2d6+d8)? Or (2) suppose you wanted to find the difference of two dice rolls (e.g., d6-d6)?
An easy way to do this would be to use the characteristic functions of the underlying discrete uniform distributions. If a random variable $X$ has a probability mass function $f$, then its characteristic function $\varphi_X(t)$ is just the discrete Fourier Transform of $f$, i.e., $\varphi_X(t) = \mathcal{F}\{f\}(t) = E[e^{i t X}]$. A theorem tells us:
If the independent random variables $X$ and $Y$ have corresponding probability mass functions $f$ and $g$, then the pmf $h$ of the sum $X + Y$ of these RVs is the convolution of their pmfs $h(n) = (f \ast g)(n) = \sum_{m=-\infty}^\infty f(m) g(n-m)$.
We can use the convolution property of Fourier Transforms to restate this more simply in terms of characteristic functions:
The characteristic function $\varphi_{X+Y}(t)$ of the sum of independent random variables $X$ and $Y$ equals the product of their characteristic functions $\varphi_{X}(t) \varphi_{Y}(t)$.
This Mathematica function will make the characteristic function for an s-sided die:
MakeCf[s_] :=
Module[{Cf},
Cf := CharacteristicFunction[DiscreteUniformDistribution[{1, s}],
t];
Cf]
The pmf of a distribution can be recovered from its characteristic function, because Fourier Transforms are invertible. Here is the Mathematica code to do it:
RecoverPmf[Cf_] :=
Module[{F},
F[y_] := SeriesCoefficient[Cf /. t -> -I*Log[x], {x, 0, y}];
F]
Continuing our example, let F be the pmf that results from 2d6+d8.
F := RecoverPmf[MakeCf[6]^2 MakeCf[8]]
There are $6^2 \cdot 8 = 288$ outcomes. The domain of support of F is $S=\{3,\ldots,20\}$. Three is the min because you're rolling three dice. And twenty is the max because $20 = 2 \cdot 6 + 8$. If you want to see the image of F, compute
In:= F /@ Range[3, 20]
Out= {1/288, 1/96, 1/48, 5/144, 5/96, 7/96, 13/144, 5/48, 1/9, 1/9, \
5/48, 13/144, 7/96, 5/96, 5/144, 1/48, 1/96, 1/288}
If you want to know the number of outcomes that sum to 10, compute
In:= 6^2 8 F[10]
Out= 30
If the independent random variables $X$ and $Y$ have corresponding probability mass functions $f$ and $g$, then the pmf $h$ of the difference $X - Y$ of these RVs is the cross-correlation of their pmfs $h(n) = (f \star g)(n) = \sum_{m=-\infty}^\infty f(m) g(n+m)$.
We can use the cross-correlation property of Fourier Transforms to restate this more simply in terms of characteristic functions:
The characteristic function $\varphi_{X-Y}(t)$ of the difference of two independent random variables ${X,Y}$ equals the product of the characteristic function $\varphi_{X}(t)$ and $\varphi_{Y}(-t)$ (N.B. the negative sign in front of the variable t in the second characteristic function).
So, using Mathematica to find the pmf G of d6-d6:
G := RecoverPmf[MakeCf[6] (MakeCf[6] /. t -> -t)]
There are $6^2 = 36$ outcomes. The domain of support of G is $S=\{-5,\ldots,5\}$. -5 is the min because $-5=1-6$. And 5 is the max because $6-1=5$. If you want to see the image of G, compute
In:= G /@ Range[-5, 5]
Out= {1/36, 1/18, 1/12, 1/9, 5/36, 1/6, 5/36, 1/9, 1/12, 1/18, 1/36}
|
How to easily determine the results distribution for multiple dice?
Characteristic functions can make computations involving the sums and differences of random variables really easy. Mathematica has lots of functions to work with statistical distributions, including a
|
10,202
|
How to easily determine the results distribution for multiple dice?
|
Approximate Solution
I explained the exact solution earlier (see below). I will now offer an approximate solution which may suit your needs better.
Let:
$X_i$ be the outcome of a roll of a $s$ faced dice where $i=1, ... n$.
$S$ be the total of all $n$ dice.
$\bar{X}$ be the sample average.
By definition, we have:
$\bar{X} = \frac{\sum_iX_i}{n}$
In other words,
$\bar{X} = \frac{S}{n}$
The idea now is to visualize the process of observing ${X_i}$ as the outcome of throwing the same dice $n$ times instead of as outcome of throwing $n$ dice. Thus, we can invoke the central limit theorem (ignoring technicalities associated with going from discrete distribution to continuous), we have as $n \rightarrow \infty$:
$\bar{X} \sim N(\mu, \sigma^2/n)$
where,
$\mu = (s+1)/2$ is the mean of the roll of a single dice and
$\sigma^2 = (s^2-1)/12$ is the associated variance.
The above is obviously an approximation as the underlying distribution $X_i$ has discrete support.
But,
$S = n \bar{X}$.
Thus, we have:
$S \sim N(n \mu, n \sigma^2)$.
Exact Solution
Wikipedia has a brief explanation as how to calculate the required probabilities. I will elaborate a bit more as to why the explanation there makes sense. To the extent possible I have used similar notation to the Wikipedia article.
Suppose that you have $n$ dice each with $s$ faces and you want to compute the probability that a single roll of all $n$ dice the total adds up to $k$. The approach is as follows:
Define:
$F_{s,n}(k)$: Probability that you get a total of $k$ on a single roll of $n$ dices with $s$ faces.
By definition, we have:
$F_{s,1}(k) = \frac{1}{s}$
The above states that if you just have one dice with $s$ faces the probability of obtaining a total $k$ between 1 and s is the familiar $\frac{1}{s}$.
Consider the situation when you roll two dice: You can obtain a sum of $k$ as follows: The first roll is between 1 to $k-1$ and the corresponding roll for the second one is between $k-1$ to $1$. Thus, we have:
$F_{s,2}(k) = \sum_{i=1}^{i=k-1}{F_{s,1}(i) F_{s,1}(k-i)}$
Now consider a roll of three dice: You can get a sum of $k$ if you roll a 1 to $k-2$ on the first dice and the sum on the remaining two dice is between $k-1$ to $2$. Thus,
$F_{s,3}(k) = \sum_{i=1}^{i=k-2}{F_{s,1}(i) F_{s,2}(k-i)}$
Continuing the above logic, we get the recursion equation:
$F_{s,n}(k) = \sum_{i=1}^{i=k-n+1}{F_{s,1}(i) F_{s,n-1}(k-i)}$
See the Wikipedia link for more details.
|
How to easily determine the results distribution for multiple dice?
|
Approximate Solution
I explained the exact solution earlier (see below). I will now offer an approximate solution which may suit your needs better.
Let:
$X_i$ be the outcome of a roll of a $s$ faced
|
How to easily determine the results distribution for multiple dice?
Approximate Solution
I explained the exact solution earlier (see below). I will now offer an approximate solution which may suit your needs better.
Let:
$X_i$ be the outcome of a roll of a $s$ faced dice where $i=1, ... n$.
$S$ be the total of all $n$ dice.
$\bar{X}$ be the sample average.
By definition, we have:
$\bar{X} = \frac{\sum_iX_i}{n}$
In other words,
$\bar{X} = \frac{S}{n}$
The idea now is to visualize the process of observing ${X_i}$ as the outcome of throwing the same dice $n$ times instead of as outcome of throwing $n$ dice. Thus, we can invoke the central limit theorem (ignoring technicalities associated with going from discrete distribution to continuous), we have as $n \rightarrow \infty$:
$\bar{X} \sim N(\mu, \sigma^2/n)$
where,
$\mu = (s+1)/2$ is the mean of the roll of a single dice and
$\sigma^2 = (s^2-1)/12$ is the associated variance.
The above is obviously an approximation as the underlying distribution $X_i$ has discrete support.
But,
$S = n \bar{X}$.
Thus, we have:
$S \sim N(n \mu, n \sigma^2)$.
Exact Solution
Wikipedia has a brief explanation as how to calculate the required probabilities. I will elaborate a bit more as to why the explanation there makes sense. To the extent possible I have used similar notation to the Wikipedia article.
Suppose that you have $n$ dice each with $s$ faces and you want to compute the probability that a single roll of all $n$ dice the total adds up to $k$. The approach is as follows:
Define:
$F_{s,n}(k)$: Probability that you get a total of $k$ on a single roll of $n$ dices with $s$ faces.
By definition, we have:
$F_{s,1}(k) = \frac{1}{s}$
The above states that if you just have one dice with $s$ faces the probability of obtaining a total $k$ between 1 and s is the familiar $\frac{1}{s}$.
Consider the situation when you roll two dice: You can obtain a sum of $k$ as follows: The first roll is between 1 to $k-1$ and the corresponding roll for the second one is between $k-1$ to $1$. Thus, we have:
$F_{s,2}(k) = \sum_{i=1}^{i=k-1}{F_{s,1}(i) F_{s,1}(k-i)}$
Now consider a roll of three dice: You can get a sum of $k$ if you roll a 1 to $k-2$ on the first dice and the sum on the remaining two dice is between $k-1$ to $2$. Thus,
$F_{s,3}(k) = \sum_{i=1}^{i=k-2}{F_{s,1}(i) F_{s,2}(k-i)}$
Continuing the above logic, we get the recursion equation:
$F_{s,n}(k) = \sum_{i=1}^{i=k-n+1}{F_{s,1}(i) F_{s,n-1}(k-i)}$
See the Wikipedia link for more details.
|
How to easily determine the results distribution for multiple dice?
Approximate Solution
I explained the exact solution earlier (see below). I will now offer an approximate solution which may suit your needs better.
Let:
$X_i$ be the outcome of a roll of a $s$ faced
|
10,203
|
How to easily determine the results distribution for multiple dice?
|
Here's another way to calculate the probability distribution of the sum of two dice by hand using convolutions.
To keep the example really simple, we're going to calculate the probability distribution of the sum of a three-sided die (d3) whose random variable we will call X and a two-sided die (d2) whose random variable we'll call Y.
You're going to make a table. Across the top row, write the probability distribution of X (outcomes of rolling a fair d3). Down the left column, write the probability distribution of Y (outcomes of rolling a fair d2).
You're going to construct the outer product of the top row of probabilities with the left column of probabilities. For example, the lower-right cell will be the product of Pr[X=3]=1/3 times Pr[Y=2]=1/2 as shown in the accompanying figure. In our simplistic example, all the cells equal 1/6.
Next, you're going to sum along the oblique lines of the outer-product matrix as shown in the accompanying diagram. Each oblique line passes through one-or-more cells which I've colored the same: The top line passes through one blue cell, the next line passes through two red cells, and so on.
Each of the sums along the obliques represents a probability in the resulting distribution. For example, the sum of the red cells equals the probability of the two dice summing to 3. These probabilities are shown down the right side of the accompanying diagram.
This technique can be used with any two discrete distributions with finite support. And you can apply it iteratively. For example, if you want to know the distribution of three six-sided dice (3d6), you can first calculate 2d6=d6+d6; then 3d6=d6+2d6.
There is a free (but closed license) programming language called J. Its an array-based language with its roots in APL. It has builtin operators to perform outer products and sums along the obliques in matrices, making the technique I illustrated quite simple to implement.
In the following J code, I define two verbs. First the verb d constructs an array representing the pmf of an s-sided die. For example, d 6 is the pmf of a 6-sided die. Second, the verb conv finds the outer product of two arrays and sums along the oblique lines. So conv~ d 6 prints out the pmf of 2d6:
d=:$%
conv=:+//.@(*/)
|:(2+i.11),:conv~d 6
2 0.0277778
3 0.0555556
4 0.0833333
5 0.111111
6 0.138889
7 0.166667
8 0.138889
9 0.111111
10 0.0833333
11 0.0555556
12 0.0277778
As you can see, J is cryptic, but terse.
|
How to easily determine the results distribution for multiple dice?
|
Here's another way to calculate the probability distribution of the sum of two dice by hand using convolutions.
To keep the example really simple, we're going to calculate the probability distribution
|
How to easily determine the results distribution for multiple dice?
Here's another way to calculate the probability distribution of the sum of two dice by hand using convolutions.
To keep the example really simple, we're going to calculate the probability distribution of the sum of a three-sided die (d3) whose random variable we will call X and a two-sided die (d2) whose random variable we'll call Y.
You're going to make a table. Across the top row, write the probability distribution of X (outcomes of rolling a fair d3). Down the left column, write the probability distribution of Y (outcomes of rolling a fair d2).
You're going to construct the outer product of the top row of probabilities with the left column of probabilities. For example, the lower-right cell will be the product of Pr[X=3]=1/3 times Pr[Y=2]=1/2 as shown in the accompanying figure. In our simplistic example, all the cells equal 1/6.
Next, you're going to sum along the oblique lines of the outer-product matrix as shown in the accompanying diagram. Each oblique line passes through one-or-more cells which I've colored the same: The top line passes through one blue cell, the next line passes through two red cells, and so on.
Each of the sums along the obliques represents a probability in the resulting distribution. For example, the sum of the red cells equals the probability of the two dice summing to 3. These probabilities are shown down the right side of the accompanying diagram.
This technique can be used with any two discrete distributions with finite support. And you can apply it iteratively. For example, if you want to know the distribution of three six-sided dice (3d6), you can first calculate 2d6=d6+d6; then 3d6=d6+2d6.
There is a free (but closed license) programming language called J. Its an array-based language with its roots in APL. It has builtin operators to perform outer products and sums along the obliques in matrices, making the technique I illustrated quite simple to implement.
In the following J code, I define two verbs. First the verb d constructs an array representing the pmf of an s-sided die. For example, d 6 is the pmf of a 6-sided die. Second, the verb conv finds the outer product of two arrays and sums along the oblique lines. So conv~ d 6 prints out the pmf of 2d6:
d=:$%
conv=:+//.@(*/)
|:(2+i.11),:conv~d 6
2 0.0277778
3 0.0555556
4 0.0833333
5 0.111111
6 0.138889
7 0.166667
8 0.138889
9 0.111111
10 0.0833333
11 0.0555556
12 0.0277778
As you can see, J is cryptic, but terse.
|
How to easily determine the results distribution for multiple dice?
Here's another way to calculate the probability distribution of the sum of two dice by hand using convolutions.
To keep the example really simple, we're going to calculate the probability distribution
|
10,204
|
How to easily determine the results distribution for multiple dice?
|
Love the username! Well done :)
The outcomes you should count are the dice rolls, all $6\times 6=36$ of them as shown in your table.
For example, $\frac{1}{36}$ of the time the sum is $2$, and $\frac{2}{36}$ of the time the sum is $3$, and $\frac{4}{36}$ of the time the sum is $4$, and so on.
|
How to easily determine the results distribution for multiple dice?
|
Love the username! Well done :)
The outcomes you should count are the dice rolls, all $6\times 6=36$ of them as shown in your table.
For example, $\frac{1}{36}$ of the time the sum is $2$, and $\frac
|
How to easily determine the results distribution for multiple dice?
Love the username! Well done :)
The outcomes you should count are the dice rolls, all $6\times 6=36$ of them as shown in your table.
For example, $\frac{1}{36}$ of the time the sum is $2$, and $\frac{2}{36}$ of the time the sum is $3$, and $\frac{4}{36}$ of the time the sum is $4$, and so on.
|
How to easily determine the results distribution for multiple dice?
Love the username! Well done :)
The outcomes you should count are the dice rolls, all $6\times 6=36$ of them as shown in your table.
For example, $\frac{1}{36}$ of the time the sum is $2$, and $\frac
|
10,205
|
How to easily determine the results distribution for multiple dice?
|
You can solve this with a recursive formula. In that case the probabilities of the rolls with $n$ dice are calculated by the rolls with $n-1$ dice.
$$a_n(l) = \sum_{l-6 \leq k \leq l-1 \\ \text{ and } n-1 \leq k \leq 6(n-1)} a_{n-1}(k)$$
The first limit for k in the summation are the six preceding numbers. E.g if You want to roll 13 with 3 dice then you can do this if your first two dice roll between 7 and 12.
The second limit for k in the summation is the limits of what you can roll with n-1 dice
The outcome:
1 1 1 1 1 1
1 2 3 4 5 6 5 4 3 2 1
1 3 6 10 15 21 25 27 27 25 21 15 10 6 3 1
1 4 10 20 35 56 80 104 125 140 146 140 125 104 80 56 35 20 10 4 1
1 5 15 35 70 126 205 305 420 540 651 735 780 780 735 651 540 420 305 205 126 70 35 15 5 1
edit: The above answer was an answer from another question that was merged into the question by C.Ross
The code below shows how the calculations for that answer (to the question asking for 5 dice) were performed in R. They are similar to the summations performed in Excel in the answer by Glen B.
# recursive formula
nextdice <- function(n,a,l) {
x = 0
for (i in 1:6) {
if ((l-i >= n-1) & (l-i<=6*(n-1))) {
x = x+a[l-i-(n-2)]
}
}
return(x)
}
# generating combinations for rolling with up to 5 dices
a_1 <- rep(1,6)
a_2 <- sapply(2:12,FUN = function(x) {nextdice(2,a_1,x)})
a_3 <- sapply(3:18,FUN = function(x) {nextdice(3,a_2,x)})
a_4 <- sapply(4:24,FUN = function(x) {nextdice(4,a_3,x)})
a_5 <- sapply(5:30,FUN = function(x) {nextdice(5,a_4,x)})
|
How to easily determine the results distribution for multiple dice?
|
You can solve this with a recursive formula. In that case the probabilities of the rolls with $n$ dice are calculated by the rolls with $n-1$ dice.
$$a_n(l) = \sum_{l-6 \leq k \leq l-1 \\ \text{ and }
|
How to easily determine the results distribution for multiple dice?
You can solve this with a recursive formula. In that case the probabilities of the rolls with $n$ dice are calculated by the rolls with $n-1$ dice.
$$a_n(l) = \sum_{l-6 \leq k \leq l-1 \\ \text{ and } n-1 \leq k \leq 6(n-1)} a_{n-1}(k)$$
The first limit for k in the summation are the six preceding numbers. E.g if You want to roll 13 with 3 dice then you can do this if your first two dice roll between 7 and 12.
The second limit for k in the summation is the limits of what you can roll with n-1 dice
The outcome:
1 1 1 1 1 1
1 2 3 4 5 6 5 4 3 2 1
1 3 6 10 15 21 25 27 27 25 21 15 10 6 3 1
1 4 10 20 35 56 80 104 125 140 146 140 125 104 80 56 35 20 10 4 1
1 5 15 35 70 126 205 305 420 540 651 735 780 780 735 651 540 420 305 205 126 70 35 15 5 1
edit: The above answer was an answer from another question that was merged into the question by C.Ross
The code below shows how the calculations for that answer (to the question asking for 5 dice) were performed in R. They are similar to the summations performed in Excel in the answer by Glen B.
# recursive formula
nextdice <- function(n,a,l) {
x = 0
for (i in 1:6) {
if ((l-i >= n-1) & (l-i<=6*(n-1))) {
x = x+a[l-i-(n-2)]
}
}
return(x)
}
# generating combinations for rolling with up to 5 dices
a_1 <- rep(1,6)
a_2 <- sapply(2:12,FUN = function(x) {nextdice(2,a_1,x)})
a_3 <- sapply(3:18,FUN = function(x) {nextdice(3,a_2,x)})
a_4 <- sapply(4:24,FUN = function(x) {nextdice(4,a_3,x)})
a_5 <- sapply(5:30,FUN = function(x) {nextdice(5,a_4,x)})
|
How to easily determine the results distribution for multiple dice?
You can solve this with a recursive formula. In that case the probabilities of the rolls with $n$ dice are calculated by the rolls with $n-1$ dice.
$$a_n(l) = \sum_{l-6 \leq k \leq l-1 \\ \text{ and }
|
10,206
|
How to easily determine the results distribution for multiple dice?
|
One approach is to say that the probability $X_n=k$ is the coefficient of $x^{k}$ in the expansion of the generating function $$\left(\frac{x^6+x^5+x^4+x^3+x^2+x^1}{6}\right)^n=\left(\frac{x(1-x^6)}{6(1-x)}\right)^n$$
So for example with six dice and a target of $k=22$, you will find $P(X_6=22)= \frac{10}{6^6}$. That link (to a math.stackexchange question) gives other approaches too
|
How to easily determine the results distribution for multiple dice?
|
One approach is to say that the probability $X_n=k$ is the coefficient of $x^{k}$ in the expansion of the generating function $$\left(\frac{x^6+x^5+x^4+x^3+x^2+x^1}{6}\right)^n=\left(\frac{x(1-x^6)}{6
|
How to easily determine the results distribution for multiple dice?
One approach is to say that the probability $X_n=k$ is the coefficient of $x^{k}$ in the expansion of the generating function $$\left(\frac{x^6+x^5+x^4+x^3+x^2+x^1}{6}\right)^n=\left(\frac{x(1-x^6)}{6(1-x)}\right)^n$$
So for example with six dice and a target of $k=22$, you will find $P(X_6=22)= \frac{10}{6^6}$. That link (to a math.stackexchange question) gives other approaches too
|
How to easily determine the results distribution for multiple dice?
One approach is to say that the probability $X_n=k$ is the coefficient of $x^{k}$ in the expansion of the generating function $$\left(\frac{x^6+x^5+x^4+x^3+x^2+x^1}{6}\right)^n=\left(\frac{x(1-x^6)}{6
|
10,207
|
What is importance sampling?
|
Importance sampling is a form of sampling from a distribution different from the distribution of interest to more easily obtain better estimates of a parameter from the distribution of interest. Typically this will provide estimates of the parameter with a lower variance than would be obtained by sampling directly from the original distribution with the same sample size.
It is applied in various contexts. In general sampling from the different distributions allows for more samples to be taken in a portion of the distribution of interest that is dictated by the application (important region).
One example might be that you want to have a sample that includes more samples from the tails of the distribution than pure random sampling from the distribution of interest would provide.
The wikipedia article that I have seen on this subject is too abstract. It is better to look at various specific examples. However, it does include links to interesting applications such as Bayesian Networks.
One example of importance sampling in the 1940s and 1950s is a variance reduction technique (a form of the Monte Carlo Method). See for example the book Monte Carlo Methods by Hammersley and Handscomb published as a Methuen Monograph/Chapman and Hall in 1964 and reprinted in 1966 and later by other publishers. Section 5.4 of the book covers Importance Sampling.
|
What is importance sampling?
|
Importance sampling is a form of sampling from a distribution different from the distribution of interest to more easily obtain better estimates of a parameter from the distribution of interest. Typic
|
What is importance sampling?
Importance sampling is a form of sampling from a distribution different from the distribution of interest to more easily obtain better estimates of a parameter from the distribution of interest. Typically this will provide estimates of the parameter with a lower variance than would be obtained by sampling directly from the original distribution with the same sample size.
It is applied in various contexts. In general sampling from the different distributions allows for more samples to be taken in a portion of the distribution of interest that is dictated by the application (important region).
One example might be that you want to have a sample that includes more samples from the tails of the distribution than pure random sampling from the distribution of interest would provide.
The wikipedia article that I have seen on this subject is too abstract. It is better to look at various specific examples. However, it does include links to interesting applications such as Bayesian Networks.
One example of importance sampling in the 1940s and 1950s is a variance reduction technique (a form of the Monte Carlo Method). See for example the book Monte Carlo Methods by Hammersley and Handscomb published as a Methuen Monograph/Chapman and Hall in 1964 and reprinted in 1966 and later by other publishers. Section 5.4 of the book covers Importance Sampling.
|
What is importance sampling?
Importance sampling is a form of sampling from a distribution different from the distribution of interest to more easily obtain better estimates of a parameter from the distribution of interest. Typic
|
10,208
|
What is importance sampling?
|
Importance sampling is a simulation or Monte Carlo method intended for approximating integrals. The term "sampling" is somewhat confusing in that it does not intend to provide samples from a given distribution.
The intuition behind importance sampling is that a well-defined integral, like
$$\mathfrak{I}=\int_\mathfrak{X} h(x)\,\text{d}x$$
can be expressed as an expectation for a wide range of probability distributions:
$$\mathfrak{I}=\mathbb{E}_f[H(X)]=\int_\mathfrak{X} H(x)f(x)\,\text{d}x$$
where $f$ denotes the density of a probability distribution and $H$ is determined by $h$ and $f$. (Note that $H(\cdot)$ is usually different from $h(\cdot)$.) Indeed, the choice
$$H(x)=\dfrac{h(x)}{f(x)}$$leads to the equalities $H(x)f(x)=h(x)$ and $\mathfrak{I}=\mathbb{E}_f[H(X)]$$-$under some restrictions on the support of $f$, meaning $f(x)>0$ when $h(x)\ne 0$$-$. Hence, as pointed out by W. Huber in his comment, there is no unicity in the representation of an integral as an expectation, but on the opposite an infinite array of such representations, some of which are better than others once a criterion to compare them is adopted. For instance, Michael Chernick mentions choosing $f$ towards reducing the variance of the estimator.
Once this elementary property is understood, the implementation of the idea is to rely on the Law of Large Numbers as in other Monte Carlo methods, i.e., to simulate [via a pseudo-random generator] an iid sample $(x_1,\ldots,x_n)$ distributed from $f$ and to use the approximation
$$\hat{\mathfrak{I}}=\frac{1}{n} \sum_{i=1}^n H(x_i)$$which
is an unbiased estimator of $\mathfrak{I}$
converges almost surely to $\mathfrak{I}$
Depending on the choice of the distribution $f$, the above estimator $\hat{\mathfrak{I}}$ may or may not have a finite variance. However, there always exist choices of $f$ that allow for a finite variance and even for an arbitrarily small variance (albeit those choices may be unavailable in practice). And there also exist choices of $f$ that make the importance sampling estimator $\hat{\mathfrak{I}}$ a very poor approximation of ${\mathfrak{I}}$. This includes all the choices where the variance gets infinite, even though a recent paper by Chatterjee and Diaconis studies how to compare importance samplers with infinite variance. The picture below is taken from my blog discussion of the paper and illustrates the poor convergence of infinite variance estimators.
Importance sampling with importance distribution an Exp(1)
distribution target distribution an Exp(1/10) distribution, and
function of interest $h(x)=x$. The true value of the integral is $10$.
[The following is reproduced from our book Monte Carlo Statistical Methods.]
The following example from Ripley (1987) shows why it may actually pay to generate from a distribution other than the (original) distribution $f$ appearing in the integral
$$\int_\mathfrak{X} h(x) f(x)\,\text{d}x$$of interest or, in other words, to
modify the representation of an integral as an expectation against a
given density.
Example (Cauchy tail probability)
Suppose that the quantity of interest is the probability, $p$, that
a Cauchy ${\mathcal{C}}(0,1)$ variable
is larger than $2$, that is,
$$
p = \int_2^{+\infty} \; {1\over \pi(1 + x^2)} \; \text{d}x \;.
$$
When $p$ is evaluated through the empirical average
$$
{\hat{p}}_1 = {1\over m} \; \sum_{j=1}^m \; \mathbb{I}_{X_{j} > 2}
$$
of an iid sample $X_1,\ldots,X_m$ $\sim$ $\; \mathcal{C}(0,1)$, the
variance of this estimator is $p(1-p)/m$ (equal to $0.127/m$ since $p=0.15$).
This variance can be reduced by taking into account the
symmetric nature of ${\mathcal{C}}(0,1)$, since the average
$$
{\hat{p}}_2 = {1\over 2m} \; \sum_{j=1}^m \; \mathbb{I}_{|X_{j}| > 2}
$$
has variance $p(1-2p)/2m$ equal to $0.052/m$.
The (relative) inefficiency of these methods is due to the generation
of values outside the domain of interest, $[2,+\infty)$,
which are, in some sense,
irrelevant for the approximation of $p$. [This relates to Michael Chernick mentioning tail area estimation.] If $p$ is written as
$$
p = {1\over 2} - \int_0^2 \; {1\over \pi(1 + x^2)} \; \text{d}x \;,
$$
the integral above can be considered to be the expectation of
$h(X) = 2/\pi(1 + X^2)$, where $X \sim {\mathcal{U}}_{[0, 2]}$.
An alternative method of evaluation for $p$ is therefore
$$
{\hat{p}}_3 = {1\over 2} - {1\over m} \; \sum_{j=1}^m \; h(U_j)
$$
for $U_j \sim {\mathcal{U}}_{[0,2]}$. The variance of ${\hat{p}}_3$ is
$(\mathbb{E}[h^2] - \mathbb{E}[h]^2)/m$ and an integration by parts shows that
it is equal to $0.0285/m$. Moreover, since $p$ can be written as
$$
p = \int_0^{1/2} \; {y^{-2}\over \pi(1 + y^{-2})} \; \text{d}y \;,
$$
this integral can also be seen as the expectation of
${1\over 4} \; h(Y) = 1/2\pi(1 + Y^2)$ against the
uniform distribution on $[0,1/2]$ and another evaluation of $p$ is
$$
{\hat{p}}_4 = {1\over 4 m} \; \sum_{j=1}^m \; h(Y_j)
$$
when $Y_j \sim {\mathcal{U}}_{[0,1/2]}$. The same integration by
parts shows that the variance of ${\hat{p}}_{4}$ is then
$0.95 \; 10^{-4}/m$.
Compared with ${\hat{p}}_1$, the reduction in variance brought by ${\hat p}_4$
is of order $10^{-3}$, which implies, in
particular, that this evaluation requires
$\sqrt{1000} \approx 32$ times fewer simulations than $\hat p_1$
to achieve the same precision. $\blacktriangleright$
|
What is importance sampling?
|
Importance sampling is a simulation or Monte Carlo method intended for approximating integrals. The term "sampling" is somewhat confusing in that it does not intend to provide samples from a given dis
|
What is importance sampling?
Importance sampling is a simulation or Monte Carlo method intended for approximating integrals. The term "sampling" is somewhat confusing in that it does not intend to provide samples from a given distribution.
The intuition behind importance sampling is that a well-defined integral, like
$$\mathfrak{I}=\int_\mathfrak{X} h(x)\,\text{d}x$$
can be expressed as an expectation for a wide range of probability distributions:
$$\mathfrak{I}=\mathbb{E}_f[H(X)]=\int_\mathfrak{X} H(x)f(x)\,\text{d}x$$
where $f$ denotes the density of a probability distribution and $H$ is determined by $h$ and $f$. (Note that $H(\cdot)$ is usually different from $h(\cdot)$.) Indeed, the choice
$$H(x)=\dfrac{h(x)}{f(x)}$$leads to the equalities $H(x)f(x)=h(x)$ and $\mathfrak{I}=\mathbb{E}_f[H(X)]$$-$under some restrictions on the support of $f$, meaning $f(x)>0$ when $h(x)\ne 0$$-$. Hence, as pointed out by W. Huber in his comment, there is no unicity in the representation of an integral as an expectation, but on the opposite an infinite array of such representations, some of which are better than others once a criterion to compare them is adopted. For instance, Michael Chernick mentions choosing $f$ towards reducing the variance of the estimator.
Once this elementary property is understood, the implementation of the idea is to rely on the Law of Large Numbers as in other Monte Carlo methods, i.e., to simulate [via a pseudo-random generator] an iid sample $(x_1,\ldots,x_n)$ distributed from $f$ and to use the approximation
$$\hat{\mathfrak{I}}=\frac{1}{n} \sum_{i=1}^n H(x_i)$$which
is an unbiased estimator of $\mathfrak{I}$
converges almost surely to $\mathfrak{I}$
Depending on the choice of the distribution $f$, the above estimator $\hat{\mathfrak{I}}$ may or may not have a finite variance. However, there always exist choices of $f$ that allow for a finite variance and even for an arbitrarily small variance (albeit those choices may be unavailable in practice). And there also exist choices of $f$ that make the importance sampling estimator $\hat{\mathfrak{I}}$ a very poor approximation of ${\mathfrak{I}}$. This includes all the choices where the variance gets infinite, even though a recent paper by Chatterjee and Diaconis studies how to compare importance samplers with infinite variance. The picture below is taken from my blog discussion of the paper and illustrates the poor convergence of infinite variance estimators.
Importance sampling with importance distribution an Exp(1)
distribution target distribution an Exp(1/10) distribution, and
function of interest $h(x)=x$. The true value of the integral is $10$.
[The following is reproduced from our book Monte Carlo Statistical Methods.]
The following example from Ripley (1987) shows why it may actually pay to generate from a distribution other than the (original) distribution $f$ appearing in the integral
$$\int_\mathfrak{X} h(x) f(x)\,\text{d}x$$of interest or, in other words, to
modify the representation of an integral as an expectation against a
given density.
Example (Cauchy tail probability)
Suppose that the quantity of interest is the probability, $p$, that
a Cauchy ${\mathcal{C}}(0,1)$ variable
is larger than $2$, that is,
$$
p = \int_2^{+\infty} \; {1\over \pi(1 + x^2)} \; \text{d}x \;.
$$
When $p$ is evaluated through the empirical average
$$
{\hat{p}}_1 = {1\over m} \; \sum_{j=1}^m \; \mathbb{I}_{X_{j} > 2}
$$
of an iid sample $X_1,\ldots,X_m$ $\sim$ $\; \mathcal{C}(0,1)$, the
variance of this estimator is $p(1-p)/m$ (equal to $0.127/m$ since $p=0.15$).
This variance can be reduced by taking into account the
symmetric nature of ${\mathcal{C}}(0,1)$, since the average
$$
{\hat{p}}_2 = {1\over 2m} \; \sum_{j=1}^m \; \mathbb{I}_{|X_{j}| > 2}
$$
has variance $p(1-2p)/2m$ equal to $0.052/m$.
The (relative) inefficiency of these methods is due to the generation
of values outside the domain of interest, $[2,+\infty)$,
which are, in some sense,
irrelevant for the approximation of $p$. [This relates to Michael Chernick mentioning tail area estimation.] If $p$ is written as
$$
p = {1\over 2} - \int_0^2 \; {1\over \pi(1 + x^2)} \; \text{d}x \;,
$$
the integral above can be considered to be the expectation of
$h(X) = 2/\pi(1 + X^2)$, where $X \sim {\mathcal{U}}_{[0, 2]}$.
An alternative method of evaluation for $p$ is therefore
$$
{\hat{p}}_3 = {1\over 2} - {1\over m} \; \sum_{j=1}^m \; h(U_j)
$$
for $U_j \sim {\mathcal{U}}_{[0,2]}$. The variance of ${\hat{p}}_3$ is
$(\mathbb{E}[h^2] - \mathbb{E}[h]^2)/m$ and an integration by parts shows that
it is equal to $0.0285/m$. Moreover, since $p$ can be written as
$$
p = \int_0^{1/2} \; {y^{-2}\over \pi(1 + y^{-2})} \; \text{d}y \;,
$$
this integral can also be seen as the expectation of
${1\over 4} \; h(Y) = 1/2\pi(1 + Y^2)$ against the
uniform distribution on $[0,1/2]$ and another evaluation of $p$ is
$$
{\hat{p}}_4 = {1\over 4 m} \; \sum_{j=1}^m \; h(Y_j)
$$
when $Y_j \sim {\mathcal{U}}_{[0,1/2]}$. The same integration by
parts shows that the variance of ${\hat{p}}_{4}$ is then
$0.95 \; 10^{-4}/m$.
Compared with ${\hat{p}}_1$, the reduction in variance brought by ${\hat p}_4$
is of order $10^{-3}$, which implies, in
particular, that this evaluation requires
$\sqrt{1000} \approx 32$ times fewer simulations than $\hat p_1$
to achieve the same precision. $\blacktriangleright$
|
What is importance sampling?
Importance sampling is a simulation or Monte Carlo method intended for approximating integrals. The term "sampling" is somewhat confusing in that it does not intend to provide samples from a given dis
|
10,209
|
Why are standard frequentist hypotheses so uninteresting?
|
You can regard this as an example of 'All models are wrong but some are useful'. Null hypothesis testing is a simplification.
Null hypothesis testing is often not the primary goal and instead it is more like a tool for some other goal, and it is used as an indicator of the quality of a certain result/measurement.
An experimenter wants to know the effect size and know whether the result is statistically significant.
For the latter, statistical significance, one can use a null hypothesis test (which answers the question whether the observation has a statistically significant deviation from zero).
The null hypothesis test and p-values are now considered as a bit of an old fashioned tool. Better expressions of experimental results are confidence intervals or intervals from Bayesian approaches.
The equality hypothesis is a priori known to be wrong
Yes, if you consider coins.
But an exception might be hardcore science like physics or chemistry where certain theories are tested. For instance the equivalence principle.
In addition if the equality hypothesis is a priori wrong, then why perform an experiment? If something is a priori wrong then the point is not to show that this something is wrong, instead the point is to show that there is an effect that can be easily measured. A casino that wants to test coins may not care about the theoretical probability that coins are not exactly p=0.5 fair and might differ by some theoretically small value, they care about finding out coins with a larger difference. And the point of the null hypothesis test is to prevent false positives.
Also note the two approaches/philosophies behind null hypothesis testing
Fisher: You may have observed some effect, and as expected it is not zero, but if your p-value is high then it means that your test has little precision and little strength in differentiating between different effect sizes (even down to a true effect size of zero, the observed effect may have likely occured and thus statistical fluctuations govern your observation). So you better gather some more data.
The p-value and null hypothesis is a rule of thumb for indicating precision of an experiment.
Neyman and Pearson: (from 'On the Problem of the Most Efficient Tests of Statistical Hypotheses')
Indeed, if $x$ is a continuous variable – as for example is the angular distance between two stars – then any value of $x$ is a singularity of relative probability equal to zero. We are inclined to think that as far as a particular hypothesis is concerned, no test based upon the theory of probability can by itself provide any valuable evidence of the truth or falsehood of that hypothesis.
But we may look at the purpose of tests from another view-point. Without hoping to know whether each separate hypothesis is true or false, we may search for rules to govern our behaviour with regard to them, in following which we insure that, in the long run of experience, we shall not be too often wrong.
The hypothesis test is a practical device to create a decision rule. One goal is to make this rule efficient and using a likelihood ratio with a null hypothesis is one method of achieving that.
In "real life" one is always only interested in some finite accuracy $\epsilon$, meaning the hypothesis of interest is actually of the form $H_0: |\mu-\mu_0|<\epsilon$.
This is captured by hypothesis testing. An example is two one-sided t-tests for equivalence testing and can be explained with the following image and can be considered as testing three hypotheses instead of two for the absolute difference
$$\begin{array}{}H_0&:& \text{|difference|} = 0\\
H_\epsilon&:& 0 <\text{|difference|} \leq \epsilon\\
H_\text{effect}&:& \epsilon < \text{|difference|} \end{array}$$
Below is a sketch of the position of the confidence interval within these 3 regions (unlike the typical sketch of TOST, there are actually 5 situations instead of 4).
The point of observations and experiments is to find a data driven answer to questions by excluding/eliminating what is (probably) not the answer (Popper's falsification).
Null hypothesis testing does this in a somewhat crude manner and does not differentiate between the situations B, C, E. However, in many situations this is not all too much of a problem. In a lot of situations the problem is not to test tiny effects with $H_0: |\mu-\mu_0|<\epsilon$. The effect size is expected to be sufficiently large and above some $\epsilon$. In many practical cases testing $|\text{difference}| > \epsilon$ is nearly the same as $|\text{difference}| > 0$ and the null hypothesis test is a simplification. It is in the modern days of large amounts of data that effect sizes of $\epsilon$ play a role in results.
Before this issue was dealt with by having arbitrary cut-off values for p-values and by power analysis. If a test had a p-values below some significance level, then the conclusion is that the effect must be some effect beyond some size. These p-values are still arbitrary, also with TOST equivalence testing. A researcher has some given significance level and computes a required sample size to obtain a given power for a given effect that the researcher wants to be able to measure. The effect of replacing $H_0$ by some range within $\epsilon$ is effectively changing the power curve. For a given effect size close to $\epsilon$ the power is reduced and it becomes less likely to reject the null hypothesis. It is effectively just a shift in the power.
Why are standard frequentist hypotheses so uninteresting?
They are simple basic examples that allow for easy computations. It is easier to work with them. But indeed, it is more difficult to imagine the practical relevance.
|
Why are standard frequentist hypotheses so uninteresting?
|
You can regard this as an example of 'All models are wrong but some are useful'. Null hypothesis testing is a simplification.
Null hypothesis testing is often not the primary goal and instead it is m
|
Why are standard frequentist hypotheses so uninteresting?
You can regard this as an example of 'All models are wrong but some are useful'. Null hypothesis testing is a simplification.
Null hypothesis testing is often not the primary goal and instead it is more like a tool for some other goal, and it is used as an indicator of the quality of a certain result/measurement.
An experimenter wants to know the effect size and know whether the result is statistically significant.
For the latter, statistical significance, one can use a null hypothesis test (which answers the question whether the observation has a statistically significant deviation from zero).
The null hypothesis test and p-values are now considered as a bit of an old fashioned tool. Better expressions of experimental results are confidence intervals or intervals from Bayesian approaches.
The equality hypothesis is a priori known to be wrong
Yes, if you consider coins.
But an exception might be hardcore science like physics or chemistry where certain theories are tested. For instance the equivalence principle.
In addition if the equality hypothesis is a priori wrong, then why perform an experiment? If something is a priori wrong then the point is not to show that this something is wrong, instead the point is to show that there is an effect that can be easily measured. A casino that wants to test coins may not care about the theoretical probability that coins are not exactly p=0.5 fair and might differ by some theoretically small value, they care about finding out coins with a larger difference. And the point of the null hypothesis test is to prevent false positives.
Also note the two approaches/philosophies behind null hypothesis testing
Fisher: You may have observed some effect, and as expected it is not zero, but if your p-value is high then it means that your test has little precision and little strength in differentiating between different effect sizes (even down to a true effect size of zero, the observed effect may have likely occured and thus statistical fluctuations govern your observation). So you better gather some more data.
The p-value and null hypothesis is a rule of thumb for indicating precision of an experiment.
Neyman and Pearson: (from 'On the Problem of the Most Efficient Tests of Statistical Hypotheses')
Indeed, if $x$ is a continuous variable – as for example is the angular distance between two stars – then any value of $x$ is a singularity of relative probability equal to zero. We are inclined to think that as far as a particular hypothesis is concerned, no test based upon the theory of probability can by itself provide any valuable evidence of the truth or falsehood of that hypothesis.
But we may look at the purpose of tests from another view-point. Without hoping to know whether each separate hypothesis is true or false, we may search for rules to govern our behaviour with regard to them, in following which we insure that, in the long run of experience, we shall not be too often wrong.
The hypothesis test is a practical device to create a decision rule. One goal is to make this rule efficient and using a likelihood ratio with a null hypothesis is one method of achieving that.
In "real life" one is always only interested in some finite accuracy $\epsilon$, meaning the hypothesis of interest is actually of the form $H_0: |\mu-\mu_0|<\epsilon$.
This is captured by hypothesis testing. An example is two one-sided t-tests for equivalence testing and can be explained with the following image and can be considered as testing three hypotheses instead of two for the absolute difference
$$\begin{array}{}H_0&:& \text{|difference|} = 0\\
H_\epsilon&:& 0 <\text{|difference|} \leq \epsilon\\
H_\text{effect}&:& \epsilon < \text{|difference|} \end{array}$$
Below is a sketch of the position of the confidence interval within these 3 regions (unlike the typical sketch of TOST, there are actually 5 situations instead of 4).
The point of observations and experiments is to find a data driven answer to questions by excluding/eliminating what is (probably) not the answer (Popper's falsification).
Null hypothesis testing does this in a somewhat crude manner and does not differentiate between the situations B, C, E. However, in many situations this is not all too much of a problem. In a lot of situations the problem is not to test tiny effects with $H_0: |\mu-\mu_0|<\epsilon$. The effect size is expected to be sufficiently large and above some $\epsilon$. In many practical cases testing $|\text{difference}| > \epsilon$ is nearly the same as $|\text{difference}| > 0$ and the null hypothesis test is a simplification. It is in the modern days of large amounts of data that effect sizes of $\epsilon$ play a role in results.
Before this issue was dealt with by having arbitrary cut-off values for p-values and by power analysis. If a test had a p-values below some significance level, then the conclusion is that the effect must be some effect beyond some size. These p-values are still arbitrary, also with TOST equivalence testing. A researcher has some given significance level and computes a required sample size to obtain a given power for a given effect that the researcher wants to be able to measure. The effect of replacing $H_0$ by some range within $\epsilon$ is effectively changing the power curve. For a given effect size close to $\epsilon$ the power is reduced and it becomes less likely to reject the null hypothesis. It is effectively just a shift in the power.
Why are standard frequentist hypotheses so uninteresting?
They are simple basic examples that allow for easy computations. It is easier to work with them. But indeed, it is more difficult to imagine the practical relevance.
|
Why are standard frequentist hypotheses so uninteresting?
You can regard this as an example of 'All models are wrong but some are useful'. Null hypothesis testing is a simplification.
Null hypothesis testing is often not the primary goal and instead it is m
|
10,210
|
Why are standard frequentist hypotheses so uninteresting?
|
You have to crawl before you walk, and simple examples like testing a coin for bias, under a null hypothesis of zero bias, make for a teachable example for complete beginners (which every single one of us was at one point).
Jumping straight to, say, equivalence testing without even discussing easier null hypothesis significance testing seems like poor pedagogy. Where the majority of statistics education seems to suffer is when it comes to teaching the numerous limitations of hypothesis testing. After all, the OP is right: we basically always know the null hypothesis to be at least a little bit false, and we probably are more interested in something along the lines of $H_0: \vert \mu_1-\mu_2\vert<\epsilon$. Better integration of equivalence testing like this into early statistics curricula is an interesting idea—at least after some basics are covered.
|
Why are standard frequentist hypotheses so uninteresting?
|
You have to crawl before you walk, and simple examples like testing a coin for bias, under a null hypothesis of zero bias, make for a teachable example for complete beginners (which every single one o
|
Why are standard frequentist hypotheses so uninteresting?
You have to crawl before you walk, and simple examples like testing a coin for bias, under a null hypothesis of zero bias, make for a teachable example for complete beginners (which every single one of us was at one point).
Jumping straight to, say, equivalence testing without even discussing easier null hypothesis significance testing seems like poor pedagogy. Where the majority of statistics education seems to suffer is when it comes to teaching the numerous limitations of hypothesis testing. After all, the OP is right: we basically always know the null hypothesis to be at least a little bit false, and we probably are more interested in something along the lines of $H_0: \vert \mu_1-\mu_2\vert<\epsilon$. Better integration of equivalence testing like this into early statistics curricula is an interesting idea—at least after some basics are covered.
|
Why are standard frequentist hypotheses so uninteresting?
You have to crawl before you walk, and simple examples like testing a coin for bias, under a null hypothesis of zero bias, make for a teachable example for complete beginners (which every single one o
|
10,211
|
Why are standard frequentist hypotheses so uninteresting?
|
No model is ever true. This means that not only the null hypothesis is not true, neither is the alternative, nor something like $|\mu_1-\mu_2|<\epsilon$. If you're interested in which model is true, you're generally lost in model-based statistics; there's nothing particularly wrong about standard null hypotheses. Whether the $H_0$ or any parametric model is true is simply the wrong question.
Of course you can decide yourself what you're interested in, but I find often informative whether or not data give any evidence against a simplistic random variation "nothing meaningful is going on" model. Of course we all know that non-rejection doesn't mean the null model is true, but if you can't reject it you should really really really not claim that the data show anything meaningful, and by the way then of course you can't reject $|\mu_1-\mu_2|<\epsilon$ either, whatever $\epsilon$.
Of course you should be interested in effect sizes and not only run a null hypothesis test, so that even in case your point null is not rejected you can see whether data are still compatible with a ridiculously low effect (i.e., compute a confidence interval and see whether something as small as $\epsilon$ is in it, in case you can specify a "critical $\epsilon$").
Baseline: What's "interesting" is subjective, but the rationale of testing a point null is not the question whether it's true (it isn't, but it isn't alone at that), but rather whether there's any clear "signal" in the data deviating from it. In case there is, you've got to do more to learn more.
Note particularly that it is one thing to actually reject the $H_0$, but quite another to just claim, in case you didn't reject it, that you'd have rejected it with more data. Particularly then you won't have any idea in which direction things will go. And also, D. Mayo made the valid point that if rejecting a $H_0$ were so easy indeed, why is it often so hard to replicate rejections?
Another consideration is that in fact tests will not always reject a false null hypothesis with a large enough data set, because (a) many standard frequentist tests are one sided and with a large data set things may go to the wrong side, and (b) in case the nominal model is wrong (which it always is), one can in many cases even find other models that imply a low probability to reject the null hypothesis for a range of parameters and also for big data sets, for example if you use a t-test and the true underlying distribution has very heavy tails and/or produces outliers, or if you have negative correlation between observations.
|
Why are standard frequentist hypotheses so uninteresting?
|
No model is ever true. This means that not only the null hypothesis is not true, neither is the alternative, nor something like $|\mu_1-\mu_2|<\epsilon$. If you're interested in which model is true, y
|
Why are standard frequentist hypotheses so uninteresting?
No model is ever true. This means that not only the null hypothesis is not true, neither is the alternative, nor something like $|\mu_1-\mu_2|<\epsilon$. If you're interested in which model is true, you're generally lost in model-based statistics; there's nothing particularly wrong about standard null hypotheses. Whether the $H_0$ or any parametric model is true is simply the wrong question.
Of course you can decide yourself what you're interested in, but I find often informative whether or not data give any evidence against a simplistic random variation "nothing meaningful is going on" model. Of course we all know that non-rejection doesn't mean the null model is true, but if you can't reject it you should really really really not claim that the data show anything meaningful, and by the way then of course you can't reject $|\mu_1-\mu_2|<\epsilon$ either, whatever $\epsilon$.
Of course you should be interested in effect sizes and not only run a null hypothesis test, so that even in case your point null is not rejected you can see whether data are still compatible with a ridiculously low effect (i.e., compute a confidence interval and see whether something as small as $\epsilon$ is in it, in case you can specify a "critical $\epsilon$").
Baseline: What's "interesting" is subjective, but the rationale of testing a point null is not the question whether it's true (it isn't, but it isn't alone at that), but rather whether there's any clear "signal" in the data deviating from it. In case there is, you've got to do more to learn more.
Note particularly that it is one thing to actually reject the $H_0$, but quite another to just claim, in case you didn't reject it, that you'd have rejected it with more data. Particularly then you won't have any idea in which direction things will go. And also, D. Mayo made the valid point that if rejecting a $H_0$ were so easy indeed, why is it often so hard to replicate rejections?
Another consideration is that in fact tests will not always reject a false null hypothesis with a large enough data set, because (a) many standard frequentist tests are one sided and with a large data set things may go to the wrong side, and (b) in case the nominal model is wrong (which it always is), one can in many cases even find other models that imply a low probability to reject the null hypothesis for a range of parameters and also for big data sets, for example if you use a t-test and the true underlying distribution has very heavy tails and/or produces outliers, or if you have negative correlation between observations.
|
Why are standard frequentist hypotheses so uninteresting?
No model is ever true. This means that not only the null hypothesis is not true, neither is the alternative, nor something like $|\mu_1-\mu_2|<\epsilon$. If you're interested in which model is true, y
|
10,212
|
Why are standard frequentist hypotheses so uninteresting?
|
The appeal of such hypotheses lies in their simplicity and the analytical tractability (or just simplicity) of testing them.*
In "real life" one is always only interested in some finite accuracy $\epsilon$, meaning the hypothesis of interest is actually of the form $H_0: |\mu-\mu_0|<\epsilon$.
This might be true for continuous phenomena, but not for discrete ones. E.g. in genetics a gene either has an effect on something or not. (I guess there can be even better examples than that.)
The fact that the null hypothesis cannot be rejected is by definition temporary, and is an artifact of not enough data. Given enough data, any type of equality hypothesis on continuous variables will be rejected in a real world use case.
Again, this holds for continuous phenomena only.
What we can criticize is perhaps the choice of examples in textbooks. Perhaps more examples of discrete phenomena are in order.
*Your criticism could just as well be directed at statistical models. These are often quite simple (e.g. the ubiquitous linear models), and much of their appeal is also in their tractability and simplicity of interpretation. Or even models in general, as again they are simplifications of reality with all of the drawbacks (but also benefits) that come with that.
|
Why are standard frequentist hypotheses so uninteresting?
|
The appeal of such hypotheses lies in their simplicity and the analytical tractability (or just simplicity) of testing them.*
In "real life" one is always only interested in some finite accuracy $\e
|
Why are standard frequentist hypotheses so uninteresting?
The appeal of such hypotheses lies in their simplicity and the analytical tractability (or just simplicity) of testing them.*
In "real life" one is always only interested in some finite accuracy $\epsilon$, meaning the hypothesis of interest is actually of the form $H_0: |\mu-\mu_0|<\epsilon$.
This might be true for continuous phenomena, but not for discrete ones. E.g. in genetics a gene either has an effect on something or not. (I guess there can be even better examples than that.)
The fact that the null hypothesis cannot be rejected is by definition temporary, and is an artifact of not enough data. Given enough data, any type of equality hypothesis on continuous variables will be rejected in a real world use case.
Again, this holds for continuous phenomena only.
What we can criticize is perhaps the choice of examples in textbooks. Perhaps more examples of discrete phenomena are in order.
*Your criticism could just as well be directed at statistical models. These are often quite simple (e.g. the ubiquitous linear models), and much of their appeal is also in their tractability and simplicity of interpretation. Or even models in general, as again they are simplifications of reality with all of the drawbacks (but also benefits) that come with that.
|
Why are standard frequentist hypotheses so uninteresting?
The appeal of such hypotheses lies in their simplicity and the analytical tractability (or just simplicity) of testing them.*
In "real life" one is always only interested in some finite accuracy $\e
|
10,213
|
Why are standard frequentist hypotheses so uninteresting?
|
(1) The more boring a null hypothesis, the more interesting it is when you are unable to reject.
E.g. after one million flips, we still cannot distinguish the coin from perfectly unbiased. (After one million patients, we still cannot distinguish the treatment from placebo.)
(2) If your question isn't a testing question, don't use a test to answer it.
E.g. instead of a yes/no question "is the coin biased", you want to estimate "how biased is the coin". (What is the impact of a disease on life expectancy.)
|
Why are standard frequentist hypotheses so uninteresting?
|
(1) The more boring a null hypothesis, the more interesting it is when you are unable to reject.
E.g. after one million flips, we still cannot distinguish the coin from perfectly unbiased. (After one
|
Why are standard frequentist hypotheses so uninteresting?
(1) The more boring a null hypothesis, the more interesting it is when you are unable to reject.
E.g. after one million flips, we still cannot distinguish the coin from perfectly unbiased. (After one million patients, we still cannot distinguish the treatment from placebo.)
(2) If your question isn't a testing question, don't use a test to answer it.
E.g. instead of a yes/no question "is the coin biased", you want to estimate "how biased is the coin". (What is the impact of a disease on life expectancy.)
|
Why are standard frequentist hypotheses so uninteresting?
(1) The more boring a null hypothesis, the more interesting it is when you are unable to reject.
E.g. after one million flips, we still cannot distinguish the coin from perfectly unbiased. (After one
|
10,214
|
Why are standard frequentist hypotheses so uninteresting?
|
To calculate a p-value, you need a null hypothesis such that the test statistic has a known distribution. Simple asserting $|\mu|<\epsilon$ doesn't give you a distribution.
|
Why are standard frequentist hypotheses so uninteresting?
|
To calculate a p-value, you need a null hypothesis such that the test statistic has a known distribution. Simple asserting $|\mu|<\epsilon$ doesn't give you a distribution.
|
Why are standard frequentist hypotheses so uninteresting?
To calculate a p-value, you need a null hypothesis such that the test statistic has a known distribution. Simple asserting $|\mu|<\epsilon$ doesn't give you a distribution.
|
Why are standard frequentist hypotheses so uninteresting?
To calculate a p-value, you need a null hypothesis such that the test statistic has a known distribution. Simple asserting $|\mu|<\epsilon$ doesn't give you a distribution.
|
10,215
|
Why are standard frequentist hypotheses so uninteresting?
|
In "real life" one is always only interested in some finite accuracy ϵ, meaning the hypothesis of interest is actually of the form H0:|μ−μ0|<ϵ.
Indeed, it is an important practical issue that a significant effect turn out to be small and therefore "insignificant" for practical purposes. As an anecdotal example: bilingual children start speaking later than their peers in monolingual families... but this discrepancy is smaller than that between boys and girls (boys start speaking later than girls.) - The effect is statistically significant, but of too little importance to deprive your child from learning a second language from their birth.
There are procedures for testing whether the effect is bigger than some pre-specified value, see Equivalence testing. However these testing procedures are based on simpler testing procedures, which therefore must be learned beforehand.
The equality hypothesis is a priori known to be wrong when considering continuous variables (no coin is perfectly unbiased in reality!), and as a corollary,
The fact that the null hypothesis cannot be rejected is by definition temporary, and is an artifact of not enough data. Given enough data, any type of equality hypothesis on continuous variables will be rejected in a real world use case.
The seeming paradox arises here, because we abandon some idealizations, while preserving the other: thus, while taking into account that no coin is perfect, we still assume that a) we can make an infinite number of trials, and b) the effect is important (greater than some $\epsilon$.) A well known adagio about models is that "All models are wrong, but some are useful" and statistical testing is a case in point.
In short story On Exactitude in Science Jorge Luis Borges has given a well-known poetic description of why any useful model/theory is necessarily approximate, whereas the one that takes into account everything is totally useless. (See here for the full text.)
|
Why are standard frequentist hypotheses so uninteresting?
|
In "real life" one is always only interested in some finite accuracy ϵ, meaning the hypothesis of interest is actually of the form H0:|μ−μ0|<ϵ.
Indeed, it is an important practical issue that a sign
|
Why are standard frequentist hypotheses so uninteresting?
In "real life" one is always only interested in some finite accuracy ϵ, meaning the hypothesis of interest is actually of the form H0:|μ−μ0|<ϵ.
Indeed, it is an important practical issue that a significant effect turn out to be small and therefore "insignificant" for practical purposes. As an anecdotal example: bilingual children start speaking later than their peers in monolingual families... but this discrepancy is smaller than that between boys and girls (boys start speaking later than girls.) - The effect is statistically significant, but of too little importance to deprive your child from learning a second language from their birth.
There are procedures for testing whether the effect is bigger than some pre-specified value, see Equivalence testing. However these testing procedures are based on simpler testing procedures, which therefore must be learned beforehand.
The equality hypothesis is a priori known to be wrong when considering continuous variables (no coin is perfectly unbiased in reality!), and as a corollary,
The fact that the null hypothesis cannot be rejected is by definition temporary, and is an artifact of not enough data. Given enough data, any type of equality hypothesis on continuous variables will be rejected in a real world use case.
The seeming paradox arises here, because we abandon some idealizations, while preserving the other: thus, while taking into account that no coin is perfect, we still assume that a) we can make an infinite number of trials, and b) the effect is important (greater than some $\epsilon$.) A well known adagio about models is that "All models are wrong, but some are useful" and statistical testing is a case in point.
In short story On Exactitude in Science Jorge Luis Borges has given a well-known poetic description of why any useful model/theory is necessarily approximate, whereas the one that takes into account everything is totally useless. (See here for the full text.)
|
Why are standard frequentist hypotheses so uninteresting?
In "real life" one is always only interested in some finite accuracy ϵ, meaning the hypothesis of interest is actually of the form H0:|μ−μ0|<ϵ.
Indeed, it is an important practical issue that a sign
|
10,216
|
Why are standard frequentist hypotheses so uninteresting?
|
I wouldn't put too much philosophical labor into contemplating the null hypothesis per se, as the OP does.
As I have discussed here, this is a device through which we can determine whether the data allow us to assert probabilistically the direction of influence.
And the direction of influence is a heavyweight, in all worlds.
|
Why are standard frequentist hypotheses so uninteresting?
|
I wouldn't put too much philosophical labor into contemplating the null hypothesis per se, as the OP does.
As I have discussed here, this is a device through which we can determine whether the data al
|
Why are standard frequentist hypotheses so uninteresting?
I wouldn't put too much philosophical labor into contemplating the null hypothesis per se, as the OP does.
As I have discussed here, this is a device through which we can determine whether the data allow us to assert probabilistically the direction of influence.
And the direction of influence is a heavyweight, in all worlds.
|
Why are standard frequentist hypotheses so uninteresting?
I wouldn't put too much philosophical labor into contemplating the null hypothesis per se, as the OP does.
As I have discussed here, this is a device through which we can determine whether the data al
|
10,217
|
When does Fisher's "go get more data" approach make sense?
|
The frequentist paradigm is a conflation of Fisher's and Neyman-Pearson's views. Only in using one approach and another interpretation do problems arise.
It should seem strange to anyone that collecting more data is problematic, as more data is more evidence. Indeed, the problem lies not in collecting more data, but in using the $p$-value to decide to do so, when it is also the measure of interest. Collecting more data based on the $p$-value is only $p$-hacking if you compute a new $p$-value.
If you have insufficient evidence to make a satisfactory conclusion about the research question, then by all means, go get more data. However, concede that you are now past the NHST stage of your research, and focus instead on quantifying the effect of interest.
An interesting note is that Bayesians do not suffer from this dilemma. Consider the following as an example:
If a frequentist concludes no significant difference and then switches to a test of equivalence, surely the false positive rate has increased;
A Bayesian can express the highest density interval and region of practical equivalence of a difference simultaneously and sleep just the same at night.
|
When does Fisher's "go get more data" approach make sense?
|
The frequentist paradigm is a conflation of Fisher's and Neyman-Pearson's views. Only in using one approach and another interpretation do problems arise.
It should seem strange to anyone that collecti
|
When does Fisher's "go get more data" approach make sense?
The frequentist paradigm is a conflation of Fisher's and Neyman-Pearson's views. Only in using one approach and another interpretation do problems arise.
It should seem strange to anyone that collecting more data is problematic, as more data is more evidence. Indeed, the problem lies not in collecting more data, but in using the $p$-value to decide to do so, when it is also the measure of interest. Collecting more data based on the $p$-value is only $p$-hacking if you compute a new $p$-value.
If you have insufficient evidence to make a satisfactory conclusion about the research question, then by all means, go get more data. However, concede that you are now past the NHST stage of your research, and focus instead on quantifying the effect of interest.
An interesting note is that Bayesians do not suffer from this dilemma. Consider the following as an example:
If a frequentist concludes no significant difference and then switches to a test of equivalence, surely the false positive rate has increased;
A Bayesian can express the highest density interval and region of practical equivalence of a difference simultaneously and sleep just the same at night.
|
When does Fisher's "go get more data" approach make sense?
The frequentist paradigm is a conflation of Fisher's and Neyman-Pearson's views. Only in using one approach and another interpretation do problems arise.
It should seem strange to anyone that collecti
|
10,218
|
When does Fisher's "go get more data" approach make sense?
|
Given a big enough sample size, a test will always show significant results, unless the true effect size is exactly zero, as discussed here. In practice, the true effect size is not zero, so gathering more data will eventually be able to detect the most minuscule differences.
The (IMO) facetious answer from Fisher was in response to a relatively trivial question that at its premise is conflating 'significant difference' with 'practically relevant difference'.
It would be equivalent to a researcher coming into my office and asking "I weighed this lead weight labeled '25 gram' and it measured 25.0 grams. I believe it to be mislabeled, what should I do?" To which I could answer, "Get a more precise scale."
That being said, I believe the go-get-more-data approach is appropriate if the initial test is woefully underpowered to detect the magnitude of difference that is practically relevant.
|
When does Fisher's "go get more data" approach make sense?
|
Given a big enough sample size, a test will always show significant results, unless the true effect size is exactly zero, as discussed here. In practice, the true effect size is not zero, so gatherin
|
When does Fisher's "go get more data" approach make sense?
Given a big enough sample size, a test will always show significant results, unless the true effect size is exactly zero, as discussed here. In practice, the true effect size is not zero, so gathering more data will eventually be able to detect the most minuscule differences.
The (IMO) facetious answer from Fisher was in response to a relatively trivial question that at its premise is conflating 'significant difference' with 'practically relevant difference'.
It would be equivalent to a researcher coming into my office and asking "I weighed this lead weight labeled '25 gram' and it measured 25.0 grams. I believe it to be mislabeled, what should I do?" To which I could answer, "Get a more precise scale."
That being said, I believe the go-get-more-data approach is appropriate if the initial test is woefully underpowered to detect the magnitude of difference that is practically relevant.
|
When does Fisher's "go get more data" approach make sense?
Given a big enough sample size, a test will always show significant results, unless the true effect size is exactly zero, as discussed here. In practice, the true effect size is not zero, so gatherin
|
10,219
|
When does Fisher's "go get more data" approach make sense?
|
What we call P-hacking is applying a significance test multiple times and only reporting the significance results. Whether this is good or bad is situationally dependent.
To explain, let's think about true effects in Bayesian terms, rather than null and alternative hypotheses. As long as we believe our effects of interest come from a continuous distribution, then we know the null hypothesis is false. However, in the case of a two-sided test, we don't know whether it is positive or negative. Under this light, we can think of p-values for two sided tests as a measure of how strong the evidence is that our estimate has the correct direction (i.e., positive or negative effect).
Under this interpretation, any significance test can have three possible outcomes: we see enough evidence to conclude the direction of the effect and we are correct, we see enough evidence to conclude the direction of the effect but we are wrong, or we don't see enough evidence to conclude the direction of the effect. Note that conditional that you have enough evidence (i.e., $p < \alpha$), the probability of getting the direction correct should be greater than the probability of getting it incorrect (unless you have some really crazy, really bad test), although as the true effect size approaches zero, the conditional probability of getting the direction correct given sufficient evidence approaches 0.5.
Now, consider what happens when you keep going back to get more data. Each time you get more data, your probability of getting the direction correct conditional on sufficient data only goes up. So under in this scenario, we should realize that by getting more data, although we are in fact increasing the probability of a type I error, we are also reducing the probability of mistakenly concluding the wrong direction.
Take this in contrast the more typical abuse of P-hacking; we test 100's of effect sizes that have good probability of being very small and only report the significant ones. Note that in this case, if all the effects are small, we have a near 50% chance of getting the direction wrong when we declare significance.
Of course, the produced p-values from this data-double-down should still come with a grain of salt. While, in general, you shouldn't have a problem with people collecting more data to be more certain about an effect size, this could be abused in other ways. For example, a clever PI might realize that instead of collecting all 100 data points at once, they could save a bunch of money and increase power by first collecting 50 data points, analyzing the data, and then collecting the next 50 if it's not significant. In this scenario, they increase the probability of getting the direction of the effect wrong conditional on declaring significance, since they are more likely to get the direction of the effect wrong with 50 data points than with 100 data points.
And finally, consider the implications of not getting more data when we have an insignificant result. That would imply never collecting more information on the topic, which won't really push the science forward, would it? One underpowered study would kill a whole field.
|
When does Fisher's "go get more data" approach make sense?
|
What we call P-hacking is applying a significance test multiple times and only reporting the significance results. Whether this is good or bad is situationally dependent.
To explain, let's think abou
|
When does Fisher's "go get more data" approach make sense?
What we call P-hacking is applying a significance test multiple times and only reporting the significance results. Whether this is good or bad is situationally dependent.
To explain, let's think about true effects in Bayesian terms, rather than null and alternative hypotheses. As long as we believe our effects of interest come from a continuous distribution, then we know the null hypothesis is false. However, in the case of a two-sided test, we don't know whether it is positive or negative. Under this light, we can think of p-values for two sided tests as a measure of how strong the evidence is that our estimate has the correct direction (i.e., positive or negative effect).
Under this interpretation, any significance test can have three possible outcomes: we see enough evidence to conclude the direction of the effect and we are correct, we see enough evidence to conclude the direction of the effect but we are wrong, or we don't see enough evidence to conclude the direction of the effect. Note that conditional that you have enough evidence (i.e., $p < \alpha$), the probability of getting the direction correct should be greater than the probability of getting it incorrect (unless you have some really crazy, really bad test), although as the true effect size approaches zero, the conditional probability of getting the direction correct given sufficient evidence approaches 0.5.
Now, consider what happens when you keep going back to get more data. Each time you get more data, your probability of getting the direction correct conditional on sufficient data only goes up. So under in this scenario, we should realize that by getting more data, although we are in fact increasing the probability of a type I error, we are also reducing the probability of mistakenly concluding the wrong direction.
Take this in contrast the more typical abuse of P-hacking; we test 100's of effect sizes that have good probability of being very small and only report the significant ones. Note that in this case, if all the effects are small, we have a near 50% chance of getting the direction wrong when we declare significance.
Of course, the produced p-values from this data-double-down should still come with a grain of salt. While, in general, you shouldn't have a problem with people collecting more data to be more certain about an effect size, this could be abused in other ways. For example, a clever PI might realize that instead of collecting all 100 data points at once, they could save a bunch of money and increase power by first collecting 50 data points, analyzing the data, and then collecting the next 50 if it's not significant. In this scenario, they increase the probability of getting the direction of the effect wrong conditional on declaring significance, since they are more likely to get the direction of the effect wrong with 50 data points than with 100 data points.
And finally, consider the implications of not getting more data when we have an insignificant result. That would imply never collecting more information on the topic, which won't really push the science forward, would it? One underpowered study would kill a whole field.
|
When does Fisher's "go get more data" approach make sense?
What we call P-hacking is applying a significance test multiple times and only reporting the significance results. Whether this is good or bad is situationally dependent.
To explain, let's think abou
|
10,220
|
When does Fisher's "go get more data" approach make sense?
|
Thanks. There are a couple things to bear in mind here:
The quote may be apocryphal.
It's quite reasonable to go get more / better data, or data from a different source (more precise scale, cf., @Underminer's answer; different situation or controls; etc.), for a second study (cf., @Glen_b's comment). That is, you wouldn't analyze the additional data in conjunction with the original data: say you had N=10 with a non-significant result, you could gather another N=20 data and analyze them alone (not testing the full 30 together). If the quote isn't apocryphal, that could have been what Fisher had in mind.
Fisher's philosophy of science was essentially Popperian. That is, the null wasn't necessarily something to reject perfunctorily so as to confirm your theory, but ideally could be your theory itself, such that rejection means your pet theory is wrong and you need to go back to the drawing board. In such a case, type I error inflation would not benefit the researcher. (On the other hand, this interpretation cuts against Fisher giving this advice unless he was being a quarrelsome, which would not have been out of character.)
At any rate, it's worth pointing out that the reason I included that comment is that it illustrates something fundamental about the difference in the nature of the two approaches.
|
When does Fisher's "go get more data" approach make sense?
|
Thanks. There are a couple things to bear in mind here:
The quote may be apocryphal.
It's quite reasonable to go get more / better data, or data from a different source (more precise scale, cf.,
|
When does Fisher's "go get more data" approach make sense?
Thanks. There are a couple things to bear in mind here:
The quote may be apocryphal.
It's quite reasonable to go get more / better data, or data from a different source (more precise scale, cf., @Underminer's answer; different situation or controls; etc.), for a second study (cf., @Glen_b's comment). That is, you wouldn't analyze the additional data in conjunction with the original data: say you had N=10 with a non-significant result, you could gather another N=20 data and analyze them alone (not testing the full 30 together). If the quote isn't apocryphal, that could have been what Fisher had in mind.
Fisher's philosophy of science was essentially Popperian. That is, the null wasn't necessarily something to reject perfunctorily so as to confirm your theory, but ideally could be your theory itself, such that rejection means your pet theory is wrong and you need to go back to the drawing board. In such a case, type I error inflation would not benefit the researcher. (On the other hand, this interpretation cuts against Fisher giving this advice unless he was being a quarrelsome, which would not have been out of character.)
At any rate, it's worth pointing out that the reason I included that comment is that it illustrates something fundamental about the difference in the nature of the two approaches.
|
When does Fisher's "go get more data" approach make sense?
Thanks. There are a couple things to bear in mind here:
The quote may be apocryphal.
It's quite reasonable to go get more / better data, or data from a different source (more precise scale, cf.,
|
10,221
|
When does Fisher's "go get more data" approach make sense?
|
If the alternative had a small a priori probability, then an experiment that fails to reject the null will decrease it further, making any further research even less cost-effective. For instance, suppose the a priori probability is .01. Then your entropy is .08 bits. If the probability gets reduced to .001, then your entropy is now .01. Thus, continuing to collect data is often not cost effective. One reason why it would be cost effective would be that knowing is so important that even the remaining .01 bits of entropy is worth reducing.
Another reason would be if the a priori probability was really high. If your a priori probability was more than 50%, then failing to reject the null increases your entropy, making it more cost effective to continue collecting data. An example would be when you're nearly certain that there is an effect, but don't know in which direction.
For instance, if you're a counterintelligence agent and you're sure that a department has a mole, and have narrowed it down to two suspects, and are doing some statistical analysis to decide which one, then a statistically insignificant result would justify collecting more data.
|
When does Fisher's "go get more data" approach make sense?
|
If the alternative had a small a priori probability, then an experiment that fails to reject the null will decrease it further, making any further research even less cost-effective. For instance, supp
|
When does Fisher's "go get more data" approach make sense?
If the alternative had a small a priori probability, then an experiment that fails to reject the null will decrease it further, making any further research even less cost-effective. For instance, suppose the a priori probability is .01. Then your entropy is .08 bits. If the probability gets reduced to .001, then your entropy is now .01. Thus, continuing to collect data is often not cost effective. One reason why it would be cost effective would be that knowing is so important that even the remaining .01 bits of entropy is worth reducing.
Another reason would be if the a priori probability was really high. If your a priori probability was more than 50%, then failing to reject the null increases your entropy, making it more cost effective to continue collecting data. An example would be when you're nearly certain that there is an effect, but don't know in which direction.
For instance, if you're a counterintelligence agent and you're sure that a department has a mole, and have narrowed it down to two suspects, and are doing some statistical analysis to decide which one, then a statistically insignificant result would justify collecting more data.
|
When does Fisher's "go get more data" approach make sense?
If the alternative had a small a priori probability, then an experiment that fails to reject the null will decrease it further, making any further research even less cost-effective. For instance, supp
|
10,222
|
R code for time series forecasting using Kalman filter
|
Have you looked at Time Series Task View at CRAN?
It lists several entries for packages covering Kalman filtering:
dlm
FKF
KFAS
and more as this is a pretty common techique for time series estimation.
|
R code for time series forecasting using Kalman filter
|
Have you looked at Time Series Task View at CRAN?
It lists several entries for packages covering Kalman filtering:
dlm
FKF
KFAS
and more as this is a pretty common techique for time series estimati
|
R code for time series forecasting using Kalman filter
Have you looked at Time Series Task View at CRAN?
It lists several entries for packages covering Kalman filtering:
dlm
FKF
KFAS
and more as this is a pretty common techique for time series estimation.
|
R code for time series forecasting using Kalman filter
Have you looked at Time Series Task View at CRAN?
It lists several entries for packages covering Kalman filtering:
dlm
FKF
KFAS
and more as this is a pretty common techique for time series estimati
|
10,223
|
R code for time series forecasting using Kalman filter
|
In addition to the packages mentioned in other answers, you may want to look at
package forecast which deals with a particular class of models cast in state-space form and package MARSS with examples and applications in biology (see in particular the well-writen manual, Chap. 5).
For general applications, I aggree, though, with the previous answers, with
dlm being in my view a versatile and powerful package (well described in the book Dynamic Linear Models in R, by Petris et al.), KFAS offering routines which implement most of the algorithms described in the excellent Time Series Analysis by State Space Methods and FKF with limited facilities and no examples, but being the fastest.
|
R code for time series forecasting using Kalman filter
|
In addition to the packages mentioned in other answers, you may want to look at
package forecast which deals with a particular class of models cast in state-space form and package MARSS with examples
|
R code for time series forecasting using Kalman filter
In addition to the packages mentioned in other answers, you may want to look at
package forecast which deals with a particular class of models cast in state-space form and package MARSS with examples and applications in biology (see in particular the well-writen manual, Chap. 5).
For general applications, I aggree, though, with the previous answers, with
dlm being in my view a versatile and powerful package (well described in the book Dynamic Linear Models in R, by Petris et al.), KFAS offering routines which implement most of the algorithms described in the excellent Time Series Analysis by State Space Methods and FKF with limited facilities and no examples, but being the fastest.
|
R code for time series forecasting using Kalman filter
In addition to the packages mentioned in other answers, you may want to look at
package forecast which deals with a particular class of models cast in state-space form and package MARSS with examples
|
10,224
|
R code for time series forecasting using Kalman filter
|
For good examples look at the dlm vignette I would avoid all the other packages if you don't have a clear idea of what you want to do and how.
|
R code for time series forecasting using Kalman filter
|
For good examples look at the dlm vignette I would avoid all the other packages if you don't have a clear idea of what you want to do and how.
|
R code for time series forecasting using Kalman filter
For good examples look at the dlm vignette I would avoid all the other packages if you don't have a clear idea of what you want to do and how.
|
R code for time series forecasting using Kalman filter
For good examples look at the dlm vignette I would avoid all the other packages if you don't have a clear idea of what you want to do and how.
|
10,225
|
R code for time series forecasting using Kalman filter
|
The package stsm is now available on CRAN. The package offers some utilities to fit the basic structural time series model.
The packages mentioned in other answers provide flexible interfaces to cast a broad range of time series models in state-space form and give sound implementations of the Kalman filter. However, in my view, little attention is given to the procedure that optimizes the likelihood function. A general purpose algorithm --the L-BFGS-B algorithm-- is typically used. The stsm package enhances the standard procedure and provides specific algorithms to fit the basic structural model.
Further details are given in the the document provided with the package. For a quick example you can also see this post.
|
R code for time series forecasting using Kalman filter
|
The package stsm is now available on CRAN. The package offers some utilities to fit the basic structural time series model.
The packages mentioned in other answers provide flexible interfaces to cast
|
R code for time series forecasting using Kalman filter
The package stsm is now available on CRAN. The package offers some utilities to fit the basic structural time series model.
The packages mentioned in other answers provide flexible interfaces to cast a broad range of time series models in state-space form and give sound implementations of the Kalman filter. However, in my view, little attention is given to the procedure that optimizes the likelihood function. A general purpose algorithm --the L-BFGS-B algorithm-- is typically used. The stsm package enhances the standard procedure and provides specific algorithms to fit the basic structural model.
Further details are given in the the document provided with the package. For a quick example you can also see this post.
|
R code for time series forecasting using Kalman filter
The package stsm is now available on CRAN. The package offers some utilities to fit the basic structural time series model.
The packages mentioned in other answers provide flexible interfaces to cast
|
10,226
|
What is the best way to visualize relationship between discrete and continuous variables?
|
Below: The original plot may be misleading because the discrete nature of the variables makes the points overlap:
One way to work around it is to introduce some transparency to the data symbol:
Another way is to displace the location of the symbol mildly to create a smear. This technique is called "jittering:"
Both solutions will still allow you to fit a straight line to assess linearity.
R code for your reference:
x <- trunc(runif(200)*10)
y <- x * 2 + trunc(runif(200)*10)
plot(x,y,pch=16)
plot(x,y,col="#00000020",pch=16)
plot(jitter(x),jitter(y),col="#000000",pch=16)
|
What is the best way to visualize relationship between discrete and continuous variables?
|
Below: The original plot may be misleading because the discrete nature of the variables makes the points overlap:
One way to work around it is to introduce some transparency to the data symbol:
Anot
|
What is the best way to visualize relationship between discrete and continuous variables?
Below: The original plot may be misleading because the discrete nature of the variables makes the points overlap:
One way to work around it is to introduce some transparency to the data symbol:
Another way is to displace the location of the symbol mildly to create a smear. This technique is called "jittering:"
Both solutions will still allow you to fit a straight line to assess linearity.
R code for your reference:
x <- trunc(runif(200)*10)
y <- x * 2 + trunc(runif(200)*10)
plot(x,y,pch=16)
plot(x,y,col="#00000020",pch=16)
plot(jitter(x),jitter(y),col="#000000",pch=16)
|
What is the best way to visualize relationship between discrete and continuous variables?
Below: The original plot may be misleading because the discrete nature of the variables makes the points overlap:
One way to work around it is to introduce some transparency to the data symbol:
Anot
|
10,227
|
What is the best way to visualize relationship between discrete and continuous variables?
|
I would use boxplots to display the relationship between a discrete and a continuous variable. You can make your boxplots vertical or horizontal with standard statistical software, so it's easy to visualize as either IV or DV. It is possible to use a scatterplot with a discrete and continuous variable, just assign a number to the discrete variable (e.g., 1 & 2), and jitter those values (note top plot on right here).
Regarding your comment that the line of best fit might be biased, it depends on what you have. For instance, if you have a discrete variable with two levels as your IV, and a continuous variable as your DV, you can draw a line through the two means and this will not be biased. (We would typically think of this situation as being appropriate for a t-test, but it is actually a form--i.e., simple case--of regression, see my answer here.) On the other hand, if you have a discrete variable with two levels as your DV, standard (OLS) regression would be inappropriate (logistic regression would be called for) and the line of best fit would be biased, but you could fit (& plot) a lowess line as part of your initial data exploration.
For visualizing the relationship between two discrete variables, I would use a mosaic plot. You could also use a sieve plot, an association plot, or a dynamic pressure plot with some programming.
|
What is the best way to visualize relationship between discrete and continuous variables?
|
I would use boxplots to display the relationship between a discrete and a continuous variable. You can make your boxplots vertical or horizontal with standard statistical software, so it's easy to vi
|
What is the best way to visualize relationship between discrete and continuous variables?
I would use boxplots to display the relationship between a discrete and a continuous variable. You can make your boxplots vertical or horizontal with standard statistical software, so it's easy to visualize as either IV or DV. It is possible to use a scatterplot with a discrete and continuous variable, just assign a number to the discrete variable (e.g., 1 & 2), and jitter those values (note top plot on right here).
Regarding your comment that the line of best fit might be biased, it depends on what you have. For instance, if you have a discrete variable with two levels as your IV, and a continuous variable as your DV, you can draw a line through the two means and this will not be biased. (We would typically think of this situation as being appropriate for a t-test, but it is actually a form--i.e., simple case--of regression, see my answer here.) On the other hand, if you have a discrete variable with two levels as your DV, standard (OLS) regression would be inappropriate (logistic regression would be called for) and the line of best fit would be biased, but you could fit (& plot) a lowess line as part of your initial data exploration.
For visualizing the relationship between two discrete variables, I would use a mosaic plot. You could also use a sieve plot, an association plot, or a dynamic pressure plot with some programming.
|
What is the best way to visualize relationship between discrete and continuous variables?
I would use boxplots to display the relationship between a discrete and a continuous variable. You can make your boxplots vertical or horizontal with standard statistical software, so it's easy to vi
|
10,228
|
What is the best way to visualize relationship between discrete and continuous variables?
|
When considering the relationship between a binary outcome variable and a continuous predictor, I would use the loess smoother (with outlier detection turned off, e.g., in R lowess(x, y, iter=0).
In the next release of the R Hmisc package you can easily create a single lattice graphic that puts such curves into a multipanel display for multiple predictors, e.g.
summaryRc(heart.attack ~ age + blood.pressure + weight, data=mydata)
|
What is the best way to visualize relationship between discrete and continuous variables?
|
When considering the relationship between a binary outcome variable and a continuous predictor, I would use the loess smoother (with outlier detection turned off, e.g., in R lowess(x, y, iter=0).
In t
|
What is the best way to visualize relationship between discrete and continuous variables?
When considering the relationship between a binary outcome variable and a continuous predictor, I would use the loess smoother (with outlier detection turned off, e.g., in R lowess(x, y, iter=0).
In the next release of the R Hmisc package you can easily create a single lattice graphic that puts such curves into a multipanel display for multiple predictors, e.g.
summaryRc(heart.attack ~ age + blood.pressure + weight, data=mydata)
|
What is the best way to visualize relationship between discrete and continuous variables?
When considering the relationship between a binary outcome variable and a continuous predictor, I would use the loess smoother (with outlier detection turned off, e.g., in R lowess(x, y, iter=0).
In t
|
10,229
|
What is the best way to visualize relationship between discrete and continuous variables?
|
If you are not satisfied with simple scatter plots you might want to add the frequencies of the data points at each value of the discrete variable. How to do this then just depends on the statistical program you are using. Here is an example for Stata.
You can also apply this to the scatter plot of two categorical variables. Otherwise a box plot or overlaid bar charts may be fine but this really depends on how you want to present these variables.
|
What is the best way to visualize relationship between discrete and continuous variables?
|
If you are not satisfied with simple scatter plots you might want to add the frequencies of the data points at each value of the discrete variable. How to do this then just depends on the statistical
|
What is the best way to visualize relationship between discrete and continuous variables?
If you are not satisfied with simple scatter plots you might want to add the frequencies of the data points at each value of the discrete variable. How to do this then just depends on the statistical program you are using. Here is an example for Stata.
You can also apply this to the scatter plot of two categorical variables. Otherwise a box plot or overlaid bar charts may be fine but this really depends on how you want to present these variables.
|
What is the best way to visualize relationship between discrete and continuous variables?
If you are not satisfied with simple scatter plots you might want to add the frequencies of the data points at each value of the discrete variable. How to do this then just depends on the statistical
|
10,230
|
What is the best way to visualize relationship between discrete and continuous variables?
|
I found a paper applicable on association between two binary variables on http://www.boekboek.com/xb130929113026 - here, in that article it is shown and proved that the strenght of association between two binary variables can be expressed as a fraction of perfect association. So it becomes possible and preferable to state: the association between variable A and variable B is for instance 50% instead of the contemporarily stating: OR = 9 (not easy to interpret) or the realtive risk = 2 (contemporarily the relative risk is considered too to be a measure of association although in fact it is a function of association, prevalence or incidence and positivity).
|
What is the best way to visualize relationship between discrete and continuous variables?
|
I found a paper applicable on association between two binary variables on http://www.boekboek.com/xb130929113026 - here, in that article it is shown and proved that the strenght of association between
|
What is the best way to visualize relationship between discrete and continuous variables?
I found a paper applicable on association between two binary variables on http://www.boekboek.com/xb130929113026 - here, in that article it is shown and proved that the strenght of association between two binary variables can be expressed as a fraction of perfect association. So it becomes possible and preferable to state: the association between variable A and variable B is for instance 50% instead of the contemporarily stating: OR = 9 (not easy to interpret) or the realtive risk = 2 (contemporarily the relative risk is considered too to be a measure of association although in fact it is a function of association, prevalence or incidence and positivity).
|
What is the best way to visualize relationship between discrete and continuous variables?
I found a paper applicable on association between two binary variables on http://www.boekboek.com/xb130929113026 - here, in that article it is shown and proved that the strenght of association between
|
10,231
|
Why is the logistic distribution called "logistic"?
|
The source document for the name "logistic" seems to be this 1844 presentation by P.-F. Verhulst, "Recherches mathématiques sur la loi d'accroissement de la population," in NOUVEAUX MÉMOIRES DE L'ACADÉMIE ROYALE DES SCIENCES ET BELLES-LETTRES DE BRUXELLES, vol. 18, p 3.
He differentiated what we would now call exponential growth of population when resources are essentially unlimited (as seen for example in the growth of the US population in the late 18th and early 19th centuries) from the slower growth when resource limits begin to be reached.
What we call exponential growth, however, he called a "logarithmique" curve (page 6).
He then developed a formula for population growth in the presence of resource limits, and said of the resulting curve:
"Nous donnerons le nom de logistique à la courbe..." which I translate as "We call the curve logistic..." (original emphasis).
That would seem to be intended to distinguish this growth pattern from the "logarithmique" growth in the absence of resource limits, as the figure at the end of the paper illustrates.
The specific form of the equation presented by Verhulst allows for an arbitrary upper asymptote (eq. 5, page 9), while the form we know and love in statistics is the specific case with an asymptote of 1.
|
Why is the logistic distribution called "logistic"?
|
The source document for the name "logistic" seems to be this 1844 presentation by P.-F. Verhulst, "Recherches mathématiques sur la loi d'accroissement de la population," in NOUVEAUX MÉMOIRES DE L'ACAD
|
Why is the logistic distribution called "logistic"?
The source document for the name "logistic" seems to be this 1844 presentation by P.-F. Verhulst, "Recherches mathématiques sur la loi d'accroissement de la population," in NOUVEAUX MÉMOIRES DE L'ACADÉMIE ROYALE DES SCIENCES ET BELLES-LETTRES DE BRUXELLES, vol. 18, p 3.
He differentiated what we would now call exponential growth of population when resources are essentially unlimited (as seen for example in the growth of the US population in the late 18th and early 19th centuries) from the slower growth when resource limits begin to be reached.
What we call exponential growth, however, he called a "logarithmique" curve (page 6).
He then developed a formula for population growth in the presence of resource limits, and said of the resulting curve:
"Nous donnerons le nom de logistique à la courbe..." which I translate as "We call the curve logistic..." (original emphasis).
That would seem to be intended to distinguish this growth pattern from the "logarithmique" growth in the absence of resource limits, as the figure at the end of the paper illustrates.
The specific form of the equation presented by Verhulst allows for an arbitrary upper asymptote (eq. 5, page 9), while the form we know and love in statistics is the specific case with an asymptote of 1.
|
Why is the logistic distribution called "logistic"?
The source document for the name "logistic" seems to be this 1844 presentation by P.-F. Verhulst, "Recherches mathématiques sur la loi d'accroissement de la population," in NOUVEAUX MÉMOIRES DE L'ACAD
|
10,232
|
Why is the logistic distribution called "logistic"?
|
(Cross-posted from History of Science and Mathematics: source of “logistic growth”?)
As Ed states, the term logistic is due to the Belgian mathematician Pierre François Verhulst, who invented the logistic growth model, and named it logistic (French: logistique) in his 1845 "Recherches mathématiques sur la loi d'accroissement de la population", p. 8:
Nous donnerons le nom de logistique à la courbe
We will give the name logistic to the curve
He does not explain why he uses this term, but it is presumably by analogy with arithmetic, geometric, and in contrast to logarithmic (per text and illustration that Ed includes).
The French term logistique is from Ancient Greek λογιστικός (logistikós, “practiced in arithmetic; rational”), from λογίζομαι (logízomai, “I reason, I calculate”), from λόγος (lógos, “reason, computation”), whence English logos, logic, logarithm, etc. In Ancient Greek mathematics, logistikós was a division of mathematics: practical computation and accounting, in contrast to ἀριθμητική (arithmētikḗ), the theoretical or philosophical study of numbers. Confusingly, today we call practical computation arithmetic, and don't use logistic to refer to computation.
Verhulst first discusses the arithmetic growth and geometric growth models, referring to arithmetic progression and geometric progression, and calling the geometric growth curve a logarithmic curve (confusingly, the modern term is instead exponential curve, which is the inverse), then follows with his new model of "logistic" growth, which is presumably named by analogy, after a traditional division of mathematics, and in contrast to the logarithmic curve. The term logarithm is itself derived as log-arithm, from Ancient Greek λόγος (lógos) and ἀριθμός (arithmós), the sources respectively of logistic and arithmetic.
There is no connection with logis (lodging), though that is the source of the term logistics (1830).
|
Why is the logistic distribution called "logistic"?
|
(Cross-posted from History of Science and Mathematics: source of “logistic growth”?)
As Ed states, the term logistic is due to the Belgian mathematician Pierre François Verhulst, who invented the logi
|
Why is the logistic distribution called "logistic"?
(Cross-posted from History of Science and Mathematics: source of “logistic growth”?)
As Ed states, the term logistic is due to the Belgian mathematician Pierre François Verhulst, who invented the logistic growth model, and named it logistic (French: logistique) in his 1845 "Recherches mathématiques sur la loi d'accroissement de la population", p. 8:
Nous donnerons le nom de logistique à la courbe
We will give the name logistic to the curve
He does not explain why he uses this term, but it is presumably by analogy with arithmetic, geometric, and in contrast to logarithmic (per text and illustration that Ed includes).
The French term logistique is from Ancient Greek λογιστικός (logistikós, “practiced in arithmetic; rational”), from λογίζομαι (logízomai, “I reason, I calculate”), from λόγος (lógos, “reason, computation”), whence English logos, logic, logarithm, etc. In Ancient Greek mathematics, logistikós was a division of mathematics: practical computation and accounting, in contrast to ἀριθμητική (arithmētikḗ), the theoretical or philosophical study of numbers. Confusingly, today we call practical computation arithmetic, and don't use logistic to refer to computation.
Verhulst first discusses the arithmetic growth and geometric growth models, referring to arithmetic progression and geometric progression, and calling the geometric growth curve a logarithmic curve (confusingly, the modern term is instead exponential curve, which is the inverse), then follows with his new model of "logistic" growth, which is presumably named by analogy, after a traditional division of mathematics, and in contrast to the logarithmic curve. The term logarithm is itself derived as log-arithm, from Ancient Greek λόγος (lógos) and ἀριθμός (arithmós), the sources respectively of logistic and arithmetic.
There is no connection with logis (lodging), though that is the source of the term logistics (1830).
|
Why is the logistic distribution called "logistic"?
(Cross-posted from History of Science and Mathematics: source of “logistic growth”?)
As Ed states, the term logistic is due to the Belgian mathematician Pierre François Verhulst, who invented the logi
|
10,233
|
Why is the logistic distribution called "logistic"?
|
The logistic distribution is not a common distribution in analysis, but it ties together the notion of a latent underlying continuous variable which is thresholded in binary outcomes. It turns out that thresholding a logistic RV (to 1 if the RV is greater than some unknown value and 0 otherwise) and calculating a maximum likelihood leads to logistic regression. Contrast this approach with thresholding a normally distributed random variable which leads to probit regression. Applying multiple thresholds leads to cumulative link models.
Now, if your question concerned logistic regression, the term was coined by David Cox in 1958 "The regression analysis of binary sequences (with discussion)" in JRRS. He used the term to the logistic, sigmoidal shape of the modeled mean. For describing the process of a curve which models probabilities that accumulate according to a probabilistically sound way, the term "logistic" is an intuitive choice and the nomenclature stuck.
|
Why is the logistic distribution called "logistic"?
|
The logistic distribution is not a common distribution in analysis, but it ties together the notion of a latent underlying continuous variable which is thresholded in binary outcomes. It turns out tha
|
Why is the logistic distribution called "logistic"?
The logistic distribution is not a common distribution in analysis, but it ties together the notion of a latent underlying continuous variable which is thresholded in binary outcomes. It turns out that thresholding a logistic RV (to 1 if the RV is greater than some unknown value and 0 otherwise) and calculating a maximum likelihood leads to logistic regression. Contrast this approach with thresholding a normally distributed random variable which leads to probit regression. Applying multiple thresholds leads to cumulative link models.
Now, if your question concerned logistic regression, the term was coined by David Cox in 1958 "The regression analysis of binary sequences (with discussion)" in JRRS. He used the term to the logistic, sigmoidal shape of the modeled mean. For describing the process of a curve which models probabilities that accumulate according to a probabilistically sound way, the term "logistic" is an intuitive choice and the nomenclature stuck.
|
Why is the logistic distribution called "logistic"?
The logistic distribution is not a common distribution in analysis, but it ties together the notion of a latent underlying continuous variable which is thresholded in binary outcomes. It turns out tha
|
10,234
|
How to compute the standard errors of a logistic regression's coefficients
|
Does your software give you a parameter covariance (or variance-covariance) matrix? If so, the standard errors are the square root of the diagonal of that matrix. You probably want to consult a textbook (or google for university lecture notes) for how to get the $V_\beta$ matrix for linear and generalized linear models.
|
How to compute the standard errors of a logistic regression's coefficients
|
Does your software give you a parameter covariance (or variance-covariance) matrix? If so, the standard errors are the square root of the diagonal of that matrix. You probably want to consult a text
|
How to compute the standard errors of a logistic regression's coefficients
Does your software give you a parameter covariance (or variance-covariance) matrix? If so, the standard errors are the square root of the diagonal of that matrix. You probably want to consult a textbook (or google for university lecture notes) for how to get the $V_\beta$ matrix for linear and generalized linear models.
|
How to compute the standard errors of a logistic regression's coefficients
Does your software give you a parameter covariance (or variance-covariance) matrix? If so, the standard errors are the square root of the diagonal of that matrix. You probably want to consult a text
|
10,235
|
How to compute the standard errors of a logistic regression's coefficients
|
The standard errors of the model coefficients are the square roots of the diagonal entries of the covariance matrix. Consider the following:
Design matrix:
$\textbf{X = }\begin{bmatrix} 1 & x_{1,1} & \ldots & x_{1,p} \\ 1 & x_{2,1} & \ldots & x_{2,p} \\ \vdots & \vdots & \ddots & \vdots \\ 1 & x_{n,1} & \ldots & x_{n,p}
\end{bmatrix}$
, where $x_{i,j}$ is the value of the $j$th predictor for the $i$th observations.
(NOTE: This assumes a model with an intercept.)
$\textbf{V = } \begin{bmatrix} \hat{\pi}_{1}(1 - \hat{\pi}_{1}) & 0 & \ldots & 0 \\ 0 & \hat{\pi}_{2}(1 - \hat{\pi}_{2}) & \ldots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \ldots & \hat{\pi}_{n}(1 - \hat{\pi}_{n}) \end{bmatrix}$
, where $\hat{\pi}_{i}$ represents the predicted probability of class membership for observation $i$.
The covariance matrix can be written as:
$\textbf{(X}^{T}\textbf{V}\textbf{X)}^{-1}$
This can be implemented with the following code:
import numpy as np
from sklearn import linear_model
# Initiate logistic regression object
logit = linear_model.LogisticRegression()
# Fit model. Let X_train = matrix of predictors, y_train = matrix of variable.
# NOTE: Do not include a column for the intercept when fitting the model.
resLogit = logit.fit(X_train, y_train)
# Calculate matrix of predicted class probabilities.
# Check resLogit.classes_ to make sure that sklearn ordered your classes as expected
predProbs = resLogit.predict_proba(X_train)
# Design matrix -- add column of 1's at the beginning of your X_train matrix
X_design = np.hstack([np.ones((X_train.shape[0], 1)), X_train])
# Initiate matrix of 0's, fill diagonal with each predicted observation's variance
V = np.diagflat(np.product(predProbs, axis=1))
# Covariance matrix
# Note that the @-operater does matrix multiplication in Python 3.5+, so if you're running
# Python 3.5+, you can replace the covLogit-line below with the more readable:
# covLogit = np.linalg.inv(X_design.T @ V @ X_design)
covLogit = np.linalg.inv(np.dot(np.dot(X_design.T, V), X_design))
print("Covariance matrix: ", covLogit)
# Standard errors
print("Standard errors: ", np.sqrt(np.diag(covLogit)))
# Wald statistic (coefficient / s.e.) ^ 2
logitParams = np.insert(resLogit.coef_, 0, resLogit.intercept_)
print("Wald statistics: ", (logitParams / np.sqrt(np.diag(covLogit))) ** 2)
All that being said, statsmodels will probably be a better package to use if you want access to a LOT of "out-the-box" diagnostics.
|
How to compute the standard errors of a logistic regression's coefficients
|
The standard errors of the model coefficients are the square roots of the diagonal entries of the covariance matrix. Consider the following:
Design matrix:
$\textbf{X = }\begin{bmatrix} 1 & x_{1,1}
|
How to compute the standard errors of a logistic regression's coefficients
The standard errors of the model coefficients are the square roots of the diagonal entries of the covariance matrix. Consider the following:
Design matrix:
$\textbf{X = }\begin{bmatrix} 1 & x_{1,1} & \ldots & x_{1,p} \\ 1 & x_{2,1} & \ldots & x_{2,p} \\ \vdots & \vdots & \ddots & \vdots \\ 1 & x_{n,1} & \ldots & x_{n,p}
\end{bmatrix}$
, where $x_{i,j}$ is the value of the $j$th predictor for the $i$th observations.
(NOTE: This assumes a model with an intercept.)
$\textbf{V = } \begin{bmatrix} \hat{\pi}_{1}(1 - \hat{\pi}_{1}) & 0 & \ldots & 0 \\ 0 & \hat{\pi}_{2}(1 - \hat{\pi}_{2}) & \ldots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \ldots & \hat{\pi}_{n}(1 - \hat{\pi}_{n}) \end{bmatrix}$
, where $\hat{\pi}_{i}$ represents the predicted probability of class membership for observation $i$.
The covariance matrix can be written as:
$\textbf{(X}^{T}\textbf{V}\textbf{X)}^{-1}$
This can be implemented with the following code:
import numpy as np
from sklearn import linear_model
# Initiate logistic regression object
logit = linear_model.LogisticRegression()
# Fit model. Let X_train = matrix of predictors, y_train = matrix of variable.
# NOTE: Do not include a column for the intercept when fitting the model.
resLogit = logit.fit(X_train, y_train)
# Calculate matrix of predicted class probabilities.
# Check resLogit.classes_ to make sure that sklearn ordered your classes as expected
predProbs = resLogit.predict_proba(X_train)
# Design matrix -- add column of 1's at the beginning of your X_train matrix
X_design = np.hstack([np.ones((X_train.shape[0], 1)), X_train])
# Initiate matrix of 0's, fill diagonal with each predicted observation's variance
V = np.diagflat(np.product(predProbs, axis=1))
# Covariance matrix
# Note that the @-operater does matrix multiplication in Python 3.5+, so if you're running
# Python 3.5+, you can replace the covLogit-line below with the more readable:
# covLogit = np.linalg.inv(X_design.T @ V @ X_design)
covLogit = np.linalg.inv(np.dot(np.dot(X_design.T, V), X_design))
print("Covariance matrix: ", covLogit)
# Standard errors
print("Standard errors: ", np.sqrt(np.diag(covLogit)))
# Wald statistic (coefficient / s.e.) ^ 2
logitParams = np.insert(resLogit.coef_, 0, resLogit.intercept_)
print("Wald statistics: ", (logitParams / np.sqrt(np.diag(covLogit))) ** 2)
All that being said, statsmodels will probably be a better package to use if you want access to a LOT of "out-the-box" diagnostics.
|
How to compute the standard errors of a logistic regression's coefficients
The standard errors of the model coefficients are the square roots of the diagonal entries of the covariance matrix. Consider the following:
Design matrix:
$\textbf{X = }\begin{bmatrix} 1 & x_{1,1}
|
10,236
|
How to compute the standard errors of a logistic regression's coefficients
|
If you're interested in doing inference, then you'll probably want to have a look at statsmodels. Standard errors and common statistical tests are available. Here's a logistic regression example.
|
How to compute the standard errors of a logistic regression's coefficients
|
If you're interested in doing inference, then you'll probably want to have a look at statsmodels. Standard errors and common statistical tests are available. Here's a logistic regression example.
|
How to compute the standard errors of a logistic regression's coefficients
If you're interested in doing inference, then you'll probably want to have a look at statsmodels. Standard errors and common statistical tests are available. Here's a logistic regression example.
|
How to compute the standard errors of a logistic regression's coefficients
If you're interested in doing inference, then you'll probably want to have a look at statsmodels. Standard errors and common statistical tests are available. Here's a logistic regression example.
|
10,237
|
How to compute the standard errors of a logistic regression's coefficients
|
Building upon the fantastic work of @j_sack I have two impulses to build on his code:
Since predict_proba is giving you the probability for n-classes, the result is an nD-array and that is why one should(?) specify the class of interest, e.g.:
predProbs[:,0]
(check class of interest with resLogit.classes_)
The diagonal matrix should not include the raw-predicted-probability but $w_{ii}=\pi_i(1-\pi_i) $ e.g:
V = np.diagflat(np.product(predProbs[:,0] * (1-predProbs[:,0]), axis=1))
|
How to compute the standard errors of a logistic regression's coefficients
|
Building upon the fantastic work of @j_sack I have two impulses to build on his code:
Since predict_proba is giving you the probability for n-classes, the result is an nD-array and that is why one sh
|
How to compute the standard errors of a logistic regression's coefficients
Building upon the fantastic work of @j_sack I have two impulses to build on his code:
Since predict_proba is giving you the probability for n-classes, the result is an nD-array and that is why one should(?) specify the class of interest, e.g.:
predProbs[:,0]
(check class of interest with resLogit.classes_)
The diagonal matrix should not include the raw-predicted-probability but $w_{ii}=\pi_i(1-\pi_i) $ e.g:
V = np.diagflat(np.product(predProbs[:,0] * (1-predProbs[:,0]), axis=1))
|
How to compute the standard errors of a logistic regression's coefficients
Building upon the fantastic work of @j_sack I have two impulses to build on his code:
Since predict_proba is giving you the probability for n-classes, the result is an nD-array and that is why one sh
|
10,238
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
|
First a general comment: Note that the Anderson-Darling test is for completely specified distributions, while the Shapiro-Wilk is for normals with any mean and variance. However, as noted in D'Agostino & Stephens$^{[1]}$ the Anderson-Darling adapts in a very convenient way to the estimation case, akin to (but converges faster and is modified in a way that's simpler to deal with than) the Lilliefors test for the Kolmogorov-Smirnov case. Specifically, at the normal, by $n=5$, tables of the asymptotic value of $A^*=A^2\left(1+\frac{4}{n}-\frac{25}{n^2}\right)$ may be used (don't be testing goodness of fit for n<5).
I have read somewhere in the literature that the Shapiro–Wilk test is considered to be the best normality test because for a given significance level, α, the probability of rejecting the null hypothesis if it's false is higher than in the case of the other normality tests.
As a general statement this is false.
Which normality tests are "better" depends on which classes of alternatives you're interested in. One reason the Shapiro-Wilk is popular is that it tends to have very good power under a broad range of useful alternatives. It comes up in many studies of power, and usually performs very well, but it's not universally best.
It's quite easy to find alternatives under which it's less powerful.
For example, against light tailed alternatives it often has less power than the studentized range $u=\frac{\max(x)−\min(x)}{sd(x)}$ (compare them on a test of normality on uniform data, for example - at $n=30$, a test based on $u$ has power of about 63% compared to a bit over 38% for the Shapiro Wilk).
The Anderson-Darling (adjusted for parameter estimation) does better at the double exponential. Moment-skewness does better against some skew alternatives.
Could you please explain to me, using mathematical arguments if possible, how exactly it works compared to some of the other normality tests (say the Anderson–Darling test)?
I will explain in general terms (if you want more specific details the original papers and some of the later papers that discuss them would be your best bet):
Consider a simpler but closely related test, the Shapiro-Francia; it's effectively a function of the correlation between the order statistics and the expected order statistics under normality (and as such, a pretty direct measure of "how straight the line is" in the normal Q-Q plot). As I recall, the Shapiro-Wilk is more powerful because it also takes into account the covariances between the order statistics, producing a best linear estimator of $\sigma$ from the Q-Q plot, which is then scaled by $s$. When the distribution is far from normal, the ratio isn't close to 1.
By comparison the Anderson-Darling, like the Kolmogorov-Smirnov and the Cramér-von Mises, is based on the empirical CDF. Specifically, it's based on weighted deviations between ECDF and theoretical ECDF (the weighting-for-variance makes it more sensitive to deviations in the tail).
The test by Shapiro and Chen$^{[2]}$ (1995) (based on spacings between order statistics) often exhibits slightly more power than the Shapiro-Wilk (but not always); they often perform very similarly.
--
Use the Shapiro Wilk because it's often powerful, widely available and many people are familiar with it (removing the need to explain in detail what it is if you use it in a paper) -- just don't use it under the illusion that it's "the best normality test". There isn't one best normality test.
[1]: D’Agostino, R. B. and Stephens, M. A. (1986)
Goodness of Fit Techniques,
Marcel Dekker, New York.
[2]: Chen, L. and Shapiro, S. (1995)
"An Alternative test for normality based on normalized spacings."
Journal of Statistical Computation and Simulation 53, 269-287.
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
|
First a general comment: Note that the Anderson-Darling test is for completely specified distributions, while the Shapiro-Wilk is for normals with any mean and variance. However, as noted in D'Agostin
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
First a general comment: Note that the Anderson-Darling test is for completely specified distributions, while the Shapiro-Wilk is for normals with any mean and variance. However, as noted in D'Agostino & Stephens$^{[1]}$ the Anderson-Darling adapts in a very convenient way to the estimation case, akin to (but converges faster and is modified in a way that's simpler to deal with than) the Lilliefors test for the Kolmogorov-Smirnov case. Specifically, at the normal, by $n=5$, tables of the asymptotic value of $A^*=A^2\left(1+\frac{4}{n}-\frac{25}{n^2}\right)$ may be used (don't be testing goodness of fit for n<5).
I have read somewhere in the literature that the Shapiro–Wilk test is considered to be the best normality test because for a given significance level, α, the probability of rejecting the null hypothesis if it's false is higher than in the case of the other normality tests.
As a general statement this is false.
Which normality tests are "better" depends on which classes of alternatives you're interested in. One reason the Shapiro-Wilk is popular is that it tends to have very good power under a broad range of useful alternatives. It comes up in many studies of power, and usually performs very well, but it's not universally best.
It's quite easy to find alternatives under which it's less powerful.
For example, against light tailed alternatives it often has less power than the studentized range $u=\frac{\max(x)−\min(x)}{sd(x)}$ (compare them on a test of normality on uniform data, for example - at $n=30$, a test based on $u$ has power of about 63% compared to a bit over 38% for the Shapiro Wilk).
The Anderson-Darling (adjusted for parameter estimation) does better at the double exponential. Moment-skewness does better against some skew alternatives.
Could you please explain to me, using mathematical arguments if possible, how exactly it works compared to some of the other normality tests (say the Anderson–Darling test)?
I will explain in general terms (if you want more specific details the original papers and some of the later papers that discuss them would be your best bet):
Consider a simpler but closely related test, the Shapiro-Francia; it's effectively a function of the correlation between the order statistics and the expected order statistics under normality (and as such, a pretty direct measure of "how straight the line is" in the normal Q-Q plot). As I recall, the Shapiro-Wilk is more powerful because it also takes into account the covariances between the order statistics, producing a best linear estimator of $\sigma$ from the Q-Q plot, which is then scaled by $s$. When the distribution is far from normal, the ratio isn't close to 1.
By comparison the Anderson-Darling, like the Kolmogorov-Smirnov and the Cramér-von Mises, is based on the empirical CDF. Specifically, it's based on weighted deviations between ECDF and theoretical ECDF (the weighting-for-variance makes it more sensitive to deviations in the tail).
The test by Shapiro and Chen$^{[2]}$ (1995) (based on spacings between order statistics) often exhibits slightly more power than the Shapiro-Wilk (but not always); they often perform very similarly.
--
Use the Shapiro Wilk because it's often powerful, widely available and many people are familiar with it (removing the need to explain in detail what it is if you use it in a paper) -- just don't use it under the illusion that it's "the best normality test". There isn't one best normality test.
[1]: D’Agostino, R. B. and Stephens, M. A. (1986)
Goodness of Fit Techniques,
Marcel Dekker, New York.
[2]: Chen, L. and Shapiro, S. (1995)
"An Alternative test for normality based on normalized spacings."
Journal of Statistical Computation and Simulation 53, 269-287.
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
First a general comment: Note that the Anderson-Darling test is for completely specified distributions, while the Shapiro-Wilk is for normals with any mean and variance. However, as noted in D'Agostin
|
10,239
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
|
Clearly the comparison that you read did not include SnowsPenultimateNormalityTest (http://cran.r-project.org/web/packages/TeachingDemos/TeachingDemos.pdf) since it has the highest possible power across all alternatives. So it should be considered "Best" if power is the only consideration (Note that my opinions are clearly biased, but documented in the link/documentation).
However, I agree with Nick Cox's comment that the best test is a plot rather than a formal test since the question of "Normal enough" is much more important than "Exactly normal". If you want a meaningful test then I would suggest combining the qq plot with the methodology in this paper:
Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F
and Wickham, H. (2009) Statistical Inference for exploratory data
analysis and model diagnostics Phil. Trans. R. Soc. A 2009 367,
4361-4383 doi: 10.1098/rsta.2009.0120
One implementation of that is the vis.test function in the TeachingDemos package for R (same package as SnowsPenultimateNormalityTest).
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
|
Clearly the comparison that you read did not include SnowsPenultimateNormalityTest (http://cran.r-project.org/web/packages/TeachingDemos/TeachingDemos.pdf) since it has the highest possible power acr
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
Clearly the comparison that you read did not include SnowsPenultimateNormalityTest (http://cran.r-project.org/web/packages/TeachingDemos/TeachingDemos.pdf) since it has the highest possible power across all alternatives. So it should be considered "Best" if power is the only consideration (Note that my opinions are clearly biased, but documented in the link/documentation).
However, I agree with Nick Cox's comment that the best test is a plot rather than a formal test since the question of "Normal enough" is much more important than "Exactly normal". If you want a meaningful test then I would suggest combining the qq plot with the methodology in this paper:
Buja, A., Cook, D. Hofmann, H., Lawrence, M. Lee, E.-K., Swayne, D.F
and Wickham, H. (2009) Statistical Inference for exploratory data
analysis and model diagnostics Phil. Trans. R. Soc. A 2009 367,
4361-4383 doi: 10.1098/rsta.2009.0120
One implementation of that is the vis.test function in the TeachingDemos package for R (same package as SnowsPenultimateNormalityTest).
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
Clearly the comparison that you read did not include SnowsPenultimateNormalityTest (http://cran.r-project.org/web/packages/TeachingDemos/TeachingDemos.pdf) since it has the highest possible power acr
|
10,240
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
|
A more serious answer to further this question and especially @silverfish's continued interest. One approach to answering questions like this is to run some simulations to compare. Below is some R code that simulates data under various alternatives and does several of the normality tests and compares the power (and a confidence interval on the power since power is estimated via simulation). I tweaked the sample sizes somewhat because it was not interesting when many of the powers were close to 100% or 5%, I found round numbers that gave powers near 80%. Anyone interested could easily take this code and modify it for different assumptions, different alternatives, etc.
You can see that there are alternatives for which some of the tests do better and others where they do worse. The important question is then which alternatives are most realistic for your scientific questions/area. This really should be followed up with a simulation of the effect of the types of non-normality of interest on other tests being done. Some of these types of non-normality greatly affect other normal based tests, others don't affect them much.
> library(nortest)
>
> simfun1 <- function(fun=function(n) rnorm(n), n=250) {
+ x <- fun(n)
+ c(sw=shapiro.test(x)$p.value, sf=sf.test(x)$p.value, ad=ad.test(x)$p.value,
+ cvm=cvm.test(x)$p.value, lillie=lillie.test(x)$p.value,
+ pearson=pearson.test(x)$p.value, snow=0)
+ }
>
> ### Test size using null hypothesis near true
>
> out1 <- replicate(10000, simfun1())
> apply(out1, 1, function(x) mean(x<=0.05))
sw sf ad cvm lillie pearson snow
0.0490 0.0520 0.0521 0.0509 0.0531 0.0538 1.0000
> apply(out1, 1, function(x) prop.test(sum(x<=0.05),length(x))$conf.int) #$
sw sf ad cvm lillie pearson snow
[1,] 0.04489158 0.04776981 0.04786582 0.04671398 0.04882619 0.04949870 0.9995213
[2,] 0.05345887 0.05657820 0.05668211 0.05543493 0.05772093 0.05844785 1.0000000
>
> ### Test again with mean and sd different
>
> out2 <- replicate(10000, simfun1(fun=function(n) rnorm(n,100,5)))
> apply(out2, 1, function(x) mean(x<=0.05))
sw sf ad cvm lillie pearson snow
0.0482 0.0513 0.0461 0.0477 0.0515 0.0506 1.0000
> apply(out2, 1, function(x) prop.test(sum(x<=0.05),length(x))$conf.int) #$
sw sf ad cvm lillie pearson snow
[1,] 0.04412478 0.04709785 0.04211345 0.04364569 0.04728982 0.04642612 0.9995213
[2,] 0.05262633 0.05585073 0.05043938 0.05210583 0.05605860 0.05512303 1.0000000
>
> #### now for the power under different forms of non-normality
>
> ## heavy tails, t(3)
> rt3 <- function(n) rt(n, df=3)
>
> out3 <- replicate(10000, simfun1(fun=rt3, n=75))
There were 50 or more warnings (use warnings() to see the first 50)
> round(apply(out3, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.788 0.831 0.756 0.726 0.624 0.440 1.000
> round(apply(out3, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.780 0.824 0.748 0.717 0.614 0.431 1
[2,] 0.796 0.838 0.765 0.734 0.633 0.450 1
>
>
> ## light tails, uniform
> u <- function(n) runif(n)
>
> out4 <- replicate(10000, simfun1(fun=u, n=65))
> round(apply(out4, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.906 0.712 0.745 0.591 0.362 0.270 1.000
> round(apply(out4, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.900 0.703 0.737 0.581 0.353 0.261 1
[2,] 0.911 0.720 0.754 0.600 0.372 0.279 1
>
> ## double exponential, Laplace
> de <- function(n) sample(c(-1,1), n, replace=TRUE) * rexp(n)
>
> out5 <- replicate(10000, simfun1(fun=de, n=100))
> round(apply(out5, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.796 0.844 0.824 0.820 0.706 0.477 1.000
> round(apply(out5, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.788 0.837 0.817 0.813 0.697 0.467 1
[2,] 0.804 0.851 0.832 0.828 0.715 0.486 1
>
> ## skewed, gamma(2,2)
> g22 <- function(n) rgamma(n,2,2)
>
> out6 <- replicate(10000, simfun1(fun=g22, n=50))
Warning message:
In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
> round(apply(out6, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.954 0.930 0.893 0.835 0.695 0.656 1.000
> round(apply(out6, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.950 0.925 0.886 0.827 0.686 0.646 1
[2,] 0.958 0.935 0.899 0.842 0.704 0.665 1
>
> ## skewed, gamma(2,2)
> g99 <- function(n) rgamma(n,9,9)
>
> out7 <- replicate(10000, simfun1(fun=g99, n=150))
> round(apply(out7, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.844 0.818 0.724 0.651 0.526 0.286 1.000
> round(apply(out7, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.836 0.810 0.715 0.642 0.516 0.277 1
[2,] 0.851 0.826 0.732 0.660 0.536 0.294 1
>
> ## tails normal, middle not
> mid <- function(n) {
+ x <- rnorm(n)
+ x[ x > -0.5 & x < 0.5 ] <- 0
+ x
+ }
>
> out9 <- replicate(10000, simfun1(fun=mid, n=30))
Warning messages:
1: In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
2: In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
> round(apply(out9, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.374 0.371 0.624 0.739 0.884 0.948 1.000
> round(apply(out9, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.365 0.362 0.614 0.730 0.878 0.943 1
[2,] 0.384 0.381 0.633 0.747 0.890 0.952 1
>
> ## mixture on variance
> mv <- function(n, p=0.1, sd=3) {
+ rnorm(n,0, ifelse(runif(n)<p, sd, 1))
+ }
>
> out10 <- replicate(10000, simfun1(fun=mv, n=100))
Warning message:
In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
> round(apply(out10, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.800 0.844 0.682 0.609 0.487 0.287 1.000
> round(apply(out10, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.792 0.837 0.673 0.599 0.477 0.278 1
[2,] 0.808 0.851 0.691 0.619 0.497 0.296 1
>
> ## mixture on mean
> mm <- function(n, p=0.3, mu=2) {
+ rnorm(n, ifelse(runif(n)<p, mu, 0), 1)
+ }
>
> out11 <- replicate(10000, simfun1(fun=mm, n=400))
> round(apply(out11, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.776 0.710 0.808 0.788 0.669 0.354 1.000
> round(apply(out11, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.768 0.701 0.801 0.780 0.659 0.344 1
[2,] 0.784 0.719 0.816 0.796 0.678 0.363 1
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
|
A more serious answer to further this question and especially @silverfish's continued interest. One approach to answering questions like this is to run some simulations to compare. Below is some R c
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
A more serious answer to further this question and especially @silverfish's continued interest. One approach to answering questions like this is to run some simulations to compare. Below is some R code that simulates data under various alternatives and does several of the normality tests and compares the power (and a confidence interval on the power since power is estimated via simulation). I tweaked the sample sizes somewhat because it was not interesting when many of the powers were close to 100% or 5%, I found round numbers that gave powers near 80%. Anyone interested could easily take this code and modify it for different assumptions, different alternatives, etc.
You can see that there are alternatives for which some of the tests do better and others where they do worse. The important question is then which alternatives are most realistic for your scientific questions/area. This really should be followed up with a simulation of the effect of the types of non-normality of interest on other tests being done. Some of these types of non-normality greatly affect other normal based tests, others don't affect them much.
> library(nortest)
>
> simfun1 <- function(fun=function(n) rnorm(n), n=250) {
+ x <- fun(n)
+ c(sw=shapiro.test(x)$p.value, sf=sf.test(x)$p.value, ad=ad.test(x)$p.value,
+ cvm=cvm.test(x)$p.value, lillie=lillie.test(x)$p.value,
+ pearson=pearson.test(x)$p.value, snow=0)
+ }
>
> ### Test size using null hypothesis near true
>
> out1 <- replicate(10000, simfun1())
> apply(out1, 1, function(x) mean(x<=0.05))
sw sf ad cvm lillie pearson snow
0.0490 0.0520 0.0521 0.0509 0.0531 0.0538 1.0000
> apply(out1, 1, function(x) prop.test(sum(x<=0.05),length(x))$conf.int) #$
sw sf ad cvm lillie pearson snow
[1,] 0.04489158 0.04776981 0.04786582 0.04671398 0.04882619 0.04949870 0.9995213
[2,] 0.05345887 0.05657820 0.05668211 0.05543493 0.05772093 0.05844785 1.0000000
>
> ### Test again with mean and sd different
>
> out2 <- replicate(10000, simfun1(fun=function(n) rnorm(n,100,5)))
> apply(out2, 1, function(x) mean(x<=0.05))
sw sf ad cvm lillie pearson snow
0.0482 0.0513 0.0461 0.0477 0.0515 0.0506 1.0000
> apply(out2, 1, function(x) prop.test(sum(x<=0.05),length(x))$conf.int) #$
sw sf ad cvm lillie pearson snow
[1,] 0.04412478 0.04709785 0.04211345 0.04364569 0.04728982 0.04642612 0.9995213
[2,] 0.05262633 0.05585073 0.05043938 0.05210583 0.05605860 0.05512303 1.0000000
>
> #### now for the power under different forms of non-normality
>
> ## heavy tails, t(3)
> rt3 <- function(n) rt(n, df=3)
>
> out3 <- replicate(10000, simfun1(fun=rt3, n=75))
There were 50 or more warnings (use warnings() to see the first 50)
> round(apply(out3, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.788 0.831 0.756 0.726 0.624 0.440 1.000
> round(apply(out3, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.780 0.824 0.748 0.717 0.614 0.431 1
[2,] 0.796 0.838 0.765 0.734 0.633 0.450 1
>
>
> ## light tails, uniform
> u <- function(n) runif(n)
>
> out4 <- replicate(10000, simfun1(fun=u, n=65))
> round(apply(out4, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.906 0.712 0.745 0.591 0.362 0.270 1.000
> round(apply(out4, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.900 0.703 0.737 0.581 0.353 0.261 1
[2,] 0.911 0.720 0.754 0.600 0.372 0.279 1
>
> ## double exponential, Laplace
> de <- function(n) sample(c(-1,1), n, replace=TRUE) * rexp(n)
>
> out5 <- replicate(10000, simfun1(fun=de, n=100))
> round(apply(out5, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.796 0.844 0.824 0.820 0.706 0.477 1.000
> round(apply(out5, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.788 0.837 0.817 0.813 0.697 0.467 1
[2,] 0.804 0.851 0.832 0.828 0.715 0.486 1
>
> ## skewed, gamma(2,2)
> g22 <- function(n) rgamma(n,2,2)
>
> out6 <- replicate(10000, simfun1(fun=g22, n=50))
Warning message:
In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
> round(apply(out6, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.954 0.930 0.893 0.835 0.695 0.656 1.000
> round(apply(out6, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.950 0.925 0.886 0.827 0.686 0.646 1
[2,] 0.958 0.935 0.899 0.842 0.704 0.665 1
>
> ## skewed, gamma(2,2)
> g99 <- function(n) rgamma(n,9,9)
>
> out7 <- replicate(10000, simfun1(fun=g99, n=150))
> round(apply(out7, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.844 0.818 0.724 0.651 0.526 0.286 1.000
> round(apply(out7, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.836 0.810 0.715 0.642 0.516 0.277 1
[2,] 0.851 0.826 0.732 0.660 0.536 0.294 1
>
> ## tails normal, middle not
> mid <- function(n) {
+ x <- rnorm(n)
+ x[ x > -0.5 & x < 0.5 ] <- 0
+ x
+ }
>
> out9 <- replicate(10000, simfun1(fun=mid, n=30))
Warning messages:
1: In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
2: In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
> round(apply(out9, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.374 0.371 0.624 0.739 0.884 0.948 1.000
> round(apply(out9, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.365 0.362 0.614 0.730 0.878 0.943 1
[2,] 0.384 0.381 0.633 0.747 0.890 0.952 1
>
> ## mixture on variance
> mv <- function(n, p=0.1, sd=3) {
+ rnorm(n,0, ifelse(runif(n)<p, sd, 1))
+ }
>
> out10 <- replicate(10000, simfun1(fun=mv, n=100))
Warning message:
In cvm.test(x) :
p-value is smaller than 7.37e-10, cannot be computed more accurately
> round(apply(out10, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.800 0.844 0.682 0.609 0.487 0.287 1.000
> round(apply(out10, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.792 0.837 0.673 0.599 0.477 0.278 1
[2,] 0.808 0.851 0.691 0.619 0.497 0.296 1
>
> ## mixture on mean
> mm <- function(n, p=0.3, mu=2) {
+ rnorm(n, ifelse(runif(n)<p, mu, 0), 1)
+ }
>
> out11 <- replicate(10000, simfun1(fun=mm, n=400))
> round(apply(out11, 1, function(x) mean(x<=0.05, na.rm=TRUE)),3)
sw sf ad cvm lillie pearson snow
0.776 0.710 0.808 0.788 0.669 0.354 1.000
> round(apply(out11, 1, function(x){
+ prop.test(sum(x<=0.05,na.rm=TRUE),sum(!is.na(x)))$conf.int),3) } #$
sw sf ad cvm lillie pearson snow
[1,] 0.768 0.701 0.801 0.780 0.659 0.344 1
[2,] 0.784 0.719 0.816 0.796 0.678 0.363 1
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
A more serious answer to further this question and especially @silverfish's continued interest. One approach to answering questions like this is to run some simulations to compare. Below is some R c
|
10,241
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
|
I'm late to the party, but will answer with references to the published peer-reviewed research. The reason why I don't answer Yes/No to OP's question is that it is more complicated than it may seem. There isn't one test which would be the most powerful for samples coming from any distribution with or without outliers. Outliers may severely diminish power of one test and increase for another. Some test work better when the sample comes from symmetrical distribution etc.
Henry C. Thode, Testing for Normality, 2002 - This is a the most comprehensive book on the subject. If I had to dumb it down to a simple answer, then SW is not more powerful than AD in all cases. Here are two excerpt for your reading pleasure.
From section 7.1.5: On the basis of power, the choice of test is
directly related to the information available or the assumptions made
concerning the alternative. The more specific the alternative, the more specific and more powerful the test will usually be; this will also result in the most reliable recommendations.
and
A joint skewness and kurtosis test such as $K_s^2$ provides high power
against a wide range of alternatives, as does the Anderson-Darling
$A^2$. Wilk-Shapiro W showed relatively high power among skewed and
short-tailed symmetric alternatives when compared to other tests, and
respectable power for long-tailed symmetric alternatives.
Romao, Xavier, Raimundo Delgado, and Anibal Costa. "An empirical power comparison of univariate goodness-of-fit tests for normality." Journal of Statistical Computation and Simulation 80.5 (2010): 545-591. This is the most recent published research on the subject I know of.
The study addresses the performance of 33 normality tests, for various
sample sizes, considering several significance levels and for a number
of symmetric, asymmetric and modified normal distributions. General
recommendations for normality testing resulting from the study are
defined according to the nature of the non-normality
If you really want to boil down their research to yes/no, then the answer is YES. Shapiro-Wilks test seems to be a little bit more powerful in most cases than Anderson-Darling. They recommend Shapiro Wilk test when you don't have a particular alternative distribution in mind. However, if you're interested in this subject, the paper is worth reading. At least look at the tables.
Edith Seier, Normality Tests: Power Comparison, in International Encyclopedia of Statistical Science, 2014 - A survey of published research on the subject. Again, the answer depends on the sample and your knowledge about the alternative distribution, but trivialized answer would be YES, Shapiro-Wilk is usually more powerful, but not always.
Henry C. Thode, Normality Tests, in International Encyclopedia of Statistical Science, 2014 - Description of popular normality tests. His recommendation:
As indicated previously, the number of normality tests is large, too
large for even the majority of them to be mentioned here. Overall the
best tests appear to be the moment tests, Shapiro–Wilk W,
Anderson–Darling $A^2$ (see Anderson-Darling Tests of Goodness-of-Fit),
and the Jarque–Bera test. Specifics on these and many other normality
tests and their characteristics can be found in Thode (2002) and on
general goodness of t issues, including normality tests, in
D’Agostino and Stephens (1986).
Now, this was all about univariate tests. The Thode (2002) also has multivariate test, censored data, normal mixtures, testing in the presence of outliers, and much more.
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
|
I'm late to the party, but will answer with references to the published peer-reviewed research. The reason why I don't answer Yes/No to OP's question is that it is more complicated than it may seem. T
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darling?
I'm late to the party, but will answer with references to the published peer-reviewed research. The reason why I don't answer Yes/No to OP's question is that it is more complicated than it may seem. There isn't one test which would be the most powerful for samples coming from any distribution with or without outliers. Outliers may severely diminish power of one test and increase for another. Some test work better when the sample comes from symmetrical distribution etc.
Henry C. Thode, Testing for Normality, 2002 - This is a the most comprehensive book on the subject. If I had to dumb it down to a simple answer, then SW is not more powerful than AD in all cases. Here are two excerpt for your reading pleasure.
From section 7.1.5: On the basis of power, the choice of test is
directly related to the information available or the assumptions made
concerning the alternative. The more specific the alternative, the more specific and more powerful the test will usually be; this will also result in the most reliable recommendations.
and
A joint skewness and kurtosis test such as $K_s^2$ provides high power
against a wide range of alternatives, as does the Anderson-Darling
$A^2$. Wilk-Shapiro W showed relatively high power among skewed and
short-tailed symmetric alternatives when compared to other tests, and
respectable power for long-tailed symmetric alternatives.
Romao, Xavier, Raimundo Delgado, and Anibal Costa. "An empirical power comparison of univariate goodness-of-fit tests for normality." Journal of Statistical Computation and Simulation 80.5 (2010): 545-591. This is the most recent published research on the subject I know of.
The study addresses the performance of 33 normality tests, for various
sample sizes, considering several significance levels and for a number
of symmetric, asymmetric and modified normal distributions. General
recommendations for normality testing resulting from the study are
defined according to the nature of the non-normality
If you really want to boil down their research to yes/no, then the answer is YES. Shapiro-Wilks test seems to be a little bit more powerful in most cases than Anderson-Darling. They recommend Shapiro Wilk test when you don't have a particular alternative distribution in mind. However, if you're interested in this subject, the paper is worth reading. At least look at the tables.
Edith Seier, Normality Tests: Power Comparison, in International Encyclopedia of Statistical Science, 2014 - A survey of published research on the subject. Again, the answer depends on the sample and your knowledge about the alternative distribution, but trivialized answer would be YES, Shapiro-Wilk is usually more powerful, but not always.
Henry C. Thode, Normality Tests, in International Encyclopedia of Statistical Science, 2014 - Description of popular normality tests. His recommendation:
As indicated previously, the number of normality tests is large, too
large for even the majority of them to be mentioned here. Overall the
best tests appear to be the moment tests, Shapiro–Wilk W,
Anderson–Darling $A^2$ (see Anderson-Darling Tests of Goodness-of-Fit),
and the Jarque–Bera test. Specifics on these and many other normality
tests and their characteristics can be found in Thode (2002) and on
general goodness of t issues, including normality tests, in
D’Agostino and Stephens (1986).
Now, this was all about univariate tests. The Thode (2002) also has multivariate test, censored data, normal mixtures, testing in the presence of outliers, and much more.
|
Is Shapiro–Wilk the best normality test? Why might it be better than other tests like Anderson-Darli
I'm late to the party, but will answer with references to the published peer-reviewed research. The reason why I don't answer Yes/No to OP's question is that it is more complicated than it may seem. T
|
10,242
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
I'm trying to figure out how actual working analysts handle data that doesn't quite meet the assumptions.
It depends on my needs, which assumptions are violated, in what way, how badly, how much that affects the inference, and sometimes on the sample size.
I'm running analysis on grouped data from trees in four groups. I've got data for about 35 attributes for each tree and I'm going through each attribute to determine if the groups differ significantly on that attribute. However, in a couple of cases, the ANOVA assumptions are slightly violated because the variances aren't equal (according to a Levene's test, using alpha=.05).
1) If sample sizes are equal, you don't have much of a problem. ANOVA is quite (level-)robust to different variances if the n's are equal.
2) testing equality of variance before deciding whether to assume it is recommended against by a number of studies. If you're in any real doubt that they'll be close to equal, it's better to simply assume they're unequal.
Some references:
Zimmerman, D.W. (2004),
"A note on preliminary tests of equality of variances."
Br. J. Math. Stat. Psychol., May; 57(Pt 1): 173-81.
http://www.ncbi.nlm.nih.gov/pubmed/15171807
Henrik gives three references here
3) It's the effect size that matters, rather than whether your sample is large enough to tell you they're significantly different. So in large samples, a small difference in variance will show as highly significant by Levene's test, but will be of essentially no consequence in its impact. If the samples are large and the effect size - the ratio of variances or the differences in variances - are quite close to what they should be, then the p-value is of no consequence. (On the other hand, in small samples, a nice big p-value is of little comfort. Either way the test doesn't answer the right question.)
Note that there's a Welch-Satterthwaite type adjustment to the estimate of residual standard error and d.f. in ANOVA, just as there is in two-sample t-tests.
Use a non-parametric test like a Wilcoxon (if so, which one?).
If you're interested in location-shift alternatives, you're still assuming constant spread. If you're interested in much more general alternatives then you might perhaps consider it; the k-sample equivalent to a Wilcoxon test is a Kruskal-Wallis test.
Do some kind of correction to the ANOVA result
See my above suggestion of considering Welch-Satterthwaite, that's a 'kind of correction'.
(Alternatively you might cast your ANOVA as a set of pairwise Welch-type t-tests, in which case you likely would want to look at a Bonferroni or something similar)
I've also read some things that suggest that heteroscedasticity isn't really that big of a problem for ANOVA unless the means and variances are correlated (i.e. they both increase together)
You'd have to cite something like that. Having looked at a number of situations with t-tests, I don't think it's clearly true, so I'd like to see why they think so; perhaps the situation is restricted in some way. It would be nice if it were the case though because pretty often generalized linear models can help with that situation.
Finally, I should add that I'm doing this analysis for publication in a peer-reviewed journal, so whatever approach I settle on has to pass muster with reviewers.
It's very hard to predict what might satisfy your reviewers. Most of us don't work with trees.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
I'm trying to figure out how actual working analysts handle data that doesn't quite meet the assumptions.
It depends on my needs, which assumptions are violated, in what way, how badly, how much tha
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
I'm trying to figure out how actual working analysts handle data that doesn't quite meet the assumptions.
It depends on my needs, which assumptions are violated, in what way, how badly, how much that affects the inference, and sometimes on the sample size.
I'm running analysis on grouped data from trees in four groups. I've got data for about 35 attributes for each tree and I'm going through each attribute to determine if the groups differ significantly on that attribute. However, in a couple of cases, the ANOVA assumptions are slightly violated because the variances aren't equal (according to a Levene's test, using alpha=.05).
1) If sample sizes are equal, you don't have much of a problem. ANOVA is quite (level-)robust to different variances if the n's are equal.
2) testing equality of variance before deciding whether to assume it is recommended against by a number of studies. If you're in any real doubt that they'll be close to equal, it's better to simply assume they're unequal.
Some references:
Zimmerman, D.W. (2004),
"A note on preliminary tests of equality of variances."
Br. J. Math. Stat. Psychol., May; 57(Pt 1): 173-81.
http://www.ncbi.nlm.nih.gov/pubmed/15171807
Henrik gives three references here
3) It's the effect size that matters, rather than whether your sample is large enough to tell you they're significantly different. So in large samples, a small difference in variance will show as highly significant by Levene's test, but will be of essentially no consequence in its impact. If the samples are large and the effect size - the ratio of variances or the differences in variances - are quite close to what they should be, then the p-value is of no consequence. (On the other hand, in small samples, a nice big p-value is of little comfort. Either way the test doesn't answer the right question.)
Note that there's a Welch-Satterthwaite type adjustment to the estimate of residual standard error and d.f. in ANOVA, just as there is in two-sample t-tests.
Use a non-parametric test like a Wilcoxon (if so, which one?).
If you're interested in location-shift alternatives, you're still assuming constant spread. If you're interested in much more general alternatives then you might perhaps consider it; the k-sample equivalent to a Wilcoxon test is a Kruskal-Wallis test.
Do some kind of correction to the ANOVA result
See my above suggestion of considering Welch-Satterthwaite, that's a 'kind of correction'.
(Alternatively you might cast your ANOVA as a set of pairwise Welch-type t-tests, in which case you likely would want to look at a Bonferroni or something similar)
I've also read some things that suggest that heteroscedasticity isn't really that big of a problem for ANOVA unless the means and variances are correlated (i.e. they both increase together)
You'd have to cite something like that. Having looked at a number of situations with t-tests, I don't think it's clearly true, so I'd like to see why they think so; perhaps the situation is restricted in some way. It would be nice if it were the case though because pretty often generalized linear models can help with that situation.
Finally, I should add that I'm doing this analysis for publication in a peer-reviewed journal, so whatever approach I settle on has to pass muster with reviewers.
It's very hard to predict what might satisfy your reviewers. Most of us don't work with trees.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
I'm trying to figure out how actual working analysts handle data that doesn't quite meet the assumptions.
It depends on my needs, which assumptions are violated, in what way, how badly, how much tha
|
10,243
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
It’s actually not very difficult to handle heteroscedasticity in simple linear models (e.g., one- or two-way ANOVA-like models).
Robustness of ANOVA
First, as others have note, the ANOVA is amazingly robust to deviations from the assumption of equal variances, especially if you have approximately balanced data (equal number of observations in each group). Preliminary tests on equal variances, other the other hand, are not (though Levene’s test is much better than the F-test commonly taught in textbooks). As George Box put it:
To make the preliminary test on variances is rather like putting to sea in a rowing boat to find out whether conditions are sufficiently calm for an ocean liner to leave port!
Even though the ANOVA is very robust, as it’s very easy to take heteroscedaticity into account, there’s little reason not to do so.
Non-parametric tests
If you’re really interested in differences in means, the non-parametric tests (e.g., the Kruskal–Wallis test) are really not of any use. They do test differences between groups, but they do not in general test differences in means.
Example data
Let’s generate a simple example of data where one would like to use ANOVA, but where the assumption of equal variances is not true.
set.seed(1232)
pop = data.frame(group=factor(c("A","B","C")),
mean=c(1,2,5),
sd=c(1,3,4))
d = do.call(rbind, rep(list(pop),13))
d$x = rnorm(nrow(d), d$mean, d$sd)
We have three groups, with (clear) differences in both means and variances:
stripchart(x ~ group, data=d)
ANOVA
Not surprisingly, a normal ANOVA handles this quite well:
> mod.aov = aov(x ~ group, data=d)
> summary(mod.aov)
Df Sum Sq Mean Sq F value Pr(>F)
group 2 199.4 99.69 13.01 5.6e-05 ***
Residuals 36 275.9 7.66
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
So, which groups differ? Let’s use Tukey’s HSD method:
> TukeyHSD(mod.aov)
Tukey multiple comparisons of means
95% family-wise confidence level
Fit: aov(formula = x ~ group, data = d)
$group
diff lwr upr p adj
B-A 1.736692 -0.9173128 4.390698 0.2589215
C-A 5.422838 2.7688327 8.076843 0.0000447
C-B 3.686146 1.0321403 6.340151 0.0046867
With a P-value of 0.26, we can’t claim any difference (in means) between group A and B. And even if we didn’t take into account that we did three comparisons, we wouldn’t get a low P-value (P = 0.12):
> summary.lm(mod.aov)
[…]
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.5098 0.7678 0.664 0.511
groupB 1.7367 1.0858 1.599 0.118
groupC 5.4228 1.0858 4.994 0.0000153 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.768 on 36 degrees of freedom
Why is that? Based on the plot, there is a pretty clear difference. The reason is that ANOVA assumes equal variances in each group, and estimates a common standard deviation of 2.77 (shown as ‘Residual standard error’ in the summary.lm table, or you can get it by taking the square root of the residual mean square (7.66) in the ANOVA table).
But group A has a (population) standard deviation of 1, and this overestimate of 2.77 makes it (needlessly) difficult to get statistically significant results, i.e., we have a test with (too) low power.
‘ANOVA’ with unequal variances
So, how to fit a proper model, one that takes into account the differences in variances? It’s easy in R:
> oneway.test(x ~ group, data=d, var.equal=FALSE)
One-way analysis of means (not assuming equal variances)
data: x and group
F = 12.7127, num df = 2.000, denom df = 19.055, p-value = 0.0003107
So, if you want to run a simple one-way ‘ANOVA’ in R without assuming equal variances, use this function. It’s basically an extension of the (Welch) t.test() for two samples with unequal variances.
Unfortunately, it doesn’t work with TukeyHSD() (or most other functions you use on aov objects), so even if we’re pretty sure there are group differences, we don’t know where they are.
Modelling the heteroscedasticity
The best solution is to model the variances explicitly. And it’s very easy in R:
> library(nlme)
> mod.gls = gls(x ~ group, data=d,
weights=varIdent(form= ~ 1 | group))
> anova(mod.gls)
Denom. DF: 36
numDF F-value p-value
(Intercept) 1 16.57316 0.0002
group 2 13.15743 0.0001
Still significant differences, of course. But now the differences between group A and B have also become statically significant (P = 0.025):
> summary(mod.gls)
Generalized least squares fit by REML
Model: x ~ group
[…]
Variance function:
Structure: Different standard
deviations per stratum
Formula: ~1 | group
Parameter estimates:
A B C
1.000000 2.444532 3.913382
Coefficients:
Value Std.Error t-value p-value
(Intercept) 0.509768 0.2816667 1.809829 0.0787
groupB 1.736692 0.7439273 2.334492 0.0253
groupC 5.422838 1.1376880 4.766542 0.0000
[…]
Residual standard error: 1.015564
Degrees of freedom: 39 total; 36 residual
So using an appropriate model helps! Also note that we get estimates of the (relative) standard deviations. The estimated standard deviation for group A can be found at the bottom of the, results, 1.02. The estimated standard deviation of group B is 2.44 times this, or 2.48, and the estimated standard deviation of group C is similarly 3.97 (type intervals(mod.gls) to get confidence intervals for the relative standard deviations of groups B and C).
Correcting for multiple testing
However, we really should correct for multiple testing. This is easy using the ‘multcomp’ library. Unfortunately, it does’t have built-in support for ‘gls’ objects, so we’ll have to add some helper functions first:
model.matrix.gls <- function(object, ...)
model.matrix(terms(object), data = getData(object), ...)
model.frame.gls <- function(object, ...)
model.frame(formula(object), data = getData(object), ...)
terms.gls <- function(object, ...)
terms(model.frame(object),...)
Now let’s get to work:
> library(multcomp)
> mod.gls.mc = glht(mod.gls, linfct = mcp(group = "Tukey"))
> summary(mod.gls.mc)
[…]
Linear Hypotheses:
Estimate Std. Error z value Pr(>|z|)
B - A == 0 1.7367 0.7439 2.334 0.0480 *
C - A == 0 5.4228 1.1377 4.767 <0.001 ***
C - B == 0 3.6861 1.2996 2.836 0.0118 *
Still statistically significant difference between group A and group B! ☺ And we can even get (simultaneous) confidence intervals for the differences between group means:
> confint(mod.gls.mc)
[…]
Linear Hypotheses:
Estimate lwr upr
B - A == 0 1.73669 0.01014 3.46324
C - A == 0 5.42284 2.78242 8.06325
C - B == 0 3.68615 0.66984 6.70245
Using an approximately (here exactly) correct model, we can trust these results!
Note that for this simple example, the data for group C doesn’t really add any information on the differences between group A and B, since we model both separate means and standard deviations for each group. We could have just used pairwise t-tests corrected for multiple comparisons:
> pairwise.t.test(d$x, d$group, pool.sd=FALSE)
Pairwise comparisons using t tests with non-pooled SD
data: d$x and d$group
A B
B 0.03301 -
C 0.00098 0.02032
P value adjustment method: holm
However, for more complicated models, e.g., two-way models, or linear models with many predictors, using GLS (generalised least squares) and explicitly modelling the variance functions is the best solution.
And the variance function need not simply be a different constant in each group; we can impose structure on it. For example, we can model the variance as a power of the mean of each group (and thus only need to estimate one parameter, the exponent), or perhaps as the logarithm of one of the predictors in the model. All this is very easy with GLS (and gls() in R).
Generalised least squares is IMHO a very underused statistical modelling technique. Instead of worrying about deviations from the model assumptions, model those deviations!
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
It’s actually not very difficult to handle heteroscedasticity in simple linear models (e.g., one- or two-way ANOVA-like models).
Robustness of ANOVA
First, as others have note, the ANOVA is amazingly
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
It’s actually not very difficult to handle heteroscedasticity in simple linear models (e.g., one- or two-way ANOVA-like models).
Robustness of ANOVA
First, as others have note, the ANOVA is amazingly robust to deviations from the assumption of equal variances, especially if you have approximately balanced data (equal number of observations in each group). Preliminary tests on equal variances, other the other hand, are not (though Levene’s test is much better than the F-test commonly taught in textbooks). As George Box put it:
To make the preliminary test on variances is rather like putting to sea in a rowing boat to find out whether conditions are sufficiently calm for an ocean liner to leave port!
Even though the ANOVA is very robust, as it’s very easy to take heteroscedaticity into account, there’s little reason not to do so.
Non-parametric tests
If you’re really interested in differences in means, the non-parametric tests (e.g., the Kruskal–Wallis test) are really not of any use. They do test differences between groups, but they do not in general test differences in means.
Example data
Let’s generate a simple example of data where one would like to use ANOVA, but where the assumption of equal variances is not true.
set.seed(1232)
pop = data.frame(group=factor(c("A","B","C")),
mean=c(1,2,5),
sd=c(1,3,4))
d = do.call(rbind, rep(list(pop),13))
d$x = rnorm(nrow(d), d$mean, d$sd)
We have three groups, with (clear) differences in both means and variances:
stripchart(x ~ group, data=d)
ANOVA
Not surprisingly, a normal ANOVA handles this quite well:
> mod.aov = aov(x ~ group, data=d)
> summary(mod.aov)
Df Sum Sq Mean Sq F value Pr(>F)
group 2 199.4 99.69 13.01 5.6e-05 ***
Residuals 36 275.9 7.66
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
So, which groups differ? Let’s use Tukey’s HSD method:
> TukeyHSD(mod.aov)
Tukey multiple comparisons of means
95% family-wise confidence level
Fit: aov(formula = x ~ group, data = d)
$group
diff lwr upr p adj
B-A 1.736692 -0.9173128 4.390698 0.2589215
C-A 5.422838 2.7688327 8.076843 0.0000447
C-B 3.686146 1.0321403 6.340151 0.0046867
With a P-value of 0.26, we can’t claim any difference (in means) between group A and B. And even if we didn’t take into account that we did three comparisons, we wouldn’t get a low P-value (P = 0.12):
> summary.lm(mod.aov)
[…]
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.5098 0.7678 0.664 0.511
groupB 1.7367 1.0858 1.599 0.118
groupC 5.4228 1.0858 4.994 0.0000153 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.768 on 36 degrees of freedom
Why is that? Based on the plot, there is a pretty clear difference. The reason is that ANOVA assumes equal variances in each group, and estimates a common standard deviation of 2.77 (shown as ‘Residual standard error’ in the summary.lm table, or you can get it by taking the square root of the residual mean square (7.66) in the ANOVA table).
But group A has a (population) standard deviation of 1, and this overestimate of 2.77 makes it (needlessly) difficult to get statistically significant results, i.e., we have a test with (too) low power.
‘ANOVA’ with unequal variances
So, how to fit a proper model, one that takes into account the differences in variances? It’s easy in R:
> oneway.test(x ~ group, data=d, var.equal=FALSE)
One-way analysis of means (not assuming equal variances)
data: x and group
F = 12.7127, num df = 2.000, denom df = 19.055, p-value = 0.0003107
So, if you want to run a simple one-way ‘ANOVA’ in R without assuming equal variances, use this function. It’s basically an extension of the (Welch) t.test() for two samples with unequal variances.
Unfortunately, it doesn’t work with TukeyHSD() (or most other functions you use on aov objects), so even if we’re pretty sure there are group differences, we don’t know where they are.
Modelling the heteroscedasticity
The best solution is to model the variances explicitly. And it’s very easy in R:
> library(nlme)
> mod.gls = gls(x ~ group, data=d,
weights=varIdent(form= ~ 1 | group))
> anova(mod.gls)
Denom. DF: 36
numDF F-value p-value
(Intercept) 1 16.57316 0.0002
group 2 13.15743 0.0001
Still significant differences, of course. But now the differences between group A and B have also become statically significant (P = 0.025):
> summary(mod.gls)
Generalized least squares fit by REML
Model: x ~ group
[…]
Variance function:
Structure: Different standard
deviations per stratum
Formula: ~1 | group
Parameter estimates:
A B C
1.000000 2.444532 3.913382
Coefficients:
Value Std.Error t-value p-value
(Intercept) 0.509768 0.2816667 1.809829 0.0787
groupB 1.736692 0.7439273 2.334492 0.0253
groupC 5.422838 1.1376880 4.766542 0.0000
[…]
Residual standard error: 1.015564
Degrees of freedom: 39 total; 36 residual
So using an appropriate model helps! Also note that we get estimates of the (relative) standard deviations. The estimated standard deviation for group A can be found at the bottom of the, results, 1.02. The estimated standard deviation of group B is 2.44 times this, or 2.48, and the estimated standard deviation of group C is similarly 3.97 (type intervals(mod.gls) to get confidence intervals for the relative standard deviations of groups B and C).
Correcting for multiple testing
However, we really should correct for multiple testing. This is easy using the ‘multcomp’ library. Unfortunately, it does’t have built-in support for ‘gls’ objects, so we’ll have to add some helper functions first:
model.matrix.gls <- function(object, ...)
model.matrix(terms(object), data = getData(object), ...)
model.frame.gls <- function(object, ...)
model.frame(formula(object), data = getData(object), ...)
terms.gls <- function(object, ...)
terms(model.frame(object),...)
Now let’s get to work:
> library(multcomp)
> mod.gls.mc = glht(mod.gls, linfct = mcp(group = "Tukey"))
> summary(mod.gls.mc)
[…]
Linear Hypotheses:
Estimate Std. Error z value Pr(>|z|)
B - A == 0 1.7367 0.7439 2.334 0.0480 *
C - A == 0 5.4228 1.1377 4.767 <0.001 ***
C - B == 0 3.6861 1.2996 2.836 0.0118 *
Still statistically significant difference between group A and group B! ☺ And we can even get (simultaneous) confidence intervals for the differences between group means:
> confint(mod.gls.mc)
[…]
Linear Hypotheses:
Estimate lwr upr
B - A == 0 1.73669 0.01014 3.46324
C - A == 0 5.42284 2.78242 8.06325
C - B == 0 3.68615 0.66984 6.70245
Using an approximately (here exactly) correct model, we can trust these results!
Note that for this simple example, the data for group C doesn’t really add any information on the differences between group A and B, since we model both separate means and standard deviations for each group. We could have just used pairwise t-tests corrected for multiple comparisons:
> pairwise.t.test(d$x, d$group, pool.sd=FALSE)
Pairwise comparisons using t tests with non-pooled SD
data: d$x and d$group
A B
B 0.03301 -
C 0.00098 0.02032
P value adjustment method: holm
However, for more complicated models, e.g., two-way models, or linear models with many predictors, using GLS (generalised least squares) and explicitly modelling the variance functions is the best solution.
And the variance function need not simply be a different constant in each group; we can impose structure on it. For example, we can model the variance as a power of the mean of each group (and thus only need to estimate one parameter, the exponent), or perhaps as the logarithm of one of the predictors in the model. All this is very easy with GLS (and gls() in R).
Generalised least squares is IMHO a very underused statistical modelling technique. Instead of worrying about deviations from the model assumptions, model those deviations!
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
It’s actually not very difficult to handle heteroscedasticity in simple linear models (e.g., one- or two-way ANOVA-like models).
Robustness of ANOVA
First, as others have note, the ANOVA is amazingly
|
10,244
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
There may indeed be some transformation of your data that produces an acceptably normal distribution. Of course, now your inference is about about the transformed data, not the not-transformed data.
Assuming you are talking about a oneway ANOVA, the Kruskal-Wallis test is an appropriate nonparametric analog to the oneway ANOVA. Dunn's test (not the garden-variety rank sum test) is perhaps the most common nonparametric test appropriate for post hoc pair-wise multiple comparisons, although there are other tests such as the Conover-Iman test (strictly more powerful than Dunn's test after rejection of the kruskal-Wallis), and the Dwass-Steele-Crichtlow-Fligner test.
Multiple comparisons procedures (whether family-wise error rate variety or false discovery rate variety) don't really have anything directly to do with your specific test assumptions (e.g., normality of data), rather they have to do with the meaning of $\alpha$ (willingness to make a false rejection of a null hypothesis) given that you are performing multiple tests.
The ANOVA is based on a ratio of within group and between group variances. I am not entirely sure what you mean by heteroscedasticity in this context, but if you mean unequal variances between groups, that would seem to me to fundamentally break the logic of the test's null hypothesis.
A simple Google Scholar query for "Dunn's test" along with a general term from your discipline should return plenty of published examples.
References
Conover, W. J. and Iman, R. L. (1979). On multiple-comparisons procedures. Technical Report LA-7677-MS, Los Alamos Scientific Laboratory.
Crichtlow, D. E. and Fligner, M. A. (1991). On distribution-free multiple comparisons in the one-way analysis of variance. Communications in Statistics—Theory and Methods, 20(1):127.
Dunn, O. J. (1964). Multiple comparisons using rank sums. Technometrics, 6(3):241–252.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
There may indeed be some transformation of your data that produces an acceptably normal distribution. Of course, now your inference is about about the transformed data, not the not-transformed data.
A
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
There may indeed be some transformation of your data that produces an acceptably normal distribution. Of course, now your inference is about about the transformed data, not the not-transformed data.
Assuming you are talking about a oneway ANOVA, the Kruskal-Wallis test is an appropriate nonparametric analog to the oneway ANOVA. Dunn's test (not the garden-variety rank sum test) is perhaps the most common nonparametric test appropriate for post hoc pair-wise multiple comparisons, although there are other tests such as the Conover-Iman test (strictly more powerful than Dunn's test after rejection of the kruskal-Wallis), and the Dwass-Steele-Crichtlow-Fligner test.
Multiple comparisons procedures (whether family-wise error rate variety or false discovery rate variety) don't really have anything directly to do with your specific test assumptions (e.g., normality of data), rather they have to do with the meaning of $\alpha$ (willingness to make a false rejection of a null hypothesis) given that you are performing multiple tests.
The ANOVA is based on a ratio of within group and between group variances. I am not entirely sure what you mean by heteroscedasticity in this context, but if you mean unequal variances between groups, that would seem to me to fundamentally break the logic of the test's null hypothesis.
A simple Google Scholar query for "Dunn's test" along with a general term from your discipline should return plenty of published examples.
References
Conover, W. J. and Iman, R. L. (1979). On multiple-comparisons procedures. Technical Report LA-7677-MS, Los Alamos Scientific Laboratory.
Crichtlow, D. E. and Fligner, M. A. (1991). On distribution-free multiple comparisons in the one-way analysis of variance. Communications in Statistics—Theory and Methods, 20(1):127.
Dunn, O. J. (1964). Multiple comparisons using rank sums. Technometrics, 6(3):241–252.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
There may indeed be some transformation of your data that produces an acceptably normal distribution. Of course, now your inference is about about the transformed data, not the not-transformed data.
A
|
10,245
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
It sounds to me as though you are doing the footwork and are trying your best but are worried your efforts will not be good enough to get your paper past the reviewers. Very much a real-world problem. I think all researchers struggle with analyses that appear to be borderline or even frankly breaching assumptions from time to time. After all there are millions of articles evaluating e.g. treatment effects in 3 small groups of mice with something like 6 - 7 mice in each group. How to know if Anova assumptions are satisfied in such a paper!
I have reviewed a large number of papers especially in the field of cardiovascular pathophysiology and actually never do feel 100% sure whether I can trust the data or not in an article that I read. But for me as a reviewer, I actually tend to think that issues can arise at so many levels in science that there is probably little point in digging too deep into the statistics -- after all, the whole dataset could be fabricated and I would never in a million years be able to tell. Accordingly, there will always be an element of trust in this field of work, which researchers must never abuse.
The most real-world suggestion I would give is that you need to think everything through very carefully before you submit and make sure you will be able to answer truthfully any questions asked by the reviewers. As long as you have done your best, your intentions are honest and you sleep well at night I think you should be ok.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
|
It sounds to me as though you are doing the footwork and are trying your best but are worried your efforts will not be good enough to get your paper past the reviewers. Very much a real-world problem.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
It sounds to me as though you are doing the footwork and are trying your best but are worried your efforts will not be good enough to get your paper past the reviewers. Very much a real-world problem. I think all researchers struggle with analyses that appear to be borderline or even frankly breaching assumptions from time to time. After all there are millions of articles evaluating e.g. treatment effects in 3 small groups of mice with something like 6 - 7 mice in each group. How to know if Anova assumptions are satisfied in such a paper!
I have reviewed a large number of papers especially in the field of cardiovascular pathophysiology and actually never do feel 100% sure whether I can trust the data or not in an article that I read. But for me as a reviewer, I actually tend to think that issues can arise at so many levels in science that there is probably little point in digging too deep into the statistics -- after all, the whole dataset could be fabricated and I would never in a million years be able to tell. Accordingly, there will always be an element of trust in this field of work, which researchers must never abuse.
The most real-world suggestion I would give is that you need to think everything through very carefully before you submit and make sure you will be able to answer truthfully any questions asked by the reviewers. As long as you have done your best, your intentions are honest and you sleep well at night I think you should be ok.
|
Practically speaking, how do people handle ANOVA when the data doesn't quite meet assumptions?
It sounds to me as though you are doing the footwork and are trying your best but are worried your efforts will not be good enough to get your paper past the reviewers. Very much a real-world problem.
|
10,246
|
Why are neural networks described as black-box models?
|
A neural network is a black box in the sense that while it can approximate any function, studying its structure won't give you any insights on the structure of the function being approximated.
As an example, one common use of neural networks on the banking business is to classify loaners on "good payers" and "bad payers". You have a matrix of input characteristics $C$ (sex, age, income, etc) and a vector of results $R$ ("defaulted", "not defaulted", etc). When you model this using a neural network, you are supposing that there is a function $f(C)=R$, in the proper sense of a mathematical function. This function f can be arbitrarily complex, and might change according to the evolution of the business, so you can't derive it by hand.
Then you use the Neural Network to build an approximation of $f$ that has a error rate that is acceptable to your application. This works, and the precision can be arbitrarily small - you can expand the network, fine tune its training parameters and get more data until the precision hits your goals.
The black box issue is: The approximation given by the neural network will not give you any insight on the form of f. There is no simple link between the weights and the function being approximated. Even the analysis of which input characteristic is irrelevant is a open problem (see this link).
Plus, from a traditional statistics viewpoint, a neural network is a non-identifiable model: Given a dataset and network topology, there can be two neural networks with different weights but exactly the same result. This makes the analysis very hard.
As an example of "non-black box models", or "interpretable models", you have regression equations and decision trees. The first one gives you a closed form approximation of f where the importance of each element is explicit, the second one is a graphical description of some relative risks\odds ratios.
|
Why are neural networks described as black-box models?
|
A neural network is a black box in the sense that while it can approximate any function, studying its structure won't give you any insights on the structure of the function being approximated.
As an e
|
Why are neural networks described as black-box models?
A neural network is a black box in the sense that while it can approximate any function, studying its structure won't give you any insights on the structure of the function being approximated.
As an example, one common use of neural networks on the banking business is to classify loaners on "good payers" and "bad payers". You have a matrix of input characteristics $C$ (sex, age, income, etc) and a vector of results $R$ ("defaulted", "not defaulted", etc). When you model this using a neural network, you are supposing that there is a function $f(C)=R$, in the proper sense of a mathematical function. This function f can be arbitrarily complex, and might change according to the evolution of the business, so you can't derive it by hand.
Then you use the Neural Network to build an approximation of $f$ that has a error rate that is acceptable to your application. This works, and the precision can be arbitrarily small - you can expand the network, fine tune its training parameters and get more data until the precision hits your goals.
The black box issue is: The approximation given by the neural network will not give you any insight on the form of f. There is no simple link between the weights and the function being approximated. Even the analysis of which input characteristic is irrelevant is a open problem (see this link).
Plus, from a traditional statistics viewpoint, a neural network is a non-identifiable model: Given a dataset and network topology, there can be two neural networks with different weights but exactly the same result. This makes the analysis very hard.
As an example of "non-black box models", or "interpretable models", you have regression equations and decision trees. The first one gives you a closed form approximation of f where the importance of each element is explicit, the second one is a graphical description of some relative risks\odds ratios.
|
Why are neural networks described as black-box models?
A neural network is a black box in the sense that while it can approximate any function, studying its structure won't give you any insights on the structure of the function being approximated.
As an e
|
10,247
|
Why are neural networks described as black-box models?
|
Google has published Inception-v3. It's a Neural Network (NN) for image classification algorithm (telling a cat from a dog).
In the paper they talk about the current state of image classification
For example, GoogleNet employed only 5 million parameters, which represented a 12x reduction with respect to its predecessor AlexNet, which used 60 million parameters.Furthermore, VGGNet employed about 3x more parameters than AlexNet
and that is basically why we call NN for black boxes. If I train an image classification model - with 10 million parameters - and hand it to you. What can you do with it?
You can certainly run it and classify images. It will work great! But you can not answer any of the following questions by studying all the weights, biases and network structure.
Can this network tell a Husky from a Poodle?
Which objects are easy to classify for the algorithm, which are difficult?
Which part of a dog is the most important for being able to classify it correctly? The tail or the foot?
If I photoshop a cats head on a dog, what happens, and why?
You can maybe answer the questions by just running the NN and see the result (black box), but you have no change of understanding why it is behaving the way it does in edge cases.
|
Why are neural networks described as black-box models?
|
Google has published Inception-v3. It's a Neural Network (NN) for image classification algorithm (telling a cat from a dog).
In the paper they talk about the current state of image classification
For
|
Why are neural networks described as black-box models?
Google has published Inception-v3. It's a Neural Network (NN) for image classification algorithm (telling a cat from a dog).
In the paper they talk about the current state of image classification
For example, GoogleNet employed only 5 million parameters, which represented a 12x reduction with respect to its predecessor AlexNet, which used 60 million parameters.Furthermore, VGGNet employed about 3x more parameters than AlexNet
and that is basically why we call NN for black boxes. If I train an image classification model - with 10 million parameters - and hand it to you. What can you do with it?
You can certainly run it and classify images. It will work great! But you can not answer any of the following questions by studying all the weights, biases and network structure.
Can this network tell a Husky from a Poodle?
Which objects are easy to classify for the algorithm, which are difficult?
Which part of a dog is the most important for being able to classify it correctly? The tail or the foot?
If I photoshop a cats head on a dog, what happens, and why?
You can maybe answer the questions by just running the NN and see the result (black box), but you have no change of understanding why it is behaving the way it does in edge cases.
|
Why are neural networks described as black-box models?
Google has published Inception-v3. It's a Neural Network (NN) for image classification algorithm (telling a cat from a dog).
In the paper they talk about the current state of image classification
For
|
10,248
|
Simplify sum of combinations with same n, all possible values of k
|
See
http://en.wikipedia.org/wiki/Combination#Number_of_k-combinations_for_all_k
which says
$$ \sum_{k=0}^{n} \binom{n}{k} = 2^n$$
You can prove this using the binomial theorem where $x=y=1$.
Now, since $\binom{n}{0} = 1$ for any $n$, it follows that
$$ \sum_{k=1}^{n} \binom{n}{k} = 2^n - 1$$
In your case $n=8$, so the answer is $2^8 - 1 = 255$.
|
Simplify sum of combinations with same n, all possible values of k
|
See
http://en.wikipedia.org/wiki/Combination#Number_of_k-combinations_for_all_k
which says
$$ \sum_{k=0}^{n} \binom{n}{k} = 2^n$$
You can prove this using the binomial theorem where $x=y=1$.
Now,
|
Simplify sum of combinations with same n, all possible values of k
See
http://en.wikipedia.org/wiki/Combination#Number_of_k-combinations_for_all_k
which says
$$ \sum_{k=0}^{n} \binom{n}{k} = 2^n$$
You can prove this using the binomial theorem where $x=y=1$.
Now, since $\binom{n}{0} = 1$ for any $n$, it follows that
$$ \sum_{k=1}^{n} \binom{n}{k} = 2^n - 1$$
In your case $n=8$, so the answer is $2^8 - 1 = 255$.
|
Simplify sum of combinations with same n, all possible values of k
See
http://en.wikipedia.org/wiki/Combination#Number_of_k-combinations_for_all_k
which says
$$ \sum_{k=0}^{n} \binom{n}{k} = 2^n$$
You can prove this using the binomial theorem where $x=y=1$.
Now,
|
10,249
|
Simplify sum of combinations with same n, all possible values of k
|
Homework?
Hint:
Remember the binomial theorem:
$$
(x+y)^n = \sum_{k=0}^{n}\binom{n}{k}x^ky^{n-k}
$$
Now, if you could just find x and y so that $x^ky^{n-k}$ is constant...
|
Simplify sum of combinations with same n, all possible values of k
|
Homework?
Hint:
Remember the binomial theorem:
$$
(x+y)^n = \sum_{k=0}^{n}\binom{n}{k}x^ky^{n-k}
$$
Now, if you could just find x and y so that $x^ky^{n-k}$ is constant...
|
Simplify sum of combinations with same n, all possible values of k
Homework?
Hint:
Remember the binomial theorem:
$$
(x+y)^n = \sum_{k=0}^{n}\binom{n}{k}x^ky^{n-k}
$$
Now, if you could just find x and y so that $x^ky^{n-k}$ is constant...
|
Simplify sum of combinations with same n, all possible values of k
Homework?
Hint:
Remember the binomial theorem:
$$
(x+y)^n = \sum_{k=0}^{n}\binom{n}{k}x^ky^{n-k}
$$
Now, if you could just find x and y so that $x^ky^{n-k}$ is constant...
|
10,250
|
Why do you need to scale data in KNN
|
The k-nearest neighbor algorithm relies on majority voting based on class membership of 'k' nearest samples for a given test point. The nearness of samples is typically based on Euclidean distance.
Consider a simple two class classification problem, where a Class 1 sample is chosen (black) along with it's 10-nearest neighbors (filled green). In the first figure, data is not normalized, whereas in the second one it is.
Notice, how without normalization, all the nearest neighbors are aligned in the direction of the axis with the smaller range, i.e. $x_1$ leading to incorrect classification.
Normalization solves this problem!
|
Why do you need to scale data in KNN
|
The k-nearest neighbor algorithm relies on majority voting based on class membership of 'k' nearest samples for a given test point. The nearness of samples is typically based on Euclidean distance.
C
|
Why do you need to scale data in KNN
The k-nearest neighbor algorithm relies on majority voting based on class membership of 'k' nearest samples for a given test point. The nearness of samples is typically based on Euclidean distance.
Consider a simple two class classification problem, where a Class 1 sample is chosen (black) along with it's 10-nearest neighbors (filled green). In the first figure, data is not normalized, whereas in the second one it is.
Notice, how without normalization, all the nearest neighbors are aligned in the direction of the axis with the smaller range, i.e. $x_1$ leading to incorrect classification.
Normalization solves this problem!
|
Why do you need to scale data in KNN
The k-nearest neighbor algorithm relies on majority voting based on class membership of 'k' nearest samples for a given test point. The nearness of samples is typically based on Euclidean distance.
C
|
10,251
|
Why do you need to scale data in KNN
|
Suppose you had a dataset (m "examples" by n "features") and all but one feature dimension had values strictly between 0 and 1, while a single feature dimension had values that range from -1000000 to 1000000. When taking the euclidean distance between pairs of "examples", the values of the feature dimensions that range between 0 and 1 may become uninformative and the algorithm would essentially rely on the single dimension whose values are substantially larger. Just work out some example euclidean distance calculations and you can understand how the scale affects the nearest neighbor computation.
|
Why do you need to scale data in KNN
|
Suppose you had a dataset (m "examples" by n "features") and all but one feature dimension had values strictly between 0 and 1, while a single feature dimension had values that range from -1000000 to
|
Why do you need to scale data in KNN
Suppose you had a dataset (m "examples" by n "features") and all but one feature dimension had values strictly between 0 and 1, while a single feature dimension had values that range from -1000000 to 1000000. When taking the euclidean distance between pairs of "examples", the values of the feature dimensions that range between 0 and 1 may become uninformative and the algorithm would essentially rely on the single dimension whose values are substantially larger. Just work out some example euclidean distance calculations and you can understand how the scale affects the nearest neighbor computation.
|
Why do you need to scale data in KNN
Suppose you had a dataset (m "examples" by n "features") and all but one feature dimension had values strictly between 0 and 1, while a single feature dimension had values that range from -1000000 to
|
10,252
|
Why do you need to scale data in KNN
|
If the scale of features is very different then normalization is required. This is because the distance calculation done in KNN uses feature values.
When the one feature values are large than other, that feature will dominate the distance hence the outcome of the KNN.
see example on gist.github.com
|
Why do you need to scale data in KNN
|
If the scale of features is very different then normalization is required. This is because the distance calculation done in KNN uses feature values.
When the one feature values are large than other, t
|
Why do you need to scale data in KNN
If the scale of features is very different then normalization is required. This is because the distance calculation done in KNN uses feature values.
When the one feature values are large than other, that feature will dominate the distance hence the outcome of the KNN.
see example on gist.github.com
|
Why do you need to scale data in KNN
If the scale of features is very different then normalization is required. This is because the distance calculation done in KNN uses feature values.
When the one feature values are large than other, t
|
10,253
|
Why do you need to scale data in KNN
|
The larger the scale a particular feature has relative to other features, the more weight that feature will have in distance calculations.
Scaling all features to a common scale gives each feature an equal weight in distance calculations.
But notice that scaling introduces a particular weighting on the distance function, so how can we assume that it is somehow the correct one for KNN?
So my answer is: scaling should not be assumed to be a requirement.
|
Why do you need to scale data in KNN
|
The larger the scale a particular feature has relative to other features, the more weight that feature will have in distance calculations.
Scaling all features to a common scale gives each feature an
|
Why do you need to scale data in KNN
The larger the scale a particular feature has relative to other features, the more weight that feature will have in distance calculations.
Scaling all features to a common scale gives each feature an equal weight in distance calculations.
But notice that scaling introduces a particular weighting on the distance function, so how can we assume that it is somehow the correct one for KNN?
So my answer is: scaling should not be assumed to be a requirement.
|
Why do you need to scale data in KNN
The larger the scale a particular feature has relative to other features, the more weight that feature will have in distance calculations.
Scaling all features to a common scale gives each feature an
|
10,254
|
Polynomial contrasts for regression
|
Just to recap (and in case the OP hyperlinks fail in the future), we are looking at a dataset hsb2 as such:
id female race ses schtyp prog read write math science socst
1 70 0 4 1 1 1 57 52 41 47 57
2 121 1 4 2 1 3 68 59 53 63 61
...
199 118 1 4 2 1 1 55 62 58 58 61
200 137 1 4 3 1 2 63 65 65 53 61
which can be imported here.
We turn the variable read into an ordered / ordinal variable:
hsb2$readcat<-cut(hsb2$read, 4, ordered = TRUE)
(means = tapply(hsb2$write, hsb2$readcat, mean))
(28,40] (40,52] (52,64] (64,76]
42.77273 49.97849 56.56364 61.83333
Now we are all set to just run a regular ANOVA - yes, it is R, and we basically have a continuous dependent variable, write, and an explanatory variable with multiple levels, readcat. In R we can use lm(write ~ readcat, hsb2)
1. Generating the contrast matrix:
There are four different levels to the ordered variable readcat, so we'll have $n-1=3$ contrasts.
table(hsb2$readcat)
(28,40] (40,52] (52,64] (64,76]
22 93 55 30
First, let's go for the money, and take a look at the built-in R function:
contr.poly(4)
.L .Q .C
[1,] -0.6708204 0.5 -0.2236068
[2,] -0.2236068 -0.5 0.6708204
[3,] 0.2236068 -0.5 -0.6708204
[4,] 0.6708204 0.5 0.2236068
Now let's dissect what went on under the hood:
scores = 1:4 # 1 2 3 4 These are the four levels of the explanatory variable.
y = scores - mean(scores) # scores - 2.5
$y = \small [-1.5, -0.5, 0.5, 1.5]$
$\small \text{seq_len(n) - 1} = [0, 1, 2, 3]$
n = 4; X <- outer(y, seq_len(n) - 1, "^") # n = 4 in this case
$\small\begin{bmatrix}
1&-1.5&2.25&-3.375\\1&-0.5&0.25&-0.125\\1&0.5&0.25&0.125\\1&1.5&2.25&3.375
\end{bmatrix}$
What happened there? the outer(a, b, "^") raises the elements of a to the elements of b, so that the first column results from the operations, $\small(-1.5)^0$, $\small(-0.5)^0$, $\small 0.5^0$ and $\small 1.5^0$; the second column from $\small(-1.5)^1$, $\small(-0.5)^1$, $\small0.5^1$ and $\small1.5^1$; the third from $\small(-1.5)^2=2.25$, $\small(-0.5)^2 = 0.25$, $\small0.5^2 = 0.25$ and $\small1.5^2 = 2.25$; and the fourth, $\small(-1.5)^3=-3.375$, $\small(-0.5)^3=-0.125$, $\small0.5^3=0.125$ and $\small1.5^3=3.375$.
Next we do a $QR$ orthonormal decomposition of this matrix and take the compact representation of Q (c_Q = qr(X)$qr). Some of the inner workings of the functions used in QR factorization in R used in this post are further explained here.
$\small\begin{bmatrix}
-2&0&-2.5&0\\0.5&-2.236&0&-4.584\\0.5&0.447&2&0\\0.5&0.894&-0.9296&-1.342
\end{bmatrix}$
... of which we save the diagonal only (z = c_Q * (row(c_Q) == col(c_Q))). What lies in the diagonal: Just the "bottom" entries of the $\bf R$ part of the $QR$ decomposition. Just? well, no... It turns out that the diagonal of a upper triangular matrix contains the eigenvalues of the matrix!
Next we call the following function: raw = qr.qy(qr(X), z), the result of which can be replicated "manually" by two operations: 1. Turning the compact form of $Q$, i.e. qr(X)$qr, into $Q$, a transformation that can be achieved with Q = qr.Q(qr(X)), and 2. Carrying out the matrix multiplication $Qz$, as in Q %*% z.
Crucially, multiplying $\bf Q$ by the eigenvalues of $\bf R$ does not change the orthogonality of the constituent column vectors, but given that the absolute value of the eigenvalues appears in decreasing order from top left to bottom right, the multiplication of $Qz$ will tend to decrease the values in the higher order polynomial columns:
Matrix of Eigenvalues of R
[,1] [,2] [,3] [,4]
[1,] -2 0.000000 0 0.000000
[2,] 0 -2.236068 0 0.000000
[3,] 0 0.000000 2 0.000000
[4,] 0 0.000000 0 -1.341641
Compare the values in the later column vectors (quadratic and cubic) before and after the $QR$ factorization operations, and to the unaffected first two columns.
Before QR factorization operations (orthogonal col. vec.)
[,1] [,2] [,3] [,4]
[1,] 1 -1.5 2.25 -3.375
[2,] 1 -0.5 0.25 -0.125
[3,] 1 0.5 0.25 0.125
[4,] 1 1.5 2.25 3.375
After QR operations (equally orthogonal col. vec.)
[,1] [,2] [,3] [,4]
[1,] 1 -1.5 1 -0.295
[2,] 1 -0.5 -1 0.885
[3,] 1 0.5 -1 -0.885
[4,] 1 1.5 1 0.295
Finally we call (Z <- sweep(raw, 2L, apply(raw, 2L, function(x) sqrt(sum(x^2))), "/", check.margin = FALSE)) turning the matrix raw into an orthonormal vectors:
Orthonormal vectors (orthonormal basis of R^4)
[,1] [,2] [,3] [,4]
[1,] 0.5 -0.6708204 0.5 -0.2236068
[2,] 0.5 -0.2236068 -0.5 0.6708204
[3,] 0.5 0.2236068 -0.5 -0.6708204
[4,] 0.5 0.6708204 0.5 0.2236068
This function simply "normalizes" the matrix by dividing ("/") columnwise each element by the $\small\sqrt{\sum_\text{col.} x_i^2}$. So it can be decomposed in two steps: $(\text{i})$ apply(raw, 2, function(x)sqrt(sum(x^2))), resulting in 2 2.236 2 1.341, which are the denominators for each column in $(\text{ii})$ where every element in a column is divided by the corresponding value of $(\text{i})$.
At this point the column vectors form an orthonormal basis of $\mathbb{R}^4$, until we get rid of the first column, which will be the intercept, and we have reproduced the result of contr.poly(4):
$\small\begin{bmatrix}
-0.6708204&0.5&-0.2236068\\-0.2236068&-0.5&0.6708204\\0.2236068&-0.5&-0.6708204\\0.6708204&0.5&0.2236068
\end{bmatrix}$
The columns of this matrix are orthonormal, as can be shown by (sum(Z[,3]^2))^(1/4) = 1 and z[,3]%*%z[,4] = 0, for example (incidentally the same goes for rows). And, each column is the result of raising the initial $\text{scores - mean}$ to the $1$-st, $2$-nd and $3$-rd power, respectively - i.e. linear, quadratic and cubic.
2. Which contrasts (columns) contribute significantly to explain the differences between levels in the explanatory variable?
We can just run the ANOVA and look at the summary...
summary(lm(write ~ readcat, hsb2))
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 52.7870 0.6339 83.268 <2e-16 ***
readcat.L 14.2587 1.4841 9.607 <2e-16 ***
readcat.Q -0.9680 1.2679 -0.764 0.446
readcat.C -0.1554 1.0062 -0.154 0.877
... to see that there is a linear effect of readcat on write, so that the original values (in the third chunk of code in the beginning of the post) can be reproduced as:
coeff = coefficients(lm(write ~ readcat, hsb2))
C = contr.poly(4)
(recovered = c(coeff %*% c(1, C[1,]),
coeff %*% c(1, C[2,]),
coeff %*% c(1, C[3,]),
coeff %*% c(1, C[4,])))
[1] 42.77273 49.97849 56.56364 61.83333
... or...
... or much better...
Being orthogonal contrasts the sum of their components adds to zero $\displaystyle \sum_{i=1}^t a_i = 0$ for $a_1,\cdots,a_t$ constants, and the dot product of any two of them is zero. If we could visualized them they would look something like this:
The idea behind orthogonal contrast is that the inferences that we can exctract (in this case generating coefficients via a linear regression) will be the result of independent aspects of the data. This would not be the case if we simply used $X^0, X^1, \cdots. X^n$ as contrasts.
Graphically, this is much easier to understand. Compare the actual means by groups in large square black blocks to the prediced values, and see why a straight line approximation with minimal contribution of quadratic and cubic polynomials (with curves only approximated with loess) is optimal:
If, just for effect, the coefficients of the ANOVA had been as large for the linear contrast for the other approximations (quadratic and cubic), the nonsensical plot that follows would depict more clearly the polynomial plots of each "contribution":
The code is here.
|
Polynomial contrasts for regression
|
Just to recap (and in case the OP hyperlinks fail in the future), we are looking at a dataset hsb2 as such:
id female race ses schtyp prog read write math science socst
1 70 0 4 1
|
Polynomial contrasts for regression
Just to recap (and in case the OP hyperlinks fail in the future), we are looking at a dataset hsb2 as such:
id female race ses schtyp prog read write math science socst
1 70 0 4 1 1 1 57 52 41 47 57
2 121 1 4 2 1 3 68 59 53 63 61
...
199 118 1 4 2 1 1 55 62 58 58 61
200 137 1 4 3 1 2 63 65 65 53 61
which can be imported here.
We turn the variable read into an ordered / ordinal variable:
hsb2$readcat<-cut(hsb2$read, 4, ordered = TRUE)
(means = tapply(hsb2$write, hsb2$readcat, mean))
(28,40] (40,52] (52,64] (64,76]
42.77273 49.97849 56.56364 61.83333
Now we are all set to just run a regular ANOVA - yes, it is R, and we basically have a continuous dependent variable, write, and an explanatory variable with multiple levels, readcat. In R we can use lm(write ~ readcat, hsb2)
1. Generating the contrast matrix:
There are four different levels to the ordered variable readcat, so we'll have $n-1=3$ contrasts.
table(hsb2$readcat)
(28,40] (40,52] (52,64] (64,76]
22 93 55 30
First, let's go for the money, and take a look at the built-in R function:
contr.poly(4)
.L .Q .C
[1,] -0.6708204 0.5 -0.2236068
[2,] -0.2236068 -0.5 0.6708204
[3,] 0.2236068 -0.5 -0.6708204
[4,] 0.6708204 0.5 0.2236068
Now let's dissect what went on under the hood:
scores = 1:4 # 1 2 3 4 These are the four levels of the explanatory variable.
y = scores - mean(scores) # scores - 2.5
$y = \small [-1.5, -0.5, 0.5, 1.5]$
$\small \text{seq_len(n) - 1} = [0, 1, 2, 3]$
n = 4; X <- outer(y, seq_len(n) - 1, "^") # n = 4 in this case
$\small\begin{bmatrix}
1&-1.5&2.25&-3.375\\1&-0.5&0.25&-0.125\\1&0.5&0.25&0.125\\1&1.5&2.25&3.375
\end{bmatrix}$
What happened there? the outer(a, b, "^") raises the elements of a to the elements of b, so that the first column results from the operations, $\small(-1.5)^0$, $\small(-0.5)^0$, $\small 0.5^0$ and $\small 1.5^0$; the second column from $\small(-1.5)^1$, $\small(-0.5)^1$, $\small0.5^1$ and $\small1.5^1$; the third from $\small(-1.5)^2=2.25$, $\small(-0.5)^2 = 0.25$, $\small0.5^2 = 0.25$ and $\small1.5^2 = 2.25$; and the fourth, $\small(-1.5)^3=-3.375$, $\small(-0.5)^3=-0.125$, $\small0.5^3=0.125$ and $\small1.5^3=3.375$.
Next we do a $QR$ orthonormal decomposition of this matrix and take the compact representation of Q (c_Q = qr(X)$qr). Some of the inner workings of the functions used in QR factorization in R used in this post are further explained here.
$\small\begin{bmatrix}
-2&0&-2.5&0\\0.5&-2.236&0&-4.584\\0.5&0.447&2&0\\0.5&0.894&-0.9296&-1.342
\end{bmatrix}$
... of which we save the diagonal only (z = c_Q * (row(c_Q) == col(c_Q))). What lies in the diagonal: Just the "bottom" entries of the $\bf R$ part of the $QR$ decomposition. Just? well, no... It turns out that the diagonal of a upper triangular matrix contains the eigenvalues of the matrix!
Next we call the following function: raw = qr.qy(qr(X), z), the result of which can be replicated "manually" by two operations: 1. Turning the compact form of $Q$, i.e. qr(X)$qr, into $Q$, a transformation that can be achieved with Q = qr.Q(qr(X)), and 2. Carrying out the matrix multiplication $Qz$, as in Q %*% z.
Crucially, multiplying $\bf Q$ by the eigenvalues of $\bf R$ does not change the orthogonality of the constituent column vectors, but given that the absolute value of the eigenvalues appears in decreasing order from top left to bottom right, the multiplication of $Qz$ will tend to decrease the values in the higher order polynomial columns:
Matrix of Eigenvalues of R
[,1] [,2] [,3] [,4]
[1,] -2 0.000000 0 0.000000
[2,] 0 -2.236068 0 0.000000
[3,] 0 0.000000 2 0.000000
[4,] 0 0.000000 0 -1.341641
Compare the values in the later column vectors (quadratic and cubic) before and after the $QR$ factorization operations, and to the unaffected first two columns.
Before QR factorization operations (orthogonal col. vec.)
[,1] [,2] [,3] [,4]
[1,] 1 -1.5 2.25 -3.375
[2,] 1 -0.5 0.25 -0.125
[3,] 1 0.5 0.25 0.125
[4,] 1 1.5 2.25 3.375
After QR operations (equally orthogonal col. vec.)
[,1] [,2] [,3] [,4]
[1,] 1 -1.5 1 -0.295
[2,] 1 -0.5 -1 0.885
[3,] 1 0.5 -1 -0.885
[4,] 1 1.5 1 0.295
Finally we call (Z <- sweep(raw, 2L, apply(raw, 2L, function(x) sqrt(sum(x^2))), "/", check.margin = FALSE)) turning the matrix raw into an orthonormal vectors:
Orthonormal vectors (orthonormal basis of R^4)
[,1] [,2] [,3] [,4]
[1,] 0.5 -0.6708204 0.5 -0.2236068
[2,] 0.5 -0.2236068 -0.5 0.6708204
[3,] 0.5 0.2236068 -0.5 -0.6708204
[4,] 0.5 0.6708204 0.5 0.2236068
This function simply "normalizes" the matrix by dividing ("/") columnwise each element by the $\small\sqrt{\sum_\text{col.} x_i^2}$. So it can be decomposed in two steps: $(\text{i})$ apply(raw, 2, function(x)sqrt(sum(x^2))), resulting in 2 2.236 2 1.341, which are the denominators for each column in $(\text{ii})$ where every element in a column is divided by the corresponding value of $(\text{i})$.
At this point the column vectors form an orthonormal basis of $\mathbb{R}^4$, until we get rid of the first column, which will be the intercept, and we have reproduced the result of contr.poly(4):
$\small\begin{bmatrix}
-0.6708204&0.5&-0.2236068\\-0.2236068&-0.5&0.6708204\\0.2236068&-0.5&-0.6708204\\0.6708204&0.5&0.2236068
\end{bmatrix}$
The columns of this matrix are orthonormal, as can be shown by (sum(Z[,3]^2))^(1/4) = 1 and z[,3]%*%z[,4] = 0, for example (incidentally the same goes for rows). And, each column is the result of raising the initial $\text{scores - mean}$ to the $1$-st, $2$-nd and $3$-rd power, respectively - i.e. linear, quadratic and cubic.
2. Which contrasts (columns) contribute significantly to explain the differences between levels in the explanatory variable?
We can just run the ANOVA and look at the summary...
summary(lm(write ~ readcat, hsb2))
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 52.7870 0.6339 83.268 <2e-16 ***
readcat.L 14.2587 1.4841 9.607 <2e-16 ***
readcat.Q -0.9680 1.2679 -0.764 0.446
readcat.C -0.1554 1.0062 -0.154 0.877
... to see that there is a linear effect of readcat on write, so that the original values (in the third chunk of code in the beginning of the post) can be reproduced as:
coeff = coefficients(lm(write ~ readcat, hsb2))
C = contr.poly(4)
(recovered = c(coeff %*% c(1, C[1,]),
coeff %*% c(1, C[2,]),
coeff %*% c(1, C[3,]),
coeff %*% c(1, C[4,])))
[1] 42.77273 49.97849 56.56364 61.83333
... or...
... or much better...
Being orthogonal contrasts the sum of their components adds to zero $\displaystyle \sum_{i=1}^t a_i = 0$ for $a_1,\cdots,a_t$ constants, and the dot product of any two of them is zero. If we could visualized them they would look something like this:
The idea behind orthogonal contrast is that the inferences that we can exctract (in this case generating coefficients via a linear regression) will be the result of independent aspects of the data. This would not be the case if we simply used $X^0, X^1, \cdots. X^n$ as contrasts.
Graphically, this is much easier to understand. Compare the actual means by groups in large square black blocks to the prediced values, and see why a straight line approximation with minimal contribution of quadratic and cubic polynomials (with curves only approximated with loess) is optimal:
If, just for effect, the coefficients of the ANOVA had been as large for the linear contrast for the other approximations (quadratic and cubic), the nonsensical plot that follows would depict more clearly the polynomial plots of each "contribution":
The code is here.
|
Polynomial contrasts for regression
Just to recap (and in case the OP hyperlinks fail in the future), we are looking at a dataset hsb2 as such:
id female race ses schtyp prog read write math science socst
1 70 0 4 1
|
10,255
|
Polynomial contrasts for regression
|
I will use your example to explain how it works. Using polynomial contrasts with four groups yields following.
\begin{align}
E\,write_1 &= \mu -0.67L + 0.5Q -0.22C\\
E\,write_2 &= \mu -0.22L -0.5Q + 0.67C\\
E\,write_3 &= \mu + 0.22L -0.5Q -0.67C\\
E\,write_4 &= \mu + 0.67L + 0.5Q + 0.22C
\end{align}
Where first equation works for the group of lowest reading scores and the fourth one for the group of best reading scores. we can compare these equations to the one given using normal linear regression (supposing $read_i$ is continous)
$$E\,write_i=\mu+read_iL + read_i^2Q+read_i^3C$$
Usually instead of $L,Q,C$ you would have $\beta_1, \beta_2, \beta_3$ and written at first position. But this writing resembles the one with polynomial contrasts. So numbers in front of $L, Q, C$ are actually instead of $read_i, read_i^2, read_i^3$. You can see that coefficients before $L$ have linear trend, before $Q$ quadratic and before $C$ cubic.
Then R estimates parameters $\mu, L,Q,C$ and gives you
$$
\widehat{\mu}=52.79, \widehat{L}=14.26, \widehat{Q}=−0.97, \widehat{C}=−0.16
$$
Where $\widehat{\mu}=\frac{1}{4}\sum_{i=1}^4E\,write_i$ and estimated coefficients $\widehat{\mu}, \widehat{L}, \widehat{Q}, \widehat{C}$ are something like estimates at normal linear regression. So from the output you can see if estimated coefficients are significantly different from zero, so you could anticipate some kind of linear, quadratic or cubic trend.
In that example is significantly non-zero only $\widehat{L}$. So your conclusion could be: We see that the better scoring in writing depends linearly on reading score, but there is no significant quadratic or cubic effect.
|
Polynomial contrasts for regression
|
I will use your example to explain how it works. Using polynomial contrasts with four groups yields following.
\begin{align}
E\,write_1 &= \mu -0.67L + 0.5Q -0.22C\\
E\,write_2 &= \mu -0.22L -0.5Q +
|
Polynomial contrasts for regression
I will use your example to explain how it works. Using polynomial contrasts with four groups yields following.
\begin{align}
E\,write_1 &= \mu -0.67L + 0.5Q -0.22C\\
E\,write_2 &= \mu -0.22L -0.5Q + 0.67C\\
E\,write_3 &= \mu + 0.22L -0.5Q -0.67C\\
E\,write_4 &= \mu + 0.67L + 0.5Q + 0.22C
\end{align}
Where first equation works for the group of lowest reading scores and the fourth one for the group of best reading scores. we can compare these equations to the one given using normal linear regression (supposing $read_i$ is continous)
$$E\,write_i=\mu+read_iL + read_i^2Q+read_i^3C$$
Usually instead of $L,Q,C$ you would have $\beta_1, \beta_2, \beta_3$ and written at first position. But this writing resembles the one with polynomial contrasts. So numbers in front of $L, Q, C$ are actually instead of $read_i, read_i^2, read_i^3$. You can see that coefficients before $L$ have linear trend, before $Q$ quadratic and before $C$ cubic.
Then R estimates parameters $\mu, L,Q,C$ and gives you
$$
\widehat{\mu}=52.79, \widehat{L}=14.26, \widehat{Q}=−0.97, \widehat{C}=−0.16
$$
Where $\widehat{\mu}=\frac{1}{4}\sum_{i=1}^4E\,write_i$ and estimated coefficients $\widehat{\mu}, \widehat{L}, \widehat{Q}, \widehat{C}$ are something like estimates at normal linear regression. So from the output you can see if estimated coefficients are significantly different from zero, so you could anticipate some kind of linear, quadratic or cubic trend.
In that example is significantly non-zero only $\widehat{L}$. So your conclusion could be: We see that the better scoring in writing depends linearly on reading score, but there is no significant quadratic or cubic effect.
|
Polynomial contrasts for regression
I will use your example to explain how it works. Using polynomial contrasts with four groups yields following.
\begin{align}
E\,write_1 &= \mu -0.67L + 0.5Q -0.22C\\
E\,write_2 &= \mu -0.22L -0.5Q +
|
10,256
|
Is there always a maximizer for any MLE problem?
|
Perhaps the engineer had in mind canonical exponential families: in their natural parametrization, the parameter space is convex and the log-likelihood is concave (see Thm 1.6.3 in Bickel & Doksum's Mathematical Statistics, Volume 1). Also, under some mild technical conditions (basically that the model be "full rank", or equivalently, that the natural parameter by identifiable), the log-likelihood function is strictly concave, which implies there exists a unique maximizer. (Corollary 1.6.2 in the same reference.) [Also, the lecture notes cited by @biostat make the same point.]
Note that the natural parametrization of a canonical exponential family is usually different from the standard parametrization. So, while @cardinal points out that the log-likelihood for the family $\mathcal{N}(\mu,\sigma^2)$ is not convex in $\sigma^2$, it will be concave in the natural parameters, which are $\eta_1 = \mu / \sigma^2$ and $\eta_2 = -1/\sigma^2$.
|
Is there always a maximizer for any MLE problem?
|
Perhaps the engineer had in mind canonical exponential families: in their natural parametrization, the parameter space is convex and the log-likelihood is concave (see Thm 1.6.3 in Bickel & Doksum's M
|
Is there always a maximizer for any MLE problem?
Perhaps the engineer had in mind canonical exponential families: in their natural parametrization, the parameter space is convex and the log-likelihood is concave (see Thm 1.6.3 in Bickel & Doksum's Mathematical Statistics, Volume 1). Also, under some mild technical conditions (basically that the model be "full rank", or equivalently, that the natural parameter by identifiable), the log-likelihood function is strictly concave, which implies there exists a unique maximizer. (Corollary 1.6.2 in the same reference.) [Also, the lecture notes cited by @biostat make the same point.]
Note that the natural parametrization of a canonical exponential family is usually different from the standard parametrization. So, while @cardinal points out that the log-likelihood for the family $\mathcal{N}(\mu,\sigma^2)$ is not convex in $\sigma^2$, it will be concave in the natural parameters, which are $\eta_1 = \mu / \sigma^2$ and $\eta_2 = -1/\sigma^2$.
|
Is there always a maximizer for any MLE problem?
Perhaps the engineer had in mind canonical exponential families: in their natural parametrization, the parameter space is convex and the log-likelihood is concave (see Thm 1.6.3 in Bickel & Doksum's M
|
10,257
|
Is there always a maximizer for any MLE problem?
|
Likelihood function often attains maximum for estimation of parameter of interest. Nevertheless, sometime MLE does not exist, such as for Gaussian mixture distribution or nonparametric functions, which has more than one peaks (bi or multi -modal). I often face the problem of estimating population genetics unknown parameters i.e., recombination rates, effect of natural selection.
One of the reason also @cardinal point out that is unbounded parametric space.
Moreover, I would recommend the following article, see section 3 (for function) and Fig.3. However, there is quite useful and handy document information about MLE.
|
Is there always a maximizer for any MLE problem?
|
Likelihood function often attains maximum for estimation of parameter of interest. Nevertheless, sometime MLE does not exist, such as for Gaussian mixture distribution or nonparametric functions, whic
|
Is there always a maximizer for any MLE problem?
Likelihood function often attains maximum for estimation of parameter of interest. Nevertheless, sometime MLE does not exist, such as for Gaussian mixture distribution or nonparametric functions, which has more than one peaks (bi or multi -modal). I often face the problem of estimating population genetics unknown parameters i.e., recombination rates, effect of natural selection.
One of the reason also @cardinal point out that is unbounded parametric space.
Moreover, I would recommend the following article, see section 3 (for function) and Fig.3. However, there is quite useful and handy document information about MLE.
|
Is there always a maximizer for any MLE problem?
Likelihood function often attains maximum for estimation of parameter of interest. Nevertheless, sometime MLE does not exist, such as for Gaussian mixture distribution or nonparametric functions, whic
|
10,258
|
Is there always a maximizer for any MLE problem?
|
Perhaps someone will find the following simple example useful.
Consider flipping a coin once. Let $\theta$ denote the probability of heads. If it is known that the coin can come up either heads or tails then $\theta \in (0,1)$. Since the set $(0,1)$ is open, the parameter space is not compact. The likelihood for $\theta$ is given by
$$
\begin{cases}
\theta & \text{heads} \\
1-\theta & \text{tails}
\end{cases} .
$$
In neither case is there a maximum for $\theta$ on $(0,1)$.
|
Is there always a maximizer for any MLE problem?
|
Perhaps someone will find the following simple example useful.
Consider flipping a coin once. Let $\theta$ denote the probability of heads. If it is known that the coin can come up either heads or ta
|
Is there always a maximizer for any MLE problem?
Perhaps someone will find the following simple example useful.
Consider flipping a coin once. Let $\theta$ denote the probability of heads. If it is known that the coin can come up either heads or tails then $\theta \in (0,1)$. Since the set $(0,1)$ is open, the parameter space is not compact. The likelihood for $\theta$ is given by
$$
\begin{cases}
\theta & \text{heads} \\
1-\theta & \text{tails}
\end{cases} .
$$
In neither case is there a maximum for $\theta$ on $(0,1)$.
|
Is there always a maximizer for any MLE problem?
Perhaps someone will find the following simple example useful.
Consider flipping a coin once. Let $\theta$ denote the probability of heads. If it is known that the coin can come up either heads or ta
|
10,259
|
Is there always a maximizer for any MLE problem?
|
I admit I may be missing something, but --
If this is an estimation problem, and the goal is to estimate an unknown parameter, and the parameter is known to come from some closed and bounded set, and the likelihood function is continuous, then there has to exist a value for this parameter that maximizes the likelihood function. In other words, a maximum has to exist. (It need not be unique, but at least one maximum must exist. There is no guarantee that all local maxima will be global maxima, but that isn't a necessary condition for a maximum to exist.)
I don't know whether the likelihood function always has to be convex, but that isn't a necessary condition for there to exist a maximum.
If I've overlooked something, I'd welcome hearing what it is that I am missing.
|
Is there always a maximizer for any MLE problem?
|
I admit I may be missing something, but --
If this is an estimation problem, and the goal is to estimate an unknown parameter, and the parameter is known to come from some closed and bounded set, and
|
Is there always a maximizer for any MLE problem?
I admit I may be missing something, but --
If this is an estimation problem, and the goal is to estimate an unknown parameter, and the parameter is known to come from some closed and bounded set, and the likelihood function is continuous, then there has to exist a value for this parameter that maximizes the likelihood function. In other words, a maximum has to exist. (It need not be unique, but at least one maximum must exist. There is no guarantee that all local maxima will be global maxima, but that isn't a necessary condition for a maximum to exist.)
I don't know whether the likelihood function always has to be convex, but that isn't a necessary condition for there to exist a maximum.
If I've overlooked something, I'd welcome hearing what it is that I am missing.
|
Is there always a maximizer for any MLE problem?
I admit I may be missing something, but --
If this is an estimation problem, and the goal is to estimate an unknown parameter, and the parameter is known to come from some closed and bounded set, and
|
10,260
|
Is there always a maximizer for any MLE problem?
|
Re: a comment by @Cardinal.
I suspect those that referred to Cardinal's comment below the original question, missed its subtle mischief: the OP makes a problematic statement, because it refers to the likelihood as a cost function (which we usually want to minimize), and then talks about concavity and maximization. The Gaussian likelihood is certainly not convex in $\sigma^2$.
Moreover, the log-likelihood is not "always concave": the easiest example is the Student-t distribution whose log-likelihood is not concave, or the Gamma log-likelihood for shape parameter $<1$ (it is convex then).
But even more than that, there is another subtle point, i.e. that what we want is for the log-likelihood to be concave at the stationary point:
The sample likelihood of i.i.d. zero-mean Normals is concave at the stationary point. To wit,
$$f_x(x) = \frac 1 {\sqrt{2\pi}} \frac 1 \sigma \exp\left\{-\frac 12 \frac{x^2}{\sigma^2}\right\}.$$
To work with $\sigma^2$ set $\sigma^2 \equiv v$ and take the log-sample likelihood.
$$\log \mathcal L = -\frac{n}{2}\ln(2\pi) -\frac{n}{2} \ln v -\frac 12 \frac{\sum_{i=1}^nx_i^2}{v} $$
$$\frac{\partial \log \mathcal L}{\partial v}= -\frac{n}{2}\frac 1 v + \frac 12 \frac{\sum_{i=1}^nx_i^2}{v^2}$$
$$\frac{\partial^2 \log \mathcal L}{\partial v^2}= \frac{n}{2}\frac 1 {v^2} - \frac{\sum_{i=1}^nx_i^2}{v^3} = \frac{n}{2v^2}\left(1- \frac 2 v \frac 1n \sum_{i=1}^nx_i^2\right).$$
Evidently, this is neither concave nor convex. On its own it can be either, depending on the sample of $x$'s and on the true value of $v$. But at the stationary point we have
$$\hat v = \frac 1n \sum_{i=1}^nx_i^2$$
and inserting this into the f.o.c we get
$$\frac{\partial^2 \log \mathcal L}{\partial v^2} |_{{\rm f.o.c.}}= -\frac{n}{2\hat v^2} <0.$$
So the sample log-likelihood of a sample of i.i.d. zero-mean Normals is concave at the stationary point related to $\sigma^2$.
|
Is there always a maximizer for any MLE problem?
|
Re: a comment by @Cardinal.
I suspect those that referred to Cardinal's comment below the original question, missed its subtle mischief: the OP makes a problematic statement, because it refers to the
|
Is there always a maximizer for any MLE problem?
Re: a comment by @Cardinal.
I suspect those that referred to Cardinal's comment below the original question, missed its subtle mischief: the OP makes a problematic statement, because it refers to the likelihood as a cost function (which we usually want to minimize), and then talks about concavity and maximization. The Gaussian likelihood is certainly not convex in $\sigma^2$.
Moreover, the log-likelihood is not "always concave": the easiest example is the Student-t distribution whose log-likelihood is not concave, or the Gamma log-likelihood for shape parameter $<1$ (it is convex then).
But even more than that, there is another subtle point, i.e. that what we want is for the log-likelihood to be concave at the stationary point:
The sample likelihood of i.i.d. zero-mean Normals is concave at the stationary point. To wit,
$$f_x(x) = \frac 1 {\sqrt{2\pi}} \frac 1 \sigma \exp\left\{-\frac 12 \frac{x^2}{\sigma^2}\right\}.$$
To work with $\sigma^2$ set $\sigma^2 \equiv v$ and take the log-sample likelihood.
$$\log \mathcal L = -\frac{n}{2}\ln(2\pi) -\frac{n}{2} \ln v -\frac 12 \frac{\sum_{i=1}^nx_i^2}{v} $$
$$\frac{\partial \log \mathcal L}{\partial v}= -\frac{n}{2}\frac 1 v + \frac 12 \frac{\sum_{i=1}^nx_i^2}{v^2}$$
$$\frac{\partial^2 \log \mathcal L}{\partial v^2}= \frac{n}{2}\frac 1 {v^2} - \frac{\sum_{i=1}^nx_i^2}{v^3} = \frac{n}{2v^2}\left(1- \frac 2 v \frac 1n \sum_{i=1}^nx_i^2\right).$$
Evidently, this is neither concave nor convex. On its own it can be either, depending on the sample of $x$'s and on the true value of $v$. But at the stationary point we have
$$\hat v = \frac 1n \sum_{i=1}^nx_i^2$$
and inserting this into the f.o.c we get
$$\frac{\partial^2 \log \mathcal L}{\partial v^2} |_{{\rm f.o.c.}}= -\frac{n}{2\hat v^2} <0.$$
So the sample log-likelihood of a sample of i.i.d. zero-mean Normals is concave at the stationary point related to $\sigma^2$.
|
Is there always a maximizer for any MLE problem?
Re: a comment by @Cardinal.
I suspect those that referred to Cardinal's comment below the original question, missed its subtle mischief: the OP makes a problematic statement, because it refers to the
|
10,261
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
|
To understand why we use the t-distribution, you need to know what is the underlying distribution of $\widehat{\beta}$ and of the Residual sum of squares ($RSS$) as these two put together will give you the t-distribution.
The easier part is the distribution of $\widehat{\beta}$ which is a normal distribution - to see this note that $\widehat{\beta}$=$(X^{T}X)^{-1}X^{T}Y$ so it is a linear function of $Y$ where $Y\sim N(X\beta, \sigma^{2}I_{n})$. As a result it is also normally distributed, $\widehat{\beta} \sim N(\beta, \sigma^{2}(X^{T}X)^{-1})$ - let me know if you need help deriving the distribution of $\widehat{\beta}$.
Additionally, $RSS \sim \sigma^{2}\chi^{2}_{n-p}$, where $n$ is the number of observations and $p$ is the number of parameters used in your regression. The proof of this is a bit more involved, but also straightforward to derive (see proof here Why is RSS distributed chi square times n-p?).
Up until this point I have considered everything in matrix/vector notation, but let's for simplicity use $\widehat{\beta}_{i}$ and use its normal distribution which will give us:
\begin{equation}
\frac{\widehat{\beta}_{i}-\beta_{i}}{\sigma\sqrt{(X^{T}X)^{-1}_{ii}}} \sim N(0,1)
\end{equation}
Additionally, from the chi-squared distribution of $RSS$ we have that:
\begin{equation}
\frac{(n-p)s^{2}}{\sigma^{2}} \sim \chi^{2}_{n-p}
\end{equation}
This was simply a rearrangement of the first chi-squared expression and is independent of the $N(0,1)$. Additionally, we define $s^{2}=\frac{RSS}{n-p}$, which is an unbiased estimator for $\sigma^{2}$. By the definition of the $t_{n-p}$ definition that dividing a normal distribution by an independent chi-squared (over its degrees of freedom) gives you a t-distribution (for the proof see: A normal divided by the $\sqrt{\chi^2(s)/s}$ gives you a t-distribution -- proof) you get that:
\begin{equation}
\frac{\widehat{\beta}_{i}-\beta_{i}}{s\sqrt{(X^{T}X)^{-1}_{ii}}} \sim t_{n-p}
\end{equation}
Where $s\sqrt{(X^{T}X)^{-1}_{ii}}=SE(\widehat{\beta}_{i})$.
Let me know if it makes sense.
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
|
To understand why we use the t-distribution, you need to know what is the underlying distribution of $\widehat{\beta}$ and of the Residual sum of squares ($RSS$) as these two put together will give yo
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
To understand why we use the t-distribution, you need to know what is the underlying distribution of $\widehat{\beta}$ and of the Residual sum of squares ($RSS$) as these two put together will give you the t-distribution.
The easier part is the distribution of $\widehat{\beta}$ which is a normal distribution - to see this note that $\widehat{\beta}$=$(X^{T}X)^{-1}X^{T}Y$ so it is a linear function of $Y$ where $Y\sim N(X\beta, \sigma^{2}I_{n})$. As a result it is also normally distributed, $\widehat{\beta} \sim N(\beta, \sigma^{2}(X^{T}X)^{-1})$ - let me know if you need help deriving the distribution of $\widehat{\beta}$.
Additionally, $RSS \sim \sigma^{2}\chi^{2}_{n-p}$, where $n$ is the number of observations and $p$ is the number of parameters used in your regression. The proof of this is a bit more involved, but also straightforward to derive (see proof here Why is RSS distributed chi square times n-p?).
Up until this point I have considered everything in matrix/vector notation, but let's for simplicity use $\widehat{\beta}_{i}$ and use its normal distribution which will give us:
\begin{equation}
\frac{\widehat{\beta}_{i}-\beta_{i}}{\sigma\sqrt{(X^{T}X)^{-1}_{ii}}} \sim N(0,1)
\end{equation}
Additionally, from the chi-squared distribution of $RSS$ we have that:
\begin{equation}
\frac{(n-p)s^{2}}{\sigma^{2}} \sim \chi^{2}_{n-p}
\end{equation}
This was simply a rearrangement of the first chi-squared expression and is independent of the $N(0,1)$. Additionally, we define $s^{2}=\frac{RSS}{n-p}$, which is an unbiased estimator for $\sigma^{2}$. By the definition of the $t_{n-p}$ definition that dividing a normal distribution by an independent chi-squared (over its degrees of freedom) gives you a t-distribution (for the proof see: A normal divided by the $\sqrt{\chi^2(s)/s}$ gives you a t-distribution -- proof) you get that:
\begin{equation}
\frac{\widehat{\beta}_{i}-\beta_{i}}{s\sqrt{(X^{T}X)^{-1}_{ii}}} \sim t_{n-p}
\end{equation}
Where $s\sqrt{(X^{T}X)^{-1}_{ii}}=SE(\widehat{\beta}_{i})$.
Let me know if it makes sense.
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
To understand why we use the t-distribution, you need to know what is the underlying distribution of $\widehat{\beta}$ and of the Residual sum of squares ($RSS$) as these two put together will give yo
|
10,262
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
|
The answer is actually very simple: you use t-distribution because it was pretty much designed specifically for this purpose.
Ok, the nuance here is that it wasn't designed specifically for the linear regression. Gosset came up with distribution of sample that was drawn from the population. For instance, you draw a sample $x_1,x_2,\dots,x_n$, and calculate its mean $\bar x=\sum_{i=1}^n x_i/n$. What is the distribution of a sample mean $\bar x$?
If you knew the true (population) standard deviation $\sigma$, then you'd say that the variable $\xi=(\bar x-\mu)\sqrt n/\sigma$ is from the standard normal distribution $\mathcal N(0,1)$. The trouble's that you usually do not know $\sigma$, and can only estimate it $\hat\sigma$. So, Gosset figured out the distribution when you substitute $\sigma$ with $\hat\sigma$ in the denominator, and the distribution is now called after his pseduonym "Student t".
The technicalities of linear regression lead to a situation where we can estimate the standard error $\hat\sigma_\beta$ of the coefficient estimate $\hat\beta$, but we do not know the true $\sigma$, therefore Student t distribution is applied here too.
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
|
The answer is actually very simple: you use t-distribution because it was pretty much designed specifically for this purpose.
Ok, the nuance here is that it wasn't designed specifically for the linear
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
The answer is actually very simple: you use t-distribution because it was pretty much designed specifically for this purpose.
Ok, the nuance here is that it wasn't designed specifically for the linear regression. Gosset came up with distribution of sample that was drawn from the population. For instance, you draw a sample $x_1,x_2,\dots,x_n$, and calculate its mean $\bar x=\sum_{i=1}^n x_i/n$. What is the distribution of a sample mean $\bar x$?
If you knew the true (population) standard deviation $\sigma$, then you'd say that the variable $\xi=(\bar x-\mu)\sqrt n/\sigma$ is from the standard normal distribution $\mathcal N(0,1)$. The trouble's that you usually do not know $\sigma$, and can only estimate it $\hat\sigma$. So, Gosset figured out the distribution when you substitute $\sigma$ with $\hat\sigma$ in the denominator, and the distribution is now called after his pseduonym "Student t".
The technicalities of linear regression lead to a situation where we can estimate the standard error $\hat\sigma_\beta$ of the coefficient estimate $\hat\beta$, but we do not know the true $\sigma$, therefore Student t distribution is applied here too.
|
Why is a T distribution used for hypothesis testing a linear regression coefficient?
The answer is actually very simple: you use t-distribution because it was pretty much designed specifically for this purpose.
Ok, the nuance here is that it wasn't designed specifically for the linear
|
10,263
|
How to compare models on the basis of AIC?
|
One does not compare the absolute values of two AICs (which can be like $\sim 100$ but also $\sim 1000000$), but considers their difference:
$$\Delta_i=AIC_i-AIC_{\rm min},$$
where $AIC_i$ is the AIC of the $i$-th model, and $AIC_{\rm min}$ is the lowest AIC one obtains among the set of models examined (i.e., the prefered model). The rule of thumb, outlined e.g. in Burnham & Anderson 2004, is:
if $\Delta_i<2$, then there is substantial support for the $i$-th model (or the evidence against it is worth only a bare mention), and the proposition that it is a proper description is highly probable;
if $2<\Delta_i<4$, then there is strong support for the $i$-th model;
if $4<\Delta_i<7$, then there is considerably less support for the $i$-th model;
models with $\Delta_i>10$ have essentially no support.
Now, regarding the 0.7% mentioned in the question, consider two situations:
$AIC_1=AIC_{\rm min}=100$ and $AIC_2$ is bigger by 0.7%: $AIC_2=100.7$. Then $\Delta_2=0.7<2$ so there is no substantial difference between the models.
$AIC_1=AIC_{\rm min}=100000$ and $AIC_2$ is bigger by 0.7%: $AIC_2=100700$. Then $\Delta_2=700\gg 10$ so there is no support for the 2-nd model.
Hence, saying that the difference between AICs is 0.7% does not provide any information.
The AIC value contains scaling constants coming from the log-likelihood
$\mathcal{L}$, and so $\Delta_i$ are free of such constants. One
might consider $\Delta_i = AIC_i − AIC_{\rm min}$ a rescaling transformation that forces the best model to have $AIC_{\rm min} := 0$.
The formulation of AIC penalizes the use of an excessive number of parameters, hence discourages overfitting. It prefers models with fewer parameters, as long as the others do not provide a substantially better fit. AIC tries to select a model (among the examined ones) that most adequately describes reality (in the form of the data under examination). This means that in fact the model being a real description of the data is never considered. Note that AIC gives you the information which model describes the data better, it does not give any interpretation.
Personally, I would say that if you have a simple model and a complicated one that has a much lower AIC, then the simple model is not good enough. If the more complex model is really much more complicated but the $\Delta_i$ is not huge (maybe $\Delta_i<2$, maybe $\Delta_i<5$ - depends on the particular situation) I would stick to the simpler model if it's really easier to work with.
Further, you can ascribe a probability to the $i$-th model via
$$p_i=\exp\left(\frac{-\Delta_i}{2}\right),$$
which provides a relative (compared to $AIC_{\rm min}$) probability that the $i$-th models minimizes the AIC. For example, $\Delta_i=1.5$ corresponds to $p_i=0.47$ (quite high), and $\Delta_i=15$ corresponds to $p_i=0.0005$ (quite low). The first case means that there is 47% probability that the $i$-th model might in fact be a better description than the model that yielded $AIC_{\rm min}$, and in the second case this probability is only 0.05%.
Finally, regarding the formula for AIC:
$$AIC=2k-2\mathcal{L},$$
it is important to note that when two models with similar $\mathcal{L}$ are considered, the $\Delta_i$ depends solely on the number
of parameters due to the $2k$ term. Hence, when $\frac{\Delta_i}{2\Delta k} < 1$, the relative improvement is due to actual improvement of the fit, not to increasing the number of parameters only.
TL;DR
It's a bad reason; use the difference between the absolute values of the AICs.
The percentage says nothing.
Not possible to answer this question due to no information on the models, data, and what does different results mean.
|
How to compare models on the basis of AIC?
|
One does not compare the absolute values of two AICs (which can be like $\sim 100$ but also $\sim 1000000$), but considers their difference:
$$\Delta_i=AIC_i-AIC_{\rm min},$$
where $AIC_i$ is the AIC
|
How to compare models on the basis of AIC?
One does not compare the absolute values of two AICs (which can be like $\sim 100$ but also $\sim 1000000$), but considers their difference:
$$\Delta_i=AIC_i-AIC_{\rm min},$$
where $AIC_i$ is the AIC of the $i$-th model, and $AIC_{\rm min}$ is the lowest AIC one obtains among the set of models examined (i.e., the prefered model). The rule of thumb, outlined e.g. in Burnham & Anderson 2004, is:
if $\Delta_i<2$, then there is substantial support for the $i$-th model (or the evidence against it is worth only a bare mention), and the proposition that it is a proper description is highly probable;
if $2<\Delta_i<4$, then there is strong support for the $i$-th model;
if $4<\Delta_i<7$, then there is considerably less support for the $i$-th model;
models with $\Delta_i>10$ have essentially no support.
Now, regarding the 0.7% mentioned in the question, consider two situations:
$AIC_1=AIC_{\rm min}=100$ and $AIC_2$ is bigger by 0.7%: $AIC_2=100.7$. Then $\Delta_2=0.7<2$ so there is no substantial difference between the models.
$AIC_1=AIC_{\rm min}=100000$ and $AIC_2$ is bigger by 0.7%: $AIC_2=100700$. Then $\Delta_2=700\gg 10$ so there is no support for the 2-nd model.
Hence, saying that the difference between AICs is 0.7% does not provide any information.
The AIC value contains scaling constants coming from the log-likelihood
$\mathcal{L}$, and so $\Delta_i$ are free of such constants. One
might consider $\Delta_i = AIC_i − AIC_{\rm min}$ a rescaling transformation that forces the best model to have $AIC_{\rm min} := 0$.
The formulation of AIC penalizes the use of an excessive number of parameters, hence discourages overfitting. It prefers models with fewer parameters, as long as the others do not provide a substantially better fit. AIC tries to select a model (among the examined ones) that most adequately describes reality (in the form of the data under examination). This means that in fact the model being a real description of the data is never considered. Note that AIC gives you the information which model describes the data better, it does not give any interpretation.
Personally, I would say that if you have a simple model and a complicated one that has a much lower AIC, then the simple model is not good enough. If the more complex model is really much more complicated but the $\Delta_i$ is not huge (maybe $\Delta_i<2$, maybe $\Delta_i<5$ - depends on the particular situation) I would stick to the simpler model if it's really easier to work with.
Further, you can ascribe a probability to the $i$-th model via
$$p_i=\exp\left(\frac{-\Delta_i}{2}\right),$$
which provides a relative (compared to $AIC_{\rm min}$) probability that the $i$-th models minimizes the AIC. For example, $\Delta_i=1.5$ corresponds to $p_i=0.47$ (quite high), and $\Delta_i=15$ corresponds to $p_i=0.0005$ (quite low). The first case means that there is 47% probability that the $i$-th model might in fact be a better description than the model that yielded $AIC_{\rm min}$, and in the second case this probability is only 0.05%.
Finally, regarding the formula for AIC:
$$AIC=2k-2\mathcal{L},$$
it is important to note that when two models with similar $\mathcal{L}$ are considered, the $\Delta_i$ depends solely on the number
of parameters due to the $2k$ term. Hence, when $\frac{\Delta_i}{2\Delta k} < 1$, the relative improvement is due to actual improvement of the fit, not to increasing the number of parameters only.
TL;DR
It's a bad reason; use the difference between the absolute values of the AICs.
The percentage says nothing.
Not possible to answer this question due to no information on the models, data, and what does different results mean.
|
How to compare models on the basis of AIC?
One does not compare the absolute values of two AICs (which can be like $\sim 100$ but also $\sim 1000000$), but considers their difference:
$$\Delta_i=AIC_i-AIC_{\rm min},$$
where $AIC_i$ is the AIC
|
10,264
|
Construction of Dirichlet distribution with Gamma distribution
|
Jacobians--the absolute determinants of the change of variable function--appear formidable and can be complicated. Nevertheless, they are an essential and unavoidable part of the calculation of a multivariate change of variable. It would seem there's nothing for it but to write down a $k+1$ by $k+1$ matrix of derivatives and do the calculation.
There's a better way. It's shown at the end in the "Solution" section. Because the purpose of this post is to introduce statisticians to what may be a new method for many, much of it is devoted to explaining the machinery behind the solution. This is the algebra of differential forms. (Differential forms are the things that one integrates in multiple dimensions.) A detailed, worked example is included to help make this become more familiar.
Background
Over a century ago, mathematicians developed the theory of differential algebra to work with the "higher order derivatives" that occur in multi-dimensional geometry. The determinant is a special case of the basic objects manipulated by such algebras, which typically are alternating multilinear forms. The beauty of this lies in how simple the calculations can become.
Here's all you need to know.
A differential is an expression of the form "$dx_i$". It is the concatenation of "$d$" with any variable name.
A one-form is a linear combination of differentials, such as $dx_1+dx_2$ or even $x_2 dx_1 - \exp(x_2) dx_2$. That is, the coefficients are functions of the variables.
Forms can be "multiplied" using a wedge product, written $\wedge$. This product is anti-commutative (also called alternating): for any two one-forms $\omega$ and $\eta$,
$$\omega \wedge \eta = -\eta \wedge \omega.$$
This multiplication is linear and associative: in other words, it works in the familiar fashion. An immediate consequence is that $\omega \wedge \omega = -\omega \wedge \omega$, implying the square of any one-form is always zero. That makes multiplication extremely easy!
For the purposes of manipulating the integrands that appear in probability calculations, an expression like $dx_1 dx_2 \cdots dx_{k+1}$ can be understood as $|dx_1\wedge dx_2 \wedge \cdots \wedge dx_{k+1}|$.
When $y = g(x_1, \ldots, x_n)$ is a function, then its differential is given by differentiation:
$$dy = dg(x_1, \ldots, x_n) = \frac{\partial g}{\partial x_1}(x_1, \ldots, x_n) dx_1 + \cdots + \frac{\partial g}{\partial x_n}(x_1, \ldots, x_n) dx_n.$$
The connection with Jacobians is this: the Jacobian of a transformation $(y_1, \ldots, y_n) = F(x_1, \ldots, x_n) = (f_1(x_1, \ldots, x_n), \ldots, f_n(x_1, \ldots, x_n))$ is, up to sign, simply the coefficient of $dx_1\wedge \dots \wedge dx_n$ that appears in computing
$$dy_1 \wedge \cdots \wedge dy_n = df_1(x_1,\ldots, x_n)\wedge \cdots \wedge df_n(x_1, \ldots, x_n)$$
after expanding each of the $df_i$ as a linear combination of the $dx_j$ in rule (5).
Example
The simplicity of this definition of a Jacobian is appealing. Not yet convinced it's worthwhile? Consider the well-known problem of converting two-dimensional integrals from Cartesian coordinates $(x, y)$ to polar coordinates $(r,\theta)$, where $(x,y) = (r\cos(\theta), r\sin(\theta))$. The following is an utterly mechanical application of the preceding rules, where "$(*)$" is used to abbreviate expressions that will obviously disappear by virtue of rule (3), which implies $dr\wedge dr = d\theta\wedge d\theta = 0$.
$$\eqalign{
dx dy &= |dx\wedge dy| = |d(r\cos(\theta)) \wedge d(r\sin(\theta))| \\
&= |(\cos(\theta)dr - r\sin(\theta)d\theta) \wedge (\sin(\theta)dr + r\cos(\theta)d\theta| \\
&= |(*)dr\wedge dr + (*) d\theta\wedge d\theta - r\sin(\theta)d\theta\wedge \sin(\theta)dr + \cos(\theta)dr \wedge r\cos(\theta) d\theta| \\
&= |0 + 0 + r\sin^2(\theta) dr\wedge d\theta + r\cos^2(\theta) dr\wedge d\theta| \\
&= |r(\sin^2(\theta) + \cos^2(\theta)) dr\wedge d\theta)| \\
&= r\ dr d\theta
}.$$
The point of this is the ease with which such calculations can be performed, without messing about with matrices, determinants, or other such multi-indicial objects. You just multiply things out, remembering that wedges are anti-commutative. It's easier than what is taught in high school algebra.
Preliminaries
Let's see this differential algebra in action. In this problem, the PDF of the joint distribution of $(X_1, X_2, \ldots, X_{k+1})$ is the product of the individual PDFs (because the $X_i$ are assumed to be independent). In order to handle the change to the variables $Y_i$ we must be explicit about the differential elements that will be integrated. These form the term $dx_1 dx_2 \cdots dx_{k+1}$. Including the PDF gives the probability element
$$\eqalign{
f_\mathbf{X}(\mathbf{x},\mathbf{\alpha})dx_1 \cdots dx_{k+1} &\propto \left(x_1^{\alpha_1-1}\exp\left(-x_1\right)\right)\cdots \left(x_{k+1}^{\alpha_{k+1}-1}\exp\left(-x_{k+1}\right) \right)dx_1 \cdots dx_{k+1} \\
&= x_1^{\alpha_1-1}\cdots x_{k+1}^{\alpha_{k+1}-1}\exp\left(-\left(x_1+\cdots+x_{k+1}\right)\right)dx_1 \cdots dx_{k+1}.
}$$
(The normalizing constant has been ignored; it will be recovered at the end.)
Staring at the definitions of the $Y_i$ a few seconds ought to reveal the utility of introducing the new variable
$$Z = X_1 + X_2 + \cdots + X_{k+1},$$
giving the relationships
$$X_i = Y_i Z.$$
This suggests making the change of variables $x_i \to y_i z$ in the probability element. The intention is to retain the first $k$ variables $y_1, \ldots, y_k$ along with $z$ and then integrate out $z$. To do so, we have to re-express all the $dx_i$ in terms of the new variables. This is the heart of the problem. It's where the differential algebra takes place. To begin with,
$$dx_i = d(y_i z) = y_i dz + z dy_i.$$
Note that since $Y_1+Y_2+\cdots+Y_{k+1}=1$, then
$$0 = d(1) = d(y_1 + y_2 + \cdots + y_{k+1}) = dy_1 + dy_2 + \cdots + dy_{k+1}.$$
Consider the one-form
$$\omega = dx_1 + \cdots + dx_k = z(dy_1 + \cdots + dy_k) + (y_1+\cdots + y_k) dz.$$
It appears in the differential of the last variable:
$$\eqalign{
dx_{k+1} &= z dy_{k+1} + y_{k+1}dz \\
&= -z(dy_1 + \cdots + dy_k) + (1-y_1-\cdots -y_k)dz \\
&= dz - \omega.
}$$
The value of this lies in the observation that
$$dx_1 \wedge \cdots \wedge dx_k \wedge \omega = 0$$
because, when you expand this product, there is one term containing $dx_1 \wedge dx_1 = 0$ as a factor, another containing $dx_2 \wedge dx_2 = 0$, and so on: they all disappear. Consequently,
$$\eqalign{
dx_1 \wedge \cdots \wedge dx_k \wedge dx_{k+1} &= dx_1 \wedge \cdots \wedge dx_k \wedge dz - dx_1 \wedge \cdots \wedge dx_k \wedge \omega \\
&= dx_1 \wedge \cdots \wedge dx_k \wedge dz.
}$$
Whence (because all products $dz\wedge dz$ disappear),
$$\eqalign{
dx_1 \wedge \cdots \wedge dx_{k+1} &= (z dy_1 + y_1 dz) \wedge \cdots \wedge (z dy_k + y_k dz) \wedge dz \\
&= z^k dy_1 \wedge \cdots \wedge dy_k \wedge dz.
}$$
The Jacobian is simply $|z^k| = z^k$, the coefficient of the differential product on the right hand side.
Solution
The transformation $(x_1, \ldots, x_k, x_{k+1})\to (y_1, \ldots, y_k, z)$ is one-to-one: its inverse is given by $x_i = y_i z$ for $1\le i\le k$ and $x_{k+1} = z(1-y_1-\cdots-y_k)$. Therefore we don't have to fuss any more about the new probability element; it simply is
$$\eqalign{
&(z y_1)^{\alpha_1-1}\cdots (z y_k)^{\alpha_k-1}\left(z(1-y_1-\cdots-y_k)\right)^{\alpha_{k+1}-1}\exp\left(-z\right)|z^k dy_1 \wedge \cdots \wedge dy_k \wedge dz| \\
&= \left(z^{\alpha_1+\cdots+\alpha_{k+1}-1}\exp\left(-z\right) dz\right)\left( y_1^{\alpha_1-1} \cdots y_k^{\alpha_k-1}\left(1-y_1-\cdots-y_k\right)^{\alpha_{k+1}-1}dy_1 \cdots dy_k\right).
}$$
That is manifestly a product of a Gamma$(\alpha_1+\cdots+\alpha_{k+1})$ distribution (for $Z$) and a Dirichlet$(\mathbf\alpha)$ distribution (for $(Y_1,\ldots, Y_k)$). In fact, since the original normalizing constant must have been a product of $\Gamma(\alpha_i)$, we deduce immediately that the new normalizing constant must be divided by $\Gamma(\alpha_1+\cdots+\alpha_{k+1})$, enabling the PDF to be written
$$f_\mathbf{Y}(\mathbf{y},\mathbf{\alpha}) = \frac{\Gamma(\alpha_1+\cdots+\alpha_{k+1})}{\Gamma(\alpha_1)\cdots\Gamma(\alpha_{k+1})}\left( y_1^{\alpha_1-1} \cdots y_k^{\alpha_k-1}\left(1-y_1-\cdots-y_k\right)^{\alpha_{k+1}-1}\right).$$
|
Construction of Dirichlet distribution with Gamma distribution
|
Jacobians--the absolute determinants of the change of variable function--appear formidable and can be complicated. Nevertheless, they are an essential and unavoidable part of the calculation of a mul
|
Construction of Dirichlet distribution with Gamma distribution
Jacobians--the absolute determinants of the change of variable function--appear formidable and can be complicated. Nevertheless, they are an essential and unavoidable part of the calculation of a multivariate change of variable. It would seem there's nothing for it but to write down a $k+1$ by $k+1$ matrix of derivatives and do the calculation.
There's a better way. It's shown at the end in the "Solution" section. Because the purpose of this post is to introduce statisticians to what may be a new method for many, much of it is devoted to explaining the machinery behind the solution. This is the algebra of differential forms. (Differential forms are the things that one integrates in multiple dimensions.) A detailed, worked example is included to help make this become more familiar.
Background
Over a century ago, mathematicians developed the theory of differential algebra to work with the "higher order derivatives" that occur in multi-dimensional geometry. The determinant is a special case of the basic objects manipulated by such algebras, which typically are alternating multilinear forms. The beauty of this lies in how simple the calculations can become.
Here's all you need to know.
A differential is an expression of the form "$dx_i$". It is the concatenation of "$d$" with any variable name.
A one-form is a linear combination of differentials, such as $dx_1+dx_2$ or even $x_2 dx_1 - \exp(x_2) dx_2$. That is, the coefficients are functions of the variables.
Forms can be "multiplied" using a wedge product, written $\wedge$. This product is anti-commutative (also called alternating): for any two one-forms $\omega$ and $\eta$,
$$\omega \wedge \eta = -\eta \wedge \omega.$$
This multiplication is linear and associative: in other words, it works in the familiar fashion. An immediate consequence is that $\omega \wedge \omega = -\omega \wedge \omega$, implying the square of any one-form is always zero. That makes multiplication extremely easy!
For the purposes of manipulating the integrands that appear in probability calculations, an expression like $dx_1 dx_2 \cdots dx_{k+1}$ can be understood as $|dx_1\wedge dx_2 \wedge \cdots \wedge dx_{k+1}|$.
When $y = g(x_1, \ldots, x_n)$ is a function, then its differential is given by differentiation:
$$dy = dg(x_1, \ldots, x_n) = \frac{\partial g}{\partial x_1}(x_1, \ldots, x_n) dx_1 + \cdots + \frac{\partial g}{\partial x_n}(x_1, \ldots, x_n) dx_n.$$
The connection with Jacobians is this: the Jacobian of a transformation $(y_1, \ldots, y_n) = F(x_1, \ldots, x_n) = (f_1(x_1, \ldots, x_n), \ldots, f_n(x_1, \ldots, x_n))$ is, up to sign, simply the coefficient of $dx_1\wedge \dots \wedge dx_n$ that appears in computing
$$dy_1 \wedge \cdots \wedge dy_n = df_1(x_1,\ldots, x_n)\wedge \cdots \wedge df_n(x_1, \ldots, x_n)$$
after expanding each of the $df_i$ as a linear combination of the $dx_j$ in rule (5).
Example
The simplicity of this definition of a Jacobian is appealing. Not yet convinced it's worthwhile? Consider the well-known problem of converting two-dimensional integrals from Cartesian coordinates $(x, y)$ to polar coordinates $(r,\theta)$, where $(x,y) = (r\cos(\theta), r\sin(\theta))$. The following is an utterly mechanical application of the preceding rules, where "$(*)$" is used to abbreviate expressions that will obviously disappear by virtue of rule (3), which implies $dr\wedge dr = d\theta\wedge d\theta = 0$.
$$\eqalign{
dx dy &= |dx\wedge dy| = |d(r\cos(\theta)) \wedge d(r\sin(\theta))| \\
&= |(\cos(\theta)dr - r\sin(\theta)d\theta) \wedge (\sin(\theta)dr + r\cos(\theta)d\theta| \\
&= |(*)dr\wedge dr + (*) d\theta\wedge d\theta - r\sin(\theta)d\theta\wedge \sin(\theta)dr + \cos(\theta)dr \wedge r\cos(\theta) d\theta| \\
&= |0 + 0 + r\sin^2(\theta) dr\wedge d\theta + r\cos^2(\theta) dr\wedge d\theta| \\
&= |r(\sin^2(\theta) + \cos^2(\theta)) dr\wedge d\theta)| \\
&= r\ dr d\theta
}.$$
The point of this is the ease with which such calculations can be performed, without messing about with matrices, determinants, or other such multi-indicial objects. You just multiply things out, remembering that wedges are anti-commutative. It's easier than what is taught in high school algebra.
Preliminaries
Let's see this differential algebra in action. In this problem, the PDF of the joint distribution of $(X_1, X_2, \ldots, X_{k+1})$ is the product of the individual PDFs (because the $X_i$ are assumed to be independent). In order to handle the change to the variables $Y_i$ we must be explicit about the differential elements that will be integrated. These form the term $dx_1 dx_2 \cdots dx_{k+1}$. Including the PDF gives the probability element
$$\eqalign{
f_\mathbf{X}(\mathbf{x},\mathbf{\alpha})dx_1 \cdots dx_{k+1} &\propto \left(x_1^{\alpha_1-1}\exp\left(-x_1\right)\right)\cdots \left(x_{k+1}^{\alpha_{k+1}-1}\exp\left(-x_{k+1}\right) \right)dx_1 \cdots dx_{k+1} \\
&= x_1^{\alpha_1-1}\cdots x_{k+1}^{\alpha_{k+1}-1}\exp\left(-\left(x_1+\cdots+x_{k+1}\right)\right)dx_1 \cdots dx_{k+1}.
}$$
(The normalizing constant has been ignored; it will be recovered at the end.)
Staring at the definitions of the $Y_i$ a few seconds ought to reveal the utility of introducing the new variable
$$Z = X_1 + X_2 + \cdots + X_{k+1},$$
giving the relationships
$$X_i = Y_i Z.$$
This suggests making the change of variables $x_i \to y_i z$ in the probability element. The intention is to retain the first $k$ variables $y_1, \ldots, y_k$ along with $z$ and then integrate out $z$. To do so, we have to re-express all the $dx_i$ in terms of the new variables. This is the heart of the problem. It's where the differential algebra takes place. To begin with,
$$dx_i = d(y_i z) = y_i dz + z dy_i.$$
Note that since $Y_1+Y_2+\cdots+Y_{k+1}=1$, then
$$0 = d(1) = d(y_1 + y_2 + \cdots + y_{k+1}) = dy_1 + dy_2 + \cdots + dy_{k+1}.$$
Consider the one-form
$$\omega = dx_1 + \cdots + dx_k = z(dy_1 + \cdots + dy_k) + (y_1+\cdots + y_k) dz.$$
It appears in the differential of the last variable:
$$\eqalign{
dx_{k+1} &= z dy_{k+1} + y_{k+1}dz \\
&= -z(dy_1 + \cdots + dy_k) + (1-y_1-\cdots -y_k)dz \\
&= dz - \omega.
}$$
The value of this lies in the observation that
$$dx_1 \wedge \cdots \wedge dx_k \wedge \omega = 0$$
because, when you expand this product, there is one term containing $dx_1 \wedge dx_1 = 0$ as a factor, another containing $dx_2 \wedge dx_2 = 0$, and so on: they all disappear. Consequently,
$$\eqalign{
dx_1 \wedge \cdots \wedge dx_k \wedge dx_{k+1} &= dx_1 \wedge \cdots \wedge dx_k \wedge dz - dx_1 \wedge \cdots \wedge dx_k \wedge \omega \\
&= dx_1 \wedge \cdots \wedge dx_k \wedge dz.
}$$
Whence (because all products $dz\wedge dz$ disappear),
$$\eqalign{
dx_1 \wedge \cdots \wedge dx_{k+1} &= (z dy_1 + y_1 dz) \wedge \cdots \wedge (z dy_k + y_k dz) \wedge dz \\
&= z^k dy_1 \wedge \cdots \wedge dy_k \wedge dz.
}$$
The Jacobian is simply $|z^k| = z^k$, the coefficient of the differential product on the right hand side.
Solution
The transformation $(x_1, \ldots, x_k, x_{k+1})\to (y_1, \ldots, y_k, z)$ is one-to-one: its inverse is given by $x_i = y_i z$ for $1\le i\le k$ and $x_{k+1} = z(1-y_1-\cdots-y_k)$. Therefore we don't have to fuss any more about the new probability element; it simply is
$$\eqalign{
&(z y_1)^{\alpha_1-1}\cdots (z y_k)^{\alpha_k-1}\left(z(1-y_1-\cdots-y_k)\right)^{\alpha_{k+1}-1}\exp\left(-z\right)|z^k dy_1 \wedge \cdots \wedge dy_k \wedge dz| \\
&= \left(z^{\alpha_1+\cdots+\alpha_{k+1}-1}\exp\left(-z\right) dz\right)\left( y_1^{\alpha_1-1} \cdots y_k^{\alpha_k-1}\left(1-y_1-\cdots-y_k\right)^{\alpha_{k+1}-1}dy_1 \cdots dy_k\right).
}$$
That is manifestly a product of a Gamma$(\alpha_1+\cdots+\alpha_{k+1})$ distribution (for $Z$) and a Dirichlet$(\mathbf\alpha)$ distribution (for $(Y_1,\ldots, Y_k)$). In fact, since the original normalizing constant must have been a product of $\Gamma(\alpha_i)$, we deduce immediately that the new normalizing constant must be divided by $\Gamma(\alpha_1+\cdots+\alpha_{k+1})$, enabling the PDF to be written
$$f_\mathbf{Y}(\mathbf{y},\mathbf{\alpha}) = \frac{\Gamma(\alpha_1+\cdots+\alpha_{k+1})}{\Gamma(\alpha_1)\cdots\Gamma(\alpha_{k+1})}\left( y_1^{\alpha_1-1} \cdots y_k^{\alpha_k-1}\left(1-y_1-\cdots-y_k\right)^{\alpha_{k+1}-1}\right).$$
|
Construction of Dirichlet distribution with Gamma distribution
Jacobians--the absolute determinants of the change of variable function--appear formidable and can be complicated. Nevertheless, they are an essential and unavoidable part of the calculation of a mul
|
10,265
|
Caret and coefficients (glmnet)
|
Lets say your caret model is called "model". You can access the final glmnet model with model$finalModel. You can then call coef(model$finalModel), etc. You will have to select a value of lambda for which you want coefficients, such as coef(model$finalModel, model$bestTune$.lambda).
Take a look at the summaryFunction parameter for the trainControl function. It will allow you to specify any function you want to minimize (or maximize, see the maximize argument to train), given a predictor and a response.
It might be hard to get at adjusted R^2 in this way, but you could probably get R^2 or something similar.
|
Caret and coefficients (glmnet)
|
Lets say your caret model is called "model". You can access the final glmnet model with model$finalModel. You can then call coef(model$finalModel), etc. You will have to select a value of lambda for
|
Caret and coefficients (glmnet)
Lets say your caret model is called "model". You can access the final glmnet model with model$finalModel. You can then call coef(model$finalModel), etc. You will have to select a value of lambda for which you want coefficients, such as coef(model$finalModel, model$bestTune$.lambda).
Take a look at the summaryFunction parameter for the trainControl function. It will allow you to specify any function you want to minimize (or maximize, see the maximize argument to train), given a predictor and a response.
It might be hard to get at adjusted R^2 in this way, but you could probably get R^2 or something similar.
|
Caret and coefficients (glmnet)
Lets say your caret model is called "model". You can access the final glmnet model with model$finalModel. You can then call coef(model$finalModel), etc. You will have to select a value of lambda for
|
10,266
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
Roughly speaking, the difference between $E(X \mid Y)$ and $E(X \mid Y = y)$ is that the former is a random variable, whereas the latter is (in some sense) a realization of $E(X \mid Y)$. For example, if $$(X, Y) \sim \mathcal N\left(\mathbf 0, \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix}\right)$$
then $E(X \mid Y)$ is the random variable
$$
E(X \mid Y) = \rho Y.
$$
Conversely, once $Y = y$ is observed, we would more likely be interested in the quantity $E(X \mid Y = y) = \rho y$ which is a scalar.
Maybe this seems like needless complication, but regarding $E(X \mid Y)$ as a random variable in its own right is what makes things like the tower-law $E(X) = E[E(X \mid Y)]$ make sense - the thing on the inside of the braces is random, so we can ask what its expectation is, whereas there is nothing random about $E(X \mid Y = y)$. In most cases we might hope to calculate
$$
E(X \mid Y = y) = \int x f_{X\mid Y}(x \mid y) \ dx
$$
and then get $E(X \mid Y)$ by "plugging in" the random variable $Y$ in place of $y$ in the resulting expression. As hinted in an earlier comment, there is a bit of subtlety that can creep in with regards to how these things are rigorously defined and linking them up in the appropriate way. This tends to happen with conditional probability, due to some technical issues with the underlying theory.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
Roughly speaking, the difference between $E(X \mid Y)$ and $E(X \mid Y = y)$ is that the former is a random variable, whereas the latter is (in some sense) a realization of $E(X \mid Y)$. For example,
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
Roughly speaking, the difference between $E(X \mid Y)$ and $E(X \mid Y = y)$ is that the former is a random variable, whereas the latter is (in some sense) a realization of $E(X \mid Y)$. For example, if $$(X, Y) \sim \mathcal N\left(\mathbf 0, \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix}\right)$$
then $E(X \mid Y)$ is the random variable
$$
E(X \mid Y) = \rho Y.
$$
Conversely, once $Y = y$ is observed, we would more likely be interested in the quantity $E(X \mid Y = y) = \rho y$ which is a scalar.
Maybe this seems like needless complication, but regarding $E(X \mid Y)$ as a random variable in its own right is what makes things like the tower-law $E(X) = E[E(X \mid Y)]$ make sense - the thing on the inside of the braces is random, so we can ask what its expectation is, whereas there is nothing random about $E(X \mid Y = y)$. In most cases we might hope to calculate
$$
E(X \mid Y = y) = \int x f_{X\mid Y}(x \mid y) \ dx
$$
and then get $E(X \mid Y)$ by "plugging in" the random variable $Y$ in place of $y$ in the resulting expression. As hinted in an earlier comment, there is a bit of subtlety that can creep in with regards to how these things are rigorously defined and linking them up in the appropriate way. This tends to happen with conditional probability, due to some technical issues with the underlying theory.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
Roughly speaking, the difference between $E(X \mid Y)$ and $E(X \mid Y = y)$ is that the former is a random variable, whereas the latter is (in some sense) a realization of $E(X \mid Y)$. For example,
|
10,267
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
Suppose that $X$ and $Y$ are random variables.
Let $y_0$ be a fixed real number, say $y_0 = 1$. Then,
$E[X\mid Y=y_0]= E[X\mid Y = 1]$ is a
number: it is the conditional expected value of $X$ given that $Y$ has
value $1$. Now, note for some other fixed real number $y_1$, say $y_1=1.5$, $E[X\mid Y = y_1] = E[X\mid Y = 1.5]$ would be the conditional expected value of
$X$ given $Y = 1.5$ (a real number). There is no reason to suppose
that $E[X\mid Y = 1.5]$ and $E[X\mid Y = 1]$ have the same value. Thus,
we can also regard $E[X\mid Y=y]$ as being a real-valued function $g(y)$
that maps real numbers $y$ to real numbers $E[X\mid Y = y]$. Note that
the statement in the OP's question that $E[X\mid Y = y]$ is a function of
$x$ is incorrect: $E[X\mid Y = y]$ is a real-valued function of $y$.
On the other hand, $E[X\mid Y]$ is a random variable $Z$ which
happens to be a function of the random variable $Y$. Now, whenever
we write $Z = h(Y)$, what we mean is that whenever the random variable
$Y$ happens to have value $y$, the random variable $Z$ has value
$h(y)$. Whenever $Y$ takes on value $y$, the random variable
$Z = E[X\mid Y]$ takes on value $E[X\mid Y = y] = g(y)$.
Thus, $E[X\mid Y]$ is just another name for the random
variable $Z = g(Y)$. Note that $E[X\mid Y]$ is a function of $Y$
(not $y$ as in the statement of the OP's question).
As a a simple illustrative
example, suppose that
$X$ and $Y$ are discrete random variables with joint distribution
\begin{align}
P(X=0,Y=0) &= 0.1,~~ P(X=0, Y=1) = 0.2,\\
P(X=1,Y=0) &= 0.3,~~ P(X=1,Y=1) = 0.4.
\end{align}
Note that $X$ and $Y$ are (dependent) Bernoulli random variables
with parameters $0.7$ and $0.6$ respectively, and so $E[X] = 0.7$
and $E[Y] = 0.6$.
Now, note that conditioned on $Y=0$, $X$ is a Bernoulli random variable
with parameter $0.75$ while conditioned on $Y = 1$, $X$ is a Bernoulli
random variable with parameter $\frac 23$. If you cannot see why this is
so immediately, just work out the details: for example
$$P(X=1\mid Y = 0) = \frac{P(X=1, Y=0)}{P(Y=0)} = \frac{0.3}{0.4} = \frac 34,\\
P(X=0\mid Y = 0) = \frac{P(X=0, Y=0)}{P(Y=0)} = \frac{0.1}{0.4} = \frac 14,$$
and similarly for $P(X=1\mid Y=1)$ and $P(X=0\mid Y = 1)$.
Hence, we have that
$$E[X\mid Y = 0] = \frac 34, \quad E[X \mid Y = 1] = \frac 23.$$
Thus, $E[X\mid Y = y] = g(y)$ where $g(y)$ is a real-valued function
enjoying the
properties: $$g(0) = \frac 34, \quad g(1) = \frac 23.$$
On the other hand, $E[X\mid Y] = g(Y)$ is a random variable
that takes on values $\frac 34$ and $\frac 23$ with
probabilities $0.4 = P(Y=0)$ and $0.6 = P(Y=1)$ respectively.
Note that $E[X\mid Y]$ is a discrete random variable
but is not a Bernoulli random variable.
As a final touch, note that
$$E[Z] = E\left[E[X\mid Y]\right] = E[g(Y)] =
0.4\times \frac 34 + 0.6\times \frac 23 = 0.7 = E[X].$$
That is, the expected value of this function of $Y$, which
we computed using only the marginal distribution of $Y$,
happens to have the same numerical value as $E[X]$ !! This
is an illustration of a more general result that many
people believe is a LIE:
$$E\left[E[X\mid Y]\right] = E[X].$$
Sorry, that's just a small joke. LIE is an acronym for Law of Iterated
Expectation which is a perfectly valid result that everyone
believes is the truth.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
Suppose that $X$ and $Y$ are random variables.
Let $y_0$ be a fixed real number, say $y_0 = 1$. Then,
$E[X\mid Y=y_0]= E[X\mid Y = 1]$ is a
number: it is the conditional expected value of $X$ given
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
Suppose that $X$ and $Y$ are random variables.
Let $y_0$ be a fixed real number, say $y_0 = 1$. Then,
$E[X\mid Y=y_0]= E[X\mid Y = 1]$ is a
number: it is the conditional expected value of $X$ given that $Y$ has
value $1$. Now, note for some other fixed real number $y_1$, say $y_1=1.5$, $E[X\mid Y = y_1] = E[X\mid Y = 1.5]$ would be the conditional expected value of
$X$ given $Y = 1.5$ (a real number). There is no reason to suppose
that $E[X\mid Y = 1.5]$ and $E[X\mid Y = 1]$ have the same value. Thus,
we can also regard $E[X\mid Y=y]$ as being a real-valued function $g(y)$
that maps real numbers $y$ to real numbers $E[X\mid Y = y]$. Note that
the statement in the OP's question that $E[X\mid Y = y]$ is a function of
$x$ is incorrect: $E[X\mid Y = y]$ is a real-valued function of $y$.
On the other hand, $E[X\mid Y]$ is a random variable $Z$ which
happens to be a function of the random variable $Y$. Now, whenever
we write $Z = h(Y)$, what we mean is that whenever the random variable
$Y$ happens to have value $y$, the random variable $Z$ has value
$h(y)$. Whenever $Y$ takes on value $y$, the random variable
$Z = E[X\mid Y]$ takes on value $E[X\mid Y = y] = g(y)$.
Thus, $E[X\mid Y]$ is just another name for the random
variable $Z = g(Y)$. Note that $E[X\mid Y]$ is a function of $Y$
(not $y$ as in the statement of the OP's question).
As a a simple illustrative
example, suppose that
$X$ and $Y$ are discrete random variables with joint distribution
\begin{align}
P(X=0,Y=0) &= 0.1,~~ P(X=0, Y=1) = 0.2,\\
P(X=1,Y=0) &= 0.3,~~ P(X=1,Y=1) = 0.4.
\end{align}
Note that $X$ and $Y$ are (dependent) Bernoulli random variables
with parameters $0.7$ and $0.6$ respectively, and so $E[X] = 0.7$
and $E[Y] = 0.6$.
Now, note that conditioned on $Y=0$, $X$ is a Bernoulli random variable
with parameter $0.75$ while conditioned on $Y = 1$, $X$ is a Bernoulli
random variable with parameter $\frac 23$. If you cannot see why this is
so immediately, just work out the details: for example
$$P(X=1\mid Y = 0) = \frac{P(X=1, Y=0)}{P(Y=0)} = \frac{0.3}{0.4} = \frac 34,\\
P(X=0\mid Y = 0) = \frac{P(X=0, Y=0)}{P(Y=0)} = \frac{0.1}{0.4} = \frac 14,$$
and similarly for $P(X=1\mid Y=1)$ and $P(X=0\mid Y = 1)$.
Hence, we have that
$$E[X\mid Y = 0] = \frac 34, \quad E[X \mid Y = 1] = \frac 23.$$
Thus, $E[X\mid Y = y] = g(y)$ where $g(y)$ is a real-valued function
enjoying the
properties: $$g(0) = \frac 34, \quad g(1) = \frac 23.$$
On the other hand, $E[X\mid Y] = g(Y)$ is a random variable
that takes on values $\frac 34$ and $\frac 23$ with
probabilities $0.4 = P(Y=0)$ and $0.6 = P(Y=1)$ respectively.
Note that $E[X\mid Y]$ is a discrete random variable
but is not a Bernoulli random variable.
As a final touch, note that
$$E[Z] = E\left[E[X\mid Y]\right] = E[g(Y)] =
0.4\times \frac 34 + 0.6\times \frac 23 = 0.7 = E[X].$$
That is, the expected value of this function of $Y$, which
we computed using only the marginal distribution of $Y$,
happens to have the same numerical value as $E[X]$ !! This
is an illustration of a more general result that many
people believe is a LIE:
$$E\left[E[X\mid Y]\right] = E[X].$$
Sorry, that's just a small joke. LIE is an acronym for Law of Iterated
Expectation which is a perfectly valid result that everyone
believes is the truth.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
Suppose that $X$ and $Y$ are random variables.
Let $y_0$ be a fixed real number, say $y_0 = 1$. Then,
$E[X\mid Y=y_0]= E[X\mid Y = 1]$ is a
number: it is the conditional expected value of $X$ given
|
10,268
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
$E(X|Y)$ is the expectation of a random variable: the expectation of $X$ conditional on $Y$.
$E(X|Y=y)$, on the other hand, is a particular value: the expected value of $X$ when $Y=y$.
Think of it this way: let $X$ represent the caloric intake and $Y$ represent height. $E(X|Y)$ is then the caloric intake, conditional on height - and in this case, $E(X|Y=y)$ represents our best guess at the caloric intake ($X$) when a person has a certain height $Y = y$, say, 180 centimeters.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
$E(X|Y)$ is the expectation of a random variable: the expectation of $X$ conditional on $Y$.
$E(X|Y=y)$, on the other hand, is a particular value: the expected value of $X$ when $Y=y$.
Think of it thi
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
$E(X|Y)$ is the expectation of a random variable: the expectation of $X$ conditional on $Y$.
$E(X|Y=y)$, on the other hand, is a particular value: the expected value of $X$ when $Y=y$.
Think of it this way: let $X$ represent the caloric intake and $Y$ represent height. $E(X|Y)$ is then the caloric intake, conditional on height - and in this case, $E(X|Y=y)$ represents our best guess at the caloric intake ($X$) when a person has a certain height $Y = y$, say, 180 centimeters.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
$E(X|Y)$ is the expectation of a random variable: the expectation of $X$ conditional on $Y$.
$E(X|Y=y)$, on the other hand, is a particular value: the expected value of $X$ when $Y=y$.
Think of it thi
|
10,269
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
$E(X|Y)$ is expected value of values of $X$ given values of $Y$
$E(X|Y=y)$ is expected value of $X$ given the value of $Y$ is $y$
Generally $P(X|Y)$ is probability of values $X$ given values $Y$, but you can get more precise and say $P(X=x|Y=y)$, i.e. probability of value $x$ from all $X$'s given the $y$'th value of $Y$'s. The difference is that in the first case it is about "values of" and in the second you consider a certain value.
You could find the diagram below helpful.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
|
$E(X|Y)$ is expected value of values of $X$ given values of $Y$
$E(X|Y=y)$ is expected value of $X$ given the value of $Y$ is $y$
Generally $P(X|Y)$ is probability of values $X$ given values $Y$, but
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
$E(X|Y)$ is expected value of values of $X$ given values of $Y$
$E(X|Y=y)$ is expected value of $X$ given the value of $Y$ is $y$
Generally $P(X|Y)$ is probability of values $X$ given values $Y$, but you can get more precise and say $P(X=x|Y=y)$, i.e. probability of value $x$ from all $X$'s given the $y$'th value of $Y$'s. The difference is that in the first case it is about "values of" and in the second you consider a certain value.
You could find the diagram below helpful.
|
What is the difference between $E(X|Y)$ and $E(X|Y=y)$?
$E(X|Y)$ is expected value of values of $X$ given values of $Y$
$E(X|Y=y)$ is expected value of $X$ given the value of $Y$ is $y$
Generally $P(X|Y)$ is probability of values $X$ given values $Y$, but
|
10,270
|
Symbolic computation in R?
|
Yes. There is the Ryacas package which is hosted on Google Code here. Ryacas has recently been expanded/converted to the rMathpiper package which is hosted here. I have used Ryacas and it is straightforward, but you will need to install Yacas in order for it to work (Yacas does all the heavy lifting; Ryacas is just an R interface to Yacas).
There is also the rSymPy project hosted on Google Code here. I haven't tried this one. The idea is similar, though, link to the sympy CAS which does the symbolic work.
|
Symbolic computation in R?
|
Yes. There is the Ryacas package which is hosted on Google Code here. Ryacas has recently been expanded/converted to the rMathpiper package which is hosted here. I have used Ryacas and it is straig
|
Symbolic computation in R?
Yes. There is the Ryacas package which is hosted on Google Code here. Ryacas has recently been expanded/converted to the rMathpiper package which is hosted here. I have used Ryacas and it is straightforward, but you will need to install Yacas in order for it to work (Yacas does all the heavy lifting; Ryacas is just an R interface to Yacas).
There is also the rSymPy project hosted on Google Code here. I haven't tried this one. The idea is similar, though, link to the sympy CAS which does the symbolic work.
|
Symbolic computation in R?
Yes. There is the Ryacas package which is hosted on Google Code here. Ryacas has recently been expanded/converted to the rMathpiper package which is hosted here. I have used Ryacas and it is straig
|
10,271
|
Symbolic computation in R?
|
Some things are also in base R --- see help(deriv) or help(D).
A simple example from that help page:
R> trig.exp <- expression(sin(cos(x + y^2)))
R> ( D.sc <- D(trig.exp, "x") )
-(cos(cos(x + y^2)) * sin(x + y^2))
R> all.equal(D(trig.exp[[1]], "x"), D.sc)
[1] TRUE
R>
|
Symbolic computation in R?
|
Some things are also in base R --- see help(deriv) or help(D).
A simple example from that help page:
R> trig.exp <- expression(sin(cos(x + y^2)))
R> ( D.sc <- D(trig.exp, "x") )
-(cos(cos(x + y^2))
|
Symbolic computation in R?
Some things are also in base R --- see help(deriv) or help(D).
A simple example from that help page:
R> trig.exp <- expression(sin(cos(x + y^2)))
R> ( D.sc <- D(trig.exp, "x") )
-(cos(cos(x + y^2)) * sin(x + y^2))
R> all.equal(D(trig.exp[[1]], "x"), D.sc)
[1] TRUE
R>
|
Symbolic computation in R?
Some things are also in base R --- see help(deriv) or help(D).
A simple example from that help page:
R> trig.exp <- expression(sin(cos(x + y^2)))
R> ( D.sc <- D(trig.exp, "x") )
-(cos(cos(x + y^2))
|
10,272
|
Symbolic computation in R?
|
It makes more sense to use a "real" CAS like Maxima.
|
Symbolic computation in R?
|
It makes more sense to use a "real" CAS like Maxima.
|
Symbolic computation in R?
It makes more sense to use a "real" CAS like Maxima.
|
Symbolic computation in R?
It makes more sense to use a "real" CAS like Maxima.
|
10,273
|
Is there any intuitive explanation of why logistic regression will not work for perfect separation case? And why adding regularization will fix it?
|
A 2D demo with toy data will be used to explain what was happening for perfect separation on logistic regression with and without regularization. The experiments started with an overlapping data set and we gradually move two classes apart. The objective function contour and optima (logistic loss) will be shown in the right sub figure. The data and the linear decision boundary are plotted in left sub figure.
First we try the logistic regression without regularization.
As we can see with the data moving apart, the objective function (logistic loss) is changing dramatically, and the optim is moving away to a larger value.
When we have completed the operation, the contour will not be a "closed shape". At this time, the objective function will always be smaller when the solution moves to upper right comer.
Next we try logistic regression with L2 regularization (L1 is similar).
With the same setup, adding a very small L2 regularization will change the objective function with respect to the separation of the data.
In this case, we will always have the "convex" objective. No matter how much separation the data has.
code (I also use same code for this answer: Regularization methods for logistic regression)
set.seed(0)
d=mlbench::mlbench.2dnormals(100, 2, r=1)
x = d$x
y = ifelse(d$classes==1, 1, 0)
logistic_loss <- function(w){
p = plogis(x %*% w)
L = -y*log(p) - (1-y)*log(1-p)
LwR2 = sum(L) + lambda*t(w) %*% w
return(c(LwR2))
}
logistic_loss_gr <- function(w){
p = plogis(x %*% w)
v = t(x) %*% (p - y)
return(c(v) + 2*lambda*w)
}
w_grid_v = seq(-10, 10, 0.1)
w_grid = expand.grid(w_grid_v, w_grid_v)
lambda = 0
opt1 = optimx::optimx(c(1,1), fn=logistic_loss, gr=logistic_loss_gr, method="BFGS")
z1 = matrix(apply(w_grid,1,logistic_loss), ncol=length(w_grid_v))
lambda = 5
opt2 = optimx::optimx(c(1,1), fn=logistic_loss, method="BFGS")
z2 = matrix(apply(w_grid,1,logistic_loss), ncol=length(w_grid_v))
plot(d, xlim=c(-3,3), ylim=c(-3,3))
abline(0, -opt1$p2/opt1$p1, col='blue', lwd=2)
abline(0, -opt2$p2/opt2$p1, col='black', lwd=2)
contour(w_grid_v, w_grid_v, z1, col='blue', lwd=2, nlevels=8)
contour(w_grid_v, w_grid_v, z2, col='black', lwd=2, nlevels=8, add=T)
points(opt1$p1, opt1$p2, col='blue', pch=19)
points(opt2$p1, opt2$p2, col='black', pch=19)
|
Is there any intuitive explanation of why logistic regression will not work for perfect separation c
|
A 2D demo with toy data will be used to explain what was happening for perfect separation on logistic regression with and without regularization. The experiments started with an overlapping data set a
|
Is there any intuitive explanation of why logistic regression will not work for perfect separation case? And why adding regularization will fix it?
A 2D demo with toy data will be used to explain what was happening for perfect separation on logistic regression with and without regularization. The experiments started with an overlapping data set and we gradually move two classes apart. The objective function contour and optima (logistic loss) will be shown in the right sub figure. The data and the linear decision boundary are plotted in left sub figure.
First we try the logistic regression without regularization.
As we can see with the data moving apart, the objective function (logistic loss) is changing dramatically, and the optim is moving away to a larger value.
When we have completed the operation, the contour will not be a "closed shape". At this time, the objective function will always be smaller when the solution moves to upper right comer.
Next we try logistic regression with L2 regularization (L1 is similar).
With the same setup, adding a very small L2 regularization will change the objective function with respect to the separation of the data.
In this case, we will always have the "convex" objective. No matter how much separation the data has.
code (I also use same code for this answer: Regularization methods for logistic regression)
set.seed(0)
d=mlbench::mlbench.2dnormals(100, 2, r=1)
x = d$x
y = ifelse(d$classes==1, 1, 0)
logistic_loss <- function(w){
p = plogis(x %*% w)
L = -y*log(p) - (1-y)*log(1-p)
LwR2 = sum(L) + lambda*t(w) %*% w
return(c(LwR2))
}
logistic_loss_gr <- function(w){
p = plogis(x %*% w)
v = t(x) %*% (p - y)
return(c(v) + 2*lambda*w)
}
w_grid_v = seq(-10, 10, 0.1)
w_grid = expand.grid(w_grid_v, w_grid_v)
lambda = 0
opt1 = optimx::optimx(c(1,1), fn=logistic_loss, gr=logistic_loss_gr, method="BFGS")
z1 = matrix(apply(w_grid,1,logistic_loss), ncol=length(w_grid_v))
lambda = 5
opt2 = optimx::optimx(c(1,1), fn=logistic_loss, method="BFGS")
z2 = matrix(apply(w_grid,1,logistic_loss), ncol=length(w_grid_v))
plot(d, xlim=c(-3,3), ylim=c(-3,3))
abline(0, -opt1$p2/opt1$p1, col='blue', lwd=2)
abline(0, -opt2$p2/opt2$p1, col='black', lwd=2)
contour(w_grid_v, w_grid_v, z1, col='blue', lwd=2, nlevels=8)
contour(w_grid_v, w_grid_v, z2, col='black', lwd=2, nlevels=8, add=T)
points(opt1$p1, opt1$p2, col='blue', pch=19)
points(opt2$p1, opt2$p2, col='black', pch=19)
|
Is there any intuitive explanation of why logistic regression will not work for perfect separation c
A 2D demo with toy data will be used to explain what was happening for perfect separation on logistic regression with and without regularization. The experiments started with an overlapping data set a
|
10,274
|
Setting knots in natural cubic splines in R
|
How to specify the knots in R
The ns function generates a natural regression spline basis given an input vector. The knots can be specified either via a degrees-of-freedom argument df which takes an integer or via a knots argument knots which takes a vector giving the desired placement of the knots. Note that in the code you've written
library(splines)
lda.pred <- lda(y ~ ns(x, knots=5))
you have not requested five knots, but rather have requested a single (interior) knot at location 5.
If you use the df argument, then the interior knots will be selected based on quantiles of the vector x. For example, if you make the call
ns(x, df=5)
Then the basis will include two boundary knots and 4 internal knots, placed at the 20th, 40th, 60th, and 80th quantiles of x, respectively. The boundary knots, by default, are placed at the min and max of x.
Here is an example to specify the locations of the knots
x <- 0:100
ns(x, knots=c(20,35,50))
If you were to instead call ns(x, df=4), you would end up with 3 internal knots at locations 25, 50, and 75, respectively.
You can also specify whether you want an intercept term. Normally this isn't specified since ns is most often used in conjunction with lm, which includes an intercept implicitly (unless forced not to). If you use intercept=TRUE in your call to ns, make sure you know why you're doing so, since if you do this and then call lm naively, the design matrix will end up being rank deficient.
Strategies for placing knots
Knots are most commonly placed at quantiles, like the default behavior of ns. The intuition is that if you have lots of data clustered close together, then you might want more knots there to model any potential nonlinearities in that region. But, that doesn't mean this is either (a) the only choice or (b) the best choice.
Other choices can obviously be made and are domain-specific. Looking at histograms and density estimates of your predictors may provide clues as to where knots are needed, unless there is some "canonical" choice given your data.
In terms of interpreting regressions, I would note that, while you can certainly "play around" with knot placement, you should realize that you incur a model-selection penalty for this that you should be careful to evaluate and should adjust any inferences as a result.
|
Setting knots in natural cubic splines in R
|
How to specify the knots in R
The ns function generates a natural regression spline basis given an input vector. The knots can be specified either via a degrees-of-freedom argument df which takes an i
|
Setting knots in natural cubic splines in R
How to specify the knots in R
The ns function generates a natural regression spline basis given an input vector. The knots can be specified either via a degrees-of-freedom argument df which takes an integer or via a knots argument knots which takes a vector giving the desired placement of the knots. Note that in the code you've written
library(splines)
lda.pred <- lda(y ~ ns(x, knots=5))
you have not requested five knots, but rather have requested a single (interior) knot at location 5.
If you use the df argument, then the interior knots will be selected based on quantiles of the vector x. For example, if you make the call
ns(x, df=5)
Then the basis will include two boundary knots and 4 internal knots, placed at the 20th, 40th, 60th, and 80th quantiles of x, respectively. The boundary knots, by default, are placed at the min and max of x.
Here is an example to specify the locations of the knots
x <- 0:100
ns(x, knots=c(20,35,50))
If you were to instead call ns(x, df=4), you would end up with 3 internal knots at locations 25, 50, and 75, respectively.
You can also specify whether you want an intercept term. Normally this isn't specified since ns is most often used in conjunction with lm, which includes an intercept implicitly (unless forced not to). If you use intercept=TRUE in your call to ns, make sure you know why you're doing so, since if you do this and then call lm naively, the design matrix will end up being rank deficient.
Strategies for placing knots
Knots are most commonly placed at quantiles, like the default behavior of ns. The intuition is that if you have lots of data clustered close together, then you might want more knots there to model any potential nonlinearities in that region. But, that doesn't mean this is either (a) the only choice or (b) the best choice.
Other choices can obviously be made and are domain-specific. Looking at histograms and density estimates of your predictors may provide clues as to where knots are needed, unless there is some "canonical" choice given your data.
In terms of interpreting regressions, I would note that, while you can certainly "play around" with knot placement, you should realize that you incur a model-selection penalty for this that you should be careful to evaluate and should adjust any inferences as a result.
|
Setting knots in natural cubic splines in R
How to specify the knots in R
The ns function generates a natural regression spline basis given an input vector. The knots can be specified either via a degrees-of-freedom argument df which takes an i
|
10,275
|
Should I capitalise the "N" in "Normal Distribution" in British English?
|
For what it's worth, Wikipedia says this on the origin of the name:
Since its introduction, the normal distribution has been known by many different name... Gauss himself apparently coined the term with reference to the "normal equations" involved in its applications, with normal having its technical meaning of orthogonal rather than "usual". However, by the end of the 19th century some authors had started using the name normal distribution, where the word "normal" was used as an adjective...
https://en.wikipedia.org/wiki/Normal_distribution#Naming
It is also not capitalized in the Wikipedia article, nor have I seen it capitalized in general as an American English speaker. For all intents and purposes normal IS an adjective, though not one that's meant to imply all other distributions are 'abnormal'.
|
Should I capitalise the "N" in "Normal Distribution" in British English?
|
For what it's worth, Wikipedia says this on the origin of the name:
Since its introduction, the normal distribution has been known by many different name... Gauss himself apparently coined the term w
|
Should I capitalise the "N" in "Normal Distribution" in British English?
For what it's worth, Wikipedia says this on the origin of the name:
Since its introduction, the normal distribution has been known by many different name... Gauss himself apparently coined the term with reference to the "normal equations" involved in its applications, with normal having its technical meaning of orthogonal rather than "usual". However, by the end of the 19th century some authors had started using the name normal distribution, where the word "normal" was used as an adjective...
https://en.wikipedia.org/wiki/Normal_distribution#Naming
It is also not capitalized in the Wikipedia article, nor have I seen it capitalized in general as an American English speaker. For all intents and purposes normal IS an adjective, though not one that's meant to imply all other distributions are 'abnormal'.
|
Should I capitalise the "N" in "Normal Distribution" in British English?
For what it's worth, Wikipedia says this on the origin of the name:
Since its introduction, the normal distribution has been known by many different name... Gauss himself apparently coined the term w
|
10,276
|
Should I capitalise the "N" in "Normal Distribution" in British English?
|
On one hand, "Normal" seems not to be an adjective, nor a feature of some distribution that it is more normal than any other (or more "beta", more "binomial"). "Normal" is a name of a distribution and can to be considered as a proper noun, and so be capitalized. As @Scortchi noticed in his comment, this is also a general term and people seem to capitalize such terms. If you look into the literature, you'll see that some authors capitalize all the names of distributions, while some seem to never do so.
On another hand, currently (e.g. by Forbes et al., Krishnamoorty, Fisher, Cox et al. and others), it seems that most commonly names of distributions are written in lowercase (e.g. normal, beta, binomial) and are capitalized if they come from surnames (e.g. Cauchy, Gaussian, Poisson). There are also some names that are always written in lowercase as $t$-distribution (example here). While Halperin et al. (1965) in their recommendations do not mention distribution names, in their text they write about chi-squared and standarized normal distributions in lowercase.
This convention may be confusing since in formulas names of distributions are almost always written capitalized (e.g. $X \sim \mathrm{Normal}(\mu, \sigma)$ or $X \sim \mathcal{N}(\mu, \sigma)$) and also because many names come from surnames. However, contrary to my initial answer, it seems that lowercase names are used more commonly and so can be considered as a current convention.
(image source: Freeman, 2006)
Halperin, M., Hartley, H.O., and Hoel, P.G. (1965). Recommended Standards for Statistical Symbols and Notation. COPSS Committee on Symbols and Notation. The American Statistician, 19(3): 12–14.
Freeman, A. (2006). A visual comparison of normal and paranormal distributions. J Epidemiol Community Health, 60(1): 6.
|
Should I capitalise the "N" in "Normal Distribution" in British English?
|
On one hand, "Normal" seems not to be an adjective, nor a feature of some distribution that it is more normal than any other (or more "beta", more "binomial"). "Normal" is a name of a distribution and
|
Should I capitalise the "N" in "Normal Distribution" in British English?
On one hand, "Normal" seems not to be an adjective, nor a feature of some distribution that it is more normal than any other (or more "beta", more "binomial"). "Normal" is a name of a distribution and can to be considered as a proper noun, and so be capitalized. As @Scortchi noticed in his comment, this is also a general term and people seem to capitalize such terms. If you look into the literature, you'll see that some authors capitalize all the names of distributions, while some seem to never do so.
On another hand, currently (e.g. by Forbes et al., Krishnamoorty, Fisher, Cox et al. and others), it seems that most commonly names of distributions are written in lowercase (e.g. normal, beta, binomial) and are capitalized if they come from surnames (e.g. Cauchy, Gaussian, Poisson). There are also some names that are always written in lowercase as $t$-distribution (example here). While Halperin et al. (1965) in their recommendations do not mention distribution names, in their text they write about chi-squared and standarized normal distributions in lowercase.
This convention may be confusing since in formulas names of distributions are almost always written capitalized (e.g. $X \sim \mathrm{Normal}(\mu, \sigma)$ or $X \sim \mathcal{N}(\mu, \sigma)$) and also because many names come from surnames. However, contrary to my initial answer, it seems that lowercase names are used more commonly and so can be considered as a current convention.
(image source: Freeman, 2006)
Halperin, M., Hartley, H.O., and Hoel, P.G. (1965). Recommended Standards for Statistical Symbols and Notation. COPSS Committee on Symbols and Notation. The American Statistician, 19(3): 12–14.
Freeman, A. (2006). A visual comparison of normal and paranormal distributions. J Epidemiol Community Health, 60(1): 6.
|
Should I capitalise the "N" in "Normal Distribution" in British English?
On one hand, "Normal" seems not to be an adjective, nor a feature of some distribution that it is more normal than any other (or more "beta", more "binomial"). "Normal" is a name of a distribution and
|
10,277
|
Measuring accuracy of a logistic regression-based model
|
A measure that is often used to validate logistic regression, is the AUC of the ROC curve (plot of sensitivity against 1-specificity - just google for the terms if needed). This, in essence, evaluates the whole range of threshold values.
On the downside: evaluating the whole range of threshold values may be not what you're after, since this (typically) includes thresholds that result in very large numbers of false negatives or false positives. There are versions of the AUC that account for this (partial AUC), so if that is an issue for you, you can look into that.
|
Measuring accuracy of a logistic regression-based model
|
A measure that is often used to validate logistic regression, is the AUC of the ROC curve (plot of sensitivity against 1-specificity - just google for the terms if needed). This, in essence, evaluates
|
Measuring accuracy of a logistic regression-based model
A measure that is often used to validate logistic regression, is the AUC of the ROC curve (plot of sensitivity against 1-specificity - just google for the terms if needed). This, in essence, evaluates the whole range of threshold values.
On the downside: evaluating the whole range of threshold values may be not what you're after, since this (typically) includes thresholds that result in very large numbers of false negatives or false positives. There are versions of the AUC that account for this (partial AUC), so if that is an issue for you, you can look into that.
|
Measuring accuracy of a logistic regression-based model
A measure that is often used to validate logistic regression, is the AUC of the ROC curve (plot of sensitivity against 1-specificity - just google for the terms if needed). This, in essence, evaluates
|
10,278
|
Measuring accuracy of a logistic regression-based model
|
You are correct to worry about proportion classified correct as mainly reflecting the effect of an arbitrary boundary. I'd recommend two measures. One is the $c$-index or ROC area as others have described. This has an interpretation that is simpler than thinking about an ROC curve, and is a measure of pure predictive discrimination. Secondly, estimate a continuous calibration curve without any binning of data. If predictions are being assessed on an independent dataset, you can use lowess with outlier detection turned off to estimate the relationship between predicted and actual Prob[Y=1]. The val.prob function in the R rms package will do both of these things. Other functions in rms will do the same for internal validation, using resampling to remove the effects of overfitting.
|
Measuring accuracy of a logistic regression-based model
|
You are correct to worry about proportion classified correct as mainly reflecting the effect of an arbitrary boundary. I'd recommend two measures. One is the $c$-index or ROC area as others have des
|
Measuring accuracy of a logistic regression-based model
You are correct to worry about proportion classified correct as mainly reflecting the effect of an arbitrary boundary. I'd recommend two measures. One is the $c$-index or ROC area as others have described. This has an interpretation that is simpler than thinking about an ROC curve, and is a measure of pure predictive discrimination. Secondly, estimate a continuous calibration curve without any binning of data. If predictions are being assessed on an independent dataset, you can use lowess with outlier detection turned off to estimate the relationship between predicted and actual Prob[Y=1]. The val.prob function in the R rms package will do both of these things. Other functions in rms will do the same for internal validation, using resampling to remove the effects of overfitting.
|
Measuring accuracy of a logistic regression-based model
You are correct to worry about proportion classified correct as mainly reflecting the effect of an arbitrary boundary. I'd recommend two measures. One is the $c$-index or ROC area as others have des
|
10,279
|
Measuring accuracy of a logistic regression-based model
|
If your data are grouped by $x$ values, you can compute the model predicted value and it's associated confidence interval, and see if the observed percentage falls within that range. For example, if you had 10 observations at $x=10$, 10 obs at $x=20$, 10 obs at $x=30$, etc., then mean(y[x==10]==1), mean(y[x==20]==1), etc., would yield percentages that can be compared to predictions. Bear in mind, that even if the model is perfect, some observed percentages will bounce outside of the 95% CI, just like in OLS regression. If your data are not grouped, you can form your own groups by binning the data according to ranges of the $x$ variable, as you suggest. This isn't fully valid, as it will depend on the choice of bins, can be useful as a way of exploring your model.
In general, the task you have given yourself here is difficult. That's because, with logistic regression, you are dealing with two different kinds of things. The model's predictions are a latent variable, whereas your observed response variable (while presumably generated by a latent variable) is not. Of course, people will often want to know what the predicted response is, and that's totally reasonable; this is just one of those cases where life isn't fair.
If you do want to predict the outcome, you need to decide what you want to maximize. If you have just 1 case, and you want your prediction to be most likely to be right, you should predict $y=1$, if $\hat y\ge .5$. (This is all pretty intuitive.) On the other hand, if you want to maximize overall accuracy over your total sample (or any other group), you should predict $y=1$, if $\hat y \ge p(y=1)$. For example, let's say that in your sample, 30% of all cases are 1's, then if $\hat y = .31$, you should predict that $y$ will be $1$, even though it's $<.5$. This is counter-intuitive, and a lot of people stumble here, but this algorithm will maximize your accuracy.
A more comprehensive way to think about how much information is in your model, is to integrate over how accurate you would be given every possible threshold $(0, 1)$. This is the area under the curve (AUC) of the model's receiver operating characteristic (ROC), discussed by @Nick Sabbe. Remember that there is no $R^2$ for logistic regression. There are so called 'pseudo $R^2$'s, but the AUC (or the concordance, $c$, a synonym) is probably the best way to think about this issue.
|
Measuring accuracy of a logistic regression-based model
|
If your data are grouped by $x$ values, you can compute the model predicted value and it's associated confidence interval, and see if the observed percentage falls within that range. For example, if
|
Measuring accuracy of a logistic regression-based model
If your data are grouped by $x$ values, you can compute the model predicted value and it's associated confidence interval, and see if the observed percentage falls within that range. For example, if you had 10 observations at $x=10$, 10 obs at $x=20$, 10 obs at $x=30$, etc., then mean(y[x==10]==1), mean(y[x==20]==1), etc., would yield percentages that can be compared to predictions. Bear in mind, that even if the model is perfect, some observed percentages will bounce outside of the 95% CI, just like in OLS regression. If your data are not grouped, you can form your own groups by binning the data according to ranges of the $x$ variable, as you suggest. This isn't fully valid, as it will depend on the choice of bins, can be useful as a way of exploring your model.
In general, the task you have given yourself here is difficult. That's because, with logistic regression, you are dealing with two different kinds of things. The model's predictions are a latent variable, whereas your observed response variable (while presumably generated by a latent variable) is not. Of course, people will often want to know what the predicted response is, and that's totally reasonable; this is just one of those cases where life isn't fair.
If you do want to predict the outcome, you need to decide what you want to maximize. If you have just 1 case, and you want your prediction to be most likely to be right, you should predict $y=1$, if $\hat y\ge .5$. (This is all pretty intuitive.) On the other hand, if you want to maximize overall accuracy over your total sample (or any other group), you should predict $y=1$, if $\hat y \ge p(y=1)$. For example, let's say that in your sample, 30% of all cases are 1's, then if $\hat y = .31$, you should predict that $y$ will be $1$, even though it's $<.5$. This is counter-intuitive, and a lot of people stumble here, but this algorithm will maximize your accuracy.
A more comprehensive way to think about how much information is in your model, is to integrate over how accurate you would be given every possible threshold $(0, 1)$. This is the area under the curve (AUC) of the model's receiver operating characteristic (ROC), discussed by @Nick Sabbe. Remember that there is no $R^2$ for logistic regression. There are so called 'pseudo $R^2$'s, but the AUC (or the concordance, $c$, a synonym) is probably the best way to think about this issue.
|
Measuring accuracy of a logistic regression-based model
If your data are grouped by $x$ values, you can compute the model predicted value and it's associated confidence interval, and see if the observed percentage falls within that range. For example, if
|
10,280
|
Measuring accuracy of a logistic regression-based model
|
I think you could establish a threshold (say 0.5), so when your probability is equals to or greater than that threshold your predicted class would be 1, and 0 otherwise. Then, you could obtain a measure of your accuracy in this way:
confusion_matrix <- ftable(actual_value, predicted_value)
accuracy <- sum(diag(confusion_matrix))/number of events*100
Given that your probability is the probability of given your data (x) and using your model your class value (y) is equal to 1, I do not understand why you always obtain probability values lower than 0.5. Which is the frequency of your actual classes (actual_value)?
|
Measuring accuracy of a logistic regression-based model
|
I think you could establish a threshold (say 0.5), so when your probability is equals to or greater than that threshold your predicted class would be 1, and 0 otherwise. Then, you could obtain a measu
|
Measuring accuracy of a logistic regression-based model
I think you could establish a threshold (say 0.5), so when your probability is equals to or greater than that threshold your predicted class would be 1, and 0 otherwise. Then, you could obtain a measure of your accuracy in this way:
confusion_matrix <- ftable(actual_value, predicted_value)
accuracy <- sum(diag(confusion_matrix))/number of events*100
Given that your probability is the probability of given your data (x) and using your model your class value (y) is equal to 1, I do not understand why you always obtain probability values lower than 0.5. Which is the frequency of your actual classes (actual_value)?
|
Measuring accuracy of a logistic regression-based model
I think you could establish a threshold (say 0.5), so when your probability is equals to or greater than that threshold your predicted class would be 1, and 0 otherwise. Then, you could obtain a measu
|
10,281
|
Measuring accuracy of a logistic regression-based model
|
You may want to have look at my package softclassval (at softclassval.r-forge.r-project.org you find also two oral presentations I gave about the ideas behind the package).
I wrote it for a slightly different problem, namely if the reference (e.g. pathologist) "refuses" to give a clear class. However, you can use it with "normal" hard classes and it avoids the definition of a threshold for hardening the originally continuous prediction - so you don't evaluate the 0.8.
However, I recommend to use it alongside with, say, a ROC or specificity-sensitivity-diagram: the results will often look quite bad as "my" methods will penalize already slight deviations (e.g. 0.9 instead of 1 gives 0.1 difference for my measures, but all thresholds below 0.9 will ignore this). Actually I think is rather an advantage: the lack of this sensitivity agaist small deviations is one of the major points of criticism with those "hardened" measures like accuracy, sensitivity, recall, etc.
In addition, by comparing mean absolute error (MAE) and root mean squared error RMSE you can find out whether you have many small deviations or fewer grossly misjudged samples.
|
Measuring accuracy of a logistic regression-based model
|
You may want to have look at my package softclassval (at softclassval.r-forge.r-project.org you find also two oral presentations I gave about the ideas behind the package).
I wrote it for a slightly d
|
Measuring accuracy of a logistic regression-based model
You may want to have look at my package softclassval (at softclassval.r-forge.r-project.org you find also two oral presentations I gave about the ideas behind the package).
I wrote it for a slightly different problem, namely if the reference (e.g. pathologist) "refuses" to give a clear class. However, you can use it with "normal" hard classes and it avoids the definition of a threshold for hardening the originally continuous prediction - so you don't evaluate the 0.8.
However, I recommend to use it alongside with, say, a ROC or specificity-sensitivity-diagram: the results will often look quite bad as "my" methods will penalize already slight deviations (e.g. 0.9 instead of 1 gives 0.1 difference for my measures, but all thresholds below 0.9 will ignore this). Actually I think is rather an advantage: the lack of this sensitivity agaist small deviations is one of the major points of criticism with those "hardened" measures like accuracy, sensitivity, recall, etc.
In addition, by comparing mean absolute error (MAE) and root mean squared error RMSE you can find out whether you have many small deviations or fewer grossly misjudged samples.
|
Measuring accuracy of a logistic regression-based model
You may want to have look at my package softclassval (at softclassval.r-forge.r-project.org you find also two oral presentations I gave about the ideas behind the package).
I wrote it for a slightly d
|
10,282
|
Measuring accuracy of a logistic regression-based model
|
I wonder why you aren't using the bernoulli log-likelihood function. Basically, for every $0$ actual value, you score $-\log (1-\hat {p}) $. This measures how close to predicting $0$ your model is. Similarly, for every $1$ actual value you score $-\log (\hat {p}) $. This measures how close to predicting $1$ your model is.
This does not suffer from arbitrary thresholds. The smaller the measure the better.
|
Measuring accuracy of a logistic regression-based model
|
I wonder why you aren't using the bernoulli log-likelihood function. Basically, for every $0$ actual value, you score $-\log (1-\hat {p}) $. This measures how close to predicting $0$ your model is. S
|
Measuring accuracy of a logistic regression-based model
I wonder why you aren't using the bernoulli log-likelihood function. Basically, for every $0$ actual value, you score $-\log (1-\hat {p}) $. This measures how close to predicting $0$ your model is. Similarly, for every $1$ actual value you score $-\log (\hat {p}) $. This measures how close to predicting $1$ your model is.
This does not suffer from arbitrary thresholds. The smaller the measure the better.
|
Measuring accuracy of a logistic regression-based model
I wonder why you aren't using the bernoulli log-likelihood function. Basically, for every $0$ actual value, you score $-\log (1-\hat {p}) $. This measures how close to predicting $0$ your model is. S
|
10,283
|
Measuring accuracy of a logistic regression-based model
|
Here's my quick suggestion: Since your dependent variable is binary, you can assume it follows a Bernoulli distribution, with probability given by logistic regression $Pr_{i} = invlogit(a + bx_{i})$.
Now, set one simulation as follow:
$ y.rep[i] \sim Bernoulli (p[i])$
Then, run this simulation, say, 100 times. You will have a matrix with n rows (n is the number of subjects) and k columns (in this case, k=100, the number of simulations). In r code:
for (j in 1:100)
mat.y.rep[,j] <- Bernoulli ( p) # p is a vector with a probability for each subject
Now you compute the difference between the predicted in each simulation and observed. After computing this difference, just compute the mean number of true-positive and false-positive for each row (each subject) and plot the histogram. Or compute both for each column (simulation) e plot the histogram (I prefer this).
Hope it helps...
|
Measuring accuracy of a logistic regression-based model
|
Here's my quick suggestion: Since your dependent variable is binary, you can assume it follows a Bernoulli distribution, with probability given by logistic regression $Pr_{i} = invlogit(a + bx_{i})$.
|
Measuring accuracy of a logistic regression-based model
Here's my quick suggestion: Since your dependent variable is binary, you can assume it follows a Bernoulli distribution, with probability given by logistic regression $Pr_{i} = invlogit(a + bx_{i})$.
Now, set one simulation as follow:
$ y.rep[i] \sim Bernoulli (p[i])$
Then, run this simulation, say, 100 times. You will have a matrix with n rows (n is the number of subjects) and k columns (in this case, k=100, the number of simulations). In r code:
for (j in 1:100)
mat.y.rep[,j] <- Bernoulli ( p) # p is a vector with a probability for each subject
Now you compute the difference between the predicted in each simulation and observed. After computing this difference, just compute the mean number of true-positive and false-positive for each row (each subject) and plot the histogram. Or compute both for each column (simulation) e plot the histogram (I prefer this).
Hope it helps...
|
Measuring accuracy of a logistic regression-based model
Here's my quick suggestion: Since your dependent variable is binary, you can assume it follows a Bernoulli distribution, with probability given by logistic regression $Pr_{i} = invlogit(a + bx_{i})$.
|
10,284
|
Measuring accuracy of a logistic regression-based model
|
There are many ways to estimate the accuracy of such predictions and the optimal choice really depends on what will the estimation implemented for.
For example, if you plan to select a few high score hits for an expensive follow-up study you may want to maximize the precision at high scores. On the other hand, if the follow-up study is cheap you may want to maximize the recall (sensitivity) at lower scores. The ROC AUC may be suitable if you are comparing different method, etc.
On the practical side, R's ROCR package contains 2 useful functions
pred.obj <- prediction(predictions, labels,...)
performance(pred.obj, measure, ...)
Together, these functions can calculate a wide range of accuracy measures, including global scalar values (such as "auc") and score-dependent vectors for plotting Recall-precision and ROC curves ("prec", "rec", "tpr" and "fpr", etc.)
|
Measuring accuracy of a logistic regression-based model
|
There are many ways to estimate the accuracy of such predictions and the optimal choice really depends on what will the estimation implemented for.
For example, if you plan to select a few high scor
|
Measuring accuracy of a logistic regression-based model
There are many ways to estimate the accuracy of such predictions and the optimal choice really depends on what will the estimation implemented for.
For example, if you plan to select a few high score hits for an expensive follow-up study you may want to maximize the precision at high scores. On the other hand, if the follow-up study is cheap you may want to maximize the recall (sensitivity) at lower scores. The ROC AUC may be suitable if you are comparing different method, etc.
On the practical side, R's ROCR package contains 2 useful functions
pred.obj <- prediction(predictions, labels,...)
performance(pred.obj, measure, ...)
Together, these functions can calculate a wide range of accuracy measures, including global scalar values (such as "auc") and score-dependent vectors for plotting Recall-precision and ROC curves ("prec", "rec", "tpr" and "fpr", etc.)
|
Measuring accuracy of a logistic regression-based model
There are many ways to estimate the accuracy of such predictions and the optimal choice really depends on what will the estimation implemented for.
For example, if you plan to select a few high scor
|
10,285
|
Measuring accuracy of a logistic regression-based model
|
You need to define what you mean by "accuracy". What you would like to know, please pardon me for putting words in your mouth, is how well your model fits the training data, and more importantly, how well this model "generalizes" to samples not in your training data. Although ROC curves can be useful in analyzing the tradeoff between precision and recall for various values of the threshold, I suggest adding mean-squared-error, or the Brier score to your toolbox. It's easy to compute, and you can immediately get a feel for whether feature changes affect the fit of the model, when applied to training data. Since overfit is possible in this case, your job isn't done here. To evaluate generalization performance, or how well you do on data you haven't seen, it isn't enough to look at your performance on the training samples. Of course your model is good at those, because they the values you used to determine the coefficients to your logistic. You need to set aside some samples for test data. Your MSE performance on this set should set your generalization expectations according to the Hoeffding inequality. Your maximum generalization error will depend on the number of features in your model as well as the number of samples used to compute the test statistic. Be mindful that you'll need to steal some of your training samples for test samples. I recommend 10-fold cross-validation, where you shuffle, choose 90% for training, 10% for testing, and then measure, repeat, and then average all the measurements.
|
Measuring accuracy of a logistic regression-based model
|
You need to define what you mean by "accuracy". What you would like to know, please pardon me for putting words in your mouth, is how well your model fits the training data, and more importantly, how
|
Measuring accuracy of a logistic regression-based model
You need to define what you mean by "accuracy". What you would like to know, please pardon me for putting words in your mouth, is how well your model fits the training data, and more importantly, how well this model "generalizes" to samples not in your training data. Although ROC curves can be useful in analyzing the tradeoff between precision and recall for various values of the threshold, I suggest adding mean-squared-error, or the Brier score to your toolbox. It's easy to compute, and you can immediately get a feel for whether feature changes affect the fit of the model, when applied to training data. Since overfit is possible in this case, your job isn't done here. To evaluate generalization performance, or how well you do on data you haven't seen, it isn't enough to look at your performance on the training samples. Of course your model is good at those, because they the values you used to determine the coefficients to your logistic. You need to set aside some samples for test data. Your MSE performance on this set should set your generalization expectations according to the Hoeffding inequality. Your maximum generalization error will depend on the number of features in your model as well as the number of samples used to compute the test statistic. Be mindful that you'll need to steal some of your training samples for test samples. I recommend 10-fold cross-validation, where you shuffle, choose 90% for training, 10% for testing, and then measure, repeat, and then average all the measurements.
|
Measuring accuracy of a logistic regression-based model
You need to define what you mean by "accuracy". What you would like to know, please pardon me for putting words in your mouth, is how well your model fits the training data, and more importantly, how
|
10,286
|
Application of wavelets to time-series-based anomaly detection algorithms
|
Wavelets are useful to detect singularities in a signal (see for example the paper here (see figure 3 for an illustration) and the references mentioned in this paper. I guess singularities can sometimes be an anomaly?
The idea here is that the Continuous wavelet transform (CWT) has maxima lines that propagates along frequencies, i.e. the longer the line is, the higher is the singularity. See Figure 3 in the paper to see what I mean! note that there is free Matlab code related to that paper, it should be here.
Additionally, I can give you some heuristics detailing why the DISCRETE (preceding example is about the continuous one) wavelet transform (DWT) is interesting for a statistician (excuse non-exhaustivity) :
There is a wide class of (realistic (Besov space)) signals that are transformed into a sparse sequence by the wavelet transform. (compression property)
A wide class of (quasi-stationary) processes that are transformed into a sequence with almost uncorrelated features (decorrelation property)
Wavelet coefficients contain information that is localized in time and in frequency (at different scales). (multi-scale property)
Wavelet coefficients of a signal concentrate on its singularities.
|
Application of wavelets to time-series-based anomaly detection algorithms
|
Wavelets are useful to detect singularities in a signal (see for example the paper here (see figure 3 for an illustration) and the references mentioned in this paper. I guess singularities can someti
|
Application of wavelets to time-series-based anomaly detection algorithms
Wavelets are useful to detect singularities in a signal (see for example the paper here (see figure 3 for an illustration) and the references mentioned in this paper. I guess singularities can sometimes be an anomaly?
The idea here is that the Continuous wavelet transform (CWT) has maxima lines that propagates along frequencies, i.e. the longer the line is, the higher is the singularity. See Figure 3 in the paper to see what I mean! note that there is free Matlab code related to that paper, it should be here.
Additionally, I can give you some heuristics detailing why the DISCRETE (preceding example is about the continuous one) wavelet transform (DWT) is interesting for a statistician (excuse non-exhaustivity) :
There is a wide class of (realistic (Besov space)) signals that are transformed into a sparse sequence by the wavelet transform. (compression property)
A wide class of (quasi-stationary) processes that are transformed into a sequence with almost uncorrelated features (decorrelation property)
Wavelet coefficients contain information that is localized in time and in frequency (at different scales). (multi-scale property)
Wavelet coefficients of a signal concentrate on its singularities.
|
Application of wavelets to time-series-based anomaly detection algorithms
Wavelets are useful to detect singularities in a signal (see for example the paper here (see figure 3 for an illustration) and the references mentioned in this paper. I guess singularities can someti
|
10,287
|
Application of wavelets to time-series-based anomaly detection algorithms
|
The list in the presentation that you reference seems fairly arbitrary to me, and the technique that would be used will really depend on the specific problem. You will note however that it also includes Kalman filters, so I suspect that the intended usage is as a filtering technique. Wavelet transforms generally fall under the subject of signal processing, and will often be used as a pre-processing step with very noisy data. An example is the "Multi-scale anomaly detection" paper by Chen and Zhan (see below). The approach would be to run an analysis on the different spectrum rather than on the original noisy series.
Wavelets are often compared to a continuous-time fourier transform, although they have the benefit of being localized in both time and frequency. Wavelets can be used both for signal compression and also for smoothing (wavelet shrinkage). Ultimately, it could make sense to apply a further statistical after the wavelet transform has been applied (by looking in at the auto-correlation function for instance). One further aspect of wavelets that could be useful for anomaly detection is the effect of localization: namely, a discontinuity will only influence the wavelet that is near it (unlike a fourier transform). One application of this is to finding locally stationary time series (using an LSW).
Guy Nason has a nice book that I would recommend if you want to delve further into the practical statistical application: "Wavelet Methods in Statistics with R". This is specifically targeting the application of wavelets to statistical analysis, and he provides many real world examples along with all the code (using the wavethresh package). Nason's book does not address "anomaly detection" specifically, although it does do an admiral job of providing a general overview.
Lastly, the wikipedia article does provide many good introductory references, so it is worth going through it in detail.
Xiao-yun Chen, Yan-yan Zhan "Multi-scale anomaly detection algorithm based on infrequent pattern of time series" Journal of Computational and Applied Mathematics Volume 214 , Issue 1 (April 2008)
G.P. Nason "Wavelet Methods in Statistics with R" Springer, 2008
[As a side note: if you are looking for a good modern technique for change point detection, I would suggest trying a HMM before spending too much time with wavelet methods, unless you have good reason to be using wavelets in your particular field. This is based on my personal experience. There are of course many other nonlinear models that could be considered, so it really depends on your specific problem.]
|
Application of wavelets to time-series-based anomaly detection algorithms
|
The list in the presentation that you reference seems fairly arbitrary to me, and the technique that would be used will really depend on the specific problem. You will note however that it also inclu
|
Application of wavelets to time-series-based anomaly detection algorithms
The list in the presentation that you reference seems fairly arbitrary to me, and the technique that would be used will really depend on the specific problem. You will note however that it also includes Kalman filters, so I suspect that the intended usage is as a filtering technique. Wavelet transforms generally fall under the subject of signal processing, and will often be used as a pre-processing step with very noisy data. An example is the "Multi-scale anomaly detection" paper by Chen and Zhan (see below). The approach would be to run an analysis on the different spectrum rather than on the original noisy series.
Wavelets are often compared to a continuous-time fourier transform, although they have the benefit of being localized in both time and frequency. Wavelets can be used both for signal compression and also for smoothing (wavelet shrinkage). Ultimately, it could make sense to apply a further statistical after the wavelet transform has been applied (by looking in at the auto-correlation function for instance). One further aspect of wavelets that could be useful for anomaly detection is the effect of localization: namely, a discontinuity will only influence the wavelet that is near it (unlike a fourier transform). One application of this is to finding locally stationary time series (using an LSW).
Guy Nason has a nice book that I would recommend if you want to delve further into the practical statistical application: "Wavelet Methods in Statistics with R". This is specifically targeting the application of wavelets to statistical analysis, and he provides many real world examples along with all the code (using the wavethresh package). Nason's book does not address "anomaly detection" specifically, although it does do an admiral job of providing a general overview.
Lastly, the wikipedia article does provide many good introductory references, so it is worth going through it in detail.
Xiao-yun Chen, Yan-yan Zhan "Multi-scale anomaly detection algorithm based on infrequent pattern of time series" Journal of Computational and Applied Mathematics Volume 214 , Issue 1 (April 2008)
G.P. Nason "Wavelet Methods in Statistics with R" Springer, 2008
[As a side note: if you are looking for a good modern technique for change point detection, I would suggest trying a HMM before spending too much time with wavelet methods, unless you have good reason to be using wavelets in your particular field. This is based on my personal experience. There are of course many other nonlinear models that could be considered, so it really depends on your specific problem.]
|
Application of wavelets to time-series-based anomaly detection algorithms
The list in the presentation that you reference seems fairly arbitrary to me, and the technique that would be used will really depend on the specific problem. You will note however that it also inclu
|
10,288
|
Application of wavelets to time-series-based anomaly detection algorithms
|
Most commonly used and implemented discrete wavelet basis functions (as distinct from the CWT described in Robin's answer) have two nice properties that make them useful for anomaly detection:
They're compactly supported.
They act as band-pass filters with the pass-band determined by their support.
What this means in practical terms is that your discrete wavelet decomposition looks at local changes in the signal across a variety of scales and frequency bands. If you have (for instance) large-magnitude, high-frequency noise superimposed across a function that displays a low-magnitude shift over a longer period, the wavelet transform will efficiently separate these two scales and let you see the baseline shift that many other techniques will miss; a shift in this baseline can suggest a disease outbreak or some other change of interest. In a lot of ways, you can treat the decomposition itself as a smoother (and there's been quite a bit of work done on efficient shrinkage for wavelet coefficients in nonparametric estimation, see e.g. pretty much anything on wavelets by Donoho). Unlike pure frequency-based methods, the compact support means that they're capable of handling non-stationary data. Unlike purely time-based methods, they allow for some frequency-based filtering.
In practical terms, to detect anomalies or change points, you would apply a discrete wavelet transform (probably the variant known either as the "Maximum Overlap DWT" or "shift invariant DWT", depending on who you read) to the data, and look at the lower-frequency sets of coefficients to see if you have significant shifts in the baseline. This will show you when a long-term change is occurring underneath any day-to-day noise. Percival and Walden (see references below) derive a few tests for statistically significant coefficients that you could use to see if a shift like this is significant or not.
An excellent reference work for discrete wavelets is Percival and Walden, "Wavelet Methods for Time Series Analysis". A good introductory work is "Introduction to wavelets and wavelet transforms, a primer" by Burrus, Gopinath, and Guo. If you're coming from an engineering background, then "Elements of wavelets for engineers and scientists" is a good introduction from a signal-processing point of view.
(Edited to include Robin's comments)
|
Application of wavelets to time-series-based anomaly detection algorithms
|
Most commonly used and implemented discrete wavelet basis functions (as distinct from the CWT described in Robin's answer) have two nice properties that make them useful for anomaly detection:
They'r
|
Application of wavelets to time-series-based anomaly detection algorithms
Most commonly used and implemented discrete wavelet basis functions (as distinct from the CWT described in Robin's answer) have two nice properties that make them useful for anomaly detection:
They're compactly supported.
They act as band-pass filters with the pass-band determined by their support.
What this means in practical terms is that your discrete wavelet decomposition looks at local changes in the signal across a variety of scales and frequency bands. If you have (for instance) large-magnitude, high-frequency noise superimposed across a function that displays a low-magnitude shift over a longer period, the wavelet transform will efficiently separate these two scales and let you see the baseline shift that many other techniques will miss; a shift in this baseline can suggest a disease outbreak or some other change of interest. In a lot of ways, you can treat the decomposition itself as a smoother (and there's been quite a bit of work done on efficient shrinkage for wavelet coefficients in nonparametric estimation, see e.g. pretty much anything on wavelets by Donoho). Unlike pure frequency-based methods, the compact support means that they're capable of handling non-stationary data. Unlike purely time-based methods, they allow for some frequency-based filtering.
In practical terms, to detect anomalies or change points, you would apply a discrete wavelet transform (probably the variant known either as the "Maximum Overlap DWT" or "shift invariant DWT", depending on who you read) to the data, and look at the lower-frequency sets of coefficients to see if you have significant shifts in the baseline. This will show you when a long-term change is occurring underneath any day-to-day noise. Percival and Walden (see references below) derive a few tests for statistically significant coefficients that you could use to see if a shift like this is significant or not.
An excellent reference work for discrete wavelets is Percival and Walden, "Wavelet Methods for Time Series Analysis". A good introductory work is "Introduction to wavelets and wavelet transforms, a primer" by Burrus, Gopinath, and Guo. If you're coming from an engineering background, then "Elements of wavelets for engineers and scientists" is a good introduction from a signal-processing point of view.
(Edited to include Robin's comments)
|
Application of wavelets to time-series-based anomaly detection algorithms
Most commonly used and implemented discrete wavelet basis functions (as distinct from the CWT described in Robin's answer) have two nice properties that make them useful for anomaly detection:
They'r
|
10,289
|
Application of wavelets to time-series-based anomaly detection algorithms
|
Really nice answers so far!
For the mathematical proof regarding robin's first sentence, (i.e. Wavelets are useful to detect singularities in a signal), originally by Yves Meyer, see Singularity Detection and Processing with Wavelets (Mallat and Hwang, 1992). Not only they are useful, they are guaranteed to concentrate around singularities and make them quantifiable via their Lipschitz measure, kind of an "if and only if" condition.
This said, I'd like to reflect on robin's hypothesis that singularities can be an anomaly, and possibly broaden it by rather saying that, since wavelet representations concentrate more on singularities, the result is generally sparser, and a sparser representation can allow to identify anomalies more reliably (even if just as a consequence of having less parameters).
Of course, not everything can be solved with wavelets, this is not the 90s anymore. Now we throw neural networks at everything!
|
Application of wavelets to time-series-based anomaly detection algorithms
|
Really nice answers so far!
For the mathematical proof regarding robin's first sentence, (i.e. Wavelets are useful to detect singularities in a signal), originally by Yves Meyer, see Singularity Detec
|
Application of wavelets to time-series-based anomaly detection algorithms
Really nice answers so far!
For the mathematical proof regarding robin's first sentence, (i.e. Wavelets are useful to detect singularities in a signal), originally by Yves Meyer, see Singularity Detection and Processing with Wavelets (Mallat and Hwang, 1992). Not only they are useful, they are guaranteed to concentrate around singularities and make them quantifiable via their Lipschitz measure, kind of an "if and only if" condition.
This said, I'd like to reflect on robin's hypothesis that singularities can be an anomaly, and possibly broaden it by rather saying that, since wavelet representations concentrate more on singularities, the result is generally sparser, and a sparser representation can allow to identify anomalies more reliably (even if just as a consequence of having less parameters).
Of course, not everything can be solved with wavelets, this is not the 90s anymore. Now we throw neural networks at everything!
|
Application of wavelets to time-series-based anomaly detection algorithms
Really nice answers so far!
For the mathematical proof regarding robin's first sentence, (i.e. Wavelets are useful to detect singularities in a signal), originally by Yves Meyer, see Singularity Detec
|
10,290
|
Help me understand adjusted odds ratio in logistic regression
|
Odds are a way to express chances. Odds ratios are just that: one odds divided by another. That means an odds ratio is what you multiply one odds by to produce another. Let's see how they work in this common situation.
Converting between odds and probability
The odds of a binary response $Y$ are the ratio of the chance it happens (coded with $1$), written $\Pr(Y=1)$, to the chance it does not (coded with $0$), written $\Pr(Y=0)$:
$$\text{Odds}(Y) = \frac{\Pr(Y=1)}{\Pr(Y=0)} = \frac{\Pr(Y=1)}{1 - \Pr(Y=1)}.$$
The equivalent expression on the right shows it suffices to model $\Pr(Y=1)$ to find the odds. Conversely, note that we can solve
$$\Pr(Y=1) = \frac{\text{Odds}(Y)}{1 + \text{Odds}(Y)} = 1 - \frac{1}{1 + \text{Odds}(Y)}.$$
Logistic regression
Logistic regression models the logarithm of the odds of $Y$ as a linear function of explanatory variables. Most generally, writing these variables as $x_1, \ldots, x_p$, and including a possible constant term in the linear function, we may name the coefficients (which are to be estimated from the data) as $\beta_1,\ldots, \beta_p$ and $\beta_0$. Formally this produces the model
$$\log\left(\text{Odds}(Y)\right) = \beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p.$$
The odds themselves can be recovered by undoing the logarithm:
$$\text{Odds}(Y) = \exp(\beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p).$$
Using categorical variables
Categorical variables, such as age group, gender, presence of Glaucoma, etc., are incorporated by means of "dummy coding." To show that how the variable is coded does not matter, I will provide a simple example of one small group; its generalization to multiple groups should be obvious. In this study one variable is "pupil size," with three categories, "Large", "Medium", and "Small". (The study treats these as purely categorical, apparently paying no attention to their inherent order.) Intuitively, each category has its own odds, say $\alpha_L$ for "Large", $\alpha_M$ for "Medium", and $\alpha_S$ for "Small". This means that, all other things equal,
$$\text{Odds}(Y) = \exp(\color{Blue}{\alpha_L + \beta_0} + \beta_1 x_1 + \cdots + \beta_p x_p)$$
for anybody in the "Large" category,
$$\text{Odds}(Y) = \exp(\color{Blue}{\alpha_M + \beta_0} + \beta_1 x_1 + \cdots + \beta_p x_p)$$
for anybody in the "Medium" category, and
$$\text{Odds}(Y) = \exp(\color{Blue}{\alpha_S + \beta_0} + \beta_1 x_1 + \cdots + \beta_p x_p)$$
for those in the "Small" category.
Creating identifiable coefficients
I have colored the first two coefficients to highlight them, because I want you to notice that they allow a simple change to occur: we could pick any number $\gamma$ and, by adding it to $\beta_0$ and subtracting it from each of $\alpha_L$, $\alpha_M$, and $\alpha_S$, we would not change any predicted odds. This is because of the obvious equivalences of the form
$$\alpha_L + \beta_0 = (\alpha_L - \gamma) + (\gamma + \beta_0 ),$$
etc. Although this presents no problems for the model--it still predicts exactly the same things--it shows that the parameters are not in themselves interpretable. What stays the same when we do this addition-subtraction maneuver are the differences between the coefficients. Conventionally, to address this lack of identifiability, people (and by default, software) choose one of the categories in each variable as the "base" or "reference" and simply stipulate that its coefficient will be zero. This removes the ambiguity.
The paper lists reference categories first; "Large" in this case. Thus, $\alpha_L$ is subtracted from each of $\alpha_L, \alpha_M,$ and $\alpha_S$, and added to $\beta_0$ to compensate.
The log odds for a hypothetical individual falling into all the base categories therefore equals $\beta_0$ plus a bunch of terms associated with all other "covariates"--the non-categorical variables:
$$\text{Odds(Base category)} = \exp(\beta_0 + \beta_1X_1 + \cdots + \beta_p X_p).$$
No terms associated with any categorical variables appear here. (I have slightly changed the notation at this point: the betas $\beta_i$ now are the coefficients only of the covariates, while the full model includes the alphas $\alpha_j$ for the various categories.)
Comparing odds
Let us compare odds. Suppose a hypothetical individual is a
male patient aged 80–89 with a white cataract, no fundal view, and a small pupil being operated on by a specialist registrar, ...
Associated with this patient (let's call him Charlie) are estimated coefficients for each category: $\alpha_\text{80-89}$ for his age group, $\alpha_\text{male}$ for being male, and so on. Wherever his attribute is the base for its category, the coefficient is zero by convention, as we have seen. Because this is a linear model, the coefficients add. Thus, to the base log odds given above, the log odds for this patient are obtained by adding in
$$\alpha_\text{80-89}+\alpha_\text{male}+\alpha_\text{no Glaucoma}+ \cdots + \alpha_\text{specialist registrar}.$$
This is precisely the amount by which the log odds of this patient vary from the base. To convert from log odds, undo the logarithm and recall that this turns addition into multiplication. Therefore, the base odds must be multiplied by
$$\exp(\alpha_\text{80-89})\exp(\alpha_\text{male})\exp(\alpha_\text{no Glaucoma}) \cdots \exp(\alpha_\text{specialist registrar}).$$
These are the numbers given in the table under "Adjusted OR" (adjusted odds ratio). (It is called "adjusted" because covariates $x_1, \ldots, x_p$ were included in the model. They play no role in any of our calculations, as you will see. It is called a "ratio" because it is precisely the amount by which the base odds must be multiplied to produce the patient's predicted odds: see the first paragraph of this post.) In order in the table, they are $\exp(\alpha_\text{80-89})=1.58$, $\exp(\alpha_\text{male})=1.28$, $\exp(\alpha_\text{no Glaucoma})=1.00$, and so on. According to the article, their product works out to $34.5$. Therefore
$$\text{Odds(Charlie)} = 34.5\times \text{Odds(Base)}.$$
(Notice that the base categories all have odds ratios of $1.00=\exp(0)$, because including $1$ in the product leaves it unchanged. That's how you can spot the base categories in the table.)
Restating the results as probabilities
Finally, let us convert this result to probabilities. We were told the baseline predicted probability is $0.736\%=0.00736$. Therefore, using the formulas relating odds and probabilities derived at the outset, we may compute
$$\text{Odds(Base)} = \frac{0.00736}{1 - 0.00736} = 0.00741.$$
Consequently Charlie's odds are
$$\text{Odds(Charlie)} = 34.5\times 0.00741 = 0.256.$$
Finally, converting this back to probabilities gives
$$\Pr(Y(\text{Charlie})=1) = 1 - \frac{1}{1 + 0.256} = 0.204.$$
|
Help me understand adjusted odds ratio in logistic regression
|
Odds are a way to express chances. Odds ratios are just that: one odds divided by another. That means an odds ratio is what you multiply one odds by to produce another. Let's see how they work in t
|
Help me understand adjusted odds ratio in logistic regression
Odds are a way to express chances. Odds ratios are just that: one odds divided by another. That means an odds ratio is what you multiply one odds by to produce another. Let's see how they work in this common situation.
Converting between odds and probability
The odds of a binary response $Y$ are the ratio of the chance it happens (coded with $1$), written $\Pr(Y=1)$, to the chance it does not (coded with $0$), written $\Pr(Y=0)$:
$$\text{Odds}(Y) = \frac{\Pr(Y=1)}{\Pr(Y=0)} = \frac{\Pr(Y=1)}{1 - \Pr(Y=1)}.$$
The equivalent expression on the right shows it suffices to model $\Pr(Y=1)$ to find the odds. Conversely, note that we can solve
$$\Pr(Y=1) = \frac{\text{Odds}(Y)}{1 + \text{Odds}(Y)} = 1 - \frac{1}{1 + \text{Odds}(Y)}.$$
Logistic regression
Logistic regression models the logarithm of the odds of $Y$ as a linear function of explanatory variables. Most generally, writing these variables as $x_1, \ldots, x_p$, and including a possible constant term in the linear function, we may name the coefficients (which are to be estimated from the data) as $\beta_1,\ldots, \beta_p$ and $\beta_0$. Formally this produces the model
$$\log\left(\text{Odds}(Y)\right) = \beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p.$$
The odds themselves can be recovered by undoing the logarithm:
$$\text{Odds}(Y) = \exp(\beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p).$$
Using categorical variables
Categorical variables, such as age group, gender, presence of Glaucoma, etc., are incorporated by means of "dummy coding." To show that how the variable is coded does not matter, I will provide a simple example of one small group; its generalization to multiple groups should be obvious. In this study one variable is "pupil size," with three categories, "Large", "Medium", and "Small". (The study treats these as purely categorical, apparently paying no attention to their inherent order.) Intuitively, each category has its own odds, say $\alpha_L$ for "Large", $\alpha_M$ for "Medium", and $\alpha_S$ for "Small". This means that, all other things equal,
$$\text{Odds}(Y) = \exp(\color{Blue}{\alpha_L + \beta_0} + \beta_1 x_1 + \cdots + \beta_p x_p)$$
for anybody in the "Large" category,
$$\text{Odds}(Y) = \exp(\color{Blue}{\alpha_M + \beta_0} + \beta_1 x_1 + \cdots + \beta_p x_p)$$
for anybody in the "Medium" category, and
$$\text{Odds}(Y) = \exp(\color{Blue}{\alpha_S + \beta_0} + \beta_1 x_1 + \cdots + \beta_p x_p)$$
for those in the "Small" category.
Creating identifiable coefficients
I have colored the first two coefficients to highlight them, because I want you to notice that they allow a simple change to occur: we could pick any number $\gamma$ and, by adding it to $\beta_0$ and subtracting it from each of $\alpha_L$, $\alpha_M$, and $\alpha_S$, we would not change any predicted odds. This is because of the obvious equivalences of the form
$$\alpha_L + \beta_0 = (\alpha_L - \gamma) + (\gamma + \beta_0 ),$$
etc. Although this presents no problems for the model--it still predicts exactly the same things--it shows that the parameters are not in themselves interpretable. What stays the same when we do this addition-subtraction maneuver are the differences between the coefficients. Conventionally, to address this lack of identifiability, people (and by default, software) choose one of the categories in each variable as the "base" or "reference" and simply stipulate that its coefficient will be zero. This removes the ambiguity.
The paper lists reference categories first; "Large" in this case. Thus, $\alpha_L$ is subtracted from each of $\alpha_L, \alpha_M,$ and $\alpha_S$, and added to $\beta_0$ to compensate.
The log odds for a hypothetical individual falling into all the base categories therefore equals $\beta_0$ plus a bunch of terms associated with all other "covariates"--the non-categorical variables:
$$\text{Odds(Base category)} = \exp(\beta_0 + \beta_1X_1 + \cdots + \beta_p X_p).$$
No terms associated with any categorical variables appear here. (I have slightly changed the notation at this point: the betas $\beta_i$ now are the coefficients only of the covariates, while the full model includes the alphas $\alpha_j$ for the various categories.)
Comparing odds
Let us compare odds. Suppose a hypothetical individual is a
male patient aged 80–89 with a white cataract, no fundal view, and a small pupil being operated on by a specialist registrar, ...
Associated with this patient (let's call him Charlie) are estimated coefficients for each category: $\alpha_\text{80-89}$ for his age group, $\alpha_\text{male}$ for being male, and so on. Wherever his attribute is the base for its category, the coefficient is zero by convention, as we have seen. Because this is a linear model, the coefficients add. Thus, to the base log odds given above, the log odds for this patient are obtained by adding in
$$\alpha_\text{80-89}+\alpha_\text{male}+\alpha_\text{no Glaucoma}+ \cdots + \alpha_\text{specialist registrar}.$$
This is precisely the amount by which the log odds of this patient vary from the base. To convert from log odds, undo the logarithm and recall that this turns addition into multiplication. Therefore, the base odds must be multiplied by
$$\exp(\alpha_\text{80-89})\exp(\alpha_\text{male})\exp(\alpha_\text{no Glaucoma}) \cdots \exp(\alpha_\text{specialist registrar}).$$
These are the numbers given in the table under "Adjusted OR" (adjusted odds ratio). (It is called "adjusted" because covariates $x_1, \ldots, x_p$ were included in the model. They play no role in any of our calculations, as you will see. It is called a "ratio" because it is precisely the amount by which the base odds must be multiplied to produce the patient's predicted odds: see the first paragraph of this post.) In order in the table, they are $\exp(\alpha_\text{80-89})=1.58$, $\exp(\alpha_\text{male})=1.28$, $\exp(\alpha_\text{no Glaucoma})=1.00$, and so on. According to the article, their product works out to $34.5$. Therefore
$$\text{Odds(Charlie)} = 34.5\times \text{Odds(Base)}.$$
(Notice that the base categories all have odds ratios of $1.00=\exp(0)$, because including $1$ in the product leaves it unchanged. That's how you can spot the base categories in the table.)
Restating the results as probabilities
Finally, let us convert this result to probabilities. We were told the baseline predicted probability is $0.736\%=0.00736$. Therefore, using the formulas relating odds and probabilities derived at the outset, we may compute
$$\text{Odds(Base)} = \frac{0.00736}{1 - 0.00736} = 0.00741.$$
Consequently Charlie's odds are
$$\text{Odds(Charlie)} = 34.5\times 0.00741 = 0.256.$$
Finally, converting this back to probabilities gives
$$\Pr(Y(\text{Charlie})=1) = 1 - \frac{1}{1 + 0.256} = 0.204.$$
|
Help me understand adjusted odds ratio in logistic regression
Odds are a way to express chances. Odds ratios are just that: one odds divided by another. That means an odds ratio is what you multiply one odds by to produce another. Let's see how they work in t
|
10,291
|
Topic models and word co-occurrence methods
|
Recently, a huge body of literature discussing how to extract information from written text has grown. Hence I will just describe four milestones/popular models and their advantages/disadvantages and thus highlight (some of) the main differences (or at least what I think are the main/most important differences).
You mention the "easiest" approach, which would be to cluster the documents by matching them against a predefined query of terms (as in PMI). These lexical matching methods however might be inaccurate due to polysemy (multiple meanings) and synonymy (multiple words that have similar meanings) of single terms.
As a remedy, latent semantic indexing (LSI) tries to overcome this by mapping terms and documents into a latent semantic space via a singular value decomposition. The LSI results are more robust indicators of meaning than individual terms would be. However, one drawback of LSI is that it lacks in terms of solid probabilistic foundation.
This was partly solved by the invention of probabilistic LSI (pLSI). In pLSI models each word in a document is drawn from a mixture model specified via multinomial random variables (which also allows higher-order co-occurences as @sviatoslav hong mentioned). This was an important step forward in probabilistic text modeling, but was incomplete in the sense that it offers no probabilistic structure at the level of documents.
Latent Dirichlet Allocation (LDA) alleviates this and was the first fully probabilistic model for text clustering. Blei et al. (2003) show that pLSI is a maximum a-posteriori estimated LDA model under a uniform Dirichlet prior.
Note that the models mentioned above (LSI, pLSI, LDA) have in common that they are based on the “bag-of-words” assumption - i.e. that within a document, words are exchangeable, i.e. the order of words in a document can be neglected. This assumption of exchangeability offers a further justification for LDA over the other approaches: Assuming that not only words within documents are exchangeable, but also documents, i.e., the order of documents within a corpus can be neglected, De Finetti's theorem states that any set of exchangeable random variables has a representation as a mixture distribution. Thus if exchangeability for documents and words within documents is assumed, a mixture model for both is needed. Exactly this is what LDA generally achieves but PMI or LSI do not (and even pLSI not as beautiful as LDA).
|
Topic models and word co-occurrence methods
|
Recently, a huge body of literature discussing how to extract information from written text has grown. Hence I will just describe four milestones/popular models and their advantages/disadvantages and
|
Topic models and word co-occurrence methods
Recently, a huge body of literature discussing how to extract information from written text has grown. Hence I will just describe four milestones/popular models and their advantages/disadvantages and thus highlight (some of) the main differences (or at least what I think are the main/most important differences).
You mention the "easiest" approach, which would be to cluster the documents by matching them against a predefined query of terms (as in PMI). These lexical matching methods however might be inaccurate due to polysemy (multiple meanings) and synonymy (multiple words that have similar meanings) of single terms.
As a remedy, latent semantic indexing (LSI) tries to overcome this by mapping terms and documents into a latent semantic space via a singular value decomposition. The LSI results are more robust indicators of meaning than individual terms would be. However, one drawback of LSI is that it lacks in terms of solid probabilistic foundation.
This was partly solved by the invention of probabilistic LSI (pLSI). In pLSI models each word in a document is drawn from a mixture model specified via multinomial random variables (which also allows higher-order co-occurences as @sviatoslav hong mentioned). This was an important step forward in probabilistic text modeling, but was incomplete in the sense that it offers no probabilistic structure at the level of documents.
Latent Dirichlet Allocation (LDA) alleviates this and was the first fully probabilistic model for text clustering. Blei et al. (2003) show that pLSI is a maximum a-posteriori estimated LDA model under a uniform Dirichlet prior.
Note that the models mentioned above (LSI, pLSI, LDA) have in common that they are based on the “bag-of-words” assumption - i.e. that within a document, words are exchangeable, i.e. the order of words in a document can be neglected. This assumption of exchangeability offers a further justification for LDA over the other approaches: Assuming that not only words within documents are exchangeable, but also documents, i.e., the order of documents within a corpus can be neglected, De Finetti's theorem states that any set of exchangeable random variables has a representation as a mixture distribution. Thus if exchangeability for documents and words within documents is assumed, a mixture model for both is needed. Exactly this is what LDA generally achieves but PMI or LSI do not (and even pLSI not as beautiful as LDA).
|
Topic models and word co-occurrence methods
Recently, a huge body of literature discussing how to extract information from written text has grown. Hence I will just describe four milestones/popular models and their advantages/disadvantages and
|
10,292
|
Topic models and word co-occurrence methods
|
I might be 3 years late but I want to follow up your question on the example of "high-order of co-occurrences".
Basically, if term t1 co-occurs with term t2 that co-occurs with term t3, then term t1 is the 2nd-order co-occurrence with term t3. You can go to higher order if you want but at the end you control how similar two words should be.
|
Topic models and word co-occurrence methods
|
I might be 3 years late but I want to follow up your question on the example of "high-order of co-occurrences".
Basically, if term t1 co-occurs with term t2 that co-occurs with term t3, then term t1
|
Topic models and word co-occurrence methods
I might be 3 years late but I want to follow up your question on the example of "high-order of co-occurrences".
Basically, if term t1 co-occurs with term t2 that co-occurs with term t3, then term t1 is the 2nd-order co-occurrence with term t3. You can go to higher order if you want but at the end you control how similar two words should be.
|
Topic models and word co-occurrence methods
I might be 3 years late but I want to follow up your question on the example of "high-order of co-occurrences".
Basically, if term t1 co-occurs with term t2 that co-occurs with term t3, then term t1
|
10,293
|
Topic models and word co-occurrence methods
|
LDA can capture higher-order of co-occurrences of terms (due to the assumption of each topic is a multinomial distribution over terms), which is not possible by just computing PMI between terms.
|
Topic models and word co-occurrence methods
|
LDA can capture higher-order of co-occurrences of terms (due to the assumption of each topic is a multinomial distribution over terms), which is not possible by just computing PMI between terms.
|
Topic models and word co-occurrence methods
LDA can capture higher-order of co-occurrences of terms (due to the assumption of each topic is a multinomial distribution over terms), which is not possible by just computing PMI between terms.
|
Topic models and word co-occurrence methods
LDA can capture higher-order of co-occurrences of terms (due to the assumption of each topic is a multinomial distribution over terms), which is not possible by just computing PMI between terms.
|
10,294
|
What is a white noise process?
|
A white noise process is one with a mean zero and no correlation between its values at different times. See the 'white random process' section of Wikipedia's article on white noise.
|
What is a white noise process?
|
A white noise process is one with a mean zero and no correlation between its values at different times. See the 'white random process' section of Wikipedia's article on white noise.
|
What is a white noise process?
A white noise process is one with a mean zero and no correlation between its values at different times. See the 'white random process' section of Wikipedia's article on white noise.
|
What is a white noise process?
A white noise process is one with a mean zero and no correlation between its values at different times. See the 'white random process' section of Wikipedia's article on white noise.
|
10,295
|
What is a white noise process?
|
A white noise process is a random process of random variables that are uncorrelated, have mean zero, and a finite variance.
Formally, $X(t)$ is a white noise process if $$E(X(t)) = 0, E(X(t)^2) = S^2\text{, and } E(X(t)X(h)) = 0 \text{ for } t\neq h\text{.}$$
A slightly stronger condition is that they are independent from one another; this is an "independent white noise process."
|
What is a white noise process?
|
A white noise process is a random process of random variables that are uncorrelated, have mean zero, and a finite variance.
Formally, $X(t)$ is a white noise process if $$E(X(t)) = 0, E(X(t)^2) = S^2
|
What is a white noise process?
A white noise process is a random process of random variables that are uncorrelated, have mean zero, and a finite variance.
Formally, $X(t)$ is a white noise process if $$E(X(t)) = 0, E(X(t)^2) = S^2\text{, and } E(X(t)X(h)) = 0 \text{ for } t\neq h\text{.}$$
A slightly stronger condition is that they are independent from one another; this is an "independent white noise process."
|
What is a white noise process?
A white noise process is a random process of random variables that are uncorrelated, have mean zero, and a finite variance.
Formally, $X(t)$ is a white noise process if $$E(X(t)) = 0, E(X(t)^2) = S^2
|
10,296
|
What is a white noise process?
|
I myself usually think of white noise as an iid sequence with zero mean. At different times values of the process are then independent of each other, which is much stronger requirement than correlation zero. What is the best with this definition that it works in any context.
Side note. I only explained my intuition, the correct definition of white noise is given by @onestop. The definition I gave is mathematically defined as white noise in strict sense.
|
What is a white noise process?
|
I myself usually think of white noise as an iid sequence with zero mean. At different times values of the process are then independent of each other, which is much stronger requirement than correlatio
|
What is a white noise process?
I myself usually think of white noise as an iid sequence with zero mean. At different times values of the process are then independent of each other, which is much stronger requirement than correlation zero. What is the best with this definition that it works in any context.
Side note. I only explained my intuition, the correct definition of white noise is given by @onestop. The definition I gave is mathematically defined as white noise in strict sense.
|
What is a white noise process?
I myself usually think of white noise as an iid sequence with zero mean. At different times values of the process are then independent of each other, which is much stronger requirement than correlatio
|
10,297
|
Generative vs discriminative models (in Bayesian context)
|
Both are used in supervised learning where you want to learn a rule that maps input x to output y, given a number of training examples of the form $\{(x_i,y_i)\}$. A generative model (e.g., naive Bayes) explicitly models the joint probability distribution $p(x,y)$ and then uses the Bayes rule to compute $p(y|x)$. On the other hand, a discriminative model (e.g., logistic regression) directly models $p(y|x)$.
Some people argue that the discriminative model is better in the sense that it directly models the quantity you care about $(y)$, so you don't have to spend your modeling efforts on the input x (you need to compute $p(x|y)$ as well in a generative model). However, the generative model has its own advantages such as the capability of dealing with missing data, etc. For some comparison, you can take a look at this paper: On Discriminative vs. Generative classifiers: A comparison of logistic regression and naive Bayes
There can be cases when one model is better than the other (e.g., discriminative models usually tend to do better if you have lots of data; generative models may be better if you have some extra unlabeled data). In fact, there exists hybird models too that try to bring in the best of both worlds. See this paper for an example: Principled hybrids of generative and discriminative models
|
Generative vs discriminative models (in Bayesian context)
|
Both are used in supervised learning where you want to learn a rule that maps input x to output y, given a number of training examples of the form $\{(x_i,y_i)\}$. A generative model (e.g., naive Baye
|
Generative vs discriminative models (in Bayesian context)
Both are used in supervised learning where you want to learn a rule that maps input x to output y, given a number of training examples of the form $\{(x_i,y_i)\}$. A generative model (e.g., naive Bayes) explicitly models the joint probability distribution $p(x,y)$ and then uses the Bayes rule to compute $p(y|x)$. On the other hand, a discriminative model (e.g., logistic regression) directly models $p(y|x)$.
Some people argue that the discriminative model is better in the sense that it directly models the quantity you care about $(y)$, so you don't have to spend your modeling efforts on the input x (you need to compute $p(x|y)$ as well in a generative model). However, the generative model has its own advantages such as the capability of dealing with missing data, etc. For some comparison, you can take a look at this paper: On Discriminative vs. Generative classifiers: A comparison of logistic regression and naive Bayes
There can be cases when one model is better than the other (e.g., discriminative models usually tend to do better if you have lots of data; generative models may be better if you have some extra unlabeled data). In fact, there exists hybird models too that try to bring in the best of both worlds. See this paper for an example: Principled hybrids of generative and discriminative models
|
Generative vs discriminative models (in Bayesian context)
Both are used in supervised learning where you want to learn a rule that maps input x to output y, given a number of training examples of the form $\{(x_i,y_i)\}$. A generative model (e.g., naive Baye
|
10,298
|
Generative vs discriminative models (in Bayesian context)
|
One addition to the above answer:
Since discriminant cares P(Y|X) only, while generative cares P(X,Y) and P(X) at the same time, in order to predict P(Y|X) well, the generative model has less degree of freedom in the model compared to discriminant model. So generative model is more robust, less prone to overfitting while discriminant is the other way around.
That explains the above answer
There can be cases when one model is better than the other (e.g., discriminative models usually tend to do better if you have lots of data; generative models may be better if you have some extra unlabeled data).
|
Generative vs discriminative models (in Bayesian context)
|
One addition to the above answer:
Since discriminant cares P(Y|X) only, while generative cares P(X,Y) and P(X) at the same time, in order to predict P(Y|X) well, the generative model has less degree o
|
Generative vs discriminative models (in Bayesian context)
One addition to the above answer:
Since discriminant cares P(Y|X) only, while generative cares P(X,Y) and P(X) at the same time, in order to predict P(Y|X) well, the generative model has less degree of freedom in the model compared to discriminant model. So generative model is more robust, less prone to overfitting while discriminant is the other way around.
That explains the above answer
There can be cases when one model is better than the other (e.g., discriminative models usually tend to do better if you have lots of data; generative models may be better if you have some extra unlabeled data).
|
Generative vs discriminative models (in Bayesian context)
One addition to the above answer:
Since discriminant cares P(Y|X) only, while generative cares P(X,Y) and P(X) at the same time, in order to predict P(Y|X) well, the generative model has less degree o
|
10,299
|
From a statistical perspective, can one infer causality using propensity scores with an observational study?
|
At the beginning of an article aiming at promoting the use of PSs in epidemiology, Oakes and Church (1) cited Hernán and Robins's claims about confounding effect in epidemiology (2):
Can you guarantee that the results
from your observational study are
unaffected by unmeasured confounding?
The only answer an epidemiologist can
provide is ‘no’.
This is not just to say that we cannot ensure that results from observational studies are unbiased or useless (because, as @propofol said, their results can be useful for designing RCTs), but also that PSs do certainly not offer a complete solution to this problem, or at least do not necessarily yield better results than other matching or multivariate methods (see e.g. (10)).
Propensity scores (PS) are, by construction, probabilistic not causal indicators. The choice of the covariates that enter the propensity score function is a key element for ensuring its reliability, and their weakness, as has been said, mainly stands from not controlling for unobserved confounders (which is quite likely in retrospective or case-control studies). Others factors have to be considered: (a) model misspecification will impact direct effect estimates (not really more than in the OLS case, though), (b) there may be missing data at the level of the covariates, (c) PSs do not overcome synergistic effects which are know to affect causal interpretation (8,9).
As for references, I found Roger Newson's slides -- Causality, confounders, and propensity scores -- relatively well-balanced about the pros and cons of using propensity scores, with illustrations from real studies.
There were also several good papers discussing the use of propensity scores in observational studies or environmental epidemiology two years ago in Statistics in Medicine, and I enclose a couple of them at the end (3-6). But I like Pearl's review (7) because it offers a larger perspective on causality issues (PSs are discussed p. 117 and 130). Obviously, you will find many more illustrations by looking at applied research. I would like to add two recent articles from William R Shadish that came across Andrew Gelman's website (11,12). The use of propensity scores is discussed, but the two papers more largely focus on causal inference in observational studies (and how it compare to randomized settings).
References
Oakes, J.M. and Church, T.R. (2007). Invited Commentary: Advancing Propensity Score Methods in Epidemiology. American Journal of Epidemiology, 165(10), 1119-1121.
Hernan M.A. and Robins J.M. (2006). Instruments for causal inference: an epidemiologist's dream? Epidemiology, 17, 360-72.
Rubin, D. (2007). The design versus the analysis of observational studies for causal effects: Parallels with the design of randomized trials. Statistics in Medicine, 26, 20–36.
Shrier, I. (2008). Letter to the editor. Statistics in Medicine, 27, 2740–2741.
Pearl, J. (2009). Remarks on the method of propensity score. Statistics in Medicine, 28, 1415–1424.
Stuart, E.A. (2008). Developing practical recommendations for the use of propensity scores: Discussion of ‘A critical appraisal of propensity score matching in the medical literature between 1996 and 2003’ by Peter Austin. Statistics in Medicine, 27, 2062–2065.
Pearl, J. (2009). Causal inference in statistics: An overview. Statistics Surveys, 3, 96-146.
Oakes, J.M. and Johnson, P.J. (2006). Propensity score matching for social epidemiology. In Methods in Social Epidemiology, J.M. Oakes and S. Kaufman (Eds.), pp. 364-386. Jossez-Bass.
Höfler, M (2005). Causal inference based on counterfactuals. BMC Medical Research Methodology, 5, 28.
Winkelmayer, W.C. and Kurth, T. (2004). Propensity scores: help or hype? Nephrology Dialysis Transplantation, 19(7), 1671-1673.
Shadish, W.R., Clark, M.H., and Steiner, P.M. (2008). Can Nonrandomized Experiments Yield Accurate Answers? A Randomized Experiment Comparing Random and Nonrandom Assignments. JASA, 103(484), 1334-1356.
Cook, T.D., Shadish, W.R., and Wong, V.C. (2008). Three Conditions under Which Experiments and Observational Studies Produce Comparable Causal Estimates: New Findings from Within-Study Comparisons. Journal of Policy Analysis and Management, 27(4), 724–750.
|
From a statistical perspective, can one infer causality using propensity scores with an observationa
|
At the beginning of an article aiming at promoting the use of PSs in epidemiology, Oakes and Church (1) cited Hernán and Robins's claims about confounding effect in epidemiology (2):
Can you guarante
|
From a statistical perspective, can one infer causality using propensity scores with an observational study?
At the beginning of an article aiming at promoting the use of PSs in epidemiology, Oakes and Church (1) cited Hernán and Robins's claims about confounding effect in epidemiology (2):
Can you guarantee that the results
from your observational study are
unaffected by unmeasured confounding?
The only answer an epidemiologist can
provide is ‘no’.
This is not just to say that we cannot ensure that results from observational studies are unbiased or useless (because, as @propofol said, their results can be useful for designing RCTs), but also that PSs do certainly not offer a complete solution to this problem, or at least do not necessarily yield better results than other matching or multivariate methods (see e.g. (10)).
Propensity scores (PS) are, by construction, probabilistic not causal indicators. The choice of the covariates that enter the propensity score function is a key element for ensuring its reliability, and their weakness, as has been said, mainly stands from not controlling for unobserved confounders (which is quite likely in retrospective or case-control studies). Others factors have to be considered: (a) model misspecification will impact direct effect estimates (not really more than in the OLS case, though), (b) there may be missing data at the level of the covariates, (c) PSs do not overcome synergistic effects which are know to affect causal interpretation (8,9).
As for references, I found Roger Newson's slides -- Causality, confounders, and propensity scores -- relatively well-balanced about the pros and cons of using propensity scores, with illustrations from real studies.
There were also several good papers discussing the use of propensity scores in observational studies or environmental epidemiology two years ago in Statistics in Medicine, and I enclose a couple of them at the end (3-6). But I like Pearl's review (7) because it offers a larger perspective on causality issues (PSs are discussed p. 117 and 130). Obviously, you will find many more illustrations by looking at applied research. I would like to add two recent articles from William R Shadish that came across Andrew Gelman's website (11,12). The use of propensity scores is discussed, but the two papers more largely focus on causal inference in observational studies (and how it compare to randomized settings).
References
Oakes, J.M. and Church, T.R. (2007). Invited Commentary: Advancing Propensity Score Methods in Epidemiology. American Journal of Epidemiology, 165(10), 1119-1121.
Hernan M.A. and Robins J.M. (2006). Instruments for causal inference: an epidemiologist's dream? Epidemiology, 17, 360-72.
Rubin, D. (2007). The design versus the analysis of observational studies for causal effects: Parallels with the design of randomized trials. Statistics in Medicine, 26, 20–36.
Shrier, I. (2008). Letter to the editor. Statistics in Medicine, 27, 2740–2741.
Pearl, J. (2009). Remarks on the method of propensity score. Statistics in Medicine, 28, 1415–1424.
Stuart, E.A. (2008). Developing practical recommendations for the use of propensity scores: Discussion of ‘A critical appraisal of propensity score matching in the medical literature between 1996 and 2003’ by Peter Austin. Statistics in Medicine, 27, 2062–2065.
Pearl, J. (2009). Causal inference in statistics: An overview. Statistics Surveys, 3, 96-146.
Oakes, J.M. and Johnson, P.J. (2006). Propensity score matching for social epidemiology. In Methods in Social Epidemiology, J.M. Oakes and S. Kaufman (Eds.), pp. 364-386. Jossez-Bass.
Höfler, M (2005). Causal inference based on counterfactuals. BMC Medical Research Methodology, 5, 28.
Winkelmayer, W.C. and Kurth, T. (2004). Propensity scores: help or hype? Nephrology Dialysis Transplantation, 19(7), 1671-1673.
Shadish, W.R., Clark, M.H., and Steiner, P.M. (2008). Can Nonrandomized Experiments Yield Accurate Answers? A Randomized Experiment Comparing Random and Nonrandom Assignments. JASA, 103(484), 1334-1356.
Cook, T.D., Shadish, W.R., and Wong, V.C. (2008). Three Conditions under Which Experiments and Observational Studies Produce Comparable Causal Estimates: New Findings from Within-Study Comparisons. Journal of Policy Analysis and Management, 27(4), 724–750.
|
From a statistical perspective, can one infer causality using propensity scores with an observationa
At the beginning of an article aiming at promoting the use of PSs in epidemiology, Oakes and Church (1) cited Hernán and Robins's claims about confounding effect in epidemiology (2):
Can you guarante
|
10,300
|
From a statistical perspective, can one infer causality using propensity scores with an observational study?
|
Propensity scores are typically used in the matching literature. Propensity scores use pre-treatment covariates to estimate the probability of receiving treatment. Essentially, a regression (either just regular OLS or logit, probit, etc) is used to calculate the propensity score with treatment as your outcome and pre-treatment variables are your covariates. Once a good estimate of the propensity score is obtained, subjects with similar propensity scores, but different treatments received, are matched to one another. The treatment effect is the difference in means between these two groups.
Rosenbaum and Rubin (1983) show that matching treated and control subjects using just the propensity score is sufficient to remove all bias in the estimate of the treatment effect stemming from the observed pre-treatment covariates used to construct the score. Note that this proof requires the use of the true propensity score, rather than an estimate. The advantage of this approach is it turns a problem of matching in multiple dimensions (one for each pre-treatment covariate) into a univariate matching case---a great simplification.
Rosenbaum, Paul R. and Donald B. Rubin. 1983. "The Central Role of the Propensity Score in Observational Studies for Causal Effects." Biometrika. 70(1): 41--55.
|
From a statistical perspective, can one infer causality using propensity scores with an observationa
|
Propensity scores are typically used in the matching literature. Propensity scores use pre-treatment covariates to estimate the probability of receiving treatment. Essentially, a regression (either ju
|
From a statistical perspective, can one infer causality using propensity scores with an observational study?
Propensity scores are typically used in the matching literature. Propensity scores use pre-treatment covariates to estimate the probability of receiving treatment. Essentially, a regression (either just regular OLS or logit, probit, etc) is used to calculate the propensity score with treatment as your outcome and pre-treatment variables are your covariates. Once a good estimate of the propensity score is obtained, subjects with similar propensity scores, but different treatments received, are matched to one another. The treatment effect is the difference in means between these two groups.
Rosenbaum and Rubin (1983) show that matching treated and control subjects using just the propensity score is sufficient to remove all bias in the estimate of the treatment effect stemming from the observed pre-treatment covariates used to construct the score. Note that this proof requires the use of the true propensity score, rather than an estimate. The advantage of this approach is it turns a problem of matching in multiple dimensions (one for each pre-treatment covariate) into a univariate matching case---a great simplification.
Rosenbaum, Paul R. and Donald B. Rubin. 1983. "The Central Role of the Propensity Score in Observational Studies for Causal Effects." Biometrika. 70(1): 41--55.
|
From a statistical perspective, can one infer causality using propensity scores with an observationa
Propensity scores are typically used in the matching literature. Propensity scores use pre-treatment covariates to estimate the probability of receiving treatment. Essentially, a regression (either ju
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.