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 |
|---|---|---|---|---|---|---|
34,701 | Preserving comments on graphs for exploratory data analysis | I tend to do more and more analyses in R notebooks within RStudio. This way, I can have code, annotations and graphs toghether in one place and don't have to produce pdfs all the time - which is a real time saver. You write text and code in an editor and by clicking on a button, the code is executed (and the graph drawn) in place. So text, code and plot stay neatly together. It is also very easy to convert into HTML or PDF by some mouse clicks.
I don't know, how well this works with Python, as I mostly use R. | Preserving comments on graphs for exploratory data analysis | I tend to do more and more analyses in R notebooks within RStudio. This way, I can have code, annotations and graphs toghether in one place and don't have to produce pdfs all the time - which is a rea | Preserving comments on graphs for exploratory data analysis
I tend to do more and more analyses in R notebooks within RStudio. This way, I can have code, annotations and graphs toghether in one place and don't have to produce pdfs all the time - which is a real time saver. You write text and code in an editor and by clicking on a button, the code is executed (and the graph drawn) in place. So text, code and plot stay neatly together. It is also very easy to convert into HTML or PDF by some mouse clicks.
I don't know, how well this works with Python, as I mostly use R. | Preserving comments on graphs for exploratory data analysis
I tend to do more and more analyses in R notebooks within RStudio. This way, I can have code, annotations and graphs toghether in one place and don't have to produce pdfs all the time - which is a rea |
34,702 | Preserving comments on graphs for exploratory data analysis | It sounds like you want some kind of literate programming. R affords Sweave, and Knitr that interface with LaTeX. There are other options for different kinds of output formats, such as ODFweave for editable documents (like Word documents), and RMarkdown that can output multiple types (like HTML in addition to the above mentioned). Other statistical software commonly have analogous features.
(There is a bit of up-front work in using these. I typically do one-off projects instead of longer-term projects that require regular, and similar, reports, so I typically use @NickCox's method of dumping or copying to a file and writing comments around it.) | Preserving comments on graphs for exploratory data analysis | It sounds like you want some kind of literate programming. R affords Sweave, and Knitr that interface with LaTeX. There are other options for different kinds of output formats, such as ODFweave for | Preserving comments on graphs for exploratory data analysis
It sounds like you want some kind of literate programming. R affords Sweave, and Knitr that interface with LaTeX. There are other options for different kinds of output formats, such as ODFweave for editable documents (like Word documents), and RMarkdown that can output multiple types (like HTML in addition to the above mentioned). Other statistical software commonly have analogous features.
(There is a bit of up-front work in using these. I typically do one-off projects instead of longer-term projects that require regular, and similar, reports, so I typically use @NickCox's method of dumping or copying to a file and writing comments around it.) | Preserving comments on graphs for exploratory data analysis
It sounds like you want some kind of literate programming. R affords Sweave, and Knitr that interface with LaTeX. There are other options for different kinds of output formats, such as ODFweave for |
34,703 | Preserving comments on graphs for exploratory data analysis | In R: Sometimes I add an extra plot to a pdf with some basic information. This is most useful if the annotations are short and relate to the plot data such that you can paste extra information. For example:
pdf("cars-plots.pdf")
plot(cars)
plot.new()
legend("center", bty = "n", legend =
paste0("Data: 'cars'\n",
"cor = ", round(cor(cars)[1, 2], 2), "\n",
"N = ", nrow(cars), "\n",
Sys.Date()))
dev.off()
Alternatively, if you have longer annotations, producing a report using R Markdown might be a solution. | Preserving comments on graphs for exploratory data analysis | In R: Sometimes I add an extra plot to a pdf with some basic information. This is most useful if the annotations are short and relate to the plot data such that you can paste extra information. For ex | Preserving comments on graphs for exploratory data analysis
In R: Sometimes I add an extra plot to a pdf with some basic information. This is most useful if the annotations are short and relate to the plot data such that you can paste extra information. For example:
pdf("cars-plots.pdf")
plot(cars)
plot.new()
legend("center", bty = "n", legend =
paste0("Data: 'cars'\n",
"cor = ", round(cor(cars)[1, 2], 2), "\n",
"N = ", nrow(cars), "\n",
Sys.Date()))
dev.off()
Alternatively, if you have longer annotations, producing a report using R Markdown might be a solution. | Preserving comments on graphs for exploratory data analysis
In R: Sometimes I add an extra plot to a pdf with some basic information. This is most useful if the annotations are short and relate to the plot data such that you can paste extra information. For ex |
34,704 | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen? | In my discussion here I am assuming your $\theta$ is effectively a longitude and $\phi$ is effectively a latitude. Perhaps more typical spherical co-ordinates use an angle down from the north pole rather than up from the equator and swap the roles of the two symbols from that - but it's no problem to deal with it either way, so I'll stick with what your notation appears to be.
Note that the distribution of radius is not of interest here, only the angles, so we could project everything onto a unit sphere without changing the angles. This is quite useful in the normal case.
With a spherically symmetric distribution like the three dimensional standard normal, the appearance of the distribution of inclination has to do with the fact that there's a lot more area on the surface of a sphere near the equator than near the poles.
If you follow through the mathematics (or write a geometric argument in terms of elements of probability similar to the earlier 2D question), you can get that the inclination should have a density proportional to $\cos(\phi)$. Here's a geometrical argument that should motivate it in the "elements of probability" terms:
Since the radius at the equator is 1 and the radius at latitude $\phi$ is $\cos(\phi)$, the circumference at latitude $\phi$ is proportional to $\cos(\phi)$, and so the density at $\phi$ is proportional to $\cos(\phi)$.
Uniform case: With the 3D-uniform normalized to constant radius, you don't have uniformity of density on the sphere for the same reason that we didn't in the 2D case - when you project onto the sphere, there's a lot more "density" on the sphere near the angles where the corners are than where the sides are (with parts near the middle of the edges being in between) -- because there's more of the volume of the cube for angles close to the corners than for angles near the middle of the faces.
We can see this by generating many random values uniformly in the cube and projecting them onto the sphere. Since there's more volume near the corners than near the faces of the cube, there's greater density looking "inward" from the corners than the faces. If we plot the height (recall this is a projected-z-value, $z^* = z/r$, where $r=\sqrt{x^2+y^2+z^2}$) above the equator against the longitude, we get the top plot below:
That height corresponds to the vertical side of the right triangle in the previous diagram; that height is the $\sin$ of $\phi$ ($z^*=\sin(\phi)$). To convert that to the latitude ($\phi$), we would take the arcsin of that projected vertical height, which is what we see in the lower plot. This "stretches" things more the closer we get to the pole, making the density as a function of latitude drop to 0 at the north and south pole (for both the uniform and for the normal case).
The density for $\phi$ will then be the integral of that bivariate density over $\theta$.
Looking at the marginal for $\theta$ (i.e. strips running down at fixed values of $\theta$) makes for four peaks in the density of $\theta$ as you note - indeed this follows directly from the 2D case, but as we now see, it also makes for a pair of peaks in the density of $\phi$ away from the equator, corresponding to a region on the surface of the unit sphere where the corners and upper/lower edges of the cube project. | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen? | In my discussion here I am assuming your $\theta$ is effectively a longitude and $\phi$ is effectively a latitude. Perhaps more typical spherical co-ordinates use an angle down from the north pole rat | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen?
In my discussion here I am assuming your $\theta$ is effectively a longitude and $\phi$ is effectively a latitude. Perhaps more typical spherical co-ordinates use an angle down from the north pole rather than up from the equator and swap the roles of the two symbols from that - but it's no problem to deal with it either way, so I'll stick with what your notation appears to be.
Note that the distribution of radius is not of interest here, only the angles, so we could project everything onto a unit sphere without changing the angles. This is quite useful in the normal case.
With a spherically symmetric distribution like the three dimensional standard normal, the appearance of the distribution of inclination has to do with the fact that there's a lot more area on the surface of a sphere near the equator than near the poles.
If you follow through the mathematics (or write a geometric argument in terms of elements of probability similar to the earlier 2D question), you can get that the inclination should have a density proportional to $\cos(\phi)$. Here's a geometrical argument that should motivate it in the "elements of probability" terms:
Since the radius at the equator is 1 and the radius at latitude $\phi$ is $\cos(\phi)$, the circumference at latitude $\phi$ is proportional to $\cos(\phi)$, and so the density at $\phi$ is proportional to $\cos(\phi)$.
Uniform case: With the 3D-uniform normalized to constant radius, you don't have uniformity of density on the sphere for the same reason that we didn't in the 2D case - when you project onto the sphere, there's a lot more "density" on the sphere near the angles where the corners are than where the sides are (with parts near the middle of the edges being in between) -- because there's more of the volume of the cube for angles close to the corners than for angles near the middle of the faces.
We can see this by generating many random values uniformly in the cube and projecting them onto the sphere. Since there's more volume near the corners than near the faces of the cube, there's greater density looking "inward" from the corners than the faces. If we plot the height (recall this is a projected-z-value, $z^* = z/r$, where $r=\sqrt{x^2+y^2+z^2}$) above the equator against the longitude, we get the top plot below:
That height corresponds to the vertical side of the right triangle in the previous diagram; that height is the $\sin$ of $\phi$ ($z^*=\sin(\phi)$). To convert that to the latitude ($\phi$), we would take the arcsin of that projected vertical height, which is what we see in the lower plot. This "stretches" things more the closer we get to the pole, making the density as a function of latitude drop to 0 at the north and south pole (for both the uniform and for the normal case).
The density for $\phi$ will then be the integral of that bivariate density over $\theta$.
Looking at the marginal for $\theta$ (i.e. strips running down at fixed values of $\theta$) makes for four peaks in the density of $\theta$ as you note - indeed this follows directly from the 2D case, but as we now see, it also makes for a pair of peaks in the density of $\phi$ away from the equator, corresponding to a region on the surface of the unit sphere where the corners and upper/lower edges of the cube project. | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen?
In my discussion here I am assuming your $\theta$ is effectively a longitude and $\phi$ is effectively a latitude. Perhaps more typical spherical co-ordinates use an angle down from the north pole rat |
34,705 | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen? | The complementary cumulative distribution for the spherical latitude $\phi$ gives the chance that a random point in the cube $[-1,1]^3$ will lie above the cone that graphs the function $z = \cot(\phi)\sqrt{x^2+y^2}$. Because these points are uniformly distributed throughout the cube (which has a volume of $8$), this chance is one-eighth the volume between the cone and the top of the cube. When the latitude exceeds $\pi/4$, this volume is that of a right cone with height $1$ and base $\cot(\phi)$, equal to
$$F_{+}(\phi) = \frac{1}{8}\frac{\pi}{3}\cot^2(\phi).$$
See the two righthand plots in the figure.
When the latitude is less than $\arctan(1/\sqrt{2})$, this is the volume of the intersection of a semi-infinite cone and the cube. An integration in polar coordinates gives the expression
$$F_{-}(\phi) = \frac{1}{8}\left(4-\frac{4}{3} \tan (\phi ) \left(\sqrt{2}+2 \tanh ^{-1}\left(\tan \left(\frac{\pi }{8}\right)\right)\right)\right).$$
See the two leftmost plots in the figure.
The negative derivatives of these expressions give the density. Between $\arctan(1/\sqrt{2})\approx \pi/5$ and $\pi/4$ is a transition region where the intersection of the cone with the cube is complicated. Although an exact expression could be developed, it would be messy. What we do know is that the density must change continuously from the derivative of $-F_{-}$ to the derivative of $-F_{+}$ as $\phi$ varies between those points. This is shown in a histogram of a million simulated values (from the upper half of the cube only--the lower half will be a mirror image). The gold curve is the graph of $-\frac{d}{d\phi}F_{-}$ while the red curve at the right is the graph of $-\frac{d}{d\phi}F_{+}.$
This clarifies why the modes are not at $\phi=\pm \pi/4$, but must lie between these values and $\pm \arctan(1/\sqrt{2})$. | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen? | The complementary cumulative distribution for the spherical latitude $\phi$ gives the chance that a random point in the cube $[-1,1]^3$ will lie above the cone that graphs the function $z = \cot(\phi) | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen?
The complementary cumulative distribution for the spherical latitude $\phi$ gives the chance that a random point in the cube $[-1,1]^3$ will lie above the cone that graphs the function $z = \cot(\phi)\sqrt{x^2+y^2}$. Because these points are uniformly distributed throughout the cube (which has a volume of $8$), this chance is one-eighth the volume between the cone and the top of the cube. When the latitude exceeds $\pi/4$, this volume is that of a right cone with height $1$ and base $\cot(\phi)$, equal to
$$F_{+}(\phi) = \frac{1}{8}\frac{\pi}{3}\cot^2(\phi).$$
See the two righthand plots in the figure.
When the latitude is less than $\arctan(1/\sqrt{2})$, this is the volume of the intersection of a semi-infinite cone and the cube. An integration in polar coordinates gives the expression
$$F_{-}(\phi) = \frac{1}{8}\left(4-\frac{4}{3} \tan (\phi ) \left(\sqrt{2}+2 \tanh ^{-1}\left(\tan \left(\frac{\pi }{8}\right)\right)\right)\right).$$
See the two leftmost plots in the figure.
The negative derivatives of these expressions give the density. Between $\arctan(1/\sqrt{2})\approx \pi/5$ and $\pi/4$ is a transition region where the intersection of the cone with the cube is complicated. Although an exact expression could be developed, it would be messy. What we do know is that the density must change continuously from the derivative of $-F_{-}$ to the derivative of $-F_{+}$ as $\phi$ varies between those points. This is shown in a histogram of a million simulated values (from the upper half of the cube only--the lower half will be a mirror image). The gold curve is the graph of $-\frac{d}{d\phi}F_{-}$ while the red curve at the right is the graph of $-\frac{d}{d\phi}F_{+}.$
This clarifies why the modes are not at $\phi=\pm \pi/4$, but must lie between these values and $\pm \arctan(1/\sqrt{2})$. | How is the spherical elevation angle distributed when $(x,y,z)$ are uniformly and normally chosen?
The complementary cumulative distribution for the spherical latitude $\phi$ gives the chance that a random point in the cube $[-1,1]^3$ will lie above the cone that graphs the function $z = \cot(\phi) |
34,706 | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear regression? | You have to think about it geometrically in terms of vectors and distances between them!
To understand the idea refer to the next slide:
In this example, you have two feature vectors $\mathbf{x}_1$ and $\mathbf{x}_2$ (so $p=2$). These vectors are in 3D space (so $N=3$).
The vector $\mathbf{y}$ is a vector in this 3D space and is given!
The goal is to find the linear combination $\hat{\mathbf{y}}$ (i.e. finding the coefficients $\beta_j$, refer to previous slides) of $\mathbf{x}_1$ and $\mathbf{x}_2$ that allows you to get as close as possible to $\mathbf{y}$.
Back to the example, since you have only 2 feature vectors $\mathbf{x}_1$ and $\mathbf{x}_2$, all their possible linear combinations (from which we will choose one that becomes $\hat{\mathbf{y}}$) will form a plane. We call it the span of the two vectors. This means that $\hat{\mathbf{y}}$ can only live on this plane.
The trick to understand now is to think of $\hat{\mathbf{y}}$ and $\mathbf{y}$ as geometric vectors not only algebraic vectors.
Let's note $\mathbf{e}=\mathbf{y} - \hat{\mathbf{y}}$ which is equivalent to writing $\mathbf{y} = \hat{\mathbf{y}}+\mathbf{e}$ which geometrically means that to get $\mathbf{y}$ you have to add $\mathbf{e}$ to $\hat{\mathbf{y}}$ and $\mathbf{e}$ then represents what separates $\hat{\mathbf{y}}$ from $\mathbf{y}$. Its modulus represents the distance between the two vectors $\hat{\mathbf{y}}$ and $\mathbf{y}$. Patience, we are almost there... :-)
The goal is to minimize this distance. If you refer the the figure above and imagine moving around your $\hat{\mathbf{y}}$ vector inside the subspace spanned by $\mathbf{x}_1$ and $\mathbf{x}_2$ (i.e. the plane) (you also have to imagine $\mathbf{e}$ moving with it going from the head of the vector $\hat{\mathbf{y}}$ to the head of the vector $\mathbf{y}$), then, where do you think that the distance will be minimal?
This happens when $\hat{\mathbf{y}}$ is just under $\mathbf{y}$ such that $\mathbf{e}$ becomes perpendicular to the subspace.
Conclusion:
Minimizing the distance (technically the squared distance) between $\hat{\mathbf{y}}$ and $\mathbf{y}$ is equivalent to having the vector representing this distance perpendicular to the subspace spanned by the feature vectors! | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear | You have to think about it geometrically in terms of vectors and distances between them!
To understand the idea refer to the next slide:
In this example, you have two feature vectors $\mathbf{x}_1$ a | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear regression?
You have to think about it geometrically in terms of vectors and distances between them!
To understand the idea refer to the next slide:
In this example, you have two feature vectors $\mathbf{x}_1$ and $\mathbf{x}_2$ (so $p=2$). These vectors are in 3D space (so $N=3$).
The vector $\mathbf{y}$ is a vector in this 3D space and is given!
The goal is to find the linear combination $\hat{\mathbf{y}}$ (i.e. finding the coefficients $\beta_j$, refer to previous slides) of $\mathbf{x}_1$ and $\mathbf{x}_2$ that allows you to get as close as possible to $\mathbf{y}$.
Back to the example, since you have only 2 feature vectors $\mathbf{x}_1$ and $\mathbf{x}_2$, all their possible linear combinations (from which we will choose one that becomes $\hat{\mathbf{y}}$) will form a plane. We call it the span of the two vectors. This means that $\hat{\mathbf{y}}$ can only live on this plane.
The trick to understand now is to think of $\hat{\mathbf{y}}$ and $\mathbf{y}$ as geometric vectors not only algebraic vectors.
Let's note $\mathbf{e}=\mathbf{y} - \hat{\mathbf{y}}$ which is equivalent to writing $\mathbf{y} = \hat{\mathbf{y}}+\mathbf{e}$ which geometrically means that to get $\mathbf{y}$ you have to add $\mathbf{e}$ to $\hat{\mathbf{y}}$ and $\mathbf{e}$ then represents what separates $\hat{\mathbf{y}}$ from $\mathbf{y}$. Its modulus represents the distance between the two vectors $\hat{\mathbf{y}}$ and $\mathbf{y}$. Patience, we are almost there... :-)
The goal is to minimize this distance. If you refer the the figure above and imagine moving around your $\hat{\mathbf{y}}$ vector inside the subspace spanned by $\mathbf{x}_1$ and $\mathbf{x}_2$ (i.e. the plane) (you also have to imagine $\mathbf{e}$ moving with it going from the head of the vector $\hat{\mathbf{y}}$ to the head of the vector $\mathbf{y}$), then, where do you think that the distance will be minimal?
This happens when $\hat{\mathbf{y}}$ is just under $\mathbf{y}$ such that $\mathbf{e}$ becomes perpendicular to the subspace.
Conclusion:
Minimizing the distance (technically the squared distance) between $\hat{\mathbf{y}}$ and $\mathbf{y}$ is equivalent to having the vector representing this distance perpendicular to the subspace spanned by the feature vectors! | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear
You have to think about it geometrically in terms of vectors and distances between them!
To understand the idea refer to the next slide:
In this example, you have two feature vectors $\mathbf{x}_1$ a |
34,707 | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear regression? | If you prefer an algebraic answer to the +1 geometric answer by MedNait, note that
$$
y-\hat y=My
$$
with $M=I-X(X'X)^{-1}X'$ the "residual maker matrix".
Then,
$$MX=X-X(X'X)^{-1}X'X=X-X=0$$ | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear | If you prefer an algebraic answer to the +1 geometric answer by MedNait, note that
$$
y-\hat y=My
$$
with $M=I-X(X'X)^{-1}X'$ the "residual maker matrix".
Then,
$$MX=X-X(X'X)^{-1}X'X=X-X=0$$ | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear regression?
If you prefer an algebraic answer to the +1 geometric answer by MedNait, note that
$$
y-\hat y=My
$$
with $M=I-X(X'X)^{-1}X'$ the "residual maker matrix".
Then,
$$MX=X-X(X'X)^{-1}X'X=X-X=0$$ | Why is $\mathbf{y}-\mathbf{\hat{y}}$ perpendicular to the subspace spanned by $\mathbf{x}$ in linear
If you prefer an algebraic answer to the +1 geometric answer by MedNait, note that
$$
y-\hat y=My
$$
with $M=I-X(X'X)^{-1}X'$ the "residual maker matrix".
Then,
$$MX=X-X(X'X)^{-1}X'X=X-X=0$$ |
34,708 | How does R calculate the p-value for this binomial regression? | It may help you to read my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR? Your question here is nearly a duplicate of that, but there are a couple of additional elements in your question that can be addressed.
As @CliffAB notes, the p-values in the summary.glm() output are from Wald tests. These are analogous to $t$-tests of coefficients for a linear model in that they are the difference between the fitted value of the coefficient and the reference value (taken to be $0$), divided by the standard error. The difference is that these are taken to be distributed as a standard normal instead of $t$. On the other hand, these are valid for large samples and we don't necessarily know what constitutes a 'large sample' in any given case.
Using anova.glm() gives you access to different tests. When you set test="Rao", it gives you the p-value from a score test. And when you set either test="Chisq" or test="LRT" (they are the same), it gives you the p-value from a likelihood ratio test.
The anova.glm() function does test the same null hypothesis as the Wald test in the summary() output in this case. That is only because your model has just one variable. The anova.glm() function will perform sequential tests, which are analogous to 'type I SS' in a linear setting, whereas the Wald tests from summary() are analogous to 'type III SS' in a linear setting (see my answer here: How to interpret type I, type II, and type III ANOVA and MANOVA?). Consider:
x2 = rnorm(n)
m2 = glm(y~x+x2, family="binomial")
summary(m2)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -0.05906436 0.186876339 -0.3160612 7.519561e-01
# x -0.01567551 0.003537183 -4.4316372 9.352029e-06
# x2 -0.05967796 0.099093504 -0.6022388 5.470152e-01
anova(m2, test="LRT")
# Terms added sequentially (first to last)
#
# Df Deviance Resid. Df Resid. Dev Pr(>Chi)
# NULL 499 619.10
# x 1 20.3841 498 598.72 6.335e-06 ***
# x2 1 0.3627 497 598.35 0.547
m3 = glm(y~x2+x, family="binomial") # I just switched the order of x & x2 here
summary(m3)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -0.05906436 0.186876339 -0.3160612 7.519561e-01
# x2 -0.05967796 0.099093504 -0.6022388 5.470152e-01 # these are the same
# x -0.01567551 0.003537183 -4.4316372 9.352029e-06 # as above
anova(m3, test="LRT")
# Terms added sequentially (first to last)
#
# Df Deviance Resid. Df Resid. Dev Pr(>Chi)
# NULL 499 619.10
# x2 1 0.1585 498 618.94 0.6906 # these differ from the
# x 1 20.5883 497 598.35 5.694e-06 *** # anova output above
You can shoehorn the anova.glm() function to give you score and likelihood ratio tests of individual variables in a multiple logistic regression model that are analogous to 'type III SS', but it is tedious. You would need to keep refitting your model so that each variable in turn is listed last in the formula provided to the glm() call. The last p-value listed in the anova.glm() output is one that will be analogous to 'type III SS'.
To get the score or likelihood ratio tests of individual variables more conveniently, use drop1() instead. Consider:
drop1(m3, test="LRT")
# Single term deletions
#
# Model:
# y ~ x2 + x
# Df Deviance AIC LRT Pr(>Chi)
# <none> 598.35 604.35
# x2 1 598.72 602.72 0.3627 0.547 # the same as when x2 is last above
# x 1 618.94 622.94 20.5883 5.694e-06 *** # the same as when x is last above | How does R calculate the p-value for this binomial regression? | It may help you to read my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR? Your question here is nearly a duplicat | How does R calculate the p-value for this binomial regression?
It may help you to read my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR? Your question here is nearly a duplicate of that, but there are a couple of additional elements in your question that can be addressed.
As @CliffAB notes, the p-values in the summary.glm() output are from Wald tests. These are analogous to $t$-tests of coefficients for a linear model in that they are the difference between the fitted value of the coefficient and the reference value (taken to be $0$), divided by the standard error. The difference is that these are taken to be distributed as a standard normal instead of $t$. On the other hand, these are valid for large samples and we don't necessarily know what constitutes a 'large sample' in any given case.
Using anova.glm() gives you access to different tests. When you set test="Rao", it gives you the p-value from a score test. And when you set either test="Chisq" or test="LRT" (they are the same), it gives you the p-value from a likelihood ratio test.
The anova.glm() function does test the same null hypothesis as the Wald test in the summary() output in this case. That is only because your model has just one variable. The anova.glm() function will perform sequential tests, which are analogous to 'type I SS' in a linear setting, whereas the Wald tests from summary() are analogous to 'type III SS' in a linear setting (see my answer here: How to interpret type I, type II, and type III ANOVA and MANOVA?). Consider:
x2 = rnorm(n)
m2 = glm(y~x+x2, family="binomial")
summary(m2)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -0.05906436 0.186876339 -0.3160612 7.519561e-01
# x -0.01567551 0.003537183 -4.4316372 9.352029e-06
# x2 -0.05967796 0.099093504 -0.6022388 5.470152e-01
anova(m2, test="LRT")
# Terms added sequentially (first to last)
#
# Df Deviance Resid. Df Resid. Dev Pr(>Chi)
# NULL 499 619.10
# x 1 20.3841 498 598.72 6.335e-06 ***
# x2 1 0.3627 497 598.35 0.547
m3 = glm(y~x2+x, family="binomial") # I just switched the order of x & x2 here
summary(m3)$coefficients
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) -0.05906436 0.186876339 -0.3160612 7.519561e-01
# x2 -0.05967796 0.099093504 -0.6022388 5.470152e-01 # these are the same
# x -0.01567551 0.003537183 -4.4316372 9.352029e-06 # as above
anova(m3, test="LRT")
# Terms added sequentially (first to last)
#
# Df Deviance Resid. Df Resid. Dev Pr(>Chi)
# NULL 499 619.10
# x2 1 0.1585 498 618.94 0.6906 # these differ from the
# x 1 20.5883 497 598.35 5.694e-06 *** # anova output above
You can shoehorn the anova.glm() function to give you score and likelihood ratio tests of individual variables in a multiple logistic regression model that are analogous to 'type III SS', but it is tedious. You would need to keep refitting your model so that each variable in turn is listed last in the formula provided to the glm() call. The last p-value listed in the anova.glm() output is one that will be analogous to 'type III SS'.
To get the score or likelihood ratio tests of individual variables more conveniently, use drop1() instead. Consider:
drop1(m3, test="LRT")
# Single term deletions
#
# Model:
# y ~ x2 + x
# Df Deviance AIC LRT Pr(>Chi)
# <none> 598.35 604.35
# x2 1 598.72 602.72 0.3627 0.547 # the same as when x2 is last above
# x 1 618.94 622.94 20.5883 5.694e-06 *** # the same as when x is last above | How does R calculate the p-value for this binomial regression?
It may help you to read my answer here: Why do my p-values differ between logistic regression output, chi-squared test, and the confidence interval for the OR? Your question here is nearly a duplicat |
34,709 | How does R calculate the p-value for this binomial regression? | In R, the summary function for glm computes the p-value using a simple Wald statistic, i.e.
$2 \times \Phi \left(\frac{-|\hat \beta|} { SE(\hat \beta) } \right) $
where $\hat \beta$ is the regression parameter of interest, $SE(\hat \beta)$ is the standard error of this estimated regression parameter and $\Phi$ is the CDF of a standard normal distribution.
To recreate this from your output, try
beta = coef(model)[2]
# getting estimate
B_SE = sqrt(vcov(model)[2,2])
# extracting standard error
pvalue = pnorm(-abs(beta) / B_SE) * 2
# pvalue = 1.027859e-05 | How does R calculate the p-value for this binomial regression? | In R, the summary function for glm computes the p-value using a simple Wald statistic, i.e.
$2 \times \Phi \left(\frac{-|\hat \beta|} { SE(\hat \beta) } \right) $
where $\hat \beta$ is the regressio | How does R calculate the p-value for this binomial regression?
In R, the summary function for glm computes the p-value using a simple Wald statistic, i.e.
$2 \times \Phi \left(\frac{-|\hat \beta|} { SE(\hat \beta) } \right) $
where $\hat \beta$ is the regression parameter of interest, $SE(\hat \beta)$ is the standard error of this estimated regression parameter and $\Phi$ is the CDF of a standard normal distribution.
To recreate this from your output, try
beta = coef(model)[2]
# getting estimate
B_SE = sqrt(vcov(model)[2,2])
# extracting standard error
pvalue = pnorm(-abs(beta) / B_SE) * 2
# pvalue = 1.027859e-05 | How does R calculate the p-value for this binomial regression?
In R, the summary function for glm computes the p-value using a simple Wald statistic, i.e.
$2 \times \Phi \left(\frac{-|\hat \beta|} { SE(\hat \beta) } \right) $
where $\hat \beta$ is the regressio |
34,710 | Step Change Detection | There may be some more sophisticated methods for this but here is my first thought.
You basically want to take the derivative of the function and find where it is the largest. Numerically, you can just take the difference between data points and find which two points have the biggest difference. Then the midpoint of the x-values for these two points is your location of biggest change.
This simple method is susceptible to the noise. So you can first filter the data using a filter that does not shift the data to the right or left. If you use a simple FIR filter, then filter front to back and then filter the result from back to front. The result is a doubly filtered and NON shifted data set. Then follow the procedure above to find the point with the largest difference between values.
You can also use more sophisticated numerical differential calculations that use more then the difference of two points. | Step Change Detection | There may be some more sophisticated methods for this but here is my first thought.
You basically want to take the derivative of the function and find where it is the largest. Numerically, you can j | Step Change Detection
There may be some more sophisticated methods for this but here is my first thought.
You basically want to take the derivative of the function and find where it is the largest. Numerically, you can just take the difference between data points and find which two points have the biggest difference. Then the midpoint of the x-values for these two points is your location of biggest change.
This simple method is susceptible to the noise. So you can first filter the data using a filter that does not shift the data to the right or left. If you use a simple FIR filter, then filter front to back and then filter the result from back to front. The result is a doubly filtered and NON shifted data set. Then follow the procedure above to find the point with the largest difference between values.
You can also use more sophisticated numerical differential calculations that use more then the difference of two points. | Step Change Detection
There may be some more sophisticated methods for this but here is my first thought.
You basically want to take the derivative of the function and find where it is the largest. Numerically, you can j |
34,711 | Step Change Detection | Your data visually suggests an asymptotic (gradual) change to the new level. Time series methods can often be used to detect these kinds of structures even if the data is not time series. Please post your data and I may be able to demonstrate this with "toys" at my disposal. If your data is time series then as @jason reflected one needs to deal effectively with the noise model to correctly "see" the structure.
EDITED UPON RECEIPT OF DATA:
Modelling is often an iterative approach with interim steps providing valuable clues to a useful model. I took your data and introduced it to AUTOBOX (one of my toys which I have helped develop). An initial graph strongly suggested a longitudinal (chronological) data set where the X series is reported at fixed intervals. AUTOBOX automatically suggested a standard ARIMA model (with Intervention Detection) replacing the non-stationary X with a differencing operator. Here is the actual/fit/forecast graph and the suggested model.
Upon examination another possible model incorporating a lag structure for an indicator variable suggested itself. I introduced a Pulse at time period 76 (a Dynamic Predictor expressly allowing up to a possible lag effect of 50 periods) (the beginning of the transition) to deal with the relationship between the original Y and the user-suggested X in order to more fully investigate the effect of X than accept the total setting-aside of X.
Following is the actual-fit-forecast graph for that approach and the identified robust transfer function model . with residual plot and residual acf here
The final model captures the dynamics in certain lags of the Dynamic Predictor and a few pulses and a reasonable memory structure.
Even the most powerful analysis packages often need some guidance when dealing with complex real world data sets like this one as nothing compares to the creative human mind. | Step Change Detection | Your data visually suggests an asymptotic (gradual) change to the new level. Time series methods can often be used to detect these kinds of structures even if the data is not time series. Please post | Step Change Detection
Your data visually suggests an asymptotic (gradual) change to the new level. Time series methods can often be used to detect these kinds of structures even if the data is not time series. Please post your data and I may be able to demonstrate this with "toys" at my disposal. If your data is time series then as @jason reflected one needs to deal effectively with the noise model to correctly "see" the structure.
EDITED UPON RECEIPT OF DATA:
Modelling is often an iterative approach with interim steps providing valuable clues to a useful model. I took your data and introduced it to AUTOBOX (one of my toys which I have helped develop). An initial graph strongly suggested a longitudinal (chronological) data set where the X series is reported at fixed intervals. AUTOBOX automatically suggested a standard ARIMA model (with Intervention Detection) replacing the non-stationary X with a differencing operator. Here is the actual/fit/forecast graph and the suggested model.
Upon examination another possible model incorporating a lag structure for an indicator variable suggested itself. I introduced a Pulse at time period 76 (a Dynamic Predictor expressly allowing up to a possible lag effect of 50 periods) (the beginning of the transition) to deal with the relationship between the original Y and the user-suggested X in order to more fully investigate the effect of X than accept the total setting-aside of X.
Following is the actual-fit-forecast graph for that approach and the identified robust transfer function model . with residual plot and residual acf here
The final model captures the dynamics in certain lags of the Dynamic Predictor and a few pulses and a reasonable memory structure.
Even the most powerful analysis packages often need some guidance when dealing with complex real world data sets like this one as nothing compares to the creative human mind. | Step Change Detection
Your data visually suggests an asymptotic (gradual) change to the new level. Time series methods can often be used to detect these kinds of structures even if the data is not time series. Please post |
34,712 | Step Change Detection | One technique is to test all values of the x variable for the standard deviation of the data before and after it. For a true step function, the sum of those two will be minimal at the step location, and the minimum should be a good starting parameter for your nonlinear function.
Here is a plot of your original data (black), the standard deviation before x (blue), after x (red) and the sum of the last two (green). | Step Change Detection | One technique is to test all values of the x variable for the standard deviation of the data before and after it. For a true step function, the sum of those two will be minimal at the step location, a | Step Change Detection
One technique is to test all values of the x variable for the standard deviation of the data before and after it. For a true step function, the sum of those two will be minimal at the step location, and the minimum should be a good starting parameter for your nonlinear function.
Here is a plot of your original data (black), the standard deviation before x (blue), after x (red) and the sum of the last two (green). | Step Change Detection
One technique is to test all values of the x variable for the standard deviation of the data before and after it. For a true step function, the sum of those two will be minimal at the step location, a |
34,713 | Step Change Detection | I recognize that this question is old. But I wanted to throw another method out there. Canny wrote a paper (A Computational Approach to Edge Detection) where he solved this problem in the two dimensional case for edge detection in images. You can read the paper if you like, but to cut to the chase, you can get a very good approximation to the change point by doing the following:
Perform the convolution of your signal with the derivative of the Gaussian.
$$
f(x) = \frac{-x}{\chi^2} e^{-\frac{x^2}{\sigma^2}}
$$
where $\chi$ is a scaling factor.
The peak of the response is where the change point occurs.
In my experience with this method, I have found that choosing the correct scaling parameters is difficult. But there may be more work on this that I am not aware of.
I have summarized Canny's paper and provided an example here. | Step Change Detection | I recognize that this question is old. But I wanted to throw another method out there. Canny wrote a paper (A Computational Approach to Edge Detection) where he solved this problem in the two dimensio | Step Change Detection
I recognize that this question is old. But I wanted to throw another method out there. Canny wrote a paper (A Computational Approach to Edge Detection) where he solved this problem in the two dimensional case for edge detection in images. You can read the paper if you like, but to cut to the chase, you can get a very good approximation to the change point by doing the following:
Perform the convolution of your signal with the derivative of the Gaussian.
$$
f(x) = \frac{-x}{\chi^2} e^{-\frac{x^2}{\sigma^2}}
$$
where $\chi$ is a scaling factor.
The peak of the response is where the change point occurs.
In my experience with this method, I have found that choosing the correct scaling parameters is difficult. But there may be more work on this that I am not aware of.
I have summarized Canny's paper and provided an example here. | Step Change Detection
I recognize that this question is old. But I wanted to throw another method out there. Canny wrote a paper (A Computational Approach to Edge Detection) where he solved this problem in the two dimensio |
34,714 | Step Change Detection | You may investigate Wavelet tranformed time-series using short period types haar/db4.
I have no pointers but just some search terms, try 'wavelet change point detection'.
There are several R packages on Wavelets, see time-series task view: https://cran.r-project.org/web/views/TimeSeries.html
Look here for some example:
http://it.mathworks.com/help/wavelet/examples/detecting-discontinuities-and-breakdown-points.html?requestedDomain=www.mathworks.com
For theory look for Mallat et Hwang paper: "Singularity detection and processing with wavelets"
See related answer: Application of wavelets to time-series-based anomaly detection algorithms | Step Change Detection | You may investigate Wavelet tranformed time-series using short period types haar/db4.
I have no pointers but just some search terms, try 'wavelet change point detection'.
There are several R package | Step Change Detection
You may investigate Wavelet tranformed time-series using short period types haar/db4.
I have no pointers but just some search terms, try 'wavelet change point detection'.
There are several R packages on Wavelets, see time-series task view: https://cran.r-project.org/web/views/TimeSeries.html
Look here for some example:
http://it.mathworks.com/help/wavelet/examples/detecting-discontinuities-and-breakdown-points.html?requestedDomain=www.mathworks.com
For theory look for Mallat et Hwang paper: "Singularity detection and processing with wavelets"
See related answer: Application of wavelets to time-series-based anomaly detection algorithms | Step Change Detection
You may investigate Wavelet tranformed time-series using short period types haar/db4.
I have no pointers but just some search terms, try 'wavelet change point detection'.
There are several R package |
34,715 | Difference between correlation and covariance: is covariance only useful if the relation is linear? | As @RichardHardy points out in his comment, correlation is simply scaled covariance. So, they are useful for exactly the same types of relationships, but correlations are comparable across different relationships and correlations will not be affected by choice of units, while covariances will.
set.seed(123)
htin <- rnorm(100,68,3)
wtpound <- htin*2.5 + rnorm(100,0,5)
htm <- htin*0.0254
wtkg <- wtpound/2.2
cor(htin,wtpound) #0.81
cov(htin,wtpound) #18.09
cor(htm,wtkg) #0.81
cov(htm,wtkg) #0.21
If you have a perfect U shaped relation, both cov and corr will be 0:
x <- seq(-4,4,by = 0.1)
y <- x^2
cor(x,y) #1.63*10^-16
cov(x,y) #1.89*10^-15 | Difference between correlation and covariance: is covariance only useful if the relation is linear? | As @RichardHardy points out in his comment, correlation is simply scaled covariance. So, they are useful for exactly the same types of relationships, but correlations are comparable across different r | Difference between correlation and covariance: is covariance only useful if the relation is linear?
As @RichardHardy points out in his comment, correlation is simply scaled covariance. So, they are useful for exactly the same types of relationships, but correlations are comparable across different relationships and correlations will not be affected by choice of units, while covariances will.
set.seed(123)
htin <- rnorm(100,68,3)
wtpound <- htin*2.5 + rnorm(100,0,5)
htm <- htin*0.0254
wtkg <- wtpound/2.2
cor(htin,wtpound) #0.81
cov(htin,wtpound) #18.09
cor(htm,wtkg) #0.81
cov(htm,wtkg) #0.21
If you have a perfect U shaped relation, both cov and corr will be 0:
x <- seq(-4,4,by = 0.1)
y <- x^2
cor(x,y) #1.63*10^-16
cov(x,y) #1.89*10^-15 | Difference between correlation and covariance: is covariance only useful if the relation is linear?
As @RichardHardy points out in his comment, correlation is simply scaled covariance. So, they are useful for exactly the same types of relationships, but correlations are comparable across different r |
34,716 | Difference between correlation and covariance: is covariance only useful if the relation is linear? | Unlike Pearson correlation, covariance itself is not a measure of the magnitude of linear relationship. It is a measure of co-variation (which could be just monotonic). This is because covariance depends not only on the strength of linear association but also on the magnitude of the variances. In order for covariance to be only the measure of linear association the variances must be controlled for somehow, without that control covariance might occur stronger under nonlinear underlying relationship than under linear one.
Example: let there be completely linearly tied variables X and Y. Without touching Y move quite apart two polar utmost values of X. Now the relationship is only monotonic, but due to widening the range of X the covariance has enhanced.
But covariance has theoretical upper limit equal $\sigma_X \sigma_Y$ which is attainable only under exact linear relationship. In the example, if we back-rescale the widened X data to its original variance the newer value of covariance will drop lower, not higher, than the very initial value. And this is because we had abandoned the linear relationship for monotonic one. Linearity coefficient, the Pearson $r=cov_{XY}/(\sigma_X \sigma_Y)$ is nothing else than the covariance relative that its upper limit.
But the limiting fact that - under controlling the variances (such as standardizing them) - covariance is maximized when the bond is linear, does not make covariance the measure of the magnitude of linear association. It would be improper to call the covariance coefficient the "linear covariance coefficient" like we say it "linear correlation coefficient".
However, covariance is often used in place of Pearson correlation in analyses which assume linear models. For example, you can do factor analysis based on covariance matrix rather than correlation matrix. While covariance can tap not just linearity among the manifest variables, latent factors yet effect the variables but linearly (Pt 2) according to the model, therefore accounting or taking responsibility only for linear bonds between them.
Covariance the higher the...
more monotonic is the association (i.e. the fewer are the
instances of inversions in the data
greater is the combined variability $\sigma_X^2+\sigma_Y^2$
more equal are the two variabilities
more equal or proportional are the variables' values: under
condition that $\sigma_X=\sigma_Y$ cov will be maximal when
$X_i=Y_i$ (considering already centered variables), or, equivalently,
under $\sigma_X \ne \sigma_Y$ cov will be maximal when $X_i=kY_i$.
Linearity. | Difference between correlation and covariance: is covariance only useful if the relation is linear? | Unlike Pearson correlation, covariance itself is not a measure of the magnitude of linear relationship. It is a measure of co-variation (which could be just monotonic). This is because covariance depe | Difference between correlation and covariance: is covariance only useful if the relation is linear?
Unlike Pearson correlation, covariance itself is not a measure of the magnitude of linear relationship. It is a measure of co-variation (which could be just monotonic). This is because covariance depends not only on the strength of linear association but also on the magnitude of the variances. In order for covariance to be only the measure of linear association the variances must be controlled for somehow, without that control covariance might occur stronger under nonlinear underlying relationship than under linear one.
Example: let there be completely linearly tied variables X and Y. Without touching Y move quite apart two polar utmost values of X. Now the relationship is only monotonic, but due to widening the range of X the covariance has enhanced.
But covariance has theoretical upper limit equal $\sigma_X \sigma_Y$ which is attainable only under exact linear relationship. In the example, if we back-rescale the widened X data to its original variance the newer value of covariance will drop lower, not higher, than the very initial value. And this is because we had abandoned the linear relationship for monotonic one. Linearity coefficient, the Pearson $r=cov_{XY}/(\sigma_X \sigma_Y)$ is nothing else than the covariance relative that its upper limit.
But the limiting fact that - under controlling the variances (such as standardizing them) - covariance is maximized when the bond is linear, does not make covariance the measure of the magnitude of linear association. It would be improper to call the covariance coefficient the "linear covariance coefficient" like we say it "linear correlation coefficient".
However, covariance is often used in place of Pearson correlation in analyses which assume linear models. For example, you can do factor analysis based on covariance matrix rather than correlation matrix. While covariance can tap not just linearity among the manifest variables, latent factors yet effect the variables but linearly (Pt 2) according to the model, therefore accounting or taking responsibility only for linear bonds between them.
Covariance the higher the...
more monotonic is the association (i.e. the fewer are the
instances of inversions in the data
greater is the combined variability $\sigma_X^2+\sigma_Y^2$
more equal are the two variabilities
more equal or proportional are the variables' values: under
condition that $\sigma_X=\sigma_Y$ cov will be maximal when
$X_i=Y_i$ (considering already centered variables), or, equivalently,
under $\sigma_X \ne \sigma_Y$ cov will be maximal when $X_i=kY_i$.
Linearity. | Difference between correlation and covariance: is covariance only useful if the relation is linear?
Unlike Pearson correlation, covariance itself is not a measure of the magnitude of linear relationship. It is a measure of co-variation (which could be just monotonic). This is because covariance depe |
34,717 | Difference between correlation and covariance: is covariance only useful if the relation is linear? | Well, I think that a good measure of dependence of two random variables must be scale invariant. The philosophy is simple, if I know how random variables $X$ and $Y$ qualitatively depends on each other then this qualitative dependence should not change if we made a change of scale, only the magnitude of the dependence. This is why we normalize the covariance by the product of the standard deviations. The motivation to do that specifically normalization comes from linear algebra, at the end, the correlation is the angle between $X$ and $Y$. | Difference between correlation and covariance: is covariance only useful if the relation is linear? | Well, I think that a good measure of dependence of two random variables must be scale invariant. The philosophy is simple, if I know how random variables $X$ and $Y$ qualitatively depends on each othe | Difference between correlation and covariance: is covariance only useful if the relation is linear?
Well, I think that a good measure of dependence of two random variables must be scale invariant. The philosophy is simple, if I know how random variables $X$ and $Y$ qualitatively depends on each other then this qualitative dependence should not change if we made a change of scale, only the magnitude of the dependence. This is why we normalize the covariance by the product of the standard deviations. The motivation to do that specifically normalization comes from linear algebra, at the end, the correlation is the angle between $X$ and $Y$. | Difference between correlation and covariance: is covariance only useful if the relation is linear?
Well, I think that a good measure of dependence of two random variables must be scale invariant. The philosophy is simple, if I know how random variables $X$ and $Y$ qualitatively depends on each othe |
34,718 | Does ReLU layer work well for a shallow network? | Changing the activation function interacts with all of the other configuration choices that you've made, from the initialization method to the regularization parameters. You'll have to tune the network again. | Does ReLU layer work well for a shallow network? | Changing the activation function interacts with all of the other configuration choices that you've made, from the initialization method to the regularization parameters. You'll have to tune the networ | Does ReLU layer work well for a shallow network?
Changing the activation function interacts with all of the other configuration choices that you've made, from the initialization method to the regularization parameters. You'll have to tune the network again. | Does ReLU layer work well for a shallow network?
Changing the activation function interacts with all of the other configuration choices that you've made, from the initialization method to the regularization parameters. You'll have to tune the networ |
34,719 | Does ReLU layer work well for a shallow network? | When you replace sigmoid or tanh with ReLU, typically you will also need to:
Decrease your learning rate significantly, usually by 1/100th. This is because ReLU output grows without bound and is much less resistant to high learning rates.
Increase number of parameters (i.e. weight) by around 2X or more. This is because of dead relu issue.
You might have to increase number of epochs due to much lower LR.
You will typically need better initialization method than random init, such as Glorot init or He init. Many times you can get by without this but at expense of much slower convergence.
Very likely you will also need more stronger regularization such as dropout, again because of larger number of parameters and increased numbers of epochs.
So in summary, things are not as simple as swapping sigmoid/tanh with ReLU. As soon as you add ReLU, you need above changes to compensate for other effects. | Does ReLU layer work well for a shallow network? | When you replace sigmoid or tanh with ReLU, typically you will also need to:
Decrease your learning rate significantly, usually by 1/100th. This is because ReLU output grows without bound and is much | Does ReLU layer work well for a shallow network?
When you replace sigmoid or tanh with ReLU, typically you will also need to:
Decrease your learning rate significantly, usually by 1/100th. This is because ReLU output grows without bound and is much less resistant to high learning rates.
Increase number of parameters (i.e. weight) by around 2X or more. This is because of dead relu issue.
You might have to increase number of epochs due to much lower LR.
You will typically need better initialization method than random init, such as Glorot init or He init. Many times you can get by without this but at expense of much slower convergence.
Very likely you will also need more stronger regularization such as dropout, again because of larger number of parameters and increased numbers of epochs.
So in summary, things are not as simple as swapping sigmoid/tanh with ReLU. As soon as you add ReLU, you need above changes to compensate for other effects. | Does ReLU layer work well for a shallow network?
When you replace sigmoid or tanh with ReLU, typically you will also need to:
Decrease your learning rate significantly, usually by 1/100th. This is because ReLU output grows without bound and is much |
34,720 | Does ReLU layer work well for a shallow network? | ReLU i.e. Rectified Linear Unit and tanh both are non-linear activation function applied to neural layer. Both have their own importance. It only depends on the problem in hand that we want to solve and the output that we want. Sometimes people prefer to use ReLU over tanh because ReLU involves less computation.
When I started studying Deep Learning, I had the question Why do we not just use linear activation function instead of non-linear? Answer is output will be just linear combination of input and hidden layer will have no effect and so hidden layer will not be able to learn important feature.
For example, if we want the output to lie within (-1,1) then we need tanh. If we need output between (0,1) then use sigmoid function . In case of ReLU it will give max{0,x}.There are many other activation functions like leaky ReLU.
Now in order to choose appropriate activation function for our purpose to give better result it is just a matter of experiment and practice which is known as tuning in data science world.
In your case, you may need to tune your parameter which is known as parameter tuning like number of neurons in hidden layers, number of layers etc.
Does ReLU layer work well for a shallow network?
Yes,of course ReLU layer work well for a shallow network. | Does ReLU layer work well for a shallow network? | ReLU i.e. Rectified Linear Unit and tanh both are non-linear activation function applied to neural layer. Both have their own importance. It only depends on the problem in hand that we want to solve a | Does ReLU layer work well for a shallow network?
ReLU i.e. Rectified Linear Unit and tanh both are non-linear activation function applied to neural layer. Both have their own importance. It only depends on the problem in hand that we want to solve and the output that we want. Sometimes people prefer to use ReLU over tanh because ReLU involves less computation.
When I started studying Deep Learning, I had the question Why do we not just use linear activation function instead of non-linear? Answer is output will be just linear combination of input and hidden layer will have no effect and so hidden layer will not be able to learn important feature.
For example, if we want the output to lie within (-1,1) then we need tanh. If we need output between (0,1) then use sigmoid function . In case of ReLU it will give max{0,x}.There are many other activation functions like leaky ReLU.
Now in order to choose appropriate activation function for our purpose to give better result it is just a matter of experiment and practice which is known as tuning in data science world.
In your case, you may need to tune your parameter which is known as parameter tuning like number of neurons in hidden layers, number of layers etc.
Does ReLU layer work well for a shallow network?
Yes,of course ReLU layer work well for a shallow network. | Does ReLU layer work well for a shallow network?
ReLU i.e. Rectified Linear Unit and tanh both are non-linear activation function applied to neural layer. Both have their own importance. It only depends on the problem in hand that we want to solve a |
34,721 | Does ReLU layer work well for a shallow network? | I am wondering if it is due to that I did not find the best parameters or simply because ReLU is only good for deep networks?
I believe I can safely assume that you mean hyperparameters instead of parameters.
A neural network with 5 hidden layers is not shallow. You can consider it deep.
The hyperparameter space search for 'best' hyperparameters is a never ending task. By best I mean the hyperparameters that lets the network attain the global minima.
I agree with Sycorax that once you change the activation function you need to tune the network again. Usually, one can achieve comparable performance across many different configurations of hyperparams for the same task. | Does ReLU layer work well for a shallow network? | I am wondering if it is due to that I did not find the best parameters or simply because ReLU is only good for deep networks?
I believe I can safely assume that you mean hyperparameters instead of pa | Does ReLU layer work well for a shallow network?
I am wondering if it is due to that I did not find the best parameters or simply because ReLU is only good for deep networks?
I believe I can safely assume that you mean hyperparameters instead of parameters.
A neural network with 5 hidden layers is not shallow. You can consider it deep.
The hyperparameter space search for 'best' hyperparameters is a never ending task. By best I mean the hyperparameters that lets the network attain the global minima.
I agree with Sycorax that once you change the activation function you need to tune the network again. Usually, one can achieve comparable performance across many different configurations of hyperparams for the same task. | Does ReLU layer work well for a shallow network?
I am wondering if it is due to that I did not find the best parameters or simply because ReLU is only good for deep networks?
I believe I can safely assume that you mean hyperparameters instead of pa |
34,722 | How do iterative methods for solving maximizing likelihood problems work? | By necessity I will barely scratch the surface here (to do the topic justice would require a much longer answer), but I think that this is such an important issue that at least an outline of some common approaches should be given, with links to some of the things that are mentioned along the way.
Does anyone know about the computational iteration processes for maximum likelihood estimation?
There's not a single method, but many different methods suitable for different circumstances.
If these set of equations cannot be solved practically then how the computer solves them?
By "practically" I assume you mean something like "algebraically in closed form" -- and strictly speaking the likelihood itself is not solved. Solving is normally something you do with equations, to find arguments that satisfy the equation.
Maximizing the likelihood can sometimes be turned into a problem that involves solving an equation, though.
Recall that the likelihood is a function of the parameters.
Maximizing the likelihood -- finding the parameters that yield the largest value of the likelihood function - is therefore an optimization problem.
There are numerous approaches that are used to optimize functions.
In many cases the log of the likelihood is easier to deal with (for a variety of reasons); the parameters that maximize the log-likelihood will also maximize the likelihood. Further, it's common to take the negative (or sometimes twice the negative) of the log-likelihood and minimize it; in part this is because most optimizers are written as function-minimizers rather than maximizers, though $-2\log\mathcal{L}$ also has important statistical uses.
For functions of continuous random variables it is sometimes possible to use differential calculus to obtain a set of equations whose solution will be turning points of the likelihood function (which can include local maxima; if you can show there's a unique global maximum it will either be at a turning point or a boundary point). However, for most moderately complex problems (and even many fairly simple ones) it's often better to try to maximize the likelihood more directly than try to solve such equations.
More generally, iterative computer methods are used to step through a sequence of parameter-values in such a way as to (if successful) approximately locate the maximum. There are a number of approaches of varying sophistication and requirements. For example, one approach is simply "head downhill" on the likelihood surface (gradient descent/steepest descent), but there's also Newton's method (also see here), various quasi-Newton methods (like BFGS). One approach closely related to Newton's method commonly used to maximize likelihood is Fisher scoring.
These sorts of methods generally require at least first derivatives of the likelihood usually obtained algebraically (though in some cases numeric derivatives are used). Some derivative-free methods exist (like Nelder-Mead, for example). Some methods combine several different techniques, taking advantage of faster methods when they work but using safer-but-slower approaches otherwise.
In general, however, multiple local maxima can occur, and then (at least in most cases) identifying the location of the global maximum may be very difficult.
Here's a simple example, with a small sample from a Cauchy distribution:
Sometimes maxima occur at boundaries; this may cause difficulties for many of those methods (at least if applied uncritically).
A common example offered to beginning students is to estimate $\theta$ from a sample from a uniform on $(0,\theta)$ -- just blindly trying to set the derivative of the likelihood (or the log-likelihood) to zero will be unfruitful, but it's a trivial case to optimize with a little care.
Sometimes an iterated function ($\theta = F(\theta)$) can be set up such that the maximum of the likelihood corresponds to a fixed point of the function. An example is seen in this answer.
In other circumstances, you may have discrete parameters. One common example is the hypergeometric distribution (the parameter being the number of success states in the population). However in that particular case the likelihood can be shown to be increasing to the left of a particular value, and decreasing to the right of it, making the solution simple for the hypergeometric.
In some discrete cases finding the actual ML may be NP-hard. Sometimes various approximations may be used to get reasonable estimates in reasonable time. | How do iterative methods for solving maximizing likelihood problems work? | By necessity I will barely scratch the surface here (to do the topic justice would require a much longer answer), but I think that this is such an important issue that at least an outline of some comm | How do iterative methods for solving maximizing likelihood problems work?
By necessity I will barely scratch the surface here (to do the topic justice would require a much longer answer), but I think that this is such an important issue that at least an outline of some common approaches should be given, with links to some of the things that are mentioned along the way.
Does anyone know about the computational iteration processes for maximum likelihood estimation?
There's not a single method, but many different methods suitable for different circumstances.
If these set of equations cannot be solved practically then how the computer solves them?
By "practically" I assume you mean something like "algebraically in closed form" -- and strictly speaking the likelihood itself is not solved. Solving is normally something you do with equations, to find arguments that satisfy the equation.
Maximizing the likelihood can sometimes be turned into a problem that involves solving an equation, though.
Recall that the likelihood is a function of the parameters.
Maximizing the likelihood -- finding the parameters that yield the largest value of the likelihood function - is therefore an optimization problem.
There are numerous approaches that are used to optimize functions.
In many cases the log of the likelihood is easier to deal with (for a variety of reasons); the parameters that maximize the log-likelihood will also maximize the likelihood. Further, it's common to take the negative (or sometimes twice the negative) of the log-likelihood and minimize it; in part this is because most optimizers are written as function-minimizers rather than maximizers, though $-2\log\mathcal{L}$ also has important statistical uses.
For functions of continuous random variables it is sometimes possible to use differential calculus to obtain a set of equations whose solution will be turning points of the likelihood function (which can include local maxima; if you can show there's a unique global maximum it will either be at a turning point or a boundary point). However, for most moderately complex problems (and even many fairly simple ones) it's often better to try to maximize the likelihood more directly than try to solve such equations.
More generally, iterative computer methods are used to step through a sequence of parameter-values in such a way as to (if successful) approximately locate the maximum. There are a number of approaches of varying sophistication and requirements. For example, one approach is simply "head downhill" on the likelihood surface (gradient descent/steepest descent), but there's also Newton's method (also see here), various quasi-Newton methods (like BFGS). One approach closely related to Newton's method commonly used to maximize likelihood is Fisher scoring.
These sorts of methods generally require at least first derivatives of the likelihood usually obtained algebraically (though in some cases numeric derivatives are used). Some derivative-free methods exist (like Nelder-Mead, for example). Some methods combine several different techniques, taking advantage of faster methods when they work but using safer-but-slower approaches otherwise.
In general, however, multiple local maxima can occur, and then (at least in most cases) identifying the location of the global maximum may be very difficult.
Here's a simple example, with a small sample from a Cauchy distribution:
Sometimes maxima occur at boundaries; this may cause difficulties for many of those methods (at least if applied uncritically).
A common example offered to beginning students is to estimate $\theta$ from a sample from a uniform on $(0,\theta)$ -- just blindly trying to set the derivative of the likelihood (or the log-likelihood) to zero will be unfruitful, but it's a trivial case to optimize with a little care.
Sometimes an iterated function ($\theta = F(\theta)$) can be set up such that the maximum of the likelihood corresponds to a fixed point of the function. An example is seen in this answer.
In other circumstances, you may have discrete parameters. One common example is the hypergeometric distribution (the parameter being the number of success states in the population). However in that particular case the likelihood can be shown to be increasing to the left of a particular value, and decreasing to the right of it, making the solution simple for the hypergeometric.
In some discrete cases finding the actual ML may be NP-hard. Sometimes various approximations may be used to get reasonable estimates in reasonable time. | How do iterative methods for solving maximizing likelihood problems work?
By necessity I will barely scratch the surface here (to do the topic justice would require a much longer answer), but I think that this is such an important issue that at least an outline of some comm |
34,723 | Intuition behind pearson correlation, co-variance and cosine similarity | We can ignore the matrix formulation, and just consider two vectors $x$ and $y$ (since the matrix formulation is just the vector operation repeated over different pairs of vectors). One intuitive/geometric distinction between covariance/correlation/cosine similarity is their invariance to different transformations of the input. That is, if we transform $x$ and $y$, under what types of transformations will the scores keep the same value?
Covariance subtracts the means before taking the dot product. Therefore, it's invariant to shifts.
Pearson correlation subtracts the means and divides by the standard deviations before taking the dot product. Therefore, it's invariant to shifts and scaling.
Cosine similarity divides by the norms before taking the dot product. Therefore it's invariant to scaling, but not shifts. Geometrically, it can be thought of as measuring the size of the angle between the two vectors (as its name suggests, it's the cosine of the angle).
All of these quantities depend on the dot product, so they can only detect linear structure. To address a question from the comments, mutual information is fully general, and can detect structure for any distribution. But, it's harder to estimate from finite data than other quantities, and more care must be taken. Also, it measures dependence, but doesn't indicate the direction of a relationship (e.g. variables that are correlated or anticorrelated can have the same same mutual information). Mutual information is a valid measure of dependence when no 'direction of relationship' even exists (non-monotonic relationships). If the goal is to detect relationships that are nonlinear but monotonic, then Spearman rank correlation and Kendall's tau are good options. | Intuition behind pearson correlation, co-variance and cosine similarity | We can ignore the matrix formulation, and just consider two vectors $x$ and $y$ (since the matrix formulation is just the vector operation repeated over different pairs of vectors). One intuitive/geom | Intuition behind pearson correlation, co-variance and cosine similarity
We can ignore the matrix formulation, and just consider two vectors $x$ and $y$ (since the matrix formulation is just the vector operation repeated over different pairs of vectors). One intuitive/geometric distinction between covariance/correlation/cosine similarity is their invariance to different transformations of the input. That is, if we transform $x$ and $y$, under what types of transformations will the scores keep the same value?
Covariance subtracts the means before taking the dot product. Therefore, it's invariant to shifts.
Pearson correlation subtracts the means and divides by the standard deviations before taking the dot product. Therefore, it's invariant to shifts and scaling.
Cosine similarity divides by the norms before taking the dot product. Therefore it's invariant to scaling, but not shifts. Geometrically, it can be thought of as measuring the size of the angle between the two vectors (as its name suggests, it's the cosine of the angle).
All of these quantities depend on the dot product, so they can only detect linear structure. To address a question from the comments, mutual information is fully general, and can detect structure for any distribution. But, it's harder to estimate from finite data than other quantities, and more care must be taken. Also, it measures dependence, but doesn't indicate the direction of a relationship (e.g. variables that are correlated or anticorrelated can have the same same mutual information). Mutual information is a valid measure of dependence when no 'direction of relationship' even exists (non-monotonic relationships). If the goal is to detect relationships that are nonlinear but monotonic, then Spearman rank correlation and Kendall's tau are good options. | Intuition behind pearson correlation, co-variance and cosine similarity
We can ignore the matrix formulation, and just consider two vectors $x$ and $y$ (since the matrix formulation is just the vector operation repeated over different pairs of vectors). One intuitive/geom |
34,724 | Restricted Maximum Likelihood (REML) Estimate of Variance Component | NB. I simplify notation somewhat and do not use bold typesetting.
The following rules for matrix differentials are useful:
\begin{align}
d\log \vert A\vert &= \mathrm{tr}(A^{-1}dA) \\
dA^{-1} & = -A^{-1}(dA)A^{-1}.
\end{align}
A good source for such rules and how to derive them is Magnus and Neudecker. That text also explains how to go between differentials and derivatives. You can also refer to this document by Minka. The Matrix Cookbook is another standard reference for such rules. In addition to derivatives, this answer also makes repeated use of cyclic invariance and linearity of the trace operator.
Based on these rules we get the following expressions for the differentials in question: $$
d\Sigma_i^{-1} = -\Sigma_i^{-1}d\Sigma_i \Sigma_i^{-1}
= -\Sigma^{-2}d\sigma^2,
$$
$$
d\log \vert \Sigma_i \vert = \mathrm{tr}\Sigma_i^{-1}d\Sigma_i
= \mathrm{tr}\Sigma_i^{-1}Id\sigma^2,
$$
and
\begin{align}
d\log\vert X_i'\Sigma_i^{-1}X_i\vert &= \mathrm{tr}[(X_i'\Sigma_iX)^{-1}X_i'd\Sigma_i^{-1}X_i] \\
&= -\mathrm{tr}[(X_i'\Sigma_iX)^{-1}X_i'(\Sigma_i^{-1}d\Sigma_i \Sigma_i^{-1})X_i]\\
&= -\mathrm{tr}[\Sigma_i^{-1}X_i(X_i'\Sigma_iX)^{-1}X_i'\Sigma_i^{-1}Id\sigma^2]
\end{align}
Thus, the gradient of the log-restricted likelihood up to scaling and additive terms not involving $\sigma^2$ is:
\begin{align}
\sum_i \frac{\partial}{\partial \sigma^2}\left[-\log \vert \Sigma_i \vert - \log \vert X_i'\Sigma_i^{-1}X_i \vert - (y_i - X_i\beta)'\Sigma_i^{-1}(y_i - X_i\beta) \right] = \\
\sum_i \mathrm{tr}\left[-\Sigma_i^{-1} + [\Sigma_i^{-1}X_i(X_i'\Sigma_i^{-1}X)^{-1}X_i'\Sigma_i^{-1}] + (y_i - X_i \beta)'\Sigma_i^{-2}(y_i - X_i\beta)\right].
\end{align}
Since the $\Sigma_i$ are (I assume) positive definite, and in particular full rank, setting the gradient to zero is equivalent to:
$$
\sum_i \mathrm{tr}\left[I - [X_i(X_i'\Sigma_i^{-1}X)^{-1}X_i'\Sigma_i^{-1}] - \Sigma_i^{-1}(y_i - X_i\beta)(y_i - X_i \beta)'\right] = 0.
$$
Now notice that $Q_i := I - [X_i(X_i'\Sigma_i^{-1}X)^{-1}X_i'\Sigma_i^{-1}]$ is a projection matrix onto the orthogonal complement of the column space of $X_i$. Thus, its trace equals the dimension of the space onto which it is projecting: $n_i - p$. Factoring out $\sigma^2$ then gives the REML estimate of $\sigma^2$ as the solution to $$\sigma^2 = \sum_i (y_i - X\beta)'[I + Z_iGZ_i' / \sigma^2]^{-1}(y_i - X_i\beta) / (N_0 - p),$$
assuming the optimization problem is convex.
This is different from your expression. It's possible I made a mistake somewhere and, in that case, hopefully you or another reader can spot it. After reading some more though, my impression is that mixed models are commonly parameterized in terms of $\tilde{G} = G/\sigma^2$. Parameterizing the first order condition derived here in terms of $\tilde{G}$ would make it agree with your first order condition. | Restricted Maximum Likelihood (REML) Estimate of Variance Component | NB. I simplify notation somewhat and do not use bold typesetting.
The following rules for matrix differentials are useful:
\begin{align}
d\log \vert A\vert &= \mathrm{tr}(A^{-1}dA) \\
dA^{-1} & = -A^ | Restricted Maximum Likelihood (REML) Estimate of Variance Component
NB. I simplify notation somewhat and do not use bold typesetting.
The following rules for matrix differentials are useful:
\begin{align}
d\log \vert A\vert &= \mathrm{tr}(A^{-1}dA) \\
dA^{-1} & = -A^{-1}(dA)A^{-1}.
\end{align}
A good source for such rules and how to derive them is Magnus and Neudecker. That text also explains how to go between differentials and derivatives. You can also refer to this document by Minka. The Matrix Cookbook is another standard reference for such rules. In addition to derivatives, this answer also makes repeated use of cyclic invariance and linearity of the trace operator.
Based on these rules we get the following expressions for the differentials in question: $$
d\Sigma_i^{-1} = -\Sigma_i^{-1}d\Sigma_i \Sigma_i^{-1}
= -\Sigma^{-2}d\sigma^2,
$$
$$
d\log \vert \Sigma_i \vert = \mathrm{tr}\Sigma_i^{-1}d\Sigma_i
= \mathrm{tr}\Sigma_i^{-1}Id\sigma^2,
$$
and
\begin{align}
d\log\vert X_i'\Sigma_i^{-1}X_i\vert &= \mathrm{tr}[(X_i'\Sigma_iX)^{-1}X_i'd\Sigma_i^{-1}X_i] \\
&= -\mathrm{tr}[(X_i'\Sigma_iX)^{-1}X_i'(\Sigma_i^{-1}d\Sigma_i \Sigma_i^{-1})X_i]\\
&= -\mathrm{tr}[\Sigma_i^{-1}X_i(X_i'\Sigma_iX)^{-1}X_i'\Sigma_i^{-1}Id\sigma^2]
\end{align}
Thus, the gradient of the log-restricted likelihood up to scaling and additive terms not involving $\sigma^2$ is:
\begin{align}
\sum_i \frac{\partial}{\partial \sigma^2}\left[-\log \vert \Sigma_i \vert - \log \vert X_i'\Sigma_i^{-1}X_i \vert - (y_i - X_i\beta)'\Sigma_i^{-1}(y_i - X_i\beta) \right] = \\
\sum_i \mathrm{tr}\left[-\Sigma_i^{-1} + [\Sigma_i^{-1}X_i(X_i'\Sigma_i^{-1}X)^{-1}X_i'\Sigma_i^{-1}] + (y_i - X_i \beta)'\Sigma_i^{-2}(y_i - X_i\beta)\right].
\end{align}
Since the $\Sigma_i$ are (I assume) positive definite, and in particular full rank, setting the gradient to zero is equivalent to:
$$
\sum_i \mathrm{tr}\left[I - [X_i(X_i'\Sigma_i^{-1}X)^{-1}X_i'\Sigma_i^{-1}] - \Sigma_i^{-1}(y_i - X_i\beta)(y_i - X_i \beta)'\right] = 0.
$$
Now notice that $Q_i := I - [X_i(X_i'\Sigma_i^{-1}X)^{-1}X_i'\Sigma_i^{-1}]$ is a projection matrix onto the orthogonal complement of the column space of $X_i$. Thus, its trace equals the dimension of the space onto which it is projecting: $n_i - p$. Factoring out $\sigma^2$ then gives the REML estimate of $\sigma^2$ as the solution to $$\sigma^2 = \sum_i (y_i - X\beta)'[I + Z_iGZ_i' / \sigma^2]^{-1}(y_i - X_i\beta) / (N_0 - p),$$
assuming the optimization problem is convex.
This is different from your expression. It's possible I made a mistake somewhere and, in that case, hopefully you or another reader can spot it. After reading some more though, my impression is that mixed models are commonly parameterized in terms of $\tilde{G} = G/\sigma^2$. Parameterizing the first order condition derived here in terms of $\tilde{G}$ would make it agree with your first order condition. | Restricted Maximum Likelihood (REML) Estimate of Variance Component
NB. I simplify notation somewhat and do not use bold typesetting.
The following rules for matrix differentials are useful:
\begin{align}
d\log \vert A\vert &= \mathrm{tr}(A^{-1}dA) \\
dA^{-1} & = -A^ |
34,725 | Restricted Maximum Likelihood (REML) Estimate of Variance Component | This is the AD Model Builder code for the model. This version will
estimate the fixed effects.
DATA_SECTION
init_number N // number of individuals
init_int p
init_int q
init_vector n(1,N) // number of time points
init_3darray X(1,N,1,n,1,p)
init_3darray Z(1,N,1,n,1,q)
init_matrix obsy(1,N,1,n)
PARAMETER_SECTION
init_number log_sigma
!! int q1=q*(q-1)/2;
init_vector chcoff(1,q1)
init_vector logs(1,q)
init_vector beta(1,p)
random_effects_matrix eps(1,N,1,q)
objective_function_value f
PROCEDURE_SECTION
for (int i=1;i<=N;i++)
{
f+=f1(i,eps(i),beta,log_sigma,logs,chcoff);
}
SEPARABLE_FUNCTION dvariable f1(int i,const dvar_vector& epsi,const dvar_vector beta,const prevariable & log_sigma,const dvar_vector& logs,const dvar_vector& chcoff)
dvariable sigma=exp(log_sigma);
dvar_vector s=exp(logs);
dvariable var=square(sigma);
dvar_matrix ch(1,q,1,q);
ch.initialize();
// ch is the choleski decomp of G
ch(1,1)=s(1);
int offset=0;
for (int j=2;j<=q;j++)
{
ch(j)(1,j-1)=chcoff(1+offset,j-1+offset).shift(1);
ch(j,j)=1.0;
ch(j)/=norm(ch(j));
offset+=j-1;
ch(j)*=s(j);
}
dvar_vector predy=X(i)*beta+Z(i)*(ch*epsi);
f+= 0.5*n(i)*log(var)+0.5*norm2(obsy(i)-predy)/var;
f+= 0.5*norm2(epsi);
The REML version is calculated by integrating over the fixed effects.
This involves changing one line in the above code.
init_vector beta(1,p)
is changed to
random_effects_vector beta(1,p)
Now suppose I wanted to modify this code to use the student t distribution.
The line
f+= 0.5*n(i)*log(var)+0.5*norm2(obsy(i)-predy)/var;
is changed to
f-=ld_student(obsy(i),predy,var,dof);
and the lines
init_number log_dof_coff
dvariable dof=1.0+exp(log_dof_coff);
are added to the code in the appropriate places to include the degrees of freedom parameter.
Note that while there is a closed form solution for integrating over the
parameters for the normal distribution, this is not true for the student.
The integration is carried out via the Laplace approximation. | Restricted Maximum Likelihood (REML) Estimate of Variance Component | This is the AD Model Builder code for the model. This version will
estimate the fixed effects.
DATA_SECTION
init_number N // number of individuals
init_int p
init_int q
init_vector n(1,N) // | Restricted Maximum Likelihood (REML) Estimate of Variance Component
This is the AD Model Builder code for the model. This version will
estimate the fixed effects.
DATA_SECTION
init_number N // number of individuals
init_int p
init_int q
init_vector n(1,N) // number of time points
init_3darray X(1,N,1,n,1,p)
init_3darray Z(1,N,1,n,1,q)
init_matrix obsy(1,N,1,n)
PARAMETER_SECTION
init_number log_sigma
!! int q1=q*(q-1)/2;
init_vector chcoff(1,q1)
init_vector logs(1,q)
init_vector beta(1,p)
random_effects_matrix eps(1,N,1,q)
objective_function_value f
PROCEDURE_SECTION
for (int i=1;i<=N;i++)
{
f+=f1(i,eps(i),beta,log_sigma,logs,chcoff);
}
SEPARABLE_FUNCTION dvariable f1(int i,const dvar_vector& epsi,const dvar_vector beta,const prevariable & log_sigma,const dvar_vector& logs,const dvar_vector& chcoff)
dvariable sigma=exp(log_sigma);
dvar_vector s=exp(logs);
dvariable var=square(sigma);
dvar_matrix ch(1,q,1,q);
ch.initialize();
// ch is the choleski decomp of G
ch(1,1)=s(1);
int offset=0;
for (int j=2;j<=q;j++)
{
ch(j)(1,j-1)=chcoff(1+offset,j-1+offset).shift(1);
ch(j,j)=1.0;
ch(j)/=norm(ch(j));
offset+=j-1;
ch(j)*=s(j);
}
dvar_vector predy=X(i)*beta+Z(i)*(ch*epsi);
f+= 0.5*n(i)*log(var)+0.5*norm2(obsy(i)-predy)/var;
f+= 0.5*norm2(epsi);
The REML version is calculated by integrating over the fixed effects.
This involves changing one line in the above code.
init_vector beta(1,p)
is changed to
random_effects_vector beta(1,p)
Now suppose I wanted to modify this code to use the student t distribution.
The line
f+= 0.5*n(i)*log(var)+0.5*norm2(obsy(i)-predy)/var;
is changed to
f-=ld_student(obsy(i),predy,var,dof);
and the lines
init_number log_dof_coff
dvariable dof=1.0+exp(log_dof_coff);
are added to the code in the appropriate places to include the degrees of freedom parameter.
Note that while there is a closed form solution for integrating over the
parameters for the normal distribution, this is not true for the student.
The integration is carried out via the Laplace approximation. | Restricted Maximum Likelihood (REML) Estimate of Variance Component
This is the AD Model Builder code for the model. This version will
estimate the fixed effects.
DATA_SECTION
init_number N // number of individuals
init_int p
init_int q
init_vector n(1,N) // |
34,726 | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard errors different? | I note that the Stata coefficient table mentioned "Robust Std. Err.", while glmm is probably not using robust errors. That would account for SE differences.
Also, ppml seems to actually drop "non-significant" regressors, and R's quasipoisson family allows for over dispersion in a way that's different from, say, negative binomial regression, which is perhaps different from ppml.
I noticed that you asked in a couple of places about what R package would yield equivalent results to ppml for (economics) gravity models, and got no answers. I'm sorry to see that and wish I could give a more-informed recommendation. It appears that what you need is a Poisson regression with robust standard errors, that handles zero values. I'm not sure what R packages support that. (Not sure if ppml handles over dispersion or not.)
Bayesian regression packages such as rstanarm might handle heteroscedasticity more robustly, but I am not sure. I'd tend to use something like a student_t family for that, but you have to use poisson so I'm not sure of the answer there. You might try the negative binomial family (neg_binomial_2 in rstanarm's stan_glm), which also handles over-dispersion and may be more robust than quasipoisson.
See also: When to use robust standard errors in Poisson regression? | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard | I note that the Stata coefficient table mentioned "Robust Std. Err.", while glmm is probably not using robust errors. That would account for SE differences.
Also, ppml seems to actually drop "non-sign | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard errors different?
I note that the Stata coefficient table mentioned "Robust Std. Err.", while glmm is probably not using robust errors. That would account for SE differences.
Also, ppml seems to actually drop "non-significant" regressors, and R's quasipoisson family allows for over dispersion in a way that's different from, say, negative binomial regression, which is perhaps different from ppml.
I noticed that you asked in a couple of places about what R package would yield equivalent results to ppml for (economics) gravity models, and got no answers. I'm sorry to see that and wish I could give a more-informed recommendation. It appears that what you need is a Poisson regression with robust standard errors, that handles zero values. I'm not sure what R packages support that. (Not sure if ppml handles over dispersion or not.)
Bayesian regression packages such as rstanarm might handle heteroscedasticity more robustly, but I am not sure. I'd tend to use something like a student_t family for that, but you have to use poisson so I'm not sure of the answer there. You might try the negative binomial family (neg_binomial_2 in rstanarm's stan_glm), which also handles over-dispersion and may be more robust than quasipoisson.
See also: When to use robust standard errors in Poisson regression? | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard
I note that the Stata coefficient table mentioned "Robust Std. Err.", while glmm is probably not using robust errors. That would account for SE differences.
Also, ppml seems to actually drop "non-sign |
34,727 | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard errors different? | To expand on Wayne's excellent answer, ppml uses a robust (to heteroskedasticity) variance-covariance matrix and also a finite sample adjustment to that matrix to reduce bias.
These are very similar to what sandwich() from the package of the same name computes in R. The only difference is how the finite-sample adjustment is done. In the sandwich(...) function, no finite-sample adjustment is done at all by default, i.e., the sandwich is divided by 1/n where n is the number of observations. Alternatively, sandwich(..., adjust = TRUE) can be used which divides by 1/(n - k) where k is the number of regressors. Stata, however, divides by 1/(n - 1).
Here's how you can get R to match Stata by using a custom sandwich variance with an adjustment factor of 1/(n-1):
. clear
. set more off
. capture ssc install rsource
. use http://personal.lse.ac.uk/tenreyro/mock, clear
. saveold ~/Desktop/mock, version(12) replace
(saving in Stata 12 format, which can be read by Stata 11 or 12)
file ~/Desktop/mock.dta saved
. rsource, terminator(XXX) rpath("/usr/local/bin/R") roptions("--vanilla")
Assumed R program path: "/usr/local/bin/R"
Loading required package: zoo
Attaching package: 'zoo'
The following objects are masked from 'package:base':
as.Date, as.Date.numeric
Beginning of R output
R version 3.2.4 (2016-03-10) -- "Very Secure Dishes"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin13.4.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> library("foreign")
> library("sandwich")
> library("lmtest")
> mock<-read.dta("~/Desktop/mock.dta")
> glmm<-glm(formula=y ~ x + w, family=quasipoisson(link="log"),data=mock)
>
> sandwich1 <- function(object, ...) sandwich(object) * nobs(object) / (nobs(object) - 1)
> coeftest(glmm,vcov=sandwich1)
z test of coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.516969 0.098062 5.2718 1.351e-07 ***
x 0.125657 0.101591 1.2369 0.2161
w 0.013410 0.710752 0.0189 0.9849
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>
End of R output
.
. ppml y x w
note: checking the existence of the estimates
Number of regressors excluded to ensure that the estimates exist: 0
Number of observations excluded: 0
note: starting ppml estimation
note: y has noninteger values
Iteration 1: deviance = 139.7855
Iteration 2: deviance = 137.7284
Iteration 3: deviance = 137.7222
Iteration 4: deviance = 137.7222
Number of parameters: 3
Number of observations: 100
Pseudo log-likelihood: -173.89764
R-squared: .01628639
Option strict is: off
------------------------------------------------------------------------------
| Robust
y | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
x | .1256565 .1015913 1.24 0.216 -.0734588 .3247718
w | .0134101 .7107518 0.02 0.985 -1.379638 1.406458
_cons | .5169689 .0980624 5.27 0.000 .3247702 .7091676
------------------------------------------------------------------------------
Here's the Stata/R code that generates the output above. I am using rsource to run R from Stata (and you will need to tweak the rpath() below to match your setup), but that is not really necessary: you can just run the rsource part from R.
clear
set more off
capture ssc install rsource
use http://personal.lse.ac.uk/tenreyro/mock, clear
saveold ~/Desktop/mock, version(12) replace
rsource, terminator(XXX) rpath("/usr/local/bin/R") roptions("--vanilla")
library("foreign")
library("sandwich")
library("lmtest")
mock<-read.dta("~/Desktop/mock.dta")
glmm<-glm(formula=y ~ x + w, family=quasipoisson(link="log"),data=mock)
sandwich1 <- function(object, ...) sandwich(object) * nobs(object) / (nobs(object) - 1)
coeftest(glmm,vcov=sandwich1)
XXX
ppml y x w | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard | To expand on Wayne's excellent answer, ppml uses a robust (to heteroskedasticity) variance-covariance matrix and also a finite sample adjustment to that matrix to reduce bias.
These are very similar t | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard errors different?
To expand on Wayne's excellent answer, ppml uses a robust (to heteroskedasticity) variance-covariance matrix and also a finite sample adjustment to that matrix to reduce bias.
These are very similar to what sandwich() from the package of the same name computes in R. The only difference is how the finite-sample adjustment is done. In the sandwich(...) function, no finite-sample adjustment is done at all by default, i.e., the sandwich is divided by 1/n where n is the number of observations. Alternatively, sandwich(..., adjust = TRUE) can be used which divides by 1/(n - k) where k is the number of regressors. Stata, however, divides by 1/(n - 1).
Here's how you can get R to match Stata by using a custom sandwich variance with an adjustment factor of 1/(n-1):
. clear
. set more off
. capture ssc install rsource
. use http://personal.lse.ac.uk/tenreyro/mock, clear
. saveold ~/Desktop/mock, version(12) replace
(saving in Stata 12 format, which can be read by Stata 11 or 12)
file ~/Desktop/mock.dta saved
. rsource, terminator(XXX) rpath("/usr/local/bin/R") roptions("--vanilla")
Assumed R program path: "/usr/local/bin/R"
Loading required package: zoo
Attaching package: 'zoo'
The following objects are masked from 'package:base':
as.Date, as.Date.numeric
Beginning of R output
R version 3.2.4 (2016-03-10) -- "Very Secure Dishes"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin13.4.0 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> library("foreign")
> library("sandwich")
> library("lmtest")
> mock<-read.dta("~/Desktop/mock.dta")
> glmm<-glm(formula=y ~ x + w, family=quasipoisson(link="log"),data=mock)
>
> sandwich1 <- function(object, ...) sandwich(object) * nobs(object) / (nobs(object) - 1)
> coeftest(glmm,vcov=sandwich1)
z test of coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.516969 0.098062 5.2718 1.351e-07 ***
x 0.125657 0.101591 1.2369 0.2161
w 0.013410 0.710752 0.0189 0.9849
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>
End of R output
.
. ppml y x w
note: checking the existence of the estimates
Number of regressors excluded to ensure that the estimates exist: 0
Number of observations excluded: 0
note: starting ppml estimation
note: y has noninteger values
Iteration 1: deviance = 139.7855
Iteration 2: deviance = 137.7284
Iteration 3: deviance = 137.7222
Iteration 4: deviance = 137.7222
Number of parameters: 3
Number of observations: 100
Pseudo log-likelihood: -173.89764
R-squared: .01628639
Option strict is: off
------------------------------------------------------------------------------
| Robust
y | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
x | .1256565 .1015913 1.24 0.216 -.0734588 .3247718
w | .0134101 .7107518 0.02 0.985 -1.379638 1.406458
_cons | .5169689 .0980624 5.27 0.000 .3247702 .7091676
------------------------------------------------------------------------------
Here's the Stata/R code that generates the output above. I am using rsource to run R from Stata (and you will need to tweak the rpath() below to match your setup), but that is not really necessary: you can just run the rsource part from R.
clear
set more off
capture ssc install rsource
use http://personal.lse.ac.uk/tenreyro/mock, clear
saveold ~/Desktop/mock, version(12) replace
rsource, terminator(XXX) rpath("/usr/local/bin/R") roptions("--vanilla")
library("foreign")
library("sandwich")
library("lmtest")
mock<-read.dta("~/Desktop/mock.dta")
glmm<-glm(formula=y ~ x + w, family=quasipoisson(link="log"),data=mock)
sandwich1 <- function(object, ...) sandwich(object) * nobs(object) / (nobs(object) - 1)
coeftest(glmm,vcov=sandwich1)
XXX
ppml y x w | Calculation of the gravity model in R and Stata software: why are coefficients the same but standard
To expand on Wayne's excellent answer, ppml uses a robust (to heteroskedasticity) variance-covariance matrix and also a finite sample adjustment to that matrix to reduce bias.
These are very similar t |
34,728 | What is the best method of reporting multiple tests of equivalence? | Regression table presentations are easy enough to modify to accommodate tests for equivalence, including relevance tests—where you base conclusions off of both tests for difference (tests of $H^{^{+}}_{0}$) and tests for equivalence (tests of $H^{^{-}}_{0}$). For example (assuming you are presenting multiple tests in a regression context, hence the $\beta$):
You can present both one-sided test statistics ($t_1$ and $t_2$) and their associated p-values ($p_1$ and $p_2$) from the tests for equivalence, and in addition present the test statistic $t$ and p-value ($p$) for the tests for difference.
In addition you may want to include a column for your definition of equivalence if it varies from test to test (I use $\Delta$ to indicate my equivalence/relevance threshold defined in units of my measures, and $\varepsilon$ to indicate this threshold defined in units of my test statistic). If you use a consistently defined of equivalence/relevance threshold for all tests, you would likely indicate that in a footnote to the table.
You can also facilitate interpretation by including columns to explicitly articulate rejection decisions for equivalence and difference tests. Including a relevance test column (combining results as I have illustrated here) may also facilitate interpretation.
Of course, one can also use this format to present independent tests, and to present different kinds of TOST test statistics (e.g. z test statistics like those used with non-parametric tests, exact binomial test statistics, etc.). | What is the best method of reporting multiple tests of equivalence? | Regression table presentations are easy enough to modify to accommodate tests for equivalence, including relevance tests—where you base conclusions off of both tests for difference (tests of $H^{^{+}} | What is the best method of reporting multiple tests of equivalence?
Regression table presentations are easy enough to modify to accommodate tests for equivalence, including relevance tests—where you base conclusions off of both tests for difference (tests of $H^{^{+}}_{0}$) and tests for equivalence (tests of $H^{^{-}}_{0}$). For example (assuming you are presenting multiple tests in a regression context, hence the $\beta$):
You can present both one-sided test statistics ($t_1$ and $t_2$) and their associated p-values ($p_1$ and $p_2$) from the tests for equivalence, and in addition present the test statistic $t$ and p-value ($p$) for the tests for difference.
In addition you may want to include a column for your definition of equivalence if it varies from test to test (I use $\Delta$ to indicate my equivalence/relevance threshold defined in units of my measures, and $\varepsilon$ to indicate this threshold defined in units of my test statistic). If you use a consistently defined of equivalence/relevance threshold for all tests, you would likely indicate that in a footnote to the table.
You can also facilitate interpretation by including columns to explicitly articulate rejection decisions for equivalence and difference tests. Including a relevance test column (combining results as I have illustrated here) may also facilitate interpretation.
Of course, one can also use this format to present independent tests, and to present different kinds of TOST test statistics (e.g. z test statistics like those used with non-parametric tests, exact binomial test statistics, etc.). | What is the best method of reporting multiple tests of equivalence?
Regression table presentations are easy enough to modify to accommodate tests for equivalence, including relevance tests—where you base conclusions off of both tests for difference (tests of $H^{^{+}} |
34,729 | What is the best method of reporting multiple tests of equivalence? | I think one can do all these multiple tests of equivalence within a single linear-mixed models. Given you have multiple (2+) measures after the change took place it is rather natural to present these multiple tests as part of a single repeated-measurements model.
In particular, one could define indicator variables between the successive steps and then check their significance; essentially doing multiple $t$-test in one-go. I think that a random structure with a simple intercept and slope for each subject would be fine. I do not see the absence of independent variables other than time as a structural problem. If anything I think it simplifies matters further.
From what I understand given a starting value(val0) something takes place (step0) while stepping from the first measurement period to the second. For the subsequent intra-measurement time periods (step1, step2, step3) nothing happens. Measurement error is assumed constant. So one has something like this:
I create this sample with the following code:
set.seed(123)
sampleTimes <- seq(0,1, length.out = 5);
N = 10^2;
val0 <- rnorm(N, mean = 0, sd = 5); # Starting values
slopeAt0 <- rnorm( N, mean = -10, sd = 5); # Effect kicks in
val1to5 <- val0 + slopeAt0 * diff(sampleTimes[1:2]) # so val0 is +2.5 higher
trueMeans <- cbind( val0, t(matrix(rep(val1to5,4), 4, byrow = TRUE)))
obsSample <- trueMeans + rnorm(N*5)
subject <- (1:N)
matplot(sampleTimes, t(obsSample),type = 'l', ylab= 'Obs. Sample') # Visualise
And define a series of indicator variables for the periods stepping from one measurement point to the next. Notice that I define no "last step" step4; we do not know what happens after the last measurement point at $t_4$.
Q <- data.frame( t = rep(sampleTimes, times = N),
ID = rep(subject, each = 5), reads = as.vector(t(obsSample)),
step0 = rep(c(1,0,0,0,0), times = N),
step1 = rep(c(0,1,0,0,0), times = N),
step2 = rep(c(0,0,1,0,0), times = N),
step3 = rep(c(0,0,0,1,0), times = N))
Using this design it is a relatively simple task to fit an LME and check if the stepX variables become statistically significant. The intercept and slope will absorb any subject-specific variations and one bootstrap that model directly. One can also use the $t$-values from the original LME too.
library(lme4)
m1 <- lmer(reads ~ step0 + step1 + step2 + step3 + (t+1|ID), Q)
summary(m1)
confZ = confint(m1, method='boot', nsim= 1000)
print(confZ)
# Computing bootstrap confidence intervals ...
# 2.5 % 97.5 %
# .sig01 3.7653500 5.0961341
# .sig02 -0.2043878 0.9843421
# .sig03 0.3396433 1.2702728
# .sigma 0.9869698 1.1579640
# (Intercept) -3.2169570 -1.2982469
# step0 2.5430254 3.2526163
# step1 -0.2465836 0.4475912
# step2 -0.0728649 0.5659132
# step3 -0.1625806 0.4023341
The results are quite reasonable I think, even for the modest sample size ($N = 10^2$) used. Wanting to be on the safe side I included a random slope and this came as probably redundant (sig02) (the original problem description does not specify it there is an additional time-varying trend) but excluding it does not alter the basic findings in any way: something happens during the step0 period. | What is the best method of reporting multiple tests of equivalence? | I think one can do all these multiple tests of equivalence within a single linear-mixed models. Given you have multiple (2+) measures after the change took place it is rather natural to present these | What is the best method of reporting multiple tests of equivalence?
I think one can do all these multiple tests of equivalence within a single linear-mixed models. Given you have multiple (2+) measures after the change took place it is rather natural to present these multiple tests as part of a single repeated-measurements model.
In particular, one could define indicator variables between the successive steps and then check their significance; essentially doing multiple $t$-test in one-go. I think that a random structure with a simple intercept and slope for each subject would be fine. I do not see the absence of independent variables other than time as a structural problem. If anything I think it simplifies matters further.
From what I understand given a starting value(val0) something takes place (step0) while stepping from the first measurement period to the second. For the subsequent intra-measurement time periods (step1, step2, step3) nothing happens. Measurement error is assumed constant. So one has something like this:
I create this sample with the following code:
set.seed(123)
sampleTimes <- seq(0,1, length.out = 5);
N = 10^2;
val0 <- rnorm(N, mean = 0, sd = 5); # Starting values
slopeAt0 <- rnorm( N, mean = -10, sd = 5); # Effect kicks in
val1to5 <- val0 + slopeAt0 * diff(sampleTimes[1:2]) # so val0 is +2.5 higher
trueMeans <- cbind( val0, t(matrix(rep(val1to5,4), 4, byrow = TRUE)))
obsSample <- trueMeans + rnorm(N*5)
subject <- (1:N)
matplot(sampleTimes, t(obsSample),type = 'l', ylab= 'Obs. Sample') # Visualise
And define a series of indicator variables for the periods stepping from one measurement point to the next. Notice that I define no "last step" step4; we do not know what happens after the last measurement point at $t_4$.
Q <- data.frame( t = rep(sampleTimes, times = N),
ID = rep(subject, each = 5), reads = as.vector(t(obsSample)),
step0 = rep(c(1,0,0,0,0), times = N),
step1 = rep(c(0,1,0,0,0), times = N),
step2 = rep(c(0,0,1,0,0), times = N),
step3 = rep(c(0,0,0,1,0), times = N))
Using this design it is a relatively simple task to fit an LME and check if the stepX variables become statistically significant. The intercept and slope will absorb any subject-specific variations and one bootstrap that model directly. One can also use the $t$-values from the original LME too.
library(lme4)
m1 <- lmer(reads ~ step0 + step1 + step2 + step3 + (t+1|ID), Q)
summary(m1)
confZ = confint(m1, method='boot', nsim= 1000)
print(confZ)
# Computing bootstrap confidence intervals ...
# 2.5 % 97.5 %
# .sig01 3.7653500 5.0961341
# .sig02 -0.2043878 0.9843421
# .sig03 0.3396433 1.2702728
# .sigma 0.9869698 1.1579640
# (Intercept) -3.2169570 -1.2982469
# step0 2.5430254 3.2526163
# step1 -0.2465836 0.4475912
# step2 -0.0728649 0.5659132
# step3 -0.1625806 0.4023341
The results are quite reasonable I think, even for the modest sample size ($N = 10^2$) used. Wanting to be on the safe side I included a random slope and this came as probably redundant (sig02) (the original problem description does not specify it there is an additional time-varying trend) but excluding it does not alter the basic findings in any way: something happens during the step0 period. | What is the best method of reporting multiple tests of equivalence?
I think one can do all these multiple tests of equivalence within a single linear-mixed models. Given you have multiple (2+) measures after the change took place it is rather natural to present these |
34,730 | What is the best method of reporting multiple tests of equivalence? | Others have given you more direct answers to your question, but I'm going to try and show a different solution to the problem. Unless I'm misunderstanding you, it seems like a two-way (period area) fixed effects model would work best (with robust SEs, of course!).
$$
y_i = \sum_k \alpha_k \times \mathbf{1}[i \in \text{period}_k] + \sum_j \beta_j \times \mathbf{1}[i \in \text{area}_j] + \epsilon_i
$$
You could do an F-test (joint null test) on all the $\alpha_k$ to see if there is any change across time at all, and you can do a Wald test to see if a subset of coefficients (in your case $\alpha_2 = \alpha_3 = \dots = \alpha_K$) are the same. This also gets around all of the multiple testing problems you should be worrying about if you're doing a bunch of pairwise tests.
All of the above can be done within the text. For a visual inspection.. I know you're asking for a table, but I think a plot like this with 95% intervals is much more convincing. But maybe it's just the style of my field. | What is the best method of reporting multiple tests of equivalence? | Others have given you more direct answers to your question, but I'm going to try and show a different solution to the problem. Unless I'm misunderstanding you, it seems like a two-way (period area) fi | What is the best method of reporting multiple tests of equivalence?
Others have given you more direct answers to your question, but I'm going to try and show a different solution to the problem. Unless I'm misunderstanding you, it seems like a two-way (period area) fixed effects model would work best (with robust SEs, of course!).
$$
y_i = \sum_k \alpha_k \times \mathbf{1}[i \in \text{period}_k] + \sum_j \beta_j \times \mathbf{1}[i \in \text{area}_j] + \epsilon_i
$$
You could do an F-test (joint null test) on all the $\alpha_k$ to see if there is any change across time at all, and you can do a Wald test to see if a subset of coefficients (in your case $\alpha_2 = \alpha_3 = \dots = \alpha_K$) are the same. This also gets around all of the multiple testing problems you should be worrying about if you're doing a bunch of pairwise tests.
All of the above can be done within the text. For a visual inspection.. I know you're asking for a table, but I think a plot like this with 95% intervals is much more convincing. But maybe it's just the style of my field. | What is the best method of reporting multiple tests of equivalence?
Others have given you more direct answers to your question, but I'm going to try and show a different solution to the problem. Unless I'm misunderstanding you, it seems like a two-way (period area) fi |
34,731 | Why does multiplication in the frequency domain equal convolution in the time domain? | Let's suppose we could find a (measurable) function $\chi$ defined on the real numbers with the property that
$$\chi(a + b) = \chi(a)\chi(b)$$
for all numbers $a$ and $b$ and for which there is a finite positive number $M$ for which $|\chi(a)| \le M$ for all $a$. Notice how $\chi$ relates addition (which is the fundamental operation appearing in a convolution) and multiplication.
Why are these properties useful? Suppose $X$ and $Y$ are independent random variables. Let $t$ be any real number. Then (taking up these two properties in reverse order)
$\mathbb{E}(\chi(tX)) \le \mathbb{E}(|\chi(tX)|) = \mathbb{E}(M) = M \lt \infty$ (with a similar expression for $Y$) shows that the expectations of the random variables $\chi(tX)$ and $\chi(tY)$ exist and are finite, with a uniform bound $M$ independent of $t$.
This procedure of taking a random variable $X$ and transforming it into the function
$$t \to \mathbb{E}(\chi(tX)) = (\operatorname{cf}_\chi(X))(t)$$
thereby assigns a well-defined, bounded function $\operatorname{cf}_\chi(X)$ to every random variable $X$--no matter what awful properties $X$ might have.
$\mathbb{E}(\chi(t(X+Y))) = \mathbb{E}(\chi(tX)\chi(tY)) = \mathbb{E}(\chi(tX))\mathbb{E}(\chi(tY))$ because $X$ and $Y$ are independent. Written slightly differently,
$$(\operatorname{cf}_\chi(X+Y))(t) = ((\operatorname{cf}_\chi(X))(\operatorname{cf}_\chi(Y)))(t)$$
That is, the transformation $\operatorname{cf}_\chi$ converts convolution (addition of random variables) into (pointwise) multiplication of functions.
Much more can be said: see the literature on Fourier Analysis. But in the meantime, the question has been answered in a way that shows "time" and "frequency" may be red herrings: this fundamental property of converting convolution into multiplication relies only on the existence of a nice $\chi$.
The only real-valued functions with the defining properties of $\chi$ are $\chi(a) = 1$ and $\chi(a) = 0$. They lead to nothing useful. But if we allow $\chi$ to have complex values, then $\chi(a) = \exp(ia)$ is one such function and it produces useful results. (Moreover, all such $\chi$ are derived from this one: they must be of the form $a\to \exp(ia\lambda)$ for some fixed real number $\lambda$.) In this case $\operatorname{cf}_\chi(X)$ is called the characteristic function of $X$.
It's not hard to see that when $\chi$ is not identically zero, $|\chi(a)|$ must always equal $1$, no matter what $a$ is. Such functions are called (complex) multiplicative characters (of the additive group of real numbers). | Why does multiplication in the frequency domain equal convolution in the time domain? | Let's suppose we could find a (measurable) function $\chi$ defined on the real numbers with the property that
$$\chi(a + b) = \chi(a)\chi(b)$$
for all numbers $a$ and $b$ and for which there is a fini | Why does multiplication in the frequency domain equal convolution in the time domain?
Let's suppose we could find a (measurable) function $\chi$ defined on the real numbers with the property that
$$\chi(a + b) = \chi(a)\chi(b)$$
for all numbers $a$ and $b$ and for which there is a finite positive number $M$ for which $|\chi(a)| \le M$ for all $a$. Notice how $\chi$ relates addition (which is the fundamental operation appearing in a convolution) and multiplication.
Why are these properties useful? Suppose $X$ and $Y$ are independent random variables. Let $t$ be any real number. Then (taking up these two properties in reverse order)
$\mathbb{E}(\chi(tX)) \le \mathbb{E}(|\chi(tX)|) = \mathbb{E}(M) = M \lt \infty$ (with a similar expression for $Y$) shows that the expectations of the random variables $\chi(tX)$ and $\chi(tY)$ exist and are finite, with a uniform bound $M$ independent of $t$.
This procedure of taking a random variable $X$ and transforming it into the function
$$t \to \mathbb{E}(\chi(tX)) = (\operatorname{cf}_\chi(X))(t)$$
thereby assigns a well-defined, bounded function $\operatorname{cf}_\chi(X)$ to every random variable $X$--no matter what awful properties $X$ might have.
$\mathbb{E}(\chi(t(X+Y))) = \mathbb{E}(\chi(tX)\chi(tY)) = \mathbb{E}(\chi(tX))\mathbb{E}(\chi(tY))$ because $X$ and $Y$ are independent. Written slightly differently,
$$(\operatorname{cf}_\chi(X+Y))(t) = ((\operatorname{cf}_\chi(X))(\operatorname{cf}_\chi(Y)))(t)$$
That is, the transformation $\operatorname{cf}_\chi$ converts convolution (addition of random variables) into (pointwise) multiplication of functions.
Much more can be said: see the literature on Fourier Analysis. But in the meantime, the question has been answered in a way that shows "time" and "frequency" may be red herrings: this fundamental property of converting convolution into multiplication relies only on the existence of a nice $\chi$.
The only real-valued functions with the defining properties of $\chi$ are $\chi(a) = 1$ and $\chi(a) = 0$. They lead to nothing useful. But if we allow $\chi$ to have complex values, then $\chi(a) = \exp(ia)$ is one such function and it produces useful results. (Moreover, all such $\chi$ are derived from this one: they must be of the form $a\to \exp(ia\lambda)$ for some fixed real number $\lambda$.) In this case $\operatorname{cf}_\chi(X)$ is called the characteristic function of $X$.
It's not hard to see that when $\chi$ is not identically zero, $|\chi(a)|$ must always equal $1$, no matter what $a$ is. Such functions are called (complex) multiplicative characters (of the additive group of real numbers). | Why does multiplication in the frequency domain equal convolution in the time domain?
Let's suppose we could find a (measurable) function $\chi$ defined on the real numbers with the property that
$$\chi(a + b) = \chi(a)\chi(b)$$
for all numbers $a$ and $b$ and for which there is a fini |
34,732 | Why does multiplication in the frequency domain equal convolution in the time domain? | The answer depends on what you're looking for in the answer.
For instance, to me this was the answer, and the rest was just the details:
$$e^a\cdot e^b=e^{a+b}$$
It's all about the exponent, when you multiply them their arguments get added. | Why does multiplication in the frequency domain equal convolution in the time domain? | The answer depends on what you're looking for in the answer.
For instance, to me this was the answer, and the rest was just the details:
$$e^a\cdot e^b=e^{a+b}$$
It's all about the exponent, when you | Why does multiplication in the frequency domain equal convolution in the time domain?
The answer depends on what you're looking for in the answer.
For instance, to me this was the answer, and the rest was just the details:
$$e^a\cdot e^b=e^{a+b}$$
It's all about the exponent, when you multiply them their arguments get added. | Why does multiplication in the frequency domain equal convolution in the time domain?
The answer depends on what you're looking for in the answer.
For instance, to me this was the answer, and the rest was just the details:
$$e^a\cdot e^b=e^{a+b}$$
It's all about the exponent, when you |
34,733 | Classification with a neural network when one class has disproportionately many entries | You are coping with an imbalanced dataset.
Lucky for you, you are not alone.
This is a common problem.
For surveys on the topic see Editorial: Special Issue on Learning from Imbalanced Data
Sets (6 pages) and Learning from Imbalanced Data (22 pages)
The method I like best is the following:
The method is based of the boosting algorithm Robert E. Schapire presented at "The strength of weak learnability" (Machine Learning, 5(2):197–227, 1990. The Strength of Weak Learnability ).
In this paper, Schapire presented a boosting algorithm based on combining triplets of 3 weak learners recursively. By the way, this was the first boosting algorithm.
We can use the first step of the algorithm (even without the recursion) to cope with the lack of balance.
The algorithm trains the first learner, L1, one the original data set.
The second learner, L2, is trained on a set on which L1 has 50% chance to be correct (by sampling from the original distribution).
The third learner, L3, is trained on the cases on which L1 and L2 disagree.
As output, return the majority of the classifiers.
See the paper to see why it improves the classification.
Now, for the application of the method of an imbalanced set:
Assume the concept is binary and the majority of the samples are classified as true.
Let L1 return always true.
L2 is being trained were L1 has 50% chance to be right. Since L1 is just true, L2 is being trained on a balanced data set.
L3 is being trained when L1 and L2 disagree, that is, when L2 predicts false.
The ensemble predicts by majority vote; hence, it predicts false only when both L2 and L3 predict false.
I used this method in practice many times, and it is very useful.
It also has a theoretical justification so all fronts are covered. | Classification with a neural network when one class has disproportionately many entries | You are coping with an imbalanced dataset.
Lucky for you, you are not alone.
This is a common problem.
For surveys on the topic see Editorial: Special Issue on Learning from Imbalanced Data
Sets (6 p | Classification with a neural network when one class has disproportionately many entries
You are coping with an imbalanced dataset.
Lucky for you, you are not alone.
This is a common problem.
For surveys on the topic see Editorial: Special Issue on Learning from Imbalanced Data
Sets (6 pages) and Learning from Imbalanced Data (22 pages)
The method I like best is the following:
The method is based of the boosting algorithm Robert E. Schapire presented at "The strength of weak learnability" (Machine Learning, 5(2):197–227, 1990. The Strength of Weak Learnability ).
In this paper, Schapire presented a boosting algorithm based on combining triplets of 3 weak learners recursively. By the way, this was the first boosting algorithm.
We can use the first step of the algorithm (even without the recursion) to cope with the lack of balance.
The algorithm trains the first learner, L1, one the original data set.
The second learner, L2, is trained on a set on which L1 has 50% chance to be correct (by sampling from the original distribution).
The third learner, L3, is trained on the cases on which L1 and L2 disagree.
As output, return the majority of the classifiers.
See the paper to see why it improves the classification.
Now, for the application of the method of an imbalanced set:
Assume the concept is binary and the majority of the samples are classified as true.
Let L1 return always true.
L2 is being trained were L1 has 50% chance to be right. Since L1 is just true, L2 is being trained on a balanced data set.
L3 is being trained when L1 and L2 disagree, that is, when L2 predicts false.
The ensemble predicts by majority vote; hence, it predicts false only when both L2 and L3 predict false.
I used this method in practice many times, and it is very useful.
It also has a theoretical justification so all fronts are covered. | Classification with a neural network when one class has disproportionately many entries
You are coping with an imbalanced dataset.
Lucky for you, you are not alone.
This is a common problem.
For surveys on the topic see Editorial: Special Issue on Learning from Imbalanced Data
Sets (6 p |
34,734 | Classification with a neural network when one class has disproportionately many entries | An important point to make here is that classifying all of the patterns as $c_1$ might be the correct answer, from a statistical decision theory perspective. If misclassification costs are equal, we want to classify the pattern according to the class with the highest posterior probability, i.e. $p(C = c_i|\vec{x})$, which depends on the prior probabilities. So it may be that the prior probabilities of the minority classes are sufficiently low, and the distribution of patterns for each class sufficiently broad, that the true posterior probability is always highest for the majority class. If this is not acceptable for your application, then that probably means that your misclassification costs are not equal, so you need to think about what the costs of each kind of misclassification actually are, and build that into your cost function used to train the network.
Note if your network outputs estimates of probability of class membership, then it is offten possible to post-process the output of the trained network, rather than pre-process and retrain - see the excellent boook by Chris Bishop ("Neural Networks for Pattern Recognition").
In my experience, it isn't so much a "class imbalance problem" per se, but that there are just too few patterns from the minority class to accurately estimate their distribution, and if you increase the size of the dataset (but keep the ratios the same) the problem often goes away. | Classification with a neural network when one class has disproportionately many entries | An important point to make here is that classifying all of the patterns as $c_1$ might be the correct answer, from a statistical decision theory perspective. If misclassification costs are equal, we | Classification with a neural network when one class has disproportionately many entries
An important point to make here is that classifying all of the patterns as $c_1$ might be the correct answer, from a statistical decision theory perspective. If misclassification costs are equal, we want to classify the pattern according to the class with the highest posterior probability, i.e. $p(C = c_i|\vec{x})$, which depends on the prior probabilities. So it may be that the prior probabilities of the minority classes are sufficiently low, and the distribution of patterns for each class sufficiently broad, that the true posterior probability is always highest for the majority class. If this is not acceptable for your application, then that probably means that your misclassification costs are not equal, so you need to think about what the costs of each kind of misclassification actually are, and build that into your cost function used to train the network.
Note if your network outputs estimates of probability of class membership, then it is offten possible to post-process the output of the trained network, rather than pre-process and retrain - see the excellent boook by Chris Bishop ("Neural Networks for Pattern Recognition").
In my experience, it isn't so much a "class imbalance problem" per se, but that there are just too few patterns from the minority class to accurately estimate their distribution, and if you increase the size of the dataset (but keep the ratios the same) the problem often goes away. | Classification with a neural network when one class has disproportionately many entries
An important point to make here is that classifying all of the patterns as $c_1$ might be the correct answer, from a statistical decision theory perspective. If misclassification costs are equal, we |
34,735 | Why are simultaneous confidence intervals wider than the normal ones? | Consider two parameters and assume for simplicity that they are estimated independently. Say the sample mean and variance of a normal population which are estimates for the respective population quantities and are known to be indepedent.
From basic statistics we know how to construct confidence intervals for $\mu$ and $\sigma^2$ based on our estimates. Since this is a normal distribution, we have two beautiful pivotal quantities, namely
$$\frac{\bar{X}-\mu}{\sigma/\sqrt{n}} \sim N(0,1)\quad \text{and} \quad \frac{\left(n-1 \right) S^2}{\sigma^2} \sim \chi^2_{n-1} $$
Based on these distributions we can now find quantiles such that
$$ P \left[ -z_{0.975} < \frac{\bar{X}-\mu}{\sigma/\sqrt{n}} < z_{0.975} \right] =0.95 \quad \text{and} \quad P\left[ \chi^2_{0.025}<\frac{\left(n-1 \right) S^2}{\sigma^2} < \chi^2 _{0.975} \right] = 0.95$$
Easy enough but there is a logical fallacy in these intervals, which you might have picked up. In the first interval I have assumed that $\sigma$ is known and this is clearly not the case, otherwise we wouldn't need the second interval!
What we can do to resolve this contradiction is use the four inequalities to determine a confidence region for both $\mu$ and $\sigma^2$. Thus we will now be concerned with the probability
\begin{align} \label{eq:1} P\left[-z_{0.975} < \frac{\bar{X}-\mu}{\sigma/\sqrt{n}} < z_{0.975} \ , \ \chi^2_{0.025} < \frac{\left(n-1 \right) S^2}{\sigma^2} < \chi^2 _{0.975}\right] \tag{1} \end{align}
With a slight reformulation of the above inequalities it is possible to determine the boundaries of $\mu$ and $\sigma^2$. Here is how the resulting region looks like
Pay no attention to the labels in the graph, these are just minor differences in the notation of the quantiles. You can now project onto the coordinate axes to obtain a confidence interval for both $\mu $ and $\sigma^2$. But we still do not know the level of this confidence region.
We have now arrived at the crux of the matter. My question to you is exactly that : what is the confidence level of this region? Surely we have used two 95% intervals so at first one might think that we are still at the 95% level. A moment of reflection will reveal however that this is incorrect.
In this simplified setting the confidence level can be computed exactly using the independence $\bar{X}$ and $S^2$. Take a look at equation (\ref{eq:1}) and recall that for two independent events A and B, $P\left[ A \cap B \right] = P[A] P[B]$. Thus
$$ P\left[z_{0.975} < \frac{\bar{X}-\mu}{\sigma/\sqrt{n}} < z_{0.975} \ , \ \chi^2_{0.025} < \frac{\left(n-1 \right) S^2}{\sigma^2} < \chi^2 _{0.975}\right] = 0.95^2 = 0.9025$$
And we have found out the hard way that two 95 % intervals do not mean that the joint confidence level, i.e. the confidence level of equation (\ref{eq:1}), is 0.95. By Bonferroni's inequality we can establish a lower bound - which is nearly attained in this case - but other than that not much can be said for the general case of non-independence.
In view of this, it is often preferable to take a conservative approach and specify simultaneous confidence intervals that have at least 0.95 coverage. Indeed, the concept of exact confidence interval no longer exists in simultaneous interval estimation. Tukey's, Scheffe's and even Bonferroni's procedures are all conservative in nature. For instance, in ANOVA when you want to test contrasts you will be able to build intervals that are at least of 0.95 level but you can never be sure what their exact level is.
Of course, the intervals then are much wider than in the individual cases. It appears that we cannot do better, however, so better be safe than sorry.
Hope this helps. | Why are simultaneous confidence intervals wider than the normal ones? | Consider two parameters and assume for simplicity that they are estimated independently. Say the sample mean and variance of a normal population which are estimates for the respective population quant | Why are simultaneous confidence intervals wider than the normal ones?
Consider two parameters and assume for simplicity that they are estimated independently. Say the sample mean and variance of a normal population which are estimates for the respective population quantities and are known to be indepedent.
From basic statistics we know how to construct confidence intervals for $\mu$ and $\sigma^2$ based on our estimates. Since this is a normal distribution, we have two beautiful pivotal quantities, namely
$$\frac{\bar{X}-\mu}{\sigma/\sqrt{n}} \sim N(0,1)\quad \text{and} \quad \frac{\left(n-1 \right) S^2}{\sigma^2} \sim \chi^2_{n-1} $$
Based on these distributions we can now find quantiles such that
$$ P \left[ -z_{0.975} < \frac{\bar{X}-\mu}{\sigma/\sqrt{n}} < z_{0.975} \right] =0.95 \quad \text{and} \quad P\left[ \chi^2_{0.025}<\frac{\left(n-1 \right) S^2}{\sigma^2} < \chi^2 _{0.975} \right] = 0.95$$
Easy enough but there is a logical fallacy in these intervals, which you might have picked up. In the first interval I have assumed that $\sigma$ is known and this is clearly not the case, otherwise we wouldn't need the second interval!
What we can do to resolve this contradiction is use the four inequalities to determine a confidence region for both $\mu$ and $\sigma^2$. Thus we will now be concerned with the probability
\begin{align} \label{eq:1} P\left[-z_{0.975} < \frac{\bar{X}-\mu}{\sigma/\sqrt{n}} < z_{0.975} \ , \ \chi^2_{0.025} < \frac{\left(n-1 \right) S^2}{\sigma^2} < \chi^2 _{0.975}\right] \tag{1} \end{align}
With a slight reformulation of the above inequalities it is possible to determine the boundaries of $\mu$ and $\sigma^2$. Here is how the resulting region looks like
Pay no attention to the labels in the graph, these are just minor differences in the notation of the quantiles. You can now project onto the coordinate axes to obtain a confidence interval for both $\mu $ and $\sigma^2$. But we still do not know the level of this confidence region.
We have now arrived at the crux of the matter. My question to you is exactly that : what is the confidence level of this region? Surely we have used two 95% intervals so at first one might think that we are still at the 95% level. A moment of reflection will reveal however that this is incorrect.
In this simplified setting the confidence level can be computed exactly using the independence $\bar{X}$ and $S^2$. Take a look at equation (\ref{eq:1}) and recall that for two independent events A and B, $P\left[ A \cap B \right] = P[A] P[B]$. Thus
$$ P\left[z_{0.975} < \frac{\bar{X}-\mu}{\sigma/\sqrt{n}} < z_{0.975} \ , \ \chi^2_{0.025} < \frac{\left(n-1 \right) S^2}{\sigma^2} < \chi^2 _{0.975}\right] = 0.95^2 = 0.9025$$
And we have found out the hard way that two 95 % intervals do not mean that the joint confidence level, i.e. the confidence level of equation (\ref{eq:1}), is 0.95. By Bonferroni's inequality we can establish a lower bound - which is nearly attained in this case - but other than that not much can be said for the general case of non-independence.
In view of this, it is often preferable to take a conservative approach and specify simultaneous confidence intervals that have at least 0.95 coverage. Indeed, the concept of exact confidence interval no longer exists in simultaneous interval estimation. Tukey's, Scheffe's and even Bonferroni's procedures are all conservative in nature. For instance, in ANOVA when you want to test contrasts you will be able to build intervals that are at least of 0.95 level but you can never be sure what their exact level is.
Of course, the intervals then are much wider than in the individual cases. It appears that we cannot do better, however, so better be safe than sorry.
Hope this helps. | Why are simultaneous confidence intervals wider than the normal ones?
Consider two parameters and assume for simplicity that they are estimated independently. Say the sample mean and variance of a normal population which are estimates for the respective population quant |
34,736 | Why are simultaneous confidence intervals wider than the normal ones? | Consider simultaneously estimating two parameters. We want to guarantee that, under repeated sampling, for some confidence level c and significance level $\alpha$, $(c = 1-\alpha )$% of our confidences interval pairs (one on each parameter) would both include the parameter.
Without loss of generality, let $\alpha$ = 0.05, c = 0.95. Let's construct single individual confidence intervals on each of them. The probability of each of these intervals containing their parameter is 0.95 under repeated sampling. Assuming independence, the probability of them both including their parameters under repeated sampling is 0.95*0.95 = 0.9025 < 0.95. If we wanted them both to include the true parameter values under repeated sampling 0.95 of the time, we would need $\alpha = \sqrt{0.95} = 0.975...$, which will obviously be a bigger interval on each parameter.
We will consider two levels of confidence here (we will assume that all the parameters we are measuring are the same for simplicity, so pretend we are simultaneous estimating the mean of two normal distributions in this discussion): one overall confidence level ($c_1$), and one confidence level for each parameter ($c_2$). $c_1$ is the long term probability of *every single one * of our confidence intervals successfully covering their respective parameters under repeated sampling, and is what we are directly interested in. If I were to say: "I want a 95% CI on these two parameters", the 95% = 0.95 corresponds to $c_1$. Once we have $c_1$, it falls to us to calculate $c_2$, which in our example here with two independent parameters is about 0.975. $c_2$ represents the "confidence level" we will have on each parameter. It has to be greater than if we were just estimating that parameter alone, and so will lead to a greater interval.
As the number of parameters to simultaneously estimate increases, the confidence of getting each individual one right will also have to increase for static overall confidence, because as we have more parameters to estimate, we have more opportunities for failure under repeated sampling.
For example, consider estimating a million parameters. If we give them all 0.95 individual confidence intervals, there's no way we would be say that the set of all confidence intervals here will include the true parameters under repeated sampling 95% of the time under repeated sampling. | Why are simultaneous confidence intervals wider than the normal ones? | Consider simultaneously estimating two parameters. We want to guarantee that, under repeated sampling, for some confidence level c and significance level $\alpha$, $(c = 1-\alpha )$% of our confidence | Why are simultaneous confidence intervals wider than the normal ones?
Consider simultaneously estimating two parameters. We want to guarantee that, under repeated sampling, for some confidence level c and significance level $\alpha$, $(c = 1-\alpha )$% of our confidences interval pairs (one on each parameter) would both include the parameter.
Without loss of generality, let $\alpha$ = 0.05, c = 0.95. Let's construct single individual confidence intervals on each of them. The probability of each of these intervals containing their parameter is 0.95 under repeated sampling. Assuming independence, the probability of them both including their parameters under repeated sampling is 0.95*0.95 = 0.9025 < 0.95. If we wanted them both to include the true parameter values under repeated sampling 0.95 of the time, we would need $\alpha = \sqrt{0.95} = 0.975...$, which will obviously be a bigger interval on each parameter.
We will consider two levels of confidence here (we will assume that all the parameters we are measuring are the same for simplicity, so pretend we are simultaneous estimating the mean of two normal distributions in this discussion): one overall confidence level ($c_1$), and one confidence level for each parameter ($c_2$). $c_1$ is the long term probability of *every single one * of our confidence intervals successfully covering their respective parameters under repeated sampling, and is what we are directly interested in. If I were to say: "I want a 95% CI on these two parameters", the 95% = 0.95 corresponds to $c_1$. Once we have $c_1$, it falls to us to calculate $c_2$, which in our example here with two independent parameters is about 0.975. $c_2$ represents the "confidence level" we will have on each parameter. It has to be greater than if we were just estimating that parameter alone, and so will lead to a greater interval.
As the number of parameters to simultaneously estimate increases, the confidence of getting each individual one right will also have to increase for static overall confidence, because as we have more parameters to estimate, we have more opportunities for failure under repeated sampling.
For example, consider estimating a million parameters. If we give them all 0.95 individual confidence intervals, there's no way we would be say that the set of all confidence intervals here will include the true parameters under repeated sampling 95% of the time under repeated sampling. | Why are simultaneous confidence intervals wider than the normal ones?
Consider simultaneously estimating two parameters. We want to guarantee that, under repeated sampling, for some confidence level c and significance level $\alpha$, $(c = 1-\alpha )$% of our confidence |
34,737 | How to verify if data follows Zipf's law without looking at the graph | You can't actually verify that your data does come from Zipf's law, but you may be able to tell that it doesn't. You can make some assessment of whether it's consistent with Zipf's law (at least to the degree that you can tell with the data you have).
The paper by Clauset, Shalizi and Newman[1] gives an explicit recipe to follow in Box 1 $^\dagger$ in their paper.
$^\dagger$ this is located at the top of the third page of the arXiv version of their paper (linked under the full paper reference below)
I believe it's brief enough to simply quote:
... In broad outline, however, the recipe we
propose for the analysis of power-law data is straightforward and goes as follows.
Estimate the parameters $x_\text{min}$ and $α$
of the power-law model using the methods
described in Section 3.
Calculate the goodness-of-fit between the data and the power law using the
method described in Section 4. If the resulting p-value is greater than 0.1 the
power law is a plausible hypothesis for the data, otherwise it is rejected.
Compare the power law with alternative hypotheses via a likelihood ratio test, as described in Section 5. For each alternative, if the calculated likelihood ratio is significantly different from zero, then its sign indicates
whether the alternative is favored over the power-law model or not.
Step 3, the likelihood ratio test for alternative hypotheses, could in principle be replaced with any of several other established and statistically principled approaches for model comparison, such as a fully Bayesian approach [32], a cross-validation approach [59], or a minimum description length approach [20], although none of these methods are described here.
See:
[1]: Clauset A., C.R. Shalizi, and M. E. J. Newman (2009),
"Power-Law Distributions in Empirical Data,"
SIAM Rev., 51(4), 661–703. (43 pages)
http://epubs.siam.org/doi/abs/10.1137/070710111
(arXiv version)
(also see Shalizi's So you think you have a power law)
Ahem: Did you spot the error? Note that when they say "if the calculated likelihood ratio is significantly different from zero" they are actually referring to the log of the likelihood ratio.
[Disclaimer: I generally think that explicit hypothesis testing of goodness of fit answers the wrong question, and this case is not really an exception, but there are several aspects to the above paper that reduce my usual concerns somewhat. In any case it is very much worth reading, and contains a good deal of very sensible advice.] | How to verify if data follows Zipf's law without looking at the graph | You can't actually verify that your data does come from Zipf's law, but you may be able to tell that it doesn't. You can make some assessment of whether it's consistent with Zipf's law (at least to th | How to verify if data follows Zipf's law without looking at the graph
You can't actually verify that your data does come from Zipf's law, but you may be able to tell that it doesn't. You can make some assessment of whether it's consistent with Zipf's law (at least to the degree that you can tell with the data you have).
The paper by Clauset, Shalizi and Newman[1] gives an explicit recipe to follow in Box 1 $^\dagger$ in their paper.
$^\dagger$ this is located at the top of the third page of the arXiv version of their paper (linked under the full paper reference below)
I believe it's brief enough to simply quote:
... In broad outline, however, the recipe we
propose for the analysis of power-law data is straightforward and goes as follows.
Estimate the parameters $x_\text{min}$ and $α$
of the power-law model using the methods
described in Section 3.
Calculate the goodness-of-fit between the data and the power law using the
method described in Section 4. If the resulting p-value is greater than 0.1 the
power law is a plausible hypothesis for the data, otherwise it is rejected.
Compare the power law with alternative hypotheses via a likelihood ratio test, as described in Section 5. For each alternative, if the calculated likelihood ratio is significantly different from zero, then its sign indicates
whether the alternative is favored over the power-law model or not.
Step 3, the likelihood ratio test for alternative hypotheses, could in principle be replaced with any of several other established and statistically principled approaches for model comparison, such as a fully Bayesian approach [32], a cross-validation approach [59], or a minimum description length approach [20], although none of these methods are described here.
See:
[1]: Clauset A., C.R. Shalizi, and M. E. J. Newman (2009),
"Power-Law Distributions in Empirical Data,"
SIAM Rev., 51(4), 661–703. (43 pages)
http://epubs.siam.org/doi/abs/10.1137/070710111
(arXiv version)
(also see Shalizi's So you think you have a power law)
Ahem: Did you spot the error? Note that when they say "if the calculated likelihood ratio is significantly different from zero" they are actually referring to the log of the likelihood ratio.
[Disclaimer: I generally think that explicit hypothesis testing of goodness of fit answers the wrong question, and this case is not really an exception, but there are several aspects to the above paper that reduce my usual concerns somewhat. In any case it is very much worth reading, and contains a good deal of very sensible advice.] | How to verify if data follows Zipf's law without looking at the graph
You can't actually verify that your data does come from Zipf's law, but you may be able to tell that it doesn't. You can make some assessment of whether it's consistent with Zipf's law (at least to th |
34,738 | How to verify if data follows Zipf's law without looking at the graph | Partial answers may reside in parametric tests. The following could be of interest:
A simple and efficient test for Zipf’s law, Economics Letters, 2000,
Testing for Zipf’s Law: A Common Pitfall, Economics Letters, 2011. | How to verify if data follows Zipf's law without looking at the graph | Partial answers may reside in parametric tests. The following could be of interest:
A simple and efficient test for Zipf’s law, Economics Letters, 2000,
Testing for Zipf’s Law: A Common Pitfall, Econ | How to verify if data follows Zipf's law without looking at the graph
Partial answers may reside in parametric tests. The following could be of interest:
A simple and efficient test for Zipf’s law, Economics Letters, 2000,
Testing for Zipf’s Law: A Common Pitfall, Economics Letters, 2011. | How to verify if data follows Zipf's law without looking at the graph
Partial answers may reside in parametric tests. The following could be of interest:
A simple and efficient test for Zipf’s law, Economics Letters, 2000,
Testing for Zipf’s Law: A Common Pitfall, Econ |
34,739 | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | SPSS Algorithms state that in doing pairwise comparisons after Friedman test they use the Dunn's (1964) procedure. I didn't read that Dunn's original paper so I can't say if SPSS follows it correctly, - but I've just sat and programmed Friedman's test and its post-hoc pairwise comparisons following the above SPSS algorithms documentation, and I confirm that there is no bug and that my results were identical to what SPSS output and the OP showed in the question. (See my code here).
According to the Dunn's approach (as SPSS carries it out) the test statistic is simply the difference in the mean values of the two samples (variables) being compared, that difference after the values were turned into ranks within cases. (It is the ranks left from Friedman's test computations, that is, ranking of the $k$ [k=3 in our example data] values within each case, with mean rank assignment for ties.) St. error of the statistic is $\sqrt{k(k+1)/(6n)}$. It divides the test statistic to yield standardized statistic $Z$ which is plugged in st. normal distribution to give the (Bonferroni yet uncorrected) 2-sided significance.
This comparison test looks very conservative. It failed to praise the pair V1-V2 as significant: Z=1.838, p=.066 despite that the omnibus Friedman is strongly significant: p=.002. In contrast, Sign test for pair V1-V2 (it will be the same irrespective whether you perform it on the raw values or on the ranks left from Friedman) has Z=3.575, p=.0004.
One reason the SPSS "Dunn's approach" is quite conservative is its st. error formula accounting for all the $k$, not 2, variables.
Another reason why it is so less powerful than the Sign test is that it bases itself on all the $n$ cases, including those with ties, while Sign test discards cases with ties; and there is many cases with ties in our data. The problem of power in conjunction with treatment of ties in tests such as Sign was observed, for example in this Q/A.
I took V1 and V2 and, for cases with ties, untied them in a random fashion (by adding negative or positive noise), and computed Sign test (now based on all $n$ cases of course). 500 such trials gave me mean Z=1.927, which is now far from Z=3.575 and much closer on the road of conservatism towards the observed Dunn's Z=1.838.
I feel myself dissatisfied with SPSS' "Dunn's" pairwise comparisons as they are too conservative/weak. We expect that if an omnibus test is significant post hoc tests will confirm it often, if not ever. In our example, even Bonferroni-uncorrected p-value could not support the omnibus conclusion.
Is SPSS at all correct in adopting the "Dunn's approach" (originally proposed for Kruskal-Wallis; see also this Q/A) for Friedman post-hoc testing? I can't say, being hardly an expert in multiple comparisons. I would encourage somebody who knows it to comment or post a really helpful answer on this thread.
P.S. I'm quite aware that, while Friedman test can be seen as an extension of Sign test from 2 to $k$ samples (variables), a pairwise post hoc test after Friedman is not and should not be exactly the Sign test. Neither it would be Wilcoxon paired-samle test. The "Dunn's approach" (if adapted to paired-sample situation) looks plausible post hoc because it compares, without further ranking, the "horizontal" ranks obtained at Friedman and reflecting all the $k$ samples. What bothered me, though, was that the approach appeared overconservative in the example of the post.
Later Addition. To me, Dunn's approach as it is implemented after Friedman's test in SPSS is incorrect. It does not adjust for ties in the same fashion as the parent omnibus test (Friedman) does it. Actually, it does not adjust for the ties at all, while it should. (The issue of ties handling is touched in the current answer above.)
The formula of Friedman's test statistic (explained in SPSS Algorithms) is
$$\chi^2= \frac{[12/(nk(k+1))]\sum^k C^2-3n(k+1)}{1-\Sigma T/[nk(k^2-1)]}$$
The denominator of the formula contains the adjustment for ties. If $k=2$ then quantity $\Sigma T/[nk(k^2-1)]$ is the proportion of cases in which the two variables are equal (tied).
Consider Friedman test performed with our variables V1 and V2 ($k=2$). The proportion of cases with ties is 287/400=.7175 and the test statistic is 13.460, df=1 with significance p=.00024. But the "Dunn's" comparison computed following SPSS formulas will be
Sample1 Sample2 MeanRank1 MeanRank2 TestStat StError Z Sig2side AdjSig
V1 V2 1.54875 1.45125 .0975 .0500 1.9500 .05118 .05118
Nonsignificant. Why? No proper (Friedman style) adjustment for ties was done.
In the presense of only $k=2$ samples in data a correct post hoc pairwise comparison test must give the same result (statistic and p-value) as the omnibus test - it is actually a property which proves that the post hoc test corresponds (is isomorphic) to the parent omnibus test. It is indeed so with Kruskal-Wallis test and Dunn's test - just program it following SPSS Algorithms and test with V1 and V2 as two independent groups, and you'll get same p=.0153 both for KW and for Dunn. But we saw that a similar equivalence is absent in relations between Friedman test and "Dunn's approach" post-Friedman comparison test.
Conclusion. Post hoc multiple comparison test being performed by SPSS (version 22 and earlier) after Friedman's test is defective. Maybe it is correct when there is no ties, but I don't know. The post hoc test does not treat ties the way Friedman does it (while it should). I cannot say anything about the formula of st. error, sqrt[k*(k+1)/(6n)], they are using: it was derived from discrete uniform distribution, but they didn't write how; is it correct? Either the "Dunn's test approach" was adapted to Friedman inadequatly by SPSS or Dunn's test cannot be adapted to Friedman at all. | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | SPSS Algorithms state that in doing pairwise comparisons after Friedman test they use the Dunn's (1964) procedure. I didn't read that Dunn's original paper so I can't say if SPSS follows it correctly, | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
SPSS Algorithms state that in doing pairwise comparisons after Friedman test they use the Dunn's (1964) procedure. I didn't read that Dunn's original paper so I can't say if SPSS follows it correctly, - but I've just sat and programmed Friedman's test and its post-hoc pairwise comparisons following the above SPSS algorithms documentation, and I confirm that there is no bug and that my results were identical to what SPSS output and the OP showed in the question. (See my code here).
According to the Dunn's approach (as SPSS carries it out) the test statistic is simply the difference in the mean values of the two samples (variables) being compared, that difference after the values were turned into ranks within cases. (It is the ranks left from Friedman's test computations, that is, ranking of the $k$ [k=3 in our example data] values within each case, with mean rank assignment for ties.) St. error of the statistic is $\sqrt{k(k+1)/(6n)}$. It divides the test statistic to yield standardized statistic $Z$ which is plugged in st. normal distribution to give the (Bonferroni yet uncorrected) 2-sided significance.
This comparison test looks very conservative. It failed to praise the pair V1-V2 as significant: Z=1.838, p=.066 despite that the omnibus Friedman is strongly significant: p=.002. In contrast, Sign test for pair V1-V2 (it will be the same irrespective whether you perform it on the raw values or on the ranks left from Friedman) has Z=3.575, p=.0004.
One reason the SPSS "Dunn's approach" is quite conservative is its st. error formula accounting for all the $k$, not 2, variables.
Another reason why it is so less powerful than the Sign test is that it bases itself on all the $n$ cases, including those with ties, while Sign test discards cases with ties; and there is many cases with ties in our data. The problem of power in conjunction with treatment of ties in tests such as Sign was observed, for example in this Q/A.
I took V1 and V2 and, for cases with ties, untied them in a random fashion (by adding negative or positive noise), and computed Sign test (now based on all $n$ cases of course). 500 such trials gave me mean Z=1.927, which is now far from Z=3.575 and much closer on the road of conservatism towards the observed Dunn's Z=1.838.
I feel myself dissatisfied with SPSS' "Dunn's" pairwise comparisons as they are too conservative/weak. We expect that if an omnibus test is significant post hoc tests will confirm it often, if not ever. In our example, even Bonferroni-uncorrected p-value could not support the omnibus conclusion.
Is SPSS at all correct in adopting the "Dunn's approach" (originally proposed for Kruskal-Wallis; see also this Q/A) for Friedman post-hoc testing? I can't say, being hardly an expert in multiple comparisons. I would encourage somebody who knows it to comment or post a really helpful answer on this thread.
P.S. I'm quite aware that, while Friedman test can be seen as an extension of Sign test from 2 to $k$ samples (variables), a pairwise post hoc test after Friedman is not and should not be exactly the Sign test. Neither it would be Wilcoxon paired-samle test. The "Dunn's approach" (if adapted to paired-sample situation) looks plausible post hoc because it compares, without further ranking, the "horizontal" ranks obtained at Friedman and reflecting all the $k$ samples. What bothered me, though, was that the approach appeared overconservative in the example of the post.
Later Addition. To me, Dunn's approach as it is implemented after Friedman's test in SPSS is incorrect. It does not adjust for ties in the same fashion as the parent omnibus test (Friedman) does it. Actually, it does not adjust for the ties at all, while it should. (The issue of ties handling is touched in the current answer above.)
The formula of Friedman's test statistic (explained in SPSS Algorithms) is
$$\chi^2= \frac{[12/(nk(k+1))]\sum^k C^2-3n(k+1)}{1-\Sigma T/[nk(k^2-1)]}$$
The denominator of the formula contains the adjustment for ties. If $k=2$ then quantity $\Sigma T/[nk(k^2-1)]$ is the proportion of cases in which the two variables are equal (tied).
Consider Friedman test performed with our variables V1 and V2 ($k=2$). The proportion of cases with ties is 287/400=.7175 and the test statistic is 13.460, df=1 with significance p=.00024. But the "Dunn's" comparison computed following SPSS formulas will be
Sample1 Sample2 MeanRank1 MeanRank2 TestStat StError Z Sig2side AdjSig
V1 V2 1.54875 1.45125 .0975 .0500 1.9500 .05118 .05118
Nonsignificant. Why? No proper (Friedman style) adjustment for ties was done.
In the presense of only $k=2$ samples in data a correct post hoc pairwise comparison test must give the same result (statistic and p-value) as the omnibus test - it is actually a property which proves that the post hoc test corresponds (is isomorphic) to the parent omnibus test. It is indeed so with Kruskal-Wallis test and Dunn's test - just program it following SPSS Algorithms and test with V1 and V2 as two independent groups, and you'll get same p=.0153 both for KW and for Dunn. But we saw that a similar equivalence is absent in relations between Friedman test and "Dunn's approach" post-Friedman comparison test.
Conclusion. Post hoc multiple comparison test being performed by SPSS (version 22 and earlier) after Friedman's test is defective. Maybe it is correct when there is no ties, but I don't know. The post hoc test does not treat ties the way Friedman does it (while it should). I cannot say anything about the formula of st. error, sqrt[k*(k+1)/(6n)], they are using: it was derived from discrete uniform distribution, but they didn't write how; is it correct? Either the "Dunn's test approach" was adapted to Friedman inadequatly by SPSS or Dunn's test cannot be adapted to Friedman at all. | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
SPSS Algorithms state that in doing pairwise comparisons after Friedman test they use the Dunn's (1964) procedure. I didn't read that Dunn's original paper so I can't say if SPSS follows it correctly, |
34,740 | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | I found (via a ResearchGate question) lots of good stuff in the vignette for the PMCMR package (which is now deprecated in favor of PMCMRplus), including post hoc tests by Nemenyi (1963) and Conover (1999). The vignette (citing Conover,1999) claims that the Quade test is more powerful than the Friedman test if $k<5$, and a post hoc test for that is implemented in these packages too. Its pairwise comparisons seem to give a more satisfying result that is congruent with the omnibus test.
Note also some caveats about the Friedman test quoted below. Following this logic, I've been using regular old Tukey post hocs for a repeated measures ANOVA of rank-transformed data. This takes a bit more doing in terms of R code, but it should be easy in SPSS...just make sure to do the rank transformation on one big vector that pools all repeated measures all at once rather than rank-transforming each measure independently (this caused a problem for a collaborator of mine recently)! Results of this method seem satisfying in Niksr's case too (see below).
Quote from T. Baguley's weblog, Beware the Friedman test!
The ranks for the Friedman test depend only on the order of scores within each participant – they completely ignore the differences between participants. This differs dramatically from the Wilcoxon test where information about the relative size of differences between participants is preserved. Zimmerman and Zumbo (1993)...explain that the Friedman test...is not really a form of ANOVA but an extension of the sign test...
This is bad news because the sign test tends to have low power relative to the paired $t$ test or Wilcoxon sign rank test. Indeed, the asymptotic relative efficiency relative to ANOVA of the Friedman test is $.955 J/(J+1)$ where $J$ is the number of repeated measures (see Zimmerman & Zumbo, 1993). Thus it is about .72 for $J = 3$ and .76 for $J = 4$, implying quite a big hit in power relative to ANOVA when the assumptions are met. This is a large sample limit, but small samples should also have considerably less power because the sign test and the Friedman test, in effect, throw information away. The additional robustness of the sign test may sometimes justify its application (as it may outperform Wilcoxon for heavy-tailed distributions), but this does not appear to be the case for the Friedman test. Thus, where one-way repeated measures ANOVA is not appropriate, rank transformation followed by ANOVA will provide a more robust test with greater statistical power than the Friedman test.
Sure enough, the rank-transformed RMANOVA does produce a smaller $p$ than the Friedman test in Niksr's case. As for what the appropriate post hoc for a Friedman test is, I'm still wondering myself, so pardon the lack of a definitive answer here, and please comment or edit freely if you can help sort through the choices – it seems there are many. My code below demonstrates the outcomes of the five options in PMCMRplus for Niksr's data using defaults for $p$ value adjustments. Note that defaults differ across tests, which may make them harder to compare. I'm open to suggestions/edits on this too if identical adjustments would be more useful in this answer.
R code
library(foreign);library(PCMCRplus);library(car);library(lme4);library(multcomp)
CVd8a=read.spss(file.choose(),use.value.labels=T,max.value.labels=Inf,to.data.frame=T)
quade.test(as.matrix(CVd8a)) #this is in the stats package
quadeAllPairsTest(CVd8a) #this requires PMCMRplus
CVd8L=stack(CVd8a);CVd8L$PID=rep(1:nrow(CVd8a),ncol(CVd8a)) #long format for RMANOVA in R
Anova(lmer(rank(values,'keep')~ind+(1|PID),CVd8L),3,'F') #1-way RMANOVA, type 3 SS, F test
summary(glht(lmer(rank(values,'keep')~ind+(1|PID),CVd8L),mcp(ind='Tukey')))
cld(lsmeans(lmer(rank(values,'keep')~ind+(1|PID),CVd8L),'ind')) #compact letter display
# Various Post hocs explicitly intended to follow the Friedman test:
frdAllPairsNemenyiTest(CVd8a)
frdAllPairsConoverTest(CVd8a)
frdAllPairsMillerTest(CVd8a)
frdAllPairsSiegelTest(CVd8a)
frdAllPairsExactTest(CVd8a)
Output (abridged)
Quade test
Quade F = 6.5769, num df = 2, denom df = 798, p-value = 0.001469
Pairwise comparisons using Quade's test with TDist approximation
V1 V2
V2 0.0034 -
V3 0.0057 0.7832
P value adjustment method: holm
Analysis of Deviance Table (Type III Wald F tests with Kenward-Roger df)
F Df Df.res Pr(>F)
(Intercept) 1894.7708 1 830.45 < 2.2e-16 ***
ind 6.4579 2 798.00 0.001651 **
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Tukey Contrasts
Linear Hypotheses:
Estimate Std. Error z value Pr(>|z|)
V2 - V1 == 0 -49.311 14.934 -3.302 0.00292 **
V3 - V1 == 0 -43.006 14.934 -2.880 0.01127 *
V3 - V2 == 0 6.305 14.934 0.422 0.90644
(Adjusted p values reported -- single-step method)
ind lsmean SE df lower.CL upper.CL .group
V2 581.9612 14.50235 830.45 553.4957 610.4268 1
V3 588.2662 14.50235 830.45 559.8007 616.7318 1
V1 631.2725 14.50235 830.45 602.8069 659.7381 2
Degrees-of-freedom method: satterthwaite
Results are given on the rank (not the response) scale.
Confidence level used: 0.95
P value adjustment: tukey method for comparing a family of 3 estimates
significance level used: alpha = 0.05
Nemenyi-Wilcoxon-Wilcox all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.16 -
V3 0.24 0.97
P value adjustment method: single-step
Conover's all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.0039 -
V3 0.0141 0.9155
P value adjustment method: single-step
Miller / Bortz et al. / Wike all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.18 -
V3 0.27 0.97
P value adjustment method: none
Siegel-Castellan all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.20 -
V3 0.22 0.82
P value adjustment method: holm
Eisinga, Heskes, Pelzer & Te Grotenhuis all-pairs test with exact p-values for a two-way
balanced complete block design
V1 V2
V2 0.21 -
V3 0.22 0.82
P value adjustment method: holm | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | I found (via a ResearchGate question) lots of good stuff in the vignette for the PMCMR package (which is now deprecated in favor of PMCMRplus), including post hoc tests by Nemenyi (1963) and Conover ( | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
I found (via a ResearchGate question) lots of good stuff in the vignette for the PMCMR package (which is now deprecated in favor of PMCMRplus), including post hoc tests by Nemenyi (1963) and Conover (1999). The vignette (citing Conover,1999) claims that the Quade test is more powerful than the Friedman test if $k<5$, and a post hoc test for that is implemented in these packages too. Its pairwise comparisons seem to give a more satisfying result that is congruent with the omnibus test.
Note also some caveats about the Friedman test quoted below. Following this logic, I've been using regular old Tukey post hocs for a repeated measures ANOVA of rank-transformed data. This takes a bit more doing in terms of R code, but it should be easy in SPSS...just make sure to do the rank transformation on one big vector that pools all repeated measures all at once rather than rank-transforming each measure independently (this caused a problem for a collaborator of mine recently)! Results of this method seem satisfying in Niksr's case too (see below).
Quote from T. Baguley's weblog, Beware the Friedman test!
The ranks for the Friedman test depend only on the order of scores within each participant – they completely ignore the differences between participants. This differs dramatically from the Wilcoxon test where information about the relative size of differences between participants is preserved. Zimmerman and Zumbo (1993)...explain that the Friedman test...is not really a form of ANOVA but an extension of the sign test...
This is bad news because the sign test tends to have low power relative to the paired $t$ test or Wilcoxon sign rank test. Indeed, the asymptotic relative efficiency relative to ANOVA of the Friedman test is $.955 J/(J+1)$ where $J$ is the number of repeated measures (see Zimmerman & Zumbo, 1993). Thus it is about .72 for $J = 3$ and .76 for $J = 4$, implying quite a big hit in power relative to ANOVA when the assumptions are met. This is a large sample limit, but small samples should also have considerably less power because the sign test and the Friedman test, in effect, throw information away. The additional robustness of the sign test may sometimes justify its application (as it may outperform Wilcoxon for heavy-tailed distributions), but this does not appear to be the case for the Friedman test. Thus, where one-way repeated measures ANOVA is not appropriate, rank transformation followed by ANOVA will provide a more robust test with greater statistical power than the Friedman test.
Sure enough, the rank-transformed RMANOVA does produce a smaller $p$ than the Friedman test in Niksr's case. As for what the appropriate post hoc for a Friedman test is, I'm still wondering myself, so pardon the lack of a definitive answer here, and please comment or edit freely if you can help sort through the choices – it seems there are many. My code below demonstrates the outcomes of the five options in PMCMRplus for Niksr's data using defaults for $p$ value adjustments. Note that defaults differ across tests, which may make them harder to compare. I'm open to suggestions/edits on this too if identical adjustments would be more useful in this answer.
R code
library(foreign);library(PCMCRplus);library(car);library(lme4);library(multcomp)
CVd8a=read.spss(file.choose(),use.value.labels=T,max.value.labels=Inf,to.data.frame=T)
quade.test(as.matrix(CVd8a)) #this is in the stats package
quadeAllPairsTest(CVd8a) #this requires PMCMRplus
CVd8L=stack(CVd8a);CVd8L$PID=rep(1:nrow(CVd8a),ncol(CVd8a)) #long format for RMANOVA in R
Anova(lmer(rank(values,'keep')~ind+(1|PID),CVd8L),3,'F') #1-way RMANOVA, type 3 SS, F test
summary(glht(lmer(rank(values,'keep')~ind+(1|PID),CVd8L),mcp(ind='Tukey')))
cld(lsmeans(lmer(rank(values,'keep')~ind+(1|PID),CVd8L),'ind')) #compact letter display
# Various Post hocs explicitly intended to follow the Friedman test:
frdAllPairsNemenyiTest(CVd8a)
frdAllPairsConoverTest(CVd8a)
frdAllPairsMillerTest(CVd8a)
frdAllPairsSiegelTest(CVd8a)
frdAllPairsExactTest(CVd8a)
Output (abridged)
Quade test
Quade F = 6.5769, num df = 2, denom df = 798, p-value = 0.001469
Pairwise comparisons using Quade's test with TDist approximation
V1 V2
V2 0.0034 -
V3 0.0057 0.7832
P value adjustment method: holm
Analysis of Deviance Table (Type III Wald F tests with Kenward-Roger df)
F Df Df.res Pr(>F)
(Intercept) 1894.7708 1 830.45 < 2.2e-16 ***
ind 6.4579 2 798.00 0.001651 **
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Tukey Contrasts
Linear Hypotheses:
Estimate Std. Error z value Pr(>|z|)
V2 - V1 == 0 -49.311 14.934 -3.302 0.00292 **
V3 - V1 == 0 -43.006 14.934 -2.880 0.01127 *
V3 - V2 == 0 6.305 14.934 0.422 0.90644
(Adjusted p values reported -- single-step method)
ind lsmean SE df lower.CL upper.CL .group
V2 581.9612 14.50235 830.45 553.4957 610.4268 1
V3 588.2662 14.50235 830.45 559.8007 616.7318 1
V1 631.2725 14.50235 830.45 602.8069 659.7381 2
Degrees-of-freedom method: satterthwaite
Results are given on the rank (not the response) scale.
Confidence level used: 0.95
P value adjustment: tukey method for comparing a family of 3 estimates
significance level used: alpha = 0.05
Nemenyi-Wilcoxon-Wilcox all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.16 -
V3 0.24 0.97
P value adjustment method: single-step
Conover's all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.0039 -
V3 0.0141 0.9155
P value adjustment method: single-step
Miller / Bortz et al. / Wike all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.18 -
V3 0.27 0.97
P value adjustment method: none
Siegel-Castellan all-pairs test for a two-way balanced complete block design
V1 V2
V2 0.20 -
V3 0.22 0.82
P value adjustment method: holm
Eisinga, Heskes, Pelzer & Te Grotenhuis all-pairs test with exact p-values for a two-way
balanced complete block design
V1 V2
V2 0.21 -
V3 0.22 0.82
P value adjustment method: holm | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
I found (via a ResearchGate question) lots of good stuff in the vignette for the PMCMR package (which is now deprecated in favor of PMCMRplus), including post hoc tests by Nemenyi (1963) and Conover ( |
34,741 | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | I did Dunn's test on your data with the dunn.test R package which yielded this:
> library(foreign, pos=14)
> Dataset <- read.spss("/Users/Friedman_Sample.sav", use.value.labels=TRUE,
+ max.value.labels=Inf, to.data.frame=TRUE)
> colnames(Dataset) <- tolower(colnames(Dataset))
> library(relimp, pos=15)
> showData(Dataset, placement='-20+200', font=getRcmdr('logFont'), maxwidth=80,
+ maxheight=30, suppress.X11.warnings=FALSE)
> local({
+ .Responses <- na.omit(with(Dataset, cbind(v1, v2, v3)))
+ cat("\nMedians:\n")
+ print(apply(.Responses, 2, median))
+ friedman.test(.Responses)
+ })
Medians:
v1 v2 v3
5 5 5
Friedman rank sum test
data: .Responses
Friedman chi-squared = 12.117, df = 2, p-value = 0.002338
> dunn.test(Dataset)
Kruskal-Wallis rank sum test
data: Dataset and group
Kruskal-Wallis chi-squared = 6.8206, df = 2, p-value = 0.03
Comparison of Dataset by group
(No adjustment)
Col Mean-|
Row Mean | 1 2
---------+----------------------
2 | -2.399474
| 0.0082
|
3 | -2.092674 0.306799
| 0.0182 0.3795 | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | I did Dunn's test on your data with the dunn.test R package which yielded this:
> library(foreign, pos=14)
> Dataset <- read.spss("/Users/Friedman_Sample.sav", use.value.labels=TRUE,
+ max.value.l | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
I did Dunn's test on your data with the dunn.test R package which yielded this:
> library(foreign, pos=14)
> Dataset <- read.spss("/Users/Friedman_Sample.sav", use.value.labels=TRUE,
+ max.value.labels=Inf, to.data.frame=TRUE)
> colnames(Dataset) <- tolower(colnames(Dataset))
> library(relimp, pos=15)
> showData(Dataset, placement='-20+200', font=getRcmdr('logFont'), maxwidth=80,
+ maxheight=30, suppress.X11.warnings=FALSE)
> local({
+ .Responses <- na.omit(with(Dataset, cbind(v1, v2, v3)))
+ cat("\nMedians:\n")
+ print(apply(.Responses, 2, median))
+ friedman.test(.Responses)
+ })
Medians:
v1 v2 v3
5 5 5
Friedman rank sum test
data: .Responses
Friedman chi-squared = 12.117, df = 2, p-value = 0.002338
> dunn.test(Dataset)
Kruskal-Wallis rank sum test
data: Dataset and group
Kruskal-Wallis chi-squared = 6.8206, df = 2, p-value = 0.03
Comparison of Dataset by group
(No adjustment)
Col Mean-|
Row Mean | 1 2
---------+----------------------
2 | -2.399474
| 0.0082
|
3 | -2.092674 0.306799
| 0.0182 0.3795 | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
I did Dunn's test on your data with the dunn.test R package which yielded this:
> library(foreign, pos=14)
> Dataset <- read.spss("/Users/Friedman_Sample.sav", use.value.labels=TRUE,
+ max.value.l |
34,742 | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | since the question has passed one year, I'm not sure whether you have settled down this problem. Recently I have met the same confusion that I have a significant result after Friedman test in SPSS but I don't know where the significance from and it seems that the spss were not able to do the post test by Dunnt.
I have checked other resources and statistic information, and my answer is that: first, don't worry about your previous result. the hypothesis in the Friedman is not the hypothesis in the post test; second, the spss could not do the Dunnt post test but we can use Wilcoxon signed-rank, the limitation is that you should pair your samples and use the bofferonie correction to lowdown the type 1 error. | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant | since the question has passed one year, I'm not sure whether you have settled down this problem. Recently I have met the same confusion that I have a significant result after Friedman test in SPSS but | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
since the question has passed one year, I'm not sure whether you have settled down this problem. Recently I have met the same confusion that I have a significant result after Friedman test in SPSS but I don't know where the significance from and it seems that the spss were not able to do the post test by Dunnt.
I have checked other resources and statistic information, and my answer is that: first, don't worry about your previous result. the hypothesis in the Friedman is not the hypothesis in the post test; second, the spss could not do the Dunnt post test but we can use Wilcoxon signed-rank, the limitation is that you should pair your samples and use the bofferonie correction to lowdown the type 1 error. | Friedman's test is very significant, but its post hoc comparisons (SPSS) are not significant
since the question has passed one year, I'm not sure whether you have settled down this problem. Recently I have met the same confusion that I have a significant result after Friedman test in SPSS but |
34,743 | Can I get the parameters of a lognormal distribution from the sample mean & median? | It rather depends on what you mean by "get". In general you can't obtain population quantities from sample information. However, you can often obtain estimates, though in this case the estimates may not be very good.
If you have them, you can readily calculate the parameters from the population mean and median; if $\tilde{m}=\exp(\mu)$ is the population median and $m=\exp(\mu+\frac12\sigma^2)$ is the population mean then $\mu=\log(\tilde{m})$ and $\sigma^2=2\log(\frac{m}{\tilde{m}})=2(\log(m)-\log(\tilde{m}))$.
You could similarly attempt to use the sample mean and sample median in some kind of estimator of the population quantities.
If the only things you have are the sample mean and median from a lognormal ($\bar{x}$ and $\tilde{x}$ respectively) then you could at least use the obvious strategy of replacing population quantities by sample ones*, combining method of moments and method of quantiles ... $\hat{\mu}=\log(\tilde{x})$ and $\hat{\sigma}^2=2\log(\frac{\bar{x}}{\tilde{x}})=2(\log(\bar{x})-\log(\tilde{x}))$.
I believe these estimators will be consistent. However, in small samples these are sure to be biased, and may not be very efficient, but you may not have a lot of choice without considerable analysis.
Of course, in reality, you don't really know your data are drawn from a lognormal distribution - that's pretty much a guess. However, in practice it might be a quite serviceable assumption.
Ideally one would work out the joint distribution of the sample mean and median from a lognormal, and then try to maximize the likelihood over the parameters on that bivariate distribution; that should do about as well as possible, but that's more a decent research problem (maybe worth a paper if it hasn't been done before) than a matter of a few paragraphs of answer.
One could conduct some simulation investigations into the properties of the joint distribution of sample mean and median (asymptotically I expect the joint distribution of their logs to be close to bivariate normal but in small samples this is not the case).
For example, consider that the distribution of the ratio of mean to median should be scale-free -- a function of $\sigma$ only. Even if we can't compute it algebraically, we can look at how the ratio (for example) behaves as $\sigma$ changes. One might then be able to choose the $\sigma$ that approximately maximizes the chance of getting the ratio you observed ($\mu$ could be estimated in a variety of ways, but the obvious one - the log of the median, as mentioned earlier - would not be terrible).
* Warning: it's perfectly possible for the sample median to exceed the sample mean. In that case the simple estimator suggested above is no help, since it relies on the mean being above the median (it will give a negative estimate for a positive parameter). Indeed, if $\sigma^2$ is smallish (including perfectly plausible values you will see in practice in many applications), this naive estimator may be very poor unless the sample size is huge. On the other hand it seems to perform fairly well even at fairly modest sample sizes for larger $\sigma^2$ values.
Such an issue isn't a huge surprise. | Can I get the parameters of a lognormal distribution from the sample mean & median? | It rather depends on what you mean by "get". In general you can't obtain population quantities from sample information. However, you can often obtain estimates, though in this case the estimates may n | Can I get the parameters of a lognormal distribution from the sample mean & median?
It rather depends on what you mean by "get". In general you can't obtain population quantities from sample information. However, you can often obtain estimates, though in this case the estimates may not be very good.
If you have them, you can readily calculate the parameters from the population mean and median; if $\tilde{m}=\exp(\mu)$ is the population median and $m=\exp(\mu+\frac12\sigma^2)$ is the population mean then $\mu=\log(\tilde{m})$ and $\sigma^2=2\log(\frac{m}{\tilde{m}})=2(\log(m)-\log(\tilde{m}))$.
You could similarly attempt to use the sample mean and sample median in some kind of estimator of the population quantities.
If the only things you have are the sample mean and median from a lognormal ($\bar{x}$ and $\tilde{x}$ respectively) then you could at least use the obvious strategy of replacing population quantities by sample ones*, combining method of moments and method of quantiles ... $\hat{\mu}=\log(\tilde{x})$ and $\hat{\sigma}^2=2\log(\frac{\bar{x}}{\tilde{x}})=2(\log(\bar{x})-\log(\tilde{x}))$.
I believe these estimators will be consistent. However, in small samples these are sure to be biased, and may not be very efficient, but you may not have a lot of choice without considerable analysis.
Of course, in reality, you don't really know your data are drawn from a lognormal distribution - that's pretty much a guess. However, in practice it might be a quite serviceable assumption.
Ideally one would work out the joint distribution of the sample mean and median from a lognormal, and then try to maximize the likelihood over the parameters on that bivariate distribution; that should do about as well as possible, but that's more a decent research problem (maybe worth a paper if it hasn't been done before) than a matter of a few paragraphs of answer.
One could conduct some simulation investigations into the properties of the joint distribution of sample mean and median (asymptotically I expect the joint distribution of their logs to be close to bivariate normal but in small samples this is not the case).
For example, consider that the distribution of the ratio of mean to median should be scale-free -- a function of $\sigma$ only. Even if we can't compute it algebraically, we can look at how the ratio (for example) behaves as $\sigma$ changes. One might then be able to choose the $\sigma$ that approximately maximizes the chance of getting the ratio you observed ($\mu$ could be estimated in a variety of ways, but the obvious one - the log of the median, as mentioned earlier - would not be terrible).
* Warning: it's perfectly possible for the sample median to exceed the sample mean. In that case the simple estimator suggested above is no help, since it relies on the mean being above the median (it will give a negative estimate for a positive parameter). Indeed, if $\sigma^2$ is smallish (including perfectly plausible values you will see in practice in many applications), this naive estimator may be very poor unless the sample size is huge. On the other hand it seems to perform fairly well even at fairly modest sample sizes for larger $\sigma^2$ values.
Such an issue isn't a huge surprise. | Can I get the parameters of a lognormal distribution from the sample mean & median?
It rather depends on what you mean by "get". In general you can't obtain population quantities from sample information. However, you can often obtain estimates, though in this case the estimates may n |
34,744 | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian | A multivariate Gaussian (or Normal) random variable $X=(X_1,X_2,\ldots,X_n)$ can be defined as an affine transformation of a tuple of independent standard Normal variates $Z=(Z_1,Z_2,\ldots, Z_m)$. This easily implies the desired result, because when we condition $X$, we impose linear constraints among the $Z_j$. (If this is not obvious, please read on through the details.) This merely reduces the number of "free" $Z_j$ contributing to the variation among the $X_i$--but those $X_i$ nevertheless remain affine combinations of independent standard Normals, QED.
We can obtain this result in three steps of increasing generality. First, the distribution of $X$ conditional on its first component is Normal. Second, this implies the distribution of $X$ conditional on some linear constraint $C^\prime X = d$ is Normal. Finally, that implies the distribution of $X$ conditional on any finite set of $r$ such linear constraints is Normal.
Details
By definition,
$$X = \mathbb{A} Z + B$$
for some $n\times m$ matrix $\mathbb{A} = (a_{ij})$ and $n$-vector $B = (b_1, b_2, \ldots, b_n)$. Because one affine followed by another is still an affine transformation, notice that any affine transformation of $X$ is therefore also Normal. This fact will be used repeatedly.
Fix a number $x_1$ in order to consider the distribution of $X$ conditional on $X_1=x_1$. Replacing $X_1$ by its definition produces
$$x_1 = X_1 = b_1 + a_{11}Z_1 + a_{12}Z_2 + \cdots + a_{1m}Z_m.$$
When all the $a_{1j}=0$, the two cases $x_1=b_1$ and $x_1\ne b_1$ are easy to dispose of, so let's move on to the alternative where, for at least one index $k$, $a_{1k}\ne 0$. Solving for $Z_k$ exhibits it as an affine combination of the remaining $Z_j,\, j\ne k$:
$$Z_k = \frac{1}{a_{1k}}\left(x_1 - b_1 - (a_{11}Z_1 + \cdots + a_{1,k-1} + a_{1,k+1} + \cdots + a_{1m}Z_m)\right).$$
Plugging this in to $\mathbb{A}Z + B$ produces an affine combination of the remaining $Z_j$, explicitly exhibiting the conditional distribution of $X$ as an affine combination of $m-1$ independent standard normal variates, whence the conditional distribution is Normal.
Now consider any vector $C=(c_1, c_2, \ldots, c_n)$ and another constant $d$. To obtain the conditional distribution of $X$ given $C^\prime X = d$, construct the $n+1$-vector
$$Y = (Y_1,Y_2,\ldots, Y_{n+1})=(C^\prime X, X_1, X_2, \ldots, X_n) + (d, b_1, b_2, \ldots, b_n).$$
It is an affine combination of the same $Z_j$: the matrix $\mathbb{A}$ is row-augmented (at the top) by $C^\prime \mathbb{A}$ (an $n+1\times m$ matrix) and the vector of means $B$ is augmented at the beginning by the constant $d$. Therefore, by definition, $Y$ is multivariate Normal. Applying the preceding result to $Y$ and $d$ immediately shows that $Y$, conditional on $Y_1 = d$, is multivariate Normal. Upon ignoring the first component of $Y$ (which is an affine transformation!), that is precisely the distribution of $X$ conditional on $C^\prime X = d$.
The distribution of $X$ conditional on $\mathbb{C}X = D$ for an $r\times n$ matrix $\mathbb{C}$ and an $r$-vector $D$ is obtained inductively by applying the preceding construction one term at a time (working row-by-row through $\mathbb{C}$ and component-by-component through $D$). The conditionals are Normal at every step, whence the final conditional distribution is Normal, too. | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian | A multivariate Gaussian (or Normal) random variable $X=(X_1,X_2,\ldots,X_n)$ can be defined as an affine transformation of a tuple of independent standard Normal variates $Z=(Z_1,Z_2,\ldots, Z_m)$. T | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian
A multivariate Gaussian (or Normal) random variable $X=(X_1,X_2,\ldots,X_n)$ can be defined as an affine transformation of a tuple of independent standard Normal variates $Z=(Z_1,Z_2,\ldots, Z_m)$. This easily implies the desired result, because when we condition $X$, we impose linear constraints among the $Z_j$. (If this is not obvious, please read on through the details.) This merely reduces the number of "free" $Z_j$ contributing to the variation among the $X_i$--but those $X_i$ nevertheless remain affine combinations of independent standard Normals, QED.
We can obtain this result in three steps of increasing generality. First, the distribution of $X$ conditional on its first component is Normal. Second, this implies the distribution of $X$ conditional on some linear constraint $C^\prime X = d$ is Normal. Finally, that implies the distribution of $X$ conditional on any finite set of $r$ such linear constraints is Normal.
Details
By definition,
$$X = \mathbb{A} Z + B$$
for some $n\times m$ matrix $\mathbb{A} = (a_{ij})$ and $n$-vector $B = (b_1, b_2, \ldots, b_n)$. Because one affine followed by another is still an affine transformation, notice that any affine transformation of $X$ is therefore also Normal. This fact will be used repeatedly.
Fix a number $x_1$ in order to consider the distribution of $X$ conditional on $X_1=x_1$. Replacing $X_1$ by its definition produces
$$x_1 = X_1 = b_1 + a_{11}Z_1 + a_{12}Z_2 + \cdots + a_{1m}Z_m.$$
When all the $a_{1j}=0$, the two cases $x_1=b_1$ and $x_1\ne b_1$ are easy to dispose of, so let's move on to the alternative where, for at least one index $k$, $a_{1k}\ne 0$. Solving for $Z_k$ exhibits it as an affine combination of the remaining $Z_j,\, j\ne k$:
$$Z_k = \frac{1}{a_{1k}}\left(x_1 - b_1 - (a_{11}Z_1 + \cdots + a_{1,k-1} + a_{1,k+1} + \cdots + a_{1m}Z_m)\right).$$
Plugging this in to $\mathbb{A}Z + B$ produces an affine combination of the remaining $Z_j$, explicitly exhibiting the conditional distribution of $X$ as an affine combination of $m-1$ independent standard normal variates, whence the conditional distribution is Normal.
Now consider any vector $C=(c_1, c_2, \ldots, c_n)$ and another constant $d$. To obtain the conditional distribution of $X$ given $C^\prime X = d$, construct the $n+1$-vector
$$Y = (Y_1,Y_2,\ldots, Y_{n+1})=(C^\prime X, X_1, X_2, \ldots, X_n) + (d, b_1, b_2, \ldots, b_n).$$
It is an affine combination of the same $Z_j$: the matrix $\mathbb{A}$ is row-augmented (at the top) by $C^\prime \mathbb{A}$ (an $n+1\times m$ matrix) and the vector of means $B$ is augmented at the beginning by the constant $d$. Therefore, by definition, $Y$ is multivariate Normal. Applying the preceding result to $Y$ and $d$ immediately shows that $Y$, conditional on $Y_1 = d$, is multivariate Normal. Upon ignoring the first component of $Y$ (which is an affine transformation!), that is precisely the distribution of $X$ conditional on $C^\prime X = d$.
The distribution of $X$ conditional on $\mathbb{C}X = D$ for an $r\times n$ matrix $\mathbb{C}$ and an $r$-vector $D$ is obtained inductively by applying the preceding construction one term at a time (working row-by-row through $\mathbb{C}$ and component-by-component through $D$). The conditionals are Normal at every step, whence the final conditional distribution is Normal, too. | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian
A multivariate Gaussian (or Normal) random variable $X=(X_1,X_2,\ldots,X_n)$ can be defined as an affine transformation of a tuple of independent standard Normal variates $Z=(Z_1,Z_2,\ldots, Z_m)$. T |
34,745 | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian | The device used in the answer that you cite will also get you the conditional distribution. Here is a self-contained derivation with a slight change in notation.
Partition the column vector $X:=(X_1, X_2,\ldots, X_n)^T$ into subvectors $X_a$ and $X_b$:
$$
X = \left(\begin{matrix}X_a\\X_b\end{matrix}\right)
$$
and correspondingly partition the mean vector $\mu$ and covariance matrix $\Sigma$ of $X$:
$$
\mu = \left(\begin{matrix}\mu_a\\ \mu_b\end{matrix}\right);\qquad
\Sigma=\left(\begin{matrix}\Sigma_{a,a}&\Sigma_{a,b}\\\Sigma_{b,a}&\Sigma_{b,b}\end{matrix}\right)$$
The key is to find a matrix $C$ of constants such that
$$Z:=X_a- C X_b\tag1$$
is uncorrelated with $X_b$; and since $Z$ and $X_b$ are both Gaussian, they are also independent. For $Z$ and $X_b$ to be uncorrelated we demand
$$
0= \operatorname{cov} (Z, X_b)=\operatorname{cov} (X_a - CX_b, X_b)=\Sigma_{a,b}-C\Sigma_{b,b}.\tag2
$$
Such a $C$ can always be found: If $\Sigma_{b,b}$ is invertible, then $$
C:=\Sigma_{a,b}\Sigma_{b,b}^{-1}\tag3$$ will do; otherwise you can take $\Sigma_{b,b}^{-1}$ to be the Moore-Penrose pseudoinverse of $\Sigma_{b,b}$.
Now the conditional distribution of $X_a$ given $X_b=x_b$ is easily obtained:
$$P(X_a\in A\mid X_b=x_b)=P(Z+CX_b\in A\mid X_b=x_b)
\stackrel{(*)}=P(Z+Cx_b\in A),\tag4
$$
where in (*) we use the fact that $Z$ and $X_b$ are independent. But $Z+Cx_b$ clearly has a Gaussian distribution, since it's an affine transformation of the original vector $X$... and we're done!
This same device gets you the conditional mean:
$$\begin{align}
E(X_a\mid X_b=x_b)&=E(Z + C X_b\mid X_b=x_b)\\
&=E(Z\mid X_b=x_b) + Cx_b\\
&\stackrel{(*)}=E(Z) + Cx_b\\
&= E(X_a)- CE(X_b) + C(x_b)\\
&= \mu_a + C(x_b - \mu_b)
\end{align}
$$
and the conditional variance:
$$\begin{align}
\operatorname{var}(X_a\mid X_b=x_b)&=\operatorname{var}(Z + C X_b\mid X_b=x_b)\\
&=\operatorname{var}(Z\mid X_b=x_b)\\
&\stackrel{(*)}=\operatorname{var}(Z)\\
&= \operatorname{cov}(Z, X_a-CX_b)\\
&=\operatorname{cov}(Z, X_a) - \underbrace{\operatorname{cov}(Z, X_b)}_0 C^T\\
&=\operatorname{cov}(X_a-CX_b, X_a)\\
&=\Sigma_{a,a}-C\Sigma_{b,a}
\end{align}
$$ | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian | The device used in the answer that you cite will also get you the conditional distribution. Here is a self-contained derivation with a slight change in notation.
Partition the column vector $X:=(X_1, | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian
The device used in the answer that you cite will also get you the conditional distribution. Here is a self-contained derivation with a slight change in notation.
Partition the column vector $X:=(X_1, X_2,\ldots, X_n)^T$ into subvectors $X_a$ and $X_b$:
$$
X = \left(\begin{matrix}X_a\\X_b\end{matrix}\right)
$$
and correspondingly partition the mean vector $\mu$ and covariance matrix $\Sigma$ of $X$:
$$
\mu = \left(\begin{matrix}\mu_a\\ \mu_b\end{matrix}\right);\qquad
\Sigma=\left(\begin{matrix}\Sigma_{a,a}&\Sigma_{a,b}\\\Sigma_{b,a}&\Sigma_{b,b}\end{matrix}\right)$$
The key is to find a matrix $C$ of constants such that
$$Z:=X_a- C X_b\tag1$$
is uncorrelated with $X_b$; and since $Z$ and $X_b$ are both Gaussian, they are also independent. For $Z$ and $X_b$ to be uncorrelated we demand
$$
0= \operatorname{cov} (Z, X_b)=\operatorname{cov} (X_a - CX_b, X_b)=\Sigma_{a,b}-C\Sigma_{b,b}.\tag2
$$
Such a $C$ can always be found: If $\Sigma_{b,b}$ is invertible, then $$
C:=\Sigma_{a,b}\Sigma_{b,b}^{-1}\tag3$$ will do; otherwise you can take $\Sigma_{b,b}^{-1}$ to be the Moore-Penrose pseudoinverse of $\Sigma_{b,b}$.
Now the conditional distribution of $X_a$ given $X_b=x_b$ is easily obtained:
$$P(X_a\in A\mid X_b=x_b)=P(Z+CX_b\in A\mid X_b=x_b)
\stackrel{(*)}=P(Z+Cx_b\in A),\tag4
$$
where in (*) we use the fact that $Z$ and $X_b$ are independent. But $Z+Cx_b$ clearly has a Gaussian distribution, since it's an affine transformation of the original vector $X$... and we're done!
This same device gets you the conditional mean:
$$\begin{align}
E(X_a\mid X_b=x_b)&=E(Z + C X_b\mid X_b=x_b)\\
&=E(Z\mid X_b=x_b) + Cx_b\\
&\stackrel{(*)}=E(Z) + Cx_b\\
&= E(X_a)- CE(X_b) + C(x_b)\\
&= \mu_a + C(x_b - \mu_b)
\end{align}
$$
and the conditional variance:
$$\begin{align}
\operatorname{var}(X_a\mid X_b=x_b)&=\operatorname{var}(Z + C X_b\mid X_b=x_b)\\
&=\operatorname{var}(Z\mid X_b=x_b)\\
&\stackrel{(*)}=\operatorname{var}(Z)\\
&= \operatorname{cov}(Z, X_a-CX_b)\\
&=\operatorname{cov}(Z, X_a) - \underbrace{\operatorname{cov}(Z, X_b)}_0 C^T\\
&=\operatorname{cov}(X_a-CX_b, X_a)\\
&=\Sigma_{a,a}-C\Sigma_{b,a}
\end{align}
$$ | Conceptual proof that conditional of a multivariate Gaussian is multivariate Gaussian
The device used in the answer that you cite will also get you the conditional distribution. Here is a self-contained derivation with a slight change in notation.
Partition the column vector $X:=(X_1, |
34,746 | Distribution of sum of order statistics | Since$$(y_1,\ldots,y_r)\sim\frac{n!\theta^{-r}}{(n-r)!}e^{-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]}\mathbb{I}_{y_\le y_2\le \ldots \le y_r}$$you have the joint pdf of $(y_1,\ldots,y_r)$. From there, you can deduce the pdf of $$s_r=\sum_{i=1}^{r}y_i+(n-r)y_r\,.$$Indeed, because the Jacobian of the transform is constant,\begin{align*}f_s(y_1,\ldots,y_{r-1},s_r) &\propto f_Y\left(y_1,\ldots,\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}\Big/(n-r+1)\right) \\&\propto \theta^{-r} \exp\{-s_r/\theta\}\mathbb{I}_{y_\le y_2\le \ldots \le\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)}\end{align*}implies by integration in $y_1,\ldots,y_{r-1}$ that$$f_s(s_r)\propto\theta^{-r} \exp\{-s_r/\theta\}s_r^{r-1}$$
Indeed,
\begin{align*}
f_s(s_r)&=\int\cdots\int f_s(y_1,\ldots,y_{r-1},s_r)\text{d}y_1\cdots\text{d}y_{r-1}\\
&= \theta^{-r} \exp\{-s_r/\theta\}\int\cdots\int
\mathbb{I}_{y_\le y_2\le \ldots \le\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)}\text{d}y_1\cdots\text{d}y_{r-1}
\end{align*}
leads to constraint $y_{r-1}$ by $y_{r-2}\le y_{r-1}$ and by
$$y_{r-1}\le \left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)=\left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+1)-\frac{y_{r-1}}{n-r+1}$$
which simplifies into
$$y_{r-1}\le \left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+2)$$
If one starts integrating in $y_{r-1}$, the most inner integral is
\begin{align*}\int_{y_{r-2}}^{\{s_r-\sum_{i=1}^{r-2}y_i\}/(n-r+2)}\text{d}y_{r-1}&=\left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+2)-y_{r-2}\\
&=\left\{s_r-\sum_{i=1}^{r-3}y_i\right\}/(n-r+2)-\frac{(n-r+1)y_{r-2}}{n-r+2}
\end{align*}
and from there one can proceed by recursion.
Hence$$s_r\sim\mathcal{G}a(r,1/\theta)$$
Here is an R simulation to show the fit:
obtained as follows
n=10
r=5
sim=matrix(rexp(n*1e4),1e4,n)
sim=t(apply(sim,1,sort))
res=apply(sim[,1:r],1,sum)+(n-r)*sim[,5]
hist(res,prob=TRUE)
curve(dgamma(x,sh=(n-r),sc=1),add=TRUE) | Distribution of sum of order statistics | Since$$(y_1,\ldots,y_r)\sim\frac{n!\theta^{-r}}{(n-r)!}e^{-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]}\mathbb{I}_{y_\le y_2\le \ldots \le y_r}$$you have the joint pdf of $(y_1,\ldots,y_r)$. From the | Distribution of sum of order statistics
Since$$(y_1,\ldots,y_r)\sim\frac{n!\theta^{-r}}{(n-r)!}e^{-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]}\mathbb{I}_{y_\le y_2\le \ldots \le y_r}$$you have the joint pdf of $(y_1,\ldots,y_r)$. From there, you can deduce the pdf of $$s_r=\sum_{i=1}^{r}y_i+(n-r)y_r\,.$$Indeed, because the Jacobian of the transform is constant,\begin{align*}f_s(y_1,\ldots,y_{r-1},s_r) &\propto f_Y\left(y_1,\ldots,\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}\Big/(n-r+1)\right) \\&\propto \theta^{-r} \exp\{-s_r/\theta\}\mathbb{I}_{y_\le y_2\le \ldots \le\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)}\end{align*}implies by integration in $y_1,\ldots,y_{r-1}$ that$$f_s(s_r)\propto\theta^{-r} \exp\{-s_r/\theta\}s_r^{r-1}$$
Indeed,
\begin{align*}
f_s(s_r)&=\int\cdots\int f_s(y_1,\ldots,y_{r-1},s_r)\text{d}y_1\cdots\text{d}y_{r-1}\\
&= \theta^{-r} \exp\{-s_r/\theta\}\int\cdots\int
\mathbb{I}_{y_\le y_2\le \ldots \le\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)}\text{d}y_1\cdots\text{d}y_{r-1}
\end{align*}
leads to constraint $y_{r-1}$ by $y_{r-2}\le y_{r-1}$ and by
$$y_{r-1}\le \left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)=\left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+1)-\frac{y_{r-1}}{n-r+1}$$
which simplifies into
$$y_{r-1}\le \left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+2)$$
If one starts integrating in $y_{r-1}$, the most inner integral is
\begin{align*}\int_{y_{r-2}}^{\{s_r-\sum_{i=1}^{r-2}y_i\}/(n-r+2)}\text{d}y_{r-1}&=\left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+2)-y_{r-2}\\
&=\left\{s_r-\sum_{i=1}^{r-3}y_i\right\}/(n-r+2)-\frac{(n-r+1)y_{r-2}}{n-r+2}
\end{align*}
and from there one can proceed by recursion.
Hence$$s_r\sim\mathcal{G}a(r,1/\theta)$$
Here is an R simulation to show the fit:
obtained as follows
n=10
r=5
sim=matrix(rexp(n*1e4),1e4,n)
sim=t(apply(sim,1,sort))
res=apply(sim[,1:r],1,sum)+(n-r)*sim[,5]
hist(res,prob=TRUE)
curve(dgamma(x,sh=(n-r),sc=1),add=TRUE) | Distribution of sum of order statistics
Since$$(y_1,\ldots,y_r)\sim\frac{n!\theta^{-r}}{(n-r)!}e^{-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]}\mathbb{I}_{y_\le y_2\le \ldots \le y_r}$$you have the joint pdf of $(y_1,\ldots,y_r)$. From the |
34,747 | Distribution of sum of order statistics | I am also self-studying introduction to Mathematical Statistics 7th edition and I solved the same problem yesterday. This site has helped me a lot. I would like to contribute it too. I am not a native English speaker so please don't mind if my expression is not natural.
The problem asked us to find mgf of $\hat \theta$. We can find it using
mgf of $y_1,y_2,...,y_r$ that is $M_{\vec Y_r} ( \vec t)$.
Since $$f_{\vec Y_r}= {n!\over(n-r)! \theta^r} e^{-{1 \over \theta } (\sum^r_{i=1} {y_i}+(n-r)y_r)} $$ and $$M_{\vec Y_r} ( \vec t)=M_{\vec Y_r}((t_1,t_2,...,t_r)')=E[e^{t'Y}] $$
, this is what we get :
$$M_{\vec Y_r} ((t_1,t_2,...,t_r)')=\int_A {n!\over(n-r)! \theta^r} e^{ \sum^{r-1}_{i=1} {(t_i-{1 \over \theta })y_i}+(t_r-{(n-r+1)\over \theta})y_r} dy_1 dy_2 ...dy_r $$
where $A=\{(y_1,y_2,...,y_r)| 0<y_1\leq y_2 \leq ...\leq y_r < \infty \}$and $t_i <{1\over\theta}$.
We are interested in $\hat \theta= {1\over r}{(\sum^r_{i=1} {y_i}+(n-r)y_r)} $ which has the mgf, $M_{\hat \theta}(t)=E[e^{t \hat\theta}]$. And this is exactly the same with $M_{\vec Y_r} (({t\over r},{t\over r},...,{t\over r},{{n-r+1}\over r}t)')$
Here is some trick to simplify this, let $q_i=e^{-({1\over \theta}-{t\over r}) y_i}$ where $1 >q_1 \ge q_2 \ge ... \ge q_n >0$ and express the integral with $q_i$ s.
$$M_{\hat \theta}(t)={n!\over(n-r)! \theta^r} {1 \over { ({1 \over \theta }-{t \over r})^r}}
\int_0^1 \int_0^{q_1}...\int_0^{q_{r-1}} \int_0^{q_r} q_r^{(n-r)} dq_r dq_{r-1}...dq_2 dq_1 $$
You can calculate this easily.
$$M_{\hat \theta}(t)=(1-{\theta \over r}t)^{-r}$$
So you can conclude $$\hat\theta \sim \Gamma(r,{\theta \over r})$$ which has the mean $\theta$.
Thank you for reading my first answer on stackexchange. | Distribution of sum of order statistics | I am also self-studying introduction to Mathematical Statistics 7th edition and I solved the same problem yesterday. This site has helped me a lot. I would like to contribute it too. I am not a nativ | Distribution of sum of order statistics
I am also self-studying introduction to Mathematical Statistics 7th edition and I solved the same problem yesterday. This site has helped me a lot. I would like to contribute it too. I am not a native English speaker so please don't mind if my expression is not natural.
The problem asked us to find mgf of $\hat \theta$. We can find it using
mgf of $y_1,y_2,...,y_r$ that is $M_{\vec Y_r} ( \vec t)$.
Since $$f_{\vec Y_r}= {n!\over(n-r)! \theta^r} e^{-{1 \over \theta } (\sum^r_{i=1} {y_i}+(n-r)y_r)} $$ and $$M_{\vec Y_r} ( \vec t)=M_{\vec Y_r}((t_1,t_2,...,t_r)')=E[e^{t'Y}] $$
, this is what we get :
$$M_{\vec Y_r} ((t_1,t_2,...,t_r)')=\int_A {n!\over(n-r)! \theta^r} e^{ \sum^{r-1}_{i=1} {(t_i-{1 \over \theta })y_i}+(t_r-{(n-r+1)\over \theta})y_r} dy_1 dy_2 ...dy_r $$
where $A=\{(y_1,y_2,...,y_r)| 0<y_1\leq y_2 \leq ...\leq y_r < \infty \}$and $t_i <{1\over\theta}$.
We are interested in $\hat \theta= {1\over r}{(\sum^r_{i=1} {y_i}+(n-r)y_r)} $ which has the mgf, $M_{\hat \theta}(t)=E[e^{t \hat\theta}]$. And this is exactly the same with $M_{\vec Y_r} (({t\over r},{t\over r},...,{t\over r},{{n-r+1}\over r}t)')$
Here is some trick to simplify this, let $q_i=e^{-({1\over \theta}-{t\over r}) y_i}$ where $1 >q_1 \ge q_2 \ge ... \ge q_n >0$ and express the integral with $q_i$ s.
$$M_{\hat \theta}(t)={n!\over(n-r)! \theta^r} {1 \over { ({1 \over \theta }-{t \over r})^r}}
\int_0^1 \int_0^{q_1}...\int_0^{q_{r-1}} \int_0^{q_r} q_r^{(n-r)} dq_r dq_{r-1}...dq_2 dq_1 $$
You can calculate this easily.
$$M_{\hat \theta}(t)=(1-{\theta \over r}t)^{-r}$$
So you can conclude $$\hat\theta \sim \Gamma(r,{\theta \over r})$$ which has the mean $\theta$.
Thank you for reading my first answer on stackexchange. | Distribution of sum of order statistics
I am also self-studying introduction to Mathematical Statistics 7th edition and I solved the same problem yesterday. This site has helped me a lot. I would like to contribute it too. I am not a nativ |
34,748 | Sampling from Dirichlet-Multinomial | Since $$\Pr(\mathbf{x}\mid\boldsymbol{\alpha})=\int_{\mathbf{p}}\Pr(\mathbf{x}\mid \mathbf{p})\Pr(\mathbf{p}\mid\boldsymbol{\alpha})\textrm{d}\mathbf{p}$$the integral representation implies that $\Pr(\mathbf{x}\mid\boldsymbol{\alpha})$ is the marginal of $\Pr(\mathbf{x},\mathbf{p}\mid\boldsymbol{\alpha})$. Generating $\mathbf{x}$ thus results from generating $\mathbf p$ and then generating $\mathbf{x}$ conditional on $\mathbf p$. This means a generating mechanism is
Generate $\mathbf p\sim\dfrac{1}{\mathrm{B}(\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1}$, the $\text{Dir}(\alpha_1,\ldots,\alpha_K)$ distribution;
Generate $\mathbf{x}|{\mathbf p} \sim \dfrac{n!}{x_1!\cdots x_K!}\,p_1^{x_1}\cdots p_K^{x_K}$, the $\text{Mult}(p_1,\ldots,p_K)$ distribution;
where both steps are hopefully straightforward.
For instance, here are the R commands that correspond to the above:
k=5 # dimension of the problem
n=75 # sample size
alpha=runif(k) # value of alpha, here chosen at random
p=rgamma(k,alpha) # pre-simulation of the Dirichlet
y=sample(1:k,n,prob=p/sum(p),rep=TRUE) # Multinomial
x=sum(y==1)
for (i in 2:k) x=c(x,sum(y==i))
or, when using rmultinom:
x=rmultinom(1,n,p)
with an example
> alpha
[1] 0.2216704 0.6642411 0.2528082 0.6309828 0.6942128
> p/sum(p)
[1] 0.02193043 0.07335277 0.23146885 0.00250276 0.67074519
> x
[1] 1 6 15 0 53 | Sampling from Dirichlet-Multinomial | Since $$\Pr(\mathbf{x}\mid\boldsymbol{\alpha})=\int_{\mathbf{p}}\Pr(\mathbf{x}\mid \mathbf{p})\Pr(\mathbf{p}\mid\boldsymbol{\alpha})\textrm{d}\mathbf{p}$$the integral representation implies that $\Pr( | Sampling from Dirichlet-Multinomial
Since $$\Pr(\mathbf{x}\mid\boldsymbol{\alpha})=\int_{\mathbf{p}}\Pr(\mathbf{x}\mid \mathbf{p})\Pr(\mathbf{p}\mid\boldsymbol{\alpha})\textrm{d}\mathbf{p}$$the integral representation implies that $\Pr(\mathbf{x}\mid\boldsymbol{\alpha})$ is the marginal of $\Pr(\mathbf{x},\mathbf{p}\mid\boldsymbol{\alpha})$. Generating $\mathbf{x}$ thus results from generating $\mathbf p$ and then generating $\mathbf{x}$ conditional on $\mathbf p$. This means a generating mechanism is
Generate $\mathbf p\sim\dfrac{1}{\mathrm{B}(\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1}$, the $\text{Dir}(\alpha_1,\ldots,\alpha_K)$ distribution;
Generate $\mathbf{x}|{\mathbf p} \sim \dfrac{n!}{x_1!\cdots x_K!}\,p_1^{x_1}\cdots p_K^{x_K}$, the $\text{Mult}(p_1,\ldots,p_K)$ distribution;
where both steps are hopefully straightforward.
For instance, here are the R commands that correspond to the above:
k=5 # dimension of the problem
n=75 # sample size
alpha=runif(k) # value of alpha, here chosen at random
p=rgamma(k,alpha) # pre-simulation of the Dirichlet
y=sample(1:k,n,prob=p/sum(p),rep=TRUE) # Multinomial
x=sum(y==1)
for (i in 2:k) x=c(x,sum(y==i))
or, when using rmultinom:
x=rmultinom(1,n,p)
with an example
> alpha
[1] 0.2216704 0.6642411 0.2528082 0.6309828 0.6942128
> p/sum(p)
[1] 0.02193043 0.07335277 0.23146885 0.00250276 0.67074519
> x
[1] 1 6 15 0 53 | Sampling from Dirichlet-Multinomial
Since $$\Pr(\mathbf{x}\mid\boldsymbol{\alpha})=\int_{\mathbf{p}}\Pr(\mathbf{x}\mid \mathbf{p})\Pr(\mathbf{p}\mid\boldsymbol{\alpha})\textrm{d}\mathbf{p}$$the integral representation implies that $\Pr( |
34,749 | Is a spike-and-slab prior a proper prior? | First let's look at Mitchell and Beauchamp (1988)[1], for a description of what a spike-and-slab prior is:
That is, $\beta_j$ is uniformly distributed between the two limits $-f_j$ and $f_j$, except for a bit of probability mass concentrated at 0 if $x_j$ is vulnerable to deletion. We are interested in taking $f_j$ to be very large for all $j$, ...
Now if $f_j$ is large-but-finite, this is a proper prior - we can even write down the cdf explicitly.
(You'll sometimes see people actually draw something like this: - which might help with picturing it in some sense, but the problem with that is what then does the y-axis represent? It can't be density because the spike represents probability, and it can't be probability because the uniform part represents density. The two parts are on completely different scales. This seems to encourage the mistaken notion of conflating probability and density.)
Mitchell and Beauchamp keep $f_j$ finite but assume that it's large enough that the relevant integrals from $-f_j$ to $f_j$ can be well approximated by integrals from $-\infty$ to $\infty$.
If, however, we take the limit as $f_j\to\infty$ then of course it wouldn't be a proper prior. When being used as a prior for variable selection this generally isn't going to be done because of the way that impacts variable selection (try it for a simple case).
Other priors have been given the name "spike and slab" since -- including the case with a Gaussian slab, as you mention. In that case, the prior is proper as long as the variance of the normal is finite.
[1]: Mitchell T.J. and Beauchamp, J.J. (1988),
"Bayesian Variable Selection in Linear Regression"
Journal of the American Statistical Association, Vol. 83, No. 404 (Dec.),1023-1032 | Is a spike-and-slab prior a proper prior? | First let's look at Mitchell and Beauchamp (1988)[1], for a description of what a spike-and-slab prior is:
That is, $\beta_j$ is uniformly distributed between the two limits $-f_j$ and $f_j$, except | Is a spike-and-slab prior a proper prior?
First let's look at Mitchell and Beauchamp (1988)[1], for a description of what a spike-and-slab prior is:
That is, $\beta_j$ is uniformly distributed between the two limits $-f_j$ and $f_j$, except for a bit of probability mass concentrated at 0 if $x_j$ is vulnerable to deletion. We are interested in taking $f_j$ to be very large for all $j$, ...
Now if $f_j$ is large-but-finite, this is a proper prior - we can even write down the cdf explicitly.
(You'll sometimes see people actually draw something like this: - which might help with picturing it in some sense, but the problem with that is what then does the y-axis represent? It can't be density because the spike represents probability, and it can't be probability because the uniform part represents density. The two parts are on completely different scales. This seems to encourage the mistaken notion of conflating probability and density.)
Mitchell and Beauchamp keep $f_j$ finite but assume that it's large enough that the relevant integrals from $-f_j$ to $f_j$ can be well approximated by integrals from $-\infty$ to $\infty$.
If, however, we take the limit as $f_j\to\infty$ then of course it wouldn't be a proper prior. When being used as a prior for variable selection this generally isn't going to be done because of the way that impacts variable selection (try it for a simple case).
Other priors have been given the name "spike and slab" since -- including the case with a Gaussian slab, as you mention. In that case, the prior is proper as long as the variance of the normal is finite.
[1]: Mitchell T.J. and Beauchamp, J.J. (1988),
"Bayesian Variable Selection in Linear Regression"
Journal of the American Statistical Association, Vol. 83, No. 404 (Dec.),1023-1032 | Is a spike-and-slab prior a proper prior?
First let's look at Mitchell and Beauchamp (1988)[1], for a description of what a spike-and-slab prior is:
That is, $\beta_j$ is uniformly distributed between the two limits $-f_j$ and $f_j$, except |
34,750 | Difference between "Design based approach" and "Model based approach"? | A comprehensive overview and comparison between model-based and design-based approaches in impossible to fit into an answer on Cross Validated (not to mention that I'm not qualified enough to even attempt that). Having said that, it is an important and interesting topic, so I'd like to try to partially answer your first question as well as to share some relevant resources for further studying.
Generally, terms model-based and design-based refer to approaches to performing statistical inference from data. Since inference implies making conclusions about a population, based on the analysis of a sample, assumptions about an underlying statistical model is what essentially differentiates model-based approach and design-based approach. Despite the presence of the word "model" in one approach and the absence of it in the other, make no mistake: both approaches are based on a notion of statistical model. The key difference is whether a statistical model considered an unknown construct or a known one. In particular, in a model-based approach can be defined as an approach, where statistical model is unknown (hence, the presence of the word "model", as it's the focus of discovery). Correspondingly, a design-based approach can be defines as one, where statistical model is known and the focus is on a study/experiment design.
Returning to the question's snippet, I would say that it essentially describes the same taxonomy, but in the context of the causality aspect. I'm not sure what paper is that snippet from, but I have been able to find a video of a talk, which has a slide with exactly the same snippet. The talk is a the University of Michigan's 2012 Woytinsky Lecture, which is called "Model-Based or Design-Based? Methodological Approaches in Empirical Micro" and presented by Prof. David Card (UC, Berkley). The part, where Dr. Card provides his explanation of the difference between model-based and design-based approaches in context of causality is located between minutes seven and ten in the above-referenced video of the talk. I have found his explanation clear enough. Let me warn you, that after that slot, if you decide to watch further, the talk contains a questionable statement - which I personally completely and respectfully disagree with - about the equality between data mining and machine learning. But, this is off-topic for the current question, anyway. It might also be useful to watch the rest of the talk - in particular, between minutes ten and fourteen, Dr. Card introduces a "middle ground" approach to causality, which resembles the hybrid approach, mentioned below.
In addition that, there are several resources, which I think are relevant to the topic and might be helpful. For example, the paper "Inference, design-based vs. model-based" by Koch and Gillings (2004) as well as related, but a bit less clear (hence, not fully cited) papers: this, this, this and this.
Finally, I would like to share probably the best resource of all that I have referenced so far - a very comprehensive and nicely-written research paper on the topic by Sonya Sterba (2010). In addition to an excellent overview of model-based and design-based approaches (frameworks), the author introduces an alternative hybrid model/design-based inferential framework.
References
Koch, G. G., & Gillings, D. B. (2004). Inference, design-based vs. model-based. In Encyclopedia of Statistical Sciences. Wiley. doi:10.1002/0471667196.ess1235.pub2
Sterba, S. K. (2009). Alternative model-based and design-based frameworks for inference from samples to populations: From polarization to integration. Multivariate Behavioral Research, 44(6), 711–740. doi:10.1080/00273170903333574 | Difference between "Design based approach" and "Model based approach"? | A comprehensive overview and comparison between model-based and design-based approaches in impossible to fit into an answer on Cross Validated (not to mention that I'm not qualified enough to even att | Difference between "Design based approach" and "Model based approach"?
A comprehensive overview and comparison between model-based and design-based approaches in impossible to fit into an answer on Cross Validated (not to mention that I'm not qualified enough to even attempt that). Having said that, it is an important and interesting topic, so I'd like to try to partially answer your first question as well as to share some relevant resources for further studying.
Generally, terms model-based and design-based refer to approaches to performing statistical inference from data. Since inference implies making conclusions about a population, based on the analysis of a sample, assumptions about an underlying statistical model is what essentially differentiates model-based approach and design-based approach. Despite the presence of the word "model" in one approach and the absence of it in the other, make no mistake: both approaches are based on a notion of statistical model. The key difference is whether a statistical model considered an unknown construct or a known one. In particular, in a model-based approach can be defined as an approach, where statistical model is unknown (hence, the presence of the word "model", as it's the focus of discovery). Correspondingly, a design-based approach can be defines as one, where statistical model is known and the focus is on a study/experiment design.
Returning to the question's snippet, I would say that it essentially describes the same taxonomy, but in the context of the causality aspect. I'm not sure what paper is that snippet from, but I have been able to find a video of a talk, which has a slide with exactly the same snippet. The talk is a the University of Michigan's 2012 Woytinsky Lecture, which is called "Model-Based or Design-Based? Methodological Approaches in Empirical Micro" and presented by Prof. David Card (UC, Berkley). The part, where Dr. Card provides his explanation of the difference between model-based and design-based approaches in context of causality is located between minutes seven and ten in the above-referenced video of the talk. I have found his explanation clear enough. Let me warn you, that after that slot, if you decide to watch further, the talk contains a questionable statement - which I personally completely and respectfully disagree with - about the equality between data mining and machine learning. But, this is off-topic for the current question, anyway. It might also be useful to watch the rest of the talk - in particular, between minutes ten and fourteen, Dr. Card introduces a "middle ground" approach to causality, which resembles the hybrid approach, mentioned below.
In addition that, there are several resources, which I think are relevant to the topic and might be helpful. For example, the paper "Inference, design-based vs. model-based" by Koch and Gillings (2004) as well as related, but a bit less clear (hence, not fully cited) papers: this, this, this and this.
Finally, I would like to share probably the best resource of all that I have referenced so far - a very comprehensive and nicely-written research paper on the topic by Sonya Sterba (2010). In addition to an excellent overview of model-based and design-based approaches (frameworks), the author introduces an alternative hybrid model/design-based inferential framework.
References
Koch, G. G., & Gillings, D. B. (2004). Inference, design-based vs. model-based. In Encyclopedia of Statistical Sciences. Wiley. doi:10.1002/0471667196.ess1235.pub2
Sterba, S. K. (2009). Alternative model-based and design-based frameworks for inference from samples to populations: From polarization to integration. Multivariate Behavioral Research, 44(6), 711–740. doi:10.1080/00273170903333574 | Difference between "Design based approach" and "Model based approach"?
A comprehensive overview and comparison between model-based and design-based approaches in impossible to fit into an answer on Cross Validated (not to mention that I'm not qualified enough to even att |
34,751 | How to project a new vector onto the PC space using kernel PCA? | Let's consider the training dataset first. Principal components (sometimes called PC "scores") are the centered data projected onto the principal axes. In kPCA, eigenvectors of the kernel matrix directly give you principal components, but scaled to have unit sum-of-squares. To get the correct scaling, one needs to multiply them by the square roots of the respective eigenvalues, so $$\mathbf X_\mathrm{projected\:on\: axis \:\#i} = \sqrt{\lambda_i} \mathbf E_i,$$ where $\mathbf E_i$ and $\lambda_i$ are the $i$-th eigenvector and eigenvalue of the kernel matrix: $\mathbf K \mathbf E_i = \lambda_i \mathbf E_i$. You wrote it wrong in your question.
This is easy to see by considering standard, non-kernel, PCA. Let $\mathbf X$ be the $n\times p$ centered data matrix. PCA amounts to an SVD decomposition of the (centered) data matrix: $$\mathbf X = \mathbf U \mathbf S \mathbf V^\top,$$ where $\mathbf U \mathbf S$ are PCs (PC "scores") and $\mathbf V$ are principal axes. Usually PCA is introduced via eigen-decomposition of the covariance matrix: $\mathbf C = \mathbf X^\top\mathbf X/n$, which has $\mathbf V$ as eigenvectors. Alternatively, one can consider the so called Gram matrix $$\mathbf K = \mathbf X \mathbf X^\top = \mathbf U \mathbf S^2 \mathbf U^\top,$$ which has $\mathbf U$ as eigenvectors and $\mathbf S^2$ as eigenvalues. To get PCs $\mathbf{US}$ one needs to multiply eigenvectors $\mathbf U$ with the square roots of the eigenvalues.
The kernel matrix in kPCA is what I called Gram matrix above. So the bottomline is: multiply its eigenvectors with the square roots of its eigenvalues.
Turning now to your main question, you have a new (test) data point $\mathbf x$ (a row vector) that needs to be projected on the principal axes. When faced with a question about kPCA, always think about how you would do it in standard PCA. You need to compute $\mathbf x \mathbf V$. But say you don't know $\mathbf V$ (that's the case in kPCA). Well, you can compute $\mathbf k = \mathbf x \mathbf X^\top$, which is a (row) vector of kernels between the new data point and all the old ones. And now $$\mathbf x \mathbf V = \mathbf x \mathbf V \mathbf S \mathbf U^\top \mathbf U \mathbf S^{-1} = \mathbf x \mathbf X^\top \mathbf U \mathbf S^{-1} = \mathbf k \mathbf U \mathbf S^{-1}.$$ Rewriting this in your kPCA notation, $$\mathbf x_\mathrm{projected} = \mathbf k \mathbf E \boldsymbol \Lambda^{-1/2},$$ where $\boldsymbol \Lambda$ is the diagonal matrix with eigenvalues $\lambda_i$ on the diagonal. | How to project a new vector onto the PC space using kernel PCA? | Let's consider the training dataset first. Principal components (sometimes called PC "scores") are the centered data projected onto the principal axes. In kPCA, eigenvectors of the kernel matrix direc | How to project a new vector onto the PC space using kernel PCA?
Let's consider the training dataset first. Principal components (sometimes called PC "scores") are the centered data projected onto the principal axes. In kPCA, eigenvectors of the kernel matrix directly give you principal components, but scaled to have unit sum-of-squares. To get the correct scaling, one needs to multiply them by the square roots of the respective eigenvalues, so $$\mathbf X_\mathrm{projected\:on\: axis \:\#i} = \sqrt{\lambda_i} \mathbf E_i,$$ where $\mathbf E_i$ and $\lambda_i$ are the $i$-th eigenvector and eigenvalue of the kernel matrix: $\mathbf K \mathbf E_i = \lambda_i \mathbf E_i$. You wrote it wrong in your question.
This is easy to see by considering standard, non-kernel, PCA. Let $\mathbf X$ be the $n\times p$ centered data matrix. PCA amounts to an SVD decomposition of the (centered) data matrix: $$\mathbf X = \mathbf U \mathbf S \mathbf V^\top,$$ where $\mathbf U \mathbf S$ are PCs (PC "scores") and $\mathbf V$ are principal axes. Usually PCA is introduced via eigen-decomposition of the covariance matrix: $\mathbf C = \mathbf X^\top\mathbf X/n$, which has $\mathbf V$ as eigenvectors. Alternatively, one can consider the so called Gram matrix $$\mathbf K = \mathbf X \mathbf X^\top = \mathbf U \mathbf S^2 \mathbf U^\top,$$ which has $\mathbf U$ as eigenvectors and $\mathbf S^2$ as eigenvalues. To get PCs $\mathbf{US}$ one needs to multiply eigenvectors $\mathbf U$ with the square roots of the eigenvalues.
The kernel matrix in kPCA is what I called Gram matrix above. So the bottomline is: multiply its eigenvectors with the square roots of its eigenvalues.
Turning now to your main question, you have a new (test) data point $\mathbf x$ (a row vector) that needs to be projected on the principal axes. When faced with a question about kPCA, always think about how you would do it in standard PCA. You need to compute $\mathbf x \mathbf V$. But say you don't know $\mathbf V$ (that's the case in kPCA). Well, you can compute $\mathbf k = \mathbf x \mathbf X^\top$, which is a (row) vector of kernels between the new data point and all the old ones. And now $$\mathbf x \mathbf V = \mathbf x \mathbf V \mathbf S \mathbf U^\top \mathbf U \mathbf S^{-1} = \mathbf x \mathbf X^\top \mathbf U \mathbf S^{-1} = \mathbf k \mathbf U \mathbf S^{-1}.$$ Rewriting this in your kPCA notation, $$\mathbf x_\mathrm{projected} = \mathbf k \mathbf E \boldsymbol \Lambda^{-1/2},$$ where $\boldsymbol \Lambda$ is the diagonal matrix with eigenvalues $\lambda_i$ on the diagonal. | How to project a new vector onto the PC space using kernel PCA?
Let's consider the training dataset first. Principal components (sometimes called PC "scores") are the centered data projected onto the principal axes. In kPCA, eigenvectors of the kernel matrix direc |
34,752 | How many random effects to specify in lmer? | When you are specifying random effects in an lme4::lmer model, the random
factors go on the left of the pipe and the non-independence grouping variables
go on the right, so the fully specified model in your question would very
likely be:
lmer(rt ~ A*B*C + (A*B|subj))
I took some time to explore the difference between a random effect on the left
of the pipe to a random effect on the right side of the pipe but it made a
better post on it's own than as an answer to your particular question.
RPubs doc
Gist code
The most noticeable difference between the following two models...
lmer(rt ~ A + (1|subj/A))
lmer(rt ~ A + (A|subj))
...is that the latter estimates a random correlation parameter between random
intercepts and random slopes. If you remove that random correlation
parameter...
lmer(rt ~ A + (1|subj/A))
lmer(rt ~ A + (1|subj) + (0+A|subj))
...the two models return the exact same fixed effects (parameter estimates
and associated errors), though I would guess that similarity depends on
the particular design of the study. | How many random effects to specify in lmer? | When you are specifying random effects in an lme4::lmer model, the random
factors go on the left of the pipe and the non-independence grouping variables
go on the right, so the fully specified model i | How many random effects to specify in lmer?
When you are specifying random effects in an lme4::lmer model, the random
factors go on the left of the pipe and the non-independence grouping variables
go on the right, so the fully specified model in your question would very
likely be:
lmer(rt ~ A*B*C + (A*B|subj))
I took some time to explore the difference between a random effect on the left
of the pipe to a random effect on the right side of the pipe but it made a
better post on it's own than as an answer to your particular question.
RPubs doc
Gist code
The most noticeable difference between the following two models...
lmer(rt ~ A + (1|subj/A))
lmer(rt ~ A + (A|subj))
...is that the latter estimates a random correlation parameter between random
intercepts and random slopes. If you remove that random correlation
parameter...
lmer(rt ~ A + (1|subj/A))
lmer(rt ~ A + (1|subj) + (0+A|subj))
...the two models return the exact same fixed effects (parameter estimates
and associated errors), though I would guess that similarity depends on
the particular design of the study. | How many random effects to specify in lmer?
When you are specifying random effects in an lme4::lmer model, the random
factors go on the left of the pipe and the non-independence grouping variables
go on the right, so the fully specified model i |
34,753 | How many random effects to specify in lmer? | With respect to the question which model is the most appropriate, I am still learning this for myself, but I can recommend an excellent paper covering this topic:
Barr, DJ, Levy R., Scheepers C., Tily HJ. (2013) Random effects structure for confirmatory hypothesis testing: Keep it maximal, Journal of Memory and Language 68 (2013) 255–278
As the title implies, the bottomline is that you should always try to include the maximum random effects structure, because only that guarantees that you do not inflate Type I error (it is also an excellent tutorial on what random intercepts and slopes do in the regression model).
However, sometimes complex random effects structures can lead to problems with model convergence. That is why some researchers propose a little less radical approach, and suggest that you should keep the maximal random effects structure that is justified by data (i.e. you test whether the random effects improve the model fit by using anova() and strip it to significant random effects only). Florian Jaeger covers this issue in his excellent blog:
http://hlplab.wordpress.com/2009/05/14/random-effect-structure/
http://hlplab.wordpress.com/2011/06/25/more-on-random-slopes/ | How many random effects to specify in lmer? | With respect to the question which model is the most appropriate, I am still learning this for myself, but I can recommend an excellent paper covering this topic:
Barr, DJ, Levy R., Scheepers C., Til | How many random effects to specify in lmer?
With respect to the question which model is the most appropriate, I am still learning this for myself, but I can recommend an excellent paper covering this topic:
Barr, DJ, Levy R., Scheepers C., Tily HJ. (2013) Random effects structure for confirmatory hypothesis testing: Keep it maximal, Journal of Memory and Language 68 (2013) 255–278
As the title implies, the bottomline is that you should always try to include the maximum random effects structure, because only that guarantees that you do not inflate Type I error (it is also an excellent tutorial on what random intercepts and slopes do in the regression model).
However, sometimes complex random effects structures can lead to problems with model convergence. That is why some researchers propose a little less radical approach, and suggest that you should keep the maximal random effects structure that is justified by data (i.e. you test whether the random effects improve the model fit by using anova() and strip it to significant random effects only). Florian Jaeger covers this issue in his excellent blog:
http://hlplab.wordpress.com/2009/05/14/random-effect-structure/
http://hlplab.wordpress.com/2011/06/25/more-on-random-slopes/ | How many random effects to specify in lmer?
With respect to the question which model is the most appropriate, I am still learning this for myself, but I can recommend an excellent paper covering this topic:
Barr, DJ, Levy R., Scheepers C., Til |
34,754 | How can you print the decision tree of a RandomForestClassifier | Your RandomForest creates 100 tree, so you can not print these in one step. Try iterate over the trees in the forest and print them out one by one:
from sklearn import tree
i_tree = 0
for tree_in_forest in forest.estimators_:
with open('tree_' + str(i_tree) + '.dot', 'w') as my_file:
my_file = tree.export_graphviz(tree_in_forest, out_file = my_file)
i_tree = i_tree + 1
If you want to know the actual parameters of the trees like splitting attribute (feature), splitting value (threshold), node samples (n_node_samples) etc., you can use print getmembers(tree_in_forest.tree_) in the for cycle. To use one of these parameters, eg. threshold, use this: tree_in_forest.tree_.threshold It returns with a list. | How can you print the decision tree of a RandomForestClassifier | Your RandomForest creates 100 tree, so you can not print these in one step. Try iterate over the trees in the forest and print them out one by one:
from sklearn import tree
i_tree = 0
for tree_in_fore | How can you print the decision tree of a RandomForestClassifier
Your RandomForest creates 100 tree, so you can not print these in one step. Try iterate over the trees in the forest and print them out one by one:
from sklearn import tree
i_tree = 0
for tree_in_forest in forest.estimators_:
with open('tree_' + str(i_tree) + '.dot', 'w') as my_file:
my_file = tree.export_graphviz(tree_in_forest, out_file = my_file)
i_tree = i_tree + 1
If you want to know the actual parameters of the trees like splitting attribute (feature), splitting value (threshold), node samples (n_node_samples) etc., you can use print getmembers(tree_in_forest.tree_) in the for cycle. To use one of these parameters, eg. threshold, use this: tree_in_forest.tree_.threshold It returns with a list. | How can you print the decision tree of a RandomForestClassifier
Your RandomForest creates 100 tree, so you can not print these in one step. Try iterate over the trees in the forest and print them out one by one:
from sklearn import tree
i_tree = 0
for tree_in_fore |
34,755 | Counterexample against binomial assumptions | Breaking each one, singly:
(1) The number of trials, $n$, is fixed.
The experiment continues until $k$ successes are observed. Or until $m$ successes in a row. Or until the number of successes exceeds the number of failures by 2.
(2) There are two and only two outcomes, labelled as "success" and "failure". The probability of outcome "success" is the same across the n trials.
P(success) is drawn from a beta distribution with mean $p$. Or P(success) alternates between $p_\text{A}$ and $p_\text{B}$.
(3) The trials are independent. That is, the outcome of one trial doesn't affect that of the others.
P(Success|Success at previous trial) = $p_1$ and
P(Success|Failure at previous trial) = $p_2$
You suggested something like an urn model as a concrete example, and it's quite easy to construct several forms of urn model of this third case (if you use sampling with replacement) - or you could use dice if there's more than one die you could use. | Counterexample against binomial assumptions | Breaking each one, singly:
(1) The number of trials, $n$, is fixed.
The experiment continues until $k$ successes are observed. Or until $m$ successes in a row. Or until the number of successes excee | Counterexample against binomial assumptions
Breaking each one, singly:
(1) The number of trials, $n$, is fixed.
The experiment continues until $k$ successes are observed. Or until $m$ successes in a row. Or until the number of successes exceeds the number of failures by 2.
(2) There are two and only two outcomes, labelled as "success" and "failure". The probability of outcome "success" is the same across the n trials.
P(success) is drawn from a beta distribution with mean $p$. Or P(success) alternates between $p_\text{A}$ and $p_\text{B}$.
(3) The trials are independent. That is, the outcome of one trial doesn't affect that of the others.
P(Success|Success at previous trial) = $p_1$ and
P(Success|Failure at previous trial) = $p_2$
You suggested something like an urn model as a concrete example, and it's quite easy to construct several forms of urn model of this third case (if you use sampling with replacement) - or you could use dice if there's more than one die you could use. | Counterexample against binomial assumptions
Breaking each one, singly:
(1) The number of trials, $n$, is fixed.
The experiment continues until $k$ successes are observed. Or until $m$ successes in a row. Or until the number of successes excee |
34,756 | Counterexample against binomial assumptions | Taking your example of picking balls from an urn. Assume you have M balls in the urn, with some black and some red. You pick N balls (with N a fixed number) and count up the number B which are black. B is not binomially distributed, because the probability of getting a black ball at each pick depends on how many black balls you've already picked. | Counterexample against binomial assumptions | Taking your example of picking balls from an urn. Assume you have M balls in the urn, with some black and some red. You pick N balls (with N a fixed number) and count up the number B which are black. | Counterexample against binomial assumptions
Taking your example of picking balls from an urn. Assume you have M balls in the urn, with some black and some red. You pick N balls (with N a fixed number) and count up the number B which are black. B is not binomially distributed, because the probability of getting a black ball at each pick depends on how many black balls you've already picked. | Counterexample against binomial assumptions
Taking your example of picking balls from an urn. Assume you have M balls in the urn, with some black and some red. You pick N balls (with N a fixed number) and count up the number B which are black. |
34,757 | Counterexample against binomial assumptions | Correct me if I am wrong here.
a) A counterexample only violates Assumption (1) would be a negative binomial process, where the number of trial is the random variable; The situation where a variable from a geometric distribution also works.
b) A counterexample only violates Assumption (3) would be a hypergeometric process. I came up with idea based on @Hong_Ooi's comment. The assumption (2) holds in a hypergeometric process setting is not that obvious at first glance though.
For example, suppose we have 10 balls, 6 blacks and 4 reds, in the urn. Suppose we draw 3 balls (fixed trials, assumption (1) holds) without replacement from the urn, and we are interested in the probability of 2 black balls out of the 3. The reason why assumption (2) holds is as follows.
Pr(1st draw is a black) = 6/10
Pr(2nd draw is a black) = Pr(BB) + Pr(RB) = 6/10 * 5/9 + 4/10 * 6/9 = 54/90 = 6/10
Pr(3rd draw is a black) = Pr(BBB) + Pr(BRB) + Pr(RBB) + Pr(RRB) = 6/10 *5/9 *4/8 + 6/10 *4/9 *5/8 + 4/10 *6/9 *5/8 + 4/10 * 3/9 *6/8 = 6/10
The same goes for the probability of "red" ball. That said, assumption (2) holds. But obviously assumption (3)doesn't. For example, Pr(2nd draw is a black, given 1st is a black) is not equal to Pr(1st draw is a black). Thus the independence assumption violates. | Counterexample against binomial assumptions | Correct me if I am wrong here.
a) A counterexample only violates Assumption (1) would be a negative binomial process, where the number of trial is the random variable; The situation where a variable f | Counterexample against binomial assumptions
Correct me if I am wrong here.
a) A counterexample only violates Assumption (1) would be a negative binomial process, where the number of trial is the random variable; The situation where a variable from a geometric distribution also works.
b) A counterexample only violates Assumption (3) would be a hypergeometric process. I came up with idea based on @Hong_Ooi's comment. The assumption (2) holds in a hypergeometric process setting is not that obvious at first glance though.
For example, suppose we have 10 balls, 6 blacks and 4 reds, in the urn. Suppose we draw 3 balls (fixed trials, assumption (1) holds) without replacement from the urn, and we are interested in the probability of 2 black balls out of the 3. The reason why assumption (2) holds is as follows.
Pr(1st draw is a black) = 6/10
Pr(2nd draw is a black) = Pr(BB) + Pr(RB) = 6/10 * 5/9 + 4/10 * 6/9 = 54/90 = 6/10
Pr(3rd draw is a black) = Pr(BBB) + Pr(BRB) + Pr(RBB) + Pr(RRB) = 6/10 *5/9 *4/8 + 6/10 *4/9 *5/8 + 4/10 *6/9 *5/8 + 4/10 * 3/9 *6/8 = 6/10
The same goes for the probability of "red" ball. That said, assumption (2) holds. But obviously assumption (3)doesn't. For example, Pr(2nd draw is a black, given 1st is a black) is not equal to Pr(1st draw is a black). Thus the independence assumption violates. | Counterexample against binomial assumptions
Correct me if I am wrong here.
a) A counterexample only violates Assumption (1) would be a negative binomial process, where the number of trial is the random variable; The situation where a variable f |
34,758 | Counterexample against binomial assumptions | It is quite easy and many of the answers/comments are making this more complicated than it needs to be.
Suppose you are looking at someone taking freethrow shots. Assumption two is met because you can either miss or make the shot. But assumption three might or might not be met. If the person is shooting a bunch of shots at the same time, they will get tired, and so their success probability will decline as time goes on. But if we are taking a set of trials that occur on different days, then they are independent of one another.
Suppose we say that we will look at 10 shots, or 100 shots, or whatever. Then assumption one is met. But if we say we will look at however many shots occur in an hour, or a year, or whatever, then assumption one is violated because we don't have a fixed number of trials, so we can't use the binomial distribution to predict in advance our likelihood hitting at least a certain percentage of our shots. (If I generally have a 50% chance of making any individual shot, and I want to know how likely it is that I will hit at least 2/3 of my shots, I can't make that calculation without knowing how many shots I'll take-- if I only take 3 shots, I have a much better chance than if I'm taking 3000 shots). | Counterexample against binomial assumptions | It is quite easy and many of the answers/comments are making this more complicated than it needs to be.
Suppose you are looking at someone taking freethrow shots. Assumption two is met because you | Counterexample against binomial assumptions
It is quite easy and many of the answers/comments are making this more complicated than it needs to be.
Suppose you are looking at someone taking freethrow shots. Assumption two is met because you can either miss or make the shot. But assumption three might or might not be met. If the person is shooting a bunch of shots at the same time, they will get tired, and so their success probability will decline as time goes on. But if we are taking a set of trials that occur on different days, then they are independent of one another.
Suppose we say that we will look at 10 shots, or 100 shots, or whatever. Then assumption one is met. But if we say we will look at however many shots occur in an hour, or a year, or whatever, then assumption one is violated because we don't have a fixed number of trials, so we can't use the binomial distribution to predict in advance our likelihood hitting at least a certain percentage of our shots. (If I generally have a 50% chance of making any individual shot, and I want to know how likely it is that I will hit at least 2/3 of my shots, I can't make that calculation without knowing how many shots I'll take-- if I only take 3 shots, I have a much better chance than if I'm taking 3000 shots). | Counterexample against binomial assumptions
It is quite easy and many of the answers/comments are making this more complicated than it needs to be.
Suppose you are looking at someone taking freethrow shots. Assumption two is met because you |
34,759 | Counterexample against binomial assumptions | 1) From a healthcare perspective, consider a clinical trial. Let no. of deaths in a trial be assumed to be binomially distributed with p=prob of success/death and n=number of patients in that trial.
Above assumption will not hold if :
a) Chances of death in one patient is different from another patient, happens when health conditions of patients is very varied (identical trials assumption violated)
b) Disease is infectious, as death of a patient is effected by other patients' deaths. (independent trials assumption violated)
2) On a simpler note : Choosing Chinese cuisine for lunch isn't binomially distributed, because if you have it today, you won't have it tomorrow (independent trials assumption violated) | Counterexample against binomial assumptions | 1) From a healthcare perspective, consider a clinical trial. Let no. of deaths in a trial be assumed to be binomially distributed with p=prob of success/death and n=number of patients in that trial.
| Counterexample against binomial assumptions
1) From a healthcare perspective, consider a clinical trial. Let no. of deaths in a trial be assumed to be binomially distributed with p=prob of success/death and n=number of patients in that trial.
Above assumption will not hold if :
a) Chances of death in one patient is different from another patient, happens when health conditions of patients is very varied (identical trials assumption violated)
b) Disease is infectious, as death of a patient is effected by other patients' deaths. (independent trials assumption violated)
2) On a simpler note : Choosing Chinese cuisine for lunch isn't binomially distributed, because if you have it today, you won't have it tomorrow (independent trials assumption violated) | Counterexample against binomial assumptions
1) From a healthcare perspective, consider a clinical trial. Let no. of deaths in a trial be assumed to be binomially distributed with p=prob of success/death and n=number of patients in that trial.
|
34,760 | Analysis of hamster wheel rotational data | In a lab setting this is very often done to study circadian (i.e. ~24 hours long) rhythms.
If you can record the activity for long periods (say a few days) you can do some periodicity analysis.
The usual representation of this type of data is the actogram, which also allows you to see whether there are day to day differences.
In this example after day 8 the mouse was put in constant darkness and, as you can see, although the rhythm is always there, it shortens revealing what is usually called the "free-running rhythm".
Note that this picture is particularly clean. Sometimes you do have activity during the day!
From: Measuring Circadian and Acute Light Responses in Mice using Wheel Running Activity - LeGates and Altimus, JOVE 2011
This papers gives a nice introduction on how to analyse wheel-running data:
A guideline for analyzing circadian wheel-running behavior in rodents under different lighting conditions - Jud et al. Biol Proced Online. 2005
You can also do some frequency analysis, for instance using chi-square periodograms.
See: The chi square periodogram: its utility for analysis of circadian rhythms. - Sokolove and Bushell, J Theor Biol. 1978 (sorry, behind a pay wall, but see also the refs here)
One thing you may do is to see whether these rhythms change during the week. For instance, I assume you wake up later (and make less noise) during weekends.
Does that affect the end of wheel running activity?
Do the rhythms change between summer and winter?
Also, if you hook up a camera to the system you can do some motion tracking. Here is an example of "hamster tracking" using Python and OpenCV. | Analysis of hamster wheel rotational data | In a lab setting this is very often done to study circadian (i.e. ~24 hours long) rhythms.
If you can record the activity for long periods (say a few days) you can do some periodicity analysis.
The us | Analysis of hamster wheel rotational data
In a lab setting this is very often done to study circadian (i.e. ~24 hours long) rhythms.
If you can record the activity for long periods (say a few days) you can do some periodicity analysis.
The usual representation of this type of data is the actogram, which also allows you to see whether there are day to day differences.
In this example after day 8 the mouse was put in constant darkness and, as you can see, although the rhythm is always there, it shortens revealing what is usually called the "free-running rhythm".
Note that this picture is particularly clean. Sometimes you do have activity during the day!
From: Measuring Circadian and Acute Light Responses in Mice using Wheel Running Activity - LeGates and Altimus, JOVE 2011
This papers gives a nice introduction on how to analyse wheel-running data:
A guideline for analyzing circadian wheel-running behavior in rodents under different lighting conditions - Jud et al. Biol Proced Online. 2005
You can also do some frequency analysis, for instance using chi-square periodograms.
See: The chi square periodogram: its utility for analysis of circadian rhythms. - Sokolove and Bushell, J Theor Biol. 1978 (sorry, behind a pay wall, but see also the refs here)
One thing you may do is to see whether these rhythms change during the week. For instance, I assume you wake up later (and make less noise) during weekends.
Does that affect the end of wheel running activity?
Do the rhythms change between summer and winter?
Also, if you hook up a camera to the system you can do some motion tracking. Here is an example of "hamster tracking" using Python and OpenCV. | Analysis of hamster wheel rotational data
In a lab setting this is very often done to study circadian (i.e. ~24 hours long) rhythms.
If you can record the activity for long periods (say a few days) you can do some periodicity analysis.
The us |
34,761 | Analysis of hamster wheel rotational data | What questions would you ask about the data?
How long did the hamster spend on the wheel last night?
Was it longer or shorter than the night before that?
Is there any day per week that the hamster runs longer on the wheel? Eg does a hamster have a week day or weekend day %^)?
How long does the hamster stay on the wheel in a continuous stretch, on average?
Does different type of food affect the time the hamster spends on the wheel?
Do my activities change the hamster's wheel behaviour?
All of these would suggest different types of plots. Aggregate time on wheel by day, plot over days.
See http://journal.r-project.org/archive/2013-1/hofmann-unwin-cook.pdf for how to plot data in different ways to explore different things, answer different questions. One plot is almost never enough. | Analysis of hamster wheel rotational data | What questions would you ask about the data?
How long did the hamster spend on the wheel last night?
Was it longer or shorter than the night before that?
Is there any day per week that the hamster ru | Analysis of hamster wheel rotational data
What questions would you ask about the data?
How long did the hamster spend on the wheel last night?
Was it longer or shorter than the night before that?
Is there any day per week that the hamster runs longer on the wheel? Eg does a hamster have a week day or weekend day %^)?
How long does the hamster stay on the wheel in a continuous stretch, on average?
Does different type of food affect the time the hamster spends on the wheel?
Do my activities change the hamster's wheel behaviour?
All of these would suggest different types of plots. Aggregate time on wheel by day, plot over days.
See http://journal.r-project.org/archive/2013-1/hofmann-unwin-cook.pdf for how to plot data in different ways to explore different things, answer different questions. One plot is almost never enough. | Analysis of hamster wheel rotational data
What questions would you ask about the data?
How long did the hamster spend on the wheel last night?
Was it longer or shorter than the night before that?
Is there any day per week that the hamster ru |
34,762 | Intervention Analysis Coding in R TSA Package | This is pretty straight forward if you use a tsoutlier package in R. This was not possible in $R$ until Thanks to @javlacalle created tsoutlier package. See the question that I posted earlier.
With regards to incorporating regressors like intervention analysis that you posted, you could use outlier.effects in the tsoutlier package to create regressors in ARIMAX model. See below for an example. This is similar to what you have asked. You could change the $\delta$ values in the temproary change to obtain desired shape of the curve. In the example below, I have left it to be default value for $\delta$ to be 0.7. You can consult package manual for further detail. tsoutlier package is great because it works with auto.arima and automatically identifies outliers and lets you code this arimax model.
In the example below I have shown you how to incorporate Level shift and Temporary change (which is what you are looking for). The outlier package identifies a level shift at 12 and temproary change at 20 which I both created as regressors using outliers.effects function. Temporary change has a decay effect which is nicely captured in this example.
library(tsoutliers)
library(expsmooth)
library(fma)
## Identify Outliers
outlier.chicken <- tsoutliers::tso(chicken,types = c("AO","LS","TC"),maxit.iloop=10)
outlier.chicken
plot(outlier.chicken)
n <- length(chicken)
## Create Outliers Regressors for ARIMAX
## Two type of outliers Level Shift (LS) and Temprory Change (TC)
mo.ls <- outliers("LS", 12)
ls <- outliers.effects(mo.ls, n)
mo.tc <- outliers("TC", 20)
tc <- outliers.effects(mo.tc, n)
xreg.outliers <- cbind(ls,tc)
## Create Arimax using Outliers as regressor variables.
arima.model <- auto.arima(chicken,xreg=xreg.outliers)
arima.model
output from outlier detection
Series: chicken
ARIMA(0,1,0)
Coefficients:
LS12 TC20
37.1400 36.3763
s.e. 11.8641 10.9382
sigma^2 estimated as 140.8: log likelihood=-264.19
AIC=534.38 AICc=534.75 BIC=541.08
Outliers:
type ind time coefhat tstat
1 LS 12 1935 37.14 3.130
2 TC 20 1943 36.38 3.326
output from auto.arima incorporating outliers as xreg
series: chicken
ARIMA(0,1,0) with drift
Coefficients:
drift LS12 TC20
-2.7450 39.8850 36.3763
s.e. 1.3997 11.6267 10.6414
sigma^2 estimated as 133.2: log likelihood=-262.32
AIC=532.64 AICc=533.26 BIC=541.58
Hope this helps | Intervention Analysis Coding in R TSA Package | This is pretty straight forward if you use a tsoutlier package in R. This was not possible in $R$ until Thanks to @javlacalle created tsoutlier package. See the question that I posted earlier.
With re | Intervention Analysis Coding in R TSA Package
This is pretty straight forward if you use a tsoutlier package in R. This was not possible in $R$ until Thanks to @javlacalle created tsoutlier package. See the question that I posted earlier.
With regards to incorporating regressors like intervention analysis that you posted, you could use outlier.effects in the tsoutlier package to create regressors in ARIMAX model. See below for an example. This is similar to what you have asked. You could change the $\delta$ values in the temproary change to obtain desired shape of the curve. In the example below, I have left it to be default value for $\delta$ to be 0.7. You can consult package manual for further detail. tsoutlier package is great because it works with auto.arima and automatically identifies outliers and lets you code this arimax model.
In the example below I have shown you how to incorporate Level shift and Temporary change (which is what you are looking for). The outlier package identifies a level shift at 12 and temproary change at 20 which I both created as regressors using outliers.effects function. Temporary change has a decay effect which is nicely captured in this example.
library(tsoutliers)
library(expsmooth)
library(fma)
## Identify Outliers
outlier.chicken <- tsoutliers::tso(chicken,types = c("AO","LS","TC"),maxit.iloop=10)
outlier.chicken
plot(outlier.chicken)
n <- length(chicken)
## Create Outliers Regressors for ARIMAX
## Two type of outliers Level Shift (LS) and Temprory Change (TC)
mo.ls <- outliers("LS", 12)
ls <- outliers.effects(mo.ls, n)
mo.tc <- outliers("TC", 20)
tc <- outliers.effects(mo.tc, n)
xreg.outliers <- cbind(ls,tc)
## Create Arimax using Outliers as regressor variables.
arima.model <- auto.arima(chicken,xreg=xreg.outliers)
arima.model
output from outlier detection
Series: chicken
ARIMA(0,1,0)
Coefficients:
LS12 TC20
37.1400 36.3763
s.e. 11.8641 10.9382
sigma^2 estimated as 140.8: log likelihood=-264.19
AIC=534.38 AICc=534.75 BIC=541.08
Outliers:
type ind time coefhat tstat
1 LS 12 1935 37.14 3.130
2 TC 20 1943 36.38 3.326
output from auto.arima incorporating outliers as xreg
series: chicken
ARIMA(0,1,0) with drift
Coefficients:
drift LS12 TC20
-2.7450 39.8850 36.3763
s.e. 1.3997 11.6267 10.6414
sigma^2 estimated as 133.2: log likelihood=-262.32
AIC=532.64 AICc=533.26 BIC=541.58
Hope this helps | Intervention Analysis Coding in R TSA Package
This is pretty straight forward if you use a tsoutlier package in R. This was not possible in $R$ until Thanks to @javlacalle created tsoutlier package. See the question that I posted earlier.
With re |
34,763 | Intervention Analysis Coding in R TSA Package | @forecaster gave a great answer using a package that I will be checking out. This is the answer to my question using the arimax function. The trick is to see that (assuming the event occurs at T=200):
So, we can create the covariate as 0 for t < 200 and then 1,2,3....200 and use transfer=list(c(0,0))
We could also use this variable directly as a regressor via xreg. | Intervention Analysis Coding in R TSA Package | @forecaster gave a great answer using a package that I will be checking out. This is the answer to my question using the arimax function. The trick is to see that (assuming the event occurs at T=200): | Intervention Analysis Coding in R TSA Package
@forecaster gave a great answer using a package that I will be checking out. This is the answer to my question using the arimax function. The trick is to see that (assuming the event occurs at T=200):
So, we can create the covariate as 0 for t < 200 and then 1,2,3....200 and use transfer=list(c(0,0))
We could also use this variable directly as a regressor via xreg. | Intervention Analysis Coding in R TSA Package
@forecaster gave a great answer using a package that I will be checking out. This is the answer to my question using the arimax function. The trick is to see that (assuming the event occurs at T=200): |
34,764 | Intervention Analysis Coding in R TSA Package | use a fixed vector to fix delta = 1.
fixed=c(NA,NA,1,NA)
you need to figure out where the NA's should be
located in the vector.See the docs for arima. I first
estimate arimax() without the fixed vector to find the
correct positions. Then add the fixed vector to the command
and rerun. | Intervention Analysis Coding in R TSA Package | use a fixed vector to fix delta = 1.
fixed=c(NA,NA,1,NA)
you need to figure out where the NA's should be
located in the vector.See the docs for arima. I first
estimate arimax() without the fixed vecto | Intervention Analysis Coding in R TSA Package
use a fixed vector to fix delta = 1.
fixed=c(NA,NA,1,NA)
you need to figure out where the NA's should be
located in the vector.See the docs for arima. I first
estimate arimax() without the fixed vector to find the
correct positions. Then add the fixed vector to the command
and rerun. | Intervention Analysis Coding in R TSA Package
use a fixed vector to fix delta = 1.
fixed=c(NA,NA,1,NA)
you need to figure out where the NA's should be
located in the vector.See the docs for arima. I first
estimate arimax() without the fixed vecto |
34,765 | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | It is very unclear why you are dwelling on the CLT. What matters for your purpose is robustness and goodness of fit. For time-to-event data it is common to use a semiparametric survival model such as the Cox proportional odds model. You can also use the proportional odds ordinal logistic model, if there is no censoring. Such an ordinal model can handle the other outcome variables. Both proportional hazards and other ordinal models do not require you to select a transformation for $Y$, and they handle arbitrary clumping (e.g., at zero days).
Among other problems with "CLT thinking" is its false assumption that standard deviations are good measures of dispersion for asymmetrically distributed $Y$. | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | It is very unclear why you are dwelling on the CLT. What matters for your purpose is robustness and goodness of fit. For time-to-event data it is common to use a semiparametric survival model such a | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
It is very unclear why you are dwelling on the CLT. What matters for your purpose is robustness and goodness of fit. For time-to-event data it is common to use a semiparametric survival model such as the Cox proportional odds model. You can also use the proportional odds ordinal logistic model, if there is no censoring. Such an ordinal model can handle the other outcome variables. Both proportional hazards and other ordinal models do not require you to select a transformation for $Y$, and they handle arbitrary clumping (e.g., at zero days).
Among other problems with "CLT thinking" is its false assumption that standard deviations are good measures of dispersion for asymmetrically distributed $Y$. | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
It is very unclear why you are dwelling on the CLT. What matters for your purpose is robustness and goodness of fit. For time-to-event data it is common to use a semiparametric survival model such a |
34,766 | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | Not only do you have to worry about normality, you have to worry about equality of variance; with count data (and right skew continuous distributions for that matter), variance tends to be related to mean in some way. This variance issue won't be fixed by the central limit theorem.
I think you're correct in your thought that perhaps you should use something like Poisson regression for your count variable. There are some alternatives, but Poisson regression would be the first thing I'd consider. However, from the look of some of your plots, it's possible you'll need something heavier tailed, like a negative binomial.
I'd initially be considering some form of GLM for all your response variables. This will also make it easier to deal with the curvature (via use of appropriate link functions).
You mention censoring in your comment below; you're right not to ignore the censoring - Cox proportional hazards (which you mentioned) is a standard thing to try but there are other options available. | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | Not only do you have to worry about normality, you have to worry about equality of variance; with count data (and right skew continuous distributions for that matter), variance tends to be related to | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
Not only do you have to worry about normality, you have to worry about equality of variance; with count data (and right skew continuous distributions for that matter), variance tends to be related to mean in some way. This variance issue won't be fixed by the central limit theorem.
I think you're correct in your thought that perhaps you should use something like Poisson regression for your count variable. There are some alternatives, but Poisson regression would be the first thing I'd consider. However, from the look of some of your plots, it's possible you'll need something heavier tailed, like a negative binomial.
I'd initially be considering some form of GLM for all your response variables. This will also make it easier to deal with the curvature (via use of appropriate link functions).
You mention censoring in your comment below; you're right not to ignore the censoring - Cox proportional hazards (which you mentioned) is a standard thing to try but there are other options available. | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
Not only do you have to worry about normality, you have to worry about equality of variance; with count data (and right skew continuous distributions for that matter), variance tends to be related to |
34,767 | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | OP, I may be misreading you: if I am, please let me know and I'll delete this answer.
It seems to me that you are fundamentally confused about what the CLT means. Nobody else has pointed this out, so perhaps I am wrong -- again, if so, please chime in.
Your post includes the following:
OR - and this brings me to the question in my title - because of the
size of the dataset, which is fairly large, could one say that the
central limit theorem holds true and I don't have to worry about the
data-distribution? Clearly my plots tell me I do, no?!?
If I log-transform my data, things start to look quite ok (Figure
3)
What exactly do you mean when you say "the central limit theorem holds true"? If I am reading you correctly, you believe that, given a large enough sample size, all distributions become normal -- and that is false.
To give a concrete example: if $X_i$ are i.i.d. Uniform on $[0, 1]$, then $\frac{1}{n}\sum_{i=1}^nX_i$ will be asymptotically normally distributed as $n\rightarrow\infty$. But that does not mean that, given a large sample size, you should expect a histogram of the $X_i$s to look like a normal distribution. | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | OP, I may be misreading you: if I am, please let me know and I'll delete this answer.
It seems to me that you are fundamentally confused about what the CLT means. Nobody else has pointed this out, so | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
OP, I may be misreading you: if I am, please let me know and I'll delete this answer.
It seems to me that you are fundamentally confused about what the CLT means. Nobody else has pointed this out, so perhaps I am wrong -- again, if so, please chime in.
Your post includes the following:
OR - and this brings me to the question in my title - because of the
size of the dataset, which is fairly large, could one say that the
central limit theorem holds true and I don't have to worry about the
data-distribution? Clearly my plots tell me I do, no?!?
If I log-transform my data, things start to look quite ok (Figure
3)
What exactly do you mean when you say "the central limit theorem holds true"? If I am reading you correctly, you believe that, given a large enough sample size, all distributions become normal -- and that is false.
To give a concrete example: if $X_i$ are i.i.d. Uniform on $[0, 1]$, then $\frac{1}{n}\sum_{i=1}^nX_i$ will be asymptotically normally distributed as $n\rightarrow\infty$. But that does not mean that, given a large sample size, you should expect a histogram of the $X_i$s to look like a normal distribution. | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
OP, I may be misreading you: if I am, please let me know and I'll delete this answer.
It seems to me that you are fundamentally confused about what the CLT means. Nobody else has pointed this out, so |
34,768 | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | The central limit theorem is an asymptotic result, which means that it has to hold as $n \rightarrow \infty$ (under certain regularity conditions), large enough is too vague a term.
In your case the distribution has a very heavy right tail (judging from the variance computed in figure 2). Thus, the occasional large value can make up a big chunk of the sum.
To make ideas clearer suppose 100 numbers sampled from the true distribution yielded 98 zeros and 2 numbers with value 300. Your estimate of the mean will be 6 which is far more affected by the occasional large numbers (300). | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | The central limit theorem is an asymptotic result, which means that it has to hold as $n \rightarrow \infty$ (under certain regularity conditions), large enough is too vague a term.
In your case the | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
The central limit theorem is an asymptotic result, which means that it has to hold as $n \rightarrow \infty$ (under certain regularity conditions), large enough is too vague a term.
In your case the distribution has a very heavy right tail (judging from the variance computed in figure 2). Thus, the occasional large value can make up a big chunk of the sum.
To make ideas clearer suppose 100 numbers sampled from the true distribution yielded 98 zeros and 2 numbers with value 300. Your estimate of the mean will be 6 which is far more affected by the occasional large numbers (300). | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
The central limit theorem is an asymptotic result, which means that it has to hold as $n \rightarrow \infty$ (under certain regularity conditions), large enough is too vague a term.
In your case the |
34,769 | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | The distributions of $X$ and $Y$ are not important
The distribution of $X$ and $Y$ don't matter to linear regression. Recall the usual assumptions of the ordinary least squares. Nowhere it says anything about the shape of the dependent and independent variable.
To believe it, run this regression in R:
x<-rexp(1000)
y<-5*x+rnorm(1000)
summary(lm(y~x))
Both $X$ and $Y$ are exponentially distributed, regression still finds the right parameter.
The normality of the errors is overrated
You showed us that the residuals are not normal. Okay, what does that actually tell you? Very little.
It doesn't mean the estimates are wrong, try this in R:
x<-rexp(1000)
y<-5*x+rexp(1000)
summary(lm(y~x))
And see, even with exponential errors, the regression is still on the mark.
The fact is: normality of the errors only matters to the estimation of confidence intervals and p values.
What if you really need confidence intervals or p-values and the residuals aren't normal? Use bootstrap.
A real problem is outliers (see those residuals at 15 in your plot?), those do bias results and you might have to remove them, or use some robust regression or both.
Your real problem is model selection
What I see is that you have many models you can feed this data to. You are asking us to pick one. We can't answer that for you. You have to do this on your own. Luckily it's pretty easy to do.
Run all the models you can think of. All the regressions, with all the transformations of the data and all the permutations of regressors. Then choose the one that predicts better.
Learn cross-validation. Which is easy and does precisely that. Choose the model with the lowest cross-validated error | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | The distributions of $X$ and $Y$ are not important
The distribution of $X$ and $Y$ don't matter to linear regression. Recall the usual assumptions of the ordinary least squares. Nowhere it says anythi | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
The distributions of $X$ and $Y$ are not important
The distribution of $X$ and $Y$ don't matter to linear regression. Recall the usual assumptions of the ordinary least squares. Nowhere it says anything about the shape of the dependent and independent variable.
To believe it, run this regression in R:
x<-rexp(1000)
y<-5*x+rnorm(1000)
summary(lm(y~x))
Both $X$ and $Y$ are exponentially distributed, regression still finds the right parameter.
The normality of the errors is overrated
You showed us that the residuals are not normal. Okay, what does that actually tell you? Very little.
It doesn't mean the estimates are wrong, try this in R:
x<-rexp(1000)
y<-5*x+rexp(1000)
summary(lm(y~x))
And see, even with exponential errors, the regression is still on the mark.
The fact is: normality of the errors only matters to the estimation of confidence intervals and p values.
What if you really need confidence intervals or p-values and the residuals aren't normal? Use bootstrap.
A real problem is outliers (see those residuals at 15 in your plot?), those do bias results and you might have to remove them, or use some robust regression or both.
Your real problem is model selection
What I see is that you have many models you can feed this data to. You are asking us to pick one. We can't answer that for you. You have to do this on your own. Luckily it's pretty easy to do.
Run all the models you can think of. All the regressions, with all the transformations of the data and all the permutations of regressors. Then choose the one that predicts better.
Learn cross-validation. Which is easy and does precisely that. Choose the model with the lowest cross-validated error | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
The distributions of $X$ and $Y$ are not important
The distribution of $X$ and $Y$ don't matter to linear regression. Recall the usual assumptions of the ordinary least squares. Nowhere it says anythi |
34,770 | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | Некоторые вдохновения: 1) Если мы не так много нулей, ZIP & ZINB может быть рациональный выбор; 2) мне кажется, приятно и проще inpretability будет для барьер модель: logit для reg шансов - "0 или >0" и какой-то граф-регрессии для >0 (Пуассона, Q-Poiss., negBin., гамма, logNorm и др.). Опять же, последняя похожа на " выбор модели' проблема (choosinng виде stohastic спецификации части). http://cran.r-project.org/web/packages/pscl/vignettes/countreg.pdf
Удачи! | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT? | Некоторые вдохновения: 1) Если мы не так много нулей, ZIP & ZINB может быть рациональный выбор; 2) мне кажется, приятно и проще inpretability будет для барьер модель: logit для reg шансов - "0 или >0" | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
Некоторые вдохновения: 1) Если мы не так много нулей, ZIP & ZINB может быть рациональный выбор; 2) мне кажется, приятно и проще inpretability будет для барьер модель: logit для reg шансов - "0 или >0" и какой-то граф-регрессии для >0 (Пуассона, Q-Poiss., negBin., гамма, logNorm и др.). Опять же, последняя похожа на " выбор модели' проблема (choosinng виде stohastic спецификации части). http://cran.r-project.org/web/packages/pscl/vignettes/countreg.pdf
Удачи! | Dealing with non-normal distribution in "big" datasets, when do we throw out the CLT?
Некоторые вдохновения: 1) Если мы не так много нулей, ZIP & ZINB может быть рациональный выбор; 2) мне кажется, приятно и проще inpretability будет для барьер модель: logit для reg шансов - "0 или >0" |
34,771 | Reporting regression statistics after logarithmic transformation | In a log-linear model of an outcome $\ln y$ with a continuous untransformed explanatory variable $x$ and a dummy explanatory variable $d$:
$100 \cdot \beta_x$ is the percentage change in $y$ for a small change in $x$ (up or down)
If d switches from 0 to 1, the percent change in $y$ is $100 \cdot [\exp(\beta_d) - 1]$.
If d switches from 1 to 0, the percent change in $y$ is $100 \cdot [\exp(-\beta_d)-1]$
Personally, I find this semi-elasticity interpretation much easier to follow than a multiplicative effect on the geometric baseline mean (exponentiated intercept) for the dummy variable, and the ratio of $\frac{\mathbf E[y \vert x+1]}{\mathbf E[y \vert x]}=\exp \beta_x$. If $y$ was a ratio, maybe this would make more sense.
For the graphs, you can plot two lines of re-transformed $y$ against x, one with $d=1$ and one with $d=0$:
\begin{equation}E[y \vert x]=\exp (\alpha +\beta_x \cdot x +\beta_d \cdot d) \cdot E[\exp (u)].\end{equation}
The second part of this expression is the hard part. If we assume normality and independence, we can approximate the second term with $\exp (\frac{\hat \sigma^2}{2}),$ where we use the RMSE from the logged regression for the unobserved $\sigma$. Or we can use a weaker assumption of $iid$ on $u_i$, and use the sample average of the exponentiated residuals from the logged model for the second term. That's the Duan "smearing" approach. It might make sense to take two averages: one for the $d=1$ observations and one for $d=0$ if you have reasons to believe there's heteroskedacity across the two groups.
Finally, all this re-transformation nonsense can also be avoided by using a GLM model.
Here's an example using Stata:
. sysuse auto, clear
(1978 Automobile Data)
. gen lnp=ln(price)
. reg lnp i.foreign mpg
Source | SS df MS Number of obs = 74
-------------+------------------------------ F( 2, 71) = 17.80
Model | 3.74819416 2 1.87409708 Prob > F = 0.0000
Residual | 7.47533892 71 .105286464 R-squared = 0.3340
-------------+------------------------------ Adj R-squared = 0.3152
Total | 11.2235331 73 .153747029 Root MSE = .32448
------------------------------------------------------------------------------
lnp | Coef. Std. Err. t P>|t| [95% Conf. Interval]
-------------+----------------------------------------------------------------
foreign |
Foreign | .2824445 .0897634 3.15 0.002 .1034612 .4614277
mpg | -.0421151 .0071399 -5.90 0.000 -.0563517 -.0278785
_cons | 9.4536 .1485422 63.64 0.000 9.157415 9.749785
------------------------------------------------------------------------------
The foreign price premium is 32% and significant:
. nlcom 100*(exp(_b[1.foreign])-1)
_nl_1: 100*(exp(_b[1.foreign])-1)
------------------------------------------------------------------------------
lnp | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
_nl_1 | 32.63681 11.90594 2.74 0.006 9.301603 55.97202
------------------------------------------------------------------------------
Here are the exponentiated coefficients:
. reg, eform(b)
Source | SS df MS Number of obs = 74
-------------+------------------------------ F( 2, 71) = 17.80
Model | 3.74819416 2 1.87409708 Prob > F = 0.0000
Residual | 7.47533892 71 .105286464 R-squared = 0.3340
-------------+------------------------------ Adj R-squared = 0.3152
Total | 11.2235331 73 .153747029 Root MSE = .32448
------------------------------------------------------------------------------
lnp | b Std. Err. t P>|t| [95% Conf. Interval]
-------------+----------------------------------------------------------------
foreign |
Foreign | 1.326368 .1190594 3.15 0.002 1.109003 1.586337
mpg | .9587594 .0068455 -5.90 0.000 .9452067 .9725066
_cons | 12754 1894.507 63.64 0.000 9484.509 17150.53
------------------------------------------------------------------------------
The foreign premium is just about identical. The geometric mean price for domestic cars seems pretty high to me, but that is because we are conditioning on mileage (these are the Caddies and Lincolns and Mercuries). Now we implement the Duan's re-transformations approach by hand:
. predict double uhat, residual
. predict double lnyhat, xb
. gen double expuhat = exp(uhat)
. sum expuhat, meanonly
. gen double yhat = r(mean)*exp(lnyhat)
You can also use Chris Baum's levpredict:
. /* Make Sure I Did Things Right */
. levpredict yhat2, duan
. compare yhat yhat2
---------- difference ----------
count minimum average maximum
------------------------------------------------------------------------
yhat=yhat2 74
----------
jointly defined 74 0 0 0
----------
total 74
Now for the graph code:
. tw ///
> (line yhat mpg if foreign ==1, sort lcolor(green)) ///
> (line yhat mpg if foreign ==0, sort lcolor(orange)) ///
> (scatter price mpg if foreign==1, mcolor(green) msymbol(Oh) jitter(2)) ///
> (scatter price mpg if foreign==0, mcolor(orange) msymbol(Oh) jitter(2)) ///
> ,legend(label(1 "E[Price|Foreign]") label(2 "E[Price|Domestic]") label(3 "Foreign") label(4 "Domestic") rows(1)) ///
> ytitle("Dollars") title("Duan Smearing In Action") ///
> ylab(, angle(horizontal) format(%9.0fc)) plotregion(fcolor(white) lcolor(white)) graphregion(fcolor(white) lcolor(white)) ///
>
Looks reasonable: | Reporting regression statistics after logarithmic transformation | In a log-linear model of an outcome $\ln y$ with a continuous untransformed explanatory variable $x$ and a dummy explanatory variable $d$:
$100 \cdot \beta_x$ is the percentage change in $y$ for a sm | Reporting regression statistics after logarithmic transformation
In a log-linear model of an outcome $\ln y$ with a continuous untransformed explanatory variable $x$ and a dummy explanatory variable $d$:
$100 \cdot \beta_x$ is the percentage change in $y$ for a small change in $x$ (up or down)
If d switches from 0 to 1, the percent change in $y$ is $100 \cdot [\exp(\beta_d) - 1]$.
If d switches from 1 to 0, the percent change in $y$ is $100 \cdot [\exp(-\beta_d)-1]$
Personally, I find this semi-elasticity interpretation much easier to follow than a multiplicative effect on the geometric baseline mean (exponentiated intercept) for the dummy variable, and the ratio of $\frac{\mathbf E[y \vert x+1]}{\mathbf E[y \vert x]}=\exp \beta_x$. If $y$ was a ratio, maybe this would make more sense.
For the graphs, you can plot two lines of re-transformed $y$ against x, one with $d=1$ and one with $d=0$:
\begin{equation}E[y \vert x]=\exp (\alpha +\beta_x \cdot x +\beta_d \cdot d) \cdot E[\exp (u)].\end{equation}
The second part of this expression is the hard part. If we assume normality and independence, we can approximate the second term with $\exp (\frac{\hat \sigma^2}{2}),$ where we use the RMSE from the logged regression for the unobserved $\sigma$. Or we can use a weaker assumption of $iid$ on $u_i$, and use the sample average of the exponentiated residuals from the logged model for the second term. That's the Duan "smearing" approach. It might make sense to take two averages: one for the $d=1$ observations and one for $d=0$ if you have reasons to believe there's heteroskedacity across the two groups.
Finally, all this re-transformation nonsense can also be avoided by using a GLM model.
Here's an example using Stata:
. sysuse auto, clear
(1978 Automobile Data)
. gen lnp=ln(price)
. reg lnp i.foreign mpg
Source | SS df MS Number of obs = 74
-------------+------------------------------ F( 2, 71) = 17.80
Model | 3.74819416 2 1.87409708 Prob > F = 0.0000
Residual | 7.47533892 71 .105286464 R-squared = 0.3340
-------------+------------------------------ Adj R-squared = 0.3152
Total | 11.2235331 73 .153747029 Root MSE = .32448
------------------------------------------------------------------------------
lnp | Coef. Std. Err. t P>|t| [95% Conf. Interval]
-------------+----------------------------------------------------------------
foreign |
Foreign | .2824445 .0897634 3.15 0.002 .1034612 .4614277
mpg | -.0421151 .0071399 -5.90 0.000 -.0563517 -.0278785
_cons | 9.4536 .1485422 63.64 0.000 9.157415 9.749785
------------------------------------------------------------------------------
The foreign price premium is 32% and significant:
. nlcom 100*(exp(_b[1.foreign])-1)
_nl_1: 100*(exp(_b[1.foreign])-1)
------------------------------------------------------------------------------
lnp | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
_nl_1 | 32.63681 11.90594 2.74 0.006 9.301603 55.97202
------------------------------------------------------------------------------
Here are the exponentiated coefficients:
. reg, eform(b)
Source | SS df MS Number of obs = 74
-------------+------------------------------ F( 2, 71) = 17.80
Model | 3.74819416 2 1.87409708 Prob > F = 0.0000
Residual | 7.47533892 71 .105286464 R-squared = 0.3340
-------------+------------------------------ Adj R-squared = 0.3152
Total | 11.2235331 73 .153747029 Root MSE = .32448
------------------------------------------------------------------------------
lnp | b Std. Err. t P>|t| [95% Conf. Interval]
-------------+----------------------------------------------------------------
foreign |
Foreign | 1.326368 .1190594 3.15 0.002 1.109003 1.586337
mpg | .9587594 .0068455 -5.90 0.000 .9452067 .9725066
_cons | 12754 1894.507 63.64 0.000 9484.509 17150.53
------------------------------------------------------------------------------
The foreign premium is just about identical. The geometric mean price for domestic cars seems pretty high to me, but that is because we are conditioning on mileage (these are the Caddies and Lincolns and Mercuries). Now we implement the Duan's re-transformations approach by hand:
. predict double uhat, residual
. predict double lnyhat, xb
. gen double expuhat = exp(uhat)
. sum expuhat, meanonly
. gen double yhat = r(mean)*exp(lnyhat)
You can also use Chris Baum's levpredict:
. /* Make Sure I Did Things Right */
. levpredict yhat2, duan
. compare yhat yhat2
---------- difference ----------
count minimum average maximum
------------------------------------------------------------------------
yhat=yhat2 74
----------
jointly defined 74 0 0 0
----------
total 74
Now for the graph code:
. tw ///
> (line yhat mpg if foreign ==1, sort lcolor(green)) ///
> (line yhat mpg if foreign ==0, sort lcolor(orange)) ///
> (scatter price mpg if foreign==1, mcolor(green) msymbol(Oh) jitter(2)) ///
> (scatter price mpg if foreign==0, mcolor(orange) msymbol(Oh) jitter(2)) ///
> ,legend(label(1 "E[Price|Foreign]") label(2 "E[Price|Domestic]") label(3 "Foreign") label(4 "Domestic") rows(1)) ///
> ytitle("Dollars") title("Duan Smearing In Action") ///
> ylab(, angle(horizontal) format(%9.0fc)) plotregion(fcolor(white) lcolor(white)) graphregion(fcolor(white) lcolor(white)) ///
>
Looks reasonable: | Reporting regression statistics after logarithmic transformation
In a log-linear model of an outcome $\ln y$ with a continuous untransformed explanatory variable $x$ and a dummy explanatory variable $d$:
$100 \cdot \beta_x$ is the percentage change in $y$ for a sm |
34,772 | Reporting regression statistics after logarithmic transformation | Use transformed variables on plots, and show the coefficients of transformed variables. For instance, if you use $y'=\log y$, then show everything for $y'$ not $y$.
If you would like to inverse the transform, then be very careful. For instance, $y'\sim\mathcal{N}(0,1)$ will have $E[y']=0$ but $E[y]=E[e^{y'}]=\sqrt{e}$. It was easy in the case of a $\log$ transform, but can become tricky with other function, so it's better to avoid it unless you're specifically asked. | Reporting regression statistics after logarithmic transformation | Use transformed variables on plots, and show the coefficients of transformed variables. For instance, if you use $y'=\log y$, then show everything for $y'$ not $y$.
If you would like to inverse the t | Reporting regression statistics after logarithmic transformation
Use transformed variables on plots, and show the coefficients of transformed variables. For instance, if you use $y'=\log y$, then show everything for $y'$ not $y$.
If you would like to inverse the transform, then be very careful. For instance, $y'\sim\mathcal{N}(0,1)$ will have $E[y']=0$ but $E[y]=E[e^{y'}]=\sqrt{e}$. It was easy in the case of a $\log$ transform, but can become tricky with other function, so it's better to avoid it unless you're specifically asked. | Reporting regression statistics after logarithmic transformation
Use transformed variables on plots, and show the coefficients of transformed variables. For instance, if you use $y'=\log y$, then show everything for $y'$ not $y$.
If you would like to inverse the t |
34,773 | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of the proposal distribution? | If your proposal has very a low variance, then your proposed new state will be very similar to the current state, so $\frac{\pi(x_2)}{\pi(x_1)}$ will be close to 1 (in the limit, with 0 variance, the proposal and current state will be same and you'll have it exactly equal to 1), so acceptance rate will be close to 100%.
If your proposal has high variance, however, $\frac{\pi(x_2)}{\pi(x_1)}$ will (at least sometimes) be way smaller than 1, so your acceptance rate will get closer and closer to 0%. So the acceptance rate decreases as the variance of the proposal increases.
The problem with very low variances (which will get you higher acceptance rate) is that they take longer to explore the posterior space by never moving far away from the current state. Adaptive MCMC methods like Haario et Al. try to handle such problem by changing the variance matrix of the proposal on the fly.
To tune your acceptance rate you could just try increase and decrease the variance, a somewhat trial and error approach. But depending on the geometry of the posterior, the acceptance rate might change drastically during the sampling process. Also, for multiparameter models the proposal covariance matrix has many variance and covariance terms and such method gets impractical.
There is more sofiscated methods to handle this like the adaptative metropolis method outlined in the link above, or you might want to take a look at other methods like those listed here. You may also try software like Jags and Stan if Metropolis doesn't work for your problem. | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of t | If your proposal has very a low variance, then your proposed new state will be very similar to the current state, so $\frac{\pi(x_2)}{\pi(x_1)}$ will be close to 1 (in the limit, with 0 variance, the | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of the proposal distribution?
If your proposal has very a low variance, then your proposed new state will be very similar to the current state, so $\frac{\pi(x_2)}{\pi(x_1)}$ will be close to 1 (in the limit, with 0 variance, the proposal and current state will be same and you'll have it exactly equal to 1), so acceptance rate will be close to 100%.
If your proposal has high variance, however, $\frac{\pi(x_2)}{\pi(x_1)}$ will (at least sometimes) be way smaller than 1, so your acceptance rate will get closer and closer to 0%. So the acceptance rate decreases as the variance of the proposal increases.
The problem with very low variances (which will get you higher acceptance rate) is that they take longer to explore the posterior space by never moving far away from the current state. Adaptive MCMC methods like Haario et Al. try to handle such problem by changing the variance matrix of the proposal on the fly.
To tune your acceptance rate you could just try increase and decrease the variance, a somewhat trial and error approach. But depending on the geometry of the posterior, the acceptance rate might change drastically during the sampling process. Also, for multiparameter models the proposal covariance matrix has many variance and covariance terms and such method gets impractical.
There is more sofiscated methods to handle this like the adaptative metropolis method outlined in the link above, or you might want to take a look at other methods like those listed here. You may also try software like Jags and Stan if Metropolis doesn't work for your problem. | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of t
If your proposal has very a low variance, then your proposed new state will be very similar to the current state, so $\frac{\pi(x_2)}{\pi(x_1)}$ will be close to 1 (in the limit, with 0 variance, the |
34,774 | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of the proposal distribution? | I think noting some definitions may be beneficial for future reference to this question and answer.
Ratio of number of accepted proposed states to the number of propositions gives the acceptance rate. Note that acceptance rate is the rate of acceptance over the course of the random walk.
$\alpha$ in the question is called "acceptance probability" by Robert & Casella in their book Introduction to Monte Carlo Methods with R (2010, p. 171). This is very reasonable since $\alpha$, in their presentation, adapted to the notation in the question, is seen here:
$$
x_2=
\begin{cases}
x_2 & \quad \text{with probability } \alpha(x_2,x_1) \\
x_1 & \quad \text{with probability } 1 - \alpha(x_2,x_1)\\
\end{cases}
\\
\\ \text{where }\ \alpha(x_2,x_1) = \min\left\{1, \frac{\pi(x_2)p(x_1 | x_2)}{\pi(x_1)p(x_2 | x_1)}\right\}
$$
Now note that $\alpha$ here may becomes independent of the proposal density in case of a random walk proposal when $p(x|y)=p(y|x)$. However, the acceptance rate as defined above is still dependent on it due to the reasons explained by random_user.
Robert and Casella are very clear about differentiating the two and define the latter as "[...] the average of acceptance probability over the iterations."
I have little experience on the matter but it was enough for me to observe that what is referred to in question by "acceptance rate" is sometimes named "acceptance ratio" (see Wikipedia for instance), leading to similar confusions as in the question. | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of t | I think noting some definitions may be beneficial for future reference to this question and answer.
Ratio of number of accepted proposed states to the number of propositions gives the acceptance rate. | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of the proposal distribution?
I think noting some definitions may be beneficial for future reference to this question and answer.
Ratio of number of accepted proposed states to the number of propositions gives the acceptance rate. Note that acceptance rate is the rate of acceptance over the course of the random walk.
$\alpha$ in the question is called "acceptance probability" by Robert & Casella in their book Introduction to Monte Carlo Methods with R (2010, p. 171). This is very reasonable since $\alpha$, in their presentation, adapted to the notation in the question, is seen here:
$$
x_2=
\begin{cases}
x_2 & \quad \text{with probability } \alpha(x_2,x_1) \\
x_1 & \quad \text{with probability } 1 - \alpha(x_2,x_1)\\
\end{cases}
\\
\\ \text{where }\ \alpha(x_2,x_1) = \min\left\{1, \frac{\pi(x_2)p(x_1 | x_2)}{\pi(x_1)p(x_2 | x_1)}\right\}
$$
Now note that $\alpha$ here may becomes independent of the proposal density in case of a random walk proposal when $p(x|y)=p(y|x)$. However, the acceptance rate as defined above is still dependent on it due to the reasons explained by random_user.
Robert and Casella are very clear about differentiating the two and define the latter as "[...] the average of acceptance probability over the iterations."
I have little experience on the matter but it was enough for me to observe that what is referred to in question by "acceptance rate" is sometimes named "acceptance ratio" (see Wikipedia for instance), leading to similar confusions as in the question. | Can we change the acceptance rate in random walk Metropolis algorithm by changing the parameter of t
I think noting some definitions may be beneficial for future reference to this question and answer.
Ratio of number of accepted proposed states to the number of propositions gives the acceptance rate. |
34,775 | How to normalize Poisson distributed data before PCA | First off, be aware that the term "normalize" is ambiguous within statistical science. You apply it to scaling by (value $-$ mean) / standard deviation, which is commonly also described as standardization. But it is also often applied to transformations that produce versions of a variable that are more nearly normal (Gaussian) in distribution. Yet again, a further use is that of scaling to fit within a prescribed range, say $[0, 1]$.
Standardization itself does not affect how far a distribution is normal, as it is merely a linear transformation, and skewness and kurtosis (for example), and more generally all measures of distribution shape, remain as they were.
As for principal component analysis (PCA), prior standardization is common, indeed arguably essential, whenever the individual variables are measured using different units of measurement. Conversely, PCA without standardization can make sense so long as all variables are measured in the same units. The difference corresponds to basing PCA on the correlation matrix (prior standardization) and on the covariance matrix (no prior standardization). Without standardization, PCA results are inevitably dominated by the variables with highest variance; if that is desired (or at worst unproblematic), then you will not be troubled.
Other way round, all variables being standardized gives them all, broadly speaking, the same importance; and even that could be wrong, or not what you most want. For example, the variable with the least variance and that with the most will end up on the same scale and with equal weight. Only rarely does that match what a researcher most needs, although it can be hard to build in what is needed without subjectivity or circularity. In practice, PCA seems most successful when the input variables have a strong family resemblance and least successful when the researcher inputs a mishmash of quite different variables, as say different social, economic or demographic characteristics of countries or other political units. PCA is not a washing machine; the dirt is not removed, but just redistributed.
If skewness is very high, you have a choice. Often results will be clearer if PCA is applied to transformed variables. For example, the effects of outliers or extreme data points will often be muted when variables are transformed. Conversely, PCA as a transformation technique does not depend on, or assume, that any (let alone all) of the variables fed to it being normally distributed.
In abstraction, it is difficult to advise in detail, but it will often be sensible to apply PCA both to the original data when highly skewed and to transformed data, and then to report either or both results, depending on what is helpful scientifically or substantively.
PCA itself is indifferent to whether variables are transformed in the same way, or indeed to whether some variables are transformed and others are not. Whenever it makes sense, there is some appeal in transforming variables in the same way, but this is perhaps more a question of taste than of technique.
As a simple example, if several variables are all measures of size in some sense, then skewness is very likely. Transforming all variables by taking logarithms (so long as all values are positive) will then often be valuable as a precursor to PCA, but neither analysis should be thought of as "correct"; rather they give complementary views of the data.
Note 1: I rather doubt that you "have to" do PCA unless you are committed to some exercise as part of a course of study. It seems very likely that some kind of Poisson modelling would be closer to scientific goals and just as fruitful as PCA, but without detail on those goals that is a matter of speculation.
Note 2: In the case of positive integers, roots and logarithms both have merit as transformations. I note that you state that your data are Poisson distributed without showing any evidence. | How to normalize Poisson distributed data before PCA | First off, be aware that the term "normalize" is ambiguous within statistical science. You apply it to scaling by (value $-$ mean) / standard deviation, which is commonly also described as standardiza | How to normalize Poisson distributed data before PCA
First off, be aware that the term "normalize" is ambiguous within statistical science. You apply it to scaling by (value $-$ mean) / standard deviation, which is commonly also described as standardization. But it is also often applied to transformations that produce versions of a variable that are more nearly normal (Gaussian) in distribution. Yet again, a further use is that of scaling to fit within a prescribed range, say $[0, 1]$.
Standardization itself does not affect how far a distribution is normal, as it is merely a linear transformation, and skewness and kurtosis (for example), and more generally all measures of distribution shape, remain as they were.
As for principal component analysis (PCA), prior standardization is common, indeed arguably essential, whenever the individual variables are measured using different units of measurement. Conversely, PCA without standardization can make sense so long as all variables are measured in the same units. The difference corresponds to basing PCA on the correlation matrix (prior standardization) and on the covariance matrix (no prior standardization). Without standardization, PCA results are inevitably dominated by the variables with highest variance; if that is desired (or at worst unproblematic), then you will not be troubled.
Other way round, all variables being standardized gives them all, broadly speaking, the same importance; and even that could be wrong, or not what you most want. For example, the variable with the least variance and that with the most will end up on the same scale and with equal weight. Only rarely does that match what a researcher most needs, although it can be hard to build in what is needed without subjectivity or circularity. In practice, PCA seems most successful when the input variables have a strong family resemblance and least successful when the researcher inputs a mishmash of quite different variables, as say different social, economic or demographic characteristics of countries or other political units. PCA is not a washing machine; the dirt is not removed, but just redistributed.
If skewness is very high, you have a choice. Often results will be clearer if PCA is applied to transformed variables. For example, the effects of outliers or extreme data points will often be muted when variables are transformed. Conversely, PCA as a transformation technique does not depend on, or assume, that any (let alone all) of the variables fed to it being normally distributed.
In abstraction, it is difficult to advise in detail, but it will often be sensible to apply PCA both to the original data when highly skewed and to transformed data, and then to report either or both results, depending on what is helpful scientifically or substantively.
PCA itself is indifferent to whether variables are transformed in the same way, or indeed to whether some variables are transformed and others are not. Whenever it makes sense, there is some appeal in transforming variables in the same way, but this is perhaps more a question of taste than of technique.
As a simple example, if several variables are all measures of size in some sense, then skewness is very likely. Transforming all variables by taking logarithms (so long as all values are positive) will then often be valuable as a precursor to PCA, but neither analysis should be thought of as "correct"; rather they give complementary views of the data.
Note 1: I rather doubt that you "have to" do PCA unless you are committed to some exercise as part of a course of study. It seems very likely that some kind of Poisson modelling would be closer to scientific goals and just as fruitful as PCA, but without detail on those goals that is a matter of speculation.
Note 2: In the case of positive integers, roots and logarithms both have merit as transformations. I note that you state that your data are Poisson distributed without showing any evidence. | How to normalize Poisson distributed data before PCA
First off, be aware that the term "normalize" is ambiguous within statistical science. You apply it to scaling by (value $-$ mean) / standard deviation, which is commonly also described as standardiza |
34,776 | How to normalize Poisson distributed data before PCA | As Nick points out, there is some confusion as to whether you mean standardisation (making each variable zero mean and unit variance vectors) or a transformation to make each variable more normally distributed. As you mentioned skewed data, I will address that point.
The square root or log transformations may be applied to the counts to downweight the effects of extreme values, which may dominate the construction of the early axes if doing so would explain large amounts of variance.
For count data though, PCA is rarely competitive in terms of variance explained. Correspondence Analysis will tend to ordinate such data as well if not better than PCA, though it is working on relative compositions (counts) not absolute-valued compositions; in PCA, the following samples with observations on 3 variables
x <- c(1, 5, 1)
y <- c(5, 25, 5)
would be assumed markedly different, but under CA, as these have the same relative composition, would be considered exactly equal.
At this point you should be asking yourself what it is that you hope to achieve with the ordination/dimension reduction and let that lead to you an appropriate method. | How to normalize Poisson distributed data before PCA | As Nick points out, there is some confusion as to whether you mean standardisation (making each variable zero mean and unit variance vectors) or a transformation to make each variable more normally di | How to normalize Poisson distributed data before PCA
As Nick points out, there is some confusion as to whether you mean standardisation (making each variable zero mean and unit variance vectors) or a transformation to make each variable more normally distributed. As you mentioned skewed data, I will address that point.
The square root or log transformations may be applied to the counts to downweight the effects of extreme values, which may dominate the construction of the early axes if doing so would explain large amounts of variance.
For count data though, PCA is rarely competitive in terms of variance explained. Correspondence Analysis will tend to ordinate such data as well if not better than PCA, though it is working on relative compositions (counts) not absolute-valued compositions; in PCA, the following samples with observations on 3 variables
x <- c(1, 5, 1)
y <- c(5, 25, 5)
would be assumed markedly different, but under CA, as these have the same relative composition, would be considered exactly equal.
At this point you should be asking yourself what it is that you hope to achieve with the ordination/dimension reduction and let that lead to you an appropriate method. | How to normalize Poisson distributed data before PCA
As Nick points out, there is some confusion as to whether you mean standardisation (making each variable zero mean and unit variance vectors) or a transformation to make each variable more normally di |
34,777 | How to normalize Poisson distributed data before PCA | You can use Box-Cox transformation.
𝑓(𝑥)= (𝑥^𝜆−1)/𝜆 𝑖𝑓 𝜆≠0 & 𝑙𝑜𝑔(𝑥) 𝑖𝑓 𝜆=0
In R the MASS library includes boxcox function to find the optimal 𝜆 | How to normalize Poisson distributed data before PCA | You can use Box-Cox transformation.
𝑓(𝑥)= (𝑥^𝜆−1)/𝜆 𝑖𝑓 𝜆≠0 & 𝑙𝑜𝑔(𝑥) 𝑖𝑓 𝜆=0
In R the MASS library includes boxcox function to find the optimal 𝜆 | How to normalize Poisson distributed data before PCA
You can use Box-Cox transformation.
𝑓(𝑥)= (𝑥^𝜆−1)/𝜆 𝑖𝑓 𝜆≠0 & 𝑙𝑜𝑔(𝑥) 𝑖𝑓 𝜆=0
In R the MASS library includes boxcox function to find the optimal 𝜆 | How to normalize Poisson distributed data before PCA
You can use Box-Cox transformation.
𝑓(𝑥)= (𝑥^𝜆−1)/𝜆 𝑖𝑓 𝜆≠0 & 𝑙𝑜𝑔(𝑥) 𝑖𝑓 𝜆=0
In R the MASS library includes boxcox function to find the optimal 𝜆 |
34,778 | Proof that the log-likelihood is asymptotically quadratic | DISCUSSION: Local asymptotic quadraticity of the log-likelihood is proven under the same set of assumptions that prove the asymptotic normality of the ML estimator -it is not a prerequisite. The proof of MLE's asymptotic normality, given this set of assumptions, can be much more straightforward and short-and I provide it at the end. I combine two very different book sources, David Pollard's unpublished "Asymptopia" (ch. 2), and Hayashi's "Econometrics") (ch.7). I follow the notation of Hayashi. Moreover this is a "$n\rightarrow \infty$" kind of proof.
Assume a sample of size $n$ of i.i.d. observations coming from a distribution with density function $f_X(x;\theta_0)$ and use the following notation:
$$\ln f_X(x_i;\theta) = m(x_i;\theta),\;\; \frac {\partial m(x_i;\theta)}{\partial \theta}= s(x_i;\theta),\;\;\frac {\partial^2 m(x_i;\theta)}{\partial \theta\partial \theta}= H(x_i;\theta)$$
We have in turn, the log-likelihood, the score , and the Hessian, all related to observation $i$, not to the whole sample.
Notation should be understood as reflecting vector-matrices (for more than one unknown parameter).
Consider the average log-likelihood function (makes no difference in ML estimation, and strictly speaking, we should consider this likelihood in order for ML to be included in the M-estimators family)
$$\ell (\mathbf x;\theta) = \frac 1n \sum_{i=1}^nm(x_i;\theta)$$
Make the following assumptions that hold for a neighborhood of $\theta_0$, $\mathcal N(\theta_0)$:
[a] $\qquad m(x_i;\theta)$ is indeed twice differentiable, with second derivative continuous at $\theta_0$
[b] $\qquad$Its first derivative evaluated at $\theta_0$, $s(x_i;\theta_0)$ is square-integrable with respect to the probability measure involved (in other words, $E[s(x_i;\theta_0)s(x_i;\theta_0)']$ exists and is finite).
[c] $\qquad$ Its second derivative $H(x_i;\theta)$ is dominated by an integrable function in all $\mathcal N(\theta_0)$, (which means $E\left[\text {sup}_{\theta \in N(\theta_0)} ||H(x_i;\theta)||\right] <\infty$
[d] $\qquad$ $E[H(x_i;\theta)]$ is not a singular matrix (so its inverse exists)
[e] $\qquad$ $\theta_0$ is an interior point of the parameter space $\Theta$
[f] $\qquad$ There exists $\hat \theta: \hat \theta\xrightarrow{p}\theta_0$.
As Pollard remarks, the reason why we consider asymptotic normality of an estimator given that it is consistent, is that its asymptotic distribution would be of no use to us if the estimator was inconsistent.
LOCAL QUADRATICITY to go to ASYMPTOTIC NORMALITY.
We note that local quadraticity is proven for the sample average log-joint density, not for the sample log-likelihood -i.e. we are one step before viewing the sample log joint density as a likelihood function of $\theta$. But we will continue to call it "log-likelihood".
In the above framework, the proof for local quadraticity essentially consists of nothing more than proving that the remainder from a 2nd order Taylor expansion of $m(x_i;\theta)$ around $\theta_0$ goes to zero asymptotically.
1st Step: Local Quadraticity
Assumption $[a]$ permits us to take this 2nd-order Taylor expansion and assumptions $[b]$ and $[c]$ permit to consider its expected value:
$$E[m(x_i;\theta)] = E[m(x_i;\theta_0)]+(\theta-\theta_0)E[s(x_i;\theta_0)]+\frac12(\theta-\theta_0)^2E[H(x_i;\theta_0)] + (\theta-\theta_0)^2E[R_2(x_i;\theta-\theta_0)]$$
where we have used the Peano form of the remainder term. Note that expectations relate to the $X$'s, the ML estimator has not yet been introduced.
Now, from a prior step, when proving the existence of a consistent estimator, by the "Identification Condition" we know that $E[m(x_i;\theta)]$ is at a maximum when $\theta =\theta_0$. Then due to assumption $[e]$ ($\theta_0$ is an interior point), this implies that $E[s(x_i;\theta_0)]=0$. If $\theta_0$ was not interior, then the Taylor expansion would retain a possibly non-zero linear term in $\theta$, and we would not be able to guarantee quadraticity (and this is why when $\theta_0$ is at the boundary the asymtptotic properties change).
Then one goes to show that the remainder converges uniformly in probability to zero (too much to write it down here), and we are left with
$$\ell (\mathbf x;\theta) = \frac 1n \sum_{i=1}^nm(x_i;\theta) \xrightarrow{p}E[m(x_i;\theta)] \xrightarrow{p} E[m(x_i;\theta_0)]+\frac12(\theta-\theta_0)^2E[H(x_i;\theta_0)] +o_p[(\theta-\theta_0)^2] $$
which is what is called "being locally asymptotically quadratic".
2nd step: Asymptotic Normality of the ML estimator
Keeping in mind the above results, we now take the 2nd-order Taylor expansion of the sample log-likelihood around $\theta_0$, manipulating the linear term,
$$\ell (x_i;\theta) = \ell (x_i;\theta_0) + \frac{(\theta-\theta_0)}{\sqrt n}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)+\frac12(\theta-\theta_0)^2\frac 1n\sum_{i=1}^{n}H(x_i;\theta_0) + R_n(x_i;(\theta-\theta_0))$$
Here too the remainder is shown to converge uniformly in probability to zero. If then we consider the derivative of the above with respect to $\theta$, and we set it equal to zero, we will obtain
$$\frac 1{\sqrt n}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)+(\hat \theta-\theta_0)\frac 1n\sum_{i=1}^{n}H(x_i;\theta_0)=0$$
where $\hat \theta$ is a "consistent root", which exists by assumption $[f]$.
Assumption $[d]$ permits to manipulate around and write
$${\sqrt n}(\hat \theta-\theta_0) = \left(-\frac 1n\sum_{i=1}^{n}H(x_i;\theta_0)\right)^{-1}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)$$
Assumption $[e]$ invoked previously gives us $E[s(x_i;\theta_0)]=0$. Assumption $[b]$ gives us that $E[s(x_i;\theta_0)s(x_i;\theta_0)']$ exists and is finite. Then the Central Limit Theorem holds and we have
$$\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0) \rightarrow_d N\left(0, E[s(x_i;\theta_0)s(x_i;\theta_0)']\right)$$
Finally, assumption $[c]$ guarantees that the inverse term is finite so
$${\sqrt n}(\hat \theta-\theta_0)\rightarrow_d N\left(0, (E[H(x_i;\theta_0)])^{-1}E[s(x_i;\theta_0)s(x_i;\theta_0)'](E[H(x_i;\theta_0)]^{-1})'\right)$$
DIRECT PROOF OF ASYMPTOTIC NORMALITY
Under the same set of assumptions, using the Mean-Value Theorem, we take a mean-value expansion of $\frac {\partial \ell(x_i;\hat \theta)}{\partial \theta}$ at $\theta_0$ and we obtain
$$\frac {\partial \ell(x_i;\hat \theta)}{\partial \theta}=\frac 1n\sum_{i=1}^{n}s(x_i;\theta_0)+(\hat \theta-\theta_0)\frac 1n\sum_{i=1}^{n}H(x_i;\bar \theta)=0$$
where $\bar \theta$ is a mean value between $\hat \theta$ and $\theta_0$. The assumptions permit us to write
$${\sqrt n}(\hat \theta-\theta_0) = \left(-\frac 1n\sum_{i=1}^{n}H(x_i;\bar \theta)\right)^{-1}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)$$
$\bar \theta$ is sandwiched between $\hat \theta$ and $\theta_0$ and it is also consistent for $\theta$. This and the assumptions, lead us to the same final result as before. | Proof that the log-likelihood is asymptotically quadratic | DISCUSSION: Local asymptotic quadraticity of the log-likelihood is proven under the same set of assumptions that prove the asymptotic normality of the ML estimator -it is not a prerequisite. The proof | Proof that the log-likelihood is asymptotically quadratic
DISCUSSION: Local asymptotic quadraticity of the log-likelihood is proven under the same set of assumptions that prove the asymptotic normality of the ML estimator -it is not a prerequisite. The proof of MLE's asymptotic normality, given this set of assumptions, can be much more straightforward and short-and I provide it at the end. I combine two very different book sources, David Pollard's unpublished "Asymptopia" (ch. 2), and Hayashi's "Econometrics") (ch.7). I follow the notation of Hayashi. Moreover this is a "$n\rightarrow \infty$" kind of proof.
Assume a sample of size $n$ of i.i.d. observations coming from a distribution with density function $f_X(x;\theta_0)$ and use the following notation:
$$\ln f_X(x_i;\theta) = m(x_i;\theta),\;\; \frac {\partial m(x_i;\theta)}{\partial \theta}= s(x_i;\theta),\;\;\frac {\partial^2 m(x_i;\theta)}{\partial \theta\partial \theta}= H(x_i;\theta)$$
We have in turn, the log-likelihood, the score , and the Hessian, all related to observation $i$, not to the whole sample.
Notation should be understood as reflecting vector-matrices (for more than one unknown parameter).
Consider the average log-likelihood function (makes no difference in ML estimation, and strictly speaking, we should consider this likelihood in order for ML to be included in the M-estimators family)
$$\ell (\mathbf x;\theta) = \frac 1n \sum_{i=1}^nm(x_i;\theta)$$
Make the following assumptions that hold for a neighborhood of $\theta_0$, $\mathcal N(\theta_0)$:
[a] $\qquad m(x_i;\theta)$ is indeed twice differentiable, with second derivative continuous at $\theta_0$
[b] $\qquad$Its first derivative evaluated at $\theta_0$, $s(x_i;\theta_0)$ is square-integrable with respect to the probability measure involved (in other words, $E[s(x_i;\theta_0)s(x_i;\theta_0)']$ exists and is finite).
[c] $\qquad$ Its second derivative $H(x_i;\theta)$ is dominated by an integrable function in all $\mathcal N(\theta_0)$, (which means $E\left[\text {sup}_{\theta \in N(\theta_0)} ||H(x_i;\theta)||\right] <\infty$
[d] $\qquad$ $E[H(x_i;\theta)]$ is not a singular matrix (so its inverse exists)
[e] $\qquad$ $\theta_0$ is an interior point of the parameter space $\Theta$
[f] $\qquad$ There exists $\hat \theta: \hat \theta\xrightarrow{p}\theta_0$.
As Pollard remarks, the reason why we consider asymptotic normality of an estimator given that it is consistent, is that its asymptotic distribution would be of no use to us if the estimator was inconsistent.
LOCAL QUADRATICITY to go to ASYMPTOTIC NORMALITY.
We note that local quadraticity is proven for the sample average log-joint density, not for the sample log-likelihood -i.e. we are one step before viewing the sample log joint density as a likelihood function of $\theta$. But we will continue to call it "log-likelihood".
In the above framework, the proof for local quadraticity essentially consists of nothing more than proving that the remainder from a 2nd order Taylor expansion of $m(x_i;\theta)$ around $\theta_0$ goes to zero asymptotically.
1st Step: Local Quadraticity
Assumption $[a]$ permits us to take this 2nd-order Taylor expansion and assumptions $[b]$ and $[c]$ permit to consider its expected value:
$$E[m(x_i;\theta)] = E[m(x_i;\theta_0)]+(\theta-\theta_0)E[s(x_i;\theta_0)]+\frac12(\theta-\theta_0)^2E[H(x_i;\theta_0)] + (\theta-\theta_0)^2E[R_2(x_i;\theta-\theta_0)]$$
where we have used the Peano form of the remainder term. Note that expectations relate to the $X$'s, the ML estimator has not yet been introduced.
Now, from a prior step, when proving the existence of a consistent estimator, by the "Identification Condition" we know that $E[m(x_i;\theta)]$ is at a maximum when $\theta =\theta_0$. Then due to assumption $[e]$ ($\theta_0$ is an interior point), this implies that $E[s(x_i;\theta_0)]=0$. If $\theta_0$ was not interior, then the Taylor expansion would retain a possibly non-zero linear term in $\theta$, and we would not be able to guarantee quadraticity (and this is why when $\theta_0$ is at the boundary the asymtptotic properties change).
Then one goes to show that the remainder converges uniformly in probability to zero (too much to write it down here), and we are left with
$$\ell (\mathbf x;\theta) = \frac 1n \sum_{i=1}^nm(x_i;\theta) \xrightarrow{p}E[m(x_i;\theta)] \xrightarrow{p} E[m(x_i;\theta_0)]+\frac12(\theta-\theta_0)^2E[H(x_i;\theta_0)] +o_p[(\theta-\theta_0)^2] $$
which is what is called "being locally asymptotically quadratic".
2nd step: Asymptotic Normality of the ML estimator
Keeping in mind the above results, we now take the 2nd-order Taylor expansion of the sample log-likelihood around $\theta_0$, manipulating the linear term,
$$\ell (x_i;\theta) = \ell (x_i;\theta_0) + \frac{(\theta-\theta_0)}{\sqrt n}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)+\frac12(\theta-\theta_0)^2\frac 1n\sum_{i=1}^{n}H(x_i;\theta_0) + R_n(x_i;(\theta-\theta_0))$$
Here too the remainder is shown to converge uniformly in probability to zero. If then we consider the derivative of the above with respect to $\theta$, and we set it equal to zero, we will obtain
$$\frac 1{\sqrt n}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)+(\hat \theta-\theta_0)\frac 1n\sum_{i=1}^{n}H(x_i;\theta_0)=0$$
where $\hat \theta$ is a "consistent root", which exists by assumption $[f]$.
Assumption $[d]$ permits to manipulate around and write
$${\sqrt n}(\hat \theta-\theta_0) = \left(-\frac 1n\sum_{i=1}^{n}H(x_i;\theta_0)\right)^{-1}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)$$
Assumption $[e]$ invoked previously gives us $E[s(x_i;\theta_0)]=0$. Assumption $[b]$ gives us that $E[s(x_i;\theta_0)s(x_i;\theta_0)']$ exists and is finite. Then the Central Limit Theorem holds and we have
$$\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0) \rightarrow_d N\left(0, E[s(x_i;\theta_0)s(x_i;\theta_0)']\right)$$
Finally, assumption $[c]$ guarantees that the inverse term is finite so
$${\sqrt n}(\hat \theta-\theta_0)\rightarrow_d N\left(0, (E[H(x_i;\theta_0)])^{-1}E[s(x_i;\theta_0)s(x_i;\theta_0)'](E[H(x_i;\theta_0)]^{-1})'\right)$$
DIRECT PROOF OF ASYMPTOTIC NORMALITY
Under the same set of assumptions, using the Mean-Value Theorem, we take a mean-value expansion of $\frac {\partial \ell(x_i;\hat \theta)}{\partial \theta}$ at $\theta_0$ and we obtain
$$\frac {\partial \ell(x_i;\hat \theta)}{\partial \theta}=\frac 1n\sum_{i=1}^{n}s(x_i;\theta_0)+(\hat \theta-\theta_0)\frac 1n\sum_{i=1}^{n}H(x_i;\bar \theta)=0$$
where $\bar \theta$ is a mean value between $\hat \theta$ and $\theta_0$. The assumptions permit us to write
$${\sqrt n}(\hat \theta-\theta_0) = \left(-\frac 1n\sum_{i=1}^{n}H(x_i;\bar \theta)\right)^{-1}\cdot\frac 1{\sqrt n}\sum_{i=1}^{n}s(x_i;\theta_0)$$
$\bar \theta$ is sandwiched between $\hat \theta$ and $\theta_0$ and it is also consistent for $\theta$. This and the assumptions, lead us to the same final result as before. | Proof that the log-likelihood is asymptotically quadratic
DISCUSSION: Local asymptotic quadraticity of the log-likelihood is proven under the same set of assumptions that prove the asymptotic normality of the ML estimator -it is not a prerequisite. The proof |
34,779 | Measure for Separability | The most common measures of separability are based on how much the intra-class distributions overlap (probabilistic measures). There are a couple of these, Jeffries-Matusita distance, Bhattacharya distance and the transformed divergence. You can easily google up some descriptions. They are quite straightforward to implement.
There also some based on the behavior of nearest neighbors. The separability index, which basically looks at the proportion of neighbors that overlap. And the Hypothesis margin which looks at the distance from an object’s nearest neighbour of the same class (near-hit) and a nearest neighbour of the opposing class (near-miss). Then creates a measure by summing over this.
And then you also have things like class scatter matrices and collective entropy.
EDIT
Probabilistic separability measures in R
separability.measures <- function ( Vector.1 , Vector.2 ) {
# convert vectors to matrices in case they are not
Matrix.1 <- as.matrix (Vector.1)
Matrix.2 <- as.matrix (Vector.2)
# define means
mean.Matrix.1 <- mean ( Matrix.1 )
mean.Matrix.2 <- mean ( Matrix.2 )
# define difference of means
mean.difference <- mean.Matrix.1 - mean.Matrix.2
# define covariances for supplied matrices
cv.Matrix.1 <- cov ( Matrix.1 )
cv.Matrix.2 <- cov ( Matrix.2 )
# define the halfsum of cv's as "p"
p <- ( cv.Matrix.1 + cv.Matrix.2 ) / 2
# --%<------------------------------------------------------------------------
# calculate the Bhattacharryya index
bh.distance <- 0.125 *t ( mean.difference ) * p^ ( -1 ) * mean.difference +
0.5 * log (det ( p ) / sqrt (det ( cv.Matrix.1 ) * det ( cv.Matrix.2 )
)
)
# --%<------------------------------------------------------------------------
# calculate Jeffries-Matusita
# following formula is bound between 0 and 2.0
jm.distance <- 2 * ( 1 - exp ( -bh.distance ) )
# also found in the bibliography:
# jm.distance <- 1000 * sqrt ( 2 * ( 1 - exp ( -bh.distance ) ) )
# the latter formula is bound between 0 and 1414.0
# --%<------------------------------------------------------------------------
# calculate the divergence
# trace (is the sum of the diagonal elements) of a square matrix
trace.of.matrix <- function ( SquareMatrix ) {
sum ( diag ( SquareMatrix ) ) }
# term 1
divergence.term.1 <- 1/2 * trace.of.matrix (( cv.Matrix.1 - cv.Matrix.2 ) *
( cv.Matrix.2^ (-1) - cv.Matrix.1^ (-1) )
)
# term 2
divergence.term.2 <- 1/2 * trace.of.matrix (( cv.Matrix.1^ (-1) + cv.Matrix.2^ (-1) ) *
( mean.Matrix.1 - mean.Matrix.2 ) *
t ( mean.Matrix.1 - mean.Matrix.2 )
)
# divergence
divergence <- divergence.term.1 + divergence.term.2
# --%<------------------------------------------------------------------------
# and the transformed divergence
transformed.divergence <- 2 * ( 1 - exp ( - ( divergence / 8 ) ) )
indices <- data.frame(
jm=jm.distance,bh=bh.distance,div=divergence,tdiv=transformed.divergence)
return(indices)
}
And some silly reproducible examples:
##### EXAMPLE 1
# two samples
sample.1 <- c (1362, 1411, 1457, 1735, 1621, 1621, 1791, 1863, 1863, 1838)
sample.2 <- c (1362, 1411, 1457, 10030, 1621, 1621, 1791, 1863, 1863, 1838)
# separability between these two samples
separability.measures ( sample.1 , sample.2 )
##### EXAMPLE 2
# parameters for a normal distibution
meen <- 0.2
sdevn <- 2
x <- seq(-20,20,length=5000)
# two samples from two normal distibutions
normal1 <- dnorm(x,mean=0,sd=1) # standard normal
normal2 <- dnorm(x,mean=meen, sd=sdevn) # normal with the parameters selected above
# separability between these two normal distibutions
separability.measures ( normal1 , normal2 )
Note that these measures only work for two classes and 1 variable at a time, and sometimes have some assumptions (like the classes following a normal distibution) so you should read about them before using them thoroughly. But they still might suit your needs. | Measure for Separability | The most common measures of separability are based on how much the intra-class distributions overlap (probabilistic measures). There are a couple of these, Jeffries-Matusita distance, Bhattacharya dis | Measure for Separability
The most common measures of separability are based on how much the intra-class distributions overlap (probabilistic measures). There are a couple of these, Jeffries-Matusita distance, Bhattacharya distance and the transformed divergence. You can easily google up some descriptions. They are quite straightforward to implement.
There also some based on the behavior of nearest neighbors. The separability index, which basically looks at the proportion of neighbors that overlap. And the Hypothesis margin which looks at the distance from an object’s nearest neighbour of the same class (near-hit) and a nearest neighbour of the opposing class (near-miss). Then creates a measure by summing over this.
And then you also have things like class scatter matrices and collective entropy.
EDIT
Probabilistic separability measures in R
separability.measures <- function ( Vector.1 , Vector.2 ) {
# convert vectors to matrices in case they are not
Matrix.1 <- as.matrix (Vector.1)
Matrix.2 <- as.matrix (Vector.2)
# define means
mean.Matrix.1 <- mean ( Matrix.1 )
mean.Matrix.2 <- mean ( Matrix.2 )
# define difference of means
mean.difference <- mean.Matrix.1 - mean.Matrix.2
# define covariances for supplied matrices
cv.Matrix.1 <- cov ( Matrix.1 )
cv.Matrix.2 <- cov ( Matrix.2 )
# define the halfsum of cv's as "p"
p <- ( cv.Matrix.1 + cv.Matrix.2 ) / 2
# --%<------------------------------------------------------------------------
# calculate the Bhattacharryya index
bh.distance <- 0.125 *t ( mean.difference ) * p^ ( -1 ) * mean.difference +
0.5 * log (det ( p ) / sqrt (det ( cv.Matrix.1 ) * det ( cv.Matrix.2 )
)
)
# --%<------------------------------------------------------------------------
# calculate Jeffries-Matusita
# following formula is bound between 0 and 2.0
jm.distance <- 2 * ( 1 - exp ( -bh.distance ) )
# also found in the bibliography:
# jm.distance <- 1000 * sqrt ( 2 * ( 1 - exp ( -bh.distance ) ) )
# the latter formula is bound between 0 and 1414.0
# --%<------------------------------------------------------------------------
# calculate the divergence
# trace (is the sum of the diagonal elements) of a square matrix
trace.of.matrix <- function ( SquareMatrix ) {
sum ( diag ( SquareMatrix ) ) }
# term 1
divergence.term.1 <- 1/2 * trace.of.matrix (( cv.Matrix.1 - cv.Matrix.2 ) *
( cv.Matrix.2^ (-1) - cv.Matrix.1^ (-1) )
)
# term 2
divergence.term.2 <- 1/2 * trace.of.matrix (( cv.Matrix.1^ (-1) + cv.Matrix.2^ (-1) ) *
( mean.Matrix.1 - mean.Matrix.2 ) *
t ( mean.Matrix.1 - mean.Matrix.2 )
)
# divergence
divergence <- divergence.term.1 + divergence.term.2
# --%<------------------------------------------------------------------------
# and the transformed divergence
transformed.divergence <- 2 * ( 1 - exp ( - ( divergence / 8 ) ) )
indices <- data.frame(
jm=jm.distance,bh=bh.distance,div=divergence,tdiv=transformed.divergence)
return(indices)
}
And some silly reproducible examples:
##### EXAMPLE 1
# two samples
sample.1 <- c (1362, 1411, 1457, 1735, 1621, 1621, 1791, 1863, 1863, 1838)
sample.2 <- c (1362, 1411, 1457, 10030, 1621, 1621, 1791, 1863, 1863, 1838)
# separability between these two samples
separability.measures ( sample.1 , sample.2 )
##### EXAMPLE 2
# parameters for a normal distibution
meen <- 0.2
sdevn <- 2
x <- seq(-20,20,length=5000)
# two samples from two normal distibutions
normal1 <- dnorm(x,mean=0,sd=1) # standard normal
normal2 <- dnorm(x,mean=meen, sd=sdevn) # normal with the parameters selected above
# separability between these two normal distibutions
separability.measures ( normal1 , normal2 )
Note that these measures only work for two classes and 1 variable at a time, and sometimes have some assumptions (like the classes following a normal distibution) so you should read about them before using them thoroughly. But they still might suit your needs. | Measure for Separability
The most common measures of separability are based on how much the intra-class distributions overlap (probabilistic measures). There are a couple of these, Jeffries-Matusita distance, Bhattacharya dis |
34,780 | Retrieving minimum width that contains specified fraction of all values | Headlines:
A keyword is shorth.
For an R implementation and links to a current project with publications, see Günther Sawitzki's page at http://www.statlab.uni-heidelberg.de/people/gs/
There is a Stata implementation, which can be installed by ssc inst shorth.
More slowly, and without trying to do justice to Sawitzki's work:
The order statistics of a sample of $n$ values of $x$ are defined by
$x_{(1)} \le x_{(2)} \le \cdots \le x_{(n-1)} \le x_{(n)}.$
Let $h = \lfloor n / 2\rfloor$. Then the shortest half of the data from rank $k$ to rank $k + h$ is identified to minimise $x_{(k + h)} - x_{(k)}$ over $k = 1, \cdots, n - h$. This interval we call the length of the shortest half.
The shorth was named by J.W. Tukey and introduced in the Princeton robustness study of estimators of location by Andrews, Bickel, Hampel, Huber, Rogers and Tukey (1972, p.26) as the mean of $x_{(k)}, \cdots, x_{(k + h)}$. It attracted attention for its unusual asymptotic properties (pp.50-52): on those, see also the later accounts of Shorack and Wellner (1986, pp.767-771) and Kim and Pollard (1990). Otherwise it quickly dropped out of sight for about a decade. Incidentally, Hampel (1997) shows that results available to the Princeton study on asymmetric situations, but not fully analysed at the time, put the shorth in better light than was then appreciated.
Interest revived in such ideas when Rousseeuw (1984), building on a suggestion by
Hampel (1975), pointed out that the midpoint of the shortest half $(x_{(k)} + x_{(k + h)}) / 2$ is the least median of squares (LMS) estimator of location for $x$. See Rousseeuw (1984) and Rousseeuw and Leroy (1987) for applications of LMS and related ideas to regression and other problems. Note that this LMS midpoint is also called the shorth in some recent literature (e.g. David and Nagaraja 2003, p.223; Maronna, Martin and Yohai 2006, p.48). Further, the shortest half itself is also sometimes called the shorth, as the title of Grübel (1988) indicates.
The length of the shortest half is a robust measure of scale or spread: see Rousseeuw
and Leroy (1988), Grübel (1988), Rousseeuw and Croux (1993) and Martin and Zamar (1993)
for further analysis and discussion.
The length of the shortest half in a Gaussian (normal) with mean 0 and standard
deviation 1 is 1.349 to 3 d.p. Thus to estimate standard deviation from the observed length, divide by this Gaussian length.
Some broad-brush comments follow on advantages and disadvantages of shortest half
ideas, from the standpoint of practical data analysts as much as mathematical or
theoretical statisticians. Whatever the project, it will always be wise to compare
shorth results with standard summary measures (including other means, notably geometric
and harmonic means) and to relate results to graphs of distributions. Moreover, if your
interest is in the existence or extent of bimodality or multimodality, it will be best
to look directly at suitably smoothed estimates of the density function.
Simplicity The idea of the shortest half is simple and easy to explain to students
and researchers who do not regard themselves as statistical specialists. It leads
directly to two measures of location and one of spread that are fairly intuitive. It is
also relatively amenable to hand calculation with primitive tools (pencil and paper,
calculators, spreadsheets).
Connections The similarities and differences between the length of the shortest
half, the interquartile range and the median absolute deviation from the median (MAD)
(or for that matter the probable error) are immediate. Thus, shortest half ideas are
linked to other statistical ideas that should already be familiar to many data analysts.
Graphic interpretation The shortest half can easily be related to standard displays
of distributions such as cumulative distribution and quantile plots, histograms and
stem-and-leaf plots.
Mode By averaging where the data are densest, the shorth and also the LMS midpoint
introduce a mode flavour to summary of location. When applied to distributions that
are approximately symmetric, the shorth will be close to the mean and median, but more
resistant than the mean to outliers in either tail and more efficient than the median for
distributions near Gaussian (normal) in shape. When applied to distributions that are
unimodal and asymmetric, the shorth and the LMS will typically be nearer the mode than
either the mean or the median. Note that the idea of estimating the mode as the
midpoint of the shortest interval that contains a fixed number of observations goes
back at least to Dalenius (1965). See also Robertson and Cryer (1974), Bickel (2002)
and Bickel and Frühwirth (2006) on other estimators of the mode. The half-sample mode
estimator of Bickel and Frühwirth is especially interesting as a recursive selection of
the shortest half. Stata users can download a Stata implementation by ssc inst hsmode.
Outlier identification A resistant standardisation such as (value - shorth) /
length may help in identifying outliers. For discussions of related ideas, see Carey et
al. (1997) and included references.
Generalise to shortest fraction The idea can be generalised to proportions other
than one-half.
At the same time, note that
Not useful for all distributions When applied to distributions that are
approximately J-shaped, the shorth will approximate the mean of the lower half of the
data and the LMS midpoint will be rather higher. When applied to distributions that are
approximately U-shaped, the shorth and the LMS midpoint will be within whichever half
of the distribution happens to have higher average density. Neither behaviour seems
especially interesting or useful, but equally there is little call for single mode-like
summaries for J-shaped or U-shaped distributions; for J shapes, the mode is, or should
be, the minimum and for U shapes, bimodality makes the idea of a single mode moot, if
not invalid.
Ties The shortest half may not be uniquely defined. Even with measured data,
rounding of reported values may frequently give rise to ties. What to do with two or
more shortest halves has been little discussed in the literature. Note that tied halves
may either overlap or be disjoint. Different implementations may tackle this in slightly different ways.
Rationale for window length Why half is taken to mean $1 + \lfloor n / 2\rfloor$ also does not appear to be discussed. Evidently we need a rule that yields a window length for both odd and even $n$; it is preferable that the rule be simple; and there is usually some slight arbitrariness in choosing a rule of this kind. It is also important that any rule behave reasonably for small $n$: even if a program is not deliberately invoked for very small sample sizes the procedure used should make sense for all possible
sizes. Note that, with this rule, given $n = 1$ the shorth is just the single sample
value, and given $n = 2$ the shorth is the average of the two sample values. A further
detail about this rule is that it always defines a slight majority, thus enforcing
democratic decisions about the data. However, there seems no strong reason not to use $\lceil n / 2\rceil$ as an even simpler rule, except that all authors on the shorth appear to have followed $1 + \lfloor n / 2\rfloor$.
Use with weighted data Identification of the shortest half would seem to extend
only rather messily to situations in which observations are associated with unequal
weights.
Length when most values identical When at least half of the values in a sample are
equal to some constant, the length of the shortest half is 0. So, for example, if most
values are 0 and some are larger, the length of the shortest half is not particularly
useful as a measure of scale or spread.
Andrews, D.F., P.J. Bickel, F.R. Hampel, P.J. Huber, W.H. Rogers and J.W. Tukey. 1972. Robust estimates of location: survey and advances. Princeton, NJ: Princeton University Press.
Bickel, D.R. 2002. Robust estimators of the mode and skewness of continuous data. Computational Statistics & Data Analysis 39: 153-163.
Bickel, D.R. and R. Frühwirth. 2006. On a fast, robust estimator of the mode: comparisons to other estimators with applications. Computational Statistics & Data Analysis 50: 3500-3530.
Carey, V.J., E.E. Walters, C.G. Wager and B.A. Rosner. 1997. Resistant and test-based outlier rejection: effects on Gaussian one- and two-sample inference. Technometrics 39: 320-330.
Christmann, A., U. Gather and G. Scholz. 1994. Some properties of the length of the shortest half. Statistica Neerlandica 48: 209-213.
Dalenius, T. 1965. The mode - A neglected statistical parameter. Journal, Royal
Statistical Society A 128: 110-117.
Grübel, R. 1988. The length of the shorth. Annals of Statistics 16: 619-628.
Hampel, F.R. 1975. Beyond location parameters: robust concepts and methods. Bulletin, International Statistical Institute 46: 375-382.
Hampel, F.R. 1997. Some additional notes on the "Princeton robustness year". In Brillinger, D.R., L.T. Fernholz and S. Morgenthaler (eds) The practice of data analysis: essays in honor of John W. Tukey. Princeton, NJ: Princeton University Press, 133-153.
Kim, J. and D. Pollard. 1990. Cube root asymptotics. Annals of Statistics 18: 191-219.
Maronna, R.A., R.D. Martin and V.J. Yohai. 2006. Robust statistics: theory and methods. Chichester: John Wiley.
Martin, R.D. and R.H. Zamar. 1993. Bias robust estimation of scale. Annals of Statistics 21: 991-1017.
Robertson, T. and J.D. Cryer. 1974. An iterative procedure for estimating the mode.
Journal, American Statistical Association 69: 1012-1016.
Rousseeuw, P.J. 1984. Least median of squares regression. Journal, American Statistical Association 79: 871-880.
Rousseeuw, P.J. and C. Croux. 1993. Alternatives to the median absolute deviation. Journal, American Statistical Association 88: 1273-1283.
Rousseeuw, P.J. and A.M. Leroy. 1987. Robust regression and outlier detection. New York: John Wiley.
Rousseeuw, P.J. and A.M. Leroy. 1988. A robust scale estimator based on the shortest half. Statistica Neerlandica 42: 103-116.
Shorack, G.R. and J.A. Wellner. 1986. Empirical processes with applications to statistics. New York: John Wiley. | Retrieving minimum width that contains specified fraction of all values | Headlines:
A keyword is shorth.
For an R implementation and links to a current project with publications, see Günther Sawitzki's page at http://www.statlab.uni-heidelberg.de/people/gs/
There is a S | Retrieving minimum width that contains specified fraction of all values
Headlines:
A keyword is shorth.
For an R implementation and links to a current project with publications, see Günther Sawitzki's page at http://www.statlab.uni-heidelberg.de/people/gs/
There is a Stata implementation, which can be installed by ssc inst shorth.
More slowly, and without trying to do justice to Sawitzki's work:
The order statistics of a sample of $n$ values of $x$ are defined by
$x_{(1)} \le x_{(2)} \le \cdots \le x_{(n-1)} \le x_{(n)}.$
Let $h = \lfloor n / 2\rfloor$. Then the shortest half of the data from rank $k$ to rank $k + h$ is identified to minimise $x_{(k + h)} - x_{(k)}$ over $k = 1, \cdots, n - h$. This interval we call the length of the shortest half.
The shorth was named by J.W. Tukey and introduced in the Princeton robustness study of estimators of location by Andrews, Bickel, Hampel, Huber, Rogers and Tukey (1972, p.26) as the mean of $x_{(k)}, \cdots, x_{(k + h)}$. It attracted attention for its unusual asymptotic properties (pp.50-52): on those, see also the later accounts of Shorack and Wellner (1986, pp.767-771) and Kim and Pollard (1990). Otherwise it quickly dropped out of sight for about a decade. Incidentally, Hampel (1997) shows that results available to the Princeton study on asymmetric situations, but not fully analysed at the time, put the shorth in better light than was then appreciated.
Interest revived in such ideas when Rousseeuw (1984), building on a suggestion by
Hampel (1975), pointed out that the midpoint of the shortest half $(x_{(k)} + x_{(k + h)}) / 2$ is the least median of squares (LMS) estimator of location for $x$. See Rousseeuw (1984) and Rousseeuw and Leroy (1987) for applications of LMS and related ideas to regression and other problems. Note that this LMS midpoint is also called the shorth in some recent literature (e.g. David and Nagaraja 2003, p.223; Maronna, Martin and Yohai 2006, p.48). Further, the shortest half itself is also sometimes called the shorth, as the title of Grübel (1988) indicates.
The length of the shortest half is a robust measure of scale or spread: see Rousseeuw
and Leroy (1988), Grübel (1988), Rousseeuw and Croux (1993) and Martin and Zamar (1993)
for further analysis and discussion.
The length of the shortest half in a Gaussian (normal) with mean 0 and standard
deviation 1 is 1.349 to 3 d.p. Thus to estimate standard deviation from the observed length, divide by this Gaussian length.
Some broad-brush comments follow on advantages and disadvantages of shortest half
ideas, from the standpoint of practical data analysts as much as mathematical or
theoretical statisticians. Whatever the project, it will always be wise to compare
shorth results with standard summary measures (including other means, notably geometric
and harmonic means) and to relate results to graphs of distributions. Moreover, if your
interest is in the existence or extent of bimodality or multimodality, it will be best
to look directly at suitably smoothed estimates of the density function.
Simplicity The idea of the shortest half is simple and easy to explain to students
and researchers who do not regard themselves as statistical specialists. It leads
directly to two measures of location and one of spread that are fairly intuitive. It is
also relatively amenable to hand calculation with primitive tools (pencil and paper,
calculators, spreadsheets).
Connections The similarities and differences between the length of the shortest
half, the interquartile range and the median absolute deviation from the median (MAD)
(or for that matter the probable error) are immediate. Thus, shortest half ideas are
linked to other statistical ideas that should already be familiar to many data analysts.
Graphic interpretation The shortest half can easily be related to standard displays
of distributions such as cumulative distribution and quantile plots, histograms and
stem-and-leaf plots.
Mode By averaging where the data are densest, the shorth and also the LMS midpoint
introduce a mode flavour to summary of location. When applied to distributions that
are approximately symmetric, the shorth will be close to the mean and median, but more
resistant than the mean to outliers in either tail and more efficient than the median for
distributions near Gaussian (normal) in shape. When applied to distributions that are
unimodal and asymmetric, the shorth and the LMS will typically be nearer the mode than
either the mean or the median. Note that the idea of estimating the mode as the
midpoint of the shortest interval that contains a fixed number of observations goes
back at least to Dalenius (1965). See also Robertson and Cryer (1974), Bickel (2002)
and Bickel and Frühwirth (2006) on other estimators of the mode. The half-sample mode
estimator of Bickel and Frühwirth is especially interesting as a recursive selection of
the shortest half. Stata users can download a Stata implementation by ssc inst hsmode.
Outlier identification A resistant standardisation such as (value - shorth) /
length may help in identifying outliers. For discussions of related ideas, see Carey et
al. (1997) and included references.
Generalise to shortest fraction The idea can be generalised to proportions other
than one-half.
At the same time, note that
Not useful for all distributions When applied to distributions that are
approximately J-shaped, the shorth will approximate the mean of the lower half of the
data and the LMS midpoint will be rather higher. When applied to distributions that are
approximately U-shaped, the shorth and the LMS midpoint will be within whichever half
of the distribution happens to have higher average density. Neither behaviour seems
especially interesting or useful, but equally there is little call for single mode-like
summaries for J-shaped or U-shaped distributions; for J shapes, the mode is, or should
be, the minimum and for U shapes, bimodality makes the idea of a single mode moot, if
not invalid.
Ties The shortest half may not be uniquely defined. Even with measured data,
rounding of reported values may frequently give rise to ties. What to do with two or
more shortest halves has been little discussed in the literature. Note that tied halves
may either overlap or be disjoint. Different implementations may tackle this in slightly different ways.
Rationale for window length Why half is taken to mean $1 + \lfloor n / 2\rfloor$ also does not appear to be discussed. Evidently we need a rule that yields a window length for both odd and even $n$; it is preferable that the rule be simple; and there is usually some slight arbitrariness in choosing a rule of this kind. It is also important that any rule behave reasonably for small $n$: even if a program is not deliberately invoked for very small sample sizes the procedure used should make sense for all possible
sizes. Note that, with this rule, given $n = 1$ the shorth is just the single sample
value, and given $n = 2$ the shorth is the average of the two sample values. A further
detail about this rule is that it always defines a slight majority, thus enforcing
democratic decisions about the data. However, there seems no strong reason not to use $\lceil n / 2\rceil$ as an even simpler rule, except that all authors on the shorth appear to have followed $1 + \lfloor n / 2\rfloor$.
Use with weighted data Identification of the shortest half would seem to extend
only rather messily to situations in which observations are associated with unequal
weights.
Length when most values identical When at least half of the values in a sample are
equal to some constant, the length of the shortest half is 0. So, for example, if most
values are 0 and some are larger, the length of the shortest half is not particularly
useful as a measure of scale or spread.
Andrews, D.F., P.J. Bickel, F.R. Hampel, P.J. Huber, W.H. Rogers and J.W. Tukey. 1972. Robust estimates of location: survey and advances. Princeton, NJ: Princeton University Press.
Bickel, D.R. 2002. Robust estimators of the mode and skewness of continuous data. Computational Statistics & Data Analysis 39: 153-163.
Bickel, D.R. and R. Frühwirth. 2006. On a fast, robust estimator of the mode: comparisons to other estimators with applications. Computational Statistics & Data Analysis 50: 3500-3530.
Carey, V.J., E.E. Walters, C.G. Wager and B.A. Rosner. 1997. Resistant and test-based outlier rejection: effects on Gaussian one- and two-sample inference. Technometrics 39: 320-330.
Christmann, A., U. Gather and G. Scholz. 1994. Some properties of the length of the shortest half. Statistica Neerlandica 48: 209-213.
Dalenius, T. 1965. The mode - A neglected statistical parameter. Journal, Royal
Statistical Society A 128: 110-117.
Grübel, R. 1988. The length of the shorth. Annals of Statistics 16: 619-628.
Hampel, F.R. 1975. Beyond location parameters: robust concepts and methods. Bulletin, International Statistical Institute 46: 375-382.
Hampel, F.R. 1997. Some additional notes on the "Princeton robustness year". In Brillinger, D.R., L.T. Fernholz and S. Morgenthaler (eds) The practice of data analysis: essays in honor of John W. Tukey. Princeton, NJ: Princeton University Press, 133-153.
Kim, J. and D. Pollard. 1990. Cube root asymptotics. Annals of Statistics 18: 191-219.
Maronna, R.A., R.D. Martin and V.J. Yohai. 2006. Robust statistics: theory and methods. Chichester: John Wiley.
Martin, R.D. and R.H. Zamar. 1993. Bias robust estimation of scale. Annals of Statistics 21: 991-1017.
Robertson, T. and J.D. Cryer. 1974. An iterative procedure for estimating the mode.
Journal, American Statistical Association 69: 1012-1016.
Rousseeuw, P.J. 1984. Least median of squares regression. Journal, American Statistical Association 79: 871-880.
Rousseeuw, P.J. and C. Croux. 1993. Alternatives to the median absolute deviation. Journal, American Statistical Association 88: 1273-1283.
Rousseeuw, P.J. and A.M. Leroy. 1987. Robust regression and outlier detection. New York: John Wiley.
Rousseeuw, P.J. and A.M. Leroy. 1988. A robust scale estimator based on the shortest half. Statistica Neerlandica 42: 103-116.
Shorack, G.R. and J.A. Wellner. 1986. Empirical processes with applications to statistics. New York: John Wiley. | Retrieving minimum width that contains specified fraction of all values
Headlines:
A keyword is shorth.
For an R implementation and links to a current project with publications, see Günther Sawitzki's page at http://www.statlab.uni-heidelberg.de/people/gs/
There is a S |
34,781 | Case-control study and Logistic regression | Logistic regression is a valid inferential method, because, as you've noted you're modeling the odds. The coefficients on explanatory variables $X$ will also be valid. However, the intercept term $\beta_0$ will not be; this is because the number of positive and negative outcomes are fixed by the case-control design. So the intercept term will be meaningless, but your other estimates are fine. More information is in Agresti, An Introduction to Categorical Data Analysis (second edition; 2007), p. 105. | Case-control study and Logistic regression | Logistic regression is a valid inferential method, because, as you've noted you're modeling the odds. The coefficients on explanatory variables $X$ will also be valid. However, the intercept term $\be | Case-control study and Logistic regression
Logistic regression is a valid inferential method, because, as you've noted you're modeling the odds. The coefficients on explanatory variables $X$ will also be valid. However, the intercept term $\beta_0$ will not be; this is because the number of positive and negative outcomes are fixed by the case-control design. So the intercept term will be meaningless, but your other estimates are fine. More information is in Agresti, An Introduction to Categorical Data Analysis (second edition; 2007), p. 105. | Case-control study and Logistic regression
Logistic regression is a valid inferential method, because, as you've noted you're modeling the odds. The coefficients on explanatory variables $X$ will also be valid. However, the intercept term $\be |
34,782 | Function of random variables | Yes you can definitely have functions of random variables. And yes, in the case you present above
$$E[f(x)]=4$$ however, this is only because the expectation works as a linear operator. Had the function been more complex you could not apply what you did as easily. For sake of argument consider the random variable $X$ and the function of the random variable $f(X)=X^2$. If $E[X]=2$ then we cannot conclude that
$$E[f(x)]=E[X^2]=E[X]^2$$ as the logic from above would follow. Instead we would need to calculate new distribution of our new random variable $f(X)$ (yes a function of a random variable is a random variable itself). Now calculating the distribution of our new random variable is not always trivial though and there are more than one way to do. The straight forward brute force way is the following:
$$F(f(X))=\text{Pr}(f(X)\leq x)=\text{Pr}(X\leq f^{-1}(x))$$
and to continue on in that manner, however, this assumes that we have a function $f$ that is invertible. A convenient method for when the function of the random variable is a strictly monotone function over the support of $X$ we have the following: Let $Y=f(x)$
$$p_{Y}(y)=p_X(f^{-1}(y))\bigg|\frac{df^{-1}(y)}{dy}\bigg|$$
If you want to read more about this I would say google functions of random variables, transformations of random variables or look here: http://en.wikipedia.org/wiki/Random_variable
Also, any introductory textbook on probability theory will cover all of this in great detail. | Function of random variables | Yes you can definitely have functions of random variables. And yes, in the case you present above
$$E[f(x)]=4$$ however, this is only because the expectation works as a linear operator. Had the functi | Function of random variables
Yes you can definitely have functions of random variables. And yes, in the case you present above
$$E[f(x)]=4$$ however, this is only because the expectation works as a linear operator. Had the function been more complex you could not apply what you did as easily. For sake of argument consider the random variable $X$ and the function of the random variable $f(X)=X^2$. If $E[X]=2$ then we cannot conclude that
$$E[f(x)]=E[X^2]=E[X]^2$$ as the logic from above would follow. Instead we would need to calculate new distribution of our new random variable $f(X)$ (yes a function of a random variable is a random variable itself). Now calculating the distribution of our new random variable is not always trivial though and there are more than one way to do. The straight forward brute force way is the following:
$$F(f(X))=\text{Pr}(f(X)\leq x)=\text{Pr}(X\leq f^{-1}(x))$$
and to continue on in that manner, however, this assumes that we have a function $f$ that is invertible. A convenient method for when the function of the random variable is a strictly monotone function over the support of $X$ we have the following: Let $Y=f(x)$
$$p_{Y}(y)=p_X(f^{-1}(y))\bigg|\frac{df^{-1}(y)}{dy}\bigg|$$
If you want to read more about this I would say google functions of random variables, transformations of random variables or look here: http://en.wikipedia.org/wiki/Random_variable
Also, any introductory textbook on probability theory will cover all of this in great detail. | Function of random variables
Yes you can definitely have functions of random variables. And yes, in the case you present above
$$E[f(x)]=4$$ however, this is only because the expectation works as a linear operator. Had the functi |
34,783 | Function of random variables | BabakP's answer is a good one. Read it, but I'd like to add a few points.
The computation of the distribution of a transformation of a random variable (or of several variables) is often called statistical tolerancing. A problem is, for most such transformations, there is no simple distribution that works. Thus suppose X is a Gaussian random variable, then F(X), where F is a linear function, also has a Gaussian distribution, but with an adjusted mean and variance, based on the transformation L, and the mean and variance of X.
However, things get nasty almost always when F(X) is at all nonlinear. Ok, if F is the exponential function, then F(X) for normal X has a lognormal distribution. But most nonlinear functions will not give you some well known distribution. So what can you do?
One simple solution is to compute the mean and variance of the transformation. Given a mean and variance, one might choose to assume a normal distribution with that mean and variance. One might even do more, computing the first four moments of F(X). There are several families of distributions (Pearson & Johnson families) that allow you to find a distribution that matches the moments you have just found.
So, the question is, how might one compute those moments? The simple answer is if you knew the derivative of F, then approximating F by a truncated (first order) Taylor series around the mean of X can allow you to find approximations for those moments. Essentially, if F is well approximated by a linear function over the support of X, then those moments will be good estimates. (For a Gaussian distribution, the support might be considered to be something like +/-6 sigma.)
Others have used second order Taylor series approximations. Here too we can compute approximate moments of the transformation.
And finally, I might mention Taguchi methods, as well as modified Taguchi methods. They too allow you to find approximations of the moments. A nice thing about the modified Taguchi methods is they are based on Gaussian integrations, and allow you to use higher order approximations quite easily, without any need to compute the derivatives of your transformation F.
Another nice feature of the modified Taguchi methods is they easily allow you to formulate a method that works on uniform random variables X, or gamma random variables, etc. In fact, there are schemes that will allow you to solve for the moments of a wide variety of random variables. | Function of random variables | BabakP's answer is a good one. Read it, but I'd like to add a few points.
The computation of the distribution of a transformation of a random variable (or of several variables) is often called statist | Function of random variables
BabakP's answer is a good one. Read it, but I'd like to add a few points.
The computation of the distribution of a transformation of a random variable (or of several variables) is often called statistical tolerancing. A problem is, for most such transformations, there is no simple distribution that works. Thus suppose X is a Gaussian random variable, then F(X), where F is a linear function, also has a Gaussian distribution, but with an adjusted mean and variance, based on the transformation L, and the mean and variance of X.
However, things get nasty almost always when F(X) is at all nonlinear. Ok, if F is the exponential function, then F(X) for normal X has a lognormal distribution. But most nonlinear functions will not give you some well known distribution. So what can you do?
One simple solution is to compute the mean and variance of the transformation. Given a mean and variance, one might choose to assume a normal distribution with that mean and variance. One might even do more, computing the first four moments of F(X). There are several families of distributions (Pearson & Johnson families) that allow you to find a distribution that matches the moments you have just found.
So, the question is, how might one compute those moments? The simple answer is if you knew the derivative of F, then approximating F by a truncated (first order) Taylor series around the mean of X can allow you to find approximations for those moments. Essentially, if F is well approximated by a linear function over the support of X, then those moments will be good estimates. (For a Gaussian distribution, the support might be considered to be something like +/-6 sigma.)
Others have used second order Taylor series approximations. Here too we can compute approximate moments of the transformation.
And finally, I might mention Taguchi methods, as well as modified Taguchi methods. They too allow you to find approximations of the moments. A nice thing about the modified Taguchi methods is they are based on Gaussian integrations, and allow you to use higher order approximations quite easily, without any need to compute the derivatives of your transformation F.
Another nice feature of the modified Taguchi methods is they easily allow you to formulate a method that works on uniform random variables X, or gamma random variables, etc. In fact, there are schemes that will allow you to solve for the moments of a wide variety of random variables. | Function of random variables
BabakP's answer is a good one. Read it, but I'd like to add a few points.
The computation of the distribution of a transformation of a random variable (or of several variables) is often called statist |
34,784 | Predicting with GAM, using an offset | First, from the help-page of gam (bold font added by me):
offset: Can be used to supply a model offset for use in fitting. Note
that this offset will always be completely ignored when predicting,
unlike an offset included in formula: this conforms to the behaviour
of lm and glm.
So for predicting, you should use the formula-specification. Further, if you specify your offset as an argument, rather than in the formula, you should use an equal sign (=):
mod2<-gam(Y ~ covariate1 + covariate2 + covariate3 + covariate4, offset=log(sampled area), family=quasipoisson)
This should give the exact same result as this specification:
mod1<-gam(Y ~ offset(log(sampled area))+ covariate1 + covariate2 + covariate3 + covariate4, family=quasipoisson)
I honestly don't know what R caluclates if you specify the offset inside the brackets, like offset(sampled area).
Hope that helps. | Predicting with GAM, using an offset | First, from the help-page of gam (bold font added by me):
offset: Can be used to supply a model offset for use in fitting. Note
that this offset will always be completely ignored when predicting,
| Predicting with GAM, using an offset
First, from the help-page of gam (bold font added by me):
offset: Can be used to supply a model offset for use in fitting. Note
that this offset will always be completely ignored when predicting,
unlike an offset included in formula: this conforms to the behaviour
of lm and glm.
So for predicting, you should use the formula-specification. Further, if you specify your offset as an argument, rather than in the formula, you should use an equal sign (=):
mod2<-gam(Y ~ covariate1 + covariate2 + covariate3 + covariate4, offset=log(sampled area), family=quasipoisson)
This should give the exact same result as this specification:
mod1<-gam(Y ~ offset(log(sampled area))+ covariate1 + covariate2 + covariate3 + covariate4, family=quasipoisson)
I honestly don't know what R caluclates if you specify the offset inside the brackets, like offset(sampled area).
Hope that helps. | Predicting with GAM, using an offset
First, from the help-page of gam (bold font added by me):
offset: Can be used to supply a model offset for use in fitting. Note
that this offset will always be completely ignored when predicting,
|
34,785 | In R, find function F(x) to transform values in a vector to a normal distribution? | @AndreSilva is right that regression does not require the data to be normal. The assumption of linear regression is that the residuals are normal. It may help to read this thread: what-if-residuals-are-normally-distributed-but-y-is-not, to clarify this issue.
However, this point does not go far enough. First, the normality of the residuals serves to ensure that you can trust the standard p-values that software outputs. Even then, you can trust your p-values without normal residuals, if your N is sufficiently large. With $N>1,000,000$, there is likely to be little reason to worry about the validity of your p-values.
At any rate, if you want to make a predictive model, whether or not the residuals are normal is irrelevant. OLS regression methods are unbiased whether the residuals are normal or not, without regard for N. Thus, if you want to make point predictions (i.e., $\hat y_i$, the predicted mean of the conditional response distribution where $X=x_i$), you will be fine. If you want to make interval predictions, you can do that as well, you just shouldn't use the normal distribution (which would be the default) to do so. Instead, you can use the estimated density of your residuals to make prediction intervals. | In R, find function F(x) to transform values in a vector to a normal distribution? | @AndreSilva is right that regression does not require the data to be normal. The assumption of linear regression is that the residuals are normal. It may help to read this thread: what-if-residuals- | In R, find function F(x) to transform values in a vector to a normal distribution?
@AndreSilva is right that regression does not require the data to be normal. The assumption of linear regression is that the residuals are normal. It may help to read this thread: what-if-residuals-are-normally-distributed-but-y-is-not, to clarify this issue.
However, this point does not go far enough. First, the normality of the residuals serves to ensure that you can trust the standard p-values that software outputs. Even then, you can trust your p-values without normal residuals, if your N is sufficiently large. With $N>1,000,000$, there is likely to be little reason to worry about the validity of your p-values.
At any rate, if you want to make a predictive model, whether or not the residuals are normal is irrelevant. OLS regression methods are unbiased whether the residuals are normal or not, without regard for N. Thus, if you want to make point predictions (i.e., $\hat y_i$, the predicted mean of the conditional response distribution where $X=x_i$), you will be fine. If you want to make interval predictions, you can do that as well, you just shouldn't use the normal distribution (which would be the default) to do so. Instead, you can use the estimated density of your residuals to make prediction intervals. | In R, find function F(x) to transform values in a vector to a normal distribution?
@AndreSilva is right that regression does not require the data to be normal. The assumption of linear regression is that the residuals are normal. It may help to read this thread: what-if-residuals- |
34,786 | In R, find function F(x) to transform values in a vector to a normal distribution? | Your data do not need to be "Normal". What need to have normal distribution are the residuals (predicted versus observed) derived from your (multiple) linear regression model.
Did you test this presupposition? | In R, find function F(x) to transform values in a vector to a normal distribution? | Your data do not need to be "Normal". What need to have normal distribution are the residuals (predicted versus observed) derived from your (multiple) linear regression model.
Did you test this presup | In R, find function F(x) to transform values in a vector to a normal distribution?
Your data do not need to be "Normal". What need to have normal distribution are the residuals (predicted versus observed) derived from your (multiple) linear regression model.
Did you test this presupposition? | In R, find function F(x) to transform values in a vector to a normal distribution?
Your data do not need to be "Normal". What need to have normal distribution are the residuals (predicted versus observed) derived from your (multiple) linear regression model.
Did you test this presup |
34,787 | In R, find function F(x) to transform values in a vector to a normal distribution? | A classical linear model (such as simple linear regression) for a sample $y=(y_1, \ldots, y_n)$ has form $y_i = \mu_i + \epsilon_i$ where the "error terms" $\epsilon_1, \ldots, \epsilon_n \sim_{i.i.d} {\cal N}(0, \sigma^2)$ and the means $(\mu_1, \ldots, \mu_n)$ are unknown numbers satisfying some linear constraints.
Thus each $y_i$ is assumed to be generated from a normal distribution: $y_i \sim {\cal N}(\mu_i, \sigma^2)$ but drawing a histogram or an estimated density for the $y_i$ does not allow to check normality because they are not identically distributed (the distribution of $y_i$ depends on $i$ through $\mu_i$). In other words the $y_i$ are assumed to be generated from a normal distribution but not from a common distribution. If you have an "i.i.d" sample from an unknown distribution then you can estimate this distribution with a histogram or an estimated density, but if the sample is not "i.i.d" the histogram or the estimated density is useless.
However the error terms $\epsilon_i$ are identically distributed. One never knows the realizations of the $\epsilon_i$ because the $\mu_i$ are unknown, but the residuals $\hat\epsilon_i = y_i - \hat\mu_i$ approximate the realizations of the error terms and one can assess departure from the normality on the sample of residuals.
In some cases, for instance a one-way ANOVA, you can separately check normality by drawing a histogram of the $y_i$ in each group of individuals defined by the factor because the model assumes the $y_i$ are normal and i.i.d in each group. If the group sizes are small it is better to check normality with the residuals. | In R, find function F(x) to transform values in a vector to a normal distribution? | A classical linear model (such as simple linear regression) for a sample $y=(y_1, \ldots, y_n)$ has form $y_i = \mu_i + \epsilon_i$ where the "error terms" $\epsilon_1, \ldots, \epsilon_n \sim_{i.i.d} | In R, find function F(x) to transform values in a vector to a normal distribution?
A classical linear model (such as simple linear regression) for a sample $y=(y_1, \ldots, y_n)$ has form $y_i = \mu_i + \epsilon_i$ where the "error terms" $\epsilon_1, \ldots, \epsilon_n \sim_{i.i.d} {\cal N}(0, \sigma^2)$ and the means $(\mu_1, \ldots, \mu_n)$ are unknown numbers satisfying some linear constraints.
Thus each $y_i$ is assumed to be generated from a normal distribution: $y_i \sim {\cal N}(\mu_i, \sigma^2)$ but drawing a histogram or an estimated density for the $y_i$ does not allow to check normality because they are not identically distributed (the distribution of $y_i$ depends on $i$ through $\mu_i$). In other words the $y_i$ are assumed to be generated from a normal distribution but not from a common distribution. If you have an "i.i.d" sample from an unknown distribution then you can estimate this distribution with a histogram or an estimated density, but if the sample is not "i.i.d" the histogram or the estimated density is useless.
However the error terms $\epsilon_i$ are identically distributed. One never knows the realizations of the $\epsilon_i$ because the $\mu_i$ are unknown, but the residuals $\hat\epsilon_i = y_i - \hat\mu_i$ approximate the realizations of the error terms and one can assess departure from the normality on the sample of residuals.
In some cases, for instance a one-way ANOVA, you can separately check normality by drawing a histogram of the $y_i$ in each group of individuals defined by the factor because the model assumes the $y_i$ are normal and i.i.d in each group. If the group sizes are small it is better to check normality with the residuals. | In R, find function F(x) to transform values in a vector to a normal distribution?
A classical linear model (such as simple linear regression) for a sample $y=(y_1, \ldots, y_n)$ has form $y_i = \mu_i + \epsilon_i$ where the "error terms" $\epsilon_1, \ldots, \epsilon_n \sim_{i.i.d} |
34,788 | For what distribution is a trimmed mean the maximum likelihood estimator? | The distributions, if any, are obtained as integrals of the estimating equations. Let us assume for simplicity that the scale parameter is known, and the trimming parameters, if any, are fixed.
For the sample mean, the estimating equation is $${\rm E}(x-\mu)=0.$$ Imagining that this is the derivative of the log-likelihood, with an awful lot of abuse of notation and loss of rigor, we have $$ \frac{{\rm d}\ln l(\mu;x)}{{\rm d}\mu} = x-\mu, \quad \ln l(\mu;x) = a (x-\mu)^2, \quad l(\mu;x) \propto \exp[ a(x-\mu)^2],$$ where the $a$ parameter (integration constant) has to be negative to ensure that it integrates to something meaningful.
For the sample median, the estimating equation is $${\rm E \, sign}(x-\mu)=0.$$ Integrate this to get $$l(\mu;x) \propto \exp[ a|x-\mu| ],$$ where again we would have to choose $a$ to be negative to make sense.
For the trimmed mean, the estimating equation is $${\rm E}\rho(x,\mu,c) = 0, \quad \rho(x,\mu,c) = \left\{ \begin{array}{ll} x-\mu, & |x-\mu|\le c, \\ 0, & |x-\mu|>c. \end{array} \right.$$ Let's see what it integrates to: $$l(\mu;x, c) = \left\{ \begin{array}{ll} \exp[ a(x-\mu)^2], & |x-\mu|\le c, \\ b, & |x-\mu|>c. \end{array} \right.$$ Looks like a censored normal in the center, but look at the tails: they are improper if $b>0$. So to get a proper distribution, we have to set $b=0$. But then we have a logical inconsistency: this distribution would have to give a zero pdf to some actual data in the trimmed tails. This is self-contradictory, and shows some undesirable side effects of trimming.
Sometimes, it is beneficial to establish "likelihoodity" of a method to show its asymptotic normality, and efficiency for a narrow class of distributions. In general, asymptotic normality of the trimmed mean can follow from the theory of $M$-estimates. | For what distribution is a trimmed mean the maximum likelihood estimator? | The distributions, if any, are obtained as integrals of the estimating equations. Let us assume for simplicity that the scale parameter is known, and the trimming parameters, if any, are fixed.
For t | For what distribution is a trimmed mean the maximum likelihood estimator?
The distributions, if any, are obtained as integrals of the estimating equations. Let us assume for simplicity that the scale parameter is known, and the trimming parameters, if any, are fixed.
For the sample mean, the estimating equation is $${\rm E}(x-\mu)=0.$$ Imagining that this is the derivative of the log-likelihood, with an awful lot of abuse of notation and loss of rigor, we have $$ \frac{{\rm d}\ln l(\mu;x)}{{\rm d}\mu} = x-\mu, \quad \ln l(\mu;x) = a (x-\mu)^2, \quad l(\mu;x) \propto \exp[ a(x-\mu)^2],$$ where the $a$ parameter (integration constant) has to be negative to ensure that it integrates to something meaningful.
For the sample median, the estimating equation is $${\rm E \, sign}(x-\mu)=0.$$ Integrate this to get $$l(\mu;x) \propto \exp[ a|x-\mu| ],$$ where again we would have to choose $a$ to be negative to make sense.
For the trimmed mean, the estimating equation is $${\rm E}\rho(x,\mu,c) = 0, \quad \rho(x,\mu,c) = \left\{ \begin{array}{ll} x-\mu, & |x-\mu|\le c, \\ 0, & |x-\mu|>c. \end{array} \right.$$ Let's see what it integrates to: $$l(\mu;x, c) = \left\{ \begin{array}{ll} \exp[ a(x-\mu)^2], & |x-\mu|\le c, \\ b, & |x-\mu|>c. \end{array} \right.$$ Looks like a censored normal in the center, but look at the tails: they are improper if $b>0$. So to get a proper distribution, we have to set $b=0$. But then we have a logical inconsistency: this distribution would have to give a zero pdf to some actual data in the trimmed tails. This is self-contradictory, and shows some undesirable side effects of trimming.
Sometimes, it is beneficial to establish "likelihoodity" of a method to show its asymptotic normality, and efficiency for a narrow class of distributions. In general, asymptotic normality of the trimmed mean can follow from the theory of $M$-estimates. | For what distribution is a trimmed mean the maximum likelihood estimator?
The distributions, if any, are obtained as integrals of the estimating equations. Let us assume for simplicity that the scale parameter is known, and the trimming parameters, if any, are fixed.
For t |
34,789 | For what distribution is a trimmed mean the maximum likelihood estimator? | Special cases like the median aside, I don't think that trimmed means are generally ML; if they were, they'd already be some form of M-estimator. However, if you take a distribution which is normal in the middle with, say, exponential tails - the distribution corresponding to a Huber M-estimator - then for a particular level of trimming, the trimmed mean would be expected to be highly efficient. | For what distribution is a trimmed mean the maximum likelihood estimator? | Special cases like the median aside, I don't think that trimmed means are generally ML; if they were, they'd already be some form of M-estimator. However, if you take a distribution which is normal in | For what distribution is a trimmed mean the maximum likelihood estimator?
Special cases like the median aside, I don't think that trimmed means are generally ML; if they were, they'd already be some form of M-estimator. However, if you take a distribution which is normal in the middle with, say, exponential tails - the distribution corresponding to a Huber M-estimator - then for a particular level of trimming, the trimmed mean would be expected to be highly efficient. | For what distribution is a trimmed mean the maximum likelihood estimator?
Special cases like the median aside, I don't think that trimmed means are generally ML; if they were, they'd already be some form of M-estimator. However, if you take a distribution which is normal in |
34,790 | Kolmogorov Smirnov conflicts with visual data | I think your issues are now clarified enough to construct a decent answer (with plenty of links explaining the issues).
There are several issues here:
1. K-S test with estimated parameters
The sample mean and s.d. ($\bar{x}$ and $s$ ) are not population parameters ($\mu$ and $\sigma$).
The calculation of the null-distribution (/critical values) of the Kolmogorov-Smirnov test is based on a fully specified distribution, not an estimated one -- the p-values aren't meaningful if you use parameter estimates. In particular, the p-values will tend to be larger than what you'd get if the conditions under which the test was derived held.
When you want to estimate parameters the Kolmogorov-Smirnov-type of test is called a Lilliefors test, which has different tables.
So the Lilliefors is the correct test to use if you want to do a K-S -style for normality but with estimated mean and standard deviation. It's not necessary to get the original paper to use this test - you can simulate the null distribution (and to substantially better accuracy than Lilliefors was able to do in the 1960s).
Though if testing normality is the aim, the Shapiro-Wilk or Shapiro-Francia tests are more typical and have better power; Anderson-Darling tests are also common (parameter estimation is an issue for the A-D test as well, but check the discussion of the issue in D'Agostino & Stephens' Goodness of Fit Techniques).
Also see How to test whether a sample of data fits the family of Gamma distribution?
However, having identified the issue with your p-value doesn't mean that a goodness-of-fit test addresses your original issue.
2. Using hypothesis testing of normality for procedures that assume it
You carry the idea that the appropriate action when dealing with an ANOVA-like situation is to formally test normality via some goodness of fit test and only on rejection consider a nonparametric test. I would say this is not generally an appropriate understanding.
First, the hypothesis test answers the wrong question; indeed a rejection gives an answer to a question you already know the answer to.
Is normality testing 'essentially useless'?
Testing normality
What tests do I use to confirm that residuals are normally distributed?
Is it reasonable to make some assessment of normality if one is considering using a procedure that relies on it? Certainly; a visual assessment - a diagnostic such as a Q-Q plot - shows you how non-normal your data appear and will let you see whether the extent and type of non-normality you have would be enough to make your concerned about the particular procedure you would be applying.
In this case your histogram would be enough to say 'don't assume that's normal', though ordinarily I wouldn't base such a decision only on a histogram
Secondly, you can just do a Kruskal-Wallis without testing normality. It's valid when the data are normal, it's just somewhat less powerful than the usual ANOVA.
Only the fact that ANOVA is reasonably robust to mild non-normality makes it a reasonable choice in many circumstances. If I anticipated more than moderate skewness or kurtosis I'd avoid assuming normality (though Kruskal-Wallis is not the only option there).
Khan and Rayner (2003),
Robustness to Non-Normality of Common Tests for the Many-Sample Location Problem,
Journal of Applied Mathematics and Decision Sciences, 7(4), 187-206
suggest that in situations of high kurtosis - when sample sizes are not very small - that the Kruskal Wallis is definitely preferred to the F-test* (when sample sizes are small they suggest avoiding the Kruskal-Wallis)
*(the comments apply to the Mann-Whitney vs t test when there are two samples)
You certainly don't need to show something isn't normal to apply Kruskal-Wallis.
There are other alternatives to the Kruskal Wallis that don't assume normality, such as resampling-based tests (randomization tests, bootstrap tests) and robustified versions of ANOVA-type tests.
Also see:
How robust is ANOVA when group sizes are unequal and residuals are not normally distributed?
3. Assumptions of ANOVA
ANOVA doesn't assume the entire set of numbers is normal. That is, unconditional normality is not an assumption of ANOVA - only conditional normality.
Which is to say, you can't really assess the ANOVA assumption on the original data; you assess it on the residuals.
https://stats.stackexchange.com/a/6351/805
https://stats.stackexchange.com/a/27611/805
Also:
https://stats.stackexchange.com/a/9575/805 (t-tests, a special case of ANOVA)
https://stats.stackexchange.com/a/12266/805 (regression, a generalization of ANOVA) | Kolmogorov Smirnov conflicts with visual data | I think your issues are now clarified enough to construct a decent answer (with plenty of links explaining the issues).
There are several issues here:
1. K-S test with estimated parameters
The sample | Kolmogorov Smirnov conflicts with visual data
I think your issues are now clarified enough to construct a decent answer (with plenty of links explaining the issues).
There are several issues here:
1. K-S test with estimated parameters
The sample mean and s.d. ($\bar{x}$ and $s$ ) are not population parameters ($\mu$ and $\sigma$).
The calculation of the null-distribution (/critical values) of the Kolmogorov-Smirnov test is based on a fully specified distribution, not an estimated one -- the p-values aren't meaningful if you use parameter estimates. In particular, the p-values will tend to be larger than what you'd get if the conditions under which the test was derived held.
When you want to estimate parameters the Kolmogorov-Smirnov-type of test is called a Lilliefors test, which has different tables.
So the Lilliefors is the correct test to use if you want to do a K-S -style for normality but with estimated mean and standard deviation. It's not necessary to get the original paper to use this test - you can simulate the null distribution (and to substantially better accuracy than Lilliefors was able to do in the 1960s).
Though if testing normality is the aim, the Shapiro-Wilk or Shapiro-Francia tests are more typical and have better power; Anderson-Darling tests are also common (parameter estimation is an issue for the A-D test as well, but check the discussion of the issue in D'Agostino & Stephens' Goodness of Fit Techniques).
Also see How to test whether a sample of data fits the family of Gamma distribution?
However, having identified the issue with your p-value doesn't mean that a goodness-of-fit test addresses your original issue.
2. Using hypothesis testing of normality for procedures that assume it
You carry the idea that the appropriate action when dealing with an ANOVA-like situation is to formally test normality via some goodness of fit test and only on rejection consider a nonparametric test. I would say this is not generally an appropriate understanding.
First, the hypothesis test answers the wrong question; indeed a rejection gives an answer to a question you already know the answer to.
Is normality testing 'essentially useless'?
Testing normality
What tests do I use to confirm that residuals are normally distributed?
Is it reasonable to make some assessment of normality if one is considering using a procedure that relies on it? Certainly; a visual assessment - a diagnostic such as a Q-Q plot - shows you how non-normal your data appear and will let you see whether the extent and type of non-normality you have would be enough to make your concerned about the particular procedure you would be applying.
In this case your histogram would be enough to say 'don't assume that's normal', though ordinarily I wouldn't base such a decision only on a histogram
Secondly, you can just do a Kruskal-Wallis without testing normality. It's valid when the data are normal, it's just somewhat less powerful than the usual ANOVA.
Only the fact that ANOVA is reasonably robust to mild non-normality makes it a reasonable choice in many circumstances. If I anticipated more than moderate skewness or kurtosis I'd avoid assuming normality (though Kruskal-Wallis is not the only option there).
Khan and Rayner (2003),
Robustness to Non-Normality of Common Tests for the Many-Sample Location Problem,
Journal of Applied Mathematics and Decision Sciences, 7(4), 187-206
suggest that in situations of high kurtosis - when sample sizes are not very small - that the Kruskal Wallis is definitely preferred to the F-test* (when sample sizes are small they suggest avoiding the Kruskal-Wallis)
*(the comments apply to the Mann-Whitney vs t test when there are two samples)
You certainly don't need to show something isn't normal to apply Kruskal-Wallis.
There are other alternatives to the Kruskal Wallis that don't assume normality, such as resampling-based tests (randomization tests, bootstrap tests) and robustified versions of ANOVA-type tests.
Also see:
How robust is ANOVA when group sizes are unequal and residuals are not normally distributed?
3. Assumptions of ANOVA
ANOVA doesn't assume the entire set of numbers is normal. That is, unconditional normality is not an assumption of ANOVA - only conditional normality.
Which is to say, you can't really assess the ANOVA assumption on the original data; you assess it on the residuals.
https://stats.stackexchange.com/a/6351/805
https://stats.stackexchange.com/a/27611/805
Also:
https://stats.stackexchange.com/a/9575/805 (t-tests, a special case of ANOVA)
https://stats.stackexchange.com/a/12266/805 (regression, a generalization of ANOVA) | Kolmogorov Smirnov conflicts with visual data
I think your issues are now clarified enough to construct a decent answer (with plenty of links explaining the issues).
There are several issues here:
1. K-S test with estimated parameters
The sample |
34,791 | Linear regression - variance error term | In ordinary linear regression we do know the distribution of the error term $\varepsilon$, up to the single unknown parameter $\sigma^2$. Namely, our model is that the errors are drawn iid from the distribution
$$\varepsilon_i \sim \mathcal N(0,\sigma^2).$$
We then estimate $\sigma^2$ along with the unknown $\beta$ coefficients. | Linear regression - variance error term | In ordinary linear regression we do know the distribution of the error term $\varepsilon$, up to the single unknown parameter $\sigma^2$. Namely, our model is that the errors are drawn iid from the di | Linear regression - variance error term
In ordinary linear regression we do know the distribution of the error term $\varepsilon$, up to the single unknown parameter $\sigma^2$. Namely, our model is that the errors are drawn iid from the distribution
$$\varepsilon_i \sim \mathcal N(0,\sigma^2).$$
We then estimate $\sigma^2$ along with the unknown $\beta$ coefficients. | Linear regression - variance error term
In ordinary linear regression we do know the distribution of the error term $\varepsilon$, up to the single unknown parameter $\sigma^2$. Namely, our model is that the errors are drawn iid from the di |
34,792 | Linear regression - variance error term | We should not make this assumption uncritically.
The error term $\varepsilon_i$ conditional on a particular $X$ value $X_i$, like any random variable, has a variance, usually written $\sigma_i^2$. There is no assumption here, it is just notation for that variance.
However, one of the assumptions of classical linear regression is that the error terms conditional on different $X$ values all have the same variance, that is, for any $X_i$ and $X_j$, $\sigma_i^2 = \sigma_j^2$. This assumption, known as homoscedasticity, may or may not be met for a particular model applied to a particular population. Before drawing conclusions from ordinary least squares (OLS) regression it is good practice to apply appropriate tests (or at least inspection of residuals) to assess whether this assumption is met. Where the assumption is met we are justified in using a common symbol, usually $\sigma^2$, for the common variance of the error terms.
Where the assumption is not met, that is, where there is heteroscedasticity, OLS regression is liable to give biased estimates of the variances of the regression coefficients. In that case weighted least squares is used to correct for the heteroscedasticity. Properly used, this has the effect of transforming the model in such a way that homoscedasticity is restored. | Linear regression - variance error term | We should not make this assumption uncritically.
The error term $\varepsilon_i$ conditional on a particular $X$ value $X_i$, like any random variable, has a variance, usually written $\sigma_i^2$. The | Linear regression - variance error term
We should not make this assumption uncritically.
The error term $\varepsilon_i$ conditional on a particular $X$ value $X_i$, like any random variable, has a variance, usually written $\sigma_i^2$. There is no assumption here, it is just notation for that variance.
However, one of the assumptions of classical linear regression is that the error terms conditional on different $X$ values all have the same variance, that is, for any $X_i$ and $X_j$, $\sigma_i^2 = \sigma_j^2$. This assumption, known as homoscedasticity, may or may not be met for a particular model applied to a particular population. Before drawing conclusions from ordinary least squares (OLS) regression it is good practice to apply appropriate tests (or at least inspection of residuals) to assess whether this assumption is met. Where the assumption is met we are justified in using a common symbol, usually $\sigma^2$, for the common variance of the error terms.
Where the assumption is not met, that is, where there is heteroscedasticity, OLS regression is liable to give biased estimates of the variances of the regression coefficients. In that case weighted least squares is used to correct for the heteroscedasticity. Properly used, this has the effect of transforming the model in such a way that homoscedasticity is restored. | Linear regression - variance error term
We should not make this assumption uncritically.
The error term $\varepsilon_i$ conditional on a particular $X$ value $X_i$, like any random variable, has a variance, usually written $\sigma_i^2$. The |
34,793 | How representative is Poisson distribution of the distribution of events in reality? | One example I can speak for is supermarket sales of Consumer Packaged Goods (CPG). These are also count events - the supermarket may sell 0 units a day, or 1, or 2 and so on, so the Poisson distribution seems like a good first fit.
However, the underlying binomial distribution @PeterEllis notes does not hold. Yes, we may be able to model the number of customers with a binomial... but some customers will buy 1 unit, some will buy 2 units and some will load their pantries and buy 10 units.
The result will usually be overdispersed, so that a negative binomial distribution fits much better than a Poisson one. (Occasionally, we may even see underdispersion for very fast moving items like milk). | How representative is Poisson distribution of the distribution of events in reality? | One example I can speak for is supermarket sales of Consumer Packaged Goods (CPG). These are also count events - the supermarket may sell 0 units a day, or 1, or 2 and so on, so the Poisson distributi | How representative is Poisson distribution of the distribution of events in reality?
One example I can speak for is supermarket sales of Consumer Packaged Goods (CPG). These are also count events - the supermarket may sell 0 units a day, or 1, or 2 and so on, so the Poisson distribution seems like a good first fit.
However, the underlying binomial distribution @PeterEllis notes does not hold. Yes, we may be able to model the number of customers with a binomial... but some customers will buy 1 unit, some will buy 2 units and some will load their pantries and buy 10 units.
The result will usually be overdispersed, so that a negative binomial distribution fits much better than a Poisson one. (Occasionally, we may even see underdispersion for very fast moving items like milk). | How representative is Poisson distribution of the distribution of events in reality?
One example I can speak for is supermarket sales of Consumer Packaged Goods (CPG). These are also count events - the supermarket may sell 0 units a day, or 1, or 2 and so on, so the Poisson distributi |
34,794 | How representative is Poisson distribution of the distribution of events in reality? | If the things being counted are independent of each other and the rate is constant (or follows a model like in poisson regression) then the Poisson distribution will generally hold quite well. Examples like cars arriving at a garage tend to work fairly well (over periods of time that the rate is fairly constant, including both rush hour and the middle of the night for a garage frequented by 9 to 5 workers would not work well). What time you arrive at the garage will have little or influence on what time I arrive. There are exceptions however in that if 2 people arrange to meet at a given time then they are likely to arrive closer together, if one follows the other then they will be even closer. Also things like a nearby traffic light could cause clumps in the arrivals that would not match a Poisson.
If you want to compare a specific dataset to see if the Poisson is a good match then you can use a hanging rootogram. | How representative is Poisson distribution of the distribution of events in reality? | If the things being counted are independent of each other and the rate is constant (or follows a model like in poisson regression) then the Poisson distribution will generally hold quite well. Exampl | How representative is Poisson distribution of the distribution of events in reality?
If the things being counted are independent of each other and the rate is constant (or follows a model like in poisson regression) then the Poisson distribution will generally hold quite well. Examples like cars arriving at a garage tend to work fairly well (over periods of time that the rate is fairly constant, including both rush hour and the middle of the night for a garage frequented by 9 to 5 workers would not work well). What time you arrive at the garage will have little or influence on what time I arrive. There are exceptions however in that if 2 people arrange to meet at a given time then they are likely to arrive closer together, if one follows the other then they will be even closer. Also things like a nearby traffic light could cause clumps in the arrivals that would not match a Poisson.
If you want to compare a specific dataset to see if the Poisson is a good match then you can use a hanging rootogram. | How representative is Poisson distribution of the distribution of events in reality?
If the things being counted are independent of each other and the rate is constant (or follows a model like in poisson regression) then the Poisson distribution will generally hold quite well. Exampl |
34,795 | How representative is Poisson distribution of the distribution of events in reality? | As @Stephan says, the straight Poisson may not have enough variance to be a good model of real non-negative integer measurements governed by a hazard function.
So, often the negative binomial is used, which has an additional parameter $\alpha > 0$ determining the over-dispersion.
I've found it useful to parameterize by $\beta=\ln(\alpha)$ because as the over-dispersion $\alpha$ approaches 0, meaning the negative binomial approaches Poisson, the negative binomial becomes difficult to compute.
Another way to increase the dispersion is zero-inflation, which can be applied to either Poisson or negative binomial.
To use that, at each measurement time, first conduct a Bernoulli trial (flip a coin).
If the coin is "heads", the measurement is 0.
Otherwise the measurement is drawn from the Poisson or negative binomial distribution. | How representative is Poisson distribution of the distribution of events in reality? | As @Stephan says, the straight Poisson may not have enough variance to be a good model of real non-negative integer measurements governed by a hazard function.
So, often the negative binomial is used, | How representative is Poisson distribution of the distribution of events in reality?
As @Stephan says, the straight Poisson may not have enough variance to be a good model of real non-negative integer measurements governed by a hazard function.
So, often the negative binomial is used, which has an additional parameter $\alpha > 0$ determining the over-dispersion.
I've found it useful to parameterize by $\beta=\ln(\alpha)$ because as the over-dispersion $\alpha$ approaches 0, meaning the negative binomial approaches Poisson, the negative binomial becomes difficult to compute.
Another way to increase the dispersion is zero-inflation, which can be applied to either Poisson or negative binomial.
To use that, at each measurement time, first conduct a Bernoulli trial (flip a coin).
If the coin is "heads", the measurement is 0.
Otherwise the measurement is drawn from the Poisson or negative binomial distribution. | How representative is Poisson distribution of the distribution of events in reality?
As @Stephan says, the straight Poisson may not have enough variance to be a good model of real non-negative integer measurements governed by a hazard function.
So, often the negative binomial is used, |
34,796 | How representative is Poisson distribution of the distribution of events in reality? | I have seen that if the events turn out to be regular then the Poisson model overestimates the variance (logical and obvious), whilst if the events turn out to be clustered then the Poisson model underestimates the variance. The Poisson distribution is generated from a random Poisson point process.
My old textbook recommends Cox, D.R. and Miller, H.D. (1965) The theory of stochastic processes pub. Wiley for further reading. In the introductory book a first-order differential equation is derived for such a random process, which is solved to give the probability of observing no events in time $t$, $P(0,t) = e^{-at}$ where $a$ is the rate of events and $t$ is time, then by considering $P(1,t), P(2,t),$ etc. the general Poisson formula is derived by inspection. C. Chatfield Statistics for technology: a course in applied statistics, 2nd Ed. 1978, pub. Chapman and Hall: see pages 70-75.
Those two examples violate the underlying randomness requirement. If the events are more or less random then the Poisson model is a fair model. Cars arriving a busy town centre car park may be an example of a clustered data set, due to 9 to 5 users, perhaps? | How representative is Poisson distribution of the distribution of events in reality? | I have seen that if the events turn out to be regular then the Poisson model overestimates the variance (logical and obvious), whilst if the events turn out to be clustered then the Poisson model und | How representative is Poisson distribution of the distribution of events in reality?
I have seen that if the events turn out to be regular then the Poisson model overestimates the variance (logical and obvious), whilst if the events turn out to be clustered then the Poisson model underestimates the variance. The Poisson distribution is generated from a random Poisson point process.
My old textbook recommends Cox, D.R. and Miller, H.D. (1965) The theory of stochastic processes pub. Wiley for further reading. In the introductory book a first-order differential equation is derived for such a random process, which is solved to give the probability of observing no events in time $t$, $P(0,t) = e^{-at}$ where $a$ is the rate of events and $t$ is time, then by considering $P(1,t), P(2,t),$ etc. the general Poisson formula is derived by inspection. C. Chatfield Statistics for technology: a course in applied statistics, 2nd Ed. 1978, pub. Chapman and Hall: see pages 70-75.
Those two examples violate the underlying randomness requirement. If the events are more or less random then the Poisson model is a fair model. Cars arriving a busy town centre car park may be an example of a clustered data set, due to 9 to 5 users, perhaps? | How representative is Poisson distribution of the distribution of events in reality?
I have seen that if the events turn out to be regular then the Poisson model overestimates the variance (logical and obvious), whilst if the events turn out to be clustered then the Poisson model und |
34,797 | Baseline differences in RCT: Which variables (if any) should be included as covariates? | As Stephen Senn has written, it is not appropriate to compare baseline distributions in a randomized study. The way I like to talk about this is to ask the question "where do you stop?", i.e., how many other baseline covariates should you go back and try to retrieve? You will find counter-balancing covariates if you look hard enough.
The basis for chosing a model is not post-hoc differences but rather apriori subject matter knowledge about which variables are likely to be important predictors of the response variable. The baseline version of the response variable is certainly a dominating predictor but there are others that are likely to be important. The goal is explaining explainable heterogeneity in the outcome to maximize precision and power. There is almost no role for statistical significance testing in model formulation.
A pre-specified model will take care of chance differences on the variables that matter - those predicting the outcome. | Baseline differences in RCT: Which variables (if any) should be included as covariates? | As Stephen Senn has written, it is not appropriate to compare baseline distributions in a randomized study. The way I like to talk about this is to ask the question "where do you stop?", i.e., how ma | Baseline differences in RCT: Which variables (if any) should be included as covariates?
As Stephen Senn has written, it is not appropriate to compare baseline distributions in a randomized study. The way I like to talk about this is to ask the question "where do you stop?", i.e., how many other baseline covariates should you go back and try to retrieve? You will find counter-balancing covariates if you look hard enough.
The basis for chosing a model is not post-hoc differences but rather apriori subject matter knowledge about which variables are likely to be important predictors of the response variable. The baseline version of the response variable is certainly a dominating predictor but there are others that are likely to be important. The goal is explaining explainable heterogeneity in the outcome to maximize precision and power. There is almost no role for statistical significance testing in model formulation.
A pre-specified model will take care of chance differences on the variables that matter - those predicting the outcome. | Baseline differences in RCT: Which variables (if any) should be included as covariates?
As Stephen Senn has written, it is not appropriate to compare baseline distributions in a randomized study. The way I like to talk about this is to ask the question "where do you stop?", i.e., how ma |
34,798 | Baseline differences in RCT: Which variables (if any) should be included as covariates? | Normally what you should care about in comparing the two groups at baseline is not so much statistical significance of differences but size of differences: is any of these differences large enough to matter to the study? Large enough to affect the group comparisons and variable relationships that are the focus of the research? Large enough that adjusting for it (by using it as a covariate) is necessary?
Now, your case is a little bit interesting in that, even with random assignment, you've got 4 out of 24 variables showing differences significant at the .05 level (17% instead of the expected 5%). That may seem concerning for your randomization process or some other aspect of the study. But theoretically, if the randomization were done flawlessly and there was no attrition in either group afterwards, a result this extreme or more so should occur 2.4% of the time, based on 24!/(4!(24-4)!) (.05^4) (.95^(24-4)). That is not really such a rare occurrence after all. What you have could well be a set of random differences. I'd stick with judging based on magnitude of differences. | Baseline differences in RCT: Which variables (if any) should be included as covariates? | Normally what you should care about in comparing the two groups at baseline is not so much statistical significance of differences but size of differences: is any of these differences large enough to | Baseline differences in RCT: Which variables (if any) should be included as covariates?
Normally what you should care about in comparing the two groups at baseline is not so much statistical significance of differences but size of differences: is any of these differences large enough to matter to the study? Large enough to affect the group comparisons and variable relationships that are the focus of the research? Large enough that adjusting for it (by using it as a covariate) is necessary?
Now, your case is a little bit interesting in that, even with random assignment, you've got 4 out of 24 variables showing differences significant at the .05 level (17% instead of the expected 5%). That may seem concerning for your randomization process or some other aspect of the study. But theoretically, if the randomization were done flawlessly and there was no attrition in either group afterwards, a result this extreme or more so should occur 2.4% of the time, based on 24!/(4!(24-4)!) (.05^4) (.95^(24-4)). That is not really such a rare occurrence after all. What you have could well be a set of random differences. I'd stick with judging based on magnitude of differences. | Baseline differences in RCT: Which variables (if any) should be included as covariates?
Normally what you should care about in comparing the two groups at baseline is not so much statistical significance of differences but size of differences: is any of these differences large enough to |
34,799 | Baseline differences in RCT: Which variables (if any) should be included as covariates? | +1 to @FrankHarrell. I might add one small point. If you randomly assigned your participants to the groups, any 'significant' differences in covariate values prior to intervention are necessarily type I errors. | Baseline differences in RCT: Which variables (if any) should be included as covariates? | +1 to @FrankHarrell. I might add one small point. If you randomly assigned your participants to the groups, any 'significant' differences in covariate values prior to intervention are necessarily ty | Baseline differences in RCT: Which variables (if any) should be included as covariates?
+1 to @FrankHarrell. I might add one small point. If you randomly assigned your participants to the groups, any 'significant' differences in covariate values prior to intervention are necessarily type I errors. | Baseline differences in RCT: Which variables (if any) should be included as covariates?
+1 to @FrankHarrell. I might add one small point. If you randomly assigned your participants to the groups, any 'significant' differences in covariate values prior to intervention are necessarily ty |
34,800 | How to evaluate results of linear regression | I'd agree with @Octern that one rarely sees people using train/test splits (or even things like cross-validation) for linear models. Overfitting is (almost) certainly not an issue with a very simple model like this one.
If you wanted to get a sense for your model's "quality", you may want to report confidence intervals (or their Bayesian equivalents) around your regression coefficients. There are several ways to do this. If you know/can assume that your errors are normally distributed, there's a simple formula (and most popular data analysis packages will give you these values).
Another popular alternative is to compute them through resampling (e.g., bootstrapping or jackknifing), which makes fewer assumptions about the distribution of errors. In either case, I'd use the complete data set for the computation. | How to evaluate results of linear regression | I'd agree with @Octern that one rarely sees people using train/test splits (or even things like cross-validation) for linear models. Overfitting is (almost) certainly not an issue with a very simple m | How to evaluate results of linear regression
I'd agree with @Octern that one rarely sees people using train/test splits (or even things like cross-validation) for linear models. Overfitting is (almost) certainly not an issue with a very simple model like this one.
If you wanted to get a sense for your model's "quality", you may want to report confidence intervals (or their Bayesian equivalents) around your regression coefficients. There are several ways to do this. If you know/can assume that your errors are normally distributed, there's a simple formula (and most popular data analysis packages will give you these values).
Another popular alternative is to compute them through resampling (e.g., bootstrapping or jackknifing), which makes fewer assumptions about the distribution of errors. In either case, I'd use the complete data set for the computation. | How to evaluate results of linear regression
I'd agree with @Octern that one rarely sees people using train/test splits (or even things like cross-validation) for linear models. Overfitting is (almost) certainly not an issue with a very simple m |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.