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
31,301
Proving the LATE Theorem of Angrist and Imbens 1994
For the first part you stated that you have a “valid” instrument. This implies for a binary treatment and instrument that $Cov(D_i,Z_i) \neq 0$ is equivalent to $P(D_i = 1|Z_i = 1) \neq P(D_i = 1|Z_i = 0)$, i.e. the instrument has an effect on whether the treatment is chosen or not. This observation which also should be stated in the Angrist and Imbens paper is key for the rest of their proof. For the first stage they assume that $P(D_i = 1|Z_i = 1) > P(D_i = 1|Z_i = 0)$, meaning that the number of compliers ($C_i)$ is larger than that of defiers ($F_i$). Using the exclusion restriction (for every $z \in$ {$0;1$} we have that $Y_{iz} = Y_{i0z} = Y_{i1z}$, i.e. the instrument does not have a direct effect on the outcome) you can write the difference in the share of compliers and defiers in the population as $$ \begin{align} P(D_i = 1|Z_i = 1) - P(D_i = 1|Z_i = 0) &= P(D_{i1} = 1|Z_i = 1) - P(D_{i0} = 1|Z_i = 0) \newline &= P(D_{i1} = 1) - P(D_{i0} = 0) \newline &= \left[ P(D_{i1} = 1, D_{i0} = 0) + P(D_{i1} = 1, D_{i0} = 1) \right] - \left[ P(D_{i1} = 0, D_{i0} = 1) + P(D_{i1} = 1, D_{i0} = 1) \right] \newline &= P(C_i) – P(F_i) \end{align} $$ where the second step uses independence to get rid of the conditioning on $Z_i$ because potential outcomes are independent of the instrument. The third step uses the law of total probability. In the last step you then only need to use monotonicity which basically assumes that defiers do not exist, so $P(F_i) = 0$ and you get $$P(C_i) = P(D_i = 1|Z_i = 1) - P(D_i = 1|Z_i = 0).$$ This would be your first stage coefficient in a 2SLS regression. The monotonicity assumption is crucial for this and one should think hard about possible reasons for why it might be violated (however, monotonicity can be relaxed, see for instance de Chaisemartin (2012) “All you need is LATE”). The second part of the proof follows a similar path. For this you need to remember that the observed treatment status is $$D_i = Z_iD_{i1} + (1-Z_i)D_{i0}$$ because you cannot observe both potential outcomes for the same individual. In this way you can relate the observed outcome to the potential outcome, the treatment status, and the instrument as $$Y_i = (1-Z_i)(1-D_i)Y_{i00} + Z_i(1-D_i)Y_{i10} + (1-Z_i)D_iY_{i01} + Z_iD_iY_{i11}$$ For the second part of the proof take the difference in the expected outcome with the instrument being switched on and on, and use the previous representation of observed outcomes and the exclusion restriction in the first step to get: $$\begin{align} E(Y_i|Z_i = 1) – E(Y_i|Z_i=0) &= E(Y_{i1}D_i + Y_{i0}(1-D_i)|Z_i=0) \newline &- E(Y_{i1}D_i + Y_{i0}(1-D_i)|Z_i=1)\newline &= E(Y_{i1}D_{i1} + Y_{i0}(1-D_{i1})|Z_i=1) \newline &- E(Y_{i1}D_{i0} + Y_{i0}(1-D_{i0})|Z_i=0) \newline &= E(Y_{i1}D_{i1} + Y_{i0}(1-D_{i1})) \newline &- E(Y_{i1}D_{i0} + Y_{i0}(1-D_{i0})) \newline &= E((Y_{i1}-Y_{i0})(D_{i1}-D_{i0})) \newline &= E(Y_{i1}-Y_{i0}|D_{i1}-D_{i0}=1)P(D_{i1}-D_{i0} = 1) \newline &- E(Y_{i1}-Y_{i0}|D_{i1}-D_{i0}=-1)P(D_{i1}-D_{i0} = -1) \newline &= E(Y_{i1}-Y_{i0}|C_i)P(C_i) - E(Y_{i1}-Y_{i0}|F_i)P(F_i) \newline &= E(Y_{i1}-Y_{i0}|C_i)P(C_i) \end{align} $$ Now this was quite a bit of work but it's not too bad if you know the steps you need to take. For the second line use again the exclusion restriction to write out the potential treatment states. In the third line use independence to get rid of the conditioning on $Z_i$ as before. In the fourth line you just factor terms. The fifth line uses the law of iterated expectations. The last line arises due to the monotonicity assumption, i.e. $P(F_i)=0$. Then you just need to divide as a last step and you arrive at $$\begin{align} E(Y_{i1}-Y_{i0}|C_i) &= \frac{E(Y_i|Z_i = 1) – E(Y_i|Z_i=0)}{P(C_i)} \newline &= \frac{E(Y_i|Z_i = 1) – E(Y_i|Z_i=0)}{P(D_i = 1|Z_i = 1) - P(D_i = 1|Z_i = 0)} \newline &= \frac{E(Y_i|Z_i = 1) – E(Y_i|Z_i=0)}{E(D_i|Z_i = 1) - E(D_i|Z_i = 0)} \end{align}$$ since $D_i$ and $Z_i$ are binary. This should show how you combine the two proofs and how they arrive at the final expression.
Proving the LATE Theorem of Angrist and Imbens 1994
For the first part you stated that you have a “valid” instrument. This implies for a binary treatment and instrument that $Cov(D_i,Z_i) \neq 0$ is equivalent to $P(D_i = 1|Z_i = 1) \neq P(D_i = 1|Z_i
Proving the LATE Theorem of Angrist and Imbens 1994 For the first part you stated that you have a “valid” instrument. This implies for a binary treatment and instrument that $Cov(D_i,Z_i) \neq 0$ is equivalent to $P(D_i = 1|Z_i = 1) \neq P(D_i = 1|Z_i = 0)$, i.e. the instrument has an effect on whether the treatment is chosen or not. This observation which also should be stated in the Angrist and Imbens paper is key for the rest of their proof. For the first stage they assume that $P(D_i = 1|Z_i = 1) > P(D_i = 1|Z_i = 0)$, meaning that the number of compliers ($C_i)$ is larger than that of defiers ($F_i$). Using the exclusion restriction (for every $z \in$ {$0;1$} we have that $Y_{iz} = Y_{i0z} = Y_{i1z}$, i.e. the instrument does not have a direct effect on the outcome) you can write the difference in the share of compliers and defiers in the population as $$ \begin{align} P(D_i = 1|Z_i = 1) - P(D_i = 1|Z_i = 0) &= P(D_{i1} = 1|Z_i = 1) - P(D_{i0} = 1|Z_i = 0) \newline &= P(D_{i1} = 1) - P(D_{i0} = 0) \newline &= \left[ P(D_{i1} = 1, D_{i0} = 0) + P(D_{i1} = 1, D_{i0} = 1) \right] - \left[ P(D_{i1} = 0, D_{i0} = 1) + P(D_{i1} = 1, D_{i0} = 1) \right] \newline &= P(C_i) – P(F_i) \end{align} $$ where the second step uses independence to get rid of the conditioning on $Z_i$ because potential outcomes are independent of the instrument. The third step uses the law of total probability. In the last step you then only need to use monotonicity which basically assumes that defiers do not exist, so $P(F_i) = 0$ and you get $$P(C_i) = P(D_i = 1|Z_i = 1) - P(D_i = 1|Z_i = 0).$$ This would be your first stage coefficient in a 2SLS regression. The monotonicity assumption is crucial for this and one should think hard about possible reasons for why it might be violated (however, monotonicity can be relaxed, see for instance de Chaisemartin (2012) “All you need is LATE”). The second part of the proof follows a similar path. For this you need to remember that the observed treatment status is $$D_i = Z_iD_{i1} + (1-Z_i)D_{i0}$$ because you cannot observe both potential outcomes for the same individual. In this way you can relate the observed outcome to the potential outcome, the treatment status, and the instrument as $$Y_i = (1-Z_i)(1-D_i)Y_{i00} + Z_i(1-D_i)Y_{i10} + (1-Z_i)D_iY_{i01} + Z_iD_iY_{i11}$$ For the second part of the proof take the difference in the expected outcome with the instrument being switched on and on, and use the previous representation of observed outcomes and the exclusion restriction in the first step to get: $$\begin{align} E(Y_i|Z_i = 1) – E(Y_i|Z_i=0) &= E(Y_{i1}D_i + Y_{i0}(1-D_i)|Z_i=0) \newline &- E(Y_{i1}D_i + Y_{i0}(1-D_i)|Z_i=1)\newline &= E(Y_{i1}D_{i1} + Y_{i0}(1-D_{i1})|Z_i=1) \newline &- E(Y_{i1}D_{i0} + Y_{i0}(1-D_{i0})|Z_i=0) \newline &= E(Y_{i1}D_{i1} + Y_{i0}(1-D_{i1})) \newline &- E(Y_{i1}D_{i0} + Y_{i0}(1-D_{i0})) \newline &= E((Y_{i1}-Y_{i0})(D_{i1}-D_{i0})) \newline &= E(Y_{i1}-Y_{i0}|D_{i1}-D_{i0}=1)P(D_{i1}-D_{i0} = 1) \newline &- E(Y_{i1}-Y_{i0}|D_{i1}-D_{i0}=-1)P(D_{i1}-D_{i0} = -1) \newline &= E(Y_{i1}-Y_{i0}|C_i)P(C_i) - E(Y_{i1}-Y_{i0}|F_i)P(F_i) \newline &= E(Y_{i1}-Y_{i0}|C_i)P(C_i) \end{align} $$ Now this was quite a bit of work but it's not too bad if you know the steps you need to take. For the second line use again the exclusion restriction to write out the potential treatment states. In the third line use independence to get rid of the conditioning on $Z_i$ as before. In the fourth line you just factor terms. The fifth line uses the law of iterated expectations. The last line arises due to the monotonicity assumption, i.e. $P(F_i)=0$. Then you just need to divide as a last step and you arrive at $$\begin{align} E(Y_{i1}-Y_{i0}|C_i) &= \frac{E(Y_i|Z_i = 1) – E(Y_i|Z_i=0)}{P(C_i)} \newline &= \frac{E(Y_i|Z_i = 1) – E(Y_i|Z_i=0)}{P(D_i = 1|Z_i = 1) - P(D_i = 1|Z_i = 0)} \newline &= \frac{E(Y_i|Z_i = 1) – E(Y_i|Z_i=0)}{E(D_i|Z_i = 1) - E(D_i|Z_i = 0)} \end{align}$$ since $D_i$ and $Z_i$ are binary. This should show how you combine the two proofs and how they arrive at the final expression.
Proving the LATE Theorem of Angrist and Imbens 1994 For the first part you stated that you have a “valid” instrument. This implies for a binary treatment and instrument that $Cov(D_i,Z_i) \neq 0$ is equivalent to $P(D_i = 1|Z_i = 1) \neq P(D_i = 1|Z_i
31,302
Proving the LATE Theorem of Angrist and Imbens 1994
There are four types of people: Never Takers (NT): $D = 0$ for both values of Z Defiers (DF): $D=0$ when $Z =1$ and $D=1$ when $Z =0$ Compliers (C): $D=1$ when $Z =1$ and $D=0$ when $Z =0$ Always Takers (AT): $D =1$ for both values of $Z$. The formula for the Wald estimator is: $$\Delta_{IV} = \frac{E(Y \vert Z=1)−E(Y \vert Z=0)}{Pr(D=1 \vert Z =1)−Pr(D=1 \vert Z =0)}$$ Using our 4 groups and the basic rules of probability, we can rewrite the two numerator pieces as: $$E(Y \vert Z=1)=E(Y_1 \vert AT)\cdot Pr(AT)+E(Y_1 \vert C)\cdot Pr(C)+E(Y_0 \vert DF) \cdot Pr(DF)+E(Y_0 \vert NT) \cdot Pr(NT)$$ and $$E(Y \vert Z=0)=E(Y_1 \vert AT)\cdot Pr(AT)+E(Y_0 \vert C)\cdot Pr(C)+E(Y_1 \vert DF) \cdot Pr(DF)+E(Y_0 \vert NT) \cdot Pr(NT) $$ The two denominator terms are: $$ Pr(D=1 \vert Z =1)=Pr(D=1 \vert Z =1,AT) \cdot Pr(AT)+Pr(D=1 \vert Z =1,C) \cdot Pr(C) \\ =Pr(AT)+Pr(C) $$ and $$ Pr(D=1 \vert Z =0)=Pr(D=1 \vert Z = 0,AT) \cdot Pr(AT)+Pr(D=1 \vert Z =0,DF) \cdot Pr(DF) \\ =Pr(AT)+Pr(DF)$$ The first of these corresponds to your first expression. Coming back to the Wald formula and plugging these in, we see that some of these terms cancel out in the subtraction, leaving $$ \Delta_{IV} =\frac{[E(Y_1 \vert C) \cdot Pr(C)+E(Y_0 \vert D) \cdot Pr(D)]−[E(Y_0 \vert C) \cdot Pr(C)+E(Y_1 \vert DF) \cdot Pr(DF)]}{Pr(C) − Pr(DF)} $$ This yields some insight. The Wald IV estimator is a weighted average of the treatment effect on the compliers and the negative of the treatment effect on the defiers. Now we make two assumptions. First, we assume monotonicity, so that the instrument can only increase or decrease the probability of participation. This means that $Pr(DF) = 0$. The monotonicity assumption is equivalent to assuming an index function model for treatment. The second assumption is that there are some compliers, which is to say that $Pr(C) > 0$. The behavior of some individuals must be altered by the instrument. This should be the case if the instrument is relevant. These two assumptions produce $$\Delta_{IV} =\frac{E(Y_1 \vert C) \cdot Pr(C)−E(Y_0 \vert C) \cdot Pr(C)}{Pr(C)}=E(Y_1 \vert C)−E(Y_0 \vert C)=LATE.$$
Proving the LATE Theorem of Angrist and Imbens 1994
There are four types of people: Never Takers (NT): $D = 0$ for both values of Z Defiers (DF): $D=0$ when $Z =1$ and $D=1$ when $Z =0$ Compliers (C): $D=1$ when $Z =1$ and $D=0$ when $Z =0$ Always Tak
Proving the LATE Theorem of Angrist and Imbens 1994 There are four types of people: Never Takers (NT): $D = 0$ for both values of Z Defiers (DF): $D=0$ when $Z =1$ and $D=1$ when $Z =0$ Compliers (C): $D=1$ when $Z =1$ and $D=0$ when $Z =0$ Always Takers (AT): $D =1$ for both values of $Z$. The formula for the Wald estimator is: $$\Delta_{IV} = \frac{E(Y \vert Z=1)−E(Y \vert Z=0)}{Pr(D=1 \vert Z =1)−Pr(D=1 \vert Z =0)}$$ Using our 4 groups and the basic rules of probability, we can rewrite the two numerator pieces as: $$E(Y \vert Z=1)=E(Y_1 \vert AT)\cdot Pr(AT)+E(Y_1 \vert C)\cdot Pr(C)+E(Y_0 \vert DF) \cdot Pr(DF)+E(Y_0 \vert NT) \cdot Pr(NT)$$ and $$E(Y \vert Z=0)=E(Y_1 \vert AT)\cdot Pr(AT)+E(Y_0 \vert C)\cdot Pr(C)+E(Y_1 \vert DF) \cdot Pr(DF)+E(Y_0 \vert NT) \cdot Pr(NT) $$ The two denominator terms are: $$ Pr(D=1 \vert Z =1)=Pr(D=1 \vert Z =1,AT) \cdot Pr(AT)+Pr(D=1 \vert Z =1,C) \cdot Pr(C) \\ =Pr(AT)+Pr(C) $$ and $$ Pr(D=1 \vert Z =0)=Pr(D=1 \vert Z = 0,AT) \cdot Pr(AT)+Pr(D=1 \vert Z =0,DF) \cdot Pr(DF) \\ =Pr(AT)+Pr(DF)$$ The first of these corresponds to your first expression. Coming back to the Wald formula and plugging these in, we see that some of these terms cancel out in the subtraction, leaving $$ \Delta_{IV} =\frac{[E(Y_1 \vert C) \cdot Pr(C)+E(Y_0 \vert D) \cdot Pr(D)]−[E(Y_0 \vert C) \cdot Pr(C)+E(Y_1 \vert DF) \cdot Pr(DF)]}{Pr(C) − Pr(DF)} $$ This yields some insight. The Wald IV estimator is a weighted average of the treatment effect on the compliers and the negative of the treatment effect on the defiers. Now we make two assumptions. First, we assume monotonicity, so that the instrument can only increase or decrease the probability of participation. This means that $Pr(DF) = 0$. The monotonicity assumption is equivalent to assuming an index function model for treatment. The second assumption is that there are some compliers, which is to say that $Pr(C) > 0$. The behavior of some individuals must be altered by the instrument. This should be the case if the instrument is relevant. These two assumptions produce $$\Delta_{IV} =\frac{E(Y_1 \vert C) \cdot Pr(C)−E(Y_0 \vert C) \cdot Pr(C)}{Pr(C)}=E(Y_1 \vert C)−E(Y_0 \vert C)=LATE.$$
Proving the LATE Theorem of Angrist and Imbens 1994 There are four types of people: Never Takers (NT): $D = 0$ for both values of Z Defiers (DF): $D=0$ when $Z =1$ and $D=1$ when $Z =0$ Compliers (C): $D=1$ when $Z =1$ and $D=0$ when $Z =0$ Always Tak
31,303
degenerate univariate Gaussian
This question uses "Gaussian" in two distinct mathematical senses (and therein lies its resolution): first as a distribution and then--at the beginning of the second paragraph--as a probability density function. However, a degenerate Gaussian does not have a PDF. Therefore we should be visualizing the distributions in terms of the one object that is guaranteed to exist no matter what; namely, the cumulative distribution function. The CDF of a degenerate Gaussian (of mean $\mu$) leaps from $0$ to $1$ at the value $\mu$, creating no difficulties with definitions or limiting values. The Gaussian density indeed "degenerates" as the standard deviation decreases, because it becomes arbitrarily large at the mean and shrinks to zero elsewhere, as shown in these plots of PDFs of Gaussian ("Normal") distributions with standard deviations $1, 1/4, 1/16,$ and $1/64$. (For better visualization, the vertical axis is cut off at the peak of the third distribution; the peak of the last and narrowest one, shown in blue, extends above $25$.) The peak must become very large to compensate for a shrinking width, because a PDF represents probability by means of area and, as required by the axioms of probability, the total area will equal $1$ only when the curve grows large in the other (vertical) direction. See A Probability distribution value exceeding 1 is OK for further explanation. This behavior has no well-defined limit at $\mu$ but the limits at all other numbers are zero. No matter what value we care to assign to the limit at $\mu$--even "$+\infty$"--the area under this limiting function is zero, so it cannot be the PDF of any distribution. The CDFs instead approach a definite curve in the limit of small standard deviations, which is evident in this corresponding plot of the CDFs of these four distributions: The colors correspond to the distributions in the same way as the previous plot. The CDF for the distribution with standard deviation $1/64$, shown in blue, leaps from $0$ to $1$ within a very short space around the mean $\mu$. In the limit of zero standard deviation, the leap will be instantaneous: the limiting curve is zero at all values less than $\mu$ and $1$ at all values greater than $\mu$ or greater. (A subtle point is that the value of the limiting curve at $\mu$ itself is $1/2.$ This is well understood; the relevant theorems do not assert that the limiting values at points where the limiting CDF has a jump will be correct.) This leap represents an "atom" at $\mu$ where all the probability is concentrated. The limiting function determines a valid probability distribution, but now, because it locates all the probability within a denumerable set of points (namely, a single point), it is discrete rather than continuous. Ordinarily we would work with its probability mass function (equal to $1$ at $\mu$).
degenerate univariate Gaussian
This question uses "Gaussian" in two distinct mathematical senses (and therein lies its resolution): first as a distribution and then--at the beginning of the second paragraph--as a probability densit
degenerate univariate Gaussian This question uses "Gaussian" in two distinct mathematical senses (and therein lies its resolution): first as a distribution and then--at the beginning of the second paragraph--as a probability density function. However, a degenerate Gaussian does not have a PDF. Therefore we should be visualizing the distributions in terms of the one object that is guaranteed to exist no matter what; namely, the cumulative distribution function. The CDF of a degenerate Gaussian (of mean $\mu$) leaps from $0$ to $1$ at the value $\mu$, creating no difficulties with definitions or limiting values. The Gaussian density indeed "degenerates" as the standard deviation decreases, because it becomes arbitrarily large at the mean and shrinks to zero elsewhere, as shown in these plots of PDFs of Gaussian ("Normal") distributions with standard deviations $1, 1/4, 1/16,$ and $1/64$. (For better visualization, the vertical axis is cut off at the peak of the third distribution; the peak of the last and narrowest one, shown in blue, extends above $25$.) The peak must become very large to compensate for a shrinking width, because a PDF represents probability by means of area and, as required by the axioms of probability, the total area will equal $1$ only when the curve grows large in the other (vertical) direction. See A Probability distribution value exceeding 1 is OK for further explanation. This behavior has no well-defined limit at $\mu$ but the limits at all other numbers are zero. No matter what value we care to assign to the limit at $\mu$--even "$+\infty$"--the area under this limiting function is zero, so it cannot be the PDF of any distribution. The CDFs instead approach a definite curve in the limit of small standard deviations, which is evident in this corresponding plot of the CDFs of these four distributions: The colors correspond to the distributions in the same way as the previous plot. The CDF for the distribution with standard deviation $1/64$, shown in blue, leaps from $0$ to $1$ within a very short space around the mean $\mu$. In the limit of zero standard deviation, the leap will be instantaneous: the limiting curve is zero at all values less than $\mu$ and $1$ at all values greater than $\mu$ or greater. (A subtle point is that the value of the limiting curve at $\mu$ itself is $1/2.$ This is well understood; the relevant theorems do not assert that the limiting values at points where the limiting CDF has a jump will be correct.) This leap represents an "atom" at $\mu$ where all the probability is concentrated. The limiting function determines a valid probability distribution, but now, because it locates all the probability within a denumerable set of points (namely, a single point), it is discrete rather than continuous. Ordinarily we would work with its probability mass function (equal to $1$ at $\mu$).
degenerate univariate Gaussian This question uses "Gaussian" in two distinct mathematical senses (and therein lies its resolution): first as a distribution and then--at the beginning of the second paragraph--as a probability densit
31,304
Glivenko-Cantelli Theorem
The differerence is in uniform convergence. 1 is saying that for all x there is a single n such that error is less than epsilon ( uniform). The other one is saying for each x there is a large enough n that error is less than epsilon(pointwise). An example from wikipedia of pointwise but not uniform convergence is $ f_n (x)=x^n $ on $0\le x\le 1$. You need larger and larger n as you get closer to $x=1$.
Glivenko-Cantelli Theorem
The differerence is in uniform convergence. 1 is saying that for all x there is a single n such that error is less than epsilon ( uniform). The other one is saying for each x there is a large enough
Glivenko-Cantelli Theorem The differerence is in uniform convergence. 1 is saying that for all x there is a single n such that error is less than epsilon ( uniform). The other one is saying for each x there is a large enough n that error is less than epsilon(pointwise). An example from wikipedia of pointwise but not uniform convergence is $ f_n (x)=x^n $ on $0\le x\le 1$. You need larger and larger n as you get closer to $x=1$.
Glivenko-Cantelli Theorem The differerence is in uniform convergence. 1 is saying that for all x there is a single n such that error is less than epsilon ( uniform). The other one is saying for each x there is a large enough
31,305
Glivenko-Cantelli Theorem
It is perhaps worth noting that pointwise convergence of $\hat F_n(x)$ to $F(x)$ already implies uniform convergence where $F$ is continuous (because the cdfs are bounded and monotone). More precisely, if $[a,b]$ is an interval that does not contain any discontinuities of $F$, the convergence is uniform on $[a,b]$ -- and that's still true for $a=-\infty$ or $b=\infty$. The conclusion of the Glivenko-Cantelli theorem is stronger: that the convergence is uniform even at discontinuities, and this is important. By contrast, if $\hat F_n$ are a sequence of empirical CDFs from distributions $F_n$ converging in distribution to $F$, we have pointwise convergence of $\hat F_n(x)$ to $F(x)$, and uniform convergence on intervals with no discontinuities, but not uniform convergence everywhere.
Glivenko-Cantelli Theorem
It is perhaps worth noting that pointwise convergence of $\hat F_n(x)$ to $F(x)$ already implies uniform convergence where $F$ is continuous (because the cdfs are bounded and monotone). More precisel
Glivenko-Cantelli Theorem It is perhaps worth noting that pointwise convergence of $\hat F_n(x)$ to $F(x)$ already implies uniform convergence where $F$ is continuous (because the cdfs are bounded and monotone). More precisely, if $[a,b]$ is an interval that does not contain any discontinuities of $F$, the convergence is uniform on $[a,b]$ -- and that's still true for $a=-\infty$ or $b=\infty$. The conclusion of the Glivenko-Cantelli theorem is stronger: that the convergence is uniform even at discontinuities, and this is important. By contrast, if $\hat F_n$ are a sequence of empirical CDFs from distributions $F_n$ converging in distribution to $F$, we have pointwise convergence of $\hat F_n(x)$ to $F(x)$, and uniform convergence on intervals with no discontinuities, but not uniform convergence everywhere.
Glivenko-Cantelli Theorem It is perhaps worth noting that pointwise convergence of $\hat F_n(x)$ to $F(x)$ already implies uniform convergence where $F$ is continuous (because the cdfs are bounded and monotone). More precisel
31,306
Sparse Autoencoder [Hyper]parameters
The autoencoder package is just an implementation of the autoencoder described in Andrew Ng's class notes, which might be a good starting point for further reading. Now, to tackle your questions People sometimes distinguish between *parameters*, which the learning algorithm calculates itself, and *hyperparameters*, which control that learning process and need to be provided to the learning algorithm. **It is important to realise that there are NO MAGIC VALUES** for the hyperparameters. The optimal value will vary, depending on the data you're modeling: you'll have to try them on your data. a) Lambda ($\lambda$) controls how the weights are updated during backpropagation. Instead of just updating the weights based on the difference between the model's output and the ground truth), the cost function includes a term which penalizes large weights (actually the squared value of all weights). Lambda controls the relative importance of this penalty term, which tends to drag weights towards zero and helps avoid overfitting. b) Rho ($\rho)$ and beta $(\beta$) control sparseness. Rho is the expected activation of a hidden unit (averaged across the training set). The representation will become sparser and sparser as it becomes smaller. This sparseness is imposed by adjusting the bias term, and beta controls the size of its updates. (It looks like $\beta$ actually just rescales the overall learning rate $\alpha$.) c) Epsilon ($\epsilon)$ controls the initial weight values, which are drawn at random from $N(0, \epsilon^2)$. Your rho values don't seem unreasonable since both are near the bottom of the activation function's range (0 to 1 for logistic, -1 to 1 for tanh). However, this obviously depends on the amount of sparseness you want and the number of hidden units you use too. LeCunn's major concern with small weights that the error surface becomes very flat near the origin if you're using a symmetric sigmoid. Elsewhere in that paper, he recommends initializing with weights randomly drawn from a normal distribution with zero mean and $m^{-1/2}$ standard deviation, where $m$ is the number of connections each unit receives. There are lots of "rules of thumb" for choosing the number of hidden units. Your initial guess (2x input) seems in line with most of them. That said, these guesstimates are much more guesswork than estimation. Assuming you've got the processing power, I would err on the side of more hidden units, then enforce sparseness with a low rho value. One obvious use of autoencoders is to generate more compact feature representations for other learning algorithms. A raw image might have millions of pixels, but a (sparse) autoencoder can re-represent that in a much smaller space. [Geoff Hinton][2] (and others) have shown that they generate useful features for subsequent classification. Some of the deep learning work uses autoencoders or similar to pretrain the network. [Vincent et al.][3] use autoencoders directly to perform classification. The ability to generate succinct feature representations can be used in other contexts as well. Here's a neat little project where autoencoder-produced states are used to guide a reinforcement learning algorithm through Atari games. Finally, one can also use autoencoders to reconstruct noisy or degraded input, like so, which can be a useful end in and of itself.
Sparse Autoencoder [Hyper]parameters
The autoencoder package is just an implementation of the autoencoder described in Andrew Ng's class notes, which might be a good starting point for further reading. Now, to tackle your questions Peo
Sparse Autoencoder [Hyper]parameters The autoencoder package is just an implementation of the autoencoder described in Andrew Ng's class notes, which might be a good starting point for further reading. Now, to tackle your questions People sometimes distinguish between *parameters*, which the learning algorithm calculates itself, and *hyperparameters*, which control that learning process and need to be provided to the learning algorithm. **It is important to realise that there are NO MAGIC VALUES** for the hyperparameters. The optimal value will vary, depending on the data you're modeling: you'll have to try them on your data. a) Lambda ($\lambda$) controls how the weights are updated during backpropagation. Instead of just updating the weights based on the difference between the model's output and the ground truth), the cost function includes a term which penalizes large weights (actually the squared value of all weights). Lambda controls the relative importance of this penalty term, which tends to drag weights towards zero and helps avoid overfitting. b) Rho ($\rho)$ and beta $(\beta$) control sparseness. Rho is the expected activation of a hidden unit (averaged across the training set). The representation will become sparser and sparser as it becomes smaller. This sparseness is imposed by adjusting the bias term, and beta controls the size of its updates. (It looks like $\beta$ actually just rescales the overall learning rate $\alpha$.) c) Epsilon ($\epsilon)$ controls the initial weight values, which are drawn at random from $N(0, \epsilon^2)$. Your rho values don't seem unreasonable since both are near the bottom of the activation function's range (0 to 1 for logistic, -1 to 1 for tanh). However, this obviously depends on the amount of sparseness you want and the number of hidden units you use too. LeCunn's major concern with small weights that the error surface becomes very flat near the origin if you're using a symmetric sigmoid. Elsewhere in that paper, he recommends initializing with weights randomly drawn from a normal distribution with zero mean and $m^{-1/2}$ standard deviation, where $m$ is the number of connections each unit receives. There are lots of "rules of thumb" for choosing the number of hidden units. Your initial guess (2x input) seems in line with most of them. That said, these guesstimates are much more guesswork than estimation. Assuming you've got the processing power, I would err on the side of more hidden units, then enforce sparseness with a low rho value. One obvious use of autoencoders is to generate more compact feature representations for other learning algorithms. A raw image might have millions of pixels, but a (sparse) autoencoder can re-represent that in a much smaller space. [Geoff Hinton][2] (and others) have shown that they generate useful features for subsequent classification. Some of the deep learning work uses autoencoders or similar to pretrain the network. [Vincent et al.][3] use autoencoders directly to perform classification. The ability to generate succinct feature representations can be used in other contexts as well. Here's a neat little project where autoencoder-produced states are used to guide a reinforcement learning algorithm through Atari games. Finally, one can also use autoencoders to reconstruct noisy or degraded input, like so, which can be a useful end in and of itself.
Sparse Autoencoder [Hyper]parameters The autoencoder package is just an implementation of the autoencoder described in Andrew Ng's class notes, which might be a good starting point for further reading. Now, to tackle your questions Peo
31,307
Sparse Autoencoder [Hyper]parameters
Some part of Matt Krause's answer doesn't seem to me correct (Lambda and Beta), also epsilon is not mentioned. Actually this post should be a comment, but I'm answering the question because of 50 reputation restriction. Feel free to comment if you see any mistake. From http://web.stanford.edu/class/archive/cs/cs294a/cs294a.1104/sparseAutoencoder.pdf Lambda is coefficient of weight decay term which discourage weights to reach big values since it may overfit. Weight decay term (or weight regularization term) is a part of the cost function like sparsity term explained below. rho is sparsity constraint which controls average number of activation on hidden layer. It is included to make autoencoder work even with relatively big number of hidden units with respect to input units. For example, if input size is 100 and hidden size is 100 or larger (even smaller but close to 100), the output can be constructed without any lost, since hidden units can learn identity function. Beta is coeffecient of sparsity term which is a part of the cost function. It controls relative importance of sparsity term. Lambda and Beta specify the relative importance of their terms in cost function. Epsilon (if they've used the same notation with Andrew Ng) is regularization parameter for whitening process which has low-pass filter effect on input. That has some important effects on reconstruction methods. Check the link for that under reconstruction based models. I think they have used linear activation for the output layer and used some type of whitening (univariating features). Update rate of parameters (weights and biases) is called learning rate and denoted by eta in general. However, it has been used as alpha by Andrew Ng. Check the first link.
Sparse Autoencoder [Hyper]parameters
Some part of Matt Krause's answer doesn't seem to me correct (Lambda and Beta), also epsilon is not mentioned. Actually this post should be a comment, but I'm answering the question because of 50 repu
Sparse Autoencoder [Hyper]parameters Some part of Matt Krause's answer doesn't seem to me correct (Lambda and Beta), also epsilon is not mentioned. Actually this post should be a comment, but I'm answering the question because of 50 reputation restriction. Feel free to comment if you see any mistake. From http://web.stanford.edu/class/archive/cs/cs294a/cs294a.1104/sparseAutoencoder.pdf Lambda is coefficient of weight decay term which discourage weights to reach big values since it may overfit. Weight decay term (or weight regularization term) is a part of the cost function like sparsity term explained below. rho is sparsity constraint which controls average number of activation on hidden layer. It is included to make autoencoder work even with relatively big number of hidden units with respect to input units. For example, if input size is 100 and hidden size is 100 or larger (even smaller but close to 100), the output can be constructed without any lost, since hidden units can learn identity function. Beta is coeffecient of sparsity term which is a part of the cost function. It controls relative importance of sparsity term. Lambda and Beta specify the relative importance of their terms in cost function. Epsilon (if they've used the same notation with Andrew Ng) is regularization parameter for whitening process which has low-pass filter effect on input. That has some important effects on reconstruction methods. Check the link for that under reconstruction based models. I think they have used linear activation for the output layer and used some type of whitening (univariating features). Update rate of parameters (weights and biases) is called learning rate and denoted by eta in general. However, it has been used as alpha by Andrew Ng. Check the first link.
Sparse Autoencoder [Hyper]parameters Some part of Matt Krause's answer doesn't seem to me correct (Lambda and Beta), also epsilon is not mentioned. Actually this post should be a comment, but I'm answering the question because of 50 repu
31,308
Interpreting coefficients in a logistic regression model with a categorical variable having more than 2 levels
If you write out the fitted model for the log odds of smoking $$\log \frac{\Pr(Y=1)}{\Pr(Y=0)} = -4.380\,1 + -0.324\,56\ I_\mathrm{teen} + 1.451\,19 \ I_\mathrm{mature} + -0.989\,1\ I_\mathrm{old}$$ where the dummies are $$I_\mathrm{teen}=\left\{ \begin{array}{l l} 0 & X\neq\mathrm{teenager}\\ 1& X=\mathrm{teenager}\\ \end{array}\right.$$ &c., you can confirm your calculations. Note though that "likely" is ambiguous—it might be taken as referring to probability—& you might prefer to say something like "the odds of a teenager's smoking are 28% lower than those of an adult's smoking" in a formal or didactic context.
Interpreting coefficients in a logistic regression model with a categorical variable having more tha
If you write out the fitted model for the log odds of smoking $$\log \frac{\Pr(Y=1)}{\Pr(Y=0)} = -4.380\,1 + -0.324\,56\ I_\mathrm{teen} + 1.451\,19 \ I_\mathrm{mature} + -0.989\,1\ I_\mathrm{old}$$ w
Interpreting coefficients in a logistic regression model with a categorical variable having more than 2 levels If you write out the fitted model for the log odds of smoking $$\log \frac{\Pr(Y=1)}{\Pr(Y=0)} = -4.380\,1 + -0.324\,56\ I_\mathrm{teen} + 1.451\,19 \ I_\mathrm{mature} + -0.989\,1\ I_\mathrm{old}$$ where the dummies are $$I_\mathrm{teen}=\left\{ \begin{array}{l l} 0 & X\neq\mathrm{teenager}\\ 1& X=\mathrm{teenager}\\ \end{array}\right.$$ &c., you can confirm your calculations. Note though that "likely" is ambiguous—it might be taken as referring to probability—& you might prefer to say something like "the odds of a teenager's smoking are 28% lower than those of an adult's smoking" in a formal or didactic context.
Interpreting coefficients in a logistic regression model with a categorical variable having more tha If you write out the fitted model for the log odds of smoking $$\log \frac{\Pr(Y=1)}{\Pr(Y=0)} = -4.380\,1 + -0.324\,56\ I_\mathrm{teen} + 1.451\,19 \ I_\mathrm{mature} + -0.989\,1\ I_\mathrm{old}$$ w
31,309
Interpreting coefficients in a logistic regression model with a categorical variable having more than 2 levels
It is important to understand that logistic regression parameters are only true locally. This means that the relative impact of each estimate will change depending on the value of your independent variables. Here is a paper that can helps explain things.
Interpreting coefficients in a logistic regression model with a categorical variable having more tha
It is important to understand that logistic regression parameters are only true locally. This means that the relative impact of each estimate will change depending on the value of your independent var
Interpreting coefficients in a logistic regression model with a categorical variable having more than 2 levels It is important to understand that logistic regression parameters are only true locally. This means that the relative impact of each estimate will change depending on the value of your independent variables. Here is a paper that can helps explain things.
Interpreting coefficients in a logistic regression model with a categorical variable having more tha It is important to understand that logistic regression parameters are only true locally. This means that the relative impact of each estimate will change depending on the value of your independent var
31,310
Interpreting coefficients in a logistic regression model with a categorical variable having more than 2 levels
if $y = F(\beta x) $ and $y\: \epsilon\: (1,0) $ where $F(x) $ is a logit function then $dy/dx_1 \neq dy/dx_2 $. This is because of the chain rule as $dy/dx = \frac{dy}{dF(x)}\frac{ dF(x)}{dx} $. If you look at a logit function You will see that the slope of x changes depending on where you are on the curve. In practice this means that you only interpret rank and sign in a logistic regression as the magnitude of the impact will depend on how you parameters and variables interact with the logit function
Interpreting coefficients in a logistic regression model with a categorical variable having more tha
if $y = F(\beta x) $ and $y\: \epsilon\: (1,0) $ where $F(x) $ is a logit function then $dy/dx_1 \neq dy/dx_2 $. This is because of the chain rule as $dy/dx = \frac{dy}{dF(x)}\frac{ dF(x)}{dx} $. I
Interpreting coefficients in a logistic regression model with a categorical variable having more than 2 levels if $y = F(\beta x) $ and $y\: \epsilon\: (1,0) $ where $F(x) $ is a logit function then $dy/dx_1 \neq dy/dx_2 $. This is because of the chain rule as $dy/dx = \frac{dy}{dF(x)}\frac{ dF(x)}{dx} $. If you look at a logit function You will see that the slope of x changes depending on where you are on the curve. In practice this means that you only interpret rank and sign in a logistic regression as the magnitude of the impact will depend on how you parameters and variables interact with the logit function
Interpreting coefficients in a logistic regression model with a categorical variable having more tha if $y = F(\beta x) $ and $y\: \epsilon\: (1,0) $ where $F(x) $ is a logit function then $dy/dx_1 \neq dy/dx_2 $. This is because of the chain rule as $dy/dx = \frac{dy}{dF(x)}\frac{ dF(x)}{dx} $. I
31,311
Using non-stationary time series data in OLS regression
You can do anything you want, especially if it's a term paper or something of that nature. To obtain useful results you can't use nonstationary data with OLS and time series. There are other more advanced methods where nonstationarity is a non issue. With OLS you have to difference real GDP and indices, and also apply log transform in many cases. UPDATE: when using non stationary variables in OLS you run into the potentially fatal issue of spurious regression, there's a ton of literature on this subject. Basically, your regression results will turn out garbage in most cases. You may see very significant coefficients, but the significance is artificial, and disappears when you run a proper regression. There's even more subtle phenomenon called "cointegration", but since you're working on undergrad paper, I would not worry about it. As a matter of fact, if your major is not statistics or econometrics, I would imagine your instructor will not penalize you for improper use of regressions. Clarification: you can use non-stationary data with OLS if the series are cointegrated. However, when doing so you better show that the series are cointegrated indeed, then adjust the parameter covariance matrix accordingly if you need inference. The parameters themselves would be fine. As I mentioned in original answer this is advanced concepts that are usually outside undegrad courses.
Using non-stationary time series data in OLS regression
You can do anything you want, especially if it's a term paper or something of that nature. To obtain useful results you can't use nonstationary data with OLS and time series. There are other more adva
Using non-stationary time series data in OLS regression You can do anything you want, especially if it's a term paper or something of that nature. To obtain useful results you can't use nonstationary data with OLS and time series. There are other more advanced methods where nonstationarity is a non issue. With OLS you have to difference real GDP and indices, and also apply log transform in many cases. UPDATE: when using non stationary variables in OLS you run into the potentially fatal issue of spurious regression, there's a ton of literature on this subject. Basically, your regression results will turn out garbage in most cases. You may see very significant coefficients, but the significance is artificial, and disappears when you run a proper regression. There's even more subtle phenomenon called "cointegration", but since you're working on undergrad paper, I would not worry about it. As a matter of fact, if your major is not statistics or econometrics, I would imagine your instructor will not penalize you for improper use of regressions. Clarification: you can use non-stationary data with OLS if the series are cointegrated. However, when doing so you better show that the series are cointegrated indeed, then adjust the parameter covariance matrix accordingly if you need inference. The parameters themselves would be fine. As I mentioned in original answer this is advanced concepts that are usually outside undegrad courses.
Using non-stationary time series data in OLS regression You can do anything you want, especially if it's a term paper or something of that nature. To obtain useful results you can't use nonstationary data with OLS and time series. There are other more adva
31,312
Using non-stationary time series data in OLS regression
I have a graduate degree in econometrics specializing in times eries and survival analyis. I'll try to give you short undergrad advice instad of a proof. You should never use OLS for time-series data (the only exception is SOMETIMES it is appropriate to use this technique for panel data). OLS results will be garbage - it will result in a spurious regression in which the results look good, but are void of econometric interpretation. MLE should be used instead. The short answer to why is that the covariance between your dependent variable and your error term will never be zero, one of the foundational assumptions of OLS. Instead of fitting a linear line, we have to fit a process to the data (AR(p), MA(q), ARMA(p,q), ARIMA(p,d,q), ARIMAX(p,q,x), VAR(p), etc.) Differencing your data to make it stationary will not allow you to use OLS. Stationary data still follows a process, and your model specification should allow for this. If the error term of a two time series are stationary, then it is appropriate to use cointegration techniques, but this isn't something you should try to do on your own. If you have access to a statistial package, research how to perform a Dickey-Fuller test for stationarity to determine if your data is stationary. If not, difference the data, and (assuming stationarity after first or second differencing), fit the appropriate process using MLE to your series. Forwarning: from the description you provided of your data, it sounds like it would best be modelled using vector autoregression with a transfer function (VARMAX(p,q,x)). This is also known as a recursive VAR. This is appropriate if you're trying to determine if (assumed to be stationary) multiple time series are predicting another time series. These are very accurate when modelled correctly, but they are not parsimonous (you need a large number of degrees of freedom, and you're already using a estimation prodecure that is only asymptotically unbiased, so hopefully you have plenty of observations), and it isn't something I would recommmend an undergrad trying to do. Hope that helps, Keegan
Using non-stationary time series data in OLS regression
I have a graduate degree in econometrics specializing in times eries and survival analyis. I'll try to give you short undergrad advice instad of a proof. You should never use OLS for time-series data
Using non-stationary time series data in OLS regression I have a graduate degree in econometrics specializing in times eries and survival analyis. I'll try to give you short undergrad advice instad of a proof. You should never use OLS for time-series data (the only exception is SOMETIMES it is appropriate to use this technique for panel data). OLS results will be garbage - it will result in a spurious regression in which the results look good, but are void of econometric interpretation. MLE should be used instead. The short answer to why is that the covariance between your dependent variable and your error term will never be zero, one of the foundational assumptions of OLS. Instead of fitting a linear line, we have to fit a process to the data (AR(p), MA(q), ARMA(p,q), ARIMA(p,d,q), ARIMAX(p,q,x), VAR(p), etc.) Differencing your data to make it stationary will not allow you to use OLS. Stationary data still follows a process, and your model specification should allow for this. If the error term of a two time series are stationary, then it is appropriate to use cointegration techniques, but this isn't something you should try to do on your own. If you have access to a statistial package, research how to perform a Dickey-Fuller test for stationarity to determine if your data is stationary. If not, difference the data, and (assuming stationarity after first or second differencing), fit the appropriate process using MLE to your series. Forwarning: from the description you provided of your data, it sounds like it would best be modelled using vector autoregression with a transfer function (VARMAX(p,q,x)). This is also known as a recursive VAR. This is appropriate if you're trying to determine if (assumed to be stationary) multiple time series are predicting another time series. These are very accurate when modelled correctly, but they are not parsimonous (you need a large number of degrees of freedom, and you're already using a estimation prodecure that is only asymptotically unbiased, so hopefully you have plenty of observations), and it isn't something I would recommmend an undergrad trying to do. Hope that helps, Keegan
Using non-stationary time series data in OLS regression I have a graduate degree in econometrics specializing in times eries and survival analyis. I'll try to give you short undergrad advice instad of a proof. You should never use OLS for time-series data
31,313
Where do I declare prior parameters in Stan?
I would distinguish between the prior distribution and the parameters for the prior distribution. When I started with Stan, I would set the parameters to the prior distributions just as some values. So in the model step, I would have something like model { mu ~ normal(0, 1) y ~ normal(mu, s) } for a normal prior on the mean coefficient for the distribution of y. However, as I've been using Stan more, I have tended to include them in the data step (i.e., the list you refer to where the rest of the data is stored). In this format, I would supplement the data step with data { real mu_prior_1 real<lower=0> mu_prior_2 } and adjust the model step to something like model { mu ~ normal(mu_prior_1, mu_prior_2) y ~ normal(mu, s) } The main reason I've been doing this is because it makes it easier for me to change the priors without changing the rest of the Stan code.
Where do I declare prior parameters in Stan?
I would distinguish between the prior distribution and the parameters for the prior distribution. When I started with Stan, I would set the parameters to the prior distributions just as some values. S
Where do I declare prior parameters in Stan? I would distinguish between the prior distribution and the parameters for the prior distribution. When I started with Stan, I would set the parameters to the prior distributions just as some values. So in the model step, I would have something like model { mu ~ normal(0, 1) y ~ normal(mu, s) } for a normal prior on the mean coefficient for the distribution of y. However, as I've been using Stan more, I have tended to include them in the data step (i.e., the list you refer to where the rest of the data is stored). In this format, I would supplement the data step with data { real mu_prior_1 real<lower=0> mu_prior_2 } and adjust the model step to something like model { mu ~ normal(mu_prior_1, mu_prior_2) y ~ normal(mu, s) } The main reason I've been doing this is because it makes it easier for me to change the priors without changing the rest of the Stan code.
Where do I declare prior parameters in Stan? I would distinguish between the prior distribution and the parameters for the prior distribution. When I started with Stan, I would set the parameters to the prior distributions just as some values. S
31,314
Should $H_0$ be specified as an equality or an inequality for one-sided tests
It's not simply a matter of style - and if it were, I'd actually advocate for including the inequality. What makes the equality both relevant and important is two fold: (1) often, one is really only interested in the equality case or the alternative - for example, when the inequality one the other side from the alternative would be extremely unlikely (e.g. the likely way a new drug works is fairly well understood and has no mechanism by which cholesterol could be worse - it either helps lower cholesterol or it doesn't). (2) the way the null distribution (the distribution of the test statistic under the null) is generated in a one-tailed test is to deal only with the equality case; while the $<$ part of $\leq$ may be logically possible, it's ignored in figuring out significance levels (like $P(T\geq t_c|H_0)$ for some statistic $T$) and p-values ($P(T\geq T_\text{obs}|H_0)$). (That said, in practice many people - though far from everyone - do include the inequality in stating the null, rather than just the equality. Different books take different stances on it.)
Should $H_0$ be specified as an equality or an inequality for one-sided tests
It's not simply a matter of style - and if it were, I'd actually advocate for including the inequality. What makes the equality both relevant and important is two fold: (1) often, one is really only i
Should $H_0$ be specified as an equality or an inequality for one-sided tests It's not simply a matter of style - and if it were, I'd actually advocate for including the inequality. What makes the equality both relevant and important is two fold: (1) often, one is really only interested in the equality case or the alternative - for example, when the inequality one the other side from the alternative would be extremely unlikely (e.g. the likely way a new drug works is fairly well understood and has no mechanism by which cholesterol could be worse - it either helps lower cholesterol or it doesn't). (2) the way the null distribution (the distribution of the test statistic under the null) is generated in a one-tailed test is to deal only with the equality case; while the $<$ part of $\leq$ may be logically possible, it's ignored in figuring out significance levels (like $P(T\geq t_c|H_0)$ for some statistic $T$) and p-values ($P(T\geq T_\text{obs}|H_0)$). (That said, in practice many people - though far from everyone - do include the inequality in stating the null, rather than just the equality. Different books take different stances on it.)
Should $H_0$ be specified as an equality or an inequality for one-sided tests It's not simply a matter of style - and if it were, I'd actually advocate for including the inequality. What makes the equality both relevant and important is two fold: (1) often, one is really only i
31,315
Should $H_0$ be specified as an equality or an inequality for one-sided tests
It must be an equality. In the classical approach (which I believe your texts follow), as proposed by Pearson and Neyman long time ago, H0 must be stated as an equality (and it is fundamental assumption for how the maths here works), it is necessary to have parameter assumed at a particular value, to work out the test statistic distribution and probabilities. The logic of hypothesis testing is basically a "what if" approach. Assumptions/Framework: particular statistical model, sampling from a population, decision table (very simple) with error thresholds Input (ingredients): data sample, H0 statement (about a parameter of the statistical model assumed, and that is about the unknown population) Output : Decision Steps (recipe, inference process) to arrive at the decision: 1/ Let as assume H0 is true, 2/ Let us compute some probabilities and check ... assuming H0 was true what is the probability of observing the data in front of us 3/ this is done via test statistic (assuming H0!), which is a random variable (randomness comes from random sampling) and has some distribution, some outcomes more likely some less, 3/ If H0 is true and the probability of observing what we have in front of us is below (personally set or industry standard) "suspicion" threshold (rejection level) we tend to think that something is wrong with H0 rather than with the data (i.e. not just bad luck of getting a very unlikely sample) and say "there is evidence" to reject H0. No hard proof but some "evidence". The distribution of a test statistic has a parameter and that parameter appears in the H0 as a specified value (or in other types of hypotheses as specific, defined case) which we must have a specified value in order to calculate, or work out the distributions, probabilities. A good example are games which include randomness or betting in general. If you play poker and observe a very, very unlikely outcome (e.g. one of the players winning twenty times in a row, each time with four aces) your start to think that something is wrong with the game (too good opponent? or maybe some cheating going on?), rather than that this winning has just happened by chance. That is exactly how Neyman was explaining hypothesis testing later in one of his books (I think it was in his "First course"). One might say that the whole logic above with equality in H0 is a little "dodgy". Why would we be specifying H0 at a particular ONE special point (or possibly to shoot at different points as H0s) and rejecting it (or not), when we know that we cannot PROVE or CHOOSE any special particular value as a sensible candidate for the initial guess (and all results will be stated in terms of probabilities anyway). Usually we are not interested really in checking that the mean of some measurement is exactly at particular ONE value, and if we can reject this or support by the data, but rather it would be good to know what are the probabilities of that mean (or whatever if of interest) being in certain ranges (then we can put some money on it, we have probabilities). That is obviously for another discussion. The workaround is "confidence intervals" but these in classical approach are derived fundamentally via the hypothesis testing as well and suffer from the same lets get some evidence via test-reject probabilistic logic (and what would happen if we were able to repeat it many times) ... unless one steps out to the B world.
Should $H_0$ be specified as an equality or an inequality for one-sided tests
It must be an equality. In the classical approach (which I believe your texts follow), as proposed by Pearson and Neyman long time ago, H0 must be stated as an equality (and it is fundamental assumpti
Should $H_0$ be specified as an equality or an inequality for one-sided tests It must be an equality. In the classical approach (which I believe your texts follow), as proposed by Pearson and Neyman long time ago, H0 must be stated as an equality (and it is fundamental assumption for how the maths here works), it is necessary to have parameter assumed at a particular value, to work out the test statistic distribution and probabilities. The logic of hypothesis testing is basically a "what if" approach. Assumptions/Framework: particular statistical model, sampling from a population, decision table (very simple) with error thresholds Input (ingredients): data sample, H0 statement (about a parameter of the statistical model assumed, and that is about the unknown population) Output : Decision Steps (recipe, inference process) to arrive at the decision: 1/ Let as assume H0 is true, 2/ Let us compute some probabilities and check ... assuming H0 was true what is the probability of observing the data in front of us 3/ this is done via test statistic (assuming H0!), which is a random variable (randomness comes from random sampling) and has some distribution, some outcomes more likely some less, 3/ If H0 is true and the probability of observing what we have in front of us is below (personally set or industry standard) "suspicion" threshold (rejection level) we tend to think that something is wrong with H0 rather than with the data (i.e. not just bad luck of getting a very unlikely sample) and say "there is evidence" to reject H0. No hard proof but some "evidence". The distribution of a test statistic has a parameter and that parameter appears in the H0 as a specified value (or in other types of hypotheses as specific, defined case) which we must have a specified value in order to calculate, or work out the distributions, probabilities. A good example are games which include randomness or betting in general. If you play poker and observe a very, very unlikely outcome (e.g. one of the players winning twenty times in a row, each time with four aces) your start to think that something is wrong with the game (too good opponent? or maybe some cheating going on?), rather than that this winning has just happened by chance. That is exactly how Neyman was explaining hypothesis testing later in one of his books (I think it was in his "First course"). One might say that the whole logic above with equality in H0 is a little "dodgy". Why would we be specifying H0 at a particular ONE special point (or possibly to shoot at different points as H0s) and rejecting it (or not), when we know that we cannot PROVE or CHOOSE any special particular value as a sensible candidate for the initial guess (and all results will be stated in terms of probabilities anyway). Usually we are not interested really in checking that the mean of some measurement is exactly at particular ONE value, and if we can reject this or support by the data, but rather it would be good to know what are the probabilities of that mean (or whatever if of interest) being in certain ranges (then we can put some money on it, we have probabilities). That is obviously for another discussion. The workaround is "confidence intervals" but these in classical approach are derived fundamentally via the hypothesis testing as well and suffer from the same lets get some evidence via test-reject probabilistic logic (and what would happen if we were able to repeat it many times) ... unless one steps out to the B world.
Should $H_0$ be specified as an equality or an inequality for one-sided tests It must be an equality. In the classical approach (which I believe your texts follow), as proposed by Pearson and Neyman long time ago, H0 must be stated as an equality (and it is fundamental assumpti
31,316
ANOVA terminology: "repeated measures" vs. "within/between subjects"
Repeated measures means exactly the same thing as within subjects: it means that the same subjects were measured in several different conditions. In ANOVA terminology, these conditions form a repeated measures factor, or equivalently a within subjects factor. See wikipedia. What I guess confused you is that in a repeated measures experiment one can still have between-subjects factors! For example, you can measure all subjects in several conditions (within-subject factor), but have several distinct groups of subjects (e.g. patients/controls, or males/females) -- this will be your between-subject factor. I made a quick google search, and e.g. here all of that seems to be explained pretty clear, with a nice example.
ANOVA terminology: "repeated measures" vs. "within/between subjects"
Repeated measures means exactly the same thing as within subjects: it means that the same subjects were measured in several different conditions. In ANOVA terminology, these conditions form a repeated
ANOVA terminology: "repeated measures" vs. "within/between subjects" Repeated measures means exactly the same thing as within subjects: it means that the same subjects were measured in several different conditions. In ANOVA terminology, these conditions form a repeated measures factor, or equivalently a within subjects factor. See wikipedia. What I guess confused you is that in a repeated measures experiment one can still have between-subjects factors! For example, you can measure all subjects in several conditions (within-subject factor), but have several distinct groups of subjects (e.g. patients/controls, or males/females) -- this will be your between-subject factor. I made a quick google search, and e.g. here all of that seems to be explained pretty clear, with a nice example.
ANOVA terminology: "repeated measures" vs. "within/between subjects" Repeated measures means exactly the same thing as within subjects: it means that the same subjects were measured in several different conditions. In ANOVA terminology, these conditions form a repeated
31,317
ANOVA terminology: "repeated measures" vs. "within/between subjects"
It seems to me that there are two types of repeated measures ANOVA. The first deals with repeats such as within subject measurements where there can be some dependency between the before and after measurements or the twins comparison mentioned by Jeremy Miles in his comment on amoeba's answer. That type of repeated measures ANOVA is analogous to a paired t-test. Graphpad Prism uses what seems to me to be a 2-way ANOVA for such circumstances and calls is a repeated measures ANOVA. The second type of repeated measures are where measurements are made repeatedly over time within a subject and there can be expected to be serial correlations such that the time 1 measurement is closely related to time 2 and less closely related to time 3. That results in the variance of the difference between time 1 and time 2 being less than the variance of the difference between time 1 and time 3 but similar to the variance of the difference between time 2 and time 3. That type of condition is usually described as a violation of the assumption of 'sphericity' (whatever that might be!). This type of repeated measures is often dealt with by a 'Greenhouse-Geisser' correction. The stats guide at Graphpad is a pretty good place to begin: http://www.graphpad.com/guides/prism/6/statistics/index.htm?stat_sphericity_and_compound_symmet.htm
ANOVA terminology: "repeated measures" vs. "within/between subjects"
It seems to me that there are two types of repeated measures ANOVA. The first deals with repeats such as within subject measurements where there can be some dependency between the before and after mea
ANOVA terminology: "repeated measures" vs. "within/between subjects" It seems to me that there are two types of repeated measures ANOVA. The first deals with repeats such as within subject measurements where there can be some dependency between the before and after measurements or the twins comparison mentioned by Jeremy Miles in his comment on amoeba's answer. That type of repeated measures ANOVA is analogous to a paired t-test. Graphpad Prism uses what seems to me to be a 2-way ANOVA for such circumstances and calls is a repeated measures ANOVA. The second type of repeated measures are where measurements are made repeatedly over time within a subject and there can be expected to be serial correlations such that the time 1 measurement is closely related to time 2 and less closely related to time 3. That results in the variance of the difference between time 1 and time 2 being less than the variance of the difference between time 1 and time 3 but similar to the variance of the difference between time 2 and time 3. That type of condition is usually described as a violation of the assumption of 'sphericity' (whatever that might be!). This type of repeated measures is often dealt with by a 'Greenhouse-Geisser' correction. The stats guide at Graphpad is a pretty good place to begin: http://www.graphpad.com/guides/prism/6/statistics/index.htm?stat_sphericity_and_compound_symmet.htm
ANOVA terminology: "repeated measures" vs. "within/between subjects" It seems to me that there are two types of repeated measures ANOVA. The first deals with repeats such as within subject measurements where there can be some dependency between the before and after mea
31,318
ANOVA terminology: "repeated measures" vs. "within/between subjects"
I think there is a distinction between the "ANOVA: Repeated Measures - between factors" and "ANOVA: Repeated Measures - within factors" as pointed out by Michael Lew. To clear the doubt, just imagine two hypothetical experiments in which the effect of the application of two brands of cosmetics on each arm of a patient is studied. In the first one two brands are applied simultaneously so that the patient receives either "A" or "B" brand on each of his arms. But in the second experiment, the first brand is applied, the measurements were taken, then the second brand is applied. For the first experiment, the environmental conditions that both the tested brands receive are the same. But in the second case (first brand followed by the second one), it is different.
ANOVA terminology: "repeated measures" vs. "within/between subjects"
I think there is a distinction between the "ANOVA: Repeated Measures - between factors" and "ANOVA: Repeated Measures - within factors" as pointed out by Michael Lew. To clear the doubt, just imagine
ANOVA terminology: "repeated measures" vs. "within/between subjects" I think there is a distinction between the "ANOVA: Repeated Measures - between factors" and "ANOVA: Repeated Measures - within factors" as pointed out by Michael Lew. To clear the doubt, just imagine two hypothetical experiments in which the effect of the application of two brands of cosmetics on each arm of a patient is studied. In the first one two brands are applied simultaneously so that the patient receives either "A" or "B" brand on each of his arms. But in the second experiment, the first brand is applied, the measurements were taken, then the second brand is applied. For the first experiment, the environmental conditions that both the tested brands receive are the same. But in the second case (first brand followed by the second one), it is different.
ANOVA terminology: "repeated measures" vs. "within/between subjects" I think there is a distinction between the "ANOVA: Repeated Measures - between factors" and "ANOVA: Repeated Measures - within factors" as pointed out by Michael Lew. To clear the doubt, just imagine
31,319
ANOVA terminology: "repeated measures" vs. "within/between subjects"
I think usually within or between participants design means whether participants receive all levels or one level of an IV, while the repeated measures were spoken in terms of DVs, such as whether a DV is measured several times, or there are several DVs that you intend to contrast measured. However, in experiments with repeated measures, the different timing of measures or the DVs can be entered in the data analysis as a within factor.
ANOVA terminology: "repeated measures" vs. "within/between subjects"
I think usually within or between participants design means whether participants receive all levels or one level of an IV, while the repeated measures were spoken in terms of DVs, such as whether a DV
ANOVA terminology: "repeated measures" vs. "within/between subjects" I think usually within or between participants design means whether participants receive all levels or one level of an IV, while the repeated measures were spoken in terms of DVs, such as whether a DV is measured several times, or there are several DVs that you intend to contrast measured. However, in experiments with repeated measures, the different timing of measures or the DVs can be entered in the data analysis as a within factor.
ANOVA terminology: "repeated measures" vs. "within/between subjects" I think usually within or between participants design means whether participants receive all levels or one level of an IV, while the repeated measures were spoken in terms of DVs, such as whether a DV
31,320
SE of fit versus SE of prediction
It is hard to answer without knowing more about what mod is. That is why we suggest a reproducible example. If mod is a glm fit with a 'gaussian' family (the default) then it is just a linear model and you can use predict.lm instead which has the interval argument that can be set to "prediction" to compute prediction intervals. If mod is a glm fit with a non-Gaussian family then the concept of a standard error of prediction may not even make sense (what is the prediction interval when the predictions are all TRUE/FALSE?). If you can give more detail (a reproducible example and a clear statement of what you want) then we will have a better chance of giving a useful answer.
SE of fit versus SE of prediction
It is hard to answer without knowing more about what mod is. That is why we suggest a reproducible example. If mod is a glm fit with a 'gaussian' family (the default) then it is just a linear model a
SE of fit versus SE of prediction It is hard to answer without knowing more about what mod is. That is why we suggest a reproducible example. If mod is a glm fit with a 'gaussian' family (the default) then it is just a linear model and you can use predict.lm instead which has the interval argument that can be set to "prediction" to compute prediction intervals. If mod is a glm fit with a non-Gaussian family then the concept of a standard error of prediction may not even make sense (what is the prediction interval when the predictions are all TRUE/FALSE?). If you can give more detail (a reproducible example and a clear statement of what you want) then we will have a better chance of giving a useful answer.
SE of fit versus SE of prediction It is hard to answer without knowing more about what mod is. That is why we suggest a reproducible example. If mod is a glm fit with a 'gaussian' family (the default) then it is just a linear model a
31,321
SE of fit versus SE of prediction
I would like to throw in a comment for non-normal distributions and non-identity link functions. se.fit=T yields standard errors of the prediction, i.e. a measure of uncertainty for the predicted value. This prediction, by one of the Central Value Theorems, can be assumed to be normally distributed at the link scale, and hence its standard error can be given as the standard deviation of a normal distribution. When using type="response", the prediction is back-transformed with the anti-link function (e.g. plogis for the logit-link). Using type="response"and se.fit=T yields non-sensical values, as it only returns one set of standard errors at the response scale. As the link-function is non-linear, the symmetric errors at the link scale must be asymmetric at the response scale. Thus, we can choose type="response" or se.fit=T, but not both when using non-identity link functions. (I don't understand why predict.glm has not been programmed to throw an error in this case.)
SE of fit versus SE of prediction
I would like to throw in a comment for non-normal distributions and non-identity link functions. se.fit=T yields standard errors of the prediction, i.e. a measure of uncertainty for the predicted valu
SE of fit versus SE of prediction I would like to throw in a comment for non-normal distributions and non-identity link functions. se.fit=T yields standard errors of the prediction, i.e. a measure of uncertainty for the predicted value. This prediction, by one of the Central Value Theorems, can be assumed to be normally distributed at the link scale, and hence its standard error can be given as the standard deviation of a normal distribution. When using type="response", the prediction is back-transformed with the anti-link function (e.g. plogis for the logit-link). Using type="response"and se.fit=T yields non-sensical values, as it only returns one set of standard errors at the response scale. As the link-function is non-linear, the symmetric errors at the link scale must be asymmetric at the response scale. Thus, we can choose type="response" or se.fit=T, but not both when using non-identity link functions. (I don't understand why predict.glm has not been programmed to throw an error in this case.)
SE of fit versus SE of prediction I would like to throw in a comment for non-normal distributions and non-identity link functions. se.fit=T yields standard errors of the prediction, i.e. a measure of uncertainty for the predicted valu
31,322
Are random forests Bayesian?
Not really. Random Forests are closer to bootstrapping (there is a bootstrapping piece in the random forest fit). Bootstrapping can be seen as a Bayes analysis with a very specific prior and only looking at summaries of the posterior, but using a specific prior (that matches frequentist output) and not looking at the whole posterior does not really follow the philosophy of Bayesian analysis.
Are random forests Bayesian?
Not really. Random Forests are closer to bootstrapping (there is a bootstrapping piece in the random forest fit). Bootstrapping can be seen as a Bayes analysis with a very specific prior and only look
Are random forests Bayesian? Not really. Random Forests are closer to bootstrapping (there is a bootstrapping piece in the random forest fit). Bootstrapping can be seen as a Bayes analysis with a very specific prior and only looking at summaries of the posterior, but using a specific prior (that matches frequentist output) and not looking at the whole posterior does not really follow the philosophy of Bayesian analysis.
Are random forests Bayesian? Not really. Random Forests are closer to bootstrapping (there is a bootstrapping piece in the random forest fit). Bootstrapping can be seen as a Bayes analysis with a very specific prior and only look
31,323
Generating correlated distributions with a certain mean and standard deviation?
If you mean the individual distributions are Gaussian, then sampling from a multivariate normal with mean vector $\mathbf{\mu}$ and covariance matrix $\mathbf{\Sigma}$ will generate such data. Here is an R example using the function mvrnorm() in package MASS (which comes with R): ## means of individual distributions mu1 <- 5 mu2 <- 10 mu3 <- 0 ## variance sigma1 <- 5 sigma2 <- 1 sigma3 <- 0.5 ## Correlations X1 <- 0.5 X2 <- 0.1 X3 <- 0.8 ## load package require("MASS") We need to supply n, the number of values from each distribution, mu the mean vector, and Sigma the covariance matrix. In the code below I form these from the scalars entered above. set.seed(1) dat <- mvrnorm(100, mu = c(mu1, mu2, mu3), Sigma = matrix(c(sigma1, X1 , X3, X1 , sigma2, X2, X3 , X2 , sigma3), ncol = 3, byrow = TRUE), empirical = TRUE) I used empirical = TRUE to specify empirical not population parameters for $\mathbf{\mu}$ and $\mathbf{\Sigma}$. This results in the covariance matrix of dat having exactly the values we specified: R> cov(dat) [,1] [,2] [,3] [1,] 5.0 0.5 0.8 [2,] 0.5 1.0 0.1 [3,] 0.8 0.1 0.5 as do the column means: R> colMeans(dat) [1] 5.000e+00 1.000e+01 -8.882e-18 If you use the default, empirical = FALSE, then you get random samples from a population which will have different sample mean vector and sample covariance matrix from the specified one as you have only seen n examples from that larger population: set.seed(1) dat2 <- mvrnorm(100, mu = c(mu1, mu2, mu3), Sigma = matrix(c(sigma1, X1 , X3, X1 , sigma2, X2, X3 , X2 , sigma3), ncol = 3, byrow = TRUE)) R> cov(dat2) [,1] [,2] [,3] [1,] 4.0441 0.39858 0.61120 [2,] 0.3986 0.91110 0.04842 [3,] 0.6112 0.04842 0.48782 R> colMeans(dat2) [1] 5.24138 10.06668 0.02448
Generating correlated distributions with a certain mean and standard deviation?
If you mean the individual distributions are Gaussian, then sampling from a multivariate normal with mean vector $\mathbf{\mu}$ and covariance matrix $\mathbf{\Sigma}$ will generate such data. Here is
Generating correlated distributions with a certain mean and standard deviation? If you mean the individual distributions are Gaussian, then sampling from a multivariate normal with mean vector $\mathbf{\mu}$ and covariance matrix $\mathbf{\Sigma}$ will generate such data. Here is an R example using the function mvrnorm() in package MASS (which comes with R): ## means of individual distributions mu1 <- 5 mu2 <- 10 mu3 <- 0 ## variance sigma1 <- 5 sigma2 <- 1 sigma3 <- 0.5 ## Correlations X1 <- 0.5 X2 <- 0.1 X3 <- 0.8 ## load package require("MASS") We need to supply n, the number of values from each distribution, mu the mean vector, and Sigma the covariance matrix. In the code below I form these from the scalars entered above. set.seed(1) dat <- mvrnorm(100, mu = c(mu1, mu2, mu3), Sigma = matrix(c(sigma1, X1 , X3, X1 , sigma2, X2, X3 , X2 , sigma3), ncol = 3, byrow = TRUE), empirical = TRUE) I used empirical = TRUE to specify empirical not population parameters for $\mathbf{\mu}$ and $\mathbf{\Sigma}$. This results in the covariance matrix of dat having exactly the values we specified: R> cov(dat) [,1] [,2] [,3] [1,] 5.0 0.5 0.8 [2,] 0.5 1.0 0.1 [3,] 0.8 0.1 0.5 as do the column means: R> colMeans(dat) [1] 5.000e+00 1.000e+01 -8.882e-18 If you use the default, empirical = FALSE, then you get random samples from a population which will have different sample mean vector and sample covariance matrix from the specified one as you have only seen n examples from that larger population: set.seed(1) dat2 <- mvrnorm(100, mu = c(mu1, mu2, mu3), Sigma = matrix(c(sigma1, X1 , X3, X1 , sigma2, X2, X3 , X2 , sigma3), ncol = 3, byrow = TRUE)) R> cov(dat2) [,1] [,2] [,3] [1,] 4.0441 0.39858 0.61120 [2,] 0.3986 0.91110 0.04842 [3,] 0.6112 0.04842 0.48782 R> colMeans(dat2) [1] 5.24138 10.06668 0.02448
Generating correlated distributions with a certain mean and standard deviation? If you mean the individual distributions are Gaussian, then sampling from a multivariate normal with mean vector $\mathbf{\mu}$ and covariance matrix $\mathbf{\Sigma}$ will generate such data. Here is
31,324
Likelihood function of truncated data
What you describe needs special treatment, it is not what we usually mean by "truncated random variables"-and what we usually mean is that the random variable does not range outside the truncated support, meaning that there is not a concentration of probability mass at the point of truncation. To contrast cases: A) "Usual" meaning of a truncated rv For any distribution that we truncate its support, we must "correct" its density so that it integrates to unity when integrated over the truncated support. If the variable has support in $[a,b]$, $-\infty < a < b < \infty$, then (pdf $f$, cdf $F$) $$\int_a^bf_X(x)dx = \int_a^Mf_X(x)dx+\int_M^bf_X(x)dx = \int_a^Mf_X(x)dx + \left[1-F_X(M)\right]=1 $$ $$\Rightarrow \int_a^Mf_X(x)dx = F_X(M)$$ Since the LHS is the integral over the truncated support, we see that the density of the truncated r.v., call it $\tilde X$, must be $$f_{\tilde X}(\tilde x) = f_{X}(x\mid X\le M)=f_X(x)dx\cdot \left[F_X(M)\right]^{-1} $$ so that it integrates to unity over $[a, M]$. The middle term in the above expression makes us think of this situation (rightfully) as a form of conditioning -but not on another random variable, but on the possible values the r.v. itself can take. Here a joint density/likelihood function of a collection of $n$ truncated i.i.d r.v.'s would be $n$ times the above density, as usual. B) Probability mass concentration Here, which is what you describe in the question, things are different. The point $M$ concentrates all the probability mass that corresponds to the support of the variable higher than $M$. This creates a point of discontinuity in the density and makes it having two branches $$\begin{align} f_{X^*}(x^*) &= f_X(x^*) \qquad x^*<M\\ f_{X^*}(x^*) &= P(X^* \ge M) \qquad x^*\ge M\\ \end{align}$$ Informally, the second is "like a discrete r.v." where each point in the probability mass function represents actual probabilities. Now assume that we have $n$ such i.i.d random variables, and we want to form their joint density/likelihood function. Before looking at the actual sample, what branch should we choose? We cannot make that decision so we have to somehow include both. To do this we need to use indicator functions: denote $I\{x^*\ge M\}\equiv I_{\ge M}(x^*)$ the indicator function that takes the value $1$ when $x^*\ge M$, and $0$ otherwise. The density of such a r.v. can be written $$f_{X^*}(x^*) = f_X(x^*)\cdot \left[1-I_{\ge M}(x^*)\right]+P(X^* \ge M)\cdot I_{\ge M}(x^*) $$ and therefore the joint density function of $n$ such i.i.d. variables is $$f_{X^*}(\mathbf X^*\mid \theta) = \prod_{i=1}^n\Big[f_X(x^*_i)\cdot \left[1-I_{\ge M}(x^*_i)\right]+P(X^*_i \ge M)\cdot I_{\ge M}(x^*_i)\Big]$$ Now, the above viewed as a likelihood function, the actual sample consisting of realizations of these $n$ random variables comes into play. And in this sample, some observed realizations will be lower than the threshold $M$, some equal. Denote $m$ the number of realizations in the sample that equals $M$, and $v$ all the rest, $m+v=n$. It is immediate that for the $m$ realizations, the corresponding part of the density that will remain in the likelihood will be the $P(X^*_i \ge M)$ part, while for the $v$ realizations, the other part. Then $$\begin{align} L(\theta\mid \{x_i^*;\,i=1,...n\})&= \prod_{i=1}^v\Big[f_X(x^*_i)\Big]\cdot \prod_{j=1}^m\Big[P(X^*_j \ge M)\Big] \\& = \prod_{i=1}^v\Big[f_X(x^*_i)\Big]\cdot \Big[P(X^* \ge M)\Big]^m\\ \end{align}$$
Likelihood function of truncated data
What you describe needs special treatment, it is not what we usually mean by "truncated random variables"-and what we usually mean is that the random variable does not range outside the truncated supp
Likelihood function of truncated data What you describe needs special treatment, it is not what we usually mean by "truncated random variables"-and what we usually mean is that the random variable does not range outside the truncated support, meaning that there is not a concentration of probability mass at the point of truncation. To contrast cases: A) "Usual" meaning of a truncated rv For any distribution that we truncate its support, we must "correct" its density so that it integrates to unity when integrated over the truncated support. If the variable has support in $[a,b]$, $-\infty < a < b < \infty$, then (pdf $f$, cdf $F$) $$\int_a^bf_X(x)dx = \int_a^Mf_X(x)dx+\int_M^bf_X(x)dx = \int_a^Mf_X(x)dx + \left[1-F_X(M)\right]=1 $$ $$\Rightarrow \int_a^Mf_X(x)dx = F_X(M)$$ Since the LHS is the integral over the truncated support, we see that the density of the truncated r.v., call it $\tilde X$, must be $$f_{\tilde X}(\tilde x) = f_{X}(x\mid X\le M)=f_X(x)dx\cdot \left[F_X(M)\right]^{-1} $$ so that it integrates to unity over $[a, M]$. The middle term in the above expression makes us think of this situation (rightfully) as a form of conditioning -but not on another random variable, but on the possible values the r.v. itself can take. Here a joint density/likelihood function of a collection of $n$ truncated i.i.d r.v.'s would be $n$ times the above density, as usual. B) Probability mass concentration Here, which is what you describe in the question, things are different. The point $M$ concentrates all the probability mass that corresponds to the support of the variable higher than $M$. This creates a point of discontinuity in the density and makes it having two branches $$\begin{align} f_{X^*}(x^*) &= f_X(x^*) \qquad x^*<M\\ f_{X^*}(x^*) &= P(X^* \ge M) \qquad x^*\ge M\\ \end{align}$$ Informally, the second is "like a discrete r.v." where each point in the probability mass function represents actual probabilities. Now assume that we have $n$ such i.i.d random variables, and we want to form their joint density/likelihood function. Before looking at the actual sample, what branch should we choose? We cannot make that decision so we have to somehow include both. To do this we need to use indicator functions: denote $I\{x^*\ge M\}\equiv I_{\ge M}(x^*)$ the indicator function that takes the value $1$ when $x^*\ge M$, and $0$ otherwise. The density of such a r.v. can be written $$f_{X^*}(x^*) = f_X(x^*)\cdot \left[1-I_{\ge M}(x^*)\right]+P(X^* \ge M)\cdot I_{\ge M}(x^*) $$ and therefore the joint density function of $n$ such i.i.d. variables is $$f_{X^*}(\mathbf X^*\mid \theta) = \prod_{i=1}^n\Big[f_X(x^*_i)\cdot \left[1-I_{\ge M}(x^*_i)\right]+P(X^*_i \ge M)\cdot I_{\ge M}(x^*_i)\Big]$$ Now, the above viewed as a likelihood function, the actual sample consisting of realizations of these $n$ random variables comes into play. And in this sample, some observed realizations will be lower than the threshold $M$, some equal. Denote $m$ the number of realizations in the sample that equals $M$, and $v$ all the rest, $m+v=n$. It is immediate that for the $m$ realizations, the corresponding part of the density that will remain in the likelihood will be the $P(X^*_i \ge M)$ part, while for the $v$ realizations, the other part. Then $$\begin{align} L(\theta\mid \{x_i^*;\,i=1,...n\})&= \prod_{i=1}^v\Big[f_X(x^*_i)\Big]\cdot \prod_{j=1}^m\Big[P(X^*_j \ge M)\Big] \\& = \prod_{i=1}^v\Big[f_X(x^*_i)\Big]\cdot \Big[P(X^* \ge M)\Big]^m\\ \end{align}$$
Likelihood function of truncated data What you describe needs special treatment, it is not what we usually mean by "truncated random variables"-and what we usually mean is that the random variable does not range outside the truncated supp
31,325
Likelihood function of truncated data
The likelihood theory is a fairly general framework. Most textbooks state results for the separated cases of continuous r.vs and for that for discrete r.vs. However mixed cases occur in practice, as is the case here. For a discrete r.v. $A$, the likelihood of an observation $a$ is defined as the probability of getting the observed value $a$, say $p_A(a)$. For a continuous r.v. the likelihood $L$ is usually defined as the density at $x$, say $f_X(x)$. However in practice one only knows that $x_{\textrm{L}} < X < x_{\textrm{U}}$ - because of a limited measurement precision, and $\Pr\left\{x_{\textrm{L}} < X < x_{\textrm{U}}\right\}$ should be used as likelihood. Taking $x_{\textrm{L}}:= x - \textrm{d}x/2$, $x_{\textrm{U}}:= x + \textrm{d}x/2$ with $\mathrm{d}x$ small, we get $f_X(x)$ up to a multiplicative $\mathrm{d}x$ which does not matter. So the usual definition can be viewed as implicitly assuming an infinite precision on the observation. For a couple of r.vs $A$ and $X$ with mixed joint type discrete/continuous, the likelihood will be the joint distribution, which is usually expressed using conditional distributions, e.g. $$ L := \textrm{Pr}\left\{ A = a, \, x_{\textrm{L}} < X < x_{\textrm{U}} \right\} = \textrm{Pr}\left\{ A = a \right\} \times \textrm{Pr} \left\{x_{\textrm{L}} < X < x_{\textrm{U}} \, \vert\, A = a\right\}. $$ Thus for an interval $(x_{\textrm{L}},\, x_{\textrm{U}})$ with small length $\textrm{d}x$, $L$ is $p_A(a)$ times the density of $X$ conditional on $\{A=a\}$, say $f_{X \vert A}(x \,\vert \,a)$. Again, we omit the $\mathrm{d}x$ term. Now let us come back to your example, and consider only one observation. Then $A = 1_{\{X > M\}}$ is a Bernoulli r.v with success probability $\Pr\{X > M\}$. Depending on $X > M$ or not, either you observe only $A = 1$ or you observe both $A = 0$ and the value $x$ of $X$. In both cases you use the formula above, but $(x_{\textrm{L}},\, x_{\textrm{U}})$ is taken either as $(M,\,\infty)$ or as an interval of small length $\textrm{d}x$ containing $x$. Indeed this gives $$ L = \begin{cases} \textrm{Pr} \left\{X > M \right\} \times 1 & \textrm{if } X > M \textrm{ i.e. } A =1,\\ \textrm{Pr} \left\{X \leq M\right\} \times f_{X \vert A}(x \,\vert \,a)\,\textrm{d}x & \textrm{if } X \leq M \textrm{ i.e. } A = 0. \end{cases} $$ Since $f_{X \vert A}(x \,\vert \,0) = f_X(x) / \textrm{Pr} \left\{ X \leq M \right\}$, the likelihood is simply $f_X(x)\,\textrm{d}x$ in the second case and we get the claimed likelihood, up to the $\mathrm{d}x$ term for an observation with infinite precision. When independent observations $A_i$ and $X_i$ are made, the likelihood is obtained as the product of the marginal likelihoods leading to the expression in the question.
Likelihood function of truncated data
The likelihood theory is a fairly general framework. Most textbooks state results for the separated cases of continuous r.vs and for that for discrete r.vs. However mixed cases occur in practice, as
Likelihood function of truncated data The likelihood theory is a fairly general framework. Most textbooks state results for the separated cases of continuous r.vs and for that for discrete r.vs. However mixed cases occur in practice, as is the case here. For a discrete r.v. $A$, the likelihood of an observation $a$ is defined as the probability of getting the observed value $a$, say $p_A(a)$. For a continuous r.v. the likelihood $L$ is usually defined as the density at $x$, say $f_X(x)$. However in practice one only knows that $x_{\textrm{L}} < X < x_{\textrm{U}}$ - because of a limited measurement precision, and $\Pr\left\{x_{\textrm{L}} < X < x_{\textrm{U}}\right\}$ should be used as likelihood. Taking $x_{\textrm{L}}:= x - \textrm{d}x/2$, $x_{\textrm{U}}:= x + \textrm{d}x/2$ with $\mathrm{d}x$ small, we get $f_X(x)$ up to a multiplicative $\mathrm{d}x$ which does not matter. So the usual definition can be viewed as implicitly assuming an infinite precision on the observation. For a couple of r.vs $A$ and $X$ with mixed joint type discrete/continuous, the likelihood will be the joint distribution, which is usually expressed using conditional distributions, e.g. $$ L := \textrm{Pr}\left\{ A = a, \, x_{\textrm{L}} < X < x_{\textrm{U}} \right\} = \textrm{Pr}\left\{ A = a \right\} \times \textrm{Pr} \left\{x_{\textrm{L}} < X < x_{\textrm{U}} \, \vert\, A = a\right\}. $$ Thus for an interval $(x_{\textrm{L}},\, x_{\textrm{U}})$ with small length $\textrm{d}x$, $L$ is $p_A(a)$ times the density of $X$ conditional on $\{A=a\}$, say $f_{X \vert A}(x \,\vert \,a)$. Again, we omit the $\mathrm{d}x$ term. Now let us come back to your example, and consider only one observation. Then $A = 1_{\{X > M\}}$ is a Bernoulli r.v with success probability $\Pr\{X > M\}$. Depending on $X > M$ or not, either you observe only $A = 1$ or you observe both $A = 0$ and the value $x$ of $X$. In both cases you use the formula above, but $(x_{\textrm{L}},\, x_{\textrm{U}})$ is taken either as $(M,\,\infty)$ or as an interval of small length $\textrm{d}x$ containing $x$. Indeed this gives $$ L = \begin{cases} \textrm{Pr} \left\{X > M \right\} \times 1 & \textrm{if } X > M \textrm{ i.e. } A =1,\\ \textrm{Pr} \left\{X \leq M\right\} \times f_{X \vert A}(x \,\vert \,a)\,\textrm{d}x & \textrm{if } X \leq M \textrm{ i.e. } A = 0. \end{cases} $$ Since $f_{X \vert A}(x \,\vert \,0) = f_X(x) / \textrm{Pr} \left\{ X \leq M \right\}$, the likelihood is simply $f_X(x)\,\textrm{d}x$ in the second case and we get the claimed likelihood, up to the $\mathrm{d}x$ term for an observation with infinite precision. When independent observations $A_i$ and $X_i$ are made, the likelihood is obtained as the product of the marginal likelihoods leading to the expression in the question.
Likelihood function of truncated data The likelihood theory is a fairly general framework. Most textbooks state results for the separated cases of continuous r.vs and for that for discrete r.vs. However mixed cases occur in practice, as
31,326
Combining p-values from different statistical tests applied on the same data
Using multiple testing correction as advocated by Corone is ok, but it will cost you mountains of power as your p-values will generally be well correlated, even using Hommel correction. There is a solution which is computation demanding but will do much better in term of power. If $p_1, p_2, \dots, p_n$ are your p-values, let $p^* = \min (p_1, \dots, p_n)$. Consider that $p^*$ is your new test statistic: the smaller it is, the stronger it advocates against the null hypothesis. You need to compute $p$-value for the observed value of $p^*$ (call it $p^*_{obs}$). For this, you can simulate, say, 100 000 data sets under the null hypotheses, and for each such data set, compute a $p^*$. This gives you an empirical distribution of $p^*$ under the null hypothesis. Your $p$-value is the proportion of simulated values which are $<p^*_{obs}$. How do you simulate the data sets under the null hypothesis? In your case you have, if I guess well, cases and controls, and RNS-seq data to estimate expression levels. To simulate a data set under the null, it is customary to simply randomly permute the case/control status.
Combining p-values from different statistical tests applied on the same data
Using multiple testing correction as advocated by Corone is ok, but it will cost you mountains of power as your p-values will generally be well correlated, even using Hommel correction. There is a sol
Combining p-values from different statistical tests applied on the same data Using multiple testing correction as advocated by Corone is ok, but it will cost you mountains of power as your p-values will generally be well correlated, even using Hommel correction. There is a solution which is computation demanding but will do much better in term of power. If $p_1, p_2, \dots, p_n$ are your p-values, let $p^* = \min (p_1, \dots, p_n)$. Consider that $p^*$ is your new test statistic: the smaller it is, the stronger it advocates against the null hypothesis. You need to compute $p$-value for the observed value of $p^*$ (call it $p^*_{obs}$). For this, you can simulate, say, 100 000 data sets under the null hypotheses, and for each such data set, compute a $p^*$. This gives you an empirical distribution of $p^*$ under the null hypothesis. Your $p$-value is the proportion of simulated values which are $<p^*_{obs}$. How do you simulate the data sets under the null hypothesis? In your case you have, if I guess well, cases and controls, and RNS-seq data to estimate expression levels. To simulate a data set under the null, it is customary to simply randomly permute the case/control status.
Combining p-values from different statistical tests applied on the same data Using multiple testing correction as advocated by Corone is ok, but it will cost you mountains of power as your p-values will generally be well correlated, even using Hommel correction. There is a sol
31,327
Combining p-values from different statistical tests applied on the same data
This sort of thing would usually covered by multiple hypothesis testing, although it isn't quite a typical situation. You are correct in noting that this is different from meta-analysis, in that you are using the same data for multiple tests, but that situation is still covered by multiple-hypothesis testing. What is slightly odd here is that it is almost the same hypothesis that you are testing multiple times, and then you want the global null hypothesis that is the intersection of all of those - it is perhaps worth wondering why you feel the need to do this, but there could be legitimate reasons. Were you doing a more analytically tractable set of tests, one might head down the Union-Intersection test route, but I don't think that would get you anywhere, so I'd recommend using an out of the box multiplicity correction. I'd suggest you start by having a look at what Wikipedia has to say on the subject, but try not to get too bogged down: http://en.wikipedia.org/wiki/Multiple_comparisons So, you need to use a multiplicity correction, and ruling out Union-Intersection, roughly your options are as follows Bonferonni - Strictly dominated by Holm-Bonferroni, historical interest only Holm-Bonferroni - Will work for you, but will cost you power (possibly a lot in your case) Sidak - more powerful than BH, but you cannot use this because your p-values will be correlated Hommel - more powerful than BH, and you should be fine, since your p-values are undoubtably positively correlated Your biggest issue is that you are very likely to get very similar p-values in your different tests. Hommel shouldn't punish you too much for this. For example, you can adjust p-values in R using p.adjust p = c(0.03, 0.034, 0.041) p.adjust(p, method = "bonferroni") p.adjust(p, method = "holm") p.adjust(p, method = "hommel") > p.adjust(p, method = "bonferroni") [1] 0.090 0.102 0.123 > p.adjust(p, method = "holm") [1] 0.09 0.09 0.09 > p.adjust(p, method = "hommel") [1] 0.041 0.041 0.041 These methods all control the Family-wise Error Rate which means that if you test each p-value in turn based on it passing your threshold, then the probability of 1 or more errors is still controlled at $\alpha$. This means that you can reject the global hypothesis if you reject one or more sub-hypothesis, and the size of your test is still controlled at $\alpha$. As I intimated at the start, this won't be the most powerful attack you could do, but anything more sophisticated is going to require much more work. Why this controls $\alpha$ The global null hypothesis is that all child null hypothesis are true. Let the outcome of a single test be $X_i$ taking the value 1 if the null is rejected, 0 otherwise. Since $X_i$ are undoubtedly positively correlated, we can use Hommel to control for the FWER. This control means that the probability that one or more tests falsely reject is controlled at $\alpha$ Therefore, $P(\sum(X_i) > 0) \le \alpha$ Therefore if you reject the global hypothesis if one or more child hypotheses are rejected, the size of the global test is $\le \alpha$
Combining p-values from different statistical tests applied on the same data
This sort of thing would usually covered by multiple hypothesis testing, although it isn't quite a typical situation. You are correct in noting that this is different from meta-analysis, in that you a
Combining p-values from different statistical tests applied on the same data This sort of thing would usually covered by multiple hypothesis testing, although it isn't quite a typical situation. You are correct in noting that this is different from meta-analysis, in that you are using the same data for multiple tests, but that situation is still covered by multiple-hypothesis testing. What is slightly odd here is that it is almost the same hypothesis that you are testing multiple times, and then you want the global null hypothesis that is the intersection of all of those - it is perhaps worth wondering why you feel the need to do this, but there could be legitimate reasons. Were you doing a more analytically tractable set of tests, one might head down the Union-Intersection test route, but I don't think that would get you anywhere, so I'd recommend using an out of the box multiplicity correction. I'd suggest you start by having a look at what Wikipedia has to say on the subject, but try not to get too bogged down: http://en.wikipedia.org/wiki/Multiple_comparisons So, you need to use a multiplicity correction, and ruling out Union-Intersection, roughly your options are as follows Bonferonni - Strictly dominated by Holm-Bonferroni, historical interest only Holm-Bonferroni - Will work for you, but will cost you power (possibly a lot in your case) Sidak - more powerful than BH, but you cannot use this because your p-values will be correlated Hommel - more powerful than BH, and you should be fine, since your p-values are undoubtably positively correlated Your biggest issue is that you are very likely to get very similar p-values in your different tests. Hommel shouldn't punish you too much for this. For example, you can adjust p-values in R using p.adjust p = c(0.03, 0.034, 0.041) p.adjust(p, method = "bonferroni") p.adjust(p, method = "holm") p.adjust(p, method = "hommel") > p.adjust(p, method = "bonferroni") [1] 0.090 0.102 0.123 > p.adjust(p, method = "holm") [1] 0.09 0.09 0.09 > p.adjust(p, method = "hommel") [1] 0.041 0.041 0.041 These methods all control the Family-wise Error Rate which means that if you test each p-value in turn based on it passing your threshold, then the probability of 1 or more errors is still controlled at $\alpha$. This means that you can reject the global hypothesis if you reject one or more sub-hypothesis, and the size of your test is still controlled at $\alpha$. As I intimated at the start, this won't be the most powerful attack you could do, but anything more sophisticated is going to require much more work. Why this controls $\alpha$ The global null hypothesis is that all child null hypothesis are true. Let the outcome of a single test be $X_i$ taking the value 1 if the null is rejected, 0 otherwise. Since $X_i$ are undoubtedly positively correlated, we can use Hommel to control for the FWER. This control means that the probability that one or more tests falsely reject is controlled at $\alpha$ Therefore, $P(\sum(X_i) > 0) \le \alpha$ Therefore if you reject the global hypothesis if one or more child hypotheses are rejected, the size of the global test is $\le \alpha$
Combining p-values from different statistical tests applied on the same data This sort of thing would usually covered by multiple hypothesis testing, although it isn't quite a typical situation. You are correct in noting that this is different from meta-analysis, in that you a
31,328
Combining p-values from different statistical tests applied on the same data
In case you are still interested, I found this paper that seems to address the problem of integrating different analysis algorithms on the same set of RNA-seq data: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4344485/. It's basically proposing a weighted sum of all p-values and the weights are based on the ROC of each algorithm. The name of the paper is: Systematic integration of RNA-Seq statistical algorithms for accurate detection of differential gene expression patterns.
Combining p-values from different statistical tests applied on the same data
In case you are still interested, I found this paper that seems to address the problem of integrating different analysis algorithms on the same set of RNA-seq data: https://www.ncbi.nlm.nih.gov/pmc/ar
Combining p-values from different statistical tests applied on the same data In case you are still interested, I found this paper that seems to address the problem of integrating different analysis algorithms on the same set of RNA-seq data: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4344485/. It's basically proposing a weighted sum of all p-values and the weights are based on the ROC of each algorithm. The name of the paper is: Systematic integration of RNA-Seq statistical algorithms for accurate detection of differential gene expression patterns.
Combining p-values from different statistical tests applied on the same data In case you are still interested, I found this paper that seems to address the problem of integrating different analysis algorithms on the same set of RNA-seq data: https://www.ncbi.nlm.nih.gov/pmc/ar
31,329
How to compare two groups with multiple measurements for each individual with R?
I take the freedom to answer the question in the title, how would I analyze this data. Given that we have replicates within the samples, mixed models immediately come to mind, which should estimate the variability within each individual and control for it. Hence I fit the model using lmer from lme4. However, as we are interested in p-values, I use mixed from afex which obtains those via pbkrtest (i.e., Kenward-Rogers approximation for degrees-of-freedom). (afex also already sets the contrast to contr.sum which I would use in such a case anyway) To control for the zero floor effect (i.e., positive skew), I fit two alternative versions transforming the dependent variable either with sqrt for mild skew and log for stronger skew. require(afex) # read the dput() in as dat <- ... dat <- as.data.frame(dat) dat$Group <- factor(dat$Group) dat$Subject <- factor(dat$Subject) (model <- mixed(Value ~ Group + (1|Subject), dat)) ## Effect stat ndf ddf F.scaling p.value ## 1 (Intercept) 237.730 1 15 1 0.0000 ## 2 Group 7.749 2 15 1 0.0049 (model.s <- mixed(sqrt(Value) ~ Group + (1|Subject), dat)) ## Effect stat ndf ddf F.scaling p.value ## 1 (Intercept) 418.293 1 15 1 0.0000 ## 2 Group 4.121 2 15 1 0.0375 (model.l <- mixed(log1p(Value) ~ Group + (1|Subject), dat)) ## Effect stat ndf ddf F.scaling p.value ## 1 (Intercept) 458.650 1 15 1 0.0000 ## 2 Group 2.721 2 15 1 0.0981 The effect is significant for the untransformed and sqrt dv. But are these model sensible? Let's plot the residuals. png("qq.png", 800, 300, units = "px", pointsize = 12) par(mfrow = c(1, 3)) par(cex = 1.1) par(mar = c(2, 2, 2, 1)+0.1) qqnorm(resid(model[[2]]), main = "original") qqline(resid(model[[2]])) qqnorm(resid(model.s[[2]]), main = "sqrt") qqline(resid(model.s[[2]])) qqnorm(resid(model.l[[2]]), main = "log") qqline(resid(model.l[[2]])) dev.off() It seems that the model with sqrt trasnformation provides a reasonable fit (there still seems to be one outlier, but I will ignore it). So, let's further inspect this model using multcomp to get the comparisons among groups: require(multcomp) # using bonferroni-holm correction of multiple comparison summary(glht(model.s[[2]], linfct = mcp(Group = "Tukey")), test = adjusted("holm")) ## Simultaneous Tests for General Linear Hypotheses ## ## Multiple Comparisons of Means: Tukey Contrasts ## ## ## Fit: lmer(formula = sqrt(Value) ~ Group + (1 | Subject), data = data) ## ## Linear Hypotheses: ## Estimate Std. Error z value Pr(>|z|) ## 2 - 1 == 0 -0.0754 0.3314 -0.23 0.820 ## 3 - 1 == 0 1.1189 0.4419 2.53 0.023 * ## 3 - 2 == 0 1.1943 0.4335 2.75 0.018 * ## --- ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ## (Adjusted p values reported -- holm method) # using default multiple comparison correction (which I don't understand) summary(glht(model.s[[2]], linfct = mcp(Group = "Tukey"))) ## Simultaneous Tests for General Linear Hypotheses ## ## Multiple Comparisons of Means: Tukey Contrasts ## ## ## Fit: lmer(formula = sqrt(Value) ~ Group + (1 | Subject), data = data) ## ## Linear Hypotheses: ## Estimate Std. Error z value Pr(>|z|) ## 2 - 1 == 0 -0.0754 0.3314 -0.23 0.972 ## 3 - 1 == 0 1.1189 0.4419 2.53 0.030 * ## 3 - 2 == 0 1.1943 0.4335 2.75 0.016 * ## --- ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ## (Adjusted p values reported -- single-step method) Punchline: group 3 differs from the other two groups which do not differ among each other.
How to compare two groups with multiple measurements for each individual with R?
I take the freedom to answer the question in the title, how would I analyze this data. Given that we have replicates within the samples, mixed models immediately come to mind, which should estimate th
How to compare two groups with multiple measurements for each individual with R? I take the freedom to answer the question in the title, how would I analyze this data. Given that we have replicates within the samples, mixed models immediately come to mind, which should estimate the variability within each individual and control for it. Hence I fit the model using lmer from lme4. However, as we are interested in p-values, I use mixed from afex which obtains those via pbkrtest (i.e., Kenward-Rogers approximation for degrees-of-freedom). (afex also already sets the contrast to contr.sum which I would use in such a case anyway) To control for the zero floor effect (i.e., positive skew), I fit two alternative versions transforming the dependent variable either with sqrt for mild skew and log for stronger skew. require(afex) # read the dput() in as dat <- ... dat <- as.data.frame(dat) dat$Group <- factor(dat$Group) dat$Subject <- factor(dat$Subject) (model <- mixed(Value ~ Group + (1|Subject), dat)) ## Effect stat ndf ddf F.scaling p.value ## 1 (Intercept) 237.730 1 15 1 0.0000 ## 2 Group 7.749 2 15 1 0.0049 (model.s <- mixed(sqrt(Value) ~ Group + (1|Subject), dat)) ## Effect stat ndf ddf F.scaling p.value ## 1 (Intercept) 418.293 1 15 1 0.0000 ## 2 Group 4.121 2 15 1 0.0375 (model.l <- mixed(log1p(Value) ~ Group + (1|Subject), dat)) ## Effect stat ndf ddf F.scaling p.value ## 1 (Intercept) 458.650 1 15 1 0.0000 ## 2 Group 2.721 2 15 1 0.0981 The effect is significant for the untransformed and sqrt dv. But are these model sensible? Let's plot the residuals. png("qq.png", 800, 300, units = "px", pointsize = 12) par(mfrow = c(1, 3)) par(cex = 1.1) par(mar = c(2, 2, 2, 1)+0.1) qqnorm(resid(model[[2]]), main = "original") qqline(resid(model[[2]])) qqnorm(resid(model.s[[2]]), main = "sqrt") qqline(resid(model.s[[2]])) qqnorm(resid(model.l[[2]]), main = "log") qqline(resid(model.l[[2]])) dev.off() It seems that the model with sqrt trasnformation provides a reasonable fit (there still seems to be one outlier, but I will ignore it). So, let's further inspect this model using multcomp to get the comparisons among groups: require(multcomp) # using bonferroni-holm correction of multiple comparison summary(glht(model.s[[2]], linfct = mcp(Group = "Tukey")), test = adjusted("holm")) ## Simultaneous Tests for General Linear Hypotheses ## ## Multiple Comparisons of Means: Tukey Contrasts ## ## ## Fit: lmer(formula = sqrt(Value) ~ Group + (1 | Subject), data = data) ## ## Linear Hypotheses: ## Estimate Std. Error z value Pr(>|z|) ## 2 - 1 == 0 -0.0754 0.3314 -0.23 0.820 ## 3 - 1 == 0 1.1189 0.4419 2.53 0.023 * ## 3 - 2 == 0 1.1943 0.4335 2.75 0.018 * ## --- ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ## (Adjusted p values reported -- holm method) # using default multiple comparison correction (which I don't understand) summary(glht(model.s[[2]], linfct = mcp(Group = "Tukey"))) ## Simultaneous Tests for General Linear Hypotheses ## ## Multiple Comparisons of Means: Tukey Contrasts ## ## ## Fit: lmer(formula = sqrt(Value) ~ Group + (1 | Subject), data = data) ## ## Linear Hypotheses: ## Estimate Std. Error z value Pr(>|z|) ## 2 - 1 == 0 -0.0754 0.3314 -0.23 0.972 ## 3 - 1 == 0 1.1189 0.4419 2.53 0.030 * ## 3 - 2 == 0 1.1943 0.4335 2.75 0.016 * ## --- ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ## (Adjusted p values reported -- single-step method) Punchline: group 3 differs from the other two groups which do not differ among each other.
How to compare two groups with multiple measurements for each individual with R? I take the freedom to answer the question in the title, how would I analyze this data. Given that we have replicates within the samples, mixed models immediately come to mind, which should estimate th
31,330
How to compare two groups with multiple measurements for each individual with R?
For information, the random-effect model given by @Henrik: > f <- function(x) sqrt(x) > library(lme4) > ( fit1 <- lmer(f(Value) ~ Group + (1|Subject), data=dat) ) Linear mixed model fit by REML ['lmerMod'] Formula: f(Value) ~ Group + (1 | Subject) Data: dat REML criterion at convergence: 296.3579 Random effects: Groups Name Std.Dev. Subject (Intercept) 0.5336 Residual 0.8673 Number of obs: 108, groups: Subject, 18 Fixed Effects: (Intercept) Group2 Group3 3.03718 -0.07541 1.11886 is equivalent to a generalized least-squares model with an exchangeable correlation structure for subjects: > library(nlme) > fit2 <- gls(f(Value) ~ Group, data=dat, na.action=na.omit, correlation=corCompSymm(form= ~ 1 | Subject)) The fitted variance matrix is then: > getVarCov(fit2) Marginal variance covariance matrix [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1.03690 0.28471 0.28471 0.28471 0.28471 0.28471 [2,] 0.28471 1.03690 0.28471 0.28471 0.28471 0.28471 [3,] 0.28471 0.28471 1.03690 0.28471 0.28471 0.28471 [4,] 0.28471 0.28471 0.28471 1.03690 0.28471 0.28471 [5,] 0.28471 0.28471 0.28471 0.28471 1.03690 0.28471 [6,] 0.28471 0.28471 0.28471 0.28471 0.28471 1.03690 Standard Deviations: 1.0183 1.0183 1.0183 1.0183 1.0183 1.0183 As you can see, the diagonal entry corresponds to the total variance in the first model: > VarCorr(fit1) Groups Name Std.Dev. Subject (Intercept) 0.53358 Residual 0.86731 > 0.53358^2+0.86731^2 [1] 1.036934 and the covariance corresponds to the between-subject variance: > 0.53358^2 [1] 0.2847076 Actually the gls model is more general because it allows a negative covariance. The advantage of nlme is that you can more generally use other repeated correlation structures and also you can specify different variances per group with the weights argument. I think that residuals are different because they are constructed with the random-effects in the first model. In order to get multiple comparisons you can use the lsmeans and the multcomp packages, but the $p$-values of the hypotheses tests are anticonservative with defaults (too high) degrees of freedom. Unfortunately, the pbkrtest package does not apply to gls/lme models.
How to compare two groups with multiple measurements for each individual with R?
For information, the random-effect model given by @Henrik: > f <- function(x) sqrt(x) > library(lme4) > ( fit1 <- lmer(f(Value) ~ Group + (1|Subject), data=dat) ) Linear mixed model fit by REML ['lmer
How to compare two groups with multiple measurements for each individual with R? For information, the random-effect model given by @Henrik: > f <- function(x) sqrt(x) > library(lme4) > ( fit1 <- lmer(f(Value) ~ Group + (1|Subject), data=dat) ) Linear mixed model fit by REML ['lmerMod'] Formula: f(Value) ~ Group + (1 | Subject) Data: dat REML criterion at convergence: 296.3579 Random effects: Groups Name Std.Dev. Subject (Intercept) 0.5336 Residual 0.8673 Number of obs: 108, groups: Subject, 18 Fixed Effects: (Intercept) Group2 Group3 3.03718 -0.07541 1.11886 is equivalent to a generalized least-squares model with an exchangeable correlation structure for subjects: > library(nlme) > fit2 <- gls(f(Value) ~ Group, data=dat, na.action=na.omit, correlation=corCompSymm(form= ~ 1 | Subject)) The fitted variance matrix is then: > getVarCov(fit2) Marginal variance covariance matrix [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1.03690 0.28471 0.28471 0.28471 0.28471 0.28471 [2,] 0.28471 1.03690 0.28471 0.28471 0.28471 0.28471 [3,] 0.28471 0.28471 1.03690 0.28471 0.28471 0.28471 [4,] 0.28471 0.28471 0.28471 1.03690 0.28471 0.28471 [5,] 0.28471 0.28471 0.28471 0.28471 1.03690 0.28471 [6,] 0.28471 0.28471 0.28471 0.28471 0.28471 1.03690 Standard Deviations: 1.0183 1.0183 1.0183 1.0183 1.0183 1.0183 As you can see, the diagonal entry corresponds to the total variance in the first model: > VarCorr(fit1) Groups Name Std.Dev. Subject (Intercept) 0.53358 Residual 0.86731 > 0.53358^2+0.86731^2 [1] 1.036934 and the covariance corresponds to the between-subject variance: > 0.53358^2 [1] 0.2847076 Actually the gls model is more general because it allows a negative covariance. The advantage of nlme is that you can more generally use other repeated correlation structures and also you can specify different variances per group with the weights argument. I think that residuals are different because they are constructed with the random-effects in the first model. In order to get multiple comparisons you can use the lsmeans and the multcomp packages, but the $p$-values of the hypotheses tests are anticonservative with defaults (too high) degrees of freedom. Unfortunately, the pbkrtest package does not apply to gls/lme models.
How to compare two groups with multiple measurements for each individual with R? For information, the random-effect model given by @Henrik: > f <- function(x) sqrt(x) > library(lme4) > ( fit1 <- lmer(f(Value) ~ Group + (1|Subject), data=dat) ) Linear mixed model fit by REML ['lmer
31,331
How to compare two groups with multiple measurements for each individual with R?
Now, try to you write down the model: $y_{ijk} = ...$ where $y_{ijk}$ is the $k$-th value for individual $j$ of group $i$. Then look at what happens for the means $\bar y_{ij\bullet}$: you get a classical Gaussian linear model, with variance homogeneity because there are $6$ repeated measures for each subject: > xtabs(~Group+Subject, data=dat) Subject Group 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 6 6 6 6 6 6 6 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 6 6 6 6 6 6 6 6 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 6 6 Thus, since you are interested in mean comparisons only, you don't need to resort to a random-effect or generalised least-squares model - just use a classical (fixed effects) model using the means $\bar y_{ij\bullet}$ as the observations: tdat <- transform(dat, tvalue=f(Value)) dd <- aggregate(tvalue~Group+Subject, data=tdat, FUN=mean) fit3 <- lm(tvalue~Group, data=dd) I think this approach always correctly work when we average the data over the levels of a random effect (I show on my blog how this fails for an example with a fixed effect). The ANOVA provides the same answer as @Henrik's approach (and that shows that Kenward-Rogers approximation is correct): > anova(fit3) Analysis of Variance Table Response: tvalue Df Sum Sq Mean Sq F value Pr(>F) Group 2 3.3799 1.68994 4.121 0.03747 * Then you can use TukeyHSD() or the lsmeans package for multiple comparisons: > TukeyHSD(aov(fit3), "Group") Tukey multiple comparisons of means 95% family-wise confidence level Fit: aov(formula = fit3) $Group diff lwr upr p adj 2-1 -0.07541248 -0.93627828 0.7854533 0.9719148 3-1 1.11885667 -0.02896441 2.2666777 0.0565628 3-2 1.19426915 0.06817536 2.3203629 0.0370434 > library(lsmeans) > lsmeans(fit3, pairwise~Group) $`Group pairwise differences` estimate SE df t.ratio p.value 1 - 2 0.07541248 0.3314247 15 0.22754 0.97191 1 - 3 -1.11885667 0.4418996 15 -2.53193 0.05656 2 - 3 -1.19426915 0.4335348 15 -2.75472 0.03704 p values are adjusted using the tukey method for 3 means
How to compare two groups with multiple measurements for each individual with R?
Now, try to you write down the model: $y_{ijk} = ...$ where $y_{ijk}$ is the $k$-th value for individual $j$ of group $i$. Then look at what happens for the means $\bar y_{ij\bullet}$: you get a class
How to compare two groups with multiple measurements for each individual with R? Now, try to you write down the model: $y_{ijk} = ...$ where $y_{ijk}$ is the $k$-th value for individual $j$ of group $i$. Then look at what happens for the means $\bar y_{ij\bullet}$: you get a classical Gaussian linear model, with variance homogeneity because there are $6$ repeated measures for each subject: > xtabs(~Group+Subject, data=dat) Subject Group 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 6 6 6 6 6 6 6 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 6 6 6 6 6 6 6 6 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 6 6 Thus, since you are interested in mean comparisons only, you don't need to resort to a random-effect or generalised least-squares model - just use a classical (fixed effects) model using the means $\bar y_{ij\bullet}$ as the observations: tdat <- transform(dat, tvalue=f(Value)) dd <- aggregate(tvalue~Group+Subject, data=tdat, FUN=mean) fit3 <- lm(tvalue~Group, data=dd) I think this approach always correctly work when we average the data over the levels of a random effect (I show on my blog how this fails for an example with a fixed effect). The ANOVA provides the same answer as @Henrik's approach (and that shows that Kenward-Rogers approximation is correct): > anova(fit3) Analysis of Variance Table Response: tvalue Df Sum Sq Mean Sq F value Pr(>F) Group 2 3.3799 1.68994 4.121 0.03747 * Then you can use TukeyHSD() or the lsmeans package for multiple comparisons: > TukeyHSD(aov(fit3), "Group") Tukey multiple comparisons of means 95% family-wise confidence level Fit: aov(formula = fit3) $Group diff lwr upr p adj 2-1 -0.07541248 -0.93627828 0.7854533 0.9719148 3-1 1.11885667 -0.02896441 2.2666777 0.0565628 3-2 1.19426915 0.06817536 2.3203629 0.0370434 > library(lsmeans) > lsmeans(fit3, pairwise~Group) $`Group pairwise differences` estimate SE df t.ratio p.value 1 - 2 0.07541248 0.3314247 15 0.22754 0.97191 1 - 3 -1.11885667 0.4418996 15 -2.53193 0.05656 2 - 3 -1.19426915 0.4335348 15 -2.75472 0.03704 p values are adjusted using the tukey method for 3 means
How to compare two groups with multiple measurements for each individual with R? Now, try to you write down the model: $y_{ijk} = ...$ where $y_{ijk}$ is the $k$-th value for individual $j$ of group $i$. Then look at what happens for the means $\bar y_{ij\bullet}$: you get a class
31,332
Partial Dependency plots and Gradient boosting (GBM package)
Yes, it's really easy. Check out ?plot.gbm. The usage goes like this: plot(gbm.model, i.var = 1, lwd = 2, col = "blue", main = "") and looks like i.var controls the index of the variable to plot. You can also do two (or more) way plots using plot(gbm.model, i.var = c(1,2), lwd = 2, col = "blue", main = "")
Partial Dependency plots and Gradient boosting (GBM package)
Yes, it's really easy. Check out ?plot.gbm. The usage goes like this: plot(gbm.model, i.var = 1, lwd = 2, col = "blue", main = "") and looks like i.var controls the index of the variable to plot. Y
Partial Dependency plots and Gradient boosting (GBM package) Yes, it's really easy. Check out ?plot.gbm. The usage goes like this: plot(gbm.model, i.var = 1, lwd = 2, col = "blue", main = "") and looks like i.var controls the index of the variable to plot. You can also do two (or more) way plots using plot(gbm.model, i.var = c(1,2), lwd = 2, col = "blue", main = "")
Partial Dependency plots and Gradient boosting (GBM package) Yes, it's really easy. Check out ?plot.gbm. The usage goes like this: plot(gbm.model, i.var = 1, lwd = 2, col = "blue", main = "") and looks like i.var controls the index of the variable to plot. Y
31,333
Weights argument in lm and lme very different in R- am I using them correctly?
Q1 In lme the notation weights = ~ b would result in the varFixed variance function being used with sole argument b. This function would add to the model a variance function $s^2(v)$ that has the form $s^2(v) = |v|$, where $v$ takes the values of the vector argument b. Hence, you should use weights = ~ I(1/b) in lme() to have the variance of $\varepsilon_i = 1/b_i$. In lm what you pass weights seems is the exact opposite; weights is inversely proportional to the variance. I'm not 100% sure what you mean by weight my data, but if you mean provide the heterogeneous variance of the observations, then I think you want weights = ~ I(1/b). Q2 My gut feeling (you'd have to ask the respective authors of the two functions) is that this is beacuse lm() and lme() were written by very different people to do very different things. lm() needed (was desired to be) to be compatible with S and various books, nlme didn't, and it aimed to be more flexible, allowing the heterogeneity to be modelled more flexibly than lm allows through the use of variance functions via the varFunc infrastructure.
Weights argument in lm and lme very different in R- am I using them correctly?
Q1 In lme the notation weights = ~ b would result in the varFixed variance function being used with sole argument b. This function would add to the model a variance function $s^2(v)$ that has the form
Weights argument in lm and lme very different in R- am I using them correctly? Q1 In lme the notation weights = ~ b would result in the varFixed variance function being used with sole argument b. This function would add to the model a variance function $s^2(v)$ that has the form $s^2(v) = |v|$, where $v$ takes the values of the vector argument b. Hence, you should use weights = ~ I(1/b) in lme() to have the variance of $\varepsilon_i = 1/b_i$. In lm what you pass weights seems is the exact opposite; weights is inversely proportional to the variance. I'm not 100% sure what you mean by weight my data, but if you mean provide the heterogeneous variance of the observations, then I think you want weights = ~ I(1/b). Q2 My gut feeling (you'd have to ask the respective authors of the two functions) is that this is beacuse lm() and lme() were written by very different people to do very different things. lm() needed (was desired to be) to be compatible with S and various books, nlme didn't, and it aimed to be more flexible, allowing the heterogeneity to be modelled more flexibly than lm allows through the use of variance functions via the varFunc infrastructure.
Weights argument in lm and lme very different in R- am I using them correctly? Q1 In lme the notation weights = ~ b would result in the varFixed variance function being used with sole argument b. This function would add to the model a variance function $s^2(v)$ that has the form
31,334
Measuring correlation of point processes
A series of event times is a type of point process. A good introduction to measuring correlations between point processes, as applied to neuronal spike trains, is given by Brillinger [1976]. One of the early, seminal works on point processes is that of Cox [1955]. The simplest measure of association between two temporal point processes (let's call them $A$ and $B$) is probably the association number, $n$. To calculate $n$ a window of half-width $h$ is defined around each time in series $A$. The individual association number, $c$, is then the number of events in series $B$ that fall within a given window, and $n$ is then defined as $$ n(h) = \Sigma_{i=1}^{N} c_i $$ This is generally calculated for a range of time lags, $u$, such that we get $n(u,h=const)$ [see, e.g., equations 9 and 10, and figure 3, of Brillinger [1976]]. If series $A$ and $B$ are uncorrelated then the association number will fluctuate, as a function of lag, due to sampling variations, but will have a stable mean. If we normalize by $2hT$, where $T$ is the length of the interval from which our samples were drawn, then we get an estimate of the cross-product density. Correlations at different time lags can then be seen by inspecting the cross-product density for departures from 1 (if the processes are independent the cross-product density should be 1, which is expected at large lags for most physical processes). Assessing the significance of these departures can be addressed in a number of different ways, but many assume that at least one of the processes is Poisson [Brillinger, 1976; Mulargia, 1992]. If those assumptions are met then 95% confidence intervals on the cross-product density can be estimated by [Brillinger, 1976] $$ 1 \pm \frac{1.96}{2\sqrt{}2hTp_Ap_B} $$ where $p_A$ and $p_B$ are the mean intensities of series $A$ and $B$, given by $p_A = N/T$, where $N$ is the number of events in $A$ (similar for $B$). Excursions outside the C.I. are therefore indicative of a significant association between the event sequences at certain lags. If neither series is Poisson then a bootstrapping approach can be used to estimate confidence intervals [Morley and Freeman, 2007]. When taking this approach it's important to understand the system as resampling the series $A$ and $B$ may not work without applying, say, a moving block bootstrap to preserve correlations in the spike trains. The approach taken by Morley and Freeman was to instead resample from the individual association numbers. ... we see that n(u, h) is a summation of the N individual associations c$_i$ for given u, h. Using this set of individual associations, we can construct a new series, c*$_i$, by drawing with replacement a random selection of N individual associations. Summing these N randomly-sampled associations gives a bootstrap estimate of the association number for given u, h. Repeating this for every lag u, we construct a bootstrap estimate of the association number with lag n*(u, h). Performing this bootstrapping procedure K times allows us to model the sampling variation in n(u, h). A further treatment of assessing confidence intervals using bootstrapping techniques is given by Niehof and Morley [2012], but the above should work for two series of neuronal spike trains (or similar simple system). References: Brillinger, D. R. (1976), Measuring the association of point processes: A case history, Am. Math. Mon., 83(1), 16–22. Cox, D. R. (1955), Some statistical methods connected with series of events, J. R. Stat. Soc., Ser. B, 17(2), 129–164. Mulargia, F. (1992), Time association between series of geophysical events, Phys. Earth Planet. Inter., 72, 147–153. Morley, S. K., and M. P. Freeman (2007), On the association between northward turnings of the interplanetary magnetic field and substorm onsets, Geophys. Res. Lett., 34, L08104, doi:10.1029/2006GL028891. Niehof, J.T., and S.K. Morley (2012). “Determining the Significance of Associations between Two Series of Discrete Events : Bootstrap Methods”. United States. doi:10.2172/1035497
Measuring correlation of point processes
A series of event times is a type of point process. A good introduction to measuring correlations between point processes, as applied to neuronal spike trains, is given by Brillinger [1976]. One of th
Measuring correlation of point processes A series of event times is a type of point process. A good introduction to measuring correlations between point processes, as applied to neuronal spike trains, is given by Brillinger [1976]. One of the early, seminal works on point processes is that of Cox [1955]. The simplest measure of association between two temporal point processes (let's call them $A$ and $B$) is probably the association number, $n$. To calculate $n$ a window of half-width $h$ is defined around each time in series $A$. The individual association number, $c$, is then the number of events in series $B$ that fall within a given window, and $n$ is then defined as $$ n(h) = \Sigma_{i=1}^{N} c_i $$ This is generally calculated for a range of time lags, $u$, such that we get $n(u,h=const)$ [see, e.g., equations 9 and 10, and figure 3, of Brillinger [1976]]. If series $A$ and $B$ are uncorrelated then the association number will fluctuate, as a function of lag, due to sampling variations, but will have a stable mean. If we normalize by $2hT$, where $T$ is the length of the interval from which our samples were drawn, then we get an estimate of the cross-product density. Correlations at different time lags can then be seen by inspecting the cross-product density for departures from 1 (if the processes are independent the cross-product density should be 1, which is expected at large lags for most physical processes). Assessing the significance of these departures can be addressed in a number of different ways, but many assume that at least one of the processes is Poisson [Brillinger, 1976; Mulargia, 1992]. If those assumptions are met then 95% confidence intervals on the cross-product density can be estimated by [Brillinger, 1976] $$ 1 \pm \frac{1.96}{2\sqrt{}2hTp_Ap_B} $$ where $p_A$ and $p_B$ are the mean intensities of series $A$ and $B$, given by $p_A = N/T$, where $N$ is the number of events in $A$ (similar for $B$). Excursions outside the C.I. are therefore indicative of a significant association between the event sequences at certain lags. If neither series is Poisson then a bootstrapping approach can be used to estimate confidence intervals [Morley and Freeman, 2007]. When taking this approach it's important to understand the system as resampling the series $A$ and $B$ may not work without applying, say, a moving block bootstrap to preserve correlations in the spike trains. The approach taken by Morley and Freeman was to instead resample from the individual association numbers. ... we see that n(u, h) is a summation of the N individual associations c$_i$ for given u, h. Using this set of individual associations, we can construct a new series, c*$_i$, by drawing with replacement a random selection of N individual associations. Summing these N randomly-sampled associations gives a bootstrap estimate of the association number for given u, h. Repeating this for every lag u, we construct a bootstrap estimate of the association number with lag n*(u, h). Performing this bootstrapping procedure K times allows us to model the sampling variation in n(u, h). A further treatment of assessing confidence intervals using bootstrapping techniques is given by Niehof and Morley [2012], but the above should work for two series of neuronal spike trains (or similar simple system). References: Brillinger, D. R. (1976), Measuring the association of point processes: A case history, Am. Math. Mon., 83(1), 16–22. Cox, D. R. (1955), Some statistical methods connected with series of events, J. R. Stat. Soc., Ser. B, 17(2), 129–164. Mulargia, F. (1992), Time association between series of geophysical events, Phys. Earth Planet. Inter., 72, 147–153. Morley, S. K., and M. P. Freeman (2007), On the association between northward turnings of the interplanetary magnetic field and substorm onsets, Geophys. Res. Lett., 34, L08104, doi:10.1029/2006GL028891. Niehof, J.T., and S.K. Morley (2012). “Determining the Significance of Associations between Two Series of Discrete Events : Bootstrap Methods”. United States. doi:10.2172/1035497
Measuring correlation of point processes A series of event times is a type of point process. A good introduction to measuring correlations between point processes, as applied to neuronal spike trains, is given by Brillinger [1976]. One of th
31,335
Measuring correlation of point processes
Some people use serial correlation of the intervals to quantify it. Basically you take the correlation coefficient of two inter-spike intervals that are $m$ intervals apart. See: Maurice J. Chacron, Benjamin Lindner, André Longtin. Noise Shaping by Interval Correlations Increases Information Transfer. Physical Review Letters, Vol. 92, No. 8. (25 Feb 2004), 080601, doi:10.1103/physrevlett.92.080601
Measuring correlation of point processes
Some people use serial correlation of the intervals to quantify it. Basically you take the correlation coefficient of two inter-spike intervals that are $m$ intervals apart. See: Maurice J. Chacron,
Measuring correlation of point processes Some people use serial correlation of the intervals to quantify it. Basically you take the correlation coefficient of two inter-spike intervals that are $m$ intervals apart. See: Maurice J. Chacron, Benjamin Lindner, André Longtin. Noise Shaping by Interval Correlations Increases Information Transfer. Physical Review Letters, Vol. 92, No. 8. (25 Feb 2004), 080601, doi:10.1103/physrevlett.92.080601
Measuring correlation of point processes Some people use serial correlation of the intervals to quantify it. Basically you take the correlation coefficient of two inter-spike intervals that are $m$ intervals apart. See: Maurice J. Chacron,
31,336
Measuring correlation of point processes
There are algorithms to compute cross-correlation of two point process (times of events) directly without any binning of the input. A classical one is the multi-tau algorithm that is used in fluorescence correlation spectroscopy (FCS) to correlated the photon arrival times of an experiments over time-lags that are approximately log-spaced. Another algorithm, also used for FCS, allows computing the cross-correlation at arbitrary time-lags. There is a python package called pycorrelate that implements this latter algorithm (the specific function to look for is pcorrelate). This type of cross-correlation is totally general and can be applied for auto- or cross-correlation of any point-processes.
Measuring correlation of point processes
There are algorithms to compute cross-correlation of two point process (times of events) directly without any binning of the input. A classical one is the multi-tau algorithm that is used in fluoresce
Measuring correlation of point processes There are algorithms to compute cross-correlation of two point process (times of events) directly without any binning of the input. A classical one is the multi-tau algorithm that is used in fluorescence correlation spectroscopy (FCS) to correlated the photon arrival times of an experiments over time-lags that are approximately log-spaced. Another algorithm, also used for FCS, allows computing the cross-correlation at arbitrary time-lags. There is a python package called pycorrelate that implements this latter algorithm (the specific function to look for is pcorrelate). This type of cross-correlation is totally general and can be applied for auto- or cross-correlation of any point-processes.
Measuring correlation of point processes There are algorithms to compute cross-correlation of two point process (times of events) directly without any binning of the input. A classical one is the multi-tau algorithm that is used in fluoresce
31,337
Measuring correlation of point processes
If you have measured both neurons continuously using some form of EEG then you would want to estimate an ARIMA model for membrane potential in the controlled neuron (as a regressor) against the neuron which it is hypothesized to innervate (as an outcome). If their membrane potentials are independently influenced by other stimuli in the brain, they will show on average no association. You might want to consider adjusting for the lagged effects of the independent neuron's membrane potential as well.
Measuring correlation of point processes
If you have measured both neurons continuously using some form of EEG then you would want to estimate an ARIMA model for membrane potential in the controlled neuron (as a regressor) against the neuron
Measuring correlation of point processes If you have measured both neurons continuously using some form of EEG then you would want to estimate an ARIMA model for membrane potential in the controlled neuron (as a regressor) against the neuron which it is hypothesized to innervate (as an outcome). If their membrane potentials are independently influenced by other stimuli in the brain, they will show on average no association. You might want to consider adjusting for the lagged effects of the independent neuron's membrane potential as well.
Measuring correlation of point processes If you have measured both neurons continuously using some form of EEG then you would want to estimate an ARIMA model for membrane potential in the controlled neuron (as a regressor) against the neuron
31,338
Comparing nested GLMs via chi-squared and loglikelihood
The "chi-square value" you're looking for is the deviance (-2*(log likelihood), at least up to an additive constant that doesn't matter for the purposes of inference. R gives you the log-likelihood above (logLik) and the likelihood ratio statistic (LR.stat): the LR stat is twice the difference in the log-likelihoods (2*(2236.0-2084.7)). I'm a little puzzled by your anova results, since they don't seem to match the format that I get when I run anova() on two glm() fits: in particular, stats:::anova.glm (the anova method for glm objects) doesn't print the AIC ... are m1 and m2 really glm objects? (e.g. try class("m1")) Can you give us a reproducible example? Here's what I get for a simple example, modified from ?glm: ## Dobson (1990) Page 93: Randomized Controlled Trial : d.AD <- data.frame(counts=c(18,17,15,20,10,20,25,13,12), outcome=gl(3,1,9), treatment=gl(3,3)) glm1 <- glm(counts ~ outcome + treatment, family = poisson, data=d.AD) glm0 <- update(glm1, . ~ 1) Model comparison gives the residual deviances (your "chi-squared value") and the differences between them ... anova(glm0,glm1,test="Chisq") ## Analysis of Deviance Table ## ## Model 1: counts ~ 1 ## Model 2: counts ~ outcome + treatment ## Resid. Df Resid. Dev Df Deviance Pr(>Chi) ## 1 8 10.5814 ## 2 4 5.1291 4 5.4523 0.244 (if I left out the test="Chisq", I would get all of the above but without the p-value) I see from your cross-posting at http://article.gmane.org/gmane.comp.lang.r.general/299377 that you're actually using ordinal::clm, in which case we do get output that looks like what you have above (it's important to be precise) ... the results are not identical because the model is slightly different, and you are given the log-likelihoods (=-deviance/2) rather than the deviances, but the difference between the deviances ("LR.stat") is similar. library(ordinal) clm1 <- clm(ordered(counts) ~ outcome + treatment, family = poisson, data=d.AD) clm0 <- update(clm1, . ~ 1) anova(clm0,clm1) ## no.par AIC logLik LR.stat df Pr(>Chisq) ## clm0 7 50.777 -18.389 ## clm1 11 52.839 -15.419 5.9389 4 0.2038
Comparing nested GLMs via chi-squared and loglikelihood
The "chi-square value" you're looking for is the deviance (-2*(log likelihood), at least up to an additive constant that doesn't matter for the purposes of inference. R gives you the log-likelihood ab
Comparing nested GLMs via chi-squared and loglikelihood The "chi-square value" you're looking for is the deviance (-2*(log likelihood), at least up to an additive constant that doesn't matter for the purposes of inference. R gives you the log-likelihood above (logLik) and the likelihood ratio statistic (LR.stat): the LR stat is twice the difference in the log-likelihoods (2*(2236.0-2084.7)). I'm a little puzzled by your anova results, since they don't seem to match the format that I get when I run anova() on two glm() fits: in particular, stats:::anova.glm (the anova method for glm objects) doesn't print the AIC ... are m1 and m2 really glm objects? (e.g. try class("m1")) Can you give us a reproducible example? Here's what I get for a simple example, modified from ?glm: ## Dobson (1990) Page 93: Randomized Controlled Trial : d.AD <- data.frame(counts=c(18,17,15,20,10,20,25,13,12), outcome=gl(3,1,9), treatment=gl(3,3)) glm1 <- glm(counts ~ outcome + treatment, family = poisson, data=d.AD) glm0 <- update(glm1, . ~ 1) Model comparison gives the residual deviances (your "chi-squared value") and the differences between them ... anova(glm0,glm1,test="Chisq") ## Analysis of Deviance Table ## ## Model 1: counts ~ 1 ## Model 2: counts ~ outcome + treatment ## Resid. Df Resid. Dev Df Deviance Pr(>Chi) ## 1 8 10.5814 ## 2 4 5.1291 4 5.4523 0.244 (if I left out the test="Chisq", I would get all of the above but without the p-value) I see from your cross-posting at http://article.gmane.org/gmane.comp.lang.r.general/299377 that you're actually using ordinal::clm, in which case we do get output that looks like what you have above (it's important to be precise) ... the results are not identical because the model is slightly different, and you are given the log-likelihoods (=-deviance/2) rather than the deviances, but the difference between the deviances ("LR.stat") is similar. library(ordinal) clm1 <- clm(ordered(counts) ~ outcome + treatment, family = poisson, data=d.AD) clm0 <- update(clm1, . ~ 1) anova(clm0,clm1) ## no.par AIC logLik LR.stat df Pr(>Chisq) ## clm0 7 50.777 -18.389 ## clm1 11 52.839 -15.419 5.9389 4 0.2038
Comparing nested GLMs via chi-squared and loglikelihood The "chi-square value" you're looking for is the deviance (-2*(log likelihood), at least up to an additive constant that doesn't matter for the purposes of inference. R gives you the log-likelihood ab
31,339
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"?
You should perform all 100 analyses as a single mixed effects model, with your coefficients of interest random variables themselves. That way you can estimate a distribution for those coefficients including their overall mean, which will give you the sort of interpretation I think you are looking for. Noting that, if as I suspect is the case, you have a time series for each individual, you will also need to correct for autocorrelation of the residuals.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi
You should perform all 100 analyses as a single mixed effects model, with your coefficients of interest random variables themselves. That way you can estimate a distribution for those coefficients in
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"? You should perform all 100 analyses as a single mixed effects model, with your coefficients of interest random variables themselves. That way you can estimate a distribution for those coefficients including their overall mean, which will give you the sort of interpretation I think you are looking for. Noting that, if as I suspect is the case, you have a time series for each individual, you will also need to correct for autocorrelation of the residuals.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi You should perform all 100 analyses as a single mixed effects model, with your coefficients of interest random variables themselves. That way you can estimate a distribution for those coefficients in
31,340
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"?
The simplest thing to do would probably be a sign test. The null hypothesis is that each result has equal probability of being positive or negative (like flipping a fair coin). Your goal is to determine whether the observed results would be unlikely enough under this null hypothesis that you can reject it. What's the probability of getting 80 or more heads out of 100 flips of a fair coin? You can calculate this using the binomial distribution. In R, the relevant function is called pbinom, and you could get a (one-sided) p-value using the following line of code: pbinom(80, size = 100, prob = 0.5, lower.tail = FALSE) According to this test, your intuition is correct, you'd be exceedingly unlikely to get 80 positive results by chance if the treatment had no effect. A closely related option would be to use something like the Wilcoxon signed rank test. A better approach, if you actually want to estimate the size of the effect (rather than just determine whether it tends to be greater than zero or not), would probably be a hierarchical ("mixed") model. Here, the model says that your 100 individuals' results come from a distribution, and your goal is to see where the mean of that distribution is (along with confidence intervals). Mixed models let you say quite a bit more about your effect sizes: after fitting the model, you could say something like "we estimate that our treatment tends to improve outcomes by an average of three units, although the data is consistent with the true average effect size being anywhere from 1.5 to 4.5 units. Also, there's some variation among individuals, so a given person might see an effect anywhere from -0.5 to +6.5 units". That's a very precise and useful set of statements--much better than just "the effect is probably positive, on average", which is why this approach tends to be favored by statisticians. But if you don't need all that detail, the first approach I mentioned could be fine too.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi
The simplest thing to do would probably be a sign test. The null hypothesis is that each result has equal probability of being positive or negative (like flipping a fair coin). Your goal is to deter
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"? The simplest thing to do would probably be a sign test. The null hypothesis is that each result has equal probability of being positive or negative (like flipping a fair coin). Your goal is to determine whether the observed results would be unlikely enough under this null hypothesis that you can reject it. What's the probability of getting 80 or more heads out of 100 flips of a fair coin? You can calculate this using the binomial distribution. In R, the relevant function is called pbinom, and you could get a (one-sided) p-value using the following line of code: pbinom(80, size = 100, prob = 0.5, lower.tail = FALSE) According to this test, your intuition is correct, you'd be exceedingly unlikely to get 80 positive results by chance if the treatment had no effect. A closely related option would be to use something like the Wilcoxon signed rank test. A better approach, if you actually want to estimate the size of the effect (rather than just determine whether it tends to be greater than zero or not), would probably be a hierarchical ("mixed") model. Here, the model says that your 100 individuals' results come from a distribution, and your goal is to see where the mean of that distribution is (along with confidence intervals). Mixed models let you say quite a bit more about your effect sizes: after fitting the model, you could say something like "we estimate that our treatment tends to improve outcomes by an average of three units, although the data is consistent with the true average effect size being anywhere from 1.5 to 4.5 units. Also, there's some variation among individuals, so a given person might see an effect anywhere from -0.5 to +6.5 units". That's a very precise and useful set of statements--much better than just "the effect is probably positive, on average", which is why this approach tends to be favored by statisticians. But if you don't need all that detail, the first approach I mentioned could be fine too.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi The simplest thing to do would probably be a sign test. The null hypothesis is that each result has equal probability of being positive or negative (like flipping a fair coin). Your goal is to deter
31,341
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"?
Maybe I get that completely wrong, but what it seems to me is that you are trying to do repeated-measures ANOVA. Just define this "dummy" as a within-subject factor, and the model would do the rest. Significance itself is not very informative; it is required but not sufficient; any model would get significant with a sufficiently large number of observations. you may want to get effects size, like (partial) Eta-Squared, to get an idea of how "big" your effect is. My 2 cents.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi
Maybe I get that completely wrong, but what it seems to me is that you are trying to do repeated-measures ANOVA. Just define this "dummy" as a within-subject factor, and the model would do the rest. S
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"? Maybe I get that completely wrong, but what it seems to me is that you are trying to do repeated-measures ANOVA. Just define this "dummy" as a within-subject factor, and the model would do the rest. Significance itself is not very informative; it is required but not sufficient; any model would get significant with a sufficiently large number of observations. you may want to get effects size, like (partial) Eta-Squared, to get an idea of how "big" your effect is. My 2 cents.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi Maybe I get that completely wrong, but what it seems to me is that you are trying to do repeated-measures ANOVA. Just define this "dummy" as a within-subject factor, and the model would do the rest. S
31,342
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"?
It might be as simple as an ordinary ANCOVA calculation, but the appropriate way to analyze your data would depend on the physical situation and you haven't supplied those details.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi
It might be as simple as an ordinary ANCOVA calculation, but the appropriate way to analyze your data would depend on the physical situation and you haven't supplied those details.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positive"? It might be as simple as an ordinary ANCOVA calculation, but the appropriate way to analyze your data would depend on the physical situation and you haven't supplied those details.
If I have many positive, insignificant results, can I test "at least $n$ of these results are positi It might be as simple as an ordinary ANCOVA calculation, but the appropriate way to analyze your data would depend on the physical situation and you haven't supplied those details.
31,343
Linear model: comparing predictive power of two different measurement methods
Later One thing I want to add after hearing that you have linear mixed effect models: The $AIC, AIC_{c}$ and $BIC$ can still be used to compare the models. See this paper, for example. From other similar questions on the site, it seems that this paper is crucial. Original answer What you basically want is to compare two non-nested models. Burnham and Anderson Model selection and multimodel inference discuss this and recommend using the $AIC$, $AIC_{c}$ or $BIC$ etc. as the traditional likelihood ratio test is only applicable in nested models. They explicitly state that the information-theoretic criteria such as the $AIC, AIC_{c}, BIC$ etc. are not tests and that the word "significant" should be avoided when reporting the results. Based on this and this answers, I recommend these approaches: Make a scatterplot matrix (SPLOM) of your dataset including smoothers: pairs(Y~X1+X2, panel = panel.smooth, lwd = 2, cex = 1.5, col = "steelblue", pch=16). Check if the lines (the smoothers) are compatible with a linear relationship. Refine the model if necessary. Compute the models m1 and m2. Do some model checks (residuals etc.): plot(m1) and plot(m2). Compute the $AIC_{c}$ ($AIC$ corrected for small sample sizes) for both models and calculate the absolute difference between the two $AIC_{c}$s. The R package pscl provides the function AICc for this: abs(AICc(m1)-AICc(m2)). If this absolute difference is smaller than 2, the two models are basically indistinguishable. Otherwise prefer the model with the lower $AIC_{c}$. Compute likelihood ratio tests for non-nested models. The R package lmtest has the functions coxtest (Cox test), jtest (Davidson-MacKinnon J test) and encomptest (encompassing test of Davidson & MacKinnon). Some thoughts: If the two banana-measures are really measure the same thing, they both may be equally suited for prediction and there might not be a "best" model. This paper might also be helpful. Here is an exmple in R: #============================================================================== # Generate correlated variables #============================================================================== set.seed(123) R <- matrix(cbind( 1 , 0.8 , 0.2, 0.8 , 1 , 0.4, 0.2 , 0.4 , 1),nrow=3) # correlation matrix U <- t(chol(R)) nvars <- dim(U)[1] numobs <- 500 set.seed(1) random.normal <- matrix(rnorm(nvars*numobs,0,1), nrow=nvars, ncol=numobs); X <- U %*% random.normal newX <- t(X) raw <- as.data.frame(newX) names(raw) <- c("response","predictor1","predictor2") #============================================================================== # Check the graphic #============================================================================== par(bg="white", cex=1.2) pairs(response~predictor1+predictor2, data=raw, panel = panel.smooth, lwd = 2, cex = 1.5, col = "steelblue", pch=16, las=1) The smoothers confirm the linear relationships. This was intended, of course. #============================================================================== # Calculate the regression models and AICcs #============================================================================== library(pscl) m1 <- lm(response~predictor1, data=raw) m2 <- lm(response~predictor2, data=raw) summary(m1) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.004332 0.027292 -0.159 0.874 predictor1 0.820150 0.026677 30.743 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.6102 on 498 degrees of freedom Multiple R-squared: 0.6549, Adjusted R-squared: 0.6542 F-statistic: 945.2 on 1 and 498 DF, p-value: < 2.2e-16 summary(m2) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.01650 0.04567 -0.361 0.718 predictor2 0.18282 0.04406 4.150 3.91e-05 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 1.021 on 498 degrees of freedom Multiple R-squared: 0.03342, Adjusted R-squared: 0.03148 F-statistic: 17.22 on 1 and 498 DF, p-value: 3.913e-05 AICc(m1) [1] 928.9961 AICc(m2) [1] 1443.994 abs(AICc(m1)-AICc(m2)) [1] 514.9977 #============================================================================== # Calculate the Cox test and Davidson-MacKinnon J test #============================================================================== library(lmtest) coxtest(m1, m2) Cox test Model 1: response ~ predictor1 Model 2: response ~ predictor2 Estimate Std. Error z value Pr(>|z|) fitted(M1) ~ M2 17.102 4.1890 4.0826 4.454e-05 *** fitted(M2) ~ M1 -264.753 1.4368 -184.2652 < 2.2e-16 *** jtest(m1, m2) J test Model 1: response ~ predictor1 Model 2: response ~ predictor2 Estimate Std. Error t value Pr(>|t|) M1 + fitted(M2) -0.8298 0.151702 -5.470 7.143e-08 *** M2 + fitted(M1) 1.0723 0.034271 31.288 < 2.2e-16 *** The $AIC_{c}$ of the first model m1 is clearly lower and the $R^{2}$ is much higher. Important: In linear models of equal complexity and Gaussian error distribution, $R^2, AIC$ and $BIC$ should give the same answers (see this post). In nonlinear models, the use of $R^2$ for model performance (goodness of fit) and model selection should be avoided: see this post and this paper, for example.
Linear model: comparing predictive power of two different measurement methods
Later One thing I want to add after hearing that you have linear mixed effect models: The $AIC, AIC_{c}$ and $BIC$ can still be used to compare the models. See this paper, for example. From other simi
Linear model: comparing predictive power of two different measurement methods Later One thing I want to add after hearing that you have linear mixed effect models: The $AIC, AIC_{c}$ and $BIC$ can still be used to compare the models. See this paper, for example. From other similar questions on the site, it seems that this paper is crucial. Original answer What you basically want is to compare two non-nested models. Burnham and Anderson Model selection and multimodel inference discuss this and recommend using the $AIC$, $AIC_{c}$ or $BIC$ etc. as the traditional likelihood ratio test is only applicable in nested models. They explicitly state that the information-theoretic criteria such as the $AIC, AIC_{c}, BIC$ etc. are not tests and that the word "significant" should be avoided when reporting the results. Based on this and this answers, I recommend these approaches: Make a scatterplot matrix (SPLOM) of your dataset including smoothers: pairs(Y~X1+X2, panel = panel.smooth, lwd = 2, cex = 1.5, col = "steelblue", pch=16). Check if the lines (the smoothers) are compatible with a linear relationship. Refine the model if necessary. Compute the models m1 and m2. Do some model checks (residuals etc.): plot(m1) and plot(m2). Compute the $AIC_{c}$ ($AIC$ corrected for small sample sizes) for both models and calculate the absolute difference between the two $AIC_{c}$s. The R package pscl provides the function AICc for this: abs(AICc(m1)-AICc(m2)). If this absolute difference is smaller than 2, the two models are basically indistinguishable. Otherwise prefer the model with the lower $AIC_{c}$. Compute likelihood ratio tests for non-nested models. The R package lmtest has the functions coxtest (Cox test), jtest (Davidson-MacKinnon J test) and encomptest (encompassing test of Davidson & MacKinnon). Some thoughts: If the two banana-measures are really measure the same thing, they both may be equally suited for prediction and there might not be a "best" model. This paper might also be helpful. Here is an exmple in R: #============================================================================== # Generate correlated variables #============================================================================== set.seed(123) R <- matrix(cbind( 1 , 0.8 , 0.2, 0.8 , 1 , 0.4, 0.2 , 0.4 , 1),nrow=3) # correlation matrix U <- t(chol(R)) nvars <- dim(U)[1] numobs <- 500 set.seed(1) random.normal <- matrix(rnorm(nvars*numobs,0,1), nrow=nvars, ncol=numobs); X <- U %*% random.normal newX <- t(X) raw <- as.data.frame(newX) names(raw) <- c("response","predictor1","predictor2") #============================================================================== # Check the graphic #============================================================================== par(bg="white", cex=1.2) pairs(response~predictor1+predictor2, data=raw, panel = panel.smooth, lwd = 2, cex = 1.5, col = "steelblue", pch=16, las=1) The smoothers confirm the linear relationships. This was intended, of course. #============================================================================== # Calculate the regression models and AICcs #============================================================================== library(pscl) m1 <- lm(response~predictor1, data=raw) m2 <- lm(response~predictor2, data=raw) summary(m1) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.004332 0.027292 -0.159 0.874 predictor1 0.820150 0.026677 30.743 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.6102 on 498 degrees of freedom Multiple R-squared: 0.6549, Adjusted R-squared: 0.6542 F-statistic: 945.2 on 1 and 498 DF, p-value: < 2.2e-16 summary(m2) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.01650 0.04567 -0.361 0.718 predictor2 0.18282 0.04406 4.150 3.91e-05 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 1.021 on 498 degrees of freedom Multiple R-squared: 0.03342, Adjusted R-squared: 0.03148 F-statistic: 17.22 on 1 and 498 DF, p-value: 3.913e-05 AICc(m1) [1] 928.9961 AICc(m2) [1] 1443.994 abs(AICc(m1)-AICc(m2)) [1] 514.9977 #============================================================================== # Calculate the Cox test and Davidson-MacKinnon J test #============================================================================== library(lmtest) coxtest(m1, m2) Cox test Model 1: response ~ predictor1 Model 2: response ~ predictor2 Estimate Std. Error z value Pr(>|z|) fitted(M1) ~ M2 17.102 4.1890 4.0826 4.454e-05 *** fitted(M2) ~ M1 -264.753 1.4368 -184.2652 < 2.2e-16 *** jtest(m1, m2) J test Model 1: response ~ predictor1 Model 2: response ~ predictor2 Estimate Std. Error t value Pr(>|t|) M1 + fitted(M2) -0.8298 0.151702 -5.470 7.143e-08 *** M2 + fitted(M1) 1.0723 0.034271 31.288 < 2.2e-16 *** The $AIC_{c}$ of the first model m1 is clearly lower and the $R^{2}$ is much higher. Important: In linear models of equal complexity and Gaussian error distribution, $R^2, AIC$ and $BIC$ should give the same answers (see this post). In nonlinear models, the use of $R^2$ for model performance (goodness of fit) and model selection should be avoided: see this post and this paper, for example.
Linear model: comparing predictive power of two different measurement methods Later One thing I want to add after hearing that you have linear mixed effect models: The $AIC, AIC_{c}$ and $BIC$ can still be used to compare the models. See this paper, for example. From other simi
31,344
Linear model: comparing predictive power of two different measurement methods
There's a good 19th century answer in risk of neglect here. To compare two different straight-line fits, plot the data and the fitted lines and think about what you see. It's quite likely that one model will be clearly better, and that need not mean higher $R^2$. For example, it is possible that a straight-line model is qualitatively wrong in one or other case. Even better, the data and fit may suggest a better model. If the two models appear about equally good or poor, that's another answer. The banana example is presumably facetious here, but I would not expect straight-line fits to work well at all.... The inferential machinery wheeled out by others in answer is a thing of intellectual beauty, but sometimes you don't need a state-of-the-art sledgehammer to crack a nut. Sometimes it seems that anyone publishing that night is darker than day would always have some one asking "Have you tested that formally? What is your P-value?".
Linear model: comparing predictive power of two different measurement methods
There's a good 19th century answer in risk of neglect here. To compare two different straight-line fits, plot the data and the fitted lines and think about what you see. It's quite likely that one mod
Linear model: comparing predictive power of two different measurement methods There's a good 19th century answer in risk of neglect here. To compare two different straight-line fits, plot the data and the fitted lines and think about what you see. It's quite likely that one model will be clearly better, and that need not mean higher $R^2$. For example, it is possible that a straight-line model is qualitatively wrong in one or other case. Even better, the data and fit may suggest a better model. If the two models appear about equally good or poor, that's another answer. The banana example is presumably facetious here, but I would not expect straight-line fits to work well at all.... The inferential machinery wheeled out by others in answer is a thing of intellectual beauty, but sometimes you don't need a state-of-the-art sledgehammer to crack a nut. Sometimes it seems that anyone publishing that night is darker than day would always have some one asking "Have you tested that formally? What is your P-value?".
Linear model: comparing predictive power of two different measurement methods There's a good 19th century answer in risk of neglect here. To compare two different straight-line fits, plot the data and the fitted lines and think about what you see. It's quite likely that one mod
31,345
Linear model: comparing predictive power of two different measurement methods
Do a Cox test for non-nested models. y <- rnorm( 10 ) x1 <- y + rnorm( 10 ) / 2 x2 <- y + rnorm( 10 ) lm1 <- lm( y ~ x1 ) lm2 <- lm( y ~ x2 ) library( lmtest ) coxtest( lm1, lm2 ) ?coxtest (you will find references to other test). See also this comment and this question. In especially, consider using AIC/BIC.
Linear model: comparing predictive power of two different measurement methods
Do a Cox test for non-nested models. y <- rnorm( 10 ) x1 <- y + rnorm( 10 ) / 2 x2 <- y + rnorm( 10 ) lm1 <- lm( y ~ x1 ) lm2 <- lm( y ~ x2 ) library( lmtest ) coxtest( lm1, lm2 ) ?coxtest (you wi
Linear model: comparing predictive power of two different measurement methods Do a Cox test for non-nested models. y <- rnorm( 10 ) x1 <- y + rnorm( 10 ) / 2 x2 <- y + rnorm( 10 ) lm1 <- lm( y ~ x1 ) lm2 <- lm( y ~ x2 ) library( lmtest ) coxtest( lm1, lm2 ) ?coxtest (you will find references to other test). See also this comment and this question. In especially, consider using AIC/BIC.
Linear model: comparing predictive power of two different measurement methods Do a Cox test for non-nested models. y <- rnorm( 10 ) x1 <- y + rnorm( 10 ) / 2 x2 <- y + rnorm( 10 ) lm1 <- lm( y ~ x1 ) lm2 <- lm( y ~ x2 ) library( lmtest ) coxtest( lm1, lm2 ) ?coxtest (you wi
31,346
Cosine similarity on sparse matrix
R often does not scale well to large data. You may need to move on to more efficient implementations. There are plenty of choices around. But of course, there probably are also various R packages that could help you a bit further. Also, it pays off to stop thinking in matrixes. What you are working with is a graph. 1 is an edge, and 0 is not. An easy way to accelerate computing the similarities here is to cleverly exploit the similarity. This btw. is pretty much the benefits you get by processing the data in "column form" in Hadoop, for example. When you realize that cosine similarity consists of three components: product of A and B, length of A and length of B, you will notice that two parts are independent of the other vector, and the third part has the squared sparsity, this will drastically reduce the computations needed for a cosine similarity "matrix" (again, stop seeing it as a matrix) The streamlining then is: Compute the length of each single vector, for normalization (i.e. compute $|A|$) For each attribute (!) send a message to each pair of non-zero entries. If you have $0.01$ of non-zero values in each of $c$ columns, this will be just $O(0.0001 * c * n^2)$ messages. Count the number of messages received for each pair, this is $A\cdot B$, divide by $|A|$ and $|B|$. Alternatively: Standardize each vector to length $|A|=1$ (your matrix will no longer be binary!) For each attribute (!) send a message with the product of the two values to each pair of non-zero entries. If you have $0.01$ of non-zero values in each of $c$ columns, this will be just $O(0.0001 * c * n^2)$ messages. Sum the messages received for each pair, this is the cosine similarity. (No division necessary, as $|A|=|B|=1$) And definitely think about how to store and organize your data in memory. Here, fast data access and manipulation is 90% of the cost, the actual computations are trivial. Don't let R do it automatically, because that probably means it is doing it wrong...
Cosine similarity on sparse matrix
R often does not scale well to large data. You may need to move on to more efficient implementations. There are plenty of choices around. But of course, there probably are also various R packages that
Cosine similarity on sparse matrix R often does not scale well to large data. You may need to move on to more efficient implementations. There are plenty of choices around. But of course, there probably are also various R packages that could help you a bit further. Also, it pays off to stop thinking in matrixes. What you are working with is a graph. 1 is an edge, and 0 is not. An easy way to accelerate computing the similarities here is to cleverly exploit the similarity. This btw. is pretty much the benefits you get by processing the data in "column form" in Hadoop, for example. When you realize that cosine similarity consists of three components: product of A and B, length of A and length of B, you will notice that two parts are independent of the other vector, and the third part has the squared sparsity, this will drastically reduce the computations needed for a cosine similarity "matrix" (again, stop seeing it as a matrix) The streamlining then is: Compute the length of each single vector, for normalization (i.e. compute $|A|$) For each attribute (!) send a message to each pair of non-zero entries. If you have $0.01$ of non-zero values in each of $c$ columns, this will be just $O(0.0001 * c * n^2)$ messages. Count the number of messages received for each pair, this is $A\cdot B$, divide by $|A|$ and $|B|$. Alternatively: Standardize each vector to length $|A|=1$ (your matrix will no longer be binary!) For each attribute (!) send a message with the product of the two values to each pair of non-zero entries. If you have $0.01$ of non-zero values in each of $c$ columns, this will be just $O(0.0001 * c * n^2)$ messages. Sum the messages received for each pair, this is the cosine similarity. (No division necessary, as $|A|=|B|=1$) And definitely think about how to store and organize your data in memory. Here, fast data access and manipulation is 90% of the cost, the actual computations are trivial. Don't let R do it automatically, because that probably means it is doing it wrong...
Cosine similarity on sparse matrix R often does not scale well to large data. You may need to move on to more efficient implementations. There are plenty of choices around. But of course, there probably are also various R packages that
31,347
Cosine similarity on sparse matrix
Use the Matrix package to store the matrix, and the skmeans_xdist function to calculate cosine distances. /edit: It appears that the skmeans_xdist function is not very efficient. Here's a simple example of how you would calculate cosine similarity for a netflix-sized matrix in R. First, build the matrix: library(Matrix) set.seed(42) non_zero <- 99000000 i <- sample(1:17770, non_zero, replace=TRUE) j <- sample(1:480189, non_zero, replace=TRUE) x <- sample(1:5, non_zero, replace=TRUE) m <- sparseMatrix(i=i,j=j,x=x) #Rows are movies, columns are users m <- drop0(m) Next normalize each row so it's vector distance is 1. This takes 85 seconds on my machine. row_norms <- sqrt(rowSums(m^2)) row_norms <- t(crossprod(sign(m), Diagonal(x=row_norms))) row_norms@x <- 1/row_norms@x m_norm <- m * row_norms Finally, we can find cosine similarity, which takes me 155 seconds system.time(sim <- tcrossprod(m_norm)) Also, note that the cosine similarity matrix is pretty sparse, because many movies do not share any users in common. You can convert to cosine distance using 1-sim, but that might take a while (I haven't timed it). /edit a couple years later: Here's a faster row-normalization function: row_normalize <- function(m){ row_norms <- sqrt(rowSums(m^2)) row_norms <- t(crossprod(sign(m), Diagonal(x=row_norms))) row_norms@x <- 1/row_norms@x m_norm <- m * row_norms return(m_norm) } fast_row_normalize <- function(m){ d <- Diagonal(x=1/sqrt(rowSums(m^2))) return(t(crossprod(m, d))) } library(microbenchmark) microbenchmark( a = row_normalize(m), b = fast_row_normalize(m), times=1 ) The new function takes only 25 seconds (vs 89 seconds for the other one— I guess my computer got slower =/): Unit: seconds expr min lq mean median uq max neval a 89.68086 89.68086 89.68086 89.68086 89.68086 89.68086 1 b 24.09879 24.09879 24.09879 24.09879 24.09879 24.09879 1
Cosine similarity on sparse matrix
Use the Matrix package to store the matrix, and the skmeans_xdist function to calculate cosine distances. /edit: It appears that the skmeans_xdist function is not very efficient. Here's a simple exam
Cosine similarity on sparse matrix Use the Matrix package to store the matrix, and the skmeans_xdist function to calculate cosine distances. /edit: It appears that the skmeans_xdist function is not very efficient. Here's a simple example of how you would calculate cosine similarity for a netflix-sized matrix in R. First, build the matrix: library(Matrix) set.seed(42) non_zero <- 99000000 i <- sample(1:17770, non_zero, replace=TRUE) j <- sample(1:480189, non_zero, replace=TRUE) x <- sample(1:5, non_zero, replace=TRUE) m <- sparseMatrix(i=i,j=j,x=x) #Rows are movies, columns are users m <- drop0(m) Next normalize each row so it's vector distance is 1. This takes 85 seconds on my machine. row_norms <- sqrt(rowSums(m^2)) row_norms <- t(crossprod(sign(m), Diagonal(x=row_norms))) row_norms@x <- 1/row_norms@x m_norm <- m * row_norms Finally, we can find cosine similarity, which takes me 155 seconds system.time(sim <- tcrossprod(m_norm)) Also, note that the cosine similarity matrix is pretty sparse, because many movies do not share any users in common. You can convert to cosine distance using 1-sim, but that might take a while (I haven't timed it). /edit a couple years later: Here's a faster row-normalization function: row_normalize <- function(m){ row_norms <- sqrt(rowSums(m^2)) row_norms <- t(crossprod(sign(m), Diagonal(x=row_norms))) row_norms@x <- 1/row_norms@x m_norm <- m * row_norms return(m_norm) } fast_row_normalize <- function(m){ d <- Diagonal(x=1/sqrt(rowSums(m^2))) return(t(crossprod(m, d))) } library(microbenchmark) microbenchmark( a = row_normalize(m), b = fast_row_normalize(m), times=1 ) The new function takes only 25 seconds (vs 89 seconds for the other one— I guess my computer got slower =/): Unit: seconds expr min lq mean median uq max neval a 89.68086 89.68086 89.68086 89.68086 89.68086 89.68086 1 b 24.09879 24.09879 24.09879 24.09879 24.09879 24.09879 1
Cosine similarity on sparse matrix Use the Matrix package to store the matrix, and the skmeans_xdist function to calculate cosine distances. /edit: It appears that the skmeans_xdist function is not very efficient. Here's a simple exam
31,348
Cosine similarity on sparse matrix
Part of the mcl software (http://micans.org/mcl) is a program mcxarray created specifically to do fast all vs all comparisons, including cosine similarity. It utilises sparse representations, and it can be parallelised over different CPUs (with threads) and different machines (with jobs), with easy re-integration of the computed parts. Disclaimer - it was written by me.
Cosine similarity on sparse matrix
Part of the mcl software (http://micans.org/mcl) is a program mcxarray created specifically to do fast all vs all comparisons, including cosine similarity. It utilises sparse representations, and it c
Cosine similarity on sparse matrix Part of the mcl software (http://micans.org/mcl) is a program mcxarray created specifically to do fast all vs all comparisons, including cosine similarity. It utilises sparse representations, and it can be parallelised over different CPUs (with threads) and different machines (with jobs), with easy re-integration of the computed parts. Disclaimer - it was written by me.
Cosine similarity on sparse matrix Part of the mcl software (http://micans.org/mcl) is a program mcxarray created specifically to do fast all vs all comparisons, including cosine similarity. It utilises sparse representations, and it c
31,349
Cosine similarity on sparse matrix
I am using gensim, which works pretty well especially with text data which is usually high dimensional and sparse
Cosine similarity on sparse matrix
I am using gensim, which works pretty well especially with text data which is usually high dimensional and sparse
Cosine similarity on sparse matrix I am using gensim, which works pretty well especially with text data which is usually high dimensional and sparse
Cosine similarity on sparse matrix I am using gensim, which works pretty well especially with text data which is usually high dimensional and sparse
31,350
Cosine similarity on sparse matrix
You may consider using qlcMatrix::cosSparse. It is the fastest R package for computing cosine similarity on a matrix > 50% sparse: See my answer here for benchmarking results: https://stackoverflow.com/questions/29417754/is-there-any-sparse-support-for-dist-function-in-r/64944105#64944105
Cosine similarity on sparse matrix
You may consider using qlcMatrix::cosSparse. It is the fastest R package for computing cosine similarity on a matrix > 50% sparse: See my answer here for benchmarking results: https://stackoverflow.co
Cosine similarity on sparse matrix You may consider using qlcMatrix::cosSparse. It is the fastest R package for computing cosine similarity on a matrix > 50% sparse: See my answer here for benchmarking results: https://stackoverflow.com/questions/29417754/is-there-any-sparse-support-for-dist-function-in-r/64944105#64944105
Cosine similarity on sparse matrix You may consider using qlcMatrix::cosSparse. It is the fastest R package for computing cosine similarity on a matrix > 50% sparse: See my answer here for benchmarking results: https://stackoverflow.co
31,351
How to plot a 5D data set in "star coordinates"?
The "star coordinates" are intended to be modified interactively, beginning with a default. This answer shows how to create the default; the interactive modifications are a programming detail. The data are considered a collection of vectors $x_j = (x_{j1}, x_{j2}, \ldots, x_{jd})$ in $\mathbb{R}^d$. These are first normalized separately within each coordinate, linearly transforming the data $\{x_{ji}, j=1, 2, \ldots\}$ into the interval $[0,1]$. This is done, of course, by first subtracting their minimum from each element and dividing by the range. Call the normalized data $z_j$. The usual basis of $\mathbb{R}^d$ is the set of vectors $e_i = (0, 0, \ldots, 0, 1, 0, 0, \ldots, 0)$ having a single $1$ in the $i^\text{th}$ place. In terms of this basis, $z_j = z_{j1}e_1 + z_{j2}e_2 + \cdots + z_{jd}e_d$. A "star coordinates projection" chooses a set of distinct unit vectors $\{u_i, i=1, 2, \ldots, d\}$ in $\mathbb{R}^2$ and maps $e_i$ to $u_i$. This defines a linear transformation from $\mathbb{R}^d$ to $\mathbb{R}^2$. This map is applied to the $z_j$--it is just a matrix multiplication--to create a two-dimensional point cloud, depicted as a scatterplot. The unit vectors $u_i$ are drawn and labeled for reference. (An interactive version will allow the user to rotate each of the $u_i$ individually.) To illustrate this, here is an R implementation applied to a dataset of automobile performance characteristics. First let's obtain the data: library(MASS) x <- subset(Cars93, select=c(Price, MPG.city, Horsepower, Fuel.tank.capacity, Turn.circle)) The initial step is to normalize the data: x.range <- apply(x, 2, range) z <- t((t(x) - x.range[1,]) / (x.range[2,] - x.range[1,])) As a default, let's create $d$ equally spaced unit vectors for the $u_i$. These determine the projection prj which is applied to $z$: d <- dim(z)[2] # Dimensions prj <- t(sapply((1:d)/d, function(i) c(cos(2*pi*i), sin(2*pi*i)))) star <- z %*% prj That's it--we are all ready to plot. It is initialized to provide room for the data points, the coordinate axes, and their labels: plot(rbind(apply(star, 2, range), apply(prj*1.25, 2, range)), type="n", bty="n", xaxt="n", yaxt="n", main="Cars 93", xlab="", ylab="") Here is the plot itself, with one line for each element: axes, labels, and points: tmp <- apply(prj, 1, function(v) lines(rbind(c(0,0), v))) text(prj * 1.1, labels=colnames(z), cex=0.8, col="Gray") points(star, pch=19, col="Red"); points(star, col="0x200000") To understand this plot, it might help to compare it to a traditional method, the scatterplot matrix: pairs(x) A correlation-based principal components analysis (PCA) creates almost the same result. (pca <- princomp(x, cor=TRUE)) pca$loadings[,1] biplot(pca, choices=2:3) The output for the first command is Standard deviations: Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 1.8999932 0.8304711 0.5750447 0.4399687 0.4196363 Most of the variance is accounted for by the first component (1.9 versus 0.83 and less). The loadings onto this component are almost equal in size, as shown by the output to the second command: Price MPG.city Horsepower Fuel.tank.capacity Turn.circle 0.4202798 -0.4668682 0.4640081 0.4758205 0.4045867 This suggests--in this case--that the default star coordinates plot is projecting along the first principal component and therefore is showing, essentially, some two-dimensional combination of the second through fifth PCs. Its value compared to the PCA results (or a related factor analysis) is therefore questionable; the principal merit may be in the proposed interactivity. Although R's default biplot looks awful, here it is for comparison. To make it match the star coordinates plot better, you would need to permute the $u_i$ to agree with the sequence of axes shown in this biplot.
How to plot a 5D data set in "star coordinates"?
The "star coordinates" are intended to be modified interactively, beginning with a default. This answer shows how to create the default; the interactive modifications are a programming detail. The da
How to plot a 5D data set in "star coordinates"? The "star coordinates" are intended to be modified interactively, beginning with a default. This answer shows how to create the default; the interactive modifications are a programming detail. The data are considered a collection of vectors $x_j = (x_{j1}, x_{j2}, \ldots, x_{jd})$ in $\mathbb{R}^d$. These are first normalized separately within each coordinate, linearly transforming the data $\{x_{ji}, j=1, 2, \ldots\}$ into the interval $[0,1]$. This is done, of course, by first subtracting their minimum from each element and dividing by the range. Call the normalized data $z_j$. The usual basis of $\mathbb{R}^d$ is the set of vectors $e_i = (0, 0, \ldots, 0, 1, 0, 0, \ldots, 0)$ having a single $1$ in the $i^\text{th}$ place. In terms of this basis, $z_j = z_{j1}e_1 + z_{j2}e_2 + \cdots + z_{jd}e_d$. A "star coordinates projection" chooses a set of distinct unit vectors $\{u_i, i=1, 2, \ldots, d\}$ in $\mathbb{R}^2$ and maps $e_i$ to $u_i$. This defines a linear transformation from $\mathbb{R}^d$ to $\mathbb{R}^2$. This map is applied to the $z_j$--it is just a matrix multiplication--to create a two-dimensional point cloud, depicted as a scatterplot. The unit vectors $u_i$ are drawn and labeled for reference. (An interactive version will allow the user to rotate each of the $u_i$ individually.) To illustrate this, here is an R implementation applied to a dataset of automobile performance characteristics. First let's obtain the data: library(MASS) x <- subset(Cars93, select=c(Price, MPG.city, Horsepower, Fuel.tank.capacity, Turn.circle)) The initial step is to normalize the data: x.range <- apply(x, 2, range) z <- t((t(x) - x.range[1,]) / (x.range[2,] - x.range[1,])) As a default, let's create $d$ equally spaced unit vectors for the $u_i$. These determine the projection prj which is applied to $z$: d <- dim(z)[2] # Dimensions prj <- t(sapply((1:d)/d, function(i) c(cos(2*pi*i), sin(2*pi*i)))) star <- z %*% prj That's it--we are all ready to plot. It is initialized to provide room for the data points, the coordinate axes, and their labels: plot(rbind(apply(star, 2, range), apply(prj*1.25, 2, range)), type="n", bty="n", xaxt="n", yaxt="n", main="Cars 93", xlab="", ylab="") Here is the plot itself, with one line for each element: axes, labels, and points: tmp <- apply(prj, 1, function(v) lines(rbind(c(0,0), v))) text(prj * 1.1, labels=colnames(z), cex=0.8, col="Gray") points(star, pch=19, col="Red"); points(star, col="0x200000") To understand this plot, it might help to compare it to a traditional method, the scatterplot matrix: pairs(x) A correlation-based principal components analysis (PCA) creates almost the same result. (pca <- princomp(x, cor=TRUE)) pca$loadings[,1] biplot(pca, choices=2:3) The output for the first command is Standard deviations: Comp.1 Comp.2 Comp.3 Comp.4 Comp.5 1.8999932 0.8304711 0.5750447 0.4399687 0.4196363 Most of the variance is accounted for by the first component (1.9 versus 0.83 and less). The loadings onto this component are almost equal in size, as shown by the output to the second command: Price MPG.city Horsepower Fuel.tank.capacity Turn.circle 0.4202798 -0.4668682 0.4640081 0.4758205 0.4045867 This suggests--in this case--that the default star coordinates plot is projecting along the first principal component and therefore is showing, essentially, some two-dimensional combination of the second through fifth PCs. Its value compared to the PCA results (or a related factor analysis) is therefore questionable; the principal merit may be in the proposed interactivity. Although R's default biplot looks awful, here it is for comparison. To make it match the star coordinates plot better, you would need to permute the $u_i$ to agree with the sequence of axes shown in this biplot.
How to plot a 5D data set in "star coordinates"? The "star coordinates" are intended to be modified interactively, beginning with a default. This answer shows how to create the default; the interactive modifications are a programming detail. The da
31,352
How to plot a 5D data set in "star coordinates"?
In addition to the nice answer by @whuber, I would like to add some other options for displaying multidimensional (multivariate) data in "star coordinates", for the sake of more comprehensive coverage. My answer focuses on performing such visualization of multivariate data in R. I will start by saying that star plots (in both spider and radar variants) are supported by R's base graphics package via function stars(): http://stat.ethz.ch/R-manual/R-devel/library/graphics/html/stars.html. Next in the R "food chain" goes, obviously, ggplot2 package, which AFAIK currently doesn't have specific functions for this type of plots (please correct me, if I'm not up-to-date on this). However, a basic implementation by Hadley Wickham, using coord_polar(), can be found here. In addition, a ggplot2-based ggsubplot package offers the relevant function geom_star(): http://www.inside-r.org/packages/cran/ggsubplot/docs/geom_star. Other packages that contain the star plotting functionality include: psych - functions spider() and radar() - http://personality-project.org/r/html/spider.html, plotrix - function radial.plot() - http://onertipaday.blogspot.com/2009/01/radar-chart.html) and, possibly, some others. In addition to the above, it should be noted that it is possible to create star plots in Web-enabled software, which easily interfaces with R. For example, here is a variation of a star plot in plotly, where it's called polar area chart: https://plot.ly/r/polar-chart/#Polar-Area-Chart. Speaking about R and Web-enabled data visualization, it is impossible not to mention great D3.js library, which also can be accessed from R. Here is how to make a great-looking star plot, using D3.js: http://www.visualcinnamon.com/2013/09/making-d3-radar-chart-look-bit-better.html.
How to plot a 5D data set in "star coordinates"?
In addition to the nice answer by @whuber, I would like to add some other options for displaying multidimensional (multivariate) data in "star coordinates", for the sake of more comprehensive coverage
How to plot a 5D data set in "star coordinates"? In addition to the nice answer by @whuber, I would like to add some other options for displaying multidimensional (multivariate) data in "star coordinates", for the sake of more comprehensive coverage. My answer focuses on performing such visualization of multivariate data in R. I will start by saying that star plots (in both spider and radar variants) are supported by R's base graphics package via function stars(): http://stat.ethz.ch/R-manual/R-devel/library/graphics/html/stars.html. Next in the R "food chain" goes, obviously, ggplot2 package, which AFAIK currently doesn't have specific functions for this type of plots (please correct me, if I'm not up-to-date on this). However, a basic implementation by Hadley Wickham, using coord_polar(), can be found here. In addition, a ggplot2-based ggsubplot package offers the relevant function geom_star(): http://www.inside-r.org/packages/cran/ggsubplot/docs/geom_star. Other packages that contain the star plotting functionality include: psych - functions spider() and radar() - http://personality-project.org/r/html/spider.html, plotrix - function radial.plot() - http://onertipaday.blogspot.com/2009/01/radar-chart.html) and, possibly, some others. In addition to the above, it should be noted that it is possible to create star plots in Web-enabled software, which easily interfaces with R. For example, here is a variation of a star plot in plotly, where it's called polar area chart: https://plot.ly/r/polar-chart/#Polar-Area-Chart. Speaking about R and Web-enabled data visualization, it is impossible not to mention great D3.js library, which also can be accessed from R. Here is how to make a great-looking star plot, using D3.js: http://www.visualcinnamon.com/2013/09/making-d3-radar-chart-look-bit-better.html.
How to plot a 5D data set in "star coordinates"? In addition to the nice answer by @whuber, I would like to add some other options for displaying multidimensional (multivariate) data in "star coordinates", for the sake of more comprehensive coverage
31,353
Is using the same data for feature selection and cross-validation biased or not?
i think it is biased. What about applying FS in N-1 partition and test on last partition. and combine the features from all fold in some way(union/intersection/ or some problem specific way).
Is using the same data for feature selection and cross-validation biased or not?
i think it is biased. What about applying FS in N-1 partition and test on last partition. and combine the features from all fold in some way(union/intersection/ or some problem specific way).
Is using the same data for feature selection and cross-validation biased or not? i think it is biased. What about applying FS in N-1 partition and test on last partition. and combine the features from all fold in some way(union/intersection/ or some problem specific way).
Is using the same data for feature selection and cross-validation biased or not? i think it is biased. What about applying FS in N-1 partition and test on last partition. and combine the features from all fold in some way(union/intersection/ or some problem specific way).
31,354
Is using the same data for feature selection and cross-validation biased or not?
The simple answer is that you should do feature selection on a different dataset than you train on (you're doing this already, so don't change this)---the effect of not doing this is you will overfit your training data. You must also not do feature selection on your test set, as this will inflate estimates of your models' performance (I think you already realise this as well, but I found it a little hard to understand the question precisely). If you've divided your test set into training, validation and testing already, then there's no particular reason to do cross-validation unless you have so little data that your test set is too small to draw strong conclusions from. Many researchers have a dislike of cross validation because if used to drive model development (by which I mean, you tweak things, then run cross validation to see how they do, then tweak them some more etc.) you effectively have access to your test data and this can lead you to overestimate your performance on truly unseen data. If your data is so small that you have no choice but to do cross validation, the correct way to do this with training, dev and test sets is to explicitly split your data into three parts for each fold---the majority should be used for training, some for development (feature selection in your case, plus any other free parameters that need fitting) and finally you should test on the test portion. You can then average scores across these test portions to get an estimate of model performance: however, as I said, beware that if these scores are used to guide you to approaches you want to use for your problem, you shouldn't expect to get the same score on unseen data that you did from your cross validation.
Is using the same data for feature selection and cross-validation biased or not?
The simple answer is that you should do feature selection on a different dataset than you train on (you're doing this already, so don't change this)---the effect of not doing this is you will overfit
Is using the same data for feature selection and cross-validation biased or not? The simple answer is that you should do feature selection on a different dataset than you train on (you're doing this already, so don't change this)---the effect of not doing this is you will overfit your training data. You must also not do feature selection on your test set, as this will inflate estimates of your models' performance (I think you already realise this as well, but I found it a little hard to understand the question precisely). If you've divided your test set into training, validation and testing already, then there's no particular reason to do cross-validation unless you have so little data that your test set is too small to draw strong conclusions from. Many researchers have a dislike of cross validation because if used to drive model development (by which I mean, you tweak things, then run cross validation to see how they do, then tweak them some more etc.) you effectively have access to your test data and this can lead you to overestimate your performance on truly unseen data. If your data is so small that you have no choice but to do cross validation, the correct way to do this with training, dev and test sets is to explicitly split your data into three parts for each fold---the majority should be used for training, some for development (feature selection in your case, plus any other free parameters that need fitting) and finally you should test on the test portion. You can then average scores across these test portions to get an estimate of model performance: however, as I said, beware that if these scores are used to guide you to approaches you want to use for your problem, you shouldn't expect to get the same score on unseen data that you did from your cross validation.
Is using the same data for feature selection and cross-validation biased or not? The simple answer is that you should do feature selection on a different dataset than you train on (you're doing this already, so don't change this)---the effect of not doing this is you will overfit
31,355
Is using the same data for feature selection and cross-validation biased or not?
Did you try LOOCV? I think it's apt to train, when you have very less training data. To answer your question, that would not give you the best of results simply because it could overfit and give you misleading results, such that your classifier would not perform great on other data, that it has not seen.
Is using the same data for feature selection and cross-validation biased or not?
Did you try LOOCV? I think it's apt to train, when you have very less training data. To answer your question, that would not give you the best of results simply because it could overfit and give you
Is using the same data for feature selection and cross-validation biased or not? Did you try LOOCV? I think it's apt to train, when you have very less training data. To answer your question, that would not give you the best of results simply because it could overfit and give you misleading results, such that your classifier would not perform great on other data, that it has not seen.
Is using the same data for feature selection and cross-validation biased or not? Did you try LOOCV? I think it's apt to train, when you have very less training data. To answer your question, that would not give you the best of results simply because it could overfit and give you
31,356
Is using the same data for feature selection and cross-validation biased or not?
You could do the following to compare the performance of the classifiers Take your training set and train it on every possible feature set. For each feature set, minimize the parameters and build the model such that it fits the training set well. Now, once the models are built for all the feature sets, i.e. you have a model for every feature set, validate the models (built on different feature sets) on the validation set and select that model (built for a particular subset of feature set) that gives the minimum error on the validation set. This way, you ensure that the model built has fit well not just the training set but also the validation set. Now, take this built model and test it on the testing set. This will tell you how well the classifier performs once it runs on a data set that was neither used for training nor for validation. Also, you have selected that feature set that fits the training set and also the validation set well.
Is using the same data for feature selection and cross-validation biased or not?
You could do the following to compare the performance of the classifiers Take your training set and train it on every possible feature set. For each feature set, minimize the parameters and build the
Is using the same data for feature selection and cross-validation biased or not? You could do the following to compare the performance of the classifiers Take your training set and train it on every possible feature set. For each feature set, minimize the parameters and build the model such that it fits the training set well. Now, once the models are built for all the feature sets, i.e. you have a model for every feature set, validate the models (built on different feature sets) on the validation set and select that model (built for a particular subset of feature set) that gives the minimum error on the validation set. This way, you ensure that the model built has fit well not just the training set but also the validation set. Now, take this built model and test it on the testing set. This will tell you how well the classifier performs once it runs on a data set that was neither used for training nor for validation. Also, you have selected that feature set that fits the training set and also the validation set well.
Is using the same data for feature selection and cross-validation biased or not? You could do the following to compare the performance of the classifiers Take your training set and train it on every possible feature set. For each feature set, minimize the parameters and build the
31,357
Is using the same data for feature selection and cross-validation biased or not?
If possible it is best to hold back some data for additional cross validation. For example you can use it to validate your algorithms by building learning curves. These curves must be build on data set that has not been used before. Even if you want to simply select an algorithm that gives you highest F1 score, you'd need to use extra cross validation data set to do that. Test set must be reserved to report final accuracy of your solution (expected performance of the chosen classifier on unseen data).
Is using the same data for feature selection and cross-validation biased or not?
If possible it is best to hold back some data for additional cross validation. For example you can use it to validate your algorithms by building learning curves. These curves must be build on data se
Is using the same data for feature selection and cross-validation biased or not? If possible it is best to hold back some data for additional cross validation. For example you can use it to validate your algorithms by building learning curves. These curves must be build on data set that has not been used before. Even if you want to simply select an algorithm that gives you highest F1 score, you'd need to use extra cross validation data set to do that. Test set must be reserved to report final accuracy of your solution (expected performance of the chosen classifier on unseen data).
Is using the same data for feature selection and cross-validation biased or not? If possible it is best to hold back some data for additional cross validation. For example you can use it to validate your algorithms by building learning curves. These curves must be build on data se
31,358
Is using the same data for feature selection and cross-validation biased or not?
It can be super grossly biased, refer to the chapter of model validation in "Elements of Statistical Learning", It can make model cv accuracy above 70% while the true error rate of any model should be 50% (features are independent of the class).
Is using the same data for feature selection and cross-validation biased or not?
It can be super grossly biased, refer to the chapter of model validation in "Elements of Statistical Learning", It can make model cv accuracy above 70% while the true error rate of any model should be
Is using the same data for feature selection and cross-validation biased or not? It can be super grossly biased, refer to the chapter of model validation in "Elements of Statistical Learning", It can make model cv accuracy above 70% while the true error rate of any model should be 50% (features are independent of the class).
Is using the same data for feature selection and cross-validation biased or not? It can be super grossly biased, refer to the chapter of model validation in "Elements of Statistical Learning", It can make model cv accuracy above 70% while the true error rate of any model should be
31,359
Skewed variables in PCA or factor analysis
Skewness issue in PCA is the same as in regression: the longer tail, if it is really long relative to the whole range of the distribution, actually behaves like a big outlier—it pulls the fit line (principal component in your case) strongly toward itself because its influence is enhanced; its influence is enhanced because it is so far from the mean. In the context of PCA allowing very skewed variables is pretty similar to doing PCA without centering the data (i.e., doing PCA on the basis of cosine matrix rather than correlation matrix). It is you who decides whether to permit the long tail to influence results so greatly (and let the data be) or not (and transform the data). The issue is not connected with how you do interpretation of loadings. As you like. KMO is an index that tells you whether partial correlations are reasonably small to submit data to factor analysis. Because in factor analysis we generally expect a factor to load more than just two variables. Your KMO is low enough. You can make it better if you drop from the analysis variables with low individual KMO values (these form the diagonal of anti-image matrix, you can request to show this matrix in SPSS Factor procedure). Can tranforming variables into less skewed recover KMO? Who knows. Maybe. Note that KMO is important mostly in Factor analysis model, not Principal Components analysis model: in FA you fit pairwise correlations, whereas in PCA you don't.
Skewed variables in PCA or factor analysis
Skewness issue in PCA is the same as in regression: the longer tail, if it is really long relative to the whole range of the distribution, actually behaves like a big outlier—it pulls the fit line (pr
Skewed variables in PCA or factor analysis Skewness issue in PCA is the same as in regression: the longer tail, if it is really long relative to the whole range of the distribution, actually behaves like a big outlier—it pulls the fit line (principal component in your case) strongly toward itself because its influence is enhanced; its influence is enhanced because it is so far from the mean. In the context of PCA allowing very skewed variables is pretty similar to doing PCA without centering the data (i.e., doing PCA on the basis of cosine matrix rather than correlation matrix). It is you who decides whether to permit the long tail to influence results so greatly (and let the data be) or not (and transform the data). The issue is not connected with how you do interpretation of loadings. As you like. KMO is an index that tells you whether partial correlations are reasonably small to submit data to factor analysis. Because in factor analysis we generally expect a factor to load more than just two variables. Your KMO is low enough. You can make it better if you drop from the analysis variables with low individual KMO values (these form the diagonal of anti-image matrix, you can request to show this matrix in SPSS Factor procedure). Can tranforming variables into less skewed recover KMO? Who knows. Maybe. Note that KMO is important mostly in Factor analysis model, not Principal Components analysis model: in FA you fit pairwise correlations, whereas in PCA you don't.
Skewed variables in PCA or factor analysis Skewness issue in PCA is the same as in regression: the longer tail, if it is really long relative to the whole range of the distribution, actually behaves like a big outlier—it pulls the fit line (pr
31,360
Skewed variables in PCA or factor analysis
+1 to @ttnphns, I just want to expand a little on point #2. Transformations are often used to stabilize skew. As @ttnphns points out, you would use these before you run your analyses. Log transformations are part of the Box-Cox family of power transformations. You will want to consider a wider range of possible transformations than just logs (e.g., square root, reciprocal, etc.). The choice between different logarithmic bases has no effect on the strength of the transformation. When people are going to work mathematically with the transformed variable, natural logs are sometimes preferred, as the natural log can make for cleaner math in some cases. If you don't care about that, you may want to pick a base that will facilitate interpretation. That is, each unit increase in the new scale will represent a base-fold increase in the original scale (e.g., if you used log base 2, then every unit would be a 2-fold increase, base 10 means every unit would be a 10-fold increase, etc.), so it can be nice to pick a base that such that your data will span several units in the transformed scale.
Skewed variables in PCA or factor analysis
+1 to @ttnphns, I just want to expand a little on point #2. Transformations are often used to stabilize skew. As @ttnphns points out, you would use these before you run your analyses. Log transform
Skewed variables in PCA or factor analysis +1 to @ttnphns, I just want to expand a little on point #2. Transformations are often used to stabilize skew. As @ttnphns points out, you would use these before you run your analyses. Log transformations are part of the Box-Cox family of power transformations. You will want to consider a wider range of possible transformations than just logs (e.g., square root, reciprocal, etc.). The choice between different logarithmic bases has no effect on the strength of the transformation. When people are going to work mathematically with the transformed variable, natural logs are sometimes preferred, as the natural log can make for cleaner math in some cases. If you don't care about that, you may want to pick a base that will facilitate interpretation. That is, each unit increase in the new scale will represent a base-fold increase in the original scale (e.g., if you used log base 2, then every unit would be a 2-fold increase, base 10 means every unit would be a 10-fold increase, etc.), so it can be nice to pick a base that such that your data will span several units in the transformed scale.
Skewed variables in PCA or factor analysis +1 to @ttnphns, I just want to expand a little on point #2. Transformations are often used to stabilize skew. As @ttnphns points out, you would use these before you run your analyses. Log transform
31,361
"Since $x$ is near-gaussian, its PDF can be written as..."
(Note: I've changed your $\xi$ to $x$.) For a random variable $X$ with density $p$, if you have constraints $$ \int G_i(x)\,p(x)\,dx=c_i \, , $$ for $i=1,\dots,n$, the maximum entropy density is $$ p_0(x)=A\exp\left(\sum_{i=1}^n a_iG_i(x)\right) \, , $$ where the $a_i$'s are determined from the $c_i$'s, and $A$ is a normalization constant. In this context, the Gaussian approximation ("near-gaussianity") means two things: 1) You accept to introduce two new constraints: the mean of $X$ is $0$ and the variance is $1$ (say); 2) The corresponding $a_{n+2}$ (see bellow) is much bigger than the other $a_i$'s. These additional constraints are represented as $$ G_{n+1}(x)=x \, , \qquad c_{n+1}=0 \, , $$ $$ G_{n+2}(x)=x^2 \, , \qquad c_{n+2}=1 \, , $$ yielding $$ p_0(x)=A\exp\left(a_{n+2}x^2 + a_{n+1}x + \sum_{i=1}^n a_iG_i(x)\right) \, , $$ which can be rewritten as (just "add zero" to the exponent) $$ p_0(x)=A\exp\left(\frac{x^2}{2} - \frac{x^2}{2} + a_{n+2}x^2 + a_{n+1}x + \sum_{i=1}^n a_iG_i(x)\right) \, , $$ leading to what you want: $$ p_0(x)=A'\,\phi(x)\exp\left(a_{n+1}x + \left(a_{n+2}+\frac{1}{2}\right)x^2 + \sum_{i=1}^n a_iG_i(x)\right) \, ; $$ ready to be Taylor expanded (using the second condition of the Gaussian approximation). Doing the approximation like a Physicist (which means that we don't care about the order of the error term), using $\exp(t)\approx 1+t$, we have the approximate density $$ p_0(x) \approx A'\,\phi(x)\left(1+a_{n+1}x + \left(a_{n+2}+\frac{1}{2}\right)x^2 + \sum_{i=1}^n a_iG_i(x)\right) \, . $$ To finish, we have to determine $A'$ and the values of the $a_i$'s. This is done imposing the conditions $$ \int p_0(x)\,dx=1 \, , \qquad \int x \,p_0(x)\,dx=0 \, , \qquad \int x^2 \,p_0(x)\,dx=1 $$ $$ \int G_i(x)\, p_0(x)\,dx=c_i \, , \quad i=1,\dots,n \, , $$ to obtain a system of equations, whose solution gives $A'$ and the $a_i$'s. Without imposing additional conditions on the $G_i$'s, I don't believe that there is a simple solution in closed form. P.S. Mohammad clarified during a chat that with additional orthogonality conditions for the $G_i$'s we can solve the system.
"Since $x$ is near-gaussian, its PDF can be written as..."
(Note: I've changed your $\xi$ to $x$.) For a random variable $X$ with density $p$, if you have constraints $$ \int G_i(x)\,p(x)\,dx=c_i \, , $$ for $i=1,\dots,n$, the maximum entropy density is $$
"Since $x$ is near-gaussian, its PDF can be written as..." (Note: I've changed your $\xi$ to $x$.) For a random variable $X$ with density $p$, if you have constraints $$ \int G_i(x)\,p(x)\,dx=c_i \, , $$ for $i=1,\dots,n$, the maximum entropy density is $$ p_0(x)=A\exp\left(\sum_{i=1}^n a_iG_i(x)\right) \, , $$ where the $a_i$'s are determined from the $c_i$'s, and $A$ is a normalization constant. In this context, the Gaussian approximation ("near-gaussianity") means two things: 1) You accept to introduce two new constraints: the mean of $X$ is $0$ and the variance is $1$ (say); 2) The corresponding $a_{n+2}$ (see bellow) is much bigger than the other $a_i$'s. These additional constraints are represented as $$ G_{n+1}(x)=x \, , \qquad c_{n+1}=0 \, , $$ $$ G_{n+2}(x)=x^2 \, , \qquad c_{n+2}=1 \, , $$ yielding $$ p_0(x)=A\exp\left(a_{n+2}x^2 + a_{n+1}x + \sum_{i=1}^n a_iG_i(x)\right) \, , $$ which can be rewritten as (just "add zero" to the exponent) $$ p_0(x)=A\exp\left(\frac{x^2}{2} - \frac{x^2}{2} + a_{n+2}x^2 + a_{n+1}x + \sum_{i=1}^n a_iG_i(x)\right) \, , $$ leading to what you want: $$ p_0(x)=A'\,\phi(x)\exp\left(a_{n+1}x + \left(a_{n+2}+\frac{1}{2}\right)x^2 + \sum_{i=1}^n a_iG_i(x)\right) \, ; $$ ready to be Taylor expanded (using the second condition of the Gaussian approximation). Doing the approximation like a Physicist (which means that we don't care about the order of the error term), using $\exp(t)\approx 1+t$, we have the approximate density $$ p_0(x) \approx A'\,\phi(x)\left(1+a_{n+1}x + \left(a_{n+2}+\frac{1}{2}\right)x^2 + \sum_{i=1}^n a_iG_i(x)\right) \, . $$ To finish, we have to determine $A'$ and the values of the $a_i$'s. This is done imposing the conditions $$ \int p_0(x)\,dx=1 \, , \qquad \int x \,p_0(x)\,dx=0 \, , \qquad \int x^2 \,p_0(x)\,dx=1 $$ $$ \int G_i(x)\, p_0(x)\,dx=c_i \, , \quad i=1,\dots,n \, , $$ to obtain a system of equations, whose solution gives $A'$ and the $a_i$'s. Without imposing additional conditions on the $G_i$'s, I don't believe that there is a simple solution in closed form. P.S. Mohammad clarified during a chat that with additional orthogonality conditions for the $G_i$'s we can solve the system.
"Since $x$ is near-gaussian, its PDF can be written as..." (Note: I've changed your $\xi$ to $x$.) For a random variable $X$ with density $p$, if you have constraints $$ \int G_i(x)\,p(x)\,dx=c_i \, , $$ for $i=1,\dots,n$, the maximum entropy density is $$
31,362
Basis of Pearson correlation coefficient
What matter is $cov(X,Y)$. Denominator $\sqrt{var(X)var(Y)}$ is for getting rid of units of measure (if say $X$ is measured in meters and $Y$ in kilograms then $cov(X,Y)$ is measured in meter-kilograms which is hard to comprehend) and for standardization ($cor(X,Y)$ lies between -1 and 1 whatever variable values you have). Now back to $cov(X,Y)$. This shows how variables vary together about their means, hence co-variance. Let us take an example. Lines are drawn at sample means $\bar X$ and $\bar Y$. The points in the upper right corner are where both $X_i$ and $Y_i$ are above their means and so both $(X_i-\bar X)$ and $(Y_i-\bar Y)$ are positive. The points in the lower left corner are below their means. In both cases product $(X_i-\bar X)(Y_i-\bar Y)$ is positive. On the contrary upper left and lower right are areas where this product is negative. Now when computing covariance $cov(X,Y)=\frac1{n-1}\sum_{i=1}^n(X_i-\bar X)(Y_i-\bar Y)$ in this example points that give positive products $(X_i-\bar X)(Y_i-\bar Y)$ dominate, resulting positive covariance. This covariance is bigger when points are aligned closer to an imaginable line crossing the point $(\bar X,\bar Y)$. As a last note, covariance shows only the strength of a linear relationship. If relationship is non linear, covariance is not able to detect it.
Basis of Pearson correlation coefficient
What matter is $cov(X,Y)$. Denominator $\sqrt{var(X)var(Y)}$ is for getting rid of units of measure (if say $X$ is measured in meters and $Y$ in kilograms then $cov(X,Y)$ is measured in meter-kilogram
Basis of Pearson correlation coefficient What matter is $cov(X,Y)$. Denominator $\sqrt{var(X)var(Y)}$ is for getting rid of units of measure (if say $X$ is measured in meters and $Y$ in kilograms then $cov(X,Y)$ is measured in meter-kilograms which is hard to comprehend) and for standardization ($cor(X,Y)$ lies between -1 and 1 whatever variable values you have). Now back to $cov(X,Y)$. This shows how variables vary together about their means, hence co-variance. Let us take an example. Lines are drawn at sample means $\bar X$ and $\bar Y$. The points in the upper right corner are where both $X_i$ and $Y_i$ are above their means and so both $(X_i-\bar X)$ and $(Y_i-\bar Y)$ are positive. The points in the lower left corner are below their means. In both cases product $(X_i-\bar X)(Y_i-\bar Y)$ is positive. On the contrary upper left and lower right are areas where this product is negative. Now when computing covariance $cov(X,Y)=\frac1{n-1}\sum_{i=1}^n(X_i-\bar X)(Y_i-\bar Y)$ in this example points that give positive products $(X_i-\bar X)(Y_i-\bar Y)$ dominate, resulting positive covariance. This covariance is bigger when points are aligned closer to an imaginable line crossing the point $(\bar X,\bar Y)$. As a last note, covariance shows only the strength of a linear relationship. If relationship is non linear, covariance is not able to detect it.
Basis of Pearson correlation coefficient What matter is $cov(X,Y)$. Denominator $\sqrt{var(X)var(Y)}$ is for getting rid of units of measure (if say $X$ is measured in meters and $Y$ in kilograms then $cov(X,Y)$ is measured in meter-kilogram
31,363
Basis of Pearson correlation coefficient
If, in the formula that you display, you remove the 'dividedness' of all three terms, cov(X,Y), var(X) and var(Y) by n-1, you get even more basic formula for r: $\frac{SCP(X,Y)}{\sqrt{SS(X)} \sqrt{SS(Y)}}$, where SCP is "sum cross-products" and SS is "sum of squares". Generally, this is the formula for cosine. But since X and Y are centered ("sum of cross-products of deviations" and "sum of squares of deviations") it becomes the formula for r, - r is the cosine between centered variables. Now, cosine is the measure of proportionality; cos(X,Y)=1 when and only when Xi=kYi, that is when all points (i) lie on a straight line coming from the origin of the X vs Y coordinate system. If either the line doesn't come through the origin or points depart from the straight line cos will become smaller. Because Pearson r is the cos of the cloud which has been centered on both X and Y axes the line inevitably comes through the origin; and hence only departure of points from lying on the straight line can diminish r: r is the measure of linearity.
Basis of Pearson correlation coefficient
If, in the formula that you display, you remove the 'dividedness' of all three terms, cov(X,Y), var(X) and var(Y) by n-1, you get even more basic formula for r: $\frac{SCP(X,Y)}{\sqrt{SS(X)} \sqrt{SS(
Basis of Pearson correlation coefficient If, in the formula that you display, you remove the 'dividedness' of all three terms, cov(X,Y), var(X) and var(Y) by n-1, you get even more basic formula for r: $\frac{SCP(X,Y)}{\sqrt{SS(X)} \sqrt{SS(Y)}}$, where SCP is "sum cross-products" and SS is "sum of squares". Generally, this is the formula for cosine. But since X and Y are centered ("sum of cross-products of deviations" and "sum of squares of deviations") it becomes the formula for r, - r is the cosine between centered variables. Now, cosine is the measure of proportionality; cos(X,Y)=1 when and only when Xi=kYi, that is when all points (i) lie on a straight line coming from the origin of the X vs Y coordinate system. If either the line doesn't come through the origin or points depart from the straight line cos will become smaller. Because Pearson r is the cos of the cloud which has been centered on both X and Y axes the line inevitably comes through the origin; and hence only departure of points from lying on the straight line can diminish r: r is the measure of linearity.
Basis of Pearson correlation coefficient If, in the formula that you display, you remove the 'dividedness' of all three terms, cov(X,Y), var(X) and var(Y) by n-1, you get even more basic formula for r: $\frac{SCP(X,Y)}{\sqrt{SS(X)} \sqrt{SS(
31,364
Basis of Pearson correlation coefficient
If r = 1, there is perfect linear correlation, if r = -1 there is perfect negative linear correlation, if r = 0, there is no linear correlation. The reason we divide by standard deviations of X and Y is to obtain a measure that does not depend on scale. See this thread for more detailed answers.
Basis of Pearson correlation coefficient
If r = 1, there is perfect linear correlation, if r = -1 there is perfect negative linear correlation, if r = 0, there is no linear correlation. The reason we divide by standard deviations of X and Y
Basis of Pearson correlation coefficient If r = 1, there is perfect linear correlation, if r = -1 there is perfect negative linear correlation, if r = 0, there is no linear correlation. The reason we divide by standard deviations of X and Y is to obtain a measure that does not depend on scale. See this thread for more detailed answers.
Basis of Pearson correlation coefficient If r = 1, there is perfect linear correlation, if r = -1 there is perfect negative linear correlation, if r = 0, there is no linear correlation. The reason we divide by standard deviations of X and Y
31,365
How to assess repeatability of multivariate and method-specific outcomes?
This reminds me of cancer diagnostics, where old gene expression signatures are replaced by newer ones, that are of course supposed to be better. But how to show that they are better? Here are a couple of suggestions to compare the repeatability of the methods. 1. Use co-inertia analysis (CIA). CIA should be more advertised, unfortunately it is not widely used (no Wikipedia page for example). CIA is a two-table method that works on the same principle as canonical analysis (CA), which is to look for a pair of linear scores with maximum correlation between two sets of multi-densional measurements. Its advantage over CA is that you can do it even if you have more dimensions than observations. You could measure both methods on the same samples to get two coupled tables of 30 columns and $n$ observations. The first pair of principal components should be strongly correlated (if methods really measure the same thing). If method B is better, the residual variance should be smaller than the residual variance of method A. With this approach you address both the agreement of the methods, and their disagreement, which you interpret as noise. 2. Use a distance. You could use the Euclidean distance in 30 dimensions between the test and the retest to measure the repeatability of a method. You generate a sample of that score for each method and you can compare the samples with the Wilcoxon test. 3. Use downstream application. You are probably getting these fingerprints to take a decision, or classify patients or biological material. You can count the agreements vs disagreements between tests and retests for both methods and compare them with the Wilcoxon test. Method 3 is the simplest, but also the most down to earth. Even for high dimensional inputs, decisions are usually quite simple. And however complex our problem is, bear in mind that statistics is the science of decision. Regarding the question in your comment. What about using a robust dimensionality reduction method to reduce the multivariate data to a single dimension and analyzing it? Dimensionality reduction, however robust, will be associated with a loss of variance. If there is a way to transform your multivariate fingerprint into a single score capturing almost all of its variance, then sure, this is by far the best thing to do. But then why is the fingerprint multivariate in the first place? I assumed from the context of the OP that the fingerprint is multivariate precisely because it is hard to reduce its dimensionality further without losing information. In that case, their repeatability on a single score does not have to be a good proxy for the overall repeatability, because you may neglect the majority of the variance (close to 29/30 in the worst case).
How to assess repeatability of multivariate and method-specific outcomes?
This reminds me of cancer diagnostics, where old gene expression signatures are replaced by newer ones, that are of course supposed to be better. But how to show that they are better? Here are a coupl
How to assess repeatability of multivariate and method-specific outcomes? This reminds me of cancer diagnostics, where old gene expression signatures are replaced by newer ones, that are of course supposed to be better. But how to show that they are better? Here are a couple of suggestions to compare the repeatability of the methods. 1. Use co-inertia analysis (CIA). CIA should be more advertised, unfortunately it is not widely used (no Wikipedia page for example). CIA is a two-table method that works on the same principle as canonical analysis (CA), which is to look for a pair of linear scores with maximum correlation between two sets of multi-densional measurements. Its advantage over CA is that you can do it even if you have more dimensions than observations. You could measure both methods on the same samples to get two coupled tables of 30 columns and $n$ observations. The first pair of principal components should be strongly correlated (if methods really measure the same thing). If method B is better, the residual variance should be smaller than the residual variance of method A. With this approach you address both the agreement of the methods, and their disagreement, which you interpret as noise. 2. Use a distance. You could use the Euclidean distance in 30 dimensions between the test and the retest to measure the repeatability of a method. You generate a sample of that score for each method and you can compare the samples with the Wilcoxon test. 3. Use downstream application. You are probably getting these fingerprints to take a decision, or classify patients or biological material. You can count the agreements vs disagreements between tests and retests for both methods and compare them with the Wilcoxon test. Method 3 is the simplest, but also the most down to earth. Even for high dimensional inputs, decisions are usually quite simple. And however complex our problem is, bear in mind that statistics is the science of decision. Regarding the question in your comment. What about using a robust dimensionality reduction method to reduce the multivariate data to a single dimension and analyzing it? Dimensionality reduction, however robust, will be associated with a loss of variance. If there is a way to transform your multivariate fingerprint into a single score capturing almost all of its variance, then sure, this is by far the best thing to do. But then why is the fingerprint multivariate in the first place? I assumed from the context of the OP that the fingerprint is multivariate precisely because it is hard to reduce its dimensionality further without losing information. In that case, their repeatability on a single score does not have to be a good proxy for the overall repeatability, because you may neglect the majority of the variance (close to 29/30 in the worst case).
How to assess repeatability of multivariate and method-specific outcomes? This reminds me of cancer diagnostics, where old gene expression signatures are replaced by newer ones, that are of course supposed to be better. But how to show that they are better? Here are a coupl
31,366
How to assess repeatability of multivariate and method-specific outcomes?
I Assume from your question and comment that the 30 output variables can not (easily) or should not be transformed to a single variate. One idea to deal with data of $\mathbf{X_A}^{(n \times p_A)} \leftrightarrow \mathbf{X_B}^{(n \times p_B)}$ is that you could do regression of $\mathbf{X_A}^{(n \times p_A)} \mapsto \mathbf{X_B}^{(n \times p_B)}$ and vice versa. Additional knowledge (e.g. that variate $i$ in set A corresponds to variate $i$ also in set B) can help to restrict the mapping model and/or with the interpretation. So what about multi block PCA (or -PLS) which take this idea further? For these methods, both multivariate fingerprints for the same samples (or same individuals) are analyzed together as independent variables, with or without a third dependent block. R. Brereton: "Chemometrics for Pattern Recognition" discusses some techniques in the last chapter ("Comparing Different Patterns") and googling will lead you to a number of papers, also introductions. Note that your situations sounds similar to problems where e.g. spectroscopic and genetic measurements are analysed together (two matrices with a row-wise correspondence as opposed to analyzing e.g. time series of spectra where a data cube is analysed). Here's a paper dealing with multi-block analysis: Sahar Hassani: Analysis of -omics data: Graphical interpretation- and validation tools in multi-block methods. Also, maybe this is a good starting point into another direction: Hoefsloot et.al., Multiset Data Analysis: ANOVA Simultaneous Component Analysis and Related Methods, in: Comprehensive Chemometrics — Chemical and Biochemical Data Analysis(I don't have access to it, just saw the abstract)
How to assess repeatability of multivariate and method-specific outcomes?
I Assume from your question and comment that the 30 output variables can not (easily) or should not be transformed to a single variate. One idea to deal with data of $\mathbf{X_A}^{(n \times p_A)} \l
How to assess repeatability of multivariate and method-specific outcomes? I Assume from your question and comment that the 30 output variables can not (easily) or should not be transformed to a single variate. One idea to deal with data of $\mathbf{X_A}^{(n \times p_A)} \leftrightarrow \mathbf{X_B}^{(n \times p_B)}$ is that you could do regression of $\mathbf{X_A}^{(n \times p_A)} \mapsto \mathbf{X_B}^{(n \times p_B)}$ and vice versa. Additional knowledge (e.g. that variate $i$ in set A corresponds to variate $i$ also in set B) can help to restrict the mapping model and/or with the interpretation. So what about multi block PCA (or -PLS) which take this idea further? For these methods, both multivariate fingerprints for the same samples (or same individuals) are analyzed together as independent variables, with or without a third dependent block. R. Brereton: "Chemometrics for Pattern Recognition" discusses some techniques in the last chapter ("Comparing Different Patterns") and googling will lead you to a number of papers, also introductions. Note that your situations sounds similar to problems where e.g. spectroscopic and genetic measurements are analysed together (two matrices with a row-wise correspondence as opposed to analyzing e.g. time series of spectra where a data cube is analysed). Here's a paper dealing with multi-block analysis: Sahar Hassani: Analysis of -omics data: Graphical interpretation- and validation tools in multi-block methods. Also, maybe this is a good starting point into another direction: Hoefsloot et.al., Multiset Data Analysis: ANOVA Simultaneous Component Analysis and Related Methods, in: Comprehensive Chemometrics — Chemical and Biochemical Data Analysis(I don't have access to it, just saw the abstract)
How to assess repeatability of multivariate and method-specific outcomes? I Assume from your question and comment that the 30 output variables can not (easily) or should not be transformed to a single variate. One idea to deal with data of $\mathbf{X_A}^{(n \times p_A)} \l
31,367
How to assess repeatability of multivariate and method-specific outcomes?
30 one way analyses is certainly an option and would be an ideal "table 2" type of analysis, in which an overall performance is summarized in a logical way. It may be the case that Method B produces the first 20 factors with slightly improved precision whereas the last 10 are wildly more variable. You have the issue of inference using a partially ordered space: certainly if all 30 factors are more precise in B, then B is a better method. But there is "grey" area and with the large number of factors, it's almost guaranteed to show up in practice. If the objective of this research is to land on a single analysis, it's important to consider the weight of each outcome and their endpoint application. If these 30 variables are used in classification, prediction, and/or clustering of observational data, then I would like to see validation of these results and a comparison of A / B in classification (using something like risk stratification tables or mean percent bias), prediction (using the MSE), and clustering (using something like cross validation). This is the proper way of handling the grey area in which you can't say B is better analytically, but works much better in practice.
How to assess repeatability of multivariate and method-specific outcomes?
30 one way analyses is certainly an option and would be an ideal "table 2" type of analysis, in which an overall performance is summarized in a logical way. It may be the case that Method B produces t
How to assess repeatability of multivariate and method-specific outcomes? 30 one way analyses is certainly an option and would be an ideal "table 2" type of analysis, in which an overall performance is summarized in a logical way. It may be the case that Method B produces the first 20 factors with slightly improved precision whereas the last 10 are wildly more variable. You have the issue of inference using a partially ordered space: certainly if all 30 factors are more precise in B, then B is a better method. But there is "grey" area and with the large number of factors, it's almost guaranteed to show up in practice. If the objective of this research is to land on a single analysis, it's important to consider the weight of each outcome and their endpoint application. If these 30 variables are used in classification, prediction, and/or clustering of observational data, then I would like to see validation of these results and a comparison of A / B in classification (using something like risk stratification tables or mean percent bias), prediction (using the MSE), and clustering (using something like cross validation). This is the proper way of handling the grey area in which you can't say B is better analytically, but works much better in practice.
How to assess repeatability of multivariate and method-specific outcomes? 30 one way analyses is certainly an option and would be an ideal "table 2" type of analysis, in which an overall performance is summarized in a logical way. It may be the case that Method B produces t
31,368
How to assess repeatability of multivariate and method-specific outcomes?
I will try a multivariate ANOVA based on permutation (PERMANOVA) tests appoach. An ordination analisis (based on result on gradient length analysis) could also help.
How to assess repeatability of multivariate and method-specific outcomes?
I will try a multivariate ANOVA based on permutation (PERMANOVA) tests appoach. An ordination analisis (based on result on gradient length analysis) could also help.
How to assess repeatability of multivariate and method-specific outcomes? I will try a multivariate ANOVA based on permutation (PERMANOVA) tests appoach. An ordination analisis (based on result on gradient length analysis) could also help.
How to assess repeatability of multivariate and method-specific outcomes? I will try a multivariate ANOVA based on permutation (PERMANOVA) tests appoach. An ordination analisis (based on result on gradient length analysis) could also help.
31,369
How to assess repeatability of multivariate and method-specific outcomes?
If you could assume multivariate normality (which you said you could not) you could do a Hotelling T2 test of equality of mean vectors to see if you could claim differences between distributions or not. However although you can't do that you can still theoretically compare the distributions to see if they differ much. Divide the 30 dimensional space into rectangular grids. Use these as 30 dimensional bins. Count the number of vectors falling into each bin and apply a chi square test to see if the distributions look the same. The problem with this suggestion is that it requires judiciously selecting the bins in order to cover the data points in an appropriate way. Also the curse of dimensionality makes it difficult to identify differences between the multivariate distributions without having a very large number of point in each group. I think suggestions that gui11aume gave are sensible. I don't think the others are. Since comparing the distributions is not feasible in 30 dimensions with a typical sample some form of valid comparison of the mean vectors would seem to me to be appropriate.
How to assess repeatability of multivariate and method-specific outcomes?
If you could assume multivariate normality (which you said you could not) you could do a Hotelling T2 test of equality of mean vectors to see if you could claim differences between distributions or no
How to assess repeatability of multivariate and method-specific outcomes? If you could assume multivariate normality (which you said you could not) you could do a Hotelling T2 test of equality of mean vectors to see if you could claim differences between distributions or not. However although you can't do that you can still theoretically compare the distributions to see if they differ much. Divide the 30 dimensional space into rectangular grids. Use these as 30 dimensional bins. Count the number of vectors falling into each bin and apply a chi square test to see if the distributions look the same. The problem with this suggestion is that it requires judiciously selecting the bins in order to cover the data points in an appropriate way. Also the curse of dimensionality makes it difficult to identify differences between the multivariate distributions without having a very large number of point in each group. I think suggestions that gui11aume gave are sensible. I don't think the others are. Since comparing the distributions is not feasible in 30 dimensions with a typical sample some form of valid comparison of the mean vectors would seem to me to be appropriate.
How to assess repeatability of multivariate and method-specific outcomes? If you could assume multivariate normality (which you said you could not) you could do a Hotelling T2 test of equality of mean vectors to see if you could claim differences between distributions or no
31,370
Spline df selection in a general additive Poisson model problem
As @M.Berk mentions, GCV is known to undersmooth, primarily because this criterion weakly penalizes overfitting, which tends to result in a very shallow minimum in the GCV criterion as a function of $\lambda$, the smoothness parameter. As the minimum is very shallow, the optimal GCV can occur over a wide range of $\lambda$ estimates. Furthermore, the GCV criterion, as a function of $\lambda$ tends to have multiple minima, which can lead to the instability that you describe. Simon Wood (2011) has a nice illustration of this in his Figure 1. Wood (2011) also illustrates that AICc doesn't provide much additional benefit over GCV for low to intermediate rank bases used for the smooth functions. In contrast, REML (and also ML) smoothness selection more strongly penalizes overfit than GCV, and consequently has a much more clearly defined optimum. This leads to more stable estimates of $\lambda$ and much reduced risk of undersmoothing. Wood (2011) describes REML and ML estimation procedures that are both fast and stable, which he shows improves over existing REML (ML) approaches in terms of convergence. These ideas are available in Simon's mgcv package for R. As Wood (2011) is behind a paywall, I include a copy of a similar image (the AICc results are not shown here) taken from a set of Simon's slides, available on his website, on smoothness selection methods {PDF}. The figure, from slide 10, is shown below The two rows reflect simulated data where there is a strong (upper) or no (lower) signal respectively. The left-most panels show a realisation from each model. The remaining panels show how the GCV (middle column) and REML criteria vary as a function of $\lambda$ for 10 data sets each simulated from the real model. In the case of the upper row, notice how flat GCV is to the left of the optimum. The rug plots in these panels shows the optimal $\lambda$ for each of the 10 realisations. The REML criterion has a much more pronounced optimum and less variance in the chosen values of $\lambda$. Hence I would suggest the approach advocated by Simon Wood for his mgcv package, namely to chose as the basis dimension something that is sufficiently large as to include the flexibility anticipated in the relationship between $y = f(x) + \varepsilon$, but not so large. Then fit the model using REML smoothness selection. If the chosen model degrees of freedom is close to the dimension specified initially, increase the basis dimension and refit. As both @M.Berk and @BrendenDufault mention, a degree of subjectivity may be required when setting up the spline basis, in terms of selecting an appropriate basis dimension from which to fit the GAM. But REML smoothness selection has proven reasonably robust in my experience in a range of GAM applications using Wood's methods. Wood, S.N. (2011) Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalize linear models. J. Royal Statistical Society B 73(Part 1), 3--6.
Spline df selection in a general additive Poisson model problem
As @M.Berk mentions, GCV is known to undersmooth, primarily because this criterion weakly penalizes overfitting, which tends to result in a very shallow minimum in the GCV criterion as a function of $
Spline df selection in a general additive Poisson model problem As @M.Berk mentions, GCV is known to undersmooth, primarily because this criterion weakly penalizes overfitting, which tends to result in a very shallow minimum in the GCV criterion as a function of $\lambda$, the smoothness parameter. As the minimum is very shallow, the optimal GCV can occur over a wide range of $\lambda$ estimates. Furthermore, the GCV criterion, as a function of $\lambda$ tends to have multiple minima, which can lead to the instability that you describe. Simon Wood (2011) has a nice illustration of this in his Figure 1. Wood (2011) also illustrates that AICc doesn't provide much additional benefit over GCV for low to intermediate rank bases used for the smooth functions. In contrast, REML (and also ML) smoothness selection more strongly penalizes overfit than GCV, and consequently has a much more clearly defined optimum. This leads to more stable estimates of $\lambda$ and much reduced risk of undersmoothing. Wood (2011) describes REML and ML estimation procedures that are both fast and stable, which he shows improves over existing REML (ML) approaches in terms of convergence. These ideas are available in Simon's mgcv package for R. As Wood (2011) is behind a paywall, I include a copy of a similar image (the AICc results are not shown here) taken from a set of Simon's slides, available on his website, on smoothness selection methods {PDF}. The figure, from slide 10, is shown below The two rows reflect simulated data where there is a strong (upper) or no (lower) signal respectively. The left-most panels show a realisation from each model. The remaining panels show how the GCV (middle column) and REML criteria vary as a function of $\lambda$ for 10 data sets each simulated from the real model. In the case of the upper row, notice how flat GCV is to the left of the optimum. The rug plots in these panels shows the optimal $\lambda$ for each of the 10 realisations. The REML criterion has a much more pronounced optimum and less variance in the chosen values of $\lambda$. Hence I would suggest the approach advocated by Simon Wood for his mgcv package, namely to chose as the basis dimension something that is sufficiently large as to include the flexibility anticipated in the relationship between $y = f(x) + \varepsilon$, but not so large. Then fit the model using REML smoothness selection. If the chosen model degrees of freedom is close to the dimension specified initially, increase the basis dimension and refit. As both @M.Berk and @BrendenDufault mention, a degree of subjectivity may be required when setting up the spline basis, in terms of selecting an appropriate basis dimension from which to fit the GAM. But REML smoothness selection has proven reasonably robust in my experience in a range of GAM applications using Wood's methods. Wood, S.N. (2011) Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalize linear models. J. Royal Statistical Society B 73(Part 1), 3--6.
Spline df selection in a general additive Poisson model problem As @M.Berk mentions, GCV is known to undersmooth, primarily because this criterion weakly penalizes overfitting, which tends to result in a very shallow minimum in the GCV criterion as a function of $
31,371
Spline df selection in a general additive Poisson model problem
I think your best bet lies outside the smoothing algorithms; consider model parsimony. You allude to this, but I believe it must become your chief selection criteria. Ask yourself how many "bends" seem reasonable based on the etiology/causality of the processes being modeled. Graph the fitted splines with the plots=components(clm) statement and visually assess the fit. Perhaps the high DF splines are telling a similar story as the low DF splines, except more noisily. In that case, choose a low DF fit. After all, GAM models are intended to be exploratory. Having used the gcv option myself, I wonder about its performance under Poisson conditions, sparse data, etc. Maybe a simulation study is due here.
Spline df selection in a general additive Poisson model problem
I think your best bet lies outside the smoothing algorithms; consider model parsimony. You allude to this, but I believe it must become your chief selection criteria. Ask yourself how many "bends" se
Spline df selection in a general additive Poisson model problem I think your best bet lies outside the smoothing algorithms; consider model parsimony. You allude to this, but I believe it must become your chief selection criteria. Ask yourself how many "bends" seem reasonable based on the etiology/causality of the processes being modeled. Graph the fitted splines with the plots=components(clm) statement and visually assess the fit. Perhaps the high DF splines are telling a similar story as the low DF splines, except more noisily. In that case, choose a low DF fit. After all, GAM models are intended to be exploratory. Having used the gcv option myself, I wonder about its performance under Poisson conditions, sparse data, etc. Maybe a simulation study is due here.
Spline df selection in a general additive Poisson model problem I think your best bet lies outside the smoothing algorithms; consider model parsimony. You allude to this, but I believe it must become your chief selection criteria. Ask yourself how many "bends" se
31,372
Spline df selection in a general additive Poisson model problem
I typed up the following answer and then realized I have no idea if it's applicable to Poisson regression which I have no experience with. Perhaps people can answer that with some comments. Personally, I like the advice of B. W. Silverman (1985) "Some aspects of the spline smoothing approach to non-parametric regression curve fitting (with discussion)." (Available without subscription here): try a range of smoothing parameters and pick the one which is most visually appealing. As he also rightly points out in the same paper, while a subjective approach may be preferred, there is still the need for automatic methods. However, GCV is generally a poor choice as it has a tendency to undersmooth. See, for example Hurvich et al (1998) "Smoothing Parameter Selection in Nonparametric Regression Using an Improved Akaike Information Criterion" (Available without subscription here). In the same paper they propose a new criteria that may alleviate your problem, the corrected AIC which includes a small sample size correction. You may find the Wikipedia description of AICc easier to follow than the paper. The Wikipedia article also includes some good advice from Burnham & Anderson (i.e. use AICc rather than AIC regardless of sample size). In summary, my suggestions would be, in order of preference: Pick the smoothing parameter manually via visual assessment Use the corrected AIC (AICc) rather than GCV Use the standard AIC
Spline df selection in a general additive Poisson model problem
I typed up the following answer and then realized I have no idea if it's applicable to Poisson regression which I have no experience with. Perhaps people can answer that with some comments. Personall
Spline df selection in a general additive Poisson model problem I typed up the following answer and then realized I have no idea if it's applicable to Poisson regression which I have no experience with. Perhaps people can answer that with some comments. Personally, I like the advice of B. W. Silverman (1985) "Some aspects of the spline smoothing approach to non-parametric regression curve fitting (with discussion)." (Available without subscription here): try a range of smoothing parameters and pick the one which is most visually appealing. As he also rightly points out in the same paper, while a subjective approach may be preferred, there is still the need for automatic methods. However, GCV is generally a poor choice as it has a tendency to undersmooth. See, for example Hurvich et al (1998) "Smoothing Parameter Selection in Nonparametric Regression Using an Improved Akaike Information Criterion" (Available without subscription here). In the same paper they propose a new criteria that may alleviate your problem, the corrected AIC which includes a small sample size correction. You may find the Wikipedia description of AICc easier to follow than the paper. The Wikipedia article also includes some good advice from Burnham & Anderson (i.e. use AICc rather than AIC regardless of sample size). In summary, my suggestions would be, in order of preference: Pick the smoothing parameter manually via visual assessment Use the corrected AIC (AICc) rather than GCV Use the standard AIC
Spline df selection in a general additive Poisson model problem I typed up the following answer and then realized I have no idea if it's applicable to Poisson regression which I have no experience with. Perhaps people can answer that with some comments. Personall
31,373
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean?
The $df$ should be taken as approaching zero. See differential (infinitesimal).
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean?
The $df$ should be taken as approaching zero. See differential (infinitesimal).
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean? The $df$ should be taken as approaching zero. See differential (infinitesimal).
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean? The $df$ should be taken as approaching zero. See differential (infinitesimal).
31,374
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean?
About the first quote: Your first interpretation is correct: Jaynes replaces the integral with a rectangle approximation. Since it is an approximation to the integral, you are also correct in remarking that, for a given $df$, the finite sum over the rectangles does not give $1$. About the second quote: I am afraid Jaynes made a notational mistake in this definition. Using the Lebesgue measure on $\mathbb{R}^2$ as $\text{d}x\,\text{d}y$, we should have $$ \text{d}p(x,y|I)=\sqrt{1−ρ^2}/\sqrt{2π}\exp[−1/2(x^2+y^2−2ρxy)]\text{d}x\text{d} y $$ for the normal measure. However, since Jaynes is overall very much opposed to measure theory, I think your interpretation as a Riemann approximation is completely right!
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean?
About the first quote: Your first interpretation is correct: Jaynes replaces the integral with a rectangle approximation. Since it is an approximation to the integral, you are also correct in remarkin
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean? About the first quote: Your first interpretation is correct: Jaynes replaces the integral with a rectangle approximation. Since it is an approximation to the integral, you are also correct in remarking that, for a given $df$, the finite sum over the rectangles does not give $1$. About the second quote: I am afraid Jaynes made a notational mistake in this definition. Using the Lebesgue measure on $\mathbb{R}^2$ as $\text{d}x\,\text{d}y$, we should have $$ \text{d}p(x,y|I)=\sqrt{1−ρ^2}/\sqrt{2π}\exp[−1/2(x^2+y^2−2ρxy)]\text{d}x\text{d} y $$ for the normal measure. However, since Jaynes is overall very much opposed to measure theory, I think your interpretation as a Riemann approximation is completely right!
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean? About the first quote: Your first interpretation is correct: Jaynes replaces the integral with a rectangle approximation. Since it is an approximation to the integral, you are also correct in remarkin
31,375
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean?
The notation $\Pr(X \in dx)=f(x)dx$ is a standard notation to say that the law of the random variable $X$ has density $f$. Note that this notation is coherent with $\frac{\Pr(X\in dx)}{dx}=f(x)$ which actually says that $f$ is the Radon-Nikodym derivative of the law of $X$ with respect to the Lebesgue measure - in other words, the density. Thus the notation $p(dx)=f(x)dx$ is correct when denoting by $p$ the distribution of $X$. This notation is also coherent with the fact that $\Pr(X \in [x, x+h]) \approx hf(x)$ when $h$ is small.
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean?
The notation $\Pr(X \in dx)=f(x)dx$ is a standard notation to say that the law of the random variable $X$ has density $f$. Note that this notation is coherent with $\frac{\Pr(X\in dx)}{dx}=f(x)$ which
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean? The notation $\Pr(X \in dx)=f(x)dx$ is a standard notation to say that the law of the random variable $X$ has density $f$. Note that this notation is coherent with $\frac{\Pr(X\in dx)}{dx}=f(x)$ which actually says that $f$ is the Radon-Nikodym derivative of the law of $X$ with respect to the Lebesgue measure - in other words, the density. Thus the notation $p(dx)=f(x)dx$ is correct when denoting by $p$ the distribution of $X$. This notation is also coherent with the fact that $\Pr(X \in [x, x+h]) \approx hf(x)$ when $h$ is small.
What does Jaynes' continuous pdf notation "$g(x)~\mathrm dx$" actually mean? The notation $\Pr(X \in dx)=f(x)dx$ is a standard notation to say that the law of the random variable $X$ has density $f$. Note that this notation is coherent with $\frac{\Pr(X\in dx)}{dx}=f(x)$ which
31,376
How to compute $\mathbb P( 3 X_{(1)} \geq X_{(2)}+X_{(3)})$ for order statistics of a uniform distribution?
Write the order statistics as $(x_1,x_2,x_3,x_4)$, $0 \le x_1 \le x_2 \le x_3 \le x_4 \le 1$. Begin by noting that $x_1 \le x_2$ implies $$\Pr[3x_1 \ge x_2+x_3] = 1 - \Pr[3x_1 \lt x_2+x_3] = 1 - \Pr[x_1 \le \min(x_2, \frac{x_2+x_3}{3})].$$ This last event breaks into two disjoint events depending on which of $x_2$ and $(x_2+x_3)/2$ is the larger: $$\eqalign{ \Pr[x_1 \le \min(x_2, \frac{x_2+x_3}{3})] &= \Pr[x_2 \le \frac{x_3}{2},\quad x_1 \le x_2] \\ &+ \Pr[\frac{x_3}{2} \le x_2 \le x_3,\quad x_1 \le \frac{x_2+x_3}{3}]. }$$ Because the joint distribution is uniform on the set $0 \le x_1 \le x_2 \le x_3 \le x_4 \le 1$, with density $4! dx_4 dx_3 dx_2 dx_1$, $$ \Pr[x_2 \le \frac{x_3}{2},\quad x_1 \le x_2] = 4! \int_0^1 dx_4 \int_0^{x_4} dx_3 \int_0^{x_3/2} dx_2 \int_0^{x_2} dx_1 = \frac{1}{4} $$ and $$ \Pr[\frac{x_3}{2} \le x_2 \le x_3,\quad x_1 \le \frac{x_2+x_3}{3}]=4! \int_0^1 dx_4 \int_0^{x_4} dx_3 \int_{x_3/2}^{x_3} dx_2 \int_0^{(x_2+x_3)/2} dx_1 = \frac{7}{12}. $$ (Each integral is straightforward to perform as an iterated integral; only polynomial integrations are involved.) The desired probability therefore equals $1 - (1/4 + 7/12)$ = $1/6$. Edit A cleverer solution (which simplifies the work) derives from the recognition that when $y_j$ have iid Exponential distributions, $1\le j\le n+1$, then (writing $y_1+y_2+\cdots+y_{n+1} = Y\ $), the scaled partial sums $$x_i = \sum_{j=1}^{i}y_j/Y,$$ $1\le i\le n$, are distributed like the uniform order statistics. Because $Y$ is almost surely positive, it follows easily that for any $n\ge 3$, $$\eqalign{ \Pr[3x_1\ge x_2+x_3] &= \Pr[\frac{3y_1}{Y}\ge\frac{y_1+y_2}{Y}+\frac{y_1+y_2+y_3}{Y}]\\ &=\Pr[3y_1\ge(y_1+y_2)+(y_1+y_2+y_3)]\\ &= \Pr[y_1\ge 2y_2+y_3]\\ &= \int_0^\infty \exp(-y_3)\int_0^\infty \exp(-y_2) \int_{2y_2+y_3}^\infty \exp(-y_1) dy_1 dy_2 dy_3\\ &= \int_0^\infty \exp(-y_3)\int_0^\infty \exp(-y_2)\left[\exp(-2y_2-y_3)\right]dy_2 dy_3 \\ &= \int_0^\infty \exp(-2y_3)dy_3 \int_0^\infty \exp(-3y_2)dy_2 \\ &= \frac{1}{2} \frac{1}{3} = \frac{1}{6}. }$$
How to compute $\mathbb P( 3 X_{(1)} \geq X_{(2)}+X_{(3)})$ for order statistics of a uniform distri
Write the order statistics as $(x_1,x_2,x_3,x_4)$, $0 \le x_1 \le x_2 \le x_3 \le x_4 \le 1$. Begin by noting that $x_1 \le x_2$ implies $$\Pr[3x_1 \ge x_2+x_3] = 1 - \Pr[3x_1 \lt x_2+x_3] = 1 - \Pr
How to compute $\mathbb P( 3 X_{(1)} \geq X_{(2)}+X_{(3)})$ for order statistics of a uniform distribution? Write the order statistics as $(x_1,x_2,x_3,x_4)$, $0 \le x_1 \le x_2 \le x_3 \le x_4 \le 1$. Begin by noting that $x_1 \le x_2$ implies $$\Pr[3x_1 \ge x_2+x_3] = 1 - \Pr[3x_1 \lt x_2+x_3] = 1 - \Pr[x_1 \le \min(x_2, \frac{x_2+x_3}{3})].$$ This last event breaks into two disjoint events depending on which of $x_2$ and $(x_2+x_3)/2$ is the larger: $$\eqalign{ \Pr[x_1 \le \min(x_2, \frac{x_2+x_3}{3})] &= \Pr[x_2 \le \frac{x_3}{2},\quad x_1 \le x_2] \\ &+ \Pr[\frac{x_3}{2} \le x_2 \le x_3,\quad x_1 \le \frac{x_2+x_3}{3}]. }$$ Because the joint distribution is uniform on the set $0 \le x_1 \le x_2 \le x_3 \le x_4 \le 1$, with density $4! dx_4 dx_3 dx_2 dx_1$, $$ \Pr[x_2 \le \frac{x_3}{2},\quad x_1 \le x_2] = 4! \int_0^1 dx_4 \int_0^{x_4} dx_3 \int_0^{x_3/2} dx_2 \int_0^{x_2} dx_1 = \frac{1}{4} $$ and $$ \Pr[\frac{x_3}{2} \le x_2 \le x_3,\quad x_1 \le \frac{x_2+x_3}{3}]=4! \int_0^1 dx_4 \int_0^{x_4} dx_3 \int_{x_3/2}^{x_3} dx_2 \int_0^{(x_2+x_3)/2} dx_1 = \frac{7}{12}. $$ (Each integral is straightforward to perform as an iterated integral; only polynomial integrations are involved.) The desired probability therefore equals $1 - (1/4 + 7/12)$ = $1/6$. Edit A cleverer solution (which simplifies the work) derives from the recognition that when $y_j$ have iid Exponential distributions, $1\le j\le n+1$, then (writing $y_1+y_2+\cdots+y_{n+1} = Y\ $), the scaled partial sums $$x_i = \sum_{j=1}^{i}y_j/Y,$$ $1\le i\le n$, are distributed like the uniform order statistics. Because $Y$ is almost surely positive, it follows easily that for any $n\ge 3$, $$\eqalign{ \Pr[3x_1\ge x_2+x_3] &= \Pr[\frac{3y_1}{Y}\ge\frac{y_1+y_2}{Y}+\frac{y_1+y_2+y_3}{Y}]\\ &=\Pr[3y_1\ge(y_1+y_2)+(y_1+y_2+y_3)]\\ &= \Pr[y_1\ge 2y_2+y_3]\\ &= \int_0^\infty \exp(-y_3)\int_0^\infty \exp(-y_2) \int_{2y_2+y_3}^\infty \exp(-y_1) dy_1 dy_2 dy_3\\ &= \int_0^\infty \exp(-y_3)\int_0^\infty \exp(-y_2)\left[\exp(-2y_2-y_3)\right]dy_2 dy_3 \\ &= \int_0^\infty \exp(-2y_3)dy_3 \int_0^\infty \exp(-3y_2)dy_2 \\ &= \frac{1}{2} \frac{1}{3} = \frac{1}{6}. }$$
How to compute $\mathbb P( 3 X_{(1)} \geq X_{(2)}+X_{(3)})$ for order statistics of a uniform distri Write the order statistics as $(x_1,x_2,x_3,x_4)$, $0 \le x_1 \le x_2 \le x_3 \le x_4 \le 1$. Begin by noting that $x_1 \le x_2$ implies $$\Pr[3x_1 \ge x_2+x_3] = 1 - \Pr[3x_1 \lt x_2+x_3] = 1 - \Pr
31,377
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it?
Requirements for distances depend on method of hierarchical clustering. Single, complete, average methods need distances to be no-negative and symmetric. Ward, centroid, median methods need (squared) euclidean (which is even narrower definition than metric) distances to produce geometrically meaningful results. (One can check if his/her distance matrix is euclidean by doubly centering it [see my reply here] and looking at the eigenvalues; if no negative eigenvalues found then the distances do converge in euclidean space.)
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it?
Requirements for distances depend on method of hierarchical clustering. Single, complete, average methods need distances to be no-negative and symmetric. Ward, centroid, median methods need (squared)
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it? Requirements for distances depend on method of hierarchical clustering. Single, complete, average methods need distances to be no-negative and symmetric. Ward, centroid, median methods need (squared) euclidean (which is even narrower definition than metric) distances to produce geometrically meaningful results. (One can check if his/her distance matrix is euclidean by doubly centering it [see my reply here] and looking at the eigenvalues; if no negative eigenvalues found then the distances do converge in euclidean space.)
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it? Requirements for distances depend on method of hierarchical clustering. Single, complete, average methods need distances to be no-negative and symmetric. Ward, centroid, median methods need (squared)
31,378
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it?
No, the distance doesn't have to be a metric. It can, for instance, be an ultrametric: $$d(A, B) \le \max(d(A, C), d(B, C))$$ Ultrametric distances obtained from successive steps in the clustering algorithm can be represented using dendrograms, which you may have seen in this context.
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it?
No, the distance doesn't have to be a metric. It can, for instance, be an ultrametric: $$d(A, B) \le \max(d(A, C), d(B, C))$$ Ultrametric distances obtained from successive steps in the clustering alg
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it? No, the distance doesn't have to be a metric. It can, for instance, be an ultrametric: $$d(A, B) \le \max(d(A, C), d(B, C))$$ Ultrametric distances obtained from successive steps in the clustering algorithm can be represented using dendrograms, which you may have seen in this context.
Does a distance have to be a "metric" for an hierarchical clustering to be valid on it? No, the distance doesn't have to be a metric. It can, for instance, be an ultrametric: $$d(A, B) \le \max(d(A, C), d(B, C))$$ Ultrametric distances obtained from successive steps in the clustering alg
31,379
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
A contingency table should contain all the mutually exclusive categories on both axes. Inshore/Midchannel/Offshore look fine, however unless "less than 100% mortality" means "100% survival" in this biological setting you may need to construct tables that account for all the cases observed or explain why you restrict your analysis to the extreme ends of the sample. As 100% survival means 0% mortality, you could have a table with columns 100%=mortality / 100%>mortality>0% / mortality=0%. In this case you wouldn't any more compare percentages, but compare ordinal mortality measures across three site type categories. (What about using the original percentage values instead of categories?) A version of Kruskal-Wallis test may be appropriate here that takes ties appropriately into consideration (maybe a permutation test). There are established post hoc tests for the Kruskal-Wallis test: 1, 2, 3. (A resampling approach may help tackling with ties.) Logistic regression and binomial regression may be even better as they not only give you p values, but also useful estimates and confidence intervals of the effect sizes. However to set up those models more details would be needed concerning the 100%>mortality>0% sites.
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
A contingency table should contain all the mutually exclusive categories on both axes. Inshore/Midchannel/Offshore look fine, however unless "less than 100% mortality" means "100% survival" in this bi
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? A contingency table should contain all the mutually exclusive categories on both axes. Inshore/Midchannel/Offshore look fine, however unless "less than 100% mortality" means "100% survival" in this biological setting you may need to construct tables that account for all the cases observed or explain why you restrict your analysis to the extreme ends of the sample. As 100% survival means 0% mortality, you could have a table with columns 100%=mortality / 100%>mortality>0% / mortality=0%. In this case you wouldn't any more compare percentages, but compare ordinal mortality measures across three site type categories. (What about using the original percentage values instead of categories?) A version of Kruskal-Wallis test may be appropriate here that takes ties appropriately into consideration (maybe a permutation test). There are established post hoc tests for the Kruskal-Wallis test: 1, 2, 3. (A resampling approach may help tackling with ties.) Logistic regression and binomial regression may be even better as they not only give you p values, but also useful estimates and confidence intervals of the effect sizes. However to set up those models more details would be needed concerning the 100%>mortality>0% sites.
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? A contingency table should contain all the mutually exclusive categories on both axes. Inshore/Midchannel/Offshore look fine, however unless "less than 100% mortality" means "100% survival" in this bi
31,380
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
I am going to assume that "100% survival" means that your sites only contained a single organism. so 30 means 30 organisms died, and 31 means 31 organisms didn't. Based on this the chi-square should be fine, but it will only tell which hypothesis are not supported by the data - it won't tell you if two reasonable hypothesis are better or not. I present a probability analysis which does extract this information - it agrees with the chi-square test, but it gives you more information than the chi-square test, and a better way to present the results. The model is a bernouli model for the indicator of "death", $Y_{ij}\sim Bin(1,\theta_{ij})$ ($i$ denotes the cell of the $2\times 3$ table, and $j$ denotes the individual unit within the cell). There are two global assumption underlying the chi-square test: within a given cell of the table, the $\theta_{ij}$ are all equal, that is $\theta_{ij}=\theta_{ik}=\theta_{i}$ the $Y_{ij}$ are statistically independent, given $\theta_{i}$. This means that the probability parameters tell you everything about $Y_{ij}$ - all other information is irrelevant if you know $\theta_{i}$ Denote $X_{i}$ as the sum of $Y_{ij}$, (so $X_{1}=30,X_{2}=10,X_{3}=1$) and let $N_{i}$ be the group size (so $N_{1}=61,N_{2}=30,N_{3}=11$). Now we have a hypothesis to test: $$H_{A}:\theta_{1}=\theta_{2},\theta_{1}=\theta_{3},\theta_{2}=\theta_{3}$$ But what are the alternatives? I would say the other possible combinations of equal or not equal. $$H_{B1}:\theta_{1}\neq\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}=\theta_{3}$$ $$H_{B2}:\theta_{1}\neq\theta_{2},\theta_{1}=\theta_{3},\theta_{2}\neq\theta_{3}$$ $$H_{B3}:\theta_{1}=\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}\neq\theta_{3}$$ $$H_{C}:\theta_{1}\neq\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}\neq\theta_{3}$$ One of these hypothesis has to be true, given the "global" assumptions above. But note that none of these specify specific values for the rates - so they must be integrated out. Now given that $H_{A}$ is true, we only have one parameter (because all are equal), and the uniform prior is a conservative choice, denote this and the global assumptions by $I_{0}$. so we have: $$P(X_{1},X_{2},X_{3}|N_{1},N_{2},N_{3},H_{A},I_{0})=\int_{0}^{1}P(X_{1},X_{2},X_{3},\theta|N_{1},N_{2},N_{3},H_{A},I_{0})d\theta$$ $$={N_{1} \choose X_{1}}{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}\int_{0}^{1}\theta^{X_{1}+X_{2}+X_{3}}(1-\theta)^{N_{1}+N_{2}+N_{3}-X_{1}-X_{2}-X_{3}}d\theta$$ $$=\frac{{N_{1} \choose X_{1}}{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}}{(N_{1}+N_{2}+N_{3}+1){N_{1}+N_{2}+N_{3} \choose X_{1}+X_{2}+X_{3}}}$$ Which is a hypergeometric distribution divided by a constant. Similarly for $H_{B1}$ we will have: $$P(X_{1},X_{2},X_{3}|N_{1},N_{2},N_{3},H_{B1},I_{0})=\int_{0}^{1}P(X_{1},X_{2},X_{3},\theta_{1}\theta_{2}|N_{1},N_{2},N_{3},H_{B1},I_{0})d\theta_{1}d\theta_{2}$$ $$=\frac{{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}}{(N_{1}+1)(N_{2}+N_{3}+1){N_{2}+N_{3} \choose X_{2}+X_{3}}}$$ You can see the pattern for the others. We can calculate the odds for say $H_{A}\;vs\;H_{B1}$ by simply dividing the above two expressions. The answer is about $4$, which means the data support $H_{A}$ over $H_{B1}$ by about a factor of $4$ - fairly weak evidence in favour of equal rates. The other probabilities are given below. $$\begin{array}{c|c} Hypothesis & probability \\ \hline (H_{A}|D) & 0.018982265 \\ (H_{B1}|D) & 0.004790669 \\ (H_{B2}|D) & 0.051620022 \\ (H_{B3}|D) & 0.484155874 \\ (H_{C}|D) & 0.440451171 \\ \end{array} $$ This is showing strong evidence against equal rates, but not in strong evidence favour of a defintie alternative. It seems like there is strong evidence that the "offshore" rate is different to the other two rates, but inconclusive evidence as to whether "inshore" and "mid-channel" rates differ. This is what the chi-square test won't tell you - it only tells you that hypothesis $A$ is "crap" but not what alternative to put in its place
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
I am going to assume that "100% survival" means that your sites only contained a single organism. so 30 means 30 organisms died, and 31 means 31 organisms didn't. Based on this the chi-square should
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? I am going to assume that "100% survival" means that your sites only contained a single organism. so 30 means 30 organisms died, and 31 means 31 organisms didn't. Based on this the chi-square should be fine, but it will only tell which hypothesis are not supported by the data - it won't tell you if two reasonable hypothesis are better or not. I present a probability analysis which does extract this information - it agrees with the chi-square test, but it gives you more information than the chi-square test, and a better way to present the results. The model is a bernouli model for the indicator of "death", $Y_{ij}\sim Bin(1,\theta_{ij})$ ($i$ denotes the cell of the $2\times 3$ table, and $j$ denotes the individual unit within the cell). There are two global assumption underlying the chi-square test: within a given cell of the table, the $\theta_{ij}$ are all equal, that is $\theta_{ij}=\theta_{ik}=\theta_{i}$ the $Y_{ij}$ are statistically independent, given $\theta_{i}$. This means that the probability parameters tell you everything about $Y_{ij}$ - all other information is irrelevant if you know $\theta_{i}$ Denote $X_{i}$ as the sum of $Y_{ij}$, (so $X_{1}=30,X_{2}=10,X_{3}=1$) and let $N_{i}$ be the group size (so $N_{1}=61,N_{2}=30,N_{3}=11$). Now we have a hypothesis to test: $$H_{A}:\theta_{1}=\theta_{2},\theta_{1}=\theta_{3},\theta_{2}=\theta_{3}$$ But what are the alternatives? I would say the other possible combinations of equal or not equal. $$H_{B1}:\theta_{1}\neq\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}=\theta_{3}$$ $$H_{B2}:\theta_{1}\neq\theta_{2},\theta_{1}=\theta_{3},\theta_{2}\neq\theta_{3}$$ $$H_{B3}:\theta_{1}=\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}\neq\theta_{3}$$ $$H_{C}:\theta_{1}\neq\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}\neq\theta_{3}$$ One of these hypothesis has to be true, given the "global" assumptions above. But note that none of these specify specific values for the rates - so they must be integrated out. Now given that $H_{A}$ is true, we only have one parameter (because all are equal), and the uniform prior is a conservative choice, denote this and the global assumptions by $I_{0}$. so we have: $$P(X_{1},X_{2},X_{3}|N_{1},N_{2},N_{3},H_{A},I_{0})=\int_{0}^{1}P(X_{1},X_{2},X_{3},\theta|N_{1},N_{2},N_{3},H_{A},I_{0})d\theta$$ $$={N_{1} \choose X_{1}}{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}\int_{0}^{1}\theta^{X_{1}+X_{2}+X_{3}}(1-\theta)^{N_{1}+N_{2}+N_{3}-X_{1}-X_{2}-X_{3}}d\theta$$ $$=\frac{{N_{1} \choose X_{1}}{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}}{(N_{1}+N_{2}+N_{3}+1){N_{1}+N_{2}+N_{3} \choose X_{1}+X_{2}+X_{3}}}$$ Which is a hypergeometric distribution divided by a constant. Similarly for $H_{B1}$ we will have: $$P(X_{1},X_{2},X_{3}|N_{1},N_{2},N_{3},H_{B1},I_{0})=\int_{0}^{1}P(X_{1},X_{2},X_{3},\theta_{1}\theta_{2}|N_{1},N_{2},N_{3},H_{B1},I_{0})d\theta_{1}d\theta_{2}$$ $$=\frac{{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}}{(N_{1}+1)(N_{2}+N_{3}+1){N_{2}+N_{3} \choose X_{2}+X_{3}}}$$ You can see the pattern for the others. We can calculate the odds for say $H_{A}\;vs\;H_{B1}$ by simply dividing the above two expressions. The answer is about $4$, which means the data support $H_{A}$ over $H_{B1}$ by about a factor of $4$ - fairly weak evidence in favour of equal rates. The other probabilities are given below. $$\begin{array}{c|c} Hypothesis & probability \\ \hline (H_{A}|D) & 0.018982265 \\ (H_{B1}|D) & 0.004790669 \\ (H_{B2}|D) & 0.051620022 \\ (H_{B3}|D) & 0.484155874 \\ (H_{C}|D) & 0.440451171 \\ \end{array} $$ This is showing strong evidence against equal rates, but not in strong evidence favour of a defintie alternative. It seems like there is strong evidence that the "offshore" rate is different to the other two rates, but inconclusive evidence as to whether "inshore" and "mid-channel" rates differ. This is what the chi-square test won't tell you - it only tells you that hypothesis $A$ is "crap" but not what alternative to put in its place
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? I am going to assume that "100% survival" means that your sites only contained a single organism. so 30 means 30 organisms died, and 31 means 31 organisms didn't. Based on this the chi-square should
31,381
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
Here is the code to do the chi square tests as well as generate a variety of test statistics. However, statistical tests of association of the table margins are useless here; the answer is obvious. No one does a statistical test to see if summer is hotter than winter. Chompy<-matrix(c(30,10,1,31,20,10), 3, 2) Chompy chisq.test(Chompy) chisq.test(Chompy, simulate.p.value = TRUE, B = 10000) chompy2<-data.frame(matrix(c(30,10,1,31,20,10,1,2,1,2,1,2,1,2,3,1,2,3), 6,3)) chompy2 chompy2$X2<-factor(chompy2$X2) chompy2$X3<-factor(chompy2$X3) summary(fit1<-glm(X1~X2+X3, data=chompy2, family=poisson)) summary(fit2<-glm(X1~X2*X3, data=chompy2, family=poisson)) #oversaturated summary(fit3<-glm(X1~1, data=chompy2, family=poisson)) #null anova(fit3,fit1) library(lmtest) waldtest(fit1) waldtest(fit2) #oversaturated kruskal.test(X1~X2+X3, data=chompy2) kruskal.test(X1~X2*X3, data=chompy2)
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
Here is the code to do the chi square tests as well as generate a variety of test statistics. However, statistical tests of association of the table margins are useless here; the answer is obvious. No
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? Here is the code to do the chi square tests as well as generate a variety of test statistics. However, statistical tests of association of the table margins are useless here; the answer is obvious. No one does a statistical test to see if summer is hotter than winter. Chompy<-matrix(c(30,10,1,31,20,10), 3, 2) Chompy chisq.test(Chompy) chisq.test(Chompy, simulate.p.value = TRUE, B = 10000) chompy2<-data.frame(matrix(c(30,10,1,31,20,10,1,2,1,2,1,2,1,2,3,1,2,3), 6,3)) chompy2 chompy2$X2<-factor(chompy2$X2) chompy2$X3<-factor(chompy2$X3) summary(fit1<-glm(X1~X2+X3, data=chompy2, family=poisson)) summary(fit2<-glm(X1~X2*X3, data=chompy2, family=poisson)) #oversaturated summary(fit3<-glm(X1~1, data=chompy2, family=poisson)) #null anova(fit3,fit1) library(lmtest) waldtest(fit1) waldtest(fit2) #oversaturated kruskal.test(X1~X2+X3, data=chompy2) kruskal.test(X1~X2*X3, data=chompy2)
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? Here is the code to do the chi square tests as well as generate a variety of test statistics. However, statistical tests of association of the table margins are useless here; the answer is obvious. No
31,382
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
I believe you could use the "simultaneous confidence intervals" for doing multiple comparisons. The reference is Agresti et al. 2008 Simultaneous confidence intervals for comparing binomial parameters. Biometrics 64 1270-1275. You could find the corresponding R code in http://www.stat.ufl.edu/~aa/cda/software.html
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
I believe you could use the "simultaneous confidence intervals" for doing multiple comparisons. The reference is Agresti et al. 2008 Simultaneous confidence intervals for comparing binomial parameters
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? I believe you could use the "simultaneous confidence intervals" for doing multiple comparisons. The reference is Agresti et al. 2008 Simultaneous confidence intervals for comparing binomial parameters. Biometrics 64 1270-1275. You could find the corresponding R code in http://www.stat.ufl.edu/~aa/cda/software.html
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? I believe you could use the "simultaneous confidence intervals" for doing multiple comparisons. The reference is Agresti et al. 2008 Simultaneous confidence intervals for comparing binomial parameters
31,383
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
You can do proportion testing for 100%Mortality vs totals: Inshore Midchannel Offshore Inshore% Midchannel% Offshore% Pvalue FullMortality 30 10 1 49.180 33.333 9.091 0.029 FullSurvival 31 20 10 Total 61 30 11 P=0.029 indicates that there is a significant difference between different sites for 100%Mortality.
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?
You can do proportion testing for 100%Mortality vs totals: Inshore Midchannel Offshore Inshore% Midchannel% Offshore% Pvalue FullMortality 30 10 1 49.
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? You can do proportion testing for 100%Mortality vs totals: Inshore Midchannel Offshore Inshore% Midchannel% Offshore% Pvalue FullMortality 30 10 1 49.180 33.333 9.091 0.029 FullSurvival 31 20 10 Total 61 30 11 P=0.029 indicates that there is a significant difference between different sites for 100%Mortality.
How to carry out multiple post-hoc chi-square tests on a 2 X 3 table? You can do proportion testing for 100%Mortality vs totals: Inshore Midchannel Offshore Inshore% Midchannel% Offshore% Pvalue FullMortality 30 10 1 49.
31,384
How do you compute confidence intervals for positive predictive value?
Your first SE formula is correct. The second SE formula which concerns sensitivity should have the total number of positive cases in the denominator: $$SE_\text{sensitivity} = \sqrt{ \frac{SENS(1-SENS)}{TP+FN}} $$ The logic is that sensitivity = $\frac{TP}{TP+FN}$, and the denominator in the SE formula is the same. As @onestop pointed out in their comment methods of calculating a binomial proportion confidence interval can be used here. The method you follow is the normal approximation, however unless you have really large counts other methods like the Wilson interval will be more accurate.
How do you compute confidence intervals for positive predictive value?
Your first SE formula is correct. The second SE formula which concerns sensitivity should have the total number of positive cases in the denominator: $$SE_\text{sensitivity} = \sqrt{ \frac{SENS(1-SE
How do you compute confidence intervals for positive predictive value? Your first SE formula is correct. The second SE formula which concerns sensitivity should have the total number of positive cases in the denominator: $$SE_\text{sensitivity} = \sqrt{ \frac{SENS(1-SENS)}{TP+FN}} $$ The logic is that sensitivity = $\frac{TP}{TP+FN}$, and the denominator in the SE formula is the same. As @onestop pointed out in their comment methods of calculating a binomial proportion confidence interval can be used here. The method you follow is the normal approximation, however unless you have really large counts other methods like the Wilson interval will be more accurate.
How do you compute confidence intervals for positive predictive value? Your first SE formula is correct. The second SE formula which concerns sensitivity should have the total number of positive cases in the denominator: $$SE_\text{sensitivity} = \sqrt{ \frac{SENS(1-SE
31,385
Advice on explaining heterogeneity / heteroscedasticty
Allometry would be a good place to start that will be familiar to biologists. Logaritmic transformations are often used in allometry because the data have a power-law form, but also because the noise process is heteroskedastic (as the variability is proportional to size). For an example where this has caused a severe problem, see "Allometric equations for predicting body mass of dinosaurs", where the conclusion that dinosaurs were only half the size previously though was incorrect because an invalid assumtion of homoscedasticity was made (see the correspondance for details).
Advice on explaining heterogeneity / heteroscedasticty
Allometry would be a good place to start that will be familiar to biologists. Logaritmic transformations are often used in allometry because the data have a power-law form, but also because the noise
Advice on explaining heterogeneity / heteroscedasticty Allometry would be a good place to start that will be familiar to biologists. Logaritmic transformations are often used in allometry because the data have a power-law form, but also because the noise process is heteroskedastic (as the variability is proportional to size). For an example where this has caused a severe problem, see "Allometric equations for predicting body mass of dinosaurs", where the conclusion that dinosaurs were only half the size previously though was incorrect because an invalid assumtion of homoscedasticity was made (see the correspondance for details).
Advice on explaining heterogeneity / heteroscedasticty Allometry would be a good place to start that will be familiar to biologists. Logaritmic transformations are often used in allometry because the data have a power-law form, but also because the noise
31,386
Advice on explaining heterogeneity / heteroscedasticty
One option is to use a simulation. So set up a model where you specifically specify the heterogeneity suppose as $var(\alpha_i)=\overline{X}_i^2\sigma^2_u$. Then generate your data from this model, taking random intercepts as a simple example. $$\alpha_i=\overline{X}_i u_i\;\;\;\;\;\; u_i\sim N(0,\sigma^2_u)$$ $$Y_ij=\alpha_{i}+\beta X_{ij} + e_{ij}\;\;\;\;\;\; e_{ij}\sim N(0,\sigma^2_e)$$ (hope this notation makes sense). I believe playing around with a set-up such as this will help you answer question 2). So you would fit this model using a random intercept, when in fact it should be a random slope (which gives you a partial answer to question 3 - random intercepts can account for "fanning" to a degree - this is "level 2 fanning"). The idea of the above is to try as hard as you can to break your modeling method - try extreme conditions consistent with what you know about the data, and see what happens. If you are struggling to find these conditions, then don't worry. I did a quick check on heteroscedasticity for OLS, and it doesn't seem to affect the estimated betas too much. To me it just seems like heteroscedasticity will in some places by giving an under-estimate of the likely error, and in other places it will give an over-estimate of the likely error (in predictive terms). See below: awaiting plot of data here, user currently frustrated with computers And one thing which I always find amusing is this "non-normality of the data" that people worry about. The data does not need to be normally distributed, but the error term does. If this were not true, then GLMs would not work - GLMs use a normal approximation to the likelihood function to estimate the parameters, as do GLMMs. So I'd say if estimating fixed effect parameters is the main goal then not much to worry about, but you may get better results for prediction by taking heteroscedasticity into account.
Advice on explaining heterogeneity / heteroscedasticty
One option is to use a simulation. So set up a model where you specifically specify the heterogeneity suppose as $var(\alpha_i)=\overline{X}_i^2\sigma^2_u$. Then generate your data from this model,
Advice on explaining heterogeneity / heteroscedasticty One option is to use a simulation. So set up a model where you specifically specify the heterogeneity suppose as $var(\alpha_i)=\overline{X}_i^2\sigma^2_u$. Then generate your data from this model, taking random intercepts as a simple example. $$\alpha_i=\overline{X}_i u_i\;\;\;\;\;\; u_i\sim N(0,\sigma^2_u)$$ $$Y_ij=\alpha_{i}+\beta X_{ij} + e_{ij}\;\;\;\;\;\; e_{ij}\sim N(0,\sigma^2_e)$$ (hope this notation makes sense). I believe playing around with a set-up such as this will help you answer question 2). So you would fit this model using a random intercept, when in fact it should be a random slope (which gives you a partial answer to question 3 - random intercepts can account for "fanning" to a degree - this is "level 2 fanning"). The idea of the above is to try as hard as you can to break your modeling method - try extreme conditions consistent with what you know about the data, and see what happens. If you are struggling to find these conditions, then don't worry. I did a quick check on heteroscedasticity for OLS, and it doesn't seem to affect the estimated betas too much. To me it just seems like heteroscedasticity will in some places by giving an under-estimate of the likely error, and in other places it will give an over-estimate of the likely error (in predictive terms). See below: awaiting plot of data here, user currently frustrated with computers And one thing which I always find amusing is this "non-normality of the data" that people worry about. The data does not need to be normally distributed, but the error term does. If this were not true, then GLMs would not work - GLMs use a normal approximation to the likelihood function to estimate the parameters, as do GLMMs. So I'd say if estimating fixed effect parameters is the main goal then not much to worry about, but you may get better results for prediction by taking heteroscedasticity into account.
Advice on explaining heterogeneity / heteroscedasticty One option is to use a simulation. So set up a model where you specifically specify the heterogeneity suppose as $var(\alpha_i)=\overline{X}_i^2\sigma^2_u$. Then generate your data from this model,
31,387
Advice on explaining heterogeneity / heteroscedasticty
The best FREE online resource I know for learning about heteroskedasticity is Prof. Thoma's ECON 421 lectures from 2011. Specifically lectures 1 - 7. His lectures are very organized and easy to follow along regardless of your discipline. Here is the first lecture. You can Find the rest of the lectures from the Winter 2011 semester here as Well. http://www.youtube.com/watch?v=WK03XgoVsPM Also, the corresponding website for Prof. Thoma's Econ 421 course has Homework Problems and as well as their solutions. For solutions that require software, the solution is detailed step-by-step using a combination of text, formulas, and screen shots from Eviews. Eventhough the the steps used to solve the homework problems are detailed using screen shots from E-views, the solutions easily translate well into other statistical packages such as STATA or R stats. There are no Solutions listed for the Homeworks from the 2011 semester, which is Prof. Thoma's last video taped semester. However there are homeworks available for his Winter 2012 semester. Here is a link to the Homework solutions section of Prof. Thomas Winter 2012 421 class. Specifically here is the Solution to Homework 3 where heteroskedasticity is introduced to the homework sets. http://economistsview.typepad.com/economics421/2012/02/solution-to-homework-3.html
Advice on explaining heterogeneity / heteroscedasticty
The best FREE online resource I know for learning about heteroskedasticity is Prof. Thoma's ECON 421 lectures from 2011. Specifically lectures 1 - 7. His lectures are very organized and easy to follo
Advice on explaining heterogeneity / heteroscedasticty The best FREE online resource I know for learning about heteroskedasticity is Prof. Thoma's ECON 421 lectures from 2011. Specifically lectures 1 - 7. His lectures are very organized and easy to follow along regardless of your discipline. Here is the first lecture. You can Find the rest of the lectures from the Winter 2011 semester here as Well. http://www.youtube.com/watch?v=WK03XgoVsPM Also, the corresponding website for Prof. Thoma's Econ 421 course has Homework Problems and as well as their solutions. For solutions that require software, the solution is detailed step-by-step using a combination of text, formulas, and screen shots from Eviews. Eventhough the the steps used to solve the homework problems are detailed using screen shots from E-views, the solutions easily translate well into other statistical packages such as STATA or R stats. There are no Solutions listed for the Homeworks from the 2011 semester, which is Prof. Thoma's last video taped semester. However there are homeworks available for his Winter 2012 semester. Here is a link to the Homework solutions section of Prof. Thomas Winter 2012 421 class. Specifically here is the Solution to Homework 3 where heteroskedasticity is introduced to the homework sets. http://economistsview.typepad.com/economics421/2012/02/solution-to-homework-3.html
Advice on explaining heterogeneity / heteroscedasticty The best FREE online resource I know for learning about heteroskedasticity is Prof. Thoma's ECON 421 lectures from 2011. Specifically lectures 1 - 7. His lectures are very organized and easy to follo
31,388
Should I re-shuffle my data?
As you already use a holdout sample, I would say you should keep it and build your new models on the same training sample so that all models will consider the same relationships between features. In addition, if you perform feature selection, the samples must be left out before any of these filtering stages; that is, feature selection must be included in the cross-validation loop. Of note, there are more powerful methods than a 0.67/0.33 split for model selection, namely k-fold cross-validation or leave-one-out. See e.g. The Elements of Statistical Learning (§7.10, pp. 241-248), www.modelselection.org or A survey of cross-validation procedures for model selection by Arlot and Celisse (more advanced mathematical background required).
Should I re-shuffle my data?
As you already use a holdout sample, I would say you should keep it and build your new models on the same training sample so that all models will consider the same relationships between features. In a
Should I re-shuffle my data? As you already use a holdout sample, I would say you should keep it and build your new models on the same training sample so that all models will consider the same relationships between features. In addition, if you perform feature selection, the samples must be left out before any of these filtering stages; that is, feature selection must be included in the cross-validation loop. Of note, there are more powerful methods than a 0.67/0.33 split for model selection, namely k-fold cross-validation or leave-one-out. See e.g. The Elements of Statistical Learning (§7.10, pp. 241-248), www.modelselection.org or A survey of cross-validation procedures for model selection by Arlot and Celisse (more advanced mathematical background required).
Should I re-shuffle my data? As you already use a holdout sample, I would say you should keep it and build your new models on the same training sample so that all models will consider the same relationships between features. In a
31,389
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions?
It seems to me that CV is inappropriate here. I think you may be better off separating the change in location from the change in dispersion. In addition, the distributions you mention in your comment to the question are, for most parameter values, skewed (positively, except for the beta distribution). That makes me question whether the standard deviation is the best choice for a measure of dispersion; perhaps the interquartile range (IQR) might be better, or possibly the median absolute deviation? Similarly, rather than the mean, I might consider the median or the mode as the measure of location. The choice might in practice be determined by ease of computation as well as the field of application, the details of the model... Say you choose to use the IQR and the mode. You could summarise the change in dispersion using the ratio of posterior to prior IQRs, probably plotted on a log scale as that's usually appropriate for ratios. You could summarise the change in location using the ratio of the difference between posterior and prior modes to the prior IQR, or to the posterior IQR, or perhaps to the geometric mean of the posterior and prior IQRs. These are just some quick ideas that came to mind. I can't claim any strong underpinnings for them, or even any great personal attachment to them.
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions?
It seems to me that CV is inappropriate here. I think you may be better off separating the change in location from the change in dispersion. In addition, the distributions you mention in your comment
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions? It seems to me that CV is inappropriate here. I think you may be better off separating the change in location from the change in dispersion. In addition, the distributions you mention in your comment to the question are, for most parameter values, skewed (positively, except for the beta distribution). That makes me question whether the standard deviation is the best choice for a measure of dispersion; perhaps the interquartile range (IQR) might be better, or possibly the median absolute deviation? Similarly, rather than the mean, I might consider the median or the mode as the measure of location. The choice might in practice be determined by ease of computation as well as the field of application, the details of the model... Say you choose to use the IQR and the mode. You could summarise the change in dispersion using the ratio of posterior to prior IQRs, probably plotted on a log scale as that's usually appropriate for ratios. You could summarise the change in location using the ratio of the difference between posterior and prior modes to the prior IQR, or to the posterior IQR, or perhaps to the geometric mean of the posterior and prior IQRs. These are just some quick ideas that came to mind. I can't claim any strong underpinnings for them, or even any great personal attachment to them.
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions? It seems to me that CV is inappropriate here. I think you may be better off separating the change in location from the change in dispersion. In addition, the distributions you mention in your comment
31,390
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions?
Some alternatives, which have the same 'flavor' as CV are: The coefficient of L-variation, see e.g. Viglione. The second sample L-moment takes the place of the sample standard deviation. The $\gamma$-Winsorized standard deviation divided by the $\gamma$-trimmed mean. You probably want to divide this by $1 - 2\gamma$ to get a consistent scaling across different values of $\gamma$. I would try $\gamma = 0.2$. The square root of the number of samples times the McKean-Schrader estimate of the standard error of the median, divided by the sample median.
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions?
Some alternatives, which have the same 'flavor' as CV are: The coefficient of L-variation, see e.g. Viglione. The second sample L-moment takes the place of the sample standard deviation. The $\gamma$
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions? Some alternatives, which have the same 'flavor' as CV are: The coefficient of L-variation, see e.g. Viglione. The second sample L-moment takes the place of the sample standard deviation. The $\gamma$-Winsorized standard deviation divided by the $\gamma$-trimmed mean. You probably want to divide this by $1 - 2\gamma$ to get a consistent scaling across different values of $\gamma$. I would try $\gamma = 0.2$. The square root of the number of samples times the McKean-Schrader estimate of the standard error of the median, divided by the sample median.
Alternatives to using Coefficient of Variation to summarize a set of parameter distributions? Some alternatives, which have the same 'flavor' as CV are: The coefficient of L-variation, see e.g. Viglione. The second sample L-moment takes the place of the sample standard deviation. The $\gamma$
31,391
How do we create a confidence interval for the parameter of a permutation test?
It's OK to use permutation resampling. It really depends on a number of factors. If your permutations are a relatively low number then your estimation of your confidence interval is not so great with permutations. Your permutations are in somewhat of a gray area and probably are fine. The only difference from your prior code is that you'd generate your samples randomly instead of with permutations. And, you'd generate more of them, let's say 1000 for example. Get the difference scores for your 1000 replications of your experiment. Take the cutoffs for the middle 950 (95%). That's your confidence interval. It falls directly from the bootstrap. You've already done most of this in your example. dif.treat is 462 items long. Therefore, you need the lower 2.5% and upper 2.5% cut offs (about 11 items in on each end). Using your code from before... y <- sort(dif.treat) ci.lo <- y[11] ci.hi <- y[462-11] Off hand I'd say that 462 is a little low but you'll find a bootstrap to 10,000 comes out with scores that are little different (likely closer to the mean). Thought I'd also add in some simple code requiring the boot library (based on your prior code). diff <- function(x,i) mean(x[i[6:11]]) - mean(x[i[1:5]]) b <- boot(total, diff, R = 1000) boot.ci(b)
How do we create a confidence interval for the parameter of a permutation test?
It's OK to use permutation resampling. It really depends on a number of factors. If your permutations are a relatively low number then your estimation of your confidence interval is not so great wit
How do we create a confidence interval for the parameter of a permutation test? It's OK to use permutation resampling. It really depends on a number of factors. If your permutations are a relatively low number then your estimation of your confidence interval is not so great with permutations. Your permutations are in somewhat of a gray area and probably are fine. The only difference from your prior code is that you'd generate your samples randomly instead of with permutations. And, you'd generate more of them, let's say 1000 for example. Get the difference scores for your 1000 replications of your experiment. Take the cutoffs for the middle 950 (95%). That's your confidence interval. It falls directly from the bootstrap. You've already done most of this in your example. dif.treat is 462 items long. Therefore, you need the lower 2.5% and upper 2.5% cut offs (about 11 items in on each end). Using your code from before... y <- sort(dif.treat) ci.lo <- y[11] ci.hi <- y[462-11] Off hand I'd say that 462 is a little low but you'll find a bootstrap to 10,000 comes out with scores that are little different (likely closer to the mean). Thought I'd also add in some simple code requiring the boot library (based on your prior code). diff <- function(x,i) mean(x[i[6:11]]) - mean(x[i[1:5]]) b <- boot(total, diff, R = 1000) boot.ci(b)
How do we create a confidence interval for the parameter of a permutation test? It's OK to use permutation resampling. It really depends on a number of factors. If your permutations are a relatively low number then your estimation of your confidence interval is not so great wit
31,392
How do we create a confidence interval for the parameter of a permutation test?
As a permutation test is an exact test, giving you an exact p-value. Bootstrapping a permutation test doesn't make sense. Next to that, determining a confidence interval around a test statistic doesn't make sense either, as it is calculated based on your sample and not an estimate. You determine confidence intervals around estimates like means and the likes, but not around test statistics. Permutation tests should not be used on datasets that are so big you can't calculate all possible permutations any more. If that's the case, use a bootstrap procedure to determine the cut-off for the test statistic you use. But again, this has little to do with a 95% confidence interval. An example : I use here the classic T-statistic, but use a simple approach to bootstrapping for calculation of the empirical distribution of my statistic. Based on that, I calculate an empirical p-value : x <- c(11.4,25.3,29.9,16.5,21.1) y <- c(23.7,26.6,28.5,14.2,17.9,24.3) t.sample <- t.test(x,y)$statistic t.dist <- apply( replicate(1000,sample(c(x,y),11,replace=F)),2, function(i){t.test(i[1:5],i[6:11])$statistic}) # two sided testing center <- mean(t.dist) t.sample <-abs(t.sample-center) t.dist <- abs(t.dist - center) p.value <- sum( t.sample < t.dist ) / length(t.dist) p.value Take into account that this 2-sided testing only works for symmetrical distributions. Non-symmetrical distributions are typically only tested one-sided. EDIT : OK, I misunderstood the question. If you want to calculate a confidence interval on the estimate of the difference, you can use the code mentioned here for bootstrapping within each sample. Mind you, this is a biased estimate: generally this gives a CI that is too small. Also see the example given there as a reason why you have to use a different approach for the confidence interval and the p-value.
How do we create a confidence interval for the parameter of a permutation test?
As a permutation test is an exact test, giving you an exact p-value. Bootstrapping a permutation test doesn't make sense. Next to that, determining a confidence interval around a test statistic doesn
How do we create a confidence interval for the parameter of a permutation test? As a permutation test is an exact test, giving you an exact p-value. Bootstrapping a permutation test doesn't make sense. Next to that, determining a confidence interval around a test statistic doesn't make sense either, as it is calculated based on your sample and not an estimate. You determine confidence intervals around estimates like means and the likes, but not around test statistics. Permutation tests should not be used on datasets that are so big you can't calculate all possible permutations any more. If that's the case, use a bootstrap procedure to determine the cut-off for the test statistic you use. But again, this has little to do with a 95% confidence interval. An example : I use here the classic T-statistic, but use a simple approach to bootstrapping for calculation of the empirical distribution of my statistic. Based on that, I calculate an empirical p-value : x <- c(11.4,25.3,29.9,16.5,21.1) y <- c(23.7,26.6,28.5,14.2,17.9,24.3) t.sample <- t.test(x,y)$statistic t.dist <- apply( replicate(1000,sample(c(x,y),11,replace=F)),2, function(i){t.test(i[1:5],i[6:11])$statistic}) # two sided testing center <- mean(t.dist) t.sample <-abs(t.sample-center) t.dist <- abs(t.dist - center) p.value <- sum( t.sample < t.dist ) / length(t.dist) p.value Take into account that this 2-sided testing only works for symmetrical distributions. Non-symmetrical distributions are typically only tested one-sided. EDIT : OK, I misunderstood the question. If you want to calculate a confidence interval on the estimate of the difference, you can use the code mentioned here for bootstrapping within each sample. Mind you, this is a biased estimate: generally this gives a CI that is too small. Also see the example given there as a reason why you have to use a different approach for the confidence interval and the p-value.
How do we create a confidence interval for the parameter of a permutation test? As a permutation test is an exact test, giving you an exact p-value. Bootstrapping a permutation test doesn't make sense. Next to that, determining a confidence interval around a test statistic doesn
31,393
How do we create a confidence interval for the parameter of a permutation test?
From Joris Meys code in the Answers but with modification to allow it to be applied in more t han a single situation: I tried to edit the other one but I did not have time to finish and for some reason I can't comment (maybe because this is an old question). x <- c(11.4,25.3,29.9,16.5,21.1) y <- c(23.7,26.6,28.5,14.2,17.9,24.3) t.sample <- t.test(x,y)$statistic t.dist <- apply( replicate(1000,sample(c(x,y),length(c(x,y)),replace=F)), 2, function(i){t.test(i[1:length(x)],i[length(x)+1:length(c(x,y))])$statistic}) # two sided testing center <- mean(t.dist) t.sample <-abs(t.sample-center) t.dist <- abs(t.dist - center) p.value <- sum( t.sample < t.dist ) / length(t.dist) p.value
How do we create a confidence interval for the parameter of a permutation test?
From Joris Meys code in the Answers but with modification to allow it to be applied in more t han a single situation: I tried to edit the other one but I did not have time to finish and for some reaso
How do we create a confidence interval for the parameter of a permutation test? From Joris Meys code in the Answers but with modification to allow it to be applied in more t han a single situation: I tried to edit the other one but I did not have time to finish and for some reason I can't comment (maybe because this is an old question). x <- c(11.4,25.3,29.9,16.5,21.1) y <- c(23.7,26.6,28.5,14.2,17.9,24.3) t.sample <- t.test(x,y)$statistic t.dist <- apply( replicate(1000,sample(c(x,y),length(c(x,y)),replace=F)), 2, function(i){t.test(i[1:length(x)],i[length(x)+1:length(c(x,y))])$statistic}) # two sided testing center <- mean(t.dist) t.sample <-abs(t.sample-center) t.dist <- abs(t.dist - center) p.value <- sum( t.sample < t.dist ) / length(t.dist) p.value
How do we create a confidence interval for the parameter of a permutation test? From Joris Meys code in the Answers but with modification to allow it to be applied in more t han a single situation: I tried to edit the other one but I did not have time to finish and for some reaso
31,394
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely?
Your iterations can be rewritten as $w_n \leftarrow w_{n-1} - axx^\top w$, or equivalently \begin{equation*} w_n \leftarrow (I - axx^\top)w_{n-1} \end{equation*} and so can be seen to be a form of power iteration. Therefore, your iterations converge to the dominant eigenvector of $I - axx^\top$. It is straightforward to calculate that for $x = (x_1, x_2)$, the eigenvalues are $\lambda_1 = 1$ and $\lambda_2 = 1 - ax_1^2 - ax_2^2$ with corresponding eigenvectors $(-x_2/x_1, 1)$ and $(x_1/x_2, 1)$ respectively. If $\lambda_1 = 1$ is the dominant eigenvalue, then your iterations will converge, since $w_n \rightarrow c\cdot(-x_2/x_1, 1)$ for some finite constant c (that depends on the initial $w_0$). Next, note that $\lambda_2 \leq 1$, and so is the dominant eigenvalue if and only if $\lambda_2 < -1$. This happens iff $x_1^2 + x_2^2 > 2/a$, which occurs with probability $\Pr(\chi^2_2 > 2/a)$. But in this event, $|\lambda_2| > 1$, and so $|w_n| \rightarrow \infty$ as $n\rightarrow \infty$ and your iterations diverge. In summary, your iteration scheme diverges with probability $\Pr(\chi^2_2 > 2/a)$ for almost all initializations of $w_0$ (with the exception of $w_0 \in \operatorname{span}(\{(-x_2/x_1, 1)\})$, which of course happens with probability $0$). Below is some Python 3 code that can help verify these findings. One can try various values of $a$ and find that the expected number of divergences is fairly close to the expected number from the chi-square distribution. from scipy.stats import multivariate_normal from scipy.stats import chi2 import numpy as np np.random.seed(0) a = 0.9 num_diverged = 0 for i in range(1000): x = multivariate_normal.rvs([0, 0]) w = 20 * multivariate_normal.rvs([0, 0]) # a random initialization for w for _ in range(1000): w = w - a * w.dot(x) * x #w = w/(w[0]**2 + w[1]**2)**0.5 # Uncomment to see normalized w's print() print("Final w: ", w) if np.isnan(sum(w)) or abs(w[0]) > 100 or abs(w[1]) > 100: num_diverged += 1 print("Normalized w: ", w/np.linalg.norm(w)) if 2 <= a * x[0]**2 + a* x[1]**2: x = np.array([x[0]/x[1], 1]) else: x = np.array([-x[1]/x[0], 1]) print("Expected normalized w:", x/np.linalg.norm(x)) print() print("Number diverged:", num_diverged) print("Expected diverged:", chi2.sf(2/a, 2)*1000) Partial output: Number diverged: 335 Expected diverged: 329.1929878079054
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely?
Your iterations can be rewritten as $w_n \leftarrow w_{n-1} - axx^\top w$, or equivalently \begin{equation*} w_n \leftarrow (I - axx^\top)w_{n-1} \end{equation*} and so can be seen to be a form of pow
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely? Your iterations can be rewritten as $w_n \leftarrow w_{n-1} - axx^\top w$, or equivalently \begin{equation*} w_n \leftarrow (I - axx^\top)w_{n-1} \end{equation*} and so can be seen to be a form of power iteration. Therefore, your iterations converge to the dominant eigenvector of $I - axx^\top$. It is straightforward to calculate that for $x = (x_1, x_2)$, the eigenvalues are $\lambda_1 = 1$ and $\lambda_2 = 1 - ax_1^2 - ax_2^2$ with corresponding eigenvectors $(-x_2/x_1, 1)$ and $(x_1/x_2, 1)$ respectively. If $\lambda_1 = 1$ is the dominant eigenvalue, then your iterations will converge, since $w_n \rightarrow c\cdot(-x_2/x_1, 1)$ for some finite constant c (that depends on the initial $w_0$). Next, note that $\lambda_2 \leq 1$, and so is the dominant eigenvalue if and only if $\lambda_2 < -1$. This happens iff $x_1^2 + x_2^2 > 2/a$, which occurs with probability $\Pr(\chi^2_2 > 2/a)$. But in this event, $|\lambda_2| > 1$, and so $|w_n| \rightarrow \infty$ as $n\rightarrow \infty$ and your iterations diverge. In summary, your iteration scheme diverges with probability $\Pr(\chi^2_2 > 2/a)$ for almost all initializations of $w_0$ (with the exception of $w_0 \in \operatorname{span}(\{(-x_2/x_1, 1)\})$, which of course happens with probability $0$). Below is some Python 3 code that can help verify these findings. One can try various values of $a$ and find that the expected number of divergences is fairly close to the expected number from the chi-square distribution. from scipy.stats import multivariate_normal from scipy.stats import chi2 import numpy as np np.random.seed(0) a = 0.9 num_diverged = 0 for i in range(1000): x = multivariate_normal.rvs([0, 0]) w = 20 * multivariate_normal.rvs([0, 0]) # a random initialization for w for _ in range(1000): w = w - a * w.dot(x) * x #w = w/(w[0]**2 + w[1]**2)**0.5 # Uncomment to see normalized w's print() print("Final w: ", w) if np.isnan(sum(w)) or abs(w[0]) > 100 or abs(w[1]) > 100: num_diverged += 1 print("Normalized w: ", w/np.linalg.norm(w)) if 2 <= a * x[0]**2 + a* x[1]**2: x = np.array([x[0]/x[1], 1]) else: x = np.array([-x[1]/x[0], 1]) print("Expected normalized w:", x/np.linalg.norm(x)) print() print("Number diverged:", num_diverged) print("Expected diverged:", chi2.sf(2/a, 2)*1000) Partial output: Number diverged: 335 Expected diverged: 329.1929878079054
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely? Your iterations can be rewritten as $w_n \leftarrow w_{n-1} - axx^\top w$, or equivalently \begin{equation*} w_n \leftarrow (I - axx^\top)w_{n-1} \end{equation*} and so can be seen to be a form of pow
31,395
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely?
$\newcommand{\E}{\operatorname{E}}$ This is a new answer for the updated question, where we have a sequence of Gaussians instead of a single $x$. We have that $w_n = \left[\prod_{i=1}^n (I - ax_ix_i^\top)\right]w_0$, and want to examine the behavior as $n\rightarrow \infty$. We're going to use the trick that an infinite product converges to zero iff the product of squares converges to zero: \begin{align*} \lim_{n\rightarrow\infty}\prod_{i=1}^n(I - ax_ix_i^\top)^2 &= \lim_{n\rightarrow\infty}\exp\left(n\cdot \frac{1}{n}\sum_{i=1}^n\log(I - ax_ix_i^\top)^2\right) \\ &\overset{a.s.}{\longrightarrow}\lim_{n\rightarrow\infty}\exp\left(n\cdot \E\left[\log(I - ax_ix_i^\top)^2\right]\right) \end{align*} Above, we use the matrix exponential and matrix logarithm. Using the spectral decomposition \begin{equation*} (I - ax_ix_i^\top)^2 = \begin{bmatrix} x_{i,2}/x_{i,1} & x_{i, 1}/x_{i,2} \\ 1 & 1 \end{bmatrix} \begin{bmatrix} 1 & 0 \\ 0 & (1-a||x_i||^2)^2 \end{bmatrix} \begin{bmatrix} -\frac{x_{1,i}x_{2,i}}{||x_i||^2} & \frac{x_{1,i}^2}{||x_i||^2} \\ \frac{x_{1,i}x_{2,i}}{||x_i||^2} & \frac{x_{2,i}^2}{||x_i||^2} \end{bmatrix} \end{equation*} we can calculate that \begin{equation*} \E\left[\log(I - ax_ix_i^\top)^2\right] = \begin{bmatrix} \E\left[\frac{x_{1,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right] & 0 \\ 0 & \E\left[\frac{x_{2,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right] \end{bmatrix} \end{equation*} Thus, we are concerned with when the following matrix has limit zero: \begin{equation*} \lim_{n\rightarrow\infty}\begin{bmatrix} \exp\left(\E\left[\frac{x_{1,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right]\right) & 0 \\ 0 & \exp\left(\E\left[\frac{x_{2,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right]\right) \end{bmatrix}^n \end{equation*} and this of course happens iff it has norm less than 1. That is, \begin{equation*} \sqrt{2\cdot \left[\exp\left(\E\left[\frac{x_{1,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right]\right)\right]^2} < 1 \end{equation*} Some numerical integration suggests that the critical value is roughly $a \approx 0.92$.
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely?
$\newcommand{\E}{\operatorname{E}}$ This is a new answer for the updated question, where we have a sequence of Gaussians instead of a single $x$. We have that $w_n = \left[\prod_{i=1}^n (I - ax_ix_i^\
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely? $\newcommand{\E}{\operatorname{E}}$ This is a new answer for the updated question, where we have a sequence of Gaussians instead of a single $x$. We have that $w_n = \left[\prod_{i=1}^n (I - ax_ix_i^\top)\right]w_0$, and want to examine the behavior as $n\rightarrow \infty$. We're going to use the trick that an infinite product converges to zero iff the product of squares converges to zero: \begin{align*} \lim_{n\rightarrow\infty}\prod_{i=1}^n(I - ax_ix_i^\top)^2 &= \lim_{n\rightarrow\infty}\exp\left(n\cdot \frac{1}{n}\sum_{i=1}^n\log(I - ax_ix_i^\top)^2\right) \\ &\overset{a.s.}{\longrightarrow}\lim_{n\rightarrow\infty}\exp\left(n\cdot \E\left[\log(I - ax_ix_i^\top)^2\right]\right) \end{align*} Above, we use the matrix exponential and matrix logarithm. Using the spectral decomposition \begin{equation*} (I - ax_ix_i^\top)^2 = \begin{bmatrix} x_{i,2}/x_{i,1} & x_{i, 1}/x_{i,2} \\ 1 & 1 \end{bmatrix} \begin{bmatrix} 1 & 0 \\ 0 & (1-a||x_i||^2)^2 \end{bmatrix} \begin{bmatrix} -\frac{x_{1,i}x_{2,i}}{||x_i||^2} & \frac{x_{1,i}^2}{||x_i||^2} \\ \frac{x_{1,i}x_{2,i}}{||x_i||^2} & \frac{x_{2,i}^2}{||x_i||^2} \end{bmatrix} \end{equation*} we can calculate that \begin{equation*} \E\left[\log(I - ax_ix_i^\top)^2\right] = \begin{bmatrix} \E\left[\frac{x_{1,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right] & 0 \\ 0 & \E\left[\frac{x_{2,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right] \end{bmatrix} \end{equation*} Thus, we are concerned with when the following matrix has limit zero: \begin{equation*} \lim_{n\rightarrow\infty}\begin{bmatrix} \exp\left(\E\left[\frac{x_{1,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right]\right) & 0 \\ 0 & \exp\left(\E\left[\frac{x_{2,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right]\right) \end{bmatrix}^n \end{equation*} and this of course happens iff it has norm less than 1. That is, \begin{equation*} \sqrt{2\cdot \left[\exp\left(\E\left[\frac{x_{1,i}^2}{||x_i||^2}\cdot\log(1-a||x_i||^2)^2\right]\right)\right]^2} < 1 \end{equation*} Some numerical integration suggests that the critical value is roughly $a \approx 0.92$.
Range of $a$ such that $w \leftarrow w-a x \langle w, x \rangle$ converges almost surely? $\newcommand{\E}{\operatorname{E}}$ This is a new answer for the updated question, where we have a sequence of Gaussians instead of a single $x$. We have that $w_n = \left[\prod_{i=1}^n (I - ax_ix_i^\
31,396
Can a timeseries with a clear trend be considered stationary?
From the help page: The general regression equation which incorporates a constant and a linear trend is used and the t-statistic for a first order autoregressive coefficient equals one is computed. That is, adf.test() fits a regression using an intercept, a trend (!) and the first $k$ autoregressive terms in the series. Only in this context does it test whether the first autoregressive parameter is equal to one, which would indicate nonstationarity. Thus, a trended series can definitely be stationary in the sense of tseries::adf.test(), namely if it is stationary after accounting for the trend.
Can a timeseries with a clear trend be considered stationary?
From the help page: The general regression equation which incorporates a constant and a linear trend is used and the t-statistic for a first order autoregressive coefficient equals one is computed.
Can a timeseries with a clear trend be considered stationary? From the help page: The general regression equation which incorporates a constant and a linear trend is used and the t-statistic for a first order autoregressive coefficient equals one is computed. That is, adf.test() fits a regression using an intercept, a trend (!) and the first $k$ autoregressive terms in the series. Only in this context does it test whether the first autoregressive parameter is equal to one, which would indicate nonstationarity. Thus, a trended series can definitely be stationary in the sense of tseries::adf.test(), namely if it is stationary after accounting for the trend.
Can a timeseries with a clear trend be considered stationary? From the help page: The general regression equation which incorporates a constant and a linear trend is used and the t-statistic for a first order autoregressive coefficient equals one is computed.
31,397
What is the difference between a logistic regression and log binomial regression?
Both models are binomial generalized linear models (GLMs). The "binomial" part of that phrase means that we think the outcome $Y_i$ for each observation $i$ is generated as the result of a single weighted coin flip, 0 or 1, governed by the parameter $p_i$, which is equal to the probability of getting a 1 (i.e., $p_i = P(Y_i=1)$). Where the models differ is in the form of the relationship between the predictors $X_i$ and $p_i$. In logistic regression, the relationship is specified as $$ p_i=\text{expit}(X_i \beta)=\frac{1}{1+\exp(-X_i\beta)} $$ or, equivalently,$$ \text{logit}(p_i)=\frac{p_i}{1-p_i}=X_i\beta $$ In log-binomial regression, the relationship is specified as $$ p_i=\exp(X_i \beta) $$ or, equivalently, $$ \log(p_i)=X_i \beta $$ The coefficients $\beta$ are interpreted differently between the two models. For both, it makes sense to exponentiate them. In logistic regression, $\exp(\beta_k)$ is the odds ratio corresponding to a 1-unit change in $X_k$, holding all other variables in the model constant. In log-binomial regression, $\exp(\beta_k)$ is the risk ratio corresponding to a 1-unit change in $X_k$, holding all other variables in the model constant. Logistic regression always produces estimates of $p_i$ that are between 0 and 1. This is not true for log-binomial regression; when a model is not saturated, it is generally possible, given a set of estimated coefficients, to compute an estimate of $p_i$ that is greater than 1 (but it will always be positive). There can be numerical problems when using log-binomial regression for this reason (i.e., the model can be hard for computer programs to fit). Which model fits your data better is an empirical question, but logistic regression will almost always perform better unless there are very few 1s. For saturated models, the two models will fit exactly the same and produce the same predicted probabilities. The log-binomial model is therefore most useful when you have a saturated model and you want to interpret a coefficient as a risk ratio, e.g., when the only predictor in your model is treatment status in a randomized trial. See here and here for more discussions of these models.
What is the difference between a logistic regression and log binomial regression?
Both models are binomial generalized linear models (GLMs). The "binomial" part of that phrase means that we think the outcome $Y_i$ for each observation $i$ is generated as the result of a single weig
What is the difference between a logistic regression and log binomial regression? Both models are binomial generalized linear models (GLMs). The "binomial" part of that phrase means that we think the outcome $Y_i$ for each observation $i$ is generated as the result of a single weighted coin flip, 0 or 1, governed by the parameter $p_i$, which is equal to the probability of getting a 1 (i.e., $p_i = P(Y_i=1)$). Where the models differ is in the form of the relationship between the predictors $X_i$ and $p_i$. In logistic regression, the relationship is specified as $$ p_i=\text{expit}(X_i \beta)=\frac{1}{1+\exp(-X_i\beta)} $$ or, equivalently,$$ \text{logit}(p_i)=\frac{p_i}{1-p_i}=X_i\beta $$ In log-binomial regression, the relationship is specified as $$ p_i=\exp(X_i \beta) $$ or, equivalently, $$ \log(p_i)=X_i \beta $$ The coefficients $\beta$ are interpreted differently between the two models. For both, it makes sense to exponentiate them. In logistic regression, $\exp(\beta_k)$ is the odds ratio corresponding to a 1-unit change in $X_k$, holding all other variables in the model constant. In log-binomial regression, $\exp(\beta_k)$ is the risk ratio corresponding to a 1-unit change in $X_k$, holding all other variables in the model constant. Logistic regression always produces estimates of $p_i$ that are between 0 and 1. This is not true for log-binomial regression; when a model is not saturated, it is generally possible, given a set of estimated coefficients, to compute an estimate of $p_i$ that is greater than 1 (but it will always be positive). There can be numerical problems when using log-binomial regression for this reason (i.e., the model can be hard for computer programs to fit). Which model fits your data better is an empirical question, but logistic regression will almost always perform better unless there are very few 1s. For saturated models, the two models will fit exactly the same and produce the same predicted probabilities. The log-binomial model is therefore most useful when you have a saturated model and you want to interpret a coefficient as a risk ratio, e.g., when the only predictor in your model is treatment status in a randomized trial. See here and here for more discussions of these models.
What is the difference between a logistic regression and log binomial regression? Both models are binomial generalized linear models (GLMs). The "binomial" part of that phrase means that we think the outcome $Y_i$ for each observation $i$ is generated as the result of a single weig
31,398
What is the difference between a logistic regression and log binomial regression?
They are both GLMs, and they both take the variance of the response to have a mean-variance relationship as p(1-p) with p = probability of response. The difference regards the transformation of the expected response in the GLMs. The logistic regression models the logit transformation of the p whereas log binomial models the log of the p. The exponentiated (non-intercept) coefficients for logistic regression model are interpretted as odds ratios whereas for log-binomial they are relative risk ratios. Logistic regression is valid in outcome dependent sampling like case control studies. Log-binomial models risk overfitting response probabilities to values greater than 1. They give approximately equal estimation and inference when the probaibility of response is very low.
What is the difference between a logistic regression and log binomial regression?
They are both GLMs, and they both take the variance of the response to have a mean-variance relationship as p(1-p) with p = probability of response. The difference regards the transformation of the ex
What is the difference between a logistic regression and log binomial regression? They are both GLMs, and they both take the variance of the response to have a mean-variance relationship as p(1-p) with p = probability of response. The difference regards the transformation of the expected response in the GLMs. The logistic regression models the logit transformation of the p whereas log binomial models the log of the p. The exponentiated (non-intercept) coefficients for logistic regression model are interpretted as odds ratios whereas for log-binomial they are relative risk ratios. Logistic regression is valid in outcome dependent sampling like case control studies. Log-binomial models risk overfitting response probabilities to values greater than 1. They give approximately equal estimation and inference when the probaibility of response is very low.
What is the difference between a logistic regression and log binomial regression? They are both GLMs, and they both take the variance of the response to have a mean-variance relationship as p(1-p) with p = probability of response. The difference regards the transformation of the ex
31,399
Stratification of the continuous y (target) variable in regression setting
Update: First consider whether splitting the data into training and validation subsets makes the best use of your data for building a predictive model. Split-Sample Model Validation Bootstrap optimism corrected - results interpretation If you still want to proceed with a train/validation split, the proposed strategy is equivalent to simple random sampling: it will sample test_size items with equal probability to create a test set and allocate the remaining 1 - test_size items to the training set. To begin with, the implementation of your strategy has some obvious weaknesses. Why create bins in the interval [0,n] given n data points? Say you have 506 observations between 0 and 100. It seems wasteful to create 40 empty bins for unobserved values > 100. Say you have 506 observations between 0 and 1000. It seems inefficient to put all observations ≥ 506 in the rightmost bin. So you'll have to be a bit careful about how you define the bins as scikit-learn throws an error if there are bins with fewer than 2 data points. Other that this technical requirement, it doesn't matter how you define the bins. With stratified sampling each bin is sampled in proportion to its size, so you sample more frequently from bins with more items, which correspond to higher data density regions. But, conditional on the bin, an item in a "dense" bin with many data points has a smaller chance of being sampled than an item in "sparse" bin. In the end the two probabilities even out and each item has the same probability of being sampled, no matter how dense its region. This is simple random sampling. So in expectation, you'll get the same allocation between training and test subsets you'll get with simple random sampling. To see this, let's compute the probability that item $i$ is selected as the first item to allocate to the test set. With simple random sampling: $$ \operatorname{Pr}\left\{\text{Select $Y_i$}\right\} = \frac{1}{n} $$ With stratified strategy: $$ \operatorname{Pr}\left\{\text{Select $Y_i$}\right\} = \operatorname{Pr}\left\{\text{Select $\operatorname{Bin} (Y_i)$}\right\}\operatorname{Pr}\left\{\text{Select $Y_i$ from $\operatorname{Bin}(Y_i)$}\right\} \\ = \frac{\operatorname{Size}\left\{\operatorname{Bin}(Y_i)\right\}}{n} \frac{1}{\operatorname{Size}\left\{\operatorname{Bin} (Y_i)\right\}} = \frac{1}{n} $$ So there is no need for the more complex strategy. Just don't forget to shuffle. A quick simulation to confirm. import numpy as np from sklearn.model_selection import train_test_split np.random.seed(123) n = 1000 # Let's "label" one item, yi, by assigning it the value 501 # Otherwise, the rest of the values are uniformly distributed between 0 and 500 y = np.random.uniform(low=0, high=500, size=n - 1) y = np.append(y, 501) bins = np.linspace(0, 506, 50) y_binned = np.digitize(y, bins) nreps = 1000 select_yi = 0 for r in range(nreps): y_train, y_test = train_test_split(y, test_size=0.3, shuffle=True, stratify=y_binned) select_yi += sum(y_test == 501) # yi is assigned to the test set about 30% of the time # as expected since the test size is 30%. select_yi # > 297
Stratification of the continuous y (target) variable in regression setting
Update: First consider whether splitting the data into training and validation subsets makes the best use of your data for building a predictive model. Split-Sample Model Validation Bootstrap optimis
Stratification of the continuous y (target) variable in regression setting Update: First consider whether splitting the data into training and validation subsets makes the best use of your data for building a predictive model. Split-Sample Model Validation Bootstrap optimism corrected - results interpretation If you still want to proceed with a train/validation split, the proposed strategy is equivalent to simple random sampling: it will sample test_size items with equal probability to create a test set and allocate the remaining 1 - test_size items to the training set. To begin with, the implementation of your strategy has some obvious weaknesses. Why create bins in the interval [0,n] given n data points? Say you have 506 observations between 0 and 100. It seems wasteful to create 40 empty bins for unobserved values > 100. Say you have 506 observations between 0 and 1000. It seems inefficient to put all observations ≥ 506 in the rightmost bin. So you'll have to be a bit careful about how you define the bins as scikit-learn throws an error if there are bins with fewer than 2 data points. Other that this technical requirement, it doesn't matter how you define the bins. With stratified sampling each bin is sampled in proportion to its size, so you sample more frequently from bins with more items, which correspond to higher data density regions. But, conditional on the bin, an item in a "dense" bin with many data points has a smaller chance of being sampled than an item in "sparse" bin. In the end the two probabilities even out and each item has the same probability of being sampled, no matter how dense its region. This is simple random sampling. So in expectation, you'll get the same allocation between training and test subsets you'll get with simple random sampling. To see this, let's compute the probability that item $i$ is selected as the first item to allocate to the test set. With simple random sampling: $$ \operatorname{Pr}\left\{\text{Select $Y_i$}\right\} = \frac{1}{n} $$ With stratified strategy: $$ \operatorname{Pr}\left\{\text{Select $Y_i$}\right\} = \operatorname{Pr}\left\{\text{Select $\operatorname{Bin} (Y_i)$}\right\}\operatorname{Pr}\left\{\text{Select $Y_i$ from $\operatorname{Bin}(Y_i)$}\right\} \\ = \frac{\operatorname{Size}\left\{\operatorname{Bin}(Y_i)\right\}}{n} \frac{1}{\operatorname{Size}\left\{\operatorname{Bin} (Y_i)\right\}} = \frac{1}{n} $$ So there is no need for the more complex strategy. Just don't forget to shuffle. A quick simulation to confirm. import numpy as np from sklearn.model_selection import train_test_split np.random.seed(123) n = 1000 # Let's "label" one item, yi, by assigning it the value 501 # Otherwise, the rest of the values are uniformly distributed between 0 and 500 y = np.random.uniform(low=0, high=500, size=n - 1) y = np.append(y, 501) bins = np.linspace(0, 506, 50) y_binned = np.digitize(y, bins) nreps = 1000 select_yi = 0 for r in range(nreps): y_train, y_test = train_test_split(y, test_size=0.3, shuffle=True, stratify=y_binned) select_yi += sum(y_test == 501) # yi is assigned to the test set about 30% of the time # as expected since the test size is 30%. select_yi # > 297
Stratification of the continuous y (target) variable in regression setting Update: First consider whether splitting the data into training and validation subsets makes the best use of your data for building a predictive model. Split-Sample Model Validation Bootstrap optimis
31,400
Stratification of the continuous y (target) variable in regression setting
You are right, it's not common at all, but what you do makes sense though it may be sensitive to your binning strategy. So, it's also a good idea to plot your binned target variable. This stratification makes more sense when the target variable is so skewed such that sometimes some folds do not get enough samples from some regions of the target variable.
Stratification of the continuous y (target) variable in regression setting
You are right, it's not common at all, but what you do makes sense though it may be sensitive to your binning strategy. So, it's also a good idea to plot your binned target variable. This stratificati
Stratification of the continuous y (target) variable in regression setting You are right, it's not common at all, but what you do makes sense though it may be sensitive to your binning strategy. So, it's also a good idea to plot your binned target variable. This stratification makes more sense when the target variable is so skewed such that sometimes some folds do not get enough samples from some regions of the target variable.
Stratification of the continuous y (target) variable in regression setting You are right, it's not common at all, but what you do makes sense though it may be sensitive to your binning strategy. So, it's also a good idea to plot your binned target variable. This stratificati